feat(scans): scan uploaded source archives like repositories (#325) (#329)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 3m53s

This commit was merged in pull request #329.
This commit is contained in:
sharang committed 2026-09-23 07:22:05 +00:00
1 parent f90bfcc5c6
commit fe2414a3c0
23 files changed
+281 -60

No files matched your search

+24 -3
View File
@@ -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
+78 -20
View File
@@ -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<u32, AgentError> {
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<Finding> = 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<String, std::path::PathBuf> {
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(
+20
View File
@@ -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.
@@ -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
+36
View File
@@ -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"
}
}
}
+10
View File
@@ -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"
}
}
+15
View File
@@ -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)
+19
View File
@@ -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("<p>Exported for " + req.query.customer + "</p>" + stdout);
});
});
app.listen(8080);
@@ -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"
]
}
@@ -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",
+1 -3
View File
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"toolchain:arduino-cli@"
],
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"toolchain:rustc@1.82.0"
],
+1 -3
View File
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"toolchain:arm-none-eabi-gcc@"
],
+1 -3
View File
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"library:esp-idf@",
"library:espressif/led_strip@2.5.3",
@@ -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@"
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"library:ARM CMSIS Core@",
"library:FreeRTOS@",
+1 -3
View File
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"toolchain:arm-none-eabi-gcc@"
],
@@ -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",
@@ -1,7 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan",
"firmware_sbom"
],
"sbom": [],
@@ -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@",
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"code_scan"
],
"skipped_stages": [],
"sbom": [
"library:cmsis@",
"library:hal_nordic@",
@@ -1,8 +1,6 @@
{
"scan_status": "completed",
"skipped_stages": [
"dast"
],
"skipped_stages": [],
"sbom": [],
"findings": [
"gitleaks:stripe-access-token auth.py:2",
+21
View File
@@ -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"
]
}
}
]
}