From e65aa76ef5fe9dad3c019f6224cbe74419f304fe Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Thu, 15 Oct 2026 12:03:29 +0000 Subject: [PATCH] feat(sbom): confirm the licence of components (licence review) (#569) --- compliance-agent/src/api/handlers/dto.rs | 13 + compliance-agent/src/api/handlers/evidence.rs | 17 +- compliance-agent/src/api/handlers/licenses.rs | 391 ++++++++++++++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/handlers/sbom.rs | 272 ++++++++-- .../src/api/role_gate/router_tests.rs | 7 + compliance-agent/src/api/routes.rs | 7 + compliance-agent/src/database.rs | 15 + compliance-agent/src/lib.rs | 1 + compliance-agent/src/license_conclusions.rs | 45 ++ compliance-agent/src/pipeline/sbom_quality.rs | 4 +- compliance-core/src/models/license.rs | 479 ++++++++++++++++++ compliance-core/src/models/mod.rs | 2 + compliance-core/src/models/sbom.rs | 14 + compliance-core/src/sbom_docs.rs | 259 +++++++++- compliance-core/src/spdx_license.rs | 163 ++++++ compliance-dashboard/assets/main.css | 128 +++++ .../src/components/license_editor.rs | 444 ++++++++++++++++ compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 225 ++++++++ .../src/infrastructure/sbom.rs | 96 +++- compliance-dashboard/src/pages/sbom.rs | 179 +++++-- docs/guide/sbom.md | 49 +- 23 files changed, 2707 insertions(+), 105 deletions(-) create mode 100644 compliance-agent/src/api/handlers/licenses.rs create mode 100644 compliance-agent/src/license_conclusions.rs create mode 100644 compliance-core/src/models/license.rs create mode 100644 compliance-dashboard/src/components/license_editor.rs diff --git a/compliance-agent/src/api/handlers/dto.rs b/compliance-agent/src/api/handlers/dto.rs index d75e72b..6fd34ed 100644 --- a/compliance-agent/src/api/handlers/dto.rs +++ b/compliance-agent/src/api/handlers/dto.rs @@ -230,6 +230,10 @@ pub struct SbomFilter { /// others (`false`); see [`compliance_core::models::InImage`]. #[serde(default)] pub in_image: Option, + /// Only components whose licence is still open (`true`): the scan found + /// none and nobody has confirmed one. + #[serde(default)] + pub unresolved: Option, #[serde(default = "default_page", deserialize_with = "de_page")] pub page: u64, #[serde(default = "default_limit", deserialize_with = "de_limit")] @@ -267,6 +271,11 @@ pub struct LicenseSummary { pub license: String, pub count: u64, pub is_copyleft: bool, + /// What the licence allows (`permissive`, `weak_copyleft`, ...); for a + /// confirmed licence the category the person chose. + pub category: compliance_core::models::LicenseCategory, + /// How many of the components a person confirmed this licence for. + pub confirmed: u64, pub packages: Vec, } @@ -659,12 +668,16 @@ mod tests { license: "MIT".to_string(), count: 42, is_copyleft: false, + category: compliance_core::models::LicenseCategory::Permissive, + confirmed: 3, packages: vec!["serde".to_string()], }; let v = serde_json::to_value(&ls).unwrap(); assert_eq!(v["license"], "MIT"); assert_eq!(v["is_copyleft"], false); assert_eq!(v["count"], 42); + assert_eq!(v["category"], "permissive"); + assert_eq!(v["confirmed"], 3); } // ── Default helper functions ───────────────────────────────── diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index faa0b78..ab56a5d 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -54,6 +54,15 @@ async fn load_inputs( tracing::warn!("evidence: {e}"); StatusCode::INTERNAL_SERVER_ERROR }; + let mut sbom = collect_cursor_async( + db.sbom_entries() + .find(by_target.clone()) + .await + .map_err(load_err)?, + ) + .await; + // The licences a person confirmed are part of the evidence's SBOM. + crate::license_conclusions::attach(db, &mut sbom).await; Ok(EvidenceInputs { findings: collect_cursor_async( db.findings() @@ -62,13 +71,7 @@ async fn load_inputs( .map_err(load_err)?, ) .await, - sbom: collect_cursor_async( - db.sbom_entries() - .find(by_target.clone()) - .await - .map_err(load_err)?, - ) - .await, + sbom, cves: collect_cursor_async( db.cve_alerts() .find(by_target.clone()) diff --git a/compliance-agent/src/api/handlers/licenses.rs b/compliance-agent/src/api/handlers/licenses.rs new file mode 100644 index 0000000..df928f5 --- /dev/null +++ b/compliance-agent/src/api/handlers/licenses.rs @@ -0,0 +1,391 @@ +//! Licences a workspace confirms for its components: list them, confirm one +//! for one or many components at once, and withdraw one. The scanned +//! licence stays as detected; the confirmed one is merged in when the +//! components are read and exported ([`crate::license_conclusions`]). +//! +//! Writes are for the roles that may change Prüfwerk (IT_ADMIN, USER), as +//! the role gate decides for every `PUT` and `DELETE`. + +use axum::extract::{Extension, Query}; +use axum::http::StatusCode; +use axum::Json; +use chrono::NaiveDate; +use mongodb::bson::doc; +use serde::Deserialize; + +use compliance_core::models::license::{ + self, conclusion_id, package_key, LicenseCategory, LicenseConclusion, LicenseUsage, +}; +use compliance_core::spdx_license; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult}; +use super::findings::Actor; +use crate::license_conclusions::MAX_CONCLUSIONS; + +/// The most components one request confirms. +pub const MAX_COMPONENTS: usize = 500; + +/// A component a licence is confirmed for, as the SBOM list shows it. +#[derive(Debug, Clone, Deserialize)] +pub struct ComponentRef { + pub name: String, + pub package_manager: String, + #[serde(default)] + pub version: String, + #[serde(default)] + pub purl: Option, +} + +/// The body of [`conclude`]. +#[derive(Debug, Deserialize)] +pub struct ConcludeRequest { + pub components: Vec, + /// For every version of the packages, not just the listed ones. + #[serde(default)] + pub all_versions: bool, + /// An SPDX licence expression or a licence name SPDX knows. Empty for a + /// licence of its own, named in `license_name`. + #[serde(default)] + pub license: Option, + #[serde(default)] + pub license_name: Option, + /// Used for a licence of its own and where SPDX gives no category. + #[serde(default)] + pub category: Option, + #[serde(default)] + pub copyright: Vec, + #[serde(default)] + pub license_text: Option, + #[serde(default)] + pub license_url: Option, + #[serde(default)] + pub evidence: Option, + #[serde(default)] + pub contract_ref: Option, + #[serde(default)] + pub valid_until: Option, + #[serde(default)] + pub usage: Option, + #[serde(default)] + pub note: Option, +} + +type Refusal = (StatusCode, Json); + +fn refuse(code: StatusCode, error: impl Into) -> Refusal { + (code, Json(serde_json::json!({ "error": error.into() }))) +} + +/// Trimmed, `None` when empty. +fn text(value: Option) -> Option { + value + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()) +} + +/// The licence `req` states, as stored: the SPDX expression and its +/// category, or a `LicenseRef-` with the name and the category asked for. +/// +/// # Errors +/// +/// Neither a licence nor a name, or a licence SPDX cannot read. +fn licence_of(req: &ConcludeRequest) -> Result<(String, Option, LicenseCategory), String> { + let asked = req.category.unwrap_or(LicenseCategory::Unclear); + if let Some(license) = text(req.license.clone()) { + let spdx = spdx_license::normalise(&license).into_owned(); + if !spdx_license::is_spdx_expression(&spdx) { + return Err(format!( + "not an SPDX licence expression: {license}. For a licence SPDX does not list, give its name instead" + )); + } + let derived = spdx_license::category(&spdx); + let category = if derived == LicenseCategory::Unclear { + asked + } else { + derived + }; + return Ok((spdx, None, category)); + } + match text(req.license_name.clone()) { + Some(name) => Ok((license::license_ref(&name), Some(name), asked)), + None => Err("licence missing: give an SPDX licence or the name of the licence".into()), + } +} + +/// The conclusions `req` asks for, one per component (several components of +/// one package and version are one conclusion), by the requester of +/// `tenant`. +/// +/// # Errors +/// +/// Why the request cannot be stored. +fn conclusions_of( + req: ConcludeRequest, + tenant: &TenantCtx, +) -> Result, String> { + if req.components.is_empty() { + return Err("no component given".into()); + } + if req.components.len() > MAX_COMPONENTS { + return Err(format!("at most {MAX_COMPONENTS} components at once")); + } + let (license, license_name, category) = licence_of(&req)?; + let actor = Actor::of(&tenant.0); + let at = chrono::Utc::now(); + let copyright: Vec = req + .copyright + .iter() + .flat_map(|c| c.lines()) + .map(str::trim) + .filter(|c| !c.is_empty()) + .map(String::from) + .collect(); + let mut out: Vec = Vec::new(); + for component in &req.components { + let name = component.name.trim(); + if name.is_empty() { + return Err("a component without a name".into()); + } + let key = package_key(name, &component.package_manager, component.purl.as_deref()); + let version = (!req.all_versions) + .then(|| component.version.trim().to_string()) + .filter(|v| !v.is_empty()); + let id = conclusion_id(&key, version.as_deref()); + if out.iter().any(|c| c.id == id) { + continue; + } + let conclusion = LicenseConclusion { + id, + package_key: key, + name: name.to_string(), + package_manager: component.package_manager.trim().to_string(), + version, + license: license.clone(), + license_name: license_name.clone(), + category, + copyright: copyright.clone(), + license_text: text(req.license_text.clone()), + license_url: text(req.license_url.clone()), + evidence: text(req.evidence.clone()), + contract_ref: text(req.contract_ref.clone()), + valid_until: req.valid_until, + usage: req.usage, + note: text(req.note.clone()), + by: actor.id.to_string(), + by_name: actor.name.clone(), + support: actor.support, + at, + }; + conclusion.validate()?; + out.push(conclusion); + } + Ok(out) +} + +/// GET /api/v1/licenses/conclusions — every licence the workspace +/// confirmed, by package name. +#[tracing::instrument(skip_all)] +pub async fn list_conclusions( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> ApiResult> { + let db = tenant_db(&agent, &tenant).await?; + let conclusions = crate::license_conclusions::load(&db).await; + Ok(Json(ApiResponse { + total: Some(conclusions.len() as u64), + data: conclusions, + page: None, + })) +} + +/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more +/// components (one version, or every version of their packages). A second +/// confirmation of the same package and version replaces the first. 422 +/// with the reason when the licence or a field is not acceptable. +#[tracing::instrument(skip_all)] +pub async fn conclude( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, Refusal> { + let conclusions = + conclusions_of(req, &tenant).map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?; + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let stored = db + .license_conclusions() + .count_documents(doc! {}) + .await + .map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?; + if stored.saturating_add(conclusions.len() as u64) > MAX_CONCLUSIONS as u64 { + return Err(refuse( + StatusCode::UNPROCESSABLE_ENTITY, + format!("at most {MAX_CONCLUSIONS} confirmed licences per workspace"), + )); + } + for c in &conclusions { + db.license_conclusions() + .replace_one(doc! { "_id": &c.id }, c) + .upsert(true) + .await + .map_err(|e| { + tracing::warn!("license conclusion not stored: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "store") + })?; + } + tracing::info!( + count = conclusions.len(), + license = %conclusions[0].license, + "license confirmed" + ); + Ok(Json(serde_json::json!({ + "status": "saved", + "saved": conclusions.len(), + "conclusions": conclusions, + }))) +} + +/// The query of [`withdraw`]. +#[derive(Debug, Deserialize)] +pub struct WithdrawQuery { + /// The conclusion's id (package and version, see + /// [`license::conclusion_id`]); a query value, as it holds `/` and `@`. + pub id: String, +} + +/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence; +/// the component shows the detected one again. 404 when there is none. +#[tracing::instrument(skip_all)] +pub async fn withdraw( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> Result, Refusal> { + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let result = db + .license_conclusions() + .delete_one(doc! { "_id": &query.id }) + .await + .map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?; + if result.deleted_count == 0 { + return Err(refuse(StatusCode::NOT_FOUND, "no such confirmed licence")); + } + tracing::info!("license conclusion withdrawn"); + Ok(Json(serde_json::json!({ "status": "withdrawn" }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn req(license: Option<&str>, name: Option<&str>) -> ConcludeRequest { + ConcludeRequest { + components: vec![ + ComponentRef { + name: "left-pad".into(), + package_manager: "npm".into(), + version: "1.3.0".into(), + purl: Some("pkg:npm/left-pad@1.3.0".into()), + }, + // The same package and version twice is one conclusion. + ComponentRef { + name: "left-pad".into(), + package_manager: "npm".into(), + version: "1.3.0".into(), + purl: Some("pkg:npm/left-pad@1.3.0".into()), + }, + ComponentRef { + name: "PumpSdk".into(), + package_manager: "nuget".into(), + version: "".into(), + purl: None, + }, + ], + all_versions: false, + license: license.map(String::from), + license_name: name.map(String::from), + category: Some(LicenseCategory::Proprietary), + copyright: vec!["© 2019 Example GmbH\n\n© 2021 Other AG".into()], + license_text: Some(" ".into()), + license_url: None, + evidence: Some(" LICENSE.txt ".into()), + contract_ref: None, + valid_until: None, + usage: Some(LicenseUsage::Shipped), + note: None, + } + } + + fn tenant() -> TenantCtx { + TenantCtx(compliance_core::TenantContext { + tenant_id: "t-1".to_string(), + tenant_slug: "acme".to_string(), + org_roles: Vec::new(), + products: Vec::new(), + plan: String::new(), + status: compliance_core::TenantStatus::Active, + user_id: "u-1".to_string(), + user_name: Some("Erika Muster".to_string()), + staff: None, + api_key: None, + }) + } + + #[test] + fn an_spdx_licence_gets_its_own_category() { + let out = + conclusions_of(req(Some("Apache License, Version 2.0"), None), &tenant()).unwrap(); + assert_eq!(out.len(), 2, "duplicates are merged"); + assert_eq!(out[0].license, "Apache-2.0"); + assert_eq!( + out[0].category, + LicenseCategory::Permissive, + "not the asked category" + ); + assert_eq!(out[0].version.as_deref(), Some("1.3.0")); + assert_eq!(out[0].id, "pkg:npm/left-pad@1.3.0"); + assert_eq!(out[1].id, "nuget:PumpSdk@*", "no version is every version"); + assert_eq!(out[0].copyright, ["© 2019 Example GmbH", "© 2021 Other AG"]); + assert_eq!(out[0].license_text, None); + assert_eq!(out[0].evidence.as_deref(), Some("LICENSE.txt")); + } + + #[test] + fn a_licence_of_its_own_gets_a_license_ref() { + let out = conclusions_of(req(None, Some("Pump EULA")), &tenant()).unwrap(); + assert_eq!(out[0].license, "LicenseRef-Pump-EULA"); + assert_eq!(out[0].license_name.as_deref(), Some("Pump EULA")); + assert_eq!(out[0].category, LicenseCategory::Proprietary); + } + + #[test] + fn every_version_drops_the_version() { + let mut r = req(Some("MIT"), None); + r.all_versions = true; + let out = conclusions_of(r, &tenant()).unwrap(); + assert_eq!(out[0].id, "pkg:npm/left-pad@*"); + assert_eq!(out[0].version, None); + } + + #[test] + fn bad_requests_are_refused_with_a_reason() { + assert!(conclusions_of(req(None, None), &tenant()).is_err()); + assert!(conclusions_of(req(Some("Custom thing"), None), &tenant()).is_err()); + let mut none = req(Some("MIT"), None); + none.components.clear(); + assert!(conclusions_of(none, &tenant()).is_err()); + let mut many = req(Some("MIT"), None); + many.components = vec![many.components[0].clone(); MAX_COMPONENTS + 1]; + assert!(conclusions_of(many, &tenant()).is_err()); + let mut nameless = req(Some("MIT"), None); + nameless.components[0].name = " ".into(); + assert!(conclusions_of(nameless, &tenant()).is_err()); + let mut url = req(Some("MIT"), None); + url.license_url = Some("file:///etc/passwd".into()); + assert!(conclusions_of(url, &tenant()).is_err()); + } +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index a8e3081..e3ce2e8 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -10,6 +10,7 @@ pub mod graph; pub mod health; pub mod help_chat; pub mod issues; +pub mod licenses; pub mod manual_findings; pub mod mcp_servers; pub mod mcp_tokens; diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index b72d04b..a7cf43e 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -87,15 +87,37 @@ pub async fn list_sbom( if let Some(in_image) = filter.in_image { query.insert("in_image", doc! { "$exists": in_image }); } + let conclusions = crate::license_conclusions::load(db).await; - let skip = filter.skip(); - let total = db - .sbom_entries() - .count_documents(query.clone()) - .await - .unwrap_or(0); + let mut skip = filter.skip(); + let mut total = None; + if filter.unresolved == Some(true) { + // No licence found by the scan; `null` also matches a missing field. + query.insert("license", doc! { "$in": [mongodb::bson::Bson::Null, ""] }); + if !conclusions.is_empty() { + // Which of them nobody confirmed a licence for is known only + // here, so the page is cut from the open ones. + let open = unresolved_ids(db, &query, &conclusions).await; + total = Some(open.len() as u64); + let page: Vec<_> = open + .into_iter() + .skip(usize::try_from(skip).unwrap_or(usize::MAX)) + .take(usize::try_from(filter.limit).unwrap_or(0)) + .collect(); + query = doc! { "_id": { "$in": page } }; + skip = 0; + } + } + let total = match total { + Some(total) => total, + None => db + .sbom_entries() + .count_documents(query.clone()) + .await + .unwrap_or(0), + }; - let entries = match db + let mut entries: Vec = match db .sbom_entries() .find(query) .sort(list_order()) @@ -109,6 +131,7 @@ pub async fn list_sbom( Vec::new() } }; + compliance_core::models::license::apply(&mut entries, &conclusions); Ok(Json(ApiResponse { data: entries, @@ -123,6 +146,56 @@ fn list_order() -> mongodb::bson::Document { doc! { "in_image.basis": -1, "name": 1 } } +/// The fields a licence conclusion is matched on. +#[derive(serde::Deserialize)] +struct LicenseKeyRow { + #[serde(rename = "_id")] + id: mongodb::bson::oid::ObjectId, + name: String, + version: String, + package_manager: String, + #[serde(default)] + purl: Option, + #[serde(default)] + license: Option, +} + +/// The components of `query` (in list order) nobody confirmed a licence for. +async fn unresolved_ids( + db: &crate::database::Database, + query: &mongodb::bson::Document, + conclusions: &[compliance_core::models::LicenseConclusion], +) -> Vec { + let rows: Vec = match db + .sbom_entries() + .clone_with_type::() + .find(query.clone()) + .projection(doc! { "_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1 }) + .sort(list_order()) + .limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX)) + .await + { + Ok(cursor) => collect_cursor_async(cursor).await, + Err(e) => { + tracing::warn!("Failed to fetch open licences: {e}"); + Vec::new() + } + }; + rows.into_iter() + .filter(|r| { + compliance_core::models::license::find_for( + conclusions, + &r.name, + &r.package_manager, + &r.version, + r.purl.as_deref(), + ) + .is_none() + }) + .map(|r| r.id) + .collect() +} + #[tracing::instrument(skip_all)] pub async fn export_sbom( Extension(agent): AgentExt, @@ -143,7 +216,7 @@ pub async fn export_sbom( ); return Err(StatusCode::PAYLOAD_TOO_LARGE); } - let entries: Vec = match db + let mut entries: Vec = match db .sbom_entries() .find(doc! { "repo_id": ¶ms.repo_id }) .await @@ -154,6 +227,7 @@ pub async fn export_sbom( Vec::new() } }; + crate::license_conclusions::attach(db, &mut entries).await; let body = if params.format == "spdx" { compliance_core::sbom_docs::spdx(&entries, ¶ms.repo_id) @@ -245,53 +319,96 @@ pub async fn license_summary( query.insert("repo_id", repo_id); } - // Grouped in Mongo: this used to load every SBOM entry of the tenant (with - // its vulnerability list) into the agent when no repo was given (#67). - #[derive(serde::Deserialize)] - struct LicenseRow { - #[serde(rename = "_id")] - license: String, - count: i64, - packages: Vec, - } - let pipeline = vec![ - doc! { "$match": query }, - doc! { "$group": { - "_id": { "$ifNull": ["$license", "Unknown"] }, - "count": { "$sum": 1 }, - "packages": { "$firstN": { "input": "$name", "n": MAX_LICENSE_PACKAGES } }, - } }, - ]; - let mut summaries: Vec = match db.sbom_entries().aggregate(pipeline).await { - Ok(cursor) => { - use futures_util::StreamExt; - cursor - .filter_map(|row| async move { - let row: LicenseRow = mongodb::bson::from_document(row.ok()?).ok()?; - Some(LicenseSummary { - is_copyleft: compliance_core::spdx_license::is_copyleft(&row.license), - license: row.license, - count: u64::try_from(row.count).unwrap_or(0), - packages: row.packages, - }) - }) - .collect() - .await - } + // Only the fields the grouping needs, never whole entries with their + // vulnerability lists (#67). Grouped here rather than in Mongo, as a + // licence a person confirmed counts instead of the detected one. + let rows: Vec = match db + .sbom_entries() + .clone_with_type::() + .find(query) + .projection(doc! { + "_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1, "license": 1, + }) + .limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX)) + .await + { + Ok(cursor) => collect_cursor_async(cursor).await, Err(e) => { - tracing::warn!("Failed to aggregate SBOM licenses: {e}"); + tracing::warn!("Failed to read SBOM licenses: {e}"); Vec::new() } }; - summaries.sort_by_key(|s| std::cmp::Reverse(s.count)); - + let conclusions = crate::license_conclusions::load(db).await; Ok(Json(ApiResponse { - data: summaries, + data: summarize_licenses(&rows, &conclusions), total: None, page: None, })) } +/// One summary row per licence, most components first: the confirmed +/// licence where there is one, else the detected one, else `Unknown`. +fn summarize_licenses( + rows: &[LicenseKeyRow], + conclusions: &[compliance_core::models::LicenseConclusion], +) -> Vec { + use compliance_core::models::LicenseCategory; + use compliance_core::spdx_license; + let mut by_license: std::collections::HashMap = + std::collections::HashMap::new(); + for r in rows { + let concluded = compliance_core::models::license::find_for( + conclusions, + &r.name, + &r.package_manager, + &r.version, + r.purl.as_deref(), + ); + let detected = r + .license + .as_deref() + .map(str::trim) + .filter(|l| !l.is_empty()); + let (label, category, is_copyleft) = match (concluded, detected) { + (Some(c), _) => ( + c.display().to_string(), + c.category, + c.category.is_copyleft(), + ), + (None, Some(l)) => ( + l.to_string(), + spdx_license::category(l), + spdx_license::is_copyleft(l), + ), + (None, None) => ("Unknown".to_string(), LicenseCategory::Unclear, false), + }; + let row = by_license + .entry(label.clone()) + .or_insert_with(|| LicenseSummary { + license: label, + count: 0, + is_copyleft, + category, + confirmed: 0, + packages: Vec::new(), + }); + row.count += 1; + if concluded.is_some() { + row.confirmed += 1; + } + if (row.packages.len() as i64) < MAX_LICENSE_PACKAGES && !row.packages.contains(&r.name) { + row.packages.push(r.name.clone()); + } + } + let mut summaries: Vec = by_license.into_values().collect(); + summaries.sort_by(|a, b| { + b.count + .cmp(&a.count) + .then_with(|| a.license.cmp(&b.license)) + }); + summaries +} + #[tracing::instrument(skip_all)] pub async fn sbom_diff( Extension(agent): AgentExt, @@ -396,3 +513,68 @@ async fn diff_rows(db: &crate::database::Database, repo_id: &str) -> Vec) -> LicenseKeyRow { + LicenseKeyRow { + id: mongodb::bson::oid::ObjectId::new(), + name: name.into(), + version: "1.0".into(), + package_manager: "npm".into(), + purl: Some(format!("pkg:npm/{name}@1.0")), + license: license.map(String::from), + } + } + + #[test] + fn a_confirmed_licence_counts_instead_of_the_detected_one() { + let key = package_key("pump", "npm", Some("pkg:npm/pump@1.0")); + let conclusion = LicenseConclusion { + id: conclusion_id(&key, None), + package_key: key, + name: "pump".into(), + package_manager: "npm".into(), + version: None, + license: "LicenseRef-Pump-EULA".into(), + license_name: Some("Pump EULA".into()), + category: LicenseCategory::Proprietary, + copyright: Vec::new(), + license_text: None, + license_url: None, + evidence: None, + contract_ref: None, + valid_until: None, + usage: None, + note: None, + by: "u".into(), + by_name: None, + support: false, + at: chrono::Utc::now(), + }; + let rows = [ + row("a", Some("MIT")), + row("b", Some("MIT")), + row("c", Some("LGPL-2.1-only")), + row("d", None), + row("pump", None), + ]; + let summary = summarize_licenses(&rows, &[conclusion]); + let get = |l: &str| summary.iter().find(|s| s.license == l).unwrap(); + assert_eq!(summary[0].license, "MIT"); + assert_eq!(get("MIT").count, 2); + assert_eq!(get("MIT").category, LicenseCategory::Permissive); + assert_eq!(get("LGPL-2.1-only").category, LicenseCategory::WeakCopyleft); + assert_eq!( + get("Unknown").count, + 1, + "the confirmed one is no longer unknown" + ); + assert_eq!(get("Pump EULA").confirmed, 1); + assert_eq!(get("Pump EULA").category, LicenseCategory::Proprietary); + } +} diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index 961d588..63bd9d9 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -143,6 +143,13 @@ fn routes() -> Vec<(Method, String, bool)> { false, ), (Method::GET, "/api/v1/sbom/export".into(), false), + (Method::GET, "/api/v1/licenses/conclusions".into(), false), + (Method::PUT, "/api/v1/licenses/conclusions".into(), true), + ( + Method::DELETE, + "/api/v1/licenses/conclusions?id=pkg%3Anpm%2Fa%40*".into(), + true, + ), (Method::POST, "/api/v1/mcp-tokens".into(), true), (Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true), (Method::POST, "/api/v1/notifications/read-all".into(), true), diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 34fb69d..619ed25 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -145,6 +145,13 @@ pub fn build_router() -> Router { .route("/api/v1/sbom/licenses", get(handlers::license_summary)) .route("/api/v1/sbom/quality", get(handlers::sbom_quality)) .route("/api/v1/sbom/diff", get(handlers::sbom_diff)) + // Licences the workspace confirms for its components. + .route( + "/api/v1/licenses/conclusions", + get(handlers::licenses::list_conclusions) + .put(handlers::licenses::conclude) + .delete(handlers::licenses::withdraw), + ) .route("/api/v1/issues", get(handlers::list_issues)) .route("/api/v1/scan-runs", get(handlers::list_scan_runs)) // MCP token management (per-tenant API tokens for the MCP server) diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 229912b..a1cef14 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -334,6 +334,15 @@ impl Database { ) .await?; + // license_conclusions: looked up by package (the _id is package + version) + self.license_conclusions() + .create_index( + IndexModel::builder() + .keys(doc! { "package_key": 1 }) + .build(), + ) + .await?; + // cve_alerts: unique cve_id + repo_id self.cve_alerts() .create_index( @@ -646,6 +655,12 @@ impl Database { self.inner.collection("sbom_entries") } + /// Licences the workspace confirmed for its packages; merged into the + /// components when they are read (see [`crate::license_conclusions`]). + pub fn license_conclusions(&self) -> Collection { + self.inner.collection("license_conclusions") + } + pub fn cve_alerts(&self) -> Collection { self.inner.collection("cve_alerts") } diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 3752894..8a3bec2 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -14,6 +14,7 @@ pub mod fixtures; pub mod git_source; pub mod import; pub mod ingest; +pub mod license_conclusions; pub mod lifecycle; pub mod llm; pub mod pentest; diff --git a/compliance-agent/src/license_conclusions.rs b/compliance-agent/src/license_conclusions.rs new file mode 100644 index 0000000..c318d1a --- /dev/null +++ b/compliance-agent/src/license_conclusions.rs @@ -0,0 +1,45 @@ +//! The licences a workspace confirmed, merged into its +//! components wherever they are read: the SBOM list and licence summary, the +//! SBOM exports, the evidence pack and the SBOM quality score. A scan +//! rewrites the components, so the conclusions live in their own collection. + +use compliance_core::models::license::{self, LicenseConclusion}; +use compliance_core::models::SbomEntry; +use futures_util::TryStreamExt; +use mongodb::bson::doc; + +use crate::database::Database; + +/// The most conclusions one workspace keeps. Each is a person's decision, +/// so a workspace reaching this is far beyond normal use. +pub const MAX_CONCLUSIONS: i64 = 50_000; + +/// Every conclusion of the workspace, by package name. Empty when they +/// cannot be read: the components then show what the scan found. +pub async fn load(db: &Database) -> Vec { + let found = db + .license_conclusions() + .find(doc! {}) + .sort(doc! { "name": 1, "_id": 1 }) + .limit(MAX_CONCLUSIONS) + .await; + match found { + Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| { + tracing::warn!("license conclusions not read: {e}"); + Vec::new() + }), + Err(e) => { + tracing::warn!("license conclusions not read: {e}"); + Vec::new() + } + } +} + +/// Attach to `entries` the conclusions that apply to them. +pub async fn attach(db: &Database, entries: &mut [SbomEntry]) { + if entries.is_empty() { + return; + } + let conclusions = load(db).await; + license::apply(entries, &conclusions); +} diff --git a/compliance-agent/src/pipeline/sbom_quality.rs b/compliance-agent/src/pipeline/sbom_quality.rs index 59c2e1e..5a9201c 100644 --- a/compliance-agent/src/pipeline/sbom_quality.rs +++ b/compliance-agent/src/pipeline/sbom_quality.rs @@ -178,13 +178,15 @@ impl crate::pipeline::orchestrator::PipelineOrchestrator { if count == 0 || count > crate::api::handlers::sbom::MAX_EXPORT_COMPONENTS { return None; } - let entries: Vec = match self.db.sbom_entries().find(filter).await { + let mut entries: Vec = match self.db.sbom_entries().find(filter).await { Ok(cursor) => cursor.try_collect().await.ok()?, Err(e) => { tracing::warn!(target_id, "SBOM not scored: {e}"); return None; } }; + // Scored as exported: with the licences a person confirmed. + crate::license_conclusions::attach(&self.db, &mut entries).await; match score(&entries, subject).await { Ok(quality) => { tracing::info!( diff --git a/compliance-core/src/models/license.rs b/compliance-core/src/models/license.rs new file mode 100644 index 0000000..4925ad2 --- /dev/null +++ b/compliance-core/src/models/license.rs @@ -0,0 +1,479 @@ +//! Licences a workspace has confirmed for its components: where a scan found +//! no licence (or a wrong one), a person states the licence, its category, +//! the copyright and where it is written down. +//! +//! A conclusion is kept apart from the scanned components, which every scan +//! rewrites, and is merged into them when they are read or exported +//! ([`apply`]). It belongs to a package: to one version of it, or to every +//! version. In the exports it is the concluded licence (CycloneDX +//! `acknowledgement: concluded`, SPDX `licenseConcluded`); the licence the +//! scan detected stays the declared one. + +use chrono::{DateTime, NaiveDate, Utc}; +use serde::{Deserialize, Serialize}; + +use super::SbomEntry; +use crate::purl::Purl; +use crate::spdx_license; + +/// What a licence allows and asks for, roughly. A hint for reviewing +/// components, not legal advice. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LicenseCategory { + /// No rights reserved (CC0, Unlicense). + PublicDomain, + /// Use, change and ship freely; keep the notice (MIT, Apache-2.0, BSD). + Permissive, + /// Changes to the component itself stay open (LGPL, MPL, EPL). + WeakCopyleft, + /// Whatever is shipped with it stays open (GPL). + StrongCopyleft, + /// As strong copyleft, also when only offered over a network (AGPL). + NetworkCopyleft, + /// Bought or otherwise licensed under terms of its own. + Proprietary, + /// Written by the workspace's own company. + OwnCode, + /// Not known yet. + #[default] + Unclear, +} + +impl LicenseCategory { + /// Every category, in the order a picker lists them. + pub const ALL: [Self; 8] = [ + Self::Permissive, + Self::WeakCopyleft, + Self::StrongCopyleft, + Self::NetworkCopyleft, + Self::Proprietary, + Self::PublicDomain, + Self::OwnCode, + Self::Unclear, + ]; + + /// The stored name (`weak_copyleft`). + pub fn as_str(self) -> &'static str { + match self { + Self::PublicDomain => "public_domain", + Self::Permissive => "permissive", + Self::WeakCopyleft => "weak_copyleft", + Self::StrongCopyleft => "strong_copyleft", + Self::NetworkCopyleft => "network_copyleft", + Self::Proprietary => "proprietary", + Self::OwnCode => "own_code", + Self::Unclear => "unclear", + } + } + + /// The category of its stored name. + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.as_str() == name) + } + + /// Whether it asks for source code to be passed on (weak, strong or + /// network copyleft). + pub fn is_copyleft(self) -> bool { + matches!( + self, + Self::WeakCopyleft | Self::StrongCopyleft | Self::NetworkCopyleft + ) + } + + /// How much a licence of this category restricts, for combining the + /// terms of an expression: `OR` takes the least, `AND` the most. + pub(crate) fn restriction(self) -> u8 { + match self { + Self::PublicDomain => 0, + Self::Permissive | Self::OwnCode => 1, + Self::WeakCopyleft => 2, + Self::StrongCopyleft => 3, + Self::NetworkCopyleft => 4, + Self::Proprietary => 5, + Self::Unclear => 6, + } + } +} + +/// Where a component is used: shipped in the product, or only to build or +/// develop it. Copyleft obligations mostly bind what is shipped. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LicenseUsage { + /// Part of what is delivered (an app, a firmware image, a library in it). + Shipped, + /// Only used to build, test or develop. + BuildOnly, +} + +/// A licence a person confirmed for a package. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicenseConclusion { + /// [`conclusion_id`]: the package key and the version, or `*` for all. + #[serde(rename = "_id")] + pub id: String, + /// [`package_key`] of the package. + pub package_key: String, + pub name: String, + pub package_manager: String, + /// The version it was confirmed for; `None` for every version. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + /// An SPDX licence expression (`MIT`, `MIT OR Apache-2.0`), or a + /// `LicenseRef-` id for a licence SPDX does not list. + pub license: String, + /// The name of a `LicenseRef-` licence (`Pump Controls EULA`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub license_name: Option, + pub category: LicenseCategory, + /// Copyright lines (`© 2019 Example GmbH`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub copyright: Vec, + /// The licence text, where it is not an SPDX-listed licence. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub license_text: Option, + /// Where the licence text is published. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub license_url: Option, + /// Where the licence was found: a file in the repository, a contract, + /// a web page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub evidence: Option, + /// The contract or licence number of a bought licence. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub contract_ref: Option, + /// When a bought licence ends. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub valid_until: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub usage: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, + /// Who confirmed it (Keycloak user id), with the name the workspace reads. + pub by: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub by_name: Option, + /// BreakPilot support rather than one of the workspace's users. + #[serde(default)] + pub support: bool, + pub at: DateTime, +} + +/// The most text a field takes; a licence text may be longer. +pub const MAX_FIELD_CHARS: usize = 2_000; +/// The most a licence text takes. +pub const MAX_TEXT_CHARS: usize = 200_000; +/// The most copyright lines. +pub const MAX_COPYRIGHT_LINES: usize = 20; + +impl LicenseConclusion { + /// The licence as people read it: the name of a `LicenseRef-` licence, + /// otherwise the expression. + pub fn display(&self) -> &str { + match &self.license_name { + Some(name) if self.license.starts_with("LicenseRef-") => name, + _ => &self.license, + } + } + + /// Whether it is a licence SPDX does not list (`LicenseRef-`). + pub fn is_custom(&self) -> bool { + self.license.starts_with("LicenseRef-") + } + + /// Why it cannot be stored, in words; `Ok` when it can. + /// + /// # Errors + /// + /// The first problem found: no or an invalid licence, a custom licence + /// without a name, a field too long. + pub fn validate(&self) -> Result<(), String> { + let license = self.license.trim(); + if license.is_empty() { + return Err("licence missing".into()); + } + if self.is_custom() { + if !is_license_ref(license) { + return Err(format!("not a valid LicenseRef id: {license}")); + } + if self + .license_name + .as_deref() + .is_none_or(|n| n.trim().is_empty()) + { + return Err("a licence SPDX does not list needs a name".into()); + } + } else if !spdx_license::is_spdx_expression(license) { + return Err(format!("not an SPDX licence expression: {license}")); + } + if self.copyright.len() > MAX_COPYRIGHT_LINES { + return Err(format!("at most {MAX_COPYRIGHT_LINES} copyright lines")); + } + let short = [ + ("licence name", self.license_name.as_deref()), + ("licence URL", self.license_url.as_deref()), + ("evidence", self.evidence.as_deref()), + ("contract", self.contract_ref.as_deref()), + ("note", self.note.as_deref()), + ]; + for (field, value) in short { + if value.is_some_and(|v| v.chars().count() > MAX_FIELD_CHARS) { + return Err(format!("{field} longer than {MAX_FIELD_CHARS} characters")); + } + } + if self + .copyright + .iter() + .any(|c| c.chars().count() > MAX_FIELD_CHARS) + { + return Err(format!( + "copyright line longer than {MAX_FIELD_CHARS} characters" + )); + } + if self + .license_text + .as_deref() + .is_some_and(|t| t.chars().count() > MAX_TEXT_CHARS) + { + return Err(format!( + "licence text longer than {MAX_TEXT_CHARS} characters" + )); + } + if let Some(url) = self.license_url.as_deref() { + let lower = url.trim().to_ascii_lowercase(); + if !(lower.starts_with("https://") || lower.starts_with("http://")) { + return Err("the licence URL must start with https:// or http://".into()); + } + } + Ok(()) + } +} + +/// Whether `id` is a well-formed `LicenseRef-` id (letters, digits, `.`, `-`). +pub fn is_license_ref(id: &str) -> bool { + id.strip_prefix("LicenseRef-").is_some_and(|rest| { + !rest.is_empty() + && rest + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') + }) +} + +/// The `LicenseRef-` id of a licence SPDX does not list, made from its name: +/// `Pump Controls EULA` is `LicenseRef-Pump-Controls-EULA`. +pub fn license_ref(name: &str) -> String { + let mut id = String::from("LicenseRef-"); + let mut dash = false; + for c in name.trim().chars() { + if c.is_ascii_alphanumeric() || c == '.' { + id.push(c); + dash = false; + } else if !dash && id.len() > "LicenseRef-".len() { + id.push('-'); + dash = true; + } + } + // Only a dash after the name, never the one of `LicenseRef-`. + while id.len() > "LicenseRef-".len() && id.ends_with('-') { + id.pop(); + } + if id.len() == "LicenseRef-".len() { + id.push_str("custom"); + } + id +} + +/// The key of a package across its versions: its purl without version, +/// qualifiers and subpath (`pkg:npm/%40scope/name`), or +/// `:` without a purl. +pub fn package_key(name: &str, package_manager: &str, purl: Option<&str>) -> String { + if let Some(p) = purl.and_then(Purl::parse) { + return match &p.namespace { + Some(ns) => format!("pkg:{}/{}/{}", p.ty, ns, p.name), + None => format!("pkg:{}/{}", p.ty, p.name), + }; + } + format!("{}:{}", package_manager.trim(), name.trim()) +} + +/// The id of the conclusion for `key` at `version` (`*` for every version). +pub fn conclusion_id(key: &str, version: Option<&str>) -> String { + format!("{key}@{}", version.unwrap_or("*")) +} + +/// The conclusion that applies to `entry`: the one for its version, else +/// the one for every version of its package. +pub fn find<'a>( + conclusions: &'a [LicenseConclusion], + entry: &SbomEntry, +) -> Option<&'a LicenseConclusion> { + find_for( + conclusions, + &entry.name, + &entry.package_manager, + &entry.version, + entry.purl.as_deref(), + ) +} + +/// [`find`] for a component given by its fields. +pub fn find_for<'a>( + conclusions: &'a [LicenseConclusion], + name: &str, + package_manager: &str, + version: &str, + purl: Option<&str>, +) -> Option<&'a LicenseConclusion> { + let key = package_key(name, package_manager, purl); + let mut all_versions = None; + for c in conclusions.iter().filter(|c| c.package_key == key) { + match c.version.as_deref() { + Some(v) if v == version => return Some(c), + None => all_versions = Some(c), + Some(_) => {} + } + } + all_versions +} + +/// Attach to every entry the conclusion that applies to it. +pub fn apply(entries: &mut [SbomEntry], conclusions: &[LicenseConclusion]) { + if conclusions.is_empty() { + return; + } + for entry in entries.iter_mut() { + entry.concluded = find(conclusions, entry).cloned(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn conclusion(key: &str, version: Option<&str>, license: &str) -> LicenseConclusion { + LicenseConclusion { + id: conclusion_id(key, version), + package_key: key.into(), + name: "x".into(), + package_manager: "npm".into(), + version: version.map(String::from), + license: license.into(), + license_name: None, + category: LicenseCategory::Permissive, + copyright: Vec::new(), + license_text: None, + license_url: None, + evidence: None, + contract_ref: None, + valid_until: None, + usage: None, + note: None, + by: "u1".into(), + by_name: None, + support: false, + at: Utc::now(), + } + } + + fn entry(name: &str, version: &str, purl: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new("t".into(), name.into(), version.into(), "npm".into()); + e.purl = purl.map(String::from); + e + } + + #[test] + fn a_package_is_keyed_without_its_version() { + assert_eq!( + package_key("core", "npm", Some("pkg:npm/%40angular/core@17.0.1?x=y")), + "pkg:npm/@angular/core" + ); + // Encoded or not, the scope is the same package. + assert_eq!( + package_key("core", "npm", Some("pkg:npm/@angular/core@16.2.0")), + "pkg:npm/@angular/core" + ); + assert_eq!(package_key("Foo", "nuget", None), "nuget:Foo"); + assert_eq!(package_key("Foo", "nuget", Some("not a purl")), "nuget:Foo"); + } + + #[test] + fn the_version_conclusion_wins_over_the_package_one() { + let key = "pkg:npm/left-pad"; + let all = conclusion(key, None, "MIT"); + let one = conclusion(key, Some("1.3.0"), "ISC"); + let list = vec![all, one]; + let e = entry("left-pad", "1.3.0", Some("pkg:npm/left-pad@1.3.0")); + assert_eq!(find(&list, &e).map(|c| c.license.as_str()), Some("ISC")); + let other = entry("left-pad", "1.1.0", Some("pkg:npm/left-pad@1.1.0")); + assert_eq!(find(&list, &other).map(|c| c.license.as_str()), Some("MIT")); + let none = entry("right-pad", "1.0.0", Some("pkg:npm/right-pad@1.0.0")); + assert!(find(&list, &none).is_none()); + } + + #[test] + fn apply_attaches_and_leaves_others_alone() { + let list = vec![conclusion("pkg:npm/a", None, "MIT")]; + let mut entries = vec![ + entry("a", "1", Some("pkg:npm/a@1")), + entry("b", "1", Some("pkg:npm/b@1")), + ]; + apply(&mut entries, &list); + assert!(entries[0].concluded.is_some()); + assert!(entries[1].concluded.is_none()); + } + + #[test] + fn custom_licences_get_a_license_ref() { + assert_eq!( + license_ref("Pump Controls EULA"), + "LicenseRef-Pump-Controls-EULA" + ); + assert_eq!(license_ref(" ©© "), "LicenseRef-custom"); + assert_eq!(license_ref("v1.2 / 2020"), "LicenseRef-v1.2-2020"); + assert_eq!(license_ref("EULA!"), "LicenseRef-EULA"); + assert!(is_license_ref("LicenseRef-a.b-1")); + assert!(!is_license_ref("LicenseRef-")); + assert!(!is_license_ref("LicenseRef-a b")); + assert!(!is_license_ref("MIT")); + } + + #[test] + fn validation_names_the_problem() { + let ok = conclusion("k", None, "MIT OR Apache-2.0"); + assert!(ok.validate().is_ok()); + assert!(conclusion("k", None, "").validate().is_err()); + assert!(conclusion("k", None, "Custom thing").validate().is_err()); + let mut custom = conclusion("k", None, "LicenseRef-Pump"); + assert!(custom.validate().is_err(), "a custom licence needs a name"); + custom.license_name = Some("Pump EULA".into()); + assert!(custom.validate().is_ok()); + assert_eq!(custom.display(), "Pump EULA"); + custom.license_url = Some("ftp://x".into()); + assert!(custom.validate().is_err()); + custom.license_url = Some("https://example.com/eula".into()); + custom.copyright = vec!["c".into(); MAX_COPYRIGHT_LINES + 1]; + assert!(custom.validate().is_err()); + custom.copyright = vec!["x".repeat(MAX_FIELD_CHARS + 1)]; + assert!(custom.validate().is_err()); + custom.copyright.clear(); + custom.note = Some("x".repeat(MAX_FIELD_CHARS + 1)); + assert!(custom.validate().is_err()); + custom.note = None; + custom.license_text = Some("x".repeat(MAX_TEXT_CHARS + 1)); + assert!(custom.validate().is_err()); + custom.license = "LicenseRef-a b".into(); + custom.license_text = None; + assert!(custom.validate().is_err()); + } + + #[test] + fn categories_round_trip_their_names() { + for c in LicenseCategory::ALL { + assert_eq!(LicenseCategory::parse(c.as_str()), Some(c)); + } + assert_eq!(LicenseCategory::parse("nope"), None); + assert!(LicenseCategory::WeakCopyleft.is_copyleft()); + assert!(!LicenseCategory::Proprietary.is_copyleft()); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 4b85fd7..280ea83 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -8,6 +8,7 @@ pub mod finding; pub mod git_source; pub mod graph; pub mod issue; +pub mod license; pub mod mcp; pub mod mcp_token; pub mod notification; @@ -45,6 +46,7 @@ pub use graph::{ CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis, }; pub use issue::{IssueStatus, TrackerIssue, TrackerType}; +pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage}; pub use mcp::{McpServerConfig, McpServerStatus, McpTransport}; pub use mcp_token::{McpToken, McpTokenView}; pub use notification::{CveNotification, NotificationSeverity, NotificationStatus}; diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index 28ef6f2..db1c720 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -119,6 +119,11 @@ pub struct SbomEntry { /// stored before it was recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub in_image: Option, + /// The licence a person confirmed for the component + /// ([`super::license::LicenseConclusion`]). Never stored with it: a scan + /// rewrites the components, so it is attached when they are read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub concluded: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -135,6 +140,14 @@ pub struct ComponentHash { } impl SbomEntry { + /// The licence that counts: the confirmed one, else the detected one. + pub fn effective_license(&self) -> Option<&str> { + match &self.concluded { + Some(c) => Some(c.display()), + None => self.license.as_deref().filter(|l| !l.trim().is_empty()), + } + } + pub fn new(repo_id: String, name: String, version: String, package_manager: String) -> Self { let now = Utc::now(); Self { @@ -153,6 +166,7 @@ impl SbomEntry { manufacturer_url: None, cpe: None, in_image: None, + concluded: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index 4070c65..cd57dad 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -9,7 +9,8 @@ //! the suppliers declare them. use crate::models::{ - advisory_source, is_cve, ComponentHash, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, + advisory_source, is_cve, ComponentHash, LicenseConclusion, SbomEntry, YOCTO_RECIPE_MANAGER, + YOCTO_RECIPE_SOURCE, }; use crate::purl::Purl; use crate::spdx_license; @@ -32,8 +33,8 @@ pub fn product_ref(subject: &str) -> String { /// A license as CycloneDX writes it: an SPDX id, an SPDX expression /// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license /// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2). -/// It is the license the supplier declares (registry or lockfile metadata): -/// Prüfwerk has not concluded it. +/// It is the license the supplier declares (registry or lockfile metadata); +/// a license a person confirmed is written by [`concluded_choice`] instead. fn license_choice(license: &str) -> serde_json::Value { let license = spdx_license::normalise(license); if spdx_license::canonical_id(&license) == Some(&*license) { @@ -45,6 +46,76 @@ fn license_choice(license: &str) -> serde_json::Value { } } +/// The licence a person confirmed, as CycloneDX writes a concluded licence: +/// an SPDX id or expression, or a licence of its own by name with its text +/// and URL. CycloneDX takes either licences or one expression, never both, +/// so the declared licence is then kept as a property +/// ([`DECLARED_LICENSE_PROPERTY`]). +fn concluded_choice(c: &LicenseConclusion) -> serde_json::Value { + if c.is_custom() { + let mut license = serde_json::json!({ + "name": c.display(), + "acknowledgement": "concluded", + }); + if let Some(text) = &c.license_text { + license["text"] = serde_json::json!({ "contentType": "text/plain", "content": text }); + } + if let Some(url) = &c.license_url { + license["url"] = serde_json::Value::String(url.clone()); + } + serde_json::json!([{ "license": license }]) + } else if spdx_license::canonical_id(&c.license) == Some(c.license.as_str()) { + serde_json::json!([{ "license": { "id": c.license, "acknowledgement": "concluded" } }]) + } else { + serde_json::json!([{ "expression": c.license, "acknowledgement": "concluded" }]) + } +} + +/// The property holding the licence the scan detected, where a person +/// confirmed another one. +const DECLARED_LICENSE_PROPERTY: &str = "pruefwerk:license:declared"; + +/// The properties of a confirmed licence: its category, where the component +/// is used, a bought licence's contract and end, where it was found, and who +/// confirmed it when. +fn conclusion_properties(entry: &SbomEntry, c: &LicenseConclusion) -> Vec { + let mut props = vec![serde_json::json!({ + "name": "pruefwerk:license:category", + "value": c.category.as_str(), + })]; + let mut push = |name: &str, value: Option| { + if let Some(value) = value.filter(|v| !v.trim().is_empty()) { + props.push(serde_json::json!({ "name": name, "value": value })); + } + }; + push( + DECLARED_LICENSE_PROPERTY, + entry.license.clone().filter(|l| l.trim() != c.license), + ); + push( + "pruefwerk:license:usage", + c.usage.map(|u| match u { + crate::models::LicenseUsage::Shipped => "shipped".to_string(), + crate::models::LicenseUsage::BuildOnly => "build_only".to_string(), + }), + ); + push("pruefwerk:license:contract", c.contract_ref.clone()); + push( + "pruefwerk:license:valid_until", + c.valid_until.map(|d| d.to_string()), + ); + push("pruefwerk:license:evidence", c.evidence.clone()); + push( + "pruefwerk:license:concluded", + Some(format!( + "{} {}", + c.by_name.as_deref().unwrap_or(&c.by), + c.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) + )), + ); + props +} + /// The file a registry package is distributed as (`log4j-core-2.14.1.jar`), /// where its purl determines it. `None` for a package type whose file the /// purl does not name (PyPI wheel or sdist, Go modules) and without a version. @@ -182,8 +253,23 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec { None => comp["properties"] = serde_json::Value::Array(provenance), } } - if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) { - comp["licenses"] = license_choice(license); + match &e.concluded { + Some(c) => { + comp["licenses"] = concluded_choice(c); + if !c.copyright.is_empty() { + comp["copyright"] = serde_json::Value::String(c.copyright.join("\n")); + } + let props = conclusion_properties(e, c); + match comp["properties"].as_array_mut() { + Some(properties) => properties.extend(props), + None => comp["properties"] = serde_json::Value::Array(props), + } + } + None => { + if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) { + comp["licenses"] = license_choice(license); + } + } } if let Some(url) = &e.manufacturer_url { comp["manufacturer"] = serde_json::json!({ "url": [url] }); @@ -368,14 +454,34 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { /// An SPDX 2.3 document for `entries`, named after `subject`. pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { + // A `LicenseRef-` a package concludes must be defined in the document. + let mut extracted: Vec = Vec::new(); + let mut defined = std::collections::HashSet::new(); + for c in entries.iter().filter_map(|e| e.concluded.as_ref()) { + if c.is_custom() && defined.insert(c.license.clone()) { + let mut info = serde_json::json!({ + "licenseId": c.license, + "name": c.display(), + // SPDX requires a text; without one, where to find it. + "extractedText": c.license_text.clone().unwrap_or_else(|| { + c.license_url.clone().unwrap_or_else(|| "NOASSERTION".to_string()) + }), + }); + if let Some(url) = &c.license_url { + info["seeAlsos"] = serde_json::json!([url]); + } + extracted.push(info); + } + } let packages: Vec = entries .iter() .enumerate() .map(|(i, e)| { - // The license is what the supplier declares; nothing is - // concluded without a license review of our own. SPDX takes only - // an expression of listed ids; another license is NOASSERTION, - // its text kept as a comment. + // The declared license is what the supplier declares; a license + // is concluded only where a person of the workspace confirmed one + // (`concluded`). SPDX takes only an expression of listed ids; a + // declared license that is none is NOASSERTION, its text kept as + // a comment. let raw = e .license .as_deref() @@ -389,7 +495,8 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { "name": e.name, "versionInfo": e.version, "downloadLocation": "NOASSERTION", - "licenseConcluded": "NOASSERTION", + // Concluded only where a person confirmed the licence. + "licenseConcluded": e.concluded.as_ref().map_or("NOASSERTION", |c| c.license.as_str()), "licenseDeclared": license.as_deref().unwrap_or("NOASSERTION"), "externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({ "referenceCategory": "PACKAGE-MANAGER", @@ -400,6 +507,23 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { if let (Some(raw), None) = (raw, &license) { package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}")); } + if let Some(c) = &e.concluded { + if !c.copyright.is_empty() { + package["copyrightText"] = serde_json::Value::String(c.copyright.join("\n")); + } + let by = c.by_name.as_deref().unwrap_or(&c.by); + let note = format!( + "Concluded by {by} on {} ({})", + c.at.format("%Y-%m-%d"), + c.category.as_str() + ); + package["licenseComments"] = serde_json::Value::String( + match package["licenseComments"].as_str() { + Some(declared) => format!("{declared}. {note}"), + None => note, + }, + ); + } if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) { refs.push(serde_json::json!({ "referenceCategory": "SECURITY", @@ -414,14 +538,18 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { }) .collect(); - serde_json::json!({ + let mut doc = serde_json::json!({ "spdxVersion": "SPDX-2.3", "dataLicense": "CC0-1.0", "SPDXID": "SPDXRef-DOCUMENT", "name": format!("sbom-{subject}"), "documentNamespace": format!("https://compliance-scanner/sbom/{subject}"), "packages": packages, - }) + }); + if !extracted.is_empty() { + doc["hasExtractedLicensingInfos"] = serde_json::Value::Array(extracted); + } + doc } #[cfg(test)] @@ -558,4 +686,111 @@ mod tests { ); assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE); } + + fn concluded(license: &str, name: Option<&str>) -> LicenseConclusion { + use crate::models::license::{conclusion_id, package_key}; + let key = package_key("pump-sdk", "nuget", None); + LicenseConclusion { + id: conclusion_id(&key, None), + package_key: key, + name: "pump-sdk".into(), + package_manager: "nuget".into(), + version: None, + license: license.into(), + license_name: name.map(String::from), + category: crate::models::LicenseCategory::Proprietary, + copyright: vec!["© 2019 Example GmbH".into()], + license_text: Some("All rights reserved.".into()), + license_url: None, + evidence: Some("contract 4711".into()), + contract_ref: Some("4711".into()), + valid_until: chrono::NaiveDate::from_ymd_opt(2027, 12, 31), + usage: Some(crate::models::LicenseUsage::Shipped), + note: None, + by: "u1".into(), + by_name: Some("Erika Muster".into()), + support: false, + at: chrono::Utc::now(), + } + } + + #[test] + fn a_confirmed_custom_licence_is_concluded_and_defined() { + let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "3.1".into(), "nuget".into()); + e.license = Some("LicenseRef-file".into()); + e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA"))); + let cdx = cyclonedx(std::slice::from_ref(&e), "t"); + let comp = &cdx["components"][0]; + assert_eq!(comp["licenses"][0]["license"]["name"], "Pump EULA"); + assert_eq!( + comp["licenses"][0]["license"]["acknowledgement"], + "concluded" + ); + assert_eq!( + comp["licenses"][0]["license"]["text"]["content"], + "All rights reserved." + ); + assert_eq!(comp["copyright"], "© 2019 Example GmbH"); + let props = comp["properties"].as_array().unwrap(); + let prop = |n: &str| { + props + .iter() + .find(|p| p["name"] == n) + .map(|p| p["value"].clone()) + }; + assert_eq!( + prop("pruefwerk:license:category"), + Some("proprietary".into()) + ); + assert_eq!( + prop(DECLARED_LICENSE_PROPERTY), + Some("LicenseRef-file".into()) + ); + assert_eq!( + prop("pruefwerk:license:valid_until"), + Some("2027-12-31".into()) + ); + assert_eq!(prop("pruefwerk:license:usage"), Some("shipped".into())); + + let spdx = spdx(&[e], "t"); + let package = &spdx["packages"][0]; + assert_eq!(package["licenseConcluded"], "LicenseRef-Pump-EULA"); + assert_eq!(package["copyrightText"], "© 2019 Example GmbH"); + assert!(package["licenseComments"] + .as_str() + .unwrap() + .contains("Concluded by Erika Muster")); + let info = &spdx["hasExtractedLicensingInfos"][0]; + assert_eq!(info["licenseId"], "LicenseRef-Pump-EULA"); + assert_eq!(info["extractedText"], "All rights reserved."); + } + + #[test] + fn a_confirmed_spdx_licence_replaces_the_declared_one() { + let mut one = SbomEntry::new("t".into(), "a".into(), "1".into(), "npm".into()); + one.concluded = Some(concluded("MIT", None)); + let mut two = SbomEntry::new("t".into(), "b".into(), "1".into(), "npm".into()); + two.license = Some("MIT".into()); + two.concluded = Some(concluded("MIT OR Apache-2.0", None)); + let cdx = cyclonedx(&[one.clone(), two.clone()], "t"); + assert_eq!(cdx["components"][0]["licenses"][0]["license"]["id"], "MIT"); + assert_eq!( + cdx["components"][0]["licenses"][0]["license"]["acknowledgement"], + "concluded" + ); + assert_eq!( + cdx["components"][1]["licenses"][0]["expression"], + "MIT OR Apache-2.0" + ); + assert_eq!( + cdx["components"][1]["licenses"].as_array().unwrap().len(), + 1 + ); + let spdx = spdx(&[one, two], "t"); + assert_eq!(spdx["packages"][0]["licenseConcluded"], "MIT"); + assert_eq!(spdx["packages"][0]["licenseDeclared"], "NOASSERTION"); + assert_eq!(spdx["packages"][1]["licenseConcluded"], "MIT OR Apache-2.0"); + assert_eq!(spdx["packages"][1]["licenseDeclared"], "MIT"); + assert!(spdx.get("hasExtractedLicensingInfos").is_none()); + } } diff --git a/compliance-core/src/spdx_license.rs b/compliance-core/src/spdx_license.rs index 0d9da01..c955439 100644 --- a/compliance-core/src/spdx_license.rs +++ b/compliance-core/src/spdx_license.rs @@ -115,6 +115,136 @@ pub fn is_copyleft(license: &str) -> bool { by_term || COPYLEFT.iter().any(|c| upper.contains(c)) } +/// Families (SPDX ids without `-only`/`-or-later`/`+`, lowercase prefixes) +/// and their category. A prefix covers its versions (`gpl-` is GPL-1.0 to +/// GPL-3.0); `lgpl-` and `agpl-` are listed before `gpl-` is tried. +const FAMILIES: &[(&str, crate::models::LicenseCategory)] = { + use crate::models::LicenseCategory::{ + NetworkCopyleft, Permissive, PublicDomain, StrongCopyleft, WeakCopyleft, + }; + &[ + ("agpl-", NetworkCopyleft), + ("sspl-", NetworkCopyleft), + ("lgpl-", WeakCopyleft), + ("mpl-", WeakCopyleft), + ("epl-", WeakCopyleft), + ("cddl-", WeakCopyleft), + ("cpl-", WeakCopyleft), + ("ms-rl", WeakCopyleft), + ("ofl-", WeakCopyleft), + ("gpl-", StrongCopyleft), + ("eupl-", StrongCopyleft), + ("osl-", StrongCopyleft), + ("cc-by-sa-", StrongCopyleft), + ("cc0-", PublicDomain), + ("unlicense", PublicDomain), + ("mit", Permissive), + ("apache-", Permissive), + ("bsd-", Permissive), + ("0bsd", Permissive), + ("isc", Permissive), + ("zlib", Permissive), + ("bsl-1.0", Permissive), + ("psf-", Permissive), + ("python-", Permissive), + ("upl-", Permissive), + ("wtfpl", Permissive), + ("artistic-2.0", Permissive), + ("ms-pl", Permissive), + ("x11", Permissive), + ("unicode-", Permissive), + ("curl", Permissive), + ("ncsa", Permissive), + ("postgresql", Permissive), + ("openssl", Permissive), + ("ssleay", Permissive), + ("blueoak-", Permissive), + ("cc-by-4.0", Permissive), + ("cc-by-3.0", Permissive), + ("icu", Permissive), + ("libpng", Permissive), + ("ijg", Permissive), + ("ftl", Permissive), + ("bzip2-", Permissive), + ("hpnd", Permissive), + ] +}; + +/// The category of one SPDX licence id; `Unclear` for an id not listed in +/// [`FAMILIES`] and for a `LicenseRef-`. +fn term_category(id: &str) -> crate::models::LicenseCategory { + let base = id.strip_suffix('+').unwrap_or(id); + let base = base + .strip_suffix("-only") + .or_else(|| base.strip_suffix("-or-later")) + .unwrap_or(base) + .to_ascii_lowercase(); + FAMILIES + .iter() + .find(|(prefix, _)| base == prefix.trim_end_matches('-') || base.starts_with(prefix)) + .map_or(crate::models::LicenseCategory::Unclear, |(_, c)| *c) +} + +/// The category of a licence (an SPDX id or expression, a name or URL that +/// [`normalise`] knows). The terms of an `OR` leave the choice, so the least +/// restrictive counts; the terms of an `AND` all apply, so the most +/// restrictive counts. An exception after `WITH` does not change it. A +/// licence this module does not know is `Unclear`. +/// +/// # Examples +/// +/// ``` +/// use compliance_core::models::LicenseCategory; +/// use compliance_core::spdx_license::category; +/// +/// assert_eq!(category("Apache-2.0"), LicenseCategory::Permissive); +/// assert_eq!(category("LGPL-2.1-or-later"), LicenseCategory::WeakCopyleft); +/// assert_eq!(category("MIT OR GPL-3.0-only"), LicenseCategory::Permissive); +/// assert_eq!(category("Custom Pump License"), LicenseCategory::Unclear); +/// ``` +pub fn category(license: &str) -> crate::models::LicenseCategory { + use crate::models::LicenseCategory; + let spdx = normalise(license); + let tokens: Vec<&str> = spdx + .split(|c: char| c.is_whitespace() || c == '(' || c == ')') + .filter(|t| !t.is_empty()) + .collect(); + // Only an expression of SPDX ids (and `LicenseRef-`s) is read by its + // terms: the words of a free-text name (`Mitsubishi EULA`) are no ids. + let readable = tokens.iter().all(|t| { + OPERATORS.contains(t) + || t.starts_with("LicenseRef-") + || canonical_id(t.strip_suffix('+').unwrap_or(t)).is_some() + }); + if !readable { + return LicenseCategory::Unclear; + } + let mut terms = Vec::new(); + let mut after_with = false; + for token in &tokens { + match *token { + "WITH" => after_with = true, + "AND" | "OR" => after_with = false, + id if !after_with => terms.push(term_category(id)), + _ => {} + } + } + let by_restriction = |c: &LicenseCategory| c.restriction(); + let chosen = if tokens.contains(&"AND") { + terms.iter().copied().max_by_key(by_restriction) + } else { + // An `OR`: a term that is not known does not stop a known one from + // being chosen. + terms + .iter() + .copied() + .filter(|c| *c != LicenseCategory::Unclear) + .min_by_key(by_restriction) + .or(terms.first().copied()) + }; + chosen.unwrap_or(LicenseCategory::Unclear) +} + /// Whether `text` joins terms with an SPDX operator (`MIT OR Apache-2.0`), /// as an expression does. pub fn has_operator(text: &str) -> bool { @@ -520,6 +650,39 @@ mod tests { assert_eq!(spdx_of_name("Permit to Limit License"), None); } + #[test] + fn licences_fall_into_categories() { + use crate::models::LicenseCategory::*; + for (license, expected) in [ + ("MIT", Permissive), + ("Apache License, Version 2.0", Permissive), + ("BSD-3-Clause", Permissive), + ("0BSD", Permissive), + ("LGPL-2.1-only", WeakCopyleft), + ("GNU Lesser General Public License v2.1", WeakCopyleft), + ("MPL-2.0", WeakCopyleft), + ("EPL-2.0", WeakCopyleft), + ("GPL-2.0-only", StrongCopyleft), + ("GPL-2.0+", StrongCopyleft), + ("GPL-2.0-only WITH Classpath-exception-2.0", StrongCopyleft), + ("AGPL-3.0-or-later", NetworkCopyleft), + ("CC0-1.0", PublicDomain), + ("Unlicense", PublicDomain), + ("MIT OR GPL-3.0-only", Permissive), + ("(MIT OR Apache-2.0)", Permissive), + ("MIT AND GPL-2.0-only", StrongCopyleft), + ("LicenseRef-Pump OR MIT", Permissive), + ("LicenseRef-Pump", Unclear), + ("MIT AND LicenseRef-Pump", Unclear), + ("Custom Pump License", Unclear), + ("Mitsubishi EULA", Unclear), + ("SSPL-1.0", NetworkCopyleft), + ("", Unclear), + ] { + assert_eq!(category(license), expected, "{license}"); + } + } + #[test] fn spdx_expressions_are_recognised() { assert!(is_spdx_expression("MIT")); diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index a06c010..b7d8c44 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5768,3 +5768,131 @@ input[type="file"] { color: var(--text-secondary); font-size: 13px; } + +/* ── Licence review: confirmed licences (proprietary, unclear), the editor ── */ +.license-proprietary { + background: var(--info-bg, var(--bg-elevated)); + color: var(--info, var(--text-primary)); + border: 1px solid var(--border-bright); +} + +.license-unclear { + background: var(--bg-elevated); + color: var(--text-secondary); + border: 1px dashed var(--border-bright); +} + +.license-bar.license-weak-copyleft { + background: var(--warning); + border: none; +} + +.license-bar.license-proprietary { + background: var(--info, var(--text-secondary)); + border: none; +} + +.license-bar.license-unclear { + background: var(--text-tertiary); + border: none; +} + +.license-confirmed { + font-size: 11px; +} + +.license-edit-btn { + padding: 1px 8px; + font-size: 12px; +} + +.license-select-col { + width: 32px; + text-align: center; +} + +.license-selection-bar { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 10px; + padding: 8px 12px; + background: var(--bg-elevated); + border: 1px solid var(--border-bright); + border-radius: var(--radius-sm); + font-size: 13px; +} + +.license-open-card { + display: flex; + align-items: center; + gap: 14px; + flex-wrap: wrap; +} + +.license-confirmed-count { + font-size: 12px; + color: var(--text-tertiary); +} + +.modal-dialog.license-editor { + max-width: 620px; + max-height: calc(100vh - 48px); + overflow-y: auto; +} + +.license-kind { + display: flex; + gap: 18px; + flex-wrap: wrap; + margin-bottom: 12px; + font-size: 13px; +} + +.license-form { + display: flex; + flex-direction: column; + gap: 10px; +} + +.license-form label { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 12.5px; + color: var(--text-secondary); +} + +.license-form label.license-check { + flex-direction: row; + align-items: center; + gap: 6px; +} + +.license-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; +} + +.license-derived { + font-size: 12.5px; + color: var(--text-secondary); +} + +.license-disclaimer { + font-size: 12px !important; + color: var(--text-tertiary) !important; + margin-top: 12px; +} + +.license-withdraw { + margin-right: auto; + color: var(--danger); +} + +@media (max-width: 640px) { + .license-row { + grid-template-columns: 1fr; + } +} diff --git a/compliance-dashboard/src/components/license_editor.rs b/compliance-dashboard/src/components/license_editor.rs new file mode 100644 index 0000000..de9585b --- /dev/null +++ b/compliance-dashboard/src/components/license_editor.rs @@ -0,0 +1,444 @@ +//! The dialog to confirm the licence of one or more components: an SPDX +//! licence (its category follows from it) or one of the workspace's own, +//! with copyright, licence text, where it was found, a bought licence's +//! contract and end, and where the component is used. Saved for the listed +//! versions, or for every version of the packages. + +use dioxus::prelude::*; + +use compliance_core::models::{LicenseCategory, LicenseConclusion, LicenseUsage}; +use compliance_core::spdx_license; + +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::license_edit as tx; +use crate::i18n::{use_lang, Lang}; +use crate::infrastructure::sbom::{ + save_license_conclusion, withdraw_license_conclusion, LicenseDraft, LicenseTarget, +}; + +/// SPDX licences offered while typing; any other SPDX id or expression is +/// accepted too. +const COMMON_SPDX: [&str; 24] = [ + "MIT", + "Apache-2.0", + "BSD-3-Clause", + "BSD-2-Clause", + "ISC", + "Zlib", + "BSL-1.0", + "0BSD", + "Unlicense", + "CC0-1.0", + "MPL-2.0", + "EPL-2.0", + "LGPL-2.1-only", + "LGPL-2.1-or-later", + "LGPL-3.0-only", + "LGPL-3.0-or-later", + "GPL-2.0-only", + "GPL-2.0-or-later", + "GPL-3.0-only", + "GPL-3.0-or-later", + "AGPL-3.0-only", + "EUPL-1.2", + "MS-PL", + "Python-2.0", +]; + +/// Trimmed, `None` when empty. +fn filled(value: String) -> Option { + let value = value.trim().to_string(); + (!value.is_empty()).then_some(value) +} + +/// The badge class of a category, as the SBOM list colours licences. +pub fn category_class(category: LicenseCategory) -> &'static str { + match category { + LicenseCategory::PublicDomain | LicenseCategory::Permissive | LicenseCategory::OwnCode => { + "license-permissive" + } + LicenseCategory::WeakCopyleft => "license-weak-copyleft", + LicenseCategory::StrongCopyleft | LicenseCategory::NetworkCopyleft => "license-copyleft", + LicenseCategory::Proprietary => "license-proprietary", + LicenseCategory::Unclear => "license-unclear", + } +} + +/// "Bestätigt von Erika Muster am 2026-10-15". +pub fn confirmed_title(c: &LicenseConclusion, lang: Lang) -> String { + tx::CONFIRMED_BY + .get(lang) + .replace("{by}", c.by_name.as_deref().unwrap_or(&c.by)) + .replace("{at}", &c.at.format("%Y-%m-%d").to_string()) +} + +#[component] +pub fn LicenseEditor( + /// The components to confirm a licence for. + components: Vec, + /// The confirmation to start from (editing one component), if any. + existing: Option, + /// Called with `true` when something was saved or withdrawn. + on_close: EventHandler, +) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let start = existing.clone(); + let mut custom = use_signal(|| start.as_ref().is_some_and(LicenseConclusion::is_custom)); + let mut spdx = use_signal(|| { + start + .as_ref() + .filter(|c| !c.is_custom()) + .map(|c| c.license.clone()) + .unwrap_or_default() + }); + let mut name = use_signal(|| { + start + .as_ref() + .and_then(|c| c.license_name.clone()) + .unwrap_or_default() + }); + let mut category = use_signal(|| { + start + .as_ref() + .map_or(LicenseCategory::Proprietary, |c| c.category) + }); + let mut copyright = use_signal(|| { + start + .as_ref() + .map(|c| c.copyright.join("\n")) + .unwrap_or_default() + }); + let mut text = use_signal(|| { + start + .as_ref() + .and_then(|c| c.license_text.clone()) + .unwrap_or_default() + }); + let mut url = use_signal(|| { + start + .as_ref() + .and_then(|c| c.license_url.clone()) + .unwrap_or_default() + }); + let mut evidence = use_signal(|| { + start + .as_ref() + .and_then(|c| c.evidence.clone()) + .unwrap_or_default() + }); + let mut contract = use_signal(|| { + start + .as_ref() + .and_then(|c| c.contract_ref.clone()) + .unwrap_or_default() + }); + let mut valid_until = use_signal(|| { + start + .as_ref() + .and_then(|c| c.valid_until) + .map(|d| d.to_string()) + .unwrap_or_default() + }); + let mut usage = use_signal(|| start.as_ref().and_then(|c| c.usage)); + let mut note = use_signal(|| { + start + .as_ref() + .and_then(|c| c.note.clone()) + .unwrap_or_default() + }); + let mut all_versions = use_signal(|| start.as_ref().is_some_and(|c| c.version.is_none())); + let mut busy = use_signal(|| false); + + // The SPDX licence as typed, read the way the agent will read it. + let spdx_now = spdx(); + let normalised = spdx_license::normalise(&spdx_now).into_owned(); + let spdx_valid = spdx_license::is_spdx_expression(&normalised); + let derived = spdx_license::category(&normalised); + let can_save = !busy() + && if custom() { + !name().trim().is_empty() + } else { + spdx_valid + }; + let heading = if components.len() == 1 { + format!( + "{} · {} {}", + tx::TITLE.get(lang), + components[0].name, + components[0].version + ) + } else { + tx::TITLE_MANY + .get(lang) + .replace("{n}", &components.len().to_string()) + }; + + let targets = components.clone(); + let save = move |_: Event| { + let draft = LicenseDraft { + components: targets.clone(), + all_versions: all_versions(), + license: (!custom()).then(|| spdx().trim().to_string()), + license_name: custom().then(|| name().trim().to_string()), + // For an SPDX licence the agent derives it; sent for one SPDX + // gives none for. + category: Some(category()), + copyright: copyright() + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(String::from) + .collect(), + license_text: filled(text()), + license_url: filled(url()), + evidence: filled(evidence()), + contract_ref: filled(contract()), + valid_until: filled(valid_until()), + usage: usage(), + note: filled(note()), + }; + busy.set(true); + spawn(async move { + match save_license_conclusion(draft).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::SAVED.get(lang).to_string()); + on_close.call(true); + } + Err(e) => { + toasts.push( + ToastType::Error, + format!("{}: {e}", tx::SAVE_FAILED.get(lang)), + ); + } + } + busy.set(false); + }); + }; + + rsx! { + div { class: "modal-overlay", + onclick: move |_| if !busy() { on_close.call(false) }, + div { class: "modal-dialog license-editor", + onclick: move |e| e.stop_propagation(), + h3 { "{heading}" } + + div { class: "license-kind", + label { + input { + r#type: "radio", + name: "license-kind", + checked: !custom(), + onchange: move |_| custom.set(false), + } + " {tx::KIND_SPDX.get(lang)}" + } + label { + input { + r#type: "radio", + name: "license-kind", + checked: custom(), + onchange: move |_| custom.set(true), + } + " {tx::KIND_CUSTOM.get(lang)}" + } + } + + div { class: "form-fields license-form", + if custom() { + label { {tx::NAME_LABEL.get(lang)} + input { + value: "{name}", + placeholder: tx::NAME_HINT.get(lang), + maxlength: "2000", + oninput: move |e| name.set(e.value()), + } + } + label { {tx::CATEGORY_LABEL.get(lang)} + select { + onchange: move |e| { + if let Some(c) = LicenseCategory::parse(&e.value()) { + category.set(c); + } + }, + for c in LicenseCategory::ALL { + option { + value: c.as_str(), + selected: category() == c, + {tx::category(c).get(lang)} + } + } + } + } + } else { + label { {tx::SPDX_LABEL.get(lang)} + input { + value: "{spdx}", + list: "spdx-licenses", + placeholder: tx::SPDX_HINT.get(lang), + oninput: move |e| spdx.set(e.value()), + } + datalist { id: "spdx-licenses", + for id in COMMON_SPDX { + option { value: id } + } + } + } + if !spdx_now.trim().is_empty() && !spdx_valid { + p { class: "modal-warning", {tx::SPDX_INVALID.get(lang)} } + } + if spdx_valid { + if derived == LicenseCategory::Unclear { + label { {tx::CATEGORY_LABEL.get(lang)} + select { + onchange: move |e| { + if let Some(c) = LicenseCategory::parse(&e.value()) { + category.set(c); + } + }, + for c in LicenseCategory::ALL { + option { + value: c.as_str(), + selected: category() == c, + {tx::category(c).get(lang)} + } + } + } + } + } else { + p { class: "license-derived", + "{tx::CATEGORY_LABEL.get(lang)}: " + span { class: "sbom-license-badge {category_class(derived)}", + {tx::category(derived).get(lang)} + } + " · {tx::CATEGORY_AUTO.get(lang)}" + } + } + } + } + + label { {tx::COPYRIGHT_LABEL.get(lang)} + textarea { + rows: "2", + value: "{copyright}", + placeholder: tx::COPYRIGHT_HINT.get(lang), + oninput: move |e| copyright.set(e.value()), + } + } + if custom() { + label { {tx::TEXT_LABEL.get(lang)} + textarea { + rows: "4", + value: "{text}", + oninput: move |e| text.set(e.value()), + } + } + } + label { {tx::URL_LABEL.get(lang)} + input { + r#type: "url", + value: "{url}", + placeholder: "https://", + oninput: move |e| url.set(e.value()), + } + } + label { {tx::EVIDENCE_LABEL.get(lang)} + input { + value: "{evidence}", + placeholder: tx::EVIDENCE_HINT.get(lang), + maxlength: "2000", + oninput: move |e| evidence.set(e.value()), + } + } + if custom() && matches!(category(), LicenseCategory::Proprietary) { + div { class: "license-row", + label { {tx::CONTRACT_LABEL.get(lang)} + input { + value: "{contract}", + maxlength: "2000", + oninput: move |e| contract.set(e.value()), + } + } + label { {tx::VALID_UNTIL_LABEL.get(lang)} + input { + r#type: "date", + value: "{valid_until}", + oninput: move |e| valid_until.set(e.value()), + } + } + } + } + label { {tx::USAGE_LABEL.get(lang)} + select { + onchange: move |e| usage.set(match e.value().as_str() { + "shipped" => Some(LicenseUsage::Shipped), + "build_only" => Some(LicenseUsage::BuildOnly), + _ => None, + }), + option { value: "", selected: usage().is_none(), {tx::USAGE_UNSET.get(lang)} } + option { value: "shipped", selected: usage() == Some(LicenseUsage::Shipped), {tx::USAGE_SHIPPED.get(lang)} } + option { value: "build_only", selected: usage() == Some(LicenseUsage::BuildOnly), {tx::USAGE_BUILD.get(lang)} } + } + } + label { {tx::NOTE_LABEL.get(lang)} + textarea { + rows: "2", + value: "{note}", + maxlength: "2000", + oninput: move |e| note.set(e.value()), + } + } + label { class: "license-check", + input { + r#type: "checkbox", + checked: all_versions(), + onchange: move |e| all_versions.set(e.checked()), + } + " {tx::ALL_VERSIONS.get(lang)}" + } + } + + p { class: "license-disclaimer", {tx::DISCLAIMER.get(lang)} } + + div { class: "modal-actions", + if let Some(c) = existing.clone() { + button { + class: "btn btn-ghost license-withdraw", + disabled: busy(), + onclick: move |_| { + let id = c.id.clone(); + busy.set(true); + spawn(async move { + match withdraw_license_conclusion(id).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::WITHDRAWN.get(lang).to_string()); + on_close.call(true); + } + Err(e) => toasts.push( + ToastType::Error, + format!("{}: {e}", tx::SAVE_FAILED.get(lang)), + ), + } + busy.set(false); + }); + }, + {tx::WITHDRAW.get(lang)} + } + } + button { + class: "btn btn-secondary", + disabled: busy(), + onclick: move |_| on_close.call(false), + {tx::CANCEL.get(lang)} + } + button { + class: "btn btn-primary", + disabled: !can_save, + onclick: save, + {tx::SAVE.get(lang)} + } + } + } + } + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 3bd88e1..3fd26f0 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -11,6 +11,7 @@ pub mod file_tree; pub mod help_chat; pub mod lang_toggle; pub mod layer_pins; +pub mod license_editor; pub mod manual_findings; pub mod markdown; pub mod no_access; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index a1f732c..65f5215 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -3780,3 +3780,228 @@ pub mod webhooks { en: "Failed", }; } + +/// Confirming the licence of a component (licence review). +pub mod license_edit { + use super::Text; + + pub const TITLE: Text = Text { + de: "Lizenz bestätigen", + en: "Confirm licence", + }; + pub const TITLE_MANY: Text = Text { + de: "Lizenz für {n} Komponenten bestätigen", + en: "Confirm licence for {n} components", + }; + pub const EDIT: Text = Text { + de: "Bearbeiten", + en: "Edit", + }; + pub const EDIT_SELECTED: Text = Text { + de: "Lizenz bearbeiten", + en: "Edit licence", + }; + pub const CLEAR_SELECTION: Text = Text { + de: "Auswahl aufheben", + en: "Clear selection", + }; + pub const SELECT_ROW: Text = Text { + de: "Für die Lizenzbearbeitung auswählen", + en: "Select for licence editing", + }; + pub const KIND_SPDX: Text = Text { + de: "SPDX-Lizenz", + en: "SPDX licence", + }; + pub const KIND_CUSTOM: Text = Text { + de: "Eigene oder kommerzielle Lizenz", + en: "Own or commercial licence", + }; + pub const SPDX_LABEL: Text = Text { + de: "Lizenz (SPDX-ID oder Ausdruck)", + en: "Licence (SPDX id or expression)", + }; + pub const SPDX_HINT: Text = Text { + de: "z. B. MIT, Apache-2.0 oder „MIT OR Apache-2.0“", + en: "e.g. MIT, Apache-2.0 or “MIT OR Apache-2.0”", + }; + pub const SPDX_INVALID: Text = Text { + de: "Keine gültige SPDX-Lizenz. Für eine nicht gelistete Lizenz „Eigene oder kommerzielle Lizenz“ wählen.", + en: "Not a valid SPDX licence. For a licence SPDX does not list, choose “Own or commercial licence”.", + }; + pub const NAME_LABEL: Text = Text { + de: "Name der Lizenz", + en: "Licence name", + }; + pub const NAME_HINT: Text = Text { + de: "z. B. „Lizenzvertrag Hersteller X“", + en: "e.g. “Supplier X licence agreement”", + }; + pub const CATEGORY_LABEL: Text = Text { + de: "Kategorie", + en: "Category", + }; + pub const CATEGORY_AUTO: Text = Text { + de: "Ergibt sich aus der SPDX-Lizenz", + en: "Follows from the SPDX licence", + }; + pub const COPYRIGHT_LABEL: Text = Text { + de: "Copyright (eine Zeile je Inhaber)", + en: "Copyright (one line per holder)", + }; + pub const COPYRIGHT_HINT: Text = Text { + de: "z. B. © 2019 Beispiel GmbH", + en: "e.g. © 2019 Example GmbH", + }; + pub const TEXT_LABEL: Text = Text { + de: "Lizenztext (optional)", + en: "Licence text (optional)", + }; + pub const URL_LABEL: Text = Text { + de: "Link zum Lizenztext (optional)", + en: "Link to the licence text (optional)", + }; + pub const EVIDENCE_LABEL: Text = Text { + de: "Fundstelle", + en: "Where it was found", + }; + pub const EVIDENCE_HINT: Text = Text { + de: "z. B. Datei im Repository, Vertrag, Webseite", + en: "e.g. a file in the repository, a contract, a web page", + }; + pub const CONTRACT_LABEL: Text = Text { + de: "Vertrags- oder Lizenznummer", + en: "Contract or licence number", + }; + pub const VALID_UNTIL_LABEL: Text = Text { + de: "Gültig bis", + en: "Valid until", + }; + pub const USAGE_LABEL: Text = Text { + de: "Verwendung", + en: "Use", + }; + pub const USAGE_UNSET: Text = Text { + de: "Nicht angegeben", + en: "Not stated", + }; + pub const USAGE_SHIPPED: Text = Text { + de: "Wird mit dem Produkt ausgeliefert", + en: "Shipped with the product", + }; + pub const USAGE_BUILD: Text = Text { + de: "Nur für Build oder Entwicklung", + en: "Only for building or development", + }; + pub const ALL_VERSIONS: Text = Text { + de: "Für alle Versionen dieses Pakets", + en: "For every version of this package", + }; + pub const NOTE_LABEL: Text = Text { + de: "Notiz", + en: "Note", + }; + pub const DISCLAIMER: Text = Text { + de: "Kategorie und Pflichten sind Hinweise, keine Rechtsberatung.", + en: "Categories and obligations are guidance, not legal advice.", + }; + pub const SAVE: Text = Text { + de: "Speichern", + en: "Save", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + pub const WITHDRAW: Text = Text { + de: "Bestätigung zurücknehmen", + en: "Withdraw confirmation", + }; + pub const SAVED: Text = Text { + de: "Lizenz bestätigt", + en: "Licence confirmed", + }; + pub const WITHDRAWN: Text = Text { + de: "Bestätigung zurückgenommen", + en: "Confirmation withdrawn", + }; + pub const SAVE_FAILED: Text = Text { + de: "Speichern fehlgeschlagen", + en: "Saving failed", + }; + pub const CONFIRMED: Text = Text { + de: "bestätigt", + en: "confirmed", + }; + pub const CONFIRMED_BY: Text = Text { + de: "Bestätigt von {by} am {at}", + en: "Confirmed by {by} on {at}", + }; + pub const DETECTED: Text = Text { + de: "Erkannt", + en: "Detected", + }; + pub const OPEN_FILTER: Text = Text { + de: "Lizenz offen (unbekannt)", + en: "Licence open (unknown)", + }; + pub const OPEN_COUNT: Text = Text { + de: "{n} Komponenten ohne bekannte Lizenz", + en: "{n} components without a known licence", + }; + pub const OPEN_SHOW: Text = Text { + de: "Anzeigen und bearbeiten", + en: "Show and edit", + }; + pub const CONFIRMED_COUNT: Text = Text { + de: "{n} bestätigt", + en: "{n} confirmed", + }; + pub const CAT_PUBLIC_DOMAIN: Text = Text { + de: "Gemeinfrei", + en: "Public domain", + }; + pub const CAT_PERMISSIVE: Text = Text { + de: "Freizügig", + en: "Permissive", + }; + pub const CAT_WEAK_COPYLEFT: Text = Text { + de: "Schwaches Copyleft", + en: "Weak copyleft", + }; + pub const CAT_STRONG_COPYLEFT: Text = Text { + de: "Starkes Copyleft", + en: "Strong copyleft", + }; + pub const CAT_NETWORK_COPYLEFT: Text = Text { + de: "Netzwerk-Copyleft", + en: "Network copyleft", + }; + pub const CAT_PROPRIETARY: Text = Text { + de: "Proprietär / kommerziell", + en: "Proprietary / commercial", + }; + pub const CAT_OWN_CODE: Text = Text { + de: "Eigener Code", + en: "Own code", + }; + pub const CAT_UNCLEAR: Text = Text { + de: "Unklar", + en: "Unclear", + }; + + /// A category in words. + pub fn category(c: compliance_core::models::LicenseCategory) -> Text { + use compliance_core::models::LicenseCategory::*; + match c { + PublicDomain => CAT_PUBLIC_DOMAIN, + Permissive => CAT_PERMISSIVE, + WeakCopyleft => CAT_WEAK_COPYLEFT, + StrongCopyleft => CAT_STRONG_COPYLEFT, + NetworkCopyleft => CAT_NETWORK_COPYLEFT, + Proprietary => CAT_PROPRIETARY, + OwnCode => CAT_OWN_CODE, + Unclear => CAT_UNCLEAR, + } + } +} diff --git a/compliance-dashboard/src/infrastructure/sbom.rs b/compliance-dashboard/src/infrastructure/sbom.rs index 2a8d903..12c1508 100644 --- a/compliance-dashboard/src/infrastructure/sbom.rs +++ b/compliance-dashboard/src/infrastructure/sbom.rs @@ -64,6 +64,9 @@ pub struct SbomEntryData { /// The images an image recipe declares it in (a Yocto recipe). #[serde(default)] pub in_image: Option, + /// The licence a person of the workspace confirmed, where there is one. + #[serde(default)] + pub concluded: Option, #[serde(default)] pub created_at: Option, #[serde(default)] @@ -82,9 +85,69 @@ pub struct LicenseSummaryData { pub license: String, pub count: u64, pub is_copyleft: bool, + #[serde(default)] + pub category: compliance_core::models::LicenseCategory, + /// How many of the components a person confirmed this licence for. + #[serde(default)] + pub confirmed: u64, pub packages: Vec, } +/// The value of the licence filter that asks for the components whose +/// licence is still open (none detected, none confirmed). +pub const OPEN_LICENSE_FILTER: &str = "__open__"; + +/// A component a licence is confirmed for. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicenseTarget { + pub name: String, + pub package_manager: String, + pub version: String, + pub purl: Option, +} + +impl LicenseTarget { + /// The component of an SBOM row. + pub fn of(entry: &SbomEntryData) -> Self { + Self { + name: entry.name.clone(), + package_manager: entry.package_manager.clone(), + version: entry.version.clone(), + purl: entry.purl.clone(), + } + } +} + +/// A licence confirmation as the editor sends it; the agent adds who and +/// when, and the category of an SPDX licence. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct LicenseDraft { + pub components: Vec, + pub all_versions: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub license: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub license_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub category: Option, + pub copyright: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub license_text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub license_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub contract_ref: Option, + /// `YYYY-MM-DD`, as a date field gives it. + #[serde(skip_serializing_if = "Option::is_none")] + pub valid_until: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub usage: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct LicenseSummaryResponse { pub data: Vec, @@ -172,7 +235,9 @@ pub async fn fetch_sbom_filtered( params.push(format!("has_vulns={hv}")); } if let Some(l) = &license { - if !l.is_empty() { + if l == OPEN_LICENSE_FILTER { + params.push("unresolved=true".to_string()); + } else if !l.is_empty() { params.push(format!("license={}", l.replace(' ', "%20"))); } } @@ -195,6 +260,35 @@ pub async fn fetch_sbom_filtered( Ok(body) } +/// Confirm the licence of the draft's components. The agent refuses (422) +/// a licence it cannot read, with the reason, and read-only roles (403); +/// the refusal is the error. +#[server] +pub async fn save_license_conclusion(draft: LicenseDraft) -> Result<(), ServerFnError> { + let resp = + super::agent_client::agent_request(reqwest::Method::PUT, "/api/v1/licenses/conclusions") + .await? + .json(&draft) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Withdraw the confirmed licence `id`; the component shows the detected +/// licence again. +#[server] +pub async fn withdraw_license_conclusion(id: String) -> Result<(), ServerFnError> { + let resp = + super::agent_client::agent_request(reqwest::Method::DELETE, "/api/v1/licenses/conclusions") + .await? + .query(&[("id", id.as_str())]) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + #[server] pub async fn fetch_sbom_export(repo_id: String, format: String) -> Result { let path = format!("/api/v1/sbom/export?repo_id={repo_id}&format={format}"); diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index bfaebd2..7acc802 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -1,10 +1,12 @@ -use compliance_core::models::YOCTO_RECIPE_MANAGER; +use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER}; use dioxus::prelude::*; +use crate::components::license_editor::{category_class, confirmed_title, LicenseEditor}; +use crate::components::no_access::use_can_write; use crate::components::page_header::PageHeader; use crate::components::pagination::Pagination; use crate::components::toast::{ToastType, Toasts}; -use crate::i18n::texts::{common, sbom as tx}; +use crate::i18n::texts::{common, license_edit as lx, sbom as tx}; use crate::i18n::{use_lang, Lang}; use crate::infrastructure::sbom::*; @@ -33,6 +35,12 @@ pub fn SbomPage(target: String) -> Element { let mut show_export = use_signal(|| false); let mut export_format = use_signal(|| "cyclonedx".to_string()); + // ── Licence review: the rows picked for a bulk edit, and the open editor + // (its components, and the confirmation it starts from) ── + let can_write = use_can_write(); + let mut selected = use_signal(Vec::::new); + let mut editor = use_signal(|| Option::<(Vec, Option)>::None); + // ── Diff state ── let mut diff_repo_a = use_signal(String::new); let mut diff_repo_b = use_signal(String::new); @@ -48,7 +56,7 @@ pub fn SbomPage(target: String) -> Element { let sbom_filters = use_resource(|| async { fetch_sbom_filters().await.ok() }); // ── SBOM list (filtered) ── - let sbom = use_resource(move || { + let mut sbom = use_resource(move || { let p = page(); let repo = repo_filter(); let pm = pm_filter(); @@ -83,7 +91,7 @@ pub fn SbomPage(target: String) -> Element { }); // ── License summary ── - let license_data = use_resource(move || { + let mut license_data = use_resource(move || { let repo = repo_filter(); async move { fetch_license_summary(if repo.is_empty() { None } else { Some(repo) }) @@ -206,6 +214,11 @@ pub fn SbomPage(target: String) -> Element { class: "sbom-filter-select", onchange: move |e| { license_filter.set(e.value()); page.set(1); }, option { value: "", {tx::ALL_LICENSES.get(lang)} } + option { + value: OPEN_LICENSE_FILTER, + selected: license_filter() == OPEN_LICENSE_FILTER, + {lx::OPEN_FILTER.get(lang)} + } { match &*sbom_filters.read() { Some(Some(f)) => rsx! { @@ -288,11 +301,29 @@ pub fn SbomPage(target: String) -> Element { } } } + if can_write && !selected().is_empty() { + div { class: "license-selection-bar", + span { "{selected().len()} ✓" } + button { + class: "btn btn-primary btn-sm", + onclick: move |_| editor.set(Some((selected(), None))), + {lx::EDIT_SELECTED.get(lang)} + } + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| selected.set(Vec::new()), + {lx::CLEAR_SELECTION.get(lang)} + } + } + } div { class: "card", div { class: "table-wrapper", table { thead { tr { + if can_write { + th { class: "license-select-col" } + } th { {tx::PACKAGE.get(lang)} } th { {tx::VERSION.get(lang)} } th { {tx::MANAGER.get(lang)} } @@ -306,7 +337,18 @@ pub fn SbomPage(target: String) -> Element { let row_key = format!("{}@{}", entry.name, entry.version); let is_expanded = expanded_row() == Some(row_key.clone()); let has_vulns = !entry.known_vulnerabilities.is_empty(); - let license_class = license_css_class(entry.license.as_deref()); + let license_class = license_css_class(entry); + let shown_license = entry + .concluded + .as_ref() + .map(|c| c.display().to_string()) + .or_else(|| entry.license.clone().filter(|l| !l.trim().is_empty())) + .unwrap_or_else(|| "-".to_string()); + let target = LicenseTarget::of(entry); + let is_selected = selected().contains(&target); + let toggle_target = target.clone(); + let edit_target = target.clone(); + let edit_existing = entry.concluded.clone(); let row_key_click = row_key.clone(); // Which images declare it, on the badge's tooltip. let in_image_title = entry.in_image.as_ref().map(|i| { @@ -314,6 +356,24 @@ pub fn SbomPage(target: String) -> Element { }); rsx! { tr { + if can_write { + td { class: "license-select-col", + input { + r#type: "checkbox", + title: lx::SELECT_ROW.get(lang), + checked: is_selected, + onchange: move |e| { + let t = toggle_target.clone(); + selected.with_mut(|list| { + list.retain(|x| x != &t); + if e.checked() { + list.push(t); + } + }); + }, + } + } + } td { style: "font-weight: 500;", "{entry.name}" @@ -343,7 +403,23 @@ pub fn SbomPage(target: String) -> Element { } td { span { class: "sbom-license-badge {license_class}", - "{entry.license.as_deref().unwrap_or(\"-\")}" + "{shown_license}" + } + if let Some(c) = &entry.concluded { + " " + span { + class: "badge badge-success license-confirmed", + title: "{confirmed_title(c, lang)}", + {lx::CONFIRMED.get(lang)} + } + } + if can_write { + " " + button { + class: "btn btn-ghost btn-sm license-edit-btn", + onclick: move |_| editor.set(Some((vec![edit_target.clone()], edit_existing.clone()))), + {lx::EDIT.get(lang)} + } } } td { @@ -382,7 +458,7 @@ pub fn SbomPage(target: String) -> Element { // ── Vulnerability drill-down row ── if is_expanded && has_vulns { tr { class: "sbom-vuln-detail-row", - td { colspan: "5", + td { colspan: if can_write { "6" } else { "5" }, div { class: "sbom-vuln-detail", for vuln in &entry.known_vulnerabilities { div { class: "sbom-vuln-card", @@ -462,22 +538,61 @@ pub fn SbomPage(target: String) -> Element { } } + // ── Licence editor ── + if let Some((components, existing)) = editor() { + LicenseEditor { + components, + existing, + on_close: move |saved: bool| { + editor.set(None); + if saved { + selected.set(Vec::new()); + sbom.restart(); + license_data.restart(); + } + }, + } + } + // ═══════════════ LICENSE COMPLIANCE TAB ═══════════════ if active_tab() == "licenses" { match &*license_data.read() { Some(Some(resp)) => { let total_pkgs: u64 = resp.data.iter().map(|l| l.count).sum(); - let has_copyleft = resp.data.iter().any(|l| l.is_copyleft); - let copyleft_items: Vec<_> = resp.data.iter().filter(|l| l.is_copyleft).collect(); + let has_copyleft = resp.data.iter().any(|l| l.category.is_copyleft()); + let copyleft_items: Vec<_> = resp.data.iter().filter(|l| l.category.is_copyleft()).collect(); + let open = resp.data.iter().find(|l| l.license == "Unknown").map_or(0, |l| l.count); + let confirmed: u64 = resp.data.iter().map(|l| l.confirmed).sum(); rsx! { + if open > 0 || confirmed > 0 { + div { class: "card license-open-card", + if open > 0 { + strong { {lx::OPEN_COUNT.get(lang).replace("{n}", &open.to_string())} } + button { + class: "btn btn-primary btn-sm", + onclick: move |_| { + license_filter.set(OPEN_LICENSE_FILTER.to_string()); + page.set(1); + active_tab.set("packages".to_string()); + }, + {lx::OPEN_SHOW.get(lang)} + } + } + if confirmed > 0 { + span { class: "license-confirmed-count", + {lx::CONFIRMED_COUNT.get(lang).replace("{n}", &confirmed.to_string())} + } + } + } + } if has_copyleft { div { class: "license-copyleft-warning", strong { {tx::COPYLEFT_TITLE.get(lang)} } p { {tx::COPYLEFT_BODY.get(lang)} } for item in ©left_items { div { class: "license-copyleft-item", - span { class: "sbom-license-badge license-copyleft", "{item.license}" } + span { class: "sbom-license-badge {category_class(item.category)}", "{item.license}" } span { " — {item.count} {tx::PACKAGES_COUNT.get(lang)}: " } span { class: "license-pkg-list", "{item.packages.join(\", \")}" @@ -494,7 +609,7 @@ pub fn SbomPage(target: String) -> Element { for item in &resp.data { { let pct = (item.count as f64 / total_pkgs as f64 * 100.0).max(2.0); - let bar_class = if item.is_copyleft { "license-bar license-copyleft" } else { "license-bar license-permissive" }; + let bar_class = format!("license-bar {}", category_class(item.category)); rsx! { div { class: "license-bar-row", span { class: "license-bar-label", "{item.license}" } @@ -532,15 +647,19 @@ pub fn SbomPage(target: String) -> Element { tr { td { span { - class: "sbom-license-badge {license_type_class(item.is_copyleft)}", + class: "sbom-license-badge {category_class(item.category)}", "{item.license}" } } td { - if item.is_copyleft { - span { class: "badge badge-high", {tx::COPYLEFT.get(lang)} } - } else { - span { class: "badge badge-info", {tx::PERMISSIVE.get(lang)} } + span { + class: if item.category.is_copyleft() { "badge badge-high" } else { "badge badge-info" }, + {lx::category(item.category).get(lang)} + } + if item.confirmed > 0 { + span { class: "license-confirmed-count", + {format!(" · {}", lx::CONFIRMED_COUNT.get(lang).replace("{n}", &item.confirmed.to_string()))} + } } } td { @@ -765,27 +884,15 @@ fn version_label(entry: &SbomEntryData, lang: Lang) -> String { } } -fn license_css_class(license: Option<&str>) -> &'static str { - match license { - Some(l) => { - let upper = l.to_uppercase(); - if upper.contains("GPL") || upper.contains("AGPL") { - "license-copyleft" - } else if upper.contains("LGPL") || upper.contains("MPL") { - "license-weak-copyleft" - } else { - "license-permissive" - } +/// The badge class of a row's licence: by the confirmed licence's category, +/// else by the detected licence's (LGPL and MPL are weak copyleft, not GPL). +fn license_css_class(entry: &SbomEntryData) -> &'static str { + match (&entry.concluded, entry.license.as_deref()) { + (Some(c), _) => category_class(c.category), + (None, Some(l)) if !l.trim().is_empty() => { + category_class(compliance_core::spdx_license::category(l)) } - None => "", - } -} - -fn license_type_class(is_copyleft: bool) -> &'static str { - if is_copyleft { - "license-copyleft" - } else { - "license-permissive" + _ => "", } } diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index e71bb8f..aa89e58 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -204,10 +204,44 @@ Copyleft-licensed dependencies can require you to release your source code under | Column | Description | |--------|-------------| | **Lizenz** | License identifier | -| **Art** | **Copyleft** or **Freizügig** (permissive) | +| **Art** | The category: **Freizügig**, **Schwaches Copyleft** (LGPL, MPL, EPL), **Starkes Copyleft** (GPL), **Netzwerk-Copyleft** (AGPL), **Proprietär / kommerziell**, **Gemeinfrei**, **Eigener Code** or **Unklar**, with how many of them were confirmed | | **Pakete** | The packages using it | | **Anzahl** | Number of packages | +### Confirming a license + +Where the scan finds no license (**Unknown**) or a wrong one, people with the +IT_ADMIN or USER role can confirm the license themselves; CXO and LEGAL can +read the confirmations. + +1. On the **Lizenzen** tab, **Anzeigen und bearbeiten** next to the count of + components without a known license lists exactly those (the filter + **Lizenz offen (unbekannt)** on the **Pakete** tab does the same). +2. Click **Bearbeiten** in a row, or tick several rows and click + **Lizenz bearbeiten** to confirm one license for all of them (for + example every library of your own company). +3. Choose **SPDX-Lizenz** and type its id or expression (`MIT`, + `Apache-2.0`, `MIT OR Apache-2.0`); the category follows from it. For a + license SPDX does not list, choose **Eigene oder kommerzielle Lizenz**, + give its name and pick the category; for a bought license also the + contract number and **Gültig bis**. +4. Optionally add the copyright holders (one per line), the license text, a + link to it, where you found it (a file in the repository, a contract, a + web page), whether the component is shipped with the product or only used + to build it, and a note. +5. **Für alle Versionen dieses Pakets** applies it to every version of the + package, now and in future scans; otherwise only to the listed version. + +A confirmed license is kept apart from the scan results, so the next scan +does not undo it. The table shows it with a **bestätigt** badge (who and +when on hover), the license summary counts it instead of the detected one, +and **Bestätigung zurücknehmen** in the dialog withdraws it. The same +package in other targets gets it too. + +::: info +The categories are guidance for reviewing your components, not legal advice. +::: + ## Export 1. On the **Pakete** tab, select a target under **Alle Prüfobjekte**. Export @@ -252,8 +286,17 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1: the homepage or repository its registry names, or the repository its purl names. Never a person's name or email. - Licenses are an SPDX id, an SPDX expression or a named license, marked - `acknowledgement: declared`: they are what the package declares, not a - licence Prüfwerk concluded. + `acknowledgement: declared`: they are what the package declares. A + license a person confirmed is written instead, marked + `acknowledgement: concluded` (a license of your own by name, with its text + and URL), with the copyright in `copyright` and the properties + `pruefwerk:license:category`, `pruefwerk:license:usage`, + `pruefwerk:license:contract`, `pruefwerk:license:valid_until`, + `pruefwerk:license:evidence`, `pruefwerk:license:concluded` (who and when) + and, where the scan found another one, `pruefwerk:license:declared`. +- In SPDX, a confirmed license is `licenseConcluded` (otherwise + `NOASSERTION`), with `copyrightText`; a license of your own is defined in + `hasExtractedLicensingInfos`. - The known vulnerabilities are listed at the top level, each naming the components it affects. A vulnerability is listed once under its CVE (`source` NVD) when one is known, with its GitHub advisory under