Skill Tracer
Skills › gstack › gstack › cso-requalification.ts

cso-requalification.ts

101 lines · scripts/cso-requalification.ts at 3f79d81

1#!/usr/bin/env -S bun --no-env-file --config=/dev/null
2/**
3 * Requalification triggers: the inputs a runtime qualification was measured
4 * under. A promoted catalog records them; a catalog whose recorded triggers
5 * differ from the current source is older than its inputs and must be
6 * requalified (or its runtimes withdrawn) before it ships.
7 */
8import { spawnSync } from 'node:child_process';
9import * as fs from 'node:fs';
10import * as os from 'node:os';
11import * as path from 'node:path';
12import { canonical, sha256 } from '../lib/cso/contracts';
13import { ISOLATION_POLICY_HASH } from '../lib/cso/docker';
14import { CSO_HELPER_ABI, isEvaluationRuntimeCatalog, type RequalificationTriggers, type RuntimeCatalog } from '../lib/cso/runtime-catalog';
16const ROOT = path.resolve(import.meta.dir, '..');
17/** Compiled into every runtime image as gstack-cso-verifier and gstack-cso-preparation. */
18export const IMAGE_HELPER_ENTRYPOINTS = ['lib/cso/verifier.ts', 'lib/cso/preparation-container.ts'] as const;
19export const IMAGE_CONTEXT = 'lib/cso/images';
20/** Image-context files that describe qualification rather than enter an image; build-inputs.json is its own trigger. */
21const IMAGE_CONTEXT_EXCLUDED = new Set(['README.md', 'qualification.json', 'build-inputs.json']);
23/** Every repository file whose bytes enter a runtime image: the helpers' import closure plus the image build context. */
24export async function imageSourceFiles(root = ROOT): Promise<string[]> {
25 const build = await Bun.build({ entrypoints: IMAGE_HELPER_ENTRYPOINTS.map(entry => path.join(root, entry)), target: 'bun', metafile: true });
26 if (!build.success || !build.metafile) throw new Error('REQUALIFICATION_SOURCE_CLOSURE_FAILED');
27 // Bun reports metafile inputs relative to the process working directory, not to the entrypoints.
28 const closure = Object.keys(build.metafile.inputs).map(input => path.relative(root, path.resolve(process.cwd(), input)).split(path.sep).join('/'));
29 if (closure.some(file => file.startsWith('..') || file.includes('node_modules/'))) throw new Error('REQUALIFICATION_SOURCE_OUTSIDE_REPOSITORY');
30 const context = fs.readdirSync(path.join(root, IMAGE_CONTEXT), { withFileTypes: true })
31 .filter(entry => entry.isFile() && !IMAGE_CONTEXT_EXCLUDED.has(entry.name))
32 .map(entry => `${IMAGE_CONTEXT}/${entry.name}`);
33 return [...new Set([...closure, ...context])].sort();
36/**
37 * Digest of every image source byte. A compiled helper's leading `#!` line never
38 * runs inside the image, so it is hashed as absent; every other byte counts.
39 * `legacy` hashes the shebang too, the rule staging runs recorded before this normalization (through run 39325583697).
40 */
41function preparationSha256(root: string, files: string[], legacy = false): string {
42 const helpers = new Set<string>(IMAGE_HELPER_ENTRYPOINTS);
43 return sha256(canonical(files.map(file => {
44 const bytes = fs.readFileSync(path.join(root, file));
45 if (legacy || !helpers.has(file) || bytes[0] !== 0x23 || bytes[1] !== 0x21) return [file, sha256(bytes)];
46 const newline = bytes.indexOf(0x0a);
47 return [file, sha256(newline === -1 ? Buffer.alloc(0) : bytes.subarray(newline + 1))];
48 })));
51/** preparationSha256 of a committed tree under the current rule and the legacy rule. */
52export async function committedPreparation(commit: string, root = ROOT): Promise<{ current: string; legacy: string }> {
53 if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error('INVALID_STAGED_COMMIT');
54 const archive = spawnSync('git', ['-C', root, 'archive', '--format=tar', commit], { timeout: 60_000, maxBuffer: 512 * 1024 * 1024 });
55 if (archive.status !== 0) throw new Error(`STAGED_COMMIT_UNAVAILABLE: ${commit} is not in this checkout; fetch full history`);
56 const tree = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-staged-source-'));
57 try {
58 const extract = spawnSync('tar', ['-x', '-C', tree], { input: archive.stdout, timeout: 60_000 });
59 if (extract.status !== 0) throw new Error('STAGED_COMMIT_UNAVAILABLE: archive extraction failed');
60 const files = await imageSourceFiles(tree);
61 return { current: preparationSha256(tree, files), legacy: preparationSha256(tree, files, true) };
62 } finally {
63 fs.rmSync(tree, { recursive: true, force: true });
64 }
67export async function requalificationTriggers(root = ROOT): Promise<RequalificationTriggers> {
68 const files = await imageSourceFiles(root);
69 const buildInputs = JSON.parse(fs.readFileSync(path.join(root, IMAGE_CONTEXT, 'build-inputs.json'), 'utf8'));
70 if (typeof buildInputs?.revision !== 'string' || !buildInputs.revision) throw new Error('INVALID_BUILD_INPUTS_REVISION');
71 return {
72 helperAbi: CSO_HELPER_ABI,
73 isolationPolicyHash: ISOLATION_POLICY_HASH,
74 preparationSha256: preparationSha256(root, files),
75 buildInputsRevision: buildInputs.revision,
76 };
79/** Names of the triggers that changed since the catalog's runtimes were qualified; empty when nothing is promoted. */
80export function staleRequalificationTriggers(catalog: RuntimeCatalog, current: RequalificationTriggers): string[] {
81 if (isEvaluationRuntimeCatalog(catalog) || catalog.runtimes.length === 0) return [];
82 const recorded = catalog.promotion?.requalification;
83 if (!recorded) return Object.keys(current).sort();
84 return (Object.keys(current) as Array<keyof RequalificationTriggers>).filter(key => recorded[key] !== current[key]).sort();
87if (import.meta.main) {
88 try {
89 const [command, file, ...rest] = process.argv.slice(2);
90 if (command === 'triggers' && file === undefined) {
91 process.stdout.write(JSON.stringify(await requalificationTriggers(), null, 2) + '\n');
92 } else if (command === 'check' && file && rest.length === 0) {
93 const stale = staleRequalificationTriggers(JSON.parse(fs.readFileSync(path.resolve(file), 'utf8')), await requalificationTriggers());
94 if (stale.length) throw new Error(`STALE_RUNTIME_QUALIFICATION: ${stale.join(', ')} changed since qualification; requalify the runtimes or withdraw them from the catalog`);
95 process.stdout.write('REQUALIFICATION CURRENT\n');
96 } else throw new Error('Usage: cso-requalification.ts triggers | check <runtime-catalog.json>');
97 } catch (error) {
98 process.stderr.write((error instanceof Error ? error.message : 'REQUALIFICATION_CHECK_FAILED') + '\n');
99 process.exitCode = 1;
100 }