build: assemble verified private Linux runtime packages

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 20:00:48 +02:00
parent 312948e9ef
commit edea410253
5 changed files with 366 additions and 8 deletions
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Offline release assembly; production serving has no Python dependency."""
import argparse
import contextlib
import ctypes
import stat
import fcntl
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[1]
TARGET = 'x86_64-unknown-linux-musl'
NAME = 'strata-next-linux-x86_64-musl'
LIMIT = 1024 ** 3
def run(args, **kwargs):
return subprocess.check_output([str(x) for x in args], text=True, **kwargs).strip()
def sha256(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def source_check(repo, revision):
if not re.fullmatch(r'[0-9a-f]{40}', revision):
raise ValueError('source revision must be a full lowercase Git SHA')
if run(['git', '-C', repo, 'rev-parse', 'HEAD']) != revision:
raise ValueError('source revision differs from checkout HEAD')
if run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=no']):
raise ValueError('tracked source changes must be committed before packaging')
def snapshot(source, dest, expected):
if not re.fullmatch(r'[0-9a-f]{64}', expected):
raise ValueError('engine SHA256 must be 64 lowercase hexadecimal characters')
digest, size = hashlib.sha256(), 0
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('engine must be a regular file')
while block := src.read(65536):
size += len(block)
if size > LIMIT:
raise ValueError('engine exceeds 1 GiB package limit')
digest.update(block)
dst.write(block)
if digest.hexdigest() != expected:
raise ValueError('engine SHA256 mismatch')
dest.chmod(0o700)
return size
def static_outer(binary):
headers = run(['readelf', '-lW', binary])
dynamic = run(['readelf', '-dW', binary])
if 'INTERP' in headers or '(NEEDED)' in dynamic:
raise ValueError('outer executable must be static musl (no INTERP/NEEDED)')
return {'program_headers': headers, 'dynamic_section': dynamic}
@contextlib.contextmanager
def lock(path):
# Caller-controlled build/output paths are private; keep the inode for reuse.
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
finally:
os.close(fd)
def publish(source, output):
# Linux atomic no-replace protects even against a non-cooperating publisher.
libc = ctypes.CDLL(None, use_errno=True)
rename = getattr(libc, 'renameat2', None)
if rename is None:
raise ValueError('host libc must provide renameat2 for safe publication')
rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
rename.restype = ctypes.c_int
if rename(-100, os.fsencode(source), -100, os.fsencode(output), 1) != 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
def assemble(args):
if platform.system() != 'Linux' or platform.machine() != 'x86_64':
raise ValueError('package assembly requires Linux x86_64')
source_check(REPO, args.revision)
output = args.output.absolute()
output.parent.mkdir(parents=True, exist_ok=True)
output = output.parent.resolve() / output.name
target_dir = args.cargo_target_dir.resolve()
if output == target_dir or output in target_dir.parents or target_dir in output.parents:
raise ValueError('package output and Cargo build directory must be disjoint')
target_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
with lock(output.parent / ('.' + output.name + '.package-lock')), lock(target_dir / '.package-lock'):
if os.path.lexists(output):
raise ValueError('output already exists; select a new versioned directory')
with tempfile.TemporaryDirectory(prefix='.' + output.name + '.stage-', dir=output.parent) as tmp:
stage = Path(tmp)
engine = stage / 'engine'
size = snapshot(args.engine.resolve(), engine, args.sha256)
if args.cpu_fixture:
audit = {'kind': 'cpu-fixture', 'gpu_tested': False}
else:
spec = importlib.util.spec_from_file_location('elf_audit', REPO / 'scripts/check-static-cuda-elf.py')
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
audit = checker.inspect(engine)
env = dict(os.environ, STRATA_EMBED_ENGINE_PATH=str(engine),
STRATA_EMBED_ENGINE_SHA256=args.sha256,
STRATA_EMBED_ENGINE_REVISION=args.revision,
CARGO_TARGET_DIR=str(target_dir), CUDA_VISIBLE_DEVICES='')
env.pop('LD_LIBRARY_PATH', None)
subprocess.run(['cargo', 'build', '--manifest-path', str(REPO / 'control-plane/Cargo.toml'),
'--locked', '--release', '--target', TARGET, '--bin', 'strata-next'],
env=env, check=True)
published = stage / 'package'
published.mkdir(mode=0o700)
binary = published / NAME
shutil.copyfile(target_dir / TARGET / 'release/strata-next', binary)
binary.chmod(0o700)
outer = static_outer(binary)
probe_env = {'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': ''}
info = json.loads(run([binary, 'engine-info'], env=probe_env, timeout=30))
if not (info['embedded'] and info['sha256'] == args.sha256 and
info['declared_source_revision'] == args.revision and info['bytes'] == size and
info['target_os'] == 'linux' and info['target_arch'] == 'x86_64'):
raise ValueError('combined engine identity does not match pinned input')
probe = stage / 'probe.json'
probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True}))
run([binary, 'provision', '--config', probe], env=probe_env, timeout=30)
source_check(REPO, args.revision)
provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview',
'source_revision': args.revision, 'target': TARGET, 'engine': info,
'engine_elf_audit': audit, 'outer_elf_audit': outer,
'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'),
'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']),
'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False,
'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.',
'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'}
(published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n')
(published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json']))
if os.path.lexists(output):
raise ValueError('output appeared during assembly; refusing replacement')
publish(published, output)
return {'output': str(output), 'kind': provenance['kind'], 'gpu_tested': False}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--engine', type=Path, required=True)
parser.add_argument('--sha256', required=True)
parser.add_argument('--revision', required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently')
parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release')
args = parser.parse_args()
try:
print(json.dumps(assemble(args)))
except (ValueError, OSError, subprocess.SubprocessError) as error:
parser.exit(1, f'Package assembly failed: {error}\n')
if __name__ == '__main__':
main()
+1
View File
@@ -10,6 +10,7 @@ python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py"
python3 "${repo_root}/scripts/test-model-switch.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Fault boundaries for offline package publication; real assembly runs in Linux CI."""
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py'))
pkg = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pkg)
class PackageTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
def test_snapshot_digest_exact_and_bad_pin(self):
source = self.root / 'engine'
payload = b'fixture' * 20000
source.write_bytes(payload)
digest = hashlib.sha256(payload).hexdigest()
out = self.root / 'copy'
self.assertEqual(pkg.snapshot(source, out, digest), len(payload))
self.assertEqual(out.read_bytes(), payload)
self.assertEqual(out.stat().st_mode & 0o777, 0o700)
for pin in ['0' * 64, 'bad']:
with self.assertRaises(ValueError):
pkg.snapshot(source, self.root / pin, pin)
def test_snapshot_rejects_oversize_and_nonregular_without_block(self):
source = self.root / 'engine'
source.write_bytes(b'over limit')
with patch.object(pkg, 'LIMIT', 4), self.assertRaisesRegex(ValueError, 'limit'):
pkg.snapshot(source, self.root / 'copy', hashlib.sha256(source.read_bytes()).hexdigest())
fifo = self.root / 'pipe'
os.mkfifo(fifo)
with self.assertRaisesRegex(ValueError, 'regular'):
pkg.snapshot(fifo, self.root / 'fifo-copy', '0' * 64)
def test_source_pin_and_dirty_tree(self):
subprocess.run(['git', 'init', '-q', self.root], check=True)
(self.root / 'source').write_text('initial')
subprocess.run(['git', '-C', self.root, 'add', '.'], check=True)
subprocess.run(['git', '-C', self.root, '-c', 'user.email=fixture@example.invalid', '-c',
'user.name=Fixture', 'commit', '-qm', 'fixture'], check=True)
revision = pkg.run(['git', '-C', self.root, 'rev-parse', 'HEAD'])
pkg.source_check(self.root, revision)
for wrong in ['bad', '0' * 40]:
with self.assertRaises(ValueError):
pkg.source_check(self.root, wrong)
(self.root / 'source').write_text('changed')
with self.assertRaisesRegex(ValueError, 'committed'):
pkg.source_check(self.root, revision)
def test_lock_excludes_other_builder_and_symlink(self):
path = self.root / 'lock'
with pkg.lock(path), self.assertRaises(BlockingIOError):
with pkg.lock(path):
self.fail('second writer acquired lock')
alias = self.root / 'alias'
alias.symlink_to(path)
with self.assertRaises(OSError):
with pkg.lock(alias):
self.fail('symlink lock accepted')
@unittest.skipUnless(sys.platform == 'linux', 'Linux atomic publication')
def test_atomic_publication_never_replaces_existing_directory(self):
staged, output = self.root / 'stage', self.root / 'out'
staged.mkdir()
(staged / 'sentinel').write_text('new')
output.mkdir()
with self.assertRaises(FileExistsError):
pkg.publish(staged, output)
self.assertEqual(list(output.iterdir()), [])
output.rmdir()
pkg.publish(staged, output)
self.assertFalse(staged.exists())
self.assertEqual((output / 'sentinel').read_text(), 'new')
def test_outer_elf_rejects_loader_or_shared_library(self):
for outputs in [('INTERP', ''), ('', '(NEEDED)')]:
with patch.object(pkg, 'run', side_effect=outputs), self.assertRaises(ValueError):
pkg.static_outer(Path('fixture'))
with patch.object(pkg, 'run', side_effect=['static headers', 'no dynamic section']):
self.assertIn('program_headers', pkg.static_outer(Path('fixture')))
def test_failed_build_cleans_stage_and_does_not_publish(self):
from types import SimpleNamespace
engine = self.root / 'engine'
engine.write_bytes(b'fixture')
output = self.root / 'final'
args = SimpleNamespace(engine=engine, sha256=pkg.sha256(engine), revision='a' * 40,
output=output, cargo_target_dir=self.root / 'target', cpu_fixture=True)
with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'cargo')):
with self.assertRaises(subprocess.CalledProcessError):
pkg.assemble(args)
self.assertFalse(output.exists())
self.assertFalse(list(self.root.glob('.final.stage-*')))
output.mkdir()
(output / 'old').write_text('keep')
with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run') as build:
with self.assertRaisesRegex(ValueError, 'already exists'):
pkg.assemble(args)
build.assert_not_called()
self.assertEqual((output / 'old').read_text(), 'keep')
if __name__ == '__main__':
unittest.main()