From 41c337138da110cc8f9ee158baec8e38c29de274 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Thu, 15 Oct 2026 14:35:43 +0000 Subject: [PATCH] feat(licenses): licence policy, legal review, third-party notices (licence review v2) (#570) --- compliance-agent/src/api/handlers/evidence.rs | 1 + compliance-agent/src/api/handlers/licenses.rs | 546 ++++++++++++- compliance-agent/src/api/handlers/sbom.rs | 3 + compliance-agent/src/api/role_gate.rs | 25 +- .../src/api/role_gate/router_tests.rs | 53 +- compliance-agent/src/api/routes.rs | 12 + compliance-agent/src/database.rs | 5 + compliance-agent/src/evidence/mod.rs | 50 ++ compliance-agent/src/license_conclusions.rs | 27 + .../src/pipeline/license_policy.rs | 225 ++++++ compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 18 + compliance-core/src/lib.rs | 1 + compliance-core/src/license_notices.rs | 356 +++++++++ compliance-core/src/models/license.rs | 5 + compliance-core/src/models/license_policy.rs | 701 +++++++++++++++++ compliance-core/src/models/mod.rs | 4 + compliance-core/src/models/sbom.rs | 6 + compliance-core/src/sbom_docs.rs | 22 +- compliance-dashboard/assets/main.css | 147 ++++ .../src/components/license_review.rs | 743 ++++++++++++++++++ compliance-dashboard/src/components/mod.rs | 1 + compliance-dashboard/src/i18n/texts.rs | 256 ++++++ .../src/infrastructure/download.rs | 11 +- .../src/infrastructure/sbom.rs | 161 ++++ compliance-dashboard/src/pages/sbom.rs | 49 +- compliance-mcp/src/database.rs | 10 + compliance-mcp/src/server.rs | 22 + compliance-mcp/src/tools/sbom.rs | 170 +++- docs/features/mcp-server.md | 6 +- docs/guide/sbom.md | 67 +- 31 files changed, 3691 insertions(+), 13 deletions(-) create mode 100644 compliance-agent/src/pipeline/license_policy.rs create mode 100644 compliance-core/src/license_notices.rs create mode 100644 compliance-core/src/models/license_policy.rs create mode 100644 compliance-dashboard/src/components/license_review.rs diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index ab56a5d..b12f092 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -88,6 +88,7 @@ async fn load_inputs( catalog: crate::controls::cra_catalog(&agent.config).await, target, author: String::new(), + license_policy: crate::license_conclusions::load_policy(db).await, }) } diff --git a/compliance-agent/src/api/handlers/licenses.rs b/compliance-agent/src/api/handlers/licenses.rs index df928f5..8d5b15d 100644 --- a/compliance-agent/src/api/handlers/licenses.rs +++ b/compliance-agent/src/api/handlers/licenses.rs @@ -7,17 +7,25 @@ //! the role gate decides for every `PUT` and `DELETE`. use axum::extract::{Extension, Query}; -use axum::http::StatusCode; +use axum::http::{header, StatusCode}; +use axum::response::IntoResponse; use axum::Json; use chrono::NaiveDate; +use futures_util::TryStreamExt; use mongodb::bson::doc; use serde::Deserialize; +use compliance_core::license_notices::{self, NoticeFormat}; use compliance_core::models::license::{ self, conclusion_id, package_key, LicenseCategory, LicenseConclusion, LicenseUsage, }; +use compliance_core::models::license_policy::{ + self, LegalReview, LicensePolicy, PolicyAction, ReviewDecision, VerdictCounts, +}; +use compliance_core::models::SbomEntry; use compliance_core::spdx_license; use compliance_core::tenant_ctx::TenantCtx; +use compliance_core::OrgRole; use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult}; use super::findings::Actor; @@ -35,6 +43,10 @@ pub struct ComponentRef { pub version: String, #[serde(default)] pub purl: Option, + /// The licence the scan found, as the list shows it. Read only by a + /// review of a component nobody confirmed a licence for. + #[serde(default)] + pub license: Option, } /// The body of [`conclude`]. @@ -176,6 +188,7 @@ fn conclusions_of( by_name: actor.name.clone(), support: actor.support, at, + review: None, }; conclusion.validate()?; out.push(conclusion); @@ -278,6 +291,458 @@ pub async fn withdraw( Ok(Json(serde_json::json!({ "status": "withdrawn" }))) } +/// Whether the requester may change the policy and decide reviews: LEGAL, +/// IT_ADMIN, or BreakPilot support. USER confirms licences but does not +/// decide whether they may be used. +fn may_decide(tenant: &TenantCtx) -> bool { + let ctx = &tenant.0; + ctx.api_key.is_none() + && (ctx.staff.is_some() || ctx.has_any_role(&[OrgRole::Legal, OrgRole::ItAdmin])) +} + +fn refuse_role() -> Refusal { + ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ + "error": crate::api::role_gate::FORBIDDEN_ROLE, + "access": "read_only", + "needs": ["LEGAL", "IT_ADMIN"], + })), + ) +} + +#[tracing::instrument(skip_all)] +pub async fn get_policy( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let policy = crate::license_conclusions::load_policy(&db).await; + Ok(Json(serde_json::json!({ + "data": policy, + "may_edit": may_decide(&tenant), + }))) +} + +#[tracing::instrument(skip_all)] +pub async fn put_policy( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(policy): Json, +) -> Result, Refusal> { + if !may_decide(&tenant) { + return Err(refuse_role()); + } + let actor = Actor::of(&tenant.0); + let mut policy = policy + .normalised() + .map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?; + policy.updated_by = Some(actor.id.to_string()); + policy.updated_by_name = actor.name.clone(); + policy.updated_at = Some(chrono::Utc::now()); + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + db.license_policy() + .replace_one(doc! { "_id": license_policy::POLICY_ID }, &policy) + .upsert(true) + .await + .map_err(|e| { + tracing::warn!("license policy not stored: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "store") + })?; + tracing::info!( + rules = policy.licenses.len(), + support = actor.support, + "license policy changed" + ); + Ok(Json( + serde_json::json!({ "status": "saved", "data": policy }), + )) +} + +/// The fields of a component the policy is judged on. +#[derive(Debug, Deserialize)] +struct CheckRow { + repo_id: String, + name: String, + #[serde(default)] + version: String, + #[serde(default)] + package_manager: String, + #[serde(default)] + purl: Option, + #[serde(default)] + license: Option, +} + +impl CheckRow { + fn entry(self) -> SbomEntry { + let mut e = SbomEntry::new(self.repo_id, self.name, self.version, self.package_manager); + e.purl = self.purl; + e.license = self.license; + e + } +} + +/// The components a check or notice reads, at most +/// [`super::sbom::MAX_EXPORT_COMPONENTS`], conclusions and verdicts attached. +async fn judged_components( + db: &crate::database::Database, + repo_id: Option<&str>, +) -> (Vec, LicensePolicy) { + let mut query = doc! {}; + if let Some(repo_id) = repo_id { + query.insert("repo_id", repo_id); + } + let rows: Vec = match db + .sbom_entries() + .clone_with_type::() + .find(query) + .projection(doc! { + "_id": 0, "repo_id": 1, "name": 1, "version": 1, + "package_manager": 1, "purl": 1, "license": 1, + }) + .sort(doc! { "name": 1, "version": 1 }) + .limit(i64::try_from(super::sbom::MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX)) + .await + { + Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| { + tracing::warn!("components for the licence check not read: {e}"); + Vec::new() + }), + Err(e) => { + tracing::warn!("components for the licence check not read: {e}"); + Vec::new() + } + }; + let mut entries: Vec = rows.into_iter().map(CheckRow::entry).collect(); + let conclusions = crate::license_conclusions::load(db).await; + license::apply(&mut entries, &conclusions); + let policy = crate::license_conclusions::load_policy(db).await; + crate::license_conclusions::judge(&mut entries, &policy); + (entries, policy) +} + +/// The query of [`check`] and [`notices`]. +#[derive(Debug, Deserialize)] +pub struct CheckQuery { + #[serde(default)] + pub repo_id: Option, +} + +/// The most open components one check lists. +pub const MAX_CHECK_ITEMS: usize = 2_000; + +#[tracing::instrument(skip_all)] +pub async fn check( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> Result, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let (entries, policy) = judged_components(&db, query.repo_id.as_deref()).await; + let mut counts = VerdictCounts::default(); + let mut items = Vec::new(); + for e in &entries { + let Some(verdict) = e.policy.as_ref() else { + continue; + }; + counts.add(verdict); + let expiring = verdict + .reasons + .iter() + .any(|r| matches!(r, license_policy::VerdictReason::ExpiresSoon { .. })); + if !(verdict.is_open() || expiring || verdict.required != PolicyAction::Allow) { + continue; + } + if items.len() >= MAX_CHECK_ITEMS { + continue; + } + items.push(serde_json::json!({ + "repo_id": e.repo_id, + "name": e.name, + "version": e.version, + "package_manager": e.package_manager, + "purl": e.purl, + "license": e.effective_license(), + "detected": e.license, + "conclusion_id": e.concluded.as_ref().map(|c| c.id.clone()), + "review": e.concluded.as_ref().and_then(|c| c.review.clone()), + "verdict": verdict, + })); + } + // Forbidden first, then what needs a review, then the rest. + items.sort_by_key(|i| match i["verdict"]["action"].as_str() { + Some("forbid") => 0, + Some("review") => 1, + _ => 2, + }); + let listed = items.len(); + Ok(Json(serde_json::json!({ + "data": { + "counts": counts, + "components": entries.len(), + "items": items, + "truncated": listed >= MAX_CHECK_ITEMS, + "policy": policy, + "may_decide": may_decide(&tenant), + } + }))) +} + +/// The body of [`review`]. +#[derive(Debug, Deserialize)] +pub struct ReviewRequest { + pub components: Vec, + /// For every version of the packages, not just the listed ones. + #[serde(default)] + pub all_versions: bool, + pub decision: ReviewDecision, + #[serde(default)] + pub note: Option, +} + +/// The conclusions `req` decides on: each component's confirmed licence with +/// the review set, or, where none was confirmed, the licence the scan found +/// confirmed as it is, by the reviewer. +/// +/// # Errors +/// +/// Why the review cannot be stored: no component, a component without a +/// licence anyone could review. +fn reviewed( + req: ReviewRequest, + conclusions: &[LicenseConclusion], + 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 note = text(req.note); + if note + .as_deref() + .is_some_and(|n| n.chars().count() > license::MAX_FIELD_CHARS) + { + return Err("note too long".into()); + } + let actor = Actor::of(&tenant.0); + let at = chrono::Utc::now(); + let review = LegalReview { + decision: req.decision, + by: actor.id.to_string(), + by_name: actor.name.clone(), + support: actor.support, + note, + at, + }; + 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 = component.version.trim(); + let existing = if req.all_versions { + let id = conclusion_id(&key, None); + conclusions.iter().find(|c| c.id == id) + } else { + license::find_for( + conclusions, + name, + &component.package_manager, + version, + component.purl.as_deref(), + ) + }; + let mut conclusion = match existing { + Some(c) => c.clone(), + None => { + let detected = text(component.license.clone()).ok_or_else(|| { + format!("{name}: no licence to review; confirm the licence first") + })?; + let spdx = spdx_license::normalise(&detected).into_owned(); + if !spdx_license::is_spdx_expression(&spdx) { + return Err(format!( + "{name}: the licence found ({detected}) is no SPDX licence; confirm the licence first" + )); + } + let version = + (!req.all_versions && !version.is_empty()).then(|| version.to_string()); + LicenseConclusion { + id: conclusion_id(&key, version.as_deref()), + package_key: key, + name: name.to_string(), + package_manager: component.package_manager.trim().to_string(), + version, + category: spdx_license::category(&spdx), + license: spdx, + license_name: None, + copyright: Vec::new(), + license_text: None, + license_url: None, + evidence: Some( + "Licence as the scan found it, confirmed in the legal review".into(), + ), + contract_ref: None, + valid_until: None, + usage: None, + note: None, + by: actor.id.to_string(), + by_name: actor.name.clone(), + support: actor.support, + at, + review: None, + } + } + }; + if out.iter().any(|c| c.id == conclusion.id) { + continue; + } + conclusion.review = Some(review.clone()); + out.push(conclusion); + } + Ok(out) +} + +#[tracing::instrument(skip_all)] +pub async fn review( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, Refusal> { + if !may_decide(&tenant) { + return Err(refuse_role()); + } + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let conclusions = crate::license_conclusions::load(&db).await; + let decision = req.decision; + let reviewed = reviewed(req, &conclusions, &tenant) + .map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?; + let new = reviewed + .iter() + .filter(|r| !conclusions.iter().any(|c| c.id == r.id)) + .count(); + if conclusions.len().saturating_add(new) > usize::try_from(MAX_CONCLUSIONS).unwrap_or(0) { + return Err(refuse( + StatusCode::UNPROCESSABLE_ENTITY, + format!("at most {MAX_CONCLUSIONS} confirmed licences per workspace"), + )); + } + for c in &reviewed { + db.license_conclusions() + .replace_one(doc! { "_id": &c.id }, c) + .upsert(true) + .await + .map_err(|e| { + tracing::warn!("license review not stored: {e}"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "store") + })?; + } + tracing::info!( + count = reviewed.len(), + decision = decision.as_str(), + "license reviewed" + ); + Ok(Json(serde_json::json!({ + "status": "saved", + "saved": reviewed.len(), + "conclusions": reviewed, + }))) +} + +#[tracing::instrument(skip_all)] +pub async fn withdraw_review( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> Result, Refusal> { + if !may_decide(&tenant) { + return Err(refuse_role()); + } + let db = tenant_db(&agent, &tenant) + .await + .map_err(|code| refuse(code, "tenant"))?; + let result = db + .license_conclusions() + .update_one( + doc! { "_id": &query.id, "review": { "$exists": true } }, + doc! { "$unset": { "review": "" } }, + ) + .await + .map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?; + if result.matched_count == 0 { + return Err(refuse(StatusCode::NOT_FOUND, "no such review")); + } + tracing::info!("license review withdrawn"); + Ok(Json(serde_json::json!({ "status": "withdrawn" }))) +} + +/// The query of [`notices`]. +#[derive(Debug, Deserialize)] +pub struct NoticesQuery { + pub repo_id: String, + #[serde(default)] + pub format: NoticeFormat, + /// Also list components only used to build. + #[serde(default)] + pub build_only: bool, +} + +#[tracing::instrument(skip_all)] +pub async fn notices( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> Result { + let db = tenant_db(&agent, &tenant).await?; + let (entries, _) = judged_components(&db, Some(&query.repo_id)).await; + let product = target_name(&db, &query.repo_id).await; + let body = license_notices::render( + &entries, + &license_notices::NoticeOptions { + product: &product, + format: query.format, + include_build_only: query.build_only, + }, + ); + let disposition = format!("attachment; filename=\"{}\"", query.format.file_name()); + Ok(( + [ + ( + header::CONTENT_TYPE, + header::HeaderValue::from_static(query.format.content_type()), + ), + ( + header::CONTENT_DISPOSITION, + header::HeaderValue::from_str(&disposition) + .unwrap_or_else(|_| header::HeaderValue::from_static("attachment")), + ), + ], + body, + )) +} + +/// The name of the target `repo_id`, as the exports name the product. +pub(crate) async fn target_name(db: &crate::database::Database, repo_id: &str) -> String { + let target = match mongodb::bson::oid::ObjectId::parse_str(repo_id) { + Ok(oid) => db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .ok() + .flatten(), + Err(_) => None, + }; + target.map_or_else(|| format!("repo-{repo_id}"), |t| t.name) +} + #[cfg(test)] mod tests { use super::*; @@ -290,6 +755,7 @@ mod tests { package_manager: "npm".into(), version: "1.3.0".into(), purl: Some("pkg:npm/left-pad@1.3.0".into()), + license: None, }, // The same package and version twice is one conclusion. ComponentRef { @@ -297,12 +763,14 @@ mod tests { package_manager: "npm".into(), version: "1.3.0".into(), purl: Some("pkg:npm/left-pad@1.3.0".into()), + license: None, }, ComponentRef { name: "PumpSdk".into(), package_manager: "nuget".into(), version: "".into(), purl: None, + license: None, }, ], all_versions: false, @@ -388,4 +856,80 @@ mod tests { url.license_url = Some("file:///etc/passwd".into()); assert!(conclusions_of(url, &tenant()).is_err()); } + + fn with_roles(roles: Vec) -> TenantCtx { + let mut t = tenant(); + t.0.org_roles = roles; + t + } + + fn review_req(license: Option<&str>, decision: ReviewDecision) -> ReviewRequest { + ReviewRequest { + components: vec![ComponentRef { + name: "readline".into(), + package_manager: "deb".into(), + version: "8.2".into(), + purl: None, + license: license.map(String::from), + }], + all_versions: false, + decision, + note: Some(" ok for the firmware ".into()), + } + } + + #[test] + fn legal_and_it_admin_decide_users_do_not() { + assert!(may_decide(&with_roles(vec![OrgRole::Legal]))); + assert!(may_decide(&with_roles(vec![OrgRole::ItAdmin]))); + assert!(!may_decide(&with_roles(vec![OrgRole::User]))); + assert!(!may_decide(&with_roles(vec![OrgRole::Cxo]))); + } + + #[test] + fn a_review_without_a_confirmed_licence_confirms_the_detected_one() { + let out = reviewed( + review_req(Some("gpl-3.0-only"), ReviewDecision::Approved), + &[], + &with_roles(vec![OrgRole::Legal]), + ) + .unwrap_or_default(); + assert_eq!(out.len(), 1); + assert_eq!(out[0].license, "GPL-3.0-only"); + assert_eq!(out[0].category, LicenseCategory::StrongCopyleft); + assert_eq!(out[0].version.as_deref(), Some("8.2")); + let review = out[0].review.as_ref().map(|r| (r.decision, r.note.clone())); + assert_eq!( + review, + Some((ReviewDecision::Approved, Some("ok for the firmware".into()))) + ); + } + + #[test] + fn a_review_keeps_the_confirmed_licence_and_needs_one() { + let confirmed = conclusions_of(req(None, Some("Pump EULA")), &tenant()).unwrap_or_default(); + let mut r = review_req(None, ReviewDecision::Rejected); + r.components[0] = ComponentRef { + name: "PumpSdk".into(), + package_manager: "nuget".into(), + version: "".into(), + purl: None, + license: None, + }; + let out = reviewed(r, &confirmed, &tenant()).unwrap_or_default(); + assert_eq!(out.len(), 1); + assert_eq!(out[0].license_name.as_deref(), Some("Pump EULA")); + assert_eq!( + out[0].review.as_ref().map(|r| r.decision), + Some(ReviewDecision::Rejected) + ); + + assert!(reviewed(review_req(None, ReviewDecision::Approved), &[], &tenant()).is_err()); + assert!(reviewed( + review_req(Some("Some EULA"), ReviewDecision::Approved), + &[], + &tenant() + ) + .is_err()); + } } diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index a7cf43e..0aa9c57 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -132,6 +132,8 @@ pub async fn list_sbom( } }; compliance_core::models::license::apply(&mut entries, &conclusions); + let policy = crate::license_conclusions::load_policy(db).await; + crate::license_conclusions::judge(&mut entries, &policy); Ok(Json(ApiResponse { data: entries, @@ -555,6 +557,7 @@ mod license_summary_tests { by_name: None, support: false, at: chrono::Utc::now(), + review: None, }; let rows = [ row("a", Some("MIT")), diff --git a/compliance-agent/src/api/role_gate.rs b/compliance-agent/src/api/role_gate.rs index 604ab05..ee09e87 100644 --- a/compliance-agent/src/api/role_gate.rs +++ b/compliance-agent/src/api/role_gate.rs @@ -4,7 +4,9 @@ //! //! * `IT_ADMIN`, `USER` — read and write. //! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few -//! `POST` routes that only read ([`READ_ONLY_POSTS`]). +//! `POST` routes that only read ([`READ_ONLY_POSTS`]). `LEGAL` also +//! decides about licences: the licence policy and the legal review +//! ([`ROLE_WRITES`], decided 2026-10-15). //! * `FINANCE`, or none of these roles — nothing; every request is refused. //! //! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`. @@ -29,7 +31,7 @@ use axum::{ response::{IntoResponse, Response}, Json, }; -use compliance_core::{ApiKeyAccess, ProductAccess, TenantContext}; +use compliance_core::{ApiKeyAccess, OrgRole, ProductAccess, TenantContext}; /// The JSON `error` of a refusal. pub const FORBIDDEN_ROLE: &str = "forbidden_role"; @@ -66,6 +68,9 @@ pub const KEY_SCOPES: &[(Method, &str, &str)] = &[ (Method::GET, "/api/v1/sbom/licenses", SBOM_READ), (Method::GET, "/api/v1/sbom/quality", SBOM_READ), (Method::GET, "/api/v1/sbom/diff", SBOM_READ), + (Method::GET, "/api/v1/sbom/notices", SBOM_READ), + (Method::GET, "/api/v1/licenses/check", SBOM_READ), + (Method::GET, "/api/v1/licenses/policy", SBOM_READ), (Method::GET, "/api/v1/scan-runs", SCANS_READ), (Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN), (Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN), @@ -115,6 +120,21 @@ pub const READ_ONLY_POSTS: &[&str] = &[ "/api/v1/help/chat", ]; +/// Writes a read-only role may still make: method, route template, the +/// roles that may. The handler decides who else may (IT_ADMIN, support). +pub const ROLE_WRITES: &[(Method, &str, &[OrgRole])] = &[ + (Method::PUT, "/api/v1/licenses/policy", &[OrgRole::Legal]), + (Method::POST, "/api/v1/licenses/review", &[OrgRole::Legal]), + (Method::DELETE, "/api/v1/licenses/review", &[OrgRole::Legal]), +]; + +/// Whether `ctx` holds a role [`ROLE_WRITES`] lets write `method` on `template`. +pub fn role_may_write(ctx: &TenantContext, method: &Method, template: Option<&str>) -> bool { + ROLE_WRITES + .iter() + .any(|(m, t, roles)| m == method && Some(*t) == template && ctx.has_any_role(roles)) +} + /// Whether a request with `method` to the route `template` changes anything. /// A request that matched no route counts by its method alone. pub fn is_write(method: &Method, template: Option<&str>) -> bool { @@ -133,6 +153,7 @@ pub fn refusal( match ctx.product_access() { ProductAccess::Full => None, ProductAccess::ReadOnly if !is_write(method, template) => None, + ProductAccess::ReadOnly if role_may_write(ctx, method, template) => None, denied => Some(denied), } } diff --git a/compliance-agent/src/api/role_gate/router_tests.rs b/compliance-agent/src/api/role_gate/router_tests.rs index 63bd9d9..bb63086 100644 --- a/compliance-agent/src/api/role_gate/router_tests.rs +++ b/compliance-agent/src/api/role_gate/router_tests.rs @@ -4,7 +4,7 @@ //! these tests, so a request the gate lets through fails later (500, missing //! extension); what is checked is only whether the gate refused it. -use super::{require_org_role, KEY_SCOPES, LEGACY_SCOPES, READ_ONLY_POSTS}; +use super::{require_org_role, KEY_SCOPES, LEGACY_SCOPES, READ_ONLY_POSTS, ROLE_WRITES}; use crate::api::routes::build_router; use axum::{ body::{to_bytes, Body}, @@ -150,6 +150,9 @@ fn routes() -> Vec<(Method, String, bool)> { "/api/v1/licenses/conclusions?id=pkg%3Anpm%2Fa%40*".into(), true, ), + (Method::GET, "/api/v1/licenses/policy".into(), false), + (Method::GET, "/api/v1/licenses/check".into(), false), + (Method::GET, "/api/v1/sbom/notices".into(), false), (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), @@ -191,6 +194,54 @@ async fn roles_decide_reads_and_writes() { } } +#[tokio::test] +async fn legal_decides_about_licences_and_changes_nothing_else() { + let decisions = [ + (Method::PUT, "/api/v1/licenses/policy".to_string()), + (Method::POST, "/api/v1/licenses/review".to_string()), + ( + Method::DELETE, + "/api/v1/licenses/review?id=pkg%3Anpm%2Fa%40*".to_string(), + ), + ]; + for (method, path) in &decisions { + assert!( + !refused(Caller::Legal, method.clone(), path).await, + "LEGAL {method} {path}" + ); + assert!( + refused(Caller::Cxo, method.clone(), path).await, + "CXO {method} {path}" + ); + assert!( + refused(Caller::Finance, method.clone(), path).await, + "FINANCE {method} {path}" + ); + } + // Confirming a licence stays a write LEGAL may not make. + assert!(refused(Caller::Legal, Method::PUT, "/api/v1/licenses/conclusions").await); + // Every exception names a real route. + for (method, template, _) in ROLE_WRITES { + let resp = router(Caller::ItAdmin) + .oneshot( + Request::builder() + .method(method.clone()) + .uri(*template) + .header("content-type", "application/json") + .body(Body::from("{}")) + .expect("request"), + ) + .await + .expect("oneshot"); + assert_ne!(resp.status(), StatusCode::NOT_FOUND, "{method} {template}"); + assert_ne!( + resp.status(), + StatusCode::METHOD_NOT_ALLOWED, + "{method} {template}" + ); + } +} + #[tokio::test] async fn every_read_only_post_is_a_real_route() { // A template that no longer matches a route would silently turn back diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 619ed25..c793cdb 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -152,6 +152,18 @@ pub fn build_router() -> Router { .put(handlers::licenses::conclude) .delete(handlers::licenses::withdraw), ) + // The licence policy, what it says about each component, and the + // legal review that resolves what it asks a review for. + .route( + "/api/v1/licenses/policy", + get(handlers::licenses::get_policy).put(handlers::licenses::put_policy), + ) + .route("/api/v1/licenses/check", get(handlers::licenses::check)) + .route( + "/api/v1/licenses/review", + post(handlers::licenses::review).delete(handlers::licenses::withdraw_review), + ) + .route("/api/v1/sbom/notices", get(handlers::licenses::notices)) .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 a1cef14..81a4a89 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -661,6 +661,11 @@ impl Database { self.inner.collection("license_conclusions") } + /// The workspace's licence policy: one document, [`compliance_core::models::license_policy::POLICY_ID`]. + pub fn license_policy(&self) -> Collection { + self.inner.collection("license_policy") + } + pub fn cve_alerts(&self) -> Collection { self.inner.collection("cve_alerts") } diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index 17758e3..d566c80 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -37,6 +37,8 @@ pub struct EvidenceInputs { pub catalog: std::collections::HashMap, /// Who states the VEX (the workspace); the target's name when empty. pub author: String, + /// The workspace's licence policy, judged on the SBOM in `license-check.json`. + pub license_policy: compliance_core::models::LicensePolicy, } /// One file of the pack, as `manifest.json` lists it. @@ -62,6 +64,36 @@ struct Manifest { files: Vec, } +/// What the licence policy says about each component of the pack's SBOM. +fn license_check(inputs: &EvidenceInputs, at: DateTime) -> serde_json::Value { + use compliance_core::models::license_policy::{evaluate, VerdictCounts}; + let today = at.date_naive(); + let mut counts = VerdictCounts::default(); + let components: Vec = inputs + .sbom + .iter() + .map(|e| { + let verdict = evaluate(e, &inputs.license_policy, today); + counts.add(&verdict); + serde_json::json!({ + "name": e.name, + "version": e.version, + "package_manager": e.package_manager, + "purl": e.purl, + "license": e.effective_license(), + "review": e.concluded.as_ref().and_then(|c| c.review.clone()), + "verdict": verdict, + }) + }) + .collect(); + serde_json::json!({ + "date": today, + "policy": inputs.license_policy, + "counts": counts, + "components": components, + }) +} + /// The pack as a ZIP, and the manifest's file list. /// /// # Errors @@ -133,6 +165,21 @@ pub fn build_pack( if !enisa.is_empty() { files.push(("enisa-drafts.json", json(&enisa)?)); } + // The third-party notices and what the licence policy says about each + // component, as on the day the pack is made. + files.push(( + "THIRD-PARTY-NOTICES.txt", + compliance_core::license_notices::render( + &inputs.sbom, + &compliance_core::license_notices::NoticeOptions { + product: subject, + format: compliance_core::license_notices::NoticeFormat::Text, + include_build_only: false, + }, + ) + .into_bytes(), + )); + files.push(("license-check.json", json(&license_check(inputs, at))?)); // The SBOM's quality score of the last scan (sbomqs, #496), when it was // scored. if let Some(quality) = sbom_quality(inputs) { @@ -378,6 +425,7 @@ mod tests { last_run: None, catalog: Default::default(), author: String::new(), + license_policy: Default::default(), } } @@ -488,11 +536,13 @@ mod tests { assert_eq!( names, [ + "THIRD-PARTY-NOTICES.txt", "cra-compliance.json", "csaf-vex.json", "cve-alerts.json", "findings.csv", "findings.json", + "license-check.json", "manifest.json", "oscal-assessment-results.json", "sbom.cdx.json", diff --git a/compliance-agent/src/license_conclusions.rs b/compliance-agent/src/license_conclusions.rs index c318d1a..439e662 100644 --- a/compliance-agent/src/license_conclusions.rs +++ b/compliance-agent/src/license_conclusions.rs @@ -4,6 +4,7 @@ //! rewrites the components, so the conclusions live in their own collection. use compliance_core::models::license::{self, LicenseConclusion}; +use compliance_core::models::license_policy::{self, LicensePolicy}; use compliance_core::models::SbomEntry; use futures_util::TryStreamExt; use mongodb::bson::doc; @@ -43,3 +44,29 @@ pub async fn attach(db: &Database, entries: &mut [SbomEntry]) { let conclusions = load(db).await; license::apply(entries, &conclusions); } + +/// The workspace's licence policy; the default one when it has none or it +/// cannot be read. +pub async fn load_policy(db: &Database) -> LicensePolicy { + match db + .license_policy() + .find_one(doc! { "_id": license_policy::POLICY_ID }) + .await + { + Ok(Some(policy)) => policy, + Ok(None) => LicensePolicy::default(), + Err(e) => { + tracing::warn!("license policy not read, the default applies: {e}"); + LicensePolicy::default() + } + } +} + +/// Attach to `entries` (their conclusions attached) what `policy` says +/// about each of them today. +pub fn judge(entries: &mut [SbomEntry], policy: &LicensePolicy) { + let today = chrono::Utc::now().date_naive(); + for entry in entries.iter_mut() { + entry.policy = Some(license_policy::evaluate(entry, policy, today)); + } +} diff --git a/compliance-agent/src/pipeline/license_policy.rs b/compliance-agent/src/pipeline/license_policy.rs new file mode 100644 index 0000000..2bc2dfc --- /dev/null +++ b/compliance-agent/src/pipeline/license_policy.rs @@ -0,0 +1,225 @@ +//! The licence policy as findings: each component whose licence the +//! workspace's policy forbids (or whose bought licence ended) is a finding, +//! and the components still waiting for a legal review are one finding per +//! target, so a new licence to review shows up with the scan's other results +//! without one finding per unknown licence. +//! +//! The policy, the confirmed licences and the reviews are read at scan time; +//! a change to them shows in the licence check at once and in the findings +//! with the next scan. + +use chrono::NaiveDate; +use compliance_core::models::license::{self, package_key, LicenseConclusion}; +use compliance_core::models::license_policy::{ + self, LicensePolicy, LicenseVerdict, PolicyAction, VerdictReason, +}; +use compliance_core::models::{Finding, SbomEntry, ScanType, Severity}; + +use super::dedup; + +/// The scanner name of the findings. +pub const SCANNER: &str = "license-policy"; +/// A component the policy forbids. +pub const RULE_FORBIDDEN: &str = "license-forbidden"; +/// A bought licence that ended. +pub const RULE_EXPIRED: &str = "license-expired"; +/// Components that wait for a legal review. +pub const RULE_REVIEW: &str = "license-review-pending"; + +/// The most components a review finding names. +const MAX_LISTED: usize = 25; + +fn component(entry: &SbomEntry) -> String { + if entry.version.trim().is_empty() { + entry.name.clone() + } else { + format!("{} {}", entry.name, entry.version) + } +} + +fn licence(entry: &SbomEntry) -> &str { + entry.effective_license().unwrap_or("no licence found") +} + +/// The findings of `repo_id`'s components on `today`. +pub fn findings( + repo_id: &str, + entries: &[SbomEntry], + conclusions: &[LicenseConclusion], + policy: &LicensePolicy, + today: NaiveDate, +) -> Vec { + let mut out = Vec::new(); + let mut review: Vec = Vec::new(); + let mut seen: Vec = Vec::new(); + for scanned in entries { + let mut entry = scanned.clone(); + entry.concluded = license::find(conclusions, &entry).cloned(); + let verdict = license_policy::evaluate(&entry, policy, today); + let key = package_key(&entry.name, &entry.package_manager, entry.purl.as_deref()); + let id = format!("{key}@{}", entry.version); + if seen.contains(&id) { + continue; + } + seen.push(id); + match verdict.action { + PolicyAction::Forbid => out.push(forbidden(repo_id, &entry, &key, &verdict)), + PolicyAction::Review => { + review.push(format!("{} ({})", component(&entry), licence(&entry))) + } + PolicyAction::Allow => {} + } + } + if !review.is_empty() { + review.sort(); + let count = review.len(); + let mut listed: Vec = review.iter().take(MAX_LISTED).cloned().collect(); + if count > MAX_LISTED { + listed.push(format!("… and {} more", count - MAX_LISTED)); + } + let mut finding = Finding::new( + repo_id.to_string(), + dedup::compute_fingerprint(&[repo_id, RULE_REVIEW]), + SCANNER.to_string(), + ScanType::Sbom, + format!("{count} components wait for a licence review"), + format!( + "The workspace's licence policy asks for a legal review of these components \ + before they are used: {}.", + listed.join("; ") + ), + Severity::Low, + ); + finding.rule_id = Some(RULE_REVIEW.to_string()); + finding.remediation = Some( + "Open SBOM → Licences → Licence check. Confirm the licences that are unknown; a \ + person with the LEGAL role approves or rejects each one." + .to_string(), + ); + out.push(finding); + } + out +} + +fn forbidden(repo_id: &str, entry: &SbomEntry, key: &str, verdict: &LicenseVerdict) -> Finding { + let expired = verdict.reasons.iter().find_map(|r| match r { + VerdictReason::Expired { valid_until } => Some(*valid_until), + _ => None, + }); + let rejected = verdict.reasons.contains(&VerdictReason::Rejected); + let rule = if expired.is_some() { + RULE_EXPIRED + } else { + RULE_FORBIDDEN + }; + let (title, why) = match expired { + Some(until) => ( + format!("The licence of {} ended on {until}", component(entry)), + format!( + "The bought licence ({}) of {} was valid until {until}.", + licence(entry), + component(entry) + ), + ), + None if rejected => ( + format!( + "Licence of {} rejected in the legal review", + component(entry) + ), + format!( + "A legal review rejected the use of {} under {}.", + component(entry), + licence(entry) + ), + ), + None => ( + format!("{} is under a licence the policy forbids", component(entry)), + format!( + "{} is under {}, which the workspace's licence policy does not allow{}.", + component(entry), + licence(entry), + if verdict.shipped { + " in what is shipped" + } else { + "" + } + ), + ), + }; + let mut finding = Finding::new( + repo_id.to_string(), + dedup::compute_fingerprint(&[repo_id, rule, key, &entry.version]), + SCANNER.to_string(), + ScanType::Sbom, + title, + why, + Severity::High, + ); + finding.rule_id = Some(rule.to_string()); + finding.file_path = entry.evidence.first().cloned(); + finding.remediation = Some(match expired { + Some(_) => "Renew the licence and enter its new end date, or replace the component.".into(), + None => "Replace the component, obtain it under another licence, or have the licence \ + policy changed by the LEGAL role." + .into(), + }); + finding +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(name: &str, license: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new("r".into(), name.into(), "1.0".into(), "npm".into()); + e.license = license.map(String::from); + e + } + + fn today() -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 10, 15).unwrap_or_default() + } + + #[test] + fn forbidden_licences_are_findings_and_reviews_one_summary() { + let mut policy = LicensePolicy::default(); + policy.licenses.push(license_policy::LicenseRule { + license: "AGPL-3.0-only".into(), + action: PolicyAction::Forbid, + note: None, + }); + let entries = vec![ + entry("ok", Some("MIT")), + entry("bad", Some("AGPL-3.0-only")), + entry("bad", Some("AGPL-3.0-only")), + entry("gpl", Some("GPL-2.0-only")), + entry("unknown", None), + ]; + let out = findings("r", &entries, &[], &policy, today()); + assert_eq!(out.len(), 2); + assert_eq!(out[0].rule_id.as_deref(), Some(RULE_FORBIDDEN)); + assert_eq!(out[0].severity, Severity::High); + assert!(out[0].title.contains("bad 1.0")); + assert_eq!(out[1].rule_id.as_deref(), Some(RULE_REVIEW)); + assert!(out[1].title.starts_with("2 components")); + assert!(out[1] + .description + .contains("unknown 1.0 (no licence found)")); + // Stable across scans. + let again = findings("r", &entries, &[], &policy, today()); + assert_eq!(out[0].fingerprint, again[0].fingerprint); + assert_eq!(out[1].fingerprint, again[1].fingerprint); + } + + #[test] + fn nothing_open_is_no_finding() { + let out = findings( + "r", + &[entry("ok", Some("MIT"))], + &[], + &LicensePolicy::default(), + today(), + ); + assert!(out.is_empty()); + } +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 1f26ea1..01de802 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -30,6 +30,7 @@ mod issue_catchup; pub(crate) mod issue_creation; pub(crate) mod issue_sync; pub mod languages; +pub mod license_policy; pub mod lint; pub mod mobsfscan; pub mod nvd_cpe; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 2aec76e..b4df7b0 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -428,6 +428,7 @@ impl PipelineOrchestrator { .await; let mut sbom_entries = generated.entries; let syft_failure = generated.syft_failure; + let sbom_complete = syft_failure.is_none(); let unmapped_assemblies = generated.unmapped_assemblies; let resolved_nuget = generated.resolved_nuget; // Syft reads the lockfiles and archives: without it the SBOM is short @@ -695,6 +696,23 @@ impl PipelineOrchestrator { self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries) .await; + // The licence policy over the components just found: forbidden + // licences, ended licences, and what waits for a legal review. Only + // a complete SBOM may close the findings an earlier scan reported. + if sbom_complete && !sbom_entries.is_empty() { + let conclusions = crate::license_conclusions::load(&self.db).await; + let policy = crate::license_conclusions::load_policy(&self.db).await; + let licence_findings = crate::pipeline::license_policy::findings( + &repo_id, + &sbom_entries, + &conclusions, + &policy, + chrono::Utc::now().date_naive(), + ); + run_findings.completed(crate::pipeline::license_policy::SCANNER); + all_findings.extend(licence_findings); + } + // Stage 4: Pattern Scanning (GDPR + OAuth) tracing::info!("[{repo_id}] Stage 4: Pattern Scanning"); self.update_phase(scan_run_id, ScanPhase::PatternScanning) diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index a224401..c781990 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod error; pub mod exec_policy; #[cfg(feature = "net")] pub mod guarded_net; +pub mod license_notices; pub mod models; pub mod net_guard; pub mod purl; diff --git a/compliance-core/src/license_notices.rs b/compliance-core/src/license_notices.rs new file mode 100644 index 0000000..ccb3b44 --- /dev/null +++ b/compliance-core/src/license_notices.rs @@ -0,0 +1,356 @@ +//! Third-party notices: the file a product ships to name the components it +//! contains, their copyright and their licences (`THIRD-PARTY-NOTICES`). +//! +//! Built from a target's components with their confirmed licences attached +//! ([`crate::models::license::apply`]). Grouped by licence; for a licence +//! SPDX lists, the notice links its text on spdx.org instead of copying it; +//! for one of the workspace's own (`LicenseRef-`) it prints the text a +//! person stored. Components without a known licence are listed at the end, +//! so the gaps show. Build-only components are left out unless asked for. + +use std::collections::BTreeMap; +use std::fmt::Write as _; + +use serde::Deserialize; + +use crate::models::license_policy::is_shipped; +use crate::models::SbomEntry; +use crate::spdx_license; + +/// The formats a notice is written in. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum NoticeFormat { + /// Plain text (`THIRD-PARTY-NOTICES.txt`). + #[default] + Text, + /// Markdown (`THIRD-PARTY-NOTICES.md`). + Markdown, +} + +impl NoticeFormat { + /// The file name a download takes. + pub fn file_name(self) -> &'static str { + match self { + Self::Text => "THIRD-PARTY-NOTICES.txt", + Self::Markdown => "THIRD-PARTY-NOTICES.md", + } + } + + /// The media type of a download. + pub fn content_type(self) -> &'static str { + match self { + Self::Text => "text/plain; charset=utf-8", + Self::Markdown => "text/markdown; charset=utf-8", + } + } +} + +/// What a notice is made of. +#[derive(Debug, Clone)] +pub struct NoticeOptions<'a> { + /// The product's name for the heading (the target's name). + pub product: &'a str, + pub format: NoticeFormat, + /// Also list components only used to build. + pub include_build_only: bool, +} + +/// The components of one licence. +#[derive(Default)] +struct Group<'a> { + /// The licence's URLs: spdx.org for listed ids, the stored one otherwise. + urls: Vec, + /// Stored texts of licences SPDX does not list, once each. + texts: Vec<&'a str>, + /// `name version` with its copyright lines. + components: Vec<(String, Vec<&'a str>)>, +} + +/// The heading of the components without a licence. +const UNKNOWN: &str = "Licence not determined"; + +/// The spdx.org page of each SPDX id in `expression`. +fn spdx_urls(expression: &str) -> Vec { + let mut urls: Vec = Vec::new(); + for token in expression + .split(|c: char| c.is_whitespace() || c == '(' || c == ')') + .filter(|t| !t.is_empty()) + { + if let Some(id) = spdx_license::canonical_id(token.trim_end_matches('+')) { + let url = format!("https://spdx.org/licenses/{id}.html"); + if !urls.contains(&url) { + urls.push(url); + } + } + } + urls +} + +/// The notice for `entries` (one target's components, confirmed licences +/// attached). +pub fn render(entries: &[SbomEntry], options: &NoticeOptions<'_>) -> String { + let mut groups: BTreeMap> = BTreeMap::new(); + let mut unknown: Vec = Vec::new(); + let mut listed = 0usize; + let mut seen: Vec<(&str, &str, &str)> = Vec::new(); + for entry in entries { + let concluded = entry.concluded.as_ref(); + if !options.include_build_only && !is_shipped(concluded) { + continue; + } + // One line per package and version, however many manifests name it. + let id = ( + entry.package_manager.as_str(), + entry.name.as_str(), + entry.version.as_str(), + ); + if seen.contains(&id) { + continue; + } + seen.push(id); + listed += 1; + let component = if entry.version.trim().is_empty() { + entry.name.clone() + } else { + format!("{} {}", entry.name, entry.version) + }; + let Some(license) = entry.effective_license() else { + unknown.push(component); + continue; + }; + let group = groups.entry(license.to_string()).or_default(); + match concluded { + Some(c) => { + if let Some(url) = c.license_url.as_deref() { + if !group.urls.iter().any(|u| u == url) { + group.urls.push(url.to_string()); + } + } + for url in spdx_urls(&c.license) { + if !group.urls.contains(&url) { + group.urls.push(url); + } + } + if let Some(text) = c.license_text.as_deref() { + if !group.texts.contains(&text) { + group.texts.push(text); + } + } + group + .components + .push((component, c.copyright.iter().map(String::as_str).collect())); + } + None => { + for url in spdx_urls(&spdx_license::normalise(license)) { + if !group.urls.contains(&url) { + group.urls.push(url); + } + } + group.components.push((component, Vec::new())); + } + } + } + for group in groups.values_mut() { + group.components.sort_by(|a, b| a.0.cmp(&b.0)); + } + unknown.sort(); + match options.format { + NoticeFormat::Text => text(options, &groups, &unknown, listed), + NoticeFormat::Markdown => markdown(options, &groups, &unknown, listed), + } +} + +fn intro(options: &NoticeOptions<'_>, listed: usize) -> String { + format!( + "{} contains the following {listed} third-party components. Each is \ + distributed under the licence named for it; the copyright belongs to \ + its authors.", + options.product + ) +} + +fn text( + options: &NoticeOptions<'_>, + groups: &BTreeMap>, + unknown: &[String], + listed: usize, +) -> String { + let rule = "=".repeat(72); + let mut out = String::new(); + let _ = writeln!(out, "THIRD-PARTY NOTICES — {}\n", options.product); + let _ = writeln!(out, "{}\n", intro(options, listed)); + for (license, group) in groups { + let _ = writeln!(out, "{rule}\n{license}\n{rule}"); + for url in &group.urls { + let _ = writeln!(out, "Licence text: {url}"); + } + out.push('\n'); + for (component, copyright) in &group.components { + let _ = writeln!(out, " * {component}"); + for line in copyright { + let _ = writeln!(out, " {line}"); + } + } + for text in &group.texts { + let _ = writeln!(out, "\n{}\n", text.trim_end()); + } + out.push('\n'); + } + if !unknown.is_empty() { + let _ = writeln!(out, "{rule}\n{UNKNOWN}\n{rule}\n"); + for component in unknown { + let _ = writeln!(out, " * {component}"); + } + out.push('\n'); + } + out +} + +/// `text` with the characters markdown would read as formatting escaped. +fn md(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + if matches!( + c, + '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '#' | '|' + ) { + out.push('\\'); + } + out.push(c); + } + out +} + +fn markdown( + options: &NoticeOptions<'_>, + groups: &BTreeMap>, + unknown: &[String], + listed: usize, +) -> String { + let mut out = String::new(); + let _ = writeln!(out, "# Third-party notices — {}\n", md(options.product)); + let _ = writeln!(out, "{}\n", md(&intro(options, listed))); + for (license, group) in groups { + let _ = writeln!(out, "## {}\n", md(license)); + for url in &group.urls { + let _ = writeln!(out, "Licence text: <{url}>\n"); + } + for (component, copyright) in &group.components { + let _ = writeln!(out, "- {}", md(component)); + for line in copyright { + let _ = writeln!(out, " - {}", md(line)); + } + } + for text in &group.texts { + let _ = writeln!( + out, + "\n```text\n{}\n```", + text.trim_end().replace("```", "'''") + ); + } + out.push('\n'); + } + if !unknown.is_empty() { + let _ = writeln!(out, "## {UNKNOWN}\n"); + for component in unknown { + let _ = writeln!(out, "- {}", md(component)); + } + out.push('\n'); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::license::{conclusion_id, package_key}; + use crate::models::{LicenseCategory, LicenseConclusion, LicenseUsage}; + + fn entry(name: &str, license: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new("r".into(), name.into(), "1.0".into(), "npm".into()); + e.license = license.map(String::from); + e + } + + fn concluded(name: &str, license: &str) -> LicenseConclusion { + let key = package_key(name, "npm", None); + LicenseConclusion { + id: conclusion_id(&key, None), + package_key: key, + name: name.into(), + package_manager: "npm".into(), + version: None, + license: license.into(), + license_name: Some("Pump EULA".into()), + category: LicenseCategory::Proprietary, + copyright: vec!["© 2024 Pump GmbH".into()], + license_text: Some("You may use it.".into()), + 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(), + review: None, + } + } + + fn options(format: NoticeFormat) -> NoticeOptions<'static> { + NoticeOptions { + product: "Pump", + format, + include_build_only: false, + } + } + + #[test] + fn groups_by_licence_links_spdx_and_prints_own_texts() { + let mut own = entry("pumplib", None); + own.concluded = Some(concluded("pumplib", "LicenseRef-Pump-EULA")); + let entries = vec![ + entry("b", Some("MIT")), + entry("a", Some("MIT")), + entry("a", Some("MIT")), + own, + entry("mystery", None), + ]; + let out = render(&entries, &options(NoticeFormat::Text)); + assert!(out.contains("following 4 third-party components")); + assert!(out.contains("https://spdx.org/licenses/MIT.html")); + let a = out.find(" * a 1.0").unwrap_or(usize::MAX); + let b = out.find(" * b 1.0").unwrap_or(0); + assert!(a < b, "sorted"); + assert!(out.contains("Pump EULA")); + assert!(out.contains("© 2024 Pump GmbH")); + assert!(out.contains("You may use it.")); + assert!(out.contains("Licence not determined")); + assert!(out.contains(" * mystery 1.0")); + } + + #[test] + fn build_only_components_are_left_out_unless_asked() { + let mut tool = entry("jest", Some("MIT")); + let mut c = concluded("jest", "MIT"); + c.usage = Some(LicenseUsage::BuildOnly); + tool.concluded = Some(c); + let entries = vec![tool]; + assert!(!render(&entries, &options(NoticeFormat::Text)).contains("jest")); + let mut all = options(NoticeFormat::Text); + all.include_build_only = true; + assert!(render(&entries, &all).contains("jest")); + } + + #[test] + fn markdown_escapes_names() { + let entries = vec![entry("*evil*", Some("MIT"))]; + let out = render(&entries, &options(NoticeFormat::Markdown)); + assert!(out.starts_with("# Third-party notices — Pump")); + assert!(out.contains("- \\*evil\\* 1.0")); + assert!(out.contains("")); + } +} diff --git a/compliance-core/src/models/license.rs b/compliance-core/src/models/license.rs index 4925ad2..8a8de4d 100644 --- a/compliance-core/src/models/license.rs +++ b/compliance-core/src/models/license.rs @@ -158,6 +158,10 @@ pub struct LicenseConclusion { #[serde(default)] pub support: bool, pub at: DateTime, + /// The legal review of this licence, if one was made. Saving the + /// licence again drops it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub review: Option, } /// The most text a field takes; a licence text may be longer. @@ -373,6 +377,7 @@ mod tests { by_name: None, support: false, at: Utc::now(), + review: None, } } diff --git a/compliance-core/src/models/license_policy.rs b/compliance-core/src/models/license_policy.rs new file mode 100644 index 0000000..a6abb13 --- /dev/null +++ b/compliance-core/src/models/license_policy.rs @@ -0,0 +1,701 @@ +//! A workspace's licence policy and what it says about each component. +//! +//! The policy names, per [`LicenseCategory`], what a licence of that category +//! needs when the component is shipped and when it is only used to build: +//! nothing ([`PolicyAction::Allow`]), a legal review ([`PolicyAction::Review`]) +//! or that it may not be used ([`PolicyAction::Forbid`]). Single licences can +//! be ruled on their own (`GPL-3.0-only` forbidden, `LicenseRef-Pump-EULA` +//! allowed). A review is resolved by a person with the LEGAL role approving +//! the component's licence ([`LegalReview`]); a forbidden licence is not. +//! +//! The default forbids nothing: every copyleft, bought or unknown licence of +//! a shipped component asks for a review, so the workspace decides. A hint +//! for reviewing components, not legal advice. + +use chrono::{DateTime, NaiveDate, Utc}; +use serde::{Deserialize, Serialize}; + +use super::license::{LicenseCategory, LicenseConclusion, LicenseUsage}; +use super::SbomEntry; +use crate::spdx_license; + +/// The id of a workspace's one policy document. +pub const POLICY_ID: &str = "policy"; + +/// The most single-licence rules a policy holds. +pub const MAX_LICENSE_RULES: usize = 200; + +/// The most days ahead a bought licence's end is announced. +pub const MAX_EXPIRY_WARNING_DAYS: u32 = 365; + +/// What a licence needs before the component may be used. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PolicyAction { + /// May be used. + Allow, + /// May be used once a person with the LEGAL role approved it. + Review, + /// May not be used. + Forbid, +} + +impl PolicyAction { + /// The stored name (`review`). + pub fn as_str(self) -> &'static str { + match self { + Self::Allow => "allow", + Self::Review => "review", + Self::Forbid => "forbid", + } + } +} + +/// What a category of licence needs, shipped and build-only. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct CategoryRule { + pub category: LicenseCategory, + /// For a component in what is delivered. + pub shipped: PolicyAction, + /// For a component only used to build, test or develop. + pub build_only: PolicyAction, +} + +/// What one licence needs, whatever its category says. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LicenseRule { + /// An SPDX licence id (`GPL-3.0-only`) or a `LicenseRef-` id. + pub license: String, + pub action: PolicyAction, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +/// A workspace's licence policy. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicensePolicy { + /// Always [`POLICY_ID`]: one policy per workspace. + #[serde(rename = "_id", default = "policy_id")] + pub id: String, + /// One rule per category; a category missing here follows [`Self::default`]. + pub categories: Vec, + /// Rules for single licences, before the categories. + #[serde(default)] + pub licenses: Vec, + /// How many days before a bought licence ends it is announced. + #[serde(default = "default_expiry_warning_days")] + pub expiry_warning_days: u32, + /// Who changed it last (Keycloak user id), with the name the workspace reads. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_by: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_by_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_at: Option>, +} + +fn policy_id() -> String { + POLICY_ID.to_string() +} + +fn default_expiry_warning_days() -> u32 { + 60 +} + +impl Default for LicensePolicy { + fn default() -> Self { + use LicenseCategory as C; + use PolicyAction::{Allow, Review}; + let rule = |category, shipped, build_only| CategoryRule { + category, + shipped, + build_only, + }; + Self { + id: policy_id(), + categories: vec![ + rule(C::Permissive, Allow, Allow), + rule(C::PublicDomain, Allow, Allow), + rule(C::OwnCode, Allow, Allow), + rule(C::WeakCopyleft, Review, Allow), + rule(C::StrongCopyleft, Review, Allow), + rule(C::NetworkCopyleft, Review, Review), + rule(C::Proprietary, Review, Allow), + rule(C::Unclear, Review, Review), + ], + licenses: Vec::new(), + expiry_warning_days: default_expiry_warning_days(), + updated_by: None, + updated_by_name: None, + updated_at: None, + } + } +} + +impl LicensePolicy { + /// The rule of `category`: the policy's own, else the default one. + pub fn category_rule(&self, category: LicenseCategory) -> CategoryRule { + self.categories + .iter() + .find(|r| r.category == category) + .copied() + .or_else(|| { + Self::default() + .categories + .into_iter() + .find(|r| r.category == category) + }) + .unwrap_or(CategoryRule { + category, + shipped: PolicyAction::Review, + build_only: PolicyAction::Review, + }) + } + + /// The rule for the licence `id`, if the policy has one. + pub fn license_rule(&self, id: &str) -> Option<&LicenseRule> { + self.licenses + .iter() + .find(|r| r.license.eq_ignore_ascii_case(id)) + } + + /// The policy with one rule for every category, in picker order, and the + /// licence rules trimmed and normalised to SPDX ids. + /// + /// # Errors + /// + /// Why it cannot be stored: a licence rule that is no SPDX id or + /// `LicenseRef-`, a licence ruled twice, too many rules, a warning period + /// beyond a year. + pub fn normalised(mut self) -> Result { + let mut categories = Vec::with_capacity(LicenseCategory::ALL.len()); + for category in LicenseCategory::ALL { + categories.push(self.category_rule(category)); + } + self.categories = categories; + if self.licenses.len() > MAX_LICENSE_RULES { + return Err(format!("at most {MAX_LICENSE_RULES} licence rules")); + } + let mut licenses: Vec = Vec::with_capacity(self.licenses.len()); + for rule in self.licenses { + let raw = rule.license.trim(); + let id = if super::license::is_license_ref(raw) { + raw.to_string() + } else { + match spdx_license::canonical_id(raw) { + Some(id) => id.to_string(), + None => return Err(format!("not an SPDX licence id or LicenseRef: {raw}")), + } + }; + if licenses.iter().any(|r| r.license.eq_ignore_ascii_case(&id)) { + return Err(format!("{id} is ruled twice")); + } + let note = rule + .note + .map(|n| n.trim().to_string()) + .filter(|n| !n.is_empty()); + if note + .as_deref() + .is_some_and(|n| n.chars().count() > super::license::MAX_FIELD_CHARS) + { + return Err("rule note too long".into()); + } + licenses.push(LicenseRule { + license: id, + action: rule.action, + note, + }); + } + self.licenses = licenses; + if self.expiry_warning_days > MAX_EXPIRY_WARNING_DAYS { + return Err(format!( + "a bought licence is announced at most {MAX_EXPIRY_WARNING_DAYS} days ahead" + )); + } + self.id = policy_id(); + Ok(self) + } +} + +/// A legal decision about a component's licence. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewDecision { + /// The licence may be used as confirmed. + Approved, + /// The licence may not be used as confirmed. + Rejected, +} + +impl ReviewDecision { + /// The stored name (`approved`). + pub fn as_str(self) -> &'static str { + match self { + Self::Approved => "approved", + Self::Rejected => "rejected", + } + } +} + +/// A legal review of a confirmed licence. Saving the licence again (a change) +/// drops it: the review was of what was confirmed before. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LegalReview { + pub decision: ReviewDecision, + /// Who decided (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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, + pub at: DateTime, +} + +/// Why a component got its verdict. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum VerdictReason { + /// The rule of the licence's category. + Category { + category: LicenseCategory, + shipped: bool, + action: PolicyAction, + }, + /// The policy's rule for one licence of it. + License { + license: String, + action: PolicyAction, + }, + /// No licence is known for it. + Unknown, + /// The bought licence ended. + Expired { valid_until: NaiveDate }, + /// The bought licence ends soon. + ExpiresSoon { valid_until: NaiveDate }, + /// LEGAL approved it. + Approved, + /// LEGAL rejected it. + Rejected, +} + +/// What the policy says about one component. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LicenseVerdict { + /// What it needs, after a legal review is taken into account. + pub action: PolicyAction, + /// What the policy alone asks for. + pub required: PolicyAction, + /// Shipped (the default) or only used to build. + pub shipped: bool, + pub reasons: Vec, +} + +impl LicenseVerdict { + /// Whether it still needs a decision or may not be used. + pub fn is_open(&self) -> bool { + self.action != PolicyAction::Allow + } +} + +/// Whether `entry` is shipped: unless a person said it is only used to build. +pub fn is_shipped(concluded: Option<&LicenseConclusion>) -> bool { + !matches!( + concluded.and_then(|c| c.usage), + Some(LicenseUsage::BuildOnly) + ) +} + +/// The terms of an SPDX expression (ids, without `WITH` exceptions) and +/// whether they are joined by `AND`; `None` for text that is no expression. +fn terms(expression: &str) -> Option<(Vec, bool)> { + let normalised = spdx_license::normalise(expression); + let tokens: Vec<&str> = normalised + .split(|c: char| c.is_whitespace() || c == '(' || c == ')') + .filter(|t| !t.is_empty()) + .collect(); + // SPDX ids and `LicenseRef-`s, joined by operators. + let readable = !tokens.is_empty() + && tokens.iter().all(|t| { + matches!(*t, "AND" | "OR" | "WITH") + || super::license::is_license_ref(t) + || spdx_license::canonical_id(t.trim_end_matches('+')).is_some() + }); + if !readable { + return None; + } + let mut out = Vec::new(); + let mut after_with = false; + let mut and = false; + for token in tokens { + match token { + "WITH" => after_with = true, + "AND" => { + and = true; + after_with = false; + } + "OR" => after_with = false, + id if !after_with => out.push(id.trim_end_matches('+').to_string()), + _ => {} + } + } + Some((out, and)) +} + +/// What `policy` says about `entry` on `today`, with its confirmed licence +/// attached ([`super::license::apply`]). +pub fn evaluate(entry: &SbomEntry, policy: &LicensePolicy, today: NaiveDate) -> LicenseVerdict { + let concluded = entry.concluded.as_ref(); + let shipped = is_shipped(concluded); + let pick = |rule: CategoryRule| { + if shipped { + rule.shipped + } else { + rule.build_only + } + }; + let mut reasons = Vec::new(); + let expression = match concluded { + Some(c) => Some(c.license.as_str()), + None => entry + .license + .as_deref() + .map(str::trim) + .filter(|l| !l.is_empty()), + }; + let mut required = match expression.and_then(terms) { + None => { + // No licence, or text SPDX cannot read: the category a person + // gave, else unclear. + let category = concluded.map_or(LicenseCategory::Unclear, |c| c.category); + if expression.is_none() { + reasons.push(VerdictReason::Unknown); + } + let action = pick(policy.category_rule(category)); + reasons.push(VerdictReason::Category { + category, + shipped, + action, + }); + action + } + Some((ids, and)) => { + let mut actions = Vec::with_capacity(ids.len()); + for id in &ids { + if let Some(rule) = policy.license_rule(id) { + reasons.push(VerdictReason::License { + license: rule.license.clone(), + action: rule.action, + }); + actions.push(rule.action); + continue; + } + // A licence SPDX does not list takes the category a person + // gave it; an SPDX one its own. + let category = match concluded { + Some(c) if id.starts_with("LicenseRef-") || ids.len() == 1 => { + if c.category == LicenseCategory::Unclear { + spdx_license::category(id) + } else { + c.category + } + } + _ => spdx_license::category(id), + }; + let action = pick(policy.category_rule(category)); + let reason = VerdictReason::Category { + category, + shipped, + action, + }; + if !reasons.contains(&reason) { + reasons.push(reason); + } + actions.push(action); + } + // `AND`: every licence binds, the strictest counts. `OR`: the + // workspace may pick, the least strict counts. + let combined = if and { + actions.iter().copied().max() + } else { + actions.iter().copied().min() + }; + combined.unwrap_or(PolicyAction::Review) + } + }; + if let Some(until) = concluded.and_then(|c| c.valid_until) { + if until < today { + reasons.push(VerdictReason::Expired { valid_until: until }); + required = PolicyAction::Forbid; + } else if (until - today).num_days() <= i64::from(policy.expiry_warning_days) { + reasons.push(VerdictReason::ExpiresSoon { valid_until: until }); + } + } + let mut action = required; + match concluded + .and_then(|c| c.review.as_ref()) + .map(|r| r.decision) + { + Some(ReviewDecision::Approved) => { + reasons.push(VerdictReason::Approved); + if action == PolicyAction::Review { + action = PolicyAction::Allow; + } + } + Some(ReviewDecision::Rejected) => { + reasons.push(VerdictReason::Rejected); + action = PolicyAction::Forbid; + } + None => {} + } + LicenseVerdict { + action, + required, + shipped, + reasons, + } +} + +/// How many components need what, for a summary. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct VerdictCounts { + pub allowed: u64, + pub review: u64, + pub forbidden: u64, + /// Allowed because LEGAL approved them. + pub approved: u64, + /// Bought licences that end within the warning period. + pub expiring: u64, +} + +impl VerdictCounts { + /// Count `verdict` in. + pub fn add(&mut self, verdict: &LicenseVerdict) { + match verdict.action { + PolicyAction::Allow => self.allowed += 1, + PolicyAction::Review => self.review += 1, + PolicyAction::Forbid => self.forbidden += 1, + } + if verdict.action == PolicyAction::Allow && verdict.required == PolicyAction::Review { + self.approved += 1; + } + if verdict + .reasons + .iter() + .any(|r| matches!(r, VerdictReason::ExpiresSoon { .. })) + { + self.expiring += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::license::{conclusion_id, package_key}; + + fn today() -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 10, 15).unwrap_or_default() + } + + fn entry(license: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new("r".into(), "lib".into(), "1.0".into(), "npm".into()); + e.license = license.map(String::from); + e + } + + fn concluded(license: &str, category: LicenseCategory) -> LicenseConclusion { + let key = package_key("lib", "npm", None); + LicenseConclusion { + id: conclusion_id(&key, None), + package_key: key, + name: "lib".into(), + package_manager: "npm".into(), + version: None, + license: license.into(), + license_name: None, + category, + 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: Utc::now(), + review: None, + } + } + + fn review(decision: ReviewDecision) -> LegalReview { + LegalReview { + decision, + by: "legal".into(), + by_name: None, + support: false, + note: None, + at: Utc::now(), + } + } + + #[test] + fn the_default_allows_permissive_and_reviews_copyleft_when_shipped() { + let p = LicensePolicy::default(); + assert_eq!( + evaluate(&entry(Some("MIT")), &p, today()).action, + PolicyAction::Allow + ); + assert_eq!( + evaluate(&entry(Some("GPL-3.0-only")), &p, today()).action, + PolicyAction::Review + ); + let unknown = evaluate(&entry(None), &p, today()); + assert_eq!(unknown.action, PolicyAction::Review); + assert!(unknown.reasons.contains(&VerdictReason::Unknown)); + } + + #[test] + fn build_only_follows_the_build_rule() { + let p = LicensePolicy::default(); + let mut e = entry(Some("GPL-3.0-only")); + let mut c = concluded("GPL-3.0-only", LicenseCategory::StrongCopyleft); + c.usage = Some(LicenseUsage::BuildOnly); + e.concluded = Some(c); + let v = evaluate(&e, &p, today()); + assert!(!v.shipped); + assert_eq!(v.action, PolicyAction::Allow); + } + + #[test] + fn or_takes_the_least_and_and_the_most_strict() { + let mut p = LicensePolicy::default(); + p.licenses.push(LicenseRule { + license: "GPL-3.0-only".into(), + action: PolicyAction::Forbid, + note: None, + }); + assert_eq!( + evaluate(&entry(Some("MIT OR GPL-3.0-only")), &p, today()).action, + PolicyAction::Allow + ); + assert_eq!( + evaluate(&entry(Some("MIT AND GPL-3.0-only")), &p, today()).action, + PolicyAction::Forbid + ); + } + + #[test] + fn a_licence_rule_beats_its_category() { + let mut p = LicensePolicy::default(); + p.licenses.push(LicenseRule { + license: "LGPL-2.1-only".into(), + action: PolicyAction::Allow, + note: None, + }); + let v = evaluate(&entry(Some("LGPL-2.1-only")), &p, today()); + assert_eq!(v.action, PolicyAction::Allow); + assert!(matches!(v.reasons[0], VerdictReason::License { .. })); + } + + #[test] + fn a_custom_licence_takes_the_category_a_person_gave() { + let p = LicensePolicy::default(); + let mut e = entry(None); + e.concluded = Some(concluded("LicenseRef-Own", LicenseCategory::OwnCode)); + assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Allow); + e.concluded = Some(concluded("LicenseRef-Eula", LicenseCategory::Proprietary)); + assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Review); + } + + #[test] + fn approval_resolves_a_review_but_not_a_ban() { + let mut p = LicensePolicy::default(); + let mut e = entry(None); + let mut c = concluded("GPL-2.0-only", LicenseCategory::StrongCopyleft); + c.review = Some(review(ReviewDecision::Approved)); + e.concluded = Some(c.clone()); + let v = evaluate(&e, &p, today()); + assert_eq!( + (v.required, v.action), + (PolicyAction::Review, PolicyAction::Allow) + ); + let mut counts = VerdictCounts::default(); + counts.add(&v); + assert_eq!((counts.allowed, counts.approved), (1, 1)); + + p.licenses.push(LicenseRule { + license: "GPL-2.0-only".into(), + action: PolicyAction::Forbid, + note: None, + }); + assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Forbid); + + c.review = Some(review(ReviewDecision::Rejected)); + e.concluded = Some(c); + assert_eq!( + evaluate(&e, &LicensePolicy::default(), today()).action, + PolicyAction::Forbid + ); + } + + #[test] + fn an_ended_licence_is_forbidden_and_an_ending_one_announced() { + let p = LicensePolicy::default(); + let mut e = entry(None); + let mut c = concluded("LicenseRef-Eula", LicenseCategory::Proprietary); + c.valid_until = NaiveDate::from_ymd_opt(2026, 10, 1); + c.review = Some(review(ReviewDecision::Approved)); + e.concluded = Some(c.clone()); + assert_eq!(evaluate(&e, &p, today()).action, PolicyAction::Forbid); + c.valid_until = NaiveDate::from_ymd_opt(2026, 11, 1); + e.concluded = Some(c); + let v = evaluate(&e, &p, today()); + assert_eq!(v.action, PolicyAction::Allow); + assert!(v + .reasons + .iter() + .any(|r| matches!(r, VerdictReason::ExpiresSoon { .. }))); + } + + #[test] + fn normalising_fills_every_category_and_checks_licence_ids() { + let p = LicensePolicy { + categories: vec![CategoryRule { + category: LicenseCategory::Permissive, + shipped: PolicyAction::Review, + build_only: PolicyAction::Allow, + }], + licenses: vec![LicenseRule { + license: " gpl-3.0-only ".into(), + action: PolicyAction::Forbid, + note: Some(" ".into()), + }], + ..LicensePolicy::default() + } + .normalised() + .unwrap_or_default(); + assert_eq!(p.categories.len(), LicenseCategory::ALL.len()); + assert_eq!( + p.category_rule(LicenseCategory::Permissive).shipped, + PolicyAction::Review + ); + assert_eq!(p.licenses[0].license, "GPL-3.0-only"); + assert_eq!(p.licenses[0].note, None); + + let bad = LicensePolicy { + licenses: vec![LicenseRule { + license: "Some EULA".into(), + action: PolicyAction::Forbid, + note: None, + }], + ..LicensePolicy::default() + }; + assert!(bad.normalised().is_err()); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 280ea83..7ca036a 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -9,6 +9,7 @@ pub mod git_source; pub mod graph; pub mod issue; pub mod license; +pub mod license_policy; pub mod mcp; pub mod mcp_token; pub mod notification; @@ -47,6 +48,9 @@ pub use graph::{ }; pub use issue::{IssueStatus, TrackerIssue, TrackerType}; pub use license::{LicenseCategory, LicenseConclusion, LicenseUsage}; +pub use license_policy::{ + LegalReview, LicensePolicy, LicenseVerdict, PolicyAction, ReviewDecision, +}; 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 db1c720..ade95ca 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -124,6 +124,11 @@ pub struct SbomEntry { /// rewrites the components, so it is attached when they are read. #[serde(default, skip_serializing_if = "Option::is_none")] pub concluded: Option, + /// What the workspace's licence policy says about it + /// ([`super::license_policy::evaluate`]). Never stored: worked out when + /// the list is read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub policy: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -167,6 +172,7 @@ impl SbomEntry { cpe: None, in_image: None, concluded: None, + policy: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index cd57dad..83adcc1 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -113,6 +113,17 @@ fn conclusion_properties(entry: &SbomEntry, c: &LicenseConclusion) -> Vec serde_json::Value { package["copyrightText"] = serde_json::Value::String(c.copyright.join("\n")); } let by = c.by_name.as_deref().unwrap_or(&c.by); - let note = format!( + let mut note = format!( "Concluded by {by} on {} ({})", c.at.format("%Y-%m-%d"), c.category.as_str() ); + if let Some(review) = &c.review { + note.push_str(&format!( + "; legal review: {} by {} on {}", + review.decision.as_str(), + review.by_name.as_deref().unwrap_or(&review.by), + review.at.format("%Y-%m-%d") + )); + } package["licenseComments"] = serde_json::Value::String( match package["licenseComments"].as_str() { Some(declared) => format!("{declared}. {note}"), @@ -711,6 +730,7 @@ mod tests { by_name: Some("Erika Muster".into()), support: false, at: chrono::Utc::now(), + review: None, } } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index b7d8c44..8aada7a 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -5896,3 +5896,150 @@ input[type="file"] { grid-template-columns: 1fr; } } + +/* ── Licence check, legal review and policy ── */ +.license-check-card { + margin-bottom: 16px; +} + +.license-check-head { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 16px; + flex-wrap: wrap; + margin-bottom: 10px; +} + +.license-check-head h3 { + margin-bottom: 4px; +} + +.license-check-hint { + font-size: 13px; + color: var(--text-tertiary); + margin: 0 0 8px; + max-width: 640px; +} + +.license-check-buttons { + display: flex; + gap: 8px; +} + +.license-check-summary { + margin: 4px 0 12px; +} + +.license-expiring-count { + font-size: 12px; + color: var(--warning, #b7791f); +} + +.license-check-clear { + color: var(--text-secondary); +} + +.license-check-table td { + vertical-align: middle; +} + +.license-check-version { + color: var(--text-tertiary); + font-size: 12px; +} + +.license-check-why { + font-size: 12px; + color: var(--text-secondary); + max-width: 320px; +} + +.license-check-actions { + white-space: nowrap; +} + +.license-check-actions .btn + .btn { + margin-left: 6px; +} + +.license-policy-badge { + cursor: help; +} + +.modal-dialog.license-review-dialog { + max-width: 520px; +} + +.license-review-names { + font-size: 13px; + color: var(--text-secondary); + word-break: break-word; +} + +.modal-dialog.license-policy-dialog { + max-width: 560px; + max-height: calc(100vh - 48px); + overflow-y: auto; +} + +.license-policy-table { + width: 100%; + margin-bottom: 12px; +} + +.license-policy-table td, +.license-policy-table th { + padding: 6px 8px; +} + +.license-policy-select { + padding: 4px 6px; + border-radius: var(--radius-sm); + border: 1px solid var(--border-bright); + font-size: 13px; +} + +.license-policy-sub { + margin: 12px 0 2px; +} + +.license-policy-rule { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 6px; +} + +.license-policy-rule code { + min-width: 160px; +} + +.license-policy-rule input { + flex: 1; + min-width: 0; +} + +.license-policy-days { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px; + font-size: 13px; +} + +.license-policy-days input { + width: 80px; +} + +.license-policy-allow { + border-left: 3px solid var(--success, #2f855a); +} + +.license-policy-review { + border-left: 3px solid var(--warning); +} + +.license-policy-forbid { + border-left: 3px solid var(--danger); +} diff --git a/compliance-dashboard/src/components/license_review.rs b/compliance-dashboard/src/components/license_review.rs new file mode 100644 index 0000000..4466146 --- /dev/null +++ b/compliance-dashboard/src/components/license_review.rs @@ -0,0 +1,743 @@ +//! The licence check on the SBOM's licence tab: what the workspace's licence +//! policy says about its components, the legal review that approves or +//! rejects what the policy asks a review for, the policy itself, and the +//! third-party notices download. +//! +//! Who may decide (LEGAL, IT_ADMIN, support) is the agent's answer +//! (`may_decide`), so the buttons match what the agent accepts. + +use dioxus::prelude::*; + +use compliance_core::models::license_policy::{ + CategoryRule, LicenseRule, PolicyAction, ReviewDecision, VerdictReason, +}; +use compliance_core::models::{LegalReview, LicenseCategory, LicensePolicy, LicenseVerdict}; + +use crate::components::license_editor::category_class; +use crate::components::toast::{ToastType, Toasts}; +use crate::i18n::texts::{common, license_edit as lx, license_review as tx}; +use crate::i18n::{use_lang, Lang}; +use crate::infrastructure::sbom::{ + fetch_license_check, fetch_third_party_notices, save_license_policy, save_license_review, + withdraw_license_review, LicenseCheckItem, LicenseTarget, ReviewDraft, +}; + +/// The badge class of a policy action. +pub fn action_class(action: PolicyAction) -> &'static str { + match action { + PolicyAction::Allow => "badge badge-success", + PolicyAction::Review => "badge badge-medium", + PolicyAction::Forbid => "badge badge-critical", + } +} + +/// "freigegeben von Erika Muster am 2026-10-15". +pub fn review_title(review: &LegalReview, lang: Lang) -> String { + let decision = match review.decision { + ReviewDecision::Approved => tx::APPROVED.get(lang), + ReviewDecision::Rejected => tx::REJECTED.get(lang), + }; + let mut title = tx::REVIEWED_BY + .get(lang) + .replace("{decision}", decision) + .replace("{by}", review.by_name.as_deref().unwrap_or(&review.by)) + .replace("{at}", &review.at.format("%Y-%m-%d").to_string()); + if let Some(note) = review.note.as_deref() { + title.push_str(": "); + title.push_str(note); + } + title +} + +/// The reasons of a verdict in words, joined. +pub fn reasons_text(verdict: &LicenseVerdict, lang: Lang) -> String { + let mut parts: Vec = Vec::new(); + for reason in &verdict.reasons { + let part = match reason { + VerdictReason::Category { + category, shipped, .. + } => format!( + "{} ({})", + lx::category(*category).get(lang), + if *shipped { + tx::SHIPPED.get(lang) + } else { + tx::BUILD_ONLY.get(lang) + } + ), + VerdictReason::License { license, .. } => { + tx::REASON_RULE.get(lang).replace("{license}", license) + } + VerdictReason::Unknown => tx::REASON_UNKNOWN.get(lang).to_string(), + VerdictReason::Expired { valid_until } => tx::EXPIRED + .get(lang) + .replace("{date}", &valid_until.to_string()), + VerdictReason::ExpiresSoon { valid_until } => tx::EXPIRES_SOON + .get(lang) + .replace("{date}", &valid_until.to_string()), + VerdictReason::Approved => tx::APPROVED.get(lang).to_string(), + VerdictReason::Rejected => tx::REASON_REJECTED.get(lang).to_string(), + }; + if !parts.contains(&part) { + parts.push(part); + } + } + parts.join(" · ") +} + +/// The licence check of `repo` (every target when empty). +#[component] +pub fn LicenseCheckPanel( + /// The target picked in the filter, or empty for all. + repo: String, + /// The name of the picked target, for the notices file. + repo_name: String, + /// Called after a decision or a policy change, so the page reloads. + on_changed: EventHandler<()>, +) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + // The page mounts the panel anew (`key`) when the target changes. + let repo_for_check = repo.clone(); + let check = use_resource(move || { + let repo = repo_for_check.clone(); + async move { fetch_license_check(Some(repo)).await } + }); + let mut selected = use_signal(Vec::::new); + // The components a decision is being made for, and which decision. + let mut deciding = use_signal(|| Option::<(Vec, ReviewDecision)>::None); + let mut policy_open = use_signal(|| false); + let mut notices_busy = use_signal(|| false); + + // Copies of the handles, so the closure only reads what it captures + // and can be called from every button. + let reload = move || { + let (mut selected, mut check) = (selected, check); + selected.set(Vec::new()); + check.restart(); + on_changed.call(()); + }; + + let body = match &*check.read() { + None => rsx! { p { class: "loading", {common::LOADING.get(lang)} } }, + Some(Err(_)) => rsx! { p { {tx::LOAD_FAILED.get(lang)} } }, + Some(Ok(resp)) => { + let data = resp.data.clone(); + let may = data.may_decide; + let counts = data.counts.clone(); + let summary = tx::SUMMARY + .get(lang) + .replace("{n}", &data.components.to_string()) + .replace("{allow}", &counts.allowed.to_string()) + .replace("{review}", &counts.review.to_string()) + .replace("{forbid}", &counts.forbidden.to_string()); + let open: Vec = data.items.clone(); + let reviewable: Vec = open + .iter() + .filter(|i| i.verdict.action == PolicyAction::Review) + .cloned() + .collect(); + let all_keys: Vec = reviewable.iter().map(LicenseCheckItem::key).collect(); + let picked: Vec = open + .iter() + .filter(|i| selected().contains(&i.key())) + .map(LicenseCheckItem::target) + .collect(); + let picked_count = picked.len(); + let all_checked = + !all_keys.is_empty() && all_keys.iter().all(|k| selected().contains(k)); + rsx! { + p { class: "license-check-summary", + strong { "{summary}" } + if counts.approved > 0 { + span { class: "license-confirmed-count", + {format!(" · {}", tx::APPROVED_COUNT.get(lang).replace("{n}", &counts.approved.to_string()))} + } + } + if counts.expiring > 0 { + span { class: "license-expiring-count", + {format!(" · {}", tx::EXPIRING_COUNT.get(lang).replace("{n}", &counts.expiring.to_string()))} + } + } + } + if open.is_empty() { + p { class: "license-check-clear", {tx::ALL_CLEAR.get(lang)} } + } else { + if may && picked_count > 0 { + div { class: "license-selection-bar", + button { + class: "btn btn-primary btn-sm", + onclick: move |_| deciding.set(Some((picked.clone(), ReviewDecision::Approved))), + {format!("{} ({})", tx::APPROVE_SELECTED.get(lang), picked_count)} + } + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| selected.set(Vec::new()), + {lx::CLEAR_SELECTION.get(lang)} + } + } + } + div { class: "table-wrapper", + table { class: "license-check-table", + thead { + tr { + if may { + th { + input { + r#type: "checkbox", + title: tx::APPROVE_SELECTED.get(lang), + checked: all_checked, + onchange: move |e: FormEvent| selected.set(if e.checked() { all_keys.clone() } else { Vec::new() }), + } + } + } + th { {tx::COMPONENT.get(lang)} } + th { {tx::LICENSE.get(lang)} } + th { {tx::STATUS.get(lang)} } + th { {tx::WHY.get(lang)} } + if may { th {} } + } + } + tbody { + for item in open.clone() { + { + let key = item.key(); + let row_key = key.clone(); + let checked = selected().contains(&key); + let target = item.target(); + let approve_target = target.clone(); + let reject_target = target.clone(); + let review = item.review.clone(); + let undo_id = item.conclusion_id.clone().filter(|_| review.is_some()); + let action = item.verdict.action; + let category = category_of(&item.verdict); + rsx! { + tr { key: "{row_key}", + if may { + td { + if action == PolicyAction::Review { + input { + r#type: "checkbox", + checked: checked, + onchange: move |e: FormEvent| { + let key = key.clone(); + selected.with_mut(|list| { + list.retain(|k| *k != key); + if e.checked() { + list.push(key); + } + }); + }, + } + } + } + } + td { + strong { "{item.name}" } + if !item.version.is_empty() { + span { class: "license-check-version", " {item.version}" } + } + } + td { + span { class: "sbom-license-badge {category_class(category)}", + {item.license.clone().unwrap_or_else(|| "—".to_string())} + } + } + td { + span { class: action_class(action), {tx::action(action).get(lang)} } + if let Some(r) = &review { + " " + span { + class: if r.decision == ReviewDecision::Approved { "badge badge-success" } else { "badge badge-high" }, + title: "{review_title(r, lang)}", + if r.decision == ReviewDecision::Approved { {tx::APPROVED.get(lang)} } else { {tx::REJECTED.get(lang)} } + } + } + } + td { class: "license-check-why", "{reasons_text(&item.verdict, lang)}" } + if may { + td { class: "license-check-actions", + if action == PolicyAction::Review { + button { + class: "btn btn-primary btn-sm", + onclick: move |_| deciding.set(Some((vec![approve_target.clone()], ReviewDecision::Approved))), + {tx::APPROVE.get(lang)} + } + } + if review.is_none() { + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| deciding.set(Some((vec![reject_target.clone()], ReviewDecision::Rejected))), + {tx::REJECT.get(lang)} + } + } + if let Some(id) = undo_id { + button { + class: "btn btn-ghost btn-sm", + onclick: move |_| { + let id = id.clone(); + spawn(async move { + match withdraw_license_review(id).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::REVIEW_WITHDRAWN.get(lang).to_string()); + reload(); + } + Err(e) => toasts.push(ToastType::Error, format!("{}: {e}", tx::REVIEW_FAILED.get(lang))), + } + }); + }, + {tx::UNDO.get(lang)} + } + } + } + } + } + } + } + } + } + } + } + if data.truncated { + p { class: "license-disclaimer", {tx::TRUNCATED.get(lang)} } + } + } + if policy_open() { + PolicyDialog { + policy: data.policy.clone(), + may_edit: may, + on_close: move |saved: bool| { + policy_open.set(false); + if saved { + reload(); + } + }, + } + } + } + } + }; + + let notices_repo = repo.clone(); + rsx! { + div { class: "card license-check-card", + div { class: "license-check-head", + div { + h3 { {tx::CHECK_TITLE.get(lang)} } + p { class: "license-check-hint", {tx::CHECK_HINT.get(lang)} } + } + div { class: "license-check-buttons", + button { + class: "btn btn-secondary btn-sm", + onclick: move |_| policy_open.set(true), + {tx::POLICY_BUTTON.get(lang)} + } + button { + class: "btn btn-secondary btn-sm", + title: tx::NOTICES_HINT.get(lang), + disabled: notices_repo.is_empty() || notices_busy(), + onclick: move |_| { + let repo = repo.clone(); + let name = repo_name.clone(); + notices_busy.set(true); + spawn(async move { + match fetch_third_party_notices(repo, "text".to_string()).await { + Ok(text) => { + let file = if name.is_empty() { + "THIRD-PARTY-NOTICES.txt".to_string() + } else { + format!("THIRD-PARTY-NOTICES-{}.txt", safe_file_part(&name)) + }; + crate::infrastructure::download::save_file(&text, &file, "text/plain"); + } + Err(e) => toasts.push(ToastType::Error, format!("{}: {e}", tx::NOTICES_FAILED.get(lang))), + } + notices_busy.set(false); + }); + }, + {tx::NOTICES_BUTTON.get(lang)} + } + } + } + {body} + } + if let Some((components, decision)) = deciding() { + ReviewDialog { + components, + decision, + on_close: move |saved: bool| { + deciding.set(None); + if saved { + reload(); + } + }, + } + } + } +} + +/// The category a verdict was judged by (the first one named), for colour. +fn category_of(verdict: &LicenseVerdict) -> LicenseCategory { + verdict + .reasons + .iter() + .find_map(|r| match r { + VerdictReason::Category { category, .. } => Some(*category), + _ => None, + }) + .unwrap_or(LicenseCategory::Unclear) +} + +/// `name` as part of a file name: letters, digits, `-`, `_`, `.`. +fn safe_file_part(name: &str) -> String { + name.chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') { + c + } else { + '-' + } + }) + .collect() +} + +/// The dialog of a legal decision on one or more components. +#[component] +fn ReviewDialog( + components: Vec, + decision: ReviewDecision, + on_close: EventHandler, +) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let mut note = use_signal(String::new); + let mut all_versions = use_signal(|| false); + let mut busy = use_signal(|| false); + let n = components.len().to_string(); + let heading = match decision { + ReviewDecision::Approved => tx::REVIEW_TITLE_APPROVE.get(lang).replace("{n}", &n), + ReviewDecision::Rejected => tx::REVIEW_TITLE_REJECT.get(lang).replace("{n}", &n), + }; + let names: Vec = components + .iter() + .take(8) + .map(|c| format!("{} {}", c.name, c.version).trim().to_string()) + .collect(); + let more = components.len().saturating_sub(names.len()); + let save = move |_: Event| { + let note = note().trim().to_string(); + let draft = ReviewDraft { + components: components.clone(), + all_versions: all_versions(), + decision, + note: (!note.is_empty()).then_some(note), + }; + busy.set(true); + spawn(async move { + match save_license_review(draft).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::REVIEW_SAVED.get(lang).to_string()); + on_close.call(true); + } + Err(e) => toasts.push( + ToastType::Error, + format!("{}: {e}", tx::REVIEW_FAILED.get(lang)), + ), + } + busy.set(false); + }); + }; + rsx! { + div { class: "modal-overlay", + onclick: move |_| if !busy() { on_close.call(false) }, + div { class: "modal-dialog license-review-dialog", + onclick: move |e| e.stop_propagation(), + h3 { "{heading}" } + p { class: "license-review-names", + "{names.join(\", \")}" + if more > 0 { " … +{more}" } + } + div { class: "form-fields license-form", + label { {tx::REVIEW_NOTE.get(lang)} + textarea { + rows: "2", + maxlength: "2000", + value: "{note}", + placeholder: tx::REVIEW_NOTE_HINT.get(lang), + 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::REVIEW_ALL_VERSIONS.get(lang)}" + } + } + p { class: "license-disclaimer", {tx::DISCLAIMER.get(lang)} } + div { class: "modal-actions", + button { + class: "btn btn-ghost", + disabled: busy(), + onclick: move |_| on_close.call(false), + {tx::CANCEL.get(lang)} + } + button { + class: if decision == ReviewDecision::Approved { "btn btn-primary" } else { "btn btn-danger" }, + disabled: busy(), + onclick: save, + if decision == ReviewDecision::Approved { {tx::APPROVE.get(lang)} } else { {tx::REJECT.get(lang)} } + } + } + } + } + } +} + +/// The three actions as a picker. +#[component] +fn ActionSelect( + value: PolicyAction, + disabled: bool, + on_change: EventHandler, +) -> Element { + let lang = use_lang()(); + rsx! { + select { + class: "license-policy-select license-policy-{value.as_str()}", + disabled: disabled, + onchange: move |e| { + let action = match e.value().as_str() { + "allow" => PolicyAction::Allow, + "forbid" => PolicyAction::Forbid, + _ => PolicyAction::Review, + }; + on_change.call(action); + }, + for a in [PolicyAction::Allow, PolicyAction::Review, PolicyAction::Forbid] { + option { value: a.as_str(), selected: a == value, {tx::action(a).get(lang)} } + } + } + } +} + +/// The licence policy: one row per kind of licence, shipped and build-only, +/// rules for single licences, and how early a bought licence's end shows. +#[component] +fn PolicyDialog(policy: LicensePolicy, may_edit: bool, on_close: EventHandler) -> Element { + let lang = use_lang()(); + let mut toasts = use_context::(); + let start = policy.clone(); + let mut rules = use_signal(|| { + LicenseCategory::ALL + .into_iter() + .map(|c| start.category_rule(c)) + .collect::>() + }); + let mut licences = use_signal(|| policy.licenses.clone()); + let mut days = use_signal(|| policy.expiry_warning_days.to_string()); + let mut new_id = use_signal(String::new); + let mut new_action = use_signal(|| PolicyAction::Forbid); + let mut busy = use_signal(|| false); + let changed = policy.updated_at.map(|at| { + tx::POLICY_CHANGED_BY + .get(lang) + .replace( + "{by}", + policy + .updated_by_name + .as_deref() + .or(policy.updated_by.as_deref()) + .unwrap_or("—"), + ) + .replace("{at}", &at.format("%Y-%m-%d").to_string()) + }); + let base = policy.clone(); + let save = move |_: Event| { + let draft = LicensePolicy { + categories: rules(), + licenses: licences(), + expiry_warning_days: days().trim().parse().unwrap_or(base.expiry_warning_days), + ..base.clone() + }; + busy.set(true); + spawn(async move { + match save_license_policy(draft).await { + Ok(()) => { + toasts.push(ToastType::Success, tx::POLICY_SAVED.get(lang).to_string()); + on_close.call(true); + } + Err(e) => toasts.push( + ToastType::Error, + format!("{}: {e}", tx::POLICY_FAILED.get(lang)), + ), + } + busy.set(false); + }); + }; + let locked = !may_edit || busy(); + rsx! { + div { class: "modal-overlay", + onclick: move |_| if !busy() { on_close.call(false) }, + div { class: "modal-dialog license-policy-dialog", + onclick: move |e| e.stop_propagation(), + h3 { {tx::POLICY_TITLE.get(lang)} } + p { class: "license-check-hint", + if may_edit { {tx::POLICY_HINT.get(lang)} } else { {tx::POLICY_READ_ONLY.get(lang)} } + } + table { class: "license-policy-table", + thead { + tr { + th { {tx::POLICY_CATEGORY.get(lang)} } + th { {tx::POLICY_SHIPPED.get(lang)} } + th { {tx::POLICY_BUILD.get(lang)} } + } + } + tbody { + for (i, rule) in rules().into_iter().enumerate() { + tr { key: "{rule.category.as_str()}", + td { + span { class: "sbom-license-badge {category_class(rule.category)}", + {lx::category(rule.category).get(lang)} + } + } + td { + ActionSelect { + value: rule.shipped, + disabled: locked, + on_change: move |a| rules.with_mut(|r| r[i].shipped = a), + } + } + td { + ActionSelect { + value: rule.build_only, + disabled: locked, + on_change: move |a| rules.with_mut(|r| r[i].build_only = a), + } + } + } + } + } + } + h4 { class: "license-policy-sub", {tx::POLICY_RULES.get(lang)} } + p { class: "license-check-hint", {tx::POLICY_RULES_HINT.get(lang)} } + for (i, rule) in licences().into_iter().enumerate() { + div { class: "license-policy-rule", key: "{rule.license}", + code { "{rule.license}" } + ActionSelect { + value: rule.action, + disabled: locked, + on_change: move |a| licences.with_mut(|l| l[i].action = a), + } + if may_edit { + button { + class: "btn btn-ghost btn-sm", + disabled: locked, + onclick: move |_| { licences.with_mut(|l| { l.remove(i); }); }, + {tx::POLICY_REMOVE_RULE.get(lang)} + } + } + } + } + if may_edit { + div { class: "license-policy-rule", + input { + value: "{new_id}", + list: "spdx-licenses-policy", + placeholder: tx::POLICY_RULE_ID.get(lang), + oninput: move |e| new_id.set(e.value()), + } + ActionSelect { + value: new_action(), + disabled: locked, + on_change: move |a| new_action.set(a), + } + button { + class: "btn btn-secondary btn-sm", + disabled: locked || new_id().trim().is_empty(), + onclick: move |_| { + let id = new_id().trim().to_string(); + licences.with_mut(|l| { + if !l.iter().any(|r| r.license.eq_ignore_ascii_case(&id)) { + l.push(LicenseRule { license: id, action: new_action(), note: None }); + } + }); + new_id.set(String::new()); + }, + {tx::POLICY_ADD_RULE.get(lang)} + } + } + } + label { class: "license-policy-days", + {tx::POLICY_EXPIRY.get(lang)} + input { + r#type: "number", + min: "0", + max: "365", + disabled: locked, + value: "{days}", + oninput: move |e| days.set(e.value()), + } + } + if let Some(changed) = changed { + p { class: "license-disclaimer", "{changed}" } + } + p { class: "license-disclaimer", {tx::DISCLAIMER.get(lang)} } + div { class: "modal-actions", + button { + class: "btn btn-ghost", + disabled: busy(), + onclick: move |_| on_close.call(false), + if may_edit { {tx::CANCEL.get(lang)} } else { {tx::CLOSE.get(lang)} } + } + if may_edit { + button { + class: "btn btn-primary", + disabled: busy(), + onclick: save, + {tx::SAVE.get(lang)} + } + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reasons_read_in_words_once_each() { + let verdict = LicenseVerdict { + action: PolicyAction::Review, + required: PolicyAction::Review, + shipped: true, + reasons: vec![ + VerdictReason::Category { + category: LicenseCategory::StrongCopyleft, + shipped: true, + action: PolicyAction::Review, + }, + VerdictReason::Category { + category: LicenseCategory::StrongCopyleft, + shipped: true, + action: PolicyAction::Review, + }, + VerdictReason::Unknown, + ], + }; + let text = reasons_text(&verdict, Lang::En); + assert_eq!(text.matches("shipped").count(), 1); + assert!(text.ends_with("no licence found")); + assert_eq!(category_of(&verdict), LicenseCategory::StrongCopyleft); + } + + #[test] + fn file_names_keep_only_safe_characters() { + assert_eq!(safe_file_part("Pump / Station 2"), "Pump---Station-2"); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 3fd26f0..39d1333 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -12,6 +12,7 @@ pub mod help_chat; pub mod lang_toggle; pub mod layer_pins; pub mod license_editor; +pub mod license_review; 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 65f5215..890d314 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -4005,3 +4005,259 @@ pub mod license_edit { } } } + +/// The licence policy, the licence check and the legal review. +pub mod license_review { + use super::Text; + use compliance_core::models::license_policy::PolicyAction; + + pub const CHECK_TITLE: Text = Text { + de: "Lizenzprüfung", + en: "Licence check", + }; + pub const CHECK_HINT: Text = Text { + de: "Was die Lizenzrichtlinie des Workspace zu jeder Komponente sagt. Zur Prüfung: die Rechtsabteilung (Rolle LEGAL) gibt frei oder lehnt ab.", + en: "What the workspace's licence policy says about each component. To review: legal (LEGAL role) approves or rejects.", + }; + pub const SUMMARY: Text = Text { + de: "{n} Komponenten: {allow} erlaubt · {review} zur Prüfung · {forbid} nicht erlaubt", + en: "{n} components: {allow} allowed · {review} to review · {forbid} not allowed", + }; + pub const APPROVED_COUNT: Text = Text { + de: "{n} freigegeben", + en: "{n} approved", + }; + pub const EXPIRING_COUNT: Text = Text { + de: "{n} Lizenzen laufen bald ab", + en: "{n} licences end soon", + }; + pub const ALL_CLEAR: Text = Text { + de: "Alle Komponenten entsprechen der Richtlinie.", + en: "Every component meets the policy.", + }; + pub const TRUNCATED: Text = Text { + de: "Nur die ersten Einträge werden angezeigt. Wählen Sie ein Ziel, um die Liste einzugrenzen.", + en: "Only the first entries are shown. Pick a target to narrow the list.", + }; + pub const LOAD_FAILED: Text = Text { + de: "Die Lizenzprüfung konnte nicht geladen werden.", + en: "The licence check could not be loaded.", + }; + pub const POLICY_BUTTON: Text = Text { + de: "Richtlinie", + en: "Policy", + }; + pub const NOTICES_BUTTON: Text = Text { + de: "Drittanbieter-Hinweise", + en: "Third-party notices", + }; + pub const NOTICES_HINT: Text = Text { + de: "Datei THIRD-PARTY-NOTICES mit allen ausgelieferten Komponenten, Copyright und Lizenzen. Wählen Sie zuerst ein Ziel.", + en: "THIRD-PARTY-NOTICES file with every shipped component, copyright and licence. Pick a target first.", + }; + pub const NOTICES_FAILED: Text = Text { + de: "Hinweise konnten nicht erstellt werden", + en: "Notices could not be created", + }; + pub const COMPONENT: Text = Text { + de: "Komponente", + en: "Component", + }; + pub const LICENSE: Text = Text { + de: "Lizenz", + en: "Licence", + }; + pub const STATUS: Text = Text { + de: "Status", + en: "Status", + }; + pub const WHY: Text = Text { + de: "Grund", + en: "Why", + }; + pub const APPROVE: Text = Text { + de: "Freigeben", + en: "Approve", + }; + pub const REJECT: Text = Text { + de: "Ablehnen", + en: "Reject", + }; + pub const UNDO: Text = Text { + de: "Entscheidung zurücknehmen", + en: "Withdraw decision", + }; + pub const APPROVE_SELECTED: Text = Text { + de: "Auswahl freigeben", + en: "Approve selection", + }; + pub const APPROVED: Text = Text { + de: "freigegeben", + en: "approved", + }; + pub const REJECTED: Text = Text { + de: "abgelehnt", + en: "rejected", + }; + pub const REVIEWED_BY: Text = Text { + de: "{decision} von {by} am {at}", + en: "{decision} by {by} on {at}", + }; + pub const ACTION_ALLOW: Text = Text { + de: "Erlaubt", + en: "Allowed", + }; + pub const ACTION_REVIEW: Text = Text { + de: "Zur Prüfung", + en: "To review", + }; + pub const ACTION_FORBID: Text = Text { + de: "Nicht erlaubt", + en: "Not allowed", + }; + pub const EXPIRES_SOON: Text = Text { + de: "läuft ab am {date}", + en: "ends on {date}", + }; + pub const EXPIRED: Text = Text { + de: "abgelaufen am {date}", + en: "ended on {date}", + }; + pub const REASON_UNKNOWN: Text = Text { + de: "keine Lizenz gefunden", + en: "no licence found", + }; + pub const REASON_RULE: Text = Text { + de: "Regel für {license}", + en: "rule for {license}", + }; + pub const REASON_REJECTED: Text = Text { + de: "in der Prüfung abgelehnt", + en: "rejected in the review", + }; + pub const SHIPPED: Text = Text { + de: "ausgeliefert", + en: "shipped", + }; + pub const BUILD_ONLY: Text = Text { + de: "nur Build", + en: "build only", + }; + pub const REVIEW_TITLE_APPROVE: Text = Text { + de: "{n} Komponenten freigeben", + en: "Approve {n} components", + }; + pub const REVIEW_TITLE_REJECT: Text = Text { + de: "{n} Komponenten ablehnen", + en: "Reject {n} components", + }; + pub const REVIEW_NOTE: Text = Text { + de: "Begründung (optional)", + en: "Reason (optional)", + }; + pub const REVIEW_NOTE_HINT: Text = Text { + de: "z. B. nur dynamisch gelinkt, Quelltext liegt bei", + en: "e.g. only linked dynamically, source code enclosed", + }; + pub const REVIEW_ALL_VERSIONS: Text = Text { + de: "Für alle Versionen dieser Pakete", + en: "For every version of these packages", + }; + pub const REVIEW_SAVED: Text = Text { + de: "Entscheidung gespeichert", + en: "Decision saved", + }; + pub const REVIEW_WITHDRAWN: Text = Text { + de: "Entscheidung zurückgenommen", + en: "Decision withdrawn", + }; + pub const REVIEW_FAILED: Text = Text { + de: "Entscheidung nicht gespeichert", + en: "Decision not saved", + }; + pub const POLICY_TITLE: Text = Text { + de: "Lizenzrichtlinie", + en: "Licence policy", + }; + pub const POLICY_HINT: Text = Text { + de: "Was eine Lizenz braucht, bevor die Komponente verwendet wird. Ändern dürfen LEGAL und IT_ADMIN.", + en: "What a licence needs before the component is used. LEGAL and IT_ADMIN may change it.", + }; + pub const POLICY_READ_ONLY: Text = Text { + de: "Nur LEGAL und IT_ADMIN können die Richtlinie ändern.", + en: "Only LEGAL and IT_ADMIN can change the policy.", + }; + pub const POLICY_CATEGORY: Text = Text { + de: "Art der Lizenz", + en: "Kind of licence", + }; + pub const POLICY_SHIPPED: Text = Text { + de: "Ausgeliefert", + en: "Shipped", + }; + pub const POLICY_BUILD: Text = Text { + de: "Nur zum Bauen", + en: "Build only", + }; + pub const POLICY_RULES: Text = Text { + de: "Einzelne Lizenzen", + en: "Single licences", + }; + pub const POLICY_RULES_HINT: Text = Text { + de: "Gilt vor der Art, z. B. AGPL-3.0-only nicht erlaubt.", + en: "Applies before the kind, e.g. AGPL-3.0-only not allowed.", + }; + pub const POLICY_ADD_RULE: Text = Text { + de: "Hinzufügen", + en: "Add", + }; + pub const POLICY_REMOVE_RULE: Text = Text { + de: "Entfernen", + en: "Remove", + }; + pub const POLICY_RULE_ID: Text = Text { + de: "SPDX-ID, z. B. GPL-3.0-only", + en: "SPDX id, e.g. GPL-3.0-only", + }; + pub const POLICY_EXPIRY: Text = Text { + de: "Gekaufte Lizenzen ankündigen, Tage vor Ablauf", + en: "Announce bought licences, days before they end", + }; + pub const POLICY_SAVED: Text = Text { + de: "Richtlinie gespeichert", + en: "Policy saved", + }; + pub const POLICY_FAILED: Text = Text { + de: "Richtlinie nicht gespeichert", + en: "Policy not saved", + }; + pub const POLICY_CHANGED_BY: Text = Text { + de: "Zuletzt geändert von {by} am {at}", + en: "Last changed by {by} on {at}", + }; + pub const SAVE: Text = Text { + de: "Speichern", + en: "Save", + }; + pub const CANCEL: Text = Text { + de: "Abbrechen", + en: "Cancel", + }; + pub const CLOSE: Text = Text { + de: "Schließen", + en: "Close", + }; + pub const DISCLAIMER: Text = Text { + de: "Eine Hilfe für die Prüfung, keine Rechtsberatung.", + en: "A help for the review, not legal advice.", + }; + + /// The name of a policy action. + pub fn action(a: PolicyAction) -> Text { + match a { + PolicyAction::Allow => ACTION_ALLOW, + PolicyAction::Review => ACTION_REVIEW, + PolicyAction::Forbid => ACTION_FORBID, + } + } +} diff --git a/compliance-dashboard/src/infrastructure/download.rs b/compliance-dashboard/src/infrastructure/download.rs index a6a2cb2..50bceed 100644 --- a/compliance-dashboard/src/infrastructure/download.rs +++ b/compliance-dashboard/src/infrastructure/download.rs @@ -1,8 +1,13 @@ //! Save text the page fetched as a file in the browser. /// Save `content` as the JSON file `filename`. -#[cfg(feature = "web")] pub fn save_json(content: &str, filename: &str) { + save_file(content, filename, "application/json"); +} + +/// Save `content` as the file `filename` of media type `mime`. +#[cfg(feature = "web")] +pub fn save_file(content: &str, filename: &str, mime: &str) { use wasm_bindgen::JsCast; let Some(window) = web_sys::window() else { return; @@ -15,7 +20,7 @@ pub fn save_json(content: &str, filename: &str) { blob_parts.push(&wasm_bindgen::JsValue::from_str(content)); let opts = web_sys::BlobPropertyBag::new(); - opts.set_type("application/json"); + opts.set_type(mime); let Ok(blob) = web_sys::Blob::new_with_str_sequence_and_options(&blob_parts, &opts) else { return; }; @@ -39,4 +44,4 @@ pub fn save_json(content: &str, filename: &str) { /// Server rendering: downloads only happen in the browser. #[cfg(not(feature = "web"))] -pub fn save_json(_content: &str, _filename: &str) {} +pub fn save_file(_content: &str, _filename: &str, _mime: &str) {} diff --git a/compliance-dashboard/src/infrastructure/sbom.rs b/compliance-dashboard/src/infrastructure/sbom.rs index 12c1508..653ac32 100644 --- a/compliance-dashboard/src/infrastructure/sbom.rs +++ b/compliance-dashboard/src/infrastructure/sbom.rs @@ -67,6 +67,9 @@ pub struct SbomEntryData { /// The licence a person of the workspace confirmed, where there is one. #[serde(default)] pub concluded: Option, + /// What the workspace's licence policy says about it. + #[serde(default)] + pub policy: Option, #[serde(default)] pub created_at: Option, #[serde(default)] @@ -104,6 +107,10 @@ pub struct LicenseTarget { pub package_manager: String, pub version: String, pub purl: Option, + /// The licence the scan found: what a legal review of a component + /// nobody confirmed a licence for approves. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub license: Option, } impl LicenseTarget { @@ -114,10 +121,87 @@ impl LicenseTarget { package_manager: entry.package_manager.clone(), version: entry.version.clone(), purl: entry.purl.clone(), + license: entry.license.clone(), } } } +/// A component the licence check lists: forbidden, to review, or with a +/// bought licence that ends soon. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicenseCheckItem { + pub repo_id: String, + pub name: String, + #[serde(default)] + pub version: String, + #[serde(default)] + pub package_manager: String, + #[serde(default)] + pub purl: Option, + /// The licence that counts: the confirmed one, else the detected one. + #[serde(default)] + pub license: Option, + /// The licence the scan found. + #[serde(default)] + pub detected: Option, + /// The id of the confirmed licence, if one was confirmed. + #[serde(default)] + pub conclusion_id: Option, + #[serde(default)] + pub review: Option, + pub verdict: compliance_core::models::LicenseVerdict, +} + +impl LicenseCheckItem { + /// The component, for a review. + pub fn target(&self) -> LicenseTarget { + LicenseTarget { + name: self.name.clone(), + package_manager: self.package_manager.clone(), + version: self.version.clone(), + purl: self.purl.clone(), + license: self.detected.clone(), + } + } + + /// A key unique in the list. + pub fn key(&self) -> String { + format!( + "{}|{}|{}|{}", + self.repo_id, self.package_manager, self.name, self.version + ) + } +} + +/// The licence check of a target, or of every target. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicenseCheckData { + pub counts: compliance_core::models::license_policy::VerdictCounts, + pub components: u64, + pub items: Vec, + #[serde(default)] + pub truncated: bool, + pub policy: compliance_core::models::LicensePolicy, + /// Whether the requester may decide reviews and change the policy. + #[serde(default)] + pub may_decide: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LicenseCheckResponse { + pub data: LicenseCheckData, +} + +/// A legal decision as the review dialog sends it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ReviewDraft { + pub components: Vec, + pub all_versions: bool, + pub decision: compliance_core::models::ReviewDecision, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, +} + /// 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)] @@ -289,6 +373,83 @@ pub async fn withdraw_license_conclusion(id: String) -> Result<(), ServerFnError super::agent_client::ok_or_error(resp).await } +/// What the licence policy says about the components of `repo_id` (all +/// targets when empty). +#[server] +pub async fn fetch_license_check( + repo_id: Option, +) -> Result { + let mut req = super::agent_client::agent_get("/api/v1/licenses/check").await?; + if let Some(r) = repo_id.filter(|r| !r.is_empty()) { + req = req.query(&[("repo_id", r)]); + } + let resp = req + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + +/// Store the workspace's licence policy. Refused (403) unless LEGAL or +/// IT_ADMIN; a licence rule SPDX cannot read is refused (422) with the reason. +#[server] +pub async fn save_license_policy( + policy: compliance_core::models::LicensePolicy, +) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request(reqwest::Method::PUT, "/api/v1/licenses/policy") + .await? + .json(&policy) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Approve or reject the licence of the draft's components. +#[server] +pub async fn save_license_review(draft: ReviewDraft) -> Result<(), ServerFnError> { + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/licenses/review") + .await? + .json(&draft) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// Withdraw the legal decision on the confirmed licence `id`. +#[server] +pub async fn withdraw_license_review(id: String) -> Result<(), ServerFnError> { + let resp = + super::agent_client::agent_request(reqwest::Method::DELETE, "/api/v1/licenses/review") + .await? + .query(&[("id", id.as_str())]) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await +} + +/// The third-party notices of `repo_id` as text (`text`) or markdown. +#[server] +pub async fn fetch_third_party_notices( + repo_id: String, + format: String, +) -> Result { + let resp = super::agent_client::agent_get("/api/v1/sbom/notices") + .await? + .query(&[("repo_id", repo_id), ("format", format)]) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + if !resp.status().is_success() { + return Err(ServerFnError::new(format!("HTTP {}", resp.status()))); + } + resp.text() + .await + .map_err(|e| ServerFnError::new(e.to_string())) +} + #[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 7acc802..677531f 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -2,13 +2,17 @@ use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER}; use dioxus::prelude::*; use crate::components::license_editor::{category_class, confirmed_title, LicenseEditor}; +use crate::components::license_review::{ + action_class, reasons_text, review_title, LicenseCheckPanel, +}; 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, license_edit as lx, sbom as tx}; +use crate::i18n::texts::{common, license_edit as lx, license_review as rx, sbom as tx}; use crate::i18n::{use_lang, Lang}; use crate::infrastructure::sbom::*; +use compliance_core::models::ReviewDecision; #[component] pub fn SbomPage(target: String) -> Element { @@ -412,6 +416,22 @@ pub fn SbomPage(target: String) -> Element { title: "{confirmed_title(c, lang)}", {lx::CONFIRMED.get(lang)} } + if let Some(r) = &c.review { + " " + span { + class: if r.decision == ReviewDecision::Approved { "badge badge-success" } else { "badge badge-high" }, + title: "{review_title(r, lang)}", + if r.decision == ReviewDecision::Approved { {rx::APPROVED.get(lang)} } else { {rx::REJECTED.get(lang)} } + } + } + } + if let Some(v) = entry.policy.as_ref().filter(|v| v.is_open()) { + " " + span { + class: "{action_class(v.action)} license-policy-badge", + title: "{reasons_text(v, lang)}", + {rx::action(v.action).get(lang)} + } } if can_write { " " @@ -556,6 +576,33 @@ pub fn SbomPage(target: String) -> Element { // ═══════════════ LICENSE COMPLIANCE TAB ═══════════════ if active_tab() == "licenses" { + { + let repo = repo_filter(); + let repo_name = match &*repos.read() { + Some(Some(resp)) => resp + .data + .iter() + .find(|r| { + r.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()) + == Some(repo.as_str()) + }) + .and_then(|r| r.get("name").and_then(|n| n.as_str())) + .unwrap_or_default() + .to_string(), + _ => String::new(), + }; + rsx! { + LicenseCheckPanel { + key: "{repo}", + repo: repo.clone(), + repo_name, + on_changed: move |_| { + license_data.restart(); + sbom.restart(); + }, + } + } + } match &*license_data.read() { Some(Some(resp)) => { let total_pkgs: u64 = resp.data.iter().map(|l| l.count).sum(); diff --git a/compliance-mcp/src/database.rs b/compliance-mcp/src/database.rs index bccb2b5..abda00a 100644 --- a/compliance-mcp/src/database.rs +++ b/compliance-mcp/src/database.rs @@ -132,6 +132,16 @@ impl Database { self.inner.collection("sbom_entries") } + /// Licences the workspace confirmed, merged into the components read. + pub fn license_conclusions(&self) -> Collection { + self.inner.collection("license_conclusions") + } + + /// The workspace's licence policy (one document). + pub fn license_policy(&self) -> Collection { + self.inner.collection("license_policy") + } + pub fn dast_findings(&self) -> Collection { self.inner.collection("dast_findings") } diff --git a/compliance-mcp/src/server.rs b/compliance-mcp/src/server.rs index 16cd0dc..8edd22c 100644 --- a/compliance-mcp/src/server.rs +++ b/compliance-mcp/src/server.rs @@ -145,6 +145,28 @@ impl ComplianceMcpServer { sbom::get_sbom(&db, params).await } + #[tool( + description = "Check a target's components against the workspace's licence policy: counts of allowed, to-review and forbidden components, and the open ones with their licence, legal review and reasons" + )] + async fn license_check( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + sbom::license_check(&db, params).await + } + + #[tool( + description = "Get a target's third-party notices (THIRD-PARTY-NOTICES): its shipped components grouped by licence, with copyright lines and licence texts or links, as text (default) or markdown" + )] + async fn get_third_party_notices( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + sbom::third_party_notices(&db, params).await + } + #[tool( description = "Generate a vulnerability report for a repository showing all packages with known CVEs" )] diff --git a/compliance-mcp/src/tools/sbom.rs b/compliance-mcp/src/tools/sbom.rs index 4aba763..c494e3a 100644 --- a/compliance-mcp/src/tools/sbom.rs +++ b/compliance-mcp/src/tools/sbom.rs @@ -3,6 +3,8 @@ use rmcp::{model::*, ErrorData as McpError}; use schemars::JsonSchema; use serde::Deserialize; +use compliance_core::models::SbomEntry; + use crate::database::Database; const MAX_LIMIT: i64 = 200; @@ -125,6 +127,9 @@ pub async fn list_sbom_packages( .map_err(|e| McpError::internal_error(format!("deserialize error: {e}"), None))?; results.push(entry); } + // The licences a person confirmed count, as in the dashboard. + let conclusions = load_conclusions(db).await?; + compliance_core::models::license::apply(&mut results, &conclusions); let json = serde_json::to_string_pretty(&results) .map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?; @@ -226,16 +231,179 @@ pub async fn get_sbom(db: &Database, params: GetSbomParams) -> Result compliance_core::sbom_docs::cyclonedx(&entries, ¶ms.target_id), SbomFormat::Spdx => compliance_core::sbom_docs::spdx(&entries, ¶ms.target_id), }; super::json_result(&document) } + +/// Every licence the workspace confirmed. +async fn load_conclusions( + db: &Database, +) -> Result, McpError> { + super::collect( + db.license_conclusions() + .find(doc! {}) + .limit(50_000) + .await + .map_err(super::db_error)?, + ) + .await +} + +/// The workspace's licence policy, the default one when it has none. +async fn load_policy(db: &Database) -> Result { + Ok(db + .license_policy() + .find_one(doc! { "_id": compliance_core::models::license_policy::POLICY_ID }) + .await + .map_err(super::db_error)? + .unwrap_or_default()) +} + +/// A target's components with their confirmed licences and policy verdicts. +async fn judged( + db: &Database, + target_id: &str, +) -> Result<(Vec, compliance_core::models::LicensePolicy), McpError> { + let filter = doc! { "repo_id": target_id }; + let count = db + .sbom_entries() + .count_documents(filter.clone()) + .await + .map_err(super::db_error)?; + if count > MAX_SBOM_COMPONENTS { + return Err(McpError::invalid_request( + format!("the SBOM has {count} components, more than one check reads"), + None, + )); + } + let mut entries: Vec = super::collect( + db.sbom_entries() + .find(filter) + .sort(doc! { "name": 1, "version": 1 }) + .await + .map_err(super::db_error)?, + ) + .await?; + compliance_core::models::license::apply(&mut entries, &load_conclusions(db).await?); + let policy = load_policy(db).await?; + let today = chrono::Utc::now().date_naive(); + for e in entries.iter_mut() { + e.policy = Some(compliance_core::models::license_policy::evaluate( + e, &policy, today, + )); + } + Ok((entries, policy)) +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct LicenseCheckParams { + /// The target id (as `list_targets` returns it). + pub target_id: String, +} + +/// The most open components `license_check` lists. +const MAX_CHECK_ITEMS: usize = 500; + +/// `license_check`: what the workspace's licence policy says about a +/// target's components: counts, and the components that are forbidden or +/// wait for a legal review, with their reasons. +pub async fn license_check( + db: &Database, + params: LicenseCheckParams, +) -> Result { + use compliance_core::models::license_policy::{PolicyAction, VerdictCounts}; + let (entries, policy) = judged(db, ¶ms.target_id).await?; + let mut counts = VerdictCounts::default(); + let mut open = Vec::new(); + for e in &entries { + let Some(verdict) = e.policy.as_ref() else { + continue; + }; + counts.add(verdict); + if verdict.action != PolicyAction::Allow && open.len() < MAX_CHECK_ITEMS { + open.push(serde_json::json!({ + "name": e.name, + "version": e.version, + "package_manager": e.package_manager, + "purl": e.purl, + "license": e.effective_license(), + "confirmed": e.concluded.is_some(), + "review": e.concluded.as_ref().and_then(|c| c.review.clone()), + "action": verdict.action, + "reasons": verdict.reasons, + })); + } + } + open.sort_by_key(|i| i["action"].as_str() != Some("forbid")); + super::json_result(&serde_json::json!({ + "target_id": params.target_id, + "components": entries.len(), + "counts": counts, + "open": open, + "policy": policy, + })) +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ThirdPartyNoticesParams { + /// The target id (as `list_targets` returns it). + pub target_id: String, + /// `text` (default) or `markdown`. + #[serde(default)] + pub format: NoticesFormat, + /// Also list components only used to build (default false). + #[serde(default)] + pub include_build_only: bool, +} + +/// The formats `get_third_party_notices` writes. +#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum NoticesFormat { + #[default] + Text, + Markdown, +} + +/// `get_third_party_notices`: the THIRD-PARTY-NOTICES file of a target. +pub async fn third_party_notices( + db: &Database, + params: ThirdPartyNoticesParams, +) -> Result { + use compliance_core::license_notices::{render, NoticeFormat, NoticeOptions}; + let (entries, _) = judged(db, ¶ms.target_id).await?; + let product = match mongodb::bson::oid::ObjectId::parse_str(¶ms.target_id) { + Ok(oid) => db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(super::db_error)? + .map(|t| t.name), + Err(_) => None, + } + .unwrap_or_else(|| format!("repo-{}", params.target_id)); + let text = render( + &entries, + &NoticeOptions { + product: &product, + format: match params.format { + NoticesFormat::Text => NoticeFormat::Text, + NoticesFormat::Markdown => NoticeFormat::Markdown, + }, + include_build_only: params.include_build_only, + }, + ); + Ok(CallToolResult::success(vec![Content::text(text)])) +} diff --git a/docs/features/mcp-server.md b/docs/features/mcp-server.md index 095a71d..b59c1b1 100644 --- a/docs/features/mcp-server.md +++ b/docs/features/mcp-server.md @@ -87,9 +87,11 @@ manifest of sha256 checksums) is also served as one ZIP at | Tool | Description | |------|-------------| -| `get_sbom` | A target's whole SBOM as one CycloneDX 1.6 (default) or SPDX 2.3 document, the same the API exports. | -| `list_sbom_packages` | List SBOM packages with filters for repository, vulnerabilities, package manager, and license. | +| `get_sbom` | A target's whole SBOM as one CycloneDX 1.6 (default) or SPDX 2.3 document, the same the API exports, with the licences the workspace confirmed. | +| `list_sbom_packages` | List SBOM packages with filters for repository, vulnerabilities, package manager, and license (the detected licence); each package carries its confirmed licence. | | `sbom_vuln_report` | Generate a vulnerability report for a repository showing all packages with known CVEs. | +| `license_check` | What the workspace's licence policy says about a target's components: how many are allowed, wait for a legal review or are forbidden, and the open ones with their reasons. | +| `get_third_party_notices` | A target's third-party notices (`THIRD-PARTY-NOTICES`) as text or markdown: shipped components by licence, with copyright and licence texts or links. | ### DAST Tools diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index aa89e58..80730f0 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -212,7 +212,8 @@ Copyleft-licensed dependencies can require you to release your source code under 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. +read the confirmations (LEGAL decides about them in the +[legal review](#license-policy-and-legal-review)). 1. On the **Lizenzen** tab, **Anzeigen und bearbeiten** next to the count of components without a known license lists exactly those (the filter @@ -242,6 +243,70 @@ package in other targets gets it too. The categories are guidance for reviewing your components, not legal advice. ::: +### License policy and legal review + +The **Lizenzprüfung** card at the top of the **Lizenzen** tab shows what +your workspace's license policy says about each component: how many are +allowed, **Zur Prüfung** (waiting for a legal review) or **Nicht erlaubt**, +and lists the open ones with the reason. The same badges appear next to the +license on the **Pakete** tab. + +**The policy.** **Richtlinie** opens it. For each kind of license (permissive, +weak or strong copyleft, network copyleft, proprietary, public domain, own +code, unclear) it says what a component needs when it is **shipped** with the +product and when it is only used **to build** it: *Erlaubt*, *Zur Prüfung* +or *Nicht erlaubt*. Under **Einzelne Lizenzen** you can rule single SPDX +licenses that apply before their kind (for example `AGPL-3.0-only` *Nicht +erlaubt*). A component counts as shipped unless its confirmed license says +*nur zum Bauen*. For a license expression, `AND` takes the strictest of its +licenses and `OR` the least strict, since you may choose. A bought license +whose **Gültig bis** has passed is not allowed; one that ends within the +announced period (60 days unless changed) is listed in advance. + +The default policy forbids nothing: copyleft, bought and unknown licenses +of shipped components need a review, everything else is allowed. Only the +LEGAL and IT_ADMIN roles can change the policy; everyone else can read it. + +**The review.** People with the **LEGAL** role (and IT_ADMIN) decide the +components *Zur Prüfung*: + +1. Click **Freigeben** in a row, or tick several rows and click + **Auswahl freigeben**; **Ablehnen** rejects a component. +2. Optionally give a reason (for example "only linked dynamically, source + code enclosed") and tick **Für alle Versionen dieser Pakete** to decide + for every version. + +An approved component counts as allowed and shows **freigegeben** (who, when +and the reason on hover); a rejected one counts as not allowed. An approval +resolves a review, never a license the policy forbids: that needs a policy +change. **Entscheidung zurücknehmen** withdraws a decision. Changing a +component's confirmed license drops its review, since the review was of the +license as it was. Where nobody confirmed a license yet, approving confirms +the license the scan found (an SPDX license), in your name; an unknown +license has to be confirmed first. + +**Findings.** Every scan with a complete SBOM reports each component that is +not allowed as a finding (*High*), and the components waiting for a review +as one finding per target (*Low*). They close themselves at the next scan +once the cause is gone. Policy changes and decisions show in the license +check at once, and in the findings with the next scan. + +### Third-party notices + +Products that ship third-party components usually have to name them with +their copyright and license. **Drittanbieter-Hinweise** on the license check +card (pick a target first) downloads `THIRD-PARTY-NOTICES.txt`: the shipped +components grouped by license, with the copyright lines you confirmed, a link +to the license text on spdx.org, and the full text of your own licenses. +Components without a known license are listed at the end, so you can see what +is missing. The evidence pack contains the same file, together with +`license-check.json`, the license check on the day the pack was made. + +Through the API (`GET /api/v1/sbom/notices?repo_id=`) the notices are +also available as markdown (`format=markdown`) and with the build-only +components (`build_only=true`); an API key needs the `pruefwerk:sbom.read` +scope. + ## Export 1. On the **Pakete** tab, select a target under **Alle Prüfobjekte**. Export