diff --git a/README.md b/README.md index 4c918e4..159b6fd 100644 --- a/README.md +++ b/README.md @@ -193,7 +193,7 @@ The agent exposes a REST API on port 3001: | `PATCH` | `/api/v1/findings/bulk-status` | Update the status of several findings | | `GET` | `/api/v1/sbom` | List dependencies | | `GET` | `/api/v1/sbom/export` | Export a target's SBOM (CycloneDX 1.5 or SPDX 2.3) | -| `GET` | `/api/v1/issues` | List cross-tracker issues | +| `GET` | `/api/v1/issues` | List cross-tracker issues (search `q`, `status=open\|closed`, `repo_id`) | | `GET` | `/api/v1/scan-runs` | Scan execution history | | `GET` | `/api/v1/graph/{repo_id}` | Code knowledge graph | | `POST` | `/api/v1/graph/{repo_id}/build` | Trigger graph build | diff --git a/compliance-agent/src/api/handlers/dto.rs b/compliance-agent/src/api/handlers/dto.rs index 6fd34ed..71e6633 100644 --- a/compliance-agent/src/api/handlers/dto.rs +++ b/compliance-agent/src/api/handlers/dto.rs @@ -88,6 +88,65 @@ impl FindingsFilter { } } +/// Open or closed, as the tickets list filters them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TicketState { + /// Open or in progress. + Open, + /// Closed or resolved. + Closed, +} + +impl TicketState { + /// The stored statuses (`in_progress`) this state stands for. + pub fn statuses(self) -> Vec { + let closed = self == Self::Closed; + compliance_core::models::IssueStatus::ALL + .iter() + .filter(|s| s.is_closed() == closed) + .map(ToString::to_string) + .collect() + } +} + +/// The query of the tickets list (`GET /api/v1/issues`). +#[derive(Deserialize)] +pub struct IssuesFilter { + /// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`). + #[serde(default)] + pub q: Option, + /// Only open or only closed tickets; an unknown value is refused (400). + #[serde(default)] + pub status: Option, + /// Only the tickets of one target: of its findings and its CVEs. + #[serde(default)] + pub repo_id: Option, + #[serde(default = "default_page", deserialize_with = "de_page")] + pub page: u64, + #[serde(default = "default_limit", deserialize_with = "de_limit")] + pub limit: i64, +} + +impl IssuesFilter { + /// Documents to skip for this page. Bounded by construction. + pub fn skip(&self) -> u64 { + self.page + .saturating_sub(1) + .saturating_mul(self.limit as u64) + } + + /// The search term, trimmed; `None` when there is none. + pub fn search(&self) -> Option<&str> { + self.q.as_deref().map(str::trim).filter(|q| !q.is_empty()) + } + + /// The target to filter by; `None` for all. + pub fn target(&self) -> Option<&str> { + self.repo_id.as_deref().filter(|id| !id.is_empty()) + } +} + /// Fields a caller may sort findings by. /// /// `sort_by` went into the sort document verbatim, so a caller could sort on @@ -478,6 +537,55 @@ mod tests { assert_eq!(f.severity.as_deref(), Some("")); } + // ── IssuesFilter ───────────────────────────────────────────── + + #[test] + fn issues_filter_defaults_and_clamps() { + let f: IssuesFilter = serde_json::from_str("{}").unwrap(); + assert_eq!(f.search(), None); + assert_eq!(f.status, None); + assert_eq!(f.target(), None); + assert_eq!((f.page, f.limit), (1, 50)); + + let f: IssuesFilter = serde_json::from_str(r#"{"limit":5000,"page":0}"#).unwrap(); + assert_eq!(f.limit, MAX_PAGE_SIZE); + assert_eq!(f.skip(), 0); + } + + #[test] + fn issues_filter_ignores_blank_search_and_target() { + let f: IssuesFilter = serde_json::from_str(r#"{"q":" ","repo_id":""}"#).unwrap(); + assert_eq!(f.search(), None); + assert_eq!(f.target(), None); + + let f: IssuesFilter = serde_json::from_str(r##"{"q":" #913 ","repo_id":"t1"}"##).unwrap(); + assert_eq!(f.search(), Some("#913")); + assert_eq!(f.target(), Some("t1")); + } + + #[test] + fn issues_filter_status_is_open_or_closed_only() { + let f: IssuesFilter = serde_json::from_str(r#"{"status":"closed"}"#).unwrap(); + assert_eq!(f.status, Some(TicketState::Closed)); + assert!(serde_json::from_str::(r#"{"status":"$ne"}"#).is_err()); + } + + #[test] + fn ticket_states_cover_every_stored_status_once() { + assert_eq!(TicketState::Open.statuses(), ["open", "in_progress"]); + assert_eq!(TicketState::Closed.statuses(), ["closed", "resolved"]); + // The names are the stored ones. + for name in TicketState::Open + .statuses() + .into_iter() + .chain(TicketState::Closed.statuses()) + { + let status: compliance_core::models::IssueStatus = + serde_json::from_value(json!(name)).unwrap(); + assert_eq!(status.to_string(), name); + } + } + // ── ApiResponse ────────────────────────────────────────────── #[test] diff --git a/compliance-agent/src/api/handlers/issues.rs b/compliance-agent/src/api/handlers/issues.rs index 71d4b87..373c0be 100644 --- a/compliance-agent/src/api/handlers/issues.rs +++ b/compliance-agent/src/api/handlers/issues.rs @@ -1,32 +1,42 @@ use axum::extract::{Extension, Query}; use axum::Json; -use mongodb::bson::doc; +use mongodb::bson::{doc, Bson, Document}; use super::dto::*; +use compliance_core::models::issue::cve_issue_prefix; use compliance_core::models::TrackerIssue; use compliance_core::tenant_ctx::TenantCtx; -#[tracing::instrument(skip_all)] +/// The tenant's tickets, newest first, searched and filtered by `filter`. +/// +/// A ticket stores no target, only the finding it is about: the target filter +/// first looks up the ids of the target's findings that have a ticket. +#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))] pub async fn list_issues( Extension(agent): AgentExt, tenant: TenantCtx, - Query(params): Query, + Query(filter): Query, ) -> ApiResult> { let db = tenant_db(&agent, &tenant).await?; let db = &db; - let skip = params.skip(); + let finding_ids = match filter.target() { + Some(repo_id) => Some(ticketed_finding_ids(db, repo_id).await), + None => None, + }; + let query = issues_query(&filter, finding_ids.as_deref()); + let skip = filter.skip(); let total = db .tracker_issues() - .count_documents(doc! {}) + .count_documents(query.clone()) .await .unwrap_or(0); let issues = match db .tracker_issues() - .find(doc! {}) + .find(query) .sort(doc! { "created_at": -1 }) .skip(skip) - .limit(params.limit) + .limit(filter.limit) .await { Ok(cursor) => collect_cursor_async(cursor).await, @@ -39,6 +49,198 @@ pub async fn list_issues( Ok(Json(ApiResponse { data: issues, total: Some(total), - page: Some(params.page), + page: Some(filter.page), })) } + +/// The ids (hex) of the findings of target `repo_id` that have a ticket. +/// +/// Storing a finding's ticket sets the finding's `tracker_issue_url` +/// (`pipeline::issue_creation`), so the other findings are left out. A failed +/// lookup is logged and leaves only the target's CVE tickets. +async fn ticketed_finding_ids(db: &crate::database::Database, repo_id: &str) -> Vec { + let filter = doc! { "repo_id": repo_id, "tracker_issue_url": { "$ne": Bson::Null } }; + match db.findings().distinct("_id", filter).await { + Ok(ids) => ids + .iter() + .filter_map(Bson::as_object_id) + .map(|id| id.to_hex()) + .collect(), + Err(e) => { + tracing::warn!("Failed to look up the target's findings: {e}"); + Vec::new() + } + } +} + +/// The Mongo filter of the tickets list. +/// +/// # Arguments +/// +/// * `filter` - the caller's search and filters +/// * `finding_ids` - for a target filter, the ids of the target's findings +/// with a ticket ([`ticketed_finding_ids`]); `None` without one +/// +/// # Returns +/// +/// `{}` for no filter, else an `$and` of the search (title or ticket number), +/// the status and the target. +fn issues_query(filter: &IssuesFilter, finding_ids: Option<&[String]>) -> Document { + let mut clauses: Vec = Vec::with_capacity(3); + if let Some(term) = filter.search() { + let mut either = vec![doc! { "title": { "$regex": literal_regex(term), "$options": "i" } }]; + // `#913` is ticket 913; `913` also finds the Jira key `PROJ-913`. + let number = term.strip_prefix('#').unwrap_or(term).trim(); + if !number.is_empty() { + let exact = format!("(^|-){}$", literal_regex(number)); + either.push(doc! { "external_id": { "$regex": exact, "$options": "i" } }); + } + clauses.push(doc! { "$or": either }); + } + if let Some(state) = filter.status { + clauses.push(doc! { "status": { "$in": state.statuses() } }); + } + if let (Some(repo_id), Some(ids)) = (filter.target(), finding_ids) { + // A CVE ticket names its target in its key instead of a finding. + let cve = format!("^{}", literal_regex(&cve_issue_prefix(repo_id))); + clauses.push(doc! { "$or": [ + { "finding_id": { "$in": ids } }, + { "finding_id": { "$regex": cve } }, + ] }); + } + if clauses.is_empty() { + Document::new() + } else { + doc! { "$and": clauses } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn filter(json: &str) -> IssuesFilter { + serde_json::from_str(json).unwrap() + } + + /// The clauses of the `$and`, by position. + fn clauses(query: &Document) -> Vec { + query + .get_array("$and") + .unwrap() + .iter() + .map(|c| c.as_document().unwrap().clone()) + .collect() + } + + /// The external-id regex a search for `term` uses. + fn number_regex(term: &str) -> String { + let query = issues_query(&filter(&format!(r#"{{"q":{term:?}}}"#)), None); + let either = clauses(&query)[0].get_array("$or").unwrap().clone(); + let external = either[1].as_document().unwrap(); + external + .get_document("external_id") + .unwrap() + .get_str("$regex") + .unwrap() + .to_string() + } + + #[test] + fn no_filter_lists_everything() { + assert_eq!(issues_query(&filter("{}"), None), Document::new()); + assert_eq!( + issues_query(&filter(r#"{"q":" ","repo_id":""}"#), None), + Document::new() + ); + } + + #[test] + fn a_number_with_or_without_hash_finds_the_ticket() { + assert_eq!(number_regex("913"), "(^|-)913$"); + assert_eq!(number_regex("#913"), "(^|-)913$"); + let re = regex::RegexBuilder::new(&number_regex("#913")) + .case_insensitive(true) + .build() + .unwrap(); + assert!(re.is_match("913")); + assert!(re.is_match("PROJ-913")); + assert!(!re.is_match("1913")); + assert!(!re.is_match("9130")); + } + + #[test] + fn the_search_is_a_literal_title_substring() { + let query = issues_query(&filter(r#"{"q":"(a+)+$"}"#), None); + let either = clauses(&query)[0].get_array("$or").unwrap().clone(); + let title = either[0] + .as_document() + .unwrap() + .get_document("title") + .unwrap(); + assert_eq!(title.get_str("$regex").unwrap(), r"\(a\+\)\+\$"); + assert_eq!(title.get_str("$options").unwrap(), "i"); + } + + #[test] + fn a_lone_hash_searches_the_title_only() { + let query = issues_query(&filter(r##"{"q":"#"}"##), None); + assert_eq!(clauses(&query)[0].get_array("$or").unwrap().len(), 1); + } + + #[test] + fn the_status_filter_takes_both_stored_statuses() { + let query = issues_query(&filter(r#"{"status":"open"}"#), None); + assert_eq!( + clauses(&query)[0], + doc! { "status": { "$in": ["open", "in_progress"] } } + ); + } + + #[test] + fn the_target_filter_takes_its_findings_and_its_cves() { + let ids = vec!["65a1b2c3d4e5f60718293a4b".to_string()]; + let query = issues_query(&filter(r#"{"repo_id":"t1"}"#), Some(&ids)); + assert_eq!( + clauses(&query)[0], + doc! { "$or": [ + { "finding_id": { "$in": ["65a1b2c3d4e5f60718293a4b"] } }, + { "finding_id": { "$regex": "^cve:t1:" } }, + ] } + ); + } + + #[test] + fn a_target_without_ticketed_findings_still_has_its_cves() { + let query = issues_query(&filter(r#"{"repo_id":"t.1"}"#), Some(&[])); + let either = clauses(&query)[0].get_array("$or").unwrap().clone(); + let cve = either[1] + .as_document() + .unwrap() + .get_document("finding_id") + .unwrap(); + // The id is matched literally. + assert_eq!(cve.get_str("$regex").unwrap(), r"^cve:t\.1:"); + } + + #[test] + fn search_status_and_target_all_apply() { + // Search and target are both an `$or`: neither may replace the other. + let query = issues_query( + &filter(r#"{"q":"913","status":"closed","repo_id":"t1"}"#), + Some(&[]), + ); + let all = clauses(&query); + assert_eq!(all.len(), 3); + assert!(all[0].get_array("$or").unwrap()[0] + .as_document() + .unwrap() + .contains_key("title")); + assert!(all[1].contains_key("status")); + assert!(all[2].get_array("$or").unwrap()[0] + .as_document() + .unwrap() + .contains_key("finding_id")); + } +} diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index 8ebdcd8..351ff27 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -24,6 +24,7 @@ use std::collections::{BTreeMap, HashMap}; use mongodb::bson::doc; use compliance_core::config::IssueAutoclose; +use compliance_core::models::issue::cve_issue_prefix; use compliance_core::models::notification::{parse_severity, NotificationSeverity}; use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus}; @@ -95,7 +96,12 @@ pub(crate) struct CveIssueCounts { /// target, package and CVE, so another version of the same package does not /// open a second issue. fn issue_key(target_id: &str, alert: &CveAlert) -> String { - format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve()) + format!( + "{}{}:{}", + cve_issue_prefix(target_id), + alert.affected_package, + alert.cve() + ) } /// A severity as the `severity:` labels name it. @@ -163,7 +169,7 @@ pub(crate) async fn sync_cve_issues( alerts: &[CveAlert], complete: bool, ) -> Result { - let prefix = format!("cve:{}:", target.target_id); + let prefix = cve_issue_prefix(target.target_id); let mut existing: HashMap = HashMap::new(); let mut cursor = target .db @@ -189,7 +195,7 @@ pub(crate) async fn sync_cve_issues( .filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile)) { match existing.get(key) { - Some(issue) if is_closed(&issue.status) => { + Some(issue) if issue.status.is_closed() => { let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened."; if set_state(target, issue, comment, "open").await { record(target.db, issue, IssueStatus::Open).await?; @@ -210,7 +216,7 @@ pub(crate) async fn sync_cve_issues( .iter() .filter_map(|(key, alert)| { let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?; - let issue = existing.get(key).filter(|i| !is_closed(&i.status))?; + let issue = existing.get(key).filter(|i| !i.status.is_closed())?; Some((issue, vex)) }) .collect(); @@ -218,7 +224,7 @@ pub(crate) async fn sync_cve_issues( if complete { for (key, issue) in &existing { - if present.contains_key(key) || is_closed(&issue.status) { + if present.contains_key(key) || issue.status.is_closed() { continue; } let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed."; @@ -311,11 +317,6 @@ fn vex_comment(vex: &VexAssessment) -> String { ) } -/// Whether an issue is closed. -fn is_closed(status: &IssueStatus) -> bool { - matches!(status, IssueStatus::Closed | IssueStatus::Resolved) -} - /// The Prüfwerk label ids of a Gitea repository, created where missing; /// `None` for other trackers or when Gitea refuses. async fn gitea_label_ids(target: &CveIssueTarget<'_>) -> Option> { diff --git a/compliance-core/src/models/issue.rs b/compliance-core/src/models/issue.rs index 8f1448a..b5b2587 100644 --- a/compliance-core/src/models/issue.rs +++ b/compliance-core/src/models/issue.rs @@ -41,6 +41,49 @@ impl std::fmt::Display for IssueStatus { } } +impl IssueStatus { + /// Every status, open ones first. + pub const ALL: [Self; 4] = [Self::Open, Self::InProgress, Self::Closed, Self::Resolved]; + + /// Whether the ticket is done (closed or resolved); the other two are + /// open. + pub fn is_closed(&self) -> bool { + match self { + Self::Closed | Self::Resolved => true, + Self::Open | Self::InProgress => false, + } + } +} + +/// What a ticket is about, as its `finding_id` says. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IssueSubject<'a> { + /// One finding, by its id (the hex of its `ObjectId`). + Finding(&'a str), + /// A known vulnerability in one target's components, by the target id. + Cve { + /// The target (repository) the CVE was found in. + target_id: &'a str, + }, +} + +/// What the `finding_id` of a CVE ticket starts with. +const CVE_KEY: &str = "cve:"; + +/// The start of the `finding_id` of every CVE ticket of one target. The whole +/// key is `cve:{target_id}:{package}:{cve}`: one ticket per target, package +/// and CVE. +/// +/// # Examples +/// +/// ``` +/// use compliance_core::models::issue::cve_issue_prefix; +/// assert_eq!(cve_issue_prefix("abc"), "cve:abc:"); +/// ``` +pub fn cve_issue_prefix(target_id: &str) -> String { + format!("{CVE_KEY}{target_id}:") +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TrackerIssue { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] @@ -78,4 +121,70 @@ impl TrackerIssue { updated_at: now, } } + + /// What the ticket is about: its finding, or for a CVE ticket the target + /// the CVE is in. `None` when `finding_id` is neither (empty, for an + /// issue whose finding had no id). + pub fn subject(&self) -> Option> { + if let Some(rest) = self.finding_id.strip_prefix(CVE_KEY) { + // `rest` is `{target_id}:{package}:{cve}`; `split` always yields + // a first piece, so only an empty one is refused. + return rest + .split(':') + .next() + .filter(|id| !id.is_empty()) + .map(|target_id| IssueSubject::Cve { target_id }); + } + let id = self.finding_id.as_str(); + (id.len() == 24 && id.bytes().all(|b| b.is_ascii_hexdigit())) + .then_some(IssueSubject::Finding(id)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn issue(finding_id: &str) -> TrackerIssue { + TrackerIssue::new( + finding_id.to_string(), + TrackerType::Gitea, + "913".into(), + "https://gitea.invalid/o/r/issues/913".into(), + "[high] semgrep: hardcoded key".into(), + ) + } + + #[test] + fn a_finding_ticket_is_about_its_finding() { + let id = "65a1b2c3d4e5f60718293a4b"; + assert_eq!(issue(id).subject(), Some(IssueSubject::Finding(id))); + } + + #[test] + fn a_cve_ticket_is_about_its_target() { + let key = format!("{}openssl:CVE-2024-0001", cve_issue_prefix("tgt1")); + assert_eq!( + issue(&key).subject(), + Some(IssueSubject::Cve { target_id: "tgt1" }) + ); + } + + #[test] + fn a_ticket_without_a_usable_id_is_about_nothing() { + assert_eq!(issue("").subject(), None); + assert_eq!(issue("cve::pkg:CVE-1").subject(), None); + assert_eq!(issue("not-an-object-id").subject(), None); + // The right length, but not hex. + assert_eq!(issue("zzzzzzzzzzzzzzzzzzzzzzzz").subject(), None); + } + + #[test] + fn closed_and_resolved_are_closed() { + let closed: Vec = IssueStatus::ALL + .into_iter() + .filter(IssueStatus::is_closed) + .collect(); + assert_eq!(closed, [IssueStatus::Closed, IssueStatus::Resolved]); + } } diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index d80b6a4..fd63bfd 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -51,7 +51,7 @@ pub use git_source::{GitSource, GitSourceView, SourceRepo, GIT_SOURCE_ID}; pub use graph::{ CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis, }; -pub use issue::{IssueStatus, TrackerIssue, TrackerType}; +pub use issue::{IssueStatus, IssueSubject, TrackerIssue, TrackerType}; pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage}; pub use license_policy::{ LegalReview, LicensePolicy, LicenseVerdict, PolicyAction, ReviewDecision, diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 1707634..9ba3cc9 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -6052,3 +6052,35 @@ input[type="file"] { .license-policy-forbid { border-left: 3px solid var(--danger); } + +/* ── Tickets list ── */ +.ticket-tracker { + font-size: 12px; + color: var(--text-secondary); +} + +.ticket-number { + font-family: var(--font-mono); + white-space: nowrap; +} + +.ticket-created { + font-size: 12px; + color: var(--text-secondary); + white-space: nowrap; +} + +.ticket-links { + display: flex; + gap: 12px; + white-space: nowrap; +} + +.ticket-links a { + color: var(--accent); + text-decoration: none; +} + +.ticket-links a:hover { + text-decoration: underline; +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 95cc78b..9615eec 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2347,6 +2347,102 @@ pub mod findings { }; } +/// The tickets page: the issues Prüfwerk opened in the targets' trackers. +pub mod issues { + use compliance_core::models::IssueStatus; + + use super::Text; + + pub const TITLE: Text = super::nav::ISSUES; + pub const SUBTITLE: Text = Text { + de: "Die Tickets zu Befunden und CVEs in den Issue-Trackern der Prüfobjekte \ + (GitHub, GitLab, Gitea, Jira)", + en: "The issues for findings and CVEs in the targets' trackers \ + (GitHub, GitLab, Gitea, Jira)", + }; + pub const SEARCH: Text = Text { + de: "Titel oder Ticketnummer (#913) …", + en: "Title or issue number (#913)...", + }; + pub const COL_TRACKER: Text = Text { + de: "Tracker", + en: "Tracker", + }; + pub const COL_NUMBER: Text = Text { + de: "Nr.", + en: "No.", + }; + pub const COL_CREATED: Text = Text { + de: "Erstellt", + en: "Created", + }; + pub const COL_LINKS: Text = Text { + de: "Öffnen", + en: "Open", + }; + /// The link to the finding a ticket is about. + pub const OPEN_FINDING: Text = Text { + de: "Befund", + en: "Finding", + }; + /// The link from a CVE ticket to its target's components and CVEs. + pub const OPEN_CVES: Text = Text { + de: "CVEs des Prüfobjekts", + en: "Target's CVEs", + }; + pub const OPEN_TRACKER: Text = Text { + de: "Im Tracker", + en: "In the tracker", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Tickets konnten nicht geladen werden.", + en: "Failed to load the issues.", + }; + pub const NONE: Text = Text { + de: "Keine Tickets für diese Auswahl.", + en: "No issues for this selection.", + }; + + /// A ticket status in words. + pub fn status(status: &IssueStatus) -> Text { + match status { + IssueStatus::Open => Text { + de: "Offen", + en: "Open", + }, + IssueStatus::InProgress => Text { + de: "In Bearbeitung", + en: "In progress", + }, + IssueStatus::Closed => Text { + de: "Geschlossen", + en: "Closed", + }, + IssueStatus::Resolved => Text { + de: "Erledigt", + en: "Resolved", + }, + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn every_status_reads_differently() { + let names: Vec = IssueStatus::ALL.iter().map(status).collect(); + for (i, a) in names.iter().enumerate() { + assert!(!a.de.is_empty() && !a.en.is_empty()); + for b in &names[i + 1..] { + assert_ne!(a.de, b.de); + assert_ne!(a.en, b.en); + } + } + } + } +} + /// The SBOM page. pub mod sbom { use super::Text; diff --git a/compliance-dashboard/src/infrastructure/issues.rs b/compliance-dashboard/src/infrastructure/issues.rs index 0b3dd6a..4a6847c 100644 --- a/compliance-dashboard/src/infrastructure/issues.rs +++ b/compliance-dashboard/src/infrastructure/issues.rs @@ -3,6 +3,9 @@ use serde::{Deserialize, Serialize}; use compliance_core::models::TrackerIssue; +/// Tickets per page of the list. +pub const PAGE_SIZE: u64 = 20; + #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct IssuesListResponse { pub data: Vec, @@ -10,9 +13,41 @@ pub struct IssuesListResponse { pub page: Option, } +/// The search and filters of the tickets list; an empty field filters nothing. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +pub struct IssuesQuery { + pub page: u64, + /// A word of the title or the ticket number (`913`, `#913`). + pub q: String, + /// `open` or `closed`. + pub status: String, + /// One target's tickets. + pub repo_id: String, +} + +/// The agent path that lists the tickets `query` asks for, every value +/// URL-encoded (`#913` would otherwise end the path). +#[cfg(feature = "server")] +fn issues_path(query: &IssuesQuery) -> String { + let mut params = url::form_urlencoded::Serializer::new(String::new()); + params + .append_pair("page", &query.page.to_string()) + .append_pair("limit", &PAGE_SIZE.to_string()); + for (key, value) in [ + ("q", query.q.trim()), + ("status", query.status.as_str()), + ("repo_id", query.repo_id.as_str()), + ] { + if !value.is_empty() { + params.append_pair(key, value); + } + } + format!("/api/v1/issues?{}", params.finish()) +} + #[server] -pub async fn fetch_issues(page: u64) -> Result { - let resp = super::agent_client::agent_get(&format!("/api/v1/issues?page={page}&limit=20")) +pub async fn fetch_issues(query: IssuesQuery) -> Result { + let resp = super::agent_client::agent_get(&issues_path(&query)) .await? .send() .await @@ -23,3 +58,32 @@ pub async fn fetch_issues(page: u64) -> Result Element { + let lang = use_lang()(); let mut page = use_signal(|| 1u64); + let mut search_query = use_signal(String::new); + let mut status_filter = use_signal(String::new); + let mut repo_filter = use_signal(String::new); + + let repos = use_resource(|| async { + crate::infrastructure::onboarding::fetch_targets() + .await + .ok() + }); let issues = use_resource(move || { - let p = page(); - async move { crate::infrastructure::issues::fetch_issues(p).await.ok() } + let query = IssuesQuery { + page: page(), + q: search_query(), + status: status_filter(), + repo_id: repo_filter(), + }; + async move { fetch_issues(query).await.ok() } }); rsx! { PageHeader { - title: "Issues", - description: "Cross-tracker issue view - GitHub, GitLab, and Jira", + title: tx::TITLE.get(lang), + description: tx::SUBTITLE.get(lang), + } + + div { class: "filter-bar", + input { + r#type: "text", + placeholder: tx::SEARCH.get(lang), + style: "min-width: 240px;", + oninput: move |e| { search_query.set(e.value()); page.set(1); }, + } + select { + onchange: move |e| { repo_filter.set(e.value()); page.set(1); }, + option { value: "", {ftx::ALL_TARGETS.get(lang)} } + if let Some(Some(resp)) = &*repos.read() { + for t in &resp.data { + { + let id = t.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string(); + let name = t.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + rsx! { + option { value: "{id}", selected: repo_filter() == id, "{name}" } + } + } + } + } + } + select { + onchange: move |e| { status_filter.set(e.value()); page.set(1); }, + option { value: "", {ftx::ALL_STATUSES.get(lang)} } + // Open takes in-progress tickets too, closed the resolved ones. + option { value: "open", {tx::status(&IssueStatus::Open).get(lang)} } + option { value: "closed", {tx::status(&IssueStatus::Closed).get(lang)} } + } } match &*issues.read() { Some(Some(resp)) => { - let total_pages = resp.total.unwrap_or(0).div_ceil(20).max(1); + let total_pages = resp.total.unwrap_or(0).div_ceil(PAGE_SIZE).max(1); rsx! { div { class: "card", div { class: "table-wrapper", table { thead { tr { - th { "Tracker" } - th { "ID" } - th { "Title" } - th { "Status" } - th { "Created" } - th { "Link" } + th { {tx::COL_TRACKER.get(lang)} } + th { {tx::COL_NUMBER.get(lang)} } + th { {ftx::COL_TITLE.get(lang)} } + th { {ftx::COL_STATUS.get(lang)} } + th { {tx::COL_CREATED.get(lang)} } + th { {tx::COL_LINKS.get(lang)} } } } tbody { + if resp.data.is_empty() { + tr { + td { colspan: "6", style: "text-align: center; opacity: 0.6; padding: 24px;", + {tx::NONE.get(lang)} + } + } + } for issue in &resp.data { tr { - td { - span { class: "badge badge-info", "{issue.tracker_type}" } - } - td { - style: "font-family: monospace;", - "{issue.external_id}" - } + td { class: "ticket-tracker", {tracker_name(&issue.tracker_type)} } + td { class: "ticket-number", {ticket_number(&issue.external_id)} } td { "{issue.title}" } td { - span { class: "badge badge-info", "{issue.status}" } + span { class: "badge {status_class(&issue.status)}", + {tx::status(&issue.status).get(lang)} + } } - td { - style: "font-size: 12px; color: var(--text-secondary);", + td { class: "ticket-created", {issue.created_at.format("%Y-%m-%d %H:%M").to_string()} } td { - a { - href: "{issue.external_url}", - target: "_blank", - style: "color: var(--accent); text-decoration: none;", - "Open" + div { class: "ticket-links", + if let Some((to, label)) = ticket_link(issue) { + Link { to, {label.get(lang)} } + } + if !issue.external_url.is_empty() { + a { + href: "{issue.external_url}", + target: "_blank", + rel: "noopener noreferrer", + {tx::OPEN_TRACKER.get(lang)} + } + } } } } @@ -75,11 +137,113 @@ pub fn IssuesPage() -> Element { } }, Some(None) => rsx! { - div { class: "card", p { "Failed to load issues." } } + div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } }, None => rsx! { - div { class: "loading", "Loading issues..." } + div { class: "loading", {common::LOADING.get(lang)} } }, } } } + +/// Where a ticket leads in Prüfwerk, and the link's text: its finding, or for +/// a CVE ticket the target's components and their CVEs. `None` for a ticket +/// whose finding is unknown. +fn ticket_link(issue: &TrackerIssue) -> Option<(Route, Text)> { + Some(match issue.subject()? { + IssueSubject::Finding(id) => ( + Route::FindingDetailPage { id: id.to_string() }, + tx::OPEN_FINDING, + ), + IssueSubject::Cve { target_id } => ( + Route::SbomPage { + target: target_id.to_string(), + }, + tx::OPEN_CVES, + ), + }) +} + +/// A ticket's number as its tracker shows it: `#913`, or a Jira key as is. +fn ticket_number(external_id: &str) -> String { + if !external_id.is_empty() && external_id.bytes().all(|b| b.is_ascii_digit()) { + format!("#{external_id}") + } else { + external_id.to_string() + } +} + +/// A tracker by its product name. +fn tracker_name(tracker: &TrackerType) -> &'static str { + match tracker { + TrackerType::GitHub => "GitHub", + TrackerType::GitLab => "GitLab", + TrackerType::Gitea => "Gitea", + TrackerType::Jira => "Jira", + } +} + +/// The badge colour of a ticket status: open blue, in progress amber, done +/// green. +fn status_class(status: &IssueStatus) -> &'static str { + match status { + IssueStatus::Open => "badge-info", + IssueStatus::InProgress => "badge-medium", + IssueStatus::Closed | IssueStatus::Resolved => "badge-success", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn issue(finding_id: &str) -> TrackerIssue { + TrackerIssue::new( + finding_id.to_string(), + TrackerType::Gitea, + "913".into(), + "https://gitea.invalid/o/r/issues/913".into(), + "[high] semgrep: hardcoded key".into(), + ) + } + + #[test] + fn a_finding_ticket_links_to_its_finding() { + let id = "65a1b2c3d4e5f60718293a4b"; + let (to, label) = ticket_link(&issue(id)).expect("a link"); + assert_eq!(to, Route::FindingDetailPage { id: id.into() }); + assert_eq!(label, tx::OPEN_FINDING); + } + + #[test] + fn a_cve_ticket_links_to_its_targets_cves() { + let (to, label) = ticket_link(&issue("cve:t1:openssl:CVE-2024-0001")).expect("a link"); + assert_eq!( + to, + Route::SbomPage { + target: "t1".into() + } + ); + assert_eq!(label, tx::OPEN_CVES); + } + + #[test] + fn a_ticket_without_a_finding_has_no_link() { + assert!(ticket_link(&issue("")).is_none()); + } + + #[test] + fn numbers_read_like_the_tracker() { + assert_eq!(ticket_number("913"), "#913"); + assert_eq!(ticket_number("PROJ-913"), "PROJ-913"); + assert_eq!(ticket_number(""), ""); + } + + #[test] + fn done_tickets_are_green() { + for status in IssueStatus::ALL { + let green = status_class(&status) == "badge-success"; + assert_eq!(green, status.is_closed(), "{status}"); + } + } +} diff --git a/docs/guide/issues.md b/docs/guide/issues.md index d86da11..74fba60 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -25,18 +25,24 @@ For a repository from a managed git source, known vulnerabilities in its depende Open **Tickets** (Issues) in the sidebar to see all tracker issues across your targets. +Above the table: + +- **Search** finds a ticket by a word of its title or by its number: `913` and `#913` both find ticket 913, and `913` also finds the Jira key `PROJ-913`. +- **Target** shows only one target's tickets: those of its findings and its CVE issues. +- **Status** shows only open tickets (open or in progress) or only closed ones (closed or resolved). + The issues table shows: | Column | Description | |--------|-------------| -| Tracker | Badge showing GitHub, GitLab, Gitea, or Jira | -| ID | Issue number in the external system | -| Title | Issue title | -| Status | Open, Closed, or tracker-specific status | -| Created | When the issue was created | -| Link | Direct link to the issue in the external tracker | +| Tracker | GitHub, GitLab, Gitea, or Jira | +| Nr. (No.) | Issue number in the external system | +| Titel (Title) | Issue title | +| Status | Offen / In Bearbeitung / Geschlossen / Erledigt (Open / In progress / Closed / Resolved) | +| Erstellt (Created) | When the issue was created | +| Öffnen (Open) | **Befund** (Finding) opens the finding the ticket is about, where you set its status; for a CVE issue, **CVEs des Prüfobjekts** (Target's CVEs) opens the target's components and their CVEs. **Im Tracker** (In the tracker) opens the issue in your tracker. | -Click the link to go directly to the issue in your tracker. +The API takes the same filters: `GET /api/v1/issues?q=913&status=open&repo_id=` (`status` is `open` or `closed`). ## Supported Trackers