diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index 87ae16c..644ce72 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -173,6 +173,9 @@ pub async fn compliance_view( "data": { "target_id": id, "target_name": inputs.target.name, + // Whether Prüfwerk opens tickets for the target's findings; the + // finding page offers Breakpilot Git when it does not. + "issue_tracker_connected": inputs.target.issue_tracker_connected(), "counts": state_counts(&controls), "last_scan": inputs.last_run, "sbom_components": inputs.sbom.len(), diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 0792a2a..393e458 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -569,6 +569,19 @@ impl OnboardedTarget { && classification.suggested != self.target_type; detected.then_some(classification.suggested) } + + /// Whether Prüfwerk opens tickets for this target's findings on its own: + /// the target came from a managed git source, or an issue tracker of a + /// known type is configured on it. A tracker block without a type opens + /// nothing, so it does not count. + pub fn issue_tracker_connected(&self) -> bool { + self.source_repo.is_some() + || self + .scan_config + .issue_tracker + .as_ref() + .is_some_and(|tracker| tracker.tracker_type.is_some()) + } } pub fn default_compliance_profile(target_type: TargetType) -> ComplianceProfile { @@ -802,6 +815,28 @@ mod tests { assert_eq!(onboarded.detected_type(&android), None); } + #[test] + fn a_target_has_a_tracker_when_one_is_set_or_it_is_managed() { + let mut target = OnboardedTarget::new("fw".into(), TargetType::BackendService); + assert!(!target.issue_tracker_connected()); + // A tracker block without a type cannot open tickets. + target.scan_config.issue_tracker = Some(IssueTrackerConfig::default()); + assert!(!target.issue_tracker_connected()); + target.scan_config.issue_tracker = Some(IssueTrackerConfig { + tracker_type: Some(TrackerType::GitLab), + ..Default::default() + }); + assert!(target.issue_tracker_connected()); + // A managed repository's issues are opened by its git source. + let mut managed = OnboardedTarget::new("gt-mobile".into(), TargetType::BackendService); + managed.source_repo = Some(super::super::git_source::SourceRepo { + base_url: "https://kunde.code.example".into(), + repo_id: 7, + full_name: "kunde/gt-mobile".into(), + }); + assert!(managed.issue_tracker_connected()); + } + fn sample_target() -> OnboardedTarget { let mut t = OnboardedTarget::new("acme-web".to_string(), TargetType::WebApp); t.artifacts.push(Artifact::git_repo( diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index b453029..0a9f3d1 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -638,6 +638,56 @@ code { color: var(--text-primary); } +/* ── A finding as ticket text, and the Breakpilot Git hint ── */ + +.ticket-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + margin-bottom: 16px; +} + +.ticket-bar .btn { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12.5px; + padding: 5px 10px; +} + +.ticket-copied { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 12.5px; + color: var(--success); +} + +.ticket-copy-failed { + color: var(--danger); +} + +.ticket-hint { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 6px; + margin: 0; + font-size: 12.5px; + color: var(--text-secondary); +} + +.ticket-hint svg { + color: var(--accent); + flex-shrink: 0; +} + +.ticket-hint a { + color: var(--accent); + font-weight: 500; +} + /* ── Page Header ── */ diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 5cada51..8c6908a 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2240,6 +2240,42 @@ pub mod findings { de: "Erfasst von", en: "Reported by", }; + /// The button that copies one finding as Markdown for a ticket. + pub const COPY_TICKET: Text = Text { + de: "Als Ticket-Text kopieren", + en: "Copy as ticket text", + }; + pub const COPIED: Text = Text { + de: "Kopiert", + en: "Copied", + }; + pub const COPY_FAILED: Text = Text { + de: "Kopieren fehlgeschlagen", + en: "Copy failed", + }; + /// Shown on a finding whose target opens no tickets on its own. + pub const TICKET_HINT: Text = Text { + de: "Mit Breakpilot Git werden Tickets automatisch angelegt.", + en: "With Breakpilot Git, tickets are created automatically.", + }; + pub const CONNECT_TRACKER: Text = Text { + de: "Tracker für dieses Prüfobjekt anbinden", + en: "Connect a tracker to this target", + }; + pub const MANAGED_GIT_GUIDE: Text = Text { + de: "Anleitung Managed Git", + en: "Managed Git guide", + }; + /// The copied ticket text's section on the CRA topics. + pub const CRA_TOPICS: Text = Text { + de: "CRA-Themen", + en: "CRA topics", + }; + /// The copied ticket text's link back to the finding. + pub const OPEN_IN_PRUEFWERK: Text = Text { + de: "Im Prüfwerk öffnen", + en: "Open in Prüfwerk", + }; /// A finding status in words. Exhaustive: a new status needs both. pub fn status(status: &FindingStatus) -> Text { diff --git a/compliance-dashboard/src/pages/finding_detail.rs b/compliance-dashboard/src/pages/finding_detail.rs index 0edc12f..c2b5db3 100644 --- a/compliance-dashboard/src/pages/finding_detail.rs +++ b/compliance-dashboard/src/pages/finding_detail.rs @@ -7,14 +7,14 @@ use crate::components::code_snippet::CodeSnippet; use crate::components::markdown::render_markdown; use crate::components::page_header::PageHeader; use crate::components::severity_badge::SeverityBadge; -use crate::i18n::texts::{common, findings as tx, graph as graph_tx}; -use crate::i18n::{format_count, format_time, use_lang}; +use crate::i18n::texts::{common, finding_breakdown, findings as tx, graph as graph_tx}; +use crate::i18n::{format_count, format_time, use_lang, Lang}; use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl}; use crate::infrastructure::findings::{location, mask_secrets, wire_name}; use crate::infrastructure::graph::fetch_impact; use crate::pages::findings::status_icon; use crate::pages::graph_view::impact_has_content; -use compliance_core::models::{FindingStatus, ReviewReason, ScanType}; +use compliance_core::models::{Finding, FindingStatus, ReviewReason, ScanType}; /// What happened to the last save on this page, shown next to what was saved. #[derive(Debug, Clone, PartialEq)] @@ -38,6 +38,9 @@ pub fn FindingDetailPage(id: String) -> Element { // before it is saved. let mut reasoning_for = use_signal(|| Option::::None); let mut risk_reason = use_signal(String::new); + // The last copy as ticket text: `Some(true)` copied, `Some(false)` the + // browser refused; cleared after a moment. + let mut ticket_copied = use_signal(|| Option::::None); let mut finding = use_resource(move || { let fid = finding_id.clone(); @@ -137,6 +140,61 @@ pub fn FindingDetailPage(id: String) -> Element { .iter() .cloned() .partition(|c| c.starts_with("cra-")); + let cra_topics: Vec<(String, Option)> = cra_refs + .into_iter() + .map(|c| { + let title = control_title(&c); + (c, title) + }) + .collect(); + // Offer Breakpilot Git only once the agent said the target opens + // no tickets (not while loading), and not on a finding with one. + let show_ticket_hint = f.tracker_issue_url.is_none() + && status_data + .as_ref() + .and_then(|d| d["issue_tracker_connected"].as_bool()) + == Some(false); + let tracker_guide = docs_page( + &me.docs_url, + "guide/repositories#connecting-an-issue-tracker", + ); + let managed_git_guide = docs_page( + &me.docs_url, + match lang { + Lang::De => "guide/managed-git", + Lang::En => "guide/managed-git-en", + }, + ); + // `move` closures take ownership (like a Python closure capturing + // by value), so the copy handler gets its own clones. + let finding_for_copy = f.clone(); + let topics_for_copy = cra_topics.clone(); + let finding_id_for_copy = id.clone(); + let copy_ticket = move |_: MouseEvent| { + let link = format!( + "{}{}", + page_origin(), + Route::FindingDetailPage { + id: finding_id_for_copy.clone() + } + ); + let text = ticket_markdown(&finding_for_copy, &topics_for_copy, &link, lang); + spawn(async move { + // A JSON string is a valid JavaScript string literal. + let copied = match serde_json::to_string(&text) { + Ok(literal) => document::eval(&format!( + "await navigator.clipboard.writeText({literal}); return true;" + )) + .await + .is_ok(), + Err(_) => false, + }; + ticket_copied.set(Some(copied)); + #[cfg(feature = "web")] + gloo_timers::future::TimeoutFuture::new(2_000).await; + ticket_copied.set(None); + }); + }; rsx! { div { class: "back-nav", button { @@ -176,6 +234,40 @@ pub fn FindingDetailPage(id: String) -> Element { } } + div { class: "ticket-bar", + button { + class: "btn btn-ghost", + onclick: copy_ticket, + Icon { icon: BsClipboard, width: 14, height: 14 } + " {tx::COPY_TICKET.get(lang)}" + } + span { class: "ticket-copied", role: "status", + match ticket_copied() { + Some(true) => rsx! { + Icon { icon: BsCheckLg, width: 14, height: 14 } + " {tx::COPIED.get(lang)}" + }, + Some(false) => rsx! { + span { class: "ticket-copy-failed", {tx::COPY_FAILED.get(lang)} } + }, + None => rsx! {}, + } + } + if show_ticket_hint { + p { class: "ticket-hint", + Icon { icon: BsInfoCircle, width: 14, height: 14 } + span { {tx::TICKET_HINT.get(lang)} } + a { href: "{tracker_guide}", target: "_blank", rel: "noopener", + {tx::CONNECT_TRACKER.get(lang)} + } + span { "·" } + a { href: "{managed_git_guide}", target: "_blank", rel: "noopener", + {tx::MANAGED_GIT_GUIDE.get(lang)} + } + } + } + } + div { class: "card", div { class: "card-header", {tx::DESCRIPTION.get(lang)} } // A semgrep rule's message is Markdown (paragraphs, code @@ -220,10 +312,10 @@ pub fn FindingDetailPage(id: String) -> Element { if !f.control_refs.is_empty() { span { style: "opacity: 0.7;", {tx::CRA_REFS.get(lang)} } ul { class: "finding-refs", - for c in cra_refs { + for (c, title) in cra_topics { li { span { class: "badge badge-info", "{c}" } - if let Some(title) = control_title(&c) { + if let Some(title) = title { span { " {title}" } } } @@ -579,10 +671,92 @@ fn tracker_note( Some(format!("{} {login}", tx::tracker_change(kind).get(lang))) } +/// One finding as Markdown for a ticket the user opens by hand: title, +/// severity, status, location, description, the AI's assessment, the CRA +/// topics and a link back. A committed secret is shortened as on screen. +/// +/// # Arguments +/// +/// * `finding` - the finding shown on the page +/// * `cra_topics` - its CRA control ids, each with its title when known +/// * `link` - the finding's page in Prüfwerk +/// * `lang` - the UI language, for the labels +/// +/// # Returns +/// +/// The Markdown text, ending in a newline. +fn ticket_markdown( + finding: &Finding, + cra_topics: &[(String, Option)], + link: &str, + lang: Lang, +) -> String { + let shown = |text: &str| { + if finding.scan_type == ScanType::SecretDetection { + mask_secrets(text.trim()) + } else { + text.trim().to_string() + } + }; + let mut md = format!( + "## {}\n\n- **{}:** {}\n- **{}:** {}\n", + finding.title, + tx::COL_SEVERITY.get(lang), + finding_breakdown::severity(&finding.severity).get(lang), + tx::COL_STATUS.get(lang), + tx::finding_status(finding).get(lang), + ); + if let Some(place) = location(finding.file_path.as_deref(), finding.line_number) { + md.push_str(&format!("- **{}:** `{place}`\n", tx::WHERE.get(lang))); + } + md.push_str(&format!( + "\n### {}\n\n{}\n", + tx::DESCRIPTION.get(lang), + shown(&finding.description) + )); + if let Some(rationale) = &finding.triage_rationale { + md.push_str(&format!( + "\n### {}\n\n{}\n", + tx::TRIAGE.get(lang), + shown(rationale) + )); + } + if !cra_topics.is_empty() { + md.push_str(&format!("\n### {}\n\n", tx::CRA_TOPICS.get(lang))); + for (id, title) in cra_topics { + match title { + Some(title) => md.push_str(&format!("- `{id}` {title}\n")), + None => md.push_str(&format!("- `{id}`\n")), + } + } + } + md.push_str(&format!( + "\n[{}]({link})\n", + tx::OPEN_IN_PRUEFWERK.get(lang) + )); + md +} + +/// A page of the docs site: `docs_url` is the site's root as configured +/// (`/docs/` or a full URL, with or without the trailing slash), `page` the +/// path below it (`guide/managed-git`). +fn docs_page(docs_url: &str, page: &str) -> String { + format!("{}/{page}", docs_url.trim_end_matches('/')) +} + +/// The dashboard's origin (`https://pruefwerk.example`) in the browser; empty +/// elsewhere, which leaves a link relative. +fn page_origin() -> String { + #[cfg(feature = "web")] + if let Some(origin) = web_sys::window().and_then(|w| w.location().origin().ok()) { + return origin; + } + String::new() +} + #[cfg(test)] mod tests { use super::*; - use crate::i18n::Lang; use compliance_core::models::{AuthInfo, StatusChange}; fn change(by: &str, by_name: Option<&str>) -> StatusChange { @@ -664,4 +838,85 @@ mod tests { assert_eq!(changed_by(&c, &me(), Lang::De), "Benutzer 0b7d51aa"); assert_eq!(changed_by(&c, &me(), Lang::En), "User 0b7d51aa"); } + + fn sql_injection() -> Finding { + let mut f = Finding::new( + "repo".to_string(), + "fp".to_string(), + "semgrep".to_string(), + ScanType::Sast, + "SQL-Injection im Login".to_string(), + "Die Abfrage setzt Benutzereingaben direkt ein.\n".to_string(), + compliance_core::models::Severity::High, + ); + f.file_path = Some("src/login.rs".to_string()); + f.line_number = Some(42); + f.triage_rationale = Some("Erreichbar über das Login-Formular.".to_string()); + f + } + + #[test] + fn the_ticket_text_holds_the_finding_and_a_link_back() { + let topics = vec![ + ( + "cra-ai-2c".to_string(), + Some("Schutz vor unbefugtem Zugriff".to_string()), + ), + ("cra-ai-2f".to_string(), None), + ]; + let md = ticket_markdown( + &sql_injection(), + &topics, + "https://pruefwerk.example/findings/abc", + Lang::De, + ); + assert_eq!( + md, + "## SQL-Injection im Login\n\n\ + - **Schweregrad:** Hoch\n\ + - **Status:** Offen\n\ + - **Fundstelle:** `src/login.rs:42`\n\ + \n### Beschreibung\n\nDie Abfrage setzt Benutzereingaben direkt ein.\n\ + \n### Einschätzung\n\nErreichbar über das Login-Formular.\n\ + \n### CRA-Themen\n\n\ + - `cra-ai-2c` Schutz vor unbefugtem Zugriff\n\ + - `cra-ai-2f`\n\ + \n[Im Prüfwerk öffnen](https://pruefwerk.example/findings/abc)\n" + ); + } + + #[test] + fn the_ticket_text_leaves_out_what_the_finding_lacks() { + let mut f = sql_injection(); + f.file_path = None; + f.triage_rationale = None; + let md = ticket_markdown(&f, &[], "/findings/abc", Lang::En); + assert!(md.contains("- **Severity:** High\n")); + assert!(!md.contains("Location")); + assert!(!md.contains("Triage")); + assert!(!md.contains("CRA topics")); + assert!(md.ends_with("\n[Open in Prüfwerk](/findings/abc)\n")); + } + + #[test] + fn the_ticket_text_shortens_a_committed_secret() { + let mut f = sql_injection(); + f.scan_type = ScanType::SecretDetection; + f.description = "Token ghp_a1B2c3D4e5F6g7H8i9J0 im Code".to_string(); + let md = ticket_markdown(&f, &[], "/findings/abc", Lang::De); + assert!(!md.contains("ghp_a1B2c3D4e5F6g7H8i9J0")); + assert!(md.contains("ghp_••••••••")); + } + + #[test] + fn a_docs_page_joins_the_configured_root() { + assert_eq!( + docs_page("/docs/", "guide/managed-git"), + "/docs/guide/managed-git" + ); + assert_eq!( + docs_page("https://docs.example/pruefwerk", "guide/managed-git-en"), + "https://docs.example/pruefwerk/guide/managed-git-en" + ); + } } diff --git a/docs/guide/findings.md b/docs/guide/findings.md index c01339d..0190f00 100644 --- a/docs/guide/findings.md +++ b/docs/guide/findings.md @@ -93,6 +93,24 @@ in this order: - **Ihre Einschätzung** (Developer feedback) -- a free-text note, saved when you leave the field. +### Turning a finding into a ticket + +Below the badges, **Als Ticket-Text kopieren** (Copy as ticket text) copies +this one finding to the clipboard as Markdown: title, severity, status, +location (file and line), description, the automated review's assessment, the +**CRA-Themen** (CRA topics) and a link back to the finding in Prüfwerk. Paste +it into a new ticket in any tracker; **Kopiert** (Copied) confirms the copy. +The labels follow the dashboard's language, and a committed secret is +shortened as on the page. + +When the finding's target has no issue tracker connected and the finding has +no ticket yet, a hint beside the button reads "Mit Breakpilot Git werden +Tickets automatisch angelegt" (With Breakpilot Git, tickets are created +automatically). It links to +[Connecting an Issue Tracker](/guide/repositories#connecting-an-issue-tracker) +and to [Managed Git](/guide/managed-git). A target counts as connected when an +issue tracker is configured on it or its repository comes from Managed Git. + ## Severity Levels | Severity | Description | Typical Examples | diff --git a/docs/guide/issues.md b/docs/guide/issues.md index e303c9b..bfce3d4 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -80,3 +80,7 @@ Issues are deduplicated using the same fingerprint hash that deduplicates findin ## Linked Issues in Finding Detail When viewing a [finding's detail page](/guide/findings#finding-detail), you will see a **Verknüpftes Ticket** (Linked issue) section if an issue was created for that finding. This provides a direct link to the external tracker issue, making it easy to jump between the security context in Prüfwerk and the development workflow in your tracker. + +## Without a Connected Tracker + +Without a tracker, open the ticket by hand: **Als Ticket-Text kopieren** (Copy as ticket text) on the finding's page copies the finding as Markdown, ready to paste into a new ticket. On a target without a tracker the page also points to Breakpilot Git, where tickets are created automatically. See [Turning a finding into a ticket](/guide/findings#turning-a-finding-into-a-ticket).