fix(mcp): ускорить scoped-маршрутизацию и сервисы IPsec - проверка раз на этап для чтений
- контекст маршрута: проверка перед каждым GET (права, ключ источника, поколение, SQL) переиспользует доказательство этапа (2 с); границы фаз и внешний context.fence() по-прежнему проверяют заново; - IPsec (удаление пира, пользователя, сертификата, изменение пира): собственная проверка сервиса раз на этап для чтений, assertVerifiedConfigurationReadAccess для чтений; перед каждой нативной записью права и защиты проверяются заново (executeGuardedConfigurationWrite), checkpoint-записи аудита - свежая проверка; сверка (reconcile) остаётся строгой: отзыв прав останавливает следующее же чтение. Шарды: scoped forward/inverse/route-ai 205/240/324 -> 61/88/133 с, overlay-ipsec 175 -> 133 с (четыре приёмки IPsec 49 -> 19 с); весь набор 276 с, 149 строк на месте. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
af4203d9f1
commit
171c0e6162
5 files changed
+36
-18
No files matched your search
@@ -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<string, unknown>, 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<string, unknown>, signal?: AbortSignal, allow: () => Promise<unknown> = async () => {}) {
|
||||
const authorize = async () => { await allow(); await access(input, signal) }
|
||||
async function source(input: Record<string, unknown>, signal?: AbortSignal, allow?: () => Promise<unknown>) {
|
||||
// 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)) })
|
||||
} })
|
||||
|
||||
@@ -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<string, unknown>, 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<string, unknown>, signal?: AbortSignal, allow: () => Promise<unknown> = async () => {}) {
|
||||
const authorize = async () => { await allow(); await access(input, signal) }
|
||||
async function source(input: Record<string, unknown>, signal?: AbortSignal, allow?: () => Promise<unknown>) {
|
||||
// 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 }
|
||||
|
||||
@@ -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<string,unknown>,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<string,unknown>,signal?:AbortSignal,allow:()=>Promise<unknown>=async()=>{}){
|
||||
const authorize=async()=>{await allow();await access(input,signal)}
|
||||
async function source(input:Record<string,unknown>,signal?:AbortSignal,allow?:()=>Promise<unknown>){
|
||||
// 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)=>{
|
||||
|
||||
@@ -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<string, unknown>, 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<string, unknown>, signal?: AbortSignal, allow: () => Promise<unknown> = async () => {}) {
|
||||
const authorize = async () => { await allow(); await access(input, signal) }
|
||||
async function source(input: Record<string, unknown>, signal?: AbortSignal, allow?: () => Promise<unknown>) {
|
||||
// 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)) })
|
||||
} })
|
||||
|
||||
@@ -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<string, NativeBgpRow[]>(), failures = new Map<string, unknown>()
|
||||
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<string, string>) => {
|
||||
await fence(); const value = await clients.get(serverId)!.post<unknown>(path, body); budget(value); rawProof.push({ serverId, path, body, value }); return value
|
||||
await readFence(); const value = await clients.get(serverId)!.post<unknown>(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<NativeBgpRow & { disabled?: string }>([row], id => post(serverId, path + "/get", { ".id": id, "value-name": "disabled" }))
|
||||
|
||||
Reference in new issue
Block a user