//! #491: findings are keyed by the code they flag, not its line. A row an //! earlier run stored under the line-based fingerprint is taken over by the //! first scan after the change (same id, so the same tracker issue, status //! and triage), and a line added above a finding later neither closes it nor //! creates a new one. 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::pipeline::dedup::compute_fingerprint; use compliance_agent::pipeline::finding_store::RunFindings; use compliance_core::models::{Finding, FindingStatus, ScanType, Severity}; use mongodb::bson::doc; const TARGET: &str = "target-1"; /// A semgrep finding at `file:line`, fingerprinted by line as before #491. fn semgrep(file: &str, line: u32) -> Finding { let mut f = Finding::new( TARGET.into(), compute_fingerprint(&[ TARGET, "cra-ai-20-python-shell-command", file, &line.to_string(), ]), "semgrep".into(), ScanType::Sast, "Shell command built from a variable".into(), "d".into(), Severity::High, ); f.rule_id = Some("cra-ai-20-python-shell-command".into()); f.file_path = Some(file.into()); f.line_number = Some(line); f } /// One scan of `tree` reporting `findings`, as the pipeline saves it. async fn scan(db: &Database, tree: &std::path::Path, mut findings: Vec) -> RunFindings { let mut run = RunFindings::new("run").with_tree(tree.to_path_buf()); run.completed("semgrep"); run.label(&mut findings); run.save_new(db, &mut findings).await.unwrap(); run.write_back(db, &mut findings).await.unwrap(); run.resolve_missing(db, TARGET, &[]).await.unwrap(); run } async fn rows(db: &Database) -> Vec { use futures_util::TryStreamExt; let mut rows: Vec = db .findings() .find(doc! { "repo_id": TARGET }) .await .unwrap() .try_collect() .await .unwrap(); rows.sort_by(|a, b| a.file_path.cmp(&b.file_path)); rows } #[tokio::test] async fn findings_survive_the_new_fingerprint_and_lines_moving() { let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let prefix = format!( "contentfp_{}", &uuid::Uuid::new_v4().simple().to_string()[..10] ); let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { eprintln!("SKIP content_fingerprints: no MongoDB reachable at {uri}"); return; }; let tenant = "content-fingerprints"; let Ok(db) = pool.for_tenant_id(tenant).await else { eprintln!("SKIP content_fingerprints: MongoDB at {uri} not usable"); return; }; let tree = std::env::temp_dir().join(format!("cs-contentfp-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&tree).unwrap(); std::fs::write(tree.join("a.py"), "import os\nos.system(cmd)\n").unwrap(); std::fs::write(tree.join("b.py"), "subprocess.call(cmd, shell=True)\n").unwrap(); // Arrange: what a scan before #491 stored, line-keyed: one finding a // person marked a false positive, one still open. let mut decided = semgrep("a.py", 2); decided.status = FindingStatus::FalsePositive; let open = semgrep("b.py", 1); db.findings().insert_many([&decided, &open]).await.unwrap(); let before = rows(&db).await; // Act: the first scan after the change. scan(&db, &tree, vec![semgrep("a.py", 2), semgrep("b.py", 1)]).await; // Assert: the same rows (ids, so tracker issues), now content-keyed, // with their status and the old fingerprint on record. let adopted = rows(&db).await; assert_eq!(adopted.len(), 2, "no new rows"); for (old, new) in before.iter().zip(&adopted) { assert_eq!(old.id, new.id); assert_eq!(old.status, new.status); assert_ne!(old.fingerprint, new.fingerprint); assert_eq!( new.legacy_fingerprints, std::slice::from_ref(&old.fingerprint) ); } // Act: lines added above both findings, then another scan. std::fs::write( tree.join("a.py"), "import os\nimport sys\n\nos.system(cmd)\n", ) .unwrap(); std::fs::write( tree.join("b.py"), "# run it\nsubprocess.call( cmd, shell=True )\n", ) .unwrap(); let run = scan(&db, &tree, vec![semgrep("a.py", 4), semgrep("b.py", 2)]).await; // Assert: nothing new, nothing closed or reopened, the lines follow. let moved = rows(&db).await; assert_eq!(run.new_count(), 0); assert!(run.status_changed().is_empty(), "no close/reopen churn"); assert_eq!(moved[0].status, FindingStatus::FalsePositive); assert_eq!(moved[1].status, FindingStatus::Open); assert_eq!(moved[0].line_number, Some(4)); assert_eq!(moved[1].line_number, Some(2)); assert_eq!(moved[0].fingerprint, adopted[0].fingerprint); let _ = std::fs::remove_dir_all(&tree); pool.drop_tenant(tenant).await.ok(); }