207 lines
18 KiB
TypeScript
207 lines
18 KiB
TypeScript
import { loadRoutingMainTransition, routingMainServiceScope } from "./routing-main-transition.js"
|
|
import { pool } from "../../db/index.js"
|
|
import { findMcpOperation } from "./registry.js"
|
|
import { assertScopedCommunityRequest } from "./routing-community-scoped-request.js"
|
|
import { assertPersistentScopedProfileAuthority, routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
|
|
import { loadScopedConfigurationPacket, loadScopedNetworkCheckpoint } from "./routing-community-scoped-checkpoint.js"
|
|
import { originalEffectSelectionSchema } from "./routing-original-effects.js"
|
|
import { z } from "zod"
|
|
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
|
import { hasPermission } from "../../lib/permissions.js"
|
|
import { effectiveMcpConnection } from "./store.js"
|
|
import { accessGeneration, constantEqual, decryptSecret, fingerprint, redact, McpError, privateSecretFingerprint } from "./security.js"
|
|
import { readRouteCommunityContext } from "./routing-community-context.js"
|
|
import type { ActionContext } from "./action-types.js"
|
|
|
|
// DRAFT: activation/native identity only. No new ledger, scope contract or recovery authority.
|
|
// Fixed production reader; no caller observation/signing provider is accepted.
|
|
const proof = z.string().regex(/^[a-f0-9]{64}$/)
|
|
const packetSchema = z.object({
|
|
revision: z.literal(1), profileId: z.string().uuid(), profileVersion: z.number().int().positive(),
|
|
profileProof: proof, connectionId: z.string().uuid(), credentialId: z.string().uuid(),
|
|
principalExpiresAt: z.string().datetime(), ownerId: z.string().min(1), authorityProof: proof, grantExpiresAt: z.string().datetime(),
|
|
nativeId: z.string().regex(/^\*[a-z0-9]+$/i), candidateId: z.string().min(1),
|
|
targetProof: proof, dependencyProof: proof,
|
|
sourceProofs: z.array(z.object({ serverId: z.number().int().positive(), proof }).strict()).min(1).max(1000),
|
|
observedAt: z.string().datetime(), previousProof: proof.optional(),
|
|
transition: z.object({ planId: z.string().uuid(), operationId: z.string().uuid(), checkpointProof: proof, sourceDesiredTargetProof: proof.optional() }).strict().optional(),
|
|
}).strict()
|
|
const baselineSchema = z.object({ packet: packetSchema, proof }).strict()
|
|
export type RoutingControllerBaseline = z.infer<typeof baselineSchema>
|
|
const fail = () => new McpError("STATE_CONFLICT", "Подтверждённое исходное состояние контроллера отсутствует или изменилось", 409)
|
|
const sign = (packet: unknown) => privateSecretFingerprint(fingerprint(packet), "route-ai-controller-baseline-v1")
|
|
const supportedExecution = (profile: RouteAiProfile, before: { executionAvailable?:boolean;scopedExecutionAvailable?:boolean }) => profile.table === "main" && profile.probeVrf === "main" && (!profile.bgpContext || profile.bgpContext.inputChain === "bgp-in" && profile.bgpContext.vrf === "main") ? before.executionAvailable : before.scopedExecutionAvailable
|
|
export const routingControllerScope = (profile: RouteAiProfile) => [...new Set([profile.serverId,
|
|
...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId,
|
|
...(candidate.controlProbe?.expectedHops.map(hop => hop.serverId) ?? [])])])].sort((a, b) => a - b)
|
|
|
|
export async function routingControllerBaselinePrincipal(raw: unknown) { const value = baselineSchema.parse(raw); if (!constantEqual(value.proof, await sign(value.packet))) throw fail(); return { connectionId: value.packet.connectionId, credentialId: value.packet.credentialId, credentialExpiresAt: value.packet.principalExpiresAt } }
|
|
|
|
async function authority(context: ActionContext, profile: RouteAiProfile, grantExpiresAt: string) {
|
|
if (context.signal?.aborted) throw fail()
|
|
const current = await effectiveMcpConnection(context.principal), generation = await accessGeneration()
|
|
const grant = Date.parse(grantExpiresAt)
|
|
if (!Number.isFinite(grant) || grant <= Date.now() || grant > Math.min(Date.parse(context.principal.credentialExpiresAt),
|
|
current.owner_valid_until.getTime(), Date.parse(current.policy.expiresAt)) ||
|
|
current.id !== context.principal.connectionId || current.owner_id !== context.connection.owner_id ||
|
|
current.policy.status !== "active" || current.policy.mode === "observer" || current.generation !== generation ||
|
|
routingControllerScope(profile).some(id => !current.policy.scope.serverIds.includes(id))) throw fail()
|
|
for (const permission of ["mm:network:read", "mm:network:write", "mm:filters:write"]) {
|
|
if (!hasPermission(current.owner_permissions, permission) || !hasPermission(current.policy.permissions, permission)) throw fail()
|
|
}
|
|
for (const operation of ["routing.analyze", "routing.community.switch", "routing.path.verify"]) {
|
|
if (!current.policy.scope.operationIds.includes(operation)) throw fail()
|
|
}
|
|
return fingerprint({ connectionId: current.id, principal: context.principal, ownerId: current.owner_id,
|
|
ownerPermissions: current.owner_permissions, ownerValidUntil: current.owner_valid_until,
|
|
ownerClaimsIssuedAt: current.owner_claims_issued_at, policy: current.policy, generation, grantExpiresAt })
|
|
}
|
|
|
|
/** Human plan preparation enrolls a baseline. A tick never calls this issuer.
|
|
* The sealed service step fixes NEXT version and grant before human approval. */
|
|
export async function prepareRoutingControllerBaseline(profileId: string, profileVersion: number, rawProfile: unknown,
|
|
grantExpiresAt: string, context: ActionContext): Promise<RoutingControllerBaseline> {
|
|
z.string().uuid().parse(profileId); z.number().int().positive().parse(profileVersion)
|
|
const profile = routeAiProfileSchema.parse(rawProfile)
|
|
const authorityProof = await authority(context, profile, grantExpiresAt)
|
|
const authorize = async () => { if (await authority(context, profile, grantExpiresAt) !== authorityProof) throw fail() }
|
|
const native = await readRouteCommunityContext(profile, { authorize, signal: context.signal })
|
|
const before = native.before
|
|
if (before.bgpContextMode === "legacy-read-only") throw new McpError("UNSUPPORTED_CAPABILITY", "LEGACY_BGP_READ_ONLY", 409)
|
|
if (!supportedExecution(profile,before) || !native.ownedTarget || !before.currentCandidateId || !before.targetRuleProof ||
|
|
native.ownedTarget.nativeId !== before.nativeRuleId || !profile.candidates.some(row => row.id === before.currentCandidateId)) throw fail()
|
|
await native.fence(); await authorize()
|
|
const packet = packetSchema.parse({ revision: 1, profileId, profileVersion, profileProof: fingerprint(profile),
|
|
connectionId: context.principal.connectionId, credentialId: context.principal.credentialId, principalExpiresAt: context.principal.credentialExpiresAt, ownerId: context.connection.owner_id,
|
|
authorityProof, grantExpiresAt, nativeId: native.ownedTarget.nativeId, candidateId: before.currentCandidateId,
|
|
targetProof: before.targetRuleProof, dependencyProof: before.dependencyProof, sourceProofs: before.sourceProofs,
|
|
observedAt: new Date().toISOString() })
|
|
return { packet, proof: await sign(packet) }
|
|
}
|
|
|
|
/** Fixed live comparison for profile execute and every tick boundary.
|
|
* Original grant expiry is never renewed. No mutation capability is returned. */
|
|
export async function authenticateRoutingControllerBaseline(rawBaseline: unknown, profileId: string, profileVersion: number,
|
|
rawProfile: unknown, grantExpiresAt: string, context: ActionContext) {
|
|
const parsed = baselineSchema.safeParse(rawBaseline)
|
|
if (!parsed.success) throw fail()
|
|
const value = parsed.data, packet = value.packet, profile = routeAiProfileSchema.parse(rawProfile)
|
|
if (!constantEqual(value.proof, await sign(packet)) || packet.profileId !== profileId || packet.profileVersion !== profileVersion ||
|
|
packet.profileProof !== fingerprint(profile) || packet.grantExpiresAt !== grantExpiresAt ||
|
|
packet.connectionId !== context.principal.connectionId || packet.credentialId !== context.principal.credentialId ||
|
|
packet.principalExpiresAt !== context.principal.credentialExpiresAt || packet.ownerId !== context.connection.owner_id || Date.parse(packet.observedAt) > Date.now() ||
|
|
await authority(context, profile, grantExpiresAt) !== packet.authorityProof) throw fail()
|
|
const authorize = async () => { if (await authority(context, profile, grantExpiresAt) !== packet.authorityProof) throw fail() }
|
|
return { value, profile, authorize }
|
|
}
|
|
|
|
export async function assertRoutingControllerBaseline(rawBaseline: unknown, profileId: string, profileVersion: number, rawProfile: unknown, grantExpiresAt: string, context: ActionContext) {
|
|
const { value, profile, authorize } = await authenticateRoutingControllerBaseline(rawBaseline, profileId, profileVersion, rawProfile, grantExpiresAt, context)
|
|
const packet = value.packet
|
|
const native = await readRouteCommunityContext(profile, { authorize, signal: context.signal, expectedSources: packet.sourceProofs })
|
|
if (!supportedExecution(profile,native.before) || native.ownedTarget?.nativeId !== packet.nativeId ||
|
|
native.before.nativeRuleId !== packet.nativeId || native.before.currentCandidateId !== packet.candidateId ||
|
|
native.before.targetRuleProof !== packet.targetProof || native.before.dependencyProof !== packet.dependencyProof ||
|
|
fingerprint(native.before.sourceProofs) !== fingerprint(packet.sourceProofs)) throw fail()
|
|
await native.fence(); await authorize()
|
|
return value
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Source operation, sealed input and signed CONFIG_APPLIED authorize ONLY the
|
|
* expected baseline transition. Current readback alone can never enroll drift.
|
|
* Applied configuration/control probe is not full network verification. */
|
|
export async function advanceRoutingControllerBaseline(rawBaseline: unknown, profileId: string, profileVersion: number,
|
|
rawProfile: unknown, grantExpiresAt: string, context: ActionContext, planId: string, operationId: string) {
|
|
const { value, profile, authorize } = await authenticateRoutingControllerBaseline(rawBaseline, profileId, profileVersion, rawProfile, grantExpiresAt, context)
|
|
const original = value.packet
|
|
z.string().uuid().parse(planId); z.string().uuid().parse(operationId)
|
|
const readSource = async () => {
|
|
await authorize()
|
|
const found = (await pool.query(`SELECT o.id,o.plan_id,o.state,o.created_at,p.operation_id,p.operation_version,p.approved_by,
|
|
CASE WHEN octet_length(p.evidence::text)<=1048576 THEN p.evidence END AS evidence,
|
|
s.state AS step_state,CASE WHEN octet_length(s.intended_state::text)<=1048576 THEN s.intended_state END AS intended_state,
|
|
CASE WHEN octet_length(s.result::text)<=1048576 THEN s.result END AS result
|
|
FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id
|
|
WHERE o.id=$1 AND o.plan_id=$2 AND o.connection_id=$3 AND s.step_index=0 LIMIT 2`, [operationId, planId, context.principal.connectionId])).rows
|
|
if (found.length !== 1) throw fail()
|
|
const row = found[0]
|
|
if (row.id !== operationId || row.plan_id !== planId || row.state !== "applied" || row.step_state !== "verified" ||
|
|
row.operation_id !== "routing.community.switch" || row.operation_version !== findMcpOperation(row.operation_id)?.version ||
|
|
row.approved_by !== context.connection.owner_id || typeof row.evidence?.sealed !== "string" || !(row.created_at instanceof Date)) throw fail()
|
|
await authorize()
|
|
return row
|
|
}
|
|
const row = await readSource(), sourceIdentity = fingerprint(row)
|
|
const evidence = JSON.parse(await decryptSecret(row.evidence.sealed))
|
|
if (evidence.steps?.length === 1 && evidence.steps[0].kind === "service" && evidence.steps[0].service === "routing.community") {
|
|
const input = evidence.steps[0].input
|
|
const witness = await loadRoutingMainTransition(input,operationId,planId), prepared = witness.packet.preparation
|
|
const binding = routingProfileAuthorityBindingSchema.parse(input.persistentProfileAuthority)
|
|
if (binding.packet.profileId!==profileId || binding.packet.profileVersion!==profileVersion || fingerprint(input.profile)!==original.profileProof ||
|
|
fingerprint(input.principal)!==fingerprint(context.principal) || input.ownerId!==original.ownerId || prepared.nativeId!==original.nativeId ||
|
|
prepared.originalCandidateId!==original.candidateId || prepared.originalTargetProof!==original.targetProof || prepared.dependencyProof!==original.dependencyProof ||
|
|
fingerprint(prepared.contextSources)!==fingerprint(original.sourceProofs) || fingerprint(prepared.scope)!==fingerprint(routingMainServiceScope(profile)))throw fail()
|
|
const native = await readRouteCommunityContext(profile,{authorize,signal:context.signal,expectedSources:original.sourceProofs,selectedCandidateId:prepared.desiredCandidateId})
|
|
if(!native.before.executionAvailable || native.ownedTarget?.nativeId!==original.nativeId || native.ownedTarget.rawRow.rule!==prepared.desiredRule ||
|
|
native.before.currentCandidateId!==prepared.desiredCandidateId || native.before.targetRuleProof!==prepared.desiredTargetProof ||
|
|
native.before.dependencyProof!==original.dependencyProof || fingerprint(native.before.sourceProofs)!==fingerprint(original.sourceProofs))throw fail()
|
|
await native.fence();await authorize();await assertPersistentScopedProfileAuthority(input,context.signal)
|
|
if(fingerprint(await readSource())!==sourceIdentity)throw fail()
|
|
const next=packetSchema.parse({...original,candidateId:prepared.desiredCandidateId,targetProof:prepared.desiredTargetProof,observedAt:new Date().toISOString(),
|
|
previousProof:value.proof,transition:{planId,operationId,checkpointProof:witness.checkpointProof}})
|
|
return {packet:next,proof:await sign(next)}
|
|
}
|
|
if (evidence.steps?.length !== 1 || evidence.steps[0].kind !== "service" || evidence.steps[0].service !== "routing.community.scoped" || evidence.target?.scope !== "servers") throw fail()
|
|
const step = evidence.steps[0], input = step.input
|
|
if (input.proofRevision !== 3 || fingerprint(input.profile) !== original.profileProof ||
|
|
fingerprint(input.principal) !== fingerprint(context.principal) || input.ownerId !== original.ownerId || input.nativeId !== original.nativeId ||
|
|
input.originalCandidateId !== original.candidateId || input.originalTargetProof !== original.targetProof || input.dependencyProof !== original.dependencyProof ||
|
|
fingerprint(input.contextSources) !== fingerprint(original.sourceProofs) || fingerprint(row.intended_state) !== fingerprint(redact(step)) ||
|
|
fingerprint([...evidence.target.serverIds].sort((a:number,b:number)=>a-b)) !== fingerprint(routingControllerScope(profile))) throw fail()
|
|
const authorityBinding = routingProfileAuthorityBindingSchema.parse(input.persistentProfileAuthority)
|
|
if (authorityBinding.packet.profileId !== profileId || authorityBinding.packet.profileVersion !== profileVersion) throw fail()
|
|
await assertPersistentScopedProfileAuthority(input, context.signal)
|
|
const requestSeal = await assertScopedCommunityRequest(input)
|
|
const configuration = await loadScopedConfigurationPacket(input, requestSeal, { operationId, stepIndex: 0 })
|
|
const network = await loadScopedNetworkCheckpoint(input, requestSeal)
|
|
if (!configuration || configuration.packet.revision !== 2 || !network || network.status !== "passed") throw fail()
|
|
// A genuinely prepared effect check may pause controller advancement without
|
|
// erasing the separate successful manual configuration/control-probe receipt.
|
|
if (Object.hasOwn(input, "originalEffectSelection")) {
|
|
const effects = originalEffectSelectionSchema.safeParse(input.originalEffectSelection)
|
|
if (!effects.success || effects.data.status !== "prepared" || network.originalEffects?.status !== "observed-expected" ||
|
|
network.originalEffects.selectionIdentity !== fingerprint(effects.data) || network.originalEffects.switchEffectObserved !== true || !network.originalEffects.transition?.changedPrefixes.length) throw fail()
|
|
}
|
|
const packet = configuration.packet, result = row.result
|
|
if (packet.operationId !== operationId || packet.stepIndex !== 0 || packet.nativeId !== original.nativeId ||
|
|
packet.originalCandidateId !== original.candidateId || packet.originalTargetProof !== original.targetProof ||
|
|
packet.dependencyProof !== original.dependencyProof || fingerprint(packet.contextSources) !== fingerprint(original.sourceProofs) ||
|
|
packet.desiredCandidateId !== input.candidateId || packet.desiredTargetProof !== input.desiredTargetProof ||
|
|
Date.parse(configuration.observedAt) < row.created_at.getTime() || Date.parse(configuration.observedAt) > Date.now()) throw fail()
|
|
const expectedSeal = await privateSecretFingerprint(fingerprint({ request: requestSeal, dependency: input.dependencyProof, desired: input.desiredTargetProof,
|
|
candidate: input.candidateId, configuration: configuration.checkpointProof, network: network.networkSeal }), `route-ai-scoped-verified-v${input.proofRevision}`)
|
|
if (result?.nativeVerificationSeal !== expectedSeal || result.configurationCheckpointProof !== configuration.checkpointProof ||
|
|
result.networkCheckpointProof !== network.networkSeal || result.receiptId !== input.receiptId || result.proofRevision !== input.proofRevision ||
|
|
result.nativeWrites !== 1 || result.configurationVerified !== true || result.postProbeStatus !== "passed" || result.controlProbeVerified !== true) throw fail()
|
|
const native = await readRouteCommunityContext(profile, { authorize, signal: context.signal, expectedSources: original.sourceProofs, selectedCandidateId: packet.desiredCandidateId })
|
|
const targetProof = native.before.targetRuleProof
|
|
if (!supportedExecution(profile,native.before) || native.ownedTarget?.nativeId !== original.nativeId || native.before.nativeRuleId !== original.nativeId ||
|
|
!targetProof || !native.ownedTarget.matchesRuleProof(packet.desiredRule, packet.desiredTargetProof) || native.before.currentCandidateId !== packet.desiredCandidateId ||
|
|
native.before.dependencyProof !== original.dependencyProof || fingerprint(native.before.sourceProofs) !== fingerprint(original.sourceProofs)) throw fail()
|
|
await native.fence(); await authorize()
|
|
await assertPersistentScopedProfileAuthority(input, context.signal)
|
|
if (fingerprint(await readSource()) !== sourceIdentity) throw fail()
|
|
// Enroll the exact observed native seal for the next tick. The source seal
|
|
// still identifies this operation and its inverse when RouterOS omits quotes.
|
|
const next = packetSchema.parse({ ...original, candidateId: packet.desiredCandidateId, targetProof,
|
|
observedAt: new Date().toISOString(), previousProof: value.proof, transition: { planId, operationId, checkpointProof: configuration.checkpointProof,
|
|
...(targetProof !== packet.desiredTargetProof ? { sourceDesiredTargetProof: packet.desiredTargetProof } : {}) } })
|
|
return { packet: next, proof: await sign(next) }
|
|
}
|
|
|
|
|