167 lines
14 KiB
TypeScript
167 lines
14 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { createHmac, randomUUID } from "node:crypto"
|
|
import { pool } from "../db/index.js"
|
|
import type { AuthUser } from "../lib/permissions.js"
|
|
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
|
import { fingerprint, McpError } from "../modules/mcp/security.js"
|
|
import { ipsecManagedComment, ipsecUserComment } from "./ipsec-config.js"
|
|
import { ipsecPeerDeletePaths } from "./ipsec-peer-delete.js"
|
|
import { ipsecUserUpdateValue } from "./ipsec-user-update.js"
|
|
import { IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, type IpsecExistingCertificateExportState } from "./ipsec-existing-certificate-export-model.js"
|
|
import { createIpsecExistingCertificateExportRestAdapter, type IpsecExistingCertificateExportRestAdapterDependencies } from "./ipsec-existing-certificate-export-rest.js"
|
|
|
|
const secret = "NEVER_INLINE_PRIVATE_PASSPHRASE", bytes = "NEVER_PRIVATE_PKCS12"
|
|
const source = "a".repeat(64), server = { id: 1, host: "router.example.test" } as ServerRow
|
|
const proof = async (state: IpsecExistingCertificateExportState) => fingerprint(ipsecUserUpdateValue(state))
|
|
const base = (): IpsecExistingCertificateExportState => ({ source, proof: "unused", protections: [], catalogs: {
|
|
...Object.fromEntries([...ipsecPeerDeletePaths, "/file"].map(path => [path, []])),
|
|
"/ip/ipsec/peer": [{ ".id": "*p", name: "ike", "exchange-mode": "ike2", certificate: "ipsec-server", comment: ipsecManagedComment() }],
|
|
"/ip/ipsec/identity": [{ ".id": "*i", peer: "ike", "auth-method": "digital-signature", certificate: "ipsec-server", "remote-certificate": "client-cert", "mode-config": "ipsec-vpn", comment: ipsecUserComment("Alice") }],
|
|
"/ip/ipsec/mode-config": [{ ".id": "*m", name: "ipsec-vpn", "static-dns": "192.0.2.53" }],
|
|
"/certificate": [{ ".id": "*a", name: "ca", "key-usage": "key-cert-sign,crl-sign", authority: "true", "private-key": "true" }, { ".id": "*s", name: "ipsec-server", "common-name": "vpn.example.test", "key-usage": "tls-server" }, { ".id": "*c", name: "client-cert", "common-name": "Alice", "key-usage": "tls-client", "private-key": "true" }, { ".id": "*o", name: "foreign-other", "common-name": "Other" }],
|
|
"/file": [{ ".id": "*f", name: "foreign.p12", size: "5" }],
|
|
} })
|
|
const request = () => ({ serverId: 1, selector: { kind: "client", clientId: "identity:*i" }, privateKeyExport: true, caPrivateKeyExport: false, passphrase: ` ${secret} ` })
|
|
function fixture() {
|
|
const state = base()
|
|
let now = 100000, sourceCurrent = source, revoked = false, materialChanged = false, mode = "normal", reads = 0, generated = 0
|
|
const actor: AuthUser = { id: "real-rest-owner", email: "[email protected]", name: "Owner", apps: ["mm"], permissions: ["mm:network:write"], issuedAt: now - 1000, expiresAt: now + 600000 }
|
|
const commands: string[] = [], audits: unknown[] = [], claims = new Set<string>()
|
|
let downloaded: Buffer | undefined
|
|
const deps: IpsecExistingCertificateExportRestAdapterDependencies = {
|
|
server: async () => server,
|
|
sourceProof: async () => sourceCurrent,
|
|
proof,
|
|
checkClaims: async current => { assert.equal(current.id, actor.id); if (revoked) throw new McpError("OWNER_CLAIMS_REVOKED", secret, 401) },
|
|
privateProof: async (value, domain) => createHmac("sha256", "inert-test-private-key").update(domain).update(value).update(materialChanged ? "changed" : "").digest("hex"),
|
|
read: async (_server, authorize, control) => {
|
|
assert.ok(control?.signal); assert.ok(control?.deadlineAt)
|
|
await authorize(); reads++
|
|
if (mode === "prepareDrift" && reads === 2) state.catalogs["/certificate"][0].comment = "concurrent change"
|
|
const result = structuredClone(state); result.proof = await proof(result)
|
|
await authorize(); return result
|
|
},
|
|
boundary: async (a, work) => { assert.equal(a.transport, "rest"); assert.equal("principal" in a, false); assert.equal("policyProof" in a, false); return work() },
|
|
claim: async a => {
|
|
assert.equal(a.actor.id, actor.id)
|
|
const identity = `${a.actor.id}:${a.requestKey}`
|
|
if (claims.has(identity)) throw new McpError("STATE_CONFLICT", "already claimed", 409)
|
|
if (mode === "claimFailure") throw Error(secret)
|
|
claims.add(identity); audits.push({ claim: a })
|
|
},
|
|
checkpoint: async (a, progress) => { audits.push({ receiptId: a.receiptId, progress }); if (mode === "checkpointFailure") throw Error(secret); if (mode === "deadlineAfterExport") now += 180001 },
|
|
publish: async (_a, bundle, _after, authorize) => { await authorize(); if (mode === "publishFailure") throw Error(secret); return bundle },
|
|
generatePassphrase: () => { generated++; return "GENERATED_PRIVATE_PASSPHRASE" },
|
|
clock: () => now,
|
|
client: () => ({
|
|
post: async (path: string, fields: Record<string, string>, _timeout: unknown, _signal: unknown, beforeDispatch: () => Promise<unknown>) => {
|
|
await beforeDispatch(); commands.push(path)
|
|
state.catalogs["/file"].push({ ".id": "*new", name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(bytes)) })
|
|
if (mode === "collateral") state.catalogs["/certificate"][0].comment = "unexpected mutation"
|
|
if (mode === "revokeAfterExport") revoked = true
|
|
if (mode === "exportLostAck") throw Error(secret)
|
|
return {}
|
|
},
|
|
downloadOwnedFile: async (_file: unknown, control: { authorize: () => Promise<unknown> }) => { await control.authorize(); if (mode === "downloadFailure") throw Error(secret); downloaded = Buffer.from(bytes); return downloaded },
|
|
delete: async (path: string, _timeout: unknown, beforeDispatch: () => Promise<unknown>) => { await beforeDispatch(); commands.push(path); state.catalogs["/file"] = state.catalogs["/file"].filter(row => row[".id"] !== "*new"); if (mode === "cleanupLostAck") throw Error(secret) },
|
|
}) as never,
|
|
}
|
|
return { actor, deps, adapter: createIpsecExistingCertificateExportRestAdapter(deps), commands, audits, claims,
|
|
state: () => state, downloaded: () => downloaded, generated: () => generated,
|
|
setMode: (next: string) => { mode = next }, revoke: () => { revoked = true }, changeSource: () => { sourceCurrent = "f".repeat(64) }, changeMaterial: () => { materialChanged = true }, advance: (ms: number) => { now += ms },
|
|
}
|
|
}
|
|
let cases = 0
|
|
const oldQuery = pool.query, oldConnect = pool.connect
|
|
pool.query = (() => { throw Error("Real SQL forbidden") }) as never
|
|
pool.connect = (() => { throw Error("Real SQL forbidden") }) as never
|
|
try {
|
|
assert.equal(IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, true)
|
|
for (const target of ["client", "client-cert", "ipsec-server", "foreign-other", "ca"]) {
|
|
const f = fixture(), raw = target === "client" ? request() : { ...request(), selector: { kind: "certificate", name: target }, caPrivateKeyExport: target === "ca" }
|
|
const before = structuredClone(f.state()), key = randomUUID(), token = await f.adapter.prepare(f.actor, raw, key)
|
|
assert.equal(Object.isFrozen(token), true); assert.deepEqual(JSON.parse(JSON.stringify(token)), {})
|
|
assert.equal(JSON.stringify(token).includes(secret), false); assert.equal(JSON.stringify(token).includes(key), false)
|
|
const result = await f.adapter.execute(token, f.actor)
|
|
assert.equal(result.verified, true); assert.equal(result.automaticReplay, false); assert.equal(result.forwardingVerified, false)
|
|
assert.equal(result.publication.contentB64, Buffer.from(bytes).toString("base64")); assert.equal(result.publication.passphrase, secret)
|
|
assert.equal(result.publication.serverEndpoint, "vpn.example.test"); assert.ok(result.publication.sswanContent); assert.ok(result.publication.instructions?.includes("192.0.2.53"))
|
|
assert.equal("artifactId" in result, false); assert.equal("ipsecContentReturned" in result, false); assert.equal("humanDownloadOnly" in result, false)
|
|
assert.equal(f.commands.length, 2); assert.deepEqual(f.state(), before); assert.ok(f.downloaded()?.every(byte => byte === 0))
|
|
assert.equal(JSON.stringify(f.audits).includes(secret), false)
|
|
await assert.rejects(() => f.adapter.execute(token, f.actor)); assert.equal(f.commands.length, 2)
|
|
const replay = await f.adapter.prepare(f.actor, raw, key)
|
|
await assert.rejects(() => f.adapter.execute(replay, f.actor)); assert.equal(f.commands.length, 2)
|
|
cases++
|
|
}
|
|
for (const passphrase of [" ", " 123456 "]) {
|
|
const f = fixture(), token = await f.adapter.prepare(f.actor, { ...request(), passphrase }, randomUUID())
|
|
const result = await f.adapter.execute(token, f.actor)
|
|
assert.equal(result.publication.passphrase, "GENERATED_PRIVATE_PASSPHRASE"); assert.equal(f.generated(), 1); assert.equal(f.commands.length, 2); cases++
|
|
}
|
|
{
|
|
const f = fixture(), raw = request(), originalActor = structuredClone(f.actor), token = await f.adapter.prepare(f.actor, raw, randomUUID())
|
|
raw.selector.clientId = "identity:*wrong"; raw.passphrase = "CHANGED_PRIVATE_PASSPHRASE"; f.actor.permissions.push("mm:network:read")
|
|
// Prepared selection/material/actor are immutable snapshots, independent of caller mutation.
|
|
const result = await f.adapter.execute(token, originalActor)
|
|
assert.equal(result.certificateId, "*c"); assert.equal(result.publication.passphrase, secret); cases++
|
|
}
|
|
for (const variation of ["json", "crossFactory", "actor", "permissions", "issuedAt", "expiry", "revoke", "source", "material", "target", "protection", "deadline", "abort", "invalidTimeout"]) {
|
|
const f = fixture(), token = await f.adapter.prepare(f.actor, request(), randomUUID()), controller = new AbortController()
|
|
let candidate: unknown = token, actor = f.actor, adapter = f.adapter
|
|
if (variation === "json") candidate = JSON.parse(JSON.stringify(token))
|
|
if (variation === "crossFactory") adapter = createIpsecExistingCertificateExportRestAdapter(f.deps)
|
|
if (variation === "actor") actor = { ...f.actor, id: "other-owner" }
|
|
if (variation === "permissions") actor = { ...f.actor, permissions: [] }
|
|
if (variation === "issuedAt") actor = { ...f.actor, issuedAt: f.actor.issuedAt! + 1 }
|
|
if (variation === "expiry") actor = { ...f.actor, expiresAt: 1 }
|
|
if (variation === "revoke") f.revoke()
|
|
if (variation === "source") f.changeSource()
|
|
if (variation === "material") f.changeMaterial()
|
|
if (variation === "target") f.state().catalogs["/certificate"][2].name = "changed"
|
|
if (variation === "protection") f.state().protections.push({ object_ref: { kind: "certificate", id: "*c", protection: "deny" } })
|
|
if (variation === "deadline") f.advance(180000)
|
|
if (variation === "abort") controller.abort()
|
|
await assert.rejects(() => adapter.execute(candidate, actor, { signal: controller.signal, ...(variation === "invalidTimeout" ? { timeoutMs: Infinity } : {}) }), (error: unknown) => error instanceof Error && !error.message.includes(secret))
|
|
assert.equal(f.commands.length, 0); cases++
|
|
}
|
|
for (const variation of ["caFlag", "short", "long", "unknown", "generateLie", "key", "apps", "noIssuedAt", "noExpiry", "expired", "future", "revoked", "deny", "protected", "prepareDrift", "abort"]) {
|
|
const f = fixture(), raw: Record<string, unknown> = request(), controller = new AbortController()
|
|
let key: string = randomUUID(), actor = f.actor
|
|
if (variation === "caFlag") raw.selector = { kind: "certificate", name: "ca" }
|
|
if (variation === "short") raw.passphrase = "short"
|
|
if (variation === "long") raw.passphrase = "x".repeat(16385)
|
|
if (variation === "unknown") raw.principal = { connectionId: randomUUID() }
|
|
if (variation === "generateLie") raw.passphrase = { kind: "generate" }
|
|
if (variation === "key") key = "not-a-request-key"
|
|
if (variation === "apps") actor = { ...f.actor, apps: [] }
|
|
if (variation === "noIssuedAt") actor = { ...f.actor, issuedAt: undefined }
|
|
if (variation === "noExpiry") actor = { ...f.actor, expiresAt: undefined }
|
|
if (variation === "expired") actor = { ...f.actor, expiresAt: 99999 }
|
|
if (variation === "future") actor = { ...f.actor, issuedAt: 100001 }
|
|
if (variation === "revoked") f.revoke()
|
|
if (variation === "deny" || variation === "protected") f.state().protections.push({ object_ref: { kind: "certificate", id: "*c", protection: variation === "deny" ? "deny" : "approval" } })
|
|
if (variation === "prepareDrift") f.setMode("prepareDrift")
|
|
if (variation === "abort") controller.abort()
|
|
await assert.rejects(() => f.adapter.prepare(actor, raw, key, { signal: controller.signal }), (error: unknown) => error instanceof Error && !error.message.includes(secret))
|
|
assert.equal(f.commands.length, 0); cases++
|
|
}
|
|
for (const [mode, count] of [["claimFailure", 0], ["exportLostAck", 1], ["collateral", 1], ["revokeAfterExport", 1], ["checkpointFailure", 1], ["deadlineAfterExport", 1], ["downloadFailure", 1], ["cleanupLostAck", 2], ["publishFailure", 2]] as const) {
|
|
const f = fixture(), token = await f.adapter.prepare(f.actor, request(), randomUUID())
|
|
f.setMode(mode)
|
|
await assert.rejects(() => f.adapter.execute(token, f.actor), (error: unknown) => error instanceof Error && !error.message.includes(secret))
|
|
assert.equal(f.commands.length, count, mode)
|
|
await assert.rejects(() => f.adapter.execute(token, f.actor)); assert.equal(f.commands.length, count)
|
|
if (f.downloaded()) assert.ok(f.downloaded()!.every(byte => byte === 0))
|
|
assert.equal(JSON.stringify(f.audits).includes(secret), false); cases++
|
|
}
|
|
{
|
|
const f = fixture(), token = await f.adapter.prepare(f.actor, request(), randomUUID())
|
|
const first = f.adapter.execute(token, f.actor)
|
|
await assert.rejects(() => f.adapter.execute(token, f.actor))
|
|
await first; assert.equal(f.commands.length, 2); cases++
|
|
}
|
|
console.log("Synthetic REST existing certificate export:", JSON.stringify({ cases, actualSharedExecutor: true, syntheticDependenciesOnly: true, bothSelectors: true, roles: 4, activated: true, realRouterCalls: 0, realSql: 0 }))
|
|
} finally { pool.query = oldQuery; pool.connect = oldConnect }
|
|
|