feat(deploy): assemble verified combined runtime OCI image
This commit is contained in:
@@ -63,6 +63,16 @@ jobs:
|
||||
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
|
||||
--cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \
|
||||
--output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
|
||||
- name: Build compatible private runtime image without GPU inference
|
||||
run: |
|
||||
package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
|
||||
python3 scripts/build-runtime-image.py --package "$package" \
|
||||
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
|
||||
> "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
|
||||
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")"
|
||||
docker save --output "$package/runtime-image.tar" "$image"
|
||||
cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json"
|
||||
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: strata-next-static-cuda-preview
|
||||
@@ -71,6 +81,15 @@ jobs:
|
||||
retention-days: 7
|
||||
- name: Remove uploaded package copy
|
||||
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
|
||||
- name: Remove owned runtime image
|
||||
if: always()
|
||||
run: |
|
||||
receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
|
||||
if test -s "$receipt"; then
|
||||
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
|
||||
docker image rm "$image"
|
||||
rm "$receipt"
|
||||
fi
|
||||
- name: Remove private build intermediates
|
||||
if: always()
|
||||
run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}"
|
||||
@@ -161,7 +180,20 @@ jobs:
|
||||
sha256sum -c SHA256SUMS
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
python3 scripts/smoke-embedded-engine.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" "$RUNNER_TEMP/embedded-worker"
|
||||
python3 scripts/build-runtime-image.py --cpu-fixture --package "$RUNNER_TEMP/combined-fixture" \
|
||||
--receipt-sha256 "$(sha256sum "$RUNNER_TEMP/combined-fixture/SHA256SUMS" | cut -d ' ' -f 1)" \
|
||||
> "$RUNNER_TEMP/combined-image.json"
|
||||
python3 scripts/smoke-runtime-image.py "$RUNNER_TEMP/combined-image.json"
|
||||
rm "$RUNNER_TEMP/embedded-worker"
|
||||
- name: Remove owned CPU fixture image
|
||||
if: always()
|
||||
run: |
|
||||
receipt="$RUNNER_TEMP/combined-image.json"
|
||||
if test -s "$receipt"; then
|
||||
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
|
||||
docker image rm "$image"
|
||||
rm "$receipt"
|
||||
fi
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: strata-next-linux-x86_64-musl
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Built only from the private, validated context produced by build-runtime-image.py.
|
||||
ARG BASE
|
||||
FROM ${BASE}
|
||||
ARG BUILD_ID
|
||||
ARG PACKAGE_KIND
|
||||
LABEL io.strata.build-id=${BUILD_ID} io.strata.package-kind=${PACKAGE_KIND}
|
||||
COPY --chmod=0555 strata-next-linux-x86_64-musl /usr/local/bin/strata-next
|
||||
COPY --chmod=0444 PROVENANCE.json SHA256SUMS /usr/share/strata/
|
||||
ENV NVIDIA_VISIBLE_DEVICES=void NVIDIA_DRIVER_CAPABILITIES=compute,utility STRATA_BIND=0.0.0.0:8081
|
||||
USER 65532:65532
|
||||
WORKDIR /tmp
|
||||
EXPOSE 8081
|
||||
STOPSIGNAL SIGTERM
|
||||
ENTRYPOINT ["/usr/local/bin/strata-next"]
|
||||
CMD ["serve"]
|
||||
@@ -666,3 +666,52 @@ A successful package build does not pass the clean-node real-model gate: the
|
||||
inner engine still requires the recorded host glibc and NVIDIA driver, and lazy
|
||||
CUDA dependencies, kernels, model/MTP compatibility and quality need separate
|
||||
qualification. Existing active endpoints are not modified by this build tool.
|
||||
|
||||
## Combined runtime OCI preview (STRA-67)
|
||||
|
||||
Build a private image from a trusted STRA-65 combined package (exactly the
|
||||
executable, `PROVENANCE.json`, and `SHA256SUMS`):
|
||||
|
||||
```sh
|
||||
python3 scripts/build-runtime-image.py --package /private/package \
|
||||
--receipt-sha256 <trusted-SHA256-of-SHA256SUMS> > /private/image.json
|
||||
```
|
||||
|
||||
The builder freezes and verifies the three files before Docker receives a minimal
|
||||
context. An official Ubuntu 26.04 **linux/amd64 manifest digest** is the default
|
||||
base; its actual `getconf GNU_LIBC_VERSION` reports 2.43 in the isolated validation.
|
||||
`--base repository@sha256:DIGEST` permits another explicitly pinned glibc image.
|
||||
A base below the engine's recorded minimum glibc is rejected before image build.
|
||||
Embedded identity and GPU-hidden `engine-help` are checked inside the resulting
|
||||
non-root, read-only image. The image ID is returned only after these checks;
|
||||
failed probes remove the uniquely labelled build image. No public registry push
|
||||
occurs. Python and Docker are build tools, not serving dependencies.
|
||||
|
||||
Run the image ID with NVIDIA Container Toolkit and a compatible installed host
|
||||
driver. The caller supplies private configuration, source/model data, and a
|
||||
writable state directory owned by UID 65532. Example paths inside the configuration
|
||||
must match these mount destinations:
|
||||
|
||||
```sh
|
||||
docker run --rm --gpus all --read-only --cap-drop ALL \
|
||||
--security-opt no-new-privileges --tmpfs /tmp:rw,nosuid,nodev,size=256m \
|
||||
-e NVIDIA_VISIBLE_DEVICES=all -p 127.0.0.1:8081:8081 \
|
||||
--mount type=bind,src=/private/config,dst=/config,readonly \
|
||||
--mount type=bind,src=/private/models,dst=/models,readonly \
|
||||
--mount type=bind,src=/private/state,dst=/state \
|
||||
sha256:IMAGE_ID serve --config /config/runtime.json
|
||||
```
|
||||
|
||||
The runtime uses its native `@embedded` engine and existing asset/native-model
|
||||
configuration. Set the profile's explicit GPU requirement and `engine_probe`;
|
||||
keep the key file private and readable by the container UID. Network access is
|
||||
needed for configured acquisition; use verified offline assets to avoid it.
|
||||
Do not mount the Docker socket or include models, keys, logs or configuration in
|
||||
the build context. The default image exposes no GPU unless requested explicitly.
|
||||
|
||||
The hosted CPU path uses `--cpu-fixture` and verifies actual Responses output `A`,
|
||||
worker crash/restart and graceful shutdown in the image, with zero tolerance.
|
||||
The manual private CUDA job now saves the image and provenance alongside the
|
||||
combined package. Neither CPU success nor hidden-GPU help qualifies CUDA kernels,
|
||||
lazy driver dependencies, real model/MTP compatibility, quality or clean-node GPU
|
||||
serving. That full gate remains pending; the active user trial is not migrated.
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/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 (p.get('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()
|
||||
@@ -11,6 +11,7 @@ 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-runtime-image.py"
|
||||
python3 "${repo_root}/scripts/test-keyless-routing.py"
|
||||
|
||||
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Actual combined CPU image proof. Never use with a model/CUDA image."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def docker(*args, check=True):
|
||||
return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30)
|
||||
|
||||
|
||||
def main(receipt):
|
||||
proof = json.loads(Path(receipt).read_text())
|
||||
assert proof['kind'] == 'cpu-fixture' and proof['gpu_tested'] is False
|
||||
image = proof['image']
|
||||
label = docker('inspect', '--format', '{{index .Config.Labels "io.strata.package-kind"}}', image).stdout.strip()
|
||||
assert label == 'cpu-fixture'
|
||||
spec = importlib.util.spec_from_file_location('helper', Path(__file__).with_name('smoke-worker-cancel.py'))
|
||||
helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper)
|
||||
name = 'strata-runtime-smoke-' + uuid.uuid4().hex
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp:
|
||||
root = Path(tmp); root.chmod(0o755)
|
||||
helper.tokenizer(root)
|
||||
(root/'config.json').write_text(json.dumps({'bind': '0.0.0.0:8081', 'model': 'embedded-fixture',
|
||||
'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'],
|
||||
'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}}))
|
||||
for path in root.iterdir(): path.chmod(0o644)
|
||||
try:
|
||||
docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only',
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=',
|
||||
'-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081',
|
||||
'--mount', f'type=bind,src={root},dst=/fixture,readonly', image,
|
||||
'serve', '--config', '/fixture/config.json')
|
||||
port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1])
|
||||
def request(route, body=None):
|
||||
req = urllib.request.Request(f'http://127.0.0.1:{port}{route}',
|
||||
data=json.dumps(body).encode() if body else None, headers={'Content-Type': 'application/json'})
|
||||
with opener.open(req, timeout=5) as response: return json.load(response)
|
||||
def ready():
|
||||
deadline = time.monotonic()+15
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
if request('/status')['ready']: return
|
||||
except OSError: pass
|
||||
time.sleep(.1)
|
||||
raise AssertionError('container worker did not become ready')
|
||||
def generate():
|
||||
result = request('/v1/responses', {'model':'embedded-fixture','input':'Reply A',
|
||||
'max_output_tokens':1,'reasoning':{'effort':'none'}})
|
||||
assert result['status']=='completed'
|
||||
assert result['output'][0]['content'][0]['text']=='A'
|
||||
ready(); generate()
|
||||
before = docker('exec', name, 'cat', '/tmp/worker.pid').stdout.strip()
|
||||
docker('exec', name, 'kill', '-KILL', before)
|
||||
deadline = time.monotonic()+15
|
||||
while docker('exec', name, 'cat', '/tmp/worker.pid').stdout.strip()==before:
|
||||
assert time.monotonic()<deadline
|
||||
time.sleep(.1)
|
||||
ready(); generate()
|
||||
docker('stop', '--time', '10', name)
|
||||
state = json.loads(docker('inspect','--format','{{json .State}}',name).stdout)
|
||||
assert state['ExitCode']==0 and not state['OOMKilled']
|
||||
print('Combined CPU OCI: Responses A exact, worker crash/restart A exact, nonroot/read-only, graceful stop. No GPU/model qualification.')
|
||||
finally:
|
||||
docker('rm','-f',name,check=False)
|
||||
|
||||
|
||||
if __name__=='__main__': main(sys.argv[1])
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package corruption and ABI rejection without Docker or GPU access."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('builder', Path(__file__).with_name('build-runtime-image.py'))
|
||||
b = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(b)
|
||||
|
||||
|
||||
class PackageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
root = Path(self.tmp.name)
|
||||
self.pkg, self.stage = root/'package', root/'stage'
|
||||
self.pkg.mkdir(); self.stage.mkdir()
|
||||
self.provenance = {'schema_version': 1, 'kind': 'static-cuda-preview',
|
||||
'source_revision': 'a'*40, 'target': 'x86_64-unknown-linux-musl',
|
||||
'engine': {'embedded': True, 'target_os': 'linux', 'target_arch': 'x86_64',
|
||||
'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64},
|
||||
'engine_elf_audit': {'toolkit_shared_libraries': False,
|
||||
'host_glibc_required': True, 'minimum_glibc': '2.43'}}
|
||||
(self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input')
|
||||
self.write()
|
||||
|
||||
def write(self):
|
||||
(self.pkg/'PROVENANCE.json').write_text(json.dumps(self.provenance))
|
||||
(self.pkg/'SHA256SUMS').write_text(''.join(f'{b.digest(self.pkg/n)} {n}\n' for n in (b.NAME, 'PROVENANCE.json')))
|
||||
self.sha = b.digest(self.pkg/'SHA256SUMS')
|
||||
|
||||
def freeze(self, fixture=False):
|
||||
return b.freeze(self.pkg, self.stage, self.sha, fixture)
|
||||
|
||||
def test_frozen_bytes_and_explicit_abi_gate(self):
|
||||
p = self.freeze()
|
||||
(self.pkg/b.NAME).write_bytes(b'modified source after freeze')
|
||||
self.assertNotEqual((self.pkg/b.NAME).read_bytes(), (self.stage/b.NAME).read_bytes())
|
||||
self.assertEqual(b.check_glibc(p, 'glibc 2.43\n'), '2.43')
|
||||
with self.assertRaisesRegex(ValueError, 'below engine'):
|
||||
b.check_glibc(p, 'glibc 2.39\n')
|
||||
with self.assertRaises(ValueError): b.check_glibc(p, 'musl 1.2.5')
|
||||
|
||||
def test_pinned_receipt_rejects_replaced_hashes(self):
|
||||
(self.pkg/'SHA256SUMS').write_text('a'*64 + ' ../outside\n')
|
||||
with self.assertRaisesRegex(ValueError, 'pinned receipt'): self.freeze()
|
||||
|
||||
def test_corrupt_binary(self):
|
||||
(self.pkg/b.NAME).write_bytes(b'corruption')
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'): self.freeze()
|
||||
|
||||
def test_duplicate_or_traversal_receipt_even_with_matching_pin(self):
|
||||
for data in ['a'*64+' ../outside\n', (self.pkg/'SHA256SUMS').read_text()*2]:
|
||||
with self.subTest(data=data), tempfile.TemporaryDirectory() as stage:
|
||||
(self.pkg/'SHA256SUMS').write_text(data)
|
||||
with self.assertRaisesRegex(ValueError, 'receipt'):
|
||||
b.freeze(self.pkg, Path(stage), b.digest(self.pkg/'SHA256SUMS'), False)
|
||||
|
||||
def test_no_extra_files_or_symlinks(self):
|
||||
extra = self.pkg/'private-model'
|
||||
extra.write_text('fixture')
|
||||
with self.assertRaisesRegex(ValueError, 'exactly'): self.freeze()
|
||||
extra.unlink()
|
||||
(self.pkg/b.NAME).unlink()
|
||||
(self.pkg/b.NAME).symlink_to('/dev/null')
|
||||
with self.assertRaises(OSError): self.freeze()
|
||||
|
||||
def test_fixture_requires_explicit_flag_and_architecture_is_checked(self):
|
||||
self.provenance['kind'] = 'cpu-fixture'; self.write()
|
||||
with self.assertRaisesRegex(ValueError, 'fixture mode'): self.freeze()
|
||||
with tempfile.TemporaryDirectory() as stage:
|
||||
self.assertEqual(b.freeze(self.pkg, Path(stage), self.sha, True)['kind'], 'cpu-fixture')
|
||||
self.provenance['engine']['target_arch'] = 'aarch64'; self.write()
|
||||
with tempfile.TemporaryDirectory() as stage:
|
||||
with self.assertRaisesRegex(ValueError, 'identity'): b.freeze(self.pkg, Path(stage), self.sha, True)
|
||||
|
||||
def test_missing_elf_audit_and_size_bound(self):
|
||||
self.provenance['engine_elf_audit'] = {}; self.write()
|
||||
with self.assertRaisesRegex(ValueError, 'ELF audit'): self.freeze()
|
||||
with tempfile.TemporaryDirectory() as stage:
|
||||
with self.assertRaisesRegex(ValueError, 'size limit'):
|
||||
b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user