Files
MikrotikManager/backend/src/services/config-mutation-policy.ts
T

229 lines
17 KiB
TypeScript

import { assertActiveRoutingProfileWriter } from "../modules/mcp/routing-controller-active-writer.js"
import { AsyncLocalStorage } from "node:async_hooks"
import { randomUUID } from "node:crypto"
import { performance } from "node:perf_hooks"
import { isDeepStrictEqual } from "node:util"
import type { McpPrincipal } from "../modules/mcp/store.js"
import type { McpObjectRef } from "@mmapp/contracts/mcp"
import { pool } from "../db/index.js"
import { audit, requestAccountingWrite } from "../modules/mcp/store.js"
import { McpError } from "../modules/mcp/security.js"
import { configurationMutationSignal, withApplicationMutationLock } from "./config-mutation-lock.js"
const actor = new AsyncLocalStorage<string>()
export interface VerifiedMcpServiceMetadata {
operationId:string;planId:string;operationName:string;serviceName:string;stepIndex:number;phase:"forward"
operationVersion:number;policyVersion:number;generation:string;principal:McpPrincipal;originalExpiresAt:number
/** Digests of authenticated RANDOMIZED CIPHERTEXT, never plaintext secrets. */
sealedEvidenceProof:string;sealedPayloadProof:string
originalTemporaryGrantProof:string;originalTemporaryGrantExpiresAt:number|null
/** Snapshot of the exact server-decrypted sealed step, never public plan JSON. */
serviceInput:Record<string,unknown>
}
interface VerifiedChange { active: boolean; actorId: string; connectionId: string; approved: boolean; serverIds: number[]; objects: McpObjectRef[]; serverWide: boolean; authorize?: () => Promise<void>; beforeDispatch?: () => Promise<void>; serviceExecution?:VerifiedMcpServiceMetadata }
const verified = new AsyncLocalStorage<VerifiedChange>()
declare const serviceExecutionBrand:unique symbol
export type VerifiedMcpServiceExecution=Readonly<{[serviceExecutionBrand]:true}>
type ServiceExecutionScope={context:VerifiedChange;metadata:Readonly<VerifiedMcpServiceMetadata>;scope:{actorId:string;connectionId:string;approved:boolean;serverIds:number[];objects:McpObjectRef[];serverWide:boolean};monotonicEnd:number;validatedInput:boolean;controller:AbortController;expiryTimer?:ReturnType<typeof setTimeout>}
const serviceScopes=new WeakMap<VerifiedChange,ServiceExecutionScope>(),serviceTokens=new WeakMap<object,ServiceExecutionScope>()
const deniedService=():never=>{throw new McpError("PERMISSION_DENIED","Исходный контекст MCP service step не подтверждён",403)}
function freezeService<T>(value:T):T{
const queue:unknown[]=[value],seen=new Set<object>()
while(queue.length){const item=queue.pop();if(!item||typeof item!=="object"||seen.has(item))continue;seen.add(item);for(const value of Object.values(item))queue.push(value);Object.freeze(item)}
return value
}
const serviceScope=(context:VerifiedChange)=>({actorId:context.actorId,connectionId:context.connectionId,approved:context.approved,serverIds:context.serverIds,objects:context.objects,serverWide:context.serverWide})
function checkService(entry:ServiceExecutionScope){
const context=verified.getStore(),m=entry.metadata
if(!context)return deniedService()
if(context!==entry.context||!context.active||serviceScopes.get(context)!==entry||typeof context.authorize!=="function"
||entry.controller.signal.aborted||!isDeepStrictEqual(serviceScope(context),entry.scope)||Date.now()>=m.originalExpiresAt||performance.now()>=entry.monotonicEnd)deniedService()
if(!m.principal||typeof m.principal!=="object"||m.phase!=="forward"||m.principal.connectionId!==context.connectionId||!Number.isSafeInteger(m.originalExpiresAt)
||!Number.isSafeInteger(m.stepIndex)||m.stepIndex<0||!Number.isSafeInteger(m.operationVersion)||m.operationVersion<1
||!Number.isSafeInteger(m.policyVersion)||m.policyVersion<1)return deniedService()
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i
if(typeof context.actorId!=="string"||!context.actorId.length||typeof context.approved!=="boolean"||typeof context.serverWide!=="boolean"
||!Array.isArray(context.serverIds)||context.serverIds.some(id=>!Number.isSafeInteger(id)||id<=0)||!Array.isArray(context.objects))return deniedService()
if(![m.operationId,m.planId,m.principal.connectionId,m.principal.credentialId].every(id=>typeof id==="string"&&uuid.test(id))
||![m.sealedEvidenceProof,m.sealedPayloadProof,m.originalTemporaryGrantProof].every(proof=>typeof proof==="string"&&/^[a-f0-9]{64}$/.test(proof))
||m.originalTemporaryGrantExpiresAt!==null&&(!Number.isSafeInteger(m.originalTemporaryGrantExpiresAt)||m.originalTemporaryGrantExpiresAt<m.originalExpiresAt)
||![m.operationName,m.serviceName,m.generation].every(value=>typeof value==="string"&&value.length>0&&value.length<=200&&!/[\u0000-\u001f\u007f]/.test(value))
||!m.serviceInput||Object.getPrototypeOf(m.serviceInput)!==Object.prototype||!Number.isFinite(Date.parse(m.principal.credentialExpiresAt))
||m.originalExpiresAt>Date.parse(m.principal.credentialExpiresAt))return deniedService()
if(!entry.validatedInput){
const pending:unknown[]=[m.serviceInput],seen=new Set<object>()
while(pending.length){
const value=pending.pop()
if(value===null||typeof value==="string"||typeof value==="boolean")continue
if(typeof value==="number"&&Number.isFinite(value))continue
if(!value||typeof value!=="object"||seen.has(value)||!Array.isArray(value)&&Object.getPrototypeOf(value)!==Object.prototype)return deniedService()
seen.add(value);for(const child of Object.values(value))pending.push(child)
}
entry.validatedInput=true
}
}
/** Private origin capability, not bandwidth/enrollment permission. Fresh runtime
* authorization is checked before and after every capture/inspection. */
export async function captureVerifiedMcpServiceExecution():Promise<VerifiedMcpServiceExecution>{
const context=verified.getStore(),entry=context&&serviceScopes.get(context)
if(!entry)return deniedService();checkService(entry)
await entry.context.authorize!();checkService(entry)
const token=Object.freeze(Object.create(null)) as VerifiedMcpServiceExecution
serviceTokens.set(token,entry);return token
}
export async function inspectVerifiedMcpServiceExecution(token:unknown){
const entry=token&&typeof token==="object"?serviceTokens.get(token):undefined
if(!entry)return deniedService();checkService(entry)
await entry.context.authorize!();checkService(entry)
return freezeService({...entry.metadata,ownerId:entry.scope.actorId,connectionId:entry.scope.connectionId,
approved:entry.scope.approved,serverWide:entry.scope.serverWide,serverIds:[...entry.scope.serverIds],objects:structuredClone(entry.scope.objects)})
}
/** Separate transport lifetime, never inserted into service metadata/SQL proof.
* The fixed original horizon/signal cannot be renewed by later inspection. */
export async function inspectVerifiedMcpServiceExecutionLifetime(token:unknown):Promise<Readonly<{expiresAt:number;monotonicDeadline:number;signal:AbortSignal}>>{
const entry=token&&typeof token==="object"?serviceTokens.get(token):undefined
if(!entry)return deniedService();checkService(entry)
await entry.context.authorize!();checkService(entry)
return Object.freeze({expiresAt:entry.metadata.originalExpiresAt,monotonicDeadline:entry.monotonicEnd,signal:entry.controller.signal})
}
/** Scheduler handoff may leave an active original scope, never a retired one. */
export function assertConfigurationHandoffContext(): void {
const context = verified.getStore()
if (context && !context.active) throw new Error("Verified configuration scope has completed")
}
export function assertNoVerifiedConfigurationContext(): void {
if (verified.getStore() || actor.getStore() !== undefined) throw new Error("Scheduler bootstrap inside actor or verified context")
}
export function withConfigurationActor<T>(actorId: string, work: () => Promise<T>) { return actor.run(actorId, work) }
export async function withVerifiedConfigurationChange<T>(input: Omit<VerifiedChange, "active">, work: () => Promise<T>) {
const context = { ...input, active: true }
let service:ServiceExecutionScope|undefined
if(input.serviceExecution){
const now=Date.now(),metadata=freezeService(structuredClone(input.serviceExecution)),scope=freezeService(structuredClone(serviceScope(context)))
const controller=new AbortController()
service={context,metadata,scope,monotonicEnd:performance.now()+Math.max(0,metadata.originalExpiresAt-now),validatedInput:false,controller}
const entry=service
const expire=()=>{
const remaining=Math.min(metadata.originalExpiresAt-Date.now(),entry.monotonicEnd-performance.now())
if(!Number.isFinite(remaining)||remaining<=0){controller.abort();return}
entry.expiryTimer=setTimeout(expire,Math.max(1,Math.min(2147483647,remaining)));entry.expiryTimer.unref()
}
expire()
serviceScopes.set(context,service)
}
try { return await verified.run(context, work) } finally { context.active = false;if(service){clearTimeout(service.expiryTimer);service.controller.abort()}serviceScopes.delete(context) }
}
/** Long diagnostics recheck their live grant before another request or before
* publishing telemetry; this does not create a configuration-write intent. */
export async function assertVerifiedConfigurationAccess(): Promise<void> {
const context = verified.getStore()
if (!context?.active || !context.authorize) throw new McpError("PERMISSION_DENIED", "Нет действующего контекста операции измерения", 403)
await context.authorize()
}
/** A full database replacement affects every protected domain, including non-router objects. */
export async function assertDatabaseRestoreAllowed() {
const inherited = verified.getStore(), context = inherited?.active ? inherited : undefined
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections")
for (const row of rows) {
if (row.object_ref.protection === "deny" || !context?.approved) {
const code = row.object_ref.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
await audit(pool, context?.actorId ?? actor.getStore() ?? "system", "configuration.denied", context?.connectionId ?? null, { domain: "database.restore", code })
throw new McpError(code, "Полное восстановление затрагивает защищённый объект", 409)
}
}
}
function auditConfiguration(actorId: string, action: string, connectionId: string | null, payload: unknown) {
return requestAccountingWrite(client => audit(client, actorId, action, connectionId, payload))
}
/** Common RouterOS boundary: legacy REST/scheduler cannot bypass protected objects. */
export async function executeGuardedConfigurationWrite<T>(serverId: number, method: string, path: string, work: (signal?: AbortSignal) => Promise<T>): Promise<T> {
const signal = configurationMutationSignal()
const outcomeUnknown = () => new McpError("MUTATION_OUTCOME_UNKNOWN", "Исход записи не подтверждён. Не повторяйте изменение; требуется сверка.", 503)
signal?.throwIfAborted()
const inherited = verified.getStore(), context = inherited?.active ? inherited : undefined
// A service step can contain many native writes. Revalidate its live access
// for each dispatch, rather than only once at the beginning of that step.
await context?.authorize?.()
const actorId = context?.actorId ?? actor.getStore() ?? "system"
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=$1 OR (object_ref->>'kind'='server' AND object_ref->>'id'=$1)", [String(serverId)])
for (const row of rows) {
const protection = row.object_ref as McpObjectRef & { protection: string }
// Existing UI handlers do not provide a dependency closure. Require a reviewed
// typed plan instead of guessing that their writes miss a protected object.
const matches = !context || context.serverWide || protection.kind === "server" || context.objects.some(object => object.serverId === serverId && object.kind === protection.kind && object.id === protection.id)
if (!matches) continue
if (protection.protection === "deny" || !context?.approved) {
const code = protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED"
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { serverId, method, path, code })
throw new McpError(code, protection.protection === "deny" ? "Изменение заблокировано защитой объекта. Используйте план с проверкой зависимостей." : "Защищённый объект требует подтверждённого плана изменений.", 409)
}
}
if (context && !context.serverIds.includes(serverId)) throw new McpError("SERVER_DENIED", "Шаг вышел за область плана")
await assertActiveRoutingProfileWriter(serverId)
const writeId = randomUUID(), connectionId = context?.connectionId ?? null
// Must commit before network I/O. Do not include raw RouterOS payloads/secrets.
await auditConfiguration(actorId, "configuration.intent", connectionId, { writeId, serverId, method, path })
let result: T
let dispatched = false
try {
await context?.beforeDispatch?.()
signal?.throwIfAborted()
dispatched = true
result = await work(signal)
if (signal?.aborted) throw outcomeUnknown()
}
catch (error) {
try { await auditConfiguration(actorId, "configuration.unconfirmed", connectionId, { writeId, serverId }) }
catch { if (dispatched && !(signal?.aborted && error === signal.reason)) throw outcomeUnknown() }
if (dispatched && signal?.aborted && error !== signal.reason) throw outcomeUnknown()
throw error
}
try { await auditConfiguration(actorId, "configuration.acknowledged", connectionId, { writeId, serverId }) }
catch { throw new McpError("MUTATION_OUTCOME_UNKNOWN", "Запись отправлена, но сохранение подтверждения недоступно. Не повторяйте изменение; требуется сверка.", 503) }
if (signal?.aborted) throw outcomeUnknown()
return result
}
/** Shared DB/host boundary. Caller supplies a fixed domain ID and real dependencies. */
export async function executeGuardedApplicationWrite<T>(object: { kind: string; id: string }, dependencies: "all" | number[] | (() => Promise<number[]>), work: () => Promise<T>, affectedObjects?: () => Promise<{ kind: string; id: string }[]>): Promise<T> {
return withApplicationMutationLock(async () => {
const serverIds = dependencies === "all" ? (await pool.query("SELECT id FROM servers")).rows.map(row => Number(row.id)) : typeof dependencies === "function" ? await dependencies() : dependencies
if (serverIds.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new McpError("INVALID_INPUT", "Некорректная зависимость сервера", 400)
const inherited = verified.getStore(), context = inherited?.active ? inherited : undefined, actorId = context?.actorId ?? actor.getStore() ?? "system"
await context?.authorize?.()
if (context && serverIds.some(id => !context.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Сервис затрагивает зависимость вне проверенного плана")
const objects = affectedObjects ? await affectedObjects() : []
const { rows } = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) OR (object_ref->>'kind'='server' AND object_ref->>'id'=ANY($1::text[])) OR (object_ref->>'kind'=$2 AND object_ref->>'id'=$3) OR EXISTS(SELECT 1 FROM jsonb_array_elements($4::jsonb) AS target WHERE target->>'kind'=object_ref->>'kind' AND target->>'id'=object_ref->>'id')", [serverIds.map(String), object.kind, object.id, JSON.stringify(objects)])
for (const row of rows) {
const protection = row.object_ref as { protection: string }
if (protection.protection === "deny" || !context?.approved) {
await auditConfiguration(actorId, "configuration.denied", context?.connectionId ?? null, { domain: "application", object, serverIds })
throw new McpError(protection.protection === "deny" ? "PROTECTED_OBJECT" : "APPROVAL_REQUIRED", "Изменение приложения затрагивает защищённый объект; нужен проверенный план", 409)
}
}
const writeId = randomUUID()
await auditConfiguration(actorId, "configuration.intent", context?.connectionId ?? null, { writeId, domain: "application", object, serverIds })
let result: T
try { result = await work() }
catch (error) {
try { await auditConfiguration(actorId, "configuration.unconfirmed", context?.connectionId ?? null, { writeId, domain: "application" }) }
catch { throw new McpError("MUTATION_OUTCOME_UNKNOWN", "Исход изменения не подтверждён, квитанция аудита недоступна. Требуется сверка.", 503) }
throw error
}
try { await auditConfiguration(actorId, "configuration.acknowledged", context?.connectionId ?? null, { writeId, domain: "application" }) }
catch { throw new McpError("MUTATION_OUTCOME_UNKNOWN", "Изменение сохранено, квитанция аудита недоступна; не повторяйте операцию", 503) }
return result
})
}
/** Local origin only; fixed runtime continuation supplies every original IO. */
export function inspectCurrentVerifiedServiceOrigin() {
const context = verified.getStore(), entry = context && serviceScopes.get(context)
if (!entry) return deniedService()
checkService(entry)
return entry.metadata
}