diff --git a/compliance-agent/src/pipeline/gitleaks.rs b/compliance-agent/src/pipeline/gitleaks.rs index 9675733..b4ebab1 100644 --- a/compliance-agent/src/pipeline/gitleaks.rs +++ b/compliance-agent/src/pipeline/gitleaks.rs @@ -8,6 +8,18 @@ use crate::pipeline::dedup; pub struct GitleaksScanner; +/// How to point gitleaks at a tree. `detect` walks a git checkout's history; +/// on a directory that is not a checkout it scans **nothing** and reports no +/// leaks — a silent miss — so a plain tree (an uploaded source archive) is +/// scanned with `dir` instead. +fn source_args(repo_path: &Path) -> &'static [&'static str] { + if repo_path.join(".git").exists() { + &["detect", "--source", "."] + } else { + &["dir", "."] + } +} + impl Scanner for GitleaksScanner { fn name(&self) -> &str { "gitleaks" @@ -22,10 +34,8 @@ impl Scanner for GitleaksScanner { let output = tokio::time::timeout( std::time::Duration::from_secs(300), crate::pipeline::tool_cmd::tool("gitleaks", &[]) + .args(source_args(repo_path)) .args([ - "detect", - "--source", - ".", "--report-format", "json", "--report-path", @@ -223,6 +233,17 @@ mod tests { assert_eq!(results[0].rule_id, "generic-secret"); } + #[test] + fn a_plain_tree_is_scanned_as_a_directory() { + let dir = std::env::temp_dir().join(format!("cs-gitleaks-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).expect("mkdir"); + // An uploaded archive is not a checkout: `detect` would scan nothing there. + assert_eq!(source_args(&dir), ["dir", "."]); + std::fs::create_dir_all(dir.join(".git")).expect("mkdir .git"); + assert_eq!(source_args(&dir), ["detect", "--source", "."]); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn severity_mapping_private_key() { // Verify the severity logic from the scan method diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index a176d82..e20bf2a 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -87,6 +87,23 @@ impl PipelineOrchestrator { return Ok(0); } + self.scan_tree(&repo_path, repo, scan_run_id).await + } + + /// The static-analysis stages over a source tree, whatever put it there: a + /// git clone, or an uploaded archive that ingest already unpacked. Git-only + /// work — change detection and the commit watermark — happens around this, + /// never inside it, so an archive gets the same analysis as a repository. + #[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))] + async fn scan_tree( + &self, + tree: &std::path::Path, + repo: &RepoView, + scan_run_id: &str, + ) -> Result { + let repo_id = repo.id.as_ref().map(|id| id.to_hex()).unwrap_or_default(); + let repo_path = tree.to_path_buf(); + let mut all_findings: Vec = Vec::new(); // Stage 1: Semgrep SAST @@ -400,12 +417,6 @@ impl PipelineOrchestrator { // last_scanned_commit watermark are persisted by `finalize_target` after // `run_pipeline` returns. - // Stage 8: DAST (async, optional — only if a DastTarget is configured) - tracing::info!("[{repo_id}] Stage 8: Checking for DAST targets"); - self.update_phase(scan_run_id, ScanPhase::DastScanning) - .await; - self.maybe_trigger_dast(&repo_id, scan_run_id).await; - tracing::info!("[{repo_id}] Scan complete: {new_count} new findings"); Ok(new_count) } @@ -514,7 +525,9 @@ impl PipelineOrchestrator { ); // Ingest + classify (Firmwerk for firmware) and store the detected type. - self.classify_and_store(target, &target_id, scan_run_id) + // The ingested paths are where an uploaded archive was unpacked. + let working_paths = self + .classify_and_store(target, &target_id, scan_run_id) .await; // Provision a DAST target from a LiveUrl artifact so DAST fires for // wizard-created targets, not just migrated ones. @@ -571,17 +584,33 @@ impl PipelineOrchestrator { let n = self.run_pipeline(&repo, scan_run_id).await?; self.finalize_target(target, &repo, n).await?; new_count += n; + self.dast_after_code_scan(&target_id, &plan, scan_run_id) + .await; } - Some(_) => { - // Recorded, not just logged, so an archive upload does not read as - // "scanned, nothing found" (#325). - self.skip_stage( - scan_run_id, - "code_scan", - "SAST, secret and package-SBOM scanning run on git repositories only; \ - uploaded source archives are not scanned yet", - ) - .await; + Some(code) => { + // An uploaded source archive: ingest already unpacked it, so the + // same stages run over that tree. Nothing git-specific applies — + // there is no history to diff and no commit to watermark, so every + // run scans what was uploaded. + match working_paths.get(&code.id) { + Some(tree) => { + let repo = RepoView::from_target(target, code, &self.secrets); + let n = self.scan_tree(tree, &repo, scan_run_id).await?; + self.finalize_target(target, &repo, n).await?; + new_count += n; + self.dast_after_code_scan(&target_id, &plan, scan_run_id) + .await; + } + None => { + self.skip_stage( + scan_run_id, + "code_scan", + "the uploaded archive could not be unpacked, so there was \ + no source tree to scan", + ) + .await; + } + } } None => { // No code to scan. DAST is attempted for a target the matrix @@ -1040,12 +1069,15 @@ impl PipelineOrchestrator { /// Ingest the target's artifacts, classify (Firmwerk for firmware/RTOS/Yocto, /// heuristics otherwise), and store the detected classification on the target. /// Best-effort — never fails the scan. + /// Ingest, classify and store the detected type. Returns where each artifact + /// was ingested (artifact id -> working path), so the caller scans the tree + /// ingest already unpacked instead of unpacking it twice. async fn classify_and_store( &self, target: &OnboardedTarget, target_id: &str, scan_run_id: &str, - ) { + ) -> std::collections::HashMap { self.update_phase(scan_run_id, ScanPhase::Classification) .await; let ctx = @@ -1054,7 +1086,7 @@ impl PipelineOrchestrator { Ok(set) => set, Err(e) => { tracing::warn!(target_id, error = %e, "Unified pipeline: ingest for classification failed"); - return; + return std::collections::HashMap::new(); } }; let working_paths = ingest_set.working_paths(); @@ -1147,6 +1179,24 @@ impl PipelineOrchestrator { } } } + working_paths + } + + /// DAST after the code scan, for a target the matrix plans it for. Gated on + /// the plan: a firmware or embedded target has no web surface, and recording + /// DAST as skipped there would imply it otherwise would have run. + async fn dast_after_code_scan( + &self, + target_id: &str, + plan: &crate::pipeline::plan::ScanPlan, + scan_run_id: &str, + ) { + if !plan.has(ScanType::Dast) { + return; + } + self.update_phase(scan_run_id, ScanPhase::DastScanning) + .await; + self.maybe_trigger_dast(target_id, scan_run_id).await; } /// If the target has a `LiveUrl` artifact and DAST is planned, provision a @@ -1231,12 +1281,20 @@ impl PipelineOrchestrator { ) .await?; + // The commit watermark is a git notion: an uploaded archive has no + // history, and every run scans the bytes that were uploaded. + let Some(code) = target + .code_artifact() + .filter(|c| c.kind == ArtifactKind::GitRepo) + else { + return Ok(()); + }; let repo_path = crate::pipeline::git::clone_dir( std::path::Path::new(&self.config.git_clone_base_path), &self.tenant_id, &repo.name, ); - if let (Ok(sha), Some(code)) = (GitOps::get_head_sha(&repo_path), target.code_artifact()) { + if let Ok(sha) = GitOps::get_head_sha(&repo_path) { self.db .onboarded_targets() .update_one( diff --git a/fixtures/nightly/archive/README.md b/fixtures/nightly/archive/README.md new file mode 100644 index 0000000..fed8eaa --- /dev/null +++ b/fixtures/nightly/archive/README.md @@ -0,0 +1,20 @@ +# Source-archive fixture (#325) + +A small service delivered the way a customer without a git remote delivers one: +a zip of the sources. The harness uploads this directory as a `source_archive` +artifact, and the baseline asserts it gets the same treatment as a repository — +SAST findings, secret detection, a package SBOM from the lockfile, and CVE +matching on it. + +Planted on purpose: + +| Where | What | +|---|---| +| `src/server.js` | a shell command built from request input, and request input echoed into the response | +| `src/auth.py` | MD5 used for a signature check, and `shell=True` on a caller-supplied value | +| `config/service.env` | two expired, made-up credentials (a GitHub PAT and a Slack token shape) | +| `package-lock.json` | `lodash` 4.17.15 and `minimist` 1.2.0, both with published CVEs | + +The credentials are not real and never were: they exist so the secret scanner +has something to find in a tree that is not a git checkout, which it used to +scan as nothing at all. diff --git a/fixtures/nightly/archive/config/service.env b/fixtures/nightly/archive/config/service.env new file mode 100644 index 0000000..bc5098e --- /dev/null +++ b/fixtures/nightly/archive/config/service.env @@ -0,0 +1,6 @@ +# Deployment configuration for the order intake service. +SERVICE_PORT=8080 +LOG_LEVEL=info +# Planted, expired test credential for the scan regression — not a live secret. +GITHUB_TOKEN=ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8 +SLACK_WEBHOOK_TOKEN=xoxb-123456789012-1234567890123-aBcDeFgHiJkLmNoPqRsTuVwX diff --git a/fixtures/nightly/archive/package-lock.json b/fixtures/nightly/archive/package-lock.json new file mode 100644 index 0000000..26a5e12 --- /dev/null +++ b/fixtures/nightly/archive/package-lock.json @@ -0,0 +1,36 @@ +{ + "name": "order-intake", + "version": "1.3.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "order-intake", + "version": "1.3.0", + "dependencies": { + "lodash": "4.17.15", + "minimist": "1.2.0" + } + }, + "node_modules/lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnTdc1sV+jkFHJoLPIQqLNjBBmy1gCG7gnX0SoVv4rsTNzPtUXWFLBLhJKN1RxSiM2S2KJkYiBmB1w==" + }, + "node_modules/minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha512-7Wl+Jz+IGWuSdgsQEJ4JunV0si/iMhg42MnQQG6h1R6TNeVenULnzMPErO8nH4tHpLBkelywZubNiXcJgtOlBw==" + } + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz" + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz" + } + } +} diff --git a/fixtures/nightly/archive/package.json b/fixtures/nightly/archive/package.json new file mode 100644 index 0000000..14a78c2 --- /dev/null +++ b/fixtures/nightly/archive/package.json @@ -0,0 +1,10 @@ +{ + "name": "order-intake", + "version": "1.3.0", + "private": true, + "description": "Order intake service shipped as a source archive (no git remote).", + "dependencies": { + "lodash": "4.17.15", + "minimist": "1.2.0" + } +} diff --git a/fixtures/nightly/archive/src/auth.py b/fixtures/nightly/archive/src/auth.py new file mode 100644 index 0000000..b12dfec --- /dev/null +++ b/fixtures/nightly/archive/src/auth.py @@ -0,0 +1,15 @@ +"""Token verification for the order intake service.""" + +import hashlib +import subprocess + + +def verify(token: str, signature: str) -> bool: + # Weak hash for a signature check. + digest = hashlib.md5(token.encode()).hexdigest() + return digest == signature + + +def rotate_keys(key_id: str) -> None: + # Shell invocation built from a caller-supplied value. + subprocess.call("rotate-key --id " + key_id, shell=True) diff --git a/fixtures/nightly/archive/src/server.js b/fixtures/nightly/archive/src/server.js new file mode 100644 index 0000000..f00e125 --- /dev/null +++ b/fixtures/nightly/archive/src/server.js @@ -0,0 +1,19 @@ +// Order intake HTTP service. Planted issues, for the scan regression: +// a command built from request input, and a reflected response. +const express = require("express"); +const { exec } = require("child_process"); + +const app = express(); + +app.get("/orders/export", (req, res) => { + // Command injection: the customer id goes into a shell command unquoted. + exec("/usr/local/bin/export-orders --customer " + req.query.customer, (err, stdout) => { + if (err) { + return res.status(500).send("export failed"); + } + // Reflected cross-site scripting: request input echoed into the response. + res.send("

Exported for " + req.query.customer + "

" + stdout); + }); +}); + +app.listen(8080); diff --git a/fixtures/nightly/baselines/archive-order-intake.json b/fixtures/nightly/baselines/archive-order-intake.json new file mode 100644 index 0000000..160ec30 --- /dev/null +++ b/fixtures/nightly/baselines/archive-order-intake.json @@ -0,0 +1,32 @@ +{ + "scan_status": "completed", + "skipped_stages": [], + "sbom": [ + "npm:lodash@4.17.15", + "npm:minimist@1.2.0", + "npm:order-intake@1.3.0" + ], + "findings": [ + "gitleaks:github-pat service.env:5", + "gitleaks:slack-bot-token service.env:6", + "semgrep:cra-ai-7-weak-password-hash auth.py:9" + ], + "cves": [ + "GHSA-29mw-wpgm-hmr9", + "GHSA-35jh-r3h4-6jhm", + "GHSA-f23m-r3pf-42rh", + "GHSA-p6mc-m468-83gw", + "GHSA-r5fr-rjxr-66jc", + "GHSA-vh95-rmgr-6w4m", + "GHSA-xvch-5gv4-984h", + "GHSA-xxjr-mmjv-4gpg" + ], + "registry_rules": [ + "generic.secrets.security.detected-github-token.detected-github-token", + "javascript.express.security.audit.express-check-csurf-middleware-usage.express-check-csurf-middleware-usage", + "javascript.express.security.audit.xss.direct-response-write.direct-response-write", + "javascript.express.security.injection.raw-html-format.raw-html-format", + "javascript.lang.security.detect-child-process.detect-child-process", + "python.lang.security.audit.subprocess-shell-true.subprocess-shell-true" + ] +} diff --git a/fixtures/nightly/baselines/firmware-zephyr-example.json b/fixtures/nightly/baselines/firmware-zephyr-example.json index 2ffced7..0203aa7 100644 --- a/fixtures/nightly/baselines/firmware-zephyr-example.json +++ b/fixtures/nightly/baselines/firmware-zephyr-example.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "dast" - ], + "skipped_stages": [], "sbom": [ "github:actions/checkout@v7.0.1", "github:actions/configure-pages@v6.0.0", diff --git a/fixtures/nightly/baselines/fw-arduino.json b/fixtures/nightly/baselines/fw-arduino.json index f2ad394..4dce252 100644 --- a/fixtures/nightly/baselines/fw-arduino.json +++ b/fixtures/nightly/baselines/fw-arduino.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "toolchain:arduino-cli@" ], diff --git a/fixtures/nightly/baselines/fw-cargo-embedded.json b/fixtures/nightly/baselines/fw-cargo-embedded.json index 6102d80..4900dd9 100644 --- a/fixtures/nightly/baselines/fw-cargo-embedded.json +++ b/fixtures/nightly/baselines/fw-cargo-embedded.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "toolchain:rustc@1.82.0" ], diff --git a/fixtures/nightly/baselines/fw-cmake.json b/fixtures/nightly/baselines/fw-cmake.json index 4efc5ed..2f6a7ee 100644 --- a/fixtures/nightly/baselines/fw-cmake.json +++ b/fixtures/nightly/baselines/fw-cmake.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "toolchain:arm-none-eabi-gcc@" ], diff --git a/fixtures/nightly/baselines/fw-espidf.json b/fixtures/nightly/baselines/fw-espidf.json index 2c17451..745f597 100644 --- a/fixtures/nightly/baselines/fw-espidf.json +++ b/fixtures/nightly/baselines/fw-espidf.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "library:esp-idf@", "library:espressif/led_strip@2.5.3", diff --git a/fixtures/nightly/baselines/fw-freertos-cmake.json b/fixtures/nightly/baselines/fw-freertos-cmake.json index 5d76ec9..6a62dd6 100644 --- a/fixtures/nightly/baselines/fw-freertos-cmake.json +++ b/fixtures/nightly/baselines/fw-freertos-cmake.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "library:freertos_kernel@V11.1.0", "toolchain:arm-none-eabi-gcc@" diff --git a/fixtures/nightly/baselines/fw-freertos-lostbuild.json b/fixtures/nightly/baselines/fw-freertos-lostbuild.json index 8e649e4..af8bc05 100644 --- a/fixtures/nightly/baselines/fw-freertos-lostbuild.json +++ b/fixtures/nightly/baselines/fw-freertos-lostbuild.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "library:ARM CMSIS Core@", "library:FreeRTOS@", diff --git a/fixtures/nightly/baselines/fw-make.json b/fixtures/nightly/baselines/fw-make.json index 4efc5ed..2f6a7ee 100644 --- a/fixtures/nightly/baselines/fw-make.json +++ b/fixtures/nightly/baselines/fw-make.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "toolchain:arm-none-eabi-gcc@" ], diff --git a/fixtures/nightly/baselines/fw-platformio.json b/fixtures/nightly/baselines/fw-platformio.json index 1d3e4ca..a74f99d 100644 --- a/fixtures/nightly/baselines/fw-platformio.json +++ b/fixtures/nightly/baselines/fw-platformio.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "library:bblanchon/ArduinoJson@7.0.4", "library:espressif32@6.5.0", diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index a193803..c3201d9 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -1,7 +1,6 @@ { "scan_status": "completed", "skipped_stages": [ - "code_scan", "firmware_sbom" ], "sbom": [], diff --git a/fixtures/nightly/baselines/fw-zephyr-example-pinned.json b/fixtures/nightly/baselines/fw-zephyr-example-pinned.json index 200f568..0203aa7 100644 --- a/fixtures/nightly/baselines/fw-zephyr-example-pinned.json +++ b/fixtures/nightly/baselines/fw-zephyr-example-pinned.json @@ -1,9 +1,15 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ + "github:actions/checkout@v7.0.1", + "github:actions/configure-pages@v6.0.0", + "github:actions/deploy-pages@v5.0.0", + "github:actions/setup-python@v7.0.0", + "github:actions/upload-artifact@v7.0.1", + "github:actions/upload-pages-artifact@v5.0.0", + "github:zephyrproject-rtos/action-dco@v1.0.0", + "github:zephyrproject-rtos/action-zephyr-setup@v1.0.15", "library:cmsis_6@", "library:hal_nordic@", "library:hal_stm32@", diff --git a/fixtures/nightly/baselines/fw-zephyr-pinned.json b/fixtures/nightly/baselines/fw-zephyr-pinned.json index 769fafe..527b667 100644 --- a/fixtures/nightly/baselines/fw-zephyr-pinned.json +++ b/fixtures/nightly/baselines/fw-zephyr-pinned.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "code_scan" - ], + "skipped_stages": [], "sbom": [ "library:cmsis@", "library:hal_nordic@", diff --git a/fixtures/nightly/baselines/git-cra-vuln-demo.json b/fixtures/nightly/baselines/git-cra-vuln-demo.json index 824a8b6..9b09cd1 100644 --- a/fixtures/nightly/baselines/git-cra-vuln-demo.json +++ b/fixtures/nightly/baselines/git-cra-vuln-demo.json @@ -1,8 +1,6 @@ { "scan_status": "completed", - "skipped_stages": [ - "dast" - ], + "skipped_stages": [], "sbom": [], "findings": [ "gitleaks:stripe-access-token auth.py:2", diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index c720833..a40f6f5 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -263,6 +263,27 @@ "source_ref": "registry.example.com/pump-ctl:1.4.2" } ] + }, + { + "key": "archive-order-intake", + "name": "Source archive (no git remote)", + "target_type": "backend_service", + "description": "A service delivered as a zip of its sources, the way a customer without a git remote delivers one. It must get the same treatment as a repository: SAST, secret detection, a package SBOM from the lockfile and CVE matching (#325).", + "artifacts": [ + { + "kind": "source_archive", + "upload": "fixtures/nightly/archive" + } + ], + "expect": { + "min_sbom_components": 3, + "sast_rule_ids": [ + "github-pat", + "slack-bot-token", + "python.lang.security.audit.subprocess-shell-true.subprocess-shell-true", + "javascript.lang.security.detect-child-process.detect-child-process" + ] + } } ] }