Files
MikrotikManager/backend/scripts/writer-profile/registry-enrollment.mts
T

186 lines
13 KiB
TypeScript

import assert from 'node:assert/strict'
import type {PoolClient} from 'pg'
import {deploymentRequest} from '../database-writer-bootstrap-operator.mjs'
import {assertJsDriverEnvironment,poolOptions,retainPublisherTlsPeer} from './operator-contract.mjs'
import {readProtected} from './operator-files.mjs'
import {KEY,canonical,publicKey,sha} from '../../src/db/application-writer-profile-format.js'
import {readCurrentApplicationWriterProfile} from '../../src/db/application-writer-profile-registry-read.js'
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
import {readProtectedRegistryStructureData,type RegistryRoleBindingsData} from '../../src/db/application-writer-profile-registry-structure.js'
import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js'
import {RESTORE_WRITER_PROFILE_DEFINITION_SHA256,RESTORE_WRITER_PROFILE_MANIFEST_SHA256,restoreProfileEnrollmentSql} from '../../src/db/database-restore-quarantine-profile.js'
const baseFlags=['approval','approval-sha256','transport','transport-sha256','ca']
const digest=/^[a-f0-9]{64}$/
const json=(bytes:Buffer)=>JSON.parse(new TextDecoder('utf8',{fatal:true}).decode(bytes))
// The accepted registry fixture's two tables and relation ACLs. Other schema
// objects and cross-owner metadata grants are setup prerequisites.
const registrySql=`CREATE TABLE mmapp_control.application_writer_profile_history (
installation_id uuid NOT NULL, epoch bigint NOT NULL CHECK(epoch>0),
head_sha256 text NOT NULL CHECK(head_sha256~'^[a-f0-9]{64}$'),
previous_installation_id uuid, previous_epoch bigint, previous_head_sha256 text,
policy_sha256 text NOT NULL CHECK(policy_sha256~'^[a-f0-9]{64}$'),
policy_bytes bytea NOT NULL CHECK(octet_length(policy_bytes) BETWEEN 1 AND 1048576),
head_bytes bytea NOT NULL CHECK(octet_length(head_bytes) BETWEEN 1 AND 8192),
PRIMARY KEY(installation_id,epoch), UNIQUE(installation_id,epoch,head_sha256),
CHECK((epoch=1 AND previous_installation_id IS NULL AND previous_epoch IS NULL AND previous_head_sha256 IS NULL)
OR(epoch>1 AND previous_installation_id IS NOT NULL AND previous_installation_id=installation_id
AND previous_epoch IS NOT NULL AND previous_epoch=epoch-1 AND previous_head_sha256 IS NOT NULL)),
FOREIGN KEY(previous_installation_id,previous_epoch,previous_head_sha256)
REFERENCES mmapp_control.application_writer_profile_history(installation_id,epoch,head_sha256) MATCH FULL
);
CREATE TABLE mmapp_control.application_writer_profile_current (
id smallint PRIMARY KEY CHECK(id=1), installation_id uuid NOT NULL, epoch bigint NOT NULL, head_sha256 text NOT NULL,
FOREIGN KEY(installation_id,epoch,head_sha256) REFERENCES mmapp_control.application_writer_profile_history(installation_id,epoch,head_sha256)
);`
const targetSql=(inspect:boolean,restoreProfile:boolean)=>`SELECT d.oid::text AS "databaseOid", d.datname::text AS "databaseName",
control.system_identifier::text AS "systemIdentifier", pg_catalog.current_setting('server_version_num')::int AS "serverVersionNum",
pg_catalog.pg_is_in_recovery() AS "inRecovery", r.oid::text AS "roleOid"
FROM pg_catalog.pg_database d CROSS JOIN pg_catalog.pg_roles r CROSS JOIN pg_catalog.pg_control_system() control
JOIN pg_catalog.pg_namespace n ON n.nspname='mmapp_control'
WHERE d.datname=pg_catalog.current_database() AND r.rolname=SESSION_USER AND SESSION_USER=CURRENT_USER
AND r.rolname=$1 AND n.nspowner=r.oid AND pg_catalog.current_setting('transaction_read_only')='${inspect?'on':'off'}'
AND pg_catalog.current_setting('session_replication_role')='origin' AND pg_catalog.current_setting('event_triggers')='on'
${inspect||restoreProfile?'':`AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class c WHERE c.relnamespace=n.oid
AND c.relname IN('application_writer_profile_history','application_writer_profile_current'))`}`
const registryRelNames = ['application_writer_profile_current','application_writer_profile_history']
export function writerRegistryEnrollmentSql(bindings:RegistryRoleBindingsData){
const {operator,publisher}=bindings
return [registrySql,`REVOKE ALL ON mmapp_control.application_writer_profile_history, mmapp_control.application_writer_profile_current FROM PUBLIC;
GRANT SELECT ON mmapp_control.application_writer_profile_history, mmapp_control.application_writer_profile_current TO "${operator.name}";
GRANT SELECT, INSERT ON mmapp_control.application_writer_profile_history TO "${publisher.name}";
GRANT SELECT, INSERT, UPDATE ON mmapp_control.application_writer_profile_current TO "${publisher.name}"`]
}
/** Exact registry body for a separately authorized, retained control transaction. */
export async function enrollWriterRegistryInTransaction(sql:Parameters<typeof readProtectedRegistryStructureData>[0],bindings:RegistryRoleBindingsData){
for(const statement of writerRegistryEnrollmentSql(bindings))await sql.query(statement)
return readProtectedRegistryStructureData(sql,bindings)
}
export async function registryEnrollmentMain(args:string[]){
const inspect=args[0]==='registry-inspect'
const restoreProfile=args[0]==='restore-profile-enroll'
const flags=restoreProfile?[...baseFlags,'bootstrap','bootstrap-sha256']:baseFlags
assert((inspect||restoreProfile||args[0]==='registry-enroll')&&args.length===1+2*flags.length)
assertJsDriverEnvironment(process.env)
const values=new Map<string,string>()
for(let i=1;i<args.length;i+=2){
const name=args[i].slice(2),value=args[i+1]
assert(args[i].startsWith('--')&&flags.includes(name)&&!values.has(name)&&value)
assert(!name.endsWith('sha256')||digest.test(value))
values.set(name,value)
}
const get=(name:string)=>values.get(name)!
const approval=json(await readProtected(get('approval'),16384,get('approval-sha256')))
const manifestSha256=migrationManifestDigest()
if(restoreProfile){
assert.deepEqual(Object.keys(approval).sort(),['catalogSha256','definitionSha256','deploymentRequest','expectedHeadSha256','format','manifestSha256','previousCatalogSha256'])
assert(approval.format==='application-writer-restore-profile-enrollment-v1'&&manifestSha256===RESTORE_WRITER_PROFILE_MANIFEST_SHA256&&
approval.definitionSha256===RESTORE_WRITER_PROFILE_DEFINITION_SHA256&&[approval.catalogSha256,approval.previousCatalogSha256,approval.expectedHeadSha256]
.every(value=>typeof value==='string'&&digest.test(value)))
}else{
assert.deepEqual(Object.keys(approval).sort(),['deploymentRequest','format','manifestSha256'])
assert(approval.format==='application-writer-registry-enrollment-v1')
}
assert.equal(approval.manifestSha256,manifestSha256)
const request=deploymentRequest(approval.deploymentRequest)
let subject:Parameters<typeof publicKey>[0]|undefined
if(restoreProfile){
const bootstrap=json(await readProtected(get('bootstrap'),32768,get('bootstrap-sha256')))
assert(bootstrap.format==='application-writer-bootstrap-v1'&&bootstrap.publicationAuthorized===false&&bootstrap.readyAuthorized===false&&
canonical(deploymentRequest(bootstrap.deploymentRequest))===canonical(request),'Independently pinned bootstrap required for restore enrollment')
assert(bootstrap.verificationSubject?.installationId===request.installationId)
subject=bootstrap.verificationSubject
publicKey(subject!)
}
const bindings:RegistryRoleBindingsData=request.roles
const transport=json(await readProtected(get('transport'),16384,get('transport-sha256')))
const ca=await readProtected(get('ca'),65536,request.tls.caSha256)
const options=poolOptions(transport,request,ca,'control')
const {default:pg}=await import('pg')
const pool=new pg.Pool({...options,query_timeout:12_000})
const deadline=Date.now()+120_000
let client:PoolClient|undefined,commitSent=false,committed=false,cleanupUnconfirmed=false
let registryStructureSha256:string|undefined
let observed:'absent'|'installed'|undefined
let failure:unknown
const onError=(error:Error)=>{failure??=error}
pool.on('error',onError)
try{
const connected=await pool.connect()
client=connected
connected.on('error',onError)
const assertPeer=retainPublisherTlsPeer(connected,request.tls)
const fence=()=>{if(failure)throw failure;assert(Date.now()<deadline,'Registry enrollment deadline expired');assertPeer()}
const query=async<R extends Record<string,unknown>>(text:string,parameters?:unknown[])=>{
fence()
const result=await connected.query<R>(text,parameters)
fence()
return result
}
await query(inspect?'BEGIN READ ONLY':'BEGIN')
await query('SET LOCAL search_path = pg_catalog')
await query('SELECT pg_catalog.pg_advisory_xact_lock($1::bigint)',[KEY])
const {control,operator,runtime}=bindings
const target=await query(targetSql(inspect,restoreProfile),[control.name])
assert.deepEqual(target.rows,[{...request.source,roleOid:control.signedOid}],'Registry target/owner/absence refused')
const roles=await query<{name:string;oid:string}>('SELECT rolname::text AS name, oid::text AS oid FROM pg_catalog.pg_roles WHERE rolname=ANY($1::text[])',
[Object.values(bindings).map(role=>role.name)])
assert.deepEqual(new Map(roles.rows.map(role=>[role.name,role.oid])),new Map(Object.values(bindings).map(role=>[role.name,role.signedOid])))
const markers=MIGRATION_MANIFEST.map(pin=>({id:pin.file.slice(0,-4)}))
const actualMarkers=await query('SELECT id FROM public.schema_migrations ORDER BY id COLLATE "C" LIMIT $1',[markers.length+1])
assert.deepEqual(actualMarkers.rows,markers,'Registry enrollment requires exact current migration markers')
if(inspect){
const relations=await query<{name:string}>(`SELECT c.relname::text AS name FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='mmapp_control'
AND c.relname=ANY($1::text[]) ORDER BY c.relname COLLATE "C"`,[registryRelNames])
if(relations.rows.length){
assert.deepEqual(relations.rows.map(row=>row.name),registryRelNames,'Registry relations are incomplete')
registryStructureSha256=(await readProtectedRegistryStructureData({query},bindings)).sha256
}
assert.equal((await query('ROLLBACK')).command,'ROLLBACK')
observed=relations.rows.length?'installed':'absent'
}else{
if(restoreProfile){
const {collectSource57Catalogue,collectSource58Catalogue}=await import('./catalogue.mjs')
const previous=await readProtectedRegistryStructureData({query},bindings),before=await collectSource57Catalogue({query},{roleBindings:bindings})
assert.equal(sha(canonical({base:before.catalogSha256,security:previous.sha256})),approval.previousCatalogSha256)
await query('LOCK TABLE mmapp_control.application_writer_profile_current, mmapp_control.application_writer_profile_history IN SHARE MODE')
const current=await readCurrentApplicationWriterProfile({query},subject!)
assert(current?.headSha256===approval.expectedHeadSha256&&current.policy.manifestSha256===BUILD57_PROVENANCE.manifestSha256&&
current.policy.definitionSha256===BUILD57_PROVENANCE.templateSha256&&current.policy.catalogSha256===approval.previousCatalogSha256&&
canonical(current.policy.source)===canonical(request.source)&&canonical(current.policy.roles)===canonical(previous.roles),
'Exact signed Source57 predecessor required for restore enrollment')
await query(restoreProfileEnrollmentSql(runtime.name,operator.name))
const installed=await readProtectedRegistryStructureData({query},bindings,true),after=await collectSource58Catalogue({query},{roleBindings:bindings})
registryStructureSha256=installed.sha256
assert.equal(sha(canonical({base:after.catalogSha256,security:installed.sha256})),approval.catalogSha256)
assert.equal((await readCurrentApplicationWriterProfile({query},subject!))?.headSha256,current.headSha256)
}else{
registryStructureSha256=(await enrollWriterRegistryInTransaction({query},bindings)).sha256
}
fence()
commitSent=true
const ack=await connected.query('COMMIT')
assert.equal(ack.command,'COMMIT')
committed=true
}
}catch(error){failure??=error}
finally{
// Destroying the retained session rolls back any unsuccessful open transaction.
try{client?.release(true)}catch(error){failure??=error;cleanupUnconfirmed=true}
try{await pool.end()}catch(error){failure??=error;cleanupUnconfirmed=true}
}
if(committed)return {event:restoreProfile?'application-writer-restore-profile-enrollment':'application-writer-registry-enrollment',outcome:'committed',
installationId:request.installationId,manifestSha256,registryStructureSha256,cleanupUnconfirmed:cleanupUnconfirmed||!!failure,
automaticReplay:false,readyAuthorized:false}
if(observed&&!failure)return {event:'application-writer-registry-inspection',outcome:observed,
installationId:request.installationId,manifestSha256,registryStructureSha256,automaticReplay:false,readyAuthorized:false}
if(commitSent)throw Object.assign(Error('Registry enrollment requires inspection',{cause:failure}),{code:'WRITER_REGISTRY_TERMINAL_UNKNOWN'})
throw failure??Error('Registry enrollment refused')
}