diff --git a/compliance-agent/src/api/handlers/dto.rs b/compliance-agent/src/api/handlers/dto.rs index 5231ead..aa8ed80 100644 --- a/compliance-agent/src/api/handlers/dto.rs +++ b/compliance-agent/src/api/handlers/dto.rs @@ -65,6 +65,10 @@ pub struct FindingsFilter { pub status: Option, #[serde(default)] pub q: Option, + /// Only the findings in one app variant (`Tablet App`): its own, and the + /// groups listing a place in it. + #[serde(default)] + pub variant: Option, #[serde(default)] pub sort_by: Option, #[serde(default)] diff --git a/compliance-agent/src/api/handlers/findings.rs b/compliance-agent/src/api/handlers/findings.rs index 53e5632..3b4e9be 100644 --- a/compliance-agent/src/api/handlers/findings.rs +++ b/compliance-agent/src/api/handlers/findings.rs @@ -47,6 +47,16 @@ pub async fn list_findings( } } + if let Some(variant) = filter.variant.as_deref().filter(|v| !v.is_empty()) { + query.insert( + "$and", + mongodb::bson::bson!([{ "$or": [ + { "variant": variant }, + { "occurrences.variant": variant }, + ] }]), + ); + } + // Dynamic sort let sort_field = super::dto::finding_sort_field(filter.sort_by.as_deref()); let sort_dir: i32 = match filter.sort_order.as_deref() { @@ -115,6 +125,46 @@ fn severity_rank() -> mongodb::bson::Document { } } } +/// The query of [`list_finding_variants`]. +#[derive(Debug, serde::Deserialize)] +pub struct VariantsQuery { + /// Only one target's variants. + #[serde(default)] + pub repo_id: Option, +} + +/// The app variants the tenant's findings are labelled with (theirs and their +/// groups' places), sorted, for the findings filter. +#[tracing::instrument(skip_all, fields(repo_id = ?query.repo_id))] +pub async fn list_finding_variants( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> ApiResult> { + let db = tenant_db(&agent, &tenant).await?; + let filter = query + .repo_id + .as_ref() + .map_or_else(|| doc! {}, |repo_id| doc! { "repo_id": repo_id }); + let mut variants = std::collections::BTreeSet::new(); + for field in ["variant", "occurrences.variant"] { + match db.findings().distinct(field, filter.clone()).await { + Ok(values) => variants.extend( + values + .into_iter() + .filter_map(|v| v.as_str().map(str::to_string)), + ), + Err(e) => tracing::warn!("Failed to list finding variants: {e}"), + } + } + let variants: Vec = variants.into_iter().collect(); + Ok(Json(ApiResponse { + total: Some(variants.len() as u64), + data: variants, + page: None, + })) +} + #[tracing::instrument(skip_all, fields(finding_id = %id))] pub async fn get_finding( Extension(agent): AgentExt, diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 5afe3ba..a5ce2e7 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -81,6 +81,10 @@ pub fn build_router() -> Router { post(handlers::onboarding::trigger_target_scan), ) .route("/api/v1/findings", get(handlers::list_findings)) + .route( + "/api/v1/findings/variants", + get(handlers::list_finding_variants), + ) .route("/api/v1/findings/{id}", get(handlers::get_finding)) .route( "/api/v1/findings/{id}/status", diff --git a/compliance-agent/src/classify/mod.rs b/compliance-agent/src/classify/mod.rs index ca275cd..c0513ad 100644 --- a/compliance-agent/src/classify/mod.rs +++ b/compliance-agent/src/classify/mod.rs @@ -70,7 +70,7 @@ pub async fn classify_target( } let mut classification = rank(verdicts, detected_by, target.target_type); - // The .NET stack at any depth, as facts (#445). + // The .NET stack and the app variants at any depth, as facts (#445). for artifact in &target.artifacts { if !matches!( artifact.kind, @@ -80,6 +80,15 @@ pub async fn classify_target( } if let Some(path) = working_paths.get(&artifact.id) { dotnet::add_facts(&mut classification.facts, path); + // The app's variants (phone and tablet app, flavors, app targets), + // one fact each with what it was recognised from. + for variant in crate::pipeline::variants::app_variants(path).all() { + classification.facts.push(DetectedFact::new( + "app_variant", + variant.name.clone(), + variant.source, + )); + } } } Ok(classification) diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index 4b0bc9f..00c9590 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -23,6 +23,7 @@ use compliance_core::models::{Finding, FindingStatus, ScanChangeKind, StatusChan use crate::database::Database; use crate::error::AgentError; +use crate::pipeline::variants::AppVariants; /// The findings one scan run has saved so far, by fingerprint. pub struct RunFindings { @@ -39,6 +40,8 @@ pub struct RunFindings { /// The places listed by the groups this run reported (scanner, rule, /// file, line): a finding stored at one of them was grouped, not fixed. grouped: HashSet, + /// The app variants of the scanned tree, which label each finding. + variants: AppVariants, } /// One place a group lists: scanner, rule, file, line. @@ -63,9 +66,23 @@ impl RunFindings { completed: HashSet::new(), status_changed: Vec::new(), grouped: HashSet::new(), + variants: AppVariants::default(), } } + /// Label the findings this run saves with the app variant holding them + /// (see [`crate::pipeline::variants`]). + pub fn with_variants(mut self, variants: AppVariants) -> Self { + self.variants = variants; + self + } + + /// Label `findings` with their app variant. Called before grouping too, + /// so a group's list of places names each place's variant. + pub fn label(&self, findings: &mut [Finding]) { + self.variants.label(findings); + } + /// Record that `scanner` ran to completion over the whole tree. Call it /// before saving that scanner's findings, so a resolved one it reports /// again is reopened. @@ -94,6 +111,7 @@ impl RunFindings { db: &Database, findings: &mut [Finding], ) -> Result { + self.label(findings); self.note_groups(findings); let unknown: HashSet = findings .iter() @@ -417,6 +435,8 @@ enum WriteKind { EarlierControlRefs, /// The places of a group an earlier run stored (#464). EarlierPlaces, + /// The app variant of a row an earlier run stored. + EarlierVariant, } /// One update of a finding's stored row. @@ -505,6 +525,14 @@ fn row_writes(finding: &Finding, inserted: Option) -> Result) -> Option { .map(|f| Occurrence { file: f.file_path.clone().unwrap_or_default(), line: f.line_number, + variant: f.variant.clone(), }) .collect(); occurrences.dedup(); @@ -436,6 +437,7 @@ mod tests { .map(|i| Occurrence { file: "a.java".into(), line: Some(i), + variant: None, }) .collect(); let text = describe("Rule.", &places); diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index 5bbcf1d..84c1d69 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -132,10 +132,7 @@ impl PipelineOrchestrator { let mut created = 0u32; for finding in actionable { - let title = format!( - "[{}] {}: {}", - finding.severity, finding.scanner, finding.title - ); + let title = issue_title(finding); // Check if an issue already exists by fingerprint first, then by title let mut found_existing = false; @@ -332,6 +329,22 @@ fn issue_search_terms<'a>(finding: &'a Finding, title: &'a str) -> Vec<&'a str> } } +/// A finding's issue title: severity, scanner, the app variant when there +/// are several (the same flaw in the phone and the tablet app is two +/// issues, and the title is what an issue is found by), and its title. +fn issue_title(finding: &Finding) -> String { + match &finding.variant { + Some(variant) => format!( + "[{}] {} ({variant}): {}", + finding.severity, finding.scanner, finding.title + ), + None => format!( + "[{}] {}: {}", + finding.severity, finding.scanner, finding.title + ), + } +} + /// Format a finding into a markdown issue body for the tracker. pub(super) fn format_issue_body(finding: &Finding) -> String { let mut body = String::new(); @@ -343,6 +356,9 @@ pub(super) fn format_issue_body(finding: &Finding) -> String { if let Some(rule) = &finding.rule_id { body.push_str(&format!("**Rule:** {}\n", rule)); } + if let Some(variant) = &finding.variant { + body.push_str(&format!("**Variant:** {variant}\n")); + } if let Some(cwe) = &finding.cwe { body.push_str(&format!("**CWE:** {}\n", cwe)); } @@ -508,6 +524,26 @@ mod tests { ); } + #[test] + fn a_variant_is_in_the_title_and_the_body() { + let mut finding = Finding::new( + "r".into(), + "fp-tablet".into(), + "mobsfscan".into(), + ScanType::Sast, + "Logging".into(), + "Logs".into(), + Severity::Low, + ); + assert_eq!(issue_title(&finding), "[low] mobsfscan: Logging"); + finding.variant = Some("Tablet App".into()); + assert_eq!( + issue_title(&finding), + "[low] mobsfscan (Tablet App): Logging" + ); + assert!(format_issue_body(&finding).contains("**Variant:** Tablet App\n")); + } + #[test] fn links_only_to_an_https_dashboard() { assert_eq!( diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 6dd18e8..729b684 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -33,4 +33,5 @@ pub mod source_text; pub mod tool_cmd; mod tracker_dispatch; pub(crate) mod unity_settings; +pub mod variants; pub mod vendor; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 4762917..fc44bcd 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -168,7 +168,15 @@ impl PipelineOrchestrator { let mut all_findings: Vec = Vec::new(); // Each scanner stage saves its new findings at once, so they show while // the scan runs (#372); triage updates them at the end. - let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id); + // A phone and a tablet app, flavors, app targets: each finding names + // the variant it is in. + let tree = repo_path.clone(); + let variants = + tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree)) + .await + .unwrap_or_default(); + let mut run_findings = + crate::pipeline::finding_store::RunFindings::new(scan_run_id).with_variants(variants); // Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is // not the customer's to fix, so both analysers skip it and the run says @@ -284,6 +292,7 @@ impl PipelineOrchestrator { } } } + run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; @@ -560,6 +569,7 @@ impl PipelineOrchestrator { outside_vendor(&mut pattern_findings); all_findings.extend(pattern_findings); } + run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; @@ -581,6 +591,7 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] Gitleaks failed: {e}"), } + run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; @@ -601,6 +612,7 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] Lint scanning failed: {e}"), } + run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; diff --git a/compliance-agent/src/pipeline/variants.rs b/compliance-agent/src/pipeline/variants.rs new file mode 100644 index 0000000..cb487d3 --- /dev/null +++ b/compliance-agent/src/pipeline/variants.rs @@ -0,0 +1,539 @@ +//! The variants of a mobile app in one repository: a phone and a tablet app, +//! product flavors, several app targets of one Xcode project. +//! +//! The same flaw in the phone and in the tablet variant is two findings, as +//! each variant ships on its own and is fixed on its own. A finding (and each +//! place a grouped finding lists) is labelled with the variant whose +//! directory holds its file, so the two read apart. +//! +//! Variants are recognised from what each build system writes down: +//! +//! - **Eclipse/ADT**: sibling directories, each an app with its own +//! `AndroidManifest.xml` and `project.properties` (no Gradle); +//! - **Gradle**: several application modules (`com.android.application`), and +//! within one the source sets of its product flavors and build types +//! (`src//`); `src/main/` is shared by all and labels nothing; +//! - **Xcode**: several application targets of one project, each with its +//! sources in the directory named after it (Xcode's own layout). +//! +//! One app module, flavor or target alone is no variant: nothing is labelled. + +use std::collections::BTreeSet; +use std::path::Path; + +use compliance_core::models::Finding; + +/// How deep projects are looked for. +const MAX_DEPTH: usize = 8; + +/// Directories never searched: dependencies, build output, tool caches. +const SKIPPED_DIRS: &[&str] = &[ + ".git", + ".gradle", + "build", + "DerivedData", + "node_modules", + "Pods", + "Carthage", + "Library", + "Temp", +]; + +/// Source sets of a Gradle module that belong to every variant or none. +const SHARED_SOURCE_SETS: &[&str] = &["main", "test", "androidTest", "testFixtures"]; + +/// The Xcode product type of an app. +const XCODE_APPLICATION: &str = "\"com.apple.product-type.application\""; + +/// One variant of the app: what it is called, where its files are, and what +/// says it is one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AppVariant { + /// The variant's name (`Tablet App`, `phone`, `PumpRemote Watch`). + pub name: String, + /// The directory holding its files, relative and ending in `/`. + pub prefix: String, + /// What it was recognised from: `adt`, `gradle-module`, `gradle-flavor` + /// or `xcode-target`. + pub source: &'static str, +} + +/// The variants of the apps under `root`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AppVariants(Vec); + +impl AppVariants { + /// Every variant, in path order. + pub fn all(&self) -> &[AppVariant] { + &self.0 + } + + /// The variant whose directory holds `file` (relative to the tree), the + /// innermost when they nest. + pub fn of(&self, file: &str) -> Option<&str> { + let file = file.trim_start_matches("./"); + self.0 + .iter() + .filter(|v| file.starts_with(&v.prefix)) + .max_by_key(|v| v.prefix.len()) + .map(|v| v.name.as_str()) + } + + /// Label `findings` and the places their groups list with their variant. + /// A group spanning variants keeps none itself; each place names its own. + pub fn label(&self, findings: &mut [Finding]) { + if self.0.is_empty() { + return; + } + for finding in findings.iter_mut() { + for occurrence in &mut finding.occurrences { + occurrence.variant = self.of(&occurrence.file).map(str::to_string); + } + finding.variant = if finding.occurrences.is_empty() { + finding + .file_path + .as_deref() + .and_then(|file| self.of(file)) + .map(str::to_string) + } else { + let mut variants = finding.occurrences.iter().map(|o| o.variant.as_deref()); + let first = variants.next().flatten(); + variants + .all(|v| v == first) + .then_some(first) + .flatten() + .map(str::to_string) + }; + } + } +} + +/// `path` relative to `root`, `/`-separated, with a trailing `/`. +fn prefix_of(root: &Path, path: &Path) -> String { + let relative = path + .strip_prefix(root) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/"); + format!("{relative}/") +} + +/// The last component of `path`. +fn dir_name(path: &Path) -> String { + path.file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_default() +} + +/// Recognise the app variants under `root`. +/// +/// # Arguments +/// +/// * `root` - the checked-out or unpacked source tree +pub fn app_variants(root: &Path) -> AppVariants { + let (mut adt, mut modules, mut flavors, mut targets) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let files = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(MAX_DEPTH) + .sort_by_file_name() + .into_iter() + .filter_entry(|e| { + !(e.file_type().is_dir() + && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()); + for entry in files { + let Some(dir) = entry.path().parent() else { + continue; + }; + match entry.file_name().to_string_lossy().as_ref() { + "AndroidManifest.xml" => { + let properties = ["project.properties", "default.properties"] + .iter() + .any(|f| dir.join(f).is_file()); + let gradle = ["build.gradle", "build.gradle.kts"] + .iter() + .any(|f| dir.join(f).is_file()); + if properties && !gradle { + adt.push(AppVariant { + name: dir_name(dir), + prefix: prefix_of(root, dir), + source: "adt", + }); + } + } + "build.gradle" | "build.gradle.kts" => { + let text = std::fs::read_to_string(entry.path()).unwrap_or_default(); + if !is_android_application(&text) { + continue; + } + modules.push(AppVariant { + name: dir_name(dir), + prefix: prefix_of(root, dir), + source: "gradle-module", + }); + let mut module_flavors: Vec = declared_source_sets(&text) + .into_iter() + .map(|set| dir.join("src").join(set)) + .filter(|path| path.is_dir()) + .map(|path| AppVariant { + name: dir_name(&path), + prefix: prefix_of(root, &path), + source: "gradle-flavor", + }) + .collect(); + if module_flavors.len() > 1 { + flavors.append(&mut module_flavors); + } + } + "project.pbxproj" => { + let text = std::fs::read_to_string(entry.path()).unwrap_or_default(); + let Some(project_dir) = dir.parent() else { + continue; + }; + let mut project_targets: Vec = application_targets(&text) + .into_iter() + .map(|name| project_dir.join(name)) + .filter(|path| path.is_dir()) + .map(|path| AppVariant { + name: dir_name(&path), + prefix: prefix_of(root, &path), + source: "xcode-target", + }) + .collect(); + if project_targets.len() > 1 { + targets.append(&mut project_targets); + } + } + _ => {} + } + } + let mut out = Vec::new(); + for kind in [adt, modules] { + if kind.len() > 1 { + out.extend(kind); + } + } + out.extend(flavors); + out.extend(targets); + out.sort_by(|a, b| a.prefix.cmp(&b.prefix)); + out.dedup_by(|a, b| a.prefix == b.prefix); + AppVariants(out) +} + +/// Whether a Gradle build file builds an Android app (not a library). +fn is_android_application(text: &str) -> bool { + text.contains("com.android.application") || text.contains("android.application)") +} + +/// The product flavors and build types a Gradle build file declares: the +/// blocks directly inside `productFlavors { }` and `buildTypes { }` +/// (`phone {`, `create("tablet") {`, `getByName("debug") {`), except the +/// source sets shared by all. +fn declared_source_sets(text: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + // The depth of the open `productFlavors`/`buildTypes` block, if inside one. + let mut inside: Option = None; + let mut depth = 0_usize; + for line in text.lines() { + let line = line.split("//").next().unwrap_or_default().trim(); + let opens = line.matches('{').count(); + let closes = line.matches('}').count(); + let head = line.split('{').next().unwrap_or_default().trim(); + if inside.is_none() && opens > 0 && matches!(head, "productFlavors" | "buildTypes") { + inside = Some(depth + 1); + } else if inside == Some(depth) && opens > 0 { + if let Some(name) = block_name(head) { + if !SHARED_SOURCE_SETS.contains(&name.as_str()) { + out.insert(name); + } + } + } + depth = (depth + opens).saturating_sub(closes); + if inside.is_some_and(|d| depth < d) { + inside = None; + } + } + out +} + +/// The name a flavor or build type block opens with: `phone`, +/// `create("tablet")`, `getByName("release")`, `register("demo")`. +fn block_name(head: &str) -> Option { + let name = match head.split_once('(') { + Some((_, rest)) => rest + .split(')') + .next()? + .trim() + .trim_matches('"') + .trim_matches('\''), + None => head, + }; + (!name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + .then(|| name.to_string()) +} + +/// The names of an Xcode project's application targets. +fn application_targets(text: &str) -> Vec { + let Some(start) = text.find("/* Begin PBXNativeTarget section */") else { + return Vec::new(); + }; + let section = &text[start..]; + let section = section + .find("/* End PBXNativeTarget section */") + .map_or(section, |end| §ion[..end]); + // Each target is an object closed by `};` at its own indentation; its + // `name` and `productType` are among its keys. + section + .split("isa = PBXNativeTarget;") + .skip(1) + .filter(|target| { + let body = target.split("\n\t\t};").next().unwrap_or(target); + body.contains(XCODE_APPLICATION) + }) + .filter_map(|target| { + let body = target.split("\n\t\t};").next().unwrap_or(target); + body.lines() + .map(str::trim) + .find_map(|l| l.strip_prefix("name = ")) + .map(|n| n.trim_end_matches(';').trim_matches('"').to_string()) + }) + .collect() +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + use compliance_core::models::{Occurrence, ScanType, Severity}; + + /// A scratch tree holding `files`, removed on drop. + struct Tree(std::path::PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-variants-{}", uuid::Uuid::new_v4())); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + fn names(t: &Tree) -> Vec<(String, String, &'static str)> { + app_variants(&t.0) + .all() + .iter() + .map(|v| (v.name.clone(), v.prefix.clone(), v.source)) + .collect() + } + + fn finding(file: &str) -> Finding { + let mut f = Finding::new( + "t".into(), + format!("fp-{file}"), + "mobsfscan".into(), + ScanType::Sast, + "x".into(), + "x".into(), + Severity::Low, + ); + f.file_path = Some(file.into()); + f + } + + #[test] + fn adt_sibling_apps_are_variants_and_label_their_findings() { + let t = tree(&[ + ("Mobile App/AndroidManifest.xml", ""), + ("Mobile App/default.properties", "target=android-8"), + ("Mobile App/src/Main.java", ""), + ("Tablet App/AndroidManifest.xml", ""), + ("Tablet App/project.properties", "target=android-11"), + ]); + assert_eq!( + names(&t), + [ + ("Mobile App".into(), "Mobile App/".into(), "adt"), + ("Tablet App".into(), "Tablet App/".into(), "adt"), + ] + ); + let variants = app_variants(&t.0); + let mut findings = vec![ + finding("Mobile App/src/Main.java"), + finding("Tablet App/AndroidManifest.xml"), + finding("README.md"), + ]; + variants.label(&mut findings); + let labels: Vec> = findings.iter().map(|f| f.variant.as_deref()).collect(); + assert_eq!(labels, [Some("Mobile App"), Some("Tablet App"), None]); + } + + #[test] + fn a_group_keeps_a_variant_per_place_and_one_only_when_all_agree() { + let variants = AppVariants(vec![ + AppVariant { + name: "phone".into(), + prefix: "app/src/phone/".into(), + source: "gradle-flavor", + }, + AppVariant { + name: "tablet".into(), + prefix: "app/src/tablet/".into(), + source: "gradle-flavor", + }, + ]); + let place = |file: &str| Occurrence { + file: file.into(), + line: Some(1), + variant: None, + }; + let mut mixed = finding("app/src/phone/A.kt"); + mixed.occurrences = vec![place("app/src/phone/A.kt"), place("app/src/tablet/A.kt")]; + let mut one = finding("app/src/tablet/A.kt"); + one.occurrences = vec![place("app/src/tablet/A.kt"), place("app/src/tablet/B.kt")]; + let mut findings = vec![mixed, one]; + variants.label(&mut findings); + assert_eq!(findings[0].variant, None); + assert_eq!( + findings[0].occurrences[1].variant.as_deref(), + Some("tablet") + ); + assert_eq!(findings[1].variant.as_deref(), Some("tablet")); + // Shared code belongs to no variant. + assert_eq!(variants.of("app/src/main/A.kt"), None); + } + + #[test] + fn gradle_flavors_with_their_own_sources_are_variants() { + let build = r#" +plugins { id("com.android.application") } +android { + buildTypes { + getByName("release") { isMinifyEnabled = true } + } + flavorDimensions += "device" + productFlavors { + create("phone") { dimension = "device" } + create("tablet") { + dimension = "device" + applicationIdSuffix = ".tablet" + } + // a comment { + } +} +"#; + let t = tree(&[ + ("app/build.gradle.kts", build), + ("app/src/main/AndroidManifest.xml", ""), + ("app/src/phone/res/values/strings.xml", ""), + ("app/src/tablet/java/Tablet.kt", ""), + ]); + assert_eq!( + names(&t), + [ + ("phone".into(), "app/src/phone/".into(), "gradle-flavor"), + ("tablet".into(), "app/src/tablet/".into(), "gradle-flavor"), + ] + ); + assert_eq!( + declared_source_sets(build), + BTreeSet::from(["phone".into(), "release".into(), "tablet".into()]) + ); + } + + #[test] + fn groovy_flavors_and_two_app_modules_are_read() { + let groovy = + "apply plugin: 'com.android.application'\nandroid {\n productFlavors {\n \ + free {\n }\n pro { applicationIdSuffix '.pro' }\n }\n}\n"; + assert_eq!( + declared_source_sets(groovy), + BTreeSet::from(["free".into(), "pro".into()]) + ); + let t = tree(&[ + ( + "phone/build.gradle", + "apply plugin: 'com.android.application'", + ), + ( + "wear/build.gradle", + "plugins { alias(libs.plugins.android.application) }", + ), + ("core/build.gradle", "apply plugin: 'com.android.library'"), + ]); + assert_eq!( + names(&t), + [ + ("phone".into(), "phone/".into(), "gradle-module"), + ("wear".into(), "wear/".into(), "gradle-module"), + ] + ); + } + + #[test] + fn xcode_application_targets_with_their_directories_are_variants() { + let pbxproj = "/* Begin PBXNativeTarget section */ +\t\tA1 /* PumpRemote */ = { +\t\t\tisa = PBXNativeTarget; +\t\t\tname = PumpRemote; +\t\t\tproductType = \"com.apple.product-type.application\"; +\t\t}; +\t\tA2 /* PumpRemote iPad */ = { +\t\t\tisa = PBXNativeTarget; +\t\t\tname = \"PumpRemote iPad\"; +\t\t\tproductType = \"com.apple.product-type.application\"; +\t\t}; +\t\tA3 /* PumpRemoteTests */ = { +\t\t\tisa = PBXNativeTarget; +\t\t\tname = PumpRemoteTests; +\t\t\tproductType = \"com.apple.product-type.bundle.unit-test\"; +\t\t}; +/* End PBXNativeTarget section */ +"; + assert_eq!( + application_targets(pbxproj), + ["PumpRemote", "PumpRemote iPad"] + ); + let t = tree(&[ + ("ios/PumpRemote.xcodeproj/project.pbxproj", pbxproj), + ("ios/PumpRemote/AppDelegate.swift", ""), + ("ios/PumpRemote iPad/AppDelegate.swift", ""), + ("ios/PumpRemoteTests/Tests.swift", ""), + ]); + assert_eq!( + names(&t), + [ + ( + "PumpRemote iPad".into(), + "ios/PumpRemote iPad/".into(), + "xcode-target" + ), + ( + "PumpRemote".into(), + "ios/PumpRemote/".into(), + "xcode-target" + ), + ] + ); + } + + #[test] + fn a_single_app_has_no_variants() { + let t = tree(&[ + ( + "app/build.gradle", + "apply plugin: 'com.android.application'", + ), + ("app/src/main/AndroidManifest.xml", ""), + ]); + assert!(app_variants(&t.0).all().is_empty()); + } +} diff --git a/compliance-agent/tests/finding_variants.rs b/compliance-agent/tests/finding_variants.rs new file mode 100644 index 0000000..6edf487 --- /dev/null +++ b/compliance-agent/tests/finding_variants.rs @@ -0,0 +1,123 @@ +//! App variants (a phone and a tablet app) label the findings a scan stores: +//! new rows carry theirs, rows an earlier scan stored without one get it, and +//! a group lists the variant of each place. 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_agent::pipeline::grouping::{group_repetitive, GroupingPolicy}; +use compliance_agent::pipeline::variants::app_variants; +use compliance_core::models::{Finding, ScanType, Severity}; +use mongodb::bson::doc; + +const TENANT: &str = "finding-variants"; +const TARGET: &str = "target-1"; + +fn finding(rule: &str, file: &str, line: u32) -> Finding { + let mut f = Finding::new( + TARGET.into(), + compute_fingerprint(&[TARGET, rule, file, &line.to_string()]), + "mobsfscan".into(), + ScanType::Sast, + format!("Rule {rule}"), + format!("Rule {rule}."), + Severity::Low, + ); + f.rule_id = Some(rule.into()); + f.file_path = Some(file.into()); + f.line_number = Some(line); + f +} + +async fn row(db: &Database, fingerprint: &str) -> Finding { + db.findings() + .find_one(doc! { "fingerprint": fingerprint }) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn findings_carry_the_variant_their_file_is_in() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "variant_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP finding_variants: no MongoDB reachable at {uri}"); + return; + }; + let Ok(db) = pool.for_tenant_id(TENANT).await else { + eprintln!("SKIP finding_variants: MongoDB at {uri} not usable"); + return; + }; + + // Arrange: two Eclipse/ADT apps side by side, and a finding of the phone + // app stored by a scan from before variants. + let tree = std::env::temp_dir().join(format!("cs-variant-it-{}", uuid::Uuid::new_v4())); + for app in ["Mobile App", "Tablet App"] { + std::fs::create_dir_all(tree.join(app)).unwrap(); + std::fs::write(tree.join(app).join("AndroidManifest.xml"), "").unwrap(); + std::fs::write( + tree.join(app).join("project.properties"), + "target=android-8", + ) + .unwrap(); + } + let variants = app_variants(&tree); + let _ = std::fs::remove_dir_all(&tree); + let earlier = finding("cleartext", "Mobile App/AndroidManifest.xml", 3); + db.findings().insert_one(&earlier).await.unwrap(); + + // Act: a scan reporting the same flaw in both apps, and a rule firing in + // both often enough to be grouped. + let mut findings = vec![ + finding("cleartext", "Mobile App/AndroidManifest.xml", 3), + finding("cleartext", "Tablet App/AndroidManifest.xml", 3), + ]; + for line in 1..=3 { + findings.push(finding("logging", "Mobile App/src/Main.java", line)); + findings.push(finding("logging", "Tablet App/src/Main.java", line)); + } + let mut run = RunFindings::new("run-1").with_variants(variants); + run.label(&mut findings); + group_repetitive(&mut findings, &GroupingPolicy::default()); + run.save_new(&db, &mut findings).await.unwrap(); + run.write_back(&db, &mut findings).await.unwrap(); + + // Assert: the flaw is two findings, each in its variant; the earlier row + // got its variant; the group names the variant of each place. + let tablet = finding("cleartext", "Tablet App/AndroidManifest.xml", 3); + assert_eq!( + row(&db, &tablet.fingerprint).await.variant.as_deref(), + Some("Tablet App") + ); + assert_eq!( + row(&db, &earlier.fingerprint).await.variant.as_deref(), + Some("Mobile App") + ); + let group = findings + .iter() + .find(|f| !f.occurrences.is_empty()) + .expect("logging is grouped"); + let stored = row(&db, &group.fingerprint).await; + assert_eq!(stored.variant, None); + assert_eq!( + stored + .occurrences + .iter() + .filter(|o| o.variant.as_deref() == Some("Tablet App")) + .count(), + 3 + ); + assert!(stored + .description + .contains("Tablet App/src/Main.java:1 (Tablet App)")); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-agent/tests/nightly.rs b/compliance-agent/tests/nightly.rs index d567e46..970d857 100644 --- a/compliance-agent/tests/nightly.rs +++ b/compliance-agent/tests/nightly.rs @@ -463,9 +463,15 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let line = f["line_number"].as_u64().unwrap_or(0); + // The app variant tells apart the same file in a phone and a + // tablet app, which the file name alone does not. + let variant = f["variant"] + .as_str() + .map(|v| format!(" [{v}]")) + .unwrap_or_default(); snapshot .findings - .insert(format!("{scanner}:{rule} {file}:{line}")); + .insert(format!("{scanner}:{rule} {file}:{line}{variant}")); } } for e in &sbom { diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index 796e8db..e799212 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -152,13 +152,21 @@ pub struct Occurrence { pub file: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option, + /// The app variant whose files hold this place (`Tablet App`), when the + /// repository has several. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, } impl std::fmt::Display for Occurrence { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.line { - Some(line) => write!(f, "{}:{line}", self.file), - None => write!(f, "{}", self.file), + Some(line) => write!(f, "{}:{line}", self.file)?, + None => write!(f, "{}", self.file)?, + } + match &self.variant { + Some(variant) => write!(f, " ({variant})"), + None => Ok(()), } } } @@ -212,6 +220,10 @@ pub struct Finding { /// at one place. `file_path`/`line_number` name the first of them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub occurrences: Vec, + /// The app variant whose files hold the finding (`Tablet App`), when the + /// repository has several; for a group, the variant all its places share. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -259,6 +271,7 @@ impl Finding { reproduction: None, status_history: Vec::new(), occurrences: Vec::new(), + variant: None, created_at: now, updated_at: now, } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 400a950..a31334f 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4231,6 +4231,21 @@ tbody tr:last-child td { color: var(--text-tertiary); } +.finding-variant { + display: inline-block; + margin-top: 4px; + padding: 1px 8px; + border-radius: 999px; + font-size: 11px; + color: var(--text-secondary); + background: var(--bg-elevated); +} + +.badge-variant { + color: var(--text-secondary); + background: var(--bg-elevated); +} + .finding-target { color: var(--text-secondary); max-width: 220px; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index b0e7559..a46428d 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1422,6 +1422,15 @@ pub mod findings { de: "Alle Status", en: "All statuses", }; + pub const ALL_VARIANTS: Text = Text { + de: "Alle Varianten", + en: "All variants", + }; + /// The app variant a finding is in (phone or tablet app, a flavor). + pub const VARIANT: Text = Text { + de: "Variante", + en: "Variant", + }; pub const INFO: Text = Text { de: "Info", en: "Info", diff --git a/compliance-dashboard/src/infrastructure/findings.rs b/compliance-dashboard/src/infrastructure/findings.rs index 3daea54..85000d4 100644 --- a/compliance-dashboard/src/infrastructure/findings.rs +++ b/compliance-dashboard/src/infrastructure/findings.rs @@ -18,6 +18,8 @@ pub struct FindingsQuery { pub status: String, pub repo_id: String, pub q: String, + /// One app variant (`Tablet App`), or empty for all. + pub variant: String, pub sort_by: String, pub sort_order: String, } @@ -109,6 +111,12 @@ pub async fn fetch_findings(query: FindingsQuery) -> Result() )); } + if !query.variant.is_empty() { + path.push_str(&format!( + "&variant={}", + url::form_urlencoded::byte_serialize(query.variant.as_bytes()).collect::() + )); + } if !query.sort_by.is_empty() { path.push_str(&format!("&sort_by={}", query.sort_by)); } @@ -128,6 +136,34 @@ pub async fn fetch_findings(query: FindingsQuery) -> Result Result, ServerFnError> { + let mut path = "/api/v1/findings/variants".to_string(); + if !repo_id.is_empty() { + path.push_str(&format!("?repo_id={repo_id}")); + } + let resp = super::agent_client::agent_get(&path) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = resp + .json() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + Ok(body["data"] + .as_array() + .map(|values| { + values + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default()) +} + #[server] pub async fn fetch_finding_detail(id: String) -> Result { let resp = super::agent_client::agent_get(&format!("/api/v1/findings/{id}")) diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index d28047b..d90be32 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -114,6 +114,9 @@ pub fn FindingDetailPage(id: String) -> Element { div { class: "flex gap-2 mb-4", SeverityBadge { severity: f.severity.to_string() } + if let Some(variant) = &f.variant { + span { class: "badge badge-variant", "{tx::VARIANT.get(lang)}: {variant}" } + } if let Some(cwe) = &f.cwe { span { class: "badge badge-info", "{cwe}" } } diff --git a/compliance-dashboard/src/pages/findings.rs b/compliance-dashboard/src/pages/findings.rs index da4c8e1..c8c397e 100644 --- a/compliance-dashboard/src/pages/findings.rs +++ b/compliance-dashboard/src/pages/findings.rs @@ -26,6 +26,7 @@ pub fn FindingsPage(target: String) -> Element { let mut status_filter = use_signal(String::new); let mut repo_filter = use_signal(|| target.clone()); let mut search_query = use_signal(String::new); + let mut variant_filter = use_signal(String::new); // Most severe first: what needs attention leads. let mut sort_by = use_signal(|| "severity".to_string()); let mut sort_order = use_signal(|| "desc".to_string()); @@ -38,6 +39,17 @@ pub fn FindingsPage(target: String) -> Element { .ok() }); + // The app variants (phone and tablet app, flavors) of the chosen target, + // or of all; the filter shows only when there are some. + let variants = use_resource(move || { + let repo_id = repo_filter(); + async move { + crate::infrastructure::findings::fetch_finding_variants(repo_id) + .await + .unwrap_or_default() + } + }); + let mut findings = use_resource(move || { let query = crate::infrastructure::findings::FindingsQuery { page: page(), @@ -46,6 +58,7 @@ pub fn FindingsPage(target: String) -> Element { status: status_filter(), repo_id: repo_filter(), q: search_query(), + variant: variant_filter(), sort_by: sort_by(), sort_order: sort_order(), }; @@ -162,6 +175,15 @@ pub fn FindingsPage(target: String) -> Element { option { value: "{wire_name(&status)}", {tx::status(&status).get(lang)} } } } + if let Some(names) = variants.read().as_ref().filter(|v| !v.is_empty()) { + select { + onchange: move |e| { variant_filter.set(e.value()); page.set(1); }, + option { value: "", {tx::ALL_VARIANTS.get(lang)} } + for name in names.iter() { + option { value: "{name}", selected: variant_filter() == *name, "{name}" } + } + } + } } // Bulk action bar @@ -330,6 +352,9 @@ pub fn FindingsPage(target: String) -> Element { "{finding.title}" } span { class: "finding-tool", title: "{finding.scanner}", {tx::tool_name(&finding.scanner, lang)} } + if let Some(variant) = &finding.variant { + span { class: "finding-variant", title: tx::VARIANT.get(lang), "{variant}" } + } } td { {tx::scan_type(&finding.scan_type).get(lang)} } if let Some(names) = &target_names { diff --git a/docs/guide/findings.md b/docs/guide/findings.md index 806d577..1762dc8 100644 --- a/docs/guide/findings.md +++ b/docs/guide/findings.md @@ -13,7 +13,8 @@ the same page filtered to that target. ### Filtering -The filter bar has a search field (**Befunde durchsuchen …**) and four filters: +The filter bar has a search field (**Befunde durchsuchen …**) and four filters, +plus a fifth when an app has variants: - **Alle Prüfobjekte** -- one target, or all - **Alle Schweregrade** -- **Kritisch**, **Hoch**, **Mittel**, **Niedrig** or **Info** @@ -21,6 +22,8 @@ The filter bar has a search field (**Befunde durchsuchen …**) and four filters **Zugangsdaten im Code**, **Bekannte Schwachstelle (CVE)**, **SPS-Steuerungslogik** - **Alle Status** -- one of the statuses below +- **Alle Varianten** -- one variant of the app (see below); only shown when + the findings in view have variants Filters can be combined. The list shows 20 findings per page. @@ -29,7 +32,7 @@ Filters can be combined. The list shows 20 findings per page. | Column | Description | |--------|-------------| | **Schweregrad** (Severity) | Kritisch, Hoch, Mittel, Niedrig or Info | -| **Titel** (Title) | What was found; a click opens the finding. The tool that found it is shown beneath. | +| **Titel** (Title) | What was found; a click opens the finding. The tool that found it is shown beneath, and the app variant when there are several. | | **Art** (Type) | The kind of finding | | **Prüfobjekt** (Target) | Only when the list shows all targets | | **Fundstelle** (Location) | File and line | @@ -38,6 +41,23 @@ Filters can be combined. The list shows 20 findings per page. The **Schweregrad**, **Titel**, **Art** and **Status** headers sort the list. +### App variants + +A repository can hold several variants of one app: a phone and a tablet app +side by side (Eclipse/ADT), several Android app modules, product flavors with +their own sources (`app/src/tablet/`), or several app targets of one Xcode +project. Prüfwerk recognises them (the target page lists each as +`app_variant` under **Erkannte Merkmale**) and labels every finding with the +variant whose files it is in. Code all variants share (`src/main/`) belongs to +none. + +The same flaw in the phone and the tablet app stays two findings, each with +its variant, because each variant ships and is fixed on its own; their issues +in the tracker are separate too (the variant is in the title, and the body +has a **Variant** line). When one rule fires often enough to become a single +finding, its list of places names each place's variant, and the variant +filter finds it under every variant it touches. + ### Changing several findings at once Tick the findings (or the box in the header for the whole page) and choose a diff --git a/fixtures/nightly/baselines/mobile-legacy-adt-unity.json b/fixtures/nightly/baselines/mobile-legacy-adt-unity.json index b6ab1b5..d637997 100644 --- a/fixtures/nightly/baselines/mobile-legacy-adt-unity.json +++ b/fixtures/nightly/baselines/mobile-legacy-adt-unity.json @@ -8,8 +8,10 @@ "unity:Unity Editor@2019.2.4f1" ], "findings": [ - "mobsfscan:android_manifest_insecure_minsdk_error AndroidManifest.xml:3", - "mobsfscan:android_manifest_missing_explicit_allow_backup AndroidManifest.xml:1" + "mobsfscan:android_manifest_insecure_minsdk_error AndroidManifest.xml:3 [Pump Phone]", + "mobsfscan:android_manifest_insecure_minsdk_error AndroidManifest.xml:3 [Pump Tablet]", + "mobsfscan:android_manifest_missing_explicit_allow_backup AndroidManifest.xml:1 [Pump Phone]", + "mobsfscan:android_manifest_missing_explicit_allow_backup AndroidManifest.xml:1 [Pump Tablet]" ], "cves": [ "android-sdk-end-of-support",