134 lines
12 KiB
TypeScript
134 lines
12 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"
|
|
import { createIpsecExistingCertificateExportRestHttpHandlers, type IpsecExistingCertificateExportRestHttpAdapter, type IpsecExistingCertificateExportRestHttpInput } from "./ipsec-existing-certificate-export-rest-http.js"
|
|
import { IpsecExistingCertificateExportExecutionError } from "./ipsec-existing-certificate-export.js"
|
|
|
|
const secret = "NEVER_REST_HTTP_PASSPHRASE", bytes = "NEVER_HTTP_PRIVATE_P12", source = "a".repeat(64)
|
|
const server = { id: 1, host: "router.example.test" } as ServerRow
|
|
const body = () => ({ passphrase: secret, privateKeyExport: true, caPrivateKeyExport: false })
|
|
const actor: AuthUser = { id: "http-owner", email: "[email protected]", name: "Owner", apps: ["mm"], permissions: ["mm:network:write"], issuedAt: 99000, expiresAt: 999999 }
|
|
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": "actual-bound-cert", "mode-config": "ipsec-vpn", comment: ipsecUserComment("Display-label-not-certificate-name") }],
|
|
"/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: "actual-bound-cert", "common-name": "Certificate CN", "key-usage": "tls-client", "private-key": "true" }, { ".id": "*o", name: "foreign-other", "common-name": "Other CN" }],
|
|
} })
|
|
const proof = async (state: IpsecExistingCertificateExportState) => fingerprint(ipsecUserUpdateValue(state))
|
|
function fixture() {
|
|
const state = base(), commands: string[] = [], keys: string[] = [], audits: unknown[] = [], claimed = new Set<string>()
|
|
let mode = "normal", prepareCalls = 0, executeCalls = 0
|
|
const deps: IpsecExistingCertificateExportRestAdapterDependencies = {
|
|
server: async () => server, sourceProof: async () => mode === "source" ? "f".repeat(64) : source, proof,
|
|
privateProof: async (value, domain) => createHmac("sha256", "synthetic-private-key").update(domain).update(value).digest("hex"),
|
|
checkClaims: async () => { if (mode === "revoked") throw new McpError("OWNER_CLAIMS_REVOKED", secret, 401) },
|
|
read: async (_s, authorize, control) => { assert.ok(control?.signal); assert.ok(control?.deadlineAt); await authorize(); const value = structuredClone(state); value.proof = await proof(value); await authorize(); return value },
|
|
boundary: async (a, work) => { assert.equal(a.transport, "rest"); assert.equal("principal" in a, false); return work() },
|
|
claim: async a => { if (claimed.has(a.requestKey)) throw new McpError("STATE_CONFLICT", secret, 409); claimed.add(a.requestKey); keys.push(a.requestKey); audits.push(a) },
|
|
checkpoint: async (_a, progress) => { audits.push(progress) },
|
|
publish: async (_a, bundle, _proof, authorize) => { await authorize(); return bundle },
|
|
generatePassphrase: () => "GENERATED_PRIVATE_PASSPHRASE", clock: () => 100000,
|
|
client: () => ({
|
|
post: async (_path: string, fields: Record<string, string>, _timeout: unknown, _signal: unknown, dispatch: () => Promise<unknown>) => { await dispatch(); commands.push(fields.name); state.catalogs["/file"].push({ ".id": "*new", name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(bytes)) }); if (mode === "lostAck") throw Error(secret); return {} },
|
|
downloadOwnedFile: async (_file: unknown, control: { authorize: () => Promise<unknown> }) => { await control.authorize(); return Buffer.from(bytes) },
|
|
delete: async (path: string, _timeout: unknown, dispatch: () => Promise<unknown>) => { await dispatch(); commands.push(path); state.catalogs["/file"] = [] },
|
|
}) as never,
|
|
}
|
|
const actual = createIpsecExistingCertificateExportRestAdapter(deps)
|
|
const adapter: IpsecExistingCertificateExportRestHttpAdapter = {
|
|
prepare: async (...args) => { prepareCalls++; assert.equal(args[3]?.timeoutMs, 180000); return actual.prepare(...args) },
|
|
execute: async (...args) => { executeCalls++; assert.equal(args[2]?.timeoutMs, 180000); if (mode === "source") mode = "normal"; return actual.execute(...args) },
|
|
}
|
|
return { state, commands, keys, audits, adapter, handlers: createIpsecExistingCertificateExportRestHttpHandlers(adapter), counts: () => ({ prepareCalls, executeCalls }), setMode: (value: string) => { mode = value } }
|
|
}
|
|
const input = (): IpsecExistingCertificateExportRestHttpInput => ({ actor, serverId: "1", body: body(), requestKey: randomUUID() })
|
|
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
|
|
let cases = 0
|
|
try {
|
|
assert.equal(IPSEC_EXISTING_CERTIFICATE_EXPORT_ACTIVATED, true)
|
|
{
|
|
const f = fixture(), req = { ...input(), clientId: "identity:*i" }, result = await f.handlers.client(req)
|
|
assert.equal(result.user, "Display-label-not-certificate-name"); assert.equal(result.passphrase, secret)
|
|
assert.deepEqual(f.commands, ["actual-bound-cert", "/file/*new"]); assert.deepEqual(f.keys, [req.requestKey])
|
|
assert.equal(result.serverEndpoint, "vpn.example.test"); assert.equal(result.contentB64, Buffer.from(bytes).toString("base64")); assert.ok(result.sswanContent); assert.ok(result.instructions?.includes("192.0.2.53"))
|
|
for (const key of ["receiptId", "publication", "artifactId", "principal", "humanDownloadOnly", "ipsecContentReturned"]) assert.equal(key in result, false)
|
|
await assert.rejects(() => f.handlers.client(req)); assert.equal(f.commands.length, 2); assert.deepEqual(f.keys, [req.requestKey]); assert.equal(JSON.stringify(f.audits).includes(secret), false); cases++
|
|
}
|
|
for (const [name, user] of [["actual-bound-cert", "Certificate CN"], ["ipsec-server", "vpn.example.test"], ["foreign-other", "Other CN"], ["ca", "ca"]]) {
|
|
const f = fixture(), result = await f.handlers.certificate({ ...input(), body: { ...body(), name, caPrivateKeyExport: name === "ca" } })
|
|
assert.equal(result.user, user); assert.equal(f.commands[0], name); assert.equal(f.commands.length, 2); cases++
|
|
}
|
|
for (const variation of ["server", "unsafeServer", "key", "missingKey", "arrayKey", "clientId", "missingPrivate", "falsePrivate", "short", "long", "extra", "bodyServer", "bodyClient", "bodySelector", "clientName", "certName", "certClient", "caFlag"]) {
|
|
const f = fixture(), req = { ...input(), clientId: "identity:*i" }, raw = req.body as Record<string, unknown>
|
|
let certificate = false
|
|
if (variation === "server") req.serverId = "srv1"
|
|
if (variation === "unsafeServer") req.serverId = Number.MAX_SAFE_INTEGER + 1
|
|
if (variation === "key") req.requestKey = "bad-key"
|
|
if (variation === "missingKey") req.requestKey = undefined
|
|
if (variation === "arrayKey") req.requestKey = [randomUUID()] as never
|
|
if (variation === "clientId") req.clientId = ""
|
|
if (variation === "missingPrivate") delete raw.privateKeyExport
|
|
if (variation === "falsePrivate") raw.privateKeyExport = false
|
|
if (variation === "short") raw.passphrase = "short"
|
|
if (variation === "long") raw.passphrase = "x".repeat(16385)
|
|
if (variation === "extra") raw.unknown = secret
|
|
if (variation === "bodyServer") raw.serverId = 2
|
|
if (variation === "bodyClient") raw.clientId = "identity:*foreign"
|
|
if (variation === "bodySelector") raw.selector = { kind: "certificate", name: "ca" }
|
|
if (variation === "clientName") raw.name = "ca"
|
|
if (variation === "certName") { certificate = true; raw.name = "" }
|
|
if (variation === "certClient") { certificate = true; raw.name = "actual-bound-cert"; raw.clientId = "identity:*i" }
|
|
if (variation === "caFlag") { certificate = true; raw.name = "ca" }
|
|
await assert.rejects(() => certificate ? f.handlers.certificate(req) : f.handlers.client(req), (error: unknown) => error instanceof McpError && !error.message.includes(secret))
|
|
if (variation !== "caFlag") assert.deepEqual(f.counts(), { prepareCalls: 0, executeCalls: 0 }, variation)
|
|
assert.equal(f.commands.length, 0); cases++
|
|
}
|
|
for (const variation of ["abort", "source", "revoked", "lostAck"]) {
|
|
const f = fixture(), controller = new AbortController()
|
|
if (variation === "abort") controller.abort(secret)
|
|
else f.setMode(variation)
|
|
await assert.rejects(() => f.handlers.client({ ...input(), clientId: "identity:*i", signal: controller.signal }), (error: unknown) => {
|
|
assert.ok(error instanceof McpError); assert.equal(error.message.includes(secret), false)
|
|
if (variation === "lostAck") { assert.ok(error instanceof IpsecExistingCertificateExportExecutionError); assert.equal(error.confirmedWrites, 0); assert.equal(error.code, "MUTATION_OUTCOME_UNKNOWN") }
|
|
return true
|
|
})
|
|
assert.equal(f.commands.length, variation === "lostAck" ? 1 : 0); cases++
|
|
}
|
|
for (const mutation of ["missingBundle", "missingField", "extraField", "extraReceipt", "server", "count", "automaticReplay", "forwarding", "certId", "proof", "receiptId", "filename", "mime", "base64"]) {
|
|
const f = fixture()
|
|
const adapter: IpsecExistingCertificateExportRestHttpAdapter = { prepare: f.adapter.prepare, execute: async (...args) => {
|
|
const raw = structuredClone(await f.adapter.execute(...args)) as unknown as Record<string, unknown>, bundle = raw.publication as Record<string, unknown>
|
|
if (mutation === "missingBundle") delete raw.publication
|
|
if (mutation === "missingField") delete bundle.contentB64
|
|
if (mutation === "extraField") bundle.secretUnexpected = secret
|
|
if (mutation === "extraReceipt") raw.secretUnexpected = secret
|
|
if (mutation === "server") raw.serverId = 2
|
|
if (mutation === "count") raw.completedCommands = 1
|
|
if (mutation === "automaticReplay") raw.automaticReplay = true
|
|
if (mutation === "forwarding") raw.forwardingVerified = true
|
|
if (mutation === "certId") raw.certificateId = "not-native"
|
|
if (mutation === "proof") raw.afterProof = "bad-proof"
|
|
if (mutation === "receiptId") raw.receiptId = "bad-id"
|
|
if (mutation === "filename") bundle.filename = "foreign.p12"
|
|
if (mutation === "mime") bundle.mime = "text/plain"
|
|
if (mutation === "base64") bundle.contentB64 = "not-valid-private-file!"
|
|
return raw as never
|
|
} }
|
|
const handlers = createIpsecExistingCertificateExportRestHttpHandlers(adapter)
|
|
await assert.rejects(() => handlers.client({ ...input(), clientId: "identity:*i" }), (error: unknown) => error instanceof IpsecExistingCertificateExportExecutionError && !error.message.includes(secret))
|
|
assert.equal(f.commands.length, 2); cases++
|
|
}
|
|
console.log("Active HTTP existing certificate export mapping:", JSON.stringify({ cases, actualRestAdapterAndSharedCore: true, bothPaths: true, roles: 4, realRouterCalls: 0, realSql: 0, activated: true }))
|
|
} finally { pool.query = oldQuery; pool.connect = oldConnect }
|