Files
MikrotikManager/backend/src/routes/ipsec-mutation.test.ts
T

106 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from "node:assert/strict"
import Fastify from "fastify"
import { validatorCompiler, serializerCompiler } from "@fastify/type-provider-zod"
import { createIpsecRoutes } from "./ipsec.js"
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
import { fetchIpsecState } from "../services/ipsec-live.js"
import { db, pool } from "../db/index.js"
import { servers } from "../db/schema.js"
import { executeGuardedConfigurationWrite } from "../services/config-mutation-policy.js"
import { configurationAuditTransactionFixture, emptyActiveRoutingProfilesSqlFixture } from "../test/fixtures/managed-mutation-sql.js"
const server = { id: 1, name: "test", host: "192.0.2.1", enabled: true, routingEndpointEpoch: "00000000-0000-4000-8000-000000000001" } as Parameters<typeof fetchIpsecState>[0]
const original = MikrotikClient.fromServer
const originalSelect = db.select, originalQuery = pool.query, originalConnect = pool.connect
const auditActions: string[] = []
// Standalone fixture: model only the guarded executor's repository/lock/audit SQL.
// Unexpected SQL fails instead of contacting a real PostgreSQL instance.
const fixtureQuery = async (sql: string, params?: unknown[]) => {
const admission = configurationAuditTransactionFixture(sql, params)
if (admission) return admission
const routing = emptyActiveRoutingProfilesSqlFixture(sql, params, server.id)
if (routing) return routing
if (sql.startsWith("SELECT pg_try_advisory_lock")) return { rows: [{ acquired: true }] }
if (sql.startsWith("SELECT pg_advisory_unlock")) return { rows: [{ pg_advisory_unlock: true }] }
if (sql.startsWith("SELECT object_ref FROM mcp_protections")) return { rows: [] }
if (sql.startsWith("INSERT INTO mcp_audit(")) { auditActions.push(String(params?.[1])); return { rows: [] } }
throw Error("Unexpected SQL in standalone IPsec mutation fixture: " + sql)
}
pool.query = fixtureQuery as typeof pool.query
pool.connect = (async () => ({ query: fixtureQuery, release: () => {} })) as unknown as typeof pool.connect
db.select = (() => ({ from: (table: unknown) => { assert.equal(table, servers); return { where: () => ({ limit: async (count: number) => { assert.equal(count, 1); return [server] } }) } } })) as unknown as typeof db.select
let pkiMode = "", certificateRemoved = false
let writes = 0, records = 0, fault = "", certificateFixture = false, removedCertificates = 0, exports = 0, exportedName = ""
const identities: Record<string,string>[] = [{ ".id": "*I", peer: "ike", "auth-method": "pre-shared-key", "remote-id": "key-id:alice", "mode-config": "mc-ipsec-alice", comment: "MikrotikManager:ipsec user=Alice" }, { ".id": "*OTHER", peer: "ike", "auth-method": "pre-shared-key", "remote-id": "key-id:other", "mode-config": "mc-ipsec-other", comment: "MikrotikManager:ipsec user=Other" }]
function certificateRows(): Record<string,string>[] {const leaf:Record<string,string>={".id":"*CERT",name:"ipsec-user-shared","common-name":"shared","key-usage":"tls-client"};if(!pkiMode)return certificateRemoved ? [] : [leaf];leaf.ca="test-crl-ca";if(pkiMode==="issued")leaf.issued="true";if(pkiMode==="revoked")leaf.revoked="true";if(pkiMode==="imported")leaf.issued="false";return [...(certificateRemoved ? [] : [leaf]),{".id":"*CA",name:"test-crl-ca","common-name":"test-crl-ca","key-usage":"key-cert-sign,crl-sign",crl:"true"}];}
const modeConfigs: Record<string, string>[] = [{ ".id": "*MC", name: "mc-ipsec-alice", address: "198.18.81.250" }, { ".id": "*OTHERMC", name: "mc-ipsec-other", address: "198.18.81.249" }]
MikrotikClient.fromServer = () => ({
get: async (path: string) => structuredClone(certificateFixture && path === "/certificate" ? certificateRows() : path === "/ip/ipsec/peer" ? [{ ".id": "*P", name: "ike", "exchange-mode": "ike2" }] : path === "/ip/ipsec/identity" ? identities : path === "/ip/ipsec/mode-config" ? modeConfigs : []),
getCertificates: async () => certificateFixture ? certificateRows() : [],
exportCertificatePkcs12: async (args: { name: string }) => { exports++; exportedName = args.name; return { fileName: args.name + ".p12", content: Buffer.from("fixture-only-archive"), passphrase: "fixture-only-pass" } },
removeCertificate: async () => { writes++; removedCertificates++; certificateRemoved = true },
put: async () => { writes++ }, post: async () => { writes++ },
delete: async (path: string, _timeout?: number, beforeDispatch?: () => Promise<unknown>) => executeGuardedConfigurationWrite(server.id, "DELETE", path, async () => {
assert.equal(auditActions.at(-1), "configuration.intent", "native DELETE must follow its durable intent")
await beforeDispatch?.()
writes++
const split = path.lastIndexOf("/"), collection = path.slice(0, split), id = decodeURIComponent(path.slice(split + 1))
if (collection === "/ip/ipsec/identity") { const index = identities.findIndex(row => row[".id"] === id); assert.ok(index >= 0); identities.splice(index, 1) }
else if (collection === "/ip/ipsec/mode-config") { const index = modeConfigs.findIndex(row => row[".id"] === id); assert.ok(index >= 0); modeConfigs.splice(index, 1) }
else if (collection === "/certificate") { assert.ok(certificateRows().some(row => row[".id"] === id)); removedCertificates++; certificateRemoved = true }
else assert.fail("Unexpected native DELETE in IPsec fixture: " + path)
}),
patch: async (path: string, body: Record<string, string>, _timeout?: number, beforeDispatch?: () => Promise<unknown>) => executeGuardedConfigurationWrite(server.id, "PATCH", path, async () => {
assert.equal(auditActions.at(-1), "configuration.intent")
await beforeDispatch?.()
writes++
if (fault === "partial" && writes === 2) throw new MikrotikError(403, path, "rejected")
Object.assign(identities.find(row => path.endsWith(row[".id"]))!, body)
if (fault === "lost-ack") throw Error("socket closed after application")
}),
}) as unknown as MikrotikClient
const app = Fastify(); app.setValidatorCompiler(validatorCompiler); app.setSerializerCompiler(serializerCompiler)
await app.register(createIpsecRoutes({ findServer: async () => server, recordRevision: async () => { records++; return {created:false,revision:{} as never} } }), { prefix: "/api" })
const patch = (payload: Record<string, unknown>) => app.inject({ method: "PATCH", url: "/api/ipsec/users/1/identity:*I", payload })
try {
writes=records=0; const invalidStatic = await patch({name:"Untouched",staticIp:""}); assert.equal(invalidStatic.statusCode,400); assert.equal(writes,0); assert.equal(records,0); assert.equal(identities[0]!.comment,"MikrotikManager:ipsec user=Alice");
for (const body of [{name:"New",staticIp:"198.18.81.249"},{name:"Other"},{remoteId:"key-id:other"}]) { writes=0; const r=await patch(body); assert.equal(r.statusCode,409); assert.equal(writes,0); assert.equal(identities[0]!.comment,"MikrotikManager:ipsec user=Alice") }
writes=records=0; fault="partial"; let r=await patch({name:"New",psk:"new-test-secret"}); assert.equal(r.statusCode,502); assert.equal(r.json().state,"partial"); assert.equal(r.json().confirmedWrites,1); assert.equal(records,0); assert.equal(identities[0]!.comment,"MikrotikManager:ipsec user=New")
writes=records=0; fault="lost-ack"; r=await patch({name:"Unknown"}); assert.equal(r.statusCode,502); assert.equal(r.json().state,"unknown"); assert.equal(r.json().confirmedWrites,0); assert.equal(identities[0]!.comment,"MikrotikManager:ipsec user=Unknown"); assert.equal(records,0)
writes=records=0; fault=""; r=await patch({remoteId:"fresh"}); assert.equal(r.statusCode,200); assert.equal(identities[0]!["remote-id"],"key-id:fresh"); assert.equal(writes,1); assert.equal(records,1)
// Unauthenticated legacy callers cannot reach either private export path. Selector/label parity is covered by the authenticated shared SQL/HTTP profile.
certificateFixture=true;certificateRemoved=false;identities.splice(0,identities.length,{".id":"*UNBOUND",peer:"ike","auth-method":"pre-shared-key","remote-id":"key-id:unbound",comment:"MikrotikManager:ipsec user=shared"});
exports=0;let exported=await app.inject({method:"POST",url:"/api/ipsec/users/1/identity:*UNBOUND/cert",payload:{passphrase:"fixture-pass"}});assert.equal(exported.statusCode,401);assert.equal(exports,0);assert.equal(exported.json().contentB64,undefined);
writes=records=removedCertificates=0;
let deletion=await app.inject({method:"DELETE",url:"/api/ipsec/users/1/identity:*UNBOUND"});assert.equal(deletion.statusCode,200);assert.equal(writes,1);assert.equal(removedCertificates,0);assert.equal(records,1);
// Explicit certificate binding still permits deletion when no other references exist.
certificateRemoved=false;identities.splice(0,identities.length,{".id":"*BOUND",peer:"ike","auth-method":"digital-signature","remote-certificate":"ipsec-user-shared",comment:"MikrotikManager:ipsec user=shared"});
identities[0]!.comment="MikrotikManager:ipsec user=Renamed label";exports=0;exported=await app.inject({method:"POST",url:"/api/ipsec/users/1/identity:*BOUND/cert",payload:{passphrase:"fixture-pass"}});assert.equal(exported.statusCode,401);assert.equal(exports,0);assert.equal(exportedName,"");
writes=records=removedCertificates=0;
deletion=await app.inject({method:"DELETE",url:"/api/ipsec/users/1/identity:*BOUND"});assert.equal(deletion.statusCode,200);assert.equal(writes,2);assert.equal(removedCertificates,1);assert.equal(records,1);
certificateFixture=true;certificateRemoved=false;identities.splice(0,identities.length,...["*FIRST","*SECOND"].map((id,n)=>({".id":id,peer:"ike","auth-method":"digital-signature","remote-certificate":"ipsec-user-shared",comment:"MikrotikManager:ipsec user=Shared"+n})));
for(const method of ["PATCH","DELETE"] as const){writes=records=0;const r=await app.inject({method,url:"/api/ipsec/users/1/cert:*CERT",...(method==="PATCH"?{payload:{name:"Wrong"}}:{})});assert.equal(r.statusCode,409);assert.equal(writes,0);assert.equal(records,0)}
writes=records=0;r=await app.inject({method:"DELETE",url:"/api/ipsec/users/1/identity:*FIRST"});assert.equal(r.statusCode,409);assert.equal(writes,0);assert.equal(records,0);
writes=records=0;r=await app.inject({method:"PATCH",url:"/api/ipsec/users/1/identity:*FIRST",payload:{name:"Selected"}});assert.equal(r.statusCode,200);assert.equal(writes,1);assert.equal(identities[0]!.comment,"MikrotikManager:ipsec user=Selected");assert.equal(identities[1]!.comment,"MikrotikManager:ipsec user=Shared1");
writes=records=0;r=await app.inject({method:"DELETE",url:"/api/ipsec/users/1/identity:*FIRST?removeCertificate=false"});assert.equal(r.statusCode,200);assert.equal(writes,1);assert.equal(records,1);
// A CRL issuer protects both issued and already-revoked native certificates.
for(const mode of ["issued","revoked"]) {
pkiMode=mode;identities.splice(0,identities.length,{".id":"*CRLBOUND",peer:"ike","auth-method":"digital-signature","remote-certificate":"ipsec-user-shared",comment:"MikrotikManager:ipsec user=CRL client"});
for(const url of ["/api/ipsec/users/1/identity:*CRLBOUND","/api/ipsec/users/1/cert:*CERT"]) {writes=records=removedCertificates=0;const r=await app.inject({method:"DELETE",url});assert.equal(r.statusCode,409);assert.match(r.json().error,/CA с CRL/);assert.equal(writes,0);assert.equal(records,0);}
for(const force of ["","?force=true"]) {writes=records=0;const r=await app.inject({method:"DELETE",url:"/api/ipsec/certs/1"+force,payload:{name:"ipsec-user-shared"}});assert.equal(r.statusCode,409);assert.equal(writes,0);assert.equal(records,0);}
writes=records=removedCertificates=0;const r=await app.inject({method:"DELETE",url:"/api/ipsec/users/1/identity:*CRLBOUND?removeCertificate=false"});assert.equal(r.statusCode,200);assert.equal(writes,1);assert.equal(removedCertificates,0);assert.equal(records,1);
}
for(const force of ["","?force=true"]) {writes=records=0;const r=await app.inject({method:"DELETE",url:"/api/ipsec/certs/1"+force,payload:{name:"test-crl-ca"}});assert.equal(r.statusCode,409);assert.match(r.json().error,/всю цепочку/);assert.equal(writes,0);assert.equal(records,0);}
pkiMode="imported";identities.splice(0,identities.length);writes=records=0;r=await app.inject({method:"DELETE",url:"/api/ipsec/certs/1",payload:{name:"ipsec-user-shared"}});assert.equal(r.statusCode,200);assert.equal(writes,1);assert.equal(records,1);pkiMode="";
assert.ok(auditActions.includes("configuration.intent")); assert.ok(auditActions.includes("configuration.acknowledged"));
} finally { await app.close(); MikrotikClient.fromServer=original; db.select=originalSelect; pool.query=originalQuery; pool.connect=originalConnect }
console.log("IPsec HTTP mutations: no-write conflicts, acknowledged partial failure, applied-but-lost ack and remote ID normalization")