#!/usr/bin/env python3 """Build-time only: verify a combined package and assemble a private OCI image.""" import argparse import hashlib import json import os from pathlib import Path import re import shutil import stat import subprocess import tempfile import uuid REPO = Path(__file__).resolve().parents[1] NAME = 'strata-next-linux-x86_64-musl' FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'} # Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed. BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794' def digest(path): with path.open('rb') as source: return hashlib.file_digest(source, 'sha256').hexdigest() def frozen_file(source, dest, limit): fd = os.open(source, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) with os.fdopen(fd, 'rb') as src, dest.open('xb') as dst: if not stat.S_ISREG(os.fstat(src.fileno()).st_mode): raise ValueError('package entries must be regular files') total = 0 while block := src.read(65536): total += len(block) if total > limit: raise ValueError('package entry exceeds size limit') dst.write(block) def freeze(package, stage, receipt_sha, cpu_fixture): if not re.fullmatch(r'[0-9a-f]{64}', receipt_sha): raise ValueError('receipt SHA256 must be 64 lowercase hex characters') if {p.name for p in package.iterdir()} != FILES: raise ValueError('package must contain exactly binary, provenance and SHA256SUMS') for name in FILES: frozen_file(package / name, stage / name, 1024**3 if name == NAME else 1024**2) if digest(stage / 'SHA256SUMS') != receipt_sha: raise ValueError('pinned receipt SHA256 mismatch') hashes = {} for line in (stage / 'SHA256SUMS').read_text().splitlines(): match = re.fullmatch(r'([0-9a-f]{64}) (strata-next-linux-x86_64-musl|PROVENANCE.json)', line) if not match or match[2] in hashes: raise ValueError('invalid or duplicate receipt entry') hashes[match[2]] = match[1] if set(hashes) != {NAME, 'PROVENANCE.json'}: raise ValueError('incomplete receipt') if any(digest(stage / name) != sha for name, sha in hashes.items()): raise ValueError('package file checksum mismatch') p = json.loads((stage / 'PROVENANCE.json').read_text()) kind = 'cpu-fixture' if cpu_fixture else 'static-cuda-preview' if (not isinstance(p, dict) or type(p.get('schema_version')) is not int or p['schema_version'] != 1 or p.get('kind') != kind or p.get('target') != 'x86_64-unknown-linux-musl' or not re.fullmatch(r'[0-9a-f]{40}', p.get('source_revision', ''))): raise ValueError('unsupported package provenance or explicit fixture mode mismatch') engine = p.get('engine', {}) if (engine.get('embedded') is not True or engine.get('target_os') != 'linux' or engine.get('target_arch') != 'x86_64' or engine.get('declared_source_revision') != p['source_revision'] or type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or not re.fullmatch(r'[0-9a-f]{64}', engine.get('sha256', ''))): raise ValueError('invalid embedded engine identity') if not cpu_fixture: audit = p.get('engine_elf_audit', {}) if audit.get('toolkit_shared_libraries') is not False or audit.get('host_glibc_required') is not True: raise ValueError('missing static CUDA ELF audit') version(audit.get('minimum_glibc', '')) return p def version(value): if not isinstance(value, str) or not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', value): raise ValueError('invalid glibc version') return tuple(map(int, value.split('.'))) + (0,) * (3 - len(value.split('.'))) def check_glibc(provenance, output): match = re.fullmatch(r'glibc ([0-9]+\.[0-9]+(?:\.[0-9]+)?)\s*', output) if not match: raise ValueError('base does not report GNU glibc') minimum = provenance.get('engine_elf_audit', {}).get('minimum_glibc', '0.0') if version(match[1]) < version(minimum): raise ValueError(f'base glibc {match[1]} is below engine requirement {minimum}; choose a compatible pinned base or rebuild engine') return match[1] def docker(*args, timeout=30, check=True): return subprocess.run(['docker', *map(str, args)], capture_output=True, text=True, check=check, timeout=timeout) def isolated_run(image, arguments, *, entrypoint=None): name = 'strata-image-probe-' + uuid.uuid4().hex args = ['run', '--name', name, '--rm', '--platform', 'linux/amd64', '--network', 'none', '--read-only', '--user', '65532:65532', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void'] if entrypoint: args += ['--entrypoint', entrypoint] try: return docker(*args, image, *arguments).stdout finally: docker('rm', '-f', name, check=False) def assemble(args): if not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', args.base): raise ValueError('base must be an explicit lowercase repository@sha256 digest') image = None success = False with tempfile.TemporaryDirectory(prefix='strata-oci-') as tmp: stage = Path(tmp) p = freeze(args.package, stage, args.receipt_sha256, args.cpu_fixture) shutil.copyfile(REPO / 'deploy/Dockerfile.runtime', stage / 'Dockerfile') # Pull before timed probes, so network latency cannot masquerade as ABI failure. docker('pull', '--platform', 'linux/amd64', args.base, timeout=300) glibc = check_glibc(p, isolated_run(args.base, ['GNU_LIBC_VERSION'], entrypoint='getconf')) iid = stage / '.image-id' try: docker('build', '--platform', 'linux/amd64', '--network', 'none', '--build-arg', 'BASE=' + args.base, '--build-arg', 'BUILD_ID=' + uuid.uuid4().hex, '--build-arg', 'PACKAGE_KIND=' + p['kind'], '--iidfile', iid, stage, timeout=300) image = iid.read_text().strip() if not re.fullmatch(r'sha256:[0-9a-f]{64}', image): raise ValueError('invalid built image identity') info = json.loads(isolated_run(image, ['engine-info'])) if info != p['engine']: raise ValueError('image embedded metadata differs from pinned package') isolated_run(image, ['engine-help']) result = {'schema_version': 1, 'image': image, 'base': args.base, 'base_glibc': glibc, 'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'], 'kind': p['kind'], 'gpu_tested': False, 'model_tested': False, 'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'} success = True return result finally: if not success: # The unique build label makes this image ours, never a caller's tag. if image is None and iid.exists(): image = iid.read_text().strip() if image and re.fullmatch(r'sha256:[0-9a-f]{64}', image): docker('image', 'rm', image, check=False) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--package', type=Path, required=True) parser.add_argument('--receipt-sha256', required=True, help='trusted SHA256 of package SHA256SUMS') parser.add_argument('--base', default=BASE) parser.add_argument('--cpu-fixture', action='store_true') args = parser.parse_args() os.umask(0o077) try: print(json.dumps(assemble(args))) except (ValueError, OSError, subprocess.SubprocessError, KeyError, TypeError) as error: parser.exit(1, f'Runtime image assembly failed: {error}\n') if __name__ == '__main__': main()