Files
MikrotikManager/backend/src/services/bandwidth-admission-schema.ts
T

209 lines
16 KiB
TypeScript

/** Fixed externally provisioned namespace; never derived from caller input. */
export const BANDWIDTH_ADMISSION_CONTROL_NAMESPACE = "mmapp_control" as const
/** Fresh, opt-in control proposal only. Not a normal migration or readiness claim.
* The mmapp_control namespace MUST already be provisioned independently. This
* DDL does not create that namespace, migrate public tables or copy old data.
* SQL enforces structure, immutable ownership and transition chains. It cannot
* authenticate HMACs, native completion or private no-send ownership: the trusted
* adapter must independently verify those before SQL. GUCs grant no privilege.
* No SECURITY DEFINER, trigger-disable mechanism, TTL reclaim or cascade exists. */
export const BANDWIDTH_ADMISSION_PROPOSAL_DDL = `
CREATE FUNCTION mmapp_control.bandwidth_admission_binding_valid(
b jsonb, attempt uuid, caller text, operation text, source text, destination text,
proof text, generation text
) RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, mmapp_control AS $body$
DECLARE field text; node jsonb;
BEGIN
IF jsonb_typeof(b) IS DISTINCT FROM 'object'
OR NOT b ?& ARRAY['attemptId','callerKind','operationId','source','destination','authorityProof','authorityGeneration','controlGeneration','expiresAt','durationSec','requestProof','commandProof','bindingProof']
OR b - ARRAY['attemptId','callerKind','operationId','source','destination','authorityProof','authorityGeneration','controlGeneration','expiresAt','durationSec','requestProof','commandProof','bindingProof'] <> '{}'::jsonb THEN RETURN false; END IF;
FOREACH field IN ARRAY ARRAY['attemptId','callerKind','operationId','authorityProof','authorityGeneration','controlGeneration','requestProof','commandProof','bindingProof'] LOOP
IF jsonb_typeof(b->field) IS DISTINCT FROM 'string' THEN RETURN false; END IF;
END LOOP;
FOREACH field IN ARRAY ARRAY['authorityProof','requestProof','commandProof','bindingProof'] LOOP
IF (b->>field) !~ '^[a-f0-9]{64}$' THEN RETURN false; END IF;
END LOOP;
FOREACH field IN ARRAY ARRAY['operationId','authorityGeneration','controlGeneration'] LOOP
IF (b->>field) !~ '^[a-zA-Z0-9_.:-]{1,200}$' THEN RETURN false; END IF;
END LOOP;
FOREACH field IN ARRAY ARRAY['source','destination'] LOOP
node := b->field;
IF jsonb_typeof(node) IS DISTINCT FROM 'object'
OR NOT node ?& ARRAY['canonicalNodeId','endpointProof']
OR node - ARRAY['canonicalNodeId','endpointProof'] <> '{}'::jsonb
OR jsonb_typeof(node->'canonicalNodeId') IS DISTINCT FROM 'string'
OR jsonb_typeof(node->'endpointProof') IS DISTINCT FROM 'string'
OR (node->>'canonicalNodeId') !~ '^[a-zA-Z0-9_.:-]{1,200}$'
OR (node->>'endpointProof') !~ '^[a-f0-9]{64}$' THEN RETURN false; END IF;
END LOOP;
IF (b->>'attemptId') !~* '^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$'
OR jsonb_typeof(b->'expiresAt') IS DISTINCT FROM 'number'
OR jsonb_typeof(b->'durationSec') IS DISTINCT FROM 'number' THEN RETURN false; END IF;
RETURN COALESCE((b->>'attemptId')::uuid = attempt
AND (b->>'callerKind') COLLATE "C" = caller COLLATE "C"
AND (b->>'operationId') COLLATE "C" = operation COLLATE "C"
AND (b->'source'->>'canonicalNodeId') COLLATE "C" = source COLLATE "C"
AND (b->'destination'->>'canonicalNodeId') COLLATE "C" = destination COLLATE "C"
AND source COLLATE "C" <> destination COLLATE "C"
AND b->>'bindingProof' = proof AND (b->>'controlGeneration') COLLATE "C" = generation COLLATE "C"
AND (b->>'expiresAt')::numeric BETWEEN 1 AND 9007199254740991
AND trunc((b->>'expiresAt')::numeric) = (b->>'expiresAt')::numeric
AND (b->>'durationSec')::numeric BETWEEN 3 AND 2147483647
AND trunc((b->>'durationSec')::numeric) = (b->>'durationSec')::numeric, false);
END;
$body$;
CREATE TABLE mmapp_control.bandwidth_attempts (
attempt_id uuid PRIMARY KEY,
caller_kind text COLLATE "C" NOT NULL CHECK (caller_kind IN ('rest-speed','scheduled-speed','mcp-speed','routing-measurement','rest-diagnostic','mcp-diagnostic','legacy-diagnostic','speed-inner')),
operation_id text COLLATE "C" NOT NULL CHECK (operation_id ~ '^[a-zA-Z0-9_.:-]{1,200}$'),
binding jsonb NOT NULL CHECK (octet_length(binding::text) <= 16384),
source_node text COLLATE "C" NOT NULL,
destination_node text COLLATE "C" NOT NULL,
binding_proof text COLLATE "C" NOT NULL CHECK (binding_proof ~ '^[a-f0-9]{64}$'),
control_generation text COLLATE "C" NOT NULL CHECK (control_generation ~ '^[a-zA-Z0-9_.:-]{1,200}$'),
state text COLLATE "C" NOT NULL CHECK (state IN ('reserved','armed','unknown_busy','released')),
resolution text COLLATE "C" CHECK (resolution IN ('remote_completion','proven_not_dispatched')),
terminal_proof text COLLATE "C" CHECK (terminal_proof ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE (caller_kind, operation_id),
CHECK (mmapp_control.bandwidth_admission_binding_valid(binding,attempt_id,caller_kind,operation_id,source_node,destination_node,binding_proof,control_generation)),
CHECK (COALESCE((state <> 'released' AND resolution IS NULL AND terminal_proof IS NULL)
OR (state = 'released' AND resolution = 'proven_not_dispatched' AND terminal_proof IS NULL)
OR (state = 'released' AND resolution = 'remote_completion' AND terminal_proof IS NOT NULL), false))
);
CREATE TABLE mmapp_control.bandwidth_node_occupancy (
node_id text COLLATE "C" PRIMARY KEY,
attempt_id uuid NOT NULL REFERENCES mmapp_control.bandwidth_attempts(attempt_id) ON DELETE RESTRICT ON UPDATE RESTRICT,
binding_proof text COLLATE "C" NOT NULL CHECK (binding_proof ~ '^[a-f0-9]{64}$'),
control_generation text COLLATE "C" NOT NULL CHECK (control_generation ~ '^[a-zA-Z0-9_.:-]{1,200}$')
);
CREATE INDEX bandwidth_node_occupancy_attempt_idx ON mmapp_control.bandwidth_node_occupancy(attempt_id);
CREATE TABLE mmapp_control.bandwidth_attempt_events (
ack_id uuid PRIMARY KEY,
attempt_id uuid NOT NULL REFERENCES mmapp_control.bandwidth_attempts(attempt_id) ON DELETE RESTRICT ON UPDATE RESTRICT,
transition text COLLATE "C" NOT NULL CHECK (transition IN ('reserve','arm','complete','release-before-dispatch','quarantine')),
old_state text COLLATE "C" CHECK (old_state IN ('reserved','armed')),
new_state text COLLATE "C" NOT NULL CHECK (new_state IN ('reserved','armed','unknown_busy','released')),
binding_proof text COLLATE "C" NOT NULL CHECK (binding_proof ~ '^[a-f0-9]{64}$'),
control_generation text COLLATE "C" NOT NULL CHECK (control_generation ~ '^[a-zA-Z0-9_.:-]{1,200}$'),
evidence_proof text COLLATE "C" NOT NULL CHECK (evidence_proof ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE (attempt_id, transition),
CHECK (COALESCE((transition = 'reserve' AND old_state IS NULL AND new_state = 'reserved')
OR (transition = 'arm' AND old_state = 'reserved' AND new_state = 'armed')
OR (transition = 'complete' AND old_state = 'armed' AND new_state = 'released')
OR (transition = 'release-before-dispatch' AND old_state IN ('reserved','armed') AND new_state = 'released')
OR (transition = 'quarantine' AND old_state IN ('reserved','armed') AND new_state = 'unknown_busy'), false))
);
CREATE FUNCTION mmapp_control.bandwidth_admission_attempt_guard() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, mmapp_control AS $body$
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'bandwidth attempts cannot be deleted' USING ERRCODE='23514'; END IF;
IF TG_OP = 'INSERT' THEN
IF NEW.state <> 'reserved' OR NEW.resolution IS NOT NULL OR NEW.terminal_proof IS NOT NULL THEN RAISE EXCEPTION 'bandwidth attempt must start reserved' USING ERRCODE='23514'; END IF;
RETURN NEW;
END IF;
IF ROW(NEW.attempt_id,NEW.caller_kind,NEW.operation_id,NEW.binding,NEW.source_node,NEW.destination_node,NEW.binding_proof,NEW.control_generation,NEW.created_at)
IS DISTINCT FROM ROW(OLD.attempt_id,OLD.caller_kind,OLD.operation_id,OLD.binding,OLD.source_node,OLD.destination_node,OLD.binding_proof,OLD.control_generation,OLD.created_at) THEN
RAISE EXCEPTION 'bandwidth binding is immutable' USING ERRCODE='23514';
END IF;
IF NOT ((OLD.state = 'reserved' AND NEW.state IN ('armed','unknown_busy','released')) OR (OLD.state = 'armed' AND NEW.state IN ('unknown_busy','released')))
OR (NEW.resolution = 'remote_completion' AND OLD.state <> 'armed') THEN
RAISE EXCEPTION 'invalid bandwidth attempt transition' USING ERRCODE='23514';
END IF;
RETURN NEW;
END;
$body$;
CREATE TRIGGER bandwidth_attempt_guard BEFORE INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_attempts FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_attempt_guard();
CREATE FUNCTION mmapp_control.bandwidth_admission_occupancy_guard() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, mmapp_control AS $body$
DECLARE owner mmapp_control.bandwidth_attempts%ROWTYPE; target mmapp_control.bandwidth_node_occupancy%ROWTYPE;
BEGIN
IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'bandwidth occupancy cannot be updated' USING ERRCODE='23514'; END IF;
IF TG_OP = 'DELETE' THEN target := OLD; ELSE target := NEW; END IF;
SELECT * INTO owner FROM mmapp_control.bandwidth_attempts WHERE attempt_id = target.attempt_id FOR UPDATE;
IF NOT FOUND OR owner.binding_proof <> target.binding_proof OR owner.control_generation <> target.control_generation
OR target.node_id NOT IN (owner.source_node,owner.destination_node)
OR (TG_OP = 'INSERT' AND owner.state <> 'reserved') OR (TG_OP = 'DELETE' AND owner.state <> 'released') THEN
RAISE EXCEPTION 'bandwidth occupancy owner or state mismatch' USING ERRCODE='23514';
END IF;
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END;
$body$;
CREATE TRIGGER bandwidth_occupancy_guard BEFORE INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_node_occupancy FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_occupancy_guard();
CREATE FUNCTION mmapp_control.bandwidth_admission_event_guard() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, mmapp_control AS $body$
DECLARE owner mmapp_control.bandwidth_attempts%ROWTYPE;
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'bandwidth events are append only' USING ERRCODE='23514'; END IF;
SELECT * INTO owner FROM mmapp_control.bandwidth_attempts WHERE attempt_id = NEW.attempt_id FOR UPDATE;
IF NOT FOUND OR owner.binding_proof <> NEW.binding_proof OR owner.control_generation <> NEW.control_generation OR owner.state <> NEW.new_state THEN
RAISE EXCEPTION 'bandwidth event owner or state mismatch' USING ERRCODE='23514';
END IF;
RETURN NEW;
END;
$body$;
CREATE TRIGGER bandwidth_event_guard BEFORE INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_attempt_events FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_event_guard();
CREATE FUNCTION mmapp_control.bandwidth_admission_reject_truncate() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, mmapp_control AS $body$
BEGIN RAISE EXCEPTION 'bandwidth journal cannot be truncated' USING ERRCODE='23514'; END;
$body$;
CREATE TRIGGER bandwidth_attempts_no_truncate BEFORE TRUNCATE ON mmapp_control.bandwidth_attempts FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.bandwidth_admission_reject_truncate();
CREATE TRIGGER bandwidth_occupancy_no_truncate BEFORE TRUNCATE ON mmapp_control.bandwidth_node_occupancy FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.bandwidth_admission_reject_truncate();
CREATE TRIGGER bandwidth_events_no_truncate BEFORE TRUNCATE ON mmapp_control.bandwidth_attempt_events FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.bandwidth_admission_reject_truncate();
CREATE FUNCTION mmapp_control.bandwidth_admission_consistency_guard() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, mmapp_control AS $body$
DECLARE target_id uuid; owner mmapp_control.bandwidth_attempts%ROWTYPE; occupied bigint; reserves bigint; arms bigint; terminals bigint; total bigint; terminal mmapp_control.bandwidth_attempt_events%ROWTYPE;
BEGIN
IF TG_OP = 'DELETE' THEN target_id := OLD.attempt_id; ELSE target_id := NEW.attempt_id; END IF;
SELECT * INTO owner FROM mmapp_control.bandwidth_attempts WHERE attempt_id = target_id FOR UPDATE;
IF NOT FOUND THEN RAISE EXCEPTION 'bandwidth attempt missing' USING ERRCODE='23514'; END IF;
SELECT count(*) INTO occupied FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id = target_id;
IF (owner.state = 'released' AND occupied <> 0) OR (owner.state <> 'released' AND occupied <> 2)
OR EXISTS (SELECT 1 FROM mmapp_control.bandwidth_node_occupancy WHERE attempt_id = target_id
AND (binding_proof <> owner.binding_proof OR control_generation <> owner.control_generation OR node_id NOT IN (owner.source_node,owner.destination_node))) THEN
RAISE EXCEPTION 'bandwidth occupancy pair is incomplete' USING ERRCODE='23514';
END IF;
SELECT count(*),count(*) FILTER (WHERE transition='reserve'),count(*) FILTER (WHERE transition='arm'),count(*) FILTER (WHERE transition IN ('complete','release-before-dispatch','quarantine'))
INTO total,reserves,arms,terminals FROM mmapp_control.bandwidth_attempt_events WHERE attempt_id=target_id;
IF reserves <> 1 OR arms > 1 OR terminals > 1 OR total <> reserves+arms+terminals
OR EXISTS (SELECT 1 FROM mmapp_control.bandwidth_attempt_events WHERE attempt_id=target_id AND (binding_proof <> owner.binding_proof OR control_generation <> owner.control_generation)) THEN
RAISE EXCEPTION 'bandwidth event chain is incomplete' USING ERRCODE='23514';
END IF;
IF owner.state = 'reserved' THEN
IF total <> 1 THEN RAISE EXCEPTION 'reserved bandwidth event mismatch' USING ERRCODE='23514'; END IF;
ELSIF owner.state = 'armed' THEN
IF arms <> 1 OR terminals <> 0 OR total <> 2 THEN RAISE EXCEPTION 'armed bandwidth event mismatch' USING ERRCODE='23514'; END IF;
ELSE
SELECT * INTO terminal FROM mmapp_control.bandwidth_attempt_events WHERE attempt_id=target_id AND transition IN ('complete','release-before-dispatch','quarantine');
IF terminals <> 1 OR terminal.old_state IS DISTINCT FROM (CASE WHEN arms=1 THEN 'armed' ELSE 'reserved' END)
OR terminal.new_state <> owner.state
OR (owner.state='unknown_busy' AND terminal.transition <> 'quarantine')
OR (owner.state='released' AND owner.resolution='remote_completion' AND (terminal.transition <> 'complete' OR arms <> 1))
OR (owner.state='released' AND owner.resolution='proven_not_dispatched' AND terminal.transition <> 'release-before-dispatch') THEN
RAISE EXCEPTION 'terminal bandwidth event mismatch' USING ERRCODE='23514';
END IF;
END IF;
RETURN NULL;
END;
$body$;
CREATE CONSTRAINT TRIGGER bandwidth_attempt_consistency AFTER INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_attempts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_consistency_guard();
CREATE CONSTRAINT TRIGGER bandwidth_occupancy_consistency AFTER INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_node_occupancy DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_consistency_guard();
CREATE CONSTRAINT TRIGGER bandwidth_event_consistency AFTER INSERT OR UPDATE OR DELETE ON mmapp_control.bandwidth_attempt_events DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION mmapp_control.bandwidth_admission_consistency_guard();
-- Structural guards also run under replication apply. Table owners/superusers
-- still control DDL; this is not role isolation or HMAC verification.
ALTER TABLE mmapp_control.bandwidth_attempts ENABLE ALWAYS TRIGGER bandwidth_attempt_guard;
ALTER TABLE mmapp_control.bandwidth_node_occupancy ENABLE ALWAYS TRIGGER bandwidth_occupancy_guard;
ALTER TABLE mmapp_control.bandwidth_attempt_events ENABLE ALWAYS TRIGGER bandwidth_event_guard;
ALTER TABLE mmapp_control.bandwidth_attempts ENABLE ALWAYS TRIGGER bandwidth_attempts_no_truncate;
ALTER TABLE mmapp_control.bandwidth_node_occupancy ENABLE ALWAYS TRIGGER bandwidth_occupancy_no_truncate;
ALTER TABLE mmapp_control.bandwidth_attempt_events ENABLE ALWAYS TRIGGER bandwidth_events_no_truncate;
ALTER TABLE mmapp_control.bandwidth_attempts ENABLE ALWAYS TRIGGER bandwidth_attempt_consistency;
ALTER TABLE mmapp_control.bandwidth_node_occupancy ENABLE ALWAYS TRIGGER bandwidth_occupancy_consistency;
ALTER TABLE mmapp_control.bandwidth_attempt_events ENABLE ALWAYS TRIGGER bandwidth_event_consistency;
`