Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix(release): build and verify Linux packages for glibc 2.31 (#63)

澄潭b79567c66ff3
diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml
index abe69c93..5bb7b10b 100644
--- a/.github/workflows/build-release.yml
+++ b/.github/workflows/build-release.yml
@@ -31,9 +31,9 @@ jobs:
with:
ref: ${{ github.sha }}
persist-credentials: false
- - name: Linux build prerequisites
+ - name: Linux container host
if: runner.os == 'Linux'
- run: sudo apt-get update && sudo apt-get install --yes cmake clang pkg-config libssl-dev binutils
+ run: docker version
- name: Mac build prerequisites
if: runner.os == 'macOS'
run: command -v cmake >/dev/null || brew install cmake
@@ -81,6 +81,9 @@ jobs:
target/release-candidate/**/assets/*
target/release-candidate/**/result.json
target/release-candidate/**/build.log
+ target/release-candidate/**/linux-abi.json
+ target/release-candidate/**/runtime/*.log
+ target/release-candidate/**/runtime/diagnostics/**/*.jsonl
target/release-candidate/**/*.provenance.json
target/desktop-package/**/result.json
target/desktop-package/**/build.log
diff --git a/docs/code-map/README.md b/docs/code-map/README.md
index 855cb47c..79165e81 100644
--- a/docs/code-map/README.md
+++ b/docs/code-map/README.md
@@ -28,7 +28,7 @@ results in the relevant run record.
| Delegate, read, cancel or continue a Worker task | [Worker lifecycle and native differences](worker-context.md#follow-a-task-through-its-owners) | [Delegation](../../tools/product-e2e/tests/worker_delegation.rs), [read/Continue](../../tools/product-e2e/tests/worker_read.rs) |
| Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Session queries](../../crates/observation/src/query_v2/sessions_tests.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) |
| Manage the service through CLI or Desktop | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [daemon control](../../crates/daemon/src/control) | [Real control process](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) |
-| Build macOS / Linux release installers for either architecture | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md) | [Package-to-publication contract](../../scripts/test-build-release.py); final publishing remains in [release.yml](../../.github/workflows/release.yml) |
+| Build macOS / Linux release installers for either architecture | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md) | [Package-to-publication contract](../../scripts/test-build-release.py), [Linux ABI and installed-runtime gate](../../scripts/linux-release-baseline.json); final publishing remains in [release.yml](../../.github/workflows/release.yml) |
## Read across boundaries
diff --git a/docs/release-builds.md b/docs/release-builds.md
index 219220ce..81c90554 100644
--- a/docs/release-builds.md
+++ b/docs/release-builds.md
@@ -17,7 +17,10 @@ candidate metadata is input for review, never an automatically published release
Use the intended native platform with the repository Rust toolchain, Node 22+
(Desktop and packaging regression checks), Go matching the pinned CPA source,
-sccache and native build tools (including `readelf` on Linux).
+sccache and native build tools. Linux additionally requires Docker: the same
+command enters the pinned glibc 2.31 build image and then a separate minimal
+runtime image. Host distribution libraries are never used as the release ABI
+baseline. The native architecture check applies to the host and both containers.
The CPA checkout must contain the commit in `vendor/cpa/source.json`; its current
branch does not select the source. Invoke from the clean candidate checkout:
@@ -40,16 +43,95 @@ Each attempt is retained under `target/release-candidate/SHA/TARGET/ROUND/`.
`assets/` contains the DMG or archive plus companion manifest; `result.json`
records the full source revision, host, checks, timing, and the measured
`website_artifact` row. `build.log` retains subprocess output. No installer is
-uploaded, no user installation is changed, and no product service is started.
+uploaded and no existing user installation is changed. Linux acceptance installs
+into a temporary private HOME and starts/stops its own daemon inside an isolated
+container; the HOME is removed afterwards. Logs and package evidence are retained.
## Hosted build and publication
Run the **build-release-candidates** workflow on the public candidate branch.
Every matrix job checks out the dispatch's exact `github.sha`, uses a native
-runner and uploads its own assets and evidence. Linux uses Ubuntu 22.04 to avoid
-implicitly raising the distribution's glibc baseline to a newer runner image.
-The Linux result records ELF dependencies and symbol versions for checking the
-deployment image's library requirements.
+runner and uploads its own assets and evidence. Ubuntu runner labels select only
+the native Docker host. Both Linux architectures build against Debian 11 / glibc
+2.31 using the digest-pinned images and dated Debian and Debian-security package
+snapshots in
+[`linux-release-baseline.json`](../scripts/linux-release-baseline.json). The Rust
+toolchain remains pinned by `rust-toolchain.toml`, Cargo stays locked, and Go uses
+the pinned CPA source's toolchain declaration. Host Rust/Go tools are mounted into
+the build image; actual tool versions are retained in provenance. sccache shares
+compiler objects, while the checkout retains its default `target/`. The actual
+build image digest and fixed recipe bind the target directory to its build
+environment. Automatic BuildKit attestations are disabled for this local
+toolchain image so repeated builds retain a stable digest across Docker image
+stores; our recipe, image identity and measured toolchain provenance are retained.
+An invalid image digest stops the build. A different baseline, an older target stamp or
+pre-existing unattested release output requires a fresh worktree.
+Both package sources use the same fixed timestamp. The security source supplies
+matching libc build dependencies for the security-updated base image, including
+the amd64 clang toolchain's `libc6-i386` dependency.
+The container preserves an explicit positive `CARGO_BUILD_JOBS` from the caller;
+otherwise it uses two compiler workers. Managed workbench callers must retain
+their existing capacity reservation throughout the build.
+Already-set standard proxy variables are forwarded by name to Docker's recipe
+and compiler containers, including upper/lower-case HTTP, HTTPS, FTP, ALL and
+NO_PROXY. Docker reads the values from the inherited client environment; values
+are not command arguments or recorded provenance fields. The recipe uses Docker's
+predefined proxy build arguments, which exclude them from image history/cache
+metadata. Both native Linux build stages use the host network so existing
+loopback proxies remain reachable. The minimum runtime has no proxy forwarding
+and keeps network disabled.
+The compiler's sccache server uses a Unix socket in its private container
+filesystem, preserving the mounted object cache without contacting the host's
+existing cache service. Host sccache IPC variables are not forwarded.
+The mounted caller-selected sccache takes precedence over executables in the
+mounted Cargo HOME, so server startup and compiler requests use the same tool.
+
+The minimum distribution baseline is glibc 2.31 for **each** of x86_64 and aarch64.
+The archive ABI gate checks every ELF payload (including CPA and any future
+packaged dynamic library) after verifying the manifest, inventory and digests.
+It rejects wrong architecture, unexpected loaders/libraries, build-host search
+paths, newer loader tags, unknown symbol namespaces and symbol requirements above
+the recorded GLIBC/GLIBCXX/CXXABI/GCC/OpenSSL floors. Static executables pass without
+inventing a dynamic loader requirement. Library definitions are not confused with
+required versions. A rejected file and symbol version appear in failure evidence.
+The current package inventory contains no additional shared libraries; extending
+that inventory still requires the existing packager/installer contract change.
+
+A separate digest-pinned slim runtime image receives only the verified archive,
+installer and test driver. It runs the production installer in a fresh HOME,
+checks installed binary hashes, resolves dynamic dependencies eagerly, executes
+CLI root help and CPA help, starts `hiroute service run`, verifies real
+`system status` and `gateway show` replies twice across a resident daemon, and
+requires both management replies to remain healthy in the second round, and
+requires orderly SIGTERM shutdown with management and the Gateway listener no
+longer available. Its disposable HOME contains Debug diagnostic settings; the
+measured `level_applied` record must confirm Debug. Cleanup stops the process
+before removing the HOME, retaining safe daemon JSONL on failures. Missing
+runtime libraries fail here even if they existed in the build image. The runtime
+has no external network and does not make model calls.
+
+The CLI has no `--version` command. Release version identity comes from the
+verified archive manifest and matching installation ownership marker, with
+installed binary hashes checked against that manifest. Every real management
+call also uses the production client's version handshake, which requires the
+daemon and release versions to equal the CLI's compiled release version.
+
+Linux installation creates missing state parents with mode 0700, including the
+default `.local/state` chain and an explicitly selected absolute XDG state path.
+It preserves safe existing ancestor permissions and refuses symlinks or writable
+non-sticky ancestors, rather than changing the caller's umask or unsafe paths.
+This keeps the production diagnostic writer usable under a group-writable umask.
+
+`result.json` distinguishes the execution host, fixed build baseline and measured
+per-architecture runtime result; `linux-abi.json` binds symbol evidence to the exact
+archive and manifest hashes, source revision and target. Runtime verification also
+matches the ABI baseline and installed payload hashes. The package remains
+`awaiting_runtime` until the minimum environment
+passes. A help-only probe, x86_64 success, or successful archive checks never establish
+aarch64 runtime compatibility. Release acceptance additionally needs a protected
+API-key model call on the intended deployment host, using the same frozen archive;
+that live result is separate from the offline build gate. Rebuild after integrating
+product fixes and retain each result at its actual source revision.
1. Require all four matrix jobs to succeed for the same SHA. Keep the exact source
commit available; internal master and an exported public commit may differ.
diff --git a/scripts/build-release.py b/scripts/build-release.py
index fa5a6f7c..6cedf8e2 100644
--- a/scripts/build-release.py
+++ b/scripts/build-release.py
@@ -58,7 +58,7 @@ class Candidate:
"libc": platform.libc_ver()},
"status": "failed", "timings": []}
self.environment = dict(os.environ, RUSTC_WRAPPER="sccache", CARGO_INCREMENTAL="0",
- HIROUTE_BUILD_SOURCE_SHA=self.revision)
+ HIROUTE_BUILD_SOURCE_SHA=self.revision, LC_ALL="C")
def run(self, *arguments, env=None, timeout=None):
started = time.monotonic()
@@ -88,6 +88,12 @@ class Candidate:
metadata = json.loads(self.run("cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"))
if Path(metadata["target_directory"]).resolve() != REPO / "target":
raise ValueError("Cargo config must use checkout-local target/")
+ if self.target.endswith("linux-gnu"):
+ baseline = module("linux-release-abi").baseline()
+ if (tuple(platform.libc_ver()) != ("glibc", baseline["minimum_glibc"])
+ or os.environ.get("HIROUTE_LINUX_BASELINE_IMAGE") != baseline["build_image"]):
+ raise ValueError("Linux release must run inside the pinned glibc 2.31 build image")
+ self.result["linux_baseline"] = baseline
self.result["version"] = self.version
self.result["toolchain"] = {name: self.run(name, "--version") for name in ("cargo", "rustc")}
@@ -125,9 +131,6 @@ class Candidate:
binaries = REPO / "target" / self.target / "release"
for binary in (binaries / "hiroute", binaries / "hirouted", cpa):
inspect_elf(binary, self.target)
- self.result["linux_dependencies"] = {
- name: self.run("readelf", "--dynamic", "--version-info", binaries / name)
- for name in ("hiroute", "hirouted")}
notices = self.output / "notices"
self.script("collect-third-party-licenses", "--cargo-target", self.target,
"--cpa-source-repo", self.source_repo, "--output", notices)
@@ -142,6 +145,9 @@ class Candidate:
if any(verified[key] != expected for key, expected in (
("revision", self.revision), ("version", self.version), ("target", self.target))):
raise ValueError("standalone package differs from candidate identity")
+ abi = module("linux-release-abi").archive(manifest, archive, packager, self.run)
+ (self.output / "linux-abi.json").write_text(json.dumps(abi, indent=2) + "\n")
+ self.result["linux_abi"] = abi
self.result["cpa_source"] = provenance
artifact = {"kind": "standalone", "platform": "Linux", "architecture": self.target.split("-")[0],
"target": self.target, "format": "tar.gz", "distribution": "unsigned",
@@ -162,7 +168,8 @@ class Candidate:
assets.mkdir()
for path in files:
shutil.copyfile(path, assets / path.name)
- self.result.update(status="completed", package_integrity="green",
+ status = "awaiting_runtime" if self.target.endswith("linux-gnu") else "completed"
+ self.result.update(status=status, package_integrity="green",
website_artifact=artifact, assets=str(assets))
return self.result
except Exception as error:
@@ -179,7 +186,17 @@ def main():
parser.add_argument("--cpa-source-repo", type=Path, required=True)
args = parser.parse_args()
try:
- print(json.dumps(Candidate(args.target, args.cpa_source_repo).build(), indent=2))
+ if args.target.endswith("linux-gnu") and not os.environ.get("HIROUTE_LINUX_BASELINE_IMAGE"):
+ result = module("linux-release-container").run(args.target, args.cpa_source_repo)
+ else:
+ if args.target.endswith("linux-gnu"):
+ Path.home().mkdir(parents=True, exist_ok=True)
+ candidate = Candidate(args.target, args.cpa_source_repo)
+ result = candidate.build()
+ if args.target.endswith("linux-gnu"):
+ Path(os.environ["HIROUTE_RELEASE_RESULT"]).write_text(json.dumps({
+ "result_path": str(candidate.output / "result.json")}))
+ print(json.dumps(result, indent=2))
return 0
except (OSError, ValueError, subprocess.SubprocessError) as error:
print(str(error), file=sys.stderr)
diff --git a/scripts/install-standalone.py b/scripts/install-standalone.py
index 23e38271..1b5f709e 100755
--- a/scripts/install-standalone.py
+++ b/scripts/install-standalone.py
@@ -352,6 +352,27 @@ def prepare_service_directory(home):
current.mkdir(mode=0o700)
+def prepare_state_directory(paths):
+ """Create Linux state parents privately; preserve safe existing ancestors."""
+ if platform.system() != "Linux":
+ return
+ state = paths["state"]
+ if not state.is_absolute() or ".." in state.parts:
+ raise ValueError("standalone state parent is unsafe")
+ current = Path(state.anchor)
+ for part in state.parts[1:]:
+ current = current / part
+ if current.exists() or current.is_symlink():
+ metadata = current.lstat()
+ writable = metadata.st_mode & 0o022
+ if (not stat.S_ISDIR(metadata.st_mode)
+ or (writable and not metadata.st_mode & 0o1000)
+ or (current == state and (metadata.st_uid != os.geteuid() or writable))):
+ raise ValueError(f"standalone state parent is unsafe: {current}")
+ else:
+ current.mkdir(mode=0o700)
+
+
def current_owned_link(path, owned_root, expected_name):
if not path.is_symlink():
return False
@@ -555,6 +576,7 @@ def install(args):
version_parent = version_root.parent
resource_parent = resource_root.parent
prepare_service_directory(paths["home"])
+ prepare_state_directory(paths)
version_parent.mkdir(parents=True, exist_ok=True)
resource_parent.mkdir(parents=True, exist_ok=True)
staged_bin = Path(tempfile.mkdtemp(prefix=f".{version}.", dir=version_parent))
diff --git a/scripts/linux-release-abi.py b/scripts/linux-release-abi.py
new file mode 100644
index 00000000..ca5952dc
--- /dev/null
+++ b/scripts/linux-release-abi.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+"""Fail closed on the ABI of every ELF in the verified distribution archive."""
+import hashlib
+import json
+from pathlib import Path
+import re
+import struct
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parent
+
+
+def baseline():
+ return json.loads((ROOT / 'linux-release-baseline.json').read_text())
+
+
+def inspect(path, target, run=None):
+ policy = baseline()
+ platform = policy['targets'][target]
+ header = path.read_bytes()[:20]
+ if (len(header) != 20 or header[:6] != b'\x7fELF\x02\x01'
+ or struct.unpack_from('<H', header, 18)[0] != platform['machine']
+ or struct.unpack_from('<H', header, 16)[0] not in (2, 3)):
+ raise ValueError(f'{path.name}: invalid ELF architecture/type for {target}')
+ if run is None:
+ run = lambda *args: subprocess.check_output(args, text=True, env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C'})
+ output = run('readelf', '--wide', '--program-headers', '--dynamic', '--version-info', path)
+ interpreters = re.findall(r'Requesting program interpreter:\s*([^\]]+)\]', output)
+ if len(interpreters) > 1 or (interpreters and interpreters[0] != platform['interpreter']):
+ raise ValueError(f'{path.name}: unsupported ELF loader {interpreters}')
+ needed = re.findall(r'\(NEEDED\).*?\[([^\]]+)\]', output)
+ forbidden = set(needed) - set(policy['system_libraries'])
+ if forbidden:
+ raise ValueError(f'{path.name}: unsupported DT_NEEDED {sorted(forbidden)}')
+ # Do not permit build-host paths or a newer loader feature to bypass the floor.
+ if re.search(r'\((?:RPATH|RUNPATH|RELR|RELRSZ|RELRENT|AUDIT|DEPAUDIT|FILTER|AUXILIARY)\)', output):
+ raise ValueError(f'{path.name}: unsupported dynamic loader tag')
+ needs = output.split('Version needs section', 1)[-1] if 'Version needs section' in output else ''
+ versions = sorted(set(re.findall(r'Name:\s+(\S+)', needs)))
+ for version in versions:
+ match = re.fullmatch(r'(GLIBC|GLIBCXX|CXXABI|GCC|OPENSSL)_(\d+(?:[._]\d+)*)', version)
+ if not match:
+ raise ValueError(f'{path.name}: unsupported required symbol version {version}')
+ required = tuple(map(int, re.split('[._]', match[2])))
+ allowed = tuple(map(int, policy['symbol_versions'][match[1]].split('.')))
+ if required > allowed:
+ raise ValueError(f'{path.name}: required {version} exceeds {match[1]}_{policy["symbol_versions"][match[1]]}')
+ if not interpreters and (needed or versions) and struct.unpack_from('<H', header, 16)[0] == 2:
+ raise ValueError(f'{path.name}: dynamic executable has no loader')
+ return {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
+ 'interpreter': interpreters[0] if interpreters else None,
+ 'needed': needed, 'required_versions': versions, 'status': 'green'}
+
+
+def archive(manifest, bundle, packager, run=None):
+ verified = packager.verify(manifest, bundle)
+ members = packager.safe_members(bundle, verified['files'])
+ result = {}
+ with tempfile.TemporaryDirectory(prefix='hiroute-archive-abi-') as temporary:
+ for name, (data, mode) in members.items():
+ executable = name in ('bin/hiroute', 'bin/hirouted', 'libexec/cliproxyapi')
+ if not data.startswith(b'\x7fELF') and not executable:
+ continue
+ path = Path(temporary) / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ try:
+ facts = inspect(path, verified['target'], run)
+ except ValueError as error:
+ raise ValueError(f'archive {name}: {error}') from error
+ if facts['sha256'] != verified['files'][name]['sha256']:
+ raise ValueError(f'archive identity changed: {name}')
+ result[name] = facts
+ return {'status': 'green', 'archive_sha256': verified['archive']['sha256'],
+ 'manifest_sha256': hashlib.sha256(manifest.read_bytes()).hexdigest(),
+ 'target': verified['target'], 'revision': verified['revision'],
+ 'baseline': baseline(), 'files': result}
diff --git a/scripts/linux-release-baseline.json b/scripts/linux-release-baseline.json
new file mode 100644
index 00000000..ba13d652
--- /dev/null
+++ b/scripts/linux-release-baseline.json
@@ -0,0 +1,14 @@
+{
+ "schema": "hiroute.linux-release-baseline/v1",
+ "minimum_glibc": "2.31",
+ "distribution": "Debian 11 (bullseye)",
+ "build_image": "python:3.12.11-bullseye@sha256:7cc929040c5e8cf6036c5099d62a83708427c131fb7a7c965b5ba51e995eea1c",
+ "runtime_image": "python:3.12.11-slim-bullseye@sha256:411fa4dcfdce7e7a3057c45662beba9dcd4fa36b2e50a2bfcd6c9333e59bf0db",
+ "apt_snapshot": "20250815T000000Z",
+ "targets": {
+ "x86_64-unknown-linux-gnu": {"platform": "linux/amd64", "machine": 62, "interpreter": "/lib64/ld-linux-x86-64.so.2"},
+ "aarch64-unknown-linux-gnu": {"platform": "linux/arm64", "machine": 183, "interpreter": "/lib/ld-linux-aarch64.so.1"}
+ },
+ "symbol_versions": {"GLIBC": "2.31", "GLIBCXX": "3.4.28", "CXXABI": "1.3.12", "GCC": "4.8.0", "OPENSSL": "1.1.1"},
+ "system_libraries": ["libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1", "libresolv.so.2", "libutil.so.1", "libgcc_s.so.1", "libstdc++.so.6", "libssl.so.1.1", "libcrypto.so.1.1", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1"]
+}
diff --git a/scripts/linux-release-container.py b/scripts/linux-release-container.py
new file mode 100644
index 00000000..88f5d9bb
--- /dev/null
+++ b/scripts/linux-release-container.py
@@ -0,0 +1,144 @@
+#!/usr/bin/env python3
+"""Native container build and separate minimum-runtime acceptance for Linux releases."""
+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().parent.parent
+PROXY_NAMES = ('HTTP_PROXY', 'HTTPS_PROXY', 'FTP_PROXY', 'ALL_PROXY', 'NO_PROXY',
+ 'http_proxy', 'https_proxy', 'ftp_proxy', 'all_proxy', 'no_proxy')
+
+
+def run(target, source_repo):
+ policy = json.loads((REPO / 'scripts/linux-release-baseline.json').read_text())
+ arch = {'arm64': 'aarch64'}.get(platform.machine(), platform.machine())
+ if platform.system() != 'Linux' or target != f'{arch}-unknown-linux-gnu':
+ raise ValueError('Linux release requires a native architecture host')
+ if any(key in os.environ for key in ('CARGO_TARGET_DIR', 'CARGO_BUILD_TARGET_DIR')):
+ raise ValueError('external Cargo targets are forbidden')
+ if not shutil.which('docker'):
+ raise ValueError('Linux release requires Docker for the pinned glibc 2.31 build and runtime images')
+ sccache_executable = shutil.which('sccache')
+ if not sccache_executable:
+ raise ValueError('Linux release requires sccache on the host PATH')
+ jobs = os.environ.get('CARGO_BUILD_JOBS', '2')
+ if not jobs.isdecimal() or int(jobs) < 1:
+ raise ValueError('CARGO_BUILD_JOBS must be a positive integer')
+ revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip()
+ if subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=normal'], cwd=REPO, text=True):
+ raise ValueError('build requires a clean committed candidate')
+ root = REPO / 'target/release-candidate' / revision / target
+ root.mkdir(parents=True, exist_ok=True)
+ output = Path(tempfile.mkdtemp(prefix='container-', dir=root))
+ result = {'revision': revision, 'target': target, 'status': 'failed', 'baseline': policy,
+ 'execution_host': {'system': platform.system(), 'architecture': platform.machine(), 'libc': platform.libc_ver()}}
+ proxy_names = [name for name in PROXY_NAMES if name in os.environ]
+ result['forwarded_build_proxy_names'] = proxy_names
+
+ def command(args):
+ with (output / 'build.log').open('a') as log:
+ completed = subprocess.run(list(map(str, args)), cwd=REPO, stdout=log, stderr=subprocess.STDOUT)
+ completed.check_returncode()
+
+ try:
+ dockerfile = REPO / 'scripts/linux-release.Dockerfile'
+ result['dockerfile_sha256'] = hashlib.sha256(dockerfile.read_bytes()).hexdigest()
+ recipe = hashlib.sha256(dockerfile.read_bytes() + json.dumps(policy, sort_keys=True).encode()).hexdigest()
+ image = f'hiroute-release-{target}:{recipe[:16]}'
+ docker_build = ['docker', 'build', '--platform', policy['targets'][target]['platform'],
+ '--provenance=false', '--network', 'host',
+ '--build-arg', 'BASE_IMAGE=' + policy['build_image'],
+ '--build-arg', 'APT_SNAPSHOT=' + policy['apt_snapshot']]
+ # Docker resolves each value from its inherited environment. Standard
+ # proxy build args are excluded from image history/cache provenance.
+ for name in proxy_names:
+ docker_build.extend(['--build-arg', name])
+ command(docker_build + ['-f', dockerfile, '-t', image, REPO / 'scripts'])
+ result['build_image_id'] = subprocess.check_output(['docker', 'image', 'inspect', '--format', '{{.Id}}', image], text=True).strip()
+ if not re.fullmatch(r'sha256:[a-f0-9]{64}', result['build_image_id']):
+ raise ValueError('Docker returned an invalid build image digest')
+ cargo = Path(os.environ.get('CARGO_HOME', Path.home() / '.cargo')).resolve()
+ rustup = Path(os.environ.get('RUSTUP_HOME', Path.home() / '.rustup')).resolve()
+ go = Path(subprocess.check_output(['go', 'env', 'GOROOT'], text=True).strip()).resolve()
+ sccache = Path(sccache_executable).resolve(strict=True)
+ git_dir = Path(subprocess.check_output(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], cwd=REPO, text=True).strip())
+ source_repo = source_repo.resolve(strict=True)
+ cpa_git = Path(subprocess.check_output(['git', '-C', str(source_repo), 'rev-parse', '--path-format=absolute', '--git-common-dir'], text=True).strip())
+ cache = Path.home() / '.cache/hiroute/release-sccache'
+ cache.mkdir(parents=True, exist_ok=True)
+ common = ['docker', 'run', '--rm', '--init', '--platform', policy['targets'][target]['platform'],
+ '--user', f'{os.getuid()}:{os.getgid()}']
+ build = common + ['--network', 'host'] + [value for name in proxy_names for value in ('-e', name)] + [
+ '-w', str(REPO), '-v', f'{REPO}:{REPO}', '-v', f'{git_dir}:{git_dir}:ro',
+ '-v', f'{source_repo}:{source_repo}:ro', '-v', f'{cpa_git}:{cpa_git}:ro',
+ '-v', f'{cargo}:/opt/cargo', '-v', f'{rustup}:/opt/rustup:ro',
+ '-v', f'{go}:/opt/go:ro', '-v', f'{sccache}:/usr/local/bin/sccache:ro',
+ '-v', f'{cache}:/sccache', '-e', 'SCCACHE_DIR=/sccache',
+ '-e', 'SCCACHE_SERVER_UDS=/tmp/hiroute-release-sccache.sock',
+ '-e', 'HOME=/tmp/hiroute-build-home', '-e', 'CARGO_HOME=/opt/cargo',
+ '-e', 'RUSTUP_HOME=/opt/rustup', '-e', 'CARGO_INCREMENTAL=0',
+ '-e', 'CARGO_BUILD_JOBS=' + jobs, '-e', 'CARGO_NET_GIT_FETCH_WITH_CLI=true',
+ '-e', 'PATH=/usr/local/bin:/opt/cargo/bin:/opt/go/bin:/usr/bin:/bin',
+ '-e', 'HIROUTE_LINUX_BASELINE_IMAGE=' + policy['build_image'],
+ '-e', 'HIROUTE_RELEASE_RESULT=' + str(output / 'package.json'),
+ result['build_image_id'], 'python3', 'scripts/build-release.py',
+ '--target', target, '--cpa-source-repo', source_repo]
+ spec = importlib.util.spec_from_file_location('local_rust', REPO / 'scripts/local-rust.py')
+ local_rust = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(local_rust)
+ # Use the caller's existing lock even though the build has a private HOME.
+ with local_rust.Store().locked(REPO):
+ stamp = REPO / 'target/.linux-release-baseline.json'
+ # Automatic attestations regenerate containerd image IDs. Build
+ # without those attestations and retain our measured provenance.
+ identity = {'schema': 'hiroute.linux-release-target-baseline/v1',
+ 'image_digest': result['build_image_id'], 'recipe_sha256': recipe, 'target': target}
+ if stamp.exists():
+ if json.loads(stamp.read_text()) != identity:
+ raise ValueError('checkout target belongs to a different Linux build baseline; use a fresh worktree')
+ elif any((REPO / 'target' / path).exists() for path in ('release', target + '/release')):
+ raise ValueError('unattested release outputs already exist; use a fresh worktree')
+ stamp.write_text(json.dumps(identity) + '\n')
+ command(build)
+ package_path = Path(json.loads((output / 'package.json').read_text())['result_path'])
+ package = json.loads(package_path.read_text())
+ if package['status'] != 'awaiting_runtime' or package['revision'] != revision:
+ raise ValueError('container package identity/status mismatch')
+ assets = Path(package['assets'])
+ manifest = assets / package['website_artifact']['manifest_filename']
+ archive = assets / package['website_artifact']['filename']
+ runtime = output / 'runtime'
+ runtime.mkdir()
+ inputs = output / 'runtime-input'
+ inputs.mkdir()
+ for name in ('linux-release-runtime.py', 'install-standalone.py', 'package-standalone.py',
+ 'linux-release-baseline.json'):
+ shutil.copyfile(REPO / 'scripts' / name, inputs / name)
+ for path in (manifest, archive, package_path.parent / 'linux-abi.json'):
+ shutil.copyfile(path, inputs / path.name)
+ command(common + ['--network', 'none', '-w', '/input', '-v', f'{inputs}:/input:ro',
+ '-v', f'{runtime}:/output', policy['runtime_image'],
+ 'python3', '/input/linux-release-runtime.py', '--manifest', '/input/' + manifest.name,
+ '--archive', '/input/' + archive.name, '--abi', '/input/linux-abi.json',
+ '--output', '/output'])
+ evidence = json.loads((runtime / 'result.json').read_text())
+ if evidence['status'] != 'green' or evidence['archive_sha256'] != package['website_artifact']['sha256']:
+ raise ValueError('minimum runtime did not accept the exact archive')
+ result.update(package, status='completed', minimum_runtime=evidence,
+ baseline=policy, package_result=str(package_path))
+ package.update(status='completed', minimum_runtime=evidence, build_environment=result['build_image_id'])
+ package_path.write_text(json.dumps(package, indent=2) + '\n')
+ return result
+ except Exception as error:
+ result['error'] = str(error)
+ raise
+ finally:
+ (output / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
+ print(f'Linux container evidence: {output}', file=__import__('sys').stderr)
diff --git a/scripts/linux-release-runtime.py b/scripts/linux-release-runtime.py
new file mode 100644
index 00000000..f3179657
--- /dev/null
+++ b/scripts/linux-release-runtime.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+"""Install an exact archive in a private HOME and exercise production Local Control."""
+import argparse
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+import platform
+import signal
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+sys.dont_write_bytecode = True
+ROOT = Path(__file__).resolve().parent
+
+
+def digest(path):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def check(manifest, archive, abi, output):
+ result = {'status': 'red', 'libc': platform.libc_ver(), 'architecture': platform.machine()}
+ output.mkdir(parents=True, exist_ok=True)
+ process = None
+ private = None
+ home = None
+ diagnostics = None
+ try:
+ if tuple(platform.libc_ver()) != ('glibc', '2.31'):
+ raise ValueError('runtime acceptance requires glibc 2.31')
+ spec = importlib.util.spec_from_file_location('package_standalone', ROOT / 'package-standalone.py')
+ packager = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(packager)
+ package = packager.verify(manifest, archive)
+ if package['target'] != packager.host_target():
+ raise ValueError('runtime architecture differs from package')
+ checked = json.loads(abi.read_text())
+ policy = json.loads((ROOT / 'linux-release-baseline.json').read_text())
+ if (checked.get('status') != 'green' or checked.get('archive_sha256') != package['archive']['sha256']
+ or checked.get('manifest_sha256') != digest(manifest)
+ or checked.get('target') != package['target'] or checked.get('revision') != package['revision']
+ or checked.get('baseline') != policy
+ or any(checked.get('files', {}).get(name, {}).get('sha256') != package['files'][name]['sha256']
+ for name in ('bin/hiroute', 'bin/hirouted', 'libexec/cliproxyapi'))):
+ raise ValueError('ABI evidence differs from archive')
+ result.update(revision=package['revision'], target=package['target'],
+ archive_sha256=digest(archive), manifest_sha256=digest(manifest))
+ private = tempfile.TemporaryDirectory(prefix='hiroute-minimum-runtime-')
+ home = Path(private.name)
+ environment = {'HOME': str(home), 'PATH': '/usr/local/bin:/usr/bin:/bin',
+ 'LANG': 'C.UTF-8', 'LD_BIND_NOW': '1'}
+
+ def run(*args, required=True):
+ completed = subprocess.run(list(map(str, args)), env=environment, text=True,
+ capture_output=True, timeout=30)
+ with (output / 'commands.log').open('a') as log:
+ log.write(f'$ {" ".join(map(str, args))}\n{completed.stdout}{completed.stderr}\n')
+ if required:
+ completed.check_returncode()
+ return completed
+
+ run(sys.executable, ROOT / 'install-standalone.py', 'install',
+ '--manifest', manifest, '--archive', archive)
+ cli = home / '.local/bin/hiroute'
+ daemon = home / '.local/bin/hirouted'
+ marker = json.loads((home / '.local/share/hiroute/standalone.json').read_text())
+ if marker['version'] != package['version'] or marker['target'] != package['target']:
+ raise ValueError('installed version/target differs from verified manifest')
+ result.update(version=package['version'],
+ version_source='verified_manifest_and_installation_marker')
+ cpa = Path(marker['cpa_binary'])
+ installed = {'bin/hiroute': cli, 'bin/hirouted': daemon, 'libexec/cliproxyapi': cpa}
+ result['installed_sha256'] = {name: digest(path) for name, path in installed.items()}
+ for name, path in installed.items():
+ if digest(path) != package['files'][name]['sha256']:
+ raise ValueError(f'installed identity differs: {name}')
+ loader = checked['files'][name]['interpreter']
+ if loader:
+ # Eagerly resolve dependencies in the minimal image, not the build image.
+ run(loader, '--list', path)
+ run(cli, '--help')
+ run(cpa, '--help')
+ # Use the supported settings format in this disposable HOME; RUST_LOG does
+ # not control the product diagnostics runtime. No user configuration is read.
+ diagnostics = home / '.local/state/hiroute/diagnostics'
+ diagnostics.mkdir(parents=True, mode=0o700, exist_ok=True)
+ settings = diagnostics / 'settings.json'
+ settings.write_text(json.dumps({'schema': 'hiroute.diagnostic-settings/v1', 'revision': 1, 'level': 'debug'}))
+ settings.chmod(0o600)
+ with (output / 'daemon.log').open('w') as log:
+ process = subprocess.Popen([str(cli), 'service', 'run'], env=environment,
+ stdout=log, stderr=log, start_new_session=True)
+ result['pid'] = process.pid
+ deadline = time.monotonic() + 60
+ while True:
+ if process.poll() is not None:
+ raise ValueError('installed daemon exited before readiness')
+ response = run(cli, 'system', 'status', '--output', 'json', required=False)
+ if response.returncode == 0:
+ status = json.loads(response.stdout)
+ if status.get('data', {}).get('daemon') == 'role_all' and status['data'].get('gateway') == 'ready':
+ break
+ if time.monotonic() >= deadline:
+ raise ValueError('installed daemon never reached business readiness')
+ time.sleep(0.2)
+ rounds = []
+ for index in range(2):
+ if index:
+ time.sleep(1)
+ status = json.loads(run(cli, 'system', 'status', '--output', 'json').stdout)
+ if (process.poll() is not None or status.get('data', {}).get('daemon') != 'role_all'
+ or status['data'].get('gateway') != 'ready'):
+ raise ValueError('daemon and Gateway did not remain healthy')
+ gateway = json.loads(run(cli, 'gateway', 'show', '--output', 'json').stdout)
+ if gateway.get('data', {}).get('ready') is not True or not gateway['data'].get('connect_address'):
+ raise ValueError('real Gateway management call did not report readiness')
+ rounds.append({'system_status': status, 'gateway_show': gateway})
+ result['management'] = {'rounds': rounds}
+ records = [json.loads(line) for line in (diagnostics / 'daemon/current.jsonl').read_text().splitlines()]
+ applied = [row for row in records if 'level_applied' in row.get('event', {})]
+ if not applied or applied[-1]['event']['level_applied']['level'] != 'debug':
+ raise ValueError('daemon diagnostics did not apply Debug')
+ result['diagnostics'] = {'boot_id': applied[-1]['boot_id'],
+ 'level_applied': applied[-1]['event']['level_applied']}
+ process.send_signal(signal.SIGTERM)
+ result['daemon_exit'] = process.wait(timeout=30)
+ if result['daemon_exit'] != 0:
+ raise ValueError('daemon did not stop normally')
+ if run(cli, 'system', 'status', '--output', 'json', required=False).returncode == 0:
+ raise ValueError('management endpoint remained available after stop')
+ gateway_after = run(cli, 'gateway', 'show', '--output', 'json', required=False)
+ if gateway_after.returncode == 0 and json.loads(gateway_after.stdout).get('data', {}).get('ready') is True:
+ raise ValueError('Gateway listener remained available after stop')
+ result['status'] = 'green'
+ return result
+ except Exception as error:
+ result['error'] = str(error)
+ raise
+ finally:
+ if process is not None:
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ if process.poll() is None:
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+ result['process_stopped'] = True
+ if diagnostics is not None and diagnostics.exists():
+ for path in diagnostics.glob('daemon/*.jsonl'):
+ destination = output / 'diagnostics' / path.relative_to(diagnostics)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(path, destination)
+ if private is not None:
+ private.cleanup()
+ result['private_home_removed'] = not home.exists()
+ (output / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ('manifest', 'archive', 'abi', 'output'):
+ parser.add_argument('--' + name, type=Path, required=True)
+ args = parser.parse_args()
+ check(args.manifest, args.archive, args.abi, args.output)
diff --git a/scripts/linux-release.Dockerfile b/scripts/linux-release.Dockerfile
new file mode 100644
index 00000000..5b8faeaa
--- /dev/null
+++ b/scripts/linux-release.Dockerfile
@@ -0,0 +1,11 @@
+# The caller supplies the digest-pinned image and immutable Debian snapshot.
+ARG BASE_IMAGE
+FROM ${BASE_IMAGE}
+ARG APT_SNAPSHOT
+RUN printf 'deb [check-valid-until=no] https://snapshot.debian.org/archive/debian/%s/ bullseye main\n' "$APT_SNAPSHOT" > /etc/apt/sources.list \
+ && printf 'deb [check-valid-until=no] https://snapshot.debian.org/archive/debian-security/%s/ bullseye-security main\n' "$APT_SNAPSHOT" >> /etc/apt/sources.list \
+ && rm -f /etc/apt/sources.list.d/* \
+ && apt-get update \
+ && apt-get install --yes --no-install-recommends cmake clang pkg-config binutils \
+ && rm -rf /var/lib/apt/lists/* \
+ && test "$(getconf GNU_LIBC_VERSION)" = 'glibc 2.31'
diff --git a/scripts/test-build-release.py b/scripts/test-build-release.py
index 228843c5..4df7e0a8 100644
--- a/scripts/test-build-release.py
+++ b/scripts/test-build-release.py
@@ -18,13 +18,14 @@ REPO = Path(__file__).resolve().parent.parent
spec = importlib.util.spec_from_file_location("build_release", REPO / "scripts/build-release.py")
builder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(builder)
-MODULES = {name: builder.module(name) for name in ("package-desktop", "package-standalone", "build-cpa", "local-rust")}
+MODULES = {name: builder.module(name) for name in ("package-desktop", "package-standalone", "build-cpa", "local-rust", "linux-release-abi")}
def elf(path, machine):
path.parent.mkdir(parents=True, exist_ok=True)
header = bytearray(64)
header[:6] = b"\x7fELF\x02\x01"
+ struct.pack_into("<H", header, 16, 2)
struct.pack_into("<H", header, 18, machine)
path.write_bytes(header)
path.chmod(0o755)
@@ -54,6 +55,8 @@ class CandidateTests(unittest.TestCase):
path.write_bytes((REPO / relative).read_bytes())
path.chmod(0o644)
self.commands = []
+ patch.object(builder.platform, "libc_ver", return_value=("glibc", "2.31")).start()
+ patch.dict(os.environ, {"HIROUTE_LINUX_BASELINE_IMAGE": MODULES["linux-release-abi"].baseline()["build_image"]}).start()
def command(self, *args, **kwargs):
self.commands.append(args)
@@ -109,7 +112,8 @@ class CandidateTests(unittest.TestCase):
patch.object(MODULES["local-rust"], "Store") as store:
store.return_value.locked.return_value = nullcontext()
result = self.candidate.build()
- self.assertEqual(result["status"], "completed")
+ self.assertEqual(result["status"], "awaiting_runtime")
+ self.assertEqual(set(result["linux_abi"]["files"]), {"bin/hiroute", "bin/hirouted", "libexec/cliproxyapi"})
self.assertEqual(result["website_artifact"]["architecture"], "aarch64")
artifacts = list(Path(result["assets"]).iterdir())
self.assertEqual(len(artifacts), 2)
@@ -128,6 +132,23 @@ class CandidateTests(unittest.TestCase):
archive.write_bytes(b"tampered")
self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)
+ def test_archive_with_new_glibc_requirement_cannot_produce_accepted_assets(self):
+ def newer(*args, **kwargs):
+ if args[0] == "readelf":
+ return "Version needs section '.gnu.version_r':\n Name: GLIBC_2.34 Flags: none Version: 2"
+ return self.command(*args, **kwargs)
+ with patch.object(self.candidate, "run", side_effect=newer), \
+ patch.object(self.candidate, "script", side_effect=self.script), \
+ patch.object(MODULES["package-desktop"], "ensure_sccache_server"), \
+ patch.object(MODULES["local-rust"], "Store") as store:
+ store.return_value.locked.return_value = nullcontext()
+ with self.assertRaisesRegex(ValueError, "archive bin/hiroute.*GLIBC_2.34"):
+ self.candidate.build()
+ result = json.loads((self.candidate.output / "result.json").read_text())
+ self.assertEqual(result["status"], "failed")
+ self.assertNotIn("website_artifact", result)
+ self.assertFalse((self.candidate.output / "assets").exists())
+
def test_elf_architecture_rejects_mislabelled_and_non_elf_binaries(self):
binary = self.root / "binary"
for target, machine in ((self.target, 183), ("x86_64-unknown-linux-gnu", 62)):
diff --git a/scripts/test-linux-release.py b/scripts/test-linux-release.py
new file mode 100644
index 00000000..0ebe0966
--- /dev/null
+++ b/scripts/test-linux-release.py
@@ -0,0 +1,536 @@
+#!/usr/bin/env python3
+"""ABI boundary regressions, including real ELF fixtures and orchestration failures."""
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import platform
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stdout, nullcontext
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parent
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, ROOT / (name + '.py'))
+ value = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(value)
+ return value
+
+
+abi = load('linux-release-abi')
+container = load('linux-release-container')
+runtime = load('linux-release-runtime')
+
+
+class AbiTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.binary = self.root / 'hiroute'
+ self.target = 'x86_64-unknown-linux-gnu'
+ self.header(62)
+
+ def header(self, machine, kind=2):
+ header = bytearray(64)
+ header[:6] = b'\x7fELF\x02\x01'
+ struct.pack_into('<HH', header, 16, kind, machine)
+ self.binary.write_bytes(header)
+
+ def inspect(self, text):
+ return abi.inspect(self.binary, self.target, lambda *args: text)
+
+ def needs(self, version):
+ return f'''[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
+ 0x0001 (NEEDED) Shared library: [libc.so.6]
+Version needs section '.gnu.version_r' contains 1 entry:
+ Name: {version} Flags: none Version: 2
+'''
+
+ def test_baseline_static_and_both_native_architectures(self):
+ self.assertEqual(self.inspect(self.needs('GLIBC_2.31'))['status'], 'green')
+ self.assertIsNone(self.inspect('There is no dynamic section in this file.')['interpreter'])
+ self.header(183)
+ self.target = 'aarch64-unknown-linux-gnu'
+ text = self.needs('GLIBC_2.31').replace('/lib64/ld-linux-x86-64.so.2', '/lib/ld-linux-aarch64.so.1')
+ self.assertEqual(self.inspect(text)['status'], 'green')
+
+ def test_rejects_every_reported_regression_and_other_runtime_floors(self):
+ for version in ('GLIBC_2.32', 'GLIBC_2.33', 'GLIBC_2.34', 'GLIBC_2.9.99.1',
+ 'GLIBC_ABI_DT_RELR', 'GLIBC_PRIVATE', 'GLIBCXX_3.4.29', 'CXXABI_1.3.13',
+ 'OPENSSL_3.0.0', 'UNKNOWN_1.0'):
+ if version == 'GLIBC_2.9.99.1':
+ self.assertEqual(self.inspect(self.needs(version))['status'], 'green')
+ else:
+ with self.subTest(version=version), self.assertRaisesRegex(ValueError, version):
+ self.inspect(self.needs(version))
+
+ def test_checks_needs_not_library_exported_definitions(self):
+ self.header(62, 3)
+ self.assertEqual(self.inspect("Version definition section '.gnu.version_d':\n Name: MY_API_99")['required_versions'], [])
+
+ def test_loader_architecture_dependencies_and_new_dynamic_features(self):
+ for text in (self.needs('GLIBC_2.31').replace('libc.so.6', 'libssl.so.3'),
+ self.needs('GLIBC_2.31').replace('/lib64/ld-linux-x86-64.so.2', '/tmp/custom-loader'),
+ self.needs('GLIBC_2.31') + '\n (RUNPATH) [/build/lib]',
+ self.needs('GLIBC_2.31') + '\n (RELR) 0x00'):
+ with self.assertRaises(ValueError):
+ self.inspect(text)
+ self.header(183)
+ with self.assertRaisesRegex(ValueError, 'architecture'):
+ self.inspect('')
+
+ @unittest.skipUnless(platform.system() == 'Linux' and platform.machine() == 'x86_64' and shutil.which('cc'), 'native ELF compiler required')
+ def test_real_elf_baseline_library_static_executable_and_new_glibc_symbol(self):
+ source = self.root / 'fixture.c'
+ source.write_text('#include <stdio.h>\nvoid fixture(void) { puts("baseline"); }\n')
+ subprocess.run(['cc', '-shared', '-fPIC', str(source), '-o', str(self.binary)], check=True)
+ self.assertIn('GLIBC_2.2.5', abi.inspect(self.binary, self.target)['required_versions'])
+ source.write_text('void _start(void) { __asm__("mov $60, %rax; xor %rdi, %rdi; syscall"); }\n')
+ subprocess.run(['cc', '-nostdlib', '-static', str(source), '-o', str(self.binary)], check=True)
+ self.assertEqual(abi.inspect(self.binary, self.target)['needed'], [])
+ if tuple(map(int, platform.libc_ver()[1].split('.'))) <= (2, 31):
+ self.skipTest('new-symbol fixture requires a newer host libc')
+ source.write_text('#define _GNU_SOURCE\n#include <unistd.h>\nint fixture(void) { return close_range(100, 200, 0); }\n')
+ subprocess.run(['cc', '-shared', '-fPIC', str(source), '-o', str(self.binary)], check=True)
+ # The original architecture-only release check admits this failing payload.
+ load('build-release').inspect_elf(self.binary, self.target)
+ with self.assertRaisesRegex(ValueError, r'GLIBC_2\.34'):
+ abi.inspect(self.binary, self.target)
+
+ def test_wrong_runtime_floor_is_red_with_retained_evidence(self):
+ output = self.root / 'evidence'
+ with patch.object(runtime.platform, 'libc_ver', return_value=('glibc', '2.34')):
+ with self.assertRaisesRegex(ValueError, 'glibc 2.31'):
+ runtime.check(self.root / 'missing', self.root / 'missing', self.root / 'missing', output)
+ self.assertEqual(json.loads((output / 'result.json').read_text())['status'], 'red')
+
+ def test_no_native_container_host_never_falls_back_to_newer_libc(self):
+ with patch.object(container.platform, 'machine', return_value='x86_64'), \
+ patch.object(container.platform, 'system', return_value='Linux'), \
+ patch.object(container.shutil, 'which', return_value=None):
+ with self.assertRaisesRegex(ValueError, 'requires Docker'):
+ container.run(self.target, self.root)
+ with self.assertRaisesRegex(ValueError, 'native architecture'):
+ container.run('aarch64-unknown-linux-gnu', self.root)
+
+ def test_pinned_images_and_target_policy(self):
+ policy = abi.baseline()
+ for key in ('build_image', 'runtime_image'):
+ self.assertRegex(policy[key], r'@sha256:[a-f0-9]{64}$')
+ self.assertEqual(set(policy['targets']), {'x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu'})
+
+
[email protected](platform.system() == 'Linux', 'Linux runtime fixture')
+class RuntimeTests(unittest.TestCase):
+ """Real installer/child lifecycle fixtures; these do not prove product ABI acceptance."""
+
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.packager = load('package-standalone')
+ self.target = self.packager.host_target()
+ self.output = self.root / 'evidence'
+ for relative in ('LICENSE', 'assets/skills/hiroute-management/SKILL.md', 'docs/standalone-cli.md'):
+ path = self.root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes((ROOT.parent / relative).read_bytes())
+ path.chmod(0o644)
+
+ def package(self, case='healthy'):
+ executable = self.root / 'fixture'
+ executable.write_text('#!' + sys.executable + '\n' + '''
+import json, os, pathlib, signal, sys, time
+home = pathlib.Path(os.environ['HOME'])
+ready = home / 'fixture-ready.json'
+case = CASE
+args = sys.argv[1:]
+if args == ['--version']:
+ if case == 'cli_no_version' and pathlib.Path(sys.argv[0]).name == 'hiroute':
+ print(json.dumps({'error': {'code': 'UNKNOWN_COMMAND'}}))
+ raise SystemExit(2)
+ print('hiroute 0.2.0'); raise SystemExit(0)
+if args == ['--help']:
+ if case == 'daemon_no_help' and pathlib.Path(sys.argv[0]).name == 'hirouted':
+ print('usage: hirouted --role all --standalone', file=sys.stderr)
+ raise SystemExit(2)
+ print('fixture help'); raise SystemExit(0)
+if args == ['service', 'run']:
+ def stop(*_):
+ print('home_present_at_shutdown=' + str(home.exists()), flush=True)
+ ready.unlink(missing_ok=True)
+ raise SystemExit(0)
+ signal.signal(signal.SIGTERM, stop)
+ diagnostics = home / '.local/state/hiroute/diagnostics'
+ diagnostics.mkdir(parents=True, exist_ok=True)
+ settings = diagnostics / 'settings.json'
+ level = json.loads(settings.read_text())['level'] if settings.exists() else 'info'
+ log = diagnostics / 'daemon/current.jsonl'
+ log.parent.mkdir(parents=True, exist_ok=True)
+ log.write_text(json.dumps({'boot_id': 'a' * 32, 'event': {'level_applied': {'level': level, 'source': 'persisted', 'revision': 1}}}) + '\\n')
+ ready.write_text('0')
+ while True: time.sleep(0.02)
+if not ready.exists(): raise SystemExit(6)
+if args[:2] == ['system', 'status']:
+ count = int(ready.read_text()) + 1; ready.write_text(str(count))
+ gateway = 'unavailable' if case == 'degraded' and count > 1 else 'ready'
+ print(json.dumps({'data': {'daemon': 'role_all', 'gateway': gateway}}))
+elif args[:2] == ['gateway', 'show']:
+ print(json.dumps({'data': {'ready': case != 'bad_gateway', 'connect_address': '127.0.0.1:50000'}}))
+else: raise SystemExit(2)
+'''.replace('CASE', repr(case)))
+ executable.chmod(0o755)
+ license_path = self.root / 'cpa.LICENSE'
+ license_path.write_text('fixture license')
+ license_path.chmod(0o644)
+ notices = self.root / 'notices'
+ notices.mkdir(exist_ok=True)
+ (notices / 'THIRD-PARTY-LICENSES.txt').write_text('fixture notices')
+ (notices / 'third-party-licenses.json').write_text(json.dumps({
+ 'schema': 'hiroute.third-party-licenses/v1', 'inputs': {},
+ 'packages': [{'name': 'fixture'}], 'documents': [{'name': 'fixture'}],
+ }))
+ for path in notices.iterdir(): path.chmod(0o644)
+ args = self.packager.parser().parse_args([
+ 'build', '--version', '0.2.0', '--revision', 'a' * 40, '--target', self.target,
+ '--hiroute', str(executable), '--hirouted', str(executable), '--cpa-binary', str(executable),
+ '--cpa-version', 'fixture', '--cpa-license', str(license_path),
+ '--notices', str(notices), '--output', str(self.root / 'package'),
+ ])
+ output = io.StringIO()
+ with redirect_stdout(output), patch.object(self.packager, 'REPO', self.root):
+ self.packager.build(args)
+ packaged = json.loads(output.getvalue())
+ self.manifest = Path(packaged['manifest'])
+ self.archive = Path(packaged['archive'])
+ manifest = json.loads(self.manifest.read_text())
+ self.checked = {'status': 'green', 'target': self.target, 'revision': 'a' * 40,
+ 'archive_sha256': runtime.digest(self.archive),
+ 'manifest_sha256': runtime.digest(self.manifest), 'baseline': abi.baseline(),
+ 'files': {name: {'sha256': manifest['files'][name]['sha256'], 'interpreter': None}
+ for name in ('bin/hiroute', 'bin/hirouted', 'libexec/cliproxyapi')}}
+ self.abi = self.root / 'abi.json'
+ self.abi.write_text(json.dumps(self.checked))
+
+ def check(self):
+ with patch.object(runtime.platform, 'libc_ver', return_value=('glibc', '2.31')):
+ return runtime.check(self.manifest, self.archive, self.abi, self.output)
+
+ def test_installed_fixture_has_two_healthy_rounds_debug_and_orderly_stop(self):
+ self.package()
+ result = self.check()
+ self.assertEqual(result['status'], 'green')
+ self.assertEqual(len(result['management'].get('rounds', [])), 2)
+ self.assertEqual(result['diagnostics']['level_applied']['level'], 'debug')
+ self.assertTrue(result.get('private_home_removed', False))
+ self.assertTrue(result['process_stopped'])
+ self.assertIn('home_present_at_shutdown=True', (self.output / 'daemon.log').read_text())
+
+ def test_degraded_second_round_cannot_pass_the_resident_gateway_gate(self):
+ self.package('degraded')
+ with self.assertRaisesRegex(ValueError, 'remain healthy'):
+ self.check()
+ self.assertEqual(json.loads((self.output / 'result.json').read_text())['status'], 'red')
+
+ def test_documented_daemon_start_is_accepted_when_daemon_has_no_help_flag(self):
+ self.package('daemon_no_help')
+ self.assertEqual(self.check()['status'], 'green')
+
+ def test_cli_without_version_flag_uses_verified_installation_identity(self):
+ self.package('cli_no_version')
+ result = self.check()
+ self.assertEqual(result['status'], 'green')
+ self.assertEqual(result['version'], '0.2.0')
+ self.assertEqual(result['version_source'], 'verified_manifest_and_installation_marker')
+ self.assertNotIn(' --version\n', (self.output / 'commands.log').read_text())
+
+ def test_installation_version_must_match_the_verified_manifest(self):
+ self.package()
+ original = subprocess.run
+
+ def tamper_after_install(args, **kwargs):
+ completed = original(args, **kwargs)
+ if len(args) > 1 and Path(args[1]).name == 'install-standalone.py':
+ marker = Path(kwargs['env']['HOME']) / '.local/share/hiroute/standalone.json'
+ value = json.loads(marker.read_text())
+ value['version'] = '0.2.999'
+ marker.write_text(json.dumps(value))
+ return completed
+
+ with patch.object(runtime.subprocess, 'run', side_effect=tamper_after_install):
+ with self.assertRaisesRegex(ValueError, 'installed version/target'):
+ self.check()
+
+ def test_failure_stops_process_before_removing_home_and_preserves_diagnostics(self):
+ self.package('bad_gateway')
+ with self.assertRaisesRegex(ValueError, 'Gateway management'):
+ self.check()
+ result = json.loads((self.output / 'result.json').read_text())
+ self.assertTrue(result['process_stopped'])
+ self.assertTrue(result.get('private_home_removed', False))
+ self.assertIn('home_present_at_shutdown=True', (self.output / 'daemon.log').read_text())
+ self.assertTrue((self.output / 'diagnostics/daemon/current.jsonl').is_file())
+
+ def test_abi_file_hashes_and_baseline_must_match_the_installed_payload(self):
+ self.package()
+ for key in ('file', 'baseline'):
+ checked = json.loads(json.dumps(self.checked))
+ if key == 'file': checked['files']['bin/hiroute']['sha256'] = '0' * 64
+ else: checked['baseline']['minimum_glibc'] = '2.34'
+ self.abi.write_text(json.dumps(checked))
+ with self.subTest(key=key), self.assertRaisesRegex(ValueError, 'ABI evidence'):
+ self.check()
+
+
+class ContainerTests(unittest.TestCase):
+ """Exercise wrapper arguments and retained evidence without pretending Docker ran."""
+
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ scripts = self.root / 'scripts'
+ scripts.mkdir()
+ for name in ('linux-release-baseline.json', 'linux-release.Dockerfile',
+ 'linux-release-runtime.py', 'install-standalone.py', 'package-standalone.py'):
+ (scripts / name).write_bytes((ROOT / name).read_bytes())
+ (scripts / 'local-rust.py').write_text('from contextlib import nullcontext\nclass Store:\n def locked(self, repo): return nullcontext()\n')
+ self.source = self.root / 'cpa'
+ self.source.mkdir()
+ self.sccache = self.root / 'sccache'
+ self.sccache.write_text('fixture')
+ self.commands = []
+ self.revision = 'a' * 40
+ self.target = 'x86_64-unknown-linux-gnu'
+ self.hash = 'b' * 64
+ self.image_id = 'sha256:' + 'c' * 64
+ self.image_config_digest = self.image_id
+ self.write_build_metadata = True
+ self.include_config_metadata = True
+ self.attestation_sensitive = False
+ self.runtime_state = 'green'
+ self.addCleanup(patch.stopall)
+ patch.object(container, 'REPO', self.root).start()
+ patch.object(container.platform, 'system', return_value='Linux').start()
+ patch.object(container.platform, 'machine', return_value='x86_64').start()
+ patch.object(container.shutil, 'which', side_effect=lambda name: str(self.sccache) if name == 'sccache' else '/usr/bin/' + name).start()
+ patch.object(container.subprocess, 'check_output', side_effect=self.query).start()
+ patch.object(container.subprocess, 'run', side_effect=self.command).start()
+
+ def query(self, args, **_):
+ if args[:3] == ['git', 'rev-parse', 'HEAD']: return self.revision
+ if args[:2] == ['git', 'status']: return ''
+ if args[:3] == ['docker', 'image', 'inspect']: return self.image_id
+ if args[:3] == ['go', 'env', 'GOROOT']: return str(self.root / 'go')
+ if args[0] == 'git': return str(self.root / 'common.git')
+ self.fail(f'unexpected query: {args}')
+
+ def command(self, args, **_):
+ self.commands.append(args)
+ if args[:2] == ['docker', 'build']:
+ if self.attestation_sensitive and '--provenance=false' not in args:
+ self.image_id = 'sha256:' + format(len(self.commands), '064x')
+ if '--metadata-file' in args and self.write_build_metadata:
+ path = Path(args[args.index('--metadata-file') + 1])
+ metadata = {'containerimage.digest': self.image_id}
+ if self.include_config_metadata:
+ metadata['containerimage.config.digest'] = self.image_config_digest
+ path.write_text(json.dumps(metadata))
+ elif 'scripts/build-release.py' in args:
+ pointer = next(value.split('=', 1)[1] for value in args if value.startswith('HIROUTE_RELEASE_RESULT='))
+ output = Path(pointer).parent / 'package'
+ assets = output / 'assets'
+ assets.mkdir(parents=True)
+ archive = assets / 'candidate.tar.gz'
+ archive.write_bytes(b'fixture archive')
+ manifest = assets / 'candidate.tar.gz.json'
+ manifest.write_text('fixture manifest')
+ (output / 'linux-abi.json').write_text('{}')
+ package = {'status': 'awaiting_runtime', 'revision': self.revision, 'assets': str(assets),
+ 'website_artifact': {'filename': archive.name, 'manifest_filename': manifest.name, 'sha256': self.hash}}
+ (output / 'result.json').write_text(json.dumps(package))
+ Path(pointer).write_text(json.dumps({'result_path': str(output / 'result.json')}))
+ elif any(value.endswith('linux-release-runtime.py') for value in args):
+ output_arg = args[args.index('--output') + 1]
+ mounts = [args[i + 1] for i, value in enumerate(args) if value == '-v']
+ output_mount = next(value for value in mounts if value.split(':')[1] == output_arg)
+ output = Path(output_mount.split(':')[0])
+ (output / 'result.json').write_text(json.dumps({'status': self.runtime_state, 'archive_sha256': self.hash}))
+ return subprocess.CompletedProcess(args, 0)
+
+ def test_minimum_runtime_only_receives_staged_inputs_and_build_jobs_are_preserved(self):
+ with patch.dict(os.environ, {'CARGO_BUILD_JOBS': '8'}):
+ result = container.run(self.target, self.source)
+ self.assertEqual(result['status'], 'completed')
+ build = next(args for args in self.commands if 'scripts/build-release.py' in args)
+ self.assertIn('CARGO_BUILD_JOBS=8', build)
+ runtime_args = next(args for args in self.commands if any(value.endswith('linux-release-runtime.py') for value in args))
+ mounts = [runtime_args[i + 1] for i, value in enumerate(runtime_args) if value == '-v']
+ self.assertEqual(len(mounts), 2)
+ self.assertFalse(any(value.startswith(str(self.root) + ':') for value in mounts))
+ inputs = next(Path(value.split(':')[0]) for value in mounts if value.endswith(':/input:ro'))
+ self.assertEqual(set(path.name for path in inputs.iterdir()), {
+ 'linux-release-runtime.py', 'install-standalone.py', 'package-standalone.py',
+ 'linux-release-baseline.json', 'candidate.tar.gz', 'candidate.tar.gz.json', 'linux-abi.json',
+ })
+
+ def test_non_green_runtime_keeps_failed_result_and_awaiting_package(self):
+ self.runtime_state = 'red'
+ with self.assertRaisesRegex(ValueError, 'minimum runtime'):
+ container.run(self.target, self.source)
+ output = next((self.root / 'target/release-candidate').glob('**/container-*'))
+ self.assertEqual(json.loads((output / 'result.json').read_text())['status'], 'failed')
+ self.assertEqual(json.loads((output / 'package/result.json').read_text())['status'], 'awaiting_runtime')
+
+ def test_missing_sccache_never_mounts_the_current_directory_as_a_binary(self):
+ with patch.object(container.shutil, 'which', side_effect=lambda name: '/usr/bin/docker' if name == 'docker' else None):
+ with self.assertRaisesRegex(ValueError, 'sccache'):
+ container.run(self.target, self.source)
+
+ def test_failed_image_prerequisite_retains_red_evidence_before_product_build(self):
+ def failed_prerequisite(args, **_):
+ self.commands.append(args)
+ return subprocess.CompletedProcess(args, 100)
+
+ with patch.object(container.subprocess, 'run', side_effect=failed_prerequisite):
+ with self.assertRaises(subprocess.CalledProcessError):
+ container.run(self.target, self.source)
+ self.assertEqual(len(self.commands), 1)
+ self.assertEqual(self.commands[0][:2], ['docker', 'build'])
+ output = next((self.root / 'target/release-candidate').glob('**/container-*'))
+ result = json.loads((output / 'result.json').read_text())
+ self.assertEqual(result['status'], 'failed')
+ self.assertIn('100', result['error'])
+ self.assertEqual(result['revision'], self.revision)
+ self.assertEqual(result['baseline'], abi.baseline())
+ self.assertFalse((self.root / 'target/.linux-release-baseline.json').exists())
+
+ def test_existing_proxy_names_reach_builds_without_values_or_runtime_forwarding(self):
+ proxies = {'HTTPS_PROXY': 'https://fixture-proxy.invalid/private-value',
+ 'http_proxy': 'http://fixture-proxy.invalid/private-value',
+ 'ALL_PROXY': 'socks5://fixture-proxy.invalid/private-value',
+ 'NO_PROXY': 'fixture-bypass.invalid'}
+ with patch.dict(os.environ, proxies, clear=True):
+ container.run(self.target, self.source)
+ docker_build = self.commands[0]
+ build_arguments = [docker_build[index + 1] for index, value in enumerate(docker_build)
+ if value == '--build-arg']
+ build = next(args for args in self.commands if 'scripts/build-release.py' in args)
+ build_environment = [build[index + 1] for index, value in enumerate(build) if value == '-e']
+ runtime_arguments = next(args for args in self.commands
+ if any(value.endswith('linux-release-runtime.py') for value in args))
+ runtime_environment = [runtime_arguments[index + 1] for index, value in enumerate(runtime_arguments)
+ if value == '-e']
+ for name, secret_value in proxies.items():
+ with self.subTest(name=name):
+ self.assertIn(name, build_arguments)
+ self.assertIn(name, build_environment)
+ self.assertFalse(any(value == name or value.startswith(name + '=') for value in runtime_environment))
+ self.assertFalse(any(secret_value in argument for args in self.commands for argument in args))
+
+ def test_unset_proxies_are_not_added_to_build_or_runtime_arguments(self):
+ with patch.dict(os.environ, {}, clear=True):
+ container.run(self.target, self.source)
+ for args in self.commands:
+ self.assertFalse(any(argument.lower().split('=', 1)[0] in
+ {'http_proxy', 'https_proxy', 'ftp_proxy', 'all_proxy', 'no_proxy'}
+ for argument in args))
+
+ def test_builds_share_host_proxy_network_while_minimum_runtime_is_offline(self):
+ with patch.dict(os.environ, {'HTTPS_PROXY': 'http://127.0.0.1:12345'}, clear=True):
+ container.run(self.target, self.source)
+ docker_build = self.commands[0]
+ compiler = next(args for args in self.commands if 'scripts/build-release.py' in args)
+ runtime = next(args for args in self.commands
+ if any(value.endswith('linux-release-runtime.py') for value in args))
+ for stage, args in (('recipe', docker_build), ('compiler', compiler), ('runtime', runtime)):
+ with self.subTest(stage=stage):
+ networks = [args[index + 1] for index, value in enumerate(args) if value == '--network']
+ self.assertEqual(networks, ['none'] if stage == 'runtime' else ['host'])
+ runtime_environment = [runtime[index + 1] for index, value in enumerate(runtime) if value == '-e']
+ self.assertNotIn('HTTPS_PROXY', runtime_environment)
+
+ def test_sccache_ipc_stays_in_the_container_filesystem(self):
+ with patch.dict(os.environ, {'SCCACHE_SERVER_PORT': '4226',
+ 'SCCACHE_SERVER_UDS': '/sccache/shared.sock'}):
+ container.run(self.target, self.source)
+ compiler = next(args for args in self.commands if 'scripts/build-release.py' in args)
+ environment = [compiler[index + 1] for index, value in enumerate(compiler) if value == '-e']
+ self.assertIn('SCCACHE_SERVER_UDS=/tmp/hiroute-release-sccache.sock', environment)
+ self.assertFalse(any(value.split('=', 1)[0] == 'SCCACHE_SERVER_PORT' for value in environment))
+ self.assertNotIn('SCCACHE_SERVER_UDS=/sccache/shared.sock', environment)
+ mounts = [compiler[index + 1].split(':')[1] for index, value in enumerate(compiler) if value == '-v']
+ self.assertFalse(any('/tmp/hiroute-release-sccache.sock'.startswith(path.rstrip('/') + '/')
+ for path in mounts))
+ runtime = next(args for args in self.commands
+ if any(value.endswith('linux-release-runtime.py') for value in args))
+ self.assertFalse(any(value.startswith('SCCACHE_') for value in runtime))
+
+ def test_selected_sccache_mount_takes_precedence_over_cargo_home_tools(self):
+ container.run(self.target, self.source)
+ compiler = next(args for args in self.commands if 'scripts/build-release.py' in args)
+ environment = [compiler[index + 1] for index, value in enumerate(compiler) if value == '-e']
+ paths = next(value.split('=', 1)[1].split(':') for value in environment if value.startswith('PATH='))
+ self.assertLess(paths.index('/usr/local/bin'), paths.index('/opt/cargo/bin'))
+ mounts = [compiler[index + 1] for index, value in enumerate(compiler) if value == '-v']
+ self.assertIn(str(self.sccache) + ':/usr/local/bin/sccache:ro', mounts)
+
+ def test_disabled_attestations_preserve_stable_identity_in_both_image_stores(self):
+ for store in ('classic', 'containerd'):
+ with self.subTest(store=store):
+ stamp = self.root / 'target/.linux-release-baseline.json'
+ stamp.unlink(missing_ok=True)
+ self.image_id = 'sha256:' + 'c' * 64
+ self.include_config_metadata = store == 'classic'
+ self.attestation_sensitive = store == 'containerd'
+ first = container.run(self.target, self.source)
+ second = container.run(self.target, self.source)
+ self.assertEqual(second['status'], 'completed')
+ self.assertEqual(first['build_image_id'], second['build_image_id'])
+ self.assertTrue(all('--provenance=false' in args for args in self.commands
+ if args[:2] == ['docker', 'build']))
+ identity = json.loads(stamp.read_text())
+ self.assertEqual(identity['image_digest'], self.image_id)
+
+ def test_changed_runtime_image_is_rejected_in_both_image_stores(self):
+ for store in ('classic', 'containerd'):
+ with self.subTest(store=store):
+ stamp = self.root / 'target/.linux-release-baseline.json'
+ stamp.unlink(missing_ok=True)
+ self.include_config_metadata = store == 'classic'
+ self.image_id = 'sha256:' + 'c' * 64
+ self.image_config_digest = self.image_id
+ container.run(self.target, self.source)
+ self.image_id = 'sha256:' + 'd' * 64
+ if store == 'classic': self.image_config_digest = self.image_id
+ with self.assertRaisesRegex(ValueError, 'different Linux build baseline'):
+ container.run(self.target, self.source)
+
+ def test_invalid_image_digest_fails_before_product_build(self):
+ for image_id in ('', 'sha256:short', 'sha256:' + 'G' * 64, 'not-a-digest'):
+ with self.subTest(image_id=image_id):
+ self.commands.clear()
+ self.image_id = image_id
+ with self.assertRaisesRegex(ValueError, 'image digest'):
+ container.run(self.target, self.source)
+ self.assertEqual(len(self.commands), 1)
+
+ def test_unpublished_old_stamp_requires_a_fresh_worktree(self):
+ stamp = self.root / 'target/.linux-release-baseline.json'
+ stamp.parent.mkdir()
+ stamp.write_text(json.dumps({'image': self.image_id, 'target': self.target}))
+ with self.assertRaisesRegex(ValueError, 'different Linux build baseline'):
+ container.run(self.target, self.source)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index cea0ab42..45405287 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -44,9 +44,11 @@ PI_WORKER_BRIDGE_TEST = "crates/daemon/src/delegation/profile/pi_worker_bridge.t
PI_SDK_CONTRACT_TEST = "crates/integrations/src/agents/pi_sdk_contract.test.mjs"
INTEGRATION_SKILL = ".agents/skills/hiroute-integrate/SKILL.md"
WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}
-RELEASE_BUILD_TESTS = ("test-build-cpa.py", "test-build-release.py", "test-package-desktop.py",
+RELEASE_BUILD_TESTS = ("test-build-cpa.py", "test-build-release.py", "test-linux-release.py", "test-package-desktop.py",
"test-standalone-install.py", "test-third-party-licenses.py")
-RELEASE_BUILD_TOOLING = {".github/workflows/build-release.yml", "scripts/build-release.py",
+RELEASE_BUILD_TOOLING = {"scripts/linux-release-abi.py", "scripts/linux-release-runtime.py",
+ "scripts/linux-release-container.py", "scripts/linux-release-baseline.json",
+ "scripts/linux-release.Dockerfile", ".github/workflows/build-release.yml", "scripts/build-release.py",
"scripts/build-cpa.py", "scripts/package-desktop.py",
"scripts/package-standalone.py", "scripts/install-standalone.py",
"scripts/collect-third-party-licenses.py",
diff --git a/scripts/test-standalone-install.py b/scripts/test-standalone-install.py
index 557b8f57..af7a1bf5 100755
--- a/scripts/test-standalone-install.py
+++ b/scripts/test-standalone-install.py
@@ -210,6 +210,77 @@ class InstallerTests(StandaloneFixture):
installer.prepare_service_directory(self.home)
self.assertEqual(local.stat().st_mode & 0o777, 0o775)
+ def test_default_state_parents_are_private_with_group_writable_umask(self):
+ manifest, archive = self.build()
+ previous = os.umask(0o002)
+ try:
+ with patch.dict(os.environ, {"HOME": str(self.home)}, clear=True), patch.object(
+ installer.subprocess, "run"
+ ), patch("builtins.print"):
+ installer.install(self.install_args(manifest, archive))
+ for relative in (".local/state", ".local/state/hiroute", ".local/state/hiroute/run"):
+ self.assertEqual((self.home / relative).stat().st_mode & 0o777, 0o700)
+ finally:
+ os.umask(previous)
+
+ def test_nested_xdg_state_parents_are_private_with_group_writable_umask(self):
+ manifest, archive = self.build()
+ previous = os.umask(0o002)
+ try:
+ environment = {"HOME": str(self.home), "XDG_STATE_HOME": str(self.home / "custom/nested/state")}
+ with patch.dict(os.environ, environment, clear=True), patch.object(
+ installer.subprocess, "run"
+ ), patch("builtins.print"):
+ installer.install(self.install_args(manifest, archive))
+ for relative in ("custom", "custom/nested", "custom/nested/state", "custom/nested/state/hiroute"):
+ self.assertEqual((self.home / relative).stat().st_mode & 0o777, 0o700)
+ finally:
+ os.umask(previous)
+
+ def test_install_rejects_symlink_state_parent(self):
+ manifest, archive = self.build()
+ local = self.home / ".local"
+ local.mkdir(mode=0o700)
+ shared = self.root / "shared-state"
+ shared.mkdir(mode=0o700)
+ state = local / "state"
+ state.symlink_to(shared)
+ with patch.dict(os.environ, {"HOME": str(self.home)}, clear=True), patch.object(
+ installer.subprocess, "run"
+ ), patch("builtins.print"):
+ with self.assertRaisesRegex(ValueError, "state parent is unsafe"):
+ installer.install(self.install_args(manifest, archive))
+ self.assertTrue(state.is_symlink())
+ self.assertEqual(list(shared.iterdir()), [])
+ self.assertFalse((local / "bin/hiroute").exists())
+
+ def test_install_rejects_group_writable_state_parent_without_chmod(self):
+ manifest, archive = self.build()
+ state = self.home / ".local/state"
+ state.parent.mkdir(mode=0o700)
+ state.mkdir(mode=0o775)
+ state.chmod(0o775)
+ with patch.dict(os.environ, {"HOME": str(self.home)}, clear=True), patch.object(
+ installer.subprocess, "run"
+ ), patch("builtins.print"):
+ with self.assertRaisesRegex(ValueError, "state parent is unsafe"):
+ installer.install(self.install_args(manifest, archive))
+ self.assertEqual(state.stat().st_mode & 0o777, 0o775)
+ self.assertFalse((self.home / ".local/bin/hiroute").exists())
+
+ def test_safe_existing_state_parent_permissions_are_preserved(self):
+ manifest, archive = self.build()
+ state = self.home / ".local/state"
+ state.parent.mkdir(mode=0o700)
+ state.mkdir(mode=0o755)
+ state.chmod(0o755)
+ with patch.dict(os.environ, {"HOME": str(self.home)}, clear=True), patch.object(
+ installer.subprocess, "run"
+ ), patch("builtins.print"):
+ installer.install(self.install_args(manifest, archive))
+ self.assertEqual(state.stat().st_mode & 0o777, 0o755)
+ self.assertEqual((state / "hiroute").stat().st_mode & 0o777, 0o700)
+
def test_install_lock_rejects_concurrent_mutation(self):
with self.environment():
paths = installer.layout(self.home)