160 lines
9.9 KiB
TypeScript
160 lines
9.9 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "node:crypto"
|
|
import { mkdtemp, rmdir, unlink, writeFile } from "node:fs/promises"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { test } from "node:test"
|
|
import { fingerprint } from "../modules/mcp/security.js"
|
|
import { createServerPollRetiredArchiveChargeVerifier, createServerPollRetiredArchiveForTests } from "./server-poll-retired-archive.js"
|
|
import { createServerPollTerminalArchiveForTests, ServerPollArchiveRefused } from "./server-poll-terminal-archive.js"
|
|
import type { VerifiedServerPollHistory } from "./server-poll-history-verification.js"
|
|
|
|
const receiptId = "11111111-1111-4111-8111-111111111111"
|
|
const executionId = "22222222-2222-4222-8222-222222222222"
|
|
const connectionId = "33333333-3333-4333-8333-333333333333"
|
|
const planId = "44444444-4444-4444-8444-444444444444"
|
|
const ownerId = "owned-retired-archive"
|
|
const secret = "ORIGINAL-CREDENTIAL-OR-PAYLOAD-MUST-DISAPPEAR"
|
|
const expiredAt = "2026-10-29T03:20:00.123456Z"
|
|
const terminalAt = "2026-10-29T03:21:00.123457Z"
|
|
const completedAt = "2026-10-29T03:18:00.123458Z"
|
|
const createdAt = "2026-10-29T03:17:00.123459Z"
|
|
const gcNotBefore = "2026-11-29T03:20:00.123460Z"
|
|
const now = Date.parse("2026-11-30T00:00:00Z")
|
|
const key = randomBytes(32), mac = randomBytes(32)
|
|
const proof = async (purpose: string, value: unknown) => createHmac("sha256", mac).update(purpose).update(fingerprint(value)).digest("hex")
|
|
|
|
test("retired archive accounting derives the existing key anew for each scan and cannot bootstrap it", async () => {
|
|
const directory = await mkdtemp(join(tmpdir(), "mcp-retired-archive-key-"))
|
|
const filename = join(directory, "encryption-key"), previous = process.env.MCP_STATE_DIR
|
|
try {
|
|
process.env.MCP_STATE_DIR = directory
|
|
await assert.rejects(createServerPollRetiredArchiveChargeVerifier(), { code: "STATE_UNAVAILABLE" })
|
|
await writeFile(filename, key, { flag: "wx" })
|
|
const verifier = await createServerPollRetiredArchiveChargeVerifier()
|
|
const metadata = {
|
|
version: 2, receipt_id: receiptId, execution_id: executionId, connection_id: connectionId, owner_id: ownerId,
|
|
binding_proof: "a".repeat(64), context_proof: "b".repeat(64), terminal_digest: "c".repeat(64),
|
|
original_activity_at: terminalAt, original_expires_at: expiredAt, retention_days: 30, safety_ms: 60000,
|
|
source_digest: "d".repeat(64), source_sha256: "e".repeat(64), decoded_bytes: 10, compressed_bytes: 20,
|
|
ciphertext_bytes: 64, ciphertext_sha256: "f".repeat(64),
|
|
}
|
|
const purposeKey = createHmac("sha256", key).update("MCP private fingerprint:server-poll-retired-archive-record-v2").digest()
|
|
const archiveProof = createHmac("sha256", purposeKey).update(fingerprint({
|
|
...metadata, identity_kind: "mcp", storage_state: "compacted", admission_bytes: 32768, charged_rows: 2,
|
|
})).digest("hex")
|
|
const row = { ...metadata, archive_proof: archiveProof }
|
|
assert.equal((await verifier(row)).bytes, 32832)
|
|
await assert.rejects(verifier({ ...row, ciphertext_sha256: "0".repeat(64) }), ServerPollArchiveRefused)
|
|
await writeFile(filename, randomBytes(32))
|
|
await assert.rejects((await createServerPollRetiredArchiveChargeVerifier())(row), ServerPollArchiveRefused)
|
|
} finally {
|
|
if (previous === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = previous
|
|
await unlink(filename).catch(error => { if (error.code !== "ENOENT") throw error })
|
|
await rmdir(directory)
|
|
}
|
|
})
|
|
const encrypt = async (plain: Buffer) => {
|
|
const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, iv)
|
|
const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()])
|
|
return Buffer.concat([iv, cipher.getAuthTag(), ciphertext])
|
|
}
|
|
const decrypt = async (bytes: Buffer) => {
|
|
const cipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, 12))
|
|
cipher.setAuthTag(bytes.subarray(12, 28))
|
|
return Buffer.concat([cipher.update(bytes.subarray(28)), cipher.final()])
|
|
}
|
|
async function fixture(v2Encrypt = encrypt) {
|
|
const admission = { storage_state: "full", gc_not_before: gcNotBefore, opaque: secret }
|
|
const terminal = { operation: { finished_at: terminalAt, result: secret }, plan: { id: planId, expires_at: expiredAt, evidence: secret },
|
|
step: { intended_state: secret, result: secret } }
|
|
const journal = { execution: { created_at: createdAt, context_ciphertext: secret }, receipt: { created_at: completedAt, receipt_ciphertext: secret },
|
|
intents: [{ opaque: randomBytes(2048).toString("hex") }], acks: [{ opaque: secret }], quarantines: [] }
|
|
// Tests use genuine V1 codec authentication with a controlled source callback.
|
|
// Full production V1 source parity is tested by its existing verifier suite.
|
|
const v1 = createServerPollTerminalArchiveForTests({ encrypt, decrypt, proof, verifySource: async () => ({
|
|
receiptId, executionId, connectionId, ownerId, bindingProof: "a".repeat(64), contextProof: "b".repeat(64), terminalDigest: "c".repeat(64),
|
|
originalActivityAt: terminalAt, originalExpiresAt: expiredAt, retentionDays: 30, safetyMs: 60000,
|
|
}) })
|
|
const archive = await v1.create(JSON.stringify({ admission, terminal, journal }), now)
|
|
assert(archive)
|
|
const history = {
|
|
context: { identity: { kind: "mcp", executionId, connectionId, ownerId, credentialId: secret },
|
|
plan: { request: { receiptId, serverId: 23 }, affectedServerIds: [12, 23], maintenance: [secret] } },
|
|
receipt: { receiptId, complete: true, maintenanceComplete: true, configurationVerified: true, observation: "online",
|
|
nativeReads: 4, confirmedPublications: 8, completedPublications: 8, snapshot: { identityName: secret } },
|
|
source: { createdAt, completedAt, stageCount: 12, publications: 8,
|
|
nativeOutcomes: Array.from({ length: 4 }, (_, index) => ({ stage: "native." + index, outcome: "confirmed", resultProof: "d".repeat(64) })) },
|
|
} as unknown as VerifiedServerPollHistory
|
|
const calls = { decrypt: 0, history: 0 }
|
|
const codec = createServerPollRetiredArchiveForTests({ openV1: v1.open, verifyHistory: async () => { calls.history++; return history },
|
|
encrypt: v2Encrypt, proof, decrypt: async bytes => { calls.decrypt++; return decrypt(bytes) } })
|
|
return { codec, history, calls, input: { archive, terminal, admission: { ...admission, storage_state: "compacted",
|
|
archive_bytes: archive.ciphertext_bytes, original_activity_at: terminalAt, compact_at: "2026-10-29T03:23:00.123456Z" } } }
|
|
}
|
|
const refusal = (work: Promise<unknown>) => assert.rejects(work, (error: unknown) => {
|
|
assert(error instanceof ServerPollArchiveRefused && error.automaticReplay === false)
|
|
assert(!String(error).includes(secret))
|
|
return true
|
|
})
|
|
|
|
test("retirement authenticates V1 and projects only completed history, scope, and original lifetime", async () => {
|
|
const { codec, calls, input } = await fixture()
|
|
const retired = await codec.project(input, now)
|
|
assert(retired)
|
|
assert.equal(calls.history, 1)
|
|
assert(retired.ciphertext_bytes < input.archive.ciphertext_bytes)
|
|
const { history, metadata } = await codec.open(retired)
|
|
assert.deepEqual(history, { version: 2, operation: "servers.poll", operationVersion: 1, planId, serverId: 23, affectedServerIds: [12, 23],
|
|
gcNotBefore, terminalAt, previous: { archiveProof: input.archive.archive_proof, sourceDigest: input.archive.source_digest, sourceSha256: input.archive.source_sha256 },
|
|
history: { createdAt, completedAt, stageCount: 12, publications: 8, nativeReads: 4, observation: "online", verification: "passed" } })
|
|
assert.equal(metadata.terminal_digest, input.archive.terminal_digest)
|
|
assert.equal(metadata.original_activity_at, terminalAt)
|
|
assert.equal(metadata.original_expires_at, expiredAt)
|
|
assert.equal(metadata.retention_days, input.archive.retention_days)
|
|
assert(!JSON.stringify(history).includes(secret))
|
|
assert.equal((await codec.verifyCharge(retired)).bytes, retired.ciphertext_bytes + 32768)
|
|
})
|
|
|
|
test("retirement refuses unauthenticated V1 and any current admission or original terminal drift", async () => {
|
|
const { codec, input, calls } = await fixture()
|
|
const changed = [
|
|
{ ...input, archive: { ...input.archive, archive_proof: "e".repeat(64) } },
|
|
{ ...input, admission: { ...input.admission, gc_not_before: terminalAt } },
|
|
{ ...input, admission: { ...input.admission, original_activity_at: "2026-10-29T03:21:00.123458Z" } },
|
|
{ ...input, admission: { ...input.admission, archive_bytes: 1 } },
|
|
{ ...input, terminal: { ...input.terminal, step: { result: "changed" } } },
|
|
]
|
|
for (const row of changed) await refusal(codec.project(row, now))
|
|
assert.equal(calls.history, 0)
|
|
})
|
|
|
|
test("V2 metadata or ciphertext tamper never reaches V2 decrypt", async () => {
|
|
const { codec, input, calls } = await fixture()
|
|
const retired = await codec.project(input, now)
|
|
assert(retired)
|
|
for (const row of [
|
|
{ ...retired, version: 1 }, { ...retired, owner_id: "another-owner" },
|
|
{ ...retired, original_expires_at: "2026-10-29T03:20:00.123457Z" },
|
|
{ ...retired, terminal_digest: "e".repeat(64) },
|
|
{ ...retired, ciphertext: (retired.ciphertext[0] === "A" ? "B" : "A") + retired.ciphertext.slice(1) },
|
|
]) await refusal(codec.open(row))
|
|
assert.equal(calls.decrypt, 0)
|
|
await refusal(codec.verifyCharge(input.archive))
|
|
await refusal(codec.verifyCharge({ ...retired, ciphertext_bytes: retired.ciphertext_bytes - 1 }))
|
|
})
|
|
|
|
test("retirement refuses unknown history or a scope that omits its original target", async () => {
|
|
const { codec, history, input } = await fixture()
|
|
history.source.nativeOutcomes[0].outcome = "read-failed"
|
|
await refusal(codec.project(input, now))
|
|
history.source.nativeOutcomes[0].outcome = "confirmed"
|
|
history.context.plan.affectedServerIds = [12]
|
|
await refusal(codec.project(input, now))
|
|
})
|
|
|
|
test("a larger V2 ciphertext keeps the authenticated V1 instead of increasing the charge", async () => {
|
|
const { codec, input } = await fixture(async value => encrypt(Buffer.concat([Buffer.alloc(4096), value])))
|
|
assert.equal(await codec.project(input, now), undefined)
|
|
})
|