Files
MikrotikManager/backend/src/services/wireguard-import-execution.test.ts
T

100 lines
8.4 KiB
TypeScript

import assert from "node:assert/strict"
import { fileURLToPath } from "node:url"
import { MikrotikError } from "./mikrotik.js"
import { wireguardInterfaceCreateSchema, wireguardPublicKey } from "./wireguard-interface-create.js"
import { wireguardInterfaceDeleteProof, wireguardInterfaceDependencyPaths, type WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js"
import { wireguardImportStages, type WireguardImportPlan } from "./wireguard-import-plan.js"
import { executeWireguardImportStages, WireguardImportExecutionError, type WireguardImportCheckpoint, type WireguardImportCommand } from "./wireguard-import-execution.js"
export async function acceptWireguardImportExecutionModel() {
const key = (byte: number) => Buffer.alloc(32, byte).toString("base64")
const plan: WireguardImportPlan = { format: "rsc", interface: wireguardInterfaceCreateSchema.parse({ serverId: 141, name: "wg-import", privateKey: key(21), address: "2001:db8::1/64" }), peers: [
{ publicKey: key(22), allowedAddresses: ["192.0.2.2/32"], name: "first", privateKey: "auto", clientAddress: "10.0.0.2", clientDns: "1.1.1.1", clientEndpoint: "vpn.example.org", endpointAddress: "vpn.example.org", endpointPort: 54321, persistentKeepalive: 60, comment: "first peer" },
{ publicKey: key(23), allowedAddresses: ["2001:db8:1::/64"], name: "second", privateKey: "none", disabled: true },
] }
async function fixture(options: { loseAt?: number; rejectAt?: number; tamperAt?: number; driftAfterCheckpoint?: number; intentDriftAt?: number; clampOnEnable?: boolean; rotateOnEnable?: boolean; foreignClampOnEnable?: boolean; ifaceOpaqueOnEnable?: boolean } = {}) {
const state: WireguardInterfaceDeleteState = { base: { interfaces: [], peers: [], bindings: [], flow: { hostPublicKey: "", registered: false }, serverProof: "source", proof: "base" }, ipv4: [], ipv6: [], dependencies: Object.fromEntries(wireguardInterfaceDependencyPaths.map(path => [path, []])), filters: [], proof: "" }
state.dependencies["/ip/firewall/filter"].push({ ".id": "*f", comment: "foreign opaque", chain: "forward", action: "accept" })
if (options.foreignClampOnEnable) {
state.base.interfaces.push({ ".id": "*ff", name: "wg-foreign", "private-key": key(25), "public-key": wireguardPublicKey(key(25)), disabled: "false" })
state.dependencies["/interface"].push({ ".id": "*ff", name: "wg-foreign", type: "wg" })
}
state.proof = await wireguardInterfaceDeleteProof(state)
const baseline = state.proof, checkpoints: WireguardImportCheckpoint[] = [], commands: WireguardImportCommand[] = []
let number = 0, nativeDispatches = 0
const hash = async () => { state.proof = await wireguardInterfaceDeleteProof(state) }
const read = async () => { await hash(); return structuredClone(state) }
const apply = async (command: WireguardImportCommand) => {
if (command.method === "PUT") {
const row = { ".id": "*" + (++number).toString(16), ...command.body, dynamic: "false", "opaque-native-default": "retained" }
if (command.path === "/interface/wireguard") { Object.assign(row, { "public-key": wireguardPublicKey(plan.interface.privateKey!) }); state.base.interfaces.push(row); state.dependencies["/interface"].push({ ".id": row[".id"], name: row.name, type: "wg" }) }
else if (command.path === "/interface/wireguard/peers") { if (row["private-key"] === "auto") row["private-key"] = key(24); state.base.peers.push(row) }
else (command.path === "/ipv6/address" ? state.ipv6 : state.ipv4).push(row)
} else {
const id = decodeURIComponent(command.path.split("/").at(-1)!)
const row = [...state.base.interfaces, ...state.base.peers, ...state.ipv4, ...state.ipv6].find(row => row[".id"] === id)!
Object.assign(row, command.body)
if (command.path.startsWith("/interface/wireguard/") && !command.path.startsWith("/interface/wireguard/peers/") && command.body.disabled === "false") {
if (options.clampOnEnable || options.rotateOnEnable) {
const scalar = Buffer.from(row["private-key"], "base64")
scalar[0] &= 248; scalar[31] = (scalar[31] & 127) | 64
if (options.rotateOnEnable) scalar[1] ^= 8
row["private-key"] = scalar.toString("base64"); row["public-key"] = wireguardPublicKey(row["private-key"])
}
if (options.foreignClampOnEnable) {
const foreign = state.base.interfaces.find(row => row.name === "wg-foreign")!, scalar = Buffer.from(foreign["private-key"], "base64")
scalar[0] &= 248; scalar[31] = (scalar[31] & 127) | 64
foreign["private-key"] = scalar.toString("base64")
}
if (options.ifaceOpaqueOnEnable) row["opaque-native-default"] = "changed during own activation"
}
}
await hash()
}
const run = () => executeWireguardImportStages(plan, baseline, { authorize: async () => {}, read,
dispatch: async (command, fence) => {
const index = commands.length + 1
if (options.intentDriftAt === index) { state.dependencies["/ip/firewall/filter"][0].comment = "changed after intent"; await hash() }
await fence(); commands.push(structuredClone(command)); nativeDispatches++
if (options.rejectAt === index) throw new MikrotikError(422, command.path, "fixture rejection")
await apply(command)
if (options.loseAt === index) throw Error("fixture response lost")
if (options.tamperAt === index) { state.base.peers[0]["opaque-native-default"] = "changed"; await hash() }
},
checkpoint: async checkpoint => {
checkpoints.push(structuredClone(checkpoint))
if (options.driftAfterCheckpoint === checkpoint.completedCommands) { state.dependencies["/ip/firewall/filter"][0].comment = "foreign changed"; await hash() }
},
})
return { state, run, checkpoints, commands, nativeDispatches: () => nativeDispatches }
}
const successful = await fixture(), receipt = await successful.run()
assert.equal(receipt.verified, true); assert.equal(receipt.peersCreated, 2)
assert.equal(receipt.commandCount, wireguardImportStages(plan).length)
assert.equal(receipt.completedCommands, 7); assert.equal(successful.checkpoints.length, 7)
assert.equal(successful.state.base.peers[0].disabled, "false"); assert.equal(successful.state.base.peers[1].disabled, "true")
assert.deepEqual(successful.commands.slice(0, 4).map(command => command.body.disabled), ["true", "true", "true", "true"])
assert.equal(successful.state.base.interfaces[0].disabled, "false")
assert.equal(successful.state.ipv6[0].disabled, "false")
const clamped = await fixture({ clampOnEnable: true }), clampedReceipt = await clamped.run()
assert.equal(clampedReceipt.verified, true); assert.equal(clampedReceipt.completedCommands, 7)
assert.notEqual(clamped.state.base.interfaces[0]["private-key"], plan.interface.privateKey)
assert.equal(clamped.state.base.interfaces[0]["public-key"], wireguardPublicKey(plan.interface.privateKey!))
for (const [options, prefix, expectedDispatches, outcome] of [
[{ loseAt: 4 }, 3, 4, "needs-review"], [{ rejectAt: 4 }, 3, 4, "partial"],
[{ tamperAt: 5 }, 4, 5, "needs-review"], [{ driftAfterCheckpoint: 3 }, 3, 3, "needs-review"],
[{ intentDriftAt: 4 }, 3, 3, "needs-review"],
[{ rotateOnEnable: true }, 6, 7, "needs-review"], [{ foreignClampOnEnable: true }, 6, 7, "needs-review"],
[{ clampOnEnable: true, ifaceOpaqueOnEnable: true }, 6, 7, "needs-review"],
] as const) {
const test = await fixture(options)
await assert.rejects(test.run(), error => error instanceof WireguardImportExecutionError && error.state === outcome && error.verifiedPrefixCommands === prefix && error.commandCount === 7)
assert.equal(test.nativeDispatches(), expectedDispatches)
assert.equal(test.checkpoints.length, prefix)
assert.equal(test.commands.every(command => command.method !== ("DELETE" as string)), true, "No automatic compensation or replay")
}
console.log("WireGuard multi-peer import: disabled preparation, selective activation, full graph/opaque preservation, per-command checkpoints, durable-intent drift, explicit rejection prefix and lost response no replay/cleanup")
console.log("WireGuard import activation: corroborated X25519 scalar clamp succeeds only for selected own interface; meaningful rotation, foreign clamp and own opaque drift remain unknown")
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) await acceptWireguardImportExecutionModel()