From ab04b2f6128881497b7a797b6f333ab6b58842ac Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:09:13 +0200 Subject: [PATCH] fix: findings from the first acceptance round - Scans no longer run for hours on vendor-heavy trees. The iot-reference scan produced 11,670 findings, 11,579 of them from ruff over vendor Python under Middleware/, and the LLM triage worked through all of them, 30 at a time, one call after another. Vendor code is now left out of the pattern, secret and lint findings too (it already was for SAST); the LLM triage takes the 600 most severe findings, 4 calls at a time, the rest staying open; control triage runs 8 judge calls at a time. - A reasoning model's block is removed before its answer is parsed, ahead of the switch to Qwen3.8-27B. - A file can be added to an existing target: the editor offers an upload (archive, PLC project, firmware image, with its archive password) instead of asking for a path; the wizard and the editor share the file-kind and PLC-format helpers. - The manual-findings form and the archive-password field in the editor use the dashboard's form styling. - A robots noindex meta tag in the page head, next to the X-Robots-Tag header. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/controls/scan_triage.rs | 34 +- compliance-agent/src/llm/client.rs | 42 ++- compliance-agent/src/llm/triage.rs | 294 +++++++++++------- compliance-agent/src/pipeline/orchestrator.rs | 26 +- compliance-agent/src/pipeline/vendor.rs | 26 ++ compliance-dashboard/assets/main.css | 93 +++++- compliance-dashboard/src/app.rs | 3 + .../src/components/artifact_upload.rs | 135 ++++++++ .../src/components/manual_findings.rs | 2 +- compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 18 ++ .../src/infrastructure/onboarding.rs | 34 ++ compliance-dashboard/src/pages/onboarding.rs | 24 +- compliance-dashboard/src/pages/target.rs | 27 +- 14 files changed, 598 insertions(+), 161 deletions(-) create mode 100644 compliance-dashboard/src/components/artifact_upload.rs diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs index d0fe251..acdf550 100644 --- a/compliance-agent/src/controls/scan_triage.rs +++ b/compliance-agent/src/controls/scan_triage.rs @@ -28,6 +28,8 @@ use crate::llm::LlmClient; /// Nearest master controls judged per code region in the semantic pass. const SEMANTIC_TOP_K: usize = 5; +/// Control-triage judge calls in flight at once. +const CONTROL_TRIAGE_CONCURRENCY: usize = 8; /// Most findings one scan maps semantically: each costs an embedding and up /// to [`SEMANTIC_TOP_K`] judge calls, so an uncapped pass would add tens of /// minutes to a large scan. The most severe unmapped ones go first. @@ -63,15 +65,31 @@ pub async fn triage_repo_findings( }; let triage = ControlTriage::new(LlmControlJudge::new(llm), map, specs); + // The judge reads each finding's code; its calls run a few at a time, and + // the outcomes are applied once all are in. + let candidates: Vec<(usize, CandidateRegion)> = findings + .iter() + .enumerate() + .filter_map(|(i, f)| { + let region = fetch_region(repo_path, f.file_path.as_deref()?, f.line_number?)?; + Some((i, region)) + }) + .collect(); + let mut outcomes = Vec::with_capacity(candidates.len()); + { + let read: &[Finding] = findings; + for group in candidates.chunks(CONTROL_TRIAGE_CONCURRENCY) { + let calls = group + .iter() + .map(|(i, region)| triage.triage(&read[*i], region)); + outcomes.extend(futures_util::future::join_all(calls).await); + } + } + let mut tagged = 0; - for finding in findings.iter_mut() { - let (Some(file), Some(line)) = (finding.file_path.clone(), finding.line_number) else { - continue; - }; - let Some(region) = fetch_region(repo_path, &file, line) else { - continue; - }; - match triage.triage(finding, ®ion).await { + for ((i, _), outcome) in candidates.iter().zip(outcomes) { + let finding = &mut findings[*i]; + match outcome { TriageOutcome::Confirmed(controls) => { finding.control_refs = controls; tagged += 1; diff --git a/compliance-agent/src/llm/client.rs b/compliance-agent/src/llm/client.rs index 7f9e785..30135e9 100644 --- a/compliance-agent/src/llm/client.rs +++ b/compliance-agent/src/llm/client.rs @@ -216,7 +216,45 @@ impl LlmClient { } // Otherwise return content - let content = choice.message.content.clone().unwrap_or_default(); - Ok(LlmResponse::Content(content)) + let content = choice.message.content.as_deref().unwrap_or_default(); + Ok(LlmResponse::Content(without_reasoning(content))) + } +} + +/// `content` without a reasoning model's `…` blocks, which some +/// gateways return inline ahead of the answer; the callers parse the answer as +/// JSON. An unterminated block (the model ran out of tokens while thinking) +/// leaves nothing to parse, so it becomes empty. +fn without_reasoning(content: &str) -> String { + let mut rest = content; + let mut out = String::with_capacity(content.len()); + while let Some(start) = rest.find("") { + out.push_str(&rest[..start]); + match rest[start..].find("") { + Some(end) => rest = &rest[start + end + "".len()..], + None => { + rest = ""; + break; + } + } + } + out.push_str(rest); + out.trim().to_string() +} + +#[cfg(test)] +mod reasoning_tests { + use super::without_reasoning; + + #[test] + fn a_reasoning_models_thinking_is_not_part_of_the_answer() { + assert_eq!( + without_reasoning( + "the finding is in a test file\n[{\"action\":\"dismiss\"}]" + ), + "[{\"action\":\"dismiss\"}]" + ); + assert_eq!(without_reasoning("[1, 2]"), "[1, 2]"); + assert_eq!(without_reasoning("still going"), ""); } } diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index 2d16b30..ab70e89 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -49,32 +49,37 @@ Confidence scoring (0-10): Respond with a JSON array, one entry per finding in the same order presented (no markdown fences): [{"id": "", "action": "confirm|downgrade|upgrade|dismiss", "confidence": 0-10, "rationale": "1-2 sentences", "remediation": "optional fix"}, ...]"#; -/// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each -/// one. Nothing is removed; a flagged finding is kept as "needs review". -/// -/// # Returns -/// -/// How many findings passed triage (confirmed or re-rated). -pub async fn triage_findings( - llm: &Arc, - findings: &mut [Finding], +/// Most findings one scan sends to the LLM triage, the most severe first. +/// A large tree can yield thousands (12,000 on an RTOS reference project); the +/// rest stay open, untriaged, which is where they would be without an LLM. +const TRIAGE_MAX_FINDINGS: usize = 600; +/// Triage calls in flight at once. +const TRIAGE_CONCURRENCY: usize = 4; + +/// The findings the LLM triage looks at, by index: the most severe first, at +/// most [`TRIAGE_MAX_FINDINGS`]. +fn triage_selection(findings: &[Finding]) -> Vec { + let mut selected: Vec = (0..findings.len()).collect(); + // Stable, so equally severe findings keep their scan order. + selected.sort_by(|a, b| findings[*b].severity.cmp(&findings[*a].severity)); + selected.truncate(TRIAGE_MAX_FINDINGS); + selected +} + +/// The model's answer for one chunk: its verdicts in chunk order, or `None` +/// when the call failed or its answer could not be read. +async fn triage_chunk( + llm: &LlmClient, + chunk: &[&Finding], graph_context: Option<&GraphContext>, -) -> usize { - let mut passed = 0; + chunk_start: usize, +) -> Option> { + let mut user_prompt = String::new(); - // Process findings in chunks to avoid overflowing the LLM context window. - for chunk_start in (0..findings.len()).step_by(TRIAGE_CHUNK_SIZE) { - let chunk_end = (chunk_start + TRIAGE_CHUNK_SIZE).min(findings.len()); - let chunk = &mut findings[chunk_start..chunk_end]; + for (i, finding) in chunk.iter().enumerate() { + let file_classification = classify_file_path(finding.file_path.as_deref()); - // Build a combined prompt for the entire chunk. - let mut user_prompt = String::new(); - let mut file_classifications: Vec = Vec::new(); - - for (i, finding) in chunk.iter().enumerate() { - let file_classification = classify_file_path(finding.file_path.as_deref()); - - user_prompt.push_str(&format!( + user_prompt.push_str(&format!( "\n--- Finding {} (id: {}) ---\nScanner: {}\nRule: {}\nSeverity: {}\nTitle: {}\nDescription: {}\nFile: {}\nLine: {}\nCode: {}\nFile classification: {}", i + 1, finding.fingerprint, @@ -89,118 +94,144 @@ pub async fn triage_findings( file_classification, )); - // Enrich with surrounding code context if possible - if let Some(context) = read_surrounding_context(finding) { - user_prompt.push_str(&format!( - "\n\n--- Surrounding Code (50 lines) ---\n{context}" - )); - } + // Enrich with surrounding code context if possible + if let Some(context) = read_surrounding_context(finding) { + user_prompt.push_str(&format!( + "\n\n--- Surrounding Code (50 lines) ---\n{context}" + )); + } - // Enrich with graph context if available - if let Some(ctx) = graph_context { - if let Some(impact) = ctx - .impacts - .iter() - .find(|im| im.finding_id == finding.fingerprint) - { - user_prompt.push_str(&format!( - "\n\n--- Code Graph Context ---\n\ + // Enrich with graph context if available + if let Some(ctx) = graph_context { + if let Some(impact) = ctx + .impacts + .iter() + .find(|im| im.finding_id == finding.fingerprint) + { + user_prompt.push_str(&format!( + "\n\n--- Code Graph Context ---\n\ Blast radius: {} nodes affected\n\ Entry points affected: {}\n\ Direct callers: {}\n\ Communities affected: {}\n\ Call chains: {}", - impact.blast_radius, - if impact.affected_entry_points.is_empty() { - "none".to_string() - } else { - impact.affected_entry_points.join(", ") - }, - if impact.direct_callers.is_empty() { - "none".to_string() - } else { - impact.direct_callers.join(", ") - }, - impact.affected_communities.len(), - impact.call_chains.len(), - )); - } + impact.blast_radius, + if impact.affected_entry_points.is_empty() { + "none".to_string() + } else { + impact.affected_entry_points.join(", ") + }, + if impact.direct_callers.is_empty() { + "none".to_string() + } else { + impact.direct_callers.join(", ") + }, + impact.affected_communities.len(), + impact.call_chains.len(), + )); } - - user_prompt.push('\n'); - file_classifications.push(file_classification); } - // Send the batch to the LLM. - match llm - .chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1)) - .await - { - Ok(response) => { - let cleaned = response.trim(); - let cleaned = if cleaned.starts_with("```") { - cleaned - .trim_start_matches("```json") - .trim_start_matches("```") - .trim_end_matches("```") - .trim() - } else { - cleaned - }; + user_prompt.push('\n'); + } - match serde_json::from_str::>(cleaned) { - Ok(results) => { - for (idx, finding) in chunk.iter_mut().enumerate() { - // Match result by position; fall back to keeping the finding. - let Some(result) = results.get(idx) else { - finding.status = FindingStatus::Triaged; - passed += 1; - continue; - }; + let response = match llm + .chat(TRIAGE_SYSTEM_PROMPT, &user_prompt, Some(0.1)) + .await + { + Ok(response) => response, + Err(e) => { + tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}"); + return None; + } + }; + let cleaned = response.trim(); + let cleaned = if cleaned.starts_with("```") { + cleaned + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim() + } else { + cleaned + }; + match serde_json::from_str::>(cleaned) { + Ok(results) => Some(results), + Err(_) => { + tracing::warn!( + "Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}" + ); + None + } + } +} - let file_classification = file_classifications - .get(idx) - .map(|s| s.as_str()) - .unwrap_or("unknown"); +/// Triage `findings` with the LLM, in chunks: confirm, re-rate or flag each +/// one. Nothing is removed; a flagged finding is kept as "needs review". The +/// most severe findings go first, at most [`TRIAGE_MAX_FINDINGS`], and +/// [`TRIAGE_CONCURRENCY`] chunks are triaged at a time. +/// +/// # Returns +/// +/// How many findings passed triage (confirmed or re-rated). +pub async fn triage_findings( + llm: &Arc, + findings: &mut [Finding], + graph_context: Option<&GraphContext>, +) -> usize { + let selected = triage_selection(findings); + if selected.len() < findings.len() { + tracing::info!( + "LLM triage: the {} most severe of {} findings; the rest stay open", + selected.len(), + findings.len() + ); + } - let adjusted_confidence = - adjust_confidence(result.confidence, file_classification); - finding.confidence = Some(adjusted_confidence); - finding.triage_action = Some(result.action.clone()); - finding.triage_rationale = Some(result.rationale.clone()); + // Ask for every chunk first (read-only), a few at a time, then apply the + // answers. + let chunks: Vec<&[usize]> = selected.chunks(TRIAGE_CHUNK_SIZE).collect(); + let mut answers: Vec>> = Vec::with_capacity(chunks.len()); + { + let read: &[Finding] = findings; + for (group_no, group) in chunks.chunks(TRIAGE_CONCURRENCY).enumerate() { + let batches: Vec> = group + .iter() + .map(|indices| indices.iter().map(|&i| &read[i]).collect()) + .collect(); + let calls = batches.iter().enumerate().map(|(k, batch)| { + let start = (group_no * TRIAGE_CONCURRENCY + k) * TRIAGE_CHUNK_SIZE; + triage_chunk(llm, batch, graph_context, start) + }); + answers.extend(futures_util::future::join_all(calls).await); + } + } + let answers = chunks.into_iter().zip(answers); - if let Some(ref remediation) = result.remediation { - finding.remediation = Some(remediation.clone()); - } - - if apply_action(finding, &result.action, adjusted_confidence) { - passed += 1; - } - } - } - Err(_) => { - // Batch parse failure — keep all findings in the chunk. - tracing::warn!( - "Failed to parse batch triage response for chunk starting at {chunk_start}: {cleaned}" - ); - for finding in chunk.iter_mut() { - finding.status = FindingStatus::Triaged; - passed += 1; - } - } - } + let mut passed = 0; + for (indices, answer) in answers { + for (pos, &i) in indices.iter().enumerate() { + let finding = &mut findings[i]; + // No usable answer for the chunk, or none for this finding: keep + // it as reported. + let Some(result) = answer.as_ref().and_then(|results| results.get(pos)) else { + finding.status = FindingStatus::Triaged; + passed += 1; + continue; + }; + let file_classification = classify_file_path(finding.file_path.as_deref()); + let adjusted_confidence = adjust_confidence(result.confidence, &file_classification); + finding.confidence = Some(adjusted_confidence); + finding.triage_action = Some(result.action.clone()); + finding.triage_rationale = Some(result.rationale.clone()); + if let Some(ref remediation) = result.remediation { + finding.remediation = Some(remediation.clone()); } - Err(e) => { - // On LLM error, keep all findings in the chunk. - tracing::warn!("LLM batch triage failed for chunk starting at {chunk_start}: {e}"); - for finding in chunk.iter_mut() { - finding.status = FindingStatus::Triaged; - passed += 1; - } + if apply_action(finding, &result.action, adjusted_confidence) { + passed += 1; } } } - passed } @@ -363,6 +394,33 @@ fn default_action() -> String { #[cfg(test)] mod tests { + + #[test] + fn the_triage_takes_the_most_severe_findings_first_and_stops_at_the_cap() { + use compliance_core::models::{ScanType, Severity}; + let finding = |severity| { + Finding::new( + "t".into(), + "f".into(), + "semgrep".into(), + ScanType::Sast, + "x".into(), + "d".into(), + severity, + ) + }; + let findings = vec![ + finding(Severity::Low), + finding(Severity::Critical), + finding(Severity::Medium), + ]; + assert_eq!(triage_selection(&findings), [1, 2, 0]); + + let many: Vec = (0..TRIAGE_MAX_FINDINGS + 10) + .map(|_| finding(Severity::Info)) + .collect(); + assert_eq!(triage_selection(&many).len(), TRIAGE_MAX_FINDINGS); + } use super::*; use compliance_core::models::scan::ScanType; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 4ee710a..f18e705 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -151,7 +151,7 @@ impl PipelineOrchestrator { "sast_vendor_code", SkipCode::VendorCode, format!( - "vendor and third-party code is not analysed for SAST findings: {}; \ + "vendor and third-party code is left out of the code findings (SAST, patterns, secrets, lint): {}; \ it is still covered by the SBOM", vendor.join(", ") ), @@ -160,7 +160,16 @@ impl PipelineOrchestrator { ) .await; } - match SemgrepScanner::new(vendor) + // The same vendor code is left out of every code scanner's findings: + // the pattern, secret and lint scanners walk the whole tree. + let outside_vendor = |findings: &mut Vec| { + findings.retain(|f| { + !f.file_path + .as_deref() + .is_some_and(|p| crate::pipeline::vendor::in_vendor_dir(p, &vendor)) + }) + }; + match SemgrepScanner::new(vendor.clone()) .scan(&repo_path, &repo_id) .instrument(tracing::info_span!("stage_sast")) .await @@ -335,7 +344,7 @@ impl PipelineOrchestrator { self.update_phase(scan_run_id, ScanPhase::PatternScanning) .await; { - let pattern_findings = async { + let mut pattern_findings: Vec = async { let mut findings = Vec::new(); let gdpr = GdprPatternScanner::new(); match gdpr.scan(&repo_path, &repo_id).await { @@ -351,6 +360,7 @@ impl PipelineOrchestrator { } .instrument(tracing::info_span!("stage_pattern_scanning")) .await; + outside_vendor(&mut pattern_findings); all_findings.extend(pattern_findings); } run_findings.save_new(&self.db, &mut all_findings).await?; @@ -366,7 +376,10 @@ impl PipelineOrchestrator { .instrument(tracing::info_span!("stage_secret_detection")) .await { - Ok(output) => all_findings.extend(output.findings), + Ok(mut output) => { + outside_vendor(&mut output.findings); + all_findings.extend(output.findings); + } Err(e) => tracing::warn!("[{repo_id}] Gitleaks failed: {e}"), } run_findings.save_new(&self.db, &mut all_findings).await?; @@ -382,7 +395,10 @@ impl PipelineOrchestrator { .instrument(tracing::info_span!("stage_lint_scanning")) .await { - Ok(output) => all_findings.extend(output.findings), + Ok(mut output) => { + outside_vendor(&mut output.findings); + all_findings.extend(output.findings); + } Err(e) => tracing::warn!("[{repo_id}] Lint scanning failed: {e}"), } run_findings.save_new(&self.db, &mut all_findings).await?; diff --git a/compliance-agent/src/pipeline/vendor.rs b/compliance-agent/src/pipeline/vendor.rs index e46d2d1..751d0a1 100644 --- a/compliance-agent/src/pipeline/vendor.rs +++ b/compliance-agent/src/pipeline/vendor.rs @@ -72,6 +72,16 @@ pub fn walk_outside<'a>( .filter_map(Result::ok) } +/// Whether `file` (relative to the scanned tree, `/`-separated) lies in one +/// of the `vendor` directories [`vendor_dirs`] found. +pub fn in_vendor_dir(file: &str, vendor: &[String]) -> bool { + let file = file.trim_start_matches("./"); + vendor.iter().any(|dir| { + file.strip_prefix(dir.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }) +} + /// The top-most vendor directories under `root`, relative to it with `/` /// separators, sorted. A directory inside one that already matched is not /// listed again. @@ -170,6 +180,22 @@ fn has_child_dir(dir: &Path, name: &str) -> bool { #[cfg(test)] #[allow(clippy::expect_used)] mod tests { + + #[test] + fn a_file_is_in_a_vendor_dir_only_below_it() { + let vendor = vec!["Middleware".to_string(), "Drivers/CMSIS".to_string()]; + assert!(in_vendor_dir( + "Middleware/ARM/mbedtls/library/aes.c", + &vendor + )); + assert!(in_vendor_dir( + "./Drivers/CMSIS/Include/core_cm33.h", + &vendor + )); + // A sibling that merely starts with the same letters is the customer's. + assert!(!in_vendor_dir("MiddlewareGlue/app.c", &vendor)); + assert!(!in_vendor_dir("Core/Src/main.c", &vendor)); + } use super::*; /// A scratch tree with the given directories, removed on drop. diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 2ccff33..00ea04b 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -1388,7 +1388,10 @@ tbody tr:last-child td { .form-group input, .form-group select, -.form-group textarea { +.form-group textarea, +.form-fields input:not([type="checkbox"]):not([type="radio"]), +.form-fields select, +.form-fields textarea { width: 100%; background: var(--bg-card); border: 1px solid var(--border-bright); @@ -1401,13 +1404,18 @@ tbody tr:last-child td { .form-group input:focus, .form-group select:focus, -.form-group textarea:focus { +.form-group textarea:focus, +.form-fields input:focus, +.form-fields select:focus, +.form-fields textarea:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 3px var(--border-accent); } -.form-group input::placeholder { +.form-group input::placeholder, +.form-fields input::placeholder, +.form-fields textarea::placeholder { color: var(--text-faint); } @@ -4971,3 +4979,82 @@ tbody tr:last-child td { width: min(380px, calc(100vw - 32px)); } } + + +/* Labels that wrap their field (the manual-findings form): the same small + mono caption as a .form-group label, above the field. */ +.form-fields label { + font-family: var(--font-mono); + font-size: 10px; + font-weight: 500; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-tertiary); +} + +.form-fields label > input, +.form-fields label > select, +.form-fields label > textarea { + font-family: var(--font-body); + font-size: 13px; + text-transform: none; + letter-spacing: normal; +} + +.form-fields h5 { + font-size: 13px; + font-weight: 600; + color: var(--text-primary); +} + +/* ── Adding a file to a target ── */ +.artifact-upload { + display: grid; + gap: 8px; +} + +.artifact-upload-hint { + font-size: 12.5px; + color: var(--text-tertiary); +} + +.artifact-upload-row { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: flex-end; +} + +.artifact-upload-row .form-group { + margin: 0; + min-width: 160px; +} + +.artifact-upload-file { + flex: 1; + min-width: 220px; +} + +.artifact-upload-note { + font-size: 12.5px; + color: var(--success); +} + +.artifact-upload-note.is-error { + color: var(--danger); +} + +/* An archive's password inside the target editor: badge, field and button on + one line, wrapping on narrow screens. */ +.archive-password { + display: flex; + flex: 1 1 100%; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} + +.archive-password input { + flex: 1; + min-width: 180px; +} diff --git a/compliance-dashboard/src/app.rs b/compliance-dashboard/src/app.rs index 052b85f..c49b78a 100644 --- a/compliance-dashboard/src/app.rs +++ b/compliance-dashboard/src/app.rs @@ -63,6 +63,9 @@ const GRAPH_VIZ_JS: Asset = asset!("/assets/graph-viz.js"); #[component] pub fn App() -> Element { rsx! { + // Also sent as the X-Robots-Tag header; in the markup it is visible + // in the page source and honoured by crawlers that read only HTML. + document::Meta { name: "robots", content: "noindex, nofollow" } document::Link { rel: "icon", href: FAVICON } document::Link { rel: "stylesheet", href: TAILWIND_CSS } document::Link { rel: "stylesheet", href: MAIN_CSS } diff --git a/compliance-dashboard/src/components/artifact_upload.rs b/compliance-dashboard/src/components/artifact_upload.rs new file mode 100644 index 0000000..5a3a742 --- /dev/null +++ b/compliance-dashboard/src/components/artifact_upload.rs @@ -0,0 +1,135 @@ +//! Add a file (an archive, a PLC project, a firmware image) to an existing +//! target: upload it at once, with its archive password if it has one. + +use dioxus::prelude::*; + +use crate::i18n::texts::{common, kinds, onboarding as otx, targets as tx}; +use crate::i18n::use_lang; +use crate::infrastructure::onboarding::{ + is_file_kind, plc_format_for, set_archive_password, upload_target_artifact, ArchivePassword, + PasswordOutcome, UNSUPPORTED_ARCHIVE, +}; + +/// The upload row for target `target_id`; `on_uploaded` runs once the file +/// (and its password, if it needs one) is stored. +#[component] +pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Element { + let lang = use_lang()(); + let mut kind = use_signal(|| "source_archive".to_string()); + let mut plc_format = use_signal(|| "plcopen_xml".to_string()); + let mut file = use_signal(|| Option::::None); + let mut password = use_signal(String::new); + let mut busy = use_signal(|| false); + let mut note = use_signal(|| Option::<(bool, String)>::None); + + rsx! { + div { class: "artifact-upload", + p { class: "artifact-upload-hint", {tx::UPLOAD_HINT.get(lang)} } + div { class: "artifact-upload-row", + div { class: "form-group", + label { {otx::KIND.get(lang)} } + select { + value: "{kind}", + oninput: move |e| kind.set(e.value()), + for (value, label) in kinds::ARTIFACT_KINDS { + if is_file_kind(value) { + option { value: "{value}", selected: kind() == value, {label.get(lang)} } + } + } + } + } + div { class: "form-group artifact-upload-file", + label { {otx::FILE.get(lang)} } + input { + r#type: "file", + onchange: move |evt| { + let Some(picked) = evt.files().into_iter().next() else { return; }; + if let Some(format) = plc_format_for(&picked.name()) { + plc_format.set(format.to_string()); + } + note.set(None); + file.set(Some(picked)); + }, + } + } + if kind() == "plc_project" { + div { class: "form-group", + label { {otx::FORMAT.get(lang)} } + select { + value: "{plc_format}", + oninput: move |e| plc_format.set(e.value()), + option { value: "plcopen_xml", selected: plc_format() == "plcopen_xml", "PLCopen XML" } + option { value: "structured_text", selected: plc_format() == "structured_text", "Structured Text" } + option { value: "project_archive", selected: plc_format() == "project_archive", "Project archive (.projectarchive)" } + } + } + } + div { class: "form-group", + label { {common::ARCHIVE_PASSWORD.get(lang)} } + input { + r#type: "password", + autocomplete: "off", + value: "{password}", + oninput: move |e| password.set(e.value()), + } + } + button { + class: "btn btn-primary", + disabled: file().is_none() || busy(), + onclick: move |_| { + let Some(picked) = file() else { return; }; + let (id, kind, pw) = (target_id.clone(), kind(), password()); + let format = (kind == "plc_project").then(|| plc_format.read().clone()); + busy.set(true); + spawn(async move { + let result = match upload_target_artifact(id.clone(), kind, format, picked.into()).await { + Err(e) => { + let e = e.to_string(); + Err(if e.contains(UNSUPPORTED_ARCHIVE) { + common::UNSUPPORTED_ARCHIVE.get(lang).to_string() + } else { + format!("{}: {e}", otx::UPLOAD_FAILED.get(lang)) + }) + } + Ok(resp) => { + // The newest artifact is the one just uploaded. + let uploaded = resp.data["artifacts"] + .as_array() + .and_then(|a| a.last()) + .cloned() + .unwrap_or_default(); + if ArchivePassword::of(&uploaded) != ArchivePassword::Missing { + Ok(()) + } else if pw.is_empty() { + Err(common::PASSWORD_NEEDED.get(lang).to_string()) + } else { + let artifact_id = uploaded["id"].as_str().unwrap_or_default().to_string(); + match set_archive_password(id, artifact_id, pw).await { + Ok(PasswordOutcome::Saved | PasswordOutcome::NotEncrypted) => Ok(()), + Ok(PasswordOutcome::Wrong) => Err(common::PASSWORD_WRONG.get(lang).to_string()), + Err(e) => Err(e.to_string()), + } + } + } + }; + busy.set(false); + match result { + Ok(()) => { + note.set(Some((true, tx::UPLOADED.get(lang).to_string()))); + file.set(None); + password.set(String::new()); + on_uploaded.call(()); + } + Err(problem) => note.set(Some((false, problem))), + } + }); + }, + if busy() { {otx::UPLOADING.get(lang)} } else { {tx::UPLOAD.get(lang)} } + } + } + if let Some((ok, text)) = note() { + p { class: if ok { "artifact-upload-note" } else { "artifact-upload-note is-error" }, "{text}" } + } + } + } +} diff --git a/compliance-dashboard/src/components/manual_findings.rs b/compliance-dashboard/src/components/manual_findings.rs index 1a4ca25..edbdbdf 100644 --- a/compliance-dashboard/src/components/manual_findings.rs +++ b/compliance-dashboard/src/components/manual_findings.rs @@ -49,7 +49,7 @@ pub fn ManualFindingsPanel(target_id: String, on_change: EventHandler<()>) -> El let area = "width: 100%; min-height: 60px;"; rsx! { - div { style: "margin-top: 8px;", + div { class: "form-fields", style: "margin-top: 8px;", div { style: "opacity: 0.75; font-size: 0.85em; margin-bottom: 8px;", {tx::HINT.get(lang)} } div { style: "display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end;", label { style: field, diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 3bfdb8d..eb32580 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -1,4 +1,5 @@ pub mod app_shell; +pub mod artifact_upload; pub mod attack_chain; pub mod code_inspector; pub mod code_snippet; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index e948e0f..fe2dc16 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -851,6 +851,24 @@ pub mod targets { en: "Results of penetration tests or DAST runs, entered by hand or imported as \ SARIF or ZAP JSON. They appear next to the other findings.", }; + pub const UPLOAD_TITLE: Text = Text { + de: "Datei hinzufügen", + en: "Add a file", + }; + pub const UPLOAD_HINT: Text = Text { + de: "Ein Archiv (zip, tar, tar.gz), ein SPS-Projekt oder ein Firmware-Image. Die Datei \ + wird sofort hochgeladen und bei der nächsten Prüfung geprüft.", + en: "An archive (zip, tar, tar.gz), a PLC project or a firmware image. It is uploaded \ + at once and checked by the next scan.", + }; + pub const UPLOAD: Text = Text { + de: "Hochladen", + en: "Upload", + }; + pub const UPLOADED: Text = Text { + de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.", + en: "Uploaded. Start a scan to check the file.", + }; } /// Target types and artifact kinds, keyed by their API value. diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 9f208b0..919afcb 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -223,6 +223,28 @@ pub fn demo_seed_default_selection(targets: &[DemoSeedTarget], source_only: bool /// Validate a target name. The name is used as the clone directory downstream, /// so it must be a single safe segment (no slashes) and free of stray spaces. +/// Artifact kinds provided as an uploaded file (rather than a URL/text ref). +pub fn is_file_kind(kind: &str) -> bool { + matches!( + kind, + "plc_project" | "firmware_image" | "source_archive" | "mobile_package" + ) +} + +/// The PLC project format a file's name suggests, if any. +pub fn plc_format_for(file_name: &str) -> Option<&'static str> { + let name = file_name.to_ascii_lowercase(); + if name.ends_with(".projectarchive") || name.ends_with(".project") { + Some("project_archive") + } else if name.ends_with(".xml") || name.ends_with(".plcopen") { + Some("plcopen_xml") + } else if name.ends_with(".st") || name.ends_with(".exp") || name.ends_with(".scl") { + Some("structured_text") + } else { + None + } +} + pub fn validate_target_name(name: &str) -> Option { let n = name.trim(); if n.is_empty() { @@ -522,6 +544,18 @@ pub async fn trigger_target_scan(id: String) -> Result bool { matches!(kind, "live_url") } -/// Artifact kinds provided as an uploaded file (rather than a URL/text ref). -fn is_file_kind(kind: &str) -> bool { - matches!( - kind, - "plc_project" | "firmware_image" | "source_archive" | "mobile_package" - ) -} - /// A file staged in the wizard. It holds the browser's file handle, not its /// contents: the file is streamed straight from disk when it is uploaded, so a /// 500 MB firmware image is never copied into WASM memory. @@ -244,13 +237,8 @@ pub fn OnboardingPage() -> Element { let Some(file) = evt.files().into_iter().next() else { return; }; let name = file.name(); // Auto-detect the PLC format from the file extension. - let lname = name.to_ascii_lowercase(); - if lname.ends_with(".projectarchive") || lname.ends_with(".project") { - new_plc_format.set("project_archive".to_string()); - } else if lname.ends_with(".xml") || lname.ends_with(".plcopen") { - new_plc_format.set("plcopen_xml".to_string()); - } else if lname.ends_with(".st") || lname.ends_with(".exp") || lname.ends_with(".scl") { - new_plc_format.set("structured_text".to_string()); + if let Some(format) = plc_format_for(&name) { + new_plc_format.set(format.to_string()); } // Keep the handle only; the bytes are read // (streamed) at upload time. diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 44f7d0f..9776024 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -7,6 +7,7 @@ use dioxus_free_icons::icons::bs_icons::*; use dioxus_free_icons::Icon; use crate::app::Route; +use crate::components::artifact_upload::ArtifactUpload; use crate::components::cra_bar::CraBar; use crate::components::manual_findings::ManualFindingsPanel; use crate::components::scan_coverage::ScanCoverage; @@ -18,9 +19,9 @@ use crate::i18n::use_lang; use crate::infrastructure::evidence::{evidence_pack_url, fetch_compliance, CraCounts}; use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery}; use crate::infrastructure::onboarding::{ - delete_target, fetch_applicable_scans, fetch_target, set_archive_password, trigger_target_scan, - update_target, validate_artifact_ref, validate_target_name, ArchivePassword, ArtifactInputDto, - PasswordOutcome, + delete_target, fetch_applicable_scans, fetch_target, is_file_kind, set_archive_password, + trigger_target_scan, update_target, validate_artifact_ref, validate_target_name, + ArchivePassword, ArtifactInputDto, PasswordOutcome, }; use crate::infrastructure::platform::{use_source_only, SourceOnlyNote}; @@ -427,7 +428,7 @@ fn TargetEditor( }; rsx! { div { class: "modal-overlay", - div { class: "modal-dialog", + div { class: "modal-dialog form-fields", h3 { {tx::EDIT_TITLE.get(lang)} } div { class: "form-group", label { {tx::COL_NAME.get(lang)} } @@ -504,8 +505,11 @@ fn TargetEditor( select { value: "{e_kind}", oninput: move |e| e_kind.set(e.value()), + // Files are uploaded below; this row adds references. for (v, l) in kinds::ARTIFACT_KINDS { - option { value: "{v}", selected: e_kind() == v, {l.get(lang)} } + if !is_file_kind(v) { + option { value: "{v}", selected: e_kind() == v, {l.get(lang)} } + } } } } @@ -564,6 +568,16 @@ fn TargetEditor( if let Some(err) = e_source_err.clone() { div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" } } + h4 { class: "target-subhead", {tx::UPLOAD_TITLE.get(lang)} } + ArtifactUpload { + target_id: eid.clone(), + // The editor's artifact list is now stale: saving it + // would drop the new file, so close and reload. + on_uploaded: move |_| { + toasts.push(ToastType::Success, tx::UPLOADED.get(lang)); + on_saved.call(()); + }, + } div { class: "modal-actions", button { class: "btn btn-secondary", @@ -618,12 +632,12 @@ fn ArchivePasswordField( ("badge badge-medium", common::PASSWORD_MISSING) }; rsx! { + div { class: "archive-password", span { class: "{badge}", {label.get(lang)} } input { r#type: "password", autocomplete: "off", placeholder: common::ARCHIVE_PASSWORD.get(lang), - style: "flex: 1; min-width: 180px;", value: "{password}", oninput: move |e| password.set(e.value()), } @@ -651,5 +665,6 @@ fn ArchivePasswordField( if let Some(text) = note() { span { style: "font-size: 0.85em; opacity: 0.8;", "{text}" } } + } } }