From 5cc41008ebb6b8c3cfdca854fa4fcead562aa1d4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 16:03:43 +0200 Subject: [PATCH 01/14] Build opt-in KAR PLE CUDA profile on Gitea --- .github/workflows/linux.yml | 81 +++++++++++++++++++--- deploy/Dockerfile.cuda-builder | 16 +++++ deploy/README.md | 1 + docs/compressed-runtime.md | 19 +++++ scripts/build-linux-package.py | 44 ++++++++++++ scripts/build-runtime-image.py | 29 ++++++++ scripts/build-static-cuda.sh | 71 +++++++++++++++++-- scripts/check-local.sh | 1 + scripts/test-linux-package.py | 22 ++++++ scripts/test-runtime-image.py | 49 +++++++++++++ scripts/test-static-cuda-profile.py | 103 ++++++++++++++++++++++++++++ 11 files changed, 422 insertions(+), 14 deletions(-) create mode 100644 deploy/Dockerfile.cuda-builder create mode 100644 scripts/test-static-cuda-profile.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index bff86839..2fef89d2 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -15,6 +15,10 @@ on: description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) type: boolean default: false + hosted_cuda_ple: + description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default) + type: boolean + default: false static_cuda_package: description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference) type: boolean @@ -67,6 +71,7 @@ jobs: engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" python3 scripts/build-linux-package.py --engine "$engine" \ --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \ --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 @@ -101,15 +106,17 @@ jobs: run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" hosted-cuda-package: - if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private + if: github.event_name == 'workflow_dispatch' && (inputs.hosted_cuda_package || inputs.hosted_cuda_ple) && github.event.repository.private needs: verify runs-on: ubuntu-24.04 timeout-minutes: 150 env: CUDA_VISIBLE_DEVICES: '' + NVIDIA_VISIBLE_DEVICES: void BUILD_JOBS: '1' CARGO_BUILD_JOBS: '2' CUDA_ARCHITECTURES: '120' + STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} steps: - uses: actions/checkout@v4 - name: Install compatible host tools (no drivers) @@ -117,31 +124,86 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - sudo apt-get update && sudo apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils + sudo apt-get update && sudo apt-get install -y musl-tools binutils - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" + - name: Build pinned GPU-hidden compiler image + env: + CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b + CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} + run: | + context="$RUNNER_TEMP/strata-cuda-builder-context" + mkdir -p "$context" + cp deploy/Dockerfile.cuda-builder "$context/Dockerfile" + cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt" + docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \ + --tag "$CUDA_BUILDER_IMAGE" "$context" + docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" - name: Record actual toolchain + env: + CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} + CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b run: | "$CUDACXX" --version - g++-13 --version + docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version df -h "$RUNNER_TEMP" free -h python3 - <<'PYTOOL' import json, os, platform, subprocess from pathlib import Path info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) + packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', + os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}\\n', + 'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines() + gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', + os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True) info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), - gcc=subprocess.check_output(['g++-13','--version'],text=True), + builder_base=os.environ['CUDA_BUILDER_BASE'], + builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(), + builder_packages=packages, + gcc=gcc, nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True), cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False) (Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n') PYTOOL - name: Build actual static CUDA engine and audit without GPU env: - CC: gcc-13 - CXX: g++-13 - CUDAHOSTCXX: g++-13 - run: scripts/build-static-cuda.sh + CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} + STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} + run: | + mkdir -p "$STRATA_BUILD_DIR" + docker run --rm --platform linux/amd64 --network bridge --read-only \ + --user "$(id -u):$(id -g)" --cap-drop ALL --security-opt no-new-privileges \ + --tmpfs /tmp:rw,nosuid,size=2g \ + -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ + -e CUDACXX=/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/toolkit \ + -e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \ + -e BUILD_JOBS=1 -e CUDA_ARCHITECTURES -e STRATA_KAR_PLE \ + -e STRATA_BUILD_DIR=/build \ + --mount "type=bind,src=$GITHUB_WORKSPACE,dst=/workspace,readonly" \ + --mount "type=bind,src=$CUDAToolkit_ROOT,dst=/toolkit,readonly" \ + --mount "type=bind,src=$STRATA_BUILD_DIR,dst=/build" \ + "$CUDA_BUILDER_IMAGE" /bin/bash -euo pipefail -c ' + if compgen -G "/dev/nvidia*" >/dev/null; then + echo "NVIDIA devices unexpectedly visible in build container" >&2 + exit 1 + fi + cd /workspace + scripts/build-static-cuda.sh + ' + - name: Bind compile capability to CUDA toolchain provenance + run: | + python3 - <<'PYFEATURES' + import hashlib, json, os + from pathlib import Path + features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json' + features=json.loads(features_path.read_text()) + toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' + info=json.loads(toolchain_path.read_text()) + info['build_features']=features['features'] + info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest() + toolchain_path.write_text(json.dumps(info,indent=2)+'\n') + PYFEATURES - name: Install pinned Rust and musl target run: | rustup toolchain install 1.99.0 --profile minimal @@ -161,6 +223,7 @@ jobs: package="$RUNNER_TEMP/strata-hosted-cuda-package" /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \ --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \ --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" python3 scripts/build-runtime-image.py --package "$package" \ --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ @@ -188,6 +251,8 @@ jobs: docker image rm "$image" fi rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build" + docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true + rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" linux-static-cli: needs: verify diff --git a/deploy/Dockerfile.cuda-builder b/deploy/Dockerfile.cuda-builder new file mode 100644 index 00000000..98506466 --- /dev/null +++ b/deploy/Dockerfile.cuda-builder @@ -0,0 +1,16 @@ +ARG BUILDER_BASE=ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b +FROM ${BUILDER_BASE} + +# The caller supplies its verified runner CA bundle as build context. This +# lets later TLS fetches use the runner's complete trust store. +COPY runner-ca-bundle.crt /tmp/runner-ca-bundle.crt +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + binutils ca-certificates cmake gcc-13 g++-13 git make python3 \ + && cp /tmp/runner-ca-bundle.crt /etc/ssl/certs/ca-certificates.crt \ + && rm -f /tmp/runner-ca-bundle.crt \ + && rm -rf /var/lib/apt/lists/* + +LABEL org.opencontainers.image.title="Leleka GPU-hidden CUDA build environment" +LABEL org.opencontainers.image.description="CPU-only container for compiling the pinned CUDA engine; no NVIDIA driver or device is installed" diff --git a/deploy/README.md b/deploy/README.md index 1010ce20..bced26cf 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -977,6 +977,7 @@ engine="$PWD/artifacts/build-static-cuda/strata" python3 scripts/build-linux-package.py \ --engine "$engine" --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" \ --revision "$(git rev-parse HEAD)" \ + --build-features "$PWD/artifacts/build-static-cuda/BUILD-FEATURES.json" \ --cargo-target-dir "$PWD/artifacts/combined-build" \ --output "$PWD/artifacts/combined-v1" ``` diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 5c027abc..0ecc58c3 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -15,6 +15,25 @@ still checks payload CRCs. The feature is off in ordinary builds. `strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for comparison with `strata-next model checksum-kar-row` on the matching part. +### Static CUDA PLE package profile + +`scripts/build-static-cuda.sh` accepts only `STRATA_KAR_PLE=0|1`; it defaults +to `0`. The script always resets the cached PLE, expert-KAR, and PLE-trace +CMake options explicitly, so reusing a build directory cannot accidentally +retain those experimental arms. `STRATA_KAR_PLE=1` compiles the existing PLE +implementation from `gpu/kar`; it does not select a model, archive, PLE level, +or runtime profile. The private Gitea `hosted_cuda_package` workflow exposes +this build capability as a separate boolean, defaulting off, and binds the +selected flags and CUDA architecture into the checksummed package provenance. + +The CUDA runtime and C++ runtime are statically linked for the engine build. +The NVIDIA driver and host glibc remain system dependencies; this is not a +fully static CUDA executable and does not eliminate driver compatibility. +The combined outer CLI is separately built for musl. Neither static linking +nor a PLE-enabled package proves GPU inference, model quality, or a speedup; +the serving profile must still explicitly select the model's PLE archive, +level, and cache budget after the separate GPU gates pass. + This arm measures whether PLE transcoding changes whole-model output and task quality. It does not load the full compressed model, stage sparse PLE packets to CUDA, or establish a model throughput gain. Use the same engine source, diff --git a/scripts/build-linux-package.py b/scripts/build-linux-package.py index 5688d067..7a23774e 100644 --- a/scripts/build-linux-package.py +++ b/scripts/build-linux-package.py @@ -31,6 +31,43 @@ def sha256(path): return hashlib.file_digest(source, 'sha256').hexdigest() +def build_features(path, revision): + """Read a bounded, exact-schema static CUDA feature receipt without following links.""" + if path is None: + return None + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + if not stat.S_ISREG(os.fstat(source.fileno()).st_mode): + raise ValueError('build feature receipt must be a regular file') + raw = source.read(65537) + if len(raw) > 65536: + raise ValueError('build feature receipt exceeds size limit') + try: + record = json.loads(raw) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise ValueError('build feature receipt must be UTF-8 JSON') from error + if (not isinstance(record, dict) or set(record) != { + 'schema_version', 'source_revision', 'cuda_architectures', 'features'} or + type(record['schema_version']) is not int or record['schema_version'] != 1 or + record['source_revision'] != revision or + not isinstance(record['cuda_architectures'], str) or + not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*', + record['cuda_architectures'])): + raise ValueError('unsupported or source-mismatched build feature receipt') + canonical = (json.dumps(record, sort_keys=True, indent=2) + '\n').encode() + if raw != canonical: + raise ValueError('build feature receipt is not canonical JSON') + features = record['features'] + if (not isinstance(features, dict) or set(features) != { + 'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or + any(type(value) is not bool for value in features.values()) or + features['cuda'] is not True or features['cuda_static_runtime'] is not True or + features['cxx_static_runtime'] is not True or + features['kar_experts'] is not False or features['ple_trace'] is not False): + raise ValueError('build feature receipt violates the static CUDA PLE package contract') + return record, hashlib.sha256(raw).hexdigest() + + def source_check(repo, revision): if not re.fullmatch(r'[0-9a-f]{40}', revision): raise ValueError('source revision must be a full lowercase Git SHA') @@ -96,6 +133,9 @@ def assemble(args): if platform.system() != 'Linux' or platform.machine() != 'x86_64': raise ValueError('package assembly requires Linux x86_64') source_check(REPO, args.revision) + features = build_features(getattr(args, 'build_features', None), args.revision) + if args.cpu_fixture and features is not None: + raise ValueError('CPU fixtures cannot claim CUDA build features') output = args.output.absolute() output.parent.mkdir(parents=True, exist_ok=True) output = output.parent.resolve() / output.name @@ -149,6 +189,8 @@ def assemble(args): 'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False, 'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.', 'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'} + if features is not None: + provenance['build_features'], provenance['build_features_sha256'] = features (published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n') (published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json'])) if os.path.lexists(output): @@ -165,6 +207,8 @@ def main(): parser.add_argument('--output', type=Path, required=True) parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently') parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release') + parser.add_argument('--build-features', type=Path, + help='exact build feature receipt emitted by build-static-cuda.sh') args = parser.parse_args() try: print(json.dumps(assemble(args))) diff --git a/scripts/build-runtime-image.py b/scripts/build-runtime-image.py index bfe4d491..282bc9df 100644 --- a/scripts/build-runtime-image.py +++ b/scripts/build-runtime-image.py @@ -62,6 +62,32 @@ def freeze(package, stage, receipt_sha, cpu_fixture): 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') + feature_record = p.get('build_features') + feature_sha = p.get('build_features_sha256') + if feature_record is not None or feature_sha is not None: + if (not isinstance(feature_record, dict) or set(feature_record) != { + 'schema_version', 'source_revision', 'cuda_architectures', 'features'} or + type(feature_record['schema_version']) is not int or feature_record['schema_version'] != 1 or + feature_record['source_revision'] != p['source_revision'] or + not isinstance(feature_record['cuda_architectures'], str) or + not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*', + feature_record['cuda_architectures']) or + not isinstance(feature_sha, str) or + not re.fullmatch(r'[0-9a-f]{64}', feature_sha)): + raise ValueError('invalid static CUDA build feature provenance') + feature_values = feature_record['features'] + if (not isinstance(feature_values, dict) or set(feature_values) != { + 'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or + any(type(value) is not bool for value in feature_values.values()) or + feature_values['cuda'] is not True or feature_values['cuda_static_runtime'] is not True or + feature_values['cxx_static_runtime'] is not True or + feature_values['kar_experts'] is not False or feature_values['ple_trace'] is not False): + raise ValueError('invalid static CUDA feature selection') + canonical = (json.dumps(feature_record, sort_keys=True, indent=2) + '\n').encode() + if hashlib.sha256(canonical).hexdigest() != feature_sha: + raise ValueError('static CUDA build feature digest mismatch') + elif not cpu_fixture: + raise ValueError('CUDA package lacks an explicit build feature receipt') 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 @@ -140,6 +166,9 @@ def assemble(args): '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.'} + if p.get('build_features') is not None: + result['build_features'] = p['build_features']['features'] + result['build_features_sha256'] = p['build_features_sha256'] success = True return result finally: diff --git a/scripts/build-static-cuda.sh b/scripts/build-static-cuda.sh index 72951036..0d6e1f59 100755 --- a/scripts/build-static-cuda.sh +++ b/scripts/build-static-cuda.sh @@ -6,17 +6,76 @@ build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-static-cuda}" jobs="${BUILD_JOBS:-2}" [[ "$(uname -s)" == Linux ]] || { echo 'Static CUDA engine builds require Linux.' >&2; exit 1; } -# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML. -extra=() -if [[ -n "${STRATA_GGML_DIR:-}" ]]; then - extra+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}") +if [[ ${STRATA_KAR_PLE+x} ]]; then + kar_ple="${STRATA_KAR_PLE}" +else + kar_ple=0 fi -cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \ +case "${kar_ple}" in + 0) cmake_kar_ple=OFF ;; + 1) cmake_kar_ple=ON ;; + *) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;; +esac + +# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML. +cmake_args=( + -S "${repo_root}/engine/strata" -B "${build_dir}" -DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF -DSTRATA_CUDA_STATIC=ON \ -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="${CUDA_ARCHITECTURES:-120}" \ + -DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE="${cmake_kar_ple}" \ + -DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=OFF \ + -DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE=OFF \ + -DSTRATA_NEXT_KAR_DIR="${repo_root}/gpu/kar" \ -DSTRATA_BUILD_TESTS=OFF -DSTRATA_NATIVE_EXPERTS=ON \ - -DSTRATA_PORTABLE=ON "${extra[@]}" + -DSTRATA_PORTABLE=ON +) +if [[ -n "${STRATA_GGML_DIR:-}" ]]; then + cmake_args+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}") +fi +cmake "${cmake_args[@]}" cmake --build "${build_dir}" --parallel "${jobs}" --target strata python3 "${repo_root}/scripts/check-static-cuda-elf.py" "${build_dir}/strata" # generate.cpp handles --help before any model or GPU initialization. env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help + +# This records compile capability only. The runtime still requires an explicit +# model/profile selection; PLE is experimental and defaults off at serving time. +python3 - "${repo_root}" "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" <<'PYFEATURES' +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +repo, destination, ple, architectures = sys.argv[1:] +revision = subprocess.check_output(['git', '-C', repo, 'rev-parse', 'HEAD'], text=True).strip() +if len(revision) != 40 or any(ch not in '0123456789abcdef' for ch in revision): + raise SystemExit('could not record an exact source revision') +record = { + 'schema_version': 1, + 'source_revision': revision, + 'cuda_architectures': architectures, + 'features': { + 'cuda': True, + 'cuda_static_runtime': True, + 'cxx_static_runtime': True, + 'kar_ple': ple == '1', + 'kar_experts': False, + 'ple_trace': False, + }, +} +path = Path(destination) +path.parent.mkdir(parents=True, exist_ok=True) +fd, temporary = tempfile.mkstemp(prefix='.BUILD-FEATURES-', dir=path.parent) +try: + with os.fdopen(fd, 'w') as output: + json.dump(record, output, sort_keys=True, indent=2) + output.write('\n') + output.flush() + os.fsync(output.fileno()) + os.replace(temporary, path) +finally: + if os.path.exists(temporary): + os.unlink(temporary) +PYFEATURES diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 27af6254..97ad6a99 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -10,6 +10,7 @@ python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-menu.py" python3 "${repo_root}/scripts/test-model-switch.py" python3 "${repo_root}/scripts/test-cuda-bootstrap.py" +python3 "${repo_root}/scripts/test-static-cuda-profile.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" diff --git a/scripts/test-linux-package.py b/scripts/test-linux-package.py index 13e931a7..bb8507fd 100644 --- a/scripts/test-linux-package.py +++ b/scripts/test-linux-package.py @@ -35,6 +35,28 @@ class PackageTests(unittest.TestCase): with self.assertRaises(ValueError): pkg.snapshot(source, self.root / pin, pin) + def test_build_feature_receipt_is_pinned_strict_and_linkage_safe(self): + revision = 'a' * 40 + features = {'schema_version': 1, 'source_revision': revision, + 'cuda_architectures': '120', + 'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True, + 'kar_experts': False, 'ple_trace': False}} + path = self.root / 'BUILD-FEATURES.json' + path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n') + parsed, digest = pkg.build_features(path, revision) + self.assertEqual(parsed, features) + self.assertEqual(digest, hashlib.sha256(path.read_bytes()).hexdigest()) + with self.assertRaisesRegex(ValueError, 'source-mismatched'): + pkg.build_features(path, 'b' * 40) + features['features']['kar_experts'] = True + path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n') + with self.assertRaisesRegex(ValueError, 'contract'): + pkg.build_features(path, revision) + path.unlink() + path.symlink_to('/dev/null') + with self.assertRaises(OSError): + pkg.build_features(path, revision) + def test_snapshot_rejects_oversize_and_nonregular_without_block(self): source = self.root / 'engine' source.write_bytes(b'over limit') diff --git a/scripts/test-runtime-image.py b/scripts/test-runtime-image.py index 5fcf9034..ea44f90d 100644 --- a/scripts/test-runtime-image.py +++ b/scripts/test-runtime-image.py @@ -1,8 +1,10 @@ #!/usr/bin/env python3 """Package corruption and ABI rejection without Docker or GPU access.""" import importlib.util +import hashlib import json from pathlib import Path +import shutil import tempfile import unittest from types import SimpleNamespace @@ -26,6 +28,13 @@ class PackageTests(unittest.TestCase): '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'}} + features = {'schema_version': 1, 'source_revision': 'a'*40, + 'cuda_architectures': '120', + 'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, + 'kar_ple': False, 'kar_experts': False, 'ple_trace': False}} + canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode() + self.provenance['build_features'] = features + self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest() (self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input') self.write() @@ -46,6 +55,46 @@ class PackageTests(unittest.TestCase): b.check_glibc(p, 'glibc 2.39\n') with self.assertRaises(ValueError): b.check_glibc(p, 'musl 1.2.5') + def test_static_cuda_feature_receipt_is_preserved_and_digest_checked(self): + features = {'schema_version': 1, 'source_revision': 'a'*40, + 'cuda_architectures': '120', + 'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True, + 'kar_experts': False, 'ple_trace': False}} + canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode() + self.provenance['build_features'] = features + self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest() + self.write() + p = self.freeze() + self.assertTrue(p['build_features']['features']['kar_ple']) + self.provenance['build_features_sha256'] = '0'*64 + self.write() + shutil.rmtree(self.stage) + self.stage.mkdir() + with self.assertRaisesRegex(ValueError, 'digest mismatch'): + self.freeze() + + def test_image_receipt_carries_ple_profile_without_gpu_claim(self): + self.provenance['build_features']['features']['kar_ple'] = True + canonical = (json.dumps(self.provenance['build_features'], sort_keys=True, indent=2) + '\n').encode() + self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest() + self.write() + args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False) + image = 'sha256:' + 'c'*64 + calls = [] + def docker(*argv, **kwargs): + calls.append(argv) + if argv[0] == 'build': + Path(argv[argv.index('--iidfile')+1]).write_text(image) + return SimpleNamespace(stdout='') + engine_info = json.dumps(self.provenance['engine']) + with patch.object(b, 'docker', side_effect=docker), \ + patch.object(b, 'isolated_run', side_effect=['glibc 2.43', engine_info, 'help']): + result = b.assemble(args) + self.assertEqual(result['build_features']['kar_ple'], True) + self.assertEqual(result['build_features_sha256'], self.provenance['build_features_sha256']) + self.assertFalse(result['gpu_tested']) + self.assertFalse(any('--gpus' in call for call in calls)) + 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() diff --git a/scripts/test-static-cuda-profile.py b/scripts/test-static-cuda-profile.py new file mode 100644 index 00000000..03f86235 --- /dev/null +++ b/scripts/test-static-cuda-profile.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Exercise the static CUDA PLE build contract with a mocked Linux toolchain.""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).with_name('build-static-cuda.sh') + + +class StaticCudaProfileTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='strata-cuda-profile-') + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.repo = self.root / 'repo' + (self.repo / 'scripts').mkdir(parents=True) + (self.repo / 'engine/strata').mkdir(parents=True) + shutil.copyfile(SCRIPT, self.repo / 'scripts/build-static-cuda.sh') + checker = self.repo / 'scripts/check-static-cuda-elf.py' + checker.write_text('raise SystemExit(0)\n') + self.bin = self.root / 'bin' + self.bin.mkdir() + (self.bin / 'uname').write_text('#!/bin/sh\necho Linux\n') + (self.bin / 'cmake').write_text( + '#!/usr/bin/env python3\n' + 'import json, os, pathlib, sys\n' + 'with open(os.environ["CMAKE_CAPTURE"], "a") as out: out.write(json.dumps(sys.argv[1:])+"\\n")\n' + 'if "--build" in sys.argv:\n' + ' b=pathlib.Path(sys.argv[sys.argv.index("--build")+1]); b.mkdir(parents=True, exist_ok=True)\n' + ' p=b/"strata"; p.write_text("#!/bin/sh\\necho help\\n"); p.chmod(0o755)\n') + for executable in self.bin.iterdir(): executable.chmod(0o755) + self.capture = self.root / 'cmake.jsonl' + self.build = self.root / 'build' + subprocess.run(['git', 'init', '-q', str(self.repo)], check=True) + subprocess.run(['git', '-C', str(self.repo), 'add', '.'], check=True) + subprocess.run(['git', '-C', str(self.repo), '-c', 'user.email=fixture@example.invalid', + '-c', 'user.name=Fixture', 'commit', '-qm', 'mock toolchain fixture'], check=True) + + def run_profile(self, value='unset'): + env = dict(os.environ) + env.update(PATH=f'{self.bin}{os.pathsep}{env["PATH"]}', + STRATA_BUILD_DIR=str(self.build), CMAKE_CAPTURE=str(self.capture), + CUDA_ARCHITECTURES='120') + env.pop('STRATA_KAR_PLE', None) + if value != 'unset': + env['STRATA_KAR_PLE'] = value + return subprocess.run(['bash', str(self.repo / 'scripts/build-static-cuda.sh')], + env=env, text=True, capture_output=True) + + def captured_configure(self): + calls = [json.loads(line) for line in self.capture.read_text().splitlines()] + configure = next(call for call in reversed(calls) if '-S' in call) + return {arg.split('=', 1)[0]: arg.split('=', 1)[1] + for arg in configure if arg.startswith('-D') and '=' in arg} + + def test_defaults_off_and_explicitly_keeps_static_cuda_runtime(self): + result = self.run_profile() + self.assertEqual(result.returncode, 0, result.stderr) + flags = self.captured_configure() + self.assertEqual(flags['-DSTRATA_CUDA_STATIC'], 'ON') + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF') + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF') + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF') + self.assertEqual(flags['-DSTRATA_NEXT_KAR_DIR'], str(self.repo / 'gpu/kar')) + features = json.loads((self.build / 'BUILD-FEATURES.json').read_text()) + self.assertFalse(features['features']['kar_ple']) + self.assertTrue(features['features']['cuda_static_runtime']) + self.assertTrue(features['features']['cxx_static_runtime']) + + def test_enabled_profile_is_build_only_and_expert_arm_stays_off(self): + result = self.run_profile('1') + self.assertEqual(result.returncode, 0, result.stderr) + flags = self.captured_configure() + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'ON') + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF') + self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF') + self.assertTrue(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple']) + + def test_explicit_disable_resets_an_existing_cmake_cache(self): + self.assertEqual(self.run_profile('1').returncode, 0) + result = self.run_profile('0') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.captured_configure()['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF') + self.assertFalse(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple']) + + def test_invalid_values_fail_before_cmake(self): + for value in ('', 'true', 'ON', '2', '01'): + with self.subTest(value=value): + self.capture.unlink(missing_ok=True) + result = self.run_profile(value) + self.assertEqual(result.returncode, 2) + self.assertIn('exactly 0 or 1', result.stderr) + self.assertFalse(self.capture.exists()) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From 5c4aa294c864f7c973da1cd282458697425bda11 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 16:04:52 +0200 Subject: [PATCH 02/14] Match Gitea Linux runner label --- .github/workflows/linux.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 2fef89d2..26a0ec87 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -29,7 +29,7 @@ permissions: jobs: verify: - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install build tools @@ -108,7 +108,7 @@ jobs: hosted-cuda-package: if: github.event_name == 'workflow_dispatch' && (inputs.hosted_cuda_package || inputs.hosted_cuda_ple) && github.event.repository.private needs: verify - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest timeout-minutes: 150 env: CUDA_VISIBLE_DEVICES: '' @@ -256,7 +256,7 @@ jobs: linux-static-cli: needs: verify - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install musl toolchain @@ -392,7 +392,7 @@ jobs: linux-cli-container: needs: verify - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build actual CLI-only scratch image @@ -406,7 +406,7 @@ jobs: release-cli: if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest permissions: contents: write steps: -- 2.54.0 From a6712713177127989d898d36e6e3d7bad56085a5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 16:17:53 +0200 Subject: [PATCH 03/14] Use root package install in Gitea job containers --- .github/workflows/linux.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 26a0ec87..dbd08d40 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -33,7 +33,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install build tools - run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ python3-numpy + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy - name: Install pinned Rust run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Local checks @@ -124,7 +124,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - sudo apt-get update && sudo apt-get install -y musl-tools binutils + apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools binutils docker.io - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Build pinned GPU-hidden compiler image @@ -260,7 +260,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install musl toolchain - run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils python3-numpy + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3-numpy docker.io - name: Install pinned Rust and target run: | rustup toolchain install 1.99.0 --profile minimal @@ -395,6 +395,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - name: Install Docker CLI and verify runner daemon + run: | + command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io; } + docker version - name: Build actual CLI-only scratch image run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check . - name: Check isolated CLI container startup and shutdown -- 2.54.0 From 8ec9ab5bce6442acf3629b3b03967cdc42311918 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 16:44:56 +0200 Subject: [PATCH 04/14] Pin Gitea rustup bootstrap and manual GPU gates --- .github/workflows/linux.yml | 19 +++++----- docs/build-validation.md | 23 +++++++++++- scripts/install-pinned-rustup.sh | 61 ++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+), 12 deletions(-) create mode 100755 scripts/install-pinned-rustup.sh diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index dbd08d40..b4bbc73f 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -35,12 +35,12 @@ jobs: - name: Install build tools run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy - name: Install pinned Rust - run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy + run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Local checks run: scripts/check-local.sh keyless-cuda: - if: github.event_name == 'workflow_dispatch' && inputs.keyless_gpu + if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.keyless_gpu == 'true' runs-on: [self-hosted, linux, x64, strata-gpu] steps: - uses: actions/checkout@v4 @@ -50,7 +50,7 @@ jobs: run: scripts/check-kar-expert-gpu.sh static-cuda-package: - if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.event.repository.private + if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private needs: verify runs-on: [self-hosted, linux, x64, strata-gpu] steps: @@ -63,8 +63,7 @@ jobs: run: nice -n 10 scripts/build-static-cuda.sh - name: Install pinned Rust and musl target run: | - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl command -v musl-gcc - name: Assemble combined private package run: | @@ -106,7 +105,7 @@ jobs: run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" hosted-cuda-package: - if: github.event_name == 'workflow_dispatch' && (inputs.hosted_cuda_package || inputs.hosted_cuda_ple) && github.event.repository.private + if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private needs: verify runs-on: ubuntu-latest timeout-minutes: 150 @@ -124,7 +123,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools binutils docker.io + apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Build pinned GPU-hidden compiler image @@ -206,8 +205,7 @@ jobs: PYFEATURES - name: Install pinned Rust and musl target run: | - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - name: Assemble actual combined executable and runtime image run: | # Keep resource evidence even if the hosted runner terminates this job. @@ -263,8 +261,7 @@ jobs: run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3-numpy docker.io - name: Install pinned Rust and target run: | - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - name: Build static CLI run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next - name: Verify ELF and checksum diff --git a/docs/build-validation.md b/docs/build-validation.md index 6edfc9ca..2cabd958 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -834,8 +834,29 @@ invalid archives/receipts and do not require CUDA; only a successful manual actual-CUDA job qualifies compilation and packaging. GPU driver loading, full-model/MTP inference, quality and clean-node rollback remain separate gates. +PLE-only packaging is selected with Gitea input `hosted_cuda_ple=true`; its job +uses the CPU runner and hides all GPU devices inside the pinned build container. +The workflow reads Gitea's raw dispatch inputs as strings and explicitly +compares each opt-in to `true`, so a false string cannot enqueue GPU jobs. + +The Rust installer is pinned separately from the compiler toolchain: + +| Dependency | Pin | +| --- | --- | +| rustup-init | 1.29.0, SHA-256 `4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10` | +| rustc / cargo | 1.99.0 from `rust-toolchain.toml` | +| CUDA toolkit | 13.0.1 manifest; NVCC 13.0.88, component hashes in `deploy/cuda-toolkit.lock.json` | +| CUDA build image | Ubuntu base digest `f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b`; GCC/G++ 13 | + +The runner's `ubuntu-latest` label and job container image are runner +configuration, not immutable pins; actual OS and apt package versions are +recorded in artifact provenance. Trigger a private build on a committed branch +with the Gitea API (input values are strings): + ```sh -gh workflow run linux.yml --ref COMMITTED_REF -f hosted_cuda_package=true +tea api --repo para/leleka --login git.vezha.io --method POST \ + -d '{"ref":"refs/heads/BRANCH","inputs":{"hosted_cuda_ple":"true"}}' \ + /repos/para/leleka/actions/workflows/linux.yml/dispatches ``` ## Native per-user installation (STRA-72) diff --git a/scripts/install-pinned-rustup.sh b/scripts/install-pinned-rustup.sh new file mode 100755 index 00000000..484997e6 --- /dev/null +++ b/scripts/install-pinned-rustup.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Pin the installer independently of rust-toolchain.toml, which pins rustc/cargo. +readonly RUSTUP_VERSION="1.29.0" +readonly RUSTUP_TARGET="x86_64-unknown-linux-gnu" +readonly RUSTUP_INIT_SHA256="4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10" +readonly RUSTUP_INIT_URL="https://static.rust-lang.org/rustup/archive/${RUSTUP_VERSION}/${RUSTUP_TARGET}/rustup-init" + +# Give each Actions job an isolated installation so a host's rustup cannot +# silently override the version pinned here. +if [[ -n "${RUNNER_TEMP:-}" && -n "${GITHUB_RUN_ID:-}" ]]; then + rustup_home="${RUNNER_TEMP}/strata-rustup-${GITHUB_RUN_ID}-${GITHUB_JOB:-job}" + export CARGO_HOME="${rustup_home}/cargo" + export RUSTUP_HOME="${rustup_home}/rustup" + mkdir -p "$CARGO_HOME" + if [[ -n "${GITHUB_ENV:-}" ]]; then + printf 'CARGO_HOME=%s\nRUSTUP_HOME=%s\n' "$CARGO_HOME" "$RUSTUP_HOME" >> "$GITHUB_ENV" + fi +fi + +tmp_dir="$(mktemp -d)" +trap 'rm -rf -- "$tmp_dir"' EXIT + +python3 - "$RUSTUP_INIT_URL" "$tmp_dir/rustup-init" <<'PY' +import shutil +import sys +import urllib.request + +request = urllib.request.Request( + sys.argv[1], headers={"User-Agent": "strata-next-pinned-rustup-bootstrap/1"} +) +with urllib.request.urlopen(request, timeout=120) as response: + with open(sys.argv[2], "wb") as output: + shutil.copyfileobj(response, output) +PY + +printf '%s %s\n' "$RUSTUP_INIT_SHA256" "$tmp_dir/rustup-init" | sha256sum --check --status || { + echo "rustup-init ${RUSTUP_VERSION} checksum mismatch" >&2 + exit 1 +} + +chmod 0755 "$tmp_dir/rustup-init" +"$tmp_dir/rustup-init" -y --no-modify-path \ + --default-host "$RUSTUP_TARGET" --default-toolchain none --profile minimal + +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" +if [[ -n "${GITHUB_PATH:-}" ]]; then + printf '%s\n' "${CARGO_HOME:-$HOME/.cargo}/bin" >> "$GITHUB_PATH" +fi +rustup set auto-self-update disable + +actual_version="$(rustup --version | awk 'NR == 1 { print $2 }')" +if [[ "$actual_version" != "$RUSTUP_VERSION" ]]; then + echo "expected rustup ${RUSTUP_VERSION}, got ${actual_version:-unknown}" >&2 + exit 1 +fi + +if (( $# > 0 )); then + "$@" +fi -- 2.54.0 From 712de0f6bc4f16686d52c3c98bed2643147178cc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 17:12:25 +0200 Subject: [PATCH 05/14] fix(STRA-101): support Python 3.11 CUDA bootstrap --- .github/workflows/linux.yml | 19 +++++++- docs/build-validation.md | 18 +++++++ scripts/bootstrap-cuda-toolkit.py | 78 ++++++++++++++++++++++++++++--- scripts/test-cuda-bootstrap.py | 29 ++++++++++++ 4 files changed, 136 insertions(+), 8 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index b4bbc73f..62577b82 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -39,8 +39,25 @@ jobs: - name: Local checks run: scripts/check-local.sh + keyless-cuda-gate: + if: gitea.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + outputs: + enabled: ${{ steps.select.outputs.enabled }} + steps: + - id: select + env: + KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }} + run: | + case "${KEYLESS_GPU:-false}" in + true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;; + false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;; + *) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;; + esac + keyless-cuda: - if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.keyless_gpu == 'true' + needs: [verify, keyless-cuda-gate] + if: needs.keyless-cuda-gate.outputs.enabled == 'true' runs-on: [self-hosted, linux, x64, strata-gpu] steps: - uses: actions/checkout@v4 diff --git a/docs/build-validation.md b/docs/build-validation.md index 2cabd958..c813bb84 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -1,5 +1,23 @@ # Build validation +## 2026-10-07 — Gitea Python 3.11 archive validation + +- Exact-head Gitea run `2700` (`8ec9ab5bce6442acf3629b3b03967cdc42311918`) ran in + `node:24-bookworm` / Debian 12 with Python `3.11.2`. `verify` exposed that + `tarfile.extractall(filter="data")` requires Python 3.12; the CUDA bootstrap + now validates member paths, link containment, topology, types, and modes before + using the Python 3.11-compatible standard-library extractor. No PyPI packages + are added for this script. +- The focused archive suite passed on the same `node:24-bookworm` image. It covers + valid file/symlink/hardlink trees, traversal and link-parent attacks, privileged + mode rejection, conflicting merges, download integrity, and lock validation. +- The manual keyless-GPU path is now preceded by a CPU-side input gate and depends + on `verify`; a false selection must be resolved as skipped before any GPU runner + is eligible. This gate does not execute GPU checks or imply GPU availability. +- Run `2700` itself remains a failed historical run, and its unmatched keyless + job is still queued; this change is not validated until one exact-head Gitea + run proves the keyless job skipped and the hosted PLE package completes. + ## 2026-10-03 — experimental PLE quality arm The imported engine builds on Linux CUDA 13.2/sm_120 with the optional diff --git a/scripts/bootstrap-cuda-toolkit.py b/scripts/bootstrap-cuda-toolkit.py index 4324ca71..ef5ff247 100644 --- a/scripts/bootstrap-cuda-toolkit.py +++ b/scripts/bootstrap-cuda-toolkit.py @@ -5,12 +5,14 @@ No driver installation, model access, root privileges or inference. NVIDIA's redistrib archives are assembly inputs, not a general-purpose CUDA installer. """ import argparse +import copy import hashlib import json import os from pathlib import Path, PurePosixPath import platform import shutil +import stat import tarfile import tempfile import time @@ -54,21 +56,83 @@ def validate_lock(lock, manifest): def extract(archive, destination, root_name): + if not root_name or '/' in root_name or '\\' in root_name or root_name in ('.','..'): + raise ValueError('invalid component root') with tarfile.open(archive, 'r:xz') as source: members=source.getmembers() - if len(members)>50000 or sum(x.size for x in members)>6*1024**3: + if len(members)>50000 or any(x.size<0 for x in members) or sum(x.size for x in members)>6*1024**3: raise ValueError('archive expansion limit exceeded') - seen=set() + seen={} for item in members: - path=PurePosixPath(item.name) - if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=root_name: + raw_name=item.name + if not raw_name or '\x00' in raw_name or '\\' in raw_name or raw_name.startswith('/'): raise ValueError('archive path outside component root') - if item.name in seen: + parts=raw_name.split('/') + if parts[-1]=='' and item.isdir():parts.pop() + if not parts or any(part in ('','.','..') for part in parts) or parts[0]!=root_name: + raise ValueError('archive path outside component root') + name='/'.join(parts) + if name in seen: raise ValueError('duplicate archive member') - seen.add(item.name) + if name==root_name and not item.isdir(): + raise ValueError('component root is not a directory') if not (item.isdir() or item.isfile() or item.issym() or item.islnk()): raise ValueError('unsupported archive member') - source.extractall(destination, members=members, filter='data') + if item.mode & (stat.S_ISUID|stat.S_ISGID|stat.S_ISVTX): + raise ValueError('archive member has privileged mode bits') + clone=copy.copy(item);clone.name=name + if item.issym() or item.islnk(): + link=item.linkname + if not link or '\x00' in link or '\\' in link or link.startswith('/'): + raise ValueError('archive link outside component root') + target=list(parts[:-1] if item.issym() else []) + for part in link.split('/'): + if part in ('','.'):continue + if part=='..': + if len(target)<=1:raise ValueError('archive link outside component root') + target.pop() + else:target.append(part) + if not target or target[0]!=root_name: + raise ValueError('archive link outside component root') + if item.islnk():clone.linkname='/'.join(target) + if item.isdir(): + clone.mode=(item.mode & 0o755)|0o700 + elif item.isfile(): + clone.mode=(item.mode & 0o755)|0o600 + if item.mode & 0o111:clone.mode|=0o100 + # Never apply archive ownership. Numeric IDs are the builder's own + # identity; tarfile 3.11's root-only chown path therefore stays put. + clone.uid=os.geteuid();clone.gid=os.getegid();clone.uname=clone.gname='' + seen[name]=(item,clone) + for name,(item,_) in seen.items(): + parts=name.split('/') + for depth in range(1,len(parts)): + parent='/'.join(parts[:depth]) + if parent in seen and not seen[parent][0].isdir(): + raise ValueError('archive member is nested under a non-directory') + if item.islnk(): + target=item.linkname + if target not in seen or not (seen[target][0].isfile() or seen[target][0].islnk()): + raise ValueError('archive hard link target is missing or unsupported') + # Python 3.11 (Debian Bookworm) lacks tarfile's `filter=` argument. + # Every member is normalized and validated above before the legacy + # extractor sees it; links are constrained to the private component tree. + destination.mkdir(mode=0o700,parents=True,exist_ok=True) + if os.path.lexists(destination/root_name):raise ValueError('component root already exists') + (destination/root_name).mkdir(mode=0o700) + dirs=sorted((v[1] for v in seen.values() if v[0].isdir()),key=lambda x:(x.name.count('/'),x.name)) + files=sorted((v[1] for v in seen.values() if v[0].isfile()),key=lambda x:x.name) + symlinks=sorted((v[1] for v in seen.values() if v[0].issym()),key=lambda x:x.name) + hardlinks={name:clone for name,(item,clone) in seen.items() if item.islnk()} + ordered_hardlinks=[];visiting=set();emitted=set() + def emit_hardlink(name): + if name in emitted:return + if name in visiting:raise ValueError('archive hard link cycle') + visiting.add(name);target=hardlinks[name].linkname + if target in hardlinks:emit_hardlink(target) + visiting.remove(name);emitted.add(name);ordered_hardlinks.append(hardlinks[name]) + for name in sorted(hardlinks):emit_hardlink(name) + source.extractall(destination,members=dirs+files+ordered_hardlinks+symlinks,numeric_owner=True) return destination/root_name diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py index 8e5b21d2..b4ace246 100644 --- a/scripts/test-cuda-bootstrap.py +++ b/scripts/test-cuda-bootstrap.py @@ -20,6 +20,16 @@ class Tests(unittest.TestCase): item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item) out=m.extract(archive,root/'out','component') self.assertEqual((out/'lib/b').read_bytes(),b'a') + def test_safe_hardlink_and_archive_permissions(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/lib/a');item.size=1;item.mode=0o777;t.addfile(item,io.BytesIO(b'a')) + item=tarfile.TarInfo('component/lib/b');item.type=tarfile.LNKTYPE;item.linkname='component/lib/a';t.addfile(item) + out=m.extract(archive,root/'out','component') + self.assertEqual((out/'lib/b').read_bytes(),b'a') + self.assertFalse((out/'lib/a').stat().st_mode & 0o7000) + self.assertFalse((out/'lib/a').stat().st_mode & 0o022) def test_bad_archive_paths_and_links(self): for name,link in [('../escape',None),('/escape',None),('other/file',None),('component/b','../../escape')]: with self.subTest(name=name),tempfile.TemporaryDirectory() as tmp: @@ -30,6 +40,25 @@ class Tests(unittest.TestCase): t.addfile(item) with self.assertRaises((ValueError,tarfile.TarError)):m.extract(archive,root/'out','component') self.assertFalse((root/'escape').exists()) + def test_reject_link_ancestor_and_hardlink_escape(self): + for entries in [ + [('component/link',tarfile.SYMTYPE,'lib'),('component/link/escape',tarfile.REGTYPE,'')], + [('component/file',tarfile.LNKTYPE,'../../escape')], + ]: + with self.subTest(entries=entries),tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + for name,kind,link in entries: + item=tarfile.TarInfo(name);item.type=kind + if kind==tarfile.REGTYPE:item.size=1;t.addfile(item,io.BytesIO(b'x')) + else:item.linkname=link;t.addfile(item) + with self.assertRaises(ValueError):m.extract(archive,root/'out','component') + def test_reject_privileged_modes(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/file');item.size=1;item.mode=0o4755;t.addfile(item,io.BytesIO(b'x')) + with self.assertRaises(ValueError):m.extract(archive,root/'out','component') def test_component_merge_rejects_conflict(self): with tempfile.TemporaryDirectory() as tmp: root=Path(tmp);a=root/'a';b=root/'b';a.mkdir();b.mkdir() -- 2.54.0 From e3ca4643b83610e0d9a2b5450c2f7d9a334e0f54 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 17:45:26 +0200 Subject: [PATCH 06/14] fix(ci): stage CUDA source inside GPU-hidden build container --- .github/workflows/linux.yml | 47 ++++++++++++++++++++++------- deploy/Dockerfile.static-cli | 5 ++- docs/build-validation.md | 15 +++++++-- scripts/build-static-cuda.sh | 18 +++++++---- scripts/test-static-cuda-profile.py | 19 +++++++++++- 5 files changed, 82 insertions(+), 22 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 62577b82..4ae0043f 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -188,25 +188,48 @@ jobs: STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} run: | mkdir -p "$STRATA_BUILD_DIR" - docker run --rm --platform linux/amd64 --network bridge --read-only \ - --user "$(id -u):$(id -g)" --cap-drop ALL --security-opt no-new-privileges \ - --tmpfs /tmp:rw,nosuid,size=2g \ + container="leleka-cuda-build-${GITHUB_RUN_ID}" + volume="leleka-cuda-build-${GITHUB_RUN_ID}" + source_archive="$RUNNER_TEMP/strata-cuda-source.tar" + cleanup() { + docker rm -f "$container" >/dev/null 2>&1 || true + docker volume rm "$volume" >/dev/null 2>&1 || true + rm -f -- "$source_archive" + } + trap cleanup EXIT + git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive" + docker volume create "$volume" >/dev/null + docker create --name "$container" --platform linux/amd64 --network bridge --read-only \ + --cap-drop ALL --security-opt no-new-privileges \ + --tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \ -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ - -e CUDACXX=/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/toolkit \ + "$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null + docker start "$container" >/dev/null + docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build + docker exec "$container" chmod 0777 /work/build + # Stage tracked source only. docker cp streams the archive from the + # runner container; bind mounts cannot use its path on the daemon host. + docker cp "$source_archive" "$container:/work/source.tar" + docker exec "$container" tar -xf /work/source.tar -C /work/workspace + docker exec "$container" rm /work/source.tar + docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/" + docker exec --user "$(id -u):$(id -g)" \ + -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ + -e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \ -e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \ - -e BUILD_JOBS=1 -e CUDA_ARCHITECTURES -e STRATA_KAR_PLE \ - -e STRATA_BUILD_DIR=/build \ - --mount "type=bind,src=$GITHUB_WORKSPACE,dst=/workspace,readonly" \ - --mount "type=bind,src=$CUDAToolkit_ROOT,dst=/toolkit,readonly" \ - --mount "type=bind,src=$STRATA_BUILD_DIR,dst=/build" \ - "$CUDA_BUILDER_IMAGE" /bin/bash -euo pipefail -c ' + -e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \ + -e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \ + -e SOURCE_REVISION="$GITHUB_SHA" \ + "$container" /bin/bash -euo pipefail -c ' if compgen -G "/dev/nvidia*" >/dev/null; then echo "NVIDIA devices unexpectedly visible in build container" >&2 exit 1 fi - cd /workspace + cd /work/workspace scripts/build-static-cuda.sh ' + docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata" + docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json" - name: Bind compile capability to CUDA toolchain provenance run: | python3 - <<'PYFEATURES' @@ -272,6 +295,8 @@ jobs: linux-static-cli: needs: verify runs-on: ubuntu-latest + env: + CARGO_TARGET_DIR: ${{ github.workspace }}/control-plane/target steps: - uses: actions/checkout@v4 - name: Install musl toolchain diff --git a/deploy/Dockerfile.static-cli b/deploy/Dockerfile.static-cli index 066dde61..bc714fe0 100644 --- a/deploy/Dockerfile.static-cli +++ b/deploy/Dockerfile.static-cli @@ -7,8 +7,11 @@ RUN apt-get update \ RUN rustup target add "${RUST_TARGET}" WORKDIR /src -COPY rust-toolchain.toml ./ +ENV CARGO_TARGET_DIR=/src/control-plane/target +COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ +COPY crates/ ./crates/ COPY manifests/ ./manifests/ +COPY desktop-core/ ./desktop-core/ COPY control-plane/ ./control-plane/ COPY engine/strata/LICENSE ./engine/strata/LICENSE RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \ diff --git a/docs/build-validation.md b/docs/build-validation.md index c813bb84..ede15341 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -14,9 +14,18 @@ - The manual keyless-GPU path is now preceded by a CPU-side input gate and depends on `verify`; a false selection must be resolved as skipped before any GPU runner is eligible. This gate does not execute GPU checks or imply GPU availability. -- Run `2700` itself remains a failed historical run, and its unmatched keyless - job is still queued; this change is not validated until one exact-head Gitea - run proves the keyless job skipped and the hosted PLE package completes. +- Exact-head Gitea run `2703` (`712de0f6bc4f16686d52c3c98bed2643147178cc`) + passed `verify` and the CPU gate; both keyless GPU jobs were skipped. The hosted + PLE job exposed that the Docker daemon cannot bind-mount the runner container's + `$GITHUB_WORKSPACE`; the build now streams a tracked-source archive into a + private Docker volume and supplies the exact source SHA as provenance. The same + run found the static CLI target path mismatch and an incomplete scratch-image + workspace (missing the root lockfile and local tokenizer workspace crate); the + workflow and Dockerfile now use one explicit target directory and include the + complete Cargo workspace manifests/sources. +- Run `2703` produced no hosted package artifact. The new fixes require one fresh + exact-head Gitea run; no GPU inference, model-quality or rollback claim follows + from these CPU/build checks. ## 2026-10-03 — experimental PLE quality arm diff --git a/scripts/build-static-cuda.sh b/scripts/build-static-cuda.sh index 0d6e1f59..970e77d6 100755 --- a/scripts/build-static-cuda.sh +++ b/scripts/build-static-cuda.sh @@ -17,6 +17,16 @@ case "${kar_ple}" in *) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;; esac +if [[ ${SOURCE_REVISION+x} ]]; then + source_revision="${SOURCE_REVISION}" +else + source_revision="$(git -C "${repo_root}" rev-parse HEAD)" +fi +if [[ ! "${source_revision}" =~ ^[0-9a-f]{40}$ ]]; then + echo 'SOURCE_REVISION must be an exact lowercase 40-character Git commit.' >&2 + exit 2 +fi + # CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML. cmake_args=( -S "${repo_root}/engine/strata" -B "${build_dir}" @@ -40,18 +50,14 @@ env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help # This records compile capability only. The runtime still requires an explicit # model/profile selection; PLE is experimental and defaults off at serving time. -python3 - "${repo_root}" "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" <<'PYFEATURES' +python3 - "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" "${source_revision}" <<'PYFEATURES' import json import os from pathlib import Path -import subprocess import sys import tempfile -repo, destination, ple, architectures = sys.argv[1:] -revision = subprocess.check_output(['git', '-C', repo, 'rev-parse', 'HEAD'], text=True).strip() -if len(revision) != 40 or any(ch not in '0123456789abcdef' for ch in revision): - raise SystemExit('could not record an exact source revision') +destination, ple, architectures, revision = sys.argv[1:] record = { 'schema_version': 1, 'source_revision': revision, diff --git a/scripts/test-static-cuda-profile.py b/scripts/test-static-cuda-profile.py index 03f86235..5a75566b 100644 --- a/scripts/test-static-cuda-profile.py +++ b/scripts/test-static-cuda-profile.py @@ -42,14 +42,17 @@ class StaticCudaProfileTests(unittest.TestCase): subprocess.run(['git', '-C', str(self.repo), '-c', 'user.email=fixture@example.invalid', '-c', 'user.name=Fixture', 'commit', '-qm', 'mock toolchain fixture'], check=True) - def run_profile(self, value='unset'): + def run_profile(self, value='unset', source_revision=None): env = dict(os.environ) env.update(PATH=f'{self.bin}{os.pathsep}{env["PATH"]}', STRATA_BUILD_DIR=str(self.build), CMAKE_CAPTURE=str(self.capture), CUDA_ARCHITECTURES='120') env.pop('STRATA_KAR_PLE', None) + env.pop('SOURCE_REVISION', None) if value != 'unset': env['STRATA_KAR_PLE'] = value + if source_revision is not None: + env['SOURCE_REVISION'] = source_revision return subprocess.run(['bash', str(self.repo / 'scripts/build-static-cuda.sh')], env=env, text=True, capture_output=True) @@ -98,6 +101,20 @@ class StaticCudaProfileTests(unittest.TestCase): self.assertIn('exactly 0 or 1', result.stderr) self.assertFalse(self.capture.exists()) + def test_archive_checkout_records_explicit_exact_source_revision(self): + revision = 'a1' * 20 + (self.repo / '.git').rename(self.repo / '.git-hidden') + result = self.run_profile('1', source_revision=revision) + self.assertEqual(result.returncode, 0, result.stderr) + features = json.loads((self.build / 'BUILD-FEATURES.json').read_text()) + self.assertEqual(features['source_revision'], revision) + + def test_invalid_source_revision_fails_before_cmake(self): + result = self.run_profile('1', source_revision='not-a-commit') + self.assertEqual(result.returncode, 2) + self.assertIn('SOURCE_REVISION must be an exact lowercase 40-character Git commit', result.stderr) + self.assertFalse(self.capture.exists()) + if __name__ == '__main__': unittest.main() -- 2.54.0 From 939dfdc8133ab0281aa673ccc9a5b33c7e7fb01f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 17:56:07 +0200 Subject: [PATCH 07/14] fix(ci): install GNU time for hosted package assembly --- .github/workflows/linux.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 4ae0043f..ae45337c 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -140,7 +140,7 @@ jobs: echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 + apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Build pinned GPU-hidden compiler image -- 2.54.0 From 404be4c6a7962701eff81706a2bc7d5e6d4d2b09 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 18:06:20 +0200 Subject: [PATCH 08/14] fix(ci): isolate Docker probes and workspace package provenance --- .github/workflows/linux.yml | 2 +- scripts/build-linux-package.py | 2 +- scripts/docker_smoke_http.py | 49 ++++++++++++++++++++++++++++++++++ scripts/smoke-cli-container.py | 35 +++++++----------------- scripts/smoke-runtime-image.py | 39 +++++++++++++++++---------- scripts/smoke-service-unit.py | 9 ++++++- scripts/test-linux-package.py | 32 ++++++++++++++++++++++ 7 files changed, 125 insertions(+), 43 deletions(-) create mode 100644 scripts/docker_smoke_http.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index ae45337c..4bc2a7ec 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -169,7 +169,7 @@ jobs: from pathlib import Path info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', - os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}\\n', + os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10), 'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines() gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True) diff --git a/scripts/build-linux-package.py b/scripts/build-linux-package.py index 7a23774e..4ad5f4c1 100644 --- a/scripts/build-linux-package.py +++ b/scripts/build-linux-package.py @@ -184,7 +184,7 @@ def assemble(args): provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview', 'source_revision': args.revision, 'target': TARGET, 'engine': info, 'engine_elf_audit': audit, 'outer_elf_audit': outer, - 'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'), + 'cargo_lock_sha256': sha256(REPO / 'Cargo.lock'), 'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']), 'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False, 'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.', diff --git a/scripts/docker_smoke_http.py b/scripts/docker_smoke_http.py new file mode 100644 index 00000000..e593aa94 --- /dev/null +++ b/scripts/docker_smoke_http.py @@ -0,0 +1,49 @@ +"""CPU-only Docker HTTP probe that also works with a remote Docker daemon.""" +import json +import subprocess +import uuid + + +# Official Python 3.11.17 slim OCI index, including Linux amd64 and arm64. +# Python belongs to this disposable test helper, never the serving image. +PROBE_IMAGE = 'python@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce' +ISOLATION = ['--read-only', '--user', '65532:65532', '--cap-drop', 'ALL', + '--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=', + '-e', 'NVIDIA_VISIBLE_DEVICES=void'] +PROBE = '''import json,sys,urllib.error,urllib.request +route,payload=sys.argv[1:] +body=None if payload == 'null' else json.dumps(json.loads(payload)).encode() +request=urllib.request.Request('http://127.0.0.1:8081'+route,data=body, + headers={'Content-Type':'application/json'}) +opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) +try: + response=opener.open(request,timeout=5) +except urllib.error.HTTPError as error: + response=error +with response: + print(json.dumps({'status':response.status,'body':json.load(response)})) +''' + + +def docker(*args, check=True, timeout=30): + return subprocess.run(['docker', *map(str, args)], check=check, + capture_output=True, text=True, timeout=timeout) + + +def prepare_probe(): + if docker('image', 'inspect', PROBE_IMAGE, check=False).returncode: + docker('pull', PROBE_IMAGE, timeout=120) + identity = docker('image', 'inspect', '--format', '{{.Id}}', PROBE_IMAGE).stdout.strip() + print(f'Isolated HTTP probe: {PROBE_IMAGE}, local image {identity}', flush=True) + + +def request(container, route, body=None): + name = 'strata-http-probe-' + uuid.uuid4().hex + try: + result = docker('run', '--rm', '--name', name, *ISOLATION, + '--network', f'container:{container}', '--entrypoint', 'python3', + PROBE_IMAGE, '-c', PROBE, route, json.dumps(body)) + decoded = json.loads(result.stdout) + return decoded['status'], decoded['body'] + finally: + docker('rm', '-f', name, check=False) diff --git a/scripts/smoke-cli-container.py b/scripts/smoke-cli-container.py index c0ed8e47..5b51aaf1 100644 --- a/scripts/smoke-cli-container.py +++ b/scripts/smoke-cli-container.py @@ -2,32 +2,18 @@ """Exercise the actual CLI-only scratch image; never starts an inference worker.""" import json from pathlib import Path -import subprocess import sys import time -import urllib.error -import urllib.request import uuid - - -def docker(*args, check=True): - return subprocess.run(['docker', *args], check=check, capture_output=True, - text=True, timeout=30) +import subprocess +from docker_smoke_http import ISOLATION, docker, prepare_probe, request def main(image): name = 'strata-cli-smoke-' + uuid.uuid4().hex - common = ['--name', name, '--read-only', '--user', '65532:65532', - '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges'] + common = ['--name', name, *ISOLATION] root = Path(__file__).resolve().parents[1] - opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) - - def get(port, route): - try: - with opener.open(f'http://127.0.0.1:{port}{route}', timeout=2) as response: - return response.status, json.load(response) - except urllib.error.HTTPError as error: - return error.code, json.load(error) + prepare_probe() try: version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout @@ -38,21 +24,18 @@ def main(image): info = json.loads(docker('run', '--rm', *common, '--network', 'none', image, 'engine-info').stdout) assert info['embedded'] is False and info['model_bundled'] is False, info - docker('run', '-d', *common, '-p', '127.0.0.1::8081', - '-e', 'STRATA_BIND=0.0.0.0:8081', image, 'serve') - binding = docker('port', name, '8081/tcp').stdout.strip() - assert binding.startswith('127.0.0.1:'), binding - port = int(binding.rsplit(':', 1)[1]) + docker('run', '-d', *common, '--network', 'none', + '-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve') deadline = time.monotonic() + 15 while True: try: - assert get(port, '/health') == (200, {'status': 'ok'}) + assert request(name, '/health') == (200, {'status': 'ok'}) break - except (OSError, AssertionError): + except (OSError, AssertionError, subprocess.CalledProcessError): if time.monotonic() >= deadline: raise time.sleep(0.1) - status, ready = get(port, '/ready') + status, ready = request(name, '/ready') assert status == 503 and ready['ready'] is False, (status, ready) docker('stop', '--time', '10', name) state = json.loads(docker('inspect', '--format', '{{json .State}}', name).stdout) diff --git a/scripts/smoke-runtime-image.py b/scripts/smoke-runtime-image.py index d4ca1f25..9ecce45c 100644 --- a/scripts/smoke-runtime-image.py +++ b/scripts/smoke-runtime-image.py @@ -7,12 +7,8 @@ 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) +from docker_smoke_http import ISOLATION, PROBE_IMAGE, docker, prepare_probe, request as probe_request def main(receipt): @@ -24,32 +20,41 @@ def main(receipt): 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({})) + volume = name + '-fixture' + staging = name + '-stage' + prepare_probe() 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', + (root/'config.json').write_text(json.dumps({'bind': '127.0.0.1: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('volume', 'create', volume) + docker('run', '-d', '--name', staging, *ISOLATION, '--network', 'none', + '--mount', f'type=volume,src={volume},dst=/fixture', + '--entrypoint', 'python3', PROBE_IMAGE, '-c', 'import time; time.sleep(120)') + # Stream files through the Docker API; runner paths need not exist + # on the daemon host. The serving container gets a read-only volume. + docker('cp', str(root) + '/.', staging + ':/fixture') + docker('rm', '-f', staging) 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, + '-e', 'NVIDIA_VISIBLE_DEVICES=void', '--network', 'none', + '--mount', f'type=volume,src={volume},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) + status, result = probe_request(name, route, body) + assert status == 200, (status, result) + return result def ready(): deadline = time.monotonic()+15 while time.monotonic() Date: Wed, 7 Oct 2026 19:13:14 +0200 Subject: [PATCH 09/14] fix(ci): validate package loader and lifecycle in isolated Linux fixtures --- .github/workflows/linux.yml | 13 +- deploy/Dockerfile.systemd-smoke | 13 ++ scripts/build-linux-package.py | 76 ++++++- scripts/smoke-systemd-manager.py | 269 +++++++++++++++++++++++ scripts/test-package-loader-container.py | 54 +++++ 5 files changed, 416 insertions(+), 9 deletions(-) create mode 100644 deploy/Dockerfile.systemd-smoke create mode 100644 scripts/smoke-systemd-manager.py create mode 100644 scripts/test-package-loader-container.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 4bc2a7ec..5d12da09 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -85,7 +85,7 @@ jobs: - name: Assemble combined private package run: | engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" - python3 scripts/build-linux-package.py --engine "$engine" \ + python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ --build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \ --cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \ @@ -141,6 +141,8 @@ jobs: echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time + - name: Actual runtime-image loader boundary without GPU + run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Build pinned GPU-hidden compiler image @@ -259,7 +261,7 @@ jobs: trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT engine="$STRATA_BUILD_DIR/strata" package="$RUNNER_TEMP/strata-hosted-cuda-package" - /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \ + /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ --build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \ --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" @@ -357,12 +359,7 @@ jobs: run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native installer with actual isolated systemd user service run: | - uid=$(id -u) - sudo systemctl start "user@$uid.service" - export XDG_RUNTIME_DIR="/run/user/$uid" - export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" - python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --lifecycle - python3 scripts/smoke-native-switch.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + python3 scripts/smoke-systemd-manager.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native deployment configuration without worker launch run: python3 scripts/smoke-config-check.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Native deployment readiness deadline without GPU diff --git a/deploy/Dockerfile.systemd-smoke b/deploy/Dockerfile.systemd-smoke new file mode 100644 index 00000000..b36d157a --- /dev/null +++ b/deploy/Dockerfile.systemd-smoke @@ -0,0 +1,13 @@ +FROM ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b +RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + systemd=255.4-1ubuntu8.17 dbus=1.14.10-4ubuntu4.1 \ + dbus-user-session=1.14.10-4ubuntu4.1 python3=3.12.3-0ubuntu2.1 \ + util-linux=2.39.3-9ubuntu6.6 ca-certificates=20260601~24.04.1 && rm -rf /var/lib/apt/lists/* +RUN useradd --create-home --uid 10001 fixture && \ + mkdir -p /run/systemd/system /run/user/10001 /home/fixture/.config && \ + chown fixture:fixture /run/user/10001 /home/fixture/.config && \ + chmod 0700 /run/user/10001 /home/fixture /home/fixture/.config +# Empty disposable boot-context directory; the fixture starts a real user manager. +# No system manager, host bus, host unit directory, or host cgroup is mounted. +ENV XDG_RUNTIME_DIR=/run/user/10001 +WORKDIR /work diff --git a/scripts/build-linux-package.py b/scripts/build-linux-package.py index 4ad5f4c1..b706c4e3 100644 --- a/scripts/build-linux-package.py +++ b/scripts/build-linux-package.py @@ -14,7 +14,9 @@ import platform import re import shutil import subprocess +import sys import tempfile +import uuid REPO = Path(__file__).resolve().parents[1] TARGET = 'x86_64-unknown-linux-musl' @@ -105,6 +107,74 @@ def static_outer(binary): return {'program_headers': headers, 'dynamic_section': dynamic} +def loader_probe(binary, probe, audit, container=False): + if not container: + run([binary, 'provision', '--config', probe], + env={'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': '', + 'NVIDIA_VISIBLE_DEVICES': 'void'}, timeout=30) + return {'environment': 'assembly-host'} + # Use the same immutable base as the runtime image. A CPU runner's libc + # need not satisfy the separately audited embedded engine's libc baseline. + spec = importlib.util.spec_from_file_location('runtime_image', REPO / 'scripts/build-runtime-image.py') + runtime = importlib.util.module_from_spec(spec) + spec.loader.exec_module(runtime) + runtime.docker('pull', '--platform', 'linux/amd64', runtime.BASE, timeout=300) + glibc = runtime.check_glibc({'engine_elf_audit': audit}, + runtime.isolated_run(runtime.BASE, ['GNU_LIBC_VERSION'], entrypoint='getconf')) + image_id = runtime.docker('image', 'inspect', '--format', '{{.Id}}', runtime.BASE).stdout.strip() + name = 'strata-package-probe-' + uuid.uuid4().hex + staging_name = name + '-stage' + volume = name + try: + with tempfile.TemporaryDirectory(prefix='strata-package-probe-') as tmp: + copied = Path(tmp) / 'cli' + shutil.copyfile(binary, copied) + copied.chmod(0o755) + config = Path(tmp) / 'probe.json' + shutil.copyfile(probe, config) + config.chmod(0o644) + runtime.docker('volume', 'create', volume) + runtime.docker('create', '--name', staging_name, '--platform', 'linux/amd64', + '--network', 'none', '--cap-drop', 'ALL', + '--mount', 'type=volume,source=' + volume + ',target=/probe', + '--entrypoint', '/bin/true', runtime.BASE) + # The staging container is never started. The serving probe receives + # only a read-only volume, so docker cp cannot mutate its rootfs. + runtime.docker('cp', copied, staging_name + ':/probe/cli', timeout=180) + runtime.docker('cp', config, staging_name + ':/probe/probe.json') + runtime.docker('create', '--name', name, '--platform', 'linux/amd64', + '--network', 'none', '--read-only', '--user', '65532:65532', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', + '--tmpfs', '/tmp:rw,nosuid,nodev,size=1g', + '--mount', 'type=volume,source=' + volume + ',target=/probe,readonly', + '-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void', + '-e', 'LD_LIBRARY_PATH=', '--entrypoint', '/bin/sh', runtime.BASE, + '-c', 'for p in /dev/nvidia*; do if [ -e "$p" ]; then ' + 'echo "package probe refuses NVIDIA devices" >&2; exit 1; fi; done; ' + 'exec /probe/cli "$@"', + 'package-probe', 'provision', '--config', '/probe/probe.json') + result = runtime.docker('start', '--attach', name, timeout=60, check=False) + code = runtime.docker('inspect', '--format', '{{.State.ExitCode}}', name).stdout.strip() + if result.returncode != 0 or code != '0': + raise ValueError('pinned runtime package provision failed: ' + result.stderr.strip()) + finally: + original_failure = sys.exc_info()[0] is not None + errors = [] + for command in [('rm', '-f', name), ('rm', '-f', staging_name), ('volume', 'rm', volume)]: + try: + cleaned = runtime.docker(*command, check=False) + if cleaned.returncode and 'No such ' not in cleaned.stderr: + errors.append(cleaned.stderr.strip()) + except (OSError, subprocess.SubprocessError) as error: + errors.append(str(error)) + if errors: + print('Package probe cleanup failed: ' + '; '.join(errors), file=sys.stderr) + if not original_failure: + raise ValueError('owned package probe cleanup failed') + return {'environment': 'pinned-runtime-container', 'base': runtime.BASE, + 'image_id': image_id, 'glibc': glibc, 'user': '65532:65532', 'gpu_tested': False} + + @contextlib.contextmanager def lock(path): # Caller-controlled build/output paths are private; keep the inode for reuse. @@ -179,11 +249,13 @@ def assemble(args): raise ValueError('combined engine identity does not match pinned input') probe = stage / 'probe.json' probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True})) - run([binary, 'provision', '--config', probe], env=probe_env, timeout=30) + loader = loader_probe(binary, probe, audit, + getattr(args, 'probe_in_runtime_image', False)) source_check(REPO, args.revision) provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview', 'source_revision': args.revision, 'target': TARGET, 'engine': info, 'engine_elf_audit': audit, 'outer_elf_audit': outer, + 'loader_probe': loader, 'cargo_lock_sha256': sha256(REPO / 'Cargo.lock'), 'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']), 'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False, @@ -209,6 +281,8 @@ def main(): parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release') parser.add_argument('--build-features', type=Path, help='exact build feature receipt emitted by build-static-cuda.sh') + parser.add_argument('--probe-in-runtime-image', action='store_true', + help='execute actual provision in the pinned runtime base instead of the assembly host') args = parser.parse_args() try: print(json.dumps(assemble(args))) diff --git a/scripts/smoke-systemd-manager.py b/scripts/smoke-systemd-manager.py new file mode 100644 index 00000000..addb9ca2 --- /dev/null +++ b/scripts/smoke-systemd-manager.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Run unchanged native lifecycle gates with a disposable real systemd manager. + +CPU-only offline fixture. Setup alone gets mount/UID capabilities; journald, +D-Bus, manager, Rust CLI and synthetic workers have empty capability sets. +The private writable cgroup mount enables real manager process tracking. +Setup uses fixture-only apparmor=unconfined for the private cgroup mount; +default seccomp stays enabled. No host paths/devices/namespaces are shared. +Existing tests exercise stop/rollback; this is not a separate forced-descendant +KillMode test, installed-driver inference, or model quality evidence. +""" +import argparse +import glob +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid + +UID = 10001 +CAPS = ('SYS_ADMIN', 'CHOWN', 'SETUID', 'SETGID', 'SETPCAP') +FILES = ('smoke-service-unit.py', 'smoke-native-switch.py', 'smoke-worker-cancel.py') + + +def run(*args, **kwargs): + return subprocess.run(args, check=True, **kwargs) + + +def no_gpu(): + assert not glob.glob('/dev/nvidia*'), 'raw NVIDIA devices are forbidden' + assert os.environ.get('NVIDIA_VISIBLE_DEVICES') == 'void' + assert os.environ.get('CUDA_VISIBLE_DEVICES') == '' + + +def zero_caps(pid='self'): + status = Path(f'/proc/{pid}/status').read_text() + found = [line.split(':', 1)[1].strip() for line in status.splitlines() + if line.startswith(('CapInh:', 'CapPrm:', 'CapEff:', 'CapBnd:', 'CapAmb:'))] + assert found == ['0000000000000000'] * 5, (pid, found) + assert any(line.startswith('NoNewPrivs:') and line.split(':', 1)[1].strip() == '1' + for line in status.splitlines()), (pid, 'NoNewPrivs missing') + + +def drop_command(*args): + return ['setpriv', f'--reuid={UID}', f'--regid={UID}', '--clear-groups', + '--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', *args] + + +def root_setup(): + # Direct host invocation must fail before any mount, chown, or unit operation. + assert Path('/.dockerenv').is_file() and os.getpid() == 1 and os.getuid() == 0 + nonce = os.environ['LELEKA_MANAGER_FIXTURE_NONCE'] + assert len(nonce) == 32 and all(c in '0123456789abcdef' for c in nonce) + no_gpu() + run('dpkg-query', '-W', 'systemd', 'dbus', 'dbus-user-session', 'python3', 'util-linux', + 'ca-certificates') + assert Path('/proc/self/cgroup').read_text().strip() == '0::/' + target = Path('/sys/fs/cgroup') + assert target.is_dir() and not target.is_symlink() + mounts = Path('/proc/self/mountinfo').read_text().splitlines() + assert any(line.split()[4] == str(target) and ' - cgroup2 ' in line for line in mounts) + owned = Path('/run') / ('leleka-cgroup-' + nonce) + assert not owned.exists() + owned.mkdir(mode=0o700) + run('mount', '-t', 'cgroup2', 'none', str(owned)) + run('mount', '--move', str(owned), str(target)) + assert set(Path('/sys/fs/cgroup/cgroup.procs').read_text().split()) <= {str(os.getpid())} + for path in (target, target/'cgroup.procs', target/'cgroup.subtree_control'): + os.chown(path, UID, UID) + # Only known staged regular files are normalized. The CLI remains root-owned. + for name in (*FILES, 'smoke-systemd-manager.py', 'strata-next'): + path = Path('/work') / name + assert path.is_file() and not path.is_symlink() + os.chown(path, 0, 0) + path.chmod(0o755 if name == 'strata-next' else 0o644) + for path in (Path('/run/systemd/journal'), Path('/run/log/journal')): + path.mkdir(parents=True, exist_ok=True) + os.chown(path, UID, UID) + config = Path('/etc/systemd/journald.conf.d') + config.mkdir(exist_ok=True) + (config/'fixture.conf').write_text('[Journal]\nStorage=volatile\nReadKMsg=no\n' + 'ForwardToKMsg=no\nForwardToConsole=no\nForwardToWall=no\n') + journal = subprocess.Popen(drop_command('/usr/lib/systemd/systemd-journald')) + env = dict(os.environ, HOME='/home/fixture', USER='fixture', LOGNAME='fixture', + XDG_CONFIG_HOME='/home/fixture/.config', + DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/10001/fixture-bus', + PYTHONDONTWRITEBYTECODE='1', LELEKA_JOURNAL_PID=str(journal.pid)) + # exec retains journald's parent for bounded waitpid/reaping by the test user. + os.execvpe('setpriv', drop_command('python3', '/work/smoke-systemd-manager.py', + '--inside-user'), env) + + +def finish_process(process): + if process is None: + return + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def finish_journal(pid): + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if os.waitpid(pid, os.WNOHANG)[0]: + return + time.sleep(.05) + os.kill(pid, signal.SIGKILL) + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if os.waitpid(pid, os.WNOHANG)[0]: + return + time.sleep(.05) + raise TimeoutError('journald did not reap after SIGKILL; outer container removal required') + + +def user_tests(): + assert Path('/.dockerenv').is_file() and os.getpid() == 1 + no_gpu() + assert os.getuid() == UID + zero_caps() + journal_pid = int(os.environ['LELEKA_JOURNAL_PID']) + bus = manager = None + failed = False + cleanup_errors = [] + try: + bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork', + '--address=' + os.environ['DBUS_SESSION_BUS_ADDRESS']]) + manager = subprocess.Popen(['/usr/lib/systemd/systemd', '--user', '--unit=basic.target', + '--log-target=console', '--log-level=warning']) + deadline = time.monotonic() + 25 + while True: + assert manager.poll() is None and bus.poll() is None, 'manager or bus exited' + result = subprocess.run(['systemctl', '--user', 'show', '--property=Version'], + text=True, capture_output=True, timeout=3) + if result.returncode == 0 and Path('/run/systemd/journal/stdout').exists(): + break + assert time.monotonic() < deadline, result.stderr + time.sleep(.2) + zero_caps(manager.pid) + zero_caps(bus.pid) + zero_caps(journal_pid) + assert str(manager.pid) in Path('/sys/fs/cgroup/init.scope/cgroup.procs').read_text().split() + print(result.stdout.strip(), flush=True) + print('Private real manager, bus, journal and cgroup ready; all capabilities zero', flush=True) + run('python3', '/work/smoke-service-unit.py', '/work/strata-next', '--lifecycle', timeout=600) + run('python3', '/work/smoke-native-switch.py', '/work/strata-next', timeout=300) + except BaseException: + failed = True + raise + finally: + # Every owned process is cleaned even if another cleanup step fails. + for cleanup in ( + lambda: subprocess.run(['systemctl', '--user', 'exit'], check=False, timeout=5), + lambda: finish_process(manager), lambda: finish_process(bus), + lambda: finish_journal(journal_pid), + ): + try: + cleanup() + except Exception as error: + cleanup_errors.append(str(error)) + if cleanup_errors: + print('Fixture cleanup errors: ' + '; '.join(cleanup_errors), file=sys.stderr) + if not failed: + raise RuntimeError('owned manager fixture cleanup failed') + + +def host(binary): + assert not glob.glob('/dev/nvidia*'), 'manager fixture is restricted to a CPU host' + root = Path(__file__).resolve().parents[1] + binary = binary.resolve(strict=True) + nonce = uuid.uuid4().hex + name = 'leleka-systemd-smoke-' + nonce + image = name + ':fixture' + with tempfile.TemporaryDirectory(prefix=name + '-') as directory: + stage = Path(directory) + dockerfile = root/'deploy/Dockerfile.systemd-smoke' + context = stage/'image-context' + context.mkdir() + shutil.copy2(dockerfile, context/'Dockerfile') + for filename in (*FILES, 'smoke-systemd-manager.py'): + shutil.copy2(root/'scripts'/filename, stage/filename) + shutil.copy2(binary, stage/'strata-next') + def digest(path): + checksum = hashlib.sha256() + with path.open('rb') as source: + for block in iter(lambda: source.read(1024 * 1024), b''): + checksum.update(block) + return checksum.hexdigest() + hashes = {path.name: digest(path) for path in stage.iterdir() if path.is_file()} + hashes['Dockerfile.systemd-smoke'] = digest(dockerfile) + print(json.dumps({'fixture_sha256': hashes}, sort_keys=True), flush=True) + try: + run('docker', 'build', '--platform', 'linux/amd64', '-t', image, str(context), timeout=600) + run('docker', 'create', '--name', name, '--platform', 'linux/amd64', '--tty', + '--network', 'none', '--cgroupns', 'private', '--user', '0', '--cap-drop', 'ALL', + *(arg for cap in CAPS for arg in ('--cap-add', cap)), + '--security-opt', 'no-new-privileges', + '--security-opt', 'apparmor=unconfined', + '-e', 'NVIDIA_VISIBLE_DEVICES=void', '-e', 'CUDA_VISIBLE_DEVICES=', + '-e', 'LELEKA_MANAGER_FIXTURE_NONCE=' + nonce, + image, 'python3', '/work/smoke-systemd-manager.py', '--inside-root', timeout=30) + info = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0] + config = info['HostConfig'] + assert config['CgroupnsMode'] == 'private' and config['NetworkMode'] == 'none' + assert not config['Privileged'] and config['PidMode'] == '' + assert not config['Binds'] and not info['Mounts'] and not config['Devices'] + assert not config['DeviceRequests'] and config['IpcMode'] == 'private' + assert config['CapDrop'] == ['ALL'] + assert {cap.removeprefix('CAP_') for cap in config['CapAdd']} == set(CAPS) + assert set(config['SecurityOpt']) == {'no-new-privileges', 'apparmor=unconfined'} + print(json.dumps({'image_id': info['Image'], 'source': 'isolated CPU fixture', + 'setup_security_options': config['SecurityOpt'], + 'setup_capabilities': config['CapAdd'], + 'user_capabilities': 'zero', 'seccomp': 'Docker default'}), flush=True) + # docker cp works with a remote daemon; runner paths are not bind-mounted. + for filename in (*FILES, 'smoke-systemd-manager.py', 'strata-next'): + run('docker', 'cp', str(stage/filename), name + ':/work/' + filename, timeout=60) + run('docker', 'start', '--attach', name, timeout=1000) + state = json.loads(subprocess.check_output(['docker', 'inspect', name], text=True))[0]['State'] + assert state['ExitCode'] == 0, state + finally: + # Container removal is the final namespace-wide cleanup safety net. + original_failure = sys.exc_info()[0] is not None + errors = [] + for kind, command in (('container', ['docker', 'rm', '--force', name]), + ('image', ['docker', 'image', 'rm', image])): + try: + result = subprocess.run(command, text=True, capture_output=True, timeout=30) + if result.returncode and 'No such ' not in result.stderr: + errors.append(kind + ': ' + result.stderr) + except Exception as error: + errors.append(kind + ': ' + str(error)) + if errors: + print('Outer fixture cleanup errors: ' + '; '.join(errors), file=sys.stderr) + if not original_failure: + raise RuntimeError('outer fixture cleanup failed') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('binary', nargs='?', type=Path) + parser.add_argument('--inside-root', action='store_true') + parser.add_argument('--inside-user', action='store_true') + args = parser.parse_args() + if args.inside_root: + root_setup() + elif args.inside_user: + user_tests() + else: + assert args.binary is not None + host(args.binary) + + +if __name__ == '__main__': + main() diff --git a/scripts/test-package-loader-container.py b/scripts/test-package-loader-container.py new file mode 100644 index 00000000..760b025a --- /dev/null +++ b/scripts/test-package-loader-container.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Real CPU Docker transport/failure regression; not engine or GPU qualification.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py')) +package = importlib.util.module_from_spec(spec) +spec.loader.exec_module(package) + + +class LoaderContainerTests(unittest.TestCase): + def test_actual_nonroot_provision_and_failure_cleanup(self): + runtime_spec = importlib.util.spec_from_file_location('runtime', Path(__file__).with_name('build-runtime-image.py')) + runtime = importlib.util.module_from_spec(runtime_spec) + runtime_spec.loader.exec_module(runtime) + + def probes(): + containers = set(runtime.docker('ps', '-a', '--filter', 'name=strata-package-probe-', + '--format', '{{.ID}}').stdout.splitlines()) + volumes = set(runtime.docker('volume', 'ls', '--filter', 'name=strata-package-probe-', + '--format', '{{.Name}}').stdout.splitlines()) + return containers, volumes + + before = probes() + with tempfile.TemporaryDirectory(prefix='strata-loader-contract-') as tmp: + binary, config = Path(tmp) / 'cli', Path(tmp) / 'config' + config.write_text('{"engine":{"executable":"@embedded"},"engine_probe":true}') + binary.write_text('#!/bin/sh\n' + 'test "$(id -u)" = 65532 || exit 21\n' + 'test "$1" = provision && test "$2" = --config || exit 22\n' + 'grep -q @embedded "$3" || exit 23\n' + 'test "$NVIDIA_VISIBLE_DEVICES" = void && test -z "$CUDA_VISIBLE_DEVICES" || exit 24\n' + 'touch /tmp/owned-loader-fixture || exit 25\n' + 'if touch /forbidden-loader-fixture 2>/dev/null; then exit 26; fi\n') + original = binary.read_bytes() + audit = {'minimum_glibc': '2.38'} + result = package.loader_probe(binary, config, audit, container=True) + self.assertEqual(result['base'], runtime.BASE) + self.assertFalse(result['gpu_tested']) + self.assertEqual(binary.read_bytes(), original) + self.assertEqual(probes(), before) + binary.write_text('#!/bin/sh\nexit 42\n') + with self.assertRaisesRegex(ValueError, 'provision failed'): + package.loader_probe(binary, config, audit, container=True) + self.assertEqual(probes(), before) + with self.assertRaisesRegex(ValueError, 'below engine requirement'): + package.loader_probe(binary, config, {'minimum_glibc': '99.0'}, container=True) + self.assertEqual(probes(), before) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From e028e5d4141bf54a5106b25d6a76a2dc97ed9a89 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 19:47:22 +0200 Subject: [PATCH 10/14] fix(ci): publish verified previews through private Gitea API --- .github/workflows/linux.yml | 126 +++++++-- docs/gitea-preview-publication.md | 17 ++ scripts/check-local.sh | 1 + scripts/publish-gitea-release.py | 353 +++++++++++++++++++++++++ scripts/test-gitea-release.py | 420 ++++++++++++++++++++++++++++++ 5 files changed, 890 insertions(+), 27 deletions(-) create mode 100644 docs/gitea-preview-publication.md create mode 100644 scripts/publish-gitea-release.py create mode 100644 scripts/test-gitea-release.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 5d12da09..980788d1 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -100,13 +100,18 @@ jobs: 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 - path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/ - if-no-files-found: error - retention-days: 7 + - name: Publish exact six-file static CUDA preview through Gitea + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ + --repository "$GITHUB_REPOSITORY" --profile static-cuda \ + --tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ + --title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ + --notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \ + --directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - name: Remove uploaded package copy + if: always() run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - name: Remove owned runtime image if: always() @@ -271,16 +276,40 @@ jobs: image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" docker save --output "$package/runtime-image.tar" "$image" cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" + python3 - <<'PYBIND' + import hashlib, json, os + from pathlib import Path + package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package' + receipt=json.loads((package/'PROVENANCE.json').read_text()) + image=json.loads((package/'IMAGE-PROVENANCE.json').read_text()) + path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' + toolchain=json.loads(path.read_text()) + with (package/'runtime-image.tar').open('rb') as archive: + archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest() + toolchain['docker_builder']={ + 'source_commit': os.environ['GITHUB_SHA'], + 'image_id': toolchain['builder_image_id'], + 'engine_sha256': receipt['engine']['sha256'], + 'build_features_sha256': receipt['build_features_sha256'], + 'runtime_image_id': image['image'], + 'runtime_archive_sha256': archive_sha} + path.write_text(json.dumps(toolchain,indent=2)+'\n') + PYBIND cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json" tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - - uses: actions/upload-artifact@v4 - with: - name: strata-next-hosted-cuda-preview - path: ${{ runner.temp }}/strata-hosted-cuda-package/ - if-no-files-found: error - retention-days: 7 + - name: Publish exact eight-file hosted CUDA preview through Gitea + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ + --repository "$GITHUB_REPOSITORY" --profile cuda \ + --tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ + --title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ + --notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \ + --directory "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove uploaded package copy + if: always() run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove owned intermediate image and build files if: always() @@ -421,10 +450,15 @@ jobs: docker image rm "$image" rm "$receipt" fi - - uses: actions/upload-artifact@v4 - with: - name: strata-next-linux-x86_64-musl - path: dist/ + - name: Publish exact four-file CLI preview through Gitea + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ + --repository "$GITHUB_REPOSITORY" --profile cli \ + --tag "cli-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ + --title "CLI preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ + --notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --directory dist linux-cli-container: needs: verify @@ -447,17 +481,55 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] runs-on: ubuntu-latest - permissions: - contents: write + env: + CARGO_TARGET_DIR: ${{ github.workspace }}/control-plane/target steps: - - uses: actions/download-artifact@v4 + - uses: actions/checkout@v4 with: - name: strata-next-linux-x86_64-musl - path: dist/ - - name: Publish CLI preview release - env: - GH_TOKEN: ${{ github.token }} + ref: ${{ github.ref }} + - name: Require the exact gated tag commit + run: test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + - name: Install musl toolchain + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3 + - name: Install pinned Rust and target + run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl + - name: Rebuild static CLI at the exact gated tag + run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next + - name: Verify ELF and checksum run: | - gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \ - --repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \ - --notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease + binary=control-plane/target/x86_64-unknown-linux-musl/release/strata-next + if readelf -l "$binary" | grep -q INTERP; then + echo 'ELF has a dynamic interpreter' >&2 + exit 1 + fi + if readelf -d "$binary" | grep -q NEEDED; then + echo 'ELF has a dynamic library dependency' >&2 + exit 1 + fi + "$binary" --version + mkdir -p dist + cp "$binary" dist/strata-next-linux-x86_64-musl + { + echo "Commit: $GITHUB_SHA" + echo "Workflow: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + rustc --version + cargo --version + musl-gcc --version + readelf --version + } > dist/BUILD-PROVENANCE.txt + { + readelf -h "$binary" + readelf -l "$binary" + readelf -d "$binary" + } > dist/ELF-AUDIT.txt + cd dist + sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS + - name: Publish verified tagged CLI preview through Gitea + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ + --repository "$GITHUB_REPOSITORY" --profile cli --tag "$GITHUB_REF_NAME" --target "$GITHUB_SHA" \ + --title "Strata Next ${GITHUB_REF_NAME}" \ + --notes 'CLI/control-plane preview rebuilt at the exact tag after CLI and container gates passed. CUDA engine and model files are not included.' \ + --directory dist diff --git a/docs/gitea-preview-publication.md b/docs/gitea-preview-publication.md new file mode 100644 index 00000000..bcf023f7 --- /dev/null +++ b/docs/gitea-preview-publication.md @@ -0,0 +1,17 @@ +# Gitea preview publication + +The Linux workflow publishes through `https://git.vezha.io/api/v1` with a repository-scoped `GITEA_TOKEN` secret. Python is used only for offline CI publication; serving is unchanged. The publisher and its API fixture tests derive from tracked commit `a8fa7e0`, adapted to the current assembly receipts. The imported Strata upstream record remains unchanged. + +| Profile | Exact assets | Tag scope | +| --- | --- | --- | +| CLI | binary, BUILD-PROVENANCE.txt, ELF-AUDIT.txt, SHA256SUMS | cli-preview-RUN-ATTEMPT or explicit vVERSION | +| Hosted CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, CUDA-TOOLCHAIN.json, CUDA-LICENSES.tar, IMAGE-SHA256SUMS | cuda-preview-RUN-ATTEMPT | +| Static CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, IMAGE-SHA256SUMS | static-cuda-preview-RUN-ATTEMPT | + +All profiles reject missing/extra files, symlinks, mismatched checksums and source revisions before creating a release. CLI publication requires one exact Commit line and a static x86_64 ELF audit. The existing static CLI lifecycle, Responses, restart and CPU rollback gates remain prerequisites. A version-tag job rebuilds the same gated tag commit with the existing pinned Rust/musl build command, then repeats the original ELF audit and generates checksums for the rebuilt assets; it does not claim bitwise reproducibility against the earlier preview binary. + +CUDA publication validates current package `loader_probe` receipts from `--probe-in-runtime-image`, image/package receipt binding and canonical compile-feature digests. These producers do not emit the historical `engine_help_probe` strings; their existing loader/identity/help probes must pass for assembly to emit the current receipts. Hosted toolchain publication additionally binds the actual builder image identity, source, engine hash, compile-feature digest, runtime image identity and saved archive hash. The inactive static CUDA profile preserves its original six-file contract and has no hosted compiler or license receipt qualification. Its runner and build inputs are unchanged. + +Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and rereads each same-origin Gitea attachment to compare size and SHA256. Only then does it remove draft status. Redirects and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy. + +Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate. diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 97ad6a99..a28be2fc 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -14,6 +14,7 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.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-gitea-release.py" python3 "${repo_root}/scripts/test-keyless-routing.py" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check diff --git a/scripts/publish-gitea-release.py b/scripts/publish-gitea-release.py new file mode 100644 index 00000000..2aef223e --- /dev/null +++ b/scripts/publish-gitea-release.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Publish verified CLI or privately built CUDA previews through Gitea's API v1.""" +import argparse +import hashlib +import http.client +import ipaddress +import json +import os +from pathlib import Path +import re +import ssl +import stat +import sys +from urllib.parse import urlencode, urlsplit + +PACKAGE_BINARY = 'strata-next-linux-x86_64-musl' +PACKAGE_ASSETS = {PACKAGE_BINARY, 'PROVENANCE.json'} +IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'} +ASSETS = PACKAGE_ASSETS | IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'} +STATIC_IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json'} +STATIC_ASSETS = PACKAGE_ASSETS | STATIC_IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'} +CLI_ASSETS = {PACKAGE_BINARY, 'BUILD-PROVENANCE.txt', 'ELF-AUDIT.txt', 'SHA256SUMS'} +CHUNK_SIZE = 1024 * 1024 + + +def file_sha256(path): + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + if not stat.S_ISREG(os.fstat(source.fileno()).st_mode): + raise ValueError(f'not a regular artifact file: {path.name}') + return hashlib.file_digest(source, 'sha256').hexdigest() + + +def verify_manifest(directory, manifest, expected): + path = directory / manifest + lines = path.read_text(encoding='ascii').splitlines() + entries = {} + for line in lines: + match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line) + if not match or match[2] in entries: + raise ValueError(f'invalid {manifest} entry') + entries[match[2]] = match[1] + if set(entries) != expected: + raise ValueError(f'{manifest} does not cover the required artifact set') + for name, expected_sha in entries.items(): + if file_sha256(directory / name) != expected_sha: + raise ValueError(f'{manifest} checksum mismatch: {name}') + + +def read_json(path): + try: + value = json.loads(path.read_text(encoding='utf-8')) + except (OSError, json.JSONDecodeError) as error: + raise ValueError(f'invalid artifact JSON: {path.name}') from error + if not isinstance(value, dict): + raise ValueError(f'artifact JSON must be an object: {path.name}') + return value + + +def canonical_sha(record): + return hashlib.sha256((json.dumps(record, sort_keys=True, indent=2) + '\n').encode()).hexdigest() + + +def valid_digest(value, prefix=''): + return isinstance(value, str) and re.fullmatch(re.escape(prefix) + r'[0-9a-f]{64}', value) is not None + + +def verify_artifacts(directory, target, profile='cuda'): + if profile not in {'cli', 'cuda', 'static-cuda'}: + raise ValueError('unsupported artifact profile') + expected = {'cli': CLI_ASSETS, 'cuda': ASSETS, 'static-cuda': STATIC_ASSETS}[profile] + if not directory.is_dir(): + raise ValueError('artifact directory does not exist') + paths = list(directory.iterdir()) + if {path.name for path in paths} != expected: + raise ValueError(f'artifact directory must contain exactly the {profile.upper()} preview files') + for path in paths: + file_sha256(path) + verify_manifest(directory, 'SHA256SUMS', expected - {'SHA256SUMS'} if profile == 'cli' else PACKAGE_ASSETS) + if profile == 'cli': + provenance = (directory / 'BUILD-PROVENANCE.txt').read_text(encoding='utf-8') + commits = re.findall(r'^Commit: (.*)$', provenance, re.MULTILINE) + if commits != [target] or not re.search(r'^Workflow: https?://\S+$', provenance, re.MULTILINE): + raise ValueError('CLI build provenance is not bound to this exact commit and workflow') + audit = (directory / 'ELF-AUDIT.txt').read_text(encoding='utf-8') + if ('ELF Header:' not in audit or not re.search(r'Class:\s+ELF64', audit) or + not re.search(r'Machine:\s+Advanced Micro Devices X86-64', audit) or + 'INTERP' in audit or 'NEEDED' in audit): + raise ValueError('CLI ELF audit does not describe a static x86_64 executable') + else: + verify_manifest(directory, 'IMAGE-SHA256SUMS', STATIC_IMAGE_ASSETS if profile == 'static-cuda' else IMAGE_ASSETS) + package = read_json(directory / 'PROVENANCE.json') + engine = package.get('engine', {}) + features = package.get('build_features', {}) + feature_sha = package.get('build_features_sha256') + loader = package.get('loader_probe', {}) + audit = package.get('engine_elf_audit', {}) + if (type(package.get('schema_version')) is not int or package.get('schema_version') != 1 or + package.get('kind') != 'static-cuda-preview' or + package.get('target') != 'x86_64-unknown-linux-musl' or package.get('source_revision') != target or + package.get('gpu_tested') is not False or package.get('model_tested') is not False or + package.get('clean_node_tested') is not False or not isinstance(engine, dict) or + engine.get('embedded') is not True or engine.get('declared_source_revision') != target or + engine.get('target_os') != 'linux' or engine.get('target_arch') != 'x86_64' or + type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or + not valid_digest(engine.get('sha256')) or not isinstance(loader, dict) or + loader.get('environment') != 'pinned-runtime-container' or loader.get('gpu_tested') is not False or + loader.get('user') != '65532:65532' or not valid_digest(loader.get('image_id'), 'sha256:')): + raise ValueError('combined package provenance is not a CUDA-only preview for this commit') + if (not isinstance(audit, dict) or audit.get('toolkit_shared_libraries') is not False or + audit.get('host_glibc_required') is not True or + not isinstance(audit.get('minimum_glibc'), str) or + not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', audit['minimum_glibc']) or + not isinstance(loader.get('glibc'), str) or + not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', loader['glibc'])): + raise ValueError('CUDA ELF audit and loader glibc receipts are required') + minimum = tuple(map(int, audit['minimum_glibc'].split('.'))) + actual = tuple(map(int, loader['glibc'].split('.'))) + if actual + (0,) * (3 - len(actual)) < minimum + (0,) * (3 - len(minimum)): + raise ValueError('loader glibc is below the engine ELF audit requirement') + if (not isinstance(features, dict) or set(features) != { + 'schema_version', 'source_revision', 'cuda_architectures', 'features'} or + type(features.get('schema_version')) is not int or features.get('schema_version') != 1 or + features.get('source_revision') != target or + not isinstance(features.get('cuda_architectures'), str) or + not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*', features['cuda_architectures']) or + not valid_digest(feature_sha) or canonical_sha(features) != feature_sha): + raise ValueError('CUDA build feature receipt is not bound to this source and digest') + values = features['features'] + if (not isinstance(values, dict) or set(values) != { + 'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or + any(type(value) is not bool for value in values.values()) or + any(values[key] is not True for key in ('cuda', 'cuda_static_runtime', 'cxx_static_runtime')) or + values['kar_experts'] is not False or values['ple_trace'] is not False): + raise ValueError('unsupported CUDA compile feature selection') + image = read_json(directory / 'IMAGE-PROVENANCE.json') + if (type(image.get('schema_version')) is not int or image.get('schema_version') != 1 or + image.get('kind') != 'static-cuda-preview' or + image.get('source_revision') != target or not valid_digest(image.get('image'), 'sha256:') or + not isinstance(image.get('base'), str) or + not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', image['base']) or + image.get('base') != loader.get('base') or image.get('base_glibc') != loader.get('glibc') or + image.get('gpu_tested') is not False or image.get('model_tested') is not False or + image.get('build_features') != values or image.get('build_features_sha256') != feature_sha or + image.get('package_receipt_sha256') != file_sha256(directory / 'SHA256SUMS')): + raise ValueError('runtime image provenance is not qualified for this package and commit') + if profile == 'cuda': + toolchain = read_json(directory / 'CUDA-TOOLCHAIN.json') + builder = toolchain.get('docker_builder') + if (toolchain.get('source') != target or toolchain.get('driver_tested') is not False or + toolchain.get('model_tested') is not False or toolchain.get('build_features') != values or + toolchain.get('build_features_sha256') != feature_sha or + toolchain.get('cuda_architectures') != features['cuda_architectures'] or + not valid_digest(toolchain.get('builder_image_id'), 'sha256:') or + not isinstance(builder, dict) or builder.get('source_commit') != target or + builder.get('image_id') != toolchain.get('builder_image_id') or + builder.get('engine_sha256') != engine['sha256'] or + builder.get('build_features_sha256') != feature_sha or + builder.get('runtime_image_id') != image['image'] or + builder.get('runtime_archive_sha256') != file_sha256(directory / 'runtime-image.tar')): + raise ValueError('CUDA toolchain provenance is not bound to this commit, engine and runtime image') + return {path.name: {'size': path.stat().st_size, 'sha256': file_sha256(path)} for path in paths} + + +def parse_api_url(api_url): + parts = urlsplit(api_url) + if (parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password or + parts.query or parts.fragment or not parts.path.rstrip('/').endswith('/api/v1')): + raise ValueError('API URL must be a Gitea /api/v1 base URL') + if parts.scheme == 'http': + try: + local = ipaddress.ip_address(parts.hostname).is_loopback + except ValueError: + local = parts.hostname == 'localhost' + if not local: + raise ValueError('non-loopback Gitea API must use verified HTTPS') + if parts.hostname in {'github.com', 'api.github.com'}: + raise ValueError('API URL must identify Gitea, not GitHub') + prefix = parts.path.rstrip('/') + return parts, prefix + + +def connection(parts): + cls = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection + return cls(parts.hostname, parts.port, timeout=300, **({'context': ssl.create_default_context()} if parts.scheme == 'https' else {})) + + +def request_json(parts, prefix, path, token, payload, method='POST', expected_status=201): + body = json.dumps(payload, separators=(',', ':')).encode('utf-8') + conn = connection(parts) + try: + conn.request(method, prefix + path, body=body, + headers={'Authorization': f'token {token}', 'Content-Type': 'application/json', + 'Accept': 'application/json'}) + response = conn.getresponse() + data = response.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise ValueError('Gitea response exceeds size limit') + if response.status != expected_status: + raise RuntimeError(f'Gitea API returned HTTP {response.status}') + result = json.loads(data) + if not isinstance(result, dict): + raise ValueError('Gitea response must be a JSON object') + return result + finally: + conn.close() + + +def upload_asset(parts, prefix, path, token, asset, expected): + name = asset.name + route = prefix + path + '/assets?' + urlencode({'name': name}) + fd = os.open(asset, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + conn = None + try: + source_stat = os.fstat(fd) + if not stat.S_ISREG(source_stat.st_mode): + raise ValueError(f'not a regular artifact file: {name}') + size = source_stat.st_size + if size != expected['size']: + raise ValueError(f'artifact size changed after verification: {name}') + conn = connection(parts) + conn.putrequest('POST', route) + conn.putheader('Authorization', f'token {token}') + conn.putheader('Content-Type', 'application/octet-stream') + conn.putheader('Content-Length', str(size)) + conn.putheader('Accept', 'application/json') + conn.endheaders() + digest = hashlib.sha256() + sent = 0 + with os.fdopen(fd, 'rb') as source: + fd = -1 + while sent < size: + block = source.read(min(CHUNK_SIZE, size - sent)) + if not block: + raise ValueError(f'artifact was truncated during upload: {name}') + sent += len(block) + digest.update(block) + conn.send(block) + if digest.hexdigest() != expected['sha256']: + raise ValueError(f'artifact content changed after verification: {name}') + response = conn.getresponse() + data = response.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise ValueError('Gitea response exceeds size limit') + if response.status != 201: + raise RuntimeError(f'Gitea asset upload returned HTTP {response.status}') + metadata = json.loads(data) + if not isinstance(metadata, dict): + raise ValueError('Gitea asset response must be a JSON object') + if metadata.get('name') != name or metadata.get('size') != size: + raise ValueError(f'Gitea returned mismatched asset metadata: {name}') + verify_uploaded_asset(parts, token, metadata, expected) + return {'name': name, 'size': size} + finally: + if fd >= 0: + os.close(fd) + if conn is not None: + conn.close() + + +def verify_uploaded_asset(parts, token, metadata, expected): + # Never forward a scoped token to a redirect or to an asset's foreign URL. + url = metadata.get('browser_download_url') + if not isinstance(url, str): + raise ValueError('Gitea asset lacks its download URL') + asset_url = urlsplit(url) + if (asset_url.scheme != parts.scheme or asset_url.hostname != parts.hostname or + (asset_url.port or (443 if asset_url.scheme == 'https' else 80)) != + (parts.port or (443 if parts.scheme == 'https' else 80)) or asset_url.username or asset_url.password or + asset_url.query or asset_url.fragment or + not re.fullmatch(r'/attachments/[A-Za-z0-9-]+', asset_url.path)): + raise ValueError('Gitea asset download URL must be a same-origin attachment') + conn = connection(parts) + try: + conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'}) + response = conn.getresponse() + if response.status != 200: + raise RuntimeError(f'Gitea asset verification returned HTTP {response.status}') + digest = hashlib.sha256() + total = 0 + while block := response.read(min(CHUNK_SIZE, expected['size'] - total + 1)): + total += len(block) + if total > expected['size']: + raise ValueError('Gitea uploaded asset exceeds its verified size') + digest.update(block) + if total != expected['size'] or digest.hexdigest() != expected['sha256']: + raise ValueError('Gitea uploaded asset checksum mismatch') + finally: + conn.close() + + +def publish(api_url, repository, token, tag, target, title, notes, directory, profile='cuda'): + if not token: + raise ValueError('GITEA_TOKEN is required') + if not isinstance(token, str) or len(token) > 512 or any(not 33 <= ord(char) <= 126 for char in token): + raise ValueError('GITEA_TOKEN must be bounded printable ASCII without whitespace') + repo_parts = repository.split('/') + if len(repo_parts) != 2 or any(part in {'.', '..'} or not re.fullmatch(r'[A-Za-z0-9_.-]+', part) + for part in repo_parts): + raise ValueError('repository must be owner/name') + tag_pattern = {'cuda': r'cuda-preview-[0-9]+-[0-9]+', + 'static-cuda': r'static-cuda-preview-[0-9]+-[0-9]+', + 'cli': r'(?:cli-preview-[0-9]+-[0-9]+|v[0-9][A-Za-z0-9_.-]*)'}.get(profile, '') + if not re.fullmatch(tag_pattern, tag): + raise ValueError('tag does not match the explicit preview profile') + if not re.fullmatch(r'[0-9a-f]{40}', target): + raise ValueError('target must be a full lowercase Git SHA') + parts, prefix = parse_api_url(api_url) + hashes = verify_artifacts(directory, target, profile) + owner, repo = repo_parts + release = request_json(parts, prefix, f'/repos/{owner}/{repo}/releases', token, + {'tag_name': tag, 'target_commitish': target, 'name': title, + 'body': notes, 'draft': True, 'prerelease': True}) + release_id = release.get('id') + if (type(release_id) is not int or release_id <= 0 or release.get('draft') is not True or + release.get('prerelease') is not True or release.get('tag_name') != tag or + release.get('target_commitish') != target): + raise ValueError('Gitea did not confirm the exact draft prerelease identity') + asset_route = f'/repos/{owner}/{repo}/releases/{release_id}' + uploaded = [] + for name in sorted(hashes): + uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name])) + finalized = request_json(parts, prefix, asset_route, token, {'draft': False}, + method='PATCH', expected_status=200) + if finalized.get('id') != release_id or finalized.get('draft') is not False: + raise ValueError('Gitea did not confirm publication of the complete preview release') + return {'release_id': release_id, 'release_url': release.get('html_url'), + 'tag': tag, 'target': target, 'assets': [dict(uploaded_asset, sha256=hashes[uploaded_asset['name']]['sha256']) + for uploaded_asset in uploaded]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--api-url', default=os.environ.get('GITHUB_API_URL'), required=os.environ.get('GITHUB_API_URL') is None) + parser.add_argument('--repository', default=os.environ.get('GITHUB_REPOSITORY'), required=os.environ.get('GITHUB_REPOSITORY') is None) + parser.add_argument('--profile', choices=['cli', 'cuda', 'static-cuda'], required=True) + parser.add_argument('--tag', required=True) + parser.add_argument('--target', required=True) + parser.add_argument('--title', required=True) + parser.add_argument('--notes', required=True) + parser.add_argument('--directory', type=Path, required=True) + args = parser.parse_args() + try: + result = publish(args.api_url, args.repository, os.environ.get('GITEA_TOKEN', ''), + args.tag, args.target, args.title, args.notes, args.directory, args.profile) + print(json.dumps(result, sort_keys=True)) + except (ValueError, OSError, RuntimeError, http.client.HTTPException, json.JSONDecodeError) as error: + print(f'Gitea release publication failed: {error}', file=sys.stderr) + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py new file mode 100644 index 00000000..716aef1d --- /dev/null +++ b/scripts/test-gitea-release.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""Contract tests for private CUDA preview release publishing.""" +import hashlib +import importlib.util +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import tempfile +import threading +from urllib.parse import parse_qs, urlsplit +import unittest + +spec = importlib.util.spec_from_file_location('publisher', Path(__file__).with_name('publish-gitea-release.py')) +publisher = importlib.util.module_from_spec(spec) +spec.loader.exec_module(publisher) + +TOKEN = 'fixture-action-token' +REVISION = 'a' * 40 + + +class FakeGitea(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def send_json(self, status, payload): + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + if self.headers.get('Authorization') != f'token {TOKEN}': + self.send_json(401, {'message': 'bad token'}) + return + if self.path == '/api/v1/repos/owner/repo/releases': + body = self.rfile.read(int(self.headers['Content-Length'])) + self.server.release_payload = json.loads(body) + if self.server.fail_create: + return self.send_json(403, {'message': TOKEN}) + return self.send_json(201, dict(self.server.release_payload, id=73, html_url='http://gitea.invalid/owner/repo/releases/tag/x')) + parsed = urlsplit(self.path) + if parsed.path == '/api/v1/repos/owner/repo/releases/73/assets': + size = int(self.headers['Content-Length']) + digest = hashlib.sha256() + content = bytearray() + remaining = size + while remaining: + block = self.rfile.read(min(128 * 1024, remaining)) + if not block: + raise AssertionError('truncated streamed request body') + digest.update(block) + content.extend(block) + remaining -= len(block) + name = parse_qs(parsed.query)['name'][0] + self.server.assets.append({'name': name, 'size': size, 'sha256': digest.hexdigest()}) + if self.server.fail_asset: + return self.send_json(500, {'message': TOKEN}) + attachment = hashlib.sha256(name.encode()).hexdigest() + self.server.downloads[attachment] = bytes(content) + download = f'http://127.0.0.1:{self.server.server_port}/attachments/{attachment}' + if self.server.foreign_download: + download = 'https://foreign.invalid/attachments/id' + return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download}) + self.send_json(404, {'message': 'unexpected route'}) + + def do_GET(self): + if self.headers.get('Authorization') != f'token {TOKEN}': + return self.send_json(401, {'message': 'bad token'}) + name = self.path.removeprefix('/attachments/') + content = self.server.downloads.get(name) + if content is None: + return self.send_json(404, {}) + if self.server.corrupt_download: + content = b'x' + content[1:] + self.send_response(200) + self.send_header('Content-Length', str(len(content))) + self.end_headers() + self.wfile.write(content) + + def do_PATCH(self): + if self.headers.get('Authorization') != f'token {TOKEN}': + return self.send_json(401, {'message': 'bad token'}) + if self.path != '/api/v1/repos/owner/repo/releases/73': + return self.send_json(404, {'message': 'unexpected route'}) + self.server.finalize_payload = json.loads(self.rfile.read(int(self.headers['Content-Length']))) + self.send_json(200, {'id': 73, 'draft': self.server.finalize_payload['draft']}) + + +class PublisherTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.directory = Path(self.tmp.name) + self.server = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea) + self.server.release_payload = None + self.server.finalize_payload = None + self.server.assets = [] + self.server.fail_create = False + self.server.fail_asset = False + self.server.downloads = {} + self.server.foreign_download = False + self.server.corrupt_download = False + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.thread.join) + self.addCleanup(self.server.shutdown) + self.api_url = f'http://127.0.0.1:{self.server.server_port}/api/v1' + self.write_artifacts() + + def write_artifacts(self): + directory = self.directory + (directory / publisher.PACKAGE_BINARY).write_bytes(b'embedded-engine-fixture') + engine_sha = hashlib.sha256(b'cuda-engine-fixture').hexdigest() + features = {'schema_version': 1, 'source_revision': REVISION, 'cuda_architectures': '120', + 'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, + 'kar_ple': False, 'kar_experts': False, 'ple_trace': False}} + feature_sha = publisher.canonical_sha(features) + base = 'ubuntu@sha256:' + 'b' * 64 + package_provenance = { + 'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION, + 'target': 'x86_64-unknown-linux-musl', 'gpu_tested': False, 'model_tested': False, + 'clean_node_tested': False, + 'engine': {'sha256': engine_sha, 'embedded': True, 'target_os': 'linux', + 'target_arch': 'x86_64', 'declared_source_revision': REVISION, 'bytes': 19}, + 'engine_elf_audit': {'toolkit_shared_libraries': False, 'host_glibc_required': True, + 'minimum_glibc': '2.39'}, + 'loader_probe': {'environment': 'pinned-runtime-container', 'base': base, 'glibc': '2.43', + 'image_id': 'sha256:' + 'b' * 64, 'user': '65532:65532', 'gpu_tested': False}, + 'build_features': features, 'build_features_sha256': feature_sha, + } + (directory / 'PROVENANCE.json').write_text(json.dumps(package_provenance)) + package_files = [publisher.PACKAGE_BINARY, 'PROVENANCE.json'] + (directory / 'SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(directory / name)} {name}\n' for name in package_files)) + receipt = publisher.file_sha256(directory / 'SHA256SUMS') + (directory / 'runtime-image.tar').write_bytes(b'runtime-image-' * 180000) + image_provenance = { + 'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION, + 'image': 'sha256:' + 'c' * 64, 'base': base, 'base_glibc': '2.43', + 'gpu_tested': False, 'model_tested': False, 'package_receipt_sha256': receipt, + 'build_features': features['features'], 'build_features_sha256': feature_sha, + 'qualification': 'Non-root GPU-hidden embedded identity and loader help only.', + } + (directory / 'IMAGE-PROVENANCE.json').write_text(json.dumps(image_provenance)) + (directory / 'CUDA-TOOLCHAIN.json').write_text(json.dumps({ + 'source': REVISION, 'driver_tested': False, 'model_tested': False, + 'builder_image_id': 'sha256:' + 'd' * 64, 'cuda_architectures': '120', + 'build_features': features['features'], 'build_features_sha256': feature_sha, + 'docker_builder': {'source_commit': REVISION, 'engine_sha256': engine_sha, + 'image_id': 'sha256:' + 'd' * 64, 'build_features_sha256': feature_sha, + 'runtime_image_id': image_provenance['image'], + 'runtime_archive_sha256': publisher.file_sha256(directory / 'runtime-image.tar')}, + })) + (directory / 'CUDA-LICENSES.tar').write_bytes(b'license archive') + image_files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'] + (directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(directory / name)} {name}\n' for name in image_files)) + + def test_uploads_exact_hashed_assets_via_api_v1_and_streams_large_asset(self): + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'CUDA preview 42.1', 'Build-only preview.', self.directory) + self.assertEqual(result['release_id'], 73) + self.assertEqual(result['target'], REVISION) + self.assertEqual(len(result['assets']), len(publisher.ASSETS)) + self.assertEqual(self.server.release_payload, { + 'tag_name': 'cuda-preview-42-1', 'target_commitish': REVISION, 'name': 'CUDA preview 42.1', + 'body': 'Build-only preview.', 'draft': True, 'prerelease': True, + }) + self.assertEqual(self.server.finalize_payload, {'draft': False}) + uploaded = {asset['name']: asset for asset in self.server.assets} + self.assertEqual(set(uploaded), publisher.ASSETS) + self.assertGreater(uploaded['runtime-image.tar']['size'], publisher.CHUNK_SIZE) + for name in publisher.ASSETS: + self.assertEqual(uploaded[name]['sha256'], publisher.file_sha256(self.directory / name)) + + def test_checksum_failure_precedes_api_call(self): + (self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered') + with self.assertRaisesRegex(ValueError, 'SHA256SUMS checksum mismatch'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_wrong_source_provenance_is_rejected(self): + path = self.directory / 'IMAGE-PROVENANCE.json' + image = json.loads(path.read_text()) + image['source_revision'] = 'c' * 40 + path.write_text(json.dumps(image)) + files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'] + (self.directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in files)) + with self.assertRaisesRegex(ValueError, 'runtime image provenance'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_api_failures_redact_token_and_do_not_finalize_incomplete_release(self): + self.server.fail_create = True + with self.assertRaisesRegex(RuntimeError, r'HTTP 403$') as failure: + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertNotIn(TOKEN, str(failure.exception)) + self.assertIsNone(self.server.finalize_payload) + + self.server.fail_create = False + self.server.fail_asset = True + with self.assertRaisesRegex(RuntimeError, r'HTTP 500$'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.finalize_payload) + + def test_unexpected_extra_file_and_invalid_route_are_rejected(self): + (self.directory / 'private-key').write_text('never upload') + with self.assertRaisesRegex(ValueError, 'exactly the CUDA preview files'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + (self.directory / 'private-key').unlink() + with self.assertRaisesRegex(ValueError, 'API URL'): + publisher.publish(self.api_url.replace('/api/v1', '/api/v3'), 'owner/repo', TOKEN, + 'cuda-preview-42-1', REVISION, 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def test_invalid_scope_and_target_rejected(self): + with self.assertRaisesRegex(ValueError, 'owner/name'): + publisher.publish(self.api_url, '../repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + with self.assertRaisesRegex(ValueError, 'full lowercase Git SHA'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', 'ABC', + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def rehash(self): + for manifest, names in [('SHA256SUMS', publisher.PACKAGE_ASSETS), + ('IMAGE-SHA256SUMS', publisher.IMAGE_ASSETS)]: + (self.directory / manifest).write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(names))) + image_path = self.directory / 'IMAGE-PROVENANCE.json' + image = json.loads(image_path.read_text()) + image['package_receipt_sha256'] = publisher.file_sha256(self.directory / 'SHA256SUMS') + image_path.write_text(json.dumps(image)) + (self.directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(publisher.IMAGE_ASSETS))) + + def test_current_producer_receipt_contract(self): + # Exercise the producer's own validators, not source-text pattern checks. + import shutil + for filename in ('build-linux-package.py', 'build-runtime-image.py'): + spec = importlib.util.spec_from_file_location('producer', Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + package = json.loads((self.directory / 'PROVENANCE.json').read_text()) + feature_file = root / 'BUILD-FEATURES.json' + feature_file.write_text(json.dumps(package['build_features'], sort_keys=True, indent=2) + '\n') + if filename == 'build-linux-package.py': + self.assertEqual(module.build_features(feature_file, REVISION), + (package['build_features'], package['build_features_sha256'])) + else: + source = root / 'source' + stage = root / 'stage' + source.mkdir(); stage.mkdir() + for name in module.FILES: + shutil.copyfile(self.directory / name, source / name) + self.assertEqual(module.freeze(source, stage, + publisher.file_sha256(source / 'SHA256SUMS'), False), package) + self.assertEqual(set(publisher.verify_artifacts(self.directory, REVISION)), publisher.ASSETS) + + def test_forged_receipt_bindings_fail_even_with_fresh_checksums(self): + faults = [('CUDA-TOOLCHAIN.json', ('docker_builder', 'engine_sha256'), 'e' * 64), + ('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_image_id'), 'sha256:' + 'e' * 64), + ('CUDA-TOOLCHAIN.json', ('docker_builder', 'source_commit'), 'e' * 40), + ('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_archive_sha256'), 'e' * 64), + ('CUDA-TOOLCHAIN.json', ('build_features_sha256',), 'e' * 64), + ('IMAGE-PROVENANCE.json', ('base',), 'ubuntu@sha256:' + 'e' * 64), + ('IMAGE-PROVENANCE.json', ('gpu_tested',), True), + ('PROVENANCE.json', ('loader_probe', 'environment'), 'assembly-host'), + ('PROVENANCE.json', ('build_features', 'source_revision'), 'e' * 40), + ('PROVENANCE.json', ('build_features', 'features', 'kar_experts'), True), + ('PROVENANCE.json', ('engine_elf_audit', 'toolkit_shared_libraries'), True), + ('PROVENANCE.json', ('engine_elf_audit', 'minimum_glibc'), '99.0'), + ('PROVENANCE.json', ('loader_probe', 'glibc'), None)] + for filename, keys, value in faults: + with self.subTest(filename=filename, keys=keys): + self.write_artifacts() + path = self.directory / filename + record = json.loads(path.read_text()) + dest = record + for key in keys[:-1]: + dest = dest[key] + dest[keys[-1]] = value + path.write_text(json.dumps(record)) + self.rehash() + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertIsNone(self.server.release_payload) + + def write_cli(self): + for path in self.directory.iterdir(): + path.unlink() + (self.directory / publisher.PACKAGE_BINARY).write_bytes(b'synthetic-static-cli') + (self.directory / 'BUILD-PROVENANCE.txt').write_text( + f'Commit: {REVISION}\nWorkflow: https://gitea.invalid/owner/repo/actions/runs/42\nrustc fixture\n') + (self.directory / 'ELF-AUDIT.txt').write_text( + 'ELF Header:\n Class: ELF64\n Machine: Advanced Micro Devices X86-64\nNo dynamic section.\n') + self.rehash_cli() + + def rehash_cli(self): + (self.directory / 'SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' + for name in sorted(publisher.CLI_ASSETS - {'SHA256SUMS'}))) + + def test_cli_four_assets_and_version_tag_publish_after_all_uploads(self): + self.write_cli() + for tag in ('cli-preview-42-1', 'v0.1.0-preview'): + self.server.assets = [] + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION, + 'CLI preview', 'No engine or model.', self.directory, 'cli') + self.assertEqual({asset['name'] for asset in result['assets']}, publisher.CLI_ASSETS) + self.assertTrue(self.server.release_payload['draft']) + self.assertTrue(self.server.release_payload['prerelease']) + self.assertEqual(self.server.finalize_payload, {'draft': False}) + + def test_cli_mismatch_and_bad_static_audit_fail_before_create(self): + for fault in ('wrong-commit', 'duplicate-commit', 'dynamic-elf', 'tamper', 'extra-file'): + with self.subTest(fault=fault): + self.write_cli() + provenance = self.directory / 'BUILD-PROVENANCE.txt' + if fault == 'wrong-commit': + provenance.write_text(provenance.read_text().replace(REVISION, 'e' * 40)) + elif fault == 'duplicate-commit': + provenance.write_text(provenance.read_text() + f'Commit: {REVISION}\n') + elif fault == 'dynamic-elf': + audit = self.directory / 'ELF-AUDIT.txt' + audit.write_text(audit.read_text() + 'INTERP\n') + elif fault == 'extra-file': + (self.directory / 'private-key').write_text('synthetic') + self.rehash_cli() + if fault == 'tamper': + (self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered') + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION, + 'title', 'notes', self.directory, 'cli') + self.assertIsNone(self.server.release_payload) + + def test_missing_cuda_files_and_cli_upload_fault_leave_no_published_release(self): + (self.directory / 'CUDA-LICENSES.tar').unlink() + with self.assertRaises(ValueError): + publisher.verify_artifacts(self.directory, REVISION) + self.write_cli() + self.server.fail_asset = True + with self.assertRaises(RuntimeError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION, + 'title', 'notes', self.directory, 'cli') + self.assertTrue(self.server.release_payload['draft']) + self.assertIsNone(self.server.finalize_payload) + + def test_remote_corruption_and_foreign_download_leave_release_draft(self): + for flag in ('corrupt_download', 'foreign_download'): + with self.subTest(flag=flag): + setattr(self.server, flag, True) + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertTrue(self.server.release_payload['draft']) + self.assertIsNone(self.server.finalize_payload) + setattr(self.server, flag, False) + + def test_static_cuda_exact_six_file_profile(self): + for name in ('CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'): + (self.directory / name).unlink() + (self.directory / 'IMAGE-SHA256SUMS').write_text(''.join( + f'{publisher.file_sha256(self.directory / name)} {name}\n' + for name in sorted(publisher.STATIC_IMAGE_ASSETS))) + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'static-cuda-preview-42-1', REVISION, + 'Static preview', 'No hosted toolchain qualification.', self.directory, 'static-cuda') + self.assertEqual({asset['name'] for asset in result['assets']}, publisher.STATIC_ASSETS) + with self.assertRaises(ValueError): + publisher.verify_artifacts(self.directory, REVISION, 'cuda') + + def test_https_policy_and_profile_tag_isolation(self): + for url in ('http://gitea.invalid/api/v1', 'https://api.github.com/api/v1', + 'https://user:password@gitea.invalid/api/v1'): + with self.assertRaises(ValueError): + publisher.parse_api_url(url) + for tag in ('cli-preview-42-1', 'static-cuda-preview-42-1', 'v0.1.0'): + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION, + 'title', 'notes', self.directory, 'cuda') + self.assertIsNone(self.server.release_payload) + + def test_invalid_token_is_rejected_without_transport_or_secret_echo(self): + for token in ('synthetic-secret\r\ninjected', 'synthetic secret', 'x' * 513, 'synthetic-\u00e9'): + with self.subTest(token_kind=len(token)): + with self.assertRaisesRegex(ValueError, 'bounded printable ASCII') as failure: + publisher.publish(self.api_url, 'owner/repo', token, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertNotIn(token, str(failure.exception)) + self.assertNotIn('synthetic-secret', str(failure.exception)) + self.assertIsNone(self.server.release_payload) + + def test_nonregular_and_symlink_files_are_rejected_before_transport(self): + import os + path = self.directory / 'CUDA-LICENSES.tar' + path.unlink() + os.mkfifo(path) + with self.assertRaisesRegex(ValueError, 'regular artifact'): + publisher.verify_artifacts(self.directory, REVISION) + path.unlink() + path.symlink_to(self.directory / publisher.PACKAGE_BINARY) + with self.assertRaises(OSError): + publisher.verify_artifacts(self.directory, REVISION) + self.assertIsNone(self.server.release_payload) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From 93109983fbb6b41b30689f83a4a1fee27743e8bd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 20:00:02 +0200 Subject: [PATCH 11/14] fix(ci): verify actual Gitea release download routes --- docs/gitea-preview-publication.md | 4 +- scripts/publish-gitea-release.py | 85 +++++++++++++------- scripts/test-gitea-release.py | 125 ++++++++++++++++++++++++++++-- 3 files changed, 180 insertions(+), 34 deletions(-) diff --git a/docs/gitea-preview-publication.md b/docs/gitea-preview-publication.md index bcf023f7..3c110b8b 100644 --- a/docs/gitea-preview-publication.md +++ b/docs/gitea-preview-publication.md @@ -12,6 +12,8 @@ All profiles reject missing/extra files, symlinks, mismatched checksums and sour CUDA publication validates current package `loader_probe` receipts from `--probe-in-runtime-image`, image/package receipt binding and canonical compile-feature digests. These producers do not emit the historical `engine_help_probe` strings; their existing loader/identity/help probes must pass for assembly to emit the current receipts. Hosted toolchain publication additionally binds the actual builder image identity, source, engine hash, compile-feature digest, runtime image identity and saved archive hash. The inactive static CUDA profile preserves its original six-file contract and has no hosted compiler or license receipt qualification. Its runner and build inputs are unchanged. -Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and rereads each same-origin Gitea attachment to compare size and SHA256. Only then does it remove draft status. Redirects and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy. +Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and rereads each exact same-origin repository/tag/asset download URL to compare size and SHA256. It allows at most two same-origin redirects, restricted to attachment paths for the UUID returned by that asset upload. Only then does it remove draft status. Other redirect paths, queries, credentials and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy. Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate. + +The download URL profile was checked against read-only Gitea release `cuda-preview-2495-1` on git.vezha.io: `/para/leleka/releases/download/{tag}/{asset}`. Gitea 1.27.3 [RedirectDownload](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/routers/web/repo/repo.go) finds releases by repository/tag and includes drafts for writers; it serves the associated attachment without requiring a Git tag to exist. Synthetic tests verify download and redirect hashing while the release is still draft and before tag publication, and prove that foreign redirects receive no request or token. Actual fresh CI publication remains unqualified until that gate succeeds. diff --git a/scripts/publish-gitea-release.py b/scripts/publish-gitea-release.py index 2aef223e..1715cbd0 100644 --- a/scripts/publish-gitea-release.py +++ b/scripts/publish-gitea-release.py @@ -11,7 +11,7 @@ import re import ssl import stat import sys -from urllib.parse import urlencode, urlsplit +from urllib.parse import urlencode, urljoin, urlsplit PACKAGE_BINARY = 'strata-next-linux-x86_64-musl' PACKAGE_ASSETS = {PACKAGE_BINARY, 'PROVENANCE.json'} @@ -206,7 +206,7 @@ def request_json(parts, prefix, path, token, payload, method='POST', expected_st conn.close() -def upload_asset(parts, prefix, path, token, asset, expected): +def upload_asset(parts, prefix, path, token, asset, expected, repository, tag): name = asset.name route = prefix + path + '/assets?' + urlencode({'name': name}) fd = os.open(asset, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) @@ -249,7 +249,7 @@ def upload_asset(parts, prefix, path, token, asset, expected): raise ValueError('Gitea asset response must be a JSON object') if metadata.get('name') != name or metadata.get('size') != size: raise ValueError(f'Gitea returned mismatched asset metadata: {name}') - verify_uploaded_asset(parts, token, metadata, expected) + verify_uploaded_asset(parts, token, metadata, expected, repository, tag) return {'name': name, 'size': size} finally: if fd >= 0: @@ -258,35 +258,64 @@ def upload_asset(parts, prefix, path, token, asset, expected): conn.close() -def verify_uploaded_asset(parts, token, metadata, expected): - # Never forward a scoped token to a redirect or to an asset's foreign URL. - url = metadata.get('browser_download_url') +def validate_download_url(parts, url, allowed_paths): if not isinstance(url, str): raise ValueError('Gitea asset lacks its download URL') asset_url = urlsplit(url) if (asset_url.scheme != parts.scheme or asset_url.hostname != parts.hostname or (asset_url.port or (443 if asset_url.scheme == 'https' else 80)) != - (parts.port or (443 if parts.scheme == 'https' else 80)) or asset_url.username or asset_url.password or - asset_url.query or asset_url.fragment or - not re.fullmatch(r'/attachments/[A-Za-z0-9-]+', asset_url.path)): - raise ValueError('Gitea asset download URL must be a same-origin attachment') - conn = connection(parts) - try: - conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'}) - response = conn.getresponse() - if response.status != 200: - raise RuntimeError(f'Gitea asset verification returned HTTP {response.status}') - digest = hashlib.sha256() - total = 0 - while block := response.read(min(CHUNK_SIZE, expected['size'] - total + 1)): - total += len(block) - if total > expected['size']: - raise ValueError('Gitea uploaded asset exceeds its verified size') - digest.update(block) - if total != expected['size'] or digest.hexdigest() != expected['sha256']: - raise ValueError('Gitea uploaded asset checksum mismatch') - finally: - conn.close() + (parts.port or (443 if parts.scheme == 'https' else 80)) or + asset_url.username or asset_url.password or asset_url.query or asset_url.fragment or + asset_url.path not in allowed_paths): + raise ValueError('Gitea asset URL must match its same-origin release or attachment route') + return asset_url + + +def verify_uploaded_asset(parts, token, metadata, expected, repository, tag): + # Gitea returns a release route, which can redirect to the same asset UUID. + # Validate every hop before sending a scoped token; never follow foreign URLs. + base_path = parts.path.rstrip('/').removesuffix('/api/v1') + repo_path = base_path + '/' + repository + release_path = f"{repo_path}/releases/download/{tag}/{metadata['name']}" + url = metadata.get('browser_download_url') + validate_download_url(parts, url, {release_path}) + attachment = metadata.get('uuid') + if not isinstance(attachment, str) or not re.fullmatch( + r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', attachment): + raise ValueError('Gitea asset lacks a valid attachment UUID') + attachment_paths = {f'{base_path}/attachments/{attachment}', + f'{repo_path}/attachments/{attachment}', + f'{repo_path}/releases/attachments/{attachment}'} + for hop in range(3): + asset_url = validate_download_url(parts, url, {release_path} if hop == 0 else attachment_paths) + conn = connection(parts) + try: + conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'}) + response = conn.getresponse() + if response.status in {301, 302, 303, 307, 308}: + if hop == 2: + raise ValueError('Gitea asset verification exceeds two redirects') + location = response.getheader('Location') + if not location: + raise ValueError('Gitea asset redirect lacks its location') + candidate = urljoin(url, location) + validate_download_url(parts, candidate, attachment_paths) + url = candidate + continue + if response.status != 200: + raise RuntimeError(f'Gitea asset verification returned HTTP {response.status}') + digest = hashlib.sha256() + total = 0 + while block := response.read(min(CHUNK_SIZE, expected['size'] - total + 1)): + total += len(block) + if total > expected['size']: + raise ValueError('Gitea uploaded asset exceeds its verified size') + digest.update(block) + if total != expected['size'] or digest.hexdigest() != expected['sha256']: + raise ValueError('Gitea uploaded asset checksum mismatch') + return + finally: + conn.close() def publish(api_url, repository, token, tag, target, title, notes, directory, profile='cuda'): @@ -319,7 +348,7 @@ def publish(api_url, repository, token, tag, target, title, notes, directory, pr asset_route = f'/repos/{owner}/{repo}/releases/{release_id}' uploaded = [] for name in sorted(hashes): - uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name])) + uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name], repository, tag)) finalized = request_json(parts, prefix, asset_route, token, {'draft': False}, method='PATCH', expected_status=200) if finalized.get('id') != release_id or finalized.get('draft') is not False: diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py index 716aef1d..8fedded3 100644 --- a/scripts/test-gitea-release.py +++ b/scripts/test-gitea-release.py @@ -9,6 +9,7 @@ import tempfile import threading from urllib.parse import parse_qs, urlsplit import unittest +import uuid spec = importlib.util.spec_from_file_location('publisher', Path(__file__).with_name('publish-gitea-release.py')) publisher = importlib.util.module_from_spec(spec) @@ -37,6 +38,9 @@ class FakeGitea(BaseHTTPRequestHandler): if self.path == '/api/v1/repos/owner/repo/releases': body = self.rfile.read(int(self.headers['Content-Length'])) self.server.release_payload = json.loads(body) + self.server.current_draft = self.server.release_payload['draft'] + self.server.tag_exists = False + self.server.finalize_payload = None if self.server.fail_create: return self.send_json(403, {'message': TOKEN}) return self.send_json(201, dict(self.server.release_payload, id=73, html_url='http://gitea.invalid/owner/repo/releases/tag/x')) @@ -57,19 +61,55 @@ class FakeGitea(BaseHTTPRequestHandler): self.server.assets.append({'name': name, 'size': size, 'sha256': digest.hexdigest()}) if self.server.fail_asset: return self.send_json(500, {'message': TOKEN}) - attachment = hashlib.sha256(name.encode()).hexdigest() + attachment = str(uuid.UUID(hashlib.sha256(name.encode()).hexdigest()[:32])) self.server.downloads[attachment] = bytes(content) - download = f'http://127.0.0.1:{self.server.server_port}/attachments/{attachment}' + tag = self.server.release_payload['tag_name'] + release_path = f'/owner/repo/releases/download/{tag}/{name}' + self.server.release_paths[release_path] = attachment + if self.server.wrong_download: + release_path = release_path.replace(*self.server.wrong_download) + download = f'http://127.0.0.1:{self.server.server_port}{release_path}' if self.server.foreign_download: download = 'https://foreign.invalid/attachments/id' - return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download}) + return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download, 'uuid': attachment}) self.send_json(404, {'message': 'unexpected route'}) def do_GET(self): + self.server.gets.append((self.path, self.headers.get('Authorization'))) + self.server.get_states.append((self.server.current_draft, self.server.tag_exists)) if self.headers.get('Authorization') != f'token {TOKEN}': return self.send_json(401, {'message': 'bad token'}) - name = self.path.removeprefix('/attachments/') - content = self.server.downloads.get(name) + attachment = self.server.release_paths.get(self.path) + if attachment is not None and self.server.redirect_mode: + location = f'/attachments/{attachment}' + if self.server.redirect_mode == 'repo-attachment': + location = f'/owner/repo/releases/attachments/{attachment}' + elif self.server.redirect_mode == 'foreign': + location = self.server.foreign_url + location + elif self.server.redirect_mode == 'query': + location += '?token=synthetic' + elif self.server.redirect_mode == 'credentials': + location = f'http://user:password@127.0.0.1:{self.server.server_port}{location}' + elif self.server.redirect_mode == 'wrong-uuid': + location = '/attachments/00000000-0000-0000-0000-000000000000' + elif self.server.redirect_mode == 'wrong-route': + location = '/owner/other/releases/download/tag/asset' + self.send_response(302) + self.send_header('Location', location) + self.send_header('Content-Length', '0') + self.end_headers() + return + if attachment is None: + attachment = self.path.rsplit('/', 1)[-1] + if self.server.redirect_mode in {'loop', 'two-hops'} and '/attachments/' in self.path: + if self.server.redirect_mode == 'loop' or self.path.startswith('/attachments/'): + self.send_response(302) + location = f'/owner/repo/releases/attachments/{attachment}' + self.send_header('Location', location) + self.send_header('Content-Length', '0') + self.end_headers() + return + content = self.server.downloads.get(attachment) if content is None: return self.send_json(404, {}) if self.server.corrupt_download: @@ -85,6 +125,8 @@ class FakeGitea(BaseHTTPRequestHandler): if self.path != '/api/v1/repos/owner/repo/releases/73': return self.send_json(404, {'message': 'unexpected route'}) self.server.finalize_payload = json.loads(self.rfile.read(int(self.headers['Content-Length']))) + self.server.current_draft = self.server.finalize_payload['draft'] + self.server.tag_exists = not self.server.current_draft self.send_json(200, {'id': 73, 'draft': self.server.finalize_payload['draft']}) @@ -100,6 +142,14 @@ class PublisherTests(unittest.TestCase): self.server.fail_create = False self.server.fail_asset = False self.server.downloads = {} + self.server.release_paths = {} + self.server.gets = [] + self.server.get_states = [] + self.server.current_draft = True + self.server.tag_exists = False + self.server.wrong_download = None + self.server.redirect_mode = None + self.server.foreign_url = 'http://foreign.invalid' self.server.foreign_download = False self.server.corrupt_download = False self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) @@ -415,6 +465,71 @@ class PublisherTests(unittest.TestCase): publisher.verify_artifacts(self.directory, REVISION) self.assertIsNone(self.server.release_payload) + def test_release_download_route_and_same_origin_redirects_verify_before_publish(self): + for mode in (None, 'attachment', 'repo-attachment', 'two-hops'): + with self.subTest(mode=mode): + self.server.redirect_mode = mode + self.server.gets = [] + self.server.get_states = [] + self.server.assets = [] + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(len(result['assets']), 8) + self.assertEqual(self.server.finalize_payload, {'draft': False}) + self.assertTrue(any('/owner/repo/releases/download/cuda-preview-42-1/' in path + for path, _auth in self.server.gets)) + self.assertTrue(all(auth == f'token {TOKEN}' for _path, auth in self.server.gets)) + expected_gets = 8 * ({None: 1, 'two-hops': 3}.get(mode, 2)) + self.assertEqual(len(self.server.gets), expected_gets) + self.assertEqual(self.server.get_states, [(True, False)] * expected_gets) + self.assertFalse(self.server.current_draft) + self.assertTrue(self.server.tag_exists) + + def test_foreign_redirect_is_rejected_without_forwarding_token(self): + foreign = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea) + foreign.gets = [] + foreign.get_states = [] + foreign.current_draft = True + foreign.tag_exists = False + thread = threading.Thread(target=foreign.serve_forever, daemon=True) + thread.start() + self.addCleanup(foreign.server_close) + self.addCleanup(thread.join) + self.addCleanup(foreign.shutdown) + self.server.foreign_url = f'http://127.0.0.1:{foreign.server_port}' + self.server.redirect_mode = 'foreign' + with self.assertRaisesRegex(ValueError, 'same-origin'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(foreign.gets, []) + self.assertEqual(len(self.server.gets), 1) + self.assertIsNone(self.server.finalize_payload) + + def test_redirect_limit_and_untrusted_destinations_leave_draft(self): + for mode in ('loop', 'query', 'credentials', 'wrong-uuid', 'wrong-route'): + with self.subTest(mode=mode): + self.server.redirect_mode = mode + self.server.gets = [] + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertLessEqual(len(self.server.gets), 3) + self.assertTrue(self.server.release_payload['draft']) + self.assertIsNone(self.server.finalize_payload) + + def test_initial_download_url_requires_exact_repository_tag_and_asset(self): + for substitution in (('/owner/repo/', '/owner/other/'), + ('cuda-preview-42-1', 'cuda-preview-43-1'), + ('CUDA-LICENSES.tar', 'OTHER.tar')): + with self.subTest(substitution=substitution): + self.server.wrong_download = substitution + self.server.gets = [] + with self.assertRaisesRegex(ValueError, 'same-origin release'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(self.server.gets, []) + self.assertIsNone(self.server.finalize_payload) + if __name__ == '__main__': unittest.main() -- 2.54.0 From f015052247c6218fcb8f97b612aeaf57efb45a26 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 20:33:14 +0200 Subject: [PATCH 12/14] fix(ci): scope release write permission to Gitea publishers --- .github/workflows/linux.yml | 12 +++ docs/gitea-preview-publication.md | 2 + scripts/test-gitea-release.py | 131 ++++++++++++++++++++++++++++++ 3 files changed, 145 insertions(+) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 980788d1..ce150266 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -67,6 +67,9 @@ jobs: run: scripts/check-kar-expert-gpu.sh static-cuda-package: + permissions: + contents: read + releases: write if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private needs: verify runs-on: [self-hosted, linux, x64, strata-gpu] @@ -127,6 +130,9 @@ jobs: run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" hosted-cuda-package: + permissions: + contents: read + releases: write if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private needs: verify runs-on: ubuntu-latest @@ -324,6 +330,9 @@ jobs: rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" linux-static-cli: + permissions: + contents: read + releases: write needs: verify runs-on: ubuntu-latest env: @@ -478,6 +487,9 @@ jobs: run: docker image rm strata-cli-check || true release-cli: + permissions: + contents: read + releases: write if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] runs-on: ubuntu-latest diff --git a/docs/gitea-preview-publication.md b/docs/gitea-preview-publication.md index 3c110b8b..074aa4a2 100644 --- a/docs/gitea-preview-publication.md +++ b/docs/gitea-preview-publication.md @@ -17,3 +17,5 @@ Publication creates a draft prerelease, streams the exact verified assets, check Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate. The download URL profile was checked against read-only Gitea release `cuda-preview-2495-1` on git.vezha.io: `/para/leleka/releases/download/{tag}/{asset}`. Gitea 1.27.3 [RedirectDownload](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/routers/web/repo/repo.go) finds releases by repository/tag and includes drafts for writers; it serves the associated attachment without requiring a Git tag to exist. Synthetic tests verify download and redirect hashing while the release is still draft and before tag publication, and prove that foreign redirects receive no request or token. Actual fresh CI publication remains unqualified until that gate succeeds. + +Publication jobs request `contents: read` and the Gitea-specific `releases: write` permission on their built-in job token; the workflow default and nonpublication jobs keep read-only permissions. This follows the [Gitea 1.27 token-permission contract](https://docs.gitea.com/1.27/usage/actions/token-permissions/). Owner/repository maximums can still clamp the effective token; the real publication gate must succeed before qualification. No stored PAT is read or created. diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py index 8fedded3..c7d2cfc3 100644 --- a/scripts/test-gitea-release.py +++ b/scripts/test-gitea-release.py @@ -5,6 +5,7 @@ import importlib.util from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path +import re import tempfile import threading from urllib.parse import parse_qs, urlsplit @@ -19,6 +20,136 @@ TOKEN = 'fixture-action-token' REVISION = 'a' * 40 +def workflow_permissions(lines, indent): + """Read the workflow's explicit permission maps; reject ambiguous syntax. + + This is deliberately a bounded contract parser for the committed workflow, + not a general YAML loader. Anchors, inline maps, duplicate keys and broad + grants fail closed rather than being interpreted differently from Gitea. + """ + headers = [index for index, line in enumerate(lines) + if re.match(r'^' + ' ' * indent + r'permissions:', line)] + if not headers: + return None + if len(headers) != 1: + raise ValueError('duplicate permissions map') + start = headers[0] + if lines[start].split(':', 1)[1].split('#', 1)[0].strip(): + raise ValueError('permissions must be an explicit map') + result = {} + for line in lines[start + 1:]: + if not line.strip() or line.lstrip().startswith('#'): + continue + spaces = len(line) - len(line.lstrip(' ')) + if spaces <= indent: + break + field = re.fullmatch(' ' * (indent + 2) + r'([a-z][a-z-]*):\s*(read|write|none)\s*(?:#.*)?', line) + if field is None or field[1] in result: + raise ValueError('invalid or duplicate permission scope') + result[field[1]] = field[2] + if not result: + raise ValueError('empty permissions map') + return result + + +def publisher_workflow_contract(text): + if len(text.encode()) > 128 * 1024 or len(text.splitlines()) > 4096: + raise ValueError('workflow exceeds contract limits') + lines = text.splitlines() + if any(re.match(r'^ *\t', line) for line in lines): + raise ValueError('tab indentation is unsupported') + roots = [index for index, line in enumerate(lines) if line == 'jobs:'] + if len(roots) != 1: + raise ValueError('expected one explicit jobs map') + start = roots[0] + if workflow_permissions(lines[:start], 0) != {'contents': 'read'}: + raise ValueError('workflow default must remain contents read-only') + jobs, current = {}, None + for line in lines[start + 1:]: + if line.strip() and not line.startswith((' ', '#')): + raise ValueError('unexpected root after jobs') + header = re.fullmatch(r' ([a-zA-Z0-9_-]+):\s*(?:#.*)?', line) + if header: + current = header[1] + if current in jobs or len(jobs) >= 128: + raise ValueError('invalid job map') + jobs[current] = [] + elif (line.strip() and not line.lstrip().startswith('#') + and len(line) - len(line.lstrip(' ')) == 2): + raise ValueError('job must use an explicit block map') + elif current is not None: + jobs[current].append(line) + elif line.strip() and not line.lstrip().startswith('#'): + raise ValueError('unsupported jobs syntax') + publishers = set() + call = re.compile(r'(?:^|[\s;&|])python3?(?:\.\d+)?(?:\s+-[A-Za-z]+)*\s+[\"\']?(?:\./)?scripts/publish-gitea-release\.py[\"\']?(?:\s|$)') + for name, section in jobs.items(): + commands = [] + for index, line in enumerate(section): + run = re.fullmatch(r' run:\s*(.*)', line) + if run is None: + continue + if run[1] in ('|', '|-', '|+', '>', '>-', '>+'): + for body in section[index + 1:]: + if body.strip() and len(body) - len(body.lstrip(' ')) <= 8: + break + if not body.lstrip().startswith('#'): + commands.append(body.strip()) + else: + commands.append(run[1]) + publishes = any(call.search(command) for command in commands) + scopes = workflow_permissions(section, 4) + if publishes: + if scopes != {'contents': 'read', 'releases': 'write'}: + raise ValueError('publisher requires only contents read and releases write') + publishers.add(name) + elif scopes is not None and any(level == 'write' for level in scopes.values()): + raise ValueError('nonpublisher job must not receive writable scopes') + if len(publishers) != 4: + raise ValueError('expected four actual publisher jobs') + return publishers, jobs + + +class PublisherWorkflowTests(unittest.TestCase): + def workflow(self): + path = Path(__file__).resolve().parent.parent / '.github/workflows/linux.yml' + with path.open('rb') as source: + data = source.read(128 * 1024 + 1) + self.assertLessEqual(len(data), 128 * 1024) + return data.decode() + + def test_actual_publisher_commands_have_narrow_job_permissions(self): + publishers, jobs = publisher_workflow_contract(self.workflow()) + self.assertEqual(len(publishers), 4) + self.assertGreater(len(jobs), len(publishers)) + # Discovery follows the executed command, not a hard-coded job name. + original = sorted(publishers)[0] + renamed = self.workflow().replace(f' {original}:\n', ' renamed-publication-fixture:\n', 1) + renamed_publishers, _ = publisher_workflow_contract(renamed) + self.assertIn('renamed-publication-fixture', renamed_publishers) + self.assertNotIn(original, renamed_publishers) + + def test_permission_regressions_are_rejected_before_publication(self): + text = self.workflow() + publishers, jobs = publisher_workflow_contract(text) + nonpublisher = sorted(set(jobs) - publishers)[0] + mutations = ( + text.replace('permissions:\n contents: read', 'permissions:\n contents: write', 1), + text.replace(' releases: write', ' releases: read', 1), + text.replace(' contents: read\n releases: write', ' contents: write\n releases: write', 1), + text.replace(f' {nonpublisher}:\n', f' {nonpublisher}:\n permissions:\n contents: write\n', 1), + text.replace(' releases: write', ' releases: write\n actions: write', 1), + text + '\n inline-job: {permissions: write-all, steps: []}\n', + text + '\n alias-job: *publisher-job\n', + text + '\n anchored-job: &publisher-job\n permissions:\n contents: write\n', + ) + for index, mutation in enumerate(mutations): + with self.subTest(regression=index): + self.assertNotEqual(mutation, text) + with self.assertRaises(ValueError): + publisher_workflow_contract(mutation) + + class FakeGitea(BaseHTTPRequestHandler): def log_message(self, *_args): pass -- 2.54.0 From aaa9ecc4721ba4b39dbf8fa9a2a6ab6f0644676f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 21:01:07 +0200 Subject: [PATCH 13/14] fix(ci): verify fresh Gitea upload attachment URLs --- docs/gitea-preview-publication.md | 14 +++++- scripts/publish-gitea-release.py | 7 +-- scripts/test-gitea-release.py | 79 +++++++++++++++++++++++++++++-- 3 files changed, 93 insertions(+), 7 deletions(-) diff --git a/docs/gitea-preview-publication.md b/docs/gitea-preview-publication.md index 074aa4a2..5cd29c4e 100644 --- a/docs/gitea-preview-publication.md +++ b/docs/gitea-preview-publication.md @@ -12,10 +12,22 @@ All profiles reject missing/extra files, symlinks, mismatched checksums and sour CUDA publication validates current package `loader_probe` receipts from `--probe-in-runtime-image`, image/package receipt binding and canonical compile-feature digests. These producers do not emit the historical `engine_help_probe` strings; their existing loader/identity/help probes must pass for assembly to emit the current receipts. Hosted toolchain publication additionally binds the actual builder image identity, source, engine hash, compile-feature digest, runtime image identity and saved archive hash. The inactive static CUDA profile preserves its original six-file contract and has no hosted compiler or license receipt qualification. Its runner and build inputs are unchanged. -Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and rereads each exact same-origin repository/tag/asset download URL to compare size and SHA256. It allows at most two same-origin redirects, restricted to attachment paths for the UUID returned by that asset upload. Only then does it remove draft status. Other redirect paths, queries, credentials and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy. +Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and validates the returned UUID before accepting either the exact same-origin repository/tag/asset download URL or one of the existing exact attachment paths for that UUID, then rereads the remote bytes to compare size and SHA256. It allows at most two same-origin redirects, restricted to attachment paths for the UUID returned by that asset upload. Only then does it remove draft status. Other redirect paths, queries, credentials and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy. Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate. The download URL profile was checked against read-only Gitea release `cuda-preview-2495-1` on git.vezha.io: `/para/leleka/releases/download/{tag}/{asset}`. Gitea 1.27.3 [RedirectDownload](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/routers/web/repo/repo.go) finds releases by repository/tag and includes drafts for writers; it serves the associated attachment without requiring a Git tag to exist. Synthetic tests verify download and redirect hashing while the release is still draft and before tag publication, and prove that foreign redirects receive no request or token. Actual fresh CI publication remains unqualified until that gate succeeds. Publication jobs request `contents: read` and the Gitea-specific `releases: write` permission on their built-in job token; the workflow default and nonpublication jobs keep read-only permissions. This follows the [Gitea 1.27 token-permission contract](https://docs.gitea.com/1.27/usage/actions/token-permissions/). Owner/repository maximums can still clamp the effective token; the real publication gate must succeed before qualification. No stored PAT is read or created. + +Gitea 1.27.3 fresh-upload POST and later GET/list metadata can expose different +URLs. [Attachment.DownloadURL](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/models/repo/attachment.go) +uses the instance attachment route when the freshly created attachment has no +custom URL; subsequent [release attribute loading](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/models/repo/release.go) can populate the repository +release route when attachment names are unique. The publisher admits the same narrowly bound UUID attachment +routes at the initial hop as at redirect hops. Origin, port, path, UUID, query, +fragment, credentials, two-redirect bound, byte count and remote SHA checks remain +mandatory. Synthetic POST tests cover each admitted attachment form, corruption, +invalid/mismatched UUIDs, foreign URLs and wrong repositories without forwarding +a token. This source-derived correction is not proof of fresh private CI publication; +that remains an actual workflow gate. diff --git a/scripts/publish-gitea-release.py b/scripts/publish-gitea-release.py index 1715cbd0..fb1abf19 100644 --- a/scripts/publish-gitea-release.py +++ b/scripts/publish-gitea-release.py @@ -272,13 +272,13 @@ def validate_download_url(parts, url, allowed_paths): def verify_uploaded_asset(parts, token, metadata, expected, repository, tag): - # Gitea returns a release route, which can redirect to the same asset UUID. + # Gitea POST may return the UUID attachment route; later reads may return + # the exact release route. Both are bound to the same uploaded asset. # Validate every hop before sending a scoped token; never follow foreign URLs. base_path = parts.path.rstrip('/').removesuffix('/api/v1') repo_path = base_path + '/' + repository release_path = f"{repo_path}/releases/download/{tag}/{metadata['name']}" url = metadata.get('browser_download_url') - validate_download_url(parts, url, {release_path}) attachment = metadata.get('uuid') if not isinstance(attachment, str) or not re.fullmatch( r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', attachment): @@ -286,8 +286,9 @@ def verify_uploaded_asset(parts, token, metadata, expected, repository, tag): attachment_paths = {f'{base_path}/attachments/{attachment}', f'{repo_path}/attachments/{attachment}', f'{repo_path}/releases/attachments/{attachment}'} + initial_paths = {release_path} | attachment_paths for hop in range(3): - asset_url = validate_download_url(parts, url, {release_path} if hop == 0 else attachment_paths) + asset_url = validate_download_url(parts, url, initial_paths if hop == 0 else attachment_paths) conn = connection(parts) try: conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'}) diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py index c7d2cfc3..62d297e9 100644 --- a/scripts/test-gitea-release.py +++ b/scripts/test-gitea-release.py @@ -197,12 +197,18 @@ class FakeGitea(BaseHTTPRequestHandler): tag = self.server.release_payload['tag_name'] release_path = f'/owner/repo/releases/download/{tag}/{name}' self.server.release_paths[release_path] = attachment + initial_path = { + None: release_path, + 'attachment': f'/attachments/{attachment}', + 'repo-attachment': f'/owner/repo/attachments/{attachment}', + 'repo-release-attachment': f'/owner/repo/releases/attachments/{attachment}', + }[self.server.initial_attachment_route] if self.server.wrong_download: - release_path = release_path.replace(*self.server.wrong_download) - download = f'http://127.0.0.1:{self.server.server_port}{release_path}' + initial_path = initial_path.replace(*self.server.wrong_download) + download = f'http://127.0.0.1:{self.server.server_port}{initial_path}' if self.server.foreign_download: download = 'https://foreign.invalid/attachments/id' - return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download, 'uuid': attachment}) + return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download, 'uuid': self.server.uuid_override if self.server.uuid_override is not None else attachment}) self.send_json(404, {'message': 'unexpected route'}) def do_GET(self): @@ -279,6 +285,8 @@ class PublisherTests(unittest.TestCase): self.server.current_draft = True self.server.tag_exists = False self.server.wrong_download = None + self.server.initial_attachment_route = None + self.server.uuid_override = None self.server.redirect_mode = None self.server.foreign_url = 'http://foreign.invalid' self.server.foreign_download = False @@ -648,6 +656,71 @@ class PublisherTests(unittest.TestCase): self.assertTrue(self.server.release_payload['draft']) self.assertIsNone(self.server.finalize_payload) + def test_fresh_post_attachment_routes_verify_remote_bytes_before_finalizing(self): + for mode in ('attachment', 'repo-attachment', 'repo-release-attachment'): + with self.subTest(mode=mode): + self.server.initial_attachment_route = mode + self.server.gets = [] + self.server.get_states = [] + result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(len(result['assets']), 8) + self.assertEqual(len(self.server.gets), 8) + self.assertEqual(self.server.get_states, [(True, False)] * 8) + self.assertTrue(all('/attachments/' in path for path, _auth in self.server.gets)) + self.assertTrue(all(auth == f'token {TOKEN}' for _path, auth in self.server.gets)) + for asset in result['assets']: + self.assertEqual(asset['sha256'], hashlib.sha256( + (self.directory / asset['name']).read_bytes()).hexdigest()) + self.assertEqual(self.server.finalize_payload, {'draft': False}) + + def test_fresh_post_attachment_remote_corruption_leaves_draft(self): + self.server.initial_attachment_route = 'attachment' + self.server.corrupt_download = True + with self.assertRaisesRegex(ValueError, 'checksum mismatch'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(len(self.server.gets), 1) + self.assertTrue(self.server.current_draft) + self.assertIsNone(self.server.finalize_payload) + + def test_fresh_post_attachment_untrusted_routes_receive_no_token(self): + for mode, substitution in ( + ('attachment', ('/attachments/', '/attachments/00000000-0000-0000-0000-000000000000/')), + ('repo-attachment', ('/owner/repo/', '/owner/other/')), + ('repo-release-attachment', ('/owner/repo/', '/other/repo/')), + ('attachment', ('/attachments/', '/attachments/?token=synthetic&uuid=')), + ('attachment', ('/attachments/', '/attachments/#'))): + with self.subTest(mode=mode, substitution=substitution): + self.server.initial_attachment_route = mode + self.server.wrong_download = substitution + self.server.gets = [] + with self.assertRaisesRegex(ValueError, 'same-origin'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(self.server.gets, []) + self.assertIsNone(self.server.finalize_payload) + self.server.wrong_download = None + self.server.foreign_download = True + self.server.gets = [] + with self.assertRaisesRegex(ValueError, 'same-origin'): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(self.server.gets, []) + self.assertIsNone(self.server.finalize_payload) + + def test_fresh_post_requires_valid_matching_uuid_before_download(self): + self.server.initial_attachment_route = 'attachment' + for attachment in ('not-a-uuid', '', 73, '00000000-0000-0000-0000-000000000000'): + with self.subTest(attachment=attachment): + self.server.uuid_override = attachment + self.server.gets = [] + with self.assertRaises(ValueError): + publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION, + 'title', 'notes', self.directory) + self.assertEqual(self.server.gets, []) + self.assertIsNone(self.server.finalize_payload) + def test_initial_download_url_requires_exact_repository_tag_and_asset(self): for substitution in (('/owner/repo/', '/owner/other/'), ('cuda-preview-42-1', 'cuda-preview-43-1'), -- 2.54.0 From 310b7a9aab9e002ca997a7b4b842c43cf66d6f71 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 22:01:40 +0200 Subject: [PATCH 14/14] STRA-101 make embedded payload lifetime test tolerate fd reuse --- control-plane/src/embedded_engine.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/control-plane/src/embedded_engine.rs b/control-plane/src/embedded_engine.rs index 05c0cb30..14c6b91e 100644 --- a/control-plane/src/embedded_engine.rs +++ b/control-plane/src/embedded_engine.rs @@ -118,7 +118,7 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn sealed_payload_is_exact_immutable_and_removed_on_drop() { - use std::io::Write; + use std::{io::Write, os::unix::fs::MetadataExt}; let engine = materialize(b"immutable fixture bytes").unwrap(); let path = engine.executable.clone(); assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes"); @@ -126,8 +126,19 @@ mod tests { assert!(other.write_all(b"x").is_err()); assert!(other.set_len(0).is_err()); assert!(other.set_len(100).is_err()); - drop(other); + // Keep a witness open so this inode cannot be recycled during the check. + // Parallel tests can reuse the original descriptor number after Drop. + let original = other.metadata().unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().ino(), original.ino()); drop(engine); - assert!(!path.exists()); + match std::fs::metadata(&path) { + Ok(current) => assert_ne!( + (current.dev(), current.ino()), + (original.dev(), original.ino()), + "original descriptor still refers to the payload after Drop" + ), + Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound), + } + drop(other); } } -- 2.54.0