Files
mesh-catalog/modules/nftables/allowances.ts
T
jschoubben 7bd1e74086 nftables: serve allow, disallow and allowed, keeping allowances as its own state
The operator, 2026-11-21 20:35: a firewall module has tools to control the
firewall beside the provisioning from declarations. The holder keeps one
allowance per protocol, port and interface in its state allowances, says every
change as allowances-changed, removes an allowance at its until by a timer on
its own state (and every expired one at its start, before started), and rules
marks each allowance loaded by its comment in the mesh's table. It writes no
rule: the node-engine renders the allowances.

Builds: ADR 0683; design 33 control-verbs §1-§7, §9; design 47 H H-A-304..310, H-A-312 (2)
2026-11-21 20:40:35 +01:00

307 lines
12 KiB
TypeScript

// 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.<protocol>.<port>[.<interface>]); 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.<node> (§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<number>;
delete(key: string): Promise<void>;
keys(): Promise<string[]>;
}
/** 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<void>;
/** 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.<protocol>.<port>, and .<interface> 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<string, unknown>, 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<string, () => 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<void> {
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<void> {
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<boolean> {
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<string, unknown>, 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<string, unknown>, 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<string, unknown> = {}): 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 <key>` (§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) }));
}