Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed71ced9b3 | ||
|
|
41c337138d | ||
|
|
e65aa76ef5 | ||
|
|
70125b4556 | ||
|
|
43d8ff1589 | ||
|
|
5ce496303d | ||
|
|
a84681918b | ||
|
|
07ba0d6665 | ||
|
|
171ff9a9f8 |
No files matched your search
@@ -0,0 +1,57 @@
|
|||||||
|
name: End-of-life tables
|
||||||
|
|
||||||
|
# Compares the bundled end-of-life tables (compliance-agent/data/eol/: Yocto
|
||||||
|
# releases, .NET target frameworks, the oldest patched Android and iOS
|
||||||
|
# releases) with endoflife.date once a week. A difference (a new release, a
|
||||||
|
# changed end-of-life date) opens one issue, or updates the open one, labelled
|
||||||
|
# "eol-tables"; the tables themselves are updated by hand after checking the
|
||||||
|
# vendor's page. A separate workflow, so it never fails main CI.
|
||||||
|
#
|
||||||
|
# The issue is written with NIGHTLY_ALERT_TOKEN, the token the nightly
|
||||||
|
# regression already uses for its alert issue (issue write on this repo).
|
||||||
|
# Without it the differences are only printed in the log.
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 5 * * 1' # Mondays, 5 AM UTC
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
dry_run:
|
||||||
|
description: "Print the differences only, write no issue"
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: eol-tables
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
name: Compare with endoflife.date
|
||||||
|
runs-on: docker
|
||||||
|
container:
|
||||||
|
image: python:3.12-alpine
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
run: |
|
||||||
|
apk add --no-cache git
|
||||||
|
git init
|
||||||
|
git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||||
|
git fetch --depth=1 origin "${GITHUB_SHA}"
|
||||||
|
git checkout FETCH_HEAD
|
||||||
|
|
||||||
|
- name: Test the check
|
||||||
|
run: python3 -I -m unittest discover -s scripts -p "test_check_eol_tables.py"
|
||||||
|
|
||||||
|
- name: Compare and file the issue
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.NIGHTLY_ALERT_TOKEN }}
|
||||||
|
GITEA_API: ${{ github.server_url }}/api/v1
|
||||||
|
GITEA_REPO: ${{ github.repository }}
|
||||||
|
DRY_RUN: ${{ inputs.dry_run }}
|
||||||
|
run: |
|
||||||
|
if [ "$DRY_RUN" = "true" ]; then
|
||||||
|
python3 -I scripts/check-eol-tables.py --dry-run
|
||||||
|
else
|
||||||
|
python3 -I scripts/check-eol-tables.py
|
||||||
|
fi
|
||||||
Generated
+21
-9
@@ -2381,11 +2381,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
|
checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi",
|
||||||
"rand_core 0.10.0",
|
"rand_core 0.10.0",
|
||||||
"wasip2",
|
"wasip2",
|
||||||
"wasip3",
|
"wasip3",
|
||||||
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4350,14 +4352,15 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn-proto"
|
name = "quinn-proto"
|
||||||
version = "0.11.15"
|
version = "0.11.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
|
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"getrandom 0.3.4",
|
"getrandom 0.4.1",
|
||||||
"lru-slab",
|
"lru-slab",
|
||||||
"rand 0.9.2",
|
"rand 0.10.3",
|
||||||
|
"rand_pcg",
|
||||||
"ring",
|
"ring",
|
||||||
"rustc-hash 2.1.1",
|
"rustc-hash 2.1.1",
|
||||||
"rustls",
|
"rustls",
|
||||||
@@ -4427,9 +4430,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand"
|
name = "rand"
|
||||||
version = "0.10.0"
|
version = "0.10.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8"
|
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chacha20",
|
"chacha20",
|
||||||
"getrandom 0.4.1",
|
"getrandom 0.4.1",
|
||||||
@@ -4490,6 +4493,15 @@ dependencies = [
|
|||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_pcg"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
|
||||||
|
dependencies = [
|
||||||
|
"rand_core 0.10.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "raw-window-handle"
|
name = "raw-window-handle"
|
||||||
version = "0.6.2"
|
version = "0.6.2"
|
||||||
@@ -4670,7 +4682,7 @@ dependencies = [
|
|||||||
"http-body-util",
|
"http-body-util",
|
||||||
"pastey",
|
"pastey",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"rand 0.10.0",
|
"rand 0.10.3",
|
||||||
"rmcp-macros",
|
"rmcp-macros",
|
||||||
"schemars",
|
"schemars",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -4760,9 +4772,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.45"
|
version = "0.23.46"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
{
|
||||||
|
"source": "https://learn.microsoft.com/lifecycle/products/microsoft-net-framework and https://dotnet.microsoft.com/platform/support/policy/dotnet-core",
|
||||||
|
"endoflife_products": [
|
||||||
|
"dotnet",
|
||||||
|
"dotnetfx"
|
||||||
|
],
|
||||||
|
"checked_on": "2026-10-05",
|
||||||
|
"notes": "Microsoft's end of support per target framework moniker. Monikers not listed are supported (.NET Framework 4.7 to 4.8.1 follow the Windows they ship with).",
|
||||||
|
"frameworks": [
|
||||||
|
{
|
||||||
|
"moniker": "net11",
|
||||||
|
"end_of_support": "2011-07-12",
|
||||||
|
"product": ".NET Framework 1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net20",
|
||||||
|
"end_of_support": "2011-07-12",
|
||||||
|
"product": ".NET Framework 2.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net30",
|
||||||
|
"end_of_support": "2011-07-12",
|
||||||
|
"product": ".NET Framework 3.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net35",
|
||||||
|
"end_of_support": "2029-01-09",
|
||||||
|
"product": ".NET Framework 3.5 SP1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net40",
|
||||||
|
"end_of_support": "2016-01-12",
|
||||||
|
"product": ".NET Framework 4.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net403",
|
||||||
|
"end_of_support": "2016-01-12",
|
||||||
|
"product": ".NET Framework 4.0.3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net45",
|
||||||
|
"end_of_support": "2016-01-12",
|
||||||
|
"product": ".NET Framework 4.5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net451",
|
||||||
|
"end_of_support": "2016-01-12",
|
||||||
|
"product": ".NET Framework 4.5.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net452",
|
||||||
|
"end_of_support": "2022-04-26",
|
||||||
|
"product": ".NET Framework 4.5.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net46",
|
||||||
|
"end_of_support": "2022-04-26",
|
||||||
|
"product": ".NET Framework 4.6"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net461",
|
||||||
|
"end_of_support": "2022-04-26",
|
||||||
|
"product": ".NET Framework 4.6.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net462",
|
||||||
|
"end_of_support": "2027-01-12",
|
||||||
|
"product": ".NET Framework 4.6.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp1.0",
|
||||||
|
"end_of_support": "2019-06-27",
|
||||||
|
"product": ".NET Core 1.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp1.1",
|
||||||
|
"end_of_support": "2019-06-27",
|
||||||
|
"product": ".NET Core 1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp2.0",
|
||||||
|
"end_of_support": "2018-10-01",
|
||||||
|
"product": ".NET Core 2.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp2.1",
|
||||||
|
"end_of_support": "2021-08-21",
|
||||||
|
"product": ".NET Core 2.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp2.2",
|
||||||
|
"end_of_support": "2019-12-23",
|
||||||
|
"product": ".NET Core 2.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp3.0",
|
||||||
|
"end_of_support": "2020-03-03",
|
||||||
|
"product": ".NET Core 3.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "netcoreapp3.1",
|
||||||
|
"end_of_support": "2022-12-13",
|
||||||
|
"product": ".NET Core 3.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net5.0",
|
||||||
|
"end_of_support": "2022-05-10",
|
||||||
|
"product": ".NET 5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net6.0",
|
||||||
|
"end_of_support": "2024-11-12",
|
||||||
|
"product": ".NET 6"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net7.0",
|
||||||
|
"end_of_support": "2024-05-14",
|
||||||
|
"product": ".NET 7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net8.0",
|
||||||
|
"end_of_support": "2026-11-10",
|
||||||
|
"product": ".NET 8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net9.0",
|
||||||
|
"end_of_support": "2026-11-10",
|
||||||
|
"product": ".NET 9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"moniker": "net10.0",
|
||||||
|
"end_of_support": "2028-11-14",
|
||||||
|
"product": ".NET 10"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"android": {
|
||||||
|
"oldest_patched_api": 29,
|
||||||
|
"oldest_patched_release": "Android 10",
|
||||||
|
"endoflife_product": "android",
|
||||||
|
"notes": "Below this API level no Android release receives security updates."
|
||||||
|
},
|
||||||
|
"ios": {
|
||||||
|
"oldest_patched": "15.0",
|
||||||
|
"endoflife_product": "ios",
|
||||||
|
"notes": "The oldest iOS release that still receives security updates: iOS 15 got 15.8.8 in May 2026, while iOS 14 was last updated in October 2021 and the older iOS 12 line in January 2026, both now end of life (endoflife.date). Judged conservatively: below it is certainly unpatched."
|
||||||
|
},
|
||||||
|
"checked_on": "2026-10-05"
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
{
|
||||||
|
"source": "https://wiki.yoctoproject.org/wiki/Releases",
|
||||||
|
"dates_source": "https://endoflife.date/yocto",
|
||||||
|
"endoflife_product": "yocto",
|
||||||
|
"checked_on": "2026-10-09",
|
||||||
|
"notes": "Codename, version, LTS and support status from the Yocto Project releases wiki (page last updated 2026-09-10). The wiki gives months only; the exact release and end-of-life days are endoflife.date's, which agree with the wiki's months except Walnascar (wiki: EOL since November 2025, endoflife.date: 2025-12-07). For Thud and older, which endoflife.date does not list, the end of life is the last day of the month of the release's last point release (wiki), and the release day the first of its month. Releases are added once they are released. Oldest first.",
|
||||||
|
"releases": [
|
||||||
|
{
|
||||||
|
"codename": "jethro",
|
||||||
|
"version": "2.0",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2015-11-01",
|
||||||
|
"end_of_life": "2017-01-31"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "krogoth",
|
||||||
|
"version": "2.1",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2016-04-01",
|
||||||
|
"end_of_life": "2017-07-31"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "morty",
|
||||||
|
"version": "2.2",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2016-11-01",
|
||||||
|
"end_of_life": "2018-07-31"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "pyro",
|
||||||
|
"version": "2.3",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2017-05-01",
|
||||||
|
"end_of_life": "2018-07-31"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "rocko",
|
||||||
|
"version": "2.4",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2017-10-01",
|
||||||
|
"end_of_life": "2018-11-30"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "sumo",
|
||||||
|
"version": "2.5",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2018-04-01",
|
||||||
|
"end_of_life": "2019-04-30"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "thud",
|
||||||
|
"version": "2.6",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2018-11-01",
|
||||||
|
"end_of_life": "2019-10-31"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "warrior",
|
||||||
|
"version": "2.7",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2019-05-01",
|
||||||
|
"end_of_life": "2020-06-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "zeus",
|
||||||
|
"version": "3.0",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2019-10-22",
|
||||||
|
"end_of_life": "2020-08-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "dunfell",
|
||||||
|
"version": "3.1",
|
||||||
|
"lts": true,
|
||||||
|
"released": "2020-04-21",
|
||||||
|
"end_of_life": "2024-04-30"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "gatesgarth",
|
||||||
|
"version": "3.2",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2020-11-03",
|
||||||
|
"end_of_life": "2021-05-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "hardknott",
|
||||||
|
"version": "3.3",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2021-04-19",
|
||||||
|
"end_of_life": "2022-04-20"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "honister",
|
||||||
|
"version": "3.4",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2021-10-25",
|
||||||
|
"end_of_life": "2022-05-01"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "kirkstone",
|
||||||
|
"version": "4.0",
|
||||||
|
"lts": true,
|
||||||
|
"released": "2022-04-25",
|
||||||
|
"end_of_life": "2026-04-27"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "langdale",
|
||||||
|
"version": "4.1",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2022-10-23",
|
||||||
|
"end_of_life": "2023-05-27"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "mickledore",
|
||||||
|
"version": "4.2",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2023-05-03",
|
||||||
|
"end_of_life": "2023-11-05"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "nanbield",
|
||||||
|
"version": "4.3",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2023-11-09",
|
||||||
|
"end_of_life": "2024-06-09"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "scarthgap",
|
||||||
|
"version": "5.0",
|
||||||
|
"lts": true,
|
||||||
|
"released": "2024-04-29",
|
||||||
|
"end_of_life": "2028-04-30"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "styhead",
|
||||||
|
"version": "5.1",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2024-10-16",
|
||||||
|
"end_of_life": "2025-05-16"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "walnascar",
|
||||||
|
"version": "5.2",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2025-05-07",
|
||||||
|
"end_of_life": "2025-12-07"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "whinlatter",
|
||||||
|
"version": "5.3",
|
||||||
|
"lts": false,
|
||||||
|
"released": "2025-12-15",
|
||||||
|
"end_of_life": "2026-06-15"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"codename": "wrynose",
|
||||||
|
"version": "6.0",
|
||||||
|
"lts": true,
|
||||||
|
"released": "2026-05-13",
|
||||||
|
"end_of_life": "2030-04-30"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
//! Portal-issued API keys on the customer API (tenant-registry ADR 0001, §4).
|
||||||
|
//!
|
||||||
|
//! A `Bearer bp_…` token is an API key; every other bearer goes on to the
|
||||||
|
//! JWT middleware unchanged. The key is verified with the registry (answers
|
||||||
|
//! cached for [`crate::registry::API_KEY_TTL`]) and becomes a
|
||||||
|
//! [`TenantContext`] carrying [`ApiKeyAccess`]:
|
||||||
|
//!
|
||||||
|
//! * the tenant, scopes and ladder status come only from the registry's
|
||||||
|
//! answer; no header, path or body can name another tenant, and the support
|
||||||
|
//! header is never read;
|
||||||
|
//! * the key holds no org role, so `role_gate` judges it by its scopes;
|
||||||
|
//! * `X-BP-Actor` is recorded as who the caller acts for, never trusted.
|
||||||
|
//!
|
||||||
|
//! `401 {"error": "invalid_api_key"}` for a key the registry rejects, `503`
|
||||||
|
//! when the registry cannot answer and no fresh verdict is cached.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
extract::{Request, State},
|
||||||
|
http::{header, StatusCode},
|
||||||
|
middleware::Next,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
Json,
|
||||||
|
};
|
||||||
|
use compliance_core::auth::bypasses_customer_auth;
|
||||||
|
use compliance_core::{ApiKeyAccess, TenantContext, TenantStatus};
|
||||||
|
|
||||||
|
use super::role_gate::LEGACY_SCOPES;
|
||||||
|
use crate::agent::ComplianceAgent;
|
||||||
|
use crate::registry::ApiKeyVerify;
|
||||||
|
|
||||||
|
/// Every portal-issued API key starts with this.
|
||||||
|
pub const API_KEY_PREFIX: &str = "bp_";
|
||||||
|
|
||||||
|
/// The header a caller (e.g. a Werkmeister block) names the person it acts
|
||||||
|
/// for in. Informational: logged and audited, never used to authorise.
|
||||||
|
pub const ACTOR_HEADER: &str = "x-bp-actor";
|
||||||
|
|
||||||
|
/// The longest `X-BP-Actor` value kept; the rest is cut off.
|
||||||
|
const ACTOR_MAX_CHARS: usize = 120;
|
||||||
|
|
||||||
|
/// The JSON `error` for a key the registry does not accept.
|
||||||
|
pub const INVALID_API_KEY: &str = "invalid_api_key";
|
||||||
|
|
||||||
|
/// The middleware. Mounted outside the JWT middleware, which lets through a
|
||||||
|
/// request this one has given a key context.
|
||||||
|
pub async fn require_api_key(
|
||||||
|
State(agent): State<Arc<ComplianceAgent>>,
|
||||||
|
mut request: Request,
|
||||||
|
next: Next,
|
||||||
|
) -> Response {
|
||||||
|
if bypasses_customer_auth(request.uri().path()) {
|
||||||
|
return next.run(request).await;
|
||||||
|
}
|
||||||
|
let Some(key) = presented_key(&request) else {
|
||||||
|
return next.run(request).await;
|
||||||
|
};
|
||||||
|
let Some(registry) = agent.registry.as_ref() else {
|
||||||
|
return invalid_key();
|
||||||
|
};
|
||||||
|
let verdict = match registry.verify_api_key(&key).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("api-key verify unavailable: {e}");
|
||||||
|
return (
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
Json(serde_json::json!({ "error": "api_key_verify_unavailable" })),
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let on_behalf_of = request
|
||||||
|
.headers()
|
||||||
|
.get(ACTOR_HEADER)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(clean_actor);
|
||||||
|
let Some(ctx) = key_context(verdict, registry.product(), on_behalf_of) else {
|
||||||
|
return invalid_key();
|
||||||
|
};
|
||||||
|
request.extensions_mut().insert(ctx);
|
||||||
|
next.run(request).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `bp_…` token of an `Authorization: Bearer` header, if it is one.
|
||||||
|
fn presented_key(request: &Request) -> Option<String> {
|
||||||
|
request
|
||||||
|
.headers()
|
||||||
|
.get(header::AUTHORIZATION)?
|
||||||
|
.to_str()
|
||||||
|
.ok()?
|
||||||
|
.strip_prefix("Bearer ")
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|t| t.starts_with(API_KEY_PREFIX))
|
||||||
|
.map(str::to_owned)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_key() -> Response {
|
||||||
|
(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
Json(serde_json::json!({ "error": INVALID_API_KEY })),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The context for a verified key, or `None` if the registry rejected it.
|
||||||
|
/// `product` is this product's registry key, which a legacy key must name
|
||||||
|
/// (or name none) to get [`LEGACY_SCOPES`].
|
||||||
|
fn key_context(
|
||||||
|
v: ApiKeyVerify,
|
||||||
|
product: &str,
|
||||||
|
on_behalf_of: Option<String>,
|
||||||
|
) -> Option<TenantContext> {
|
||||||
|
if !v.valid || v.tenant_id.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let scopes =
|
||||||
|
if v.legacy && v.scopes.is_empty() && (v.product.is_empty() || v.product == product) {
|
||||||
|
LEGACY_SCOPES.iter().map(|s| (*s).to_string()).collect()
|
||||||
|
} else {
|
||||||
|
v.scopes
|
||||||
|
};
|
||||||
|
let key_id = if v.key_id.is_empty() {
|
||||||
|
"unknown".to_string()
|
||||||
|
} else {
|
||||||
|
v.key_id
|
||||||
|
};
|
||||||
|
Some(TenantContext {
|
||||||
|
tenant_id: v.tenant_id,
|
||||||
|
tenant_slug: String::new(),
|
||||||
|
org_roles: Vec::new(),
|
||||||
|
products: Vec::new(),
|
||||||
|
plan: String::new(),
|
||||||
|
// An older registry sends no status: read-only until it does.
|
||||||
|
status: TenantStatus::parse(&v.tenant_status).unwrap_or(TenantStatus::Restricted),
|
||||||
|
user_id: format!("apikey:{key_id}"),
|
||||||
|
user_name: v.holder.clone().filter(|h| !h.trim().is_empty()),
|
||||||
|
staff: None,
|
||||||
|
api_key: Some(Box::new(ApiKeyAccess {
|
||||||
|
key_id,
|
||||||
|
kind: v.kind,
|
||||||
|
holder: v.holder,
|
||||||
|
scopes,
|
||||||
|
legacy: v.legacy,
|
||||||
|
on_behalf_of,
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An `X-BP-Actor` value fit for a log line: no control characters, at most
|
||||||
|
/// [`ACTOR_MAX_CHARS`], `None` if nothing is left.
|
||||||
|
fn clean_actor(raw: &str) -> Option<String> {
|
||||||
|
let cleaned: String = raw
|
||||||
|
.chars()
|
||||||
|
.filter(|c| !c.is_control())
|
||||||
|
.take(ACTOR_MAX_CHARS)
|
||||||
|
.collect();
|
||||||
|
let trimmed = cleaned.trim();
|
||||||
|
(!trimmed.is_empty()).then(|| trimmed.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn verdict() -> ApiKeyVerify {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"valid": true,
|
||||||
|
"tenant_id": "11111111-1111-1111-1111-111111111111",
|
||||||
|
"product": "pruefwerk",
|
||||||
|
"scopes": ["pruefwerk:findings.write"],
|
||||||
|
"key_id": "k1",
|
||||||
|
"kind": "service",
|
||||||
|
"holder": "CI",
|
||||||
|
"tenant_status": "active",
|
||||||
|
"legacy": false,
|
||||||
|
}))
|
||||||
|
.expect("verdict")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_valid_key_becomes_a_roleless_context_of_its_tenant() {
|
||||||
|
let ctx = key_context(verdict(), "pruefwerk", Some("someone".into())).expect("ctx");
|
||||||
|
assert_eq!(ctx.tenant_id, "11111111-1111-1111-1111-111111111111");
|
||||||
|
assert_eq!(ctx.user_id, "apikey:k1");
|
||||||
|
assert_eq!(ctx.actor_label(), "CI");
|
||||||
|
assert!(ctx.org_roles.is_empty());
|
||||||
|
assert_eq!(ctx.status, TenantStatus::Active);
|
||||||
|
let key = ctx.api_key.expect("key");
|
||||||
|
assert_eq!(key.scopes, ["pruefwerk:findings.write"]);
|
||||||
|
assert_eq!(key.on_behalf_of.as_deref(), Some("someone"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rejected_or_tenantless_key_gets_no_context() {
|
||||||
|
let mut v = verdict();
|
||||||
|
v.valid = false;
|
||||||
|
assert!(key_context(v, "pruefwerk", None).is_none());
|
||||||
|
let mut v = verdict();
|
||||||
|
v.tenant_id.clear();
|
||||||
|
assert!(key_context(v, "pruefwerk", None).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_legacy_key_reads_only_and_only_for_this_product() {
|
||||||
|
let mut v = verdict();
|
||||||
|
v.legacy = true;
|
||||||
|
v.scopes.clear();
|
||||||
|
let key = key_context(v.clone(), "pruefwerk", None)
|
||||||
|
.and_then(|c| c.api_key)
|
||||||
|
.expect("key");
|
||||||
|
assert_eq!(key.scopes, LEGACY_SCOPES);
|
||||||
|
v.product = "werkbank".into();
|
||||||
|
let key = key_context(v, "pruefwerk", None)
|
||||||
|
.and_then(|c| c.api_key)
|
||||||
|
.expect("key");
|
||||||
|
assert!(key.scopes.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_registry_answer_is_read_only_and_anonymous() {
|
||||||
|
let v: ApiKeyVerify = serde_json::from_value(serde_json::json!({
|
||||||
|
"valid": true,
|
||||||
|
"tenant_id": "t",
|
||||||
|
"product": "pruefwerk",
|
||||||
|
"scopes": ["pruefwerk:findings.read"],
|
||||||
|
}))
|
||||||
|
.expect("old shape decodes");
|
||||||
|
let ctx = key_context(v, "pruefwerk", None).expect("ctx");
|
||||||
|
assert_eq!(ctx.status, TenantStatus::Restricted);
|
||||||
|
assert_eq!(ctx.user_id, "apikey:unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_actor_header_is_cleaned_and_capped() {
|
||||||
|
assert_eq!(clean_actor(" a\nb\u{7}c "), Some("abc".into()));
|
||||||
|
assert_eq!(clean_actor(" \t "), None);
|
||||||
|
assert_eq!(
|
||||||
|
clean_actor(&"x".repeat(500)).map(|s| s.len()),
|
||||||
|
Some(ACTOR_MAX_CHARS)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -230,6 +230,10 @@ pub struct SbomFilter {
|
|||||||
/// others (`false`); see [`compliance_core::models::InImage`].
|
/// others (`false`); see [`compliance_core::models::InImage`].
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub in_image: Option<bool>,
|
pub in_image: Option<bool>,
|
||||||
|
/// Only components whose licence is still open (`true`): the scan found
|
||||||
|
/// none and nobody has confirmed one.
|
||||||
|
#[serde(default)]
|
||||||
|
pub unresolved: Option<bool>,
|
||||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||||
pub page: u64,
|
pub page: u64,
|
||||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||||
@@ -267,6 +271,11 @@ pub struct LicenseSummary {
|
|||||||
pub license: String,
|
pub license: String,
|
||||||
pub count: u64,
|
pub count: u64,
|
||||||
pub is_copyleft: bool,
|
pub is_copyleft: bool,
|
||||||
|
/// What the licence allows (`permissive`, `weak_copyleft`, ...); for a
|
||||||
|
/// confirmed licence the category the person chose.
|
||||||
|
pub category: compliance_core::models::LicenseCategory,
|
||||||
|
/// How many of the components a person confirmed this licence for.
|
||||||
|
pub confirmed: u64,
|
||||||
pub packages: Vec<String>,
|
pub packages: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -659,12 +668,16 @@ mod tests {
|
|||||||
license: "MIT".to_string(),
|
license: "MIT".to_string(),
|
||||||
count: 42,
|
count: 42,
|
||||||
is_copyleft: false,
|
is_copyleft: false,
|
||||||
|
category: compliance_core::models::LicenseCategory::Permissive,
|
||||||
|
confirmed: 3,
|
||||||
packages: vec!["serde".to_string()],
|
packages: vec!["serde".to_string()],
|
||||||
};
|
};
|
||||||
let v = serde_json::to_value(&ls).unwrap();
|
let v = serde_json::to_value(&ls).unwrap();
|
||||||
assert_eq!(v["license"], "MIT");
|
assert_eq!(v["license"], "MIT");
|
||||||
assert_eq!(v["is_copyleft"], false);
|
assert_eq!(v["is_copyleft"], false);
|
||||||
assert_eq!(v["count"], 42);
|
assert_eq!(v["count"], 42);
|
||||||
|
assert_eq!(v["category"], "permissive");
|
||||||
|
assert_eq!(v["confirmed"], 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Default helper functions ─────────────────────────────────
|
// ── Default helper functions ─────────────────────────────────
|
||||||
|
|||||||
@@ -54,6 +54,15 @@ async fn load_inputs(
|
|||||||
tracing::warn!("evidence: {e}");
|
tracing::warn!("evidence: {e}");
|
||||||
StatusCode::INTERNAL_SERVER_ERROR
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
};
|
};
|
||||||
|
let mut sbom = collect_cursor_async(
|
||||||
|
db.sbom_entries()
|
||||||
|
.find(by_target.clone())
|
||||||
|
.await
|
||||||
|
.map_err(load_err)?,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
// The licences a person confirmed are part of the evidence's SBOM.
|
||||||
|
crate::license_conclusions::attach(db, &mut sbom).await;
|
||||||
Ok(EvidenceInputs {
|
Ok(EvidenceInputs {
|
||||||
findings: collect_cursor_async(
|
findings: collect_cursor_async(
|
||||||
db.findings()
|
db.findings()
|
||||||
@@ -62,13 +71,7 @@ async fn load_inputs(
|
|||||||
.map_err(load_err)?,
|
.map_err(load_err)?,
|
||||||
)
|
)
|
||||||
.await,
|
.await,
|
||||||
sbom: collect_cursor_async(
|
sbom,
|
||||||
db.sbom_entries()
|
|
||||||
.find(by_target.clone())
|
|
||||||
.await
|
|
||||||
.map_err(load_err)?,
|
|
||||||
)
|
|
||||||
.await,
|
|
||||||
cves: collect_cursor_async(
|
cves: collect_cursor_async(
|
||||||
db.cve_alerts()
|
db.cve_alerts()
|
||||||
.find(by_target.clone())
|
.find(by_target.clone())
|
||||||
@@ -85,6 +88,7 @@ async fn load_inputs(
|
|||||||
catalog: crate::controls::cra_catalog(&agent.config).await,
|
catalog: crate::controls::cra_catalog(&agent.config).await,
|
||||||
target,
|
target,
|
||||||
author: String::new(),
|
author: String::new(),
|
||||||
|
license_policy: crate::license_conclusions::load_policy(db).await,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -311,7 +311,9 @@ pub async fn bulk_update_finding_status(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all)]
|
/// PATCH /api/v1/findings/{id}/feedback — store the developer's feedback on a
|
||||||
|
/// finding. 404 when there is no such finding.
|
||||||
|
#[tracing::instrument(skip_all, fields(finding_id = %id))]
|
||||||
pub async fn update_finding_feedback(
|
pub async fn update_finding_feedback(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
tenant: TenantCtx,
|
tenant: TenantCtx,
|
||||||
@@ -321,13 +323,17 @@ pub async fn update_finding_feedback(
|
|||||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
let db = tenant_db(&agent, &tenant).await?;
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
|
||||||
db.findings()
|
let result = db
|
||||||
|
.findings()
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! { "_id": oid },
|
doc! { "_id": oid },
|
||||||
doc! { "$set": { "developer_feedback": &req.feedback, "updated_at": mongodb::bson::DateTime::now() } },
|
doc! { "$set": { "developer_feedback": &req.feedback, "updated_at": mongodb::bson::DateTime::now() } },
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
if result.matched_count == 0 {
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(Json(serde_json::json!({ "status": "updated" })))
|
Ok(Json(serde_json::json!({ "status": "updated" })))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,986 @@
|
|||||||
|
//! Licences a workspace confirms for its components: list them, confirm one
|
||||||
|
//! for one or many components at once, and withdraw one. The scanned
|
||||||
|
//! licence stays as detected; the confirmed one is merged in when the
|
||||||
|
//! components are read and exported ([`crate::license_conclusions`]).
|
||||||
|
//!
|
||||||
|
//! Writes are for the roles that may change Prüfwerk (IT_ADMIN, USER), as
|
||||||
|
//! the role gate decides for every `PUT` and `DELETE`.
|
||||||
|
|
||||||
|
use axum::extract::{Extension, Query};
|
||||||
|
use axum::http::{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;
|
||||||
|
use crate::license_conclusions::MAX_CONCLUSIONS;
|
||||||
|
|
||||||
|
/// The most components one request confirms.
|
||||||
|
pub const MAX_COMPONENTS: usize = 500;
|
||||||
|
|
||||||
|
/// A component a licence is confirmed for, as the SBOM list shows it.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct ComponentRef {
|
||||||
|
pub name: String,
|
||||||
|
pub package_manager: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub version: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub purl: Option<String>,
|
||||||
|
/// 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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of [`conclude`].
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ConcludeRequest {
|
||||||
|
pub components: Vec<ComponentRef>,
|
||||||
|
/// For every version of the packages, not just the listed ones.
|
||||||
|
#[serde(default)]
|
||||||
|
pub all_versions: bool,
|
||||||
|
/// An SPDX licence expression or a licence name SPDX knows. Empty for a
|
||||||
|
/// licence of its own, named in `license_name`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub license: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license_name: Option<String>,
|
||||||
|
/// Used for a licence of its own and where SPDX gives no category.
|
||||||
|
#[serde(default)]
|
||||||
|
pub category: Option<LicenseCategory>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub copyright: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license_text: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub license_url: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub evidence: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub contract_ref: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub valid_until: Option<NaiveDate>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub usage: Option<LicenseUsage>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub note: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Refusal = (StatusCode, Json<serde_json::Value>);
|
||||||
|
|
||||||
|
fn refuse(code: StatusCode, error: impl Into<String>) -> Refusal {
|
||||||
|
(code, Json(serde_json::json!({ "error": error.into() })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trimmed, `None` when empty.
|
||||||
|
fn text(value: Option<String>) -> Option<String> {
|
||||||
|
value
|
||||||
|
.map(|t| t.trim().to_string())
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The licence `req` states, as stored: the SPDX expression and its
|
||||||
|
/// category, or a `LicenseRef-` with the name and the category asked for.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Neither a licence nor a name, or a licence SPDX cannot read.
|
||||||
|
fn licence_of(req: &ConcludeRequest) -> Result<(String, Option<String>, LicenseCategory), String> {
|
||||||
|
let asked = req.category.unwrap_or(LicenseCategory::Unclear);
|
||||||
|
if let Some(license) = text(req.license.clone()) {
|
||||||
|
let spdx = spdx_license::normalise(&license).into_owned();
|
||||||
|
if !spdx_license::is_spdx_expression(&spdx) {
|
||||||
|
return Err(format!(
|
||||||
|
"not an SPDX licence expression: {license}. For a licence SPDX does not list, give its name instead"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let derived = spdx_license::category(&spdx);
|
||||||
|
let category = if derived == LicenseCategory::Unclear {
|
||||||
|
asked
|
||||||
|
} else {
|
||||||
|
derived
|
||||||
|
};
|
||||||
|
return Ok((spdx, None, category));
|
||||||
|
}
|
||||||
|
match text(req.license_name.clone()) {
|
||||||
|
Some(name) => Ok((license::license_ref(&name), Some(name), asked)),
|
||||||
|
None => Err("licence missing: give an SPDX licence or the name of the licence".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The conclusions `req` asks for, one per component (several components of
|
||||||
|
/// one package and version are one conclusion), by the requester of
|
||||||
|
/// `tenant`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Why the request cannot be stored.
|
||||||
|
fn conclusions_of(
|
||||||
|
req: ConcludeRequest,
|
||||||
|
tenant: &TenantCtx,
|
||||||
|
) -> Result<Vec<LicenseConclusion>, String> {
|
||||||
|
if req.components.is_empty() {
|
||||||
|
return Err("no component given".into());
|
||||||
|
}
|
||||||
|
if req.components.len() > MAX_COMPONENTS {
|
||||||
|
return Err(format!("at most {MAX_COMPONENTS} components at once"));
|
||||||
|
}
|
||||||
|
let (license, license_name, category) = licence_of(&req)?;
|
||||||
|
let actor = Actor::of(&tenant.0);
|
||||||
|
let at = chrono::Utc::now();
|
||||||
|
let copyright: Vec<String> = req
|
||||||
|
.copyright
|
||||||
|
.iter()
|
||||||
|
.flat_map(|c| c.lines())
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|c| !c.is_empty())
|
||||||
|
.map(String::from)
|
||||||
|
.collect();
|
||||||
|
let mut out: Vec<LicenseConclusion> = Vec::new();
|
||||||
|
for component in &req.components {
|
||||||
|
let name = component.name.trim();
|
||||||
|
if name.is_empty() {
|
||||||
|
return Err("a component without a name".into());
|
||||||
|
}
|
||||||
|
let key = package_key(name, &component.package_manager, component.purl.as_deref());
|
||||||
|
let version = (!req.all_versions)
|
||||||
|
.then(|| component.version.trim().to_string())
|
||||||
|
.filter(|v| !v.is_empty());
|
||||||
|
let id = conclusion_id(&key, version.as_deref());
|
||||||
|
if out.iter().any(|c| c.id == id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let conclusion = LicenseConclusion {
|
||||||
|
id,
|
||||||
|
package_key: key,
|
||||||
|
name: name.to_string(),
|
||||||
|
package_manager: component.package_manager.trim().to_string(),
|
||||||
|
version,
|
||||||
|
license: license.clone(),
|
||||||
|
license_name: license_name.clone(),
|
||||||
|
category,
|
||||||
|
copyright: copyright.clone(),
|
||||||
|
license_text: text(req.license_text.clone()),
|
||||||
|
license_url: text(req.license_url.clone()),
|
||||||
|
evidence: text(req.evidence.clone()),
|
||||||
|
contract_ref: text(req.contract_ref.clone()),
|
||||||
|
valid_until: req.valid_until,
|
||||||
|
usage: req.usage,
|
||||||
|
note: text(req.note.clone()),
|
||||||
|
by: actor.id.to_string(),
|
||||||
|
by_name: actor.name.clone(),
|
||||||
|
support: actor.support,
|
||||||
|
at,
|
||||||
|
review: None,
|
||||||
|
};
|
||||||
|
conclusion.validate()?;
|
||||||
|
out.push(conclusion);
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GET /api/v1/licenses/conclusions — every licence the workspace
|
||||||
|
/// confirmed, by package name.
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn list_conclusions(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
) -> ApiResult<Vec<LicenseConclusion>> {
|
||||||
|
let db = tenant_db(&agent, &tenant).await?;
|
||||||
|
let conclusions = crate::license_conclusions::load(&db).await;
|
||||||
|
Ok(Json(ApiResponse {
|
||||||
|
total: Some(conclusions.len() as u64),
|
||||||
|
data: conclusions,
|
||||||
|
page: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PUT /api/v1/licenses/conclusions — confirm a licence for one or more
|
||||||
|
/// components (one version, or every version of their packages). A second
|
||||||
|
/// confirmation of the same package and version replaces the first. 422
|
||||||
|
/// with the reason when the licence or a field is not acceptable.
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn conclude(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Json(req): Json<ConcludeRequest>,
|
||||||
|
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||||
|
let conclusions =
|
||||||
|
conclusions_of(req, &tenant).map_err(|e| refuse(StatusCode::UNPROCESSABLE_ENTITY, e))?;
|
||||||
|
let db = tenant_db(&agent, &tenant)
|
||||||
|
.await
|
||||||
|
.map_err(|code| refuse(code, "tenant"))?;
|
||||||
|
let stored = db
|
||||||
|
.license_conclusions()
|
||||||
|
.count_documents(doc! {})
|
||||||
|
.await
|
||||||
|
.map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
|
||||||
|
if stored.saturating_add(conclusions.len() as u64) > MAX_CONCLUSIONS as u64 {
|
||||||
|
return Err(refuse(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
format!("at most {MAX_CONCLUSIONS} confirmed licences per workspace"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for c in &conclusions {
|
||||||
|
db.license_conclusions()
|
||||||
|
.replace_one(doc! { "_id": &c.id }, c)
|
||||||
|
.upsert(true)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::warn!("license conclusion not stored: {e}");
|
||||||
|
refuse(StatusCode::INTERNAL_SERVER_ERROR, "store")
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
tracing::info!(
|
||||||
|
count = conclusions.len(),
|
||||||
|
license = %conclusions[0].license,
|
||||||
|
"license confirmed"
|
||||||
|
);
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"status": "saved",
|
||||||
|
"saved": conclusions.len(),
|
||||||
|
"conclusions": conclusions,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The query of [`withdraw`].
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct WithdrawQuery {
|
||||||
|
/// The conclusion's id (package and version, see
|
||||||
|
/// [`license::conclusion_id`]); a query value, as it holds `/` and `@`.
|
||||||
|
pub id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /api/v1/licenses/conclusions?id= — withdraw a confirmed licence;
|
||||||
|
/// the component shows the detected one again. 404 when there is none.
|
||||||
|
#[tracing::instrument(skip_all)]
|
||||||
|
pub async fn withdraw(
|
||||||
|
Extension(agent): AgentExt,
|
||||||
|
tenant: TenantCtx,
|
||||||
|
Query(query): Query<WithdrawQuery>,
|
||||||
|
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||||
|
let db = tenant_db(&agent, &tenant)
|
||||||
|
.await
|
||||||
|
.map_err(|code| refuse(code, "tenant"))?;
|
||||||
|
let result = db
|
||||||
|
.license_conclusions()
|
||||||
|
.delete_one(doc! { "_id": &query.id })
|
||||||
|
.await
|
||||||
|
.map_err(|_| refuse(StatusCode::INTERNAL_SERVER_ERROR, "store"))?;
|
||||||
|
if result.deleted_count == 0 {
|
||||||
|
return Err(refuse(StatusCode::NOT_FOUND, "no such confirmed licence"));
|
||||||
|
}
|
||||||
|
tracing::info!("license conclusion withdrawn");
|
||||||
|
Ok(Json(serde_json::json!({ "status": "withdrawn" })))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Json<serde_json::Value>, 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<LicensePolicy>,
|
||||||
|
) -> Result<Json<serde_json::Value>, 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<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
license: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<SbomEntry>, LicensePolicy) {
|
||||||
|
let mut query = doc! {};
|
||||||
|
if let Some(repo_id) = repo_id {
|
||||||
|
query.insert("repo_id", repo_id);
|
||||||
|
}
|
||||||
|
let rows: Vec<CheckRow> = match db
|
||||||
|
.sbom_entries()
|
||||||
|
.clone_with_type::<CheckRow>()
|
||||||
|
.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<SbomEntry> = 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a legal review can decide about `entry`: a licence was confirmed
|
||||||
|
/// for it, or the scan found an SPDX licence that a review confirms as it is.
|
||||||
|
/// Anything else needs its licence confirmed first.
|
||||||
|
fn decidable(entry: &SbomEntry) -> bool {
|
||||||
|
entry.concluded.is_some()
|
||||||
|
|| entry
|
||||||
|
.license
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.is_some_and(|l| spdx_license::is_spdx_expression(&spdx_license::normalise(l)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The query of [`check`] and [`notices`].
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct CheckQuery {
|
||||||
|
#[serde(default)]
|
||||||
|
pub repo_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<CheckQuery>,
|
||||||
|
) -> Result<Json<serde_json::Value>, 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();
|
||||||
|
// One row per package and version: a confirmation and a review are made
|
||||||
|
// for the package, whichever target it is in.
|
||||||
|
let mut items: Vec<serde_json::Value> = Vec::new();
|
||||||
|
let mut rows: std::collections::HashMap<(String, String, String), usize> =
|
||||||
|
std::collections::HashMap::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;
|
||||||
|
}
|
||||||
|
let row = (e.package_manager.clone(), e.name.clone(), e.version.clone());
|
||||||
|
if let Some(&at) = rows.get(&row) {
|
||||||
|
if let Some(item) = items.get_mut(at) {
|
||||||
|
let targets = item["targets"].as_u64().unwrap_or(1);
|
||||||
|
item["targets"] = serde_json::json!(targets + 1);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if items.len() >= MAX_CHECK_ITEMS {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
rows.insert(row, items.len());
|
||||||
|
items.push(serde_json::json!({
|
||||||
|
"repo_id": e.repo_id,
|
||||||
|
"targets": 1,
|
||||||
|
"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()),
|
||||||
|
"decidable": decidable(e),
|
||||||
|
"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),
|
||||||
|
"may_confirm": tenant.0.api_key.is_none()
|
||||||
|
&& tenant.0.product_access() == compliance_core::ProductAccess::Full,
|
||||||
|
}
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of [`review`].
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct ReviewRequest {
|
||||||
|
pub components: Vec<ComponentRef>,
|
||||||
|
/// 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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Vec<LicenseConclusion>, 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<LicenseConclusion> = 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<ReviewRequest>,
|
||||||
|
) -> Result<Json<serde_json::Value>, 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<WithdrawQuery>,
|
||||||
|
) -> Result<Json<serde_json::Value>, 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<NoticesQuery>,
|
||||||
|
) -> Result<impl IntoResponse, StatusCode> {
|
||||||
|
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::*;
|
||||||
|
|
||||||
|
fn req(license: Option<&str>, name: Option<&str>) -> ConcludeRequest {
|
||||||
|
ConcludeRequest {
|
||||||
|
components: vec![
|
||||||
|
ComponentRef {
|
||||||
|
name: "left-pad".into(),
|
||||||
|
package_manager: "npm".into(),
|
||||||
|
version: "1.3.0".into(),
|
||||||
|
purl: Some("pkg:npm/left-pad@1.3.0".into()),
|
||||||
|
license: None,
|
||||||
|
},
|
||||||
|
// The same package and version twice is one conclusion.
|
||||||
|
ComponentRef {
|
||||||
|
name: "left-pad".into(),
|
||||||
|
package_manager: "npm".into(),
|
||||||
|
version: "1.3.0".into(),
|
||||||
|
purl: Some("pkg:npm/left-pad@1.3.0".into()),
|
||||||
|
license: None,
|
||||||
|
},
|
||||||
|
ComponentRef {
|
||||||
|
name: "PumpSdk".into(),
|
||||||
|
package_manager: "nuget".into(),
|
||||||
|
version: "".into(),
|
||||||
|
purl: None,
|
||||||
|
license: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
all_versions: false,
|
||||||
|
license: license.map(String::from),
|
||||||
|
license_name: name.map(String::from),
|
||||||
|
category: Some(LicenseCategory::Proprietary),
|
||||||
|
copyright: vec!["© 2019 Example GmbH\n\n© 2021 Other AG".into()],
|
||||||
|
license_text: Some(" ".into()),
|
||||||
|
license_url: None,
|
||||||
|
evidence: Some(" LICENSE.txt ".into()),
|
||||||
|
contract_ref: None,
|
||||||
|
valid_until: None,
|
||||||
|
usage: Some(LicenseUsage::Shipped),
|
||||||
|
note: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tenant() -> TenantCtx {
|
||||||
|
TenantCtx(compliance_core::TenantContext {
|
||||||
|
tenant_id: "t-1".to_string(),
|
||||||
|
tenant_slug: "acme".to_string(),
|
||||||
|
org_roles: Vec::new(),
|
||||||
|
products: Vec::new(),
|
||||||
|
plan: String::new(),
|
||||||
|
status: compliance_core::TenantStatus::Active,
|
||||||
|
user_id: "u-1".to_string(),
|
||||||
|
user_name: Some("Erika Muster".to_string()),
|
||||||
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_spdx_licence_gets_its_own_category() {
|
||||||
|
let out =
|
||||||
|
conclusions_of(req(Some("Apache License, Version 2.0"), None), &tenant()).unwrap();
|
||||||
|
assert_eq!(out.len(), 2, "duplicates are merged");
|
||||||
|
assert_eq!(out[0].license, "Apache-2.0");
|
||||||
|
assert_eq!(
|
||||||
|
out[0].category,
|
||||||
|
LicenseCategory::Permissive,
|
||||||
|
"not the asked category"
|
||||||
|
);
|
||||||
|
assert_eq!(out[0].version.as_deref(), Some("1.3.0"));
|
||||||
|
assert_eq!(out[0].id, "pkg:npm/left-pad@1.3.0");
|
||||||
|
assert_eq!(out[1].id, "nuget:PumpSdk@*", "no version is every version");
|
||||||
|
assert_eq!(out[0].copyright, ["© 2019 Example GmbH", "© 2021 Other AG"]);
|
||||||
|
assert_eq!(out[0].license_text, None);
|
||||||
|
assert_eq!(out[0].evidence.as_deref(), Some("LICENSE.txt"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_licence_of_its_own_gets_a_license_ref() {
|
||||||
|
let out = conclusions_of(req(None, Some("Pump EULA")), &tenant()).unwrap();
|
||||||
|
assert_eq!(out[0].license, "LicenseRef-Pump-EULA");
|
||||||
|
assert_eq!(out[0].license_name.as_deref(), Some("Pump EULA"));
|
||||||
|
assert_eq!(out[0].category, LicenseCategory::Proprietary);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_version_drops_the_version() {
|
||||||
|
let mut r = req(Some("MIT"), None);
|
||||||
|
r.all_versions = true;
|
||||||
|
let out = conclusions_of(r, &tenant()).unwrap();
|
||||||
|
assert_eq!(out[0].id, "pkg:npm/left-pad@*");
|
||||||
|
assert_eq!(out[0].version, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_requests_are_refused_with_a_reason() {
|
||||||
|
assert!(conclusions_of(req(None, None), &tenant()).is_err());
|
||||||
|
assert!(conclusions_of(req(Some("Custom thing"), None), &tenant()).is_err());
|
||||||
|
let mut none = req(Some("MIT"), None);
|
||||||
|
none.components.clear();
|
||||||
|
assert!(conclusions_of(none, &tenant()).is_err());
|
||||||
|
let mut many = req(Some("MIT"), None);
|
||||||
|
many.components = vec![many.components[0].clone(); MAX_COMPONENTS + 1];
|
||||||
|
assert!(conclusions_of(many, &tenant()).is_err());
|
||||||
|
let mut nameless = req(Some("MIT"), None);
|
||||||
|
nameless.components[0].name = " ".into();
|
||||||
|
assert!(conclusions_of(nameless, &tenant()).is_err());
|
||||||
|
let mut url = req(Some("MIT"), None);
|
||||||
|
url.license_url = Some("file:///etc/passwd".into());
|
||||||
|
assert!(conclusions_of(url, &tenant()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_roles(roles: Vec<OrgRole>) -> 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_a_confirmed_or_spdx_licence_can_be_decided() {
|
||||||
|
let entry = |license: Option<&str>| {
|
||||||
|
let mut e = SbomEntry::new("r".into(), "lib".into(), "1".into(), "npm".into());
|
||||||
|
e.license = license.map(String::from);
|
||||||
|
e
|
||||||
|
};
|
||||||
|
assert!(decidable(&entry(Some("Apache License, Version 2.0"))));
|
||||||
|
assert!(decidable(&entry(Some("MIT OR GPL-3.0-only"))));
|
||||||
|
assert!(!decidable(&entry(None)));
|
||||||
|
assert!(!decidable(&entry(Some(
|
||||||
|
"http://go.microsoft.com/fwlink/?LinkID=262998"
|
||||||
|
))));
|
||||||
|
let mut confirmed = entry(None);
|
||||||
|
confirmed.concluded = conclusions_of(req(Some("MIT"), None), &tenant())
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.next();
|
||||||
|
assert!(decidable(&confirmed));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -234,6 +234,7 @@ mod tests {
|
|||||||
user_id: "u".into(),
|
user_id: "u".into(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ pub mod graph;
|
|||||||
pub mod health;
|
pub mod health;
|
||||||
pub mod help_chat;
|
pub mod help_chat;
|
||||||
pub mod issues;
|
pub mod issues;
|
||||||
|
pub mod licenses;
|
||||||
pub mod manual_findings;
|
pub mod manual_findings;
|
||||||
pub mod mcp_servers;
|
pub mod mcp_servers;
|
||||||
pub mod mcp_tokens;
|
pub mod mcp_tokens;
|
||||||
|
|||||||
@@ -472,6 +472,9 @@ pub struct PlatformTarget {
|
|||||||
pub last_scan_at: Option<chrono::DateTime<chrono::Utc>>,
|
pub last_scan_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
/// Findings that still need attention.
|
/// Findings that still need attention.
|
||||||
pub open_findings: u64,
|
pub open_findings: u64,
|
||||||
|
/// Known vulnerabilities in its components that are still open: CVE
|
||||||
|
/// alerts neither resolved nor assessed `not_affected` / `fixed`.
|
||||||
|
pub open_vulnerabilities: u64,
|
||||||
/// Its projects that the registry still lists.
|
/// Its projects that the registry still lists.
|
||||||
pub project_ids: Vec<String>,
|
pub project_ids: Vec<String>,
|
||||||
}
|
}
|
||||||
@@ -481,23 +484,56 @@ async fn open_findings_counts(
|
|||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
target_ids: Vec<String>,
|
target_ids: Vec<String>,
|
||||||
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
|
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
|
||||||
let pipeline = vec![
|
|
||||||
doc! { "$match": {
|
|
||||||
"repo_id": { "$in": target_ids },
|
|
||||||
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
|
|
||||||
} },
|
|
||||||
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
|
|
||||||
];
|
|
||||||
let rows: Vec<Document> = db
|
let rows: Vec<Document> = db
|
||||||
.findings()
|
.findings()
|
||||||
.aggregate(pipeline)
|
.aggregate(count_by_target(doc! {
|
||||||
|
"repo_id": { "$in": target_ids },
|
||||||
|
"status": { "$in": super::health::OPEN_STATUSES.to_vec() },
|
||||||
|
}))
|
||||||
.await
|
.await
|
||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
.try_collect()
|
.try_collect()
|
||||||
.await
|
.await
|
||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
Ok(rows
|
Ok(counts_by_target(&rows))
|
||||||
.iter()
|
}
|
||||||
|
|
||||||
|
/// The CVE alerts that still need a decision: not resolved by a later scan
|
||||||
|
/// and not assessed as `not_affected` or `fixed` in VEX.
|
||||||
|
fn open_vulnerabilities_filter(target_ids: Vec<String>) -> Document {
|
||||||
|
doc! {
|
||||||
|
"repo_id": { "$in": target_ids },
|
||||||
|
"resolved_at": null,
|
||||||
|
"vex.status": { "$nin": ["not_affected", "fixed"] },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open vulnerabilities (CVE alerts) of each target in `target_ids`, in one
|
||||||
|
/// query.
|
||||||
|
async fn open_vulnerabilities_counts(
|
||||||
|
db: &crate::database::Database,
|
||||||
|
target_ids: Vec<String>,
|
||||||
|
) -> Result<std::collections::HashMap<String, u64>, StatusCode> {
|
||||||
|
let rows: Vec<Document> = db
|
||||||
|
.cve_alerts()
|
||||||
|
.aggregate(count_by_target(open_vulnerabilities_filter(target_ids)))
|
||||||
|
.await
|
||||||
|
.map_err(internal)?
|
||||||
|
.try_collect()
|
||||||
|
.await
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(counts_by_target(&rows))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count_by_target(filter: Document) -> Vec<Document> {
|
||||||
|
vec![
|
||||||
|
doc! { "$match": filter },
|
||||||
|
doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn counts_by_target(rows: &[Document]) -> std::collections::HashMap<String, u64> {
|
||||||
|
rows.iter()
|
||||||
.filter_map(|row| {
|
.filter_map(|row| {
|
||||||
let id = row.get_str("_id").ok()?.to_string();
|
let id = row.get_str("_id").ok()?.to_string();
|
||||||
let n = row
|
let n = row
|
||||||
@@ -507,7 +543,7 @@ async fn open_findings_counts(
|
|||||||
.ok()?;
|
.ok()?;
|
||||||
Some((id, u64::try_from(n).ok()?))
|
Some((id, u64::try_from(n).ok()?))
|
||||||
})
|
})
|
||||||
.collect())
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/platform/tenants/{id}/targets?project=<id>` — the tenant's
|
/// `GET /api/v1/platform/tenants/{id}/targets?project=<id>` — the tenant's
|
||||||
@@ -538,11 +574,12 @@ pub async fn list_targets(
|
|||||||
.filter_map(|t| t.id.map(|id| id.to_hex()))
|
.filter_map(|t| t.id.map(|id| id.to_hex()))
|
||||||
.collect();
|
.collect();
|
||||||
let runs = db.scan_runs();
|
let runs = db.scan_runs();
|
||||||
let (mut last_scans, open) = tokio::join!(
|
let (mut last_scans, open, vulns) = tokio::join!(
|
||||||
super::onboarding::latest_scan_runs(&runs, ids.clone()),
|
super::onboarding::latest_scan_runs(&runs, ids.clone()),
|
||||||
open_findings_counts(&db, ids),
|
open_findings_counts(&db, ids.clone()),
|
||||||
|
open_vulnerabilities_counts(&db, ids),
|
||||||
);
|
);
|
||||||
let open = open?;
|
let (open, vulns) = (open?, vulns?);
|
||||||
let known = super::projects::tenant_projects(&st.agent, &tenant_id)
|
let known = super::projects::tenant_projects(&st.agent, &tenant_id)
|
||||||
.await
|
.await
|
||||||
.ok();
|
.ok();
|
||||||
@@ -553,6 +590,7 @@ pub async fn list_targets(
|
|||||||
PlatformTarget {
|
PlatformTarget {
|
||||||
last_scan_at: last_scans.remove(&id).map(|run| run.started_at),
|
last_scan_at: last_scans.remove(&id).map(|run| run.started_at),
|
||||||
open_findings: open.get(&id).copied().unwrap_or(0),
|
open_findings: open.get(&id).copied().unwrap_or(0),
|
||||||
|
open_vulnerabilities: vulns.get(&id).copied().unwrap_or(0),
|
||||||
project_ids: match known.as_deref() {
|
project_ids: match known.as_deref() {
|
||||||
Some(known) => super::projects::known_project_ids(&t.project_ids, known),
|
Some(known) => super::projects::known_project_ids(&t.project_ids, known),
|
||||||
None => t.project_ids,
|
None => t.project_ids,
|
||||||
@@ -782,3 +820,51 @@ mod build_info_tests {
|
|||||||
assert!(!BUILD_COMMIT.is_empty());
|
assert!(!BUILD_COMMIT.is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod target_count_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn open_vulnerabilities_leave_out_resolved_and_assessed_alerts() {
|
||||||
|
let f = open_vulnerabilities_filter(vec!["a".into(), "b".into()]);
|
||||||
|
assert_eq!(
|
||||||
|
f.get_document("repo_id")
|
||||||
|
.unwrap()
|
||||||
|
.get_array("$in")
|
||||||
|
.unwrap()
|
||||||
|
.len(),
|
||||||
|
2
|
||||||
|
);
|
||||||
|
assert_eq!(f.get("resolved_at"), Some(&mongodb::bson::Bson::Null));
|
||||||
|
let nin = f
|
||||||
|
.get_document("vex.status")
|
||||||
|
.unwrap()
|
||||||
|
.get_array("$nin")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
nin,
|
||||||
|
&vec![
|
||||||
|
mongodb::bson::Bson::from("not_affected"),
|
||||||
|
mongodb::bson::Bson::from("fixed")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn counts_are_read_per_target_whatever_the_integer_width() {
|
||||||
|
let rows = vec![
|
||||||
|
doc! { "_id": "a", "n": 3_i32 },
|
||||||
|
doc! { "_id": "b", "n": 5_i64 },
|
||||||
|
doc! { "_id": "c", "n": -1_i64 },
|
||||||
|
doc! { "n": 2_i32 },
|
||||||
|
];
|
||||||
|
let counts = counts_by_target(&rows);
|
||||||
|
assert_eq!(counts.get("a"), Some(&3));
|
||||||
|
assert_eq!(counts.get("b"), Some(&5));
|
||||||
|
assert_eq!(counts.len(), 2);
|
||||||
|
let stages = count_by_target(doc! { "x": 1 });
|
||||||
|
assert_eq!(stages.len(), 2);
|
||||||
|
assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -165,6 +165,7 @@ mod tests {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: Some("Sharang".to_string()),
|
user_name: Some("Sharang".to_string()),
|
||||||
}),
|
}),
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -87,15 +87,37 @@ pub async fn list_sbom(
|
|||||||
if let Some(in_image) = filter.in_image {
|
if let Some(in_image) = filter.in_image {
|
||||||
query.insert("in_image", doc! { "$exists": in_image });
|
query.insert("in_image", doc! { "$exists": in_image });
|
||||||
}
|
}
|
||||||
|
let conclusions = crate::license_conclusions::load(db).await;
|
||||||
|
|
||||||
let skip = filter.skip();
|
let mut skip = filter.skip();
|
||||||
let total = db
|
let mut total = None;
|
||||||
.sbom_entries()
|
if filter.unresolved == Some(true) {
|
||||||
.count_documents(query.clone())
|
// No licence found by the scan; `null` also matches a missing field.
|
||||||
.await
|
query.insert("license", doc! { "$in": [mongodb::bson::Bson::Null, ""] });
|
||||||
.unwrap_or(0);
|
if !conclusions.is_empty() {
|
||||||
|
// Which of them nobody confirmed a licence for is known only
|
||||||
|
// here, so the page is cut from the open ones.
|
||||||
|
let open = unresolved_ids(db, &query, &conclusions).await;
|
||||||
|
total = Some(open.len() as u64);
|
||||||
|
let page: Vec<_> = open
|
||||||
|
.into_iter()
|
||||||
|
.skip(usize::try_from(skip).unwrap_or(usize::MAX))
|
||||||
|
.take(usize::try_from(filter.limit).unwrap_or(0))
|
||||||
|
.collect();
|
||||||
|
query = doc! { "_id": { "$in": page } };
|
||||||
|
skip = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let total = match total {
|
||||||
|
Some(total) => total,
|
||||||
|
None => db
|
||||||
|
.sbom_entries()
|
||||||
|
.count_documents(query.clone())
|
||||||
|
.await
|
||||||
|
.unwrap_or(0),
|
||||||
|
};
|
||||||
|
|
||||||
let entries = match db
|
let mut entries: Vec<SbomEntry> = match db
|
||||||
.sbom_entries()
|
.sbom_entries()
|
||||||
.find(query)
|
.find(query)
|
||||||
.sort(list_order())
|
.sort(list_order())
|
||||||
@@ -109,6 +131,9 @@ pub async fn list_sbom(
|
|||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
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 {
|
Ok(Json(ApiResponse {
|
||||||
data: entries,
|
data: entries,
|
||||||
@@ -123,6 +148,56 @@ fn list_order() -> mongodb::bson::Document {
|
|||||||
doc! { "in_image.basis": -1, "name": 1 }
|
doc! { "in_image.basis": -1, "name": 1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The fields a licence conclusion is matched on.
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct LicenseKeyRow {
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
id: mongodb::bson::oid::ObjectId,
|
||||||
|
name: String,
|
||||||
|
version: String,
|
||||||
|
package_manager: String,
|
||||||
|
#[serde(default)]
|
||||||
|
purl: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
license: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The components of `query` (in list order) nobody confirmed a licence for.
|
||||||
|
async fn unresolved_ids(
|
||||||
|
db: &crate::database::Database,
|
||||||
|
query: &mongodb::bson::Document,
|
||||||
|
conclusions: &[compliance_core::models::LicenseConclusion],
|
||||||
|
) -> Vec<mongodb::bson::oid::ObjectId> {
|
||||||
|
let rows: Vec<LicenseKeyRow> = match db
|
||||||
|
.sbom_entries()
|
||||||
|
.clone_with_type::<LicenseKeyRow>()
|
||||||
|
.find(query.clone())
|
||||||
|
.projection(doc! { "_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1 })
|
||||||
|
.sort(list_order())
|
||||||
|
.limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("Failed to fetch open licences: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
rows.into_iter()
|
||||||
|
.filter(|r| {
|
||||||
|
compliance_core::models::license::find_for(
|
||||||
|
conclusions,
|
||||||
|
&r.name,
|
||||||
|
&r.package_manager,
|
||||||
|
&r.version,
|
||||||
|
r.purl.as_deref(),
|
||||||
|
)
|
||||||
|
.is_none()
|
||||||
|
})
|
||||||
|
.map(|r| r.id)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn export_sbom(
|
pub async fn export_sbom(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -143,7 +218,7 @@ pub async fn export_sbom(
|
|||||||
);
|
);
|
||||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
}
|
}
|
||||||
let entries: Vec<SbomEntry> = match db
|
let mut entries: Vec<SbomEntry> = match db
|
||||||
.sbom_entries()
|
.sbom_entries()
|
||||||
.find(doc! { "repo_id": ¶ms.repo_id })
|
.find(doc! { "repo_id": ¶ms.repo_id })
|
||||||
.await
|
.await
|
||||||
@@ -154,6 +229,7 @@ pub async fn export_sbom(
|
|||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
crate::license_conclusions::attach(db, &mut entries).await;
|
||||||
|
|
||||||
let body = if params.format == "spdx" {
|
let body = if params.format == "spdx" {
|
||||||
compliance_core::sbom_docs::spdx(&entries, ¶ms.repo_id)
|
compliance_core::sbom_docs::spdx(&entries, ¶ms.repo_id)
|
||||||
@@ -245,53 +321,96 @@ pub async fn license_summary(
|
|||||||
query.insert("repo_id", repo_id);
|
query.insert("repo_id", repo_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Grouped in Mongo: this used to load every SBOM entry of the tenant (with
|
// Only the fields the grouping needs, never whole entries with their
|
||||||
// its vulnerability list) into the agent when no repo was given (#67).
|
// vulnerability lists (#67). Grouped here rather than in Mongo, as a
|
||||||
#[derive(serde::Deserialize)]
|
// licence a person confirmed counts instead of the detected one.
|
||||||
struct LicenseRow {
|
let rows: Vec<LicenseKeyRow> = match db
|
||||||
#[serde(rename = "_id")]
|
.sbom_entries()
|
||||||
license: String,
|
.clone_with_type::<LicenseKeyRow>()
|
||||||
count: i64,
|
.find(query)
|
||||||
packages: Vec<String>,
|
.projection(doc! {
|
||||||
}
|
"_id": 1, "name": 1, "version": 1, "package_manager": 1, "purl": 1, "license": 1,
|
||||||
let pipeline = vec![
|
})
|
||||||
doc! { "$match": query },
|
.limit(i64::try_from(MAX_EXPORT_COMPONENTS).unwrap_or(i64::MAX))
|
||||||
doc! { "$group": {
|
.await
|
||||||
"_id": { "$ifNull": ["$license", "Unknown"] },
|
{
|
||||||
"count": { "$sum": 1 },
|
Ok(cursor) => collect_cursor_async(cursor).await,
|
||||||
"packages": { "$firstN": { "input": "$name", "n": MAX_LICENSE_PACKAGES } },
|
|
||||||
} },
|
|
||||||
];
|
|
||||||
let mut summaries: Vec<LicenseSummary> = match db.sbom_entries().aggregate(pipeline).await {
|
|
||||||
Ok(cursor) => {
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
cursor
|
|
||||||
.filter_map(|row| async move {
|
|
||||||
let row: LicenseRow = mongodb::bson::from_document(row.ok()?).ok()?;
|
|
||||||
Some(LicenseSummary {
|
|
||||||
is_copyleft: compliance_core::spdx_license::is_copyleft(&row.license),
|
|
||||||
license: row.license,
|
|
||||||
count: u64::try_from(row.count).unwrap_or(0),
|
|
||||||
packages: row.packages,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("Failed to aggregate SBOM licenses: {e}");
|
tracing::warn!("Failed to read SBOM licenses: {e}");
|
||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
summaries.sort_by_key(|s| std::cmp::Reverse(s.count));
|
let conclusions = crate::license_conclusions::load(db).await;
|
||||||
|
|
||||||
Ok(Json(ApiResponse {
|
Ok(Json(ApiResponse {
|
||||||
data: summaries,
|
data: summarize_licenses(&rows, &conclusions),
|
||||||
total: None,
|
total: None,
|
||||||
page: None,
|
page: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One summary row per licence, most components first: the confirmed
|
||||||
|
/// licence where there is one, else the detected one, else `Unknown`.
|
||||||
|
fn summarize_licenses(
|
||||||
|
rows: &[LicenseKeyRow],
|
||||||
|
conclusions: &[compliance_core::models::LicenseConclusion],
|
||||||
|
) -> Vec<LicenseSummary> {
|
||||||
|
use compliance_core::models::LicenseCategory;
|
||||||
|
use compliance_core::spdx_license;
|
||||||
|
let mut by_license: std::collections::HashMap<String, LicenseSummary> =
|
||||||
|
std::collections::HashMap::new();
|
||||||
|
for r in rows {
|
||||||
|
let concluded = compliance_core::models::license::find_for(
|
||||||
|
conclusions,
|
||||||
|
&r.name,
|
||||||
|
&r.package_manager,
|
||||||
|
&r.version,
|
||||||
|
r.purl.as_deref(),
|
||||||
|
);
|
||||||
|
let detected = r
|
||||||
|
.license
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty());
|
||||||
|
let (label, category, is_copyleft) = match (concluded, detected) {
|
||||||
|
(Some(c), _) => (
|
||||||
|
c.display().to_string(),
|
||||||
|
c.category,
|
||||||
|
c.category.is_copyleft(),
|
||||||
|
),
|
||||||
|
(None, Some(l)) => (
|
||||||
|
l.to_string(),
|
||||||
|
spdx_license::category(l),
|
||||||
|
spdx_license::is_copyleft(l),
|
||||||
|
),
|
||||||
|
(None, None) => ("Unknown".to_string(), LicenseCategory::Unclear, false),
|
||||||
|
};
|
||||||
|
let row = by_license
|
||||||
|
.entry(label.clone())
|
||||||
|
.or_insert_with(|| LicenseSummary {
|
||||||
|
license: label,
|
||||||
|
count: 0,
|
||||||
|
is_copyleft,
|
||||||
|
category,
|
||||||
|
confirmed: 0,
|
||||||
|
packages: Vec::new(),
|
||||||
|
});
|
||||||
|
row.count += 1;
|
||||||
|
if concluded.is_some() {
|
||||||
|
row.confirmed += 1;
|
||||||
|
}
|
||||||
|
if (row.packages.len() as i64) < MAX_LICENSE_PACKAGES && !row.packages.contains(&r.name) {
|
||||||
|
row.packages.push(r.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut summaries: Vec<LicenseSummary> = by_license.into_values().collect();
|
||||||
|
summaries.sort_by(|a, b| {
|
||||||
|
b.count
|
||||||
|
.cmp(&a.count)
|
||||||
|
.then_with(|| a.license.cmp(&b.license))
|
||||||
|
});
|
||||||
|
summaries
|
||||||
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all)]
|
#[tracing::instrument(skip_all)]
|
||||||
pub async fn sbom_diff(
|
pub async fn sbom_diff(
|
||||||
Extension(agent): AgentExt,
|
Extension(agent): AgentExt,
|
||||||
@@ -396,3 +515,69 @@ async fn diff_rows(db: &crate::database::Database, repo_id: &str) -> Vec<DiffRow
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod license_summary_tests {
|
||||||
|
use super::*;
|
||||||
|
use compliance_core::models::license::{conclusion_id, package_key};
|
||||||
|
use compliance_core::models::{LicenseCategory, LicenseConclusion};
|
||||||
|
|
||||||
|
fn row(name: &str, license: Option<&str>) -> LicenseKeyRow {
|
||||||
|
LicenseKeyRow {
|
||||||
|
id: mongodb::bson::oid::ObjectId::new(),
|
||||||
|
name: name.into(),
|
||||||
|
version: "1.0".into(),
|
||||||
|
package_manager: "npm".into(),
|
||||||
|
purl: Some(format!("pkg:npm/{name}@1.0")),
|
||||||
|
license: license.map(String::from),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_confirmed_licence_counts_instead_of_the_detected_one() {
|
||||||
|
let key = package_key("pump", "npm", Some("pkg:npm/pump@1.0"));
|
||||||
|
let conclusion = LicenseConclusion {
|
||||||
|
id: conclusion_id(&key, None),
|
||||||
|
package_key: key,
|
||||||
|
name: "pump".into(),
|
||||||
|
package_manager: "npm".into(),
|
||||||
|
version: None,
|
||||||
|
license: "LicenseRef-Pump-EULA".into(),
|
||||||
|
license_name: Some("Pump EULA".into()),
|
||||||
|
category: LicenseCategory::Proprietary,
|
||||||
|
copyright: Vec::new(),
|
||||||
|
license_text: None,
|
||||||
|
license_url: None,
|
||||||
|
evidence: None,
|
||||||
|
contract_ref: None,
|
||||||
|
valid_until: None,
|
||||||
|
usage: None,
|
||||||
|
note: None,
|
||||||
|
by: "u".into(),
|
||||||
|
by_name: None,
|
||||||
|
support: false,
|
||||||
|
at: chrono::Utc::now(),
|
||||||
|
review: None,
|
||||||
|
};
|
||||||
|
let rows = [
|
||||||
|
row("a", Some("MIT")),
|
||||||
|
row("b", Some("MIT")),
|
||||||
|
row("c", Some("LGPL-2.1-only")),
|
||||||
|
row("d", None),
|
||||||
|
row("pump", None),
|
||||||
|
];
|
||||||
|
let summary = summarize_licenses(&rows, &[conclusion]);
|
||||||
|
let get = |l: &str| summary.iter().find(|s| s.license == l).unwrap();
|
||||||
|
assert_eq!(summary[0].license, "MIT");
|
||||||
|
assert_eq!(get("MIT").count, 2);
|
||||||
|
assert_eq!(get("MIT").category, LicenseCategory::Permissive);
|
||||||
|
assert_eq!(get("LGPL-2.1-only").category, LicenseCategory::WeakCopyleft);
|
||||||
|
assert_eq!(
|
||||||
|
get("Unknown").count,
|
||||||
|
1,
|
||||||
|
"the confirmed one is no longer unknown"
|
||||||
|
);
|
||||||
|
assert_eq!(get("Pump EULA").confirmed, 1);
|
||||||
|
assert_eq!(get("Pump EULA").category, LicenseCategory::Proprietary);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod api_key_gate;
|
||||||
pub mod handlers;
|
pub mod handlers;
|
||||||
pub mod role_gate;
|
pub mod role_gate;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
|
|||||||
@@ -4,7 +4,9 @@
|
|||||||
//!
|
//!
|
||||||
//! * `IT_ADMIN`, `USER` — read and write.
|
//! * `IT_ADMIN`, `USER` — read and write.
|
||||||
//! * `CXO`, `LEGAL` — read only: `GET` / `HEAD` / `OPTIONS`, plus the few
|
//! * `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.
|
//! * `FINANCE`, or none of these roles — nothing; every request is refused.
|
||||||
//!
|
//!
|
||||||
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
|
//! Refusals are `403 {"error": "forbidden_role", "access": "none" | "read_only"}`.
|
||||||
@@ -17,6 +19,10 @@
|
|||||||
//! check, and support staff who have not chosen a tenant yet.
|
//! check, and support staff who have not chosen a tenant yet.
|
||||||
//!
|
//!
|
||||||
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
|
//! Handlers may still be stricter (manual findings stay `IT_ADMIN`-only).
|
||||||
|
//!
|
||||||
|
//! API keys (tenant-registry ADR 0001) hold no role. They reach only the
|
||||||
|
//! routes in [`KEY_SCOPES`], each with the scope it names; every other route
|
||||||
|
//! answers `403 {"error": "scope_missing"}`.
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
extract::{MatchedPath, Request},
|
extract::{MatchedPath, Request},
|
||||||
@@ -25,11 +31,81 @@ use axum::{
|
|||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
Json,
|
Json,
|
||||||
};
|
};
|
||||||
use compliance_core::{ProductAccess, TenantContext};
|
use compliance_core::{ApiKeyAccess, OrgRole, ProductAccess, TenantContext};
|
||||||
|
|
||||||
/// The JSON `error` of a refusal.
|
/// The JSON `error` of a refusal.
|
||||||
pub const FORBIDDEN_ROLE: &str = "forbidden_role";
|
pub const FORBIDDEN_ROLE: &str = "forbidden_role";
|
||||||
|
|
||||||
|
/// The JSON `error` when an API key lacks the route's scope, or the route
|
||||||
|
/// takes no key at all.
|
||||||
|
pub const SCOPE_MISSING: &str = "scope_missing";
|
||||||
|
|
||||||
|
/// Every route an API key may call: method, route template, required scope.
|
||||||
|
/// Anything not listed (manual findings, credentials, target admin,
|
||||||
|
/// settings, releasing an ENISA draft) is unreachable with a key.
|
||||||
|
pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
|
||||||
|
(Method::GET, "/api/v1/findings", FINDINGS_READ),
|
||||||
|
(Method::GET, "/api/v1/findings/variants", FINDINGS_READ),
|
||||||
|
(Method::GET, "/api/v1/findings/{id}", FINDINGS_READ),
|
||||||
|
(
|
||||||
|
Method::PATCH,
|
||||||
|
"/api/v1/findings/{id}/status",
|
||||||
|
FINDINGS_WRITE,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Method::PATCH,
|
||||||
|
"/api/v1/findings/bulk-status",
|
||||||
|
FINDINGS_WRITE,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Method::PATCH,
|
||||||
|
"/api/v1/findings/{id}/feedback",
|
||||||
|
FINDINGS_WRITE,
|
||||||
|
),
|
||||||
|
(Method::GET, "/api/v1/sbom", SBOM_READ),
|
||||||
|
(Method::GET, "/api/v1/sbom/filters", SBOM_READ),
|
||||||
|
(Method::GET, "/api/v1/sbom/export", SBOM_READ),
|
||||||
|
(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),
|
||||||
|
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
||||||
|
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
||||||
|
];
|
||||||
|
|
||||||
|
const FINDINGS_READ: &str = "pruefwerk:findings.read";
|
||||||
|
const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
|
||||||
|
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
||||||
|
const SCANS_READ: &str = "pruefwerk:scans.read";
|
||||||
|
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
||||||
|
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
||||||
|
|
||||||
|
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
||||||
|
/// read, never write or run. Such keys never reached this API before.
|
||||||
|
pub const LEGACY_SCOPES: &[&str] = &[FINDINGS_READ, SBOM_READ, SCANS_READ, ENISA_READ];
|
||||||
|
|
||||||
|
/// The scope `key` lacks for `method` on `template`, if any. A route that is
|
||||||
|
/// not in [`KEY_SCOPES`] (or matched no route) lacks `None`: no scope opens it.
|
||||||
|
pub fn key_refusal(
|
||||||
|
key: &ApiKeyAccess,
|
||||||
|
method: &Method,
|
||||||
|
template: Option<&str>,
|
||||||
|
) -> Option<Option<&'static str>> {
|
||||||
|
let required = KEY_SCOPES
|
||||||
|
.iter()
|
||||||
|
.find(|(m, t, _)| m == method && Some(*t) == template)
|
||||||
|
.map(|(_, _, scope)| *scope);
|
||||||
|
match required {
|
||||||
|
Some(scope) if key.has_scope(scope) => None,
|
||||||
|
missing => Some(missing),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// `POST` routes that only read: a query or an export with a body. Matched
|
/// `POST` routes that only read: a query or an export with a body. Matched
|
||||||
/// against the route template, so an id in the path does not matter. Every
|
/// against the route template, so an id in the path does not matter. Every
|
||||||
/// other `POST`, `PUT`, `PATCH` and `DELETE` is a write.
|
/// other `POST`, `PUT`, `PATCH` and `DELETE` is a write.
|
||||||
@@ -44,6 +120,21 @@ pub const READ_ONLY_POSTS: &[&str] = &[
|
|||||||
"/api/v1/help/chat",
|
"/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.
|
/// Whether a request with `method` to the route `template` changes anything.
|
||||||
/// A request that matched no route counts by its method alone.
|
/// A request that matched no route counts by its method alone.
|
||||||
pub fn is_write(method: &Method, template: Option<&str>) -> bool {
|
pub fn is_write(method: &Method, template: Option<&str>) -> bool {
|
||||||
@@ -62,6 +153,7 @@ pub fn refusal(
|
|||||||
match ctx.product_access() {
|
match ctx.product_access() {
|
||||||
ProductAccess::Full => None,
|
ProductAccess::Full => None,
|
||||||
ProductAccess::ReadOnly if !is_write(method, template) => None,
|
ProductAccess::ReadOnly if !is_write(method, template) => None,
|
||||||
|
ProductAccess::ReadOnly if role_may_write(ctx, method, template) => None,
|
||||||
denied => Some(denied),
|
denied => Some(denied),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,6 +168,24 @@ pub async fn require_org_role(request: Request, next: Next) -> Response {
|
|||||||
.extensions()
|
.extensions()
|
||||||
.get::<MatchedPath>()
|
.get::<MatchedPath>()
|
||||||
.map(MatchedPath::as_str);
|
.map(MatchedPath::as_str);
|
||||||
|
if let Some(key) = ctx.api_key.as_ref() {
|
||||||
|
let Some(required) = key_refusal(key, request.method(), template) else {
|
||||||
|
return next.run(request).await;
|
||||||
|
};
|
||||||
|
tracing::info!(
|
||||||
|
tenant_id = %ctx.tenant_id,
|
||||||
|
key_id = %key.key_id,
|
||||||
|
method = %request.method(),
|
||||||
|
route = template.unwrap_or("-"),
|
||||||
|
required = required.unwrap_or("-"),
|
||||||
|
"request refused: API key scope"
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
Json(serde_json::json!({ "error": SCOPE_MISSING, "required": required })),
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
let Some(access) = refusal(ctx, request.method(), template) else {
|
let Some(access) = refusal(ctx, request.method(), template) else {
|
||||||
return next.run(request).await;
|
return next.run(request).await;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
//! these tests, so a request the gate lets through fails later (500, missing
|
//! these tests, so a request the gate lets through fails later (500, missing
|
||||||
//! extension); what is checked is only whether the gate refused it.
|
//! extension); what is checked is only whether the gate refused it.
|
||||||
|
|
||||||
use super::{require_org_role, READ_ONLY_POSTS};
|
use super::{require_org_role, KEY_SCOPES, LEGACY_SCOPES, READ_ONLY_POSTS, ROLE_WRITES};
|
||||||
use crate::api::routes::build_router;
|
use crate::api::routes::build_router;
|
||||||
use axum::{
|
use axum::{
|
||||||
body::{to_bytes, Body},
|
body::{to_bytes, Body},
|
||||||
@@ -13,7 +13,7 @@ use axum::{
|
|||||||
middleware::{from_fn, Next},
|
middleware::{from_fn, Next},
|
||||||
Router,
|
Router,
|
||||||
};
|
};
|
||||||
use compliance_core::{OrgRole, StaffAccess, TenantContext, TenantStatus};
|
use compliance_core::{ApiKeyAccess, OrgRole, StaffAccess, TenantContext, TenantStatus};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
/// Who is calling.
|
/// Who is calling.
|
||||||
@@ -29,6 +29,8 @@ enum Caller {
|
|||||||
Staff,
|
Staff,
|
||||||
/// A service / machine client: no tenant context reaches the gate.
|
/// A service / machine client: no tenant context reaches the gate.
|
||||||
Service,
|
Service,
|
||||||
|
/// A portal-issued API key with these scopes (no org roles).
|
||||||
|
Key(&'static [&'static str]),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ctx(caller: Caller) -> Option<TenantContext> {
|
fn ctx(caller: Caller) -> Option<TenantContext> {
|
||||||
@@ -38,7 +40,7 @@ fn ctx(caller: Caller) -> Option<TenantContext> {
|
|||||||
Caller::Cxo => vec![OrgRole::Cxo],
|
Caller::Cxo => vec![OrgRole::Cxo],
|
||||||
Caller::Legal => vec![OrgRole::Legal],
|
Caller::Legal => vec![OrgRole::Legal],
|
||||||
Caller::Finance => vec![OrgRole::Finance],
|
Caller::Finance => vec![OrgRole::Finance],
|
||||||
Caller::NoRoles | Caller::Staff => vec![],
|
Caller::NoRoles | Caller::Staff | Caller::Key(_) => vec![],
|
||||||
Caller::Service => return None,
|
Caller::Service => return None,
|
||||||
};
|
};
|
||||||
Some(TenantContext {
|
Some(TenantContext {
|
||||||
@@ -54,6 +56,17 @@ fn ctx(caller: Caller) -> Option<TenantContext> {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
}),
|
}),
|
||||||
|
api_key: match caller {
|
||||||
|
Caller::Key(scopes) => Some(Box::new(ApiKeyAccess {
|
||||||
|
key_id: "k-1".to_string(),
|
||||||
|
kind: "service".to_string(),
|
||||||
|
holder: None,
|
||||||
|
scopes: scopes.iter().map(|s| (*s).to_string()).collect(),
|
||||||
|
legacy: false,
|
||||||
|
on_behalf_of: None,
|
||||||
|
})),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +89,11 @@ fn router(caller: Caller) -> Router {
|
|||||||
|
|
||||||
/// Whether the gate refused the request (403 `forbidden_role`).
|
/// Whether the gate refused the request (403 `forbidden_role`).
|
||||||
async fn refused(caller: Caller, method: Method, path: &str) -> bool {
|
async fn refused(caller: Caller, method: Method, path: &str) -> bool {
|
||||||
|
refusal(caller, method, path).await.as_deref() == Some("forbidden_role")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gate's `error`, if it refused the request.
|
||||||
|
async fn refusal(caller: Caller, method: Method, path: &str) -> Option<String> {
|
||||||
let req = Request::builder()
|
let req = Request::builder()
|
||||||
.method(method)
|
.method(method)
|
||||||
.uri(path)
|
.uri(path)
|
||||||
@@ -84,11 +102,11 @@ async fn refused(caller: Caller, method: Method, path: &str) -> bool {
|
|||||||
.expect("request");
|
.expect("request");
|
||||||
let resp = router(caller).oneshot(req).await.expect("oneshot");
|
let resp = router(caller).oneshot(req).await.expect("oneshot");
|
||||||
if resp.status() != StatusCode::FORBIDDEN {
|
if resp.status() != StatusCode::FORBIDDEN {
|
||||||
return false;
|
return None;
|
||||||
}
|
}
|
||||||
let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body");
|
let body = to_bytes(resp.into_body(), 64 * 1024).await.expect("body");
|
||||||
let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
|
let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
|
||||||
json["error"] == "forbidden_role"
|
json["error"].as_str().map(str::to_owned)
|
||||||
}
|
}
|
||||||
|
|
||||||
const ID: &str = "65f000000000000000000001";
|
const ID: &str = "65f000000000000000000001";
|
||||||
@@ -125,6 +143,16 @@ fn routes() -> Vec<(Method, String, bool)> {
|
|||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
(Method::GET, "/api/v1/sbom/export".into(), false),
|
(Method::GET, "/api/v1/sbom/export".into(), false),
|
||||||
|
(Method::GET, "/api/v1/licenses/conclusions".into(), false),
|
||||||
|
(Method::PUT, "/api/v1/licenses/conclusions".into(), true),
|
||||||
|
(
|
||||||
|
Method::DELETE,
|
||||||
|
"/api/v1/licenses/conclusions?id=pkg%3Anpm%2Fa%40*".into(),
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
(Method::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::POST, "/api/v1/mcp-tokens".into(), true),
|
||||||
(Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true),
|
(Method::DELETE, format!("/api/v1/mcp-tokens/{ID}"), true),
|
||||||
(Method::POST, "/api/v1/notifications/read-all".into(), true),
|
(Method::POST, "/api/v1/notifications/read-all".into(), true),
|
||||||
@@ -166,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]
|
#[tokio::test]
|
||||||
async fn every_read_only_post_is_a_real_route() {
|
async fn every_read_only_post_is_a_real_route() {
|
||||||
// A template that no longer matches a route would silently turn back
|
// A template that no longer matches a route would silently turn back
|
||||||
@@ -211,3 +287,133 @@ async fn a_refusal_says_which_access_the_role_has() {
|
|||||||
serde_json::json!({ "error": "forbidden_role", "access": "none" })
|
serde_json::json!({ "error": "forbidden_role", "access": "none" })
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every scope of the key table.
|
||||||
|
const ALL_SCOPES: &[&str] = &[
|
||||||
|
"pruefwerk:findings.write",
|
||||||
|
"pruefwerk:sbom.read",
|
||||||
|
"pruefwerk:scans.read",
|
||||||
|
"pruefwerk:scans.run",
|
||||||
|
"pruefwerk:enisa.read",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn concrete(template: &str) -> String {
|
||||||
|
template.replace("{id}", ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn every_key_route_is_real_and_needs_its_scope() {
|
||||||
|
for (method, template, scope) in KEY_SCOPES {
|
||||||
|
let path = concrete(template);
|
||||||
|
// A template that matches no route would refuse every key.
|
||||||
|
assert_eq!(
|
||||||
|
refusal(Caller::Key(ALL_SCOPES), method.clone(), &path).await,
|
||||||
|
None,
|
||||||
|
"{method} {template}"
|
||||||
|
);
|
||||||
|
let lacking_sets: [&'static [&'static str]; 2] = [&[], &["werkbank:runner"]];
|
||||||
|
for lacking in lacking_sets {
|
||||||
|
assert_eq!(
|
||||||
|
refusal(Caller::Key(lacking), method.clone(), &path)
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing"),
|
||||||
|
"{method} {template} {lacking:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Another row's scope does not open this one.
|
||||||
|
let other = KEY_SCOPES
|
||||||
|
.iter()
|
||||||
|
.map(|(_, _, s)| *s)
|
||||||
|
.find(|s| s.split('.').next() != scope.split('.').next())
|
||||||
|
.expect("the table has several scope families");
|
||||||
|
let other = ALL_SCOPES
|
||||||
|
.iter()
|
||||||
|
.find(|s| s.split('.').next() == other.split('.').next())
|
||||||
|
.expect("every family is in ALL_SCOPES");
|
||||||
|
assert_eq!(
|
||||||
|
refusal(
|
||||||
|
Caller::Key(std::slice::from_ref(other)),
|
||||||
|
method.clone(),
|
||||||
|
&path
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing"),
|
||||||
|
"{method} {template} {other}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_write_scope_grants_the_read_but_not_the_reverse() {
|
||||||
|
let path = format!("/api/v1/findings/{ID}");
|
||||||
|
let write = Caller::Key(&["pruefwerk:findings.write"]);
|
||||||
|
let read = Caller::Key(&["pruefwerk:findings.read"]);
|
||||||
|
assert_eq!(refusal(write, Method::GET, &path).await, None);
|
||||||
|
assert_eq!(refusal(read, Method::GET, &path).await, None);
|
||||||
|
assert_eq!(
|
||||||
|
refusal(read, Method::PATCH, &format!("{path}/status"))
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing")
|
||||||
|
);
|
||||||
|
// `scans.run` is not a write of `scans.read`.
|
||||||
|
assert_eq!(
|
||||||
|
refusal(
|
||||||
|
Caller::Key(&["pruefwerk:scans.run"]),
|
||||||
|
Method::GET,
|
||||||
|
"/api/v1/scan-runs"
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_key_reaches_nothing_outside_the_table() {
|
||||||
|
let in_table = |m: &Method, p: &str| {
|
||||||
|
KEY_SCOPES
|
||||||
|
.iter()
|
||||||
|
.any(|(km, t, _)| km == m && concrete(t) == p)
|
||||||
|
};
|
||||||
|
for (method, path, _) in routes() {
|
||||||
|
if in_table(&method, &path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
refusal(Caller::Key(ALL_SCOPES), method.clone(), &path)
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing"),
|
||||||
|
"{method} {path}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A listed route with another method is not listed.
|
||||||
|
assert_eq!(
|
||||||
|
refusal(
|
||||||
|
Caller::Key(ALL_SCOPES),
|
||||||
|
Method::DELETE,
|
||||||
|
&format!("/api/v1/findings/{ID}")
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.as_deref(),
|
||||||
|
Some("scope_missing")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_legacy_key_reads_but_never_writes_or_runs() {
|
||||||
|
let legacy = Caller::Key(LEGACY_SCOPES);
|
||||||
|
for (method, template, scope) in KEY_SCOPES {
|
||||||
|
let read = scope.ends_with(".read");
|
||||||
|
assert_eq!(
|
||||||
|
refusal(legacy, method.clone(), &concrete(template))
|
||||||
|
.await
|
||||||
|
.is_none(),
|
||||||
|
read,
|
||||||
|
"{method} {template}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -145,6 +145,25 @@ pub fn build_router() -> Router {
|
|||||||
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
|
.route("/api/v1/sbom/licenses", get(handlers::license_summary))
|
||||||
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
|
.route("/api/v1/sbom/quality", get(handlers::sbom_quality))
|
||||||
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
|
.route("/api/v1/sbom/diff", get(handlers::sbom_diff))
|
||||||
|
// Licences the workspace confirms for its components.
|
||||||
|
.route(
|
||||||
|
"/api/v1/licenses/conclusions",
|
||||||
|
get(handlers::licenses::list_conclusions)
|
||||||
|
.put(handlers::licenses::conclude)
|
||||||
|
.delete(handlers::licenses::withdraw),
|
||||||
|
)
|
||||||
|
// 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/issues", get(handlers::list_issues))
|
||||||
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
|
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
|
||||||
// MCP token management (per-tenant API tokens for the MCP server)
|
// MCP token management (per-tenant API tokens for the MCP server)
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ pub async fn inject_dev_tenant(mut request: Request, next: Next) -> Response {
|
|||||||
user_id: "dev-user".to_string(),
|
user_id: "dev-user".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
};
|
};
|
||||||
request.extensions_mut().insert(ctx);
|
request.extensions_mut().insert(ctx);
|
||||||
}
|
}
|
||||||
@@ -114,6 +115,11 @@ pub async fn require_entitlement(
|
|||||||
let Some(ctx) = request.extensions().get::<TenantContext>().cloned() else {
|
let Some(ctx) = request.extensions().get::<TenantContext>().cloned() else {
|
||||||
return next.run(request).await;
|
return next.run(request).await;
|
||||||
};
|
};
|
||||||
|
// An API key: the registry's verify answer already intersected its
|
||||||
|
// scopes with the tenant's entitlements and carried the ladder status.
|
||||||
|
if ctx.api_key.is_some() {
|
||||||
|
return next.run(request).await;
|
||||||
|
}
|
||||||
// A person's token (support took its own branch above; service tokens
|
// A person's token (support took its own branch above; service tokens
|
||||||
// carry no tenant context here): the registry also says whether this
|
// carry no tenant context here): the registry also says whether this
|
||||||
// member is blocked in the tenant.
|
// member is blocked in the tenant.
|
||||||
@@ -182,11 +188,11 @@ fn confirmed_support_context(
|
|||||||
ctx
|
ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Record every change BreakPilot support makes in a tenant, refused ones
|
/// Record every change BreakPilot support or an API key makes in a tenant,
|
||||||
/// included, in the platform's audit log. Reads are not logged one by one;
|
/// refused ones included, in the platform's audit log. Reads are not logged
|
||||||
/// opening a tenant is (`POST /api/v1/support/session`). Background and
|
/// one by one; opening a tenant is (`POST /api/v1/support/session`).
|
||||||
/// best-effort: an unreachable registry never blocks support.
|
/// Background and best-effort: an unreachable registry never blocks either.
|
||||||
pub async fn audit_support_writes(
|
pub async fn audit_delegated_writes(
|
||||||
State(agent): State<Arc<ComplianceAgent>>,
|
State(agent): State<Arc<ComplianceAgent>>,
|
||||||
request: Request,
|
request: Request,
|
||||||
next: Next,
|
next: Next,
|
||||||
@@ -194,10 +200,16 @@ pub async fn audit_support_writes(
|
|||||||
let staff_ctx = request
|
let staff_ctx = request
|
||||||
.extensions()
|
.extensions()
|
||||||
.get::<TenantContext>()
|
.get::<TenantContext>()
|
||||||
.filter(|c| c.staff.is_some())
|
.filter(|c| c.staff.is_some() || c.api_key.is_some())
|
||||||
.cloned();
|
.cloned();
|
||||||
let method = request.method().clone();
|
let method = request.method().clone();
|
||||||
let path = request.uri().path().to_string();
|
let path = request.uri().path().to_string();
|
||||||
|
// Only the API host's proxy sets this header, and it overwrites whatever
|
||||||
|
// the caller sent; support requests arrive through the dashboard.
|
||||||
|
let client_ip = staff_ctx
|
||||||
|
.as_ref()
|
||||||
|
.filter(|c| c.api_key.is_some())
|
||||||
|
.and_then(|_| client_ip(request.headers()));
|
||||||
let response = next.run(request).await;
|
let response = next.run(request).await;
|
||||||
let (Some(ctx), Some(registry)) = (staff_ctx, agent.registry.clone()) else {
|
let (Some(ctx), Some(registry)) = (staff_ctx, agent.registry.clone()) else {
|
||||||
return response;
|
return response;
|
||||||
@@ -205,26 +217,50 @@ pub async fn audit_support_writes(
|
|||||||
if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) {
|
if matches!(method, Method::GET | Method::HEAD | Method::OPTIONS) {
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
let entry = support_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
|
let mut entry = delegated_audit_entry(&ctx, method.as_str(), &path, response.status().as_u16());
|
||||||
|
entry.source_ip = client_ip.map(|ip| ip.to_string()).unwrap_or_default();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = registry.append_audit(&entry).await {
|
if let Err(e) = registry.append_audit(&entry).await {
|
||||||
tracing::warn!(tenant_id = %entry.tenant_id, "support audit not recorded: {e}");
|
tracing::warn!(tenant_id = %entry.tenant_id, "write audit not recorded: {e}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
response
|
response
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The audit entry for a support request. The path names the resource; the
|
/// The header the API host's proxy puts the caller's address in
|
||||||
/// query and body are left out, as they may carry customer data.
|
/// (orca-platform `pruefwerk-*/api-proxy.conf`).
|
||||||
fn support_audit_entry(
|
const CLIENT_IP_HEADER: &str = "x-bp-client-ip";
|
||||||
|
|
||||||
|
/// The caller's address from [`CLIENT_IP_HEADER`], or `None` when it is
|
||||||
|
/// missing or not an IP address (the registry stores it as Postgres `inet`,
|
||||||
|
/// which would refuse the whole entry).
|
||||||
|
fn client_ip(headers: &axum::http::HeaderMap) -> Option<std::net::IpAddr> {
|
||||||
|
headers
|
||||||
|
.get(CLIENT_IP_HEADER)?
|
||||||
|
.to_str()
|
||||||
|
.ok()?
|
||||||
|
.trim()
|
||||||
|
.parse()
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audit entry for a support or API-key request. The path names the
|
||||||
|
/// resource; the query and body are left out, as they may carry customer
|
||||||
|
/// data.
|
||||||
|
fn delegated_audit_entry(
|
||||||
ctx: &TenantContext,
|
ctx: &TenantContext,
|
||||||
method: &str,
|
method: &str,
|
||||||
path: &str,
|
path: &str,
|
||||||
status: u16,
|
status: u16,
|
||||||
) -> crate::registry::AuditEntry {
|
) -> crate::registry::AuditEntry {
|
||||||
|
let action = if ctx.api_key.is_some() {
|
||||||
|
"pruefwerk.api_key_write"
|
||||||
|
} else {
|
||||||
|
"pruefwerk.support_access"
|
||||||
|
};
|
||||||
crate::registry::AuditEntry::by(
|
crate::registry::AuditEntry::by(
|
||||||
ctx,
|
ctx,
|
||||||
"pruefwerk.support_access",
|
action,
|
||||||
serde_json::json!({ "method": method, "path": path, "status": status }),
|
serde_json::json!({ "method": method, "path": path, "status": status }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -433,13 +469,14 @@ pub async fn start_api_server(
|
|||||||
registry = agent.registry.is_some(),
|
registry = agent.registry.is_some(),
|
||||||
"Keycloak JWT auth enabled"
|
"Keycloak JWT auth enabled"
|
||||||
);
|
);
|
||||||
// Layers execute outermost-first: Extension(jwks) → JWT → org roles
|
// Layers execute outermost-first: Extension(jwks) → API key → JWT →
|
||||||
// → entitlement (registry) → support audit → status ladder → handlers.
|
// org roles / key scopes → entitlement (registry) → support and key
|
||||||
|
// audit → status ladder → handlers.
|
||||||
app = app
|
app = app
|
||||||
.layer(middleware::from_fn(require_tenant_status))
|
.layer(middleware::from_fn(require_tenant_status))
|
||||||
.layer(middleware::from_fn_with_state(
|
.layer(middleware::from_fn_with_state(
|
||||||
shared.clone(),
|
shared.clone(),
|
||||||
audit_support_writes,
|
audit_delegated_writes,
|
||||||
))
|
))
|
||||||
.layer(middleware::from_fn_with_state(
|
.layer(middleware::from_fn_with_state(
|
||||||
shared.clone(),
|
shared.clone(),
|
||||||
@@ -447,6 +484,10 @@ pub async fn start_api_server(
|
|||||||
))
|
))
|
||||||
.layer(middleware::from_fn(role_gate::require_org_role))
|
.layer(middleware::from_fn(role_gate::require_org_role))
|
||||||
.layer(middleware::from_fn(require_jwt_auth))
|
.layer(middleware::from_fn(require_jwt_auth))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
shared.clone(),
|
||||||
|
super::api_key_gate::require_api_key,
|
||||||
|
))
|
||||||
.layer(Extension(jwks_state));
|
.layer(Extension(jwks_state));
|
||||||
} else if agent.config.app_env.is_hardened() {
|
} else if agent.config.app_env.is_hardened() {
|
||||||
// `validate_deployment` rejects this configuration at load time; this
|
// `validate_deployment` rejects this configuration at load time; this
|
||||||
@@ -502,6 +543,7 @@ mod support_tests {
|
|||||||
user_id: "s-1".to_string(),
|
user_id: "s-1".to_string(),
|
||||||
user_name: Some("Sharang".to_string()),
|
user_name: Some("Sharang".to_string()),
|
||||||
}),
|
}),
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,10 +569,30 @@ mod support_tests {
|
|||||||
assert_eq!(ctx.status, TenantStatus::Restricted);
|
assert_eq!(ctx.status, TenantStatus::Restricted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_client_ip_is_taken_only_when_it_is_an_address() {
|
||||||
|
let headers = |value: &str| {
|
||||||
|
let mut map = axum::http::HeaderMap::new();
|
||||||
|
map.insert(CLIENT_IP_HEADER, HeaderValue::from_str(value).unwrap());
|
||||||
|
map
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
client_ip(&headers(" 203.0.113.7 ")).map(|ip| ip.to_string()),
|
||||||
|
Some("203.0.113.7".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client_ip(&headers("2001:db8::1")).map(|ip| ip.to_string()),
|
||||||
|
Some("2001:db8::1".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(client_ip(&headers("203.0.113.7, 10.0.0.1")), None);
|
||||||
|
assert_eq!(client_ip(&headers("evil")), None);
|
||||||
|
assert_eq!(client_ip(&axum::http::HeaderMap::new()), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_support_change_is_audited_without_its_content() {
|
fn a_support_change_is_audited_without_its_content() {
|
||||||
let entry =
|
let entry =
|
||||||
support_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
|
delegated_audit_entry(&support_ctx(), "PATCH", "/api/v1/findings/abc/status", 200);
|
||||||
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
|
assert_eq!(entry.tenant_id, "00000000-0000-0000-0000-000000000002");
|
||||||
assert_eq!(entry.action, "pruefwerk.support_access");
|
assert_eq!(entry.action, "pruefwerk.support_access");
|
||||||
assert_eq!(entry.actor_id, "s-1");
|
assert_eq!(entry.actor_id, "s-1");
|
||||||
|
|||||||
@@ -334,6 +334,15 @@ impl Database {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
// license_conclusions: looked up by package (the _id is package + version)
|
||||||
|
self.license_conclusions()
|
||||||
|
.create_index(
|
||||||
|
IndexModel::builder()
|
||||||
|
.keys(doc! { "package_key": 1 })
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
// cve_alerts: unique cve_id + repo_id
|
// cve_alerts: unique cve_id + repo_id
|
||||||
self.cve_alerts()
|
self.cve_alerts()
|
||||||
.create_index(
|
.create_index(
|
||||||
@@ -646,6 +655,17 @@ impl Database {
|
|||||||
self.inner.collection("sbom_entries")
|
self.inner.collection("sbom_entries")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Licences the workspace confirmed for its packages; merged into the
|
||||||
|
/// components when they are read (see [`crate::license_conclusions`]).
|
||||||
|
pub fn license_conclusions(&self) -> Collection<LicenseConclusion> {
|
||||||
|
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<compliance_core::models::LicensePolicy> {
|
||||||
|
self.inner.collection("license_policy")
|
||||||
|
}
|
||||||
|
|
||||||
pub fn cve_alerts(&self) -> Collection<CveAlert> {
|
pub fn cve_alerts(&self) -> Collection<CveAlert> {
|
||||||
self.inner.collection("cve_alerts")
|
self.inner.collection("cve_alerts")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ pub struct EvidenceInputs {
|
|||||||
pub catalog: std::collections::HashMap<String, compliance_core::traits::Control>,
|
pub catalog: std::collections::HashMap<String, compliance_core::traits::Control>,
|
||||||
/// Who states the VEX (the workspace); the target's name when empty.
|
/// Who states the VEX (the workspace); the target's name when empty.
|
||||||
pub author: String,
|
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.
|
/// One file of the pack, as `manifest.json` lists it.
|
||||||
@@ -62,6 +64,36 @@ struct Manifest {
|
|||||||
files: Vec<ManifestFile>,
|
files: Vec<ManifestFile>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the licence policy says about each component of the pack's SBOM.
|
||||||
|
fn license_check(inputs: &EvidenceInputs, at: DateTime<Utc>) -> serde_json::Value {
|
||||||
|
use compliance_core::models::license_policy::{evaluate, VerdictCounts};
|
||||||
|
let today = at.date_naive();
|
||||||
|
let mut counts = VerdictCounts::default();
|
||||||
|
let components: Vec<serde_json::Value> = 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.
|
/// The pack as a ZIP, and the manifest's file list.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
@@ -133,6 +165,21 @@ pub fn build_pack(
|
|||||||
if !enisa.is_empty() {
|
if !enisa.is_empty() {
|
||||||
files.push(("enisa-drafts.json", json(&enisa)?));
|
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
|
// The SBOM's quality score of the last scan (sbomqs, #496), when it was
|
||||||
// scored.
|
// scored.
|
||||||
if let Some(quality) = sbom_quality(inputs) {
|
if let Some(quality) = sbom_quality(inputs) {
|
||||||
@@ -378,6 +425,7 @@ mod tests {
|
|||||||
last_run: None,
|
last_run: None,
|
||||||
catalog: Default::default(),
|
catalog: Default::default(),
|
||||||
author: String::new(),
|
author: String::new(),
|
||||||
|
license_policy: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -488,11 +536,13 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
names,
|
names,
|
||||||
[
|
[
|
||||||
|
"THIRD-PARTY-NOTICES.txt",
|
||||||
"cra-compliance.json",
|
"cra-compliance.json",
|
||||||
"csaf-vex.json",
|
"csaf-vex.json",
|
||||||
"cve-alerts.json",
|
"cve-alerts.json",
|
||||||
"findings.csv",
|
"findings.csv",
|
||||||
"findings.json",
|
"findings.json",
|
||||||
|
"license-check.json",
|
||||||
"manifest.json",
|
"manifest.json",
|
||||||
"oscal-assessment-results.json",
|
"oscal-assessment-results.json",
|
||||||
"sbom.cdx.json",
|
"sbom.cdx.json",
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ pub mod fixtures;
|
|||||||
pub mod git_source;
|
pub mod git_source;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod ingest;
|
pub mod ingest;
|
||||||
|
pub mod license_conclusions;
|
||||||
pub mod lifecycle;
|
pub mod lifecycle;
|
||||||
pub mod llm;
|
pub mod llm;
|
||||||
pub mod pentest;
|
pub mod pentest;
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
//! The licences a workspace confirmed, merged into its
|
||||||
|
//! components wherever they are read: the SBOM list and licence summary, the
|
||||||
|
//! SBOM exports, the evidence pack and the SBOM quality score. A scan
|
||||||
|
//! rewrites the components, so the conclusions live in their own collection.
|
||||||
|
|
||||||
|
use compliance_core::models::license::{self, LicenseConclusion};
|
||||||
|
use compliance_core::models::license_policy::{self, LicensePolicy};
|
||||||
|
use compliance_core::models::SbomEntry;
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
|
||||||
|
use crate::database::Database;
|
||||||
|
|
||||||
|
/// The most conclusions one workspace keeps. Each is a person's decision,
|
||||||
|
/// so a workspace reaching this is far beyond normal use.
|
||||||
|
pub const MAX_CONCLUSIONS: i64 = 50_000;
|
||||||
|
|
||||||
|
/// Every conclusion of the workspace, by package name. Empty when they
|
||||||
|
/// cannot be read: the components then show what the scan found.
|
||||||
|
pub async fn load(db: &Database) -> Vec<LicenseConclusion> {
|
||||||
|
let found = db
|
||||||
|
.license_conclusions()
|
||||||
|
.find(doc! {})
|
||||||
|
.sort(doc! { "name": 1, "_id": 1 })
|
||||||
|
.limit(MAX_CONCLUSIONS)
|
||||||
|
.await;
|
||||||
|
match found {
|
||||||
|
Ok(cursor) => cursor.try_collect().await.unwrap_or_else(|e| {
|
||||||
|
tracing::warn!("license conclusions not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("license conclusions not read: {e}");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attach to `entries` the conclusions that apply to them.
|
||||||
|
pub async fn attach(db: &Database, entries: &mut [SbomEntry]) {
|
||||||
|
if entries.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let conclusions = load(db).await;
|
||||||
|
license::apply(entries, &conclusions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,15 +22,24 @@ use crate::pipeline::dotnet::config::{into_finding, Hit};
|
|||||||
/// The scanner name of these findings.
|
/// The scanner name of these findings.
|
||||||
pub const SCANNER: &str = "build-lifecycle";
|
pub const SCANNER: &str = "build-lifecycle";
|
||||||
|
|
||||||
/// Below this Android API level (Android 10) no Android release receives
|
/// The oldest Android release that still receives security updates, from
|
||||||
/// security updates any more.
|
/// the bundled table (`data/eol/platforms.json`): its API level, below which
|
||||||
const OLDEST_PATCHED_ANDROID_API: u32 = 29;
|
/// no release is patched, and its name.
|
||||||
|
fn android_floor() -> Option<(u32, &'static str)> {
|
||||||
|
crate::pipeline::eol_tables::platforms().map(|p| {
|
||||||
|
(
|
||||||
|
p.android.oldest_patched_api,
|
||||||
|
p.android.oldest_patched_release.as_str(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The oldest iOS release that still receives security updates: iOS 15 got
|
/// The oldest iOS release that still receives security updates, from the
|
||||||
/// 15.8.8 in May 2026, while iOS 14 was last updated in October 2021 and the
|
/// bundled table (`data/eol/platforms.json`); judged conservatively: below
|
||||||
/// older iOS 12 line in January 2026, both now end of life (endoflife.date).
|
/// it is certainly unpatched.
|
||||||
/// Judged conservatively like Unity: below it is certainly unpatched.
|
fn ios_floor() -> Option<(u32, u32)> {
|
||||||
const OLDEST_PATCHED_IOS: (u32, u32) = (15, 0);
|
crate::pipeline::eol_tables::platforms().and_then(|p| version_pair(&p.ios.oldest_patched))
|
||||||
|
}
|
||||||
|
|
||||||
/// The oldest Swift language version a supported Xcode builds: Xcode 10.2
|
/// The oldest Swift language version a supported Xcode builds: Xcode 10.2
|
||||||
/// dropped Swift 3 mode, and current Swift compilers accept 4, 4.2, 5 and 6.
|
/// dropped Swift 3 mode, and current Swift compilers accept 4, 4.2, 5 and 6.
|
||||||
@@ -174,27 +183,29 @@ fn check_adt_project(root: &Path, dir: &Path) -> Vec<Hit> {
|
|||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
line: Some(line),
|
line: Some(line),
|
||||||
}];
|
}];
|
||||||
if let Some(api) = target.and_then(|(_, l)| android_api(l)) {
|
let below_floor = target
|
||||||
if api < OLDEST_PATCHED_ANDROID_API {
|
.and_then(|(_, l)| android_api(l))
|
||||||
hits.push(Hit {
|
.zip(android_floor())
|
||||||
scanner: SCANNER,
|
.filter(|(api, (floor, _))| api < floor);
|
||||||
scan_type: ScanType::Sbom,
|
if let Some((api, (floor, floor_name))) = below_floor {
|
||||||
rule_id: "android-sdk-end-of-support",
|
hits.push(Hit {
|
||||||
title: format!("Android API {api} receives no security updates"),
|
scanner: SCANNER,
|
||||||
description: format!(
|
scan_type: ScanType::Sbom,
|
||||||
"{} builds against Android API {api}. Android releases below API \
|
rule_id: "android-sdk-end-of-support",
|
||||||
{OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, \
|
title: format!("Android API {api} receives no security updates"),
|
||||||
so the platform the app is built for stays vulnerable.",
|
description: format!(
|
||||||
relative(root, dir)
|
"{} builds against Android API {api}. Android releases below API \
|
||||||
),
|
{floor} ({floor_name}) receive no security updates, so the platform the \
|
||||||
remediation: "Raise the target and minimum API level to a supported Android \
|
app is built for stays vulnerable.",
|
||||||
release (after migrating the build to Gradle) and test on it.",
|
relative(root, dir)
|
||||||
severity: Severity::High,
|
),
|
||||||
cwe: "CWE-1104",
|
remediation: "Raise the target and minimum API level to a supported Android \
|
||||||
path,
|
release (after migrating the build to Gradle) and test on it.",
|
||||||
line: Some(line),
|
severity: Severity::High,
|
||||||
});
|
cwe: "CWE-1104",
|
||||||
}
|
path,
|
||||||
|
line: Some(line),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
hits
|
hits
|
||||||
}
|
}
|
||||||
@@ -289,8 +300,9 @@ fn ios_deployment_target(
|
|||||||
path: String,
|
path: String,
|
||||||
line: u32,
|
line: u32,
|
||||||
) -> Option<Hit> {
|
) -> Option<Hit> {
|
||||||
let (oldest, _) = OLDEST_PATCHED_IOS;
|
let floor = ios_floor()?;
|
||||||
((major, minor) < OLDEST_PATCHED_IOS).then(|| Hit {
|
let (oldest, _) = floor;
|
||||||
|
((major, minor) < floor).then(|| Hit {
|
||||||
scanner: SCANNER,
|
scanner: SCANNER,
|
||||||
scan_type: ScanType::Sbom,
|
scan_type: ScanType::Sbom,
|
||||||
rule_id: "ios-deployment-target-end-of-support",
|
rule_id: "ios-deployment-target-end-of-support",
|
||||||
@@ -337,8 +349,13 @@ fn unity_platform_hits(root: &Path, project: &Path) -> Vec<Hit> {
|
|||||||
}
|
}
|
||||||
let android_min = platforms.android.and_then(|p| p.min_os);
|
let android_min = platforms.android.and_then(|p| p.min_os);
|
||||||
if let Some(setting) = android_min {
|
if let Some(setting) = android_min {
|
||||||
let api = setting.value.parse::<u32>().ok();
|
let below_floor = setting
|
||||||
if let Some(api) = api.filter(|api| *api < OLDEST_PATCHED_ANDROID_API) {
|
.value
|
||||||
|
.parse::<u32>()
|
||||||
|
.ok()
|
||||||
|
.zip(android_floor())
|
||||||
|
.filter(|(api, (floor, _))| api < floor);
|
||||||
|
if let Some((api, (floor, floor_name))) = below_floor {
|
||||||
hits.push(Hit {
|
hits.push(Hit {
|
||||||
scanner: SCANNER,
|
scanner: SCANNER,
|
||||||
scan_type: ScanType::Sbom,
|
scan_type: ScanType::Sbom,
|
||||||
@@ -349,7 +366,7 @@ fn unity_platform_hits(root: &Path, project: &Path) -> Vec<Hit> {
|
|||||||
description: format!(
|
description: format!(
|
||||||
"{label} sets its minimum Android API level to {api}: the app installs and \
|
"{label} sets its minimum Android API level to {api}: the app installs and \
|
||||||
runs on devices still on that release. Android releases below API \
|
runs on devices still on that release. Android releases below API \
|
||||||
{OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, so \
|
{floor} ({floor_name}) receive no security updates, so \
|
||||||
those devices stay vulnerable whatever the app does. The app also runs on \
|
those devices stay vulnerable whatever the app does. The app also runs on \
|
||||||
current Android releases."
|
current Android releases."
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -295,52 +295,15 @@ pub fn runtime_of(moniker: &str) -> Option<Runtime> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Microsoft's end of support for each target framework that has one, as an
|
/// When `moniker` lost (or loses) Microsoft's support, and its product name,
|
||||||
/// ISO date and the name customers know it by. Versions not listed are
|
/// from the bundled table (`data/eol/dotnet.json`). `None` for a version
|
||||||
/// supported (.NET Framework 4.8 and 4.8.1 follow the Windows they ship with).
|
/// without an announced end (.NET Framework 4.7 to 4.8.1 follow the Windows
|
||||||
///
|
/// they ship with), or one not known here.
|
||||||
/// Sources: the .NET Framework and .NET lifecycle pages on
|
|
||||||
/// learn.microsoft.com (.NET Framework 4.5.2, 4.6 and 4.6.1 ended
|
|
||||||
/// 2022-04-26, 4.6.2 ends 2027-01-12; .NET 8 and .NET 9 end 2026-11-10).
|
|
||||||
const END_OF_SUPPORT: &[(&str, &str, &str)] = &[
|
|
||||||
("net11", "2011-07-12", ".NET Framework 1.1"),
|
|
||||||
("net20", "2011-07-12", ".NET Framework 2.0"),
|
|
||||||
("net30", "2011-07-12", ".NET Framework 3.0"),
|
|
||||||
("net35", "2029-01-09", ".NET Framework 3.5 SP1"),
|
|
||||||
("net40", "2016-01-12", ".NET Framework 4.0"),
|
|
||||||
("net403", "2016-01-12", ".NET Framework 4.0.3"),
|
|
||||||
("net45", "2016-01-12", ".NET Framework 4.5"),
|
|
||||||
("net451", "2016-01-12", ".NET Framework 4.5.1"),
|
|
||||||
("net452", "2022-04-26", ".NET Framework 4.5.2"),
|
|
||||||
("net46", "2022-04-26", ".NET Framework 4.6"),
|
|
||||||
("net461", "2022-04-26", ".NET Framework 4.6.1"),
|
|
||||||
("net462", "2027-01-12", ".NET Framework 4.6.2"),
|
|
||||||
("netcoreapp1.0", "2019-06-27", ".NET Core 1.0"),
|
|
||||||
("netcoreapp1.1", "2019-06-27", ".NET Core 1.1"),
|
|
||||||
("netcoreapp2.0", "2018-10-01", ".NET Core 2.0"),
|
|
||||||
("netcoreapp2.1", "2021-08-21", ".NET Core 2.1"),
|
|
||||||
("netcoreapp2.2", "2019-12-23", ".NET Core 2.2"),
|
|
||||||
("netcoreapp3.0", "2020-03-03", ".NET Core 3.0"),
|
|
||||||
("netcoreapp3.1", "2022-12-13", ".NET Core 3.1"),
|
|
||||||
("net5.0", "2022-05-10", ".NET 5"),
|
|
||||||
("net6.0", "2024-11-12", ".NET 6"),
|
|
||||||
("net7.0", "2024-05-14", ".NET 7"),
|
|
||||||
("net8.0", "2026-11-10", ".NET 8"),
|
|
||||||
("net9.0", "2026-11-10", ".NET 9"),
|
|
||||||
("net10.0", "2028-11-14", ".NET 10"),
|
|
||||||
];
|
|
||||||
|
|
||||||
/// When `moniker` lost (or loses) Microsoft's support, and its product name.
|
|
||||||
/// `None` for a version without an announced end, or one not known here.
|
|
||||||
pub fn end_of_support(moniker: &str) -> Option<(chrono::NaiveDate, &'static str)> {
|
pub fn end_of_support(moniker: &str) -> Option<(chrono::NaiveDate, &'static str)> {
|
||||||
END_OF_SUPPORT
|
crate::pipeline::eol_tables::dotnet_frameworks()
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(m, _, _)| *m == moniker)
|
.find(|f| f.moniker == moniker)
|
||||||
.and_then(|(_, date, name)| {
|
.map(|f| (f.end_of_support, f.product.as_str()))
|
||||||
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
|
|
||||||
.ok()
|
|
||||||
.map(|d| (d, *name))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
//! The end-of-life tables the lifecycle checks judge by, bundled from
|
||||||
|
//! `compliance-agent/data/eol/*.json`.
|
||||||
|
//!
|
||||||
|
//! The JSON files are the one place the tables live: the agent compiles them
|
||||||
|
//! in here, and the weekly CI check (`scripts/check-eol-tables.py`) compares
|
||||||
|
//! them with endoflife.date and files an issue when they drift.
|
||||||
|
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// One Yocto Project release.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct YoctoReleaseInfo {
|
||||||
|
/// The codename, lower case.
|
||||||
|
pub codename: String,
|
||||||
|
/// The Yocto Project version.
|
||||||
|
pub version: String,
|
||||||
|
/// A long term support release.
|
||||||
|
pub lts: bool,
|
||||||
|
/// Its release day.
|
||||||
|
pub released: NaiveDate,
|
||||||
|
/// The day its support ends (or ended).
|
||||||
|
pub end_of_life: NaiveDate,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Yocto release table and where it comes from.
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
pub struct YoctoTable {
|
||||||
|
/// The primary source (the Yocto Project releases wiki).
|
||||||
|
pub source: String,
|
||||||
|
/// When the table was last checked against its sources (`YYYY-MM-DD`).
|
||||||
|
pub checked_on: String,
|
||||||
|
/// The releases, oldest first.
|
||||||
|
pub releases: Vec<YoctoReleaseInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Microsoft's end of support for one target framework moniker.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
pub struct DotnetFramework {
|
||||||
|
/// The moniker (`net452`, `netcoreapp3.1`, `net8.0`).
|
||||||
|
pub moniker: String,
|
||||||
|
/// The day support ends (or ended).
|
||||||
|
pub end_of_support: NaiveDate,
|
||||||
|
/// The name customers know it by.
|
||||||
|
pub product: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
struct DotnetTable {
|
||||||
|
frameworks: Vec<DotnetFramework>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The oldest Android release that still gets security updates.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct AndroidFloor {
|
||||||
|
/// Its API level: below it no release is patched.
|
||||||
|
pub oldest_patched_api: u32,
|
||||||
|
/// Its name (`Android 10`).
|
||||||
|
pub oldest_patched_release: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The oldest iOS release that still gets security updates.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct IosFloor {
|
||||||
|
/// `major.minor`.
|
||||||
|
pub oldest_patched: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The platform floors.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct Platforms {
|
||||||
|
/// Android.
|
||||||
|
pub android: AndroidFloor,
|
||||||
|
/// iOS.
|
||||||
|
pub ios: IosFloor,
|
||||||
|
}
|
||||||
|
|
||||||
|
const YOCTO_JSON: &str = include_str!("../../data/eol/yocto.json");
|
||||||
|
const DOTNET_JSON: &str = include_str!("../../data/eol/dotnet.json");
|
||||||
|
const PLATFORMS_JSON: &str = include_str!("../../data/eol/platforms.json");
|
||||||
|
|
||||||
|
/// `text` (the bundled file `name`) parsed; logged and `None` when it does
|
||||||
|
/// not parse, which the tests below rule out for the files shipped.
|
||||||
|
fn parse<T: for<'de> Deserialize<'de>>(name: &str, text: &str) -> Option<T> {
|
||||||
|
serde_json::from_str(text)
|
||||||
|
.map_err(|e| tracing::error!(file = name, "bundled end-of-life table does not parse: {e}"))
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
static YOCTO: LazyLock<YoctoTable> =
|
||||||
|
LazyLock::new(|| parse("yocto.json", YOCTO_JSON).unwrap_or_default());
|
||||||
|
static DOTNET: LazyLock<DotnetTable> =
|
||||||
|
LazyLock::new(|| parse("dotnet.json", DOTNET_JSON).unwrap_or_default());
|
||||||
|
static PLATFORMS: LazyLock<Option<Platforms>> =
|
||||||
|
LazyLock::new(|| parse("platforms.json", PLATFORMS_JSON));
|
||||||
|
|
||||||
|
/// The Yocto release table.
|
||||||
|
pub fn yocto() -> &'static YoctoTable {
|
||||||
|
&YOCTO
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The .NET target frameworks with an end of support.
|
||||||
|
pub fn dotnet_frameworks() -> &'static [DotnetFramework] {
|
||||||
|
&DOTNET.frameworks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Android and iOS floors; `None` only if the bundled file does not
|
||||||
|
/// parse, and then no platform is judged.
|
||||||
|
pub fn platforms() -> Option<&'static Platforms> {
|
||||||
|
PLATFORMS.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_bundled_table_parses() {
|
||||||
|
let yocto: YoctoTable = serde_json::from_str(YOCTO_JSON).expect("yocto.json");
|
||||||
|
assert!(!yocto.releases.is_empty());
|
||||||
|
assert!(NaiveDate::parse_from_str(&yocto.checked_on, "%Y-%m-%d").is_ok());
|
||||||
|
let dotnet: DotnetTable = serde_json::from_str(DOTNET_JSON).expect("dotnet.json");
|
||||||
|
assert!(!dotnet.frameworks.is_empty());
|
||||||
|
let platforms: Platforms = serde_json::from_str(PLATFORMS_JSON).expect("platforms.json");
|
||||||
|
assert!(platforms.android.oldest_patched_api > 0);
|
||||||
|
assert!(platforms.ios.oldest_patched.contains('.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Finding> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut review: Vec<String> = Vec::new();
|
||||||
|
let mut seen: Vec<String> = 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<String> = 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ pub mod dedup;
|
|||||||
pub mod devskim;
|
pub mod devskim;
|
||||||
pub mod dotnet;
|
pub mod dotnet;
|
||||||
pub mod embedded_versions;
|
pub mod embedded_versions;
|
||||||
|
pub mod eol_tables;
|
||||||
pub mod finding_store;
|
pub mod finding_store;
|
||||||
pub mod firmware_sbom;
|
pub mod firmware_sbom;
|
||||||
pub mod git;
|
pub mod git;
|
||||||
@@ -29,6 +30,7 @@ mod issue_catchup;
|
|||||||
pub(crate) mod issue_creation;
|
pub(crate) mod issue_creation;
|
||||||
pub(crate) mod issue_sync;
|
pub(crate) mod issue_sync;
|
||||||
pub mod languages;
|
pub mod languages;
|
||||||
|
pub mod license_policy;
|
||||||
pub mod lint;
|
pub mod lint;
|
||||||
pub mod mobsfscan;
|
pub mod mobsfscan;
|
||||||
pub mod nvd_cpe;
|
pub mod nvd_cpe;
|
||||||
|
|||||||
@@ -428,6 +428,7 @@ impl PipelineOrchestrator {
|
|||||||
.await;
|
.await;
|
||||||
let mut sbom_entries = generated.entries;
|
let mut sbom_entries = generated.entries;
|
||||||
let syft_failure = generated.syft_failure;
|
let syft_failure = generated.syft_failure;
|
||||||
|
let sbom_complete = syft_failure.is_none();
|
||||||
let unmapped_assemblies = generated.unmapped_assemblies;
|
let unmapped_assemblies = generated.unmapped_assemblies;
|
||||||
let resolved_nuget = generated.resolved_nuget;
|
let resolved_nuget = generated.resolved_nuget;
|
||||||
// Syft reads the lockfiles and archives: without it the SBOM is short
|
// 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)
|
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
|
||||||
.await;
|
.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)
|
// Stage 4: Pattern Scanning (GDPR + OAuth)
|
||||||
tracing::info!("[{repo_id}] Stage 4: Pattern Scanning");
|
tracing::info!("[{repo_id}] Stage 4: Pattern Scanning");
|
||||||
self.update_phase(scan_run_id, ScanPhase::PatternScanning)
|
self.update_phase(scan_run_id, ScanPhase::PatternScanning)
|
||||||
|
|||||||
@@ -178,13 +178,15 @@ impl crate::pipeline::orchestrator::PipelineOrchestrator {
|
|||||||
if count == 0 || count > crate::api::handlers::sbom::MAX_EXPORT_COMPONENTS {
|
if count == 0 || count > crate::api::handlers::sbom::MAX_EXPORT_COMPONENTS {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let entries: Vec<SbomEntry> = match self.db.sbom_entries().find(filter).await {
|
let mut entries: Vec<SbomEntry> = match self.db.sbom_entries().find(filter).await {
|
||||||
Ok(cursor) => cursor.try_collect().await.ok()?,
|
Ok(cursor) => cursor.try_collect().await.ok()?,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(target_id, "SBOM not scored: {e}");
|
tracing::warn!(target_id, "SBOM not scored: {e}");
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
// Scored as exported: with the licences a person confirmed.
|
||||||
|
crate::license_conclusions::attach(&self.db, &mut entries).await;
|
||||||
match score(&entries, subject).await {
|
match score(&entries, subject).await {
|
||||||
Ok(quality) => {
|
Ok(quality) => {
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
|
|||||||
@@ -17,123 +17,20 @@ pub const RULE_EOL: &str = "yocto-release-eol";
|
|||||||
/// The rule of a release whose end of life is near: within six months for an
|
/// The rule of a release whose end of life is near: within six months for an
|
||||||
/// LTS release, two for any other ([`soon_window`]).
|
/// LTS release, two for any other ([`soon_window`]).
|
||||||
pub const RULE_EOL_SOON: &str = "yocto-release-eol-soon";
|
pub const RULE_EOL_SOON: &str = "yocto-release-eol-soon";
|
||||||
/// Where the support periods come from.
|
/// The bundled release table (`data/eol/yocto.json`): sources and check date
|
||||||
pub const SOURCE_URL: &str = "https://wiki.yoctoproject.org/wiki/Releases";
|
/// in the file, which the weekly CI check compares with endoflife.date.
|
||||||
/// When [`RELEASES`] was checked against its sources.
|
pub use crate::pipeline::eol_tables::YoctoReleaseInfo as ReleaseInfo;
|
||||||
pub const CHECKED_ON: &str = "2026-10-09";
|
|
||||||
|
|
||||||
/// One Yocto Project release.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct ReleaseInfo {
|
|
||||||
/// The codename, lower case.
|
|
||||||
pub codename: &'static str,
|
|
||||||
/// The Yocto Project version.
|
|
||||||
pub version: &'static str,
|
|
||||||
/// A long term support release.
|
|
||||||
pub lts: bool,
|
|
||||||
/// Its release day.
|
|
||||||
pub released: NaiveDate,
|
|
||||||
/// The day its support ends (or ended).
|
|
||||||
pub end_of_life: NaiveDate,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A day of the table; every date in it is valid, a test checks them.
|
|
||||||
const fn day(y: i32, m: u32, d: u32) -> NaiveDate {
|
|
||||||
match NaiveDate::from_ymd_opt(y, m, d) {
|
|
||||||
Some(date) => date,
|
|
||||||
None => NaiveDate::MIN,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fn release(
|
|
||||||
codename: &'static str,
|
|
||||||
version: &'static str,
|
|
||||||
lts: bool,
|
|
||||||
released: NaiveDate,
|
|
||||||
end_of_life: NaiveDate,
|
|
||||||
) -> ReleaseInfo {
|
|
||||||
ReleaseInfo {
|
|
||||||
codename,
|
|
||||||
version,
|
|
||||||
lts,
|
|
||||||
released,
|
|
||||||
end_of_life,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Yocto Project releases, oldest first.
|
/// The Yocto Project releases, oldest first.
|
||||||
///
|
fn releases() -> &'static [ReleaseInfo] {
|
||||||
/// Source: the Yocto Project releases wiki, <https://wiki.yoctoproject.org/wiki/Releases>
|
&crate::pipeline::eol_tables::yocto().releases
|
||||||
/// (page last updated 2026-09-10), checked on 2026-10-09: codename, version,
|
}
|
||||||
/// LTS and support status. The wiki gives months only; the exact release and
|
|
||||||
/// end-of-life days are endoflife.date's (<https://endoflife.date/yocto>,
|
|
||||||
/// checked the same day), which agree with the wiki's months except
|
|
||||||
/// Walnascar (wiki: "EOL since November 2025", endoflife.date: 2025-12-07).
|
|
||||||
/// For Thud and older, which endoflife.date does not list, the end of life
|
|
||||||
/// is the last day of the month of the release's last point release (wiki),
|
|
||||||
/// and the release day the first of its month. Blacksail (6.1, due October
|
|
||||||
/// 2026) is not released yet and not listed: a newer branch reads as an
|
|
||||||
/// unknown release.
|
|
||||||
pub const RELEASES: &[ReleaseInfo] = &[
|
|
||||||
release("jethro", "2.0", false, day(2015, 11, 1), day(2017, 1, 31)),
|
|
||||||
release("krogoth", "2.1", false, day(2016, 4, 1), day(2017, 7, 31)),
|
|
||||||
release("morty", "2.2", false, day(2016, 11, 1), day(2018, 7, 31)),
|
|
||||||
release("pyro", "2.3", false, day(2017, 5, 1), day(2018, 7, 31)),
|
|
||||||
release("rocko", "2.4", false, day(2017, 10, 1), day(2018, 11, 30)),
|
|
||||||
release("sumo", "2.5", false, day(2018, 4, 1), day(2019, 4, 30)),
|
|
||||||
release("thud", "2.6", false, day(2018, 11, 1), day(2019, 10, 31)),
|
|
||||||
release("warrior", "2.7", false, day(2019, 5, 1), day(2020, 6, 1)),
|
|
||||||
release("zeus", "3.0", false, day(2019, 10, 22), day(2020, 8, 1)),
|
|
||||||
release("dunfell", "3.1", true, day(2020, 4, 21), day(2024, 4, 30)),
|
|
||||||
release(
|
|
||||||
"gatesgarth",
|
|
||||||
"3.2",
|
|
||||||
false,
|
|
||||||
day(2020, 11, 3),
|
|
||||||
day(2021, 5, 1),
|
|
||||||
),
|
|
||||||
release(
|
|
||||||
"hardknott",
|
|
||||||
"3.3",
|
|
||||||
false,
|
|
||||||
day(2021, 4, 19),
|
|
||||||
day(2022, 4, 20),
|
|
||||||
),
|
|
||||||
release("honister", "3.4", false, day(2021, 10, 25), day(2022, 5, 1)),
|
|
||||||
release("kirkstone", "4.0", true, day(2022, 4, 25), day(2026, 4, 27)),
|
|
||||||
release(
|
|
||||||
"langdale",
|
|
||||||
"4.1",
|
|
||||||
false,
|
|
||||||
day(2022, 10, 23),
|
|
||||||
day(2023, 5, 27),
|
|
||||||
),
|
|
||||||
release(
|
|
||||||
"mickledore",
|
|
||||||
"4.2",
|
|
||||||
false,
|
|
||||||
day(2023, 5, 3),
|
|
||||||
day(2023, 11, 5),
|
|
||||||
),
|
|
||||||
release("nanbield", "4.3", false, day(2023, 11, 9), day(2024, 6, 9)),
|
|
||||||
release("scarthgap", "5.0", true, day(2024, 4, 29), day(2028, 4, 30)),
|
|
||||||
release("styhead", "5.1", false, day(2024, 10, 16), day(2025, 5, 16)),
|
|
||||||
release("walnascar", "5.2", false, day(2025, 5, 7), day(2025, 12, 7)),
|
|
||||||
release(
|
|
||||||
"whinlatter",
|
|
||||||
"5.3",
|
|
||||||
false,
|
|
||||||
day(2025, 12, 15),
|
|
||||||
day(2026, 6, 15),
|
|
||||||
),
|
|
||||||
release("wrynose", "6.0", true, day(2026, 5, 13), day(2030, 4, 30)),
|
|
||||||
];
|
|
||||||
|
|
||||||
/// The repositories whose branch names the release, most telling first.
|
/// The repositories whose branch names the release, most telling first.
|
||||||
const RELEASE_REPOS: &[&str] = &["poky", "openembedded-core", "meta-openembedded"];
|
const RELEASE_REPOS: &[&str] = &["poky", "openembedded-core", "meta-openembedded"];
|
||||||
|
|
||||||
fn by_codename(codename: &str) -> Option<&'static ReleaseInfo> {
|
fn by_codename(codename: &str) -> Option<&'static ReleaseInfo> {
|
||||||
RELEASES.iter().find(|r| r.codename == codename)
|
releases().iter().find(|r| r.codename == codename)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The release a branch or tag names: a codename as one of its words
|
/// The release a branch or tag names: a codename as one of its words
|
||||||
@@ -150,7 +47,7 @@ pub(crate) fn from_reference(reference: &str) -> Option<&'static ReleaseInfo> {
|
|||||||
let version = lower.rsplit('/').next()?.strip_prefix("yocto-")?;
|
let version = lower.rsplit('/').next()?.strip_prefix("yocto-")?;
|
||||||
let mut parts = version.split('.');
|
let mut parts = version.split('.');
|
||||||
let major_minor = format!("{}.{}", parts.next()?, parts.next()?);
|
let major_minor = format!("{}.{}", parts.next()?, parts.next()?);
|
||||||
RELEASES.iter().find(|r| r.version == major_minor)
|
releases().iter().find(|r| r.version == major_minor)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The newest of `codenames` the table knows.
|
/// The newest of `codenames` the table knows.
|
||||||
@@ -195,8 +92,8 @@ fn conf_of(layer: &Layer) -> String {
|
|||||||
/// `None` when none of them names a release the table knows.
|
/// `None` when none of them names a release the table knows.
|
||||||
pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease> {
|
pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease> {
|
||||||
let make = |info: &ReleaseInfo, basis: ReleaseBasis, file: String| YoctoRelease {
|
let make = |info: &ReleaseInfo, basis: ReleaseBasis, file: String| YoctoRelease {
|
||||||
codename: info.codename.to_string(),
|
codename: info.codename.clone(),
|
||||||
version: info.version.to_string(),
|
version: info.version.clone(),
|
||||||
lts: info.lts,
|
lts: info.lts,
|
||||||
end_of_life: info.end_of_life,
|
end_of_life: info.end_of_life,
|
||||||
basis,
|
basis,
|
||||||
@@ -236,7 +133,7 @@ pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option<YoctoRelease
|
|||||||
/// The newest LTS release on `today` whose end of life is not yet soon.
|
/// The newest LTS release on `today` whose end of life is not yet soon.
|
||||||
fn current_lts(today: NaiveDate) -> Option<&'static ReleaseInfo> {
|
fn current_lts(today: NaiveDate) -> Option<&'static ReleaseInfo> {
|
||||||
let horizon = today.checked_add_months(soon_window(true))?;
|
let horizon = today.checked_add_months(soon_window(true))?;
|
||||||
RELEASES
|
releases()
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|r| r.lts && r.released <= today && r.end_of_life > horizon)
|
.filter(|r| r.lts && r.released <= today && r.end_of_life > horizon)
|
||||||
.max_by_key(|r| r.released)
|
.max_by_key(|r| r.released)
|
||||||
@@ -280,7 +177,7 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
|
|||||||
let eol = release.end_of_life;
|
let eol = release.end_of_life;
|
||||||
let description = format!(
|
let description = format!(
|
||||||
"The layers build Yocto {name} ({version}{lts}), read from {basis}. The Yocto Project \
|
"The layers build Yocto {name} ({version}{lts}), read from {basis}. The Yocto Project \
|
||||||
{status} {eol} (source: {SOURCE_URL}, checked {CHECKED_ON}). After that, no security \
|
{status} {eol} (source: {source}, checked {checked}). After that, no security \
|
||||||
fixes are published for its recipes, so vulnerabilities in the image's components \
|
fixes are published for its recipes, so vulnerabilities in the image's components \
|
||||||
stay open unless every fix is backported by hand.\n\nCRA Annex I Part I (2)(c): \
|
stay open unless every fix is backported by hand.\n\nCRA Annex I Part I (2)(c): \
|
||||||
vulnerabilities can be addressed through security updates; Annex I Part II (2): \
|
vulnerabilities can be addressed through security updates; Annex I Part II (2): \
|
||||||
@@ -288,6 +185,8 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
|
|||||||
the product's support period.",
|
the product's support period.",
|
||||||
version = release.version,
|
version = release.version,
|
||||||
basis = basis_text(&release.basis, &release.file),
|
basis = basis_text(&release.basis, &release.file),
|
||||||
|
source = crate::pipeline::eol_tables::yocto().source,
|
||||||
|
checked = crate::pipeline::eol_tables::yocto().checked_on,
|
||||||
);
|
);
|
||||||
let remediation = match current_lts(today) {
|
let remediation = match current_lts(today) {
|
||||||
Some(lts) if lts.codename != release.codename => format!(
|
Some(lts) if lts.codename != release.codename => format!(
|
||||||
@@ -296,7 +195,7 @@ pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -
|
|||||||
layers to its branch, and LAYERSERIES_COMPAT of your layers. Until then, \
|
layers to its branch, and LAYERSERIES_COMPAT of your layers. Until then, \
|
||||||
backport the security fixes the product needs and record them (CVE_STATUS, \
|
backport the security fixes the product needs and record them (CVE_STATUS, \
|
||||||
patches).",
|
patches).",
|
||||||
display_codename(lts.codename),
|
display_codename(<s.codename),
|
||||||
lts.version,
|
lts.version,
|
||||||
lts.end_of_life
|
lts.end_of_life
|
||||||
),
|
),
|
||||||
@@ -356,10 +255,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_table_is_ordered_and_names_the_required_releases() {
|
fn the_table_is_ordered_and_names_the_required_releases() {
|
||||||
assert!(RELEASES.iter().all(|r| r.released != NaiveDate::MIN
|
assert!(releases().iter().all(|r| r.released < r.end_of_life));
|
||||||
&& r.end_of_life != NaiveDate::MIN
|
assert!(releases().windows(2).all(|w| w[0].released < w[1].released));
|
||||||
&& r.released < r.end_of_life));
|
|
||||||
assert!(RELEASES.windows(2).all(|w| w[0].released < w[1].released));
|
|
||||||
for codename in [
|
for codename in [
|
||||||
"dunfell",
|
"dunfell",
|
||||||
"kirkstone",
|
"kirkstone",
|
||||||
@@ -373,12 +270,11 @@ mod tests {
|
|||||||
] {
|
] {
|
||||||
assert!(by_codename(codename).is_some(), "{codename}");
|
assert!(by_codename(codename).is_some(), "{codename}");
|
||||||
}
|
}
|
||||||
assert_eq!(date(2026, 10, 9).to_string(), CHECKED_ON);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn branches_and_tags_name_their_release() {
|
fn branches_and_tags_name_their_release() {
|
||||||
let codename = |r: &str| from_reference(r).map(|i| i.codename);
|
let codename = |r: &str| from_reference(r).map(|i| i.codename.as_str());
|
||||||
assert_eq!(codename("scarthgap"), Some("scarthgap"));
|
assert_eq!(codename("scarthgap"), Some("scarthgap"));
|
||||||
assert_eq!(codename("scarthgap-5.0.3"), Some("scarthgap"));
|
assert_eq!(codename("scarthgap-5.0.3"), Some("scarthgap"));
|
||||||
assert_eq!(codename("yocto-5.0.3"), Some("scarthgap"));
|
assert_eq!(codename("yocto-5.0.3"), Some("scarthgap"));
|
||||||
@@ -457,7 +353,7 @@ mod tests {
|
|||||||
let info = by_codename(codename).expect("known");
|
let info = by_codename(codename).expect("known");
|
||||||
YoctoRelease {
|
YoctoRelease {
|
||||||
codename: codename.into(),
|
codename: codename.into(),
|
||||||
version: info.version.into(),
|
version: info.version.clone(),
|
||||||
lts: info.lts,
|
lts: info.lts,
|
||||||
end_of_life: info.end_of_life,
|
end_of_life: info.end_of_life,
|
||||||
basis: ReleaseBasis::Pin {
|
basis: ReleaseBasis::Pin {
|
||||||
@@ -484,7 +380,9 @@ mod tests {
|
|||||||
assert!(f
|
assert!(f
|
||||||
.description
|
.description
|
||||||
.contains("\"dunfell\" that kas.yml pins poky to"));
|
.contains("\"dunfell\" that kas.yml pins poky to"));
|
||||||
assert!(f.description.contains(SOURCE_URL));
|
assert!(f
|
||||||
|
.description
|
||||||
|
.contains("https://wiki.yoctoproject.org/wiki/Releases"));
|
||||||
assert!(f.description.contains("Annex I Part I (2)(c)"));
|
assert!(f.description.contains("Annex I Part I (2)(c)"));
|
||||||
assert!(f.description.contains("Part II"));
|
assert!(f.description.contains("Part II"));
|
||||||
assert_eq!(f.file_path.as_deref(), Some("kas.yml"));
|
assert_eq!(f.file_path.as_deref(), Some("kas.yml"));
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ use compliance_core::AgentConfig;
|
|||||||
|
|
||||||
/// How long an entitlement answer is trusted before it is re-fetched.
|
/// How long an entitlement answer is trusted before it is re-fetched.
|
||||||
pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
|
pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
/// The most API-key verdicts held at once. Callers choose the keys, so an
|
||||||
|
/// unbounded cache of invalid ones would grow without end.
|
||||||
|
const API_KEY_CACHE_MAX: usize = 10_000;
|
||||||
|
|
||||||
|
/// How long an API-key verdict is reused. A revoked key therefore keeps
|
||||||
|
/// working for up to this long; past it, an unreachable registry means `503`.
|
||||||
|
pub const API_KEY_TTL: Duration = Duration::from_secs(60);
|
||||||
/// Refresh the service token this long before it expires.
|
/// Refresh the service token this long before it expires.
|
||||||
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
|
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
|
||||||
/// Upper bound for one registry or Keycloak token request. Without it a hung
|
/// Upper bound for one registry or Keycloak token request. Without it a hung
|
||||||
@@ -77,7 +85,7 @@ pub struct AuditEntry {
|
|||||||
pub product: String,
|
pub product: String,
|
||||||
/// What happened, e.g. `pruefwerk.support_access`.
|
/// What happened, e.g. `pruefwerk.support_access`.
|
||||||
pub action: String,
|
pub action: String,
|
||||||
/// `user`, or `staff` for BreakPilot support.
|
/// `user`, `staff` for BreakPilot support, or `apikey`.
|
||||||
pub actor_type: String,
|
pub actor_type: String,
|
||||||
pub actor_id: String,
|
pub actor_id: String,
|
||||||
pub actor_name: String,
|
pub actor_name: String,
|
||||||
@@ -89,6 +97,17 @@ pub struct AuditEntry {
|
|||||||
#[serde(skip_serializing_if = "String::is_empty")]
|
#[serde(skip_serializing_if = "String::is_empty")]
|
||||||
pub target_name: String,
|
pub target_name: String,
|
||||||
pub metadata: serde_json::Value,
|
pub metadata: serde_json::Value,
|
||||||
|
/// The caller's address, when the agent knows it; the registry otherwise
|
||||||
|
/// records the address of the agent itself.
|
||||||
|
#[serde(skip_serializing_if = "String::is_empty")]
|
||||||
|
pub source_ip: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cache key for an API key: its SHA-256, hex. The key itself is never
|
||||||
|
/// held longer than the request.
|
||||||
|
fn key_digest(key: &str) -> String {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
hex::encode(Sha256::digest(key.as_bytes()))
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuditEntry {
|
impl AuditEntry {
|
||||||
@@ -96,19 +115,33 @@ impl AuditEntry {
|
|||||||
pub fn by(
|
pub fn by(
|
||||||
ctx: &compliance_core::TenantContext,
|
ctx: &compliance_core::TenantContext,
|
||||||
action: &str,
|
action: &str,
|
||||||
metadata: serde_json::Value,
|
mut metadata: serde_json::Value,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let actor_type = match (&ctx.staff, &ctx.api_key) {
|
||||||
|
(Some(_), _) => "staff",
|
||||||
|
(None, Some(key)) => {
|
||||||
|
// Who the caller says it acts for: informational only.
|
||||||
|
if let (Some(on_behalf_of), Some(map)) =
|
||||||
|
(&key.on_behalf_of, metadata.as_object_mut())
|
||||||
|
{
|
||||||
|
map.insert("on_behalf_of".to_string(), on_behalf_of.clone().into());
|
||||||
|
}
|
||||||
|
"apikey"
|
||||||
|
}
|
||||||
|
(None, None) => "user",
|
||||||
|
};
|
||||||
Self {
|
Self {
|
||||||
tenant_id: ctx.tenant_id.clone(),
|
tenant_id: ctx.tenant_id.clone(),
|
||||||
product: "pruefwerk".to_string(),
|
product: "pruefwerk".to_string(),
|
||||||
action: action.to_string(),
|
action: action.to_string(),
|
||||||
actor_type: if ctx.staff.is_some() { "staff" } else { "user" }.to_string(),
|
actor_type: actor_type.to_string(),
|
||||||
actor_id: ctx.user_id.clone(),
|
actor_id: ctx.user_id.clone(),
|
||||||
actor_name: ctx.actor_label(),
|
actor_name: ctx.actor_label(),
|
||||||
target_type: String::new(),
|
target_type: String::new(),
|
||||||
target_id: String::new(),
|
target_id: String::new(),
|
||||||
target_name: String::new(),
|
target_name: String::new(),
|
||||||
metadata,
|
metadata,
|
||||||
|
source_ip: String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,6 +155,9 @@ impl AuditEntry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The registry's answer for a portal-issued API key (tenant-registry ADR
|
||||||
|
/// 0001). Everything but `valid` defaults, so an older registry that sends
|
||||||
|
/// only `valid`, `tenant_id`, `product` and `scopes` still decodes.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct ApiKeyVerify {
|
pub struct ApiKeyVerify {
|
||||||
pub valid: bool,
|
pub valid: bool,
|
||||||
@@ -129,8 +165,26 @@ pub struct ApiKeyVerify {
|
|||||||
pub tenant_id: String,
|
pub tenant_id: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub product: String,
|
pub product: String,
|
||||||
|
/// Already intersected with the tenant's entitlements; empty for a
|
||||||
|
/// halted or archived tenant.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub scopes: Vec<String>,
|
pub scopes: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub key_id: String,
|
||||||
|
/// `personal` or `service`, as the registry labels it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub kind: String,
|
||||||
|
/// Who the key was issued to, for the history and the audit log.
|
||||||
|
#[serde(default)]
|
||||||
|
pub holder: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub expires_at: Option<String>,
|
||||||
|
/// The tenant's ladder status (`active`, `restricted`, ...).
|
||||||
|
#[serde(default)]
|
||||||
|
pub tenant_status: String,
|
||||||
|
/// A key issued before scopes existed: it carries none.
|
||||||
|
#[serde(default)]
|
||||||
|
pub legacy: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
@@ -161,6 +215,9 @@ pub struct RegistryClient {
|
|||||||
cache: DashMap<String, (Instant, EntitlementCheck)>,
|
cache: DashMap<String, (Instant, EntitlementCheck)>,
|
||||||
/// Each tenant's projects, for [`ENTITLEMENT_TTL`].
|
/// Each tenant's projects, for [`ENTITLEMENT_TTL`].
|
||||||
projects: DashMap<String, (Instant, Vec<compliance_core::models::Project>)>,
|
projects: DashMap<String, (Instant, Vec<compliance_core::models::Project>)>,
|
||||||
|
/// API-key verdicts, valid and invalid, keyed by the key's SHA-256 (never
|
||||||
|
/// the key itself), for [`API_KEY_TTL`].
|
||||||
|
api_keys: DashMap<String, (Instant, ApiKeyVerify)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for RegistryClient {
|
impl std::fmt::Debug for RegistryClient {
|
||||||
@@ -203,6 +260,7 @@ impl RegistryClient {
|
|||||||
token: Mutex::new(None),
|
token: Mutex::new(None),
|
||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
|
api_keys: DashMap::new(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,14 +503,48 @@ impl RegistryClient {
|
|||||||
Ok(page.items)
|
Ok(page.items)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Verify a portal-issued API key (`bp_…`).
|
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
|
||||||
|
/// verdict younger than [`API_KEY_TTL`].
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The registry could not answer and no fresh verdict is cached. The
|
||||||
|
/// message never contains the key.
|
||||||
pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> {
|
pub async fn verify_api_key(&self, key: &str) -> Result<ApiKeyVerify, String> {
|
||||||
|
let digest = key_digest(key);
|
||||||
|
if let Some(entry) = self.api_keys.get(&digest) {
|
||||||
|
if entry.0.elapsed() < API_KEY_TTL {
|
||||||
|
return Ok(entry.1.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let verdict = self.fetch_api_key_verdict(key).await?;
|
||||||
|
self.cache_api_key_verdict(digest, &verdict);
|
||||||
|
Ok(verdict)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep `verdict` under `digest`. At [`API_KEY_CACHE_MAX`] the expired
|
||||||
|
/// verdicts go first; if none have, this one is not kept (the request
|
||||||
|
/// still gets it).
|
||||||
|
fn cache_api_key_verdict(&self, digest: String, verdict: &ApiKeyVerify) {
|
||||||
|
if self.api_keys.len() >= API_KEY_CACHE_MAX {
|
||||||
|
self.api_keys
|
||||||
|
.retain(|_, (at, _)| at.elapsed() < API_KEY_TTL);
|
||||||
|
if self.api_keys.len() >= API_KEY_CACHE_MAX {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.api_keys
|
||||||
|
.insert(digest, (Instant::now(), verdict.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_api_key_verdict(&self, key: &str) -> Result<ApiKeyVerify, String> {
|
||||||
let resp = self
|
let resp = self
|
||||||
.request(reqwest::Method::POST, "/v1/internal/api-keys/verify")
|
.request(reqwest::Method::POST, "/v1/internal/api-keys/verify")
|
||||||
.await?
|
.await?
|
||||||
.json(&serde_json::json!({ "key": key }))
|
.json(&serde_json::json!({ "key": key }))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
// reqwest's error names the URL, never the body.
|
||||||
.map_err(|e| format!("api-key verify failed: {e}"))?;
|
.map_err(|e| format!("api-key verify failed: {e}"))?;
|
||||||
if !resp.status().is_success() {
|
if !resp.status().is_success() {
|
||||||
return Err(format!("api-key verify returned {}", resp.status()));
|
return Err(format!("api-key verify returned {}", resp.status()));
|
||||||
@@ -574,6 +666,7 @@ mod tests {
|
|||||||
token: Mutex::new(None),
|
token: Mutex::new(None),
|
||||||
cache: DashMap::new(),
|
cache: DashMap::new(),
|
||||||
projects: DashMap::new(),
|
projects: DashMap::new(),
|
||||||
|
api_keys: DashMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
@@ -586,4 +679,118 @@ mod tests {
|
|||||||
started.elapsed()
|
started.elapsed()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A registry whose verify endpoint counts its calls and can be taken
|
||||||
|
/// down (500). Every key is valid for tenant `t`.
|
||||||
|
async fn verify_registry() -> (
|
||||||
|
RegistryClient,
|
||||||
|
Arc<std::sync::atomic::AtomicUsize>,
|
||||||
|
Arc<std::sync::atomic::AtomicBool>,
|
||||||
|
) {
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
let calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let down = Arc::new(AtomicBool::new(false));
|
||||||
|
let (c, d) = (calls.clone(), down.clone());
|
||||||
|
let app = axum::Router::new().route(
|
||||||
|
"/v1/internal/api-keys/verify",
|
||||||
|
axum::routing::post(move |axum::Json(body): axum::Json<serde_json::Value>| {
|
||||||
|
let (c, d) = (c.clone(), d.clone());
|
||||||
|
async move {
|
||||||
|
c.fetch_add(1, Ordering::SeqCst);
|
||||||
|
if d.load(Ordering::SeqCst) {
|
||||||
|
return Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
let valid = body["key"] != "bp_revoked";
|
||||||
|
Ok(axum::Json(serde_json::json!({
|
||||||
|
"valid": valid,
|
||||||
|
"tenant_id": "t",
|
||||||
|
"scopes": ["pruefwerk:findings.read"],
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||||
|
let client = RegistryClient {
|
||||||
|
base_url: format!("http://{addr}"),
|
||||||
|
product: "pruefwerk".into(),
|
||||||
|
http: reqwest::Client::new(),
|
||||||
|
token_url: None,
|
||||||
|
client_id: None,
|
||||||
|
client_secret: None,
|
||||||
|
token: Mutex::new(None),
|
||||||
|
cache: DashMap::new(),
|
||||||
|
projects: DashMap::new(),
|
||||||
|
api_keys: DashMap::new(),
|
||||||
|
};
|
||||||
|
(client, calls, down)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn api_key_verdicts_are_reused_valid_or_not() {
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
let (client, calls, _) = verify_registry().await;
|
||||||
|
for _ in 0..3 {
|
||||||
|
assert!(client.verify_api_key("bp_good").await.unwrap().valid);
|
||||||
|
assert!(!client.verify_api_key("bp_revoked").await.unwrap().valid);
|
||||||
|
}
|
||||||
|
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_unreachable_registry_is_bridged_only_by_a_fresh_verdict() {
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
let (client, _, down) = verify_registry().await;
|
||||||
|
client.verify_api_key("bp_good").await.unwrap();
|
||||||
|
down.store(true, Ordering::SeqCst);
|
||||||
|
// Warm: served from the cache.
|
||||||
|
assert!(client.verify_api_key("bp_good").await.unwrap().valid);
|
||||||
|
// Cold: nothing to fall back on.
|
||||||
|
assert!(client.verify_api_key("bp_other").await.is_err());
|
||||||
|
// Expired: as cold, so a revocation is never outlived by an outage.
|
||||||
|
for mut entry in client.api_keys.iter_mut() {
|
||||||
|
entry.0 = Instant::now()
|
||||||
|
.checked_sub(API_KEY_TTL + Duration::from_secs(1))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let err = client.verify_api_key("bp_good").await.unwrap_err();
|
||||||
|
assert!(!err.contains("bp_good"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_full_cache_drops_expired_verdicts_and_never_grows_past_its_cap() {
|
||||||
|
let (client, _, _) = verify_registry().await;
|
||||||
|
let verdict = client.verify_api_key("bp_good").await.unwrap();
|
||||||
|
let aged = Instant::now()
|
||||||
|
.checked_sub(API_KEY_TTL + Duration::from_secs(1))
|
||||||
|
.unwrap();
|
||||||
|
for i in 0..API_KEY_CACHE_MAX {
|
||||||
|
client
|
||||||
|
.api_keys
|
||||||
|
.insert(format!("old-{i}"), (aged, verdict.clone()));
|
||||||
|
}
|
||||||
|
client.verify_api_key("bp_new").await.unwrap();
|
||||||
|
assert!(client.api_keys.len() < 10, "{}", client.api_keys.len());
|
||||||
|
assert!(client.api_keys.contains_key(&key_digest("bp_new")));
|
||||||
|
|
||||||
|
// Full of fresh verdicts: the new one is answered but not kept.
|
||||||
|
for i in 0..API_KEY_CACHE_MAX {
|
||||||
|
client
|
||||||
|
.api_keys
|
||||||
|
.insert(format!("new-{i}"), (Instant::now(), verdict.clone()));
|
||||||
|
}
|
||||||
|
let before = client.api_keys.len();
|
||||||
|
assert!(client.verify_api_key("bp_newer").await.unwrap().valid);
|
||||||
|
assert_eq!(client.api_keys.len(), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_cache_holds_a_digest_never_the_key() {
|
||||||
|
let (client, _, _) = verify_registry().await;
|
||||||
|
client.verify_api_key("bp_good").await.unwrap();
|
||||||
|
assert!(!client.api_keys.contains_key("bp_good"));
|
||||||
|
assert!(client.api_keys.contains_key(&key_digest("bp_good")));
|
||||||
|
assert!(client.api_keys.iter().all(|e| !e.key().contains("bp_")));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
//! Portal-issued API keys on the customer API (tenant-registry ADR 0001):
|
||||||
|
//! the key middleware, the JWT middleware, the entitlement gate, the write
|
||||||
|
//! audit and the status ladder, in the server's order, against a fake tenant
|
||||||
|
//! registry and a live Mongo (for the agent itself); skips cleanly without
|
||||||
|
//! one. The route → scope table is covered in `role_gate`'s router tests.
|
||||||
|
|
||||||
|
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::{Request, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::middleware::{from_fn, from_fn_with_state};
|
||||||
|
use axum::routing::{get, post};
|
||||||
|
use axum::{Extension, Json, Router};
|
||||||
|
use tower::ServiceExt;
|
||||||
|
|
||||||
|
use compliance_agent::agent::ComplianceAgent;
|
||||||
|
use compliance_agent::api::api_key_gate::require_api_key;
|
||||||
|
use compliance_agent::api::server::{audit_delegated_writes, require_entitlement};
|
||||||
|
use compliance_agent::database::DatabasePool;
|
||||||
|
use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState};
|
||||||
|
use compliance_core::{TenantContext, SUPPORT_TENANT_HEADER};
|
||||||
|
|
||||||
|
use common::dev_config;
|
||||||
|
|
||||||
|
/// What the fake registry was asked: the path of every call, and the bodies
|
||||||
|
/// of audit entries.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Seen {
|
||||||
|
paths: Vec<String>,
|
||||||
|
audits: Vec<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Shared = Arc<Mutex<Seen>>;
|
||||||
|
|
||||||
|
const TENANT: &str = "11111111-1111-1111-1111-111111111111";
|
||||||
|
|
||||||
|
/// The registry's verify answer for `key`, or `None` to fail with 500.
|
||||||
|
fn verdict(key: &str) -> Option<serde_json::Value> {
|
||||||
|
let status = match key {
|
||||||
|
"bp_good" => "active",
|
||||||
|
"bp_restricted" => "restricted",
|
||||||
|
"bp_revoked" => return Some(serde_json::json!({ "valid": false })),
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"valid": true,
|
||||||
|
"tenant_id": TENANT,
|
||||||
|
"product": "pruefwerk",
|
||||||
|
"scopes": ["pruefwerk:findings.write"],
|
||||||
|
"key_id": "k-1",
|
||||||
|
"kind": "service",
|
||||||
|
"holder": "CI pipeline",
|
||||||
|
"tenant_status": status,
|
||||||
|
"legacy": false,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fake_registry(seen: Shared) -> String {
|
||||||
|
let app = Router::new()
|
||||||
|
.route(
|
||||||
|
"/v1/internal/api-keys/verify",
|
||||||
|
post(
|
||||||
|
|State(seen): State<Shared>, Json(body): Json<serde_json::Value>| async move {
|
||||||
|
seen.lock().unwrap().paths.push("verify".into());
|
||||||
|
verdict(body["key"].as_str().unwrap_or_default())
|
||||||
|
.map(Json)
|
||||||
|
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/internal/entitlements/check",
|
||||||
|
post(|State(seen): State<Shared>| async move {
|
||||||
|
seen.lock().unwrap().paths.push("entitlement".into());
|
||||||
|
Json(serde_json::json!({ "allowed": true, "status": "active" }))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/v1/audit",
|
||||||
|
post(
|
||||||
|
|State(seen): State<Shared>, Json(body): Json<serde_json::Value>| async move {
|
||||||
|
seen.lock().unwrap().audits.push(body);
|
||||||
|
StatusCode::CREATED
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_state(seen);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||||
|
format!("http://{addr}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An agent whose registry is `registry`, or `None` without Mongo.
|
||||||
|
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
|
||||||
|
let uri = std::env::var("TEST_MONGODB_URI")
|
||||||
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||||
|
let db_name = format!("key_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||||
|
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
|
||||||
|
eprintln!("SKIP api_key_access: no MongoDB reachable at {uri}");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut config = dev_config(uri, db_name);
|
||||||
|
config.tenant_registry_url = Some(registry.to_string());
|
||||||
|
Some(Arc::new(ComplianceAgent::new(config, pool)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/r` answers the tenant the request runs in, for reads and writes.
|
||||||
|
fn app(agent: Arc<ComplianceAgent>) -> Router {
|
||||||
|
let tenant = |Extension(ctx): Extension<TenantContext>| async move { ctx.tenant_id };
|
||||||
|
// Same order as the server, without the role gate.
|
||||||
|
Router::new()
|
||||||
|
.route("/r", get(tenant).patch(tenant))
|
||||||
|
.layer(from_fn(require_tenant_status))
|
||||||
|
.layer(from_fn_with_state(agent.clone(), audit_delegated_writes))
|
||||||
|
.layer(from_fn_with_state(agent.clone(), require_entitlement))
|
||||||
|
.layer(from_fn(require_jwt_auth))
|
||||||
|
.layer(from_fn_with_state(agent, require_api_key))
|
||||||
|
// Never reached: no test presents a well-formed JWT.
|
||||||
|
.layer(Extension(JwksState::new(
|
||||||
|
"http://127.0.0.1:9/jwks".into(),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(
|
||||||
|
agent: &Arc<ComplianceAgent>,
|
||||||
|
method: &str,
|
||||||
|
bearer: &str,
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
) -> (StatusCode, String) {
|
||||||
|
let mut req = Request::builder()
|
||||||
|
.method(method)
|
||||||
|
.uri("/r")
|
||||||
|
.header("authorization", format!("Bearer {bearer}"));
|
||||||
|
for (name, value) in headers {
|
||||||
|
req = req.header(*name, *value);
|
||||||
|
}
|
||||||
|
let resp = app(agent.clone())
|
||||||
|
.oneshot(req.body(Body::empty()).unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = resp.status();
|
||||||
|
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(status, String::from_utf8_lossy(&bytes).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_key_works_in_its_own_tenant_only() {
|
||||||
|
let seen: Shared = Arc::default();
|
||||||
|
let base = fake_registry(seen.clone()).await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The tenant comes from the registry; the support header names another.
|
||||||
|
let other = "22222222-2222-2222-2222-222222222222";
|
||||||
|
let (status, body) = call(&agent, "GET", "bp_good", &[(SUPPORT_TENANT_HEADER, other)]).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(body, TENANT);
|
||||||
|
|
||||||
|
// Within the TTL the registry is not asked again, and the entitlement
|
||||||
|
// check is never asked for a key.
|
||||||
|
let (status, _) = call(&agent, "GET", "bp_good", &[]).await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
assert_eq!(seen.lock().unwrap().paths, ["verify"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_rejected_key_or_a_jwt_never_gets_a_key_context() {
|
||||||
|
let seen: Shared = Arc::default();
|
||||||
|
let base = fake_registry(seen.clone()).await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (status, body) = call(&agent, "GET", "bp_revoked", &[]).await;
|
||||||
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||||
|
assert!(body.contains("invalid_api_key"), "{body}");
|
||||||
|
|
||||||
|
// Not a key: the JWT middleware refuses it, and the registry's key
|
||||||
|
// verify is not asked.
|
||||||
|
let calls = seen.lock().unwrap().paths.len();
|
||||||
|
let (status, _) = call(&agent, "GET", "not-a-jwt", &[]).await;
|
||||||
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||||
|
assert_eq!(seen.lock().unwrap().paths.len(), calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_cold_cache_and_an_unreachable_registry_mean_503() {
|
||||||
|
let seen: Shared = Arc::default();
|
||||||
|
let base = fake_registry(seen).await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let (status, body) = call(&agent, "GET", "bp_unreachable", &[]).await;
|
||||||
|
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
assert!(!body.contains("bp_unreachable"), "{body}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_restricted_tenant_reads_but_does_not_write() {
|
||||||
|
let seen: Shared = Arc::default();
|
||||||
|
let base = fake_registry(seen).await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
call(&agent, "GET", "bp_restricted", &[]).await.0,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
call(&agent, "PATCH", "bp_restricted", &[]).await.0,
|
||||||
|
StatusCode::PAYMENT_REQUIRED
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_key_write_is_audited_as_the_key() {
|
||||||
|
let seen: Shared = Arc::default();
|
||||||
|
let base = fake_registry(seen.clone()).await;
|
||||||
|
let Some(agent) = agent(&base).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let (status, _) = call(
|
||||||
|
&agent,
|
||||||
|
"PATCH",
|
||||||
|
"bp_good",
|
||||||
|
&[("x-bp-actor", "jdoe"), ("x-bp-client-ip", "203.0.113.7")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK);
|
||||||
|
|
||||||
|
// The audit is posted in the background.
|
||||||
|
let mut audit = None;
|
||||||
|
for _ in 0..50 {
|
||||||
|
audit = seen.lock().unwrap().audits.first().cloned();
|
||||||
|
if audit.is_some() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||||
|
}
|
||||||
|
let audit = audit.expect("audit entry posted");
|
||||||
|
assert_eq!(audit["action"], "pruefwerk.api_key_write");
|
||||||
|
assert_eq!(audit["actor_type"], "apikey");
|
||||||
|
assert_eq!(audit["actor_id"], "apikey:k-1");
|
||||||
|
assert_eq!(audit["actor_name"], "CI pipeline");
|
||||||
|
assert_eq!(audit["metadata"]["on_behalf_of"], "jdoe");
|
||||||
|
assert_eq!(audit["tenant_id"], TENANT);
|
||||||
|
assert_eq!(audit["source_ip"], "203.0.113.7");
|
||||||
|
}
|
||||||
@@ -104,6 +104,35 @@ async fn update_finding_status() {
|
|||||||
server.cleanup().await;
|
server.cleanup().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn feedback_on_an_unknown_finding_is_404() {
|
||||||
|
let server = TestServer::start().await;
|
||||||
|
|
||||||
|
insert_finding(&server, "repo1", "Test Bug", "medium").await;
|
||||||
|
let resp = server.get("/api/v1/findings").await;
|
||||||
|
let body: serde_json::Value = resp.json().await.unwrap();
|
||||||
|
let finding_id = body["data"][0]["_id"]["$oid"].as_str().unwrap();
|
||||||
|
|
||||||
|
let feedback = json!({ "feedback": "reviewed" });
|
||||||
|
let resp = server
|
||||||
|
.patch(
|
||||||
|
&format!("/api/v1/findings/{finding_id}/feedback"),
|
||||||
|
&feedback,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(resp.status(), 200);
|
||||||
|
|
||||||
|
let resp = server
|
||||||
|
.patch(
|
||||||
|
"/api/v1/findings/000000000000000000000000/feedback",
|
||||||
|
&feedback,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(resp.status(), 404);
|
||||||
|
|
||||||
|
server.cleanup().await;
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn bulk_update_finding_status() {
|
async fn bulk_update_finding_status() {
|
||||||
let server = TestServer::start().await;
|
let server = TestServer::start().await;
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ fn tenant(id: &str, role: OrgRole) -> TenantCtx {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ fn member(user: &str) -> TenantContext {
|
|||||||
user_id: user.into(),
|
user_id: user.into(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ fn ctx(tenant_id: &str, slug: &str) -> TenantContext {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ fn ctx_with(status: TenantStatus) -> TenantContext {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -129,6 +129,12 @@ const PUBLIC_ENDPOINTS: &[&str] = &["/api/v1/health"];
|
|||||||
/// would semantically conflict with these cross-tenant / machine operations.
|
/// would semantically conflict with these cross-tenant / machine operations.
|
||||||
const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/v1/platform/"];
|
const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/v1/platform/"];
|
||||||
|
|
||||||
|
/// Whether `path` is outside the customer API: the health check, or a
|
||||||
|
/// sub-API with its own authentication ([`PUBLIC_PREFIXES`]).
|
||||||
|
pub fn bypasses_customer_auth(path: &str) -> bool {
|
||||||
|
PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p))
|
||||||
|
}
|
||||||
|
|
||||||
/// Middleware that validates Bearer JWT tokens against Keycloak's JWKS
|
/// Middleware that validates Bearer JWT tokens against Keycloak's JWKS
|
||||||
/// and attaches a `TenantContext` extension on success.
|
/// and attaches a `TenantContext` extension on success.
|
||||||
///
|
///
|
||||||
@@ -137,9 +143,16 @@ const PUBLIC_PREFIXES: &[&str] = &["/api/v1/admin/", "/api/v1/werkbank/", "/api/
|
|||||||
/// not configured), requests pass through and downstream code must
|
/// not configured), requests pass through and downstream code must
|
||||||
/// handle the missing context.
|
/// handle the missing context.
|
||||||
pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response {
|
pub async fn require_jwt_auth(mut request: Request, next: Next) -> Response {
|
||||||
let path = request.uri().path();
|
if bypasses_customer_auth(request.uri().path()) {
|
||||||
|
return next.run(request).await;
|
||||||
if PUBLIC_ENDPOINTS.contains(&path) || PUBLIC_PREFIXES.iter().any(|p| path.starts_with(p)) {
|
}
|
||||||
|
// An API key the agent's key middleware (mounted outside this one, the
|
||||||
|
// only place that inserts a context this early) has already verified.
|
||||||
|
if request
|
||||||
|
.extensions()
|
||||||
|
.get::<TenantContext>()
|
||||||
|
.is_some_and(|c| c.api_key.is_some())
|
||||||
|
{
|
||||||
return next.run(request).await;
|
return next.run(request).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,6 +309,7 @@ fn authenticate(c: Claims, requested_tenant: Option<&str>) -> Result<Authenticat
|
|||||||
user_id: staff.user_id.clone(),
|
user_id: staff.user_id.clone(),
|
||||||
user_name: staff.user_name.clone(),
|
user_name: staff.user_name.clone(),
|
||||||
staff: Some(staff),
|
staff: Some(staff),
|
||||||
|
api_key: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
// Staff who also belong to a tenant work in it like anyone else.
|
// Staff who also belong to a tenant work in it like anyone else.
|
||||||
@@ -431,6 +445,7 @@ fn claims_to_context(c: Claims) -> Result<TenantContext, String> {
|
|||||||
user_id: c.sub,
|
user_id: c.sub,
|
||||||
user_name: c.name.or(c.preferred_username),
|
user_name: c.name.or(c.preferred_username),
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ mod tests {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ pub mod error;
|
|||||||
pub mod exec_policy;
|
pub mod exec_policy;
|
||||||
#[cfg(feature = "net")]
|
#[cfg(feature = "net")]
|
||||||
pub mod guarded_net;
|
pub mod guarded_net;
|
||||||
|
pub mod license_notices;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod net_guard;
|
pub mod net_guard;
|
||||||
pub mod purl;
|
pub mod purl;
|
||||||
@@ -35,6 +36,6 @@ pub use error::CoreError;
|
|||||||
pub use exec_policy::ExecPolicy;
|
pub use exec_policy::ExecPolicy;
|
||||||
pub use net_guard::{NetGuard, NetGuardError};
|
pub use net_guard::{NetGuard, NetGuardError};
|
||||||
pub use tenant::{
|
pub use tenant::{
|
||||||
OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
|
ApiKeyAccess, OrgRole, ProductAccess, StaffAccess, TenantContext, TenantStatus, SUPPORT_ROLES,
|
||||||
SUPPORT_TENANT_HEADER,
|
SUPPORT_TENANT_HEADER,
|
||||||
};
|
};
|
||||||
@@ -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<String>,
|
||||||
|
/// 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<String> {
|
||||||
|
let mut urls: Vec<String> = 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<String, Group<'_>> = BTreeMap::new();
|
||||||
|
let mut unknown: Vec<String> = 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<String, Group<'_>>,
|
||||||
|
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<String, Group<'_>>,
|
||||||
|
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("<https://spdx.org/licenses/MIT.html>"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,484 @@
|
|||||||
|
//! Licences a workspace has confirmed for its components: where a scan found
|
||||||
|
//! no licence (or a wrong one), a person states the licence, its category,
|
||||||
|
//! the copyright and where it is written down.
|
||||||
|
//!
|
||||||
|
//! A conclusion is kept apart from the scanned components, which every scan
|
||||||
|
//! rewrites, and is merged into them when they are read or exported
|
||||||
|
//! ([`apply`]). It belongs to a package: to one version of it, or to every
|
||||||
|
//! version. In the exports it is the concluded licence (CycloneDX
|
||||||
|
//! `acknowledgement: concluded`, SPDX `licenseConcluded`); the licence the
|
||||||
|
//! scan detected stays the declared one.
|
||||||
|
|
||||||
|
use chrono::{DateTime, NaiveDate, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::SbomEntry;
|
||||||
|
use crate::purl::Purl;
|
||||||
|
use crate::spdx_license;
|
||||||
|
|
||||||
|
/// What a licence allows and asks for, roughly. A hint for reviewing
|
||||||
|
/// components, not legal advice.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum LicenseCategory {
|
||||||
|
/// No rights reserved (CC0, Unlicense).
|
||||||
|
PublicDomain,
|
||||||
|
/// Use, change and ship freely; keep the notice (MIT, Apache-2.0, BSD).
|
||||||
|
Permissive,
|
||||||
|
/// Changes to the component itself stay open (LGPL, MPL, EPL).
|
||||||
|
WeakCopyleft,
|
||||||
|
/// Whatever is shipped with it stays open (GPL).
|
||||||
|
StrongCopyleft,
|
||||||
|
/// As strong copyleft, also when only offered over a network (AGPL).
|
||||||
|
NetworkCopyleft,
|
||||||
|
/// Bought or otherwise licensed under terms of its own.
|
||||||
|
Proprietary,
|
||||||
|
/// Written by the workspace's own company.
|
||||||
|
OwnCode,
|
||||||
|
/// Not known yet.
|
||||||
|
#[default]
|
||||||
|
Unclear,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LicenseCategory {
|
||||||
|
/// Every category, in the order a picker lists them.
|
||||||
|
pub const ALL: [Self; 8] = [
|
||||||
|
Self::Permissive,
|
||||||
|
Self::WeakCopyleft,
|
||||||
|
Self::StrongCopyleft,
|
||||||
|
Self::NetworkCopyleft,
|
||||||
|
Self::Proprietary,
|
||||||
|
Self::PublicDomain,
|
||||||
|
Self::OwnCode,
|
||||||
|
Self::Unclear,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The stored name (`weak_copyleft`).
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::PublicDomain => "public_domain",
|
||||||
|
Self::Permissive => "permissive",
|
||||||
|
Self::WeakCopyleft => "weak_copyleft",
|
||||||
|
Self::StrongCopyleft => "strong_copyleft",
|
||||||
|
Self::NetworkCopyleft => "network_copyleft",
|
||||||
|
Self::Proprietary => "proprietary",
|
||||||
|
Self::OwnCode => "own_code",
|
||||||
|
Self::Unclear => "unclear",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The category of its stored name.
|
||||||
|
pub fn parse(name: &str) -> Option<Self> {
|
||||||
|
Self::ALL.into_iter().find(|c| c.as_str() == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether it asks for source code to be passed on (weak, strong or
|
||||||
|
/// network copyleft).
|
||||||
|
pub fn is_copyleft(self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self,
|
||||||
|
Self::WeakCopyleft | Self::StrongCopyleft | Self::NetworkCopyleft
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much a licence of this category restricts, for combining the
|
||||||
|
/// terms of an expression: `OR` takes the least, `AND` the most.
|
||||||
|
pub(crate) fn restriction(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::PublicDomain => 0,
|
||||||
|
Self::Permissive | Self::OwnCode => 1,
|
||||||
|
Self::WeakCopyleft => 2,
|
||||||
|
Self::StrongCopyleft => 3,
|
||||||
|
Self::NetworkCopyleft => 4,
|
||||||
|
Self::Proprietary => 5,
|
||||||
|
Self::Unclear => 6,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a component is used: shipped in the product, or only to build or
|
||||||
|
/// develop it. Copyleft obligations mostly bind what is shipped.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum LicenseUsage {
|
||||||
|
/// Part of what is delivered (an app, a firmware image, a library in it).
|
||||||
|
Shipped,
|
||||||
|
/// Only used to build, test or develop.
|
||||||
|
BuildOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A licence a person confirmed for a package.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct LicenseConclusion {
|
||||||
|
/// [`conclusion_id`]: the package key and the version, or `*` for all.
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: String,
|
||||||
|
/// [`package_key`] of the package.
|
||||||
|
pub package_key: String,
|
||||||
|
pub name: String,
|
||||||
|
pub package_manager: String,
|
||||||
|
/// The version it was confirmed for; `None` for every version.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// An SPDX licence expression (`MIT`, `MIT OR Apache-2.0`), or a
|
||||||
|
/// `LicenseRef-` id for a licence SPDX does not list.
|
||||||
|
pub license: String,
|
||||||
|
/// The name of a `LicenseRef-` licence (`Pump Controls EULA`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_name: Option<String>,
|
||||||
|
pub category: LicenseCategory,
|
||||||
|
/// Copyright lines (`© 2019 Example GmbH`).
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub copyright: Vec<String>,
|
||||||
|
/// The licence text, where it is not an SPDX-listed licence.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_text: Option<String>,
|
||||||
|
/// Where the licence text is published.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_url: Option<String>,
|
||||||
|
/// Where the licence was found: a file in the repository, a contract,
|
||||||
|
/// a web page.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub evidence: Option<String>,
|
||||||
|
/// The contract or licence number of a bought licence.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub contract_ref: Option<String>,
|
||||||
|
/// When a bought licence ends.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub valid_until: Option<NaiveDate>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub usage: Option<LicenseUsage>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub note: Option<String>,
|
||||||
|
/// Who confirmed it (Keycloak user id), with the name the workspace reads.
|
||||||
|
pub by: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub by_name: Option<String>,
|
||||||
|
/// BreakPilot support rather than one of the workspace's users.
|
||||||
|
#[serde(default)]
|
||||||
|
pub support: bool,
|
||||||
|
pub at: DateTime<Utc>,
|
||||||
|
/// 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<super::license_policy::LegalReview>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most text a field takes; a licence text may be longer.
|
||||||
|
pub const MAX_FIELD_CHARS: usize = 2_000;
|
||||||
|
/// The most a licence text takes.
|
||||||
|
pub const MAX_TEXT_CHARS: usize = 200_000;
|
||||||
|
/// The most copyright lines.
|
||||||
|
pub const MAX_COPYRIGHT_LINES: usize = 20;
|
||||||
|
|
||||||
|
impl LicenseConclusion {
|
||||||
|
/// The licence as people read it: the name of a `LicenseRef-` licence,
|
||||||
|
/// otherwise the expression.
|
||||||
|
pub fn display(&self) -> &str {
|
||||||
|
match &self.license_name {
|
||||||
|
Some(name) if self.license.starts_with("LicenseRef-") => name,
|
||||||
|
_ => &self.license,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether it is a licence SPDX does not list (`LicenseRef-`).
|
||||||
|
pub fn is_custom(&self) -> bool {
|
||||||
|
self.license.starts_with("LicenseRef-")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why it cannot be stored, in words; `Ok` when it can.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// The first problem found: no or an invalid licence, a custom licence
|
||||||
|
/// without a name, a field too long.
|
||||||
|
pub fn validate(&self) -> Result<(), String> {
|
||||||
|
let license = self.license.trim();
|
||||||
|
if license.is_empty() {
|
||||||
|
return Err("licence missing".into());
|
||||||
|
}
|
||||||
|
if self.is_custom() {
|
||||||
|
if !is_license_ref(license) {
|
||||||
|
return Err(format!("not a valid LicenseRef id: {license}"));
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.license_name
|
||||||
|
.as_deref()
|
||||||
|
.is_none_or(|n| n.trim().is_empty())
|
||||||
|
{
|
||||||
|
return Err("a licence SPDX does not list needs a name".into());
|
||||||
|
}
|
||||||
|
} else if !spdx_license::is_spdx_expression(license) {
|
||||||
|
return Err(format!("not an SPDX licence expression: {license}"));
|
||||||
|
}
|
||||||
|
if self.copyright.len() > MAX_COPYRIGHT_LINES {
|
||||||
|
return Err(format!("at most {MAX_COPYRIGHT_LINES} copyright lines"));
|
||||||
|
}
|
||||||
|
let short = [
|
||||||
|
("licence name", self.license_name.as_deref()),
|
||||||
|
("licence URL", self.license_url.as_deref()),
|
||||||
|
("evidence", self.evidence.as_deref()),
|
||||||
|
("contract", self.contract_ref.as_deref()),
|
||||||
|
("note", self.note.as_deref()),
|
||||||
|
];
|
||||||
|
for (field, value) in short {
|
||||||
|
if value.is_some_and(|v| v.chars().count() > MAX_FIELD_CHARS) {
|
||||||
|
return Err(format!("{field} longer than {MAX_FIELD_CHARS} characters"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.copyright
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.chars().count() > MAX_FIELD_CHARS)
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"copyright line longer than {MAX_FIELD_CHARS} characters"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.license_text
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|t| t.chars().count() > MAX_TEXT_CHARS)
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"licence text longer than {MAX_TEXT_CHARS} characters"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(url) = self.license_url.as_deref() {
|
||||||
|
let lower = url.trim().to_ascii_lowercase();
|
||||||
|
if !(lower.starts_with("https://") || lower.starts_with("http://")) {
|
||||||
|
return Err("the licence URL must start with https:// or http://".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `id` is a well-formed `LicenseRef-` id (letters, digits, `.`, `-`).
|
||||||
|
pub fn is_license_ref(id: &str) -> bool {
|
||||||
|
id.strip_prefix("LicenseRef-").is_some_and(|rest| {
|
||||||
|
!rest.is_empty()
|
||||||
|
&& rest
|
||||||
|
.chars()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `LicenseRef-` id of a licence SPDX does not list, made from its name:
|
||||||
|
/// `Pump Controls EULA` is `LicenseRef-Pump-Controls-EULA`.
|
||||||
|
pub fn license_ref(name: &str) -> String {
|
||||||
|
let mut id = String::from("LicenseRef-");
|
||||||
|
let mut dash = false;
|
||||||
|
for c in name.trim().chars() {
|
||||||
|
if c.is_ascii_alphanumeric() || c == '.' {
|
||||||
|
id.push(c);
|
||||||
|
dash = false;
|
||||||
|
} else if !dash && id.len() > "LicenseRef-".len() {
|
||||||
|
id.push('-');
|
||||||
|
dash = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Only a dash after the name, never the one of `LicenseRef-`.
|
||||||
|
while id.len() > "LicenseRef-".len() && id.ends_with('-') {
|
||||||
|
id.pop();
|
||||||
|
}
|
||||||
|
if id.len() == "LicenseRef-".len() {
|
||||||
|
id.push_str("custom");
|
||||||
|
}
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key of a package across its versions: its purl without version,
|
||||||
|
/// qualifiers and subpath (`pkg:npm/%40scope/name`), or
|
||||||
|
/// `<package manager>:<name>` without a purl.
|
||||||
|
pub fn package_key(name: &str, package_manager: &str, purl: Option<&str>) -> String {
|
||||||
|
if let Some(p) = purl.and_then(Purl::parse) {
|
||||||
|
return match &p.namespace {
|
||||||
|
Some(ns) => format!("pkg:{}/{}/{}", p.ty, ns, p.name),
|
||||||
|
None => format!("pkg:{}/{}", p.ty, p.name),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
format!("{}:{}", package_manager.trim(), name.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id of the conclusion for `key` at `version` (`*` for every version).
|
||||||
|
pub fn conclusion_id(key: &str, version: Option<&str>) -> String {
|
||||||
|
format!("{key}@{}", version.unwrap_or("*"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The conclusion that applies to `entry`: the one for its version, else
|
||||||
|
/// the one for every version of its package.
|
||||||
|
pub fn find<'a>(
|
||||||
|
conclusions: &'a [LicenseConclusion],
|
||||||
|
entry: &SbomEntry,
|
||||||
|
) -> Option<&'a LicenseConclusion> {
|
||||||
|
find_for(
|
||||||
|
conclusions,
|
||||||
|
&entry.name,
|
||||||
|
&entry.package_manager,
|
||||||
|
&entry.version,
|
||||||
|
entry.purl.as_deref(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`find`] for a component given by its fields.
|
||||||
|
pub fn find_for<'a>(
|
||||||
|
conclusions: &'a [LicenseConclusion],
|
||||||
|
name: &str,
|
||||||
|
package_manager: &str,
|
||||||
|
version: &str,
|
||||||
|
purl: Option<&str>,
|
||||||
|
) -> Option<&'a LicenseConclusion> {
|
||||||
|
let key = package_key(name, package_manager, purl);
|
||||||
|
let mut all_versions = None;
|
||||||
|
for c in conclusions.iter().filter(|c| c.package_key == key) {
|
||||||
|
match c.version.as_deref() {
|
||||||
|
Some(v) if v == version => return Some(c),
|
||||||
|
None => all_versions = Some(c),
|
||||||
|
Some(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all_versions
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attach to every entry the conclusion that applies to it.
|
||||||
|
pub fn apply(entries: &mut [SbomEntry], conclusions: &[LicenseConclusion]) {
|
||||||
|
if conclusions.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for entry in entries.iter_mut() {
|
||||||
|
entry.concluded = find(conclusions, entry).cloned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn conclusion(key: &str, version: Option<&str>, license: &str) -> LicenseConclusion {
|
||||||
|
LicenseConclusion {
|
||||||
|
id: conclusion_id(key, version),
|
||||||
|
package_key: key.into(),
|
||||||
|
name: "x".into(),
|
||||||
|
package_manager: "npm".into(),
|
||||||
|
version: version.map(String::from),
|
||||||
|
license: license.into(),
|
||||||
|
license_name: None,
|
||||||
|
category: LicenseCategory::Permissive,
|
||||||
|
copyright: Vec::new(),
|
||||||
|
license_text: None,
|
||||||
|
license_url: None,
|
||||||
|
evidence: None,
|
||||||
|
contract_ref: None,
|
||||||
|
valid_until: None,
|
||||||
|
usage: None,
|
||||||
|
note: None,
|
||||||
|
by: "u1".into(),
|
||||||
|
by_name: None,
|
||||||
|
support: false,
|
||||||
|
at: Utc::now(),
|
||||||
|
review: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry(name: &str, version: &str, purl: Option<&str>) -> SbomEntry {
|
||||||
|
let mut e = SbomEntry::new("t".into(), name.into(), version.into(), "npm".into());
|
||||||
|
e.purl = purl.map(String::from);
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_package_is_keyed_without_its_version() {
|
||||||
|
assert_eq!(
|
||||||
|
package_key("core", "npm", Some("pkg:npm/%40angular/core@17.0.1?x=y")),
|
||||||
|
"pkg:npm/@angular/core"
|
||||||
|
);
|
||||||
|
// Encoded or not, the scope is the same package.
|
||||||
|
assert_eq!(
|
||||||
|
package_key("core", "npm", Some("pkg:npm/@angular/core@16.2.0")),
|
||||||
|
"pkg:npm/@angular/core"
|
||||||
|
);
|
||||||
|
assert_eq!(package_key("Foo", "nuget", None), "nuget:Foo");
|
||||||
|
assert_eq!(package_key("Foo", "nuget", Some("not a purl")), "nuget:Foo");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_version_conclusion_wins_over_the_package_one() {
|
||||||
|
let key = "pkg:npm/left-pad";
|
||||||
|
let all = conclusion(key, None, "MIT");
|
||||||
|
let one = conclusion(key, Some("1.3.0"), "ISC");
|
||||||
|
let list = vec![all, one];
|
||||||
|
let e = entry("left-pad", "1.3.0", Some("pkg:npm/left-pad@1.3.0"));
|
||||||
|
assert_eq!(find(&list, &e).map(|c| c.license.as_str()), Some("ISC"));
|
||||||
|
let other = entry("left-pad", "1.1.0", Some("pkg:npm/left-pad@1.1.0"));
|
||||||
|
assert_eq!(find(&list, &other).map(|c| c.license.as_str()), Some("MIT"));
|
||||||
|
let none = entry("right-pad", "1.0.0", Some("pkg:npm/right-pad@1.0.0"));
|
||||||
|
assert!(find(&list, &none).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn apply_attaches_and_leaves_others_alone() {
|
||||||
|
let list = vec![conclusion("pkg:npm/a", None, "MIT")];
|
||||||
|
let mut entries = vec![
|
||||||
|
entry("a", "1", Some("pkg:npm/a@1")),
|
||||||
|
entry("b", "1", Some("pkg:npm/b@1")),
|
||||||
|
];
|
||||||
|
apply(&mut entries, &list);
|
||||||
|
assert!(entries[0].concluded.is_some());
|
||||||
|
assert!(entries[1].concluded.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn custom_licences_get_a_license_ref() {
|
||||||
|
assert_eq!(
|
||||||
|
license_ref("Pump Controls EULA"),
|
||||||
|
"LicenseRef-Pump-Controls-EULA"
|
||||||
|
);
|
||||||
|
assert_eq!(license_ref(" ©© "), "LicenseRef-custom");
|
||||||
|
assert_eq!(license_ref("v1.2 / 2020"), "LicenseRef-v1.2-2020");
|
||||||
|
assert_eq!(license_ref("EULA!"), "LicenseRef-EULA");
|
||||||
|
assert!(is_license_ref("LicenseRef-a.b-1"));
|
||||||
|
assert!(!is_license_ref("LicenseRef-"));
|
||||||
|
assert!(!is_license_ref("LicenseRef-a b"));
|
||||||
|
assert!(!is_license_ref("MIT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validation_names_the_problem() {
|
||||||
|
let ok = conclusion("k", None, "MIT OR Apache-2.0");
|
||||||
|
assert!(ok.validate().is_ok());
|
||||||
|
assert!(conclusion("k", None, "").validate().is_err());
|
||||||
|
assert!(conclusion("k", None, "Custom thing").validate().is_err());
|
||||||
|
let mut custom = conclusion("k", None, "LicenseRef-Pump");
|
||||||
|
assert!(custom.validate().is_err(), "a custom licence needs a name");
|
||||||
|
custom.license_name = Some("Pump EULA".into());
|
||||||
|
assert!(custom.validate().is_ok());
|
||||||
|
assert_eq!(custom.display(), "Pump EULA");
|
||||||
|
custom.license_url = Some("ftp://x".into());
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
custom.license_url = Some("https://example.com/eula".into());
|
||||||
|
custom.copyright = vec!["c".into(); MAX_COPYRIGHT_LINES + 1];
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
custom.copyright = vec!["x".repeat(MAX_FIELD_CHARS + 1)];
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
custom.copyright.clear();
|
||||||
|
custom.note = Some("x".repeat(MAX_FIELD_CHARS + 1));
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
custom.note = None;
|
||||||
|
custom.license_text = Some("x".repeat(MAX_TEXT_CHARS + 1));
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
custom.license = "LicenseRef-a b".into();
|
||||||
|
custom.license_text = None;
|
||||||
|
assert!(custom.validate().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn categories_round_trip_their_names() {
|
||||||
|
for c in LicenseCategory::ALL {
|
||||||
|
assert_eq!(LicenseCategory::parse(c.as_str()), Some(c));
|
||||||
|
}
|
||||||
|
assert_eq!(LicenseCategory::parse("nope"), None);
|
||||||
|
assert!(LicenseCategory::WeakCopyleft.is_copyleft());
|
||||||
|
assert!(!LicenseCategory::Proprietary.is_copyleft());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<CategoryRule>,
|
||||||
|
/// Rules for single licences, before the categories.
|
||||||
|
#[serde(default)]
|
||||||
|
pub licenses: Vec<LicenseRule>,
|
||||||
|
/// 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<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub updated_by_name: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub updated_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Self, String> {
|
||||||
|
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<LicenseRule> = 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<String>,
|
||||||
|
/// 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<String>,
|
||||||
|
pub at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<VerdictReason>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<String>, 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,8 @@ pub mod finding;
|
|||||||
pub mod git_source;
|
pub mod git_source;
|
||||||
pub mod graph;
|
pub mod graph;
|
||||||
pub mod issue;
|
pub mod issue;
|
||||||
|
pub mod license;
|
||||||
|
pub mod license_policy;
|
||||||
pub mod mcp;
|
pub mod mcp;
|
||||||
pub mod mcp_token;
|
pub mod mcp_token;
|
||||||
pub mod notification;
|
pub mod notification;
|
||||||
@@ -45,6 +47,10 @@ pub use graph::{
|
|||||||
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
|
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
|
||||||
};
|
};
|
||||||
pub use issue::{IssueStatus, TrackerIssue, TrackerType};
|
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::{McpServerConfig, McpServerStatus, McpTransport};
|
||||||
pub use mcp_token::{McpToken, McpTokenView};
|
pub use mcp_token::{McpToken, McpTokenView};
|
||||||
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
|
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
|
||||||
|
|||||||
@@ -119,6 +119,16 @@ pub struct SbomEntry {
|
|||||||
/// stored before it was recorded.
|
/// stored before it was recorded.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub in_image: Option<InImage>,
|
pub in_image: Option<InImage>,
|
||||||
|
/// The licence a person confirmed for the component
|
||||||
|
/// ([`super::license::LicenseConclusion`]). Never stored with it: a scan
|
||||||
|
/// rewrites the components, so it is attached when they are read.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub concluded: Option<super::license::LicenseConclusion>,
|
||||||
|
/// 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<super::license_policy::LicenseVerdict>,
|
||||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||||
@@ -135,6 +145,14 @@ pub struct ComponentHash {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SbomEntry {
|
impl SbomEntry {
|
||||||
|
/// The licence that counts: the confirmed one, else the detected one.
|
||||||
|
pub fn effective_license(&self) -> Option<&str> {
|
||||||
|
match &self.concluded {
|
||||||
|
Some(c) => Some(c.display()),
|
||||||
|
None => self.license.as_deref().filter(|l| !l.trim().is_empty()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new(repo_id: String, name: String, version: String, package_manager: String) -> Self {
|
pub fn new(repo_id: String, name: String, version: String, package_manager: String) -> Self {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
Self {
|
Self {
|
||||||
@@ -153,6 +171,8 @@ impl SbomEntry {
|
|||||||
manufacturer_url: None,
|
manufacturer_url: None,
|
||||||
cpe: None,
|
cpe: None,
|
||||||
in_image: None,
|
in_image: None,
|
||||||
|
concluded: None,
|
||||||
|
policy: None,
|
||||||
created_at: now,
|
created_at: now,
|
||||||
updated_at: now,
|
updated_at: now,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,8 @@
|
|||||||
//! the suppliers declare them.
|
//! the suppliers declare them.
|
||||||
|
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
advisory_source, is_cve, ComponentHash, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
advisory_source, is_cve, ComponentHash, LicenseConclusion, SbomEntry, YOCTO_RECIPE_MANAGER,
|
||||||
|
YOCTO_RECIPE_SOURCE,
|
||||||
};
|
};
|
||||||
use crate::purl::Purl;
|
use crate::purl::Purl;
|
||||||
use crate::spdx_license;
|
use crate::spdx_license;
|
||||||
@@ -32,8 +33,8 @@ pub fn product_ref(subject: &str) -> String {
|
|||||||
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
|
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
|
||||||
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
|
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
|
||||||
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
|
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
|
||||||
/// It is the license the supplier declares (registry or lockfile metadata):
|
/// It is the license the supplier declares (registry or lockfile metadata);
|
||||||
/// Prüfwerk has not concluded it.
|
/// a license a person confirmed is written by [`concluded_choice`] instead.
|
||||||
fn license_choice(license: &str) -> serde_json::Value {
|
fn license_choice(license: &str) -> serde_json::Value {
|
||||||
let license = spdx_license::normalise(license);
|
let license = spdx_license::normalise(license);
|
||||||
if spdx_license::canonical_id(&license) == Some(&*license) {
|
if spdx_license::canonical_id(&license) == Some(&*license) {
|
||||||
@@ -45,6 +46,87 @@ fn license_choice(license: &str) -> serde_json::Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The licence a person confirmed, as CycloneDX writes a concluded licence:
|
||||||
|
/// an SPDX id or expression, or a licence of its own by name with its text
|
||||||
|
/// and URL. CycloneDX takes either licences or one expression, never both,
|
||||||
|
/// so the declared licence is then kept as a property
|
||||||
|
/// ([`DECLARED_LICENSE_PROPERTY`]).
|
||||||
|
fn concluded_choice(c: &LicenseConclusion) -> serde_json::Value {
|
||||||
|
if c.is_custom() {
|
||||||
|
let mut license = serde_json::json!({
|
||||||
|
"name": c.display(),
|
||||||
|
"acknowledgement": "concluded",
|
||||||
|
});
|
||||||
|
if let Some(text) = &c.license_text {
|
||||||
|
license["text"] = serde_json::json!({ "contentType": "text/plain", "content": text });
|
||||||
|
}
|
||||||
|
if let Some(url) = &c.license_url {
|
||||||
|
license["url"] = serde_json::Value::String(url.clone());
|
||||||
|
}
|
||||||
|
serde_json::json!([{ "license": license }])
|
||||||
|
} else if spdx_license::canonical_id(&c.license) == Some(c.license.as_str()) {
|
||||||
|
serde_json::json!([{ "license": { "id": c.license, "acknowledgement": "concluded" } }])
|
||||||
|
} else {
|
||||||
|
serde_json::json!([{ "expression": c.license, "acknowledgement": "concluded" }])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The property holding the licence the scan detected, where a person
|
||||||
|
/// confirmed another one.
|
||||||
|
const DECLARED_LICENSE_PROPERTY: &str = "pruefwerk:license:declared";
|
||||||
|
|
||||||
|
/// The properties of a confirmed licence: its category, where the component
|
||||||
|
/// is used, a bought licence's contract and end, where it was found, and who
|
||||||
|
/// confirmed it when.
|
||||||
|
fn conclusion_properties(entry: &SbomEntry, c: &LicenseConclusion) -> Vec<serde_json::Value> {
|
||||||
|
let mut props = vec![serde_json::json!({
|
||||||
|
"name": "pruefwerk:license:category",
|
||||||
|
"value": c.category.as_str(),
|
||||||
|
})];
|
||||||
|
let mut push = |name: &str, value: Option<String>| {
|
||||||
|
if let Some(value) = value.filter(|v| !v.trim().is_empty()) {
|
||||||
|
props.push(serde_json::json!({ "name": name, "value": value }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
push(
|
||||||
|
DECLARED_LICENSE_PROPERTY,
|
||||||
|
entry.license.clone().filter(|l| l.trim() != c.license),
|
||||||
|
);
|
||||||
|
push(
|
||||||
|
"pruefwerk:license:usage",
|
||||||
|
c.usage.map(|u| match u {
|
||||||
|
crate::models::LicenseUsage::Shipped => "shipped".to_string(),
|
||||||
|
crate::models::LicenseUsage::BuildOnly => "build_only".to_string(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
push("pruefwerk:license:contract", c.contract_ref.clone());
|
||||||
|
push(
|
||||||
|
"pruefwerk:license:valid_until",
|
||||||
|
c.valid_until.map(|d| d.to_string()),
|
||||||
|
);
|
||||||
|
push("pruefwerk:license:evidence", c.evidence.clone());
|
||||||
|
push(
|
||||||
|
"pruefwerk:license:concluded",
|
||||||
|
Some(format!(
|
||||||
|
"{} {}",
|
||||||
|
c.by_name.as_deref().unwrap_or(&c.by),
|
||||||
|
c.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
if let Some(review) = &c.review {
|
||||||
|
push(
|
||||||
|
"pruefwerk:license:review",
|
||||||
|
Some(format!(
|
||||||
|
"{} by {} {}",
|
||||||
|
review.decision.as_str(),
|
||||||
|
review.by_name.as_deref().unwrap_or(&review.by),
|
||||||
|
review.at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
props
|
||||||
|
}
|
||||||
|
|
||||||
/// The file a registry package is distributed as (`log4j-core-2.14.1.jar`),
|
/// The file a registry package is distributed as (`log4j-core-2.14.1.jar`),
|
||||||
/// where its purl determines it. `None` for a package type whose file the
|
/// where its purl determines it. `None` for a package type whose file the
|
||||||
/// purl does not name (PyPI wheel or sdist, Go modules) and without a version.
|
/// purl does not name (PyPI wheel or sdist, Go modules) and without a version.
|
||||||
@@ -182,8 +264,23 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
|||||||
None => comp["properties"] = serde_json::Value::Array(provenance),
|
None => comp["properties"] = serde_json::Value::Array(provenance),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
match &e.concluded {
|
||||||
comp["licenses"] = license_choice(license);
|
Some(c) => {
|
||||||
|
comp["licenses"] = concluded_choice(c);
|
||||||
|
if !c.copyright.is_empty() {
|
||||||
|
comp["copyright"] = serde_json::Value::String(c.copyright.join("\n"));
|
||||||
|
}
|
||||||
|
let props = conclusion_properties(e, c);
|
||||||
|
match comp["properties"].as_array_mut() {
|
||||||
|
Some(properties) => properties.extend(props),
|
||||||
|
None => comp["properties"] = serde_json::Value::Array(props),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
||||||
|
comp["licenses"] = license_choice(license);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if let Some(url) = &e.manufacturer_url {
|
if let Some(url) = &e.manufacturer_url {
|
||||||
comp["manufacturer"] = serde_json::json!({ "url": [url] });
|
comp["manufacturer"] = serde_json::json!({ "url": [url] });
|
||||||
@@ -368,14 +465,34 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|||||||
|
|
||||||
/// An SPDX 2.3 document for `entries`, named after `subject`.
|
/// An SPDX 2.3 document for `entries`, named after `subject`.
|
||||||
pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||||
|
// A `LicenseRef-` a package concludes must be defined in the document.
|
||||||
|
let mut extracted: Vec<serde_json::Value> = Vec::new();
|
||||||
|
let mut defined = std::collections::HashSet::new();
|
||||||
|
for c in entries.iter().filter_map(|e| e.concluded.as_ref()) {
|
||||||
|
if c.is_custom() && defined.insert(c.license.clone()) {
|
||||||
|
let mut info = serde_json::json!({
|
||||||
|
"licenseId": c.license,
|
||||||
|
"name": c.display(),
|
||||||
|
// SPDX requires a text; without one, where to find it.
|
||||||
|
"extractedText": c.license_text.clone().unwrap_or_else(|| {
|
||||||
|
c.license_url.clone().unwrap_or_else(|| "NOASSERTION".to_string())
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if let Some(url) = &c.license_url {
|
||||||
|
info["seeAlsos"] = serde_json::json!([url]);
|
||||||
|
}
|
||||||
|
extracted.push(info);
|
||||||
|
}
|
||||||
|
}
|
||||||
let packages: Vec<serde_json::Value> = entries
|
let packages: Vec<serde_json::Value> = entries
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, e)| {
|
.map(|(i, e)| {
|
||||||
// The license is what the supplier declares; nothing is
|
// The declared license is what the supplier declares; a license
|
||||||
// concluded without a license review of our own. SPDX takes only
|
// is concluded only where a person of the workspace confirmed one
|
||||||
// an expression of listed ids; another license is NOASSERTION,
|
// (`concluded`). SPDX takes only an expression of listed ids; a
|
||||||
// its text kept as a comment.
|
// declared license that is none is NOASSERTION, its text kept as
|
||||||
|
// a comment.
|
||||||
let raw = e
|
let raw = e
|
||||||
.license
|
.license
|
||||||
.as_deref()
|
.as_deref()
|
||||||
@@ -389,7 +506,8 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|||||||
"name": e.name,
|
"name": e.name,
|
||||||
"versionInfo": e.version,
|
"versionInfo": e.version,
|
||||||
"downloadLocation": "NOASSERTION",
|
"downloadLocation": "NOASSERTION",
|
||||||
"licenseConcluded": "NOASSERTION",
|
// Concluded only where a person confirmed the licence.
|
||||||
|
"licenseConcluded": e.concluded.as_ref().map_or("NOASSERTION", |c| c.license.as_str()),
|
||||||
"licenseDeclared": license.as_deref().unwrap_or("NOASSERTION"),
|
"licenseDeclared": license.as_deref().unwrap_or("NOASSERTION"),
|
||||||
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
|
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
|
||||||
"referenceCategory": "PACKAGE-MANAGER",
|
"referenceCategory": "PACKAGE-MANAGER",
|
||||||
@@ -400,6 +518,31 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|||||||
if let (Some(raw), None) = (raw, &license) {
|
if let (Some(raw), None) = (raw, &license) {
|
||||||
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
|
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
|
||||||
}
|
}
|
||||||
|
if let Some(c) = &e.concluded {
|
||||||
|
if !c.copyright.is_empty() {
|
||||||
|
package["copyrightText"] = serde_json::Value::String(c.copyright.join("\n"));
|
||||||
|
}
|
||||||
|
let by = c.by_name.as_deref().unwrap_or(&c.by);
|
||||||
|
let 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}"),
|
||||||
|
None => note,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) {
|
if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) {
|
||||||
refs.push(serde_json::json!({
|
refs.push(serde_json::json!({
|
||||||
"referenceCategory": "SECURITY",
|
"referenceCategory": "SECURITY",
|
||||||
@@ -414,14 +557,18 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
serde_json::json!({
|
let mut doc = serde_json::json!({
|
||||||
"spdxVersion": "SPDX-2.3",
|
"spdxVersion": "SPDX-2.3",
|
||||||
"dataLicense": "CC0-1.0",
|
"dataLicense": "CC0-1.0",
|
||||||
"SPDXID": "SPDXRef-DOCUMENT",
|
"SPDXID": "SPDXRef-DOCUMENT",
|
||||||
"name": format!("sbom-{subject}"),
|
"name": format!("sbom-{subject}"),
|
||||||
"documentNamespace": format!("https://compliance-scanner/sbom/{subject}"),
|
"documentNamespace": format!("https://compliance-scanner/sbom/{subject}"),
|
||||||
"packages": packages,
|
"packages": packages,
|
||||||
})
|
});
|
||||||
|
if !extracted.is_empty() {
|
||||||
|
doc["hasExtractedLicensingInfos"] = serde_json::Value::Array(extracted);
|
||||||
|
}
|
||||||
|
doc
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -558,4 +705,112 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE);
|
assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn concluded(license: &str, name: Option<&str>) -> LicenseConclusion {
|
||||||
|
use crate::models::license::{conclusion_id, package_key};
|
||||||
|
let key = package_key("pump-sdk", "nuget", None);
|
||||||
|
LicenseConclusion {
|
||||||
|
id: conclusion_id(&key, None),
|
||||||
|
package_key: key,
|
||||||
|
name: "pump-sdk".into(),
|
||||||
|
package_manager: "nuget".into(),
|
||||||
|
version: None,
|
||||||
|
license: license.into(),
|
||||||
|
license_name: name.map(String::from),
|
||||||
|
category: crate::models::LicenseCategory::Proprietary,
|
||||||
|
copyright: vec!["© 2019 Example GmbH".into()],
|
||||||
|
license_text: Some("All rights reserved.".into()),
|
||||||
|
license_url: None,
|
||||||
|
evidence: Some("contract 4711".into()),
|
||||||
|
contract_ref: Some("4711".into()),
|
||||||
|
valid_until: chrono::NaiveDate::from_ymd_opt(2027, 12, 31),
|
||||||
|
usage: Some(crate::models::LicenseUsage::Shipped),
|
||||||
|
note: None,
|
||||||
|
by: "u1".into(),
|
||||||
|
by_name: Some("Erika Muster".into()),
|
||||||
|
support: false,
|
||||||
|
at: chrono::Utc::now(),
|
||||||
|
review: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_confirmed_custom_licence_is_concluded_and_defined() {
|
||||||
|
let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "3.1".into(), "nuget".into());
|
||||||
|
e.license = Some("LicenseRef-file".into());
|
||||||
|
e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA")));
|
||||||
|
let cdx = cyclonedx(std::slice::from_ref(&e), "t");
|
||||||
|
let comp = &cdx["components"][0];
|
||||||
|
assert_eq!(comp["licenses"][0]["license"]["name"], "Pump EULA");
|
||||||
|
assert_eq!(
|
||||||
|
comp["licenses"][0]["license"]["acknowledgement"],
|
||||||
|
"concluded"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
comp["licenses"][0]["license"]["text"]["content"],
|
||||||
|
"All rights reserved."
|
||||||
|
);
|
||||||
|
assert_eq!(comp["copyright"], "© 2019 Example GmbH");
|
||||||
|
let props = comp["properties"].as_array().unwrap();
|
||||||
|
let prop = |n: &str| {
|
||||||
|
props
|
||||||
|
.iter()
|
||||||
|
.find(|p| p["name"] == n)
|
||||||
|
.map(|p| p["value"].clone())
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
prop("pruefwerk:license:category"),
|
||||||
|
Some("proprietary".into())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prop(DECLARED_LICENSE_PROPERTY),
|
||||||
|
Some("LicenseRef-file".into())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prop("pruefwerk:license:valid_until"),
|
||||||
|
Some("2027-12-31".into())
|
||||||
|
);
|
||||||
|
assert_eq!(prop("pruefwerk:license:usage"), Some("shipped".into()));
|
||||||
|
|
||||||
|
let spdx = spdx(&[e], "t");
|
||||||
|
let package = &spdx["packages"][0];
|
||||||
|
assert_eq!(package["licenseConcluded"], "LicenseRef-Pump-EULA");
|
||||||
|
assert_eq!(package["copyrightText"], "© 2019 Example GmbH");
|
||||||
|
assert!(package["licenseComments"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("Concluded by Erika Muster"));
|
||||||
|
let info = &spdx["hasExtractedLicensingInfos"][0];
|
||||||
|
assert_eq!(info["licenseId"], "LicenseRef-Pump-EULA");
|
||||||
|
assert_eq!(info["extractedText"], "All rights reserved.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_confirmed_spdx_licence_replaces_the_declared_one() {
|
||||||
|
let mut one = SbomEntry::new("t".into(), "a".into(), "1".into(), "npm".into());
|
||||||
|
one.concluded = Some(concluded("MIT", None));
|
||||||
|
let mut two = SbomEntry::new("t".into(), "b".into(), "1".into(), "npm".into());
|
||||||
|
two.license = Some("MIT".into());
|
||||||
|
two.concluded = Some(concluded("MIT OR Apache-2.0", None));
|
||||||
|
let cdx = cyclonedx(&[one.clone(), two.clone()], "t");
|
||||||
|
assert_eq!(cdx["components"][0]["licenses"][0]["license"]["id"], "MIT");
|
||||||
|
assert_eq!(
|
||||||
|
cdx["components"][0]["licenses"][0]["license"]["acknowledgement"],
|
||||||
|
"concluded"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
cdx["components"][1]["licenses"][0]["expression"],
|
||||||
|
"MIT OR Apache-2.0"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
cdx["components"][1]["licenses"].as_array().unwrap().len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
let spdx = spdx(&[one, two], "t");
|
||||||
|
assert_eq!(spdx["packages"][0]["licenseConcluded"], "MIT");
|
||||||
|
assert_eq!(spdx["packages"][0]["licenseDeclared"], "NOASSERTION");
|
||||||
|
assert_eq!(spdx["packages"][1]["licenseConcluded"], "MIT OR Apache-2.0");
|
||||||
|
assert_eq!(spdx["packages"][1]["licenseDeclared"], "MIT");
|
||||||
|
assert!(spdx.get("hasExtractedLicensingInfos").is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -115,6 +115,136 @@ pub fn is_copyleft(license: &str) -> bool {
|
|||||||
by_term || COPYLEFT.iter().any(|c| upper.contains(c))
|
by_term || COPYLEFT.iter().any(|c| upper.contains(c))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Families (SPDX ids without `-only`/`-or-later`/`+`, lowercase prefixes)
|
||||||
|
/// and their category. A prefix covers its versions (`gpl-` is GPL-1.0 to
|
||||||
|
/// GPL-3.0); `lgpl-` and `agpl-` are listed before `gpl-` is tried.
|
||||||
|
const FAMILIES: &[(&str, crate::models::LicenseCategory)] = {
|
||||||
|
use crate::models::LicenseCategory::{
|
||||||
|
NetworkCopyleft, Permissive, PublicDomain, StrongCopyleft, WeakCopyleft,
|
||||||
|
};
|
||||||
|
&[
|
||||||
|
("agpl-", NetworkCopyleft),
|
||||||
|
("sspl-", NetworkCopyleft),
|
||||||
|
("lgpl-", WeakCopyleft),
|
||||||
|
("mpl-", WeakCopyleft),
|
||||||
|
("epl-", WeakCopyleft),
|
||||||
|
("cddl-", WeakCopyleft),
|
||||||
|
("cpl-", WeakCopyleft),
|
||||||
|
("ms-rl", WeakCopyleft),
|
||||||
|
("ofl-", WeakCopyleft),
|
||||||
|
("gpl-", StrongCopyleft),
|
||||||
|
("eupl-", StrongCopyleft),
|
||||||
|
("osl-", StrongCopyleft),
|
||||||
|
("cc-by-sa-", StrongCopyleft),
|
||||||
|
("cc0-", PublicDomain),
|
||||||
|
("unlicense", PublicDomain),
|
||||||
|
("mit", Permissive),
|
||||||
|
("apache-", Permissive),
|
||||||
|
("bsd-", Permissive),
|
||||||
|
("0bsd", Permissive),
|
||||||
|
("isc", Permissive),
|
||||||
|
("zlib", Permissive),
|
||||||
|
("bsl-1.0", Permissive),
|
||||||
|
("psf-", Permissive),
|
||||||
|
("python-", Permissive),
|
||||||
|
("upl-", Permissive),
|
||||||
|
("wtfpl", Permissive),
|
||||||
|
("artistic-2.0", Permissive),
|
||||||
|
("ms-pl", Permissive),
|
||||||
|
("x11", Permissive),
|
||||||
|
("unicode-", Permissive),
|
||||||
|
("curl", Permissive),
|
||||||
|
("ncsa", Permissive),
|
||||||
|
("postgresql", Permissive),
|
||||||
|
("openssl", Permissive),
|
||||||
|
("ssleay", Permissive),
|
||||||
|
("blueoak-", Permissive),
|
||||||
|
("cc-by-4.0", Permissive),
|
||||||
|
("cc-by-3.0", Permissive),
|
||||||
|
("icu", Permissive),
|
||||||
|
("libpng", Permissive),
|
||||||
|
("ijg", Permissive),
|
||||||
|
("ftl", Permissive),
|
||||||
|
("bzip2-", Permissive),
|
||||||
|
("hpnd", Permissive),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The category of one SPDX licence id; `Unclear` for an id not listed in
|
||||||
|
/// [`FAMILIES`] and for a `LicenseRef-`.
|
||||||
|
fn term_category(id: &str) -> crate::models::LicenseCategory {
|
||||||
|
let base = id.strip_suffix('+').unwrap_or(id);
|
||||||
|
let base = base
|
||||||
|
.strip_suffix("-only")
|
||||||
|
.or_else(|| base.strip_suffix("-or-later"))
|
||||||
|
.unwrap_or(base)
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
FAMILIES
|
||||||
|
.iter()
|
||||||
|
.find(|(prefix, _)| base == prefix.trim_end_matches('-') || base.starts_with(prefix))
|
||||||
|
.map_or(crate::models::LicenseCategory::Unclear, |(_, c)| *c)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The category of a licence (an SPDX id or expression, a name or URL that
|
||||||
|
/// [`normalise`] knows). The terms of an `OR` leave the choice, so the least
|
||||||
|
/// restrictive counts; the terms of an `AND` all apply, so the most
|
||||||
|
/// restrictive counts. An exception after `WITH` does not change it. A
|
||||||
|
/// licence this module does not know is `Unclear`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use compliance_core::models::LicenseCategory;
|
||||||
|
/// use compliance_core::spdx_license::category;
|
||||||
|
///
|
||||||
|
/// assert_eq!(category("Apache-2.0"), LicenseCategory::Permissive);
|
||||||
|
/// assert_eq!(category("LGPL-2.1-or-later"), LicenseCategory::WeakCopyleft);
|
||||||
|
/// assert_eq!(category("MIT OR GPL-3.0-only"), LicenseCategory::Permissive);
|
||||||
|
/// assert_eq!(category("Custom Pump License"), LicenseCategory::Unclear);
|
||||||
|
/// ```
|
||||||
|
pub fn category(license: &str) -> crate::models::LicenseCategory {
|
||||||
|
use crate::models::LicenseCategory;
|
||||||
|
let spdx = normalise(license);
|
||||||
|
let tokens: Vec<&str> = spdx
|
||||||
|
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
.collect();
|
||||||
|
// Only an expression of SPDX ids (and `LicenseRef-`s) is read by its
|
||||||
|
// terms: the words of a free-text name (`Mitsubishi EULA`) are no ids.
|
||||||
|
let readable = tokens.iter().all(|t| {
|
||||||
|
OPERATORS.contains(t)
|
||||||
|
|| t.starts_with("LicenseRef-")
|
||||||
|
|| canonical_id(t.strip_suffix('+').unwrap_or(t)).is_some()
|
||||||
|
});
|
||||||
|
if !readable {
|
||||||
|
return LicenseCategory::Unclear;
|
||||||
|
}
|
||||||
|
let mut terms = Vec::new();
|
||||||
|
let mut after_with = false;
|
||||||
|
for token in &tokens {
|
||||||
|
match *token {
|
||||||
|
"WITH" => after_with = true,
|
||||||
|
"AND" | "OR" => after_with = false,
|
||||||
|
id if !after_with => terms.push(term_category(id)),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let by_restriction = |c: &LicenseCategory| c.restriction();
|
||||||
|
let chosen = if tokens.contains(&"AND") {
|
||||||
|
terms.iter().copied().max_by_key(by_restriction)
|
||||||
|
} else {
|
||||||
|
// An `OR`: a term that is not known does not stop a known one from
|
||||||
|
// being chosen.
|
||||||
|
terms
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|c| *c != LicenseCategory::Unclear)
|
||||||
|
.min_by_key(by_restriction)
|
||||||
|
.or(terms.first().copied())
|
||||||
|
};
|
||||||
|
chosen.unwrap_or(LicenseCategory::Unclear)
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether `text` joins terms with an SPDX operator (`MIT OR Apache-2.0`),
|
/// Whether `text` joins terms with an SPDX operator (`MIT OR Apache-2.0`),
|
||||||
/// as an expression does.
|
/// as an expression does.
|
||||||
pub fn has_operator(text: &str) -> bool {
|
pub fn has_operator(text: &str) -> bool {
|
||||||
@@ -520,6 +650,39 @@ mod tests {
|
|||||||
assert_eq!(spdx_of_name("Permit to Limit License"), None);
|
assert_eq!(spdx_of_name("Permit to Limit License"), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn licences_fall_into_categories() {
|
||||||
|
use crate::models::LicenseCategory::*;
|
||||||
|
for (license, expected) in [
|
||||||
|
("MIT", Permissive),
|
||||||
|
("Apache License, Version 2.0", Permissive),
|
||||||
|
("BSD-3-Clause", Permissive),
|
||||||
|
("0BSD", Permissive),
|
||||||
|
("LGPL-2.1-only", WeakCopyleft),
|
||||||
|
("GNU Lesser General Public License v2.1", WeakCopyleft),
|
||||||
|
("MPL-2.0", WeakCopyleft),
|
||||||
|
("EPL-2.0", WeakCopyleft),
|
||||||
|
("GPL-2.0-only", StrongCopyleft),
|
||||||
|
("GPL-2.0+", StrongCopyleft),
|
||||||
|
("GPL-2.0-only WITH Classpath-exception-2.0", StrongCopyleft),
|
||||||
|
("AGPL-3.0-or-later", NetworkCopyleft),
|
||||||
|
("CC0-1.0", PublicDomain),
|
||||||
|
("Unlicense", PublicDomain),
|
||||||
|
("MIT OR GPL-3.0-only", Permissive),
|
||||||
|
("(MIT OR Apache-2.0)", Permissive),
|
||||||
|
("MIT AND GPL-2.0-only", StrongCopyleft),
|
||||||
|
("LicenseRef-Pump OR MIT", Permissive),
|
||||||
|
("LicenseRef-Pump", Unclear),
|
||||||
|
("MIT AND LicenseRef-Pump", Unclear),
|
||||||
|
("Custom Pump License", Unclear),
|
||||||
|
("Mitsubishi EULA", Unclear),
|
||||||
|
("SSPL-1.0", NetworkCopyleft),
|
||||||
|
("", Unclear),
|
||||||
|
] {
|
||||||
|
assert_eq!(category(license), expected, "{license}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn spdx_expressions_are_recognised() {
|
fn spdx_expressions_are_recognised() {
|
||||||
assert!(is_spdx_expression("MIT"));
|
assert!(is_spdx_expression("MIT"));
|
||||||
|
|||||||
@@ -196,6 +196,40 @@ impl StaffAccess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A portal-issued API key acting in its tenant (tenant-registry ADR 0001).
|
||||||
|
/// Everything here comes from the registry's verify answer, never from the
|
||||||
|
/// request, except `on_behalf_of`, which is informational only.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ApiKeyAccess {
|
||||||
|
/// The registry's id of the key; the actor is `apikey:<key_id>`.
|
||||||
|
pub key_id: String,
|
||||||
|
/// `personal` or `service`, as the registry labels it.
|
||||||
|
pub kind: String,
|
||||||
|
/// Who the key was issued to, if the registry says.
|
||||||
|
pub holder: Option<String>,
|
||||||
|
/// What the key may do. A legacy key's read scopes are filled in by the
|
||||||
|
/// agent; nothing else widens this list.
|
||||||
|
pub scopes: Vec<String>,
|
||||||
|
/// Issued before scopes existed.
|
||||||
|
pub legacy: bool,
|
||||||
|
/// The `X-BP-Actor` header: who a caller says it acts for. Logged and
|
||||||
|
/// audited, never used to decide anything.
|
||||||
|
pub on_behalf_of: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiKeyAccess {
|
||||||
|
/// Whether the key carries `scope`. A `<x>.write` scope also grants
|
||||||
|
/// `<x>.read`; nothing else implies anything.
|
||||||
|
pub fn has_scope(&self, scope: &str) -> bool {
|
||||||
|
let write = scope
|
||||||
|
.strip_suffix(".read")
|
||||||
|
.map(|base| format!("{base}.write"));
|
||||||
|
self.scopes
|
||||||
|
.iter()
|
||||||
|
.any(|s| s == scope || write.as_deref() == Some(s.as_str()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Everything we know about the requesting tenant at the moment a request
|
/// Everything we know about the requesting tenant at the moment a request
|
||||||
/// lands. Cheap to clone (every field is owned + small).
|
/// lands. Cheap to clone (every field is owned + small).
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -225,6 +259,12 @@ pub struct TenantContext {
|
|||||||
/// its own users. `user_id` is then the staff member's id.
|
/// its own users. `user_id` is then the staff member's id.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub staff: Option<StaffAccess>,
|
pub staff: Option<StaffAccess>,
|
||||||
|
/// Set when an API key, not a person, made the request. `user_id` is
|
||||||
|
/// then `apikey:<key_id>` and `org_roles` is empty: a key is judged by
|
||||||
|
/// its scopes, never by a role.
|
||||||
|
/// Boxed: absent on almost every request, so it costs a pointer there.
|
||||||
|
#[serde(default)]
|
||||||
|
pub api_key: Option<Box<ApiKeyAccess>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TenantContext {
|
impl TenantContext {
|
||||||
@@ -242,6 +282,11 @@ impl TenantContext {
|
|||||||
/// own rules (read-only until the registry confirms the tenant, every
|
/// own rules (read-only until the registry confirms the tenant, every
|
||||||
/// change audited), so it is not judged by org roles.
|
/// change audited), so it is not judged by org roles.
|
||||||
pub fn product_access(&self) -> ProductAccess {
|
pub fn product_access(&self) -> ProductAccess {
|
||||||
|
// Scopes, not roles, decide for a key (`role_gate`); anything that
|
||||||
|
// asks for a role refuses it.
|
||||||
|
if self.api_key.is_some() {
|
||||||
|
return ProductAccess::None;
|
||||||
|
}
|
||||||
if self.staff.is_some() {
|
if self.staff.is_some() {
|
||||||
return ProductAccess::Full;
|
return ProductAccess::Full;
|
||||||
}
|
}
|
||||||
@@ -313,6 +358,27 @@ mod tests {
|
|||||||
assert_eq!(ProductAccess::default(), ProductAccess::None);
|
assert_eq!(ProductAccess::default(), ProductAccess::None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_scope_implies_its_read_and_nothing_else() {
|
||||||
|
let key = ApiKeyAccess {
|
||||||
|
key_id: "k".into(),
|
||||||
|
kind: "service".into(),
|
||||||
|
holder: None,
|
||||||
|
scopes: vec![
|
||||||
|
"pruefwerk:findings.write".into(),
|
||||||
|
"pruefwerk:scans.run".into(),
|
||||||
|
],
|
||||||
|
legacy: false,
|
||||||
|
on_behalf_of: None,
|
||||||
|
};
|
||||||
|
assert!(key.has_scope("pruefwerk:findings.write"));
|
||||||
|
assert!(key.has_scope("pruefwerk:findings.read"));
|
||||||
|
assert!(key.has_scope("pruefwerk:scans.run"));
|
||||||
|
assert!(!key.has_scope("pruefwerk:scans.read"));
|
||||||
|
assert!(!key.has_scope("pruefwerk:sbom.read"));
|
||||||
|
assert!(!key.has_scope("pruefwerk:findings"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn support_is_not_judged_by_org_roles() {
|
fn support_is_not_judged_by_org_roles() {
|
||||||
let ctx = TenantContext {
|
let ctx = TenantContext {
|
||||||
@@ -328,6 +394,7 @@ mod tests {
|
|||||||
user_id: "s".into(),
|
user_id: "s".into(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
}),
|
}),
|
||||||
|
api_key: None,
|
||||||
};
|
};
|
||||||
assert_eq!(ctx.product_access(), ProductAccess::Full);
|
assert_eq!(ctx.product_access(), ProductAccess::Full);
|
||||||
let customer = TenantContext { staff: None, ..ctx };
|
let customer = TenantContext { staff: None, ..ctx };
|
||||||
@@ -346,6 +413,7 @@ mod tests {
|
|||||||
user_id: "u".into(),
|
user_id: "u".into(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
};
|
};
|
||||||
assert!(ctx.has_any_role(&[OrgRole::ItAdmin]));
|
assert!(ctx.has_any_role(&[OrgRole::ItAdmin]));
|
||||||
assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin]));
|
assert!(ctx.has_any_role(&[OrgRole::Cxo, OrgRole::ItAdmin]));
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ mod tests {
|
|||||||
user_id: "u-1".to_string(),
|
user_id: "u-1".to_string(),
|
||||||
user_name: None,
|
user_name: None,
|
||||||
staff: None,
|
staff: None,
|
||||||
|
api_key: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5768,3 +5768,278 @@ input[type="file"] {
|
|||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Licence review: confirmed licences (proprietary, unclear), the editor ── */
|
||||||
|
.license-proprietary {
|
||||||
|
background: var(--info-bg, var(--bg-elevated));
|
||||||
|
color: var(--info, var(--text-primary));
|
||||||
|
border: 1px solid var(--border-bright);
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-unclear {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border: 1px dashed var(--border-bright);
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-bar.license-weak-copyleft {
|
||||||
|
background: var(--warning);
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-bar.license-proprietary {
|
||||||
|
background: var(--info, var(--text-secondary));
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-bar.license-unclear {
|
||||||
|
background: var(--text-tertiary);
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-confirmed {
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-edit-btn {
|
||||||
|
padding: 1px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-select-col {
|
||||||
|
width: 32px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-selection-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
border: 1px solid var(--border-bright);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-open-card {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-confirmed-count {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-tertiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-dialog.license-editor {
|
||||||
|
max-width: 620px;
|
||||||
|
max-height: calc(100vh - 48px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-kind {
|
||||||
|
display: flex;
|
||||||
|
gap: 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-form label {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-form label.license-check {
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-derived {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-disclaimer {
|
||||||
|
font-size: 12px !important;
|
||||||
|
color: var(--text-tertiary) !important;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.license-withdraw {
|
||||||
|
margin-right: auto;
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.license-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
//! The dialog to confirm the licence of one or more components: an SPDX
|
||||||
|
//! licence (its category follows from it) or one of the workspace's own,
|
||||||
|
//! with copyright, licence text, where it was found, a bought licence's
|
||||||
|
//! contract and end, and where the component is used. Saved for the listed
|
||||||
|
//! versions, or for every version of the packages.
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
use compliance_core::models::{LicenseCategory, LicenseConclusion, LicenseUsage};
|
||||||
|
use compliance_core::spdx_license;
|
||||||
|
|
||||||
|
use crate::components::toast::{ToastType, Toasts};
|
||||||
|
use crate::i18n::texts::license_edit as tx;
|
||||||
|
use crate::i18n::{use_lang, Lang};
|
||||||
|
use crate::infrastructure::sbom::{
|
||||||
|
save_license_conclusion, withdraw_license_conclusion, LicenseDraft, LicenseTarget,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// SPDX licences offered while typing; any other SPDX id or expression is
|
||||||
|
/// accepted too.
|
||||||
|
const COMMON_SPDX: [&str; 24] = [
|
||||||
|
"MIT",
|
||||||
|
"Apache-2.0",
|
||||||
|
"BSD-3-Clause",
|
||||||
|
"BSD-2-Clause",
|
||||||
|
"ISC",
|
||||||
|
"Zlib",
|
||||||
|
"BSL-1.0",
|
||||||
|
"0BSD",
|
||||||
|
"Unlicense",
|
||||||
|
"CC0-1.0",
|
||||||
|
"MPL-2.0",
|
||||||
|
"EPL-2.0",
|
||||||
|
"LGPL-2.1-only",
|
||||||
|
"LGPL-2.1-or-later",
|
||||||
|
"LGPL-3.0-only",
|
||||||
|
"LGPL-3.0-or-later",
|
||||||
|
"GPL-2.0-only",
|
||||||
|
"GPL-2.0-or-later",
|
||||||
|
"GPL-3.0-only",
|
||||||
|
"GPL-3.0-or-later",
|
||||||
|
"AGPL-3.0-only",
|
||||||
|
"EUPL-1.2",
|
||||||
|
"MS-PL",
|
||||||
|
"Python-2.0",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Trimmed, `None` when empty.
|
||||||
|
fn filled(value: String) -> Option<String> {
|
||||||
|
let value = value.trim().to_string();
|
||||||
|
(!value.is_empty()).then_some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The badge class of a category, as the SBOM list colours licences.
|
||||||
|
pub fn category_class(category: LicenseCategory) -> &'static str {
|
||||||
|
match category {
|
||||||
|
LicenseCategory::PublicDomain | LicenseCategory::Permissive | LicenseCategory::OwnCode => {
|
||||||
|
"license-permissive"
|
||||||
|
}
|
||||||
|
LicenseCategory::WeakCopyleft => "license-weak-copyleft",
|
||||||
|
LicenseCategory::StrongCopyleft | LicenseCategory::NetworkCopyleft => "license-copyleft",
|
||||||
|
LicenseCategory::Proprietary => "license-proprietary",
|
||||||
|
LicenseCategory::Unclear => "license-unclear",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Bestätigt von Erika Muster am 2026-10-15".
|
||||||
|
pub fn confirmed_title(c: &LicenseConclusion, lang: Lang) -> String {
|
||||||
|
tx::CONFIRMED_BY
|
||||||
|
.get(lang)
|
||||||
|
.replace("{by}", c.by_name.as_deref().unwrap_or(&c.by))
|
||||||
|
.replace("{at}", &c.at.format("%Y-%m-%d").to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn LicenseEditor(
|
||||||
|
/// The components to confirm a licence for.
|
||||||
|
components: Vec<LicenseTarget>,
|
||||||
|
/// The confirmation to start from (editing one component), if any.
|
||||||
|
existing: Option<LicenseConclusion>,
|
||||||
|
/// Called with `true` when something was saved or withdrawn.
|
||||||
|
on_close: EventHandler<bool>,
|
||||||
|
) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let mut toasts = use_context::<Toasts>();
|
||||||
|
let start = existing.clone();
|
||||||
|
let mut custom = use_signal(|| start.as_ref().is_some_and(LicenseConclusion::is_custom));
|
||||||
|
let mut spdx = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.filter(|c| !c.is_custom())
|
||||||
|
.map(|c| c.license.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut name = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.license_name.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut category = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.map_or(LicenseCategory::Proprietary, |c| c.category)
|
||||||
|
});
|
||||||
|
let mut copyright = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.map(|c| c.copyright.join("\n"))
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut text = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.license_text.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut url = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.license_url.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut evidence = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.evidence.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut contract = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.contract_ref.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut valid_until = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.valid_until)
|
||||||
|
.map(|d| d.to_string())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut usage = use_signal(|| start.as_ref().and_then(|c| c.usage));
|
||||||
|
let mut note = use_signal(|| {
|
||||||
|
start
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|c| c.note.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
let mut all_versions = use_signal(|| start.as_ref().is_some_and(|c| c.version.is_none()));
|
||||||
|
let mut busy = use_signal(|| false);
|
||||||
|
|
||||||
|
// The SPDX licence as typed, read the way the agent will read it.
|
||||||
|
let spdx_now = spdx();
|
||||||
|
let normalised = spdx_license::normalise(&spdx_now).into_owned();
|
||||||
|
let spdx_valid = spdx_license::is_spdx_expression(&normalised);
|
||||||
|
let derived = spdx_license::category(&normalised);
|
||||||
|
let can_save = !busy()
|
||||||
|
&& if custom() {
|
||||||
|
!name().trim().is_empty()
|
||||||
|
} else {
|
||||||
|
spdx_valid
|
||||||
|
};
|
||||||
|
let heading = if components.len() == 1 {
|
||||||
|
format!(
|
||||||
|
"{} · {} {}",
|
||||||
|
tx::TITLE.get(lang),
|
||||||
|
components[0].name,
|
||||||
|
components[0].version
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
tx::TITLE_MANY
|
||||||
|
.get(lang)
|
||||||
|
.replace("{n}", &components.len().to_string())
|
||||||
|
};
|
||||||
|
|
||||||
|
let targets = components.clone();
|
||||||
|
let save = move |_: Event<MouseData>| {
|
||||||
|
let draft = LicenseDraft {
|
||||||
|
components: targets.clone(),
|
||||||
|
all_versions: all_versions(),
|
||||||
|
license: (!custom()).then(|| spdx().trim().to_string()),
|
||||||
|
license_name: custom().then(|| name().trim().to_string()),
|
||||||
|
// For an SPDX licence the agent derives it; sent for one SPDX
|
||||||
|
// gives none for.
|
||||||
|
category: Some(category()),
|
||||||
|
copyright: copyright()
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.map(String::from)
|
||||||
|
.collect(),
|
||||||
|
license_text: filled(text()),
|
||||||
|
license_url: filled(url()),
|
||||||
|
evidence: filled(evidence()),
|
||||||
|
contract_ref: filled(contract()),
|
||||||
|
valid_until: filled(valid_until()),
|
||||||
|
usage: usage(),
|
||||||
|
note: filled(note()),
|
||||||
|
};
|
||||||
|
busy.set(true);
|
||||||
|
spawn(async move {
|
||||||
|
match save_license_conclusion(draft).await {
|
||||||
|
Ok(()) => {
|
||||||
|
toasts.push(ToastType::Success, tx::SAVED.get(lang).to_string());
|
||||||
|
on_close.call(true);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
toasts.push(
|
||||||
|
ToastType::Error,
|
||||||
|
format!("{}: {e}", tx::SAVE_FAILED.get(lang)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
busy.set(false);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
div { class: "modal-overlay",
|
||||||
|
onclick: move |_| if !busy() { on_close.call(false) },
|
||||||
|
div { class: "modal-dialog license-editor",
|
||||||
|
onclick: move |e| e.stop_propagation(),
|
||||||
|
h3 { "{heading}" }
|
||||||
|
|
||||||
|
div { class: "license-kind",
|
||||||
|
label {
|
||||||
|
input {
|
||||||
|
r#type: "radio",
|
||||||
|
name: "license-kind",
|
||||||
|
checked: !custom(),
|
||||||
|
onchange: move |_| custom.set(false),
|
||||||
|
}
|
||||||
|
" {tx::KIND_SPDX.get(lang)}"
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
input {
|
||||||
|
r#type: "radio",
|
||||||
|
name: "license-kind",
|
||||||
|
checked: custom(),
|
||||||
|
onchange: move |_| custom.set(true),
|
||||||
|
}
|
||||||
|
" {tx::KIND_CUSTOM.get(lang)}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
div { class: "form-fields license-form",
|
||||||
|
if custom() {
|
||||||
|
label { {tx::NAME_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
value: "{name}",
|
||||||
|
placeholder: tx::NAME_HINT.get(lang),
|
||||||
|
maxlength: "2000",
|
||||||
|
oninput: move |e| name.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::CATEGORY_LABEL.get(lang)}
|
||||||
|
select {
|
||||||
|
onchange: move |e| {
|
||||||
|
if let Some(c) = LicenseCategory::parse(&e.value()) {
|
||||||
|
category.set(c);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
for c in LicenseCategory::ALL {
|
||||||
|
option {
|
||||||
|
value: c.as_str(),
|
||||||
|
selected: category() == c,
|
||||||
|
{tx::category(c).get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
label { {tx::SPDX_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
value: "{spdx}",
|
||||||
|
list: "spdx-licenses",
|
||||||
|
placeholder: tx::SPDX_HINT.get(lang),
|
||||||
|
oninput: move |e| spdx.set(e.value()),
|
||||||
|
}
|
||||||
|
datalist { id: "spdx-licenses",
|
||||||
|
for id in COMMON_SPDX {
|
||||||
|
option { value: id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !spdx_now.trim().is_empty() && !spdx_valid {
|
||||||
|
p { class: "modal-warning", {tx::SPDX_INVALID.get(lang)} }
|
||||||
|
}
|
||||||
|
if spdx_valid {
|
||||||
|
if derived == LicenseCategory::Unclear {
|
||||||
|
label { {tx::CATEGORY_LABEL.get(lang)}
|
||||||
|
select {
|
||||||
|
onchange: move |e| {
|
||||||
|
if let Some(c) = LicenseCategory::parse(&e.value()) {
|
||||||
|
category.set(c);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
for c in LicenseCategory::ALL {
|
||||||
|
option {
|
||||||
|
value: c.as_str(),
|
||||||
|
selected: category() == c,
|
||||||
|
{tx::category(c).get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
p { class: "license-derived",
|
||||||
|
"{tx::CATEGORY_LABEL.get(lang)}: "
|
||||||
|
span { class: "sbom-license-badge {category_class(derived)}",
|
||||||
|
{tx::category(derived).get(lang)}
|
||||||
|
}
|
||||||
|
" · {tx::CATEGORY_AUTO.get(lang)}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
label { {tx::COPYRIGHT_LABEL.get(lang)}
|
||||||
|
textarea {
|
||||||
|
rows: "2",
|
||||||
|
value: "{copyright}",
|
||||||
|
placeholder: tx::COPYRIGHT_HINT.get(lang),
|
||||||
|
oninput: move |e| copyright.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if custom() {
|
||||||
|
label { {tx::TEXT_LABEL.get(lang)}
|
||||||
|
textarea {
|
||||||
|
rows: "4",
|
||||||
|
value: "{text}",
|
||||||
|
oninput: move |e| text.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::URL_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
r#type: "url",
|
||||||
|
value: "{url}",
|
||||||
|
placeholder: "https://",
|
||||||
|
oninput: move |e| url.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::EVIDENCE_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
value: "{evidence}",
|
||||||
|
placeholder: tx::EVIDENCE_HINT.get(lang),
|
||||||
|
maxlength: "2000",
|
||||||
|
oninput: move |e| evidence.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if custom() && matches!(category(), LicenseCategory::Proprietary) {
|
||||||
|
div { class: "license-row",
|
||||||
|
label { {tx::CONTRACT_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
value: "{contract}",
|
||||||
|
maxlength: "2000",
|
||||||
|
oninput: move |e| contract.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::VALID_UNTIL_LABEL.get(lang)}
|
||||||
|
input {
|
||||||
|
r#type: "date",
|
||||||
|
value: "{valid_until}",
|
||||||
|
oninput: move |e| valid_until.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::USAGE_LABEL.get(lang)}
|
||||||
|
select {
|
||||||
|
onchange: move |e| usage.set(match e.value().as_str() {
|
||||||
|
"shipped" => Some(LicenseUsage::Shipped),
|
||||||
|
"build_only" => Some(LicenseUsage::BuildOnly),
|
||||||
|
_ => None,
|
||||||
|
}),
|
||||||
|
option { value: "", selected: usage().is_none(), {tx::USAGE_UNSET.get(lang)} }
|
||||||
|
option { value: "shipped", selected: usage() == Some(LicenseUsage::Shipped), {tx::USAGE_SHIPPED.get(lang)} }
|
||||||
|
option { value: "build_only", selected: usage() == Some(LicenseUsage::BuildOnly), {tx::USAGE_BUILD.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { {tx::NOTE_LABEL.get(lang)}
|
||||||
|
textarea {
|
||||||
|
rows: "2",
|
||||||
|
value: "{note}",
|
||||||
|
maxlength: "2000",
|
||||||
|
oninput: move |e| note.set(e.value()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label { class: "license-check",
|
||||||
|
input {
|
||||||
|
r#type: "checkbox",
|
||||||
|
checked: all_versions(),
|
||||||
|
onchange: move |e| all_versions.set(e.checked()),
|
||||||
|
}
|
||||||
|
" {tx::ALL_VERSIONS.get(lang)}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
p { class: "license-disclaimer", {tx::DISCLAIMER.get(lang)} }
|
||||||
|
|
||||||
|
div { class: "modal-actions",
|
||||||
|
if let Some(c) = existing.clone() {
|
||||||
|
button {
|
||||||
|
class: "btn btn-ghost license-withdraw",
|
||||||
|
disabled: busy(),
|
||||||
|
onclick: move |_| {
|
||||||
|
let id = c.id.clone();
|
||||||
|
busy.set(true);
|
||||||
|
spawn(async move {
|
||||||
|
match withdraw_license_conclusion(id).await {
|
||||||
|
Ok(()) => {
|
||||||
|
toasts.push(ToastType::Success, tx::WITHDRAWN.get(lang).to_string());
|
||||||
|
on_close.call(true);
|
||||||
|
}
|
||||||
|
Err(e) => toasts.push(
|
||||||
|
ToastType::Error,
|
||||||
|
format!("{}: {e}", tx::SAVE_FAILED.get(lang)),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
busy.set(false);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{tx::WITHDRAW.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
class: "btn btn-secondary",
|
||||||
|
disabled: busy(),
|
||||||
|
onclick: move |_| on_close.call(false),
|
||||||
|
{tx::CANCEL.get(lang)}
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
class: "btn btn-primary",
|
||||||
|
disabled: !can_save,
|
||||||
|
onclick: save,
|
||||||
|
{tx::SAVE.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
//! 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, LicenseEditor};
|
||||||
|
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<String> = 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::<Toasts>();
|
||||||
|
// 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::<String>::new);
|
||||||
|
// The components a decision is being made for, and which decision.
|
||||||
|
let mut deciding = use_signal(|| Option::<(Vec<LicenseTarget>, ReviewDecision)>::None);
|
||||||
|
let mut policy_open = use_signal(|| false);
|
||||||
|
// The component whose licence is being confirmed before a review.
|
||||||
|
let mut confirming = use_signal(|| Option::<LicenseTarget>::None);
|
||||||
|
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 may_confirm = data.may_confirm;
|
||||||
|
let acts = may || may_confirm;
|
||||||
|
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<LicenseCheckItem> = data.items.clone();
|
||||||
|
let reviewable: Vec<LicenseCheckItem> = open
|
||||||
|
.iter()
|
||||||
|
.filter(|i| i.verdict.action == PolicyAction::Review && i.decidable)
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
let all_keys: Vec<String> = reviewable.iter().map(LicenseCheckItem::key).collect();
|
||||||
|
let picked: Vec<LicenseTarget> = 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 acts { 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 confirm_target = target.clone();
|
||||||
|
let decidable = item.decidable;
|
||||||
|
let in_targets = item.targets;
|
||||||
|
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 && decidable {
|
||||||
|
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}" }
|
||||||
|
}
|
||||||
|
if in_targets > 1 {
|
||||||
|
span { class: "license-check-version",
|
||||||
|
{format!(" · {}", tx::IN_TARGETS.get(lang).replace("{n}", &in_targets.to_string()))}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 acts {
|
||||||
|
td { class: "license-check-actions",
|
||||||
|
if !decidable && may_confirm {
|
||||||
|
button {
|
||||||
|
class: "btn btn-secondary btn-sm",
|
||||||
|
title: tx::CONFIRM_FIRST_HINT.get(lang),
|
||||||
|
onclick: move |_| confirming.set(Some(confirm_target.clone())),
|
||||||
|
{tx::CONFIRM_FIRST.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !decidable && !may_confirm {
|
||||||
|
span { class: "license-check-version", {tx::CONFIRM_FIRST_OTHERS.get(lang)} }
|
||||||
|
}
|
||||||
|
if may && decidable && 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 may && decidable && 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.filter(|_| may) {
|
||||||
|
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(component) = confirming() {
|
||||||
|
LicenseEditor {
|
||||||
|
components: vec![component],
|
||||||
|
existing: None,
|
||||||
|
on_close: move |saved: bool| {
|
||||||
|
confirming.set(None);
|
||||||
|
if saved {
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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<LicenseTarget>,
|
||||||
|
decision: ReviewDecision,
|
||||||
|
on_close: EventHandler<bool>,
|
||||||
|
) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let mut toasts = use_context::<Toasts>();
|
||||||
|
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<String> = 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<MouseData>| {
|
||||||
|
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<PolicyAction>,
|
||||||
|
) -> 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<bool>) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
|
let mut toasts = use_context::<Toasts>();
|
||||||
|
let start = policy.clone();
|
||||||
|
let mut rules = use_signal(|| {
|
||||||
|
LicenseCategory::ALL
|
||||||
|
.into_iter()
|
||||||
|
.map(|c| start.category_rule(c))
|
||||||
|
.collect::<Vec<CategoryRule>>()
|
||||||
|
});
|
||||||
|
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<MouseData>| {
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,8 @@ pub mod file_tree;
|
|||||||
pub mod help_chat;
|
pub mod help_chat;
|
||||||
pub mod lang_toggle;
|
pub mod lang_toggle;
|
||||||
pub mod layer_pins;
|
pub mod layer_pins;
|
||||||
|
pub mod license_editor;
|
||||||
|
pub mod license_review;
|
||||||
pub mod manual_findings;
|
pub mod manual_findings;
|
||||||
pub mod markdown;
|
pub mod markdown;
|
||||||
pub mod no_access;
|
pub mod no_access;
|
||||||
|
|||||||
@@ -3780,3 +3780,500 @@ pub mod webhooks {
|
|||||||
en: "Failed",
|
en: "Failed",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Confirming the licence of a component (licence review).
|
||||||
|
pub mod license_edit {
|
||||||
|
use super::Text;
|
||||||
|
|
||||||
|
pub const TITLE: Text = Text {
|
||||||
|
de: "Lizenz bestätigen",
|
||||||
|
en: "Confirm licence",
|
||||||
|
};
|
||||||
|
pub const TITLE_MANY: Text = Text {
|
||||||
|
de: "Lizenz für {n} Komponenten bestätigen",
|
||||||
|
en: "Confirm licence for {n} components",
|
||||||
|
};
|
||||||
|
pub const EDIT: Text = Text {
|
||||||
|
de: "Bearbeiten",
|
||||||
|
en: "Edit",
|
||||||
|
};
|
||||||
|
pub const EDIT_SELECTED: Text = Text {
|
||||||
|
de: "Lizenz bearbeiten",
|
||||||
|
en: "Edit licence",
|
||||||
|
};
|
||||||
|
pub const CLEAR_SELECTION: Text = Text {
|
||||||
|
de: "Auswahl aufheben",
|
||||||
|
en: "Clear selection",
|
||||||
|
};
|
||||||
|
pub const SELECT_ROW: Text = Text {
|
||||||
|
de: "Für die Lizenzbearbeitung auswählen",
|
||||||
|
en: "Select for licence editing",
|
||||||
|
};
|
||||||
|
pub const KIND_SPDX: Text = Text {
|
||||||
|
de: "SPDX-Lizenz",
|
||||||
|
en: "SPDX licence",
|
||||||
|
};
|
||||||
|
pub const KIND_CUSTOM: Text = Text {
|
||||||
|
de: "Eigene oder kommerzielle Lizenz",
|
||||||
|
en: "Own or commercial licence",
|
||||||
|
};
|
||||||
|
pub const SPDX_LABEL: Text = Text {
|
||||||
|
de: "Lizenz (SPDX-ID oder Ausdruck)",
|
||||||
|
en: "Licence (SPDX id or expression)",
|
||||||
|
};
|
||||||
|
pub const SPDX_HINT: Text = Text {
|
||||||
|
de: "z. B. MIT, Apache-2.0 oder „MIT OR Apache-2.0“",
|
||||||
|
en: "e.g. MIT, Apache-2.0 or “MIT OR Apache-2.0”",
|
||||||
|
};
|
||||||
|
pub const SPDX_INVALID: Text = Text {
|
||||||
|
de: "Keine gültige SPDX-Lizenz. Für eine nicht gelistete Lizenz „Eigene oder kommerzielle Lizenz“ wählen.",
|
||||||
|
en: "Not a valid SPDX licence. For a licence SPDX does not list, choose “Own or commercial licence”.",
|
||||||
|
};
|
||||||
|
pub const NAME_LABEL: Text = Text {
|
||||||
|
de: "Name der Lizenz",
|
||||||
|
en: "Licence name",
|
||||||
|
};
|
||||||
|
pub const NAME_HINT: Text = Text {
|
||||||
|
de: "z. B. „Lizenzvertrag Hersteller X“",
|
||||||
|
en: "e.g. “Supplier X licence agreement”",
|
||||||
|
};
|
||||||
|
pub const CATEGORY_LABEL: Text = Text {
|
||||||
|
de: "Kategorie",
|
||||||
|
en: "Category",
|
||||||
|
};
|
||||||
|
pub const CATEGORY_AUTO: Text = Text {
|
||||||
|
de: "Ergibt sich aus der SPDX-Lizenz",
|
||||||
|
en: "Follows from the SPDX licence",
|
||||||
|
};
|
||||||
|
pub const COPYRIGHT_LABEL: Text = Text {
|
||||||
|
de: "Copyright (eine Zeile je Inhaber)",
|
||||||
|
en: "Copyright (one line per holder)",
|
||||||
|
};
|
||||||
|
pub const COPYRIGHT_HINT: Text = Text {
|
||||||
|
de: "z. B. © 2019 Beispiel GmbH",
|
||||||
|
en: "e.g. © 2019 Example GmbH",
|
||||||
|
};
|
||||||
|
pub const TEXT_LABEL: Text = Text {
|
||||||
|
de: "Lizenztext (optional)",
|
||||||
|
en: "Licence text (optional)",
|
||||||
|
};
|
||||||
|
pub const URL_LABEL: Text = Text {
|
||||||
|
de: "Link zum Lizenztext (optional)",
|
||||||
|
en: "Link to the licence text (optional)",
|
||||||
|
};
|
||||||
|
pub const EVIDENCE_LABEL: Text = Text {
|
||||||
|
de: "Fundstelle",
|
||||||
|
en: "Where it was found",
|
||||||
|
};
|
||||||
|
pub const EVIDENCE_HINT: Text = Text {
|
||||||
|
de: "z. B. Datei im Repository, Vertrag, Webseite",
|
||||||
|
en: "e.g. a file in the repository, a contract, a web page",
|
||||||
|
};
|
||||||
|
pub const CONTRACT_LABEL: Text = Text {
|
||||||
|
de: "Vertrags- oder Lizenznummer",
|
||||||
|
en: "Contract or licence number",
|
||||||
|
};
|
||||||
|
pub const VALID_UNTIL_LABEL: Text = Text {
|
||||||
|
de: "Gültig bis",
|
||||||
|
en: "Valid until",
|
||||||
|
};
|
||||||
|
pub const USAGE_LABEL: Text = Text {
|
||||||
|
de: "Verwendung",
|
||||||
|
en: "Use",
|
||||||
|
};
|
||||||
|
pub const USAGE_UNSET: Text = Text {
|
||||||
|
de: "Nicht angegeben",
|
||||||
|
en: "Not stated",
|
||||||
|
};
|
||||||
|
pub const USAGE_SHIPPED: Text = Text {
|
||||||
|
de: "Wird mit dem Produkt ausgeliefert",
|
||||||
|
en: "Shipped with the product",
|
||||||
|
};
|
||||||
|
pub const USAGE_BUILD: Text = Text {
|
||||||
|
de: "Nur für Build oder Entwicklung",
|
||||||
|
en: "Only for building or development",
|
||||||
|
};
|
||||||
|
pub const ALL_VERSIONS: Text = Text {
|
||||||
|
de: "Für alle Versionen dieses Pakets",
|
||||||
|
en: "For every version of this package",
|
||||||
|
};
|
||||||
|
pub const NOTE_LABEL: Text = Text {
|
||||||
|
de: "Notiz",
|
||||||
|
en: "Note",
|
||||||
|
};
|
||||||
|
pub const DISCLAIMER: Text = Text {
|
||||||
|
de: "Kategorie und Pflichten sind Hinweise, keine Rechtsberatung.",
|
||||||
|
en: "Categories and obligations are guidance, not legal advice.",
|
||||||
|
};
|
||||||
|
pub const SAVE: Text = Text {
|
||||||
|
de: "Speichern",
|
||||||
|
en: "Save",
|
||||||
|
};
|
||||||
|
pub const CANCEL: Text = Text {
|
||||||
|
de: "Abbrechen",
|
||||||
|
en: "Cancel",
|
||||||
|
};
|
||||||
|
pub const WITHDRAW: Text = Text {
|
||||||
|
de: "Bestätigung zurücknehmen",
|
||||||
|
en: "Withdraw confirmation",
|
||||||
|
};
|
||||||
|
pub const SAVED: Text = Text {
|
||||||
|
de: "Lizenz bestätigt",
|
||||||
|
en: "Licence confirmed",
|
||||||
|
};
|
||||||
|
pub const WITHDRAWN: Text = Text {
|
||||||
|
de: "Bestätigung zurückgenommen",
|
||||||
|
en: "Confirmation withdrawn",
|
||||||
|
};
|
||||||
|
pub const SAVE_FAILED: Text = Text {
|
||||||
|
de: "Speichern fehlgeschlagen",
|
||||||
|
en: "Saving failed",
|
||||||
|
};
|
||||||
|
pub const CONFIRMED: Text = Text {
|
||||||
|
de: "bestätigt",
|
||||||
|
en: "confirmed",
|
||||||
|
};
|
||||||
|
pub const CONFIRMED_BY: Text = Text {
|
||||||
|
de: "Bestätigt von {by} am {at}",
|
||||||
|
en: "Confirmed by {by} on {at}",
|
||||||
|
};
|
||||||
|
pub const DETECTED: Text = Text {
|
||||||
|
de: "Erkannt",
|
||||||
|
en: "Detected",
|
||||||
|
};
|
||||||
|
pub const OPEN_FILTER: Text = Text {
|
||||||
|
de: "Lizenz offen (unbekannt)",
|
||||||
|
en: "Licence open (unknown)",
|
||||||
|
};
|
||||||
|
pub const OPEN_COUNT: Text = Text {
|
||||||
|
de: "{n} Komponenten ohne bekannte Lizenz",
|
||||||
|
en: "{n} components without a known licence",
|
||||||
|
};
|
||||||
|
pub const OPEN_SHOW: Text = Text {
|
||||||
|
de: "Anzeigen und bearbeiten",
|
||||||
|
en: "Show and edit",
|
||||||
|
};
|
||||||
|
pub const CONFIRMED_COUNT: Text = Text {
|
||||||
|
de: "{n} bestätigt",
|
||||||
|
en: "{n} confirmed",
|
||||||
|
};
|
||||||
|
pub const CAT_PUBLIC_DOMAIN: Text = Text {
|
||||||
|
de: "Gemeinfrei",
|
||||||
|
en: "Public domain",
|
||||||
|
};
|
||||||
|
pub const CAT_PERMISSIVE: Text = Text {
|
||||||
|
de: "Freizügig",
|
||||||
|
en: "Permissive",
|
||||||
|
};
|
||||||
|
pub const CAT_WEAK_COPYLEFT: Text = Text {
|
||||||
|
de: "Schwaches Copyleft",
|
||||||
|
en: "Weak copyleft",
|
||||||
|
};
|
||||||
|
pub const CAT_STRONG_COPYLEFT: Text = Text {
|
||||||
|
de: "Starkes Copyleft",
|
||||||
|
en: "Strong copyleft",
|
||||||
|
};
|
||||||
|
pub const CAT_NETWORK_COPYLEFT: Text = Text {
|
||||||
|
de: "Netzwerk-Copyleft",
|
||||||
|
en: "Network copyleft",
|
||||||
|
};
|
||||||
|
pub const CAT_PROPRIETARY: Text = Text {
|
||||||
|
de: "Proprietär / kommerziell",
|
||||||
|
en: "Proprietary / commercial",
|
||||||
|
};
|
||||||
|
pub const CAT_OWN_CODE: Text = Text {
|
||||||
|
de: "Eigener Code",
|
||||||
|
en: "Own code",
|
||||||
|
};
|
||||||
|
pub const CAT_UNCLEAR: Text = Text {
|
||||||
|
de: "Unklar",
|
||||||
|
en: "Unclear",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A category in words.
|
||||||
|
pub fn category(c: compliance_core::models::LicenseCategory) -> Text {
|
||||||
|
use compliance_core::models::LicenseCategory::*;
|
||||||
|
match c {
|
||||||
|
PublicDomain => CAT_PUBLIC_DOMAIN,
|
||||||
|
Permissive => CAT_PERMISSIVE,
|
||||||
|
WeakCopyleft => CAT_WEAK_COPYLEFT,
|
||||||
|
StrongCopyleft => CAT_STRONG_COPYLEFT,
|
||||||
|
NetworkCopyleft => CAT_NETWORK_COPYLEFT,
|
||||||
|
Proprietary => CAT_PROPRIETARY,
|
||||||
|
OwnCode => CAT_OWN_CODE,
|
||||||
|
Unclear => CAT_UNCLEAR,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 CONFIRM_FIRST: Text = Text {
|
||||||
|
de: "Lizenz bestätigen",
|
||||||
|
en: "Confirm licence",
|
||||||
|
};
|
||||||
|
pub const CONFIRM_FIRST_HINT: Text = Text {
|
||||||
|
de: "Für diese Komponente ist keine Lizenz bekannt. Bestätigen Sie zuerst ihre Lizenz; danach kann sie freigegeben oder abgelehnt werden.",
|
||||||
|
en: "No licence is known for this component. Confirm its licence first; then it can be approved or rejected.",
|
||||||
|
};
|
||||||
|
pub const CONFIRM_FIRST_OTHERS: Text = Text {
|
||||||
|
de: "Lizenz zuerst bestätigen (IT_ADMIN oder USER)",
|
||||||
|
en: "Licence to be confirmed first (IT_ADMIN or USER)",
|
||||||
|
};
|
||||||
|
pub const IN_TARGETS: Text = Text {
|
||||||
|
de: "in {n} Prüfobjekten",
|
||||||
|
en: "in {n} targets",
|
||||||
|
};
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
//! Save text the page fetched as a file in the browser.
|
//! Save text the page fetched as a file in the browser.
|
||||||
|
|
||||||
/// Save `content` as the JSON file `filename`.
|
/// Save `content` as the JSON file `filename`.
|
||||||
#[cfg(feature = "web")]
|
|
||||||
pub fn save_json(content: &str, filename: &str) {
|
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;
|
use wasm_bindgen::JsCast;
|
||||||
let Some(window) = web_sys::window() else {
|
let Some(window) = web_sys::window() else {
|
||||||
return;
|
return;
|
||||||
@@ -15,7 +20,7 @@ pub fn save_json(content: &str, filename: &str) {
|
|||||||
blob_parts.push(&wasm_bindgen::JsValue::from_str(content));
|
blob_parts.push(&wasm_bindgen::JsValue::from_str(content));
|
||||||
|
|
||||||
let opts = web_sys::BlobPropertyBag::new();
|
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 {
|
let Ok(blob) = web_sys::Blob::new_with_str_sequence_and_options(&blob_parts, &opts) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -39,4 +44,4 @@ pub fn save_json(content: &str, filename: &str) {
|
|||||||
|
|
||||||
/// Server rendering: downloads only happen in the browser.
|
/// Server rendering: downloads only happen in the browser.
|
||||||
#[cfg(not(feature = "web"))]
|
#[cfg(not(feature = "web"))]
|
||||||
pub fn save_json(_content: &str, _filename: &str) {}
|
pub fn save_file(_content: &str, _filename: &str, _mime: &str) {}
|
||||||
@@ -64,6 +64,12 @@ pub struct SbomEntryData {
|
|||||||
/// The images an image recipe declares it in (a Yocto recipe).
|
/// The images an image recipe declares it in (a Yocto recipe).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub in_image: Option<compliance_core::models::InImage>,
|
pub in_image: Option<compliance_core::models::InImage>,
|
||||||
|
/// The licence a person of the workspace confirmed, where there is one.
|
||||||
|
#[serde(default)]
|
||||||
|
pub concluded: Option<compliance_core::models::LicenseConclusion>,
|
||||||
|
/// What the workspace's licence policy says about it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub policy: Option<compliance_core::models::LicenseVerdict>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub created_at: Option<serde_json::Value>,
|
pub created_at: Option<serde_json::Value>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -82,9 +88,161 @@ pub struct LicenseSummaryData {
|
|||||||
pub license: String,
|
pub license: String,
|
||||||
pub count: u64,
|
pub count: u64,
|
||||||
pub is_copyleft: bool,
|
pub is_copyleft: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub category: compliance_core::models::LicenseCategory,
|
||||||
|
/// How many of the components a person confirmed this licence for.
|
||||||
|
#[serde(default)]
|
||||||
|
pub confirmed: u64,
|
||||||
pub packages: Vec<String>,
|
pub packages: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The value of the licence filter that asks for the components whose
|
||||||
|
/// licence is still open (none detected, none confirmed).
|
||||||
|
pub const OPEN_LICENSE_FILTER: &str = "__open__";
|
||||||
|
|
||||||
|
/// A component a licence is confirmed for.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct LicenseTarget {
|
||||||
|
pub name: String,
|
||||||
|
pub package_manager: String,
|
||||||
|
pub version: String,
|
||||||
|
pub purl: Option<String>,
|
||||||
|
/// 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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LicenseTarget {
|
||||||
|
/// The component of an SBOM row.
|
||||||
|
pub fn of(entry: &SbomEntryData) -> Self {
|
||||||
|
Self {
|
||||||
|
name: entry.name.clone(),
|
||||||
|
package_manager: entry.package_manager.clone(),
|
||||||
|
version: entry.version.clone(),
|
||||||
|
purl: entry.purl.clone(),
|
||||||
|
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<String>,
|
||||||
|
/// The licence that counts: the confirmed one, else the detected one.
|
||||||
|
#[serde(default)]
|
||||||
|
pub license: Option<String>,
|
||||||
|
/// The licence the scan found.
|
||||||
|
#[serde(default)]
|
||||||
|
pub detected: Option<String>,
|
||||||
|
/// The id of the confirmed licence, if one was confirmed.
|
||||||
|
#[serde(default)]
|
||||||
|
pub conclusion_id: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub review: Option<compliance_core::models::LegalReview>,
|
||||||
|
/// Whether a legal review can decide about it; otherwise its licence
|
||||||
|
/// has to be confirmed first.
|
||||||
|
#[serde(default)]
|
||||||
|
pub decidable: bool,
|
||||||
|
/// In how many targets the package is (one row for all of them).
|
||||||
|
#[serde(default = "one")]
|
||||||
|
pub targets: u64,
|
||||||
|
pub verdict: compliance_core::models::LicenseVerdict,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn one() -> u64 {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
|
||||||
|
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: one row per package and version.
|
||||||
|
pub fn key(&self) -> String {
|
||||||
|
format!("{}|{}|{}", 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<LicenseCheckItem>,
|
||||||
|
#[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,
|
||||||
|
/// Whether the requester may confirm licences (IT_ADMIN, USER).
|
||||||
|
#[serde(default)]
|
||||||
|
pub may_confirm: 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<LicenseTarget>,
|
||||||
|
pub all_versions: bool,
|
||||||
|
pub decision: compliance_core::models::ReviewDecision,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub note: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A licence confirmation as the editor sends it; the agent adds who and
|
||||||
|
/// when, and the category of an SPDX licence.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct LicenseDraft {
|
||||||
|
pub components: Vec<LicenseTarget>,
|
||||||
|
pub all_versions: bool,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_name: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub category: Option<compliance_core::models::LicenseCategory>,
|
||||||
|
pub copyright: Vec<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_text: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub license_url: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub evidence: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub contract_ref: Option<String>,
|
||||||
|
/// `YYYY-MM-DD`, as a date field gives it.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub valid_until: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub usage: Option<compliance_core::models::LicenseUsage>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub note: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
pub struct LicenseSummaryResponse {
|
pub struct LicenseSummaryResponse {
|
||||||
pub data: Vec<LicenseSummaryData>,
|
pub data: Vec<LicenseSummaryData>,
|
||||||
@@ -172,7 +330,9 @@ pub async fn fetch_sbom_filtered(
|
|||||||
params.push(format!("has_vulns={hv}"));
|
params.push(format!("has_vulns={hv}"));
|
||||||
}
|
}
|
||||||
if let Some(l) = &license {
|
if let Some(l) = &license {
|
||||||
if !l.is_empty() {
|
if l == OPEN_LICENSE_FILTER {
|
||||||
|
params.push("unresolved=true".to_string());
|
||||||
|
} else if !l.is_empty() {
|
||||||
params.push(format!("license={}", l.replace(' ', "%20")));
|
params.push(format!("license={}", l.replace(' ', "%20")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,6 +355,112 @@ pub async fn fetch_sbom_filtered(
|
|||||||
Ok(body)
|
Ok(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Confirm the licence of the draft's components. The agent refuses (422)
|
||||||
|
/// a licence it cannot read, with the reason, and read-only roles (403);
|
||||||
|
/// the refusal is the error.
|
||||||
|
#[server]
|
||||||
|
pub async fn save_license_conclusion(draft: LicenseDraft) -> Result<(), ServerFnError> {
|
||||||
|
let resp =
|
||||||
|
super::agent_client::agent_request(reqwest::Method::PUT, "/api/v1/licenses/conclusions")
|
||||||
|
.await?
|
||||||
|
.json(&draft)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
super::agent_client::ok_or_error(resp).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Withdraw the confirmed licence `id`; the component shows the detected
|
||||||
|
/// licence again.
|
||||||
|
#[server]
|
||||||
|
pub async fn withdraw_license_conclusion(id: String) -> Result<(), ServerFnError> {
|
||||||
|
let resp =
|
||||||
|
super::agent_client::agent_request(reqwest::Method::DELETE, "/api/v1/licenses/conclusions")
|
||||||
|
.await?
|
||||||
|
.query(&[("id", id.as_str())])
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
super::agent_client::ok_or_error(resp).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<String>,
|
||||||
|
) -> Result<LicenseCheckResponse, ServerFnError> {
|
||||||
|
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<String, ServerFnError> {
|
||||||
|
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]
|
#[server]
|
||||||
pub async fn fetch_sbom_export(repo_id: String, format: String) -> Result<String, ServerFnError> {
|
pub async fn fetch_sbom_export(repo_id: String, format: String) -> Result<String, ServerFnError> {
|
||||||
let path = format!("/api/v1/sbom/export?repo_id={repo_id}&format={format}");
|
let path = format!("/api/v1/sbom/export?repo_id={repo_id}&format={format}");
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
use compliance_core::models::YOCTO_RECIPE_MANAGER;
|
use compliance_core::models::{LicenseConclusion, YOCTO_RECIPE_MANAGER};
|
||||||
use dioxus::prelude::*;
|
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::page_header::PageHeader;
|
||||||
use crate::components::pagination::Pagination;
|
use crate::components::pagination::Pagination;
|
||||||
use crate::components::toast::{ToastType, Toasts};
|
use crate::components::toast::{ToastType, Toasts};
|
||||||
use crate::i18n::texts::{common, 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::i18n::{use_lang, Lang};
|
||||||
use crate::infrastructure::sbom::*;
|
use crate::infrastructure::sbom::*;
|
||||||
|
use compliance_core::models::ReviewDecision;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn SbomPage(target: String) -> Element {
|
pub fn SbomPage(target: String) -> Element {
|
||||||
@@ -33,6 +39,12 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
let mut show_export = use_signal(|| false);
|
let mut show_export = use_signal(|| false);
|
||||||
let mut export_format = use_signal(|| "cyclonedx".to_string());
|
let mut export_format = use_signal(|| "cyclonedx".to_string());
|
||||||
|
|
||||||
|
// ── Licence review: the rows picked for a bulk edit, and the open editor
|
||||||
|
// (its components, and the confirmation it starts from) ──
|
||||||
|
let can_write = use_can_write();
|
||||||
|
let mut selected = use_signal(Vec::<LicenseTarget>::new);
|
||||||
|
let mut editor = use_signal(|| Option::<(Vec<LicenseTarget>, Option<LicenseConclusion>)>::None);
|
||||||
|
|
||||||
// ── Diff state ──
|
// ── Diff state ──
|
||||||
let mut diff_repo_a = use_signal(String::new);
|
let mut diff_repo_a = use_signal(String::new);
|
||||||
let mut diff_repo_b = use_signal(String::new);
|
let mut diff_repo_b = use_signal(String::new);
|
||||||
@@ -48,7 +60,7 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
let sbom_filters = use_resource(|| async { fetch_sbom_filters().await.ok() });
|
let sbom_filters = use_resource(|| async { fetch_sbom_filters().await.ok() });
|
||||||
|
|
||||||
// ── SBOM list (filtered) ──
|
// ── SBOM list (filtered) ──
|
||||||
let sbom = use_resource(move || {
|
let mut sbom = use_resource(move || {
|
||||||
let p = page();
|
let p = page();
|
||||||
let repo = repo_filter();
|
let repo = repo_filter();
|
||||||
let pm = pm_filter();
|
let pm = pm_filter();
|
||||||
@@ -83,7 +95,7 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ── License summary ──
|
// ── License summary ──
|
||||||
let license_data = use_resource(move || {
|
let mut license_data = use_resource(move || {
|
||||||
let repo = repo_filter();
|
let repo = repo_filter();
|
||||||
async move {
|
async move {
|
||||||
fetch_license_summary(if repo.is_empty() { None } else { Some(repo) })
|
fetch_license_summary(if repo.is_empty() { None } else { Some(repo) })
|
||||||
@@ -206,6 +218,11 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
class: "sbom-filter-select",
|
class: "sbom-filter-select",
|
||||||
onchange: move |e| { license_filter.set(e.value()); page.set(1); },
|
onchange: move |e| { license_filter.set(e.value()); page.set(1); },
|
||||||
option { value: "", {tx::ALL_LICENSES.get(lang)} }
|
option { value: "", {tx::ALL_LICENSES.get(lang)} }
|
||||||
|
option {
|
||||||
|
value: OPEN_LICENSE_FILTER,
|
||||||
|
selected: license_filter() == OPEN_LICENSE_FILTER,
|
||||||
|
{lx::OPEN_FILTER.get(lang)}
|
||||||
|
}
|
||||||
{
|
{
|
||||||
match &*sbom_filters.read() {
|
match &*sbom_filters.read() {
|
||||||
Some(Some(f)) => rsx! {
|
Some(Some(f)) => rsx! {
|
||||||
@@ -288,11 +305,29 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if can_write && !selected().is_empty() {
|
||||||
|
div { class: "license-selection-bar",
|
||||||
|
span { "{selected().len()} ✓" }
|
||||||
|
button {
|
||||||
|
class: "btn btn-primary btn-sm",
|
||||||
|
onclick: move |_| editor.set(Some((selected(), None))),
|
||||||
|
{lx::EDIT_SELECTED.get(lang)}
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
class: "btn btn-ghost btn-sm",
|
||||||
|
onclick: move |_| selected.set(Vec::new()),
|
||||||
|
{lx::CLEAR_SELECTION.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
div { class: "card",
|
div { class: "card",
|
||||||
div { class: "table-wrapper",
|
div { class: "table-wrapper",
|
||||||
table {
|
table {
|
||||||
thead {
|
thead {
|
||||||
tr {
|
tr {
|
||||||
|
if can_write {
|
||||||
|
th { class: "license-select-col" }
|
||||||
|
}
|
||||||
th { {tx::PACKAGE.get(lang)} }
|
th { {tx::PACKAGE.get(lang)} }
|
||||||
th { {tx::VERSION.get(lang)} }
|
th { {tx::VERSION.get(lang)} }
|
||||||
th { {tx::MANAGER.get(lang)} }
|
th { {tx::MANAGER.get(lang)} }
|
||||||
@@ -306,7 +341,18 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
let row_key = format!("{}@{}", entry.name, entry.version);
|
let row_key = format!("{}@{}", entry.name, entry.version);
|
||||||
let is_expanded = expanded_row() == Some(row_key.clone());
|
let is_expanded = expanded_row() == Some(row_key.clone());
|
||||||
let has_vulns = !entry.known_vulnerabilities.is_empty();
|
let has_vulns = !entry.known_vulnerabilities.is_empty();
|
||||||
let license_class = license_css_class(entry.license.as_deref());
|
let license_class = license_css_class(entry);
|
||||||
|
let shown_license = entry
|
||||||
|
.concluded
|
||||||
|
.as_ref()
|
||||||
|
.map(|c| c.display().to_string())
|
||||||
|
.or_else(|| entry.license.clone().filter(|l| !l.trim().is_empty()))
|
||||||
|
.unwrap_or_else(|| "-".to_string());
|
||||||
|
let target = LicenseTarget::of(entry);
|
||||||
|
let is_selected = selected().contains(&target);
|
||||||
|
let toggle_target = target.clone();
|
||||||
|
let edit_target = target.clone();
|
||||||
|
let edit_existing = entry.concluded.clone();
|
||||||
let row_key_click = row_key.clone();
|
let row_key_click = row_key.clone();
|
||||||
// Which images declare it, on the badge's tooltip.
|
// Which images declare it, on the badge's tooltip.
|
||||||
let in_image_title = entry.in_image.as_ref().map(|i| {
|
let in_image_title = entry.in_image.as_ref().map(|i| {
|
||||||
@@ -314,6 +360,24 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
});
|
});
|
||||||
rsx! {
|
rsx! {
|
||||||
tr {
|
tr {
|
||||||
|
if can_write {
|
||||||
|
td { class: "license-select-col",
|
||||||
|
input {
|
||||||
|
r#type: "checkbox",
|
||||||
|
title: lx::SELECT_ROW.get(lang),
|
||||||
|
checked: is_selected,
|
||||||
|
onchange: move |e| {
|
||||||
|
let t = toggle_target.clone();
|
||||||
|
selected.with_mut(|list| {
|
||||||
|
list.retain(|x| x != &t);
|
||||||
|
if e.checked() {
|
||||||
|
list.push(t);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
td {
|
td {
|
||||||
style: "font-weight: 500;",
|
style: "font-weight: 500;",
|
||||||
"{entry.name}"
|
"{entry.name}"
|
||||||
@@ -343,7 +407,39 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
}
|
}
|
||||||
td {
|
td {
|
||||||
span { class: "sbom-license-badge {license_class}",
|
span { class: "sbom-license-badge {license_class}",
|
||||||
"{entry.license.as_deref().unwrap_or(\"-\")}"
|
"{shown_license}"
|
||||||
|
}
|
||||||
|
if let Some(c) = &entry.concluded {
|
||||||
|
" "
|
||||||
|
span {
|
||||||
|
class: "badge badge-success license-confirmed",
|
||||||
|
title: "{confirmed_title(c, lang)}",
|
||||||
|
{lx::CONFIRMED.get(lang)}
|
||||||
|
}
|
||||||
|
if 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 {
|
||||||
|
" "
|
||||||
|
button {
|
||||||
|
class: "btn btn-ghost btn-sm license-edit-btn",
|
||||||
|
onclick: move |_| editor.set(Some((vec![edit_target.clone()], edit_existing.clone()))),
|
||||||
|
{lx::EDIT.get(lang)}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
td {
|
td {
|
||||||
@@ -382,7 +478,7 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
// ── Vulnerability drill-down row ──
|
// ── Vulnerability drill-down row ──
|
||||||
if is_expanded && has_vulns {
|
if is_expanded && has_vulns {
|
||||||
tr { class: "sbom-vuln-detail-row",
|
tr { class: "sbom-vuln-detail-row",
|
||||||
td { colspan: "5",
|
td { colspan: if can_write { "6" } else { "5" },
|
||||||
div { class: "sbom-vuln-detail",
|
div { class: "sbom-vuln-detail",
|
||||||
for vuln in &entry.known_vulnerabilities {
|
for vuln in &entry.known_vulnerabilities {
|
||||||
div { class: "sbom-vuln-card",
|
div { class: "sbom-vuln-card",
|
||||||
@@ -462,22 +558,88 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Licence editor ──
|
||||||
|
if let Some((components, existing)) = editor() {
|
||||||
|
LicenseEditor {
|
||||||
|
components,
|
||||||
|
existing,
|
||||||
|
on_close: move |saved: bool| {
|
||||||
|
editor.set(None);
|
||||||
|
if saved {
|
||||||
|
selected.set(Vec::new());
|
||||||
|
sbom.restart();
|
||||||
|
license_data.restart();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ═══════════════ LICENSE COMPLIANCE TAB ═══════════════
|
// ═══════════════ LICENSE COMPLIANCE TAB ═══════════════
|
||||||
if active_tab() == "licenses" {
|
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() {
|
match &*license_data.read() {
|
||||||
Some(Some(resp)) => {
|
Some(Some(resp)) => {
|
||||||
let total_pkgs: u64 = resp.data.iter().map(|l| l.count).sum();
|
let total_pkgs: u64 = resp.data.iter().map(|l| l.count).sum();
|
||||||
let has_copyleft = resp.data.iter().any(|l| l.is_copyleft);
|
let has_copyleft = resp.data.iter().any(|l| l.category.is_copyleft());
|
||||||
let copyleft_items: Vec<_> = resp.data.iter().filter(|l| l.is_copyleft).collect();
|
let copyleft_items: Vec<_> = resp.data.iter().filter(|l| l.category.is_copyleft()).collect();
|
||||||
|
let open = resp.data.iter().find(|l| l.license == "Unknown").map_or(0, |l| l.count);
|
||||||
|
let confirmed: u64 = resp.data.iter().map(|l| l.confirmed).sum();
|
||||||
|
|
||||||
rsx! {
|
rsx! {
|
||||||
|
if open > 0 || confirmed > 0 {
|
||||||
|
div { class: "card license-open-card",
|
||||||
|
if open > 0 {
|
||||||
|
strong { {lx::OPEN_COUNT.get(lang).replace("{n}", &open.to_string())} }
|
||||||
|
button {
|
||||||
|
class: "btn btn-primary btn-sm",
|
||||||
|
onclick: move |_| {
|
||||||
|
license_filter.set(OPEN_LICENSE_FILTER.to_string());
|
||||||
|
page.set(1);
|
||||||
|
active_tab.set("packages".to_string());
|
||||||
|
},
|
||||||
|
{lx::OPEN_SHOW.get(lang)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if confirmed > 0 {
|
||||||
|
span { class: "license-confirmed-count",
|
||||||
|
{lx::CONFIRMED_COUNT.get(lang).replace("{n}", &confirmed.to_string())}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if has_copyleft {
|
if has_copyleft {
|
||||||
div { class: "license-copyleft-warning",
|
div { class: "license-copyleft-warning",
|
||||||
strong { {tx::COPYLEFT_TITLE.get(lang)} }
|
strong { {tx::COPYLEFT_TITLE.get(lang)} }
|
||||||
p { {tx::COPYLEFT_BODY.get(lang)} }
|
p { {tx::COPYLEFT_BODY.get(lang)} }
|
||||||
for item in ©left_items {
|
for item in ©left_items {
|
||||||
div { class: "license-copyleft-item",
|
div { class: "license-copyleft-item",
|
||||||
span { class: "sbom-license-badge license-copyleft", "{item.license}" }
|
span { class: "sbom-license-badge {category_class(item.category)}", "{item.license}" }
|
||||||
span { " — {item.count} {tx::PACKAGES_COUNT.get(lang)}: " }
|
span { " — {item.count} {tx::PACKAGES_COUNT.get(lang)}: " }
|
||||||
span { class: "license-pkg-list",
|
span { class: "license-pkg-list",
|
||||||
"{item.packages.join(\", \")}"
|
"{item.packages.join(\", \")}"
|
||||||
@@ -494,7 +656,7 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
for item in &resp.data {
|
for item in &resp.data {
|
||||||
{
|
{
|
||||||
let pct = (item.count as f64 / total_pkgs as f64 * 100.0).max(2.0);
|
let pct = (item.count as f64 / total_pkgs as f64 * 100.0).max(2.0);
|
||||||
let bar_class = if item.is_copyleft { "license-bar license-copyleft" } else { "license-bar license-permissive" };
|
let bar_class = format!("license-bar {}", category_class(item.category));
|
||||||
rsx! {
|
rsx! {
|
||||||
div { class: "license-bar-row",
|
div { class: "license-bar-row",
|
||||||
span { class: "license-bar-label", "{item.license}" }
|
span { class: "license-bar-label", "{item.license}" }
|
||||||
@@ -532,15 +694,19 @@ pub fn SbomPage(target: String) -> Element {
|
|||||||
tr {
|
tr {
|
||||||
td {
|
td {
|
||||||
span {
|
span {
|
||||||
class: "sbom-license-badge {license_type_class(item.is_copyleft)}",
|
class: "sbom-license-badge {category_class(item.category)}",
|
||||||
"{item.license}"
|
"{item.license}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
td {
|
td {
|
||||||
if item.is_copyleft {
|
span {
|
||||||
span { class: "badge badge-high", {tx::COPYLEFT.get(lang)} }
|
class: if item.category.is_copyleft() { "badge badge-high" } else { "badge badge-info" },
|
||||||
} else {
|
{lx::category(item.category).get(lang)}
|
||||||
span { class: "badge badge-info", {tx::PERMISSIVE.get(lang)} }
|
}
|
||||||
|
if item.confirmed > 0 {
|
||||||
|
span { class: "license-confirmed-count",
|
||||||
|
{format!(" · {}", lx::CONFIRMED_COUNT.get(lang).replace("{n}", &item.confirmed.to_string()))}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
td {
|
td {
|
||||||
@@ -765,27 +931,15 @@ fn version_label(entry: &SbomEntryData, lang: Lang) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn license_css_class(license: Option<&str>) -> &'static str {
|
/// The badge class of a row's licence: by the confirmed licence's category,
|
||||||
match license {
|
/// else by the detected licence's (LGPL and MPL are weak copyleft, not GPL).
|
||||||
Some(l) => {
|
fn license_css_class(entry: &SbomEntryData) -> &'static str {
|
||||||
let upper = l.to_uppercase();
|
match (&entry.concluded, entry.license.as_deref()) {
|
||||||
if upper.contains("GPL") || upper.contains("AGPL") {
|
(Some(c), _) => category_class(c.category),
|
||||||
"license-copyleft"
|
(None, Some(l)) if !l.trim().is_empty() => {
|
||||||
} else if upper.contains("LGPL") || upper.contains("MPL") {
|
category_class(compliance_core::spdx_license::category(l))
|
||||||
"license-weak-copyleft"
|
|
||||||
} else {
|
|
||||||
"license-permissive"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
None => "",
|
_ => "",
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn license_type_class(is_copyleft: bool) -> &'static str {
|
|
||||||
if is_copyleft {
|
|
||||||
"license-copyleft"
|
|
||||||
} else {
|
|
||||||
"license-permissive"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -132,6 +132,16 @@ impl Database {
|
|||||||
self.inner.collection("sbom_entries")
|
self.inner.collection("sbom_entries")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Licences the workspace confirmed, merged into the components read.
|
||||||
|
pub fn license_conclusions(&self) -> Collection<compliance_core::models::LicenseConclusion> {
|
||||||
|
self.inner.collection("license_conclusions")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The workspace's licence policy (one document).
|
||||||
|
pub fn license_policy(&self) -> Collection<compliance_core::models::LicensePolicy> {
|
||||||
|
self.inner.collection("license_policy")
|
||||||
|
}
|
||||||
|
|
||||||
pub fn dast_findings(&self) -> Collection<DastFinding> {
|
pub fn dast_findings(&self) -> Collection<DastFinding> {
|
||||||
self.inner.collection("dast_findings")
|
self.inner.collection("dast_findings")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -145,6 +145,28 @@ impl ComplianceMcpServer {
|
|||||||
sbom::get_sbom(&db, params).await
|
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<sbom::LicenseCheckParams>,
|
||||||
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
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<sbom::ThirdPartyNoticesParams>,
|
||||||
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let db = self.tenant_db()?;
|
||||||
|
sbom::third_party_notices(&db, params).await
|
||||||
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Generate a vulnerability report for a repository showing all packages with known CVEs"
|
description = "Generate a vulnerability report for a repository showing all packages with known CVEs"
|
||||||
)]
|
)]
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ use rmcp::{model::*, ErrorData as McpError};
|
|||||||
use schemars::JsonSchema;
|
use schemars::JsonSchema;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use compliance_core::models::SbomEntry;
|
||||||
|
|
||||||
use crate::database::Database;
|
use crate::database::Database;
|
||||||
|
|
||||||
const MAX_LIMIT: i64 = 200;
|
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))?;
|
.map_err(|e| McpError::internal_error(format!("deserialize error: {e}"), None))?;
|
||||||
results.push(entry);
|
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)
|
let json = serde_json::to_string_pretty(&results)
|
||||||
.map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?;
|
.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<CallToolRe
|
|||||||
None,
|
None,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let entries = super::collect(
|
let mut entries = super::collect(
|
||||||
db.sbom_entries()
|
db.sbom_entries()
|
||||||
.find(filter)
|
.find(filter)
|
||||||
.await
|
.await
|
||||||
.map_err(super::db_error)?,
|
.map_err(super::db_error)?,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
let conclusions = load_conclusions(db).await?;
|
||||||
|
compliance_core::models::license::apply(&mut entries, &conclusions);
|
||||||
let document = match params.format {
|
let document = match params.format {
|
||||||
SbomFormat::Cyclonedx => compliance_core::sbom_docs::cyclonedx(&entries, ¶ms.target_id),
|
SbomFormat::Cyclonedx => compliance_core::sbom_docs::cyclonedx(&entries, ¶ms.target_id),
|
||||||
SbomFormat::Spdx => compliance_core::sbom_docs::spdx(&entries, ¶ms.target_id),
|
SbomFormat::Spdx => compliance_core::sbom_docs::spdx(&entries, ¶ms.target_id),
|
||||||
};
|
};
|
||||||
super::json_result(&document)
|
super::json_result(&document)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every licence the workspace confirmed.
|
||||||
|
async fn load_conclusions(
|
||||||
|
db: &Database,
|
||||||
|
) -> Result<Vec<compliance_core::models::LicenseConclusion>, 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<compliance_core::models::LicensePolicy, McpError> {
|
||||||
|
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<SbomEntry>, 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<SbomEntry> = 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<CallToolResult, McpError> {
|
||||||
|
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<CallToolResult, McpError> {
|
||||||
|
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)]))
|
||||||
|
}
|
||||||
@@ -62,6 +62,7 @@ export default withMermaid(defineConfig({
|
|||||||
{ text: 'Übersicht', link: '/features/overview' },
|
{ text: 'Übersicht', link: '/features/overview' },
|
||||||
{ text: 'Hilfe-Assistent', link: '/features/help-chat' },
|
{ text: 'Hilfe-Assistent', link: '/features/help-chat' },
|
||||||
{ text: 'MCP-Schnittstelle', link: '/features/mcp-server' },
|
{ text: 'MCP-Schnittstelle', link: '/features/mcp-server' },
|
||||||
|
{ text: 'API-Schlüssel', link: '/guide/api-keys' },
|
||||||
{ text: 'Tickets', link: '/guide/issues' },
|
{ text: 'Tickets', link: '/guide/issues' },
|
||||||
{ text: 'Webhooks und PR-Reviews', link: '/guide/webhooks' },
|
{ text: 'Webhooks und PR-Reviews', link: '/guide/webhooks' },
|
||||||
{ text: 'Managed Git anbinden', link: '/guide/managed-git' },
|
{ text: 'Managed Git anbinden', link: '/guide/managed-git' },
|
||||||
|
|||||||
@@ -87,9 +87,11 @@ manifest of sha256 checksums) is also served as one ZIP at
|
|||||||
|
|
||||||
| Tool | Description |
|
| 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. |
|
| `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. |
|
| `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. |
|
| `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
|
### DAST Tools
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# API-Schlüssel
|
||||||
|
|
||||||
|
Automatisierungen (eine CI-Pipeline, ein Werkmeister-Baustein, eigene Skripte)
|
||||||
|
melden sich bei der Prüfwerk-API mit einem API-Schlüssel an statt mit einem
|
||||||
|
Benutzerkonto. Schlüssel werden im Portal angelegt und widerrufen; jeder
|
||||||
|
Schlüssel gehört zu genau einer Organisation und trägt Berechtigungen
|
||||||
|
(_Scopes_).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -H "Authorization: Bearer bp_…" https://pruefwerk.breakpilot.com/api/v1/findings
|
||||||
|
```
|
||||||
|
|
||||||
|
## Was ein Schlüssel darf
|
||||||
|
|
||||||
|
| Scope | Erlaubt |
|
||||||
|
|---|---|
|
||||||
|
| `pruefwerk:findings.read` | Befunde lesen (`GET /api/v1/findings`, `/findings/variants`, `/findings/{id}`) |
|
||||||
|
| `pruefwerk:findings.write` | Status und Feedback von Befunden ändern (`PATCH /findings/{id}/status`, `/findings/bulk-status`, `/findings/{id}/feedback`); schließt das Lesen ein |
|
||||||
|
| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) |
|
||||||
|
| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) |
|
||||||
|
| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) |
|
||||||
|
| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) |
|
||||||
|
|
||||||
|
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
|
||||||
|
Prüfobjekte anlegen oder ändern, Zugangsdaten, Einstellungen, Befunde aus
|
||||||
|
manuellen Tests. Einen ENISA-Entwurf freigeben oder melden bleibt immer einer
|
||||||
|
Person vorbehalten.
|
||||||
|
|
||||||
|
Ältere Schlüssel ohne Scopes dürfen nur lesen (die vier `read`-Scopes).
|
||||||
|
|
||||||
|
## Antworten
|
||||||
|
|
||||||
|
| Status | Bedeutung |
|
||||||
|
|---|---|
|
||||||
|
| `401 invalid_api_key` | Schlüssel unbekannt, abgelaufen oder widerrufen |
|
||||||
|
| `403 scope_missing` | Der Schlüssel hat den nötigen Scope nicht, oder die Route nimmt keine Schlüssel an; `required` nennt den Scope |
|
||||||
|
| `402` | Die Organisation ist eingeschränkt: lesen ja, ändern nein |
|
||||||
|
| `503` | Prüfwerk kann den Schlüssel gerade nicht prüfen; später erneut versuchen |
|
||||||
|
|
||||||
|
## Gut zu wissen
|
||||||
|
|
||||||
|
- **Widerruf wirkt nach höchstens 60 Sekunden.** Prüfwerk merkt sich das
|
||||||
|
Prüfergebnis eines Schlüssels eine Minute lang.
|
||||||
|
- **Nachvollziehbarkeit:** Änderungen mit einem Schlüssel stehen im Verlauf
|
||||||
|
und im Audit-Log unter dem Inhaber des Schlüssels bzw. `apikey:<id>`.
|
||||||
|
Handelt ein Werkzeug für eine Person, kann es sie im Header `X-BP-Actor`
|
||||||
|
nennen; sie wird mitprotokolliert, berechtigt aber nichts.
|
||||||
|
- Ein Schlüssel wirkt nur in seiner eigenen Organisation. Angaben zur
|
||||||
|
Organisation in Headern, Pfaden oder Anfragedaten werden ignoriert.
|
||||||
@@ -93,7 +93,9 @@ Then restore once (`dotnet restore`, or in Visual Studio) and commit the
|
|||||||
Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7) is
|
Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7) is
|
||||||
a finding (CWE-1104, CRA requirement dependency monitoring `cra-ai-22`). .NET
|
a finding (CWE-1104, CRA requirement dependency monitoring `cra-ai-22`). .NET
|
||||||
Framework 4.6.2 ends on 2027-01-12, .NET 8 and 9 on 2026-11-10; the scan
|
Framework 4.6.2 ends on 2027-01-12, .NET 8 and 9 on 2026-11-10; the scan
|
||||||
reports them from then on.
|
reports them from then on. The dates are bundled
|
||||||
|
(`compliance-agent/data/eol/dotnet.json`); a weekly check compares them with
|
||||||
|
endoflife.date and opens an issue when they differ.
|
||||||
|
|
||||||
**C# code (our own Semgrep rules):** SQL built by concatenation, interpolation
|
**C# code (our own Semgrep rules):** SQL built by concatenation, interpolation
|
||||||
or `String.Format` (CWE-89), `Process.Start` with a composed command line
|
or `String.Format` (CWE-89), `Process.Start` with a composed command line
|
||||||
|
|||||||
@@ -97,7 +97,9 @@ ohne Sicherheitsupdates von Microsoft anspricht (z. B. .NET Framework 4.0,
|
|||||||
4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7), ist ein Befund
|
4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7), ist ein Befund
|
||||||
(CWE-1104, CRA-Anforderung Dependency-Monitoring `cra-ai-22`). .NET Framework
|
(CWE-1104, CRA-Anforderung Dependency-Monitoring `cra-ai-22`). .NET Framework
|
||||||
4.6.2 endet am 12.01.2027, .NET 8 und 9 am 10.11.2026; danach meldet die
|
4.6.2 endet am 12.01.2027, .NET 8 und 9 am 10.11.2026; danach meldet die
|
||||||
Prüfung auch sie.
|
Prüfung auch sie. Die Daten liegen Prüfwerk bei
|
||||||
|
(`compliance-agent/data/eol/dotnet.json`); eine wöchentliche Prüfung gleicht
|
||||||
|
sie mit endoflife.date ab und legt bei Abweichungen ein Issue an.
|
||||||
|
|
||||||
**C#-Code (eigene Semgrep-Regeln).**
|
**C#-Code (eigene Semgrep-Regeln).**
|
||||||
|
|
||||||
|
|||||||
+111
-3
@@ -204,10 +204,109 @@ Copyleft-licensed dependencies can require you to release your source code under
|
|||||||
| Column | Description |
|
| Column | Description |
|
||||||
|--------|-------------|
|
|--------|-------------|
|
||||||
| **Lizenz** | License identifier |
|
| **Lizenz** | License identifier |
|
||||||
| **Art** | **Copyleft** or **Freizügig** (permissive) |
|
| **Art** | The category: **Freizügig**, **Schwaches Copyleft** (LGPL, MPL, EPL), **Starkes Copyleft** (GPL), **Netzwerk-Copyleft** (AGPL), **Proprietär / kommerziell**, **Gemeinfrei**, **Eigener Code** or **Unklar**, with how many of them were confirmed |
|
||||||
| **Pakete** | The packages using it |
|
| **Pakete** | The packages using it |
|
||||||
| **Anzahl** | Number of packages |
|
| **Anzahl** | Number of packages |
|
||||||
|
|
||||||
|
### Confirming a license
|
||||||
|
|
||||||
|
Where the scan finds no license (**Unknown**) or a wrong one, people with the
|
||||||
|
IT_ADMIN or USER role can confirm the license themselves; CXO and LEGAL can
|
||||||
|
read the confirmations (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
|
||||||
|
**Lizenz offen (unbekannt)** on the **Pakete** tab does the same).
|
||||||
|
2. Click **Bearbeiten** in a row, or tick several rows and click
|
||||||
|
**Lizenz bearbeiten** to confirm one license for all of them (for
|
||||||
|
example every library of your own company).
|
||||||
|
3. Choose **SPDX-Lizenz** and type its id or expression (`MIT`,
|
||||||
|
`Apache-2.0`, `MIT OR Apache-2.0`); the category follows from it. For a
|
||||||
|
license SPDX does not list, choose **Eigene oder kommerzielle Lizenz**,
|
||||||
|
give its name and pick the category; for a bought license also the
|
||||||
|
contract number and **Gültig bis**.
|
||||||
|
4. Optionally add the copyright holders (one per line), the license text, a
|
||||||
|
link to it, where you found it (a file in the repository, a contract, a
|
||||||
|
web page), whether the component is shipped with the product or only used
|
||||||
|
to build it, and a note.
|
||||||
|
5. **Für alle Versionen dieses Pakets** applies it to every version of the
|
||||||
|
package, now and in future scans; otherwise only to the listed version.
|
||||||
|
|
||||||
|
A confirmed license is kept apart from the scan results, so the next scan
|
||||||
|
does not undo it. The table shows it with a **bestätigt** badge (who and
|
||||||
|
when on hover), the license summary counts it instead of the detected one,
|
||||||
|
and **Bestätigung zurücknehmen** in the dialog withdraws it. The same
|
||||||
|
package in other targets gets it too.
|
||||||
|
|
||||||
|
::: info
|
||||||
|
The categories are guidance for reviewing your components, not legal advice.
|
||||||
|
:::
|
||||||
|
|
||||||
|
### 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=<target>`) 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
|
## Export
|
||||||
|
|
||||||
1. On the **Pakete** tab, select a target under **Alle Prüfobjekte**. Export
|
1. On the **Pakete** tab, select a target under **Alle Prüfobjekte**. Export
|
||||||
@@ -252,8 +351,17 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1:
|
|||||||
the homepage or repository its registry names, or the repository its
|
the homepage or repository its registry names, or the repository its
|
||||||
purl names. Never a person's name or email.
|
purl names. Never a person's name or email.
|
||||||
- Licenses are an SPDX id, an SPDX expression or a named license, marked
|
- Licenses are an SPDX id, an SPDX expression or a named license, marked
|
||||||
`acknowledgement: declared`: they are what the package declares, not a
|
`acknowledgement: declared`: they are what the package declares. A
|
||||||
licence Prüfwerk concluded.
|
license a person confirmed is written instead, marked
|
||||||
|
`acknowledgement: concluded` (a license of your own by name, with its text
|
||||||
|
and URL), with the copyright in `copyright` and the properties
|
||||||
|
`pruefwerk:license:category`, `pruefwerk:license:usage`,
|
||||||
|
`pruefwerk:license:contract`, `pruefwerk:license:valid_until`,
|
||||||
|
`pruefwerk:license:evidence`, `pruefwerk:license:concluded` (who and when)
|
||||||
|
and, where the scan found another one, `pruefwerk:license:declared`.
|
||||||
|
- In SPDX, a confirmed license is `licenseConcluded` (otherwise
|
||||||
|
`NOASSERTION`), with `copyrightText`; a license of your own is defined in
|
||||||
|
`hasExtractedLicensingInfos`.
|
||||||
- The known vulnerabilities are listed at the top level, each naming the
|
- The known vulnerabilities are listed at the top level, each naming the
|
||||||
components it affects. A vulnerability is listed once under its CVE
|
components it affects. A vulnerability is listed once under its CVE
|
||||||
(`source` NVD) when one is known, with its GitHub advisory under
|
(`source` NVD) when one is known, with its GitHub advisory under
|
||||||
|
|||||||
+4
-3
@@ -151,7 +151,7 @@ the current long term support release (the newest LTS supported for more than
|
|||||||
six months on the scan's date). It is CWE-1104 (unmaintained third-party
|
six months on the scan's date). It is CWE-1104 (unmaintained third-party
|
||||||
components).
|
components).
|
||||||
|
|
||||||
**The release table** (in `compliance-agent/src/pipeline/yocto_pins/release.rs`)
|
**The release table** (`compliance-agent/data/eol/yocto.json`)
|
||||||
is taken from the [Yocto Project releases wiki](https://wiki.yoctoproject.org/wiki/Releases)
|
is taken from the [Yocto Project releases wiki](https://wiki.yoctoproject.org/wiki/Releases)
|
||||||
(page last updated 2026-09-10), checked on **2026-10-09**. The wiki gives
|
(page last updated 2026-09-10), checked on **2026-10-09**. The wiki gives
|
||||||
months; the exact days are [endoflife.date's](https://endoflife.date/yocto),
|
months; the exact days are [endoflife.date's](https://endoflife.date/yocto),
|
||||||
@@ -178,8 +178,9 @@ Thud and older the end of life is the month of the last point release.
|
|||||||
| Wrynose | 6.0 | yes | 2026-05-13 | 2030-04-30 |
|
| Wrynose | 6.0 | yes | 2026-05-13 | 2030-04-30 |
|
||||||
|
|
||||||
Blacksail (6.1, due October 2026) is not in the table until it is released; a
|
Blacksail (6.1, due October 2026) is not in the table until it is released; a
|
||||||
layer on it reads as an unknown release. The table is updated by hand with
|
layer on it reads as an unknown release. The table is updated by hand; a
|
||||||
each Yocto release.
|
weekly check compares it with endoflife.date and opens an issue labelled
|
||||||
|
`eol-tables` when a release is added or a date changes.
|
||||||
|
|
||||||
## Recipe inventory
|
## Recipe inventory
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,283 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Compare the bundled end-of-life tables with endoflife.date.
|
||||||
|
|
||||||
|
The tables in compliance-agent/data/eol/ are what the lifecycle findings
|
||||||
|
judge by (Yocto releases, .NET target frameworks, the oldest patched Android
|
||||||
|
and iOS releases). This script fetches the matching endoflife.date products
|
||||||
|
and lists every difference: a release endoflife.date has and the table does
|
||||||
|
not, a changed release or end-of-life date, a changed LTS flag, a moved
|
||||||
|
platform floor.
|
||||||
|
|
||||||
|
With differences it opens one Gitea issue, or updates the open one (found by
|
||||||
|
its title), labelled "eol-tables". It never edits the tables: someone checks
|
||||||
|
the difference against the vendor's own page and updates the JSON.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
check-eol-tables.py [--data-dir DIR] [--dry-run]
|
||||||
|
|
||||||
|
Environment (not needed with --dry-run):
|
||||||
|
GITEA_TOKEN a token with issue write access on the repository
|
||||||
|
GITEA_API the API base, e.g. https://git.breakpilot.com/api/v1
|
||||||
|
GITEA_REPO owner/name, e.g. platform/pruefwerk
|
||||||
|
|
||||||
|
Exit status: 0 when the check ran (with or without differences), 1 when a
|
||||||
|
source could not be read or the issue could not be written.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import datetime as dt
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
ENDOFLIFE_API = "https://endoflife.date/api/{product}.json"
|
||||||
|
ISSUE_TITLE = "[eol-tables] Bundled end-of-life tables differ from endoflife.date"
|
||||||
|
LABEL = "eol-tables"
|
||||||
|
LABEL_COLOR = "fbca04"
|
||||||
|
TIMEOUT = 30
|
||||||
|
|
||||||
|
Cycle = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_json(url: str, token: str | None = None, method: str = "GET",
|
||||||
|
body: Any = None) -> Any:
|
||||||
|
"""GET (or send) JSON; raises on an HTTP or network error."""
|
||||||
|
data = None if body is None else json.dumps(body).encode()
|
||||||
|
request = urllib.request.Request(url, data=data, method=method)
|
||||||
|
request.add_header("Accept", "application/json")
|
||||||
|
request.add_header("User-Agent", "pruefwerk-eol-check")
|
||||||
|
if data is not None:
|
||||||
|
request.add_header("Content-Type", "application/json")
|
||||||
|
if token:
|
||||||
|
request.add_header("Authorization", f"token {token}")
|
||||||
|
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
|
||||||
|
text = response.read().decode()
|
||||||
|
return json.loads(text) if text.strip() else None
|
||||||
|
|
||||||
|
|
||||||
|
def cycles(product: str) -> list[Cycle]:
|
||||||
|
"""The release cycles endoflife.date lists for `product`."""
|
||||||
|
found: list[Cycle] = fetch_json(ENDOFLIFE_API.format(product=product))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def eol_date(cycle: Cycle) -> str | None:
|
||||||
|
"""The cycle's end of life as YYYY-MM-DD, None when it has no date."""
|
||||||
|
eol = cycle.get("eol")
|
||||||
|
return eol if isinstance(eol, str) else None
|
||||||
|
|
||||||
|
|
||||||
|
def is_supported(cycle: Cycle, today: dt.date) -> bool:
|
||||||
|
"""Whether the cycle still gets security updates on `today`."""
|
||||||
|
eol = cycle.get("eol")
|
||||||
|
if isinstance(eol, bool):
|
||||||
|
return not eol
|
||||||
|
return isinstance(eol, str) and dt.date.fromisoformat(eol) >= today
|
||||||
|
|
||||||
|
|
||||||
|
def compare_yocto(table: dict[str, Any], upstream: list[Cycle]) -> list[str]:
|
||||||
|
"""Differences between the bundled Yocto releases and endoflife.date."""
|
||||||
|
bundled = {r["codename"]: r for r in table["releases"]}
|
||||||
|
out: list[str] = []
|
||||||
|
for cycle in upstream:
|
||||||
|
codename = str(cycle.get("codename", "")).lower()
|
||||||
|
mine = bundled.get(codename)
|
||||||
|
name = f"Yocto {cycle.get('codename')} ({cycle['cycle']})"
|
||||||
|
if mine is None:
|
||||||
|
out.append(f"{name}: on endoflife.date (released {cycle.get('releaseDate')}, "
|
||||||
|
f"end of life {cycle.get('eol')}), not in the table")
|
||||||
|
continue
|
||||||
|
checks = [
|
||||||
|
("version", mine["version"], cycle["cycle"]),
|
||||||
|
("LTS", mine["lts"], bool(cycle.get("lts"))),
|
||||||
|
("release date", mine["released"], cycle.get("releaseDate")),
|
||||||
|
("end of life", mine["end_of_life"], eol_date(cycle)),
|
||||||
|
]
|
||||||
|
out.extend(f"{name}: {what} is {theirs} on endoflife.date, {ours} in the table"
|
||||||
|
for what, ours, theirs in checks if ours != theirs)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def dotnet_cycle(moniker: str) -> tuple[str, str] | None:
|
||||||
|
"""The endoflife.date product and cycle of a target framework moniker."""
|
||||||
|
if moniker.startswith("netcoreapp"):
|
||||||
|
return "dotnet", moniker.removeprefix("netcoreapp")
|
||||||
|
rest = moniker.removeprefix("net")
|
||||||
|
if "." in rest:
|
||||||
|
return "dotnet", rest.split(".")[0]
|
||||||
|
if rest == "35":
|
||||||
|
return "dotnetfx", "3.5-sp1"
|
||||||
|
if rest in ("11", "20", "30"):
|
||||||
|
# .NET Framework 1.1 to 3.0 are not on endoflife.date.
|
||||||
|
return None
|
||||||
|
return "dotnetfx", ".".join(rest)
|
||||||
|
|
||||||
|
|
||||||
|
def compare_dotnet(table: dict[str, Any], upstream: dict[str, list[Cycle]]) -> list[str]:
|
||||||
|
"""Differences between the bundled .NET table and endoflife.date."""
|
||||||
|
out: list[str] = []
|
||||||
|
bundled: dict[tuple[str, str], dict[str, Any]] = {}
|
||||||
|
for framework in table["frameworks"]:
|
||||||
|
key = dotnet_cycle(framework["moniker"])
|
||||||
|
if key is not None:
|
||||||
|
bundled.setdefault(key, framework)
|
||||||
|
for product, product_cycles in upstream.items():
|
||||||
|
for cycle in product_cycles:
|
||||||
|
mine = bundled.get((product, cycle["cycle"]))
|
||||||
|
theirs = eol_date(cycle)
|
||||||
|
label = f"{product} {cycle['cycle']}"
|
||||||
|
if mine is None:
|
||||||
|
if theirs is not None:
|
||||||
|
out.append(f"{label}: end of support {theirs} on endoflife.date, "
|
||||||
|
"not in the table")
|
||||||
|
elif mine["end_of_support"] != theirs:
|
||||||
|
out.append(f"{label} ({mine['moniker']}): end of support is {theirs} on "
|
||||||
|
f"endoflife.date, {mine['end_of_support']} in the table")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def oldest_supported(product_cycles: list[Cycle], today: dt.date, key: str) -> int | None:
|
||||||
|
"""The smallest `key` (as a whole number) of the cycles still supported."""
|
||||||
|
values = [int(float(c[key])) for c in product_cycles
|
||||||
|
if c.get(key) is not None and is_supported(c, today)]
|
||||||
|
return min(values) if values else None
|
||||||
|
|
||||||
|
|
||||||
|
def compare_platforms(table: dict[str, Any], android: list[Cycle], ios: list[Cycle],
|
||||||
|
today: dt.date) -> list[str]:
|
||||||
|
"""Differences between the bundled platform floors and endoflife.date."""
|
||||||
|
out: list[str] = []
|
||||||
|
api = oldest_supported(android, today, "apiVersion")
|
||||||
|
ours = table["android"]["oldest_patched_api"]
|
||||||
|
if api is not None and api != ours:
|
||||||
|
out.append(f"Android: the oldest release with security updates is API {api} on "
|
||||||
|
f"endoflife.date, API {ours} in the table")
|
||||||
|
major = oldest_supported(ios, today, "cycle")
|
||||||
|
ours_ios = int(table["ios"]["oldest_patched"].split(".")[0])
|
||||||
|
if major is not None and major != ours_ios:
|
||||||
|
out.append(f"iOS: the oldest release with security updates is iOS {major} on "
|
||||||
|
f"endoflife.date, iOS {ours_ios} in the table")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def load(data_dir: Path, name: str) -> dict[str, Any]:
|
||||||
|
"""A bundled table."""
|
||||||
|
table: dict[str, Any] = json.loads((data_dir / name).read_text())
|
||||||
|
return table
|
||||||
|
|
||||||
|
|
||||||
|
def differences(data_dir: Path, today: dt.date) -> dict[str, list[str]]:
|
||||||
|
"""Every difference, by table file."""
|
||||||
|
dotnet = load(data_dir, "dotnet.json")
|
||||||
|
platforms = load(data_dir, "platforms.json")
|
||||||
|
return {
|
||||||
|
"yocto.json": compare_yocto(load(data_dir, "yocto.json"), cycles("yocto")),
|
||||||
|
"dotnet.json": compare_dotnet(
|
||||||
|
dotnet, {p: cycles(p) for p in dotnet["endoflife_products"]}),
|
||||||
|
"platforms.json": compare_platforms(
|
||||||
|
platforms, cycles(platforms["android"]["endoflife_product"]),
|
||||||
|
cycles(platforms["ios"]["endoflife_product"]), today),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def issue_body(diff: dict[str, list[str]], today: dt.date) -> str:
|
||||||
|
"""The issue text for `diff`."""
|
||||||
|
lines = [
|
||||||
|
"The weekly check (`scripts/check-eol-tables.py`) found the bundled end-of-life "
|
||||||
|
"tables in `compliance-agent/data/eol/` differ from endoflife.date. Check each "
|
||||||
|
"against the vendor's own page, update the JSON (and its `checked_on`), and "
|
||||||
|
"close this issue with that PR.",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
for file, found in diff.items():
|
||||||
|
if found:
|
||||||
|
lines.append(f"### `{file}`")
|
||||||
|
lines.extend(f"- {line}" for line in found)
|
||||||
|
lines.append("")
|
||||||
|
lines.append(f"Last checked: {today.isoformat()}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def without_check_date(body: str) -> str:
|
||||||
|
"""`body` without its "Last checked" line, to see whether the diff changed."""
|
||||||
|
return "\n".join(
|
||||||
|
line for line in body.splitlines() if not line.startswith("Last checked:"))
|
||||||
|
|
||||||
|
|
||||||
|
def label_id(api: str, token: str) -> int | None:
|
||||||
|
"""The id of the issue label, created if missing; None if that fails."""
|
||||||
|
try:
|
||||||
|
labels = fetch_json(f"{api}/labels?limit=100", token)
|
||||||
|
found = next((label["id"] for label in labels if label["name"] == LABEL), None)
|
||||||
|
if found is not None:
|
||||||
|
return int(found)
|
||||||
|
created = fetch_json(f"{api}/labels", token, "POST",
|
||||||
|
{"name": LABEL, "color": f"#{LABEL_COLOR}",
|
||||||
|
"description": "Bundled end-of-life tables need an update"})
|
||||||
|
return int(created["id"])
|
||||||
|
except urllib.error.URLError as error:
|
||||||
|
print(f"::warning::label {LABEL} not available ({error}); the issue is unlabelled")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def file_issue(body: str, token: str, api_base: str, repo: str) -> None:
|
||||||
|
"""Open the issue, or update the open one when the differences changed."""
|
||||||
|
api = f"{api_base.rstrip('/')}/repos/{repo}"
|
||||||
|
query = urllib.parse.quote(ISSUE_TITLE)
|
||||||
|
open_issues = fetch_json(f"{api}/issues?state=open&type=issues&q={query}", token)
|
||||||
|
existing = next((i for i in open_issues if i["title"] == ISSUE_TITLE), None)
|
||||||
|
if existing is None:
|
||||||
|
label = label_id(api, token)
|
||||||
|
payload = {"title": ISSUE_TITLE, "body": body,
|
||||||
|
"labels": [label] if label is not None else []}
|
||||||
|
created = fetch_json(f"{api}/issues", token, "POST", payload)
|
||||||
|
print(f"opened issue #{created['number']}")
|
||||||
|
elif without_check_date(existing.get("body") or "") != without_check_date(body):
|
||||||
|
fetch_json(f"{api}/issues/{existing['number']}", token, "PATCH", {"body": body})
|
||||||
|
print(f"updated issue #{existing['number']}")
|
||||||
|
else:
|
||||||
|
print(f"issue #{existing['number']} already lists these differences")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument("--data-dir", type=Path,
|
||||||
|
default=Path(__file__).resolve().parent.parent
|
||||||
|
/ "compliance-agent/data/eol")
|
||||||
|
parser.add_argument("--dry-run", action="store_true",
|
||||||
|
help="print the differences, write no issue")
|
||||||
|
args = parser.parse_args()
|
||||||
|
today = dt.date.today()
|
||||||
|
try:
|
||||||
|
diff = differences(args.data_dir, today)
|
||||||
|
except (urllib.error.URLError, OSError, ValueError, KeyError) as error:
|
||||||
|
print(f"::error::could not compare the tables: {error}")
|
||||||
|
return 1
|
||||||
|
if not any(diff.values()):
|
||||||
|
print("the bundled end-of-life tables match endoflife.date")
|
||||||
|
return 0
|
||||||
|
body = issue_body(diff, today)
|
||||||
|
print(body)
|
||||||
|
if args.dry_run:
|
||||||
|
return 0
|
||||||
|
token = os.environ.get("GITEA_TOKEN", "")
|
||||||
|
if not token:
|
||||||
|
print("::warning::GITEA_TOKEN is not set; not writing the issue")
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
file_issue(body, token, os.environ["GITEA_API"], os.environ["GITEA_REPO"])
|
||||||
|
except (urllib.error.URLError, KeyError) as error:
|
||||||
|
print(f"::error::could not write the issue: {error}")
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Offline tests of check-eol-tables.py: python3 -m unittest discover -s scripts."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime as dt
|
||||||
|
import importlib.util
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
SPEC = importlib.util.spec_from_file_location(
|
||||||
|
"check_eol_tables", Path(__file__).with_name("check-eol-tables.py"))
|
||||||
|
assert SPEC is not None and SPEC.loader is not None
|
||||||
|
check = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(check)
|
||||||
|
|
||||||
|
TODAY = dt.date(2026, 10, 9)
|
||||||
|
|
||||||
|
|
||||||
|
class CompareTests(unittest.TestCase):
|
||||||
|
def test_yocto_new_release_and_changed_dates_are_listed(self) -> None:
|
||||||
|
table = {"releases": [{"codename": "wrynose", "version": "6.0", "lts": True,
|
||||||
|
"released": "2026-05-13", "end_of_life": "2030-04-30"}]}
|
||||||
|
upstream: list[dict[str, object]] = [
|
||||||
|
{"cycle": "6.1", "codename": "Blacksail", "releaseDate": "2026-10-20",
|
||||||
|
"eol": "2027-04-30"},
|
||||||
|
{"cycle": "6.0", "codename": "Wrynose", "lts": True,
|
||||||
|
"releaseDate": "2026-05-13", "eol": "2030-05-31"},
|
||||||
|
]
|
||||||
|
found = check.compare_yocto(table, upstream)
|
||||||
|
self.assertEqual(len(found), 2)
|
||||||
|
self.assertIn("Blacksail (6.1): on endoflife.date", found[0])
|
||||||
|
self.assertIn("end of life is 2030-05-31 on endoflife.date, 2030-04-30", found[1])
|
||||||
|
same = [{**upstream[1], "eol": "2030-04-30"}]
|
||||||
|
self.assertEqual(check.compare_yocto(table, same), [])
|
||||||
|
|
||||||
|
def test_dotnet_monikers_map_to_endoflife_cycles(self) -> None:
|
||||||
|
self.assertEqual(check.dotnet_cycle("net8.0"), ("dotnet", "8"))
|
||||||
|
self.assertEqual(check.dotnet_cycle("netcoreapp3.1"), ("dotnet", "3.1"))
|
||||||
|
self.assertEqual(check.dotnet_cycle("net462"), ("dotnetfx", "4.6.2"))
|
||||||
|
self.assertEqual(check.dotnet_cycle("net35"), ("dotnetfx", "3.5-sp1"))
|
||||||
|
self.assertIsNone(check.dotnet_cycle("net20"))
|
||||||
|
table = {"frameworks": [{"moniker": "net8.0", "end_of_support": "2026-11-10",
|
||||||
|
"product": ".NET 8"}]}
|
||||||
|
upstream = {"dotnet": [{"cycle": "8", "eol": "2026-11-10"},
|
||||||
|
{"cycle": "11", "eol": "2029-11-13"},
|
||||||
|
{"cycle": "12", "eol": False}]}
|
||||||
|
self.assertEqual(check.compare_dotnet(table, upstream),
|
||||||
|
["dotnet 11: end of support 2029-11-13 on endoflife.date, "
|
||||||
|
"not in the table"])
|
||||||
|
|
||||||
|
def test_platform_floors_are_the_oldest_supported_release(self) -> None:
|
||||||
|
table = {"android": {"oldest_patched_api": 29}, "ios": {"oldest_patched": "15.0"}}
|
||||||
|
android = [{"cycle": "14", "apiVersion": "34", "eol": False},
|
||||||
|
{"cycle": "13", "apiVersion": "33", "eol": "2026-03-02"}]
|
||||||
|
ios = [{"cycle": "16", "eol": False}, {"cycle": "15", "eol": False},
|
||||||
|
{"cycle": "14", "eol": "2021-10-26"}]
|
||||||
|
found = check.compare_platforms(table, android, ios, TODAY)
|
||||||
|
self.assertEqual(found, ["Android: the oldest release with security updates is "
|
||||||
|
"API 34 on endoflife.date, API 29 in the table"])
|
||||||
|
|
||||||
|
def test_the_issue_is_updated_only_when_the_differences_change(self) -> None:
|
||||||
|
body = check.issue_body({"yocto.json": ["a"], "dotnet.json": []}, TODAY)
|
||||||
|
self.assertIn("### `yocto.json`", body)
|
||||||
|
self.assertNotIn("dotnet.json", body)
|
||||||
|
later = check.issue_body({"yocto.json": ["a"]}, dt.date(2026, 10, 16))
|
||||||
|
self.assertEqual(check.without_check_date(body), check.without_check_date(later))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user