Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec 165f5e1260 fix(ipsec): исправить сверку списка файлов при экспорте сертификатов
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m23s
Docker images / backend-image (push) Successful in 2m35s
Docker images / frontend-image (push) Successful in 2m38s
Docker images / updater-image (push) Successful in 1m7s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-22 15:36:37 +07:00
6 changed files with 64 additions and 17 deletions

No files matched your search

@@ -72,7 +72,7 @@ const router = createServer(async (req, res) => {
const certificate = catalogs["/certificate"].find(row => row[".id"] === fields[".id"])
assert(certificate && !("name" in fields))
commands.at(-1)!.name = certificate.name
catalogs["/file"].push({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
catalogs["/file"].unshift({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
if (mode === "lost") { req.socket.destroy(); return }
} else if (req.method === "DELETE" && path.startsWith("/file/")) {
catalogs["/file"] = catalogs["/file"].filter(row => row[".id"] !== path.slice("/file/".length))
@@ -53,12 +53,19 @@ export async function acceptIpsecUserCreate(actor: AuthUser) {
: path === "/certificate/sign" && ("days-valid" in fields || "name" in fields) ? ("days-valid" in fields ? "unknown parameter days-valid" : "missing =.id=")
: path === "/certificate/export-certificate" && "name" in fields ? "unknown parameter name" : undefined
if (refusal) { res.statusCode = 400; res.end(JSON.stringify({ error: 400, message: "Bad Request", detail: refusal })); return }
if ((mode === "export-refused" && path === "/certificate/export-certificate") || (mode === "cleanup-refused" && req.method === "DELETE" && path.startsWith("/file/"))) {
res.statusCode = 400; res.end(JSON.stringify({ error: 400, detail: "NEVER_NATIVE_ERROR_DETAILS" })); return
}
let result: Row = {}
if (mode !== "ignored") {
if (path === "/certificate/sign") {
const row = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]); assert(row)
Object.assign(row, { ca: fields.ca, "digest-algorithm": "sha256", fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
} else if (path === "/certificate/export-certificate") assert(catalogs["/certificate"].some(row => row[".id"] === fields[".id"])), catalogs["/file"].push({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
} else if (path === "/certificate/export-certificate") {
assert(catalogs["/certificate"].some(row => row[".id"] === fields[".id"]))
catalogs["/file"].unshift({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
if (mode === "other-file-changed") catalogs["/file"][1].size = "99"
}
else {
const catalog = Object.keys(catalogs).find(value => path === value || path.startsWith(value + "/")); assert(catalog)
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; catalogs[catalog].push(result) }
@@ -121,6 +128,23 @@ export async function acceptIpsecUserCreate(actor: AuthUser) {
assert.equal(failedExport.json().state, "partial")
assert.deepEqual(catalogs["/ip/ipsec/identity"], base["/ip/ipsec/identity"])
assert.deepEqual(catalogs["/ip/ipsec/mode-config"], base["/ip/ipsec/mode-config"])
reset(); mode = "other-file-changed"
const unrelatedChange = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice" } })
assert.equal(unrelatedChange.statusCode, 502)
assert.equal(unrelatedChange.json().completedCommands, 2)
assert.equal(catalogs["/file"].length, 2, "failed proof must stop before deletion")
for (const [fault, stage, completed] of [["export-refused", "экспорт .p12", 2], ["cleanup-refused", "удаление временного .p12", 3]] as const) {
reset(); mode = fault
const response = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice", staticIp: "192.0.2.7" } })
assert.equal(response.statusCode, 502)
const error = response.json()
assert.equal(error.completedCommands, completed)
assert(error.error.includes(stage))
assert(error.error.includes("HTTP 400"))
hidden(error)
assert.deepEqual(catalogs["/ip/ipsec/identity"], base["/ip/ipsec/identity"])
assert.deepEqual(catalogs["/ip/ipsec/mode-config"], base["/ip/ipsec/mode-config"])
}
reset(); const rawStart = commands.length
for (const request of [{ name: "Alice" }, { name: "Alice", authMethod: "pre-shared-key", psk: "NEVER_RAW" }, { name: "Alice", privateKeyExport: true, staticIp: "bad" }]) await assert.rejects(prepare(request))
assert.equal(commands.length, rawStart)
@@ -96,12 +96,14 @@ export function normalizeIpsecExistingExportPassphrase(raw: string | undefined,
}
export function projectIpsecExistingCertificateExport(state: IpsecExistingCertificateExportState, filename: string, after: IpsecExistingCertificateExportState) {
validateIpsecExistingCertificateExportState(after)
const old = state.catalogs["/file"], candidates = after.catalogs["/file"].filter(row => row.name === filename && !old.some(prior => idKey(prior[".id"]) === idKey(row[".id"])))
const old = state.catalogs["/file"], files = after.catalogs["/file"]
const candidates = files.filter(row => row.name === filename && !old.some(prior => idKey(prior[".id"]) === idKey(row[".id"])))
if (candidates.length !== 1) throw fail("Не подтверждён единственный receipt-owned файл экспорта", "VERIFICATION_FAILED")
const row = candidates[0], size = Number(row.size)
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_OWNED_FILE_BYTES) throw fail("Размер приватного файла вне предела точного /file/get (61438 байт)", "VERIFICATION_FAILED")
const projected = structuredClone(state)
projected.catalogs["/file"].push(structuredClone(row))
// The new file can appear anywhere. The proof still checks the relative order and contents of every pre-existing row.
projected.catalogs["/file"].splice(files.indexOf(row), 0, structuredClone(row))
return { projected, file: { id: row[".id"], name: filename, size } }
}
export function projectIpsecExistingCertificateCleanup(state: IpsecExistingCertificateExportState, file: { id: string; name: string; size: number }) {
@@ -69,7 +69,8 @@ assert.throws(() => project(withCert, cert.commands[1], { observedRow: signed })
const signedState = project(withCert, cert.commands[1], { observedRow: signed, ownedCertificateIds: new Set(["*new"]) })
assert.deepEqual(signedState.catalogs["/certificate"].slice(0, 2), state.catalogs["/certificate"])
assert.throws(() => project(withCert, cert.commands[1], { observedRow: { ...signed, opaque: "changed" }, ownedCertificateIds: new Set(["*new"]) }), /исходные поля/)
const withFile = project(signedState, cert.commands[2], { assignedId: "*export", observedRow: { ".id": "*export", name: "mm-ipsec-fixture.p12", size: "256", type: "file" } })
const withFile = project(signedState, cert.commands[2], { assignedId: "*export", observedRow: { ".id": "*export", name: "mm-ipsec-fixture.p12", size: "256", type: "file" }, exportIndex: 0 })
assert.equal(withFile.catalogs["/file"][0][".id"], "*export")
assert.deepEqual(project(withFile, cert.commands[3], { assignedId: "*export" }).catalogs["/file"], state.catalogs["/file"])
assert.throws(() => project(state, psk.commands[0], { assignedId: "*l", observedRow: { ".id": "*l", ...psk.commands[0].fields } }), /ACK/)
assert.throws(() => project(state, psk.commands[0], { assignedId: "*new", observedRow: { ".id": "*new", ...psk.commands[0].fields, "remote-id": "key-id:mallory" } }), /Поля/)
@@ -105,7 +105,7 @@ export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerR
/** Native defaults are admitted solely for the ACK-owned newly created row.
* Signing can change only documented generated fields of that new certificate. */
export function projectIpsecUserCreate(state: IpsecUserCreateState, command: IpsecUserCreateCommand, options: { assignedId?: string; observedRow?: Row; ownedCertificateIds?: Set<string> } = {}) {
export function projectIpsecUserCreate(state: IpsecUserCreateState, command: IpsecUserCreateCommand, options: { assignedId?: string; observedRow?: Row; ownedCertificateIds?: Set<string>; exportIndex?: number } = {}) {
const next = structuredClone(state)
const path = command.action === "sign" ? "/certificate" : command.action === "export" || command.action === "cleanup" ? "/file" : command.path
const rows = next.catalogs[path]
@@ -131,7 +131,13 @@ export function projectIpsecUserCreate(state: IpsecUserCreateState, command: Ips
for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("Создан системный объект", "VERIFICATION_FAILED")
const fields = command.action === "export" ? { name: command.name! } : command.fields
for (const [key, value] of Object.entries(fields)) if (row[key] !== value && !(["disabled", "responder"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Поля нового объекта не подтверждены", "VERIFICATION_FAILED")
rows.push(structuredClone(row))
if (command.action === "export") {
const index = options.exportIndex
if (index === undefined || !Number.isInteger(index) || index < 0 || index > rows.length) throw fail("Не подтверждена позиция нового файла экспорта", "VERIFICATION_FAILED")
rows.splice(index, 0, structuredClone(row))
} else {
rows.push(structuredClone(row))
}
}
return next
}
+24 -10
View File
@@ -2,7 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto"
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { McpError, fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
import { MAX_OWNED_FILE_BYTES, MikrotikClient } from "./mikrotik.js"
import { MAX_OWNED_FILE_BYTES, MikrotikClient, MikrotikError } from "./mikrotik.js"
import { readIpsecPeerDeleteState, ipsecPeerDeleteRows } from "./ipsec-peer-delete.js"
import { ipsecUserUpdateValue } from "./ipsec-user-update.js"
import { sameWireguardEndpoint } from "./wireguard-source.js"
@@ -37,6 +37,15 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
let completedCommands = 0, confirmedWrites = 0, bundle: IpsecCertBundle | undefined, artifactReceipt: Record<string, unknown> | undefined
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecUserCreateExecutionError(code, message, confirmedWrites, completedCommands, plan.commands.length)
for (const command of plan.commands) {
const stage = {
create: command.path === "/certificate" ? "создание сертификата" : command.path === "/ip/ipsec/mode-config" ? "назначение персонального IP" : "создание привязки IKEv2",
update: "обновление персонального IP",
sign: "подпись сертификата",
export: "экспорт .p12",
cleanup: "удаление временного .p12",
}[command.action]
const stoppedAtStage = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", detail: string) =>
stopped(code, `Создание IKEv2 остановлено на этапе «${stage}». ${detail}`)
let dispatched = false, response: unknown, assignedId: string | undefined
const fence = async () => { const fresh = await readIpsecUserCreateState(server, source); if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; команда не отправлена", 409); await source(); dispatched = true }
try {
@@ -57,7 +66,8 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
confirmedWrites++
} catch (error) {
if (!dispatched && !completedCommands && error instanceof McpError) throw error
throw stopped(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", "Создание IPsec остановлено; повтор native-команды запрещён, требуется сверка")
const detail = !dispatched ? "Команда не отправлена." : error instanceof MikrotikError ? `RouterOS вернул HTTP ${error.statusCode}.` : "Ответ RouterOS не подтверждён."
throw stoppedAtStage(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", `${detail} Перед повтором требуется сверка.`)
}
let after: IpsecUserCreateState
try {
@@ -67,23 +77,27 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
const deadline = Date.now() + 90000
while (!after.catalogs["/certificate"].find(row => row.name === command.name)?.["invalid-after"] && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 1000)); after = await readIpsecUserCreateState(server, source) }
}
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но read-back недоступен; повтор запрещён") }
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена. Не удалось перечитать состояние RouterOS.") }
let exportIndex: number | undefined
if (command.action === "export") {
const files = after.catalogs["/file"]
const candidates = files.filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"]))
if (candidates.length !== 1) throw stoppedAtStage("VERIFICATION_FAILED", "В списке RouterOS не найден единственный новый файл с ожидаемым именем.")
assignedId = candidates[0][".id"]
exportIndex = files.indexOf(candidates[0])
}
try {
const path = command.action === "sign" ? "/certificate" : command.action === "export" ? "/file" : command.path
if (command.action === "create") {
const ack = response as Record<string, unknown> | null
if (typeof ack?.[".id"] !== "string") throw Error("missing create ACK")
assignedId = ack[".id"]
} else if (command.action === "export") {
const candidates = after.catalogs["/file"].filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"]))
if (candidates.length !== 1) throw Error("missing unique export file")
assignedId = candidates[0][".id"]
}
const observedRow = after.catalogs[path].find(row => command.action === "sign" ? row.name === command.name : row[".id"] === assignedId)
const projected = projectIpsecUserCreate(state, command, { assignedId, observedRow, ownedCertificateIds })
const projected = projectIpsecUserCreate(state, command, { assignedId, observedRow, ownedCertificateIds, exportIndex })
if (await ipsecUserCreateProof(projected) !== after.proof) throw Error("configuration mismatch")
if (command.action === "create" && command.path === "/certificate") ownedCertificateIds.add(assignedId!)
} catch { throw stopped("VERIFICATION_FAILED", "Не подтверждены команда и сохранность полного состояния IPsec; повтор запрещён") }
} catch { throw stoppedAtStage("VERIFICATION_FAILED", "Проверка результата команды и состояния IPsec не пройдена.") }
state = after; completedCommands++
try {
await source(); await options.checkpoint?.({ receiptId, commandCount: plan.commands.length, completedCommands, afterProof: state.proof })
@@ -100,7 +114,7 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
bundle = { user: body.name, serverEndpoint: plan.serverEndpoint, filename: file.name, contentB64: p12B64, mime: "application/x-pkcs12", passphrase, sswanFilename: `${plan.certName}.sswan`, sswanContent: buildSswanConfig({ name: `IKEv2 ${plan.serverEndpoint}`, serverEndpoint: plan.serverEndpoint, serverId: plan.serverEndpoint, p12B64 }), instructions: buildClientInstructions({ userName: body.name, serverEndpoint: plan.serverEndpoint, p12Filename: file.name, passphrase, dns: plan.dns }) }
} finally { content.fill(0) }
}
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда проверена, но checkpoint или приватный артефакт не сохранён; повтор запрещён") }
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда подтверждена. Не удалось прочитать приватный файл или сохранить квитанцию.") }
}
const reader = { get: async (path: string) => { await source(); if (!Object.hasOwn(state.catalogs, path)) throw new McpError("STATE_UNAVAILABLE", "Неизвестный каталог истории IPsec", 502); return structuredClone(state.catalogs[path]) } } as unknown as MikrotikClient
let historyRecorded = false