From 7e3df3c44d89ee7fc6d8c27da25bc8e4ee8bd5f9 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:34:50 +0000 Subject: [PATCH 1/3] Port scanner caller contract check from Ruby to Rust --- scripts/check-scanner-caller.rb | 52 ------ scripts/check-scanner-caller/Cargo.lock | 101 +++++++++++ scripts/check-scanner-caller/Cargo.toml | 10 ++ scripts/check-scanner-caller/src/main.rs | 167 ++++++++++++++++++ scripts/tests/scanner-caller-contract-test.sh | 13 +- 5 files changed, 287 insertions(+), 56 deletions(-) delete mode 100644 scripts/check-scanner-caller.rb create mode 100644 scripts/check-scanner-caller/Cargo.lock create mode 100644 scripts/check-scanner-caller/Cargo.toml create mode 100644 scripts/check-scanner-caller/src/main.rs diff --git a/scripts/check-scanner-caller.rb b/scripts/check-scanner-caller.rb deleted file mode 100644 index 1d329c26..00000000 --- a/scripts/check-scanner-caller.rb +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env ruby -# SPDX-License-Identifier: MPL-2.0 -# Fail closed on changes to the fleet scanner's deployed security contract. -require 'psych' - -path = ARGV.fetch(0, '.github/workflows/secret-scanner.yml') -expected = 'hyperpolymath/proven-cicd-and-workflows/.github/workflows/secret-scanner-reusable.yml@1fd5e6371a50f0fc3687206a5adca0cdf7b39aa6' - -# Validate a Psych node and its descendants before loading the workflow. -# Raises RuntimeError for aliases, non-scalar mapping keys, or duplicate keys -# within a mapping. The caller reports these failures and exits with status 1. -def validate_nodes(node) - raise 'YAML aliases are not supported' if node.is_a?(Psych::Nodes::Alias) - if node.is_a?(Psych::Nodes::Mapping) - keys = node.children.each_slice(2).map do |key, _value| - raise 'non-scalar YAML key' unless key.is_a?(Psych::Nodes::Scalar) - key.value - end - raise 'duplicate YAML key' unless keys.uniq.length == keys.length - end - node.children&.each { |child| validate_nodes(child) } -end - -# Require Ruby equality with the reviewed value; returns nil on success. -# Raises RuntimeError on mismatch, using label to identify the contract field. -# The caller reports the failure and exits with status 1. -def require_equal(actual, expected, label) - raise "#{label} does not match the reviewed contract" unless actual == expected -end - -begin - tree = Psych.parse_file(path) - raise 'empty YAML' unless tree - validate_nodes(tree) - workflow = Psych.safe_load_file(path, aliases: false) - raise 'workflow must be a mapping' unless workflow.is_a?(Hash) - # Psych implements YAML 1.1, where the unquoted `on` key resolves to true. - events = workflow.key?('on') ? workflow['on'] : workflow[true] - require_equal(events, { 'pull_request' => nil, 'push' => { 'branches' => ['main'] } }, 'triggers') - require_equal(workflow['permissions'], { 'contents' => 'read' }, 'workflow permissions') - jobs = workflow['jobs'] - raise 'only the scan job is expected' unless jobs.is_a?(Hash) && jobs.keys == ['scan'] - scan = jobs.fetch('scan') - raise 'unexpected scan job fields' unless scan.is_a?(Hash) && scan.keys.sort == %w[permissions uses with] - require_equal(scan['permissions'], { 'contents' => 'read' }, 'job permissions') - require_equal(scan['uses'], expected, 'suite pin') - require_equal(scan['with'], { 'fast-pr' => false }, 'scan policy') - puts 'scanner caller contract: exact suite pin, full-history policy, triggers, least privilege and no secrets verified' -rescue StandardError => e - warn "scanner caller contract: #{e.message}" - exit 1 -end diff --git a/scripts/check-scanner-caller/Cargo.lock b/scripts/check-scanner-caller/Cargo.lock new file mode 100644 index 00000000..47bed99e --- /dev/null +++ b/scripts/check-scanner-caller/Cargo.lock @@ -0,0 +1,101 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "check-scanner-caller" +version = "0.1.0" +dependencies = [ + "yaml-rust2", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "yaml-rust2" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a8af4469040402b7fe43c26575bab9a3069f0717c4a2931ecf4fb8728ee4cec" +dependencies = [ + "arraydeque", + "encoding_rs", + "hashlink", +] diff --git a/scripts/check-scanner-caller/Cargo.toml b/scripts/check-scanner-caller/Cargo.toml new file mode 100644 index 00000000..508e5d88 --- /dev/null +++ b/scripts/check-scanner-caller/Cargo.toml @@ -0,0 +1,10 @@ +# SPDX-License-Identifier: MPL-2.0 +[package] +name = "check-scanner-caller" +version = "0.1.0" +edition = "2021" +publish = false +description = "Fail closed on changes to the fleet scanner's deployed security contract." + +[dependencies] +yaml-rust2 = "0.13.2" diff --git a/scripts/check-scanner-caller/src/main.rs b/scripts/check-scanner-caller/src/main.rs new file mode 100644 index 00000000..de771aa9 --- /dev/null +++ b/scripts/check-scanner-caller/src/main.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Fail closed on changes to the fleet scanner's deployed security contract. +//! +//! Usage: check-scanner-caller [WORKFLOW] (default: .github/workflows/secret-scanner.yml) +//! Exits 0 when the caller matches the reviewed contract, 1 otherwise. + +use std::collections::HashSet; +use std::process::ExitCode; + +use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser}; +use yaml_rust2::scanner::Marker; +use yaml_rust2::{Yaml, YamlLoader}; + +const EXPECTED_PIN: &str = "hyperpolymath/proven-cicd-and-workflows/.github/workflows/secret-scanner-reusable.yml@1fd5e6371a50f0fc3687206a5adca0cdf7b39aa6"; + +/// Walks parser events before loading. Rejects aliases, non-scalar mapping +/// keys and duplicate keys within a mapping. Keeps the first error only. +#[derive(Default)] +struct Validator { + frames: Vec, + error: Option, +} + +enum Frame { + Seq, + Map { keys: HashSet, expect_key: bool }, +} + +impl Validator { + fn fail(&mut self, msg: &str) { + if self.error.is_none() { + self.error = Some(msg.to_string()); + } + } + + /// Called at the start of every node. `scalar` is Some(text) for a scalar. + fn enter_node(&mut self, scalar: Option<&str>) { + let mut problem: Option<&'static str> = None; + if let Some(Frame::Map { keys, expect_key }) = self.frames.last_mut() { + if *expect_key { + match scalar { + Some(text) => { + if !keys.insert(text.to_string()) { + problem = Some("duplicate YAML key"); + } + } + None => problem = Some("non-scalar YAML key"), + } + } + *expect_key = !*expect_key; + } + if let Some(p) = problem { + self.fail(p); + } + } +} + +impl MarkedEventReceiver for Validator { + fn on_event(&mut self, ev: Event, _mark: Marker) { + if self.error.is_some() { + return; + } + match ev { + Event::Alias(_) => self.fail("YAML aliases are not supported"), + Event::Scalar(text, ..) => self.enter_node(Some(&text)), + Event::SequenceStart(..) => { + self.enter_node(None); + self.frames.push(Frame::Seq); + } + Event::MappingStart(..) => { + self.enter_node(None); + self.frames.push(Frame::Map { keys: HashSet::new(), expect_key: true }); + } + Event::SequenceEnd | Event::MappingEnd => { + self.frames.pop(); + } + _ => {} + } + } +} + +/// Order-insensitive structural equality. Scalars must match exactly, so +/// `false` does not equal `"false"`. +fn same(a: &Yaml, b: &Yaml) -> bool { + match (a, b) { + (Yaml::Hash(x), Yaml::Hash(y)) => { + x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same(v, w))) + } + (Yaml::Array(x), Yaml::Array(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)) + } + _ => a == b, + } +} + +fn expected(text: &str) -> Yaml { + YamlLoader::load_from_str(text) + .ok() + .and_then(|mut docs| if docs.is_empty() { None } else { Some(docs.remove(0)) }) + .expect("built-in contract literal parses") +} + +fn require_equal(actual: Option<&Yaml>, want: &Yaml, label: &str) -> Result<(), String> { + match actual { + Some(a) if same(a, want) => Ok(()), + _ => Err(format!("{label} does not match the reviewed contract")), + } +} + +fn check(path: &str) -> Result<(), String> { + let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; + + let mut validator = Validator::default(); + let mut parser = Parser::new_from_str(&text); + parser.load(&mut validator, true).map_err(|e| e.to_string())?; + if let Some(e) = validator.error { + return Err(e); + } + + let docs = YamlLoader::load_from_str(&text).map_err(|e| e.to_string())?; + let workflow = docs.first().ok_or("empty YAML")?; + let map = workflow.as_hash().ok_or("workflow must be a mapping")?; + let get = |m: &yaml_rust2::yaml::Hash, k: &str| m.get(&Yaml::String(k.to_string())).cloned(); + + // Quoted or unquoted, the key is the string "on" here. A YAML 1.1 loader + // would read a bare `on` as true, so accept that spelling too. + let events = get(map, "on").or_else(|| map.get(&Yaml::Boolean(true)).cloned()); + require_equal( + events.as_ref(), + &expected("pull_request:\npush:\n branches: [main]\n"), + "triggers", + )?; + let perms = expected("contents: read\n"); + require_equal(get(map, "permissions").as_ref(), &perms, "workflow permissions")?; + + let jobs = get(map, "jobs") + .and_then(|j| j.into_hash()) + .filter(|j| j.len() == 1 && j.contains_key(&Yaml::String("scan".into()))) + .ok_or("only the scan job is expected")?; + let scan = get(&jobs, "scan") + .and_then(|s| s.into_hash()) + .filter(|s| { + let mut keys: Vec<&str> = s.keys().filter_map(|k| k.as_str()).collect(); + keys.sort_unstable(); + s.len() == 3 && keys == ["permissions", "uses", "with"] + }) + .ok_or("unexpected scan job fields")?; + + require_equal(get(&scan, "permissions").as_ref(), &perms, "job permissions")?; + require_equal(get(&scan, "uses").as_ref(), &Yaml::String(EXPECTED_PIN.into()), "suite pin")?; + require_equal(get(&scan, "with").as_ref(), &expected("fast-pr: false\n"), "scan policy")?; + Ok(()) +} + +fn main() -> ExitCode { + let path = std::env::args().nth(1).unwrap_or_else(|| ".github/workflows/secret-scanner.yml".into()); + match check(&path) { + Ok(()) => { + println!("scanner caller contract: exact suite pin, full-history policy, triggers, least privilege and no secrets verified"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("scanner caller contract: {e}"); + ExitCode::FAILURE + } + } +} \ No newline at end of file diff --git a/scripts/tests/scanner-caller-contract-test.sh b/scripts/tests/scanner-caller-contract-test.sh index cba42e16..71f21d25 100644 --- a/scripts/tests/scanner-caller-contract-test.sh +++ b/scripts/tests/scanner-caller-contract-test.sh @@ -5,12 +5,17 @@ root=$(cd "$(dirname "$0")/../.." && pwd) tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT wf="$tmp/scanner.yml" -check="$root/scripts/check-scanner-caller.rb" +# Build the Rust checker unless a prebuilt one is supplied. +check=${CHECK_SCANNER_CALLER:-} +if [ -z "$check" ]; then + cargo build --quiet --locked --release --manifest-path "$root/scripts/check-scanner-caller/Cargo.toml" + check="${CARGO_TARGET_DIR:-$root/scripts/check-scanner-caller/target}/release/check-scanner-caller" +fi cp "$root/.github/workflows/secret-scanner.yml" "$wf" -ruby "$check" "$wf" +"$check" "$wf" reject() { local name=$1 - if ruby "$check" "$wf" >/dev/null 2>&1; then + if "$check" "$wf" >/dev/null 2>&1; then echo "FAIL: accepted $name" >&2; exit 1 fi echo "PASS: rejected $name" @@ -42,5 +47,5 @@ printf '[]\n' > "$wf"; reject 'sequence workflow' # Quoting the YAML 1.1 boolean-looking key must preserve GitHub's semantics. sed -i 's/^on:/"on":/' "$wf" -ruby "$check" "$wf" +"$check" "$wf" echo 'scanner caller parser and policy boundary controls passed' From 0c4fdcc8537021ef26b1469924eb74471eb98dc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:38:00 +0000 Subject: [PATCH 2/3] fix(ci): gate scripts/check-scanner-caller with rust-ci and Dependabot Register the crate in rust-proven.yml (rust-ci per crate) and the pinned reusable sources record, and add its directory to the Cargo Dependabot entry, closing both review findings on this PR. --- .github/dependabot.yml | 1 + .github/workflows/rust-proven.yml | 8 ++++++++ scripts/lib/pinned-reusable-sources.json | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 3412ac1b..866263f2 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -32,6 +32,7 @@ "/bots/accessibilitybot", "/bots/cipherbot", "/bots/panicbot", + "/scripts/check-scanner-caller", ], schedule: { interval: "weekly", diff --git a/.github/workflows/rust-proven.yml b/.github/workflows/rust-proven.yml index 7b564961..c60acfcf 100644 --- a/.github/workflows/rust-proven.yml +++ b/.github/workflows/rust-proven.yml @@ -96,3 +96,11 @@ jobs: uses: hyperpolymath/proven-cicd-and-workflows/.github/workflows/rust-ci.yml@50a443f01b1b85e4957b893a6f1a0ed2e8a52459 with: working_directory: idris-dependents + + rust-ci-check-scanner-caller: + name: rust-ci (scripts/check-scanner-caller) + permissions: + contents: read + uses: hyperpolymath/proven-cicd-and-workflows/.github/workflows/rust-ci.yml@50a443f01b1b85e4957b893a6f1a0ed2e8a52459 + with: + working_directory: scripts/check-scanner-caller diff --git a/scripts/lib/pinned-reusable-sources.json b/scripts/lib/pinned-reusable-sources.json index 0c24e39d..26762c5a 100644 --- a/scripts/lib/pinned-reusable-sources.json +++ b/scripts/lib/pinned-reusable-sources.json @@ -795,6 +795,11 @@ "workflow": ".github/workflows/rust-proven.yml", "job": "rust-ci-idris-dependents", "line": 96 + }, + { + "workflow": ".github/workflows/rust-proven.yml", + "job": "rust-ci-check-scanner-caller", + "line": 104 } ], "uses": [ From 5e36723da31c57c3743755f70565c2e6c50926fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:45:53 +0000 Subject: [PATCH 3/3] fix(ci): make check-scanner-caller pass rustfmt, rustdoc and the binary-only doctest gate Run cargo fmt, escape the bracketed usage text in the crate doc comment, and set doctests: false for the binary-only crate in rust-proven.yml. --- .github/workflows/rust-proven.yml | 2 + scripts/check-scanner-caller/src/main.rs | 54 +++++++++++++++++++----- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/.github/workflows/rust-proven.yml b/.github/workflows/rust-proven.yml index c60acfcf..3fba1845 100644 --- a/.github/workflows/rust-proven.yml +++ b/.github/workflows/rust-proven.yml @@ -104,3 +104,5 @@ jobs: uses: hyperpolymath/proven-cicd-and-workflows/.github/workflows/rust-ci.yml@50a443f01b1b85e4957b893a6f1a0ed2e8a52459 with: working_directory: scripts/check-scanner-caller + # Binary-only crate: `cargo test --doc` has no library to test. + doctests: false diff --git a/scripts/check-scanner-caller/src/main.rs b/scripts/check-scanner-caller/src/main.rs index de771aa9..388d1970 100644 --- a/scripts/check-scanner-caller/src/main.rs +++ b/scripts/check-scanner-caller/src/main.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 //! Fail closed on changes to the fleet scanner's deployed security contract. //! -//! Usage: check-scanner-caller [WORKFLOW] (default: .github/workflows/secret-scanner.yml) +//! Usage: check-scanner-caller \[WORKFLOW\] (default: .github/workflows/secret-scanner.yml) //! Exits 0 when the caller matches the reviewed contract, 1 otherwise. use std::collections::HashSet; @@ -23,7 +23,10 @@ struct Validator { enum Frame { Seq, - Map { keys: HashSet, expect_key: bool }, + Map { + keys: HashSet, + expect_key: bool, + }, } impl Validator { @@ -69,7 +72,10 @@ impl MarkedEventReceiver for Validator { } Event::MappingStart(..) => { self.enter_node(None); - self.frames.push(Frame::Map { keys: HashSet::new(), expect_key: true }); + self.frames.push(Frame::Map { + keys: HashSet::new(), + expect_key: true, + }); } Event::SequenceEnd | Event::MappingEnd => { self.frames.pop(); @@ -96,7 +102,13 @@ fn same(a: &Yaml, b: &Yaml) -> bool { fn expected(text: &str) -> Yaml { YamlLoader::load_from_str(text) .ok() - .and_then(|mut docs| if docs.is_empty() { None } else { Some(docs.remove(0)) }) + .and_then(|mut docs| { + if docs.is_empty() { + None + } else { + Some(docs.remove(0)) + } + }) .expect("built-in contract literal parses") } @@ -112,7 +124,9 @@ fn check(path: &str) -> Result<(), String> { let mut validator = Validator::default(); let mut parser = Parser::new_from_str(&text); - parser.load(&mut validator, true).map_err(|e| e.to_string())?; + parser + .load(&mut validator, true) + .map_err(|e| e.to_string())?; if let Some(e) = validator.error { return Err(e); } @@ -131,7 +145,11 @@ fn check(path: &str) -> Result<(), String> { "triggers", )?; let perms = expected("contents: read\n"); - require_equal(get(map, "permissions").as_ref(), &perms, "workflow permissions")?; + require_equal( + get(map, "permissions").as_ref(), + &perms, + "workflow permissions", + )?; let jobs = get(map, "jobs") .and_then(|j| j.into_hash()) @@ -146,14 +164,28 @@ fn check(path: &str) -> Result<(), String> { }) .ok_or("unexpected scan job fields")?; - require_equal(get(&scan, "permissions").as_ref(), &perms, "job permissions")?; - require_equal(get(&scan, "uses").as_ref(), &Yaml::String(EXPECTED_PIN.into()), "suite pin")?; - require_equal(get(&scan, "with").as_ref(), &expected("fast-pr: false\n"), "scan policy")?; + require_equal( + get(&scan, "permissions").as_ref(), + &perms, + "job permissions", + )?; + require_equal( + get(&scan, "uses").as_ref(), + &Yaml::String(EXPECTED_PIN.into()), + "suite pin", + )?; + require_equal( + get(&scan, "with").as_ref(), + &expected("fast-pr: false\n"), + "scan policy", + )?; Ok(()) } fn main() -> ExitCode { - let path = std::env::args().nth(1).unwrap_or_else(|| ".github/workflows/secret-scanner.yml".into()); + let path = std::env::args() + .nth(1) + .unwrap_or_else(|| ".github/workflows/secret-scanner.yml".into()); match check(&path) { Ok(()) => { println!("scanner caller contract: exact suite pin, full-history policy, triggers, least privilege and no secrets verified"); @@ -164,4 +196,4 @@ fn main() -> ExitCode { ExitCode::FAILURE } } -} \ No newline at end of file +}