diff --git a/.github/workflows/release-portability-proof.yml b/.github/workflows/release-portability-proof.yml new file mode 100644 index 000000000..f51a05b07 --- /dev/null +++ b/.github/workflows/release-portability-proof.yml @@ -0,0 +1,99 @@ +name: Release Portability Proof + +# Docker proof is explicitly dispatched; ordinary PRs run the existing Rust gates. +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-portability-${{ github.ref }} + cancel-in-progress: false + +jobs: + immutable-release-runtime: + name: v0.1.0 runtime matrix + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master + with: + toolchain: 1.95.0 + - name: Build the Rust proof controller + run: cargo build --locked --package xtask + - name: Retain the same-source resolver controller + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: release-portability-controller-${{ github.sha }} + path: target/debug/xtask + if-no-files-found: error + retention-days: 7 + - name: Prove immutable release portability + env: + GH_TOKEN: ${{ github.token }} + run: target/debug/xtask release-portability run --out target/release-portability + - name: Retain runtime proof and failures + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: ub-review-v0.1.0-release-portability + path: target/release-portability + if-no-files-found: error + retention-days: 30 + + strict-release-no-fallback: + name: strict release rejects missing asset + needs: immutable-release-runtime + runs-on: ubuntu-24.04 + timeout-minutes: 10 + container: ubuntu:24.04 + defaults: + run: + shell: bash + steps: + - name: Prepare the resolver container + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends ca-certificates curl git + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 + with: + name: release-portability-controller-${{ github.sha }} + path: ${{ runner.temp }}/portability-controller + - name: Prove the clean resolver baseline + run: | + chmod +x "$RUNNER_TEMP/portability-controller/xtask" + "$RUNNER_TEMP/portability-controller/xtask" release-portability resolver-before --out target/release-portability-resolver + - name: Reject missing release asset without fallback + id: missing_release + continue-on-error: true + uses: ./ + with: + setup-rust: 'false' + install-tools: 'false' + install-mode: release + release-version: v0.1.0 + release-asset: ub-review-missing-x86_64-unknown-linux-gnu.tar.gz + posting: artifact-only + model-mode: off + - name: Validate the resolver result + if: always() && steps.missing_release.outcome != 'skipped' + env: + STEP_OUTCOME: ${{ steps.missing_release.outcome }} + run: > + "$RUNNER_TEMP/portability-controller/xtask" release-portability resolver-after + --out target/release-portability-resolver --step-outcome "$STEP_OUTCOME" + - name: Retain resolver proof and failures + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: ub-review-v0.1.0-resolver-no-fallback + path: target/release-portability-resolver + if-no-files-found: error + retention-days: 30 diff --git a/Cargo.lock b/Cargo.lock index 8af0176d3..9565e8b19 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "android_system_properties" version = "0.1.5" @@ -183,6 +189,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550" +dependencies = [ + "cfg-if", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -225,12 +240,33 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -401,6 +437,16 @@ version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -556,6 +602,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -579,6 +631,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -956,16 +1019,38 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "xtask" version = "0.1.0" dependencies = [ "anyhow", "chrono", + "flate2", + "serde", "serde_json", + "sha2", + "tar", + "tempfile", "toml", + "wait-timeout", ] +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + [[package]] name = "zmij" version = "1.0.21" diff --git a/docs/RELEASE_PORTABILITY_PLAN.md b/docs/RELEASE_PORTABILITY_PLAN.md new file mode 100644 index 000000000..6efee3b84 --- /dev/null +++ b/docs/RELEASE_PORTABILITY_PLAN.md @@ -0,0 +1,90 @@ +# PR #1265: immutable v0.1.0 portability proof + +Status: Rust replacement implemented. Exact-head validation, dispatched runtime +and resolver receipts, and remaining gate/review blockers are recorded in +PR #1265; the prior runs below retain their historical source identity. + +## Authority and retained evidence + +- [Issue #1071](https://github.com/EffortlessMetrics/ub-review/issues/1071) + defines the clean-container portability obligation. +- [The September 5 repair direction](https://github.com/EffortlessMetrics/ub-review/pull/1265#issuecomment-5549425901) + requires Rust-owned validation, independent release identity, explicit CI + authorization, discriminating tests, and a fresh exact-head run. +- `policy/ci-budget.toml`, `policy/ci-risk-packs.toml`, and + `policy/ci-lanes.toml` govern cost and proof routing. +- Run `33166458366` and its runtime/resolver artifacts are historical evidence + from the superseded shell harness at `b1198e2`. They establish the observed + v0.1.0 Ubuntu 24.04/glibc 2.39 success and Ubuntu 22.04/glibc 2.35 loader + rejection. They do not validate the replacement harness. +- The v0.1.0 initializer's empty provider/impact defaults are immutable + historical behavior, fixed separately on main by #845. Preserve the exact + two expected policy failures and the separate explicit-config passing packet. + +## Bounded design + +Keep `xtask/src/main.rs` limited to the new command's dispatch/help. Put the +implementation in `xtask/src/release_portability/` with separate metadata, +archive, runtime, packet, and receipt responsibilities. Remove the large shell +harness; do not replace it with embedded script authority. + +The host command resolves live GitHub release/tag/asset metadata before Docker +execution. Follow annotated tags to their commit with a bounded, cycle-checked +chain. Compare the observed tag commit, exact asset names, IDs, sizes, HTTPS +URLs, and API digests against the immutable v0.1.0 policy. Independently download +and verify both the archive and checksum bytes. Retain resolved metadata and +observed comparisons, rather than copying constants into claimed observations. + +Use typed serde receipts, bounded decompression/archive inspection, and a +single validation path for both real and negative-control inputs. Reject +missing/duplicate assets, moved tags, digest/size drift, traversal, links, +duplicate/wrong-root archive members, and wrong product/version identity. + +Run two explicitly named disposable Ubuntu containers. Only the verified +release executable and a minimal synthetic review fixture enter the runtime +containers; no host Rust tooling, repository source, credentials, or source +fallback enters either container. Invoke explicit OS commands from Rust and +perform assertions, JSON/NDJSON parsing, and receipt construction in Rust on the +host. Retain OS/architecture/libc/kernel observations, version/help, initializer, +doctor, both model-off packets, checksums, inventory, and all negative controls. + +The workflow is `workflow_dispatch` only. Existing independent-baseline checks +cover ordinary PR unit proof. The dispatched jobs record their event, actor, +run ID, workflow SHA, and checked-out source SHA. A separate clean resolver +job exercises the local Action's strict missing-asset failure and invokes the +already-built xtask executable to validate and write its receipt; it installs +neither Cargo nor rustc. Workflow YAML carries orchestration, not receipt JSON. + +## Acceptance and proof + +- Typed accept/reject tests distinguish metadata parsing, annotated tag + dereference/cycles/movement, exact asset selection, duplicates/omissions, + checksum/size drift, hostile archives, wrong version, missing or conflicting + matrix rows, and deterministic receipts. +- Ubuntu 24.04/x86_64/glibc 2.39 must run the exact release and produce a valid + explicit-config model-off packet; Ubuntu 22.04/glibc 2.35 must reject it at + the loader specifically on `GLIBC_2.39`. +- Both runtime environments and the resolver control must prove absence of + Cargo, rustc, and source fallback. The two runtime containers also contain no + UB Review source checkout. +- Run `cargo fmt --all -- --check`, focused xtask tests, locked workspace + all-target/all-feature check, full locked workspace tests, strict locked + Clippy, `cargo run --locked -p xtask -- policy-check`, actionlint, and + `git diff --check`. Coordinate the shared Cargo proof slot before building. +- Keep #1265 open until a newly authorized exact-head portability dispatch and + normal gate are green. Respond to the three review threads with concrete + repair evidence, and resolve them only after the exact-head checks. + +## Boundaries, rollback, and cleanup + +No release, tag, asset, resolver default, branch protection, or public support +policy changes. No support extrapolation to other distributions/architectures, +and no current-product claim from immutable v0.1.0 behavior. Live metadata plus +the downloaded digest identifies the tested existing asset; this is not a new +signature, provenance, or release authorization claim. + +The output directory must be new so stale receipts cannot satisfy a new run. +Retain failed-run diagnostics without a successful matrix. Remove only +containers and scratch artifacts created by this command. Keep the workflow +manual if reverted; historical receipts remain historical. Handle unrelated +release/install documentation drift in a separate builder-ready follow-up. diff --git a/policy/ci-lanes.toml b/policy/ci-lanes.toml index ecb1fccc0..f3d217715 100644 --- a/policy/ci-lanes.toml +++ b/policy/ci-lanes.toml @@ -42,3 +42,10 @@ when = "release/label" target_required = false implemented = false reason = "Release archive build + checksum verification without publishing; referenced by the release risk pack (#603)." + +[[lane]] +id = "release-portability-proof" +when = "workflow_dispatch" +target_required = false +implemented = true +reason = "Explicitly dispatched immutable v0.1.0 execution and strict-resolver controls; two disposable runtime containers, no publishing or product source build, and authorization-bound receipts. Ordinary PRs use the existing Rust checks." diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 35ec61130..20dbe6bf9 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -7,8 +7,16 @@ publish = false [dependencies] anyhow = "1.0" chrono = { version = "0.4", default-features = false } +flate2 = "1.1" +serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +sha2 = "0.10" +tar = "0.4" toml = "0.9" +wait-timeout = "0.2" + +[dev-dependencies] +tempfile = "3.12" [lints.rust] unsafe_code = "forbid" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a94be0403..78e21b95c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -10,6 +10,8 @@ use serde_json::{Value as JsonValue, json}; use toml::Value; use toml::map::Map; +mod release_portability; + fn main() { if let Err(error) = run() { eprintln!("error: {error:#}"); @@ -32,6 +34,7 @@ fn run() -> Result<()> { let root = env::current_dir().context("resolve current directory")?; match command.as_str() { + "release-portability" => release_portability::run(&root, args)?, "policy-check" => { reject_extra_args(args)?; let report = check_policy(&root)?; @@ -78,7 +81,7 @@ fn run() -> Result<()> { } other => { bail!( - "unknown xtask command `{other}`; expected policy-check, policy-inventory, audit, precommit, ripr, smoke-base, calibration-report, or help" + "unknown xtask command `{other}`; expected policy-check, policy-inventory, audit, precommit, ripr, smoke-base, calibration-report, release-portability, or help" ) } } @@ -105,6 +108,8 @@ cargo xtask commands cargo xtask ripr reproduce hosted ripr ready-mode feedback locally cargo xtask smoke-base select a non-empty local smoke diff base cargo xtask calibration-report aggregate review/calibration.json files + cargo xtask release-portability run --out prove immutable v0.1.0 in an explicit dispatch + cargo xtask release-portability run --local-explicit --out opt into local Docker proof precommit options diff --git a/xtask/src/release_portability/archive.rs b/xtask/src/release_portability/archive.rs new file mode 100644 index 000000000..8c224534b --- /dev/null +++ b/xtask/src/release_portability/archive.rs @@ -0,0 +1,240 @@ +use std::io::{Cursor, Read}; + +use anyhow::{Context, Result, ensure}; +use flate2::read::GzDecoder; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::metadata::{ARCHIVE, Asset}; + +const MAX_EXPANDED_BYTES: u64 = 32 * 1024 * 1024; + +pub(super) fn sha256(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +pub(super) fn verify_download(asset: &Asset, bytes: &[u8]) -> Result<()> { + ensure!( + u64::try_from(bytes.len())? == asset.size, + "download size differs from resolved asset {}", + asset.name + ); + ensure!( + format!("sha256:{}", sha256(bytes)) == asset.digest, + "download digest differs from resolved asset {}", + asset.name + ); + Ok(()) +} + +pub(super) fn verify_checksum(bytes: &[u8], archive: &Asset) -> Result<()> { + let text = std::str::from_utf8(bytes).context("published checksum is not UTF-8")?; + let expected = archive + .digest + .strip_prefix("sha256:") + .context("archive digest algorithm")?; + let fields = text.split_whitespace().collect::>(); + // The immutable published checksum names its build-time dist/ path. + // Match that exact label; never interpret it as an extraction destination. + let published_name = format!("dist/{ARCHIVE}"); + ensure!( + fields.as_slice() == [expected, published_name.as_str()], + "published checksum does not identify the resolved archive" + ); + Ok(()) +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct ArchiveLayout { + pub schema: String, + pub member_name: String, + pub member_size: u64, + pub executable_sha256: String, +} + +pub(super) fn inspect_archive(bytes: &[u8]) -> Result<(ArchiveLayout, Vec)> { + let mut expanded = Vec::new(); + GzDecoder::new(bytes) + .take(MAX_EXPANDED_BYTES + 1) + .read_to_end(&mut expanded) + .context("decompress release archive")?; + ensure!( + u64::try_from(expanded.len())? <= MAX_EXPANDED_BYTES, + "expanded archive exceeds byte budget" + ); + let mut archive = tar::Archive::new(Cursor::new(expanded)); + let mut entries = archive.entries().context("read archive members")?; + let mut entry = entries.next().context("archive has no executable")??; + let raw_name = entry.path_bytes(); + ensure!( + raw_name.as_ref() == b"ub-review" || raw_name.as_ref() == b"./ub-review", + "archive executable is not at the exact root path" + ); + ensure!( + entry.header().entry_type().is_file(), + "archive executable is a link or non-regular member" + ); + ensure!( + entry.link_name()?.is_none(), + "archive executable has a link target" + ); + let name = String::from_utf8(raw_name.into_owned()).context("archive path is not UTF-8")?; + let size = entry.size(); + ensure!( + size > 0 && size <= MAX_EXPANDED_BYTES, + "archive executable size is invalid" + ); + let mut executable = Vec::new(); + entry + .read_to_end(&mut executable) + .context("read archived executable")?; + ensure!( + u64::try_from(executable.len())? == size, + "archive executable is truncated" + ); + ensure!( + entries.next().is_none(), + "archive contains duplicate or additional members" + ); + Ok(( + ArchiveLayout { + schema: "ub-review.release_archive_layout.v2".to_owned(), + member_name: name, + member_size: size, + executable_sha256: sha256(&executable), + }, + executable, + )) +} + +pub(super) fn verify_version(status: bool, stdout: &[u8], stderr: &[u8]) -> Result<()> { + ensure!( + status && stderr.is_empty() && std::str::from_utf8(stdout)?.trim() == "ub-review 0.1.0", + "release product/version identity mismatch" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::{Compression, write::GzEncoder}; + + fn archive(names: &[&str], kind: tar::EntryType) -> Result> { + let mut tar = tar::Builder::new(Vec::new()); + for name in names { + let mut header = tar::Header::new_gnu(); + // Raw header mutation allows hostile traversal fixtures which the + // producer-side set_path API correctly refuses to manufacture. + let path = header + .as_mut_bytes() + .get_mut(..100) + .context("tar path field")?; + path.fill(0); + path.get_mut(..name.len()) + .context("fixture path length")? + .copy_from_slice(name.as_bytes()); + header.set_entry_type(kind); + header.set_size(if kind.is_file() { 3 } else { 0 }); + header.set_mode(0o755); + if kind.is_symlink() || kind.is_hard_link() { + header.set_link_name("outside")?; + } + header.set_cksum(); + let content: &[u8] = if kind.is_file() { b"bin" } else { b"" }; + tar.append(&header, content)?; + } + let bytes = tar.into_inner()?; + let mut gzip = GzEncoder::new(Vec::new(), Compression::default()); + std::io::Write::write_all(&mut gzip, &bytes)?; + Ok(gzip.finish()?) + } + + #[test] + fn layout_rejects_traversal_links_duplicates_and_wrong_root() -> Result<()> { + let valid = archive(&["ub-review"], tar::EntryType::Regular)?; + let (layout, executable) = inspect_archive(&valid)?; + ensure!(layout.member_size == 3 && executable == b"bin"); + let (relative, relative_bytes) = + inspect_archive(&archive(&["./ub-review"], tar::EntryType::Regular)?)?; + ensure!(relative.member_name == "./ub-review" && relative_bytes == executable); + for names in [ + vec!["../ub-review"], + vec!["/ub-review"], + vec!["nested/ub-review"], + vec!["ub-review", "ub-review"], + vec![], + ] { + ensure!(inspect_archive(&archive(&names, tar::EntryType::Regular)?).is_err()); + } + for kind in [ + tar::EntryType::Symlink, + tar::EntryType::Link, + tar::EntryType::Directory, + ] { + ensure!(inspect_archive(&archive(&["ub-review"], kind)?).is_err()); + } + Ok(()) + } + + #[test] + fn archive_rejects_invalid_gzip_and_expansion_over_budget() -> Result<()> { + ensure!(inspect_archive(b"not gzip").is_err()); + let valid = archive(&["ub-review"], tar::EntryType::Regular)?; + ensure!( + inspect_archive(valid.get(..valid.len() / 2).context("truncated fixture")?).is_err() + ); + let mut gzip = GzEncoder::new(Vec::new(), Compression::fast()); + std::io::copy( + &mut std::io::repeat(0).take(MAX_EXPANDED_BYTES + 1), + &mut gzip, + )?; + let oversized = gzip.finish()?; + let error = inspect_archive(&oversized) + .err() + .context("accepted oversized expansion")?; + ensure!( + error + .to_string() + .contains("expanded archive exceeds byte budget") + ); + Ok(()) + } + + #[test] + fn download_and_identity_checks_discriminate_tampered_bytes() -> Result<()> { + let mut asset = Asset { + id: 1, + name: ARCHIVE.to_owned(), + size: 3, + digest: format!("sha256:{}", sha256(b"abc")), + browser_download_url: String::new(), + }; + verify_download(&asset, b"abc")?; + ensure!(verify_download(&asset, b"abd").is_err()); + asset.size = 4; + ensure!(verify_download(&asset, b"abc").is_err()); + let checksum = format!("{} dist/{ARCHIVE}\n", sha256(b"abc")); + verify_checksum(checksum.as_bytes(), &asset)?; + ensure!(verify_checksum(checksum.replace("dist/", "").as_bytes(), &asset).is_err()); + ensure!(verify_checksum(checksum.replace("dist/", "../").as_bytes(), &asset).is_err()); + ensure!(verify_checksum(checksum.replace(ARCHIVE, "other").as_bytes(), &asset).is_err()); + verify_version(true, b"ub-review 0.1.0\n", b"")?; + ensure!(verify_version(true, b"true (GNU coreutils) 9.4\n", b"").is_err()); + ensure!(verify_version(false, b"ub-review 0.1.0\n", b"").is_err()); + ensure!(verify_version(true, b"ub-review 0.1.0\n", b"unexpected diagnostic").is_err()); + ensure!(verify_version(true, b"ub-review 0.1.1\n", b"").is_err()); + ensure!(verify_checksum(b"\xff", &asset).is_err()); + ensure!(verify_checksum(format!("{checksum}extra").as_bytes(), &asset).is_err()); + ensure!( + verify_checksum( + checksum + .replace(&sha256(b"abc"), &sha256(b"abd")) + .as_bytes(), + &asset + ) + .is_err() + ); + Ok(()) + } +} diff --git a/xtask/src/release_portability/metadata.rs b/xtask/src/release_portability/metadata.rs new file mode 100644 index 000000000..10d1c029c --- /dev/null +++ b/xtask/src/release_portability/metadata.rs @@ -0,0 +1,320 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; + +pub(super) const REPOSITORY: &str = "EffortlessMetrics/ub-review"; +pub(super) const TAG: &str = "v0.1.0"; +pub(super) const COMMIT: &str = "743ae2b5d9b9532852f702a095cf363380c932a2"; +pub(super) const ARCHIVE: &str = "ub-review-x86_64-unknown-linux-gnu.tar.gz"; +pub(super) const ARCHIVE_SHA256: &str = + "87a660273e8d6f76d78b41d5bf2da1ed2928cb7987fbe114f9e1035d32b03465"; +const CHECKSUM_SHA256: &str = "1d3506efb235aeeeb86f02dbe45081808d6f2995a2c44c7535c0f938beb23a97"; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct Asset { + pub id: u64, + pub name: String, + pub size: u64, + pub digest: String, + pub browser_download_url: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(super) struct Release { + pub id: u64, + pub tag_name: String, + pub draft: bool, + pub prerelease: bool, + pub assets: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub(super) enum ObjectKind { + Tag, + Commit, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct GitObject { + pub sha: String, + #[serde(rename = "type")] + pub kind: ObjectKind, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(super) struct TagRef { + #[serde(rename = "ref")] + pub reference: String, + pub object: GitObject, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(super) struct AnnotatedTag { + pub sha: String, + pub object: GitObject, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct ReleaseIdentity { + pub release_id: u64, + pub tag: String, + pub tag_commit: String, + pub archive: Asset, + pub checksum: Asset, + pub tag_chain: Vec, +} + +pub(super) fn require_oid(oid: &str) -> Result<()> { + ensure!( + oid.len() == 40 + && oid + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), + "Git object identity must be a canonical forty-character SHA" + ); + Ok(()) +} + +pub(super) fn resolve_tag( + reference: &TagRef, + annotations: &BTreeMap, +) -> Result> { + ensure!( + reference.reference == format!("refs/tags/{TAG}"), + "wrong tag reference" + ); + let mut current = reference.object.clone(); + let mut seen = BTreeSet::new(); + let mut chain = Vec::new(); + loop { + require_oid(¤t.sha)?; + ensure!( + chain.len() < 8 && seen.insert(current.sha.clone()), + "tag chain is cyclic or excessive" + ); + chain.push(current.clone()); + if current.kind == ObjectKind::Commit { + ensure!( + current.sha == COMMIT, + "published tag moved from its pinned commit" + ); + return Ok(chain); + } + let annotation = annotations + .get(¤t.sha) + .context("annotated tag object is missing")?; + ensure!( + annotation.sha == current.sha, + "annotated tag identity mismatch" + ); + current = annotation.object.clone(); + } +} + +fn exact_asset(release: &Release, name: &str, id: u64, size: u64, digest: &str) -> Result { + let mut matches = release.assets.iter().filter(|asset| asset.name == name); + let asset = matches + .next() + .with_context(|| format!("missing release asset {name}"))?; + ensure!(matches.next().is_none(), "duplicate release asset {name}"); + ensure!(asset.id == id, "asset ID mismatch for {name}"); + ensure!(asset.size == size, "asset size mismatch for {name}"); + ensure!( + asset.digest == format!("sha256:{digest}"), + "asset published digest mismatch for {name}" + ); + ensure!( + asset.browser_download_url + == format!("https://github.com/{REPOSITORY}/releases/download/{TAG}/{name}"), + "asset download URL mismatch for {name}" + ); + Ok(asset.clone()) +} + +pub(super) fn validate_release( + release: &Release, + reference: &TagRef, + annotations: &BTreeMap, +) -> Result { + ensure!(release.id == 356064141, "release ID mismatch"); + ensure!( + release.tag_name == TAG && !release.draft && !release.prerelease, + "unexpected release tag/state" + ); + let chain = resolve_tag(reference, annotations)?; + let commit = chain + .last() + .context("empty resolved tag chain")? + .sha + .clone(); + Ok(ReleaseIdentity { + release_id: release.id, + tag: release.tag_name.clone(), + tag_commit: commit, + archive: exact_asset(release, ARCHIVE, 481332264, 2_750_491, ARCHIVE_SHA256)?, + checksum: exact_asset( + release, + &format!("{ARCHIVE}.sha256"), + 481332265, + 113, + CHECKSUM_SHA256, + )?, + tag_chain: chain, + }) +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + + pub(in crate::release_portability) fn release() -> Release { + Release { + id: 356064141, + tag_name: TAG.to_owned(), + draft: false, + prerelease: false, + assets: [ + (ARCHIVE.to_owned(), 481332264, 2_750_491, ARCHIVE_SHA256), + (format!("{ARCHIVE}.sha256"), 481332265, 113, CHECKSUM_SHA256), + ] + .into_iter() + .map(|(name, id, size, digest)| Asset { + browser_download_url: format!( + "https://github.com/{REPOSITORY}/releases/download/{TAG}/{name}" + ), + name, + id, + size, + digest: format!("sha256:{digest}"), + }) + .collect(), + } + } + + pub(in crate::release_portability) fn reference() -> TagRef { + TagRef { + reference: format!("refs/tags/{TAG}"), + object: GitObject { + sha: COMMIT.to_owned(), + kind: ObjectKind::Commit, + }, + } + } + + #[test] + fn typed_metadata_selects_exact_observed_assets() -> Result<()> { + let metadata: Release = serde_json::from_slice(&serde_json::to_vec(&release())?)?; + let identity = validate_release(&metadata, &reference(), &BTreeMap::new())?; + ensure!(identity.archive.id == 481332264 && identity.checksum.size == 113); + ensure!(serde_json::from_str::(r#"{"id":"wrong"}"#).is_err()); + for mutation in 0..4 { + let mut changed = release(); + match mutation { + 0 => changed.id += 1, + 1 => changed.tag_name = "v0.1.1".to_owned(), + 2 => changed.draft = true, + _ => changed.prerelease = true, + } + ensure!( + validate_release(&changed, &reference(), &BTreeMap::new()).is_err(), + "accepted metadata mutation {mutation}" + ); + } + for asset_index in 0..2 { + for mutation in 0..7 { + let mut changed = release(); + let asset = changed + .assets + .get_mut(asset_index) + .context("fixture asset")?; + match mutation { + 0 => asset.id += 1, + 1 => asset.size += 1, + 2 => asset.digest = format!("sha256:{}", "0".repeat(64)), + 3 => asset.browser_download_url = "https://example.invalid/asset".to_owned(), + 4 => asset.name = "wrong.tar.gz".to_owned(), + 5 => { + let duplicate = asset.clone(); + changed.assets.push(duplicate); + } + _ => { + changed.assets.remove(asset_index); + } + } + ensure!( + validate_release(&changed, &reference(), &BTreeMap::new()).is_err(), + "accepted asset {asset_index} mutation {mutation}" + ); + } + } + Ok(()) + } + + #[test] + fn annotated_tag_dereference_rejects_movement_missing_and_cycles() -> Result<()> { + let sha = "a".repeat(40); + let mut reference = reference(); + reference.object = GitObject { + sha: sha.clone(), + kind: ObjectKind::Tag, + }; + let mut annotations = BTreeMap::from([( + sha.clone(), + AnnotatedTag { + sha: sha.clone(), + object: GitObject { + sha: COMMIT.to_owned(), + kind: ObjectKind::Commit, + }, + }, + )]); + let chain = resolve_tag(&reference, &annotations)?; + ensure!(chain.len() == 2 && chain.last().context("resolved commit")?.sha == COMMIT); + ensure!(resolve_tag(&reference, &BTreeMap::new()).is_err()); + annotations.get_mut(&sha).context("annotation")?.object.sha = "b".repeat(40); + ensure!(resolve_tag(&reference, &annotations).is_err()); + annotations.get_mut(&sha).context("annotation")?.object = reference.object.clone(); + ensure!(resolve_tag(&reference, &annotations).is_err()); + annotations.get_mut(&sha).context("annotation")?.object = GitObject { + sha: COMMIT.to_owned(), + kind: ObjectKind::Commit, + }; + annotations.get_mut(&sha).context("annotation")?.sha = "b".repeat(40); + ensure!(resolve_tag(&reference, &annotations).is_err()); + Ok(()) + } + + #[test] + fn tag_resolution_rejects_noncanonical_identity_and_excessive_depth() -> Result<()> { + for oid in ["", "abcdef", &"A".repeat(40), &"g".repeat(40)] { + ensure!(require_oid(oid).is_err(), "accepted malformed Git identity"); + } + let mut wrong_reference = reference(); + wrong_reference.reference = "refs/tags/v0.1.1".to_owned(); + ensure!(resolve_tag(&wrong_reference, &BTreeMap::new()).is_err()); + let mut current = reference(); + let mut annotations = BTreeMap::new(); + for depth in 1..=8 { + let sha = format!("{depth:040x}"); + annotations.insert( + sha.clone(), + AnnotatedTag { + sha: sha.clone(), + object: current.object.clone(), + }, + ); + current.object = GitObject { + sha, + kind: ObjectKind::Tag, + }; + if depth < 8 { + ensure!(resolve_tag(¤t, &annotations)?.len() == depth + 1); + } else { + ensure!(resolve_tag(¤t, &annotations).is_err()); + } + } + Ok(()) + } +} diff --git a/xtask/src/release_portability/mod.rs b/xtask/src/release_portability/mod.rs new file mode 100644 index 000000000..64b3038aa --- /dev/null +++ b/xtask/src/release_portability/mod.rs @@ -0,0 +1,358 @@ +//! Immutable v0.1.0 portability proof; never publishes or builds the product. + +mod archive; +mod metadata; +mod packet; +mod process; +mod receipts; +mod resolver; +mod runtime; + +use std::collections::BTreeMap; +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result, bail, ensure}; +use serde::de::DeserializeOwned; + +use metadata::{AnnotatedTag, ObjectKind, Release, TagRef}; +use process::{Runner, strings}; +use receipts::{Authorization, write_json}; + +struct Options { + mode: String, + out: PathBuf, + local: bool, + step_outcome: Option, +} + +impl Options { + fn parse(mut args: impl Iterator) -> Result { + let mode = args + .next() + .context("release-portability requires run, resolver-before, or resolver-after")?; + ensure!( + matches!(mode.as_str(), "run" | "resolver-before" | "resolver-after"), + "unknown release-portability mode" + ); + let mut out = PathBuf::from("target/release-portability"); + let mut local = false; + let mut step_outcome = None; + while let Some(arg) = args.next() { + match arg.as_str() { + "--out" => out = args.next().context("--out requires a path")?.into(), + "--local-explicit" => local = true, + "--step-outcome" => { + step_outcome = Some( + args.next() + .context("--step-outcome requires the Action outcome")?, + ) + } + other => bail!("unexpected portability option {other}"), + } + } + ensure!(!out.as_os_str().is_empty(), "output path is empty"); + ensure!( + mode == "run" || !local, + "resolver control requires a workflow dispatch" + ); + ensure!( + (mode == "resolver-after") == step_outcome.is_some(), + "only resolver-after requires --step-outcome" + ); + Ok(Self { + mode, + out, + local, + step_outcome, + }) + } +} + +fn source_git_command(root: &Path, args: &[&str], workspace: Option<&Path>) -> Result { + let mut command = Command::new("git"); + if let Some(workspace) = workspace { + let root = root.canonicalize().context("resolve proof checkout")?; + ensure!( + root == workspace.canonicalize()?, + "proof checkout is not the dispatched workspace" + ); + // Container jobs bind-mount the runner-owned checkout. Scope Git's + // ownership acknowledgement to this exact dispatched workspace and + // this read-only process; no global config or wildcard is installed. + command + .arg("-c") + .arg(format!("safe.directory={}", root.display())); + } + command.args(args).current_dir(root); + Ok(command) +} + +fn git_text(root: &Path, args: &[&str]) -> Result { + let workspace = if env::var("GITHUB_ACTIONS").ok().as_deref() == Some("true") { + Some(PathBuf::from( + env::var_os("GITHUB_WORKSPACE").context("workflow workspace identity")?, + )) + } else { + None + }; + let output = source_git_command(root, args, workspace.as_deref())? + .output() + .context("inspect proof source")?; + ensure!( + output.status.success(), + "source Git inspection failed ({}): {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr) + .chars() + .take(512) + .collect::() + ); + Ok(String::from_utf8(output.stdout)?.trim().to_owned()) +} + +fn execution(root: &Path, local: bool) -> Result { + let source = git_text(root, &["rev-parse", "HEAD"])?; + ensure!( + git_text(root, &["status", "--porcelain"])?.is_empty(), + "portability proof requires a clean exact source checkout" + ); + let execution = if local { + ensure!( + env::var("GITHUB_ACTIONS").ok().as_deref() != Some("true"), + "workflow proof cannot substitute local execution" + ); + Authorization { + event: "local_explicit".to_owned(), + actor: env::var("USER") + .or_else(|_| env::var("USERNAME")) + .context("local proof actor")?, + run_id: format!("local-{}", std::process::id()), + workflow_sha: source.clone(), + source_sha: source, + } + } else { + ensure!( + env::var("GITHUB_EVENT_NAME")?.as_str() == "workflow_dispatch", + "expensive portability proof requires workflow_dispatch" + ); + ensure!( + env::var("GITHUB_REPOSITORY")? == metadata::REPOSITORY, + "wrong portability workflow repository" + ); + let declared_source = env::var("GITHUB_SHA")?; + ensure!( + source == declared_source, + "checked-out source differs from dispatched commit" + ); + Authorization { + event: "workflow_dispatch".to_owned(), + actor: env::var("GITHUB_ACTOR")?, + run_id: env::var("GITHUB_RUN_ID")?, + workflow_sha: env::var("GITHUB_WORKFLOW_SHA") + .context("dispatched workflow source identity")?, + source_sha: source, + } + }; + execution.validate()?; + Ok(execution) +} + +fn api(runner: &mut Runner, endpoint: &str) -> Result { + let output = runner.checked("gh", &strings(&["api", "--method", "GET", endpoint]))?; + serde_json::from_slice(&output.stdout) + .with_context(|| format!("parse public GitHub metadata for {endpoint}")) +} + +fn resolve_release(runner: &mut Runner, out: &Path) -> Result { + let repository = metadata::REPOSITORY; + let release: Release = api( + runner, + &format!("repos/{repository}/releases/tags/{}", metadata::TAG), + )?; + let reference: TagRef = api( + runner, + &format!("repos/{repository}/git/ref/tags/{}", metadata::TAG), + )?; + write_json(&out.join("github-release.json"), &release)?; + write_json(&out.join("github-tag-reference.json"), &reference)?; + let mut annotations = BTreeMap::::new(); + let mut object = reference.object.clone(); + while object.kind == ObjectKind::Tag { + metadata::require_oid(&object.sha)?; + ensure!( + annotations.len() < 8 && !annotations.contains_key(&object.sha), + "tag metadata chain is cyclic or excessive" + ); + let annotation: AnnotatedTag = api( + runner, + &format!("repos/{repository}/git/tags/{}", object.sha), + )?; + object = annotation.object.clone(); + let prior = annotations.insert(annotation.sha.clone(), annotation); + ensure!(prior.is_none(), "duplicate observed tag object"); + } + write_json(&out.join("github-tag-annotations.json"), &annotations)?; + let identity = metadata::validate_release(&release, &reference, &annotations)?; + write_json(&out.join("resolved-release.json"), &identity)?; + Ok(identity) +} + +fn download(runner: &mut Runner, out: &Path, asset: &metadata::Asset) -> Result> { + let path = out.join(&asset.name); + runner.checked( + "curl", + &strings(&[ + "--fail", + "--location", + "--silent", + "--show-error", + "--proto", + "=https", + "--proto-redir", + "=https", + "--max-time", + "120", + "--max-filesize", + &asset.size.to_string(), + "--output", + path.to_str().context("download output path")?, + &asset.browser_download_url, + ]), + )?; + let metadata = fs::metadata(&path)?; + ensure!( + metadata.is_file() && metadata.len() == asset.size, + "downloaded asset size mismatch" + ); + let bytes = fs::read(path)?; + archive::verify_download(asset, &bytes)?; + Ok(bytes) +} + +fn prove(out: &Path, execution: &Authorization) -> Result<()> { + let mut runner = Runner::new(out)?; + write_json(&out.join("authorization.json"), execution)?; + let release = resolve_release(&mut runner, out)?; + let archive = download(&mut runner, out, &release.archive)?; + let checksum = download(&mut runner, out, &release.checksum)?; + archive::verify_checksum(&checksum, &release.archive)?; + let (layout, executable) = archive::inspect_archive(&archive)?; + write_json(&out.join("archive-layout.json"), &layout)?; + let executable_path = out.join("ub-review"); + fs::write(&executable_path, executable)?; + let mut rows = Vec::new(); + for (name, image) in [ + ("ubuntu-24.04", "ubuntu:24.04"), + ("ubuntu-22.04", "ubuntu:22.04"), + ] { + rows.push(runtime::run_row( + &mut runner, + &out.join(name), + image, + runtime::VerifiedRelease { + release: &release, + layout: &layout, + archive_bytes: &archive, + executable: &executable_path, + }, + execution, + )?); + } + let matrix = receipts::reconcile(rows, &release, execution)?; + write_json(&out.join("matrix.json"), &matrix)?; + fs::write( + out.join("decision.md"), + "# Immutable v0.1.0 portability execution\n\nThe exact asset in resolved-release.json ran on Ubuntu 24.04 x86_64/glibc 2.39. Ubuntu 22.04 x86_64/glibc 2.35 rejected it at the GLIBC_2.39 loader boundary. Other distributions and architectures remain unproven. The historical initializer policy defect remains separate from the explicit-config passing model-off packet. See matrix.json and command logs for this run's source and execution.\n", + )?; + Ok(()) +} + +pub(crate) fn run(root: &Path, args: impl Iterator) -> Result<()> { + let options = Options::parse(args)?; + let execution = execution(root, options.local)?; + let out = if options.out.is_absolute() { + options.out + } else { + root.join(options.out) + }; + if options.mode == "resolver-after" { + ensure!( + out.is_dir(), + "resolver baseline output directory is missing" + ); + } else { + ensure!( + !out.exists(), + "proof output must be new; preserve or remove the prior lane output explicitly" + ); + if let Some(parent) = out.parent() { + fs::create_dir_all(parent)?; + } + fs::create_dir(&out)?; + } + match options.mode.as_str() { + "run" => prove(&out, &execution), + "resolver-before" => resolver::before(&out, execution), + "resolver-after" => resolver::after( + &out, + execution, + options + .step_outcome + .as_deref() + .context("resolver outcome")?, + ), + _ => bail!("unsupported portability mode"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn source_git_override_only_names_the_dispatched_workspace() -> Result<()> { + let workspace = tempfile::tempdir()?; + let other = tempfile::tempdir()?; + let args = ["rev-parse", "HEAD"]; + let local = source_git_command(workspace.path(), &args, None)?; + ensure!(local.get_args().collect::>() == ["rev-parse", "HEAD"]); + ensure!(source_git_command(workspace.path(), &args, Some(other.path())).is_err()); + let dispatched = source_git_command(workspace.path(), &args, Some(workspace.path()))?; + let expected = vec![ + "-c".to_owned(), + format!( + "safe.directory={}", + workspace.path().canonicalize()?.display() + ), + "rev-parse".to_owned(), + "HEAD".to_owned(), + ]; + ensure!( + dispatched + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect::>() + == expected + ); + Ok(()) + } + + #[test] + fn portability_options_require_explicit_resolver_outcome() -> Result<()> { + ensure!(Options::parse(strings(&["resolver-after"]).into_iter()).is_err()); + ensure!( + Options::parse(strings(&["resolver-before", "--local-explicit"]).into_iter()).is_err() + ); + ensure!( + Options::parse(strings(&["run", "--step-outcome", "failure"]).into_iter()).is_err() + ); + let parsed = Options::parse( + strings(&["run", "--out", "target/new-proof", "--local-explicit"]).into_iter(), + )?; + ensure!(parsed.local && parsed.out == Path::new("target/new-proof")); + Ok(()) + } +} diff --git a/xtask/src/release_portability/packet.rs b/xtask/src/release_portability/packet.rs new file mode 100644 index 000000000..3dc307940 --- /dev/null +++ b/xtask/src/release_portability/packet.rs @@ -0,0 +1,222 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::archive::sha256; + +#[derive(Debug, Deserialize)] +struct Reason { + kind: String, + id: String, +} + +#[derive(Debug, Deserialize)] +struct Gate { + schema: String, + conclusion: String, + reasons: Vec, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Terminal { + schema: String, + status: String, + #[serde(flatten)] + other: BTreeMap, +} + +#[derive(Deserialize)] +struct Review { + terminal_state: Terminal, +} + +#[derive(Debug, Serialize)] +pub(super) struct Artifact { + path: String, + size: u64, + sha256: String, +} + +#[derive(Debug, Serialize)] +pub(super) struct Inventory { + schema: &'static str, + artifact_count: usize, + artifacts: Vec, + gate_conclusion: String, + terminal_status: String, + all_json_parsed: bool, + all_ndjson_parsed: bool, +} + +fn read(path: &Path) -> Result> { + let metadata = + fs::symlink_metadata(path).with_context(|| format!("inspect {}", path.display()))?; + ensure!( + metadata.is_file() && metadata.len() <= 8 * 1024 * 1024, + "packet member is not a bounded regular file" + ); + fs::read(path).with_context(|| format!("read {}", path.display())) +} + +pub(super) fn validate_init_defect(bytes: &[u8]) -> Result<()> { + let gate: Gate = serde_json::from_slice(bytes).context("parse historical initializer gate")?; + ensure!( + gate.schema == "ub-review.gate_outcome.v1" && gate.conclusion == "fail", + "initializer no longer records the historical failure" + ); + let reasons: BTreeSet<_> = gate + .reasons + .iter() + .map(|reason| (reason.kind.as_str(), reason.id.as_str())) + .collect(); + ensure!( + gate.reasons.len() == 2 + && reasons == BTreeSet::from([("policy", "providers"), ("policy", "impact.mode")]), + "initializer gate does not contain exactly its two known historical policy failures" + ); + Ok(()) +} + +pub(super) fn inventory(root: &Path) -> Result { + for required in [ + "running-summary.md", + "review/review.json", + "review/terminal_state.json", + "review/gate_outcome.json", + ] { + ensure!( + !read(&root.join(required))?.is_empty(), + "required packet artifact {required} is empty" + ); + } + let mut pending = vec![root.to_path_buf()]; + let mut paths = Vec::new(); + let mut entry_count = 0_usize; + while let Some(directory) = pending.pop() { + for entry in fs::read_dir(directory)? { + let entry = entry?; + entry_count = entry_count + .checked_add(1) + .context("packet inventory count overflow")?; + ensure!(entry_count <= 2048, "packet inventory exceeds entry budget"); + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push(entry.path()); + } else { + ensure!(kind.is_file(), "packet contains a linked or special member"); + paths.push(entry.path()); + } + } + } + paths.sort(); + let mut artifacts = Vec::new(); + let mut total = 0_u64; + for path in paths { + let bytes = read(&path)?; + let size = u64::try_from(bytes.len())?; + total = total + .checked_add(size) + .context("packet inventory byte overflow")?; + ensure!( + total <= 64 * 1024 * 1024, + "packet inventory exceeds total byte budget" + ); + match path.extension().and_then(|extension| extension.to_str()) { + Some("json") => { + let _: Value = serde_json::from_slice(&bytes) + .with_context(|| format!("parse {}", path.display()))?; + } + Some("ndjson") => { + for (number, line) in std::str::from_utf8(&bytes)?.lines().enumerate() { + if !line.trim().is_empty() { + let _: Value = serde_json::from_str(line).with_context(|| { + format!("parse {} line {}", path.display(), number + 1) + })?; + } + } + } + _ => {} + } + artifacts.push(Artifact { + path: path + .strip_prefix(root)? + .to_string_lossy() + .replace('\\', "/"), + size, + sha256: sha256(&bytes), + }); + } + let gate: Gate = serde_json::from_slice(&read(&root.join("review/gate_outcome.json"))?)?; + let terminal: Terminal = + serde_json::from_slice(&read(&root.join("review/terminal_state.json"))?)?; + let review: Review = serde_json::from_slice(&read(&root.join("review/review.json"))?)?; + ensure!( + gate.schema == "ub-review.gate_outcome.v1" && gate.conclusion == "pass", + "explicit-config model-off gate did not pass" + ); + ensure!( + terminal.schema == "ub-review.terminal_state.v1" && terminal.status == "artifact-only", + "unexpected model-off terminal state" + ); + ensure!( + review.terminal_state == terminal, + "review terminal state disagrees with terminal artifact" + ); + Ok(Inventory { + schema: "ub-review.release_packet_inventory.v2", + artifact_count: artifacts.len(), + artifacts, + gate_conclusion: gate.conclusion, + terminal_status: terminal.status, + all_json_parsed: true, + all_ndjson_parsed: true, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn historical_initializer_defect_requires_exact_failure_set() -> Result<()> { + let bytes = br#"{"schema":"ub-review.gate_outcome.v1","conclusion":"fail","reasons":[{"kind":"policy","id":"providers"},{"kind":"policy","id":"impact.mode"}]}"#; + validate_init_defect(bytes)?; + let text = std::str::from_utf8(bytes)?; + ensure!(validate_init_defect(text.replace("impact.mode", "unrelated").as_bytes()).is_err()); + ensure!(validate_init_defect(text.replace("\"fail\"", "\"pass\"").as_bytes()).is_err()); + Ok(()) + } + + #[test] + fn packet_inventory_rejects_malformed_json_and_conflicting_terminal() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::create_dir(root.join("review"))?; + fs::write(root.join("running-summary.md"), "fixture")?; + fs::write( + root.join("review/gate_outcome.json"), + r#"{"schema":"ub-review.gate_outcome.v1","conclusion":"pass","reasons":[]}"#, + )?; + let terminal = + r#"{"schema":"ub-review.terminal_state.v1","status":"artifact-only","detail":"same"}"#; + fs::write(root.join("review/terminal_state.json"), terminal)?; + fs::write( + root.join("review/review.json"), + format!("{{\"terminal_state\":{terminal}}}"), + )?; + ensure!(inventory(root)?.artifact_count == 4); + fs::write(root.join("malformed.ndjson"), "{\n")?; + ensure!(inventory(root).is_err()); + fs::remove_file(root.join("malformed.ndjson"))?; + fs::write( + root.join("review/terminal_state.json"), + terminal.replace("same", "different"), + )?; + ensure!(inventory(root).is_err()); + Ok(()) + } +} diff --git a/xtask/src/release_portability/process.rs b/xtask/src/release_portability/process.rs new file mode 100644 index 000000000..b7586817c --- /dev/null +++ b/xtask/src/release_portability/process.rs @@ -0,0 +1,141 @@ +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::Duration; + +use anyhow::{Context, Result, ensure}; +use serde::Serialize; +use wait_timeout::ChildExt; + +const STREAM_LIMIT: u64 = 8 * 1024 * 1024; + +pub(super) struct Capture { + receipt: PathBuf, + pub success: bool, + pub code: Option, + pub stdout: Vec, + pub stderr: Vec, +} + +impl Capture { + pub fn require_success(self, label: &str) -> Result { + ensure!( + self.success, + "{label} failed with {:?}; inspect {}", + self.code, + self.receipt.display() + ); + Ok(self) + } + + pub fn text(&self) -> Result<&str> { + Ok(std::str::from_utf8(&self.stdout) + .context("command stdout is not UTF-8")? + .trim()) + } +} + +#[derive(Serialize)] +struct CommandReceipt<'a> { + program: &'a str, + arguments: &'a [String], + exit_code: Option, + timed_out: bool, + stdout_bytes: usize, + stderr_bytes: usize, +} + +pub(super) struct Runner { + logs: PathBuf, + sequence: u64, +} + +impl Runner { + pub fn new(root: &Path) -> Result { + let logs = root.join("commands"); + fs::create_dir(&logs).context("create fresh command log directory")?; + Ok(Self { logs, sequence: 0 }) + } + + pub fn run(&mut self, program: &str, args: &[String]) -> Result { + self.sequence = self + .sequence + .checked_add(1) + .context("command sequence overflow")?; + let prefix = self.logs.join(format!("{:04}", self.sequence)); + // File-backed logs do not require waiting for descendant-held pipe + // handles. The timeout owns this CLI process; Docker container teardown + // is owned separately by runtime::Container. This is not a general + // process-tree or on-disk stream-size enforcement mechanism. + let stdout_path = prefix.with_extension("stdout"); + let stderr_path = prefix.with_extension("stderr"); + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(fs::File::create(&stdout_path)?) + .stderr(fs::File::create(&stderr_path)?) + .spawn() + .with_context(|| format!("spawn {program}"))?; + let read = |path: &Path| -> std::io::Result> { + let mut bytes = Vec::new(); + fs::File::open(path)? + .take(STREAM_LIMIT + 1) + .read_to_end(&mut bytes)?; + Ok(bytes) + }; + let completed = match child.wait_timeout(Duration::from_secs(180)) { + Ok(completed) => completed, + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(error).context("wait for proof command"); + } + }; + let timed_out = completed.is_none(); + let status = match completed { + Some(status) => status, + None => { + let _ = child.kill(); + child.wait().context("reap timed out proof command")? + } + }; + let stdout = read(&stdout_path)?; + let stderr = read(&stderr_path)?; + super::receipts::write_json( + &prefix.with_extension("json"), + &CommandReceipt { + program, + arguments: args, + exit_code: status.code(), + timed_out, + stdout_bytes: stdout.len(), + stderr_bytes: stderr.len(), + }, + )?; + ensure!( + !timed_out, + "{program} exceeded the 180-second command budget" + ); + ensure!( + u64::try_from(stdout.len())? <= STREAM_LIMIT + && u64::try_from(stderr.len())? <= STREAM_LIMIT, + "{program} exceeded the captured-stream budget" + ); + Ok(Capture { + receipt: prefix.with_extension("json"), + success: status.success(), + code: status.code(), + stdout, + stderr, + }) + } + + pub fn checked(&mut self, program: &str, args: &[String]) -> Result { + self.run(program, args)?.require_success(program) + } +} + +pub(super) fn strings(args: &[&str]) -> Vec { + args.iter().map(|arg| (*arg).to_owned()).collect() +} diff --git a/xtask/src/release_portability/receipts.rs b/xtask/src/release_portability/receipts.rs new file mode 100644 index 000000000..154a9d9ff --- /dev/null +++ b/xtask/src/release_portability/receipts.rs @@ -0,0 +1,316 @@ +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; + +use super::archive::ArchiveLayout; +use super::metadata::ReleaseIdentity; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct Authorization { + pub event: String, + pub actor: String, + pub run_id: String, + pub workflow_sha: String, + pub source_sha: String, +} + +impl Authorization { + pub fn validate(&self) -> Result<()> { + ensure!( + matches!(self.event.as_str(), "workflow_dispatch" | "local_explicit"), + "portability execution is not explicitly authorized" + ); + ensure!( + !self.actor.trim().is_empty() && !self.run_id.trim().is_empty(), + "execution has no actor/run identity" + ); + super::metadata::require_oid(&self.source_sha)?; + super::metadata::require_oid(&self.workflow_sha)?; + Ok(()) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct Environment { + pub cargo_present: bool, + pub rustc_present: bool, + pub source_checkout_present: bool, + pub source_fallback_present: bool, +} + +impl Environment { + pub fn validate(&self) -> Result<()> { + ensure!( + !self.cargo_present + && !self.rustc_present + && !self.source_checkout_present + && !self.source_fallback_present, + "proof environment contains Rust tooling or source fallback" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct Platform { + pub image: String, + pub image_id: String, + pub os_id: String, + pub os_version: String, + pub architecture: String, + pub libc: String, + pub kernel: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(super) enum Outcome { + SupportedPass, + UnsupportedExpected, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub(super) struct Row { + pub schema: String, + pub release: ReleaseIdentity, + #[serde(rename = "authorization")] + pub execution: Authorization, + pub archive: ArchiveLayout, + pub platform: Platform, + pub environment: Environment, + pub outcome: Outcome, + pub checks: BTreeMap, +} + +#[derive(Debug, Serialize)] +pub(super) struct Matrix { + schema: &'static str, + release: ReleaseIdentity, + #[serde(rename = "authorization")] + execution: Authorization, + rows: Vec, + decision: BTreeMap<&'static str, &'static str>, +} + +pub(super) fn reconcile( + mut rows: Vec, + expected_release: &ReleaseIdentity, + expected_authorization: &Authorization, +) -> Result { + expected_authorization.validate()?; + ensure!(rows.len() == 2, "matrix requires exactly two runtime rows"); + rows.sort_by(|left, right| left.platform.image.cmp(&right.platform.image)); + let first = rows.first().context("matrix first row")?; + let release = first.release.clone(); + let execution = first.execution.clone(); + ensure!( + &release == expected_release && &execution == expected_authorization, + "runtime rows do not bind the independently resolved release and execution authorization" + ); + let layout = first.archive.clone(); + let mut seen = std::collections::BTreeSet::new(); + for row in &rows { + ensure!( + row.schema == "ub-review.release_portability_receipt.v2", + "wrong row schema" + ); + ensure!( + row.release == release && row.execution == execution && row.archive == layout, + "matrix rows disagree about the release, source, or archive" + ); + row.environment.validate()?; + ensure!( + row.platform.os_id == "ubuntu" && row.platform.architecture == "x86_64", + "unexpected runtime platform" + ); + ensure!( + !row.platform.image_id.is_empty() && !row.platform.kernel.is_empty(), + "missing runtime observations" + ); + ensure!( + seen.insert(row.platform.image.clone()), + "duplicate runtime image" + ); + let expected = match row.platform.image.as_str() { + "ubuntu:24.04" => ("24.04", "glibc 2.39", Outcome::SupportedPass), + "ubuntu:22.04" => ("22.04", "glibc 2.35", Outcome::UnsupportedExpected), + _ => anyhow::bail!("unrecognized runtime matrix image"), + }; + ensure!( + row.platform.os_version == expected.0 + && row.platform.libc == expected.1 + && row.outcome == expected.2, + "runtime observation contradicts the declared compatibility boundary" + ); + for name in [ + "download", + "published_checksum", + "archive_layout", + "environment", + ] { + ensure!( + row.checks.get(name).map(String::as_str) == Some("pass"), + "missing successful {name} proof" + ); + } + let required = if row.outcome == Outcome::SupportedPass { + vec![ + ("binary_identity", "pass"), + ("help", "pass"), + ("doctor", "pass"), + ("init_known_defect", "expected_policy_failure"), + ("model_off_packet", "pass"), + ("negative_controls", "pass"), + ] + } else { + vec![("loader", "GLIBC_2.39_rejection")] + }; + for (name, expected) in required { + ensure!( + row.checks.get(name).map(String::as_str) == Some(expected), + "missing successful {name} proof" + ); + } + } + Ok(Matrix { + schema: "ub-review.release_portability_matrix.v2", + release, + execution, + rows, + decision: BTreeMap::from([ + ( + "ubuntu_24_04_x86_64_glibc_2_39", + "supported_by_this_exact_asset_execution", + ), + ( + "ubuntu_22_04_x86_64_glibc_2_35", + "explicitly_unsupported_GLIBC_2.39", + ), + ("other_platforms", "not_proven"), + ( + "v0.1.0_init", + "historical_empty_policy_defaults_fixed_separately_by_845", + ), + ]), + }) +} + +pub(super) fn json_bytes(value: &impl Serialize) -> Result> { + let mut bytes = serde_json::to_vec_pretty(value)?; + bytes.push(b'\n'); + Ok(bytes) +} + +pub(super) fn write_json(path: &Path, value: &impl Serialize) -> Result<()> { + fs::write(path, json_bytes(value)?).with_context(|| format!("write {}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(image: &str) -> Result { + let supported = image == "ubuntu:24.04"; + let release = crate::release_portability::metadata::validate_release( + &crate::release_portability::metadata::tests::release(), + &crate::release_portability::metadata::tests::reference(), + &BTreeMap::new(), + )?; + Ok(Row { + schema: "ub-review.release_portability_receipt.v2".to_owned(), + release, + execution: Authorization { + event: "workflow_dispatch".to_owned(), + actor: "fixture".to_owned(), + run_id: "123".to_owned(), + workflow_sha: "a".repeat(40), + source_sha: "b".repeat(40), + }, + archive: ArchiveLayout { + schema: "ub-review.release_archive_layout.v2".to_owned(), + member_name: "ub-review".to_owned(), + member_size: 3, + executable_sha256: "c".repeat(64), + }, + platform: Platform { + image: image.to_owned(), + image_id: "sha256:fixture".to_owned(), + os_id: "ubuntu".to_owned(), + os_version: if supported { "24.04" } else { "22.04" }.to_owned(), + architecture: "x86_64".to_owned(), + libc: if supported { + "glibc 2.39" + } else { + "glibc 2.35" + } + .to_owned(), + kernel: "fixture".to_owned(), + }, + environment: Environment { + cargo_present: false, + rustc_present: false, + source_checkout_present: false, + source_fallback_present: false, + }, + outcome: if supported { + Outcome::SupportedPass + } else { + Outcome::UnsupportedExpected + }, + checks: [ + ("download", "pass"), + ("published_checksum", "pass"), + ("archive_layout", "pass"), + ("environment", "pass"), + ("binary_identity", "pass"), + ("help", "pass"), + ("doctor", "pass"), + ("init_known_defect", "expected_policy_failure"), + ("model_off_packet", "pass"), + ("negative_controls", "pass"), + ("loader", "GLIBC_2.39_rejection"), + ] + .into_iter() + .map(|(a, b)| (a.to_owned(), b.to_owned())) + .collect(), + }) + } + + #[test] + fn matrix_requires_both_exact_platforms_and_consistent_identity() -> Result<()> { + let positive = row("ubuntu:24.04")?; + let negative = row("ubuntu:22.04")?; + let check = |rows| reconcile(rows, &positive.release, &positive.execution); + let bytes = json_bytes(&check(vec![positive.clone(), negative.clone()])?)?; + let serialized: serde_json::Value = serde_json::from_slice(&bytes)?; + ensure!( + serialized.get("authorization") == Some(&serde_json::to_value(&positive.execution)?) + ); + ensure!(serialized.get("execution").is_none()); + ensure!(bytes == json_bytes(&check(vec![negative.clone(), positive.clone()])?)?); + ensure!(check(vec![positive.clone()]).is_err()); + ensure!(check(vec![positive.clone(), positive.clone()]).is_err()); + for mutation in 0..5 { + let mut changed = negative.clone(); + match mutation { + 0 => changed.release.archive.id += 1, + 1 => changed.platform.libc = "glibc 2.39".to_owned(), + 2 => changed.environment.cargo_present = true, + 3 => changed.outcome = Outcome::SupportedPass, + _ => { + changed.checks.remove("loader"); + } + } + ensure!(check(vec![positive.clone(), changed]).is_err()); + } + let mut forged_positive = positive.clone(); + let mut forged_negative = negative; + forged_positive.release.archive.id += 1; + forged_negative.release.archive.id += 1; + ensure!(check(vec![forged_positive, forged_negative]).is_err()); + Ok(()) + } +} diff --git a/xtask/src/release_portability/resolver.rs b/xtask/src/release_portability/resolver.rs new file mode 100644 index 000000000..87083f043 --- /dev/null +++ b/xtask/src/release_portability/resolver.rs @@ -0,0 +1,141 @@ +use std::env; +use std::fs; +use std::path::Path; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; + +use super::receipts::{Authorization, write_json}; + +pub(super) const MISSING_ASSET: &str = "ub-review-missing-x86_64-unknown-linux-gnu.tar.gz"; + +#[derive(Debug, Deserialize, Serialize)] +pub(super) struct ResolverEnvironment { + cargo_present: bool, + rustc_present: bool, + source_workdir_present: bool, +} + +#[derive(Deserialize, Serialize)] +struct Before { + schema: String, + #[serde(rename = "authorization")] + execution: Authorization, + environment: ResolverEnvironment, +} + +#[derive(Serialize)] +struct Receipt { + schema: &'static str, + #[serde(rename = "authorization")] + execution: Authorization, + release_tag: &'static str, + requested_asset: &'static str, + step_outcome: String, + before: ResolverEnvironment, + after: ResolverEnvironment, + outcome: &'static str, +} + +fn executable_present(name: &str) -> Result { + let path = env::var_os("PATH").context("resolver PATH is missing")?; + for directory in env::split_paths(&path) { + if directory.join(name).is_file() { + return Ok(true); + } + } + Ok(false) +} + +fn observe() -> Result { + ensure!( + cfg!(target_os = "linux"), + "strict resolver proof requires its clean Linux container" + ); + let temp = env::var_os("RUNNER_TEMP").context("resolver RUNNER_TEMP is missing")?; + Ok(ResolverEnvironment { + cargo_present: executable_present("cargo")?, + rustc_present: executable_present("rustc")?, + source_workdir_present: Path::new(&temp).join("ub-review-action-src").exists(), + }) +} + +fn require_clean(environment: &ResolverEnvironment) -> Result<()> { + ensure!( + !environment.cargo_present + && !environment.rustc_present + && !environment.source_workdir_present, + "strict release resolver has Rust tooling or a source fallback workdir" + ); + Ok(()) +} + +pub(super) fn before(out: &Path, execution: Authorization) -> Result<()> { + let environment = observe()?; + require_clean(&environment)?; + write_json( + &out.join("resolver-before.json"), + &Before { + schema: "ub-review.release_resolver_before.v2".to_owned(), + execution, + environment, + }, + ) +} + +pub(super) fn after(out: &Path, execution: Authorization, outcome: &str) -> Result<()> { + let before: Before = serde_json::from_slice(&fs::read(out.join("resolver-before.json"))?)?; + ensure!( + before.schema == "ub-review.release_resolver_before.v2" && before.execution == execution, + "resolver baseline does not bind this source and dispatch" + ); + require_clean(&before.environment)?; + let after = observe()?; + require_clean(&after)?; + ensure!( + outcome == "failure", + "strict missing-asset Action did not fail" + ); + write_json( + &out.join("resolver-no-fallback.json"), + &Receipt { + schema: "ub-review.release_resolver_no_fallback.v2", + execution, + release_tag: super::metadata::TAG, + requested_asset: MISSING_ASSET, + step_outcome: outcome.to_owned(), + before: before.environment, + after, + outcome: "rejected_without_fallback", + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clean_resolver_rejects_each_fallback_surface() -> Result<()> { + require_clean(&ResolverEnvironment { + cargo_present: false, + rustc_present: false, + source_workdir_present: false, + })?; + for (cargo, rustc, source) in [ + (true, false, false), + (false, true, false), + (false, false, true), + ] { + ensure!( + require_clean(&ResolverEnvironment { + cargo_present: cargo, + rustc_present: rustc, + source_workdir_present: source + }) + .is_err() + ); + } + Ok(()) + } +} diff --git a/xtask/src/release_portability/runtime.rs b/xtask/src/release_portability/runtime.rs new file mode 100644 index 000000000..95126a1b2 --- /dev/null +++ b/xtask/src/release_portability/runtime.rs @@ -0,0 +1,523 @@ +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::Duration; + +use anyhow::{Context, Result, ensure}; +use wait_timeout::ChildExt; + +use super::archive::{ArchiveLayout, inspect_archive, verify_download, verify_version}; +use super::metadata::{Asset, ReleaseIdentity}; +use super::packet; +use super::process::{Capture, Runner, strings}; +use super::receipts::{Authorization, Environment, Outcome, Platform, Row, write_json}; + +const BASE_SOURCE: &str = + "pub fn checked_add(left: usize, right: usize) -> Option { left.checked_add(right) }\n"; +const HEAD_SOURCE: &str = "pub fn checked_add(left: usize, right: usize) -> Option { left.checked_add(right) }\n\npub unsafe fn read_raw(value: *const usize) -> usize {\n // SAFETY: the synthetic fixture intentionally exposes a reviewable pointer contract.\n unsafe { *value }\n}\n"; +const VALID_CONFIG: &str = + "profile = \"gh-runner\"\n\n[providers]\npolicy = \"auto\"\n\n[impact]\nmode = \"shadow\"\n"; + +struct Container { + id: String, + active: bool, +} + +impl Container { + fn create(runner: &mut Runner, image: &str) -> Result { + let created = runner.checked( + "docker", + &strings(&[ + "create", + "--platform", + "linux/amd64", + image, + "sleep", + "1800", + ]), + )?; + let id = created.text()?.to_owned(); + ensure!( + id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()), + "Docker returned an invalid container identity" + ); + let container = Self { id, active: true }; + runner.checked("docker", &strings(&["start", &container.id]))?; + Ok(container) + } + + fn exec(&self, runner: &mut Runner, args: &[&str]) -> Result { + let mut command = strings(&["exec", &self.id]); + command.extend(strings(args)); + runner.run("docker", &command) + } + + fn checked(&self, runner: &mut Runner, args: &[&str]) -> Result { + self.exec(runner, args)? + .require_success("container command") + } + + fn copy_to(&self, runner: &mut Runner, source: &Path, target: &str) -> Result<()> { + runner.checked( + "docker", + &strings(&[ + "cp", + source.to_str().context("non-UTF-8 copy source")?, + &format!("{}:{target}", self.id), + ]), + )?; + Ok(()) + } + + fn copy_from(&self, runner: &mut Runner, source: &str, target: &Path) -> Result<()> { + runner.checked( + "docker", + &strings(&[ + "cp", + &format!("{}:{source}", self.id), + target.to_str().context("non-UTF-8 copy destination")?, + ]), + )?; + Ok(()) + } + + fn remove(&mut self, runner: &mut Runner) -> Result<()> { + runner.checked("docker", &strings(&["rm", "--force", &self.id]))?; + self.active = false; + Ok(()) + } +} + +impl Drop for Container { + fn drop(&mut self) { + if self.active { + let removed = (|| -> Result { + let mut child = Command::new("docker") + .args(["rm", "--force", &self.id]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + match child.wait_timeout(Duration::from_secs(15)) { + Ok(Some(status)) => Ok(status.success()), + _ => { + let _ = child.kill(); + let _ = child.wait(); + Ok(false) + } + } + })(); + if !matches!(removed, Ok(true)) { + eprintln!( + "cleanup incomplete: lane-owned Docker container {}", + self.id + ); + } + } + } +} + +fn environment(container: &Container, runner: &mut Runner) -> Result { + // Shell is used only for its executable lookup builtin. Rust evaluates + // every result and owns the environment assertion and receipt. + let cargo = container.exec(runner, &["sh", "-c", "command -v cargo"])?; + let rustc = container.exec(runner, &["sh", "-c", "command -v rustc"])?; + ensure!( + (cargo.success || cargo.code == Some(127) || cargo.code == Some(1)) + && (rustc.success || rustc.code == Some(127) || rustc.code == Some(1)), + "tool-absence probe did not execute" + ); + let source = container.exec(runner, &["test", "-e", "/work/fixture/src/main.rs"])?; + let fallback = container.exec(runner, &["test", "-e", "/work/ub-review-action-src"])?; + ensure!( + matches!(source.code, Some(0 | 1)) && matches!(fallback.code, Some(0 | 1)), + "source-absence probe did not execute" + ); + let observation = Environment { + cargo_present: cargo.success, + rustc_present: rustc.success, + source_checkout_present: source.success, + source_fallback_present: fallback.success, + }; + observation.validate()?; + Ok(observation) +} + +fn platform(container: &Container, runner: &mut Runner, image: &str) -> Result { + let os = container.checked(runner, &["cat", "/etc/os-release"])?; + let fields: BTreeMap<_, _> = os + .text()? + .lines() + .filter_map(|line| line.split_once('=')) + .map(|(key, value)| (key, value.trim_matches('"'))) + .collect(); + let image_id = runner + .checked( + "docker", + &strings(&["inspect", "--format", "{{.Image}}", &container.id]), + )? + .text()? + .to_owned(); + Ok(Platform { + image: image.to_owned(), + image_id, + os_id: fields.get("ID").context("OS ID")?.to_string(), + os_version: fields.get("VERSION_ID").context("OS version")?.to_string(), + architecture: container + .checked(runner, &["uname", "-m"])? + .text()? + .to_owned(), + libc: container + .checked(runner, &["getconf", "GNU_LIBC_VERSION"])? + .text()? + .to_owned(), + kernel: container + .checked(runner, &["uname", "-r"])? + .text()? + .to_owned(), + }) +} + +fn negatives( + container: &Container, + runner: &mut Runner, + out: &Path, + archive: &Asset, + archive_bytes: &[u8], +) -> Result<()> { + let mut tampered = archive_bytes.to_vec(); + tampered.push(0); + ensure!( + verify_download(archive, &tampered).is_err(), + "tampered asset accepted" + ); + let missing = runner.run( + "curl", + &strings(&[ + "--fail", + "--silent", + "--show-error", + "--max-time", + "10", + "file:///ub-review-portability-intentionally-missing", + ]), + )?; + ensure!( + !missing.success && missing.code == Some(37), + "missing asset control did not fail as a missing file" + ); + let executable = out.join("impostor"); + container.copy_from(runner, "/bin/true", &executable)?; + let impostor_bytes = fs::read(&executable)?; + let mut builder = tar::Builder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(u64::try_from(impostor_bytes.len())?); + header.set_mode(0o755); + header.set_cksum(); + builder.append_data(&mut header, "ub-review", impostor_bytes.as_slice())?; + let tar_bytes = builder.into_inner()?; + let mut compressed = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut compressed, &tar_bytes)?; + let impostor_archive = compressed.finish()?; + let impostor_asset = Asset { + id: 0, + name: "negative-control".to_owned(), + size: u64::try_from(impostor_archive.len())?, + digest: format!("sha256:{}", super::archive::sha256(&impostor_archive)), + browser_download_url: String::new(), + }; + verify_download(&impostor_asset, &impostor_archive)?; + let (_, extracted) = inspect_archive(&impostor_archive)?; + fs::write(&executable, extracted)?; + container.copy_to(runner, &executable, "/work/bin/impostor")?; + container.checked(runner, &["chmod", "755", "/work/bin/impostor"])?; + let identity = container.exec(runner, &["/work/bin/impostor", "--version"])?; + ensure!( + verify_version(identity.success, &identity.stdout, &identity.stderr).is_err(), + "checksum-valid impostor accepted" + ); + let mut controls = BTreeMap::from([ + ("missing_asset_rejected", true), + ("tampered_asset_rejected_before_extraction", true), + ("checksum_valid_impostor_rejected_by_identity", true), + ]); + for (name, members) in [ + ( + "wrong_layout_rejected_before_execution", + vec!["nested/ub-review"], + ), + ( + "duplicate_archive_member_rejected_before_execution", + vec!["ub-review", "ub-review"], + ), + ] { + let mut builder = tar::Builder::new(Vec::new()); + for member in members { + let mut header = tar::Header::new_gnu(); + header.set_size(3); + header.set_mode(0o755); + header.set_cksum(); + builder.append_data(&mut header, member, b"bin".as_slice())?; + } + let bytes = builder.into_inner()?; + let mut compressed = + flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut compressed, &bytes)?; + ensure!( + inspect_archive(&compressed.finish()?).is_err(), + "{name} control accepted" + ); + controls.insert(name, true); + } + write_json(&out.join("negative-controls.json"), &controls) +} + +fn supported_packet(container: &Container, runner: &mut Runner, out: &Path) -> Result<()> { + let fixture = out.join("fixture-input"); + fs::create_dir(&fixture)?; + fs::create_dir(fixture.join("src"))?; + fs::write( + fixture.join("Cargo.toml"), + "[package]\nname = \"release-portability-fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", + )?; + fs::write(fixture.join("src/lib.rs"), BASE_SOURCE)?; + fs::write(fixture.join(".ub-review.toml"), VALID_CONFIG)?; + container.copy_to(runner, &fixture, "/work/fixture")?; + // Docker's archive copy can preserve the host directory owner. Git must + // discover a repository owned by its container user; scope ownership to + // this fresh synthetic fixture rather than relaxing safe.directory. + container.checked(runner, &["stat", "-c", "%u:%g %n", "/work/fixture"])?; + container.checked(runner, &["chown", "-R", "0:0", "/work/fixture"])?; + for args in [ + vec!["git", "-C", "/work/fixture", "init", "-q", "-b", "main"], + vec![ + "git", + "-C", + "/work/fixture", + "config", + "user.name", + "UB Review Portability Proof", + ], + vec![ + "git", + "-C", + "/work/fixture", + "config", + "user.email", + "proof@invalid.example", + ], + ] { + container.checked(runner, &args)?; + } + container.checked( + runner, + &[ + "/work/bin/ub-review", + "init", + "--path", + "/work/fixture/init-generated.ub-review.toml", + "--no-guide", + "--profile", + "gh-runner", + "--force", + ], + )?; + container.copy_from( + runner, + "/work/fixture/init-generated.ub-review.toml", + &out.join("init-generated.ub-review.toml"), + )?; + container.checked(runner, &["git", "-C", "/work/fixture", "add", "."])?; + container.checked( + runner, + &[ + "git", + "-C", + "/work/fixture", + "commit", + "-q", + "-m", + "fixture base", + ], + )?; + fs::write(fixture.join("src/lib.rs"), HEAD_SOURCE)?; + container.copy_to( + runner, + &fixture.join("src/lib.rs"), + "/work/fixture/src/lib.rs", + )?; + container.checked(runner, &["git", "-C", "/work/fixture", "add", "src/lib.rs"])?; + container.checked( + runner, + &[ + "git", + "-C", + "/work/fixture", + "commit", + "-q", + "-m", + "fixture head", + ], + )?; + for (config, packet_name) in [ + ("init-generated.ub-review.toml", "packet-init-generated"), + (".ub-review.toml", "packet"), + ] { + let config_path = format!("/work/fixture/{config}"); + container.checked( + runner, + &[ + "/work/bin/ub-review", + "doctor", + "--root", + "/work/fixture", + "--config", + &config_path, + "--profile", + "gh-runner", + "--base", + "HEAD~1", + ], + )?; + let packet_path = format!("/work/fixture/{packet_name}"); + container.checked( + runner, + &[ + "/work/bin/ub-review", + "run", + "--root", + "/work/fixture", + "--base", + "HEAD~1", + "--head", + "HEAD", + "--config", + &config_path, + "--out", + &packet_path, + "--profile", + "gh-runner", + "--dry-run", + "--posting", + "artifact-only", + "--run-pass", + "manual", + "--model-mode", + "off", + "--fail-on-gate", + "false", + "--no-github-summary", + ], + )?; + container.copy_from(runner, &packet_path, &out.join(packet_name))?; + } + packet::validate_init_defect(&fs::read( + out.join("packet-init-generated/review/gate_outcome.json"), + )?)?; + let inventory = packet::inventory(&out.join("packet"))?; + write_json(&out.join("packet-inventory.json"), &inventory)?; + Ok(()) +} + +pub(super) struct VerifiedRelease<'a> { + pub release: &'a ReleaseIdentity, + pub layout: &'a ArchiveLayout, + pub archive_bytes: &'a [u8], + pub executable: &'a Path, +} + +pub(super) fn run_row( + runner: &mut Runner, + out: &Path, + image: &str, + verified: VerifiedRelease<'_>, + execution: &Authorization, +) -> Result { + let VerifiedRelease { + release, + layout, + archive_bytes, + executable, + } = verified; + fs::create_dir(out)?; + let mut container = Container::create(runner, image)?; + let result = (|| { + let platform = platform(&container, runner, image)?; + environment(&container, runner)?; + container.checked(runner, &["mkdir", "-p", "/work/bin"])?; + container.copy_to(runner, executable, "/work/bin/ub-review")?; + container.checked(runner, &["chmod", "755", "/work/bin/ub-review"])?; + let version = container.exec(runner, &["/work/bin/ub-review", "--version"])?; + let mut checks: BTreeMap = [ + "download", + "published_checksum", + "archive_layout", + "environment", + ] + .into_iter() + .map(|name| (name.to_owned(), "pass".to_owned())) + .collect(); + let outcome = if image == "ubuntu:22.04" { + ensure!( + !version.success && String::from_utf8_lossy(&version.stderr).contains("GLIBC_2.39"), + "unsupported baseline did not fail at the expected GLIBC_2.39 loader boundary" + ); + checks.insert("loader".to_owned(), "GLIBC_2.39_rejection".to_owned()); + Outcome::UnsupportedExpected + } else { + verify_version(version.success, &version.stdout, &version.stderr)?; + let help = container.checked(runner, &["/work/bin/ub-review", "--help"])?; + ensure!( + help.text()?.contains("Build box-aware evidence packets"), + "help does not identify UB Review" + ); + container.checked(runner, &["apt-get", "update", "-qq"])?; + container.checked( + runner, + &[ + "apt-get", + "install", + "-y", + "-qq", + "--no-install-recommends", + "ca-certificates", + "git", + ], + )?; + negatives(&container, runner, out, &release.archive, archive_bytes)?; + supported_packet(&container, runner, out)?; + for name in [ + "binary_identity", + "help", + "doctor", + "model_off_packet", + "negative_controls", + ] { + checks.insert(name.to_owned(), "pass".to_owned()); + } + checks.insert( + "init_known_defect".to_owned(), + "expected_policy_failure".to_owned(), + ); + Outcome::SupportedPass + }; + let environment = environment(&container, runner)?; + let row = Row { + schema: "ub-review.release_portability_receipt.v2".to_owned(), + release: release.clone(), + execution: execution.clone(), + archive: layout.clone(), + platform, + environment, + outcome, + checks, + }; + write_json(&out.join("receipt.json"), &row)?; + Ok(row) + })(); + let cleanup = container.remove(runner); + let row = result?; + cleanup?; + Ok(row) +}