diff --git a/compliance-agent/src/api/handlers/health.rs b/compliance-agent/src/api/handlers/health.rs index b4ba8fc..7b9fba4 100644 --- a/compliance-agent/src/api/handlers/health.rs +++ b/compliance-agent/src/api/handlers/health.rs @@ -12,7 +12,7 @@ pub async fn health() -> Json { /// Findings that still need someone's attention: not resolved, not a false /// positive, not an accepted risk and not ignored. -const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"]; +pub(crate) const OPEN_STATUSES: [&str; 3] = ["open", "triaged", "needs_review"]; /// How many open findings there are of each severity, by severity name. async fn open_findings_by_severity( diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index bda9acf..cb034cc 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -16,6 +16,7 @@ pub mod onboarding; pub mod oscal; pub mod pentest_handlers; pub mod platform; +pub mod projects; pub use pentest_handlers as pentest; pub mod sbom; pub mod scans; diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 96c0431..72e750b 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -47,6 +47,9 @@ pub struct UpdateTargetRequest { pub scan_config: Option, pub compliance_profile: Option, pub scan_schedule: Option, + /// The tenant's projects this target belongs to; replaces the stored + /// list. Each must be one of the tenant's projects in the registry. + pub project_ids: Option>, /// The target's artifacts (the dashboard editor sends all of them). Each /// keeps the token and uploaded file of the stored artifact it matches. #[serde(default)] @@ -80,17 +83,19 @@ pub async fn list_targets( Extension(agent): AgentExt, tenant: TenantCtx, Query(params): Query, + Query(filter): Query, ) -> Result>>, StatusCode> { let db = tenant_db(&agent, &tenant).await?; let skip = params.skip(); + let query = filter.to_query(); let total = db .onboarded_targets() - .count_documents(doc! {}) + .count_documents(query.clone()) .await .unwrap_or(0); let targets = match db .onboarded_targets() - .find(doc! {}) + .find(query) .skip(skip) .limit(params.limit) .await @@ -143,8 +148,31 @@ pub struct TargetListItem { pub last_scan: Option, } +/// Which targets a list shows (`?project=`). +#[derive(Debug, Default, serde::Deserialize)] +pub struct TargetFilter { + /// Only the targets that belong to this project. + #[serde(default)] + pub project: Option, +} + +impl TargetFilter { + /// The Mongo filter for these targets. + pub fn to_query(&self) -> mongodb::bson::Document { + match self + .project + .as_deref() + .map(str::trim) + .filter(|p| !p.is_empty()) + { + Some(project) => doc! { "project_ids": project }, + None => doc! {}, + } + } +} + /// The newest scan run of each target in `target_ids`, in one query. -async fn latest_scan_runs( +pub(crate) async fn latest_scan_runs( runs: &mongodb::Collection, target_ids: Vec, ) -> HashMap { @@ -327,6 +355,11 @@ pub async fn update_target( if let Some(ss) = req.scan_schedule { set.insert("scan_schedule", ss); } + if let Some(requested) = req.project_ids { + let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?; + let ids = super::projects::validated_project_ids(&requested, &known)?; + set.insert("project_ids", ids); + } if let (Some(arts), Some(stored)) = (req.artifacts, stored.as_ref()) { let built = merge_artifacts(&agent.secrets, &arts, &stored.artifacts).map_err(credential_error)?; @@ -932,3 +965,21 @@ pub async fn trigger_target_scan( }); Ok(Json(serde_json::json!({ "status": "scan_triggered" }))) } + +#[cfg(test)] +mod filter_tests { + use super::*; + + #[test] + fn a_project_filter_matches_its_targets() { + let filter = TargetFilter { + project: Some(" p1 ".to_string()), + }; + assert_eq!(filter.to_query(), doc! { "project_ids": "p1" }); + assert_eq!(TargetFilter::default().to_query(), doc! {}); + let blank = TargetFilter { + project: Some(String::new()), + }; + assert_eq!(blank.to_query(), doc! {}); + } +} diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index 428a49d..ff52cdf 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -443,3 +443,107 @@ pub async fn version(State(st): State) -> Json "features": st.agent.config.features.flags(), })) } + +/// A target as the portal lists it for a project. +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct PlatformTarget { + pub id: String, + pub name: String, + pub target_type: compliance_core::models::TargetType, + /// When its newest scan started; `None` before the first. + pub last_scan_at: Option>, + /// Findings that still need attention. + pub open_findings: u64, + /// Its projects that the registry still lists. + pub project_ids: Vec, +} + +/// Open findings of each target in `target_ids`, in one query. +async fn open_findings_counts( + db: &crate::database::Database, + target_ids: Vec, +) -> Result, StatusCode> { + let pipeline = vec![ + doc! { "$match": { + "repo_id": { "$in": target_ids }, + "status": { "$in": super::health::OPEN_STATUSES.to_vec() }, + } }, + doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } }, + ]; + let rows: Vec = db + .findings() + .aggregate(pipeline) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + Ok(rows + .iter() + .filter_map(|row| { + let id = row.get_str("_id").ok()?.to_string(); + let n = row + .get_i32("n") + .map(i64::from) + .or_else(|_| row.get_i64("n")) + .ok()?; + Some((id, u64::try_from(n).ok()?)) + }) + .collect()) +} + +/// `GET /api/v1/platform/tenants/{id}/targets?project=` — the tenant's +/// targets (one project's, with `project`), for the portal through the +/// registry. Read-only. Project ids the registry no longer lists are left +/// out; when it cannot be asked, the stored ids are returned as they are. +pub async fn list_targets( + State(st): State, + Path(tenant_id): Path, + Query(filter): Query, +) -> Result, StatusCode> { + let db = st + .agent + .db_pool + .for_tenant_id(&tenant_id) + .await + .map_err(internal)?; + let targets: Vec = db + .onboarded_targets() + .find(filter.to_query()) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + let ids: Vec = targets + .iter() + .filter_map(|t| t.id.map(|id| id.to_hex())) + .collect(); + let runs = db.scan_runs(); + let (mut last_scans, open) = tokio::join!( + super::onboarding::latest_scan_runs(&runs, ids.clone()), + open_findings_counts(&db, ids), + ); + let open = open?; + let known = super::projects::tenant_projects(&st.agent, &tenant_id) + .await + .ok(); + let items: Vec = targets + .into_iter() + .map(|t| { + let id = t.id.map(|id| id.to_hex()).unwrap_or_default(); + PlatformTarget { + last_scan_at: last_scans.remove(&id).map(|run| run.started_at), + open_findings: open.get(&id).copied().unwrap_or(0), + project_ids: match known.as_deref() { + Some(known) => super::projects::known_project_ids(&t.project_ids, known), + None => t.project_ids, + }, + name: t.name, + target_type: t.target_type, + id, + } + }) + .collect(); + Ok(Json(serde_json::json!({ "items": items }))) +} diff --git a/compliance-agent/src/api/handlers/projects.rs b/compliance-agent/src/api/handlers/projects.rs new file mode 100644 index 0000000..27921c7 --- /dev/null +++ b/compliance-agent/src/api/handlers/projects.rs @@ -0,0 +1,122 @@ +//! A tenant's projects, which the platform registry owns: listing them for +//! the dashboard, and checking assignments against them. +//! +//! Targets store the ids of the projects they belong to (`project_ids`). A +//! project deleted in the registry drops out of its list, and readers show +//! only ids they still find there. + +use std::collections::HashSet; + +use axum::extract::Extension; +use axum::http::StatusCode; +use axum::Json; + +use compliance_core::models::Project; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::AgentExt; +use crate::agent::ComplianceAgent; + +/// The tenant's projects from the registry. Empty without a registry (dev). +/// +/// # Errors +/// +/// `503` when the registry could not answer. +pub async fn tenant_projects( + agent: &ComplianceAgent, + tenant_id: &str, +) -> Result, StatusCode> { + let Some(registry) = agent.registry.as_ref() else { + return Ok(Vec::new()); + }; + registry.list_projects(tenant_id).await.map_err(|e| { + tracing::error!(tenant_id, "project list unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + }) +} + +/// `requested` as stored: trimmed, without duplicates, in the given order. +/// +/// # Errors +/// +/// `422` when an id is not one of the tenant's projects (`known`). +pub fn validated_project_ids( + requested: &[String], + known: &[Project], +) -> Result, StatusCode> { + let known: HashSet<&str> = known.iter().map(|p| p.id.as_str()).collect(); + let mut seen = HashSet::with_capacity(requested.len()); + let mut ids = Vec::with_capacity(requested.len()); + for id in requested.iter().map(|id| id.trim()) { + if !known.contains(id) { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + if seen.insert(id) { + ids.push(id.to_string()); + } + } + Ok(ids) +} + +/// The ids in `ids` that are still one of the tenant's projects. +pub fn known_project_ids(ids: &[String], known: &[Project]) -> Vec { + ids.iter() + .filter(|id| known.iter().any(|p| &p.id == *id)) + .cloned() + .collect() +} + +/// GET /api/v1/projects — the tenant's projects, for choosing and showing +/// them in the dashboard. +#[tracing::instrument(skip_all)] +pub async fn list_projects( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result, StatusCode> { + let projects = tenant_projects(&agent, &tenant.0.tenant_id).await?; + Ok(Json(serde_json::json!({ "data": projects }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::ProjectKind; + + fn project(id: &str) -> Project { + Project { + id: id.to_string(), + name: format!("Projekt {id}"), + kind: ProjectKind::Product, + description: String::new(), + } + } + + #[test] + fn assignments_are_trimmed_and_deduplicated() { + let known = [project("p1"), project("p2")]; + let ids = validated_project_ids( + &["p2".to_string(), " p1 ".to_string(), "p2".to_string()], + &known, + ); + assert_eq!(ids, Ok(vec!["p2".to_string(), "p1".to_string()])); + } + + #[test] + fn an_unknown_project_is_refused() { + let known = [project("p1")]; + assert_eq!( + validated_project_ids(&["p9".to_string()], &known), + Err(StatusCode::UNPROCESSABLE_ENTITY) + ); + assert_eq!(validated_project_ids(&[], &known), Ok(Vec::new())); + } + + #[test] + fn deleted_projects_drop_out_on_read() { + let known = [project("p1")]; + assert_eq!( + known_project_ids(&["p1".to_string(), "gone".to_string()], &known), + ["p1".to_string()] + ); + } +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 1405e86..9b81359 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -13,6 +13,8 @@ pub fn build_router() -> Router { .route("/api/v1/health", get(handlers::health)) .route("/api/v1/oscal/assess", post(handlers::oscal::assess_target)) .route("/api/v1/stats/overview", get(handlers::stats_overview)) + // The tenant's projects (owned by the registry), for assigning targets. + .route("/api/v1/projects", get(handlers::projects::list_projects)) // BreakPilot support access: choose and open a customer's tenant. .route( "/api/v1/support/tenants", diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index b5a8037..703ba02 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -286,6 +286,12 @@ pub async fn start_api_server( "/api/v1/platform/tenants/{id}/provision", post(platform::provision), ) + // The portal's view of a tenant's targets (per project), through the + // registry. Read-only. + .route( + "/api/v1/platform/tenants/{id}/targets", + get(platform::list_targets), + ) .route( "/api/v1/platform/tenants/{id}/suspend", post(platform::suspend), diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index e81a3f5..106098f 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -478,6 +478,15 @@ impl Database { ) .await?; + // onboarded_targets: multikey on project ids (the `?project=` filter) + self.onboarded_targets() + .create_index( + IndexModel::builder() + .keys(doc! { "project_ids": 1 }) + .build(), + ) + .await?; + // onboarded_targets: multikey on artifact kind self.onboarded_targets() .create_index( diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index 6a8c6cc..a4a6db1 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -102,6 +102,8 @@ pub struct RegistryClient { client_secret: Option, token: Mutex>, cache: DashMap, + /// Each tenant's projects, for [`ENTITLEMENT_TTL`]. + projects: DashMap)>, } impl std::fmt::Debug for RegistryClient { @@ -143,6 +145,7 @@ impl RegistryClient { .map(|s| s.expose_secret().to_string()), token: Mutex::new(None), cache: DashMap::new(), + projects: DashMap::new(), })) } @@ -332,6 +335,47 @@ impl RegistryClient { Ok(()) } + /// The tenant's active projects (`GET /v1/tenants/{id}/projects`), + /// cached ≤ 60 s. A deleted project is simply no longer listed. + /// + /// # Errors + /// + /// The registry could not be asked, or answered with an error. + pub async fn list_projects( + &self, + tenant_id: &str, + ) -> Result, String> { + if let Some(entry) = self.projects.get(tenant_id) { + if entry.0.elapsed() < ENTITLEMENT_TTL { + return Ok(entry.1.clone()); + } + } + #[derive(Deserialize)] + struct Page { + #[serde(default)] + items: Vec, + } + let resp = self + .request( + reqwest::Method::GET, + &format!("/v1/tenants/{}/projects", urlencoding::encode(tenant_id)), + ) + .await? + .send() + .await + .map_err(|e| format!("project list failed: {e}"))?; + if !resp.status().is_success() { + return Err(format!("project list returned {}", resp.status())); + } + let page: Page = resp + .json() + .await + .map_err(|e| format!("project list invalid: {e}"))?; + self.projects + .insert(tenant_id.to_string(), (Instant::now(), page.items.clone())); + Ok(page.items) + } + /// Verify a portal-issued API key (`bp_…`). pub async fn verify_api_key(&self, key: &str) -> Result { let resp = self diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index bc8cb61..ee98805 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -14,6 +14,7 @@ pub mod onboarding; pub mod oscal; pub mod oscal_assessment; pub mod pentest; +pub mod project; pub mod repository; pub mod sbom; pub mod scan; @@ -51,6 +52,7 @@ pub use pentest::{ PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo, ToolCallRecord, }; +pub use project::{Project, ProjectKind}; pub use repository::ScanTrigger; pub use sbom::{SbomEntry, VulnRef}; pub use scan::{ diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 5934c8d..a7b55ad 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -589,6 +589,11 @@ pub struct OnboardedTarget { /// Cached count of findings across this target's scans. #[serde(default)] pub findings_count: u32, + /// The tenant's projects (registry ids) this target belongs to: a + /// product or machine, or a topic such as the CRA. Organisational only; + /// what gets checked follows `compliance_profile`. + #[serde(default)] + pub project_ids: Vec, /// Creation timestamp. #[serde( default = "chrono::Utc::now", @@ -623,6 +628,7 @@ impl OnboardedTarget { webhook_enabled: false, webhook_secret: None, findings_count: 0, + project_ids: Vec::new(), created_at: now, updated_at: now, } diff --git a/compliance-core/src/models/project.rs b/compliance-core/src/models/project.rs new file mode 100644 index 0000000..d9012e8 --- /dev/null +++ b/compliance-core/src/models/project.rs @@ -0,0 +1,46 @@ +//! A tenant's projects, owned by the platform registry. +//! +//! A project groups targets organisationally: a customer's product or +//! machine, or a topic such as the CRA or the Data Act. It never changes what +//! gets checked. Targets refer to projects by the registry's id. + +use serde::{Deserialize, Serialize}; + +/// What a project stands for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProjectKind { + /// A customer's product or machine. + Product, + /// A topic such as the CRA or the Data Act. + Topic, +} + +/// One of a tenant's projects, as the registry lists it +/// (`GET /v1/tenants/{id}/projects`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Project { + /// The registry's id (a UUID). + pub id: String, + pub name: String, + pub kind: ProjectKind, + #[serde(default)] + pub description: String, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_registry_project_reads() { + let p: Project = serde_json::from_value(serde_json::json!({ + "id": "0b7d51aa-9f1c-4e33-8a1f-2d8c1e0f9a77", + "name": "Rangierlok 3000", + "kind": "product" + })) + .expect("deserialize"); + assert_eq!(p.kind, ProjectKind::Product); + assert_eq!(p.description, ""); + } +} diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 5a158d9..6227846 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5371,3 +5371,83 @@ input[type="file"] { color: var(--accent); font-weight: 600; } + +/* ═══════════════════════════════════════════════════════════════ + PROJECTS — chips, the list filter and the picker in the editor + ═══════════════════════════════════════════════════════════════ */ +.project-chips { + display: inline-flex; + flex-wrap: wrap; + gap: 4px; + margin-left: 8px; + vertical-align: middle; +} +.target-head-text .project-chips { + margin: 4px 0 0; + display: flex; +} +.project-chip { + display: inline-block; + padding: 1px 8px; + border-radius: 999px; + background: var(--accent-muted); + color: var(--accent); + font-size: 11px; + font-weight: 600; + white-space: nowrap; +} +.project-filter { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 13px; + color: var(--text-secondary); +} +.project-filter select { + min-width: 180px; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg-elevated); + color: var(--text-primary); + font: inherit; +} +.project-picker { + margin: 12px 0 0; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 10px; +} +.project-picker legend { + padding: 0 4px; + font-size: 13px; + font-weight: 600; +} +.project-picker-list { + display: grid; + gap: 4px; + max-height: 200px; + overflow-y: auto; +} +.project-picker-item { + display: flex; + align-items: center; + gap: 8px; + font-size: 14px; + cursor: pointer; +} +.project-picker-kind { + margin-left: auto; + font-size: 12px; + color: var(--text-tertiary); +} +.project-picker-hint { + margin: 8px 0 0; + font-size: 12px; + color: var(--text-tertiary); +} +@media (max-width: 560px) { + .project-filter { margin-left: 0; width: 100%; } + .project-filter select { flex: 1; min-width: 0; } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index e3589b7..9d9cd6a 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -16,6 +16,7 @@ pub mod notification_bell; pub mod page_header; pub mod pagination; pub mod pentest_wizard; +pub mod projects; pub mod scan_coverage; pub mod scan_runs; pub mod severity_badge; diff --git a/compliance-dashboard/src/components/projects.rs b/compliance-dashboard/src/components/projects.rs new file mode 100644 index 0000000..29b5c3a --- /dev/null +++ b/compliance-dashboard/src/components/projects.rs @@ -0,0 +1,75 @@ +//! A target's projects: shown as chips, chosen with a checkbox list. + +use compliance_core::models::Project; +use dioxus::prelude::*; + +use crate::i18n::texts::projects as tx; +use crate::i18n::use_lang; +use crate::infrastructure::projects::projects_named; + +/// The projects a target belongs to, as small chips. Nothing when it +/// belongs to none (or only to deleted ones). +#[component] +pub fn ProjectChips(ids: Vec, projects: Vec) -> Element { + let lang = use_lang()(); + let shown = projects_named(&ids, &projects); + if shown.is_empty() { + return rsx! {}; + } + rsx! { + span { class: "project-chips", + for p in shown { + span { + key: "{p.id}", + class: "project-chip", + title: "{tx::kind(p.kind).get(lang)}", + "{p.name}" + } + } + } + } +} + +/// Choose a target's projects from the tenant's list. +#[component] +pub fn ProjectPicker(projects: Vec, mut selected: Signal>) -> Element { + let lang = use_lang()(); + rsx! { + fieldset { class: "project-picker", + legend { {tx::TITLE.get(lang)} } + if projects.is_empty() { + p { class: "project-picker-hint", {tx::NONE_YET.get(lang)} } + } else { + div { class: "project-picker-list", + for p in projects { + { + let id = p.id.clone(); + let checked = selected.read().contains(&id); + rsx! { + label { key: "{p.id}", class: "project-picker-item", + input { + r#type: "checkbox", + checked, + onchange: move |e| { + let mut ids = selected.write(); + if e.checked() { + if !ids.contains(&id) { + ids.push(id.clone()); + } + } else { + ids.retain(|x| x != &id); + } + }, + } + span { class: "project-picker-name", "{p.name}" } + span { class: "project-picker-kind", {tx::kind(p.kind).get(lang)} } + } + } + } + } + } + p { class: "project-picker-hint", {tx::HINT.get(lang)} } + } + } + } +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index d671f5a..acb96c8 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2402,6 +2402,58 @@ pub mod demo { } /// What each scan does and why it cannot run, for the applicable-scans list. +/// The tenant's projects: products, machines or topics that group targets. +pub mod projects { + use super::Text; + use compliance_core::models::ProjectKind; + + pub const TITLE: Text = Text { + de: "Projekte", + en: "Projects", + }; + pub const FILTER: Text = Text { + de: "Projekt", + en: "Project", + }; + pub const ALL: Text = Text { + de: "Alle Projekte", + en: "All projects", + }; + pub const HINT: Text = Text { + de: "Projekte legen Sie im Portal an. Sie ordnen Prüfobjekte nur; was geprüft \ + wird, ändert sich dadurch nicht.", + en: "Projects are created in the portal. They only group targets; what gets \ + checked does not change.", + }; + pub const NONE_YET: Text = Text { + de: "Noch keine Projekte. Legen Sie sie im Portal an.", + en: "No projects yet. Create them in the portal.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Projekte konnten nicht geladen werden", + en: "The projects could not be loaded", + }; + pub const NONE_IN_PROJECT: Text = Text { + de: "Diesem Projekt ist noch kein Prüfobjekt zugeordnet.", + en: "No target belongs to this project yet.", + }; + + /// What kind of project it is. Exhaustive: a new kind needs both + /// languages. + pub fn kind(kind: ProjectKind) -> Text { + match kind { + ProjectKind::Product => Text { + de: "Produkt", + en: "Product", + }, + ProjectKind::Topic => Text { + de: "Thema", + en: "Topic", + }, + } + } +} + /// BreakPilot support access: the tenant picker and the banner. pub mod support { use super::Text; diff --git a/compliance-dashboard/src/infrastructure/mod.rs b/compliance-dashboard/src/infrastructure/mod.rs index d873311..b58de12 100644 --- a/compliance-dashboard/src/infrastructure/mod.rs +++ b/compliance-dashboard/src/infrastructure/mod.rs @@ -15,6 +15,7 @@ pub mod notifications; pub mod onboarding; pub mod pentest; pub mod platform; +pub mod projects; #[allow(clippy::too_many_arguments)] pub mod sbom; pub mod scans; diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 32a303a..0568fe3 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -311,8 +311,17 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option { /// List onboarded targets. #[server] pub async fn fetch_targets() -> Result { - let resp = super::agent_client::agent_get("/api/v1/targets") - .await? + fetch_targets_in(None).await +} + +/// The targets, only those of `project` when given (`?project=`). +#[server] +pub async fn fetch_targets_in(project: Option) -> Result { + let mut req = super::agent_client::agent_get("/api/v1/targets").await?; + if let Some(project) = project.filter(|p| !p.is_empty()) { + req = req.query(&[("project", project)]); + } + let resp = req .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; diff --git a/compliance-dashboard/src/infrastructure/projects.rs b/compliance-dashboard/src/infrastructure/projects.rs new file mode 100644 index 0000000..2d3ad10 --- /dev/null +++ b/compliance-dashboard/src/infrastructure/projects.rs @@ -0,0 +1,89 @@ +//! The tenant's projects (owned by the platform registry) and the targets' +//! assignments to them. + +use compliance_core::models::Project; +use dioxus::prelude::*; + +/// The tenant's projects (`GET /api/v1/projects`). +#[server] +pub async fn fetch_projects() -> Result, ServerFnError> { + let resp = super::agent_client::agent_get("/api/v1/projects") + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let body: serde_json::Value = super::agent_client::json_or_error(resp).await?; + serde_json::from_value(body["data"].clone()).map_err(|e| ServerFnError::new(e.to_string())) +} + +/// Replace the projects target `id` belongs to. +/// +/// # Errors +/// +/// The agent refused, e.g. an id that is no longer one of the tenant's +/// projects (422). +#[server] +pub async fn set_target_projects( + id: String, + project_ids: Vec, +) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request( + reqwest::Method::PATCH, + &format!("/api/v1/targets/{id}"), + ) + .await? + .json(&serde_json::json!({ "project_ids": project_ids })) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// The ids in a target's JSON (`project_ids`), as the agent returned it. +pub fn project_ids_of(target: &serde_json::Value) -> Vec { + target + .get("project_ids") + .and_then(|ids| ids.as_array()) + .map(|ids| { + ids.iter() + .filter_map(|id| id.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +/// The projects among `projects` that `ids` name, in the projects' order. +/// Ids of deleted projects are left out. +pub fn projects_named<'a>(ids: &[String], projects: &'a [Project]) -> Vec<&'a Project> { + projects.iter().filter(|p| ids.contains(&p.id)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::ProjectKind; + + fn project(id: &str, name: &str) -> Project { + Project { + id: id.to_string(), + name: name.to_string(), + kind: ProjectKind::Product, + description: String::new(), + } + } + + #[test] + fn a_targets_project_ids_are_read() { + let t = serde_json::json!({ "name": "fw", "project_ids": ["p1", "p2"] }); + assert_eq!(project_ids_of(&t), ["p1", "p2"]); + assert!(project_ids_of(&serde_json::json!({ "name": "old" })).is_empty()); + } + + #[test] + fn deleted_projects_are_not_shown() { + let projects = [project("p1", "Lok"), project("p2", "CRA")]; + let shown = projects_named(&["p2".to_string(), "gone".to_string()], &projects); + let names: Vec<&str> = shown.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["CRA"]); + } +} diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index a07f84d..dd973e2 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -11,6 +11,7 @@ use crate::components::artifact_upload::ArtifactUpload; use crate::components::cra_bar::CraBar; use crate::components::evidence_button::EvidencePackButton; use crate::components::manual_findings::ManualFindingsPanel; +use crate::components::projects::{ProjectChips, ProjectPicker}; use crate::components::scan_coverage::ScanCoverage; use crate::components::scan_runs::ScanRunList; use crate::components::severity_badge::SeverityBadge; @@ -25,6 +26,7 @@ use crate::infrastructure::onboarding::{ ArchivePassword, ArtifactInputDto, PasswordOutcome, }; use crate::infrastructure::platform::{use_source_only, SourceOnlyNote}; +use crate::infrastructure::projects::{fetch_projects, project_ids_of, set_target_projects}; /// Open findings listed on the page; the rest are one click away. const OPEN_SHOWN: usize = 5; @@ -94,6 +96,7 @@ pub fn TargetPage(id: String) -> Element { let mut adding_manual = use_signal(|| false); let mut starting = use_signal(|| false); let mut scans_started = use_signal(|| 0u32); + let projects = use_resource(fetch_projects); let snapshot = target.read().clone(); let Some(Some(resp)) = snapshot else { @@ -134,6 +137,9 @@ pub fn TargetPage(id: String) -> Element { header { class: "target-head", div { class: "target-head-text", h2 { "{name}" } + if let Some(Ok(projects)) = projects.read().clone() { + ProjectChips { ids: project_ids_of(&t), projects } + } p { class: "target-head-meta", span { "{type_label}" } for a in artifacts.iter() { @@ -411,6 +417,10 @@ fn TargetEditor( let mut edit_type = use_signal(|| str_at(&target, "target_type").to_string()); let mut edit_arts = use_signal(|| editable_artifacts(&target)); let mut edit_saving = use_signal(|| false); + // Projects are saved apart from the rest, and only when they changed. + let stored_projects = project_ids_of(&target); + let edit_projects = use_signal(|| stored_projects.clone()); + let projects = use_resource(fetch_projects); // The dialog's "add artifact" row. let mut e_kind = use_signal(|| "git_repo".to_string()); let mut e_source = use_signal(String::new); @@ -576,6 +586,13 @@ fn TargetEditor( on_saved.call(()); }, } + match projects.read().clone() { + Some(Ok(list)) => rsx! { ProjectPicker { projects: list, selected: edit_projects } }, + Some(Err(e)) => rsx! { + p { class: "project-picker-hint", "{crate::i18n::texts::projects::LOAD_FAILED.get(lang)}: {e}" } + }, + None => rsx! {}, + } div { class: "modal-actions", button { class: "btn btn-secondary", @@ -590,10 +607,17 @@ fn TargetEditor( let nm = edit_name(); let tt = edit_type(); let arts = edit_arts(); + let chosen = edit_projects(); + let projects_changed = chosen != stored_projects; edit_saving.set(true); spawn(async move { - match update_target(id, Some(nm), Some(tt), Some(arts)).await { - Ok(_) => { + let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts)).await { + Ok(_) if projects_changed => set_target_projects(id, chosen).await, + Ok(_) => Ok(()), + Err(e) => Err(e), + }; + match saved { + Ok(()) => { toasts.push(ToastType::Success, tx::UPDATED.get(lang)); on_saved.call(()); } diff --git a/compliance-dashboard/src/pages/targets.rs b/compliance-dashboard/src/pages/targets.rs index bae8bda..fba2e63 100644 --- a/compliance-dashboard/src/pages/targets.rs +++ b/compliance-dashboard/src/pages/targets.rs @@ -10,13 +10,15 @@ use crate::app::Route; use crate::components::cra_bar::CraBar; use crate::components::demo_targets::DemoTargetsButton; use crate::components::page_header::PageHeader; +use crate::components::projects::ProjectChips; use crate::components::scan_runs::status_badge; use crate::components::toast::{ToastType, Toasts}; use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx}; use crate::i18n::{format_ago, use_lang, Lang}; use crate::infrastructure::auth_check::{go_to_login, is_session_expired}; use crate::infrastructure::evidence::fetch_compliance_summary; -use crate::infrastructure::onboarding::{fetch_targets, trigger_target_scan}; +use crate::infrastructure::onboarding::{fetch_targets_in, trigger_target_scan}; +use crate::infrastructure::projects::{fetch_projects, project_ids_of}; use compliance_core::models::{ScanRun, ScanRunStatus}; /// How often the list refreshes while a scan is running, in milliseconds. @@ -66,10 +68,14 @@ pub fn TargetsPage() -> Element { let mut toasts = use_context::(); let navigator = use_navigator(); let mut scanning_ids = use_signal(Vec::::new); + // The chosen project filter (`None`: every target); the list reloads when + // it changes, since the resource reads it. + let mut project = use_signal(|| Option::::None); + let projects = use_resource(fetch_projects); // A failure keeps its reason, to show it; an expired sign-in goes to the // login instead. let mut targets = use_resource(move || async move { - fetch_targets().await.map_err(|e| { + fetch_targets_in(project()).await.map_err(|e| { if is_session_expired(&e) { go_to_login(); } @@ -105,6 +111,26 @@ pub fn TargetsPage() -> Element { Link { to: Route::OnboardingPage {}, class: "btn btn-primary", {tx::ADD.get(lang)} } + if let Some(Ok(list)) = projects.read().clone().filter(|p| p.as_ref().is_ok_and(|l| !l.is_empty())) { + label { class: "project-filter", + span { {crate::i18n::texts::projects::FILTER.get(lang)} } + select { + onchange: move |e| { + let v = e.value(); + project.set((!v.is_empty()).then_some(v)); + }, + option { value: "", selected: project().is_none(), {crate::i18n::texts::projects::ALL.get(lang)} } + for p in list { + option { + key: "{p.id}", + value: "{p.id}", + selected: project().as_deref() == Some(p.id.as_str()), + "{p.name}" + } + } + } + } + } } { @@ -118,6 +144,11 @@ pub fn TargetsPage() -> Element { .and_then(|r| r.counts) }; match &targets_snapshot { + Some(Ok(resp)) if resp.data.is_empty() && project().is_some() => rsx! { + div { class: "card targets-empty", + p { {crate::i18n::texts::projects::NONE_IN_PROJECT.get(lang)} } + } + }, Some(Ok(resp)) if resp.data.is_empty() => rsx! { div { class: "card targets-empty", p { {tx::EMPTY.get(lang)} } @@ -169,6 +200,9 @@ pub fn TargetsPage() -> Element { "{name}" } span { class: "targets-type", "{ttype}" } + if let Some(Ok(all)) = projects.read().clone() { + ProjectChips { ids: project_ids_of(t), projects: all } + } } td { class: "targets-scan", match last_scan {