Files
MikrotikManager/backend/src/services/vrf-production-execution.ts
T

239 lines
20 KiB
TypeScript

import { pool } from "../db/index.js"
import { readVrfProductionSnapshot } from "./vrf-production-read.js"
import { claimStoredVrfProductionTicket, type VrfTicketContext, type VrfTicketSql } from "./vrf-production-ticket-store.js"
import { inspectVrfProductionAdmission, type VrfProductionRequest, type VrfProductionSnapshot } from "./vrf-production-admission.js"
import { assertVrfProductionHistoryProvenance, assertVrfProductionTransitionCheckpoint, classifyVrfProductionTransition, openVrfProductionTransitionCheckpoint, sealVrfProductionTransitionCheckpoint, vrfProductionCheckpointCatalogs, type VrfProductionTransitionCheckpoint } from "./vrf-production-transition.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { withVrfClaimQuarantine } from "../modules/mcp/vrf-ticket-runtime.js"
import { assertVrfActionContext, vrfNativeActionFor, vrfActionContractsCurrent, type VrfAuthorityActionId } from "./vrf-production-action-binding.js"
import { findMcpOperation } from "../modules/mcp/registry.js"
import { decryptSecretExisting, encryptSecret, fingerprint, McpError, withVrfProductionSealingKey } from "../modules/mcp/security.js"
import { configurationRows, resourceById, routerClient, rosSnapshotSourceProof, type RosSnapshot, type RosStep } from "../modules/mcp/resources.js"
import { notifyVrfDiagnostic, vrfExecutionDiagnostic, type VrfExecutionDiagnostic, type VrfExecutionStage, type VrfRawReadObservation } from "./vrf-execution-diagnostic.js"
export interface VrfProductionExecutionInput {
operationId: string
planId: string
connectionId: string
ownerId: string
operationName: VrfAuthorityActionId
operationVersion: number
stepIndex: number
step: RosStep
sourceProof: string
originalSnapshots: RosSnapshot[]
/** Existing runtime authority/original grant/policy boundary. */
authorize(): Promise<unknown>
/** All original sealed dependency snapshots not explained as companions. */
assertDependencies(): Promise<unknown>
/** The existing native policy invokes this AFTER configuration.intent and
* before actual HTTP. The runtime owns the closure; never a JSON field. */
installBeforeDispatch(guard: () => Promise<void>): void
/** Private in-process observation only; never authority or public evidence. */
onDiagnostic?(value: VrfExecutionDiagnostic): unknown
}
export interface VrfProductionExecutionReceipt {
kind: "vrf-production-execution-v1"
action: VrfProductionRequest["action"]
nativeId: string
configurationVerified: true
forwardingVerified: false
}
export class VrfProductionAcknowledgedFailure extends McpError {
readonly acknowledgedWrites = 1
constructor(error: unknown) { super(error instanceof McpError ? error.code : "VERIFICATION_FAILED", "VRF native ACK получен, но финальная проверка не завершена; повтор запрещён", 409) }
}
const companionResources = new Set(["vrf", "ipv4_address", "ipv6_address", "ipv4_route", "ipv6_route", "routing_table"])
export const isVrfCompanionResource = (resource: string) => companionResources.has(resource)
function insist(value: unknown, message: string): asserts value { if (!value) throw new McpError("STATE_CONFLICT", message, 409) }
const yes = (value: unknown) => [true, "true", "yes"].includes(value as string | boolean)
export async function loadVerifiedVrfProductionHistory(input: { sql: VrfTicketSql; ownerId: string; serverId: number; sourceProof: string; nativeId?: string; secret: Uint8Array }): Promise<VrfProductionTransitionCheckpoint | undefined> {
if (!input.nativeId) return undefined
const history = await input.sql.query(`SELECT cp.after_sealed FROM mcp_operation_checkpoints cp
JOIN mcp_operation_steps st ON st.operation_id=cp.operation_id AND st.step_index=cp.step_index
JOIN mcp_operations o ON o.id=st.operation_id JOIN mcp_connections c ON c.id=o.connection_id
WHERE o.state='applied' AND st.state='verified' AND c.owner_id=$1
AND st.server_id=$2 AND st.result->>'kind'='vrf-production-execution-v1'
AND st.result->>'nativeId'=$3 AND cp.after_sealed IS NOT NULL
ORDER BY o.finished_at DESC,o.id DESC LIMIT 1`, [input.ownerId, input.serverId, input.nativeId])
if (!history.rows[0]) return undefined
const value = JSON.parse(await decryptSecretExisting(history.rows[0].after_sealed as string)) as { kind: string; sealed: string }
insist(value.kind === "vrf-production-private-checkpoint-v1", "Неверная VRF private checkpoint provenance")
return openVrfProductionTransitionCheckpoint(value.sealed, { serverId: input.serverId, sourceProof: input.sourceProof, actorId: input.ownerId, nativeId: input.nativeId }, input.secret)
}
/** Read both old and new concrete closures, including after transfer/delete.
* This synthetic CREATE selection is read-only and never an execution request. */
export function vrfProductionReadSelection(step: RosStep, oldMembers: unknown): VrfProductionRequest {
const names = new Set<string>()
for (const value of [oldMembers, step.fields.interfaces]) {
if (value === undefined || value === "none" || value === "") continue
insist(typeof value === "string", "Неизвестный исходный состав VRF")
for (const name of value.split(",")) { insist(name.length > 0 && name.trim() === name && !["all", "none", "dynamic"].includes(name), "Неоднозначный состав VRF"); names.add(name) }
}
return { action: "create", fields: { name: "__read_only_vrf_closure__", interfaces: [...names].join(",") || "none" } }
}
/** No mutation/retry authority. Only an authenticated, verified private
* checkpoint can produce a boolean whole-companion comparison. */
export async function reconcileVrfProductionStep(input: { step: RosStep; ownerId: string; sourceProof: string; oldMembers: unknown; verifiedNativeId?: string; privateCheckpoint?: string; authorize(): Promise<unknown> }): Promise<{ matchesVerifiedCheckpoint: boolean | null; checkpointAvailable: boolean }> {
insist(input.step.resource === "vrf", "Неверный typed VRF reconcile")
return withVrfProductionSealingKey(async secret => {
const checkpoint = input.privateCheckpoint && input.verifiedNativeId ? openVrfProductionTransitionCheckpoint(input.privateCheckpoint, { serverId: input.step.serverId, sourceProof: input.sourceProof, actorId: input.ownerId, nativeId: input.verifiedNativeId }, secret) : undefined
const current = await readVrfProductionSnapshot({ serverId: input.step.serverId, expectedSourceProof: input.sourceProof, request: vrfProductionReadSelection(input.step, input.oldMembers), requiredCatalogs: checkpoint ? vrfProductionCheckpointCatalogs(checkpoint) : undefined, assertAuthority: input.authorize })
if (!checkpoint) return { matchesVerifiedCheckpoint: null, checkpointAvailable: false }
let matches = true
try { assertVrfProductionTransitionCheckpoint(checkpoint, current) } catch { matches = false }
await input.authorize()
return { matchesVerifiedCheckpoint: matches, checkpointAvailable: true }
})
}
/** Known transition capability, checked before dispatch. Raw post-read remains
* authoritative. This does not turn unsupported interface/default shapes into
* permission merely because the human selected productionAdmission. */
function supported(before: VrfProductionSnapshot, request: VrfProductionRequest): void {
const target = request.id ? before.catalogs.vrf.find(row => row[".id"] === request.id) : undefined
if (target && request.fields.disabled !== undefined && !yes(request.fields.disabled)) insist(!before.catalogs.routing_table.some(row => row.name === target.name && row[".id"] !== target[".id"]), "Имя включаемой VRF занято посторонней таблицей")
const names = new Set([String(target?.interfaces ?? "none"), request.fields.interfaces ?? "none"].flatMap(value => value === "none" ? [] : value.split(",")))
const changesContext = request.action !== "patch" || request.fields.name !== undefined || request.fields.interfaces !== undefined || request.fields.disabled !== undefined
if (changesContext) for (const name of names) {
const rows = before.catalogs.interface_inventory.filter(row => row.name === name)
insist(rows.length === 1 && typeof rows[0].vrf === "string", "Нет однозначной native context identity выбранного интерфейса")
}
}
/** Existing operation/step intent is required independently of the caller's
* callback. A replay, unknown step, sibling operation or raw native dispatcher
* cannot enter this executor as a fresh command. */
async function assertIntent(input: VrfProductionExecutionInput, acknowledged = false): Promise<void> {
const { rows } = await pool.query(`SELECT o.id FROM mcp_operations o
JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_connections c ON c.id=o.connection_id
JOIN mcp_operation_steps st ON st.operation_id=o.id
WHERE o.id=$1 AND p.id=$2 AND c.id=$3 AND c.owner_id=$4 AND o.state='running'
AND p.state='executing' AND p.approved_by IS NOT NULL AND p.operation_id=$5 AND p.operation_version=$6
AND p.expires_at>clock_timestamp() AND st.step_index=$7 AND st.server_id=$8 AND st.state=$9`,
[input.operationId, input.planId, input.connectionId, input.ownerId, input.operationName, input.operationVersion, input.stepIndex, input.step.serverId, acknowledged ? "applied" : "intent"])
insist(rows.length === 1, "Exact running VRF operation intent не подтверждён; повтор запрещён")
}
export async function executeVrfProductionStep(original: VrfProductionExecutionInput): Promise<VrfProductionExecutionReceipt> {
const input = { ...original, step: structuredClone(original.step), originalSnapshots: structuredClone(original.originalSnapshots) }
insist(input.step.resource === "vrf" && input.stepIndex === 0, "Неоднозначный typed VRF executor")
const request: VrfProductionRequest = { action: input.step.action === "update" ? "patch" : input.step.action, ...(input.step.id ? { id: input.step.id } : {}), fields: input.step.fields, ...(input.step.placeBeforeId ? { placeBeforeId: input.step.placeBeforeId } : {}) }
const binding = { serverId: input.step.serverId, sourceProof: input.sourceProof, actorId: input.ownerId, planId: input.planId }
const actionId = vrfNativeActionFor(input.operationName, request)
const context: VrfTicketContext = { binding, connectionId: input.connectionId, actionId,
actionVersion: input.operationName === "routing.vrf.update" ? Number(findMcpOperation(actionId)?.version) : input.operationVersion,
...(input.operationName === "routing.vrf.update" ? { authorityAction: { id: "routing.vrf.update" as const, version: input.operationVersion as 4 } } : {}) }
assertVrfActionContext(context, request)
const assertSource = async () => {
await input.authorize()
const current = await routerClient(binding.serverId)
insist(await rosSnapshotSourceProof(current.server) === binding.sourceProof, "VRF source/endpoint epoch изменился")
await input.authorize()
}
let acknowledged = false
let executorAckObserved = false, diagnosticReported = false
let stage: VrfExecutionStage = "initial-authorization", read: VrfRawReadObservation | undefined
const mark = (next: VrfExecutionStage) => { stage = next; read = undefined }
const observeRead = (value: VrfRawReadObservation) => { read = value }
const report = (error: unknown) => {
if (diagnosticReported) return
diagnosticReported = true
try {
const diagnostic = vrfExecutionDiagnostic(input.operationId, request.action, stage, error, executorAckObserved, read)
if (diagnostic) notifyVrfDiagnostic(input.onDiagnostic, diagnostic)
} catch { /* Original exception and acknowledgement handling stay authoritative. */ }
}
const authorize = async () => { await assertVerifiedConfigurationAccess(); await input.authorize(); if (!vrfActionContractsCurrent(context)) throw new McpError("PLAN_EXPIRED", "Native/public VRF contract изменился; повтор запрещён", 409); await assertIntent(input, acknowledged); await assertSource() }
try {
await authorize()
mark("sealing-key")
return await withVrfProductionSealingKey(async secret => {
mark("history-load")
const previous = await loadVerifiedVrfProductionHistory({ sql: pool, ownerId: input.ownerId, serverId: binding.serverId, sourceProof: binding.sourceProof, nativeId: request.id, secret })
mark("raw-before")
const before = await readVrfProductionSnapshot({ serverId: binding.serverId, expectedSourceProof: binding.sourceProof, request, assertAuthority: authorize, observeRead })
mark("original-dependencies")
for (const original of input.originalSnapshots) {
if (before.catalogs[original.resource] === undefined) continue
insist(original.serverId === binding.serverId && original.sourceProof === binding.sourceProof && fingerprint(configurationRows(resourceById(original.resource), before.catalogs[original.resource])) === original.fingerprint, "Original VRF dependency projection изменилась; новый raw ticket не разрешает adoption")
}
mark("history-provenance")
if (previous) assertVrfProductionHistoryProvenance(previous, before)
mark("supported-shape")
supported(before, request)
mark("ticket-lookup")
const tickets = await pool.query<{ ticket_id: string }>("SELECT ticket_id FROM vrf_production_tickets WHERE plan_id=$1 AND connection_id=$2", [input.planId, input.connectionId])
insist(tickets.rows.length === 1, "Нет единственного authentic VRF preparation ticket")
mark("ticket-claim")
const claimed = await withVrfClaimQuarantine({ operationId: input.operationId, planId: input.planId, connectionId: input.connectionId, ownerId: input.ownerId, journal: pool,
claim: () => claimStoredVrfProductionTicket({ context, request, secret, execution: { operationId: input.operationId, stepIndex: input.stepIndex }, sql: pool, ticketId: tickets.rows[0].ticket_id, snapshot: before, assertAuthority: authorize, assertCurrentSource: assertSource }) })
insist(typeof claimed.privateSealed === "string", "Нет authentic private VRF admission")
const sealed = claimed.privateSealed
mark("checkpoint-before")
const beforeJournal = await pool.query("UPDATE mcp_operation_checkpoints SET before_sealed=$3 WHERE operation_id=$1 AND step_index=$2 RETURNING operation_id", [input.operationId, input.stepIndex, await encryptSecret(JSON.stringify({ kind: "vrf-production-before-v1", before }))])
insist(beforeJournal.rows.length === 1, "Исходный private VRF checkpoint не подтверждён; dispatch запрещён")
const preDispatch = async (installed = false) => {
const prefix = installed ? "installed" : "explicit"
mark(`${prefix}-predispatch-authorization`)
await authorize()
mark(`${prefix}-predispatch-dependencies`)
await input.assertDependencies()
mark(`${prefix}-predispatch-read`)
const current = await readVrfProductionSnapshot({ serverId: binding.serverId, expectedSourceProof: binding.sourceProof, request, requiredCatalogs: Object.keys(before.catalogs), assertAuthority: authorize, observeRead })
mark(`${prefix}-predispatch-admission`)
inspectVrfProductionAdmission({ snapshot: current, binding, request, sealed, secret, now: Date.now() })
mark(`${prefix}-predispatch-final-authorization`)
await authorize()
if (installed) mark("client-call")
}
mark("install-predispatch")
input.installBeforeDispatch(() => preDispatch(true))
await preDispatch()
mark("dispatch-source")
const { client, server } = await routerClient(binding.serverId)
insist(await rosSnapshotSourceProof(server) === binding.sourceProof, "VRF dispatch source изменился")
const path = "/ip/vrf" + (request.id ? "/" + encodeURIComponent(request.id) : "")
let deleteAck: unknown
mark("client-call")
const ack = request.action === "create" ? await client.put(path, { ...request.fields, ...(request.placeBeforeId ? { "place-before": request.placeBeforeId } : {}) })
: request.action === "delete" ? (await client.delete(path, 10000, undefined, body => {
acknowledged = true
executorAckObserved = true
mark("ack-identity")
try { deleteAck = body.trim() ? JSON.parse(body) : undefined } catch { throw new McpError("VERIFICATION_FAILED", "Native VRF DELETE ACK имеет неизвестный body; повтор запрещён", 409) }
}), deleteAck) : await client.patch(path, request.fields)
executorAckObserved = true
mark("ack-identity")
const acknowledgedId = request.action === "create" && ack && typeof ack === "object" ? (ack as Record<string, unknown>)[".id"] : request.id
insist(typeof acknowledgedId === "string", "Нет точного native ACK ID; повтор запрещён")
// Receipt is already observed even if the following durable journal fails.
acknowledged = true
if (request.action !== "create" && ack && typeof ack === "object" && Object.hasOwn(ack, ".id") && (ack as Record<string, unknown>)[".id"] !== request.id) throw new McpError("VERIFICATION_FAILED", "Native VRF ACK содержит противоречащий target ID; повтор запрещён", 409)
mark("ack-journal")
try {
const ackJournal = await pool.query("UPDATE mcp_operation_steps SET state='applied',result=$3::jsonb,finished_at=clock_timestamp() WHERE operation_id=$1 AND step_index=$2 AND state='intent' RETURNING operation_id", [input.operationId, input.stepIndex, JSON.stringify({ kind: "vrf-production-ack-v1", nativeId: acknowledgedId, action: request.action })])
insist(ackJournal.rows.length === 1, "VRF ACK journal не подтверждён")
} catch (error) { report(error); throw new McpError("VRF_ACK_JOURNAL_UNCONFIRMED", "Native VRF ACK получен, durable journal не подтверждён; сверка без повтора", 409) }
mark("post-ack-authorization")
await authorize()
mark("raw-after")
const after = await readVrfProductionSnapshot({ serverId: binding.serverId, expectedSourceProof: binding.sourceProof, request: vrfProductionReadSelection(input.step, before.catalogs.vrf.find(row => row[".id"] === request.id)?.interfaces), requiredCatalogs: Object.keys(before.catalogs), assertAuthority: authorize, observeRead })
mark("transition-classification")
const classified = classifyVrfProductionTransition({ before, after, binding, request, sealed, secret, now: Date.now(), acknowledgedId, previous })
mark("post-ack-dependencies")
await input.assertDependencies()
mark("post-ack-final-authorization")
await authorize()
mark("checkpoint-after")
try {
const checkpoint = sealVrfProductionTransitionCheckpoint(classified.checkpoint, { serverId: binding.serverId, sourceProof: binding.sourceProof, actorId: binding.actorId, nativeId: acknowledgedId }, secret)
const persisted = await pool.query("UPDATE mcp_operation_checkpoints SET after_sealed=$3 WHERE operation_id=$1 AND step_index=$2 RETURNING operation_id", [input.operationId, input.stepIndex, await encryptSecret(JSON.stringify({ kind: "vrf-production-private-checkpoint-v1", sealed: checkpoint }))])
insist(persisted.rows.length === 1, "Verified private VRF checkpoint не подтверждён")
} catch (error) { report(error); throw new McpError("VRF_VERIFIED_CHECKPOINT_UNCONFIRMED", "Native VRF ACK получен, private checkpoint не подтверждён; сверка без повтора", 409) }
const receipt: VrfProductionExecutionReceipt = { kind: "vrf-production-execution-v1", action: request.action, nativeId: acknowledgedId, configurationVerified: true, forwardingVerified: false }
return receipt
}) } catch (error) { report(error); if (acknowledged) throw new VrfProductionAcknowledgedFailure(error); throw error }
}