Files
MikrotikManager/backend/scripts/source58-restore-enrollment-owned.mjs
T

125 lines
8.7 KiB
JavaScript

import assert from 'node:assert/strict'
export async function verifyOwnedSource58RestoreEnrollment({pg,control,actor,main,store,sha,request,approvedCatalogue,subject,renewed,observe,
bootstrapFile,bootstrap,controlTransport,controlTransportSha256,ca,shared,publishSource58}){
const [{collectSource57Catalogue,collectSource58Catalogue},{BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE},
{readProtectedRegistryStructureData},{readCurrentApplicationWriterProfile},{restoreProfileEnrollmentSql},
{sourceBindingBytes},{bytes,canonical,KEY},{retainPublisherTlsPeer}]=await Promise.all([
import('./writer-profile/catalogue.mts'),import('./writer-profile/fixed58-build-definition.ts'),
import('../src/db/application-writer-profile-registry-structure.ts'),import('../src/db/application-writer-profile-registry-read.ts'),
import('../src/db/database-restore-quarantine-profile.ts'),import('../src/db/database-source-binding.ts'),
import('../src/db/application-writer-profile-format.ts'),import('./writer-profile/operator-contract.mjs'),
])
const catalogue=async(client,edition)=>{
const security=await readProtectedRegistryStructureData(client,request.roles,edition===58)
const base=await (edition===58?collectSource58Catalogue:collectSource57Catalogue)(client,{roleBindings:request.roles})
return {sha256:sha(canonical({base:base.catalogSha256,security:security.sha256})),securitySha256:security.sha256}
}
const assertQuarantineAbsent=async()=>{
const {rows:[state]}=await control.query(`SELECT pg_catalog.to_regclass('mmapp_control.database_restore_quarantine') IS NULL AS absent,
pg_catalog.has_schema_privilege($1,'mmapp_control','USAGE') AS runtime_schema,
pg_catalog.has_table_privilege($1,'mmapp_control.application_writer_profile_current','SELECT') AS runtime_registry`,[request.roles.runtime.name])
assert.deepEqual(state,{absent:true,runtime_schema:false,runtime_registry:false})
}
const client=await control.connect()
let candidate
try{
const retain=retainPublisherTlsPeer(client,request.tls)
await client.query('BEGIN')
try{
await client.query('SET LOCAL search_path=pg_catalog')
await client.query('SELECT pg_catalog.pg_advisory_xact_lock($1::bigint)',[KEY])
await client.query('LOCK TABLE mmapp_control.application_writer_profile_current, mmapp_control.application_writer_profile_history IN SHARE MODE')
const {rows:[identity]}=await client.query(`SELECT oid::text AS oid, current_database() AS db,
(pg_catalog.pg_control_system()).system_identifier::text AS system,
(SELECT oid::text FROM pg_catalog.pg_database WHERE datname=current_database()) AS database_oid
FROM pg_catalog.pg_roles WHERE rolname=SESSION_USER AND SESSION_USER=CURRENT_USER`)
assert.deepEqual(identity,{oid:request.roles.control.signedOid,db:request.source.databaseName,system:request.source.systemIdentifier,database_oid:request.source.databaseOid})
const predecessor=await readCurrentApplicationWriterProfile(client,subject)
assert.equal(predecessor.headSha256,renewed.headSha256)
assert.equal(predecessor.policy.catalogSha256,approvedCatalogue)
assert.equal((await catalogue(client,57)).sha256,approvedCatalogue)
await client.query(restoreProfileEnrollmentSql(request.roles.runtime.name,request.roles.operator.name))
candidate=await catalogue(client,58);retain()
}finally{assert.equal((await client.query('ROLLBACK')).command,'ROLLBACK')}
await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')
try{
assert.equal((await catalogue(client,57)).sha256,approvedCatalogue)
assert.equal((await readCurrentApplicationWriterProfile(client,subject)).headSha256,renewed.headSha256)
retain()
}finally{assert.equal((await client.query('ROLLBACK')).command,'ROLLBACK')}
}finally{client.release(true)}
await assertQuarantineAbsent()
assert.notEqual(candidate.sha256,approvedCatalogue)
const independentApproval=sourceBindingBytes({format:'application-writer-restore-profile-enrollment-v1',
catalogSha256:candidate.sha256,definitionSha256:BUILD58_PROVENANCE.templateSha256,deploymentRequest:request,
expectedHeadSha256:renewed.headSha256,manifestSha256:BUILD58_PROVENANCE.manifestSha256,previousCatalogSha256:approvedCatalogue})
const enroll=['restore-profile-enroll','--bootstrap',bootstrapFile,'--bootstrap-sha256',sha(bootstrap),
'--approval',await store('restore58-reviewed-approval.json',independentApproval),'--approval-sha256',sha(independentApproval),
'--transport',controlTransport,'--transport-sha256',controlTransportSha256,'--ca',ca]
if(!publishSource58){
const {rows:[first]}=await control.query(`SELECT head_bytes FROM mmapp_control.application_writer_profile_history
WHERE installation_id=$1 AND epoch=1`,[subject.installationId])
const envelope=JSON.parse(first.head_bytes.toString('utf8'))
envelope.signature=(envelope.signature[0]==='A'?'B':'A')+envelope.signature.slice(1)
const replace=raw=>control.query(`UPDATE mmapp_control.application_writer_profile_history SET head_bytes=$2
WHERE installation_id=$1 AND epoch=1`,[subject.installationId,raw])
await replace(bytes(envelope))
const connect=pg.Pool.prototype.connect
let ddlSent=0
pg.Pool.prototype.connect=function(...parameters){
const connection=connect.apply(this,parameters)
if(parameters.length||this.options.application_name!=='mmapp-writer-registry-enroll')return connection
return connection.then(client=>{
const query=client.query
client.query=function(text,...args){
if(typeof text==='string'&&text.includes('CREATE TABLE mmapp_control.database_restore_quarantine'))ddlSent++
return query.call(this,text,...args)
}
return client
})
}
try{await assert.rejects(main(enroll),/Installation signature refused/)}
finally{pg.Pool.prototype.connect=connect;await replace(first.head_bytes)}
assert.equal(ddlSent,0);await assertQuarantineAbsent()
}
const installed=await main(enroll)
assert.equal(installed.outcome,'committed');assert.equal(installed.cleanupUnconfirmed,false)
assert.equal(installed.registryStructureSha256,candidate.securitySha256);assert.equal(installed.readyAuthorized,false)
const definition=sourceBindingBytes({format:'application-writer-source58-definition-approval-v1',provenance:BUILD58_PROVENANCE,template:FIXED58_ROLE_TEMPLATE})
const candidateArgs=[...shared]
candidateArgs[candidateArgs.indexOf('--definition')+1]=await store('restore58-definition.json',definition)
candidateArgs[candidateArgs.indexOf('--definition-sha256')+1]=sha(definition)
const inspect=[...candidateArgs]
inspect.splice(inspect.indexOf('--journal'),2)
await assert.rejects(main(['source-catalogue-inspect',...inspect]),error=>error.cause?.message==='Approved source58 predecessor required')
if(publishSource58){
const {verifyOwnedSource58Publication}=await import('./source58-publication-owned.mjs')
return await verifyOwnedSource58Publication({control,actor,main,store,sha,request,subject,renewed,approvedCatalogue,candidate,
candidateArgs,inspect,manifestSha256:BUILD58_PROVENANCE.manifestSha256,definitionSha256:BUILD58_PROVENANCE.templateSha256})
}
const publisher=actor('publisher'),reader=await publisher.connect()
try{
const retain=retainPublisherTlsPeer(reader,request.tls)
await reader.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')
assert.equal((await catalogue(reader,58)).sha256,candidate.sha256)
assert.equal((await readCurrentApplicationWriterProfile(reader,subject)).headSha256,renewed.headSha256)
retain()
}finally{await reader.query('ROLLBACK');reader.release(true);await publisher.end()}
assert.equal((await observe()).headSha256,renewed.headSha256)
const runtime=actor('runtime')
try{
assert.equal((await readCurrentApplicationWriterProfile(runtime,subject)).headSha256,renewed.headSha256)
const {rows:[row]}=await runtime.query('SELECT operation_id,journal_prefix_bytes,journal_prefix_sha256 FROM mmapp_control.database_restore_quarantine WHERE id=1')
assert.deepEqual(row,{operation_id:null,journal_prefix_bytes:null,journal_prefix_sha256:null})
await assert.rejects(runtime.query('UPDATE mmapp_control.database_restore_quarantine SET operation_id=NULL'),{code:'42501'})
}finally{await runtime.end()}
return {source58RestoreProfileInstalled:true,rolledBackCandidateCount:1,rollbackRestoredExactSource57:true,
independentlyPinnedTargetMatched:true,source57HeadPreserved:true,invalidPredecessorSignatureRefusedBeforeDdl:true,
runtimeReadQuarantineAndRegistry:true,runtimeQuarantineWriteRefused:true,source58CatalogueSha256:candidate.sha256,
source58InspectionStillRequiresPublishedHead:true,
source58WriterHeadPublished:false,readyAuthorized:false}
}