Files
MikrotikManager/backend/src/services/vrf-production-read.test.ts
T

213 lines
15 KiB
TypeScript

import assert from "node:assert/strict"
import { readVrfProductionSnapshot, VRF_PRODUCTION_RAW_PATHS, type VrfProductionReadAdapter, type VrfProductionRawClient } from "./vrf-production-read.js"
import { VRF_PRODUCTION_REQUIRED_CATALOGS, sealVrfProductionAdmission, type VrfProductionRequest, type VrfProductionSnapshot } from "./vrf-production-admission.js"
import type { VrfRawReadObservation } from "./vrf-execution-diagnostic.js"
const sourceProof = "a".repeat(64)
const request: VrfProductionRequest = { action: "patch", id: "*1", fields: { name: "customers" } }
function model() {
const catalogs: VrfProductionSnapshot["catalogs"] = Object.fromEntries(VRF_PRODUCTION_REQUIRED_CATALOGS.map(resource => [resource, []]))
catalogs.ip_settings = [{ "rp-filter": "loose" }]; catalogs.ipv6_settings = [{ "disable-ipv6": "false" }]
catalogs.vrf = [{ ".id": "*1", name: "production", interfaces: "customer-vlan", disabled: "false" }, { ".id": "*2", name: "main", interfaces: "all", builtin: "true" }]
catalogs.interface_inventory = [{ ".id": "*10", name: "ether1", type: "ether", "rx-byte": "123", "unknown-field": "preserve" }, { ".id": "*11", name: "customer-vlan", type: "vlan" }]
catalogs.ethernet = [{ ".id": "*20", name: "ether1", mtu: "1500" }]
catalogs.vlan = [{ ".id": "*21", name: "customer-vlan", interface: "ether1", "vlan-id": "101" }]
catalogs.ipv4_address = [{ ".id": "*30", interface: "customer-vlan", address: "192.0.2.1/24", vrf: "production", dynamic: "false" }]
catalogs.ipv6_address = [{ ".id": "*31", interface: "customer-vlan", address: "2001:db8:1234::1/48", advertise: "yes", dynamic: "false" }, { ".id": "*32", interface: "customer-vlan", address: "fe80::1/64", dynamic: "true" }]
catalogs.ipv4_route = [{ ".id": "*40", gateway: "customer-vlan", dynamic: "true", connect: "true", "routing-table": "production" }]
const calls: string[] = []
let proof = sourceProof, enabled = true, authority = true, authorityCalls = 0, resolveCalls = 0
let afterGet: ((path: string) => void) | undefined
let afterResolve: (() => void) | undefined
const payloads: Record<string, unknown> = {}
const client: VrfProductionRawClient = { async get<T>(path: string, timeoutMs?: number, _signal?: AbortSignal, maxBytes?: number): Promise<T> {
assert.equal(timeoutMs, 10000); assert.equal(maxBytes, 8 * 1024 * 1024)
calls.push(path)
const resource = Object.keys(VRF_PRODUCTION_RAW_PATHS).find(key => VRF_PRODUCTION_RAW_PATHS[key] === path)!
const payload = Object.hasOwn(payloads, resource) ? payloads[resource] : catalogs[resource]
afterGet?.(path)
return structuredClone(payload) as T
} }
const adapter: VrfProductionReadAdapter = { async resolve(serverId) {
resolveCalls++
const source = { serverId, enabled, sourceProof: proof, client }
afterResolve?.()
return source
} }
const input = { serverId: 7, expectedSourceProof: sourceProof, request: structuredClone(request), adapter, async assertAuthority() { authorityCalls++; assert.ok(authority, "authority revoked") } }
return { catalogs, calls, payloads, input, revoke() { authority = false }, disable() { enabled = false }, changeSource() { proof = "b".repeat(64) }, afterGet(callback: typeof afterGet) { afterGet = callback }, afterResolve(callback: typeof afterResolve) { afterResolve = callback }, counters() { return { authorityCalls, resolveCalls } } }
}
const happy = model(), snapshot = await readVrfProductionSnapshot(happy.input)
assert.equal(snapshot.projection, "raw-native-v1")
assert.equal(happy.calls.length, 18)
assert.deepEqual(snapshot.catalogs, happy.catalogs)
assert.equal(snapshot.catalogs.interface_inventory[0]["unknown-field"], "preserve")
assert.equal(snapshot.catalogs.ipv6_address[1].dynamic, "true")
assert.equal(happy.counters().authorityCalls, happy.counters().resolveCalls * 2)
const sealed = sealVrfProductionAdmission({ snapshot, binding: { serverId: 7, sourceProof, actorId: "human", planId: "plan" }, request, secret: Buffer.alloc(32, 7), now: 1 })
assert.equal(sealed.admission.companionExecution, "requires-native-transition-proof")
assert.deepEqual(sealed.admission.members[0].parents.map(row => [row.id, row.configurationId]), [["*11", "*21"], ["*10", "*20"]])
assert.equal(sealed.admission.members[0].addresses.length, 3)
happy.catalogs.vlan[0].interface = "changed-after-read"
assert.equal(snapshot.catalogs.vlan[0].interface, "ether1")
for (const change of ["revoke", "disable", "source"] as const) {
const m = model()
if (change === "revoke") m.revoke()
if (change === "disable") m.disable()
if (change === "source") m.changeSource()
await assert.rejects(readVrfProductionSnapshot(m.input))
assert.equal(m.calls.length, 0)
}
for (const change of ["revoke", "disable", "source"] as const) {
const m = model()
m.afterGet(() => { if (change === "revoke") m.revoke(); if (change === "disable") m.disable(); if (change === "source") m.changeSource() })
await assert.rejects(readVrfProductionSnapshot(m.input))
assert.equal(m.calls.length, 1)
}
const resolving = model(); resolving.afterResolve(() => resolving.revoke())
await assert.rejects(readVrfProductionSnapshot(resolving.input)); assert.equal(resolving.calls.length, 0)
const finalFence = model(); finalFence.afterGet(path => { if (path === "/interface/vlan") finalFence.changeSource() })
await assert.rejects(readVrfProductionSnapshot(finalFence.input), /source changed/)
for (const payload of [undefined, { rows: [], truncated: true }, [{ name: "without-id" }], [{ ".id": "*1" }, { ".id": "*1" }], new Array(50000).fill({ ".id": "*1" }), [{ ".id": "*1", comment: "x".repeat(8 * 1024 * 1024) }]]) {
const m = model(); m.payloads.bridge = payload
await assert.rejects(readVrfProductionSnapshot(m.input), /VRF production read refused/)
}
for (const alias of ["*A", "*0a", "*000A"]) {
const m = model(); m.payloads.bridge = [{ ".id": "*a", name: "first" }, { ".id": alias, name: "second" }]
await assert.rejects(readVrfProductionSnapshot(m.input), /duplicate native ID/)
}
for (const type of ["__proto__", "constructor", "toString"]) {
const m = model(); m.catalogs.interface_inventory[1].type = type
await assert.rejects(readVrfProductionSnapshot(m.input), /unsupported\/missing concrete/)
assert.ok(m.calls.every(path => typeof path === "string" && path.startsWith("/")))
}
for (const payload of [[], [{}, {}], { foo: undefined }]) {
const m = model(); m.payloads.ip_settings = payload
await assert.rejects(readVrfProductionSnapshot(m.input), /VRF production read refused/)
}
for (const mutate of [
(m: ReturnType<typeof model>) => { m.catalogs.interface_inventory.push({ ".id": "*99", name: "ether1", type: "ether" }) },
(m: ReturnType<typeof model>) => { m.catalogs.interface_inventory[1].type = "unreviewed-type" },
(m: ReturnType<typeof model>) => { m.catalogs.vlan[0].interface = "missing" },
(m: ReturnType<typeof model>) => { m.catalogs.vlan[0].interface = "all" },
(m: ReturnType<typeof model>) => { m.catalogs.vlan[0].interface = "customer-vlan" },
(m: ReturnType<typeof model>) => { delete m.catalogs.vlan[0].interface },
(m: ReturnType<typeof model>) => { m.catalogs.vlan.push({ ...m.catalogs.vlan[0], ".id": "*99" }) },
(m: ReturnType<typeof model>) => { m.catalogs.ipv4_address[0].address = "192.0.2.1/33" },
(m: ReturnType<typeof model>) => { m.input.request.fields.interfaces = "customer-vlan,customer-vlan" },
]) {
const m = model(); mutate(m)
await assert.rejects(readVrfProductionSnapshot(m.input), /VRF production read refused/)
}
const physical = model(); physical.input.request.fields.interfaces = "ether1"
assert.equal((await readVrfProductionSnapshot(physical.input)).catalogs.ethernet[0][".id"], "*20")
const bridge = model()
bridge.catalogs.interface_inventory.push({ ".id": "*50", name: "br-users", type: "bridge" })
bridge.catalogs.bridge = [{ ".id": "*60", name: "br-users" }]
bridge.catalogs.bridge_port = [{ ".id": "*61", bridge: "br-users", interface: "ether1" }]
bridge.catalogs.bridge_vlan = [{ ".id": "*62", bridge: "br-users", tagged: "br-users,customer-vlan", untagged: "ether1", "current-tagged": "br-users,customer-vlan" }]
bridge.input.request.fields.interfaces = "br-users"
assert.equal((await readVrfProductionSnapshot(bridge.input)).catalogs.bridge_port[0][".id"], "*61")
const bond = model()
bond.catalogs.interface_inventory.push({ ".id": "*50", name: "bond-users", type: "bond" })
bond.catalogs.bonding = [{ ".id": "*60", name: "bond-users", slaves: "ether1", mode: "802.3ad" }]
bond.input.request.fields.interfaces = "bond-users"
assert.equal((await readVrfProductionSnapshot(bond.input)).catalogs.bonding[0].slaves, "ether1")
for (const [type, resource] of [["gre-tunnel", "gre"], ["ipip-tunnel", "ipip"], ["eoip-tunnel", "eoip"], ["vxlan", "vxlan"]]) {
const m = model()
m.catalogs.interface_inventory.push({ ".id": "*50", name: "customer-tunnel", type })
m.catalogs[resource] = [{ ".id": "*60", name: "customer-tunnel", "local-address": "192.0.2.1", "remote-address": "198.51.100.1", interface: "ether1" }]
if (resource === "vxlan") m.catalogs.vxlan_vtep = [{ ".id": "*70", interface: "customer-tunnel", "remote-ip": "198.51.100.1" }]
m.input.request.fields.interfaces = "customer-tunnel"
assert.equal((await readVrfProductionSnapshot(m.input)).catalogs[resource][0][".id"], "*60")
m.catalogs[resource][0]["local-address"] = "0.0.0.0"
await assert.rejects(readVrfProductionSnapshot(m.input), /unbound tunnel local source/)
}
const wg = model()
wg.catalogs.interface_inventory.push({ ".id": "*50", name: "wg-users", type: "wireguard" })
wg.catalogs.wireguard = [{ ".id": "*60", name: "wg-users", "listen-port": "51820" }]
wg.catalogs.wireguard_peer = [{ ".id": "*70", interface: "wg-users", "public-key": "opaque-public", "endpoint-address": "198.51.100.1", "allowed-address": "10.0.0.0/24" }]
wg.input.request.fields.interfaces = "wg-users"
assert.equal((await readVrfProductionSnapshot(wg.input)).catalogs.wireguard_peer[0][".id"], "*70")
wg.catalogs.wireguard_peer[0]["endpoint-address"] = "peer.example.test"
await assert.rejects(readVrfProductionSnapshot(wg.input), /unresolved WireGuard endpoint/)
const ppp = model()
ppp.catalogs.interface_inventory.push({ ".id": "*50", name: "ppp-users", type: "pppoe-out" })
ppp.catalogs.pppoe_client = [{ ".id": "*60", name: "ppp-users", interface: "ether1" }]
ppp.input.request.fields.interfaces = "ppp-users"
assert.equal((await readVrfProductionSnapshot(ppp.input)).catalogs.pppoe_client[0].interface, "ether1")
const deep = model()
deep.catalogs.interface_inventory = [{ ".id": "*10", name: "ether1", type: "ether" }]
deep.catalogs.vlan = []
for (let i = 0; i < 130; i++) {
deep.catalogs.interface_inventory.push({ ".id": `*${(1000 + i).toString(16)}`, name: `vlan-${i}`, type: "vlan" })
deep.catalogs.vlan.push({ ".id": `*${(2000 + i).toString(16)}`, name: `vlan-${i}`, interface: i === 129 ? "ether1" : `vlan-${i + 1}` })
}
deep.catalogs.vrf[0].interfaces = "vlan-0"
await assert.rejects(readVrfProductionSnapshot(deep.input), /closure budget/)
console.log("VRF production raw reader model tests passed")
// Optional observation adds no GET, authentication, source resolution or timer.
const observed = model(), observations: VrfRawReadObservation[] = []
assert.deepEqual(await readVrfProductionSnapshot({ ...observed.input, observeRead: value => observations.push(value) }), snapshot)
assert.deepEqual(observed.calls, happy.calls)
assert.deepEqual(observed.counters(), happy.counters())
assert.equal(observations.length, observed.calls.length * 5 + 2)
assert.deepEqual(observations.slice(0, 4).map(value => value.boundary), ["authority-before", "native-get", "authority-after", "shape"])
assert.ok(observations.every(value => value.serverId === 7))
assert.deepEqual(observations.at(-2), { serverId: 7, boundary: "final-authority" })
assert.deepEqual(observations.at(-1), { serverId: 7, boundary: "snapshot-validation" })
for (const rejectAsync of [false, true]) {
const unchanged = model()
await readVrfProductionSnapshot({ ...unchanged.input, observeRead: () => {
if (rejectAsync) return Promise.reject(Error("private observer failure"))
throw Error("private observer failure")
} })
await new Promise(resolve => setImmediate(resolve))
assert.deepEqual(unchanged.calls, happy.calls)
assert.deepEqual(unchanged.counters(), happy.counters())
}
const failedGet = model(), readError = Object.assign(Error("PRIVATE_NATIVE_JSON_OR_TRANSPORT"), { code: "ECONNRESET" }), readEvents: VrfRawReadObservation[] = []
const resolveSource = failedGet.input.adapter.resolve
failedGet.input.adapter.resolve = async serverId => {
const source = await resolveSource(serverId)
return { ...source, client: { async get<T>(): Promise<T> { throw readError } } }
}
await assert.rejects(readVrfProductionSnapshot({ ...failedGet.input, observeRead: value => readEvents.push(value) }), error => error === readError)
assert.deepEqual(readEvents.at(-1), { serverId: 7, catalog: "bridge", boundary: "native-get" })
const failedShape = model(), shapeEvents: VrfRawReadObservation[] = []
failedShape.payloads.bridge = { PRIVATE_NATIVE_ROWS: "not a catalog" }
await assert.rejects(readVrfProductionSnapshot({ ...failedShape.input, observeRead: value => shapeEvents.push(value) }), /incomplete\/oversized raw catalog/)
assert.deepEqual(shapeEvents.at(-1), { serverId: 7, catalog: "bridge", boundary: "shape" })
const failedAuthority = model(), authorityEvents: VrfRawReadObservation[] = []
failedAuthority.afterGet(() => failedAuthority.revoke())
await assert.rejects(readVrfProductionSnapshot({ ...failedAuthority.input, observeRead: value => authorityEvents.push(value) }))
assert.deepEqual(authorityEvents.at(-1), { serverId: 7, catalog: "bridge", boundary: "authority-after" })
assert.equal(JSON.stringify([...readEvents, ...shapeEvents, ...authorityEvents]).includes("PRIVATE"), false)
for (const kind of ["inventory", "closure", "source"] as const) {
const local = model(), localEvents: VrfRawReadObservation[] = []
if (kind === "inventory") local.catalogs.interface_inventory.push({ ".id": "*ff88", name: "ether1", type: "ether" })
if (kind === "closure") local.input.request.fields.interfaces = "missing-selected-member"
if (kind === "source") {
local.catalogs.interface_inventory.push({ ".id": "*50", name: "customer-gre", type: "gre-tunnel" })
local.catalogs.gre = [{ ".id": "*60", name: "customer-gre", "local-address": "0.0.0.0", "remote-address": "198.51.100.1" }]
local.input.request.fields.interfaces = "customer-gre"
}
await assert.rejects(readVrfProductionSnapshot({ ...local.input, observeRead: value => localEvents.push(value) }))
assert.deepEqual(localEvents.at(-1), { serverId: 7, boundary: "snapshot-validation" }, kind)
assert.ok(local.calls.length >= VRF_PRODUCTION_REQUIRED_CATALOGS.length)
}
const budget = model(), budgetEvents: VrfRawReadObservation[] = []
for (const resource of ["bridge", "bridge_port", "bridge_vlan", "ip_filter", "ipv6_filter"]) budget.catalogs[resource] = [{ ".id": "*ff88", opaque: "x".repeat(7 * 1024 * 1024) }]
await assert.rejects(readVrfProductionSnapshot({ ...budget.input, observeRead: value => budgetEvents.push(value) }), /raw evidence byte budget/)
assert.deepEqual(budgetEvents.at(-1), { serverId: 7, boundary: "snapshot-validation" })
const finalAuthority = model(), finalEvents: VrfRawReadObservation[] = []
finalAuthority.afterResolve(() => {
if (finalAuthority.counters().resolveCalls === happy.counters().resolveCalls) finalAuthority.revoke()
})
await assert.rejects(readVrfProductionSnapshot({ ...finalAuthority.input, observeRead: value => finalEvents.push(value) }))
assert.deepEqual(finalEvents.at(-1), { serverId: 7, boundary: "final-authority" })
console.log("VRF raw-reader optional diagnostics: same IO/order/timers and original read/shape/authority failures passed")