Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m5s
Docker images / frontend-image (push) Successful in 2m29s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m16s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
153 lines
17 KiB
TypeScript
153 lines
17 KiB
TypeScript
import { randomUUID } from "node:crypto"
|
|
import { z } from "zod"
|
|
import { ipsecUserCreateRequestSchema } 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 { planIpsecUserCreate } from "../../services/ipsec-user-create-model.js"
|
|
import { readIpsecUserCreateState, createIpsecUserGuarded } from "../../services/ipsec-user-create.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"
|
|
import { createIpsecUserBundleArtifact, verifyIpsecUserBundleArtifact, type IpsecUserBundleAuthority } from "./ipsec-user-create-artifact.js"
|
|
|
|
const operation = "network.ipsec.users.create"
|
|
export const ipsecUserCreateSecretPurpose = (serverId: number, clientId: string, kind: "psk" | "passphrase") => `ipsec-user-create-${kind}:${serverId}:${clientId}`
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/)
|
|
export const ipsecUserCreatePlanRequestSchema = ipsecUserCreateRequestSchema.omit({ serverId: true, psk: true, passphrase: true }).extend({ pskSecretRef: z.string().uuid().optional(), passphraseSecretRef: z.string().uuid().optional(), privateKeyExport: z.boolean().default(false) }).strict().superRefine((value, context) => {
|
|
if (value.authMethod === "pre-shared-key" && !value.pskSecretRef) context.addIssue({ code: "custom", message: "PSK требует secret reference", path: ["pskSecretRef"] })
|
|
if (value.authMethod === "certificate" && !value.privateKeyExport) context.addIssue({ code: "custom", message: "Создание сертификата включает приватный экспорт и требует явного privateKeyExport", path: ["privateKeyExport"] })
|
|
})
|
|
export const ipsecUserCreateActionSchema = z.object({ serverId: z.number().int().positive().safe(), request: ipsecUserCreatePlanRequestSchema }).strict()
|
|
const bindingSchema = ipsecUserCreateActionSchema.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: readIpsecUserCreateState, sourceProof: ipsecPeerDeleteSourceProof,
|
|
plan: planIpsecUserCreate, create: createIpsecUserGuarded, 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.create.checkpoint", connectionId, value),
|
|
artifact: createIpsecUserBundleArtifact, verifyArtifact: verifyIpsecUserBundleArtifact,
|
|
}
|
|
const conflict = () => new McpError("STATE_CONFLICT", "Клиент IPsec, источник, ссылка секрета или допуск изменились", 409)
|
|
|
|
export function hasVerifiedIpsecUserCreate(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.request.name.trim() && 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 &&
|
|
(binding.request.authMethod !== "certificate" || (z.string().uuid().safeParse(result.artifactId).success && result.humanDownloadOnly === true && result.ipsecContentReturned === false)) && !Object.hasOwn(result, "bundle")
|
|
}
|
|
|
|
/** Private binding never contains plaintext PSK. Every material resolution checks
|
|
* its current owner/purpose/server/cipher metadata before another native access. */
|
|
export function createIpsecUserCreateAdapter(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, request: binding.request }) !== 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, passphraseSecretRef, privateKeyExport: _privateKeyExport, ...request } = binding.request
|
|
const references: unknown[] = [], secrets: { psk?: string; passphrase?: string } = {}
|
|
for (const [kind, id] of [["psk", pskSecretRef], ["passphrase", passphraseSecretRef]] as const) {
|
|
if (!id) continue
|
|
const rows = await deps.query("SELECT purpose,server_id,created_by,CASE WHEN octet_length(ciphertext)<=32768 THEN ciphertext ELSE NULL END AS ciphertext FROM mcp_secrets WHERE id=$1 AND created_by=$2 LIMIT 2", [id, binding.ownerId])
|
|
const row = rows[0]
|
|
if (rows.length !== 1 || !row || row.created_by !== binding.ownerId || row.server_id !== binding.serverId || row.purpose !== ipsecUserCreateSecretPurpose(binding.serverId, binding.request.name.trim(), kind) || typeof row.ciphertext !== "string") throw new McpError("SECRET_UNAVAILABLE", "Ссылка секрета не принадлежит владельцу, серверу, клиенту и назначению IPsec", 409)
|
|
references.push({ id, ...row })
|
|
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", "Неподдерживаемый формат секрета IPsec", 409)
|
|
secrets[kind] = value
|
|
}
|
|
const referenceProof = fingerprint(references)
|
|
if (compare && referenceProof !== binding.referenceProof) throw conflict()
|
|
await access(binding, signal, external)
|
|
return { request: { ...request, serverId: binding.serverId, ...secrets }, 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 artifactAuthority = (binding: Binding, input: Record<string, unknown>): IpsecUserBundleAuthority => ({ principal: binding.principal, ownerId: binding.ownerId, policyProof: binding.policyProof, ownerProof: binding.ownerProof, generation: binding.generation, serverId: binding.serverId, clientName: binding.request.name.trim(), receiptId: binding.receiptId, sourceProof: binding.sourceProof, inputProof: fingerprint(redact(input)) })
|
|
const artifactAvailable = async (binding: Binding, input: Record<string, unknown>, result: unknown) => {
|
|
if (binding.request.authMethod !== "certificate") return true
|
|
const value = result as Record<string, unknown> | null, id = value?.artifactId
|
|
if (!z.string().uuid().safeParse(id).success) return false
|
|
return deps.verifyArtifact(String(id), artifactAuthority(binding, input), String(value?.afterProof))
|
|
}
|
|
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, request: (await material(binding, signal, external)).request }
|
|
}
|
|
const prepare = async (raw: Record<string, unknown>, context: ActionContext): Promise<ChangeEvidence> => {
|
|
const value = ipsecUserCreateActionSchema.parse(JSON.parse(JSON.stringify(ipsecUserCreateActionSchema.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, resolved.request, `mm-ipsec-${binding.receiptId}`)
|
|
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.request.name.trim(), 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.request.authMethod === "certificate" ? 1 : 0), 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.`, "PSK и passphrase принимаются только через owner/purpose/server/client secret reference; приватный bundle сохраняется зашифрованным и не возвращается модели.", ...(value.request.authMethod === "certificate" ? ["Подтверждение включает генерацию клиентского приватного ключа, подпись CA, экспорт PKCS12 и удаление временного файла на RouterOS. Содержимое читается по точному native ID: предел /file/get — 61438 байт; автоповтор при неопределённом ответе и переадресация по имени запрещены."] : []), "Каждая команда проверяет полный 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, before.request, `mm-ipsec-${binding.receiptId}`)
|
|
if (plan.commands.length !== binding.commandCount) throw conflict()
|
|
const authorize = async () => { await deps.verifiedAccess(); await before.authorize() }
|
|
await authorize()
|
|
const result = await deps.create(before.server, before.request, binding.expectedProof, authorize, { receiptId: binding.receiptId, exportPrefix: `mm-ipsec-${binding.receiptId}`, checkpoint: async value => { await authorize(); await deps.checkpoint(binding.ownerId, binding.principal.connectionId, { ...value, inputProof: fingerprint(redact(input)) }) }, saveBundle: async (bundle, afterProof) => deps.artifact(artifactAuthority(binding, input), bundle, afterProof, authorize) })
|
|
const { client: _client, bundle: _bundle, ...receipt } = result
|
|
return receipt
|
|
},
|
|
verify: async (input, result) => {
|
|
const binding = await request(input), after = await source(binding)
|
|
return hasVerifiedIpsecUserCreate({ connection_id: binding.principal.connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result }, binding, input, after.state.proof) && await artifactAvailable(binding, input, result)
|
|
},
|
|
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 && hasVerifiedIpsecUserCreate(rows[0], binding, input, latest.state.proof) && await artifactAvailable(binding, input, rows[0].result)
|
|
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 registerIpsecUserCreateActions(register: typeof add) {
|
|
const adapter = createIpsecUserCreateAdapter()
|
|
registerMcpService(operation, adapter.service)
|
|
register(operation, "mm_ipsec_user_create_plan", "Создать клиента IPsec с проверкой всех native-команд, явным приватным экспортом и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserCreateActionSchema, { version: 4, prepare: adapter.prepare })
|
|
}
|