Files
mesh-catalog/modules/nftables/test/allowances.test.ts
T
jschoubben 3ec18c9cd2 M1: nftables' setting allowances-max is marked runtime
The packet filter holder's tools read allowances-max themselves (config at
tools/index.ts); no file places it, so the manifest says "runtime": true
and the judge's placed-nowhere rule holds it as read by the module's code.

Builds: design 47 H2 H-A-430 (4)
2026-11-22 01:45:28 +01:00

358 lines
22 KiB
TypeScript

// The operator's allowances against a state in memory (ADR 0683; design 33 control-verbs §14; design 47 H-A-315,
// H-A-317, H-A-318, H-A-319).
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
Allowances, CONVERGED_BOUND_MS, LONGEST_WAIT_MS, MOST, STATE, held, markLoaded, privateOnly,
type AllowanceValue as Value, type AllowancesChanged as Changed, type Convergence, type HandAct, type Schedule, type Store,
} from "../allowances.ts";
interface Timer { ms: number; fire: () => void; cancelled: boolean }
// The loaded mesh table: the store's port from the private network only, 80 from anywhere and 8443 from both; each derived
// accept rule carries the one comment the node-engine's render writes, `derived <modules> <protocol>/<port> scope <scope>`
// (47 H2 §813 (4), H-A-357), its module list cut with a count past 128 bytes (H-A-384 (1)).
const TABLE = 'table inet mesh {\n\tchain input {\n\t\ttype filter hook input priority filter; policy drop;\n' +
'\t\tip saddr { 10.77.0.1, 10.77.0.2 } tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"\n' +
'\t\tip6 saddr { fd77::1 } tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"\n' +
'\t\ttcp dport 80 accept comment "derived route-proxy tcp/80 scope any"\n' +
'\t\tip saddr { 10.77.0.1 } tcp dport 8443 accept comment "derived a,b,+4 tcp/8443 scope private-network"\n' +
'\t\ttcp dport 8443 accept comment "derived c tcp/8443 scope any"\n' +
'\t\tip saddr { 192.168.1.0/24 } tcp dport 9500-9600 accept comment "derived nats tcp/9500-9600 scope local-network"\n' +
'\t\ttcp dport 7000 accept comment "derived x,+2 tcp/7000 scope private-network"\n' +
'\t\tip saddr { 10.77.0.1 } tcp dport 7100 accept\n\t}\n}\n';
// gate, when given, holds every delete until it opens, and every get waits a turn of the event loop: a slow store.
function fake(at = "2026-11-21T20:00:00Z", node = "shanks", kept = new Map<string, Value>(), gate?: Promise<void>) {
const said: Changed[] = [];
const journal: string[] = [];
const timers: Timer[] = [];
const clock = { now: new Date(at) };
const schedule: Schedule = (ms, fire) => {
const t = { ms, fire, cancelled: false };
timers.push(t);
return () => { t.cancelled = true; };
};
const store: Store = {
get: async (k) => {
if (gate) await new Promise((r) => setImmediate(r));
return kept.has(k) ? { value: kept.get(k)! } : null;
},
put: async (k, v) => { kept.set(k, v); return kept.size; },
delete: async (k) => { await gate; kept.delete(k); },
keys: async () => [...kept.keys()],
};
const acts: HandAct[] = [];
const asks = {
convergence: { state: "converged", since: "2026-11-01T00:00:00Z" } as Convergence | "silent",
asked: 0,
most: MOST,
table: TABLE,
};
const a = new Allowances(store, node, async (b) => { said.push(b); }, {
converged: () => {
asks.asked++;
return asks.convergence === "silent" ? new Promise<Convergence>(() => {}) : Promise.resolve(asks.convergence);
},
handAct: async (act) => { acts.push(act); },
most: async () => asks.most,
meshTable: async () => asks.table,
}, () => clock.now, schedule, (l) => journal.push(l));
return { a, kept, said, clock, timers, journal, acts, asks };
}
/** The state's key of an allowance's key on shanks (H-A-317). */
const k = (key: string) => `shanks.${key}`;
const settle = () => new Promise((r) => setImmediate(r));
test("allow keeps one key per interface, and with none the default set's key, which names no interface", async () => {
const cases: { name: string; args: Record<string, unknown>; keys: string[] }[] = [
{ name: "defaults", args: { port: 8000, why: "the operator's dev server" }, keys: ["allow.tcp.8000"] },
{ name: "two interfaces", args: { port: 5353, protocol: "udp", interfaces: ["enp6s0", "wlan0"], source: "192.168.1.0/24", why: "w" },
keys: ["allow.udp.5353.enp6s0", "allow.udp.5353.wlan0"] },
{ name: "an interface with a dot", args: { port: 1, interfaces: ["enp6s0.10"], why: "w" }, keys: ["allow.tcp.1.enp6s0.10"] },
];
for (const c of cases) {
const { a, kept, said } = fake();
const got = await a.allow(c.args, "lead@shanks");
assert.deepEqual(got.allowances.map((x) => x.key), c.keys, c.name);
assert.equal(got.said, true, c.name);
assert.deepEqual([...kept.keys()].sort(), c.keys.map(k), c.name);
assert.deepEqual(said.map((b) => [b.change, b.node, b.by, b.why, b.allowances.map((x) => x.key)]),
[["allowed", "shanks", "lead@shanks", c.args.why, c.keys]], c.name);
for (const v of kept.values()) {
assert.equal(v.by, "lead@shanks", c.name);
assert.equal(v.at, "2026-11-21T20:00:00.000Z", c.name);
assert.equal(v.source, c.args.source, c.name);
if (!c.args.interfaces) assert.equal("interface" in v, false, "the private network's interface is never in the defaults");
}
}
});
test("allow naming an outward link answers it as outward, as converged lists them; another interface and the default set do not (H-A-325)", async () => {
const { a, asks, said } = fake();
asks.convergence = { state: "converged", since: "2026-11-01T00:00:00Z", tunnel: "mesh0", outward: ["eth1"] };
const named = await a.allow({ port: 8000, interfaces: ["eth1", "enp6s0"], why: "w" }, "lead@shanks");
assert.deepEqual(named.allowances.map((x) => [x.key, x.outward]), [["allow.tcp.8000.eth1", "eth1"], ["allow.tcp.8000.enp6s0", undefined]]);
assert.equal("outward" in named.allowances[1], false, "an interface that is no outward link answers without the field");
const none = await a.allow({ port: 8001, why: "w" }, "lead@shanks");
assert.equal("outward" in none.allowances[0], false, "the default set opens no outward link");
assert.equal(said.flatMap((b) => b.allowances).some((x) => "outward" in x), false, "the event's allowances carry no outward");
});
test("allow and disallow refuse what is not an allowance, writing nothing", async () => {
const bad: [string, Record<string, unknown>, RegExp][] = [
["port 0", { port: 0, why: "w" }, /port: /],
["port 65536", { port: 65536, why: "w" }, /port: /],
["port 80a", { port: "80a", why: "w" }, /port: /],
["protocol icmp", { port: 80, protocol: "icmp", why: "w" }, /protocol: /],
["interface", { port: 80, interfaces: ["a b"], why: "w" }, /interfaces: /],
["interface too long", { port: 80, interfaces: ["abcdefghijklmnop"], why: "w" }, /interfaces: /],
["source", { port: 80, source: "10.0.0.0/33", why: "w" }, /source: /],
["until in the past", { port: 80, until: "2026-11-21T19:00:00Z", why: "w" }, /until: .*not in the future/],
["until not a time", { port: 80, until: "tomorrow", why: "w" }, /until: /],
["until without seconds", { port: 80, until: "2026-11-22T08:00Z", why: "w" }, /until: .* with seconds/],
["empty why", { port: 80, why: "" }, /why: /],
["long why", { port: 80, why: "x".repeat(501) }, /why: /],
["unknown argument", { port: 80, why: "w", comment: "x" }, /comment: not an argument/],
["the store's port with no source", { port: 5432, why: "w" }, /port: tcp 5432 is admitted .* from given sources only/],
];
for (const [name, args, want] of bad) {
const { a, kept, said, acts } = fake();
await assert.rejects(a.allow(args, "x"), want, name);
assert.equal(kept.size, 0, name);
assert.equal(said.length, 0, name);
assert.equal(acts.length, 0, name);
}
const { a, kept } = fake();
await assert.rejects(a.allow({ port: 80, why: "w" }, "unproven"), /allow: refused: the request carries no caller the tool runner proved/);
await assert.rejects(a.disallow({ port: 80, why: "w" }, "unproven"), /disallow: refused: the request carries no caller/);
await a.allow({ port: 5432, source: "192.168.1.0/24", why: "the store from the home network" }, "x");
assert.deepEqual([...kept.keys()], [k("allow.tcp.5432")]);
await assert.rejects(a.disallow({ port: 80, why: "w", source: "10.0.0.1" }, "x"), /source: not an argument/);
await assert.rejects(a.disallow({ port: 80 }, "x"), /why: /);
await assert.rejects(a.allowed({ port: 80 }), /port: not an argument/);
});
test("a 101st allowance is refused at the default allowances-max; a replacement at the bound is not", async () => {
const { a, kept } = fake();
for (let p = 1; p <= MOST; p++) await a.allow({ port: p, why: "w" }, "x");
await assert.rejects(a.allow({ port: 1000, why: "w" }, "x"), /101 allowances would be kept on this node, more than allowances-max 100/);
assert.equal(kept.size, MOST);
await a.allow({ port: 1, why: "again" }, "x");
assert.equal(kept.get(k("allow.tcp.1"))!.why, "again");
});
test("an allowance kept on one node is absent from another node's allowed, and counts not toward its bound", async () => {
const shared = new Map<string, Value>();
const shanks = fake(undefined, "shanks", shared);
const ace = fake(undefined, "ace", shared);
ace.asks.most = 1;
await shanks.a.allow({ port: 8000, why: "w" }, "x");
assert.deepEqual((await ace.a.allowed()).allowances, []);
await ace.a.allow({ port: 9000, why: "w" }, "x");
assert.deepEqual([...shared.keys()].sort(), ["ace.allow.tcp.9000", "shanks.allow.tcp.8000"]);
assert.deepEqual((await shanks.a.allowed()).allowances.map((x) => x.key), ["allow.tcp.8000"]);
await assert.rejects(ace.a.disallow({ port: 8000, why: "w" }, "x"), /no allowance allow\.tcp\.8000 /);
});
test("on an adopted node allow and disallow are refused naming the adoption and allowed answers none; a silent converged refuses both", async () => {
const { a, kept, asks, timers, said } = fake();
await a.allow({ port: 8000, why: "w" }, "x");
asks.convergence = { state: "adopted", since: "2026-11-20T10:00:00Z", found: "ufw" };
await assert.rejects(a.allow({ port: 9000, why: "w" }, "x"), /allow: refused: this node is adopted \(the found firewall ufw, since 2026-11-20T10:00:00Z\)/);
await assert.rejects(a.disallow({ port: 8000, why: "w" }, "x"), /disallow: refused: this node is adopted/);
assert.deepEqual((await a.allowed()).allowances, []);
assert.deepEqual([...kept.keys()], [k("allow.tcp.8000")]);
asks.convergence = "silent";
const pending = a.allow({ port: 9000, why: "w" }, "x");
const bound = timers.at(-1)!;
assert.equal(bound.ms, CONVERGED_BOUND_MS);
bound.fire();
await assert.rejects(pending, /allow: refused: the node-engine's converged did not answer \(no answer within 10 s\)/);
const gone = a.disallow({ port: 8000, why: "w" }, "x");
timers.at(-1)!.fire();
await assert.rejects(gone, /disallow: refused: the node-engine's converged did not answer/);
assert.equal(said.length, 1);
});
test("allowed asks converged again while none answered, and refuses when it does not answer (H-A-318)", async () => {
const { a, asks, timers, said, journal } = fake();
asks.convergence = "silent";
const start = a.started();
timers.at(-1)!.fire();
await start;
assert.match(journal.join("\n"), /start: refused: the node-engine's converged did not answer/);
assert.equal(said.at(-1)!.change, "started");
const asked = asks.asked;
const pending = a.allowed();
timers.at(-1)!.fire();
await assert.rejects(pending, /allowed: refused: the node-engine's converged did not answer/);
assert.equal(asks.asked, asked + 1);
asks.convergence = { state: "converged" };
assert.deepEqual((await a.allowed()).allowances, []);
await a.allowed();
assert.equal(asks.asked, asked + 2, "an answer held is not asked again");
});
test("privateOnly: a port a derived rule's comment scopes to the private or the local network, none to any", () => {
assert.equal(privateOnly(TABLE, "tcp", 5432), true);
assert.equal(privateOnly(TABLE, "tcp", 9550), true, "a range, local-network");
// 47 H2 §813 (4): the scope is read from the rule's comment, never from its shape.
assert.equal(privateOnly(TABLE, "tcp", 7000), true, "a comment cut with a count says private-network, whatever the shape");
assert.equal(privateOnly(TABLE, "tcp", 7100), false, "a rule with a source match and no derived comment names no scope");
assert.equal(privateOnly(TABLE, "tcp", 80), false);
assert.equal(privateOnly(TABLE, "tcp", 8443), false, "accepted from anywhere too");
assert.equal(privateOnly(TABLE, "udp", 5432), false);
assert.equal(privateOnly(TABLE, "tcp", 8000), false, "no derived rule");
});
test("allow then disallow writes the key, then deletes it, saying allowed and disallowed, with two hand-act log lines", async () => {
const { a, kept, said, acts } = fake();
const got = await a.allow({ port: 8000, interfaces: ["enp6s0"], why: "open" }, "x");
assert.equal(got.said, true);
assert.deepEqual((await a.allowed()).allowances.map((x) => x.key), ["allow.tcp.8000.enp6s0"]);
const gone = await a.disallow({ port: 8000, interfaces: ["enp6s0"], why: "done" }, "y");
assert.deepEqual(gone.allowances.map((x) => x.key), ["allow.tcp.8000.enp6s0"]);
assert.equal(gone.said, true);
assert.equal(kept.size, 0);
assert.deepEqual(said.map((b) => [b.change, b.by, b.why]), [["allowed", "x", "open"], ["disallowed", "y", "done"]]);
assert.deepEqual(acts, [
{ what: "allowed allow.tcp.8000.enp6s0 on shanks", why: "open (x)", cause: "allowance-set", verb: "allow" },
{ what: "disallowed allow.tcp.8000.enp6s0 on shanks", why: "done (y)", cause: "allowance-taken-back", verb: "disallow" },
]);
});
test("disallow is all or nothing: a key not kept is refused by name and none is deleted", async () => {
const { a, kept, said } = fake();
await a.allow({ port: 8000, interfaces: ["enp6s0"], why: "w" }, "x");
await assert.rejects(a.disallow({ port: 8000, interfaces: ["enp6s0", "wlan0"], why: "w" }, "x"), /no allowance allow\.tcp\.8000\.wlan0/);
assert.deepEqual([...kept.keys()], [k("allow.tcp.8000.enp6s0")]);
// no interfaces names the default set's key, never one of an interface
await assert.rejects(a.disallow({ port: 8000, why: "w" }, "x"), /no allowance allow\.tcp\.8000 /);
assert.equal(said.length, 1);
});
test("a second allow of one key replaces it whole and answers what it replaced; the source is no part of the key", async () => {
const { a, kept } = fake();
await a.allow({ port: 8000, source: "192.168.1.0/24", until: "2026-11-22T00:00:00Z", why: "first" }, "x");
const got = await a.allow({ port: 8000, source: "10.0.0.5", why: "second" }, "y");
assert.deepEqual(got.allowances.map((x) => [x.key, x.source, x.replaced?.source, x.replaced?.why]),
[["allow.tcp.8000", "10.0.0.5", "192.168.1.0/24", "first"]]);
assert.deepEqual([...kept.entries()].map(([key, v]) => [key, v.source, v.by, v.until]), [[k("allow.tcp.8000"), "10.0.0.5", "y", undefined]]);
});
test("at its until an allowance is deleted by its timer, says expired, is journalled, and allowed answers without it", async () => {
const { a, kept, said, clock, timers, journal } = fake();
await a.allow({ port: 8000, until: "2026-11-21T21:00:00Z", why: "for an hour" }, "x");
await a.allow({ port: 9000, why: "w" }, "x");
await a.watched({ key: k("allow.tcp.8000"), op: "put", value: kept.get(k("allow.tcp.8000"))! });
const live = timers.filter((t) => !t.cancelled);
assert.equal(live.length, 1, "one expiry timer; every converged bound is cancelled once answered");
assert.equal(live[0].ms, 3600_000);
clock.now = new Date("2026-11-21T21:00:00Z");
live[0].fire();
await settle();
assert.deepEqual([...kept.keys()], [k("allow.tcp.9000")]);
assert.deepEqual([said.at(-1)!.change, said.at(-1)!.allowances.map((x) => x.key)], ["expired", ["allow.tcp.8000"]]);
assert.match(journal.join("\n"), /the allowance allow\.tcp\.8000 .*for an hour\) expired at 2026-11-21T21:00:00Z and is removed/);
assert.deepEqual((await a.allowed()).allowances.map((x) => x.key), ["allow.tcp.9000"]);
});
test("the expiry timers follow the state: a delete cancels, a far until waits in steps, a stale timer removes nothing", async () => {
const { a, kept, clock, timers } = fake();
const v: Value = { port: 1, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00Z", until: "2026-11-21T22:00:00Z" };
await a.watched({ key: k("allow.tcp.1"), op: "put", value: v });
await a.watched({ key: k("allow.tcp.1"), op: "delete" });
assert.equal(timers.at(-1)!.cancelled, true);
const armed = timers.length;
await a.watched({ key: "ace.allow.tcp.1", op: "put", value: v });
assert.equal(timers.length, armed, "another node's key arms no timer");
await a.watched({ key: k("allow.tcp.2"), op: "put", value: { ...v, until: "2027-06-01T00:00:00Z" } });
assert.equal(timers.at(-1)!.ms, LONGEST_WAIT_MS);
await a.allow({ port: 9000, until: "2026-11-21T21:30:00Z", why: "w" }, "x");
await a.allow({ port: 9000, until: "2026-11-21T23:00:00Z", why: "w" }, "x");
clock.now = new Date("2026-11-21T21:30:00Z");
assert.equal(await a.expire("allow.tcp.9000", "2026-11-21T21:30:00Z"), false);
assert.ok(kept.has(k("allow.tcp.9000")));
// at a start, a key already past its until is removed at once
clock.now = new Date("2026-11-22T00:00:00Z");
await a.watched({ key: k("allow.tcp.9000"), op: "put", value: kept.get(k("allow.tcp.9000"))! });
await settle();
assert.ok(!kept.has(k("allow.tcp.9000")));
});
test("at a start every expired allowance is removed before started is said (H-A-312 (2))", async () => {
const { a, kept, said, clock } = fake();
await a.allow({ port: 8000, until: "2026-11-21T21:00:00Z", why: "w" }, "x");
await a.allow({ port: 9000, why: "w" }, "x");
clock.now = new Date("2026-11-21T22:00:00Z");
await a.started();
assert.deepEqual([...kept.keys()], [k("allow.tcp.9000")]);
assert.deepEqual(said.slice(-2).map((b) => [b.change, b.allowances.map((x) => x.key)]),
[["expired", ["allow.tcp.8000"]], ["started", ["allow.tcp.9000"]]]);
// §11, §14: a key past its until that the watch hands over while the start runs, through a store whose get and delete
// wait: the start waits for that expiry, so it is removed and said once, and started after it.
let open!: () => void;
const waits = new Promise<void>((r) => { open = r; });
const slow = fake("2026-11-21T22:00:00Z", "shanks", new Map(), waits);
const past: Value = { port: 7000, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00Z", until: "2026-11-21T21:00:00Z" };
slow.kept.set(k("allow.tcp.7000"), past);
await slow.a.watched({ key: k("allow.tcp.7000"), op: "put", value: past });
const start = slow.a.started();
for (let i = 0; i < 10; i++) await settle(); // the start runs as far as it goes while the expiry's delete waits
open();
await start;
assert.deepEqual(slow.said.map((b) => [b.change, b.allowances.map((x) => x.key)]),
[["expired", ["allow.tcp.7000"]], ["started", []]]);
});
test("started is said before the first allowed: the verbs are held until the start ends, a failed start refuses them", async () => {
const { a, asks, said, timers } = fake();
asks.convergence = "silent";
const start = a.started();
let answered = false;
const first = held(start, () => a.allowed())().then((r) => { answered = true; return r; });
await settle();
assert.equal(answered, false, "allowed answered while the start still waits on converged");
assert.equal(said.length, 0);
asks.convergence = { state: "converged", tunnel: "mesh0", outward: [] };
timers.find((t) => t.ms === CONVERGED_BOUND_MS && !t.cancelled)!.fire();
await first;
assert.deepEqual(said.map((b) => b.change), ["started"], "started was said before allowed answered");
const failed = Promise.reject(new Error("the allowances did not start: no bus"));
failed.catch(() => {});
await assert.rejects(held(failed, () => a.allowed())(), /did not start: no bus/);
});
test("a start says started with every allowance", async () => {
const { a, said } = fake();
await a.allow({ port: 8000, why: "w" }, "x");
await a.started();
assert.deepEqual([said.at(-1)!.change, said.at(-1)!.node, said.at(-1)!.allowances.map((x) => x.key)], ["started", "shanks", ["allow.tcp.8000"]]);
});
test("rules marks an allowance loaded only on a comment with an equal at, and lists a comment with no kept key as loaded, not kept", () => {
const table = 'table inet mesh {\n\tchain input {\n' +
'\t\tiifname != "mesh0" tcp dport 8000 accept comment "allowance allow.tcp.8000 2026-11-21T20:00:00.000Z"\n' +
'\t\tiifname != "mesh0" tcp dport 8001 accept comment "allowance allow.tcp.8001 2026-11-21T19:00:00.000Z"\n' +
'\t\tiifname != "mesh0" tcp dport 7000 accept comment "allowance allow.tcp.7000 2026-11-20T08:00:00.000Z"\n\t}\n}\n';
const base: Value = { port: 8000, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00.000Z" };
const got = markLoaded([{ key: "allow.tcp.8000", ...base }, { key: "allow.tcp.8001", ...base, port: 8001 }, { key: "allow.tcp.9000", ...base, port: 9000 }], table);
assert.deepEqual(got.allowances.map((x) => [x.key, x.loaded]), [["allow.tcp.8000", true], ["allow.tcp.8001", false], ["allow.tcp.9000", false]]);
assert.deepEqual(got.loadedNotKept, [{ key: "allow.tcp.7000", at: "2026-11-20T08:00:00.000Z" }]);
});
test("the manifest serves the six verbs, requires the state per machine, invokes converged and the hand-act log, and sets allowances-max", () => {
const m = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8"));
assert.deepEqual(m.claims[0].serves, ["rules", "reload", "remove", "allow", "disallow", "allowed"]);
assert.deepEqual(m.requires, [{ name: STATE, storage: "key-value", template: "state", options: { history: 1, "per-machine": true } }]);
assert.deepEqual(m.invokes, ["seat:node-engine.converged", "seat:mesh-hand-acts.hand-act"]);
assert.equal(m.emits, undefined, "the claim says the seat's event (H-A-317)");
assert.equal(m.config["allowances-max"].default, MOST);
assert.equal(m.config["allowances-max"].runtime, true, "the holder's code reads it itself; no file places it (H-A-430 (4))");
});