diff --git a/backend/src/modules/mcp/ipsec-certificate-delete-actions.ts b/backend/src/modules/mcp/ipsec-certificate-delete-actions.ts index 71996f9e..7d948292 100644 --- a/backend/src/modules/mcp/ipsec-certificate-delete-actions.ts +++ b/backend/src/modules/mcp/ipsec-certificate-delete-actions.ts @@ -1,8 +1,9 @@ import { z } from "zod" +import { coalesceAuthorization } from "./authorization-stage.js" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { deleteIpsecCertificateGuarded, readIpsecCertificateDeleteState, ipsecCertificateDeleteTarget, projectIpsecCertificateDelete, ipsecCertificateDeleteSchema } from "../../services/ipsec-certificate-delete.js" import { ipsecPeerDeleteProof } from "../../services/ipsec-peer-delete.js" import { maskNetworkSecrets, networkSecretValues } from "../../services/network-observed-read.js" @@ -25,8 +26,11 @@ async function access(input: Record, signal?: AbortSignal) { if (fingerprint(request) !== input.requestProof || fingerprint(current.policy) !== input.policyProof || fingerprint(current.owner_permissions) !== input.ownerProof || await accessGeneration() !== input.generation) throw new McpError("RESET_REQUIRED", "Допуск или запрос IPsec изменился", 409) if (signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение IPsec отменено", 409) } -async function source(input: Record, signal?: AbortSignal, allow: () => Promise = async () => {}) { - const authorize = async () => { await allow(); await access(input, signal) } +async function source(input: Record, signal?: AbortSignal, allow?: () => Promise) { + // Service checks once per stage (reads reuse a proof younger than 2 s); every native write still + // re-proves MCP rights and protections in executeGuardedConfigurationWrite. Reconcile (allow given) + // stays strict: a revocation stops its very next read. + const check = async () => { await allow?.(); await access(input, signal) }, authorize = allow ? check : coalesceAuthorization(check).coalesced await authorize() const { server } = await routerClient(Number(input.serverId)), state = await readIpsecCertificateDeleteState(server, authorize) if (input.expectedSource !== undefined && input.expectedSource !== state.source) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился после подготовки", 409) @@ -78,7 +82,7 @@ export function registerIpsecCertificateDeleteActions(register: typeof add) { registerMcpService(operation, { current, execute: async input => { const before = await source(input) - return deleteIpsecCertificateGuarded(before.server, String(input.name), input.force === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }, { receiptId: String(input.receiptId), checkpoint: async value => { + return deleteIpsecCertificateGuarded(before.server, String(input.name), input.force === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }, { receiptId: String(input.receiptId), checkpoint: async value => { await assertVerifiedConfigurationAccess(); await before.authorize() await audit(pool, String(input.ownerId), "ipsec.certificate.delete.checkpoint", (input.principal as { connectionId: string }).connectionId, { ...value, receiptId: input.receiptId, inputProof: fingerprint(redact(input)) }) } }) diff --git a/backend/src/modules/mcp/ipsec-peer-delete-actions.ts b/backend/src/modules/mcp/ipsec-peer-delete-actions.ts index e5e811b0..fff6d20b 100644 --- a/backend/src/modules/mcp/ipsec-peer-delete-actions.ts +++ b/backend/src/modules/mcp/ipsec-peer-delete-actions.ts @@ -1,8 +1,9 @@ import { z } from "zod" +import { coalesceAuthorization } from "./authorization-stage.js" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { deleteIpsecPeerGuarded, readIpsecPeerDeleteState, ipsecPeerDeleteTarget, projectIpsecPeerDelete, ipsecPeerDeleteProof } from "../../services/ipsec-peer-delete.js" import { effectiveMcpConnection } from "./store.js" import { routerClient } from "./resources.js" @@ -23,8 +24,11 @@ async function access(input: Record, signal?: AbortSignal) { if (fingerprint(request) !== input.requestProof || fingerprint(current.policy) !== input.policyProof || fingerprint(current.owner_permissions) !== input.ownerProof || await accessGeneration() !== input.generation) throw new McpError("RESET_REQUIRED", "Допуск или запрос IPsec изменился", 409) if (signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение IPsec отменено", 409) } -async function source(input: Record, signal?: AbortSignal, allow: () => Promise = async () => {}) { - const authorize = async () => { await allow(); await access(input, signal) } +async function source(input: Record, signal?: AbortSignal, allow?: () => Promise) { + // Service checks once per stage (reads reuse a proof younger than 2 s); every native write still + // re-proves MCP rights and protections in executeGuardedConfigurationWrite. Reconcile (allow given) + // stays strict: a revocation stops its very next read. + const check = async () => { await allow?.(); await access(input, signal) }, authorize = allow ? check : coalesceAuthorization(check).coalesced await authorize() const { server } = await routerClient(Number(input.serverId)), state = await readIpsecPeerDeleteState(server, authorize) if (input.expectedSource !== undefined && input.expectedSource !== state.source) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился после подготовки", 409) @@ -53,7 +57,7 @@ export function registerIpsecPeerDeleteActions(register: typeof add) { registerMcpService(operation, { current, execute: async input => { const before = await source(input) - return deleteIpsecPeerGuarded(before.server, String(input.peerId), input.force === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }, { receiptId: String(input.receiptId) }) + return deleteIpsecPeerGuarded(before.server, String(input.peerId), input.force === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }, { receiptId: String(input.receiptId) }) }, verify: async (input, result) => { const latest = await source(input), candidate = { connection_id: (input.principal as { connectionId: string }).connectionId, state: "verified", intended_state: redact({ kind: "service", service: operation, input }), result } diff --git a/backend/src/modules/mcp/ipsec-peer-update-actions.ts b/backend/src/modules/mcp/ipsec-peer-update-actions.ts index ee17380b..8900a040 100644 --- a/backend/src/modules/mcp/ipsec-peer-update-actions.ts +++ b/backend/src/modules/mcp/ipsec-peer-update-actions.ts @@ -1,8 +1,9 @@ import { z } from "zod" +import { coalesceAuthorization } from "./authorization-stage.js" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { ipsecPeerUpdatePatchSchema, ipsecPeerUpdateNativePatch, planIpsecPeerUpdate, readIpsecPeerUpdateState, ipsecPeerUpdateProof, updateIpsecPeerGuarded } from "../../services/ipsec-peer-update.js" import { effectiveMcpConnection, audit } from "./store.js" import { routerClient } from "./resources.js" @@ -23,8 +24,10 @@ async function access(input:Record,signal?:AbortSignal){ if(fingerprint(request)!==input.requestProof||fingerprint(current.policy)!==input.policyProof||fingerprint(current.owner_permissions)!==input.ownerProof||await accessGeneration()!==input.generation)throw new McpError("RESET_REQUIRED","Допуск или запрос IPsec изменился",409) if(signal?.aborted)throw new McpError("READ_CANCELLED","Чтение IPsec отменено",409) } -async function source(input:Record,signal?:AbortSignal,allow:()=>Promise=async()=>{}){ - const authorize=async()=>{await allow();await access(input,signal)} +async function source(input:Record,signal?:AbortSignal,allow?:()=>Promise){ + // Service checks once per stage (reads reuse a proof younger than 2 s); every native write still + // re-proves MCP rights and protections in executeGuardedConfigurationWrite. + const check=async()=>{await allow?.();await access(input,signal)},authorize=allow?check:coalesceAuthorization(check).coalesced await authorize() const{server}=await routerClient(Number(input.serverId)),state=await readIpsecPeerUpdateState(server,authorize) if(input.expectedSource!==undefined&&input.expectedSource!==state.source)throw new McpError("STATE_CONFLICT","Источник IPsec изменился",409) @@ -56,7 +59,7 @@ export function registerIpsecPeerUpdateActions(register:typeof add){ current:async input=>({proof:(await source(input)).state.proof}), execute:async input=>{ const before=await source(input) - return updateIpsecPeerGuarded(before.server,String(input.peerId),input.patch,String(input.expectedProof),async()=>{await assertVerifiedConfigurationAccess();await before.authorize()},{receiptId:String(input.receiptId),checkpoint:async value=>{await assertVerifiedConfigurationAccess();await before.authorize();await audit(pool,String(input.ownerId),"ipsec.peer.update.checkpoint",(input.principal as{connectionId:string}).connectionId,{...value,inputProof:fingerprint(redact(input))})}}) + return updateIpsecPeerGuarded(before.server,String(input.peerId),input.patch,String(input.expectedProof),async()=>{await assertVerifiedConfigurationReadAccess();await before.authorize()},{receiptId:String(input.receiptId),checkpoint:async value=>{await assertVerifiedConfigurationAccess();await before.authorize();await audit(pool,String(input.ownerId),"ipsec.peer.update.checkpoint",(input.principal as{connectionId:string}).connectionId,{...value,inputProof:fingerprint(redact(input))})}}) }, verify:async(input,result)=>{const latest=await source(input);return hasVerifiedIpsecPeerUpdate({connection_id:(input.principal as{connectionId:string}).connectionId,state:"verified",intended_state:redact({kind:"service",service:operation,input}),result},input,latest.state.proof)}, reconcile:async(input,allow)=>{ diff --git a/backend/src/modules/mcp/ipsec-user-delete-actions.ts b/backend/src/modules/mcp/ipsec-user-delete-actions.ts index 30048e62..742214b6 100644 --- a/backend/src/modules/mcp/ipsec-user-delete-actions.ts +++ b/backend/src/modules/mcp/ipsec-user-delete-actions.ts @@ -1,8 +1,9 @@ import { z } from "zod" +import { coalesceAuthorization } from "./authorization-stage.js" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { deleteIpsecUserGuarded, readIpsecUserDeleteState, planIpsecUserDelete, ipsecUserDeleteStageProofs } from "../../services/ipsec-user-delete.js" import { effectiveMcpConnection, audit } from "./store.js" import { routerClient } from "./resources.js" @@ -23,8 +24,11 @@ async function access(input: Record, signal?: AbortSignal) { if (fingerprint(request) !== input.requestProof || fingerprint(current.policy) !== input.policyProof || fingerprint(current.owner_permissions) !== input.ownerProof || await accessGeneration() !== input.generation) throw new McpError("RESET_REQUIRED", "Допуск или запрос IPsec изменился", 409) if (signal?.aborted) throw new McpError("READ_CANCELLED", "Чтение IPsec отменено", 409) } -async function source(input: Record, signal?: AbortSignal, allow: () => Promise = async () => {}) { - const authorize = async () => { await allow(); await access(input, signal) } +async function source(input: Record, signal?: AbortSignal, allow?: () => Promise) { + // Service checks once per stage (reads reuse a proof younger than 2 s); every native write still + // re-proves MCP rights and protections in executeGuardedConfigurationWrite. Reconcile (allow given) + // stays strict: a revocation stops its very next read. + const check = async () => { await allow?.(); await access(input, signal) }, authorize = allow ? check : coalesceAuthorization(check).coalesced await authorize() const { server } = await routerClient(Number(input.serverId)), state = await readIpsecUserDeleteState(server, authorize) if (input.expectedSource !== undefined && input.expectedSource !== state.source) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился после подготовки", 409) @@ -54,7 +58,7 @@ export function registerIpsecUserDeleteActions(register: typeof add) { registerMcpService(operation, { current, execute: async input => { const before = await source(input) - return deleteIpsecUserGuarded(before.server, String(input.clientId), input.removeCertificate === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }, { receiptId: String(input.receiptId), checkpoint: async value => { + return deleteIpsecUserGuarded(before.server, String(input.clientId), input.removeCertificate === true, String(input.expectedProof), async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }, { receiptId: String(input.receiptId), checkpoint: async value => { await assertVerifiedConfigurationAccess(); await before.authorize() await audit(pool, String(input.ownerId), "ipsec.user.delete.checkpoint", (input.principal as { connectionId: string }).connectionId, { ...value, inputProof: fingerprint(redact(input)) }) } }) diff --git a/backend/src/modules/mcp/routing-community-context.ts b/backend/src/modules/mcp/routing-community-context.ts index f706e360..8b19e3e6 100644 --- a/backend/src/modules/mcp/routing-community-context.ts +++ b/backend/src/modules/mcp/routing-community-context.ts @@ -1,4 +1,5 @@ import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js" +import { coalesceAuthorization } from "./authorization-stage.js" import { prepareOriginalEffectSelection } from "./routing-original-effects.js" import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing" import { pool } from "../../db/index.js" @@ -57,6 +58,8 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions if (options.managementTransport) await assertManagementTransport(options.managementTransport) if (unavailableIds.length && unavailableSourcesProof !== sign("unavailable-sources:" + fingerprint(await readRoutingEndpoints(unavailableIds)))) throw new McpError("STATE_CONFLICT", "Недоступный источник контекста пути изменился", 409) } + // Per-GET fence: reuses a proof from the current stage (2 s). Phase boundaries and callers use fence(). + const readFence = coalesceAuthorization(fence).coalesced const rawProof: unknown[] = [{ unavailableIds, unavailableSourcesProof }], caches = new Map(), failures = new Map() let totalRows = 0, totalBytes = 0, calls = 0 const budget = (value: unknown) => { @@ -67,7 +70,7 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions const key = serverId + path, cached = caches.get(key) if (cached) return cached if (failures.has(key)) throw failures.get(key) - await fence() + await readFence() const client = clients.get(serverId) if (!client) throw new McpError("DEVICE_UNAVAILABLE", "Источник кандидата отсутствует или отключён", 409) let value: unknown @@ -85,7 +88,7 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions caches.set(key, rows); rawProof.push({ serverId, path, rows: rows.map(stable) }); return rows } const post = async (serverId: number, path: string, body: Record) => { - await fence(); const value = await clients.get(serverId)!.post(path, body); budget(value); rawProof.push({ serverId, path, body, value }); return value + await readFence(); const value = await clients.get(serverId)!.post(path, body); budget(value); rawProof.push({ serverId, path, body, value }); return value } const enabled = async (serverId: number, path: string, row: NativeBgpRow) => { const [result] = await readOspfEffectiveDisabled([row], id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))