Files
MikrotikManager/backend/src/services/server-probe-legacy-verifier.ts
T

170 lines
14 KiB
TypeScript

/** Internal historical authentication only. No SQL, current grant, native work,
* migration readiness or public payload is produced by this verifier. */
import { isDeepStrictEqual } from "node:util"
import { z } from "zod"
import type { ServerProbeExecutionSource } from "../modules/mcp/diagnostic-cancellation-source.js"
import { decryptSecretExisting, fingerprint, privateFingerprinterExisting } from "../modules/mcp/security.js"
import { parseServerProbeJournalContext, validateServerProbeJournalReceipt, type ServerProbeJournalContext } from "./server-probe-journal.js"
import type { ServerProbeReceipt } from "./server-probe-execution.js"
import type { ProbeStorageScope } from "./server-probe-journal-maintenance.js"
export interface LegacyServerProbeBundle {
identityKind: "mcp" | "rest"; executionId: string
anchor?: Record<string, unknown>; quarantine?: Record<string, unknown>; cancellation?: Record<string, unknown>
stages: Record<string, unknown>[]
}
export interface LegacyServerProbeVerifierDependencies { loadMcpSource(operationId: string): Promise<ServerProbeExecutionSource> }
export interface LegacyServerProbeVerifierCrypto { open(value: string): Promise<string>; proof(domain: "receipt" | "identity", value: unknown): Promise<string> }
export type LegacyServerProbeReason = "INVALID_BUNDLE" | "SOURCE_UNAVAILABLE" | "SOURCE_MISMATCH" | "CONTEXT_UNAVAILABLE" | "ANCHOR_MISMATCH" | "RECEIPT_INVALID" | "QUARANTINE_INVALID" | "CANCELLATION_INVALID" | "STAGES_INVALID"
export type LegacyServerProbeVerification = {
status: "verified"; originalContext: Readonly<ServerProbeJournalContext>; scope: Readonly<ProbeStorageScope>
authentication: "receipt" | "approved-source" | "identity-context-only"
quarantined: boolean; cancelled: boolean; hasAnchor: boolean; terminal: boolean; stageCount: number
bindingAuthenticated: boolean; progressAuthenticated: boolean; stageLedgerAuthenticated: false; timestampsAuthenticated: false
migrationReady: false; requiresDatabaseSourceAttestation: true; automaticReplay: false
} | { status: "unresolved"; reasonCode: LegacyServerProbeReason; migrationReady: false; automaticReplay: false }
const uuid = z.string().uuid(), hash = z.string().regex(/^[a-f0-9]{64}$/)
const record = z.record(z.string(), z.unknown())
const bundleSchema = z.object({ identityKind: z.enum(["mcp", "rest"]), executionId: uuid,
anchor: record.optional(), quarantine: record.optional(), cancellation: record.optional(), stages: z.array(record).max(11) }).strict()
const envelopeSchema = z.object({ version: z.literal(1), context: z.unknown(), bindingProof: hash, receipt: z.unknown() }).strict()
const countSchema = z.object({ attempted: z.number().int().min(0).max(11), completed: z.number().int().min(0).max(11) })
.refine(value => value.completed <= value.attempted)
const sizes = [1500, 1492, 1480, 1476, 1472, 1468, 1400, 1280, 1024, 576]
class Unresolved extends Error { constructor(readonly code: LegacyServerProbeReason) { super(code) } }
function requireFact(value: unknown, code: LegacyServerProbeReason): asserts value { if (!value) throw new Unresolved(code) }
const time = (value: unknown) => value instanceof Date ? value.getTime() : typeof value === "string" ? Date.parse(value) : NaN
function validTime(value: unknown, code: LegacyServerProbeReason) { requireFact(Number.isFinite(time(value)), code) }
function context(raw: unknown) {
const parsed = parseServerProbeJournalContext(raw as ServerProbeJournalContext)
requireFact(isDeepStrictEqual(raw, parsed) && parsed.identity.expiresAt > parsed.identity.issuedAt, "CONTEXT_UNAVAILABLE")
return parsed
}
function anchorContext(row: Record<string, unknown>, executionId: string) {
requireFact(row.identity_kind === "rest" && row.execution_id === executionId && ["jwt", "local"].includes(String(row.authentication))
&& row.mcp_connection_id === null && row.mcp_credential_id === null, "ANCHOR_MISMATCH")
const issuedAt = Number(row.authority_issued_at)
requireFact(String(issuedAt) === String(row.authority_issued_at), "ANCHOR_MISMATCH")
return context({ identity: { kind: "rest", ownerId: row.actor_id, executionId,
requestId: row.request_id, authentication: row.authentication, issuedAt, expiresAt: time(row.authority_expires_at) },
sourceServerId: row.source_server_id, ...(row.destination_server_id !== null ? { destinationServerId: row.destination_server_id } : {}), tool: row.tool })
}
function checkAnchor(row: Record<string, unknown>, ctx: ServerProbeJournalContext, scope: ProbeStorageScope) {
const id = ctx.identity
requireFact(row.receipt_id === scope.receiptId && row.binding_proof === scope.bindingProof && row.identity_kind === id.kind
&& row.execution_id === id.executionId && row.actor_id === id.ownerId && row.authentication === (id.kind === "mcp" ? "mcp" : id.authentication)
&& row.mcp_connection_id === (id.kind === "mcp" ? id.connectionId : null) && row.mcp_credential_id === (id.kind === "mcp" ? id.credentialId : null)
&& row.request_id === (id.kind === "rest" ? id.requestId : null) && String(row.authority_issued_at) === String(id.issuedAt)
&& time(row.authority_expires_at) === id.expiresAt && row.source_server_id === ctx.sourceServerId
&& row.destination_server_id === (ctx.destinationServerId ?? null) && row.tool === ctx.tool, "ANCHOR_MISMATCH")
validTime(row.created_at, "ANCHOR_MISMATCH")
if (row.state === "claimed") {
requireFact(row.receipt_ciphertext === null && row.receipt_proof === null && row.finished_at === null
&& row.attempted_stages === null && row.completed_stages === null, "ANCHOR_MISMATCH")
} else {
requireFact(["completed", "failed", "cancelled"].includes(String(row.state)), "ANCHOR_MISMATCH")
validTime(row.finished_at, "ANCHOR_MISMATCH")
}
}
function stages(rows: Record<string, unknown>[], ctx: ServerProbeJournalContext, receiptId: string, hasAnchor: boolean) {
requireFact(hasAnchor || rows.length === 0, "STAGES_INVALID")
let received = 0, native = 0
for (const [index, row] of rows.entries()) {
requireFact(row.receipt_id === receiptId && row.stage_index === index + 1 && received === index
&& Number.isInteger(row.timeout_ms) && Number(row.timeout_ms) >= 1
&& Number(row.timeout_ms) <= ({ ping: 120000, traceroute: 58000, mtu: 25000, route: 10000, bandwidth: 30000, dns: 30000 }[ctx.tool]), "STAGES_INVALID")
if (row.kind === "source-dns-A") requireFact(["ping", "traceroute", "mtu"].includes(ctx.tool) && index === 0 && Number(row.timeout_ms) <= 10000, "STAGES_INVALID")
else {
const expected = { ping: "native-ping", traceroute: "native-traceroute", bandwidth: "native-bandwidth", route: "native-route-read" }
requireFact(ctx.tool === "mtu" ? native < sizes.length && row.kind === `native-mtu-${sizes[native]}`
: native === 0 && (ctx.tool === "dns" ? typeof row.kind === "string" && /^manager-dns-(A|AAAA|MX|NS|TXT|CNAME|PTR)$/.test(row.kind) : row.kind === expected[ctx.tool]), "STAGES_INVALID")
native++
}
validTime(row.created_at, "STAGES_INVALID")
if (row.state === "received") {
requireFact(row.outcome === "received" || row.outcome === "source-unavailable" && row.kind === "source-dns-A", "STAGES_INVALID")
validTime(row.received_at, "STAGES_INVALID"); received++
} else requireFact(row.state === "intent" && row.outcome === null && row.received_at === null, "STAGES_INVALID")
}
return received
}
// Inspection must never recreate missing application key state.
const productionCrypto: LegacyServerProbeVerifierCrypto = { open: decryptSecretExisting,
proof: async (domain, value) => (await privateFingerprinterExisting("server-probe-journal-v1:" + domain))(fingerprint(value)) }
function verifier(dependencies: LegacyServerProbeVerifierDependencies, crypto: LegacyServerProbeVerifierCrypto) {
return async (raw: LegacyServerProbeBundle): Promise<LegacyServerProbeVerification> => {
let phase: LegacyServerProbeReason = "INVALID_BUNDLE"
try {
const bundle = bundleSchema.parse(structuredClone(raw)), { anchor, quarantine, cancellation } = bundle
requireFact(anchor || quarantine || cancellation, "INVALID_BUNDLE")
let original: ServerProbeJournalContext | undefined, source: ServerProbeExecutionSource | undefined
let receipt: ServerProbeReceipt | undefined, receiptId: string | undefined, bindingProof: string | undefined
if (bundle.identityKind === "mcp") {
phase = "SOURCE_UNAVAILABLE"; source = await dependencies.loadMcpSource(bundle.executionId)
phase = "SOURCE_MISMATCH"; original = context(source.originalContext)
const id = original.identity
requireFact(id.kind === "mcp" && id.executionId === bundle.executionId && id.operationName === "servers.probes.run"
&& source.originalCredentialId === id.credentialId && source.scope.identityKind === "mcp" && source.scope.executionId === id.executionId
&& source.scope.ownerId === id.ownerId && time(source.scope.authorityExpiresAt) === id.expiresAt
&& isDeepStrictEqual(source.serverIds, [...new Set([original.sourceServerId, ...(original.destinationServerId !== undefined ? [original.destinationServerId] : [])])].sort((a,b) => a-b))
&& source.stageBudget === (original.tool === "mtu" ? 11 : ["ping", "traceroute"].includes(original.tool) ? 2 : 1), "SOURCE_MISMATCH")
receiptId = uuid.parse(source.scope.receiptId); bindingProof = hash.parse(source.scope.bindingProof)
}
if (anchor && anchor.state !== "claimed") {
phase = "RECEIPT_INVALID"
requireFact(typeof anchor.receipt_ciphertext === "string" && Buffer.byteLength(anchor.receipt_ciphertext) > 0
&& Buffer.byteLength(anchor.receipt_ciphertext) <= 262144 && hash.safeParse(anchor.receipt_proof).success, phase)
const plaintext = await crypto.open(anchor.receipt_ciphertext)
requireFact(Buffer.byteLength(plaintext) <= 150000 && await crypto.proof("receipt", plaintext) === anchor.receipt_proof, phase)
const envelope = envelopeSchema.parse(JSON.parse(plaintext)), fromReceipt = context(envelope.context)
requireFact(fromReceipt.identity.kind === bundle.identityKind && fromReceipt.identity.executionId === bundle.executionId
&& (!original || isDeepStrictEqual(original, fromReceipt)), phase)
original = fromReceipt
requireFact((receiptId === undefined || receiptId === anchor.receipt_id) && (bindingProof === undefined || bindingProof === envelope.bindingProof), phase)
receiptId = uuid.parse(anchor.receipt_id); bindingProof = envelope.bindingProof
receipt = validateServerProbeJournalReceipt(original, receiptId, envelope.receipt as ServerProbeReceipt)
requireFact(anchor.state === receipt.state && anchor.attempted_stages === receipt.attemptedStages && anchor.completed_stages === receipt.completedStages, phase)
}
if (!original && anchor && quarantine) { phase = "CONTEXT_UNAVAILABLE"; original = anchorContext(anchor, bundle.executionId) }
requireFact(original, "CONTEXT_UNAVAILABLE")
if (receiptId === undefined) { receiptId = uuid.parse(anchor?.receipt_id); bindingProof = hash.parse(anchor?.binding_proof) }
requireFact(bindingProof, "CONTEXT_UNAVAILABLE")
const scope: ProbeStorageScope = { ownerId: original.identity.ownerId, receiptId, bindingProof, identityKind: original.identity.kind,
executionId: original.identity.executionId, authorityExpiresAt: new Date(original.identity.expiresAt).toISOString() }
phase = "ANCHOR_MISMATCH"; if (anchor) checkAnchor(anchor, original, scope)
phase = "STAGES_INVALID"; const received = stages(bundle.stages, original, receiptId, !!anchor)
if (receipt) requireFact(received === receipt.completedStages && receipt.attemptedStages <= bundle.stages.length
&& bundle.stages.length - receipt.attemptedStages <= 1
&& (receipt.state !== "completed" || receipt.attemptedStages === bundle.stages.length), phase)
if (quarantine) {
phase = "QUARANTINE_INVALID"
requireFact(quarantine.receipt_id === receiptId && quarantine.binding_proof === bindingProof && quarantine.identity_kind === original.identity.kind
&& quarantine.execution_id === original.identity.executionId && hash.safeParse(quarantine.identity_proof).success
&& quarantine.identity_proof === await crypto.proof("identity", original)
&& typeof quarantine.error_code === "string" && /^[A-Z_]{1,64}$/.test(quarantine.error_code), phase)
const counts = countSchema.parse({ attempted: quarantine.attempted_stages, completed: quarantine.completed_stages })
requireFact(counts.attempted <= bundle.stages.length && counts.completed <= received && bundle.stages.length - counts.attempted <= 1, phase)
validTime(quarantine.created_at, phase)
}
if (cancellation) {
phase = "CANCELLATION_INVALID"; const id = original.identity
requireFact(id.kind === "mcp" && cancellation.operation_id === id.executionId && cancellation.connection_id === id.connectionId && cancellation.actor_id === id.ownerId, phase)
}
const authentication = receipt ? "receipt" : source ? "approved-source" : "identity-context-only"
requireFact(authentication !== "identity-context-only" || quarantine, "CONTEXT_UNAVAILABLE")
Object.freeze(original.identity); Object.freeze(original)
return Object.freeze({ status: "verified", originalContext: original, scope: Object.freeze(scope), authentication,
quarantined: !!quarantine, cancelled: !!cancellation, hasAnchor: !!anchor, terminal: !!receipt || !!source?.terminal,
stageCount: bundle.stages.length, bindingAuthenticated: !!receipt || !!source, progressAuthenticated: !!receipt,
stageLedgerAuthenticated: false, timestampsAuthenticated: false, migrationReady: false, requiresDatabaseSourceAttestation: true, automaticReplay: false })
} catch (failure) {
return Object.freeze({ status: "unresolved", reasonCode: failure instanceof Unresolved ? failure.code : phase, migrationReady: false, automaticReplay: false })
}
}
}
export const createLegacyServerProbeVerifier = (dependencies: LegacyServerProbeVerifierDependencies) => verifier(dependencies, productionCrypto)
/** Test-only codec composition; never populated from HTTP/MCP request JSON. */
export const createLegacyServerProbeVerifierForTests = verifier