103 lines
10 KiB
TypeScript
103 lines
10 KiB
TypeScript
/** Fixed invoker-only SQL shapes for the existing registry transaction. No
|
|
* DDL/key/bootstrap changes, dynamic SQL or occupancy access. */
|
|
import { z } from "zod"
|
|
|
|
const hash=z.string().regex(/^[a-f0-9]{64}$/),uuid=z.string().uuid().regex(/^[a-f0-9-]+$/)
|
|
const status=z.enum(["active","tombstoned","quarantined"])
|
|
const aliasSchema=z.object({subject:z.string().min(1).max(64),incarnation:uuid,node_id:uuid,status,record_mac:hash}).strict()
|
|
const nodeSchema=z.object({node_id:uuid,claim_proof:hash,enrollment_mac:hash}).strict()
|
|
const eventSchema=z.object({event_id:uuid,incarnation:uuid,node_id:uuid,kind:z.enum(["enroll","tombstone","quarantine"]),old_status:z.literal("active").nullable(),new_status:status,authority_proof:hash,event_mac:hash}).strict()
|
|
const snapshotSchema=z.object({aliases:z.array(aliasSchema).max(1),nodes:z.array(nodeSchema).max(1),events:z.array(eventSchema).max(2),claim_nodes:z.array(nodeSchema).max(1)}).strict()
|
|
export type BandwidthRegistryKind="managed"|"external"
|
|
export type BandwidthRegistrySnapshot=Readonly<z.infer<typeof snapshotSchema>>
|
|
export class BandwidthRegistryBatchRefused extends Error{constructor(){super("Bandwidth registry batch refused")}}
|
|
function fail():never{throw new BandwidthRegistryBatchRefused()}
|
|
function freeze<T>(value:T):T{if(value&&typeof value==="object"){Object.values(value).forEach(freeze);Object.freeze(value)}return value}
|
|
function subject(kind:BandwidthRegistryKind,value:unknown):string{
|
|
if(kind==="managed"){if(!Number.isSafeInteger(value)||Number(value)<1)fail();return String(value)}
|
|
if(kind!=="external"||!uuid.safeParse(value).success)fail();return value as string
|
|
}
|
|
const query=(kind:BandwidthRegistryKind,lock:boolean)=>{
|
|
const external=kind==="external",id=external?"enrollment_id":"server_id",aliases=external?"bandwidth_external_node_aliases":"bandwidth_node_aliases",events=external?"bandwidth_external_node_events":"bandwidth_node_events",cast=external?"uuid":"int8"
|
|
return `WITH aliases AS MATERIALIZED (
|
|
SELECT ${id}::pg_catalog.text AS subject,incarnation::pg_catalog.text,node_id::pg_catalog.text,status,record_mac
|
|
FROM mmapp_control.${aliases} WHERE ${id}=$1::pg_catalog.${cast} LIMIT 2${lock?" FOR UPDATE":""}
|
|
), nodes AS MATERIALIZED (
|
|
SELECT n.node_id::pg_catalog.text,n.claim_proof,n.enrollment_mac
|
|
FROM mmapp_control.bandwidth_nodes n JOIN aliases a ON n.node_id=a.node_id::pg_catalog.uuid
|
|
), events AS MATERIALIZED (
|
|
SELECT event_id::pg_catalog.text,incarnation::pg_catalog.text,node_id::pg_catalog.text,kind,old_status,new_status,authority_proof,event_mac
|
|
FROM mmapp_control.${events} WHERE ${id}=$1::pg_catalog.${cast} ORDER BY kind LIMIT 3
|
|
), claim_nodes AS MATERIALIZED (
|
|
SELECT node_id::pg_catalog.text,claim_proof,enrollment_mac FROM mmapp_control.bandwidth_nodes
|
|
WHERE $2::pg_catalog.text IS NOT NULL AND claim_proof=$2::pg_catalog.text LIMIT 2
|
|
)
|
|
SELECT COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(a)) FROM aliases a),'[]'::pg_catalog.jsonb) AS aliases,
|
|
COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(n)) FROM nodes n),'[]'::pg_catalog.jsonb) AS nodes,
|
|
COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(e)) FROM events e),'[]'::pg_catalog.jsonb) AS events,
|
|
COALESCE((SELECT pg_catalog.jsonb_agg(pg_catalog.to_jsonb(c)) FROM claim_nodes c),'[]'::pg_catalog.jsonb) AS claim_nodes`
|
|
}
|
|
const managed=query("managed",false),managedLock=query("managed",true),external=query("external",false),externalLock=query("external",true)
|
|
export function bandwidthRegistrySnapshotSql(kind:BandwidthRegistryKind,lock:boolean):string{
|
|
if(typeof lock!=="boolean"||kind!=="managed"&&kind!=="external")fail()
|
|
return kind==="managed"?lock?managedLock:managed:lock?externalLock:external
|
|
}
|
|
/** Pure snapshot shape/link validation. Cryptographic comparisons below use
|
|
* the same original claim/node/alias/event MAC domains as v1. */
|
|
export function parseBandwidthRegistrySnapshot(rows:unknown,kind:BandwidthRegistryKind,id:number|string,claimProof:string|null):BandwidthRegistrySnapshot{
|
|
const wanted=subject(kind,id);if(claimProof!==null&&!hash.safeParse(claimProof).success)fail()
|
|
if(!Array.isArray(rows)||rows.length!==1)fail()
|
|
let value:z.infer<typeof snapshotSchema>;try{value=snapshotSchema.parse(rows[0])}catch{return fail()}
|
|
const alias=value.aliases[0],node=value.nodes[0],candidate=value.claim_nodes[0]
|
|
if(!alias){if(node||value.events.length)fail()}
|
|
else{
|
|
if(alias.subject!==wanted||!node||node.node_id!==alias.node_id)fail()
|
|
const terminal=alias.status!=="active",kinds=value.events.map(event=>event.kind).sort().join(",")
|
|
if(value.events.length!==(terminal?2:1)||kinds!==(terminal?alias.status==="tombstoned"?"enroll,tombstone":"enroll,quarantine":"enroll"))fail()
|
|
for(const event of value.events)if(event.incarnation!==alias.incarnation||event.node_id!==alias.node_id||event.old_status!==(event.kind==="enroll"?null:"active")||event.new_status!==(event.kind==="enroll"?"active":alias.status))fail()
|
|
}
|
|
if(candidate&&(claimProof===null||candidate.claim_proof!==claimProof))fail()
|
|
if(claimProof!==null&&node?.claim_proof===claimProof&&(!candidate||candidate.node_id!==node.node_id||candidate.enrollment_mac!==node.enrollment_mac))fail()
|
|
return freeze(value)
|
|
}
|
|
const rootSchema=z.object({installationId:uuid,issuerKeySha256:hash,quiescenceProof:hash}).strict()
|
|
export function bandwidthRegistrySnapshotProofs(kind:BandwidthRegistryKind,snapshot:BandwidthRegistrySnapshot,authority:z.infer<typeof rootSchema>){
|
|
const root=rootSchema.parse(authority),alias=snapshot.aliases[0],node=snapshot.nodes[0];if(!alias||!node)fail()
|
|
const id=kind==="managed"?{serverId:Number(alias.subject)}:{enrollmentId:alias.subject}
|
|
subject(kind,kind==="managed"?Number(alias.subject):alias.subject)
|
|
return freeze([{purpose:kind==="managed"?"alias":"external-alias",value:{...root,...id,incarnation:alias.incarnation,nodeId:alias.node_id,status:alias.status},expected:alias.record_mac},
|
|
{purpose:"node",value:{...root,nodeId:node.node_id,claimProof:node.claim_proof},expected:node.enrollment_mac},
|
|
...snapshot.events.map(event=>({purpose:kind==="managed"?"event":"external-event",value:{...root,eventId:event.event_id,...id,incarnation:event.incarnation,nodeId:event.node_id,kind:event.kind,oldStatus:event.old_status,newStatus:event.new_status,authorityProof:event.authority_proof},expected:event.event_mac}))])
|
|
}
|
|
const batchSchema=z.object({kind:z.enum(["managed","external"]),subject:z.union([z.number().int().positive().safe(),uuid]),insertNode:z.boolean(),nodeId:uuid,claimProof:hash,nodeMac:hash,incarnation:uuid,aliasMac:hash,eventId:uuid,authorityProof:hash,eventMac:hash}).strict()
|
|
export type BandwidthRegistryEnrollmentBatch=z.infer<typeof batchSchema>
|
|
/** Only safeinteger, UUID, hash64 and boolean values enter fixed SQL literals.
|
|
* No native claims, names, endpoints, SQL callbacks, identifiers or model text. */
|
|
export function bandwidthRegistryEnrollmentSql(raw:BandwidthRegistryEnrollmentBatch):string{
|
|
if(!raw||typeof raw!=="object"||Object.getPrototypeOf(raw)!==Object.prototype||Reflect.ownKeys(raw).length!==Object.keys(raw).length||Object.values(Object.getOwnPropertyDescriptors(raw)).some(field=>!("value"in field)||!field.enumerable))fail()
|
|
let p:BandwidthRegistryEnrollmentBatch;try{p=batchSchema.parse(raw)}catch{return fail()}
|
|
const id=subject(p.kind,p.subject),external=p.kind==="external",idColumn=external?"enrollment_id":"server_id",idType=external?"uuid":"int8",aliases=external?"bandwidth_external_node_aliases":"bandwidth_node_aliases",events=external?"bandwidth_external_node_events":"bandwidth_node_events"
|
|
const literal=(v:string,t:"uuid"|"text")=>`'${v}'::pg_catalog.${t}`,node=literal(p.nodeId,"uuid"),incarnation=literal(p.incarnation,"uuid"),event=literal(p.eventId,"uuid"),claim=literal(p.claimProof,"text"),nodeMac=literal(p.nodeMac,"text"),aliasMac=literal(p.aliasMac,"text"),authority=literal(p.authorityProof,"text"),eventMac=literal(p.eventMac,"text"),subjectLiteral=external?literal(id,"uuid"):`${id}::pg_catalog.int8`
|
|
return `DO $mmapp_bandwidth_register$
|
|
DECLARE got_node pg_catalog.uuid; got_claim pg_catalog.text; got_node_mac pg_catalog.text;
|
|
got_subject pg_catalog.${idType}; got_incarnation pg_catalog.uuid; got_alias_node pg_catalog.uuid; got_alias_mac pg_catalog.text;
|
|
got_event pg_catalog.uuid; got_event_subject pg_catalog.${idType}; got_event_incarnation pg_catalog.uuid; got_event_node pg_catalog.uuid; got_authority pg_catalog.text; got_event_mac pg_catalog.text;
|
|
BEGIN
|
|
IF ${p.insertNode?"true":"false"} THEN
|
|
INSERT INTO mmapp_control.bandwidth_nodes(node_id,claim_proof,enrollment_mac) VALUES(${node},${claim},${nodeMac})
|
|
RETURNING node_id,claim_proof,enrollment_mac INTO STRICT got_node,got_claim,got_node_mac;
|
|
IF got_node IS DISTINCT FROM ${node} OR got_claim IS DISTINCT FROM ${claim} OR got_node_mac IS DISTINCT FROM ${nodeMac} THEN RAISE EXCEPTION 'bandwidth registry node mismatch' USING ERRCODE='23514'; END IF;
|
|
ELSE
|
|
SELECT node_id,claim_proof,enrollment_mac INTO STRICT got_node,got_claim,got_node_mac FROM mmapp_control.bandwidth_nodes WHERE claim_proof=${claim};
|
|
IF got_node IS DISTINCT FROM ${node} OR got_claim IS DISTINCT FROM ${claim} OR got_node_mac IS DISTINCT FROM ${nodeMac} THEN RAISE EXCEPTION 'bandwidth registry existing node mismatch' USING ERRCODE='23514'; END IF;
|
|
END IF;
|
|
INSERT INTO mmapp_control.${aliases}(${idColumn},incarnation,node_id,status,record_mac) VALUES(${subjectLiteral},${incarnation},${node},'active',${aliasMac})
|
|
RETURNING ${idColumn},incarnation,node_id,record_mac INTO STRICT got_subject,got_incarnation,got_alias_node,got_alias_mac;
|
|
IF got_subject IS DISTINCT FROM ${subjectLiteral} OR got_incarnation IS DISTINCT FROM ${incarnation} OR got_alias_node IS DISTINCT FROM ${node} OR got_alias_mac IS DISTINCT FROM ${aliasMac} THEN RAISE EXCEPTION 'bandwidth registry alias mismatch' USING ERRCODE='23514'; END IF;
|
|
INSERT INTO mmapp_control.${events}(event_id,${idColumn},incarnation,node_id,kind,old_status,new_status,authority_proof,event_mac) VALUES(${event},${subjectLiteral},${incarnation},${node},'enroll',NULL,'active',${authority},${eventMac})
|
|
RETURNING event_id,${idColumn},incarnation,node_id,authority_proof,event_mac INTO STRICT got_event,got_event_subject,got_event_incarnation,got_event_node,got_authority,got_event_mac;
|
|
IF got_event IS DISTINCT FROM ${event} OR got_event_subject IS DISTINCT FROM ${subjectLiteral} OR got_event_incarnation IS DISTINCT FROM ${incarnation} OR got_event_node IS DISTINCT FROM ${node} OR got_authority IS DISTINCT FROM ${authority} OR got_event_mac IS DISTINCT FROM ${eventMac} THEN RAISE EXCEPTION 'bandwidth registry event mismatch' USING ERRCODE='23514'; END IF;
|
|
END
|
|
$mmapp_bandwidth_register$;`
|
|
}
|