Files
pruefwerk/compliance-agent/tests/finding_migrations.rs
sharang c8af053d9d
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 4m10s
CI / Deploy Agent (push) Successful in 10m54s
fix(semgrep): short finding titles, rule messages shown as Markdown (#529)
2026-10-08 21:23:20 +00:00

176 lines
6.1 KiB
Rust

//! #463: stored findings are rewritten in place, and a rescan of the same
//! tree afterwards finds nothing new. Runs against a live Mongo
//! (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::finding_migrations::{migrate_tenant, Migrated};
use compliance_agent::pipeline::dedup::compute_fingerprint;
use compliance_agent::pipeline::finding_store::RunFindings;
use compliance_agent::pipeline::semgrep;
use compliance_core::models::{Finding, ScanType, Severity};
use mongodb::bson::doc;
const TENANT: &str = "finding-migrations";
const TARGET: &str = "target-1";
/// A semgrep finding as the scanner writes it for `rule` (as reported) at
/// `path:line`, with the given fingerprint.
fn semgrep_finding(rule: &str, fingerprint: String, path: &str, line: u32) -> Finding {
let mut f = Finding::new(
TARGET.into(),
fingerprint,
"semgrep".into(),
ScanType::Sast,
"XML parser resolves external entities".into(),
"XML parser resolves external entities".into(),
Severity::High,
);
f.rule_id = Some(rule.into());
f.file_path = Some(path.into());
f.line_number = Some(line);
f
}
async fn by_fingerprint(db: &Database, fingerprint: &str) -> Finding {
db.findings()
.find_one(doc! { "fingerprint": fingerprint })
.await
.unwrap()
.unwrap()
}
#[tokio::test]
async fn stored_findings_are_migrated_and_a_rescan_finds_nothing_new() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"migrate_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP finding_migrations: no MongoDB reachable at {uri}");
return;
};
let Ok(db) = pool.for_tenant_id(TENANT).await else {
eprintln!("SKIP finding_migrations: MongoDB at {uri} not usable");
return;
};
// Arrange: what the agent stored before #463.
let legacy = |rule: &str, path: &str, line: u32| {
let fp = compute_fingerprint(&[TARGET, rule, path, &line.to_string()]);
semgrep_finding(rule, fp, path, line)
};
let xxe = legacy("tmp.cra-ai-20-csharp-xxe", "src/Xml.cs", 7);
let cred = legacy(
"tmp.cra-ai-8-csharp-hardcoded-credential",
"src/Settings.cs",
12,
);
let older = legacy(
"tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled",
"app.py",
3,
);
let mut control = Finding::new(
TARGET.into(),
"fp-control".into(),
"control-check".into(),
ScanType::CodeReview,
"cra-ai-6: Integritaetspruefung".into(),
"Control cra-ai-6 appears violated (Updates muessen signiert sein) at a.c:1".into(),
Severity::Medium,
);
control.file_path = Some("a.c".into());
// A1: a vendored GitLab rule's whole message as the title.
let message = "The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by\nclient side JavaScript.\n\nExample:\n```\nsomeCookie.HttpOnly = true;\n```\n";
let mut cookie = semgrep_finding(
"gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag",
"fp-cookie".into(),
"src/Web.cs",
4,
);
cookie.title = message.into();
cookie.description = message.into();
db.findings()
.insert_many([xxe.clone(), cred.clone(), older.clone(), control, cookie])
.await
.unwrap();
// Act
let first = migrate_tenant(&db).await.unwrap();
// Assert: ids bare, the tmp. fingerprints untouched, the older one moved
// to what a scan computes, the title spelled right.
assert_eq!(
first,
Migrated {
rule_ids: 3,
fingerprints: 1,
titles: 1,
semgrep_titles: 1,
}
);
let row = by_fingerprint(&db, "fp-cookie").await;
assert_eq!(row.title, "Sensitive cookie without 'HttpOnly' flag");
assert_eq!(row.description, message);
let row = by_fingerprint(&db, &xxe.fingerprint).await;
assert_eq!(row.rule_id.as_deref(), Some("cra-ai-20-csharp-xxe"));
let row = by_fingerprint(&db, &cred.fingerprint).await;
assert_eq!(
row.rule_id.as_deref(),
Some("cra-ai-8-csharp-hardcoded-credential")
);
let moved = semgrep::fingerprint(TARGET, "cra-ai-1-flask-debug-enabled", "app.py", 3);
let row = by_fingerprint(&db, &moved).await;
assert_eq!(row.rule_id.as_deref(), Some("cra-ai-1-flask-debug-enabled"));
let row = by_fingerprint(&db, "fp-control").await;
assert_eq!(row.title, "cra-ai-6: Integritätsprüfung");
assert!(row.description.contains("Updates müssen"));
// A second start changes nothing.
assert_eq!(migrate_tenant(&db).await.unwrap(), Migrated::default());
// A rescan of the unchanged tree reports the same findings, with bare ids
// and whatever prefix semgrep puts in front this time: none is new.
let mut rescan: Vec<Finding> = [
("tmp.cra-ai-20-csharp-xxe", "src/Xml.cs", 7),
(
"cra-ai-8-csharp-hardcoded-credential",
"src/Settings.cs",
12,
),
(
"tmp.compliance-cra-semgrep.cra-ai-1-flask-debug-enabled",
"app.py",
3,
),
]
.into_iter()
.map(|(rule, path, line)| {
let mut f = semgrep_finding(
semgrep::bare_rule_id(rule),
semgrep::fingerprint(TARGET, rule, path, line),
path,
line,
);
f.rule_id = Some(semgrep::bare_rule_id(rule).to_string());
f
})
.collect();
let mut run = RunFindings::new("run-rescan");
run.completed("semgrep");
assert_eq!(run.save_new(&db, &mut rescan).await.unwrap(), 0);
assert_eq!(
db.findings()
.count_documents(doc! { "scanner": "semgrep" })
.await
.unwrap(),
4
);
pool.drop_tenant(TENANT).await.ok();
}