Files
mesh-catalog/modules/nftables/allowances.ts
T
jschoubben ee5e7f232f P1: the packet filter holder reads a port's scope from its derived rule's comment
A derived accept rule's one comment says derived <modules> <protocol>/<port>
scope <any|private-network|local-network>, its module list cut with a count
past 128 bytes; allow without a source is refused for a port whose derived
rules name no scope any, read from the comments, never from a rule's shape.

Builds: design 47 H2 §813 (4); H-A-357, H-A-384 (1), H-A-349 DQ-11
2026-11-22 00:55:14 +01:00

469 lines
22 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>]), kept one bucket per machine under its node's keys
// (<node>.allow.…, H-A-317), so a holder reads and writes its own node's only; 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";
import type { ConvergedAnswer } from "@novox/mesh-contracts-node-engine";
import {
allowancesByNodeAllowProtocolPortInterfaceKey, allowancesByNodeAllowProtocolPortKey,
parseAllowancesByNodeAllowProtocolPortInterfaceKey, parseAllowancesByNodeAllowProtocolPortKey, states,
type Allowance, type AllowanceValue, type AllowancesChanged, type Kept,
} from "@novox/mesh-connectivity-contracts-node-packet-filter";
// The seat's names, key forms and value forms are its generated package's (design 33 control-verbs §2, §7, §12): this
// module writes no copy of them.
export type { Allowance, AllowanceValue, AllowancesChanged, Kept };
/** The state the allowances are kept in, as the seat's definition names it (§7). */
export const STATE = states.allowances;
/** The most allowances one node keeps when the setting allowances-max says none (§3, H-A-314 (5)). */
export const MOST = 100;
/** How long the holder waits for the node-engine's converged (§10; a value, H-A-330). */
export const CONVERGED_BOUND_MS = 10_000;
/** The caller of a call the runtime named no caller for (the SDK's callers.UNPROVEN). */
export const UNPROVEN = "unproven";
type Protocol = AllowanceValue["protocol"];
/** The node's convergence state as the node-engine seat's converged answers it (§10, H-A-316, H-A-321, H-A-325). */
export type Convergence = ConvergedAnswer;
/** One act by hand, as the seat mesh-hand-acts' hand-act takes it (ADR 0565 §10): the SDK's views.HandAct. */
export interface HandAct {
what: string;
why: string;
cause: string;
verb: string;
}
/** What the holder asks beside its state: the node's convergence, the hand-act log and its setting allowances-max. */
export interface Asks {
converged: () => Promise<Convergence>;
handAct: (act: HandAct) => Promise<void>;
most: () => Promise<number>;
/** The mesh's table as loaded (`nft list table inet mesh`). */
meshTable: () => Promise<string>;
}
/** What the allowances need of the module's state: the SDK's `state()` serves it, keys from a watch of the node's own. */
export interface Store {
get(key: string): Promise<{ value: AllowanceValue } | null>;
put(key: string, value: AllowanceValue): 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?: AllowanceValue;
}
/** Says the event. */
export type Say = (body: AllowancesChanged) => 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);
};
/** The state's key of an allowance on node, in the seat's key forms (§7, H-A-317): <node>.allow.<protocol>.<port>, and
* .<interface> when it names one. */
function stateKeyOf(node: string, protocol: Protocol, port: number, iface?: string): string {
return iface
? allowancesByNodeAllowProtocolPortInterfaceKey(node, protocol, String(port), iface)
: allowancesByNodeAllowProtocolPortKey(node, protocol, String(port));
}
/** An allowance's key in every answer, the event and the rule's comment: its state's key without the node (§7). */
export function keyOf(protocol: Protocol, port: number, iface?: string): string {
return stateKeyOf("", protocol, port, iface).slice(1);
}
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);
// A full RFC 3339 time, seconds included: the node-engine reads it with Go's time.RFC3339, which refuses a time
// without them, and would withhold every later compose of the filter (§2).
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 with seconds, 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: AllowanceValue): 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;
private readonly asks: Asks;
/** The last answer of converged; undefined while none answered. */
private convergence: Convergence | undefined;
/** The expiries running now (track). */
private readonly expiring = new Set<Promise<boolean>>();
constructor(
store: Store,
node: string,
say: Say,
asks: Asks,
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.asks = asks;
this.now = now;
this.schedule = schedule;
this.journal = journal;
}
/** The state's key of an allowance's key: under this node's (H-A-317). */
private stored(key: string): string {
return `${this.node}.${key}`;
}
/** The allowance's key of a state's key of this node, or undefined for another node's or another form. */
private own(stateKey: string): string | undefined {
const parts = parseAllowancesByNodeAllowProtocolPortInterfaceKey(stateKey) ?? parseAllowancesByNodeAllowProtocolPortKey(stateKey);
return parts?.node === this.node ? stateKey.slice(this.node.length + 1) : undefined;
}
/** Ask converged, bound 10 s, keeping its answer; refused, naming why, when it does not answer (§10). */
private async askConverged(verb: string): Promise<Convergence> {
let stop: () => void = () => {};
const late = new Promise<never>((_, no) => {
stop = this.schedule(CONVERGED_BOUND_MS, () => no(new Error(`no answer within ${CONVERGED_BOUND_MS / 1000} s`)));
});
try {
const c = await Promise.race([this.asks.converged(), late]);
if (c?.state !== "adopted" && c?.state !== "converged") throw new Error(`it answered no convergence state (${JSON.stringify(c)})`);
this.convergence = c;
return c;
} catch (err) {
throw new Error(`${verb}: refused: the node-engine's converged did not answer (${err instanceof Error ? err.message : String(err)}), ` +
"and the holder never assumes the node converged; nothing is written");
} finally {
stop();
}
}
private refuseAdopted(verb: string, c: Convergence): void {
if (c.state !== "adopted") return;
const about = [c.found ? `the found firewall ${c.found}` : "", c.since ? `since ${c.since}` : ""].filter(Boolean).join(", ");
throw new Error(`${verb}: refused: this node is adopted${about ? ` (${about})` : ""}, and the mesh speaks the found firewall's terms: ` +
"no allowance is kept on an adopted node; nothing is written");
}
/** The caller as the runtime proved it; an unproven one is refused (§3, H-A-315 (3)). */
private proven(verb: string, by: string): void {
if (!by || by === UNPROVEN) throw new Error(`${verb}: refused: the request carries no caller the tool runner proved; nothing is written`);
}
/** Every allowance kept for this node, by its key, sorted. */
private async ownKeys(): Promise<string[]> {
return (await this.store.keys()).map((k) => this.own(k)).filter((k): k is string => k !== undefined).sort();
}
/** Said once each time the holder starts serving the seat, with every allowance (§8): converged asked first, every
* key past its until removed first (§11). */
async started(): Promise<void> {
try {
await this.askConverged("start");
} catch (err) {
this.journal(`${err instanceof Error ? err.message : String(err)}; allowed asks it again`);
}
// Every expiry the watch handed over ends before started is said (§11).
await Promise.all([...this.expiring]);
const allowances = await this.kept();
await this.say({ node: this.node, change: "started", allowances: this.convergence?.state === "adopted" ? [] : 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> {
const key = this.own(change.key);
if (key === undefined) return;
this.pending.get(key)?.();
this.pending.delete(key);
if (change.op !== "put" || !change.value?.until) return;
this.arm(key, change.value.until);
}
private arm(key: string, until: string): void {
const left = Date.parse(until) - this.now().getTime();
if (left <= 0) {
this.track(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 this.track(this.expire(key, until));
}));
}
/** An expiry the watch or a timer started, kept until it ends so a start waits for it (§11). */
private track(expiring: Promise<boolean>): void {
this.expiring.add(expiring);
expiring.finally(() => this.expiring.delete(expiring)).catch(() => {});
}
/** 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(this.stored(key));
if (!entry || entry.value.until !== until || Date.parse(until) > this.now().getTime()) return false;
await this.store.delete(this.stored(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: Kept[]; said: boolean }> {
this.proven("allow", by);
only(args, ["port", "protocol", "interfaces", "source", "until", "why"]);
const convergence = await this.askConverged("allow");
this.refuseAdopted("allow", convergence);
// The outward links as the node-engine classifies them for its render, from the converged answer of this call; the
// loaded table's shape is never read to tell one from the tunnel (§4, H-A-325).
const outward = new Set(convergence.outward);
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);
if (!source && privateOnly(await this.asks.meshTable(), protocol, port)) {
refuse("port", `${protocol} ${port} is admitted by a derived rule of the loaded mesh table from given sources only (its scope private-network or ` +
"local-network, such as the store's port or the broker's management port); an allowance from any source would widen it: give a source");
}
const most = await this.asks.most();
const kept = await this.ownKeys();
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 allowances-max ${most}`);
const at = now.toISOString();
const keys = interfaces.map((i) => keyOf(protocol, port, i));
await this.recorded({ what: `allowed ${keys.join(", ")} on ${this.node}${source ? ` from ${source}` : ""}${until ? ` until ${until}` : ""}`,
why: `${why} (${by})`, cause: "allowance-set", verb: "allow" });
const out: Kept[] = [];
for (const iface of interfaces) {
const key = keyOf(protocol, port, iface);
const value: AllowanceValue = {
port, protocol,
...(iface ? { interface: iface } : {}),
...(source ? { source } : {}),
...(until ? { until } : {}),
why, by, at,
};
const before = await this.store.get(this.stored(key));
await this.store.put(this.stored(key), value);
out.push({
...answered(key, value),
...(iface && outward.has(iface) ? { outward: iface } : {}),
...(before ? { replaced: answered(key, before.value) } : {}),
});
}
await this.say({ node: this.node, change: "allowed", allowances: out.map(({ replaced: _, outward: __, ...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 }> {
this.proven("disallow", by);
only(args, ["port", "protocol", "interfaces", "why"]);
this.refuseAdopted("disallow", await this.askConverged("disallow"));
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(this.stored(key));
if (!entry) throw new Error(`no allowance ${key} is kept on this node; nothing is deleted`);
found.push(answered(key, entry.value));
}
await this.recorded({ what: `disallowed ${found.map((a) => a.key).join(", ")} on ${this.node}`, why: `${why} (${by})`, cause: "allowance-taken-back", verb: "disallow" });
for (const a of found) await this.store.delete(this.stored(a.key));
await this.say({ node: this.node, change: "disallowed", allowances: found, by, why, at: this.now().toISOString() });
return { allowances: found, said: true };
}
/** Written in the hand-act log before the state is written; not written, the call is refused (§4, ADR 0565 §10). */
private async recorded(act: HandAct): Promise<void> {
try {
await this.asks.handAct(act);
} catch (err) {
throw new Error(`${act.verb}: the hand act was not recorded, so nothing is written: ${err instanceof Error ? err.message : String(err)}`);
}
}
/** Every allowance kept for this node only, sorted by key (§6); none on an adopted node, and refused while converged
* has never answered and does not answer now (H-A-318). 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 c = this.convergence ?? (await this.askConverged("allowed"));
if (c.state === "adopted") return { allowances: [] };
return { allowances: await this.kept() };
}
/** This node's allowances, every one past its until removed first (§11). */
private async kept(): Promise<Allowance[]> {
const now = this.now().getTime();
const allowances: Allowance[] = [];
for (const key of await this.ownKeys()) {
const entry = await this.store.get(this.stored(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;
}
}
/** A seat verb held until the holder's start ends (§8, §11): the watch has handed every key over, every expiry it
* started has ended and started is said, so no verb answers before started; a start that failed refuses it with
* the start's error. */
export function held<A extends unknown[], R>(start: Promise<unknown>, run: (...args: A) => Promise<R>): (...args: A) => Promise<R> {
return async (...args) => {
await start;
return run(...args);
};
}
/** Each allowance marked loaded only when a rule of the mesh's table carries its comment `allowance <key> <at>` with
* an equal at, and every such comment whose key is not kept: loaded, not kept (§7, H-A-315 (5)). */
export function markLoaded(allowances: Allowance[], meshTable: string): {
allowances: (Allowance & { loaded: boolean })[];
loadedNotKept: { key: string; at: string }[];
} {
const comments = [...meshTable.matchAll(/comment "allowance (\S+) (\S+)"/g)].map((m) => ({ key: m[1], at: m[2] }));
const kept = new Set(allowances.map((a) => a.key));
const seen = new Set<string>();
const loadedNotKept = comments.filter((c) => !kept.has(c.key) && !seen.has(c.key) && seen.add(c.key));
return {
allowances: allowances.map((a) => ({ ...a, loaded: comments.some((c) => c.key === a.key && c.at === a.at) })),
loadedNotKept,
};
}
/** The scopes the node-engine's render writes on a derived accept rule (design 47 H2 §813 (4), H-A-357). */
export type Scope = "any" | "private-network" | "local-network";
/**
* The scopes the loaded mesh table's derived accept rules give `protocol` `port`, read from each rule's one comment
* `derived <modules joined by ,> <protocol>/<port> scope <any|private-network|local-network>` (design 47 H2 §813 (4),
* H-A-357), the module list cut with a count past 128 bytes (`derived a,b,+4 tcp/443 scope any`, H-A-384 (1)); never
* from the rule's shape. A port is one port or a range `lo-hi`.
*/
export function portScopes(meshTable: string, protocol: Protocol, port: number): Scope[] {
const out: Scope[] = [];
for (const m of meshTable.matchAll(/comment "derived \S+ (tcp|udp)\/(\d+)(?:-(\d+))? scope (any|private-network|local-network)"/g)) {
const lo = Number(m[2]), hi = m[3] === undefined ? lo : Number(m[3]);
if (m[1] === protocol && lo <= port && port <= hi) out.push(m[4] as Scope);
}
return out;
}
/** Whether a derived rule admits `protocol` `port` from given sources only (the private network or the local network)
* and none from any source: its scope read from the rules' comments (§813 (4), H-A-315 (7), H-A-319). */
export function privateOnly(meshTable: string, protocol: Protocol, port: number): boolean {
const scopes = portScopes(meshTable, protocol, port);
return scopes.length > 0 && !scopes.includes("any");
}