Files
mesh-catalog/modules/nftables/tools/index.ts
T
jschoubben 31abcad907 nftables: test that a start waits for the watch's expiry; refuse a stale node-engine package
Review round 2 (1): the start's wait for the expiries the watch handed over
had no test that failed without it; the start test gains a store whose
deletes wait, and without the wait the key is said expired twice. The note:
a node-engine package naming no verb converged refuses the start loudly
instead of asking seat:node-engine.undefined.

Builds: design 33 control-verbs §10, §11, §14; design 47 H H-A-312
2026-11-21 22:05:47 +01:00

173 lines
9.9 KiB
TypeScript

// 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 { broker } from "@novox/mesh-sdk/messaging";
import { config, seatPublish } from "@novox/mesh-sdk/runtime";
import { keeps, state } from "@novox/mesh-sdk/state";
import {
allowancesChangedSubject, seat as packetFilter, verbs,
type AllowInput, type AllowedInput, type DisallowInput,
} from "@novox/mesh-connectivity-contracts-node-packet-filter";
import { seat as nodeEngine, verbs as nodeEngineVerbs } from "@novox/mesh-contracts-node-engine";
import { FirewallClient } from "../client.js";
import { Allowances, MOST, STATE, held, markLoaded, type AllowanceValue, type Convergence, type Store } from "../allowances.js";
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 that is neither the private network's tunnel nor an outward link, so an outward link is opened only when named)",
};
const why = { type: "string", description: "why, in words the operator reads (1-500 characters)" };
// The seat's verbs, held until the holder's start ends (§8, §11): started is said before any answers. The inputs' types
// name exactly the arguments of the seat's generated inputs; the holder validates every value itself.
export function getSeatVerbs(firewall: FirewallClient, allowances: Allowances, start: Promise<unknown> = Promise.resolve()): ToolDefinition[] {
const allowed = held(start, () => allowances.allowed());
return [
{
name: verbs.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. " +
"Beside it every allowance, marked loaded only when a rule of the mesh's table carries its comment allowance <key> <at> with an equal at, " +
"and every loaded allowance comment whose key is not kept, listed as loaded, not kept.",
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) => {
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();
const marked = markLoaded((await allowed()).allowances, mesh);
return { ...seen, allowances: marked.allowances, "loaded-not-kept": marked.loadedNotKept };
},
},
{
name: verbs.reload,
description: "Load the mesh's own filter again from the file the mesh writes, and answer with the mesh's table as loaded.",
input: {},
run: async () => firewall.reload(),
},
{
name: verbs.remove,
description:
"Remove one rule set the mesh did not write, named exactly as `node show` lists it: `chain X (iptables-legacy)` or `table ip6 filter, chain DOCKER-USER`. " +
"Refuses the mesh's tables, the runtime's own chains, a built-in chain and an active found firewall's chains. An operator's act, by name, never a flush.",
input: { where: { type: "string", description: "the rule set, as `node show` lists it" } },
run: async (args) => firewall.remove(String(args.where ?? "")),
},
{
name: verbs.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. " +
"Who set it is the caller the bus proved. A key that exists is replaced whole and answered. Written in the hand-act log. " +
"Refuses, naming the argument and writing nothing, an unproven caller, an adopted node or a converged that does not answer, a bad port, protocol, interface, source or until, " +
"an empty or longer why, an unknown argument, a port the loaded mesh table admits from given sources only unless a source is given, " +
"and more allowances on the node than the setting allowances-max (default 100). 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 with seconds in the future (optional)" },
why,
} satisfies Record<keyof AllowInput, object>,
run: held(start, async (args: Readonly<Record<string, unknown>>) => allowances.allow({ ...args }, callerOf(args))),
},
{
name: verbs.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. Written in the hand-act log. Refuses as allow does an unproven caller, an adopted node and a converged that does not answer.",
input: { port, protocol, interfaces, why } satisfies Record<keyof DisallowInput, object>,
run: held(start, async (args: Readonly<Record<string, unknown>>) => allowances.disallow({ ...args }, callerOf(args))),
},
{
name: verbs.allowed,
description:
"Every allowance kept for this machine only, with its key, port, protocol, interface, source, until, why, by and at; none on an adopted node. " +
"An allowance is removed at its until, so none answered has expired.",
input: {} satisfies Record<keyof AllowedInput, object>,
run: held(start, async (args: Readonly<Record<string, unknown>>) => allowances.allowed({ ...args })),
},
];
}
export function getFirewallTools(firewall: FirewallClient): ToolDefinition[] {
return [
{
name: "firewall_rules",
description: "The mesh's live nftables table on this node — what the mesh's own filter is accepting and dropping.",
input: {},
run: async () => ({ ruleset: await firewall.ruleset() }),
},
];
}
const firewall = FirewallClient.onThisMachine();
// The allowances are this module's own state, announced as kept (ADR 0495), one bucket per machine whose keys carry
// the node, so this holder watches and lists its own node's keys only (H-A-317); every change is 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 asks the node-engine's converged and 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<AllowanceValue>(STATE);
const own = new Set<string>();
// The node's keys are known once the watch handed every current value over; a start that failed refuses every listing.
let watched!: { done: () => void; failed: (err: unknown) => void };
const watching = new Promise<void>((done, failed) => { watched = { done, failed }; });
watching.catch(() => {});
const store: Store = {
get: (key) => kept.get(key),
put: (key, value) => kept.put(key, value),
delete: (key) => kept.delete(key),
keys: async () => {
await watching;
return [...own];
},
};
const allowances = new Allowances(store, node, (body) => seatPublish(allowancesChangedSubject(node), body), {
converged: async () => (await broker().request<object, Convergence>(`seat:${nodeEngine}.${nodeEngineVerbs.converged}@${node}`, {})),
handAct: async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); },
most: async () => {
const v = await config("allowances-max");
if (v === undefined || v === null || v === "") return MOST;
const n = Number(v);
if (!Number.isInteger(n) || n < 1) throw new Error(`the setting allowances-max is ${JSON.stringify(v)}, not a whole number of allowances`);
return n;
},
meshTable: () => firewall.ruleset(),
});
const start = (async () => {
// A node-engine package older than the verb converged names none: refused here, loudly, never asked as
// seat:node-engine.undefined (H-A-312).
if (!nodeEngineVerbs.converged) {
throw new Error("the node-engine seat's package names no verb converged (a package older than design 33 control-verbs §10)");
}
await keeps([{ name: STATE }]);
await kept.watch(async (change) => {
if (change.op === "put") own.add(change.key);
else own.delete(change.key);
await allowances.watched(change);
}, { key: `${node}.**` });
watched.done();
await allowances.started();
})().catch((err) => {
const failed = new Error(`the allowances did not start: ${err}`);
watched.failed(failed);
console.error(`[nftables] the allowances did not start (no expiry timers, no started said): ${err}`);
throw failed;
});
start.catch(() => {});
// 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(packetFilter, () => getSeatVerbs(firewall, allowances, start));
registerModuleTools("nftables", () => getFirewallTools(firewall));