also looking at this
feat: own runtime firmware candidates
#49
24 files
+1245
-92
| @@ -4,9 +4,13 @@ import { lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, u | ||
| 4 | 4 | import { tmpdir } from 'node:os' |
| 5 | 5 | import { dirname, join, resolve } from 'node:path' |
| 6 | 6 | import { DownloadHTTPError, Updater } from 'tuf-js' |
| 7 | import type { TargetFile } from 'tuf-js' | |
| 8 | import { Readable } from 'node:stream' | |
| 9 | import { finishRuntimeCandidate, runtimeCandidateOutput } from './candidate-files' | |
| 10 | import type { RuntimeFirmwareStage } from './staging' | |
| 7 | 11 | import { inspectRuntimeTrust } from './enrollment' |
| 8 | 12 | import type { RuntimeTrustSummary } from './enrollment' |
| 9 | import { directory, metadataLimit, regularFile, repositoryFile, safePath, sha256, syncDirectory, writeExclusive } from './files' | |
| 13 | import { directory, imageLimit, metadataLimit, regularFile, repositoryFile, safePath, sha256, syncDirectory, writeExclusive } from './files' | |
| 10 | 14 | import { object, validateMetadata } from './metadata' |
| 11 | 15 | import { admitSignedRuntime, RuntimeManifestRejected } from './manifest' |
| 12 | 16 | |
| @@ -21,6 +25,10 @@ const schema = [ | ||
| 21 | 25 | `CREATE TABLE inputs (attempt_id TEXT NOT NULL, ordinal INTEGER NOT NULL CHECK(ordinal BETWEEN 0 AND 63), path TEXT NOT NULL CHECK(length(path) BETWEEN 1 AND 256), status INTEGER NOT NULL CHECK(status IN (200, 404)), bytes BLOB, sha256 TEXT, PRIMARY KEY(attempt_id, ordinal), FOREIGN KEY(attempt_id) REFERENCES attempts(id), CHECK((status = 404 AND bytes IS NULL AND sha256 IS NULL) OR (status = 200 AND bytes IS NOT NULL AND sha256 IS NOT NULL AND length(bytes) BETWEEN 1 AND ${metadataLimit} AND length(sha256) = 64))) STRICT`, |
| 22 | 26 | `CREATE TABLE metadata (generation INTEGER PRIMARY KEY CHECK(generation BETWEEN 0 AND ${maximumGeneration}), attempt_id TEXT, ordinal INTEGER NOT NULL CHECK(ordinal BETWEEN 0 AND 63), role TEXT NOT NULL CHECK(length(role) BETWEEN 1 AND 180), version INTEGER NOT NULL CHECK(version BETWEEN 1 AND 9007199254740991), epoch INTEGER NOT NULL CHECK(epoch BETWEEN 0 AND generation), bytes BLOB NOT NULL CHECK(length(bytes) BETWEEN 1 AND ${metadataLimit}), sha256 TEXT NOT NULL CHECK(length(sha256) = 64), UNIQUE(attempt_id, ordinal), FOREIGN KEY(attempt_id) REFERENCES attempts(id)) STRICT`, |
| 23 | 27 | ] |
| 28 | const candidateSchema = [ | |
| 29 | 'CREATE TABLE candidates (id TEXT PRIMARY KEY CHECK(length(id) = 32), attempt_id TEXT NOT NULL UNIQUE, generation INTEGER NOT NULL, phase TEXT NOT NULL CHECK(phase IN (\'reserved\', \'prepared\', \'retired\')), description BLOB NOT NULL CHECK(length(description) BETWEEN 1 AND 16384), sha256 TEXT NOT NULL CHECK(length(sha256) = 64), FOREIGN KEY(attempt_id) REFERENCES attempts(id), FOREIGN KEY(generation) REFERENCES metadata(generation)) STRICT', | |
| 30 | "CREATE UNIQUE INDEX candidate_active ON candidates ((1)) WHERE phase IN ('reserved', 'prepared')", | |
| 31 | ] | |
| 24 | 32 | |
| 25 | 33 | interface TrustReference { enrollmentDirectory: string, enrollmentSha256: string } |
| 26 | 34 | interface StoreReference extends TrustReference { directory: string, storeSha256: string } |
| @@ -59,7 +67,7 @@ function configure(db: Database) { | ||
| 59 | 67 | if (!result || Object.values(result)[0] !== expected) throw new Error('Required SQLite update-store configuration unavailable') |
| 60 | 68 | } |
| 61 | 69 | } |
| 62 | function openDatabase(path: string, expectedSchema: string[]) { | |
| 70 | function openDatabase(path: string, expectedSchema: string[], allowCandidates = false) { | |
| 63 | 71 | const before = protectedFile(path, path.endsWith('writer.sqlite') ? 1024 * 1024 : maximumDatabaseBytes) |
| 64 | 72 | const db = new Database(path, { create: false, strict: true }) |
| 65 | 73 | try { |
| @@ -68,19 +76,20 @@ function openDatabase(path: string, expectedSchema: string[]) { | ||
| 68 | 76 | db.exec('PRAGMA trusted_schema=OFF; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=0;') |
| 69 | 77 | // Authenticate the protocol format before any configuration that could |
| 70 | 78 | // rewrite a foreign database's journal/header format. |
| 71 | checkSchema(db, expectedSchema) | |
| 79 | const version = databaseVersion(db) | |
| 80 | checkSchema(db, allowCandidates && version === 2 ? [...expectedSchema, ...candidateSchema] : expectedSchema, allowCandidates && version === 2 ? 2 : 1) | |
| 72 | 81 | if (Object.values(db.query('PRAGMA journal_mode').get() as Record<string, unknown>)[0] !== 'delete') throw new Error('Unexpected update-store journal format') |
| 73 | 82 | configure(db) |
| 74 | 83 | return db |
| 75 | 84 | } |
| 76 | 85 | catch (error) { db.close(); throw error } |
| 77 | 86 | } |
| 78 | function checkSchema(db: Database, expected: string[]) { | |
| 87 | function databaseVersion(db: Database) { return db.query<{ user_version: number }, []>('PRAGMA user_version').get()!.user_version } | |
| 88 | function checkSchema(db: Database, expected: string[], version = 1) { | |
| 79 | 89 | const definitions = db.query<{ sql: string }, []>("SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name").all().map(row => row.sql).sort() |
| 80 | 90 | if (JSON.stringify(definitions) !== JSON.stringify([...expected].sort())) throw new Error('Unexpected update-store schema') |
| 81 | 91 | const values = db.query<{ application_id: number }, []>('PRAGMA application_id').get() |
| 82 | const version = db.query<{ user_version: number }, []>('PRAGMA user_version').get() | |
| 83 | if (values?.application_id !== applicationId || version?.user_version !== 1 || Object.values(db.query('PRAGMA quick_check').get() as Record<string, unknown>)[0] !== 'ok' || db.query('PRAGMA foreign_key_check').all().length) throw new Error('Invalid update-store database integrity or version') | |
| 92 | if (values?.application_id !== applicationId || databaseVersion(db) !== version || Object.values(db.query('PRAGMA quick_check').get() as Record<string, unknown>)[0] !== 'ok' || db.query('PRAGMA foreign_key_check').all().length) throw new Error('Invalid update-store database integrity or version') | |
| 84 | 93 | } |
| 85 | 94 | function createDatabase(path: string, statements: string[]) { |
| 86 | 95 | writeExclusive(path, Buffer.alloc(0)) |
| @@ -144,17 +153,22 @@ async function withStore<T>(options: StoreReference, operation: (db: Database, b | ||
| 144 | 153 | let writer: Database | undefined, db: Database | undefined |
| 145 | 154 | try { |
| 146 | 155 | for (const name of readdirSync(path)) { |
| 147 | if (!['store.json', 'writer.sqlite', 'state.sqlite', 'writer.sqlite-journal', 'state.sqlite-journal'].includes(name)) throw new Error('Unexpected update-store entry') | |
| 156 | if (!['store.json', 'writer.sqlite', 'state.sqlite', 'writer.sqlite-journal', 'state.sqlite-journal', 'candidates'].includes(name)) throw new Error('Unexpected update-store entry') | |
| 148 | 157 | if (name.endsWith('-journal')) protectedFile(join(path, name), maximumDatabaseBytes, true) |
| 149 | 158 | } |
| 150 | 159 | writer = openDatabase(join(path, 'writer.sqlite'), [writerSchema]) |
| 151 | 160 | writer.exec('BEGIN IMMEDIATE') |
| 152 | 161 | const owner = writer.query<{ store_id: string }, []>('SELECT store_id FROM writer').all() |
| 153 | 162 | if (owner.length !== 1 || owner[0]!.store_id !== binding.storeId) throw new Error('Invalid update-store writer identity') |
| 154 | db = openDatabase(join(path, 'state.sqlite'), schema) | |
| 163 | db = openDatabase(join(path, 'state.sqlite'), schema, true) | |
| 164 | if (readdirSync(path).includes('candidates')) { | |
| 165 | if (databaseVersion(db) !== 2) throw new Error('Candidate files require an owned format2 store') | |
| 166 | protectedDirectory(join(path, 'candidates')) | |
| 167 | } | |
| 155 | 168 | const initial = db.query<MetadataRow, []>('SELECT * FROM metadata WHERE generation = 0').get() |
| 156 | 169 | if (initial?.sha256 !== trusted.policy.trustedRootSha256 || initial.version !== trusted.rootVersion || state(db, binding).release_floor < trusted.policy.minimumReleaseSequence) throw new Error('Update-store anchor or floor mismatch') |
| 157 | 170 | summary(db, binding, options.storeSha256) |
| 171 | for (const row of candidateRows(db)) ownedDescription(db, row, trusted) | |
| 158 | 172 | return await operation(db, binding, trusted, path) |
| 159 | 173 | } |
| 160 | 174 | finally { |
| @@ -203,7 +217,7 @@ export interface RuntimeUpdateClock { | ||
| 203 | 217 | } |
| 204 | 218 | |
| 205 | 219 | export interface RuntimeUpdateProgress { |
| 206 | phase: 'input-committed' | 'metadata-committed' | |
| 220 | phase: 'input-committed' | 'metadata-committed' | 'image-written' | 'candidate-completed' | 'candidate-reserved' | 'candidate-recorded' | 'candidate-retired' | |
| 207 | 221 | ordinal: number |
| 208 | 222 | } |
| 209 | 223 | type ProgressObserver = (event: Readonly<RuntimeUpdateProgress>) => void | Promise<void> |
| @@ -258,10 +272,22 @@ function commitMetadata(db: Database, binding: Binding, attempt: string, ordinal | ||
| 258 | 272 | return changed |
| 259 | 273 | } |
| 260 | 274 | |
| 261 | /** Verify bounded offline metadata and retain its accepted prefix. This does not stage, select or install an image. */ | |
| 262 | export async function refreshRuntimeTrustStore(options: StoreReference & { repository: string, clock: RuntimeUpdateClock, onProgress?: ProgressObserver }): Promise<Readonly<RuntimeTrustStoreSummary>> { | |
| 275 | interface RefreshOptions extends StoreReference { repository: string, clock: RuntimeUpdateClock, onProgress?: ProgressObserver } | |
| 276 | interface VerifiedSelection { | |
| 277 | db: Database | |
| 278 | binding: Binding | |
| 279 | trusted: Readonly<RuntimeTrustSummary> | |
| 280 | source: string | |
| 281 | info: TargetFile | |
| 282 | runtime: ReturnType<typeof admitSignedRuntime> | |
| 283 | attempt: string | |
| 284 | path: string | |
| 285 | } | |
| 286 | ||
| 287 | async function refreshAndComplete<T>(options: RefreshOptions, complete: (selection: VerifiedSelection) => Promise<T>, before?: (db: Database) => void): Promise<{ store: Readonly<RuntimeTrustStoreSummary>, value: T }> { | |
| 263 | 288 | options = { ...options } |
| 264 | return withStore(options, async (db, binding, trusted) => { | |
| 289 | return withStore(options, async (db, binding, trusted, path) => { | |
| 290 | before?.(db) | |
| 265 | 291 | if (db.query("SELECT id FROM attempts WHERE phase IN ('pending', 'maintenance')").get()) throw new Error('An unresolved update attempt requires recovery') |
| 266 | 292 | const current = state(db, binding), now = clockReading(options.clock, current.clock_floor_ms) |
| 267 | 293 | if (db.query<{ count: number }, []>('SELECT count(*) AS count FROM attempts').get()!.count >= 256) throw new Error('Update attempt history limit reached') |
| @@ -305,11 +331,14 @@ export async function refreshRuntimeTrustStore(options: StoreReference & { repos | ||
| 305 | 331 | const info = await updater.getTargetInfo(trusted.policy.target) |
| 306 | 332 | if (!info) throw new Error('Selected runtime target is absent') |
| 307 | 333 | const runtime = admitSignedRuntime(info, { ...trusted.policy, minimumReleaseSequence: state(db, binding).release_floor }) |
| 334 | // The signed release floor survives later image or candidate-output failure. | |
| 308 | 335 | db.transaction(() => { |
| 309 | 336 | db.query('UPDATE store_state SET release_floor = max(release_floor, ?) WHERE id = 1').run(runtime.releaseSequence) |
| 310 | db.query("UPDATE attempts SET phase = 'verified', accepted_release = ? WHERE id = ?").run(runtime.releaseSequence, attempt) | |
| 337 | db.query('UPDATE attempts SET accepted_release = ? WHERE id = ?').run(runtime.releaseSequence, attempt) | |
| 311 | 338 | })() |
| 312 | return summary(db, binding, options.storeSha256) | |
| 339 | const value = await complete({ db, binding, trusted, source, info, runtime, attempt, path }) | |
| 340 | db.query("UPDATE attempts SET phase = 'verified' WHERE id = ?").run(attempt) | |
| 341 | return { store: summary(db, binding, options.storeSha256), value } | |
| 313 | 342 | } |
| 314 | 343 | catch (error) { |
| 315 | 344 | try { db.query("UPDATE attempts SET phase = 'maintenance' WHERE id = ?").run(attempt) } |
| @@ -320,6 +349,205 @@ export async function refreshRuntimeTrustStore(options: StoreReference & { repos | ||
| 320 | 349 | }) |
| 321 | 350 | } |
| 322 | 351 | |
| 352 | /** Verify bounded offline metadata and retain its accepted prefix. This never downloads an image. */ | |
| 353 | export async function refreshRuntimeTrustStore(options: RefreshOptions): Promise<Readonly<RuntimeTrustStoreSummary>> { | |
| 354 | return (await refreshAndComplete(options, async () => undefined)).store | |
| 355 | } | |
| 356 | ||
| 357 | export interface PreparedRuntimeFirmware { | |
| 358 | schema: 'drone-runtime-prepared-image-v1' | |
| 359 | store: Readonly<RuntimeTrustStoreSummary> | |
| 360 | candidate: Readonly<RuntimeFirmwareStage> | |
| 361 | trustStatePersisted: true | |
| 362 | physicalDeploymentAllowed: false | |
| 363 | } | |
| 364 | ||
| 365 | /** Authenticate an image under current protected metadata. Never installs, selects or confirms firmware. */ | |
| 366 | export async function prepareRuntimeFirmwareUpdate(options: RefreshOptions & { output: string }): Promise<Readonly<PreparedRuntimeFirmware>> { | |
| 367 | options = { ...options } | |
| 368 | const output = runtimeCandidateOutput(options.output, [options.repository, options.directory, options.enrollmentDirectory]) | |
| 369 | const result = await refreshAndComplete(options, selection => writePreparedCandidate(selection, output, options.onProgress)) | |
| 370 | return Object.freeze({ schema: 'drone-runtime-prepared-image-v1', store: result.store, candidate: result.value, trustStatePersisted: true, physicalDeploymentAllowed: false }) | |
| 371 | } | |
| 372 | ||
| 373 | function candidateDescription({ db, binding, trusted, info, runtime }: VerifiedSelection): RuntimeFirmwareStage { | |
| 374 | const root = activeMetadata(db, state(db, binding).generation).find(row => row.role === 'root')! | |
| 375 | return { schema: 'drone-runtime-stage-v1', target: trusted.policy.target, platform: trusted.policy.platform, trustedRootSha256: root.sha256, rootVersion: root.version, ...runtime, protocolVersion: 1, signerDeclaredProfile: 'neutral-bench', length: info.length, sha256: info.hashes.sha256!, trustStatePersisted: false, physicalDeploymentAllowed: false } | |
| 376 | } | |
| 377 | ||
| 378 | async function writePreparedCandidate(selection: VerifiedSelection, output: string, onProgress?: ProgressObserver) { | |
| 379 | const { db, binding, source, info } = selection | |
| 380 | const rows = activeMetadata(db, state(db, binding).generation), root = rows.find(row => row.role === 'root')! | |
| 381 | const rootBytes = checkedMetadataBytes(root), consistent = object(object(JSON.parse(rootBytes.toString('utf8'))).signed).consistent_snapshot === true | |
| 382 | const path = consistent ? info.path.replace(/([^/]+)$/, `${info.hashes.sha256}.$1`) : info.path | |
| 383 | const image = repositoryFile(source, `targets/${path}`, imageLimit) | |
| 384 | await info.verify(Readable.from(image)) | |
| 385 | const files = new Map<string, Buffer>() | |
| 386 | for (const row of rows) { | |
| 387 | if (row.role === 'root') continue | |
| 388 | files.set(`metadata/${row.role === 'timestamp' || !consistent ? '' : `${row.version}.`}${row.role}.json`, checkedMetadataBytes(row)) | |
| 389 | } | |
| 390 | files.set(`targets/${path}`, image) | |
| 391 | const candidate = candidateDescription(selection) | |
| 392 | mkdirSync(output, { mode: 0o700 }) | |
| 393 | writeExclusive(join(output, 'trust-root.json'), rootBytes) | |
| 394 | writeExclusive(join(output, 'image.bin'), image) | |
| 395 | await onProgress?.(Object.freeze({ phase: 'image-written', ordinal: 0 })) | |
| 396 | await finishRuntimeCandidate(output, info, candidate, files) | |
| 397 | await onProgress?.(Object.freeze({ phase: 'candidate-completed', ordinal: 0 })) | |
| 398 | return Object.freeze(candidate) | |
| 399 | } | |
| 400 | ||
| 401 | interface CandidateRow { id: string, attempt_id: string, generation: number, phase: 'reserved' | 'prepared' | 'retired', description: Uint8Array, sha256: string } | |
| 402 | export interface RuntimeFirmwareCandidate { | |
| 403 | id: string | |
| 404 | attemptId: string | |
| 405 | generation: number | |
| 406 | phase: CandidateRow['phase'] | |
| 407 | directory: string | |
| 408 | description: Readonly<RuntimeFirmwareStage> | |
| 409 | integrity: 'incomplete' | 'recorded-bytes-match' | 'mismatch' | 'unavailable' | |
| 410 | currentTrustValidated: false | |
| 411 | } | |
| 412 | export interface RuntimeFirmwareCandidates { | |
| 413 | schema: 'drone-runtime-candidates-v1' | |
| 414 | stateFormat: 1 | 2 | |
| 415 | store: Readonly<RuntimeTrustStoreSummary> | |
| 416 | retainedCandidates: number | |
| 417 | /** Owned declarations only. Retired file integrity is not inspected or authenticated for current use. */ | |
| 418 | history: ReadonlyArray<Readonly<Omit<RuntimeFirmwareCandidate, 'integrity' | 'currentTrustValidated'>>> | |
| 419 | candidate: Readonly<RuntimeFirmwareCandidate> | null | |
| 420 | physicalDeploymentAllowed: false | |
| 421 | } | |
| 422 | ||
| 423 | function candidateRows(db: Database) { | |
| 424 | if (databaseVersion(db) === 1) return [] | |
| 425 | const rows = db.query<CandidateRow, []>('SELECT * FROM candidates ORDER BY rowid LIMIT 129').all() | |
| 426 | if (rows.length > 128) throw new Error('Candidate history budget exceeded') | |
| 427 | return rows | |
| 428 | } | |
| 429 | function ownedDescription(db: Database, row: CandidateRow, trusted: Readonly<RuntimeTrustSummary>): Readonly<RuntimeFirmwareStage> { | |
| 430 | const bytes = Buffer.from(row.description) | |
| 431 | if (!/^[a-f0-9]{32}$/.test(row.id) || sha256(bytes) !== row.sha256) throw new Error('Invalid owned candidate record') | |
| 432 | const value = object(JSON.parse(bytes.toString('utf8'))) | |
| 433 | const keys = ['schema', 'target', 'platform', 'trustedRootSha256', 'rootVersion', 'releaseSequence', 'protocolVersion', 'sourceRevision', 'signerDeclaredProfile', 'length', 'sha256', 'trustStatePersisted', 'physicalDeploymentAllowed'] | |
| 434 | const root = activeMetadata(db, row.generation).find(item => item.role === 'root')! | |
| 435 | checkedMetadataBytes(root) | |
| 436 | const attempt = db.query<Attempt, [string]>('SELECT * FROM attempts WHERE id = ?').get(row.attempt_id) | |
| 437 | if (Object.keys(value).length !== keys.length || !keys.every(key => Object.hasOwn(value, key)) || value.schema !== 'drone-runtime-stage-v1' || value.target !== trusted.policy.target || value.platform !== trusted.policy.platform || value.trustedRootSha256 !== root.sha256 || value.rootVersion !== root.version || !Number.isSafeInteger(value.releaseSequence) || (value.releaseSequence as number) < trusted.policy.minimumReleaseSequence || value.protocolVersion !== 1 || typeof value.sourceRevision !== 'string' || !/^[a-f0-9]{40}$/.test(value.sourceRevision) || value.signerDeclaredProfile !== 'neutral-bench' || !Number.isSafeInteger(value.length) || (value.length as number) < 1 || (value.length as number) > imageLimit || typeof value.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.sha256) || value.trustStatePersisted !== false || value.physicalDeploymentAllowed !== false || !attempt || attempt.accepted_release !== value.releaseSequence || row.generation < attempt.base_generation) throw new Error('Owned candidate does not match protected selection') | |
| 438 | return Object.freeze(value as unknown as RuntimeFirmwareStage) | |
| 439 | } | |
| 440 | function candidateIntegrity(db: Database, generation: number, path: string, description: Readonly<RuntimeFirmwareStage>): RuntimeFirmwareCandidate['integrity'] { | |
| 441 | try { | |
| 442 | protectedDirectory(path) | |
| 443 | const rows = activeMetadata(db, generation), root = rows.find(row => row.role === 'root')! | |
| 444 | const rootBytes = checkedMetadataBytes(root), consistent = object(object(JSON.parse(rootBytes.toString('utf8'))).signed).consistent_snapshot === true | |
| 445 | const imagePath = consistent ? description.target.replace(/([^/]+)$/, `${description.sha256}.$1`) : description.target | |
| 446 | const expected = new Map<string, Buffer>([['trust-root.json', rootBytes], ['stage.json', Buffer.from(`${JSON.stringify(description, null, 2)}\n`)]]) | |
| 447 | for (const row of rows) { | |
| 448 | if (row.role !== 'root') expected.set(`repository/metadata/${row.role === 'timestamp' || !consistent ? '' : `${row.version}.`}${row.role}.json`, checkedMetadataBytes(row)) | |
| 449 | } | |
| 450 | for (const file of ['image.bin', `repository/targets/${imagePath}`]) { | |
| 451 | const address = join(path, file) | |
| 452 | protectedFile(address, imageLimit) | |
| 453 | const bytes = regularFile(address, imageLimit) | |
| 454 | if (bytes.length !== description.length || sha256(bytes) !== description.sha256) return 'mismatch' | |
| 455 | expected.set(file, bytes) | |
| 456 | } | |
| 457 | const directories = new Set<string>() | |
| 458 | for (const name of expected.keys()) { | |
| 459 | for (let parent = dirname(name); parent !== '.'; parent = dirname(parent)) directories.add(parent) | |
| 460 | } | |
| 461 | const visit = (relative: string): boolean => { | |
| 462 | const base = relative ? join(path, relative) : path | |
| 463 | protectedDirectory(base) | |
| 464 | const names = readdirSync(base) | |
| 465 | if (names.length > 64) return false | |
| 466 | return names.every(name => { | |
| 467 | const child = relative ? `${relative}/${name}` : name | |
| 468 | if (directories.has(child)) return visit(child) | |
| 469 | const bytes = expected.get(child) | |
| 470 | if (!bytes) return false | |
| 471 | protectedFile(join(path, child), child.endsWith('image.bin') || child.startsWith('repository/targets/') ? imageLimit : metadataLimit) | |
| 472 | return regularFile(join(path, child), Math.max(bytes.length, 1)).equals(bytes) | |
| 473 | }) | |
| 474 | } | |
| 475 | if (!visit('')) return 'mismatch' | |
| 476 | for (const [name, bytes] of expected) { | |
| 477 | protectedFile(join(path, name), Math.max(bytes.length, 1)) | |
| 478 | if (!regularFile(join(path, name), Math.max(bytes.length, 1)).equals(bytes)) return 'mismatch' | |
| 479 | } | |
| 480 | return 'recorded-bytes-match' | |
| 481 | } | |
| 482 | catch { return 'unavailable' } | |
| 483 | } | |
| 484 | function candidatesSummary(db: Database, binding: Binding, trusted: Readonly<RuntimeTrustSummary>, path: string, storeSha256: string): Readonly<RuntimeFirmwareCandidates> { | |
| 485 | const rows = candidateRows(db), active = rows.filter(row => row.phase !== 'retired') | |
| 486 | if (active.length > 1) throw new Error('Multiple active candidate records') | |
| 487 | let candidate: Readonly<RuntimeFirmwareCandidate> | null = null | |
| 488 | const history: Array<Readonly<Omit<RuntimeFirmwareCandidate, 'integrity' | 'currentTrustValidated'>>> = [] | |
| 489 | for (const row of rows) { | |
| 490 | const description = ownedDescription(db, row, trusted) | |
| 491 | const directory = join(path, 'candidates', row.id) | |
| 492 | const recorded = Object.freeze({ id: row.id, attemptId: row.attempt_id, generation: row.generation, phase: row.phase, directory, description }) | |
| 493 | history.push(recorded) | |
| 494 | if (row === active[0]) { | |
| 495 | candidate = Object.freeze({ ...recorded, integrity: row.phase === 'reserved' ? 'incomplete' : candidateIntegrity(db, row.generation, directory, description), currentTrustValidated: false }) | |
| 496 | } | |
| 497 | } | |
| 498 | return Object.freeze({ schema: 'drone-runtime-candidates-v1', stateFormat: databaseVersion(db) as 1 | 2, store: summary(db, binding, storeSha256), retainedCandidates: rows.length, history: Object.freeze(history), candidate, physicalDeploymentAllowed: false }) | |
| 499 | } | |
| 500 | ||
| 501 | /** Inspect owned host candidates. Recorded-byte integrity is not fresh selection or boot authorization. */ | |
| 502 | export async function inspectRuntimeFirmwareCandidates(options: StoreReference): Promise<Readonly<RuntimeFirmwareCandidates>> { | |
| 503 | return withStore(options, (db, binding, trusted, path) => candidatesSummary(db, binding, trusted, path, options.storeSha256)) | |
| 504 | } | |
| 505 | ||
| 506 | /** Release only the exact active candidate reservation. Retain its records and bytes; never reset trust floors. */ | |
| 507 | export async function retireRuntimeFirmwareCandidate(options: StoreReference & { candidateId: string, onProgress?: ProgressObserver }): Promise<Readonly<RuntimeFirmwareCandidates>> { | |
| 508 | options = { ...options } | |
| 509 | if (typeof options.candidateId !== 'string' || !/^[a-f0-9]{32}$/.test(options.candidateId)) throw new Error('Exact active candidate identity required') | |
| 510 | return withStore(options, async (db, binding, trusted, path) => { | |
| 511 | const current = candidatesSummary(db, binding, trusted, path, options.storeSha256) | |
| 512 | if (current.store.attempt?.phase === 'pending' || current.store.attempt?.phase === 'maintenance') throw new Error('Resolve the metadata attempt before candidate retirement') | |
| 513 | if (!current.candidate || current.candidate.id !== options.candidateId) throw new Error('Exact active candidate identity required') | |
| 514 | db.query("UPDATE candidates SET phase = 'retired' WHERE id = ? AND phase IN ('reserved', 'prepared')").run(options.candidateId) | |
| 515 | await options.onProgress?.(Object.freeze({ phase: 'candidate-retired', ordinal: 0 })) | |
| 516 | return candidatesSummary(db, binding, trusted, path, options.storeSha256) | |
| 517 | }) | |
| 518 | } | |
| 519 | ||
| 520 | /** Reserve one owned candidate and prepare signed bytes. No installed slot or health confirmation is changed. */ | |
| 521 | export async function reserveRuntimeFirmwareCandidate(options: RefreshOptions): Promise<Readonly<RuntimeFirmwareCandidates>> { | |
| 522 | options = { ...options } | |
| 523 | runtimeCandidateOutput(options.directory, [options.repository, options.enrollmentDirectory]) | |
| 524 | const result = await refreshAndComplete(options, async selection => { | |
| 525 | const { db, binding, trusted, path, attempt } = selection | |
| 526 | if (databaseVersion(db) === 1) { | |
| 527 | db.transaction(() => { for (const sql of candidateSchema) db.exec(sql); db.exec('PRAGMA user_version=2') })() | |
| 528 | checkSchema(db, [...schema, ...candidateSchema], 2) | |
| 529 | } | |
| 530 | const id = randomBytes(16).toString('hex'), description = candidateDescription(selection) | |
| 531 | const bytes = Buffer.from(`${JSON.stringify(description)}\n`), generation = state(db, binding).generation | |
| 532 | db.query("INSERT INTO candidates VALUES(?, ?, ?, 'reserved', ?, ?)").run(id, attempt, generation, bytes, sha256(bytes)) | |
| 533 | await options.onProgress?.(Object.freeze({ phase: 'candidate-reserved', ordinal: 0 })) | |
| 534 | const parent = join(path, 'candidates') | |
| 535 | if (!readdirSync(path).includes('candidates')) { mkdirSync(parent, { mode: 0o700 }); syncDirectory(path) } | |
| 536 | protectedDirectory(parent) | |
| 537 | const output = join(parent, id) | |
| 538 | await writePreparedCandidate(selection, output, options.onProgress) | |
| 539 | if (candidateIntegrity(db, generation, output, description) !== 'recorded-bytes-match') throw new Error('Owned candidate file readback failed') | |
| 540 | db.query("UPDATE candidates SET phase = 'prepared' WHERE id = ? AND phase = 'reserved'").run(id) | |
| 541 | await options.onProgress?.(Object.freeze({ phase: 'candidate-recorded', ordinal: 0 })) | |
| 542 | return candidatesSummary(db, binding, trusted, path, options.storeSha256) | |
| 543 | }, db => { | |
| 544 | const rows = candidateRows(db) | |
| 545 | if (rows.some(row => row.phase !== 'retired')) throw new Error('An active candidate requires explicit retirement or slot transition') | |
| 546 | if (rows.length >= 128) throw new Error('Candidate history budget reached') | |
| 547 | }) | |
| 548 | return Object.freeze({ ...result.value, store: result.store }) | |
| 549 | } | |
| 550 | ||
| 323 | 551 | function causedBy(error: unknown, marker: Error) { |
| 324 | 552 | const seen = new Set<unknown>() |
| 325 | 553 | for (let value = error; value instanceof Error && !seen.has(value) && seen.size < 8; value = Object.getOwnPropertyDescriptor(value, 'cause')?.value) { |