162 lines
17 KiB
TypeScript
162 lines
17 KiB
TypeScript
import { McpError } from "../modules/mcp/security.js"
|
|
import { isHiddenSecret, parseIpsecSnapshot } from "./entity-snapshots.js"
|
|
import { isIpsecManagedComment, isManagedIpsecModeConfig } from "./ipsec-config.js"
|
|
import { observedBoolean } from "./ospf-observed-values.js"
|
|
import { validateIpsecServerInitState, type IpsecServerInitState } from "./ipsec-server-init-model.js"
|
|
import { assertPoolMutationDependencies, ipsecPoolDependencies } from "./ipsec-pool-dependencies.js"
|
|
|
|
type Row = Record<string, string>
|
|
export type IpsecRevisionRestoreState = IpsecServerInitState
|
|
export interface IpsecRevisionRestoreCommand { action: "create" | "update" | "delete"; path: string; id?: string; fields: Row; expectedFields?: Row }
|
|
const fail = (message: string, code = "STATE_CONFLICT") => new McpError(code, message, code === "STATE_UNAVAILABLE" ? 502 : 409)
|
|
const idKey = (value: string) => value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/, "*")
|
|
const nativeId = (value: string) => /^\*[a-z0-9]+$/i.test(value) && value.length <= 100
|
|
const paths = { peers: "/ip/ipsec/peer", identities: "/ip/ipsec/identity", modeConfigs: "/ip/ipsec/mode-config", pools: "/ip/pool", policies: "/ip/ipsec/policy", nat: "/ip/firewall/nat" }
|
|
const kinds: Record<string, string> = { "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/ip/ipsec/policy": "ipsec_policy", "/ip/firewall/nat": "ip_nat", "/certificate": "certificate", "/ip/ipsec/profile": "ipsec_profile", "/ip/ipsec/proposal": "ipsec_proposal", "/ip/ipsec/policy/group": "ipsec_policy_group", "/interface": "interface", "/interface/list": "interface_list" }
|
|
const refs: Record<string, string> = { peer: "/ip/ipsec/peer", "mode-config": "/ip/ipsec/mode-config", "address-pool": "/ip/pool", "next-pool": "/ip/pool", certificate: "/certificate", "remote-certificate": "/certificate", ca: "/certificate", profile: "/ip/ipsec/profile", proposal: "/ip/ipsec/proposal", group: "/ip/ipsec/policy/group", "policy-template-group": "/ip/ipsec/policy/group", "out-interface": "/interface", "out-interface-list": "/interface/list" }
|
|
const owned = (path: string, row: Row) => path === paths.modeConfigs ? isManagedIpsecModeConfig(row) : isIpsecManagedComment(row.comment)
|
|
const matches = (value: string, row: Row) => value.trim() === row.name || (nativeId(value.trim()) && idKey(value.trim()) === idKey(row[".id"]))
|
|
const tokens = (catalogs: Record<string, Row[]>, path: string, value: string) => catalogs[path]?.some(row => matches(value, row)) ? [value] : value.split(",").map(part => part.trim())
|
|
function protect(row: Row) { for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("Системный объект не может быть целью отката IPsec", "PROTECTED_OBJECT") }
|
|
|
|
/** Restores every recorded field. Snapshot policy rows omit native identity and
|
|
* template/security context: they may update only a uniquely matched existing
|
|
* managed policy. Missing policies are rejected before any native effect. */
|
|
export function planIpsecRevisionRestore(state: IpsecRevisionRestoreState, raw: unknown) {
|
|
const desired = parseIpsecSnapshot(raw)
|
|
validateIpsecServerInitState(state, true)
|
|
for (const path of ["/interface/list", "/interface/list/member"]) {
|
|
const rows = state.catalogs[path]
|
|
if (!Array.isArray(rows) || rows.length > 2000 || rows.some(row => !row || !nativeId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(rows.map(row => idKey(row[".id"]))).size !== rows.length) throw fail("Неполный каталог зависимостей NAT", "STATE_UNAVAILABLE")
|
|
}
|
|
const c = state.catalogs, commands: IpsecRevisionRestoreCommand[] = [], upserts: IpsecRevisionRestoreCommand[] = [], deletes: IpsecRevisionRestoreCommand[] = []
|
|
const targets = new Set<string>(), desiredRows = new Map<string, Row[]>(), desiredKeys = new Map<string, Set<string>>()
|
|
for (const [section, path] of Object.entries(paths)) {
|
|
const rows: Array<Record<string, unknown>> = desired[section as keyof typeof paths].map(row => ({ ...row }))
|
|
const keyField = ["identities", "policies", "nat"].includes(section) ? "comment" : "name"
|
|
if (new Set(rows.map(row => row[keyField])).size !== rows.length) throw fail("Неоднозначный маркер объекта ревизии IPsec")
|
|
desiredKeys.set(path, new Set(rows.map(row => String(row[keyField]))))
|
|
const current = c[path].filter(row => !(path === paths.policies && observedBoolean(row.dynamic) === true))
|
|
const currentKeys = current.map(row => row[keyField]?.trim()).filter(Boolean)
|
|
if (new Set(currentKeys).size !== currentKeys.length) throw fail("Неоднозначное имя или маркер native объекта IPsec")
|
|
const planned: Row[] = []
|
|
for (const want of rows) {
|
|
const key = String(want[keyField]), live = current.find(row => row[keyField]?.trim() === key)
|
|
const marker = section === "modeConfigs" ? isManagedIpsecModeConfig({ name: String(want.name), comment: String(want.comment) }) : isIpsecManagedComment(String(want.comment))
|
|
if (!marker) throw fail("Ревизия содержит чужой объект IPsec", "PROTECTED_OBJECT")
|
|
if (live) { if (live[keyField] !== key || !owned(path, live)) throw fail("Имя или маркер ревизии занят чужим объектом", "PROTECTED_OBJECT"); protect(live) }
|
|
let fields: Row
|
|
if (section === "peers") {
|
|
// RouterOS versions differ on legacy peer.certificate support. Avoid
|
|
// silently discarding the recorded value or guessing a native capability.
|
|
if (String(want.certificate) !== (live?.certificate ?? "")) throw fail("Изменение legacy peer.certificate не подтверждено данной схемой RouterOS; нужен отдельный native план", "UNSUPPORTED_CAPABILITY")
|
|
if (!live && (!want.profile || !want.address || !want.exchangeMode)) throw fail("Новый peer не может подтвердить пустые profile/address/exchange-mode: RouterOS подставляет native defaults", "UNSUPPORTED_CAPABILITY")
|
|
fields = { name: String(want.name), address: String(want.address), "exchange-mode": String(want.exchangeMode), passive: want.passive ? "yes" : "no", profile: String(want.profile), comment: String(want.comment), disabled: want.disabled ? "yes" : "no" }
|
|
} else if (section === "identities") {
|
|
if (!["pre-shared-key", "digital-signature"].includes(String(want.authMethod))) throw fail("Метод auth-method ревизии не поддержан проверенным откатом; скрытый секрет неизвестного метода восстановить нельзя", "UNSUPPORTED_CAPABILITY")
|
|
if (want.authMethod === "digital-signature" && (!want.certificate || want.certificate === "none")) throw fail("Ревизия digital-signature identity не содержит серверный сертификат", "DEPENDENCY_CONFLICT")
|
|
if (want.authMethod === "pre-shared-key" && isHiddenSecret(String(want.secret)) && (!live || live["auth-method"] !== "pre-shared-key" || !live.secret)) throw fail("Скрытый PSK новой identity или неизвестный прежний PSK нельзя восстановить без значения секрета", "UNSUPPORTED_CAPABILITY")
|
|
fields = { peer: String(want.peerName), "auth-method": String(want.authMethod), certificate: String(want.certificate), "remote-certificate": String(want.remoteCertificate), "match-by": String(want.matchBy), "remote-id": String(want.remoteId), "mode-config": String(want.modeConfig), "generate-policy": String(want.generatePolicy), ...(want.policyTemplateGroup !== undefined ? { "policy-template-group": String(want.policyTemplateGroup) } : {}), comment: String(want.comment), disabled: want.disabled ? "yes" : "no", ...(!isHiddenSecret(String(want.secret)) ? { secret: String(want.secret) } : {}) }
|
|
} else if (section === "modeConfigs") {
|
|
if (!live) throw fail("Снимок mode-config не содержит responder/address-prefix-length; отсутствующий объект нельзя безопасно восстановить", "UNSUPPORTED_CAPABILITY")
|
|
if (String(want.comment) !== (live?.comment ?? "")) throw fail("Схема RouterOS mode-config не подтверждает запись comment; поле ревизии требует отдельного native плана", "UNSUPPORTED_CAPABILITY")
|
|
fields = { name: String(want.name), "address-pool": String(want.addressPool), address: String(want.address), "static-dns": String(want.staticDns) }
|
|
} else if (section === "pools") {
|
|
if (!live && !want.ranges) throw fail("Новый IP pool не может восстановить пустые ranges", "UNSUPPORTED_CAPABILITY")
|
|
fields = { name: String(want.name), ranges: String(want.ranges), comment: String(want.comment) }
|
|
}
|
|
else if (section === "policies") {
|
|
if (!live) throw fail("Ревизия политики не содержит template/group/action/tunnel/peer: отсутствующую native policy невозможно безопасно восстановить", "UNSUPPORTED_CAPABILITY")
|
|
fields = { "src-address": String(want.srcAddress), "dst-address": String(want.dstAddress), proposal: String(want.proposal), comment: String(want.comment) }
|
|
} else {
|
|
if (want.action === "masquerade" && !want.outInterface && !want.outInterfaceList) throw fail("Ревизия NAT не содержит исходящий интерфейс", "UNSUPPORTED_CAPABILITY")
|
|
fields = { chain: String(want.chain), action: String(want.action), "src-address": String(want.srcAddress), comment: String(want.comment), "out-interface": String(want.outInterface ?? ""), "out-interface-list": String(want.outInterfaceList ?? ""), "ipsec-policy": String(want.ipsecPolicy ?? "") }
|
|
}
|
|
// Empty fields in a create are omitted only when no previous value exists;
|
|
// exact PATCH clears remain explicit and are checked after dispatch.
|
|
const expectedFields = { ...fields, ...(section === "peers" ? { certificate: String(want.certificate) } : {}) }
|
|
if (!live) fields = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== ""))
|
|
const command = { action: live ? "update" : "create", path, fields, ...(live ? { id: live[".id"] } : { expectedFields }) } as IpsecRevisionRestoreCommand
|
|
upserts.push(command)
|
|
if (live) targets.add(`${path}:${live[".id"]}`)
|
|
planned.push({ ...(live ?? { ".id": `*planned${upserts.length}` }), ...fields })
|
|
}
|
|
desiredRows.set(path, planned)
|
|
for (const live of current) if (owned(path, live) && !desiredKeys.get(path)!.has(live[keyField])) { protect(live); deletes.push({ action: "delete", path, id: live[".id"], fields: {} }); targets.add(`${path}:${live[".id"]}`) }
|
|
}
|
|
// Every foreign consumer of any changed native target blocks the whole plan,
|
|
// including CSV references and case/zero-normalized native aliases.
|
|
for (const [path, rows] of Object.entries(c)) for (const row of rows) {
|
|
if (path === paths.policies && observedBoolean(row.dynamic) === true) continue
|
|
if (owned(path, row)) continue
|
|
for (const [field, parentPath] of Object.entries(refs)) {
|
|
if (!row[field]) continue
|
|
for (const token of tokens(c, parentPath, row[field])) if (c[parentPath]?.some(parent => matches(token, parent) && targets.has(`${parentPath}:${parent[".id"]}`))) throw fail("Откат затрагивает ссылку чужой конфигурации IPsec", "DEPENDENCY_CONFLICT")
|
|
}
|
|
}
|
|
const final = structuredClone(c)
|
|
const poolTargets = c[paths.pools].filter(row => targets.has(`${paths.pools}:${row[".id"]}`))
|
|
const allowedPoolConsumers = [paths.pools, paths.modeConfigs].flatMap(path => c[path].filter(row => owned(path, row)).map(row => ({ path, id: row[".id"] })))
|
|
assertPoolMutationDependencies(c, poolTargets, allowedPoolConsumers)
|
|
for (const [path, rows] of desiredRows) final[path] = [...c[path].filter(row => !owned(path, row)), ...rows]
|
|
const resolve = (path: string, value: string) => { const found = final[path]?.filter(row => matches(value, row)) ?? []; if (found.length !== 1) throw fail("Не подтверждена точная зависимость ревизии IPsec", "DEPENDENCY_CONFLICT"); return found[0] }
|
|
for (const [path, rows] of desiredRows) for (const row of rows) for (const [field, parentPath] of Object.entries(refs)) {
|
|
const value = row[field]
|
|
if (!value) continue
|
|
for (const token of tokens(final, parentPath, value)) {
|
|
const sentinels: Record<string, string[]> = { peer: ["none"], "mode-config": ["none", "request-only"], "address-pool": ["none", "static-only"], "next-pool": ["none"], certificate: ["none"], "remote-certificate": ["none"] }
|
|
if ((sentinels[field] ?? []).includes(token) && !final[parentPath]?.some(parent => matches(token, parent))) continue
|
|
const parent = resolve(parentPath, token)
|
|
if (parentPath === "/certificate") {
|
|
if (!parent["invalid-after"]?.trim() || !parent.fingerprint?.trim()) throw fail("Сертификат ревизии не подписан или недоступен", "DEPENDENCY_CONFLICT")
|
|
if (field === "certificate" && (path === paths.peers || (path === paths.identities && row["auth-method"] === "digital-signature")) && observedBoolean(parent["private-key"]) !== true) throw fail("Приватный ключ серверного сертификата ревизии отсутствует", "DEPENDENCY_CONFLICT")
|
|
if (parent.ca) for (const issuer of tokens(final, "/certificate", parent.ca)) resolve("/certificate", issuer)
|
|
}
|
|
}
|
|
}
|
|
const early = deletes.filter(command => [paths.identities, paths.nat, paths.policies].includes(command.path))
|
|
const late = deletes.filter(command => !early.includes(command))
|
|
const order = [paths.pools, paths.modeConfigs, paths.peers, paths.policies, paths.identities, paths.nat]
|
|
const poolDeletes = late.filter(command => command.path === paths.pools), orderedPoolDeletes: IpsecRevisionRestoreCommand[] = []
|
|
const poolEdges = ipsecPoolDependencies(c).filter(edge => edge.path === paths.pools)
|
|
while (poolDeletes.length) {
|
|
const index = poolDeletes.findIndex(command => !poolEdges.some(edge => idKey(edge.poolId) === idKey(command.id!) && poolDeletes.some(other => idKey(other.id!) === idKey(edge.id))))
|
|
if (index < 0) throw fail("Не подтверждён порядок удаления цепочки пулов IPsec")
|
|
orderedPoolDeletes.push(poolDeletes.splice(index, 1)[0])
|
|
}
|
|
commands.push(...early, ...upserts.sort((a, b) => order.indexOf(a.path) - order.indexOf(b.path)), ...late.filter(command => command.path !== paths.pools).sort((a, b) => [paths.modeConfigs, paths.peers].indexOf(a.path) - [paths.modeConfigs, paths.peers].indexOf(b.path)), ...orderedPoolDeletes)
|
|
if (commands.length > 1000) throw fail("Откат IPsec превышает полный бюджет native команд", "STATE_UNAVAILABLE")
|
|
const companions = Object.entries(c).flatMap(([path, rows]) => rows.map(row => ({ kind: kinds[path] ?? path, id: row[".id"] })))
|
|
return { commands, companions, desired }
|
|
}
|
|
|
|
/** Only ACK-assigned new rows may admit native defaults. Explicit PATCH clears
|
|
* may read back as an absent property; no other omission is admitted. */
|
|
export function projectIpsecRevisionRestore(state: IpsecRevisionRestoreState, command: IpsecRevisionRestoreCommand, options: { assignedId?: string; observedRow?: Row } = {}) {
|
|
const next = structuredClone(state), rows = next.catalogs[command.path]
|
|
if (!rows) throw fail("Неизвестный каталог отката", "STATE_UNAVAILABLE")
|
|
if (command.action === "delete") {
|
|
const index = rows.findIndex(row => row[".id"] === command.id); if (index < 0) throw fail("Объект удаления отсутствует")
|
|
rows.splice(index, 1)
|
|
} else if (command.action === "update") {
|
|
const row = rows.find(item => item[".id"] === command.id)
|
|
if (!row) throw fail("Объект изменения отсутствует")
|
|
for (const [key, value] of Object.entries(command.fields)) {
|
|
if (value === "" && options.observedRow && !Object.hasOwn(options.observedRow, key)) delete row[key]
|
|
else row[key] = value
|
|
}
|
|
} else {
|
|
const row = options.observedRow, id = options.assignedId
|
|
if (!id || !nativeId(id) || !row || row[".id"] !== id || rows.some(existing => idKey(existing[".id"]) === idKey(id)) || Object.values(row).some(value => typeof value !== "string")) throw fail("Не подтверждён ACK новой строки отката", "VERIFICATION_FAILED")
|
|
protect(row)
|
|
for (const [key, value] of Object.entries(command.expectedFields ?? command.fields)) {
|
|
// Explicitly recorded emptiness may be represented as an absent optional
|
|
// native property. A nonempty provider default is never equivalent.
|
|
if (value === "" && (row[key] === undefined || row[key] === "")) continue
|
|
if (row[key] !== value && !(["disabled", "responder", "passive"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Записанные поля нового объекта отката не подтверждены", "VERIFICATION_FAILED")
|
|
}
|
|
rows.push(structuredClone(row))
|
|
}
|
|
return next
|
|
}
|