diff --git a/modules/nftables/allowances.ts b/modules/nftables/allowances.ts new file mode 100644 index 000000000..c93d74a9d --- /dev/null +++ b/modules/nftables/allowances.ts @@ -0,0 +1,306 @@ +// The operator's allowances (ADR 0683; design 33 control-verbs): a port opened by hand on this machine, beside the +// ports derived from the modules' listens. An allowance is this module's own state on the bus, one key per protocol, +// port and interface (allow..[.]); the node-engine asks `allowed` at every compose of a +// converged node's filter and renders it into the inet mesh table's input chain (design 08 control-verbs), so this +// code writes no rule. Every change is said as the seat's event allowances-changed, which the node-engine hears to +// compose the filter again; at its until an allowance is removed by a timer this module keeps per key from watching +// its own state, said and journalled, so no expired entry is kept or answered. + +import { isIP } from "node:net"; + +/** The state the allowances are kept in, as the seat's definition names it (§7). */ +export const STATE = "allowances"; + +/** The most allowances one node keeps (§2). */ +export const MOST = 100; + +/** The seat's event, on mesh.seat.node-packet-filter.event.allowances-changed. (§6). */ +export function changedSubject(node: string): string { + return `mesh.seat.node-packet-filter.event.allowances-changed.${node}`; +} + +export type Protocol = "tcp" | "udp"; + +/** One allowance as it is kept: the state's value (§7). */ +export interface Value { + port: number; + protocol: Protocol; + /** Absent: every input interface but the private network's. */ + interface?: string; + /** Absent: any source. */ + source?: string; + /** RFC 3339; absent: never expires. */ + until?: string; + why: string; + by: string; + at: string; +} + +/** One allowance as it is answered: its value with its key. */ +export interface Allowance extends Value { + key: string; +} + +export type Change = "allowed" | "disallowed" | "expired" | "started"; + +/** The event's body (§6). */ +export interface Changed { + node: string; + change: Change; + allowances: Allowance[]; + by?: string; + why?: string; + at: string; +} + +/** What the allowances need of the module's state: the SDK's `state()` serves it. */ +export interface Store { + get(key: string): Promise<{ value: Value } | null>; + put(key: string, value: Value): Promise; + delete(key: string): Promise; + keys(): Promise; +} + +/** One change of the state as its watch hands it over: the SDK's `StateChange`. */ +export interface Watched { + key: string; + op: "put" | "delete"; + value?: Value; +} + +/** Says the event. */ +export type Say = (body: Changed) => Promise; + +/** Runs `fire` after `ms` milliseconds, answering how to cancel it: `setTimeout` on the machine, a fake in tests. */ +export type Schedule = (ms: number, fire: () => void) => () => void; + +/** The longest one timer waits (Node's setTimeout holds 2^31-1 ms); a later until is waited for in steps. */ +export const LONGEST_WAIT_MS = 2 ** 31 - 1; + +export const timers: Schedule = (ms, fire) => { + const t = setTimeout(fire, ms); + return () => clearTimeout(t); +}; + +/** One key of the state: allow.., and . when it names one. */ +export function keyOf(protocol: Protocol, port: number, iface?: string): string { + return iface ? `allow.${protocol}.${port}.${iface}` : `allow.${protocol}.${port}`; +} + +const IFACE = /^[A-Za-z0-9_.-]{1,15}$/; + +function refuse(argument: string, why: string): never { + throw new Error(`${argument}: ${why}; nothing is written`); +} + +function only(args: Record, known: string[]): void { + for (const k of Object.keys(args)) { + if (!known.includes(k)) refuse(k, `not an argument of this verb (${known.join(", ") || "none"})`); + } +} + +function portOf(v: unknown): number { + if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 65535) { + refuse("port", `${JSON.stringify(v)} is not an integer from 1 to 65535`); + } + return v; +} + +function protocolOf(v: unknown): Protocol { + if (v === undefined) return "tcp"; + if (v === "tcp" || v === "udp") return v; + refuse("protocol", `${JSON.stringify(v)} is neither tcp (the default) nor udp`); +} + +function interfacesOf(v: unknown): (string | undefined)[] { + if (v === undefined) return [undefined]; + if (!Array.isArray(v)) refuse("interfaces", "a list of interface names"); + if (v.length === 0) return [undefined]; + for (const i of v) { + if (typeof i !== "string" || !IFACE.test(i)) { + refuse("interfaces", `${JSON.stringify(i)} is not 1 to 15 letters, digits, _ . or -`); + } + } + return [...new Set(v as string[])]; +} + +function sourceOf(v: unknown): string | undefined { + if (v === undefined) return undefined; + const s = typeof v === "string" ? v : ""; + const [addr, bits, more] = s.split("/"); + const family = isIP(addr); + const max = family === 4 ? 32 : 128; + if (family === 0 || more !== undefined || (bits !== undefined && !(/^\d+$/.test(bits) && Number(bits) <= max))) { + refuse("source", `${JSON.stringify(v)} is not one IPv4 or IPv6 CIDR`); + } + return s; +} + +function untilOf(v: unknown, now: Date): string | undefined { + if (v === undefined) return undefined; + const s = typeof v === "string" ? v : ""; + const t = Date.parse(s); + if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d(:\d\d(\.\d+)?)?(Z|[+-]\d\d:\d\d)$/.test(s) || Number.isNaN(t)) { + refuse("until", `${JSON.stringify(v)} is not an RFC 3339 time, such as 2026-11-22T08:00:00Z`); + } + if (t <= now.getTime()) refuse("until", `${s} is not in the future`); + return s; +} + +function whyOf(v: unknown): string { + if (typeof v !== "string" || v.length < 1 || v.length > 500) refuse("why", "required, 1 to 500 characters"); + return v; +} + +function answered(key: string, value: Value): Allowance { + return { key, ...value }; +} + +export class Allowances { + private readonly pending = new Map void>(); + private readonly store: Store; + private readonly node: string; + private readonly say: Say; + private readonly now: () => Date; + private readonly schedule: Schedule; + private readonly journal: (line: string) => void; + + constructor( + store: Store, + node: string, + say: Say, + now: () => Date = () => new Date(), + schedule: Schedule = timers, + journal: (line: string) => void = (line) => console.log(`[nftables] ${line}`), + ) { + this.store = store; + this.node = node; + this.say = say; + this.now = now; + this.schedule = schedule; + this.journal = journal; + } + + /** Said once each time the holder starts serving the seat, with every allowance (§6). */ + async started(): Promise { + const { allowances } = await this.allowed(); + await this.say({ node: this.node, change: "started", allowances, at: this.now().toISOString() }); + } + + /** One change of the module's own state, from its watch: a key with an until gets its timer, a removed key loses it. */ + async watched(change: Watched): Promise { + this.pending.get(change.key)?.(); + this.pending.delete(change.key); + if (change.op !== "put" || !change.value?.until) return; + this.arm(change.key, change.value.until); + } + + private arm(key: string, until: string): void { + const left = Date.parse(until) - this.now().getTime(); + if (left <= 0) { + void this.expire(key, until); + return; + } + const step = Math.min(left, LONGEST_WAIT_MS); + this.pending.set(key, this.schedule(step, () => { + this.pending.delete(key); + if (step < left) this.arm(key, until); + else void this.expire(key, until); + })); + } + + /** Remove a key at its until, when it still holds that until (a later allow replaced it otherwise) (§4). */ + async expire(key: string, until: string): Promise { + try { + const entry = await this.store.get(key); + if (!entry || entry.value.until !== until || Date.parse(until) > this.now().getTime()) return false; + await this.store.delete(key); + const a = answered(key, entry.value); + await this.say({ node: this.node, change: "expired", allowances: [a], at: this.now().toISOString() }); + this.journal(`the allowance ${key} (${a.protocol} ${a.port}${a.interface ? ` on ${a.interface}` : ""}${a.source ? ` from ${a.source}` : ""}, ` + + `set by ${a.by} at ${a.at}: ${a.why}) expired at ${until} and is removed`); + return true; + } catch (err) { + this.journal(`the allowance ${key} expired at ${until} and could not be removed: ${err instanceof Error ? err.message : String(err)}`); + return false; + } + } + + /** Open a port (§2): one key per named interface, or the default set's one key; a key there already is replaced + * whole and answered. */ + async allow(args: Record, by: string): Promise<{ allowances: (Allowance & { replaced?: Allowance })[]; said: boolean }> { + only(args, ["port", "protocol", "interfaces", "source", "until", "why"]); + const now = this.now(); + const port = portOf(args.port); + const protocol = protocolOf(args.protocol); + const interfaces = interfacesOf(args.interfaces); + const source = sourceOf(args.source); + const until = untilOf(args.until, now); + const why = whyOf(args.why); + const kept = (await this.store.keys()).filter((k) => k.startsWith("allow.")); + const after = new Set([...kept, ...interfaces.map((i) => keyOf(protocol, port, i))]).size; + if (after > MOST) refuse("port", `${after} allowances would be kept on this node, more than ${MOST}`); + const at = now.toISOString(); + const out: (Allowance & { replaced?: Allowance })[] = []; + for (const iface of interfaces) { + const key = keyOf(protocol, port, iface); + const value: Value = { + port, protocol, + ...(iface ? { interface: iface } : {}), + ...(source ? { source } : {}), + ...(until ? { until } : {}), + why, by, at, + }; + const before = await this.store.get(key); + await this.store.put(key, value); + out.push({ ...answered(key, value), ...(before ? { replaced: answered(key, before.value) } : {}) }); + } + await this.say({ node: this.node, change: "allowed", allowances: out.map(({ replaced: _, ...a }) => a), by, why, at }); + return { allowances: out, said: true }; + } + + /** Take back allowances (§3): every key named is deleted, or, when one does not exist, it is refused by name and + * none is deleted. */ + async disallow(args: Record, by: string): Promise<{ allowances: Allowance[]; said: boolean }> { + only(args, ["port", "protocol", "interfaces", "why"]); + const port = portOf(args.port); + const protocol = protocolOf(args.protocol); + const interfaces = interfacesOf(args.interfaces); + const why = whyOf(args.why); + const found: Allowance[] = []; + for (const iface of interfaces) { + const key = keyOf(protocol, port, iface); + const entry = await this.store.get(key); + if (!entry) throw new Error(`no allowance ${key} is kept on this node; nothing is deleted`); + found.push(answered(key, entry.value)); + } + for (const a of found) await this.store.delete(a.key); + await this.say({ node: this.node, change: "disallowed", allowances: found, by, why, at: this.now().toISOString() }); + return { allowances: found, said: true }; + } + + /** Every allowance kept, sorted by key (§4). One whose until passed before its timer fired is removed, said and + * left out, so none answered has expired. */ + async allowed(args: Record = {}): Promise<{ allowances: Allowance[] }> { + only(args, []); + const now = this.now().getTime(); + const allowances: Allowance[] = []; + for (const key of [...(await this.store.keys())].sort()) { + if (!key.startsWith("allow.")) continue; + const entry = await this.store.get(key); + if (!entry) continue; + if (entry.value.until && Date.parse(entry.value.until) <= now) { + await this.expire(key, entry.value.until); + continue; + } + allowances.push(answered(key, entry.value)); + } + return { allowances }; + } +} + +/** Each allowance marked loaded when a rule of the mesh's table carries its comment `allowance ` (§5). */ +export function markLoaded(allowances: Allowance[], meshTable: string): (Allowance & { loaded: boolean })[] { + const comments = new Set([...meshTable.matchAll(/comment "allowance ([^"]+)"/g)].map((m) => m[1])); + return allowances.map((a) => ({ ...a, loaded: comments.has(a.key) })); +} diff --git a/modules/nftables/module.json b/modules/nftables/module.json index 6c6634d86..2a60233d8 100644 --- a/modules/nftables/module.json +++ b/modules/nftables/module.json @@ -15,10 +15,20 @@ "serves": [ "rules", "reload", - "remove" + "remove", + "allow", + "disallow", + "allowed" ] } ], + "requires": [ + { + "name": "allowances", + "storage": "key-value", + "template": "state" + } + ], "filtering": { "into": "/etc/nftables.conf" }, diff --git a/modules/nftables/package.json b/modules/nftables/package.json index 6342c07b6..bff22772a 100644 --- a/modules/nftables/package.json +++ b/modules/nftables/package.json @@ -1,11 +1,11 @@ { "name": "@novox/module-nftables", "version": "0.1.0", - "description": "nftables — loads the mesh's packet filter and holds the node-packet-filter seat: its verbs rules, reload and remove (novox/hq ADR 0045, ADR 0170).", + "description": "nftables — loads the mesh's packet filter and holds the node-packet-filter seat: its verbs rules, reload, remove, allow, disallow and allowed (novox/hq ADR 0045, ADR 0170; design 47 H-A-304).", "type": "module", "private": true, "scripts": { - "build": "tsc client.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist", + "build": "tsc client.ts allowances.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist", "test": "node --test --experimental-strip-types 'test/*.test.ts'" }, "dependencies": { diff --git a/modules/nftables/test/allowances.test.ts b/modules/nftables/test/allowances.test.ts new file mode 100644 index 000000000..35efb47d1 --- /dev/null +++ b/modules/nftables/test/allowances.test.ts @@ -0,0 +1,191 @@ +// The operator's allowances against a state in memory (ADR 0683; design 33 control-verbs §9). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { + Allowances, LONGEST_WAIT_MS, MOST, STATE, changedSubject, markLoaded, + type Changed, type Schedule, type Store, type Value, +} from "../allowances.ts"; + +interface Timer { ms: number; fire: () => void; cancelled: boolean } + +function fake(at = "2026-11-21T20:00:00Z") { + const kept = new Map(); + 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) => (kept.has(k) ? { value: kept.get(k)! } : null), + put: async (k, v) => { kept.set(k, v); return kept.size; }, + delete: async (k) => { kept.delete(k); }, + keys: async () => [...kept.keys()], + }; + const a = new Allowances(store, "shanks", async (b) => { said.push(b); }, () => clock.now, schedule, (l) => journal.push(l)); + return { a, kept, said, clock, timers, journal }; +} + +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; 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, 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 and disallow refuse what is not an allowance, writing nothing", async () => { + const bad: [string, Record, 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: /], + ["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/], + ]; + for (const [name, args, want] of bad) { + const { a, kept, said } = fake(); + await assert.rejects(a.allow(args, "x"), want, name); + assert.equal(kept.size, 0, name); + assert.equal(said.length, 0, name); + } + const { a } = fake(); + 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; 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 100/); + assert.equal(kept.size, MOST); + await a.allow({ port: 1, why: "again" }, "x"); + assert.equal(kept.get("allow.tcp.1")!.why, "again"); +}); + +test("allow then disallow writes the key, then deletes it, saying allowed and disallowed", async () => { + const { a, kept, said } = fake(); + await a.allow({ port: 8000, interfaces: ["enp6s0"], why: "open" }, "x"); + 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"]]); +}); + +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()], ["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(([k, v]) => [k, v.source, v.by, v.until]), [["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: "allow.tcp.8000", op: "put", value: kept.get("allow.tcp.8000")! }); + assert.equal(timers.length, 1); + assert.equal(timers[0].ms, 3600_000); + clock.now = new Date("2026-11-21T21:00:00Z"); + timers[0].fire(); + await settle(); + assert.deepEqual([...kept.keys()], ["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", op: "put", value: v }); + await a.watched({ key: "k", op: "delete" }); + assert.equal(timers.at(-1)!.cancelled, true); + await a.watched({ key: "far", 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("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: "allow.tcp.9000", op: "put", value: kept.get("allow.tcp.9000")! }); + await settle(); + assert.ok(!kept.has("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()], ["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"]]]); +}); + +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 when a rule of the mesh's table carries its comment", () => { + const table = 'table inet mesh {\n\tchain input {\n\t\tiifname != "mesh0" tcp dport 8000 accept comment "allowance allow.tcp.8000"\n\t}\n}\n'; + const base: Value = { port: 8000, protocol: "tcp", why: "w", by: "x", at: "t" }; + const got = markLoaded([{ key: "allow.tcp.8000", ...base }, { key: "allow.tcp.9000", ...base, port: 9000 }], table); + assert.deepEqual(got.map((x) => [x.key, x.loaded]), [["allow.tcp.8000", true], ["allow.tcp.9000", false]]); +}); + +test("the manifest serves the six verbs and requires the state the code keeps", () => { + 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" }]); + assert.equal(changedSubject("shanks"), "mesh.seat.node-packet-filter.event.allowances-changed.shanks"); +}); diff --git a/modules/nftables/tools/index.ts b/modules/nftables/tools/index.ts index 4f115383e..3b0dcf2ff 100644 --- a/modules/nftables/tools/index.ts +++ b/modules/nftables/tools/index.ts @@ -1,20 +1,41 @@ -// The packet filter's tools: the node-packet-filter seat's three verbs — what the machine enforces, -// reload the mesh's own, remove one thing the mesh did not write — and the module's own reading of -// the mesh's table (novox/hq ADR 0045, ADR 0168, ADR 0170). +// The packet filter's tools: the node-packet-filter seat's six verbs — what the machine enforces, reload the +// mesh's own, remove one thing the mesh did not write, and the operator's allowances (allow, disallow, allowed) — +// and the module's own reading of the mesh's table (novox/hq ADR 0045, ADR 0168, ADR 0170, ADR 0683; design 33 +// control-verbs). import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools"; +import { callerOf } from "@novox/mesh-sdk/callers"; +import { seatPublish } from "@novox/mesh-sdk/runtime"; +import { keeps, state } from "@novox/mesh-sdk/state"; import { FirewallClient } from "../client.js"; +import { Allowances, STATE, changedSubject, markLoaded, type Store, type Value } from "../allowances.js"; -export function getSeatVerbs(firewall: FirewallClient): ToolDefinition[] { +const port = { type: "integer", description: "the port, 1-65535" }; +const protocol = { type: "string", description: "tcp (the default) or udp" }; +const interfaces = { + type: "array", + items: { type: "string" }, + description: "the input interfaces, each 1-15 letters, digits, _ . - (optional; none: every input interface but the private network's)", +}; +const why = { type: "string", description: "why, in words the operator reads (1-500 characters)" }; + +export function getSeatVerbs(firewall: FirewallClient, allowances: Allowances): ToolDefinition[] { return [ { name: "rules", description: - "The packet filter as this machine enforces it now: the nftables ruleset and, where the tool exists, the legacy filter's listings. Narrowed to one table or chain when asked.", + "The packet filter as this machine enforces it now: the nftables ruleset and, where the tool exists, the legacy filter's listings. Narrowed to one table or chain when asked. " + + "Beside it every allowance, marked loaded when a rule of the mesh's table carries its comment allowance .", input: { table: { type: "string", description: "one nftables table, as `family name` (optional)" }, chain: { type: "string", description: "one chain of that table (optional)" }, }, - run: async (args) => firewall.rules(args.table ? String(args.table) : undefined, args.chain ? String(args.chain) : undefined), + run: async (args) => { + const table = args.table ? String(args.table) : undefined; + const seen = await firewall.rules(table, args.chain ? String(args.chain) : undefined); + // The mark reads the mesh's own table whole, whatever the listing was narrowed to. + const mesh = !table && !args.chain ? seen.nftables : await firewall.ruleset(); + return { ...seen, allowances: markLoaded((await allowances.allowed()).allowances, mesh) }; + }, }, { name: "reload", @@ -30,6 +51,39 @@ export function getSeatVerbs(firewall: FirewallClient): ToolDefinition[] { input: { where: { type: "string", description: "the rule set, as `node show` lists it" } }, run: async (args) => firewall.remove(String(args.where ?? "")), }, + { + name: "allow", + description: + "Open a port by hand on this machine, beside the ports derived from the modules' listens: one allowance per protocol, port and interface, " + + "kept as this module's state and rendered by the node-engine into the inet mesh table's input chain at its next compose of the filter. " + + "A key that exists is replaced whole and answered. Refuses, naming the argument and writing nothing, a bad port, protocol, interface, source or until, " + + "an empty or longer why, an unknown argument, and more than 100 allowances on the node. Whether the loaded chain carries it is read with rules.", + input: { + port, + protocol, + interfaces, + source: { type: "string", description: "one IPv4 or IPv6 CIDR it is opened to (optional; none: any)" }, + until: { type: "string", description: "when it expires, an RFC 3339 time in the future (optional)" }, + why, + }, + run: async (args) => allowances.allow(args, callerOf(args)), + }, + { + name: "disallow", + description: + "Take back allowances: the keys the protocol, port and interfaces name (none: the default set's key) are deleted, or, when one does not exist, " + + "it is refused by name and none is deleted.", + input: { port, protocol, interfaces, why }, + run: async (args) => allowances.disallow(args, callerOf(args)), + }, + { + name: "allowed", + description: + "Every allowance kept on this machine, with its key, port, protocol, interface, source, until, why, by and at. " + + "An allowance is removed at its until, so none answered has expired.", + input: {}, + run: async (args) => allowances.allowed(args), + }, ]; } @@ -45,7 +99,18 @@ export function getFirewallTools(firewall: FirewallClient): ToolDefinition[] { } const firewall = FirewallClient.onThisMachine(); +// The allowances are this module's own state, announced as kept (ADR 0495), every change said as the seat's event +// allowances-changed of this node; watching its own state gives every key with an until its timer, at every start +// too; and a start says started, so a node-engine that refused a compose for want of an answer composes again. +const node = process.env.MESH_NODE ?? ""; +const kept = state(STATE); +const allowances = new Allowances(kept as Store, node, (body) => seatPublish(changedSubject(node), body)); +void (async () => { + await keeps([{ name: STATE }]); + await kept.watch((change) => allowances.watched(change)); + await allowances.started(); +})().catch((err) => console.error(`[nftables] the allowances did not start (no expiry timers, no started said): ${err}`)); // The seat's verbs under the seat's name: the runtime serves them on the seat's subjects where this // module holds it (ADR 0159, 0160). The module's own under its own. -registerModuleTools("node-packet-filter", () => getSeatVerbs(firewall)); +registerModuleTools("node-packet-filter", () => getSeatVerbs(firewall, allowances)); registerModuleTools("nftables", () => getFirewallTools(firewall));