diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 47ee360..a4c2635 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -4,6 +4,7 @@ on: pull_request: paths: - "src/**" + - "xtask/**" - ".github/workflows/codeql.yml" push: branches: [main] diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 06263e5..33f883a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,19 @@ name: release on: + pull_request: + paths: + - ".github/workflows/release.yml" + - "Cargo.toml" + - "Cargo.lock" + - ".cargo/config.toml" + - "README.md" + - "CHANGELOG.md" + - "LICENSE-MIT" + - "migrations/**" + - "src/**" + - "xtask/**" + - "scripts/syft-release.yaml" push: tags: - "v*" @@ -28,25 +41,32 @@ defaults: jobs: validate-tag: - name: validate tag + name: validate release candidate runs-on: ubuntu-24.04 timeout-minutes: 5 env: TAG_REF: ${{ inputs.tag || github.ref_name }} + EVENT_NAME: ${{ github.event_name }} + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + outputs: + tag_ref: ${{ steps.validate.outputs.tag_ref }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - # Build exactly the tagged bytes: without ref, a manual dispatch - # would check out the default branch and label it as the tag. + # Tag dispatches use the tag; PR rehearsals use the immutable head, not its merge ref. with: - ref: ${{ inputs.tag || github.ref_name }} + ref: ${{ github.event.pull_request.head.sha || inputs.tag || github.ref_name }} - name: Tag matches Cargo.toml version and changelog section + id: validate run: | + manifest_version="$(sed -n '/^\[package\]/,/^\[/{s/^version = "\(.*\)"/\1/p;}' Cargo.toml)" ref="$TAG_REF" + if [ "$EVENT_NAME" = pull_request ]; then + ref="v$manifest_version" + fi case "$ref" in v*) tag="${ref#v}" ;; *) echo "::error::tag must start with 'v' (got '$ref')"; exit 1 ;; esac - manifest_version="$(sed -n '/^\[package\]/,/^\[/{s/^version = "\(.*\)"/\1/p;}' Cargo.toml)" if [ "$tag" != "$manifest_version" ]; then echo "::error::tag v$tag does not match Cargo.toml version $manifest_version" exit 1 @@ -60,12 +80,19 @@ jobs: fi # Prove the checkout really is the tag before anything builds. head="$(git rev-parse HEAD)" - tagged="$(git rev-parse "$ref^{commit}")" + if [ "$EVENT_NAME" = pull_request ]; then + tagged="$CANDIDATE_SHA" + else + tagged="$(git rev-parse "$ref^{commit}")" + fi if [ "$head" != "$tagged" ]; then echo "::error::HEAD $head is not the tagged commit $tagged" exit 1 fi + printf 'tag_ref=%s\n' "$ref" >> "$GITHUB_OUTPUT" - name: Extract release notes + env: + TAG_REF: ${{ steps.validate.outputs.tag_ref }} run: | ref="$TAG_REF" version="${ref#v}" @@ -116,11 +143,11 @@ jobs: os: ubuntu-24.04-arm target: aarch64-unknown-linux-musl env: - TAG_REF: ${{ inputs.tag || github.ref_name }} + TAG_REF: ${{ needs.validate-tag.outputs.tag_ref }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ inputs.tag || github.ref_name }} + ref: ${{ github.event.pull_request.head.sha || inputs.tag || github.ref_name }} - uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable branch with: toolchain: 1.97.0 @@ -137,7 +164,9 @@ jobs: # packaging only and must not ship clap_mangen or the hidden __man # command inside released binaries. - name: Build release binary - run: cargo build --release --locked --target ${{ matrix.target }} + run: | + cargo install cargo-auditable --version 0.7.7 --locked + cargo auditable build --release --locked --target ${{ matrix.target }} - name: Generate man pages for the archive run: cargo run --quiet --locked --features man -- __man man-pages - name: Smoke test binary @@ -187,9 +216,14 @@ jobs: uses: anchore/sbom-action@e22c389904149dbc22b58101806040fa8d37a610 # v0.24.0 with: format: cyclonedx-json - file: "dist/atx-${{ inputs.tag || github.ref_name }}-${{ matrix.target }}.tar.gz" - output-file: "dist/atx-${{ inputs.tag || github.ref_name }}-${{ matrix.target }}.cdx.json" + file: "dist/atx-${{ needs.validate-tag.outputs.tag_ref }}-${{ matrix.target }}.tar.gz" + output-file: "dist/atx-${{ needs.validate-tag.outputs.tag_ref }}-${{ matrix.target }}.cdx.json" + syft-version: v1.42.3 + config: scripts/syft-release.yaml upload-artifact: false + upload-release-assets: false + - name: Validate binary dependency inventory + run: cargo xtask check-sbom "dist/atx-${TAG_REF}-${{ matrix.target }}.cdx.json" "${{ matrix.target }}" - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: archive-${{ matrix.target }} @@ -199,23 +233,24 @@ jobs: if-no-files-found: error finalize: - name: checksums and attestation - needs: archives + name: validate release inventories and checksums + needs: [validate-tag, archives] runs-on: ubuntu-24.04 timeout-minutes: 10 - permissions: - id-token: write - attestations: write env: - DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && 'true' || 'false' }} + TAG_REF: ${{ needs.validate-tag.outputs.tag_ref }} steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha || inputs.tag || github.ref_name }} + - uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c + with: + toolchain: 1.97.0 - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: path: dist merge-multiple: true - name: Verify every expected archive and SBOM is present - env: - TAG_REF: ${{ inputs.tag || github.ref_name }} run: | ref="$TAG_REF" for target in aarch64-apple-darwin x86_64-apple-darwin x86_64-unknown-linux-gnu x86_64-unknown-linux-musl aarch64-unknown-linux-gnu aarch64-unknown-linux-musl; do @@ -225,6 +260,7 @@ jobs: test -s "dist/atx-$ref-$target.cdx.json" || { echo "::error::missing SBOM for $target"; exit 1; } + cargo xtask check-sbom "dist/atx-$ref-$target.cdx.json" "$target" done test -s "dist/RELEASE_NOTES.md" || { echo "::error::missing extracted release notes"; exit 1; @@ -234,6 +270,29 @@ jobs: run: | sha256sum -- *.tar.gz *.cdx.json > SHA256SUMS cat SHA256SUMS + - name: Upload checksum manifest + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: release-checksums + path: dist/SHA256SUMS + if-no-files-found: error + + attest: + name: attest release artifacts + needs: finalize + if: github.event_name == 'push' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + id-token: write + attestations: write + env: + DRY_RUN: 'false' + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + path: dist + merge-multiple: true - name: Attest archives and SBOMs if: env.DRY_RUN == 'false' uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 @@ -251,19 +310,12 @@ jobs: for f in dist/*.tar.gz dist/*.cdx.json dist/SHA256SUMS; do gh attestation verify "$f" -R "$GITHUB_REPOSITORY" done - - name: Upload checksum manifest - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: release-checksums - path: dist/SHA256SUMS - if-no-files-found: error draft-release: name: publish draft release - needs: finalize - # The only write-to-GitHub step runs in the protected environment, so - # dry-run dispatches (workflow_dispatch) never touch it at all. - if: github.event_name != 'workflow_dispatch' + needs: attest + # Only tag pushes can enter the protected publishing environment. + if: github.event_name == 'push' environment: release runs-on: ubuntu-24.04 timeout-minutes: 10 diff --git a/docs/releasing.md b/docs/releasing.md index baab527..4f29da0 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -22,6 +22,25 @@ a reproducible `.tar.gz` with fixed timestamps and ownership. The workflow adds a `SHA256SUMS` file and a CycloneDX SBOM for every archive, then creates a draft GitHub release. Publishing the draft is a manual click. +Release builds use `cargo-auditable` 0.7.7 to embed the Rust dependency graph in +the stripped binary. The existing SBOM action uses pinned Syft 1.42.3 to scan +that archive. `cargo xtask check-sbom FILE TARGET` checks the root package, +locked crate versions, and exact default-feature direct runtime dependencies. +Empty inventories, missing crates, duplicate references, and broken edges fail +before upload and again before checksums are generated. + +The inventory covers Rust crates recorded by the build, not bundled C source +or operating-system libraries. It is not a complete native-library inventory. +Scanner timestamps can vary; the checksum manifest covers the exact SBOM files +attached to that run. Temporary extraction-file records are omitted, while +crate locations and the archive hash remain in the document. + +PRs that change release inputs run these same six native archive jobs against +the exact PR head. This rehearsal creates workflow artifacts and checksums, +not tags, attestations, releases, or registry uploads. Tag checks remain required +for actual tag builds and manual dispatches. Only a tag push can attest files +or enter the protected draft-release job. + The workflow also signs build attestations for each archive, SBOM, and the checksum file, so anyone can check that a file came from this repository's release workflow: diff --git a/scripts/README.md b/scripts/README.md index fb1b4a3..f13ae10 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -32,3 +32,8 @@ The required CI package job also tests the bin from a freshly extracted source archive. Workspace tests alone cannot catch a missing packaged test fixture. Use a fresh `CARGO_TARGET_DIR` for the extracted crate too. Reusing the workspace target can run an older test binary even when the archive contains the new code. + +`syft-release.yaml` configures the pinned release scanner. It omits temporary +extraction-file metadata, not the Rust dependency inventory, and disables +update checks. Release jobs scan the actual auditable archive and validate its +inventory with `cargo xtask check-sbom FILE TARGET` before upload and finalize. diff --git a/scripts/check-workflow-guards.sh b/scripts/check-workflow-guards.sh index b1f307b..e5c1553 100755 --- a/scripts/check-workflow-guards.sh +++ b/scripts/check-workflow-guards.sh @@ -42,6 +42,7 @@ require_literal .github/workflows/ci.yml ' COVERAGE_REGION_FLOOR: 85' require_pattern .github/workflows/codeql.yml 'ubuntu-[0-9]' require_pattern .github/workflows/codeql.yml 'macos-[0-9]' +require_literal .github/workflows/codeql.yml ' - "xtask/**"' require_pattern .github/workflows/mutation.yml 'timeout-minutes:' require_pattern .github/workflows/mutation.yml 'cargo mutants' @@ -58,7 +59,12 @@ fi require_pattern .github/workflows/release.yml 'DRY_RUN:' require_pattern .github/workflows/release.yml "if: env\.DRY_RUN == 'false'" -require_pattern .github/workflows/release.yml "if: github\.event_name != 'workflow_dispatch'" +require_pattern .github/workflows/release.yml "if: github\.event_name == 'push'" +require_pattern .github/workflows/release.yml 'cargo install cargo-auditable --version 0\.7\.7 --locked' +require_pattern .github/workflows/release.yml 'cargo auditable build --release --locked --target' +require_pattern .github/workflows/release.yml 'syft-version: v1\.42\.3' +require_pattern .github/workflows/release.yml 'cargo xtask check-sbom' +require_pattern .github/workflows/release.yml 'upload-release-assets: false' require_pattern .github/workflows/release.yml 'sha256sum .*\.tar\.gz .*\.cdx\.json .*SHA256SUMS' require_pattern .github/workflows/release.yml 'dist/SHA256SUMS' require_pattern .github/workflows/release.yml 'gh attestation verify' diff --git a/scripts/syft-release.yaml b/scripts/syft-release.yaml new file mode 100644 index 0000000..956fac1 --- /dev/null +++ b/scripts/syft-release.yaml @@ -0,0 +1,5 @@ +# Keep scanner-generated extraction paths out of the released inventory. +check-for-app-update: false +file: + metadata: + selection: none diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fea5341..45fa9fc 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,21 +1,32 @@ //! Repository maintenance tasks. Run with `cargo xtask `. +mod sbom; + use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; fn main() -> ExitCode { - if std::env::args().nth(1).as_deref() != Some("dist-man") { - eprintln!("usage: cargo xtask dist-man"); - return ExitCode::from(2); - } - match dist_man() { - Ok(path) => { - println!("{}", path.display()); + let args: Vec<_> = std::env::args_os().skip(1).collect(); + let result = match args.as_slice() { + [task] if task == "dist-man" => dist_man().map(|path| path.display().to_string()), + [task, path, target] if task == "check-sbom" => match target.to_str() { + Some(target) => sbom::check(Path::new(path), target) + .map(|count| format!("SBOM: {count} locked runtime components verified")), + None => Err("release target must be UTF-8".into()), + }, + _ => { + eprintln!("usage: cargo xtask dist-man | check-sbom FILE TARGET"); + return ExitCode::from(2); + } + }; + match result { + Ok(message) => { + println!("{message}"); ExitCode::SUCCESS } Err(error) => { - eprintln!("xtask dist-man: {error}"); + eprintln!("xtask: {error}"); ExitCode::FAILURE } } diff --git a/xtask/src/sbom.rs b/xtask/src/sbom.rs new file mode 100644 index 0000000..fd26c14 --- /dev/null +++ b/xtask/src/sbom.rs @@ -0,0 +1,441 @@ +//! Validate the Rust dependency inventory of a shipped binary. + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::Path; + +use serde_json::Value; + +const MAX_DOCUMENT_BYTES: u64 = 16 * 1024 * 1024; + +#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] +struct Package { + name: String, + version: String, +} + +pub(super) struct Inventory { + root: Package, + direct: BTreeSet, + locked: BTreeSet, +} + +fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, String> { + value + .get(key) + .and_then(Value::as_str) + .filter(|text| { + !text.is_empty() && text.len() <= 1024 && !text.chars().any(char::is_control) + }) + .ok_or_else(|| format!("missing or invalid string: {key}")) +} + +fn array<'a>(value: &'a Value, key: &str) -> Result<&'a [Value], String> { + value + .get(key) + .and_then(Value::as_array) + .map(Vec::as_slice) + .ok_or_else(|| format!("missing or invalid array: {key}")) +} + +fn package(value: &Value) -> Result { + Ok(Package { + name: text(value, "name")?.to_owned(), + version: text(value, "version")?.to_owned(), + }) +} + +/// Select the root and its locked, default-feature runtime dependencies from Cargo metadata. +pub(super) fn expected_inventory(metadata: &Value) -> Result { + let mut packages = BTreeMap::new(); + let mut root = None; + for value in array(metadata, "packages")? { + let id = text(value, "id")?; + let package = package(value)?; + if package.name == "atx" && root.replace((id, package.clone())).is_some() { + return Err("Cargo metadata contains multiple atx roots".into()); + } + if packages.insert(id, package).is_some() { + return Err("Cargo metadata contains duplicate package IDs".into()); + } + } + let (root_id, root) = root.ok_or("Cargo metadata has no atx root")?; + let resolve = metadata + .get("resolve") + .ok_or("Cargo metadata has no resolve graph")?; + let mut direct = BTreeSet::new(); + let mut found = false; + for node in array(resolve, "nodes")? { + if text(node, "id")? != root_id { + continue; + } + if std::mem::replace(&mut found, true) { + return Err("Cargo metadata contains duplicate root nodes".into()); + } + for dependency in array(node, "deps")? { + let kinds = array(dependency, "dep_kinds")?; + if kinds.is_empty() { + return Err("Cargo dependency has no resolved kinds".into()); + } + let mut runtime = false; + for kind in kinds { + match kind.get("kind") { + Some(Value::Null) => runtime = true, + Some(Value::String(value)) if matches!(value.as_str(), "dev" | "build") => {} + _ => return Err("Cargo dependency has an invalid kind".into()), + } + } + if runtime { + let id = text(dependency, "pkg")?; + direct.insert( + packages + .get(id) + .ok_or("unresolved Cargo runtime dependency")? + .clone(), + ); + } + } + } + if !found || direct.is_empty() { + return Err("Cargo metadata has no resolved runtime dependencies".into()); + } + Ok(Inventory { + root, + direct, + locked: packages.into_values().collect(), + }) +} + +/// Reject empty, mismatched, or disconnected binary inventories before artifact upload. +pub(super) fn validate(document: &Value, expected: &Inventory) -> Result { + if text(document, "bomFormat")? != "CycloneDX" + || text(document, "specVersion")? != "1.6" + || document + .get("version") + .and_then(Value::as_u64) + .is_none_or(|value| value == 0) + { + return Err("expected a CycloneDX 1.6 document with a positive revision".into()); + } + let components = array(document, "components")?; + if components.len() < 2 { + return Err("SBOM must contain the atx root and non-empty dependencies".into()); + } + let mut references = BTreeSet::new(); + let mut by_package = BTreeMap::new(); + for component in components { + let reference = text(component, "bom-ref")?; + if !references.insert(reference) { + return Err(format!("duplicate SBOM reference: {reference}")); + } + if component.get("type").and_then(Value::as_str) == Some("file") { + text(component, "name")?; + continue; + } + let package = package(component)?; + if !expected.locked.contains(&package) { + return Err(format!( + "unlocked Cargo component: {} {}", + package.name, package.version + )); + } + let purl = text(component, "purl")?; + let expected_purl = format!( + "pkg:cargo/{}@{}", + package.name, + package.version.replace('+', "%2B") + ); + if purl != expected_purl { + return Err(format!("invalid Cargo purl for {}", package.name)); + } + if by_package.insert(package, reference).is_some() { + return Err("duplicate Cargo package identity in SBOM".into()); + } + } + let root_ref = by_package + .get(&expected.root) + .ok_or("SBOM is missing the expected atx version")?; + let mut graph = BTreeMap::new(); + for dependency in array(document, "dependencies")? { + let reference = text(dependency, "ref")?; + if !references.contains(reference) { + return Err(format!("unknown dependency node: {reference}")); + } + let mut edges = BTreeSet::new(); + for edge in array(dependency, "dependsOn")? { + let value = edge + .as_str() + .filter(|text| { + !text.is_empty() && text.len() <= 1024 && !text.chars().any(char::is_control) + }) + .ok_or("dependency references must be bounded printable strings")?; + if !references.contains(value) || value == reference || !edges.insert(value) { + return Err(format!("invalid dependency edge: {reference} -> {value}")); + } + } + if graph.insert(reference, edges).is_some() { + return Err(format!("duplicate dependency node: {reference}")); + } + } + let edges = graph + .get(root_ref) + .ok_or("SBOM has no root dependency graph")?; + if edges.len() != expected.direct.len() { + return Err("SBOM root dependency set differs from the default runtime graph".into()); + } + for package in &expected.direct { + let reference = by_package.get(package).ok_or_else(|| { + format!( + "SBOM is missing locked runtime dependency {} {}", + package.name, package.version + ) + })?; + if !edges.contains(reference) { + return Err(format!("SBOM root does not depend on {}", package.name)); + } + } + Ok(by_package.len()) +} + +/// Load bounded JSON documents so malformed artifacts fail rather than exhaust the gate. +fn read_json(path: &Path) -> Result { + let file = + std::fs::File::open(path).map_err(|error| format!("open {}: {error}", path.display()))?; + if !file + .metadata() + .map_err(|error| error.to_string())? + .is_file() + { + return Err(format!("not a regular JSON file: {}", path.display())); + } + let mut bytes = Vec::new(); + file.take(MAX_DOCUMENT_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if u64::try_from(bytes.len()).map_err(|error| error.to_string())? > MAX_DOCUMENT_BYTES { + return Err("JSON document exceeds the 16 MiB gate limit".into()); + } + serde_json::from_slice(&bytes).map_err(|error| format!("parse {}: {error}", path.display())) +} + +/// Validate a binary SBOM against metadata generated from this exact checkout and target. +pub(super) fn check(path: &Path, target: &str) -> Result { + if !matches!( + target, + "aarch64-apple-darwin" + | "x86_64-apple-darwin" + | "x86_64-unknown-linux-gnu" + | "x86_64-unknown-linux-musl" + | "aarch64-unknown-linux-gnu" + | "aarch64-unknown-linux-musl" + ) { + return Err(format!("unsupported release target: {target}")); + } + let output = std::process::Command::new("cargo") + .args([ + "metadata", + "--locked", + "--format-version", + "1", + "--filter-platform", + target, + ]) + .current_dir(super::workspace_root()?) + .output() + .map_err(|error| format!("cargo metadata: {error}"))?; + if !output.status.success() { + return Err(format!( + "cargo metadata failed: {}", + String::from_utf8_lossy(&output.stderr) + )); + } + let metadata: Value = + serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?; + validate(&read_json(path)?, &expected_inventory(&metadata)?) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used)] + + use serde_json::{Value, json}; + + fn metadata() -> Value { + json!({ + "packages": [ + {"id":"root", "name":"atx", "version":"0.1.1"}, + {"id":"clap", "name":"clap", "version":"4.6.6"}, + {"id":"libc", "name":"libc", "version":"0.2.189"}, + {"id":"test", "name":"proptest", "version":"1.11.0"} + ], + "resolve":{"nodes":[{"id":"root", "deps":[ + {"pkg":"clap", "dep_kinds":[{"kind":null}]}, + {"pkg":"libc", "dep_kinds":[{"kind":null}]}, + {"pkg":"test", "dep_kinds":[{"kind":"dev"}]} + ]}]} + }) + } + + fn document() -> Value { + json!({ + "bomFormat":"CycloneDX", "specVersion":"1.6", "version":1, + "components":[ + {"bom-ref":"root", "name":"atx", "version":"0.1.1", "purl":"pkg:cargo/atx@0.1.1"}, + {"bom-ref":"clap", "name":"clap", "version":"4.6.6", "purl":"pkg:cargo/clap@4.6.6"}, + {"bom-ref":"libc", "name":"libc", "version":"0.2.189", "purl":"pkg:cargo/libc@0.2.189"} + ], + "dependencies":[ + {"ref":"root", "dependsOn":["clap","libc"]}, + {"ref":"clap", "dependsOn":["libc"]}, + {"ref":"libc", "dependsOn":[]} + ] + }) + } + + #[test] + fn binary_inventory_matches_the_locked_runtime_graph() { + let expected = super::expected_inventory(&metadata()).expect("Cargo runtime inventory"); + assert_eq!( + super::validate(&document(), &expected).expect("valid SBOM"), + 3 + ); + } + + #[test] + fn scanner_file_evidence_does_not_replace_the_cargo_root() { + let expected = super::expected_inventory(&metadata()).expect("Cargo runtime inventory"); + let mut doc = document(); + doc["components"] + .as_array_mut() + .expect("components") + .push(json!({ + "bom-ref":"binary-hash", "type":"file", "name":"/atx" + })); + assert_eq!(super::validate(&doc, &expected).expect("file evidence"), 3); + doc["components"][0] = json!({"bom-ref":"root", "type":"file", "name":"atx"}); + assert!(super::validate(&doc, &expected).is_err()); + } + + #[test] + fn incomplete_or_wrong_binary_inventory_is_rejected() { + let expected = super::expected_inventory(&metadata()).expect("Cargo runtime inventory"); + let base = document(); + let mut invalid = Vec::new(); + for value in [ + json!([]), + json!([base["components"][0].clone()]), + json!(null), + ] { + let mut doc = base.clone(); + doc["components"] = value; + invalid.push(doc); + } + for (field, value) in [ + ("name", json!("another-app")), + ("version", json!("0.1.0")), + ("purl", json!("pkg:npm/atx@0.1.1")), + ("bom-ref", json!(null)), + ] { + let mut doc = base.clone(); + doc["components"][0][field] = value; + invalid.push(doc); + } + let mut wrong_version = base.clone(); + wrong_version["components"][1]["version"] = json!("4.0.0"); + invalid.push(wrong_version); + let mut duplicate = base.clone(); + duplicate["components"][1]["bom-ref"] = json!("root"); + invalid.push(duplicate); + for value in [json!([]), json!(null)] { + let mut doc = base.clone(); + doc["dependencies"] = value; + invalid.push(doc); + } + let mut missing_direct = base.clone(); + missing_direct["dependencies"][0]["dependsOn"] = json!(["clap"]); + invalid.push(missing_direct); + let mut dangling = base.clone(); + dangling["dependencies"][1]["dependsOn"] = json!(["unknown"]); + invalid.push(dangling); + let mut controls = base.clone(); + controls["dependencies"][1]["dependsOn"] = json!(["\u{1b}[2J"]); + invalid.push(controls); + let mut wrong_format = base.clone(); + wrong_format["bomFormat"] = json!("SPDX"); + invalid.push(wrong_format); + for doc in invalid { + assert!(super::validate(&doc, &expected).is_err(), "accepted {doc}"); + } + } + + #[test] + fn cargo_graph_requires_one_root_and_resolved_runtime_packages() { + for value in [ + json!(null), + json!({}), + json!({"packages":[],"resolve":null}), + ] { + assert!(super::expected_inventory(&value).is_err()); + } + let mut missing = metadata(); + missing["resolve"]["nodes"][0]["deps"][0]["pkg"] = json!("missing"); + assert!(super::expected_inventory(&missing).is_err()); + let mut empty = metadata(); + empty["resolve"]["nodes"][0]["deps"] = json!([]); + assert!(super::expected_inventory(&empty).is_err()); + let mut kinds = metadata(); + kinds["resolve"]["nodes"][0]["deps"][0]["dep_kinds"] = json!([]); + assert!(super::expected_inventory(&kinds).is_err()); + let mut duplicate = metadata(); + let root = duplicate["packages"][0].clone(); + duplicate["packages"] + .as_array_mut() + .expect("packages") + .push(root); + assert!(super::expected_inventory(&duplicate).is_err()); + } + + #[test] + fn json_file_input_is_regular_valid_and_bounded() { + use std::io::Write; + + struct OwnedFile(std::path::PathBuf); + impl Drop for OwnedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let path = std::env::temp_dir().join(format!("atx-sbom-limit-{}.json", std::process::id())); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .expect("owned JSON fixture"); + let owned = OwnedFile(path); + file.write_all(b"{}").expect("write JSON"); + assert_eq!(super::read_json(&owned.0).expect("read JSON"), json!({})); + file.set_len(super::MAX_DOCUMENT_BYTES + 1) + .expect("oversized sparse JSON"); + assert!( + super::read_json(&owned.0) + .expect_err("bounded input") + .contains("16 MiB") + ); + file.set_len(0).expect("truncate fixture"); + assert!(super::read_json(&owned.0).is_err()); + assert!(super::read_json(&std::env::temp_dir()).is_err()); + assert!(super::check(&owned.0, "unsupported-target").is_err()); + } + + proptest::proptest! { + #[test] + fn arbitrary_json_shapes_do_not_panic(bytes in proptest::collection::vec(proptest::prelude::any::(), 0..4096)) { + if let Ok(value) = serde_json::from_slice::(&bytes) { + let expected = super::expected_inventory(&metadata()).expect("fixture inventory"); + let _ = super::validate(&value, &expected); + let _ = super::expected_inventory(&value); + } + } + } +}