Files
MikrotikManager/backend/src/modules/mcp/ipsec-user-update-actions.ts
T

137 lines
14 KiB
TypeScript

import { randomUUID } from "node:crypto"
import { z } from "zod"
import { ipsecUserPatchSchema } from "@mmapp/contracts/ipsec"
import { pool } from "../../db/index.js"
import { hasPermission } from "../../lib/permissions.js"
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
import { ipsecPeerDeleteSourceProof } from "../../services/ipsec-peer-delete.js"
import { planIpsecUserUpdate } from "../../services/ipsec-user-update-model.js"
import { readIpsecUserUpdateState, updateIpsecUserGuarded } from "../../services/ipsec-user-update.js"
import { routerClient } from "./resources.js"
import { effectiveMcpConnection, audit } from "./store.js"
import { encryptSecret, decryptSecret, fingerprint, McpError, redact } from "./security.js"
import { registerMcpService } from "./service-registry.js"
import type { ActionContext, ChangeEvidence } from "./action-types.js"
import type { add } from "./actions.js"
import type { McpServiceHandler } from "./service-registry.js"
const operation = "network.ipsec.users.update"
export const ipsecUserPskPurpose = (serverId: number, clientId: string) => `ipsec-user-psk:${serverId}:${clientId}`
const hash = z.string().regex(/^[a-f0-9]{64}$/)
export const ipsecUserUpdatePlanPatchSchema = ipsecUserPatchSchema.omit({ psk: true }).extend({ pskSecretRef: z.string().uuid().optional() }).strict()
export const ipsecUserUpdateActionSchema = z.object({ serverId: z.number().int().positive().safe(), clientId: z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/), patch: ipsecUserUpdatePlanPatchSchema }).strict()
const bindingSchema = ipsecUserUpdateActionSchema.extend({
operation: z.literal(operation), principal: z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string().datetime() }).strict(),
ownerId: z.string().min(1), ownerProof: hash, policyProof: hash, generation: z.string().min(1), sourceProof: hash, expectedProof: hash,
referenceProof: hash, requestProof: hash, commandCount: z.number().int().min(0).max(100), receiptId: z.string().uuid(), proofRevision: z.literal(2),
}).strict()
type Binding = z.infer<typeof bindingSchema>
const serviceInput = z.object({ serverId: z.number().int().positive().safe(), receiptId: z.string().uuid(), bindingCiphertext: z.string().min(1).max(262144) }).strict()
const production = {
connection: effectiveMcpConnection, router: routerClient, read: readIpsecUserUpdateState, sourceProof: ipsecPeerDeleteSourceProof,
plan: planIpsecUserUpdate, update: updateIpsecUserGuarded, seal: encryptSecret, open: decryptSecret, verifiedAccess: assertVerifiedConfigurationAccess,
query: async (sql: string, values: unknown[]) => (await pool.query(sql, values)).rows as Record<string, unknown>[],
checkpoint: async (ownerId: string, connectionId: string, value: unknown) => audit(pool, ownerId, "ipsec.user.update.checkpoint", connectionId, value),
}
const conflict = () => new McpError("STATE_CONFLICT", "Клиент IPsec, источник, ссылка секрета или допуск изменились", 409)
export function hasVerifiedIpsecUserUpdate(candidate: unknown, binding: Binding, input: Record<string, unknown>, proof: string): boolean {
if (!candidate || typeof candidate !== "object") return false
const row = candidate as Record<string, unknown>, result = row.result as Record<string, unknown> | undefined
return row.connection_id === binding.principal.connectionId && row.state === "verified" && fingerprint(row.intended_state) === fingerprint(redact({ kind: "service", service: operation, input })) && !!result &&
result.ok === true && result.verified === true && result.receiptId === binding.receiptId && result.clientId === binding.clientId && result.commandCount === binding.commandCount && result.completedCommands === binding.commandCount && result.confirmedWrites === binding.commandCount &&
result.historyRecorded === true && result.revisionRecorded === true && result.afterProof === proof && result.forwardingVerified === false && result.automaticReplay === false
}
/** Private binding never contains plaintext PSK. Every material resolution checks
* its current owner/purpose/server/cipher metadata before another native access. */
export function createIpsecUserUpdateAdapter(overrides: Partial<typeof production> = {}) {
const deps = { ...production, ...overrides }
const access = async (binding: Binding, signal?: AbortSignal, external: () => Promise<unknown> = async () => {}) => {
signal?.throwIfAborted(); await external()
const current = await deps.connection(binding.principal)
if (Date.parse(binding.principal.credentialExpiresAt) <= Date.now() || current.owner_id !== binding.ownerId || current.policy.status !== "active" || current.policy.mode === "observer" || current.owner_valid_until.getTime() <= Date.now() || Date.parse(current.policy.expiresAt) <= Date.now() || !current.policy.scope.operationIds.includes(operation) || !current.policy.scope.serverIds.includes(binding.serverId) || !hasPermission(current.owner_permissions, "mm:network:write") || !hasPermission(current.policy.permissions, "mm:network:write")) throw new McpError("PERMISSION_DENIED", "Нет актуального допуска изменения клиента IPsec", 403)
if (current.generation !== binding.generation || fingerprint(current.policy) !== binding.policyProof || fingerprint(current.owner_permissions) !== binding.ownerProof || fingerprint({ serverId: binding.serverId, clientId: binding.clientId, patch: binding.patch }) !== binding.requestProof) throw conflict()
signal?.throwIfAborted()
}
const material = async (binding: Binding, signal?: AbortSignal, external?: () => Promise<unknown>, compare = true) => {
await access(binding, signal, external)
const { pskSecretRef, ...patch } = binding.patch
let referenceProof = fingerprint([]), psk: string | undefined
if (pskSecretRef) {
const rows = await deps.query("SELECT purpose,server_id,created_by,CASE WHEN octet_length(ciphertext)<=16384 THEN ciphertext ELSE NULL END AS ciphertext FROM mcp_secrets WHERE id=$1 AND created_by=$2 LIMIT 2", [pskSecretRef, binding.ownerId])
const row = rows[0]
if (rows.length !== 1 || !row || row.created_by !== binding.ownerId || row.server_id !== binding.serverId || row.purpose !== ipsecUserPskPurpose(binding.serverId, binding.clientId) || typeof row.ciphertext !== "string") throw new McpError("SECRET_UNAVAILABLE", "Ссылка PSK не принадлежит владельцу, серверу и клиенту IPsec", 409)
referenceProof = fingerprint({ id: pskSecretRef, ...row })
if (compare && referenceProof !== binding.referenceProof) throw conflict()
const value = await deps.open(row.ciphertext).catch(() => { throw new McpError("SECRET_UNAVAILABLE", "Секрет PSK недоступен", 409) })
if (!z.string().min(8).max(16384).safeParse(value).success) throw new McpError("SECRET_UNAVAILABLE", "Неподдерживаемый формат PSK", 409)
psk = value
}
if (compare && referenceProof !== binding.referenceProof) throw conflict()
await access(binding, signal, external)
return { patch: { ...patch, ...(psk === undefined ? {} : { psk }) }, referenceProof }
}
const request = async (input: Record<string, unknown>) => {
const parsed = serviceInput.parse(input), binding = bindingSchema.parse(JSON.parse(await deps.open(parsed.bindingCiphertext)))
if (binding.serverId !== parsed.serverId || binding.receiptId !== parsed.receiptId) throw conflict()
return binding
}
const source = async (binding: Binding, signal?: AbortSignal, external?: () => Promise<unknown>) => {
const authorize = async () => { await material(binding, signal, external) }
await authorize()
const { server } = await deps.router(binding.serverId)
if (await deps.sourceProof(server) !== binding.sourceProof) throw conflict()
const state = await deps.read(server, authorize)
if (state.source !== binding.sourceProof) throw conflict()
await authorize(); return { server, state, authorize, patch: (await material(binding, signal, external)).patch }
}
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => {
const value = ipsecUserUpdateActionSchema.parse(JSON.parse(JSON.stringify(ipsecUserUpdateActionSchema.parse(raw))))
const binding: Binding = bindingSchema.parse({ ...value, operation, principal: context.principal, ownerId: context.connection.owner_id, ownerProof: fingerprint(context.connection.owner_permissions), policyProof: fingerprint(context.connection.policy), generation: context.connection.generation, sourceProof: "0".repeat(64), expectedProof: "0".repeat(64), referenceProof: fingerprint([]), requestProof: fingerprint(value), commandCount: 0, receiptId: randomUUID(), proofRevision: 2 })
const resolved = await material(binding, context.signal, undefined, false)
binding.referenceProof = resolved.referenceProof
const { server } = await deps.router(value.serverId)
binding.sourceProof = await deps.sourceProof(server)
const before = await source(binding, context.signal), plan = deps.plan(before.state, server, value.clientId, resolved.patch)
binding.expectedProof = before.state.proof; binding.commandCount = plan.commands.length
const objects: ChangeEvidence["objects"] = [{ kind: "server", id: String(value.serverId), serverId: value.serverId }, { kind: "ipsec_user", id: value.clientId, serverId: value.serverId }, { ...plan.target, serverId: value.serverId }, ...plan.companions.map(ref => ({ ...ref, serverId: value.serverId }))]
for (const protection of before.state.protections as Array<{ object_ref: { kind: string; id: string } }>) objects.push({ kind: protection.object_ref.kind, id: protection.object_ref.id, serverId: value.serverId })
if ((await source(binding, context.signal)).state.proof !== binding.expectedProof) throw conflict()
return { target: { scope: "servers", serverIds: [value.serverId] }, objects, snapshots: [], requiresHuman: true, mutationCost: plan.commands.length + 1, before: { proof: before.state.proof },
steps: [{ kind: "service", service: operation, input: { serverId: value.serverId, receiptId: binding.receiptId, bindingCiphertext: await deps.seal(JSON.stringify(binding)) } }],
warnings: [`Native-команд: ${plan.commands.length}; затем обязательная managed-only история IPsec. Пустой patch записывает только историю.`, ...(plan.ignoredFields.length ? [`Для выбранного клиента поля не меняют конфигурацию: ${plan.ignoredFields.join(", ")}.`] : []), "PSK принимается только через owner/purpose/server/client secret reference; закрытые данные не возвращаются модели.", "Каждая команда проверяет полный private proof, источник, защиты и ссылку секрета. Потеря ответа или несовпадение read-back останавливают операцию без повтора; передача трафика не подтверждается."] }
}
const service: McpServiceHandler = {
current: async input => ({ proof: (await source(await request(input))).state.proof }),
execute: async input => {
const binding = await request(input), before = await source(binding)
if (before.state.proof !== binding.expectedProof) throw conflict()
const plan = deps.plan(before.state, before.server, binding.clientId, before.patch)
if (plan.commands.length !== binding.commandCount) throw conflict()
const authorize = async () => { await deps.verifiedAccess(); await before.authorize() }
await authorize()
return deps.update(before.server, binding.clientId, before.patch, binding.expectedProof, authorize, { receiptId: binding.receiptId, checkpoint: async value => { await authorize(); await deps.checkpoint(binding.ownerId, binding.principal.connectionId, { ...value, inputProof: fingerprint(redact(input)) }) } })
},
verify: async (input, result) => {
const binding = await request(input), after = await source(binding)
return hasVerifiedIpsecUserUpdate({ connection_id: binding.principal.connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result }, binding, input, after.state.proof)
},
reconcile: async (input, external) => {
const binding = await request(input), latest = await source(binding, undefined, external)
await latest.authorize()
const rows = await deps.query("SELECT o.connection_id,s.state,s.intended_state,s.result FROM mcp_operation_steps s JOIN mcp_operations o ON o.id=s.operation_id WHERE o.connection_id=$1 AND s.intended_state->'input'->>'receiptId'=$2 LIMIT 2", [binding.principal.connectionId, binding.receiptId])
const verified = rows.length === 1 && hasVerifiedIpsecUserUpdate(rows[0], binding, input, latest.state.proof)
if ((await source(binding, undefined, external)).state.proof !== latest.state.proof) throw conflict()
return { matchesOriginalState: latest.state.proof === binding.expectedProof, matchesDesiredState: verified, automaticReplay: false, forwardingVerified: false }
},
}
return { prepare, service }
}
export function registerIpsecUserUpdateActions(register: typeof add) {
const adapter = createIpsecUserUpdateAdapter()
registerMcpService(operation, adapter.service)
register(operation, "mm_ipsec_user_edit_plan", "Изменить клиента IPsec с проверкой всех native-команд и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserUpdateActionSchema, { version: 2, prepare: adapter.prepare })
}