You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by jd...@apache.org on 2026/10/20 22:01:38 UTC
(grails-intellij-plugin) 01/01: Replace the Sonatype scan plugin with our own scanner, and ship an SBOM
This is an automated email from the ASF dual-hosted git repository.
jdaugherty pushed a commit to branch vulnerability-scan
in repository https://gitbox.apache.org/repos/asf/grails-intellij-plugin.git
commit 9efc72801b4021debfb63342ed85df276013a279
Author: James Daugherty <jd...@jdresources.net>
AuthorDate: Tue Oct 20 18:00:35 2026 -0400
Replace the Sonatype scan plugin with our own scanner, and ship an SBOM
The Sonatype scan-gradle-plugin's ossIndexAudit task is marked incompatible
with the configuration cache, so every build that ran it discarded the cache
entry. Replace it with a port of grails-core's build-logic/vulnerability-scan,
as this build's own code in org.apache.grails.intellij.build.scan:
- vulnerabilityScan looks every project's resolved runtimeClasspath and
compileClasspath up in OSV and, when SONATYPE_GUIDE_USERNAME and
SONATYPE_GUIDE_TOKEN are set, Sonatype Guide. The credentials are read when
the scan runs, so they never enter the configuration cache entry, and the
answers are cached in the Gradle user home for an hour, in the directory
grails-core uses.
- vulnerabilityScanReport, on the root project, summarizes every project's
scan in Markdown, including failed scans and exclusions that no longer
match anything.
- The IntelliJ Platform's own bundledModule/bundledPlugin components are left
out of the scan, since no database knows them. java-legacy projects and
libs/testFramework scan runtimeClasspath only: their compile-only
dependencies are era-pinned stubs or JetBrains' test-framework jars, never
shipped.
- The workflow keeps its weekly run, and a committer can now opt a pull
request in with the "vulnerability scan" label, which posts the summary as
a sticky comment.
Add a CycloneDX SBOM, as grails-core ships for its jars: the sbom task makes
the CycloneDX output reproducible (epoch or SOURCE_DATE_EPOCH timestamp,
content-derived serial number, sorted dependencies) and records each
dependency under the one license SbomLicensePolicy picks for it, failing on a
license ASF policy does not permit. The plugin ZIP carries it as sbom.json
next to LICENSE and NOTICE, and the composed jar as META-INF/sbom.json with
Sbom-Location and Sbom-Format manifest attributes.
Both are covered by TestKit tests against stubs of the OSV and Sonatype Guide
APIs and a local Maven repository, with the configuration cache on and its
problems fatal.
---
.github/scripts/postStickyComment.sh | 60 +++
.github/scripts/vulnerabilityReport.sh | 42 ++
.github/workflows/vulnerability-scan.yml | 106 +++--
AGENTS.md | 22 +
IMPROVEMENT-PLAN.md | 6 +-
README.md | 6 +-
RELEASE.md | 5 +-
build-logic/README.md | 32 +-
build-logic/build.gradle | 12 +-
....grails.intellij.build.intellij-platform.gradle | 14 +
...he.grails.intellij.build.intellij-plugin.gradle | 21 +
...apache.grails.intellij.build.java-legacy.gradle | 8 +
.../org.apache.grails.intellij.build.sbom.gradle | 120 ++++++
...intellij.build.vulnerability-scan-report.gradle | 47 +++
...grails.intellij.build.vulnerability-scan.gradle | 132 +++---
.../build/sbom/ReproducibleSbomTask.groovy | 138 ++++++
.../SbomExtension.groovy} | 25 +-
.../intellij/build/sbom/SbomLicensePolicy.groovy | 127 ++++++
.../grails/intellij/build/scan/ApiCache.groovy | 132 ++++++
.../grails/intellij/build/scan/ApiClient.groovy | 151 +++++++
.../intellij/build/scan/BuiltInExclusions.groovy | 42 ++
.../grails/intellij/build/scan/CvssV3.groovy | 95 +++++
.../build/scan/OsvVulnerabilityService.groovy | 196 +++++++++
.../scan/SonatypeGuideVulnerabilityService.groovy | 238 +++++++++++
.../build/scan/VulnerabilityExclusion.groovy | 67 +++
.../build/scan/VulnerabilityScanExtension.groovy | 60 +++
.../build/scan/VulnerabilityScanReportTask.groovy | 232 ++++++++++
.../build/scan/VulnerabilityScanTask.groovy | 415 ++++++++++++++++++
.../build/sbom/ReproducibleSbomTaskTest.groovy | 118 ++++++
.../build/sbom/SbomLicensePolicyTest.groovy | 82 ++++
.../intellij/build/sbom/SbomPluginTest.groovy | 174 ++++++++
.../grails/intellij/build/scan/CvssV3Test.groovy | 61 +++
.../grails/intellij/build/scan/OsvStub.groovy | 135 ++++++
.../build/scan/OsvVulnerabilityServiceTest.groovy | 167 ++++++++
.../intellij/build/scan/SonatypeGuideStub.groovy | 126 ++++++
.../SonatypeGuideVulnerabilityServiceTest.groovy | 185 ++++++++
.../build/scan/VulnerabilityExclusionTest.groovy | 71 ++++
.../build/scan/VulnerabilityScanPluginTest.groovy | 467 +++++++++++++++++++++
.../scan/VulnerabilityScanReportTaskTest.groovy | 133 ++++++
.../build/scan/VulnerabilityScanTaskTest.groovy | 94 +++++
build.gradle | 6 +-
libs/testFramework/build.gradle | 10 +
42 files changed, 4279 insertions(+), 101 deletions(-)
diff --git a/.github/scripts/postStickyComment.sh b/.github/scripts/postStickyComment.sh
new file mode 100755
index 0000000..fac252d
--- /dev/null
+++ b/.github/scripts/postStickyComment.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+# Creates a comment on a pull request, or updates the one a previous run left behind, so a
+# workflow that runs repeatedly on the same pull request keeps a single up to date comment
+# instead of appending a new one each time. The comment is identified by an HTML marker
+# written as its first line. Ported from grails-core.
+#
+# Usage: postStickyComment.sh <pull-request-number> <marker> <body-file>
+#
+# Requires the `gh` CLI, a GH_TOKEN with `pull-requests: write`, and GITHUB_REPOSITORY.
+
+set -euo pipefail
+
+PR_NUMBER="${1:?pull request number is required}"
+MARKER="${2:?comment marker is required}"
+BODY_FILE="${3:?path to the comment body is required}"
+
+REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is not set}"
+
+FULL_BODY_FILE=$(mktemp)
+trap 'rm -f "$FULL_BODY_FILE"' EXIT
+{
+ printf '%s\n\n' "$MARKER"
+ cat "$BODY_FILE"
+} > "$FULL_BODY_FILE"
+
+# Match on the marker rather than on the comment author so a run cannot adopt an unrelated
+# comment the same bot left on the pull request.
+EXISTING_IDS=$(gh api --paginate "repos/${REPO}/issues/${PR_NUMBER}/comments" \
+ --jq "[.[] | select((.body // \"\") | startswith(\"${MARKER}\")) | .id] | .[]")
+EXISTING_ID=$(printf '%s\n' "$EXISTING_IDS" | head -n 1)
+
+if [ -n "$EXISTING_ID" ]; then
+ echo "Updating existing comment ${EXISTING_ID} on pull request #${PR_NUMBER}"
+ jq -n --rawfile body "$FULL_BODY_FILE" '{body: $body}' \
+ | gh api -X PATCH "repos/${REPO}/issues/comments/${EXISTING_ID}" --input - --silent
+else
+ echo "Creating comment on pull request #${PR_NUMBER}"
+ jq -n --rawfile body "$FULL_BODY_FILE" '{body: $body}' \
+ | gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" --input - --silent
+fi
diff --git a/.github/scripts/vulnerabilityReport.sh b/.github/scripts/vulnerabilityReport.sh
new file mode 100755
index 0000000..4c1dbe4
--- /dev/null
+++ b/.github/scripts/vulnerabilityReport.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+# Prints the Markdown summary the `vulnerabilityScanReport` task wrote, under a heading, to
+# stdout. Shared by the job summary and the pull request comment so both present the scan
+# identically. Ported from grails-core.
+#
+# Usage: vulnerabilityReport.sh <title> [summary]
+#
+# title heading text for the report
+# summary the summary the task wrote; build/reports/vulnerability-scan/summary.md by default
+
+set -uo pipefail
+
+TITLE="${1:?report title is required}"
+SUMMARY="${2:-build/reports/vulnerability-scan/summary.md}"
+
+echo "## ${TITLE}"
+
+if [ -s "$SUMMARY" ]; then
+ cat "$SUMMARY"
+else
+ echo 'ā The scan did not produce a report; see the workflow run for the log.'
+fi
diff --git a/.github/workflows/vulnerability-scan.yml b/.github/workflows/vulnerability-scan.yml
index 3aa21c5..0587143 100644
--- a/.github/workflows/vulnerability-scan.yml
+++ b/.github/workflows/vulnerability-scan.yml
@@ -19,13 +19,17 @@ on:
# Run every Monday at 03:00 UTC
- cron: '0 3 * * 1'
workflow_dispatch:
-# Do not scan concurrently; OSS Index has per-account rate limits
+ # Opt in per pull request by applying the "vulnerability scan" label. Applying a label
+ # requires write access, so only a committer can start a scan.
+ pull_request:
+ types: [labeled, synchronize, reopened]
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: false
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
scan:
- name: "OSS Index Scan"
+ name: "Vulnerability Scan"
+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -44,39 +48,71 @@ jobs:
uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
with:
cache-provider: basic # 'basic' uses the MIT-licensed, open-source cache provider; the default 'enhanced' provider (v6+) is proprietary (Gradle commercial Terms of Use)
- - name: "š Run OSS Index Vulnerability Scan"
+ - name: "š Run Vulnerability Scan"
+ # Looks up every resolved dependency in the OSV database (https://osv.dev) and in Sonatype Guide.
+ # --continue lets the summary report the projects whose scan failed.
env:
SONATYPE_GUIDE_USERNAME: ${{ secrets.SONATYPE_GUIDE_USERNAME }}
SONATYPE_GUIDE_TOKEN: ${{ secrets.SONATYPE_GUIDE_TOKEN }}
- continue-on-error: true
- id: scan
- run: ./gradlew ossIndexAudit --continue --info 2>&1 | tee /tmp/ossindex-scan.log; exit ${PIPESTATUS[0]}
+ run: ./gradlew vulnerabilityScan vulnerabilityScanReport --continue
- name: "š Publish Vulnerability Summary"
if: always()
- run: |
- echo "## š OSS Index Vulnerability Scan" >> $GITHUB_STEP_SUMMARY
- if [ "${{ steps.scan.outcome }}" = "success" ]; then
- echo "ā
No vulnerabilities found." >> $GITHUB_STEP_SUMMARY
- else
- echo "ā Vulnerabilities detected." >> $GITHUB_STEP_SUMMARY
- echo "" >> $GITHUB_STEP_SUMMARY
- echo '```' >> $GITHUB_STEP_SUMMARY
- awk '
- BEGIN { in_section=0; in_vuln=0 }
- { gsub(/\033\[[0-9;]*m/, "") }
- /^##\[ossIndexAudit:begin\]/ { in_section=1; next }
- /^##\[ossIndexAudit:end\]/ { in_section=0; in_vuln=0; next }
- !in_section { next }
- /^\[[0-9]+\/[0-9]+\] - pkg:maven\// {
- sub(/^\[[0-9]+\/[0-9]+\] - /, "")
- if (!seen_coord[$0]++) { print ""; print }
- next
- }
- /^ Vulnerability Title:/ { in_vuln=1; block=$0 "\n"; cve_id=""; next }
- in_vuln && /^ CVE:/ { match($0,/CVE-[0-9-]+/); if (RSTART) cve_id=substr($0,RSTART,RLENGTH); block=block $0 "\n"; next }
- in_vuln && /^ Reference:/ { block=block $0 "\n"; if (cve_id && !seen_cve[cve_id]++) printf "%s",block; in_vuln=0; next }
- in_vuln { block=block $0 "\n" }
- ' /tmp/ossindex-scan.log >> $GITHUB_STEP_SUMMARY \
- || echo "(no scan output captured ā check the full log)" >> $GITHUB_STEP_SUMMARY
- echo '```' >> $GITHUB_STEP_SUMMARY
- fi
+ run: >
+ .github/scripts/vulnerabilityReport.sh
+ 'š Vulnerability Scan'
+ >> "$GITHUB_STEP_SUMMARY"
+
+ scan-pull-request:
+ name: "Vulnerability Scan - pull request"
+ # `synchronize` and `reopened` re-scan a pull request that already carries the label.
+ if: >-
+ github.event_name == 'pull_request'
+ && contains(github.event.pull_request.labels.*.name, 'vulnerability scan')
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - name: "š„ Checkout pull request"
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - name: "š Read JDK version from .sdkmanrc"
+ id: sdkmanrc
+ run: echo "java=$(grep -E '^java=' .sdkmanrc | cut -d= -f2 | sed 's/-librca$//')" >> "$GITHUB_OUTPUT"
+ - name: "āļø Setup JDK"
+ uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
+ with:
+ distribution: liberica # .sdkmanrc pins librca = Liberica
+ java-version: ${{ steps.sdkmanrc.outputs.java }}
+ - name: "š Setup Gradle"
+ uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0
+ with:
+ cache-provider: basic # 'basic' uses the MIT-licensed, open-source cache provider; the default 'enhanced' provider (v6+) is proprietary (Gradle commercial Terms of Use)
+ - name: "š Run Vulnerability Scan"
+ # GitHub withholds secrets from a pull request raised by a fork, so its scan consults OSV only,
+ # and the report says Sonatype Guide was not consulted.
+ # 60000 bytes keeps the whole summary, with the marker and heading the scripts add to it, clear of
+ # GitHub's 65536 character comment limit.
+ env:
+ SONATYPE_GUIDE_USERNAME: ${{ secrets.SONATYPE_GUIDE_USERNAME }}
+ SONATYPE_GUIDE_TOKEN: ${{ secrets.SONATYPE_GUIDE_TOKEN }}
+ run: ./gradlew vulnerabilityScan vulnerabilityScanReport --continue -PvulnerabilityScan.reportMaxBytes=60000
+ - name: "š Build Vulnerability Report"
+ if: always()
+ run: >
+ .github/scripts/vulnerabilityReport.sh
+ 'š Vulnerability Scan - pull request'
+ > /tmp/vulnerability-report.md
+ - name: "š Publish Vulnerability Summary"
+ if: always()
+ run: cat /tmp/vulnerability-report.md >> "$GITHUB_STEP_SUMMARY"
+ - name: "š¬ Comment Vulnerability Report"
+ # A pull request from a fork runs with a read-only token, which cannot comment;
+ # its report is in the job summary instead.
+ if: always() && github.event.pull_request.head.repo.full_name == github.repository
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: >
+ .github/scripts/postStickyComment.sh
+ '${{ github.event.pull_request.number }}'
+ '<!-- grails-vulnerability-scan -->'
+ /tmp/vulnerability-report.md
diff --git a/AGENTS.md b/AGENTS.md
index aaf689b..8a489b5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -39,6 +39,13 @@ limitations under the License.
./gradlew rat
./gradlew runIde
+# Dependency vulnerability scan (OSV; plus Sonatype Guide when SONATYPE_GUIDE_USERNAME and
+# SONATYPE_GUIDE_TOKEN are set) and its Markdown summary in build/reports/vulnerability-scan/
+./gradlew vulnerabilityScan vulnerabilityScanReport --continue
+
+# The CycloneDX SBOM that ships in the plugin ZIP (runs whenever the plugin jar is built)
+./gradlew :plugin:sbom
+
# GitHub Actions policy: every `uses:` must be on the ASF approved list (needs network)
./gradlew validateActions
@@ -240,6 +247,21 @@ files under it, so *Reveal in Project View* dead-ended.
- The legacy plugin id `org.intellij.grails` is grandfathered on Marketplace and
permanent for the existing listing (see `IMPROVEMENT-PLAN.md`); the `TemplateWordInPluginId` check is muted
deliberately.
+- **Vulnerability scan and SBOM are this build's own code**, in `build-logic` under
+ `org.apache.grails.intellij.build.scan` and `.sbom`, ported from grails-core (the Sonatype
+ scan-gradle-plugin it replaced was incompatible with the configuration cache and discarded the
+ entry of every build that ran it). `vulnerabilityScan` looks `runtimeClasspath` and
+ `compileClasspath` up in OSV and Sonatype Guide; the `intellij-platform` convention sets
+ `vulnerabilityScan.ignoredGroups` so the IDE's own `bundledModule:`/`bundledPlugin:` components
+ are not looked up, and `java-legacy` projects and `libs/testFramework` scan `runtimeClasspath`
+ only because their compile-only dependencies are era-pinned stubs or JetBrains' test-framework
+ jars, never shipped. An exclusion needs a reason and a removal condition (`BuiltInExclusions`,
+ or `vulnerabilityScan { exclude(...) }` in one project); the summary lists exclusions that no
+ longer match. The `sbom` task writes a reproducible CycloneDX SBOM (epoch timestamp,
+ content-derived serial number, one license per dependency as `SbomLicensePolicy` picks it) into
+ the plugin ZIP root as `sbom.json` and the composed jar as `META-INF/sbom.json`; the jar
+ depends on it, so a dependency under a license ASF policy does not permit fails any build that
+ packages the jar. See `build-logic/README.md`.
- **Coverage needs two non-default JaCoCo settings** (both in the `jacoco` and
`coverage-aggregation` convention plugins): the tests load the plugin from the sandbox jars,
which are built from the *instrumented* classes, so reports must analyse
diff --git a/IMPROVEMENT-PLAN.md b/IMPROVEMENT-PLAN.md
index 9ede873..45d7318 100644
--- a/IMPROVEMENT-PLAN.md
+++ b/IMPROVEMENT-PLAN.md
@@ -52,8 +52,10 @@ the phases below target the **new** plugin; the legacy plugin receives only Phas
## Optional ASF Follow-Up (Both Plugin Lines)
-- [ ] Generate a CycloneDX SBOM with a `LICENSE_MAPPING` for transitive dependencies
- (grails-core parity). This is not a blocker for the first compliant release.
+- [x] Generate a CycloneDX SBOM with a `LICENSE_MAPPING` for transitive dependencies
+ (grails-core parity). Done: the `sbom` convention plugin writes a reproducible SBOM
+ into the plugin ZIP (`sbom.json`) and the composed jar (`META-INF/sbom.json`), with the
+ license policy in `SbomLicensePolicy`.
---
diff --git a/README.md b/README.md
index f1daf56..f8519e6 100644
--- a/README.md
+++ b/README.md
@@ -129,7 +129,11 @@ To build a specific version rather than the default in `gradle.properties`:
./gradlew rat # Apache RAT license audit
./gradlew runIde # launch a sandbox IDE with the plugin installed
./gradlew testCodeCoverageReport # aggregate JaCoCo coverage report
-./gradlew ossIndexAudit # Sonatype OSS Index vulnerability scan (needs SONATYPE_GUIDE_TOKEN)
+./gradlew vulnerabilityScan vulnerabilityScanReport --continue
+ # dependency vulnerability scan against OSV (and Sonatype Guide when
+ # SONATYPE_GUIDE_USERNAME/SONATYPE_GUIDE_TOKEN are set), summarised in
+ # build/reports/vulnerability-scan/summary.md
+./gradlew :plugin:sbom # the CycloneDX SBOM that ships in the plugin ZIP
```
To confirm the build is reproducible, see
diff --git a/RELEASE.md b/RELEASE.md
index 36a695f..0b77414 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -217,7 +217,10 @@ from a key the PMC published to the release dist area), then checks the contents
- **Binary distribution** must carry `LICENSE` and `NOTICE` at the root of the plugin
directory ā the ZIP is the unit being distributed, and ASF policy requires both files in
every unit of distribution regardless of its format ā as well as `META-INF/LICENSE`,
- `META-INF/NOTICE`, and `META-INF/plugin.xml` inside the composed plugin jar.
+ `META-INF/NOTICE`, and `META-INF/plugin.xml` inside the composed plugin jar. The ZIP also
+ carries the CycloneDX SBOM, as `sbom.json` next to `LICENSE` and as `META-INF/sbom.json` in
+ the composed jar; it is reproducible like the rest of the archive, but it is not a policy
+ requirement and the verifier does not check it.
- **`LICENSE` and `NOTICE` contents**, in both archives: `LICENSE` must be the Apache
License 2.0 (title, version line, and end of the terms), and `NOTICE` must name *Apache
Grails IntelliJ Plugin* and carry the ASF copyright line. A file that is present but
diff --git a/build-logic/README.md b/build-logic/README.md
index ab42a9d..adfc6ff 100644
--- a/build-logic/README.md
+++ b/build-logic/README.md
@@ -13,7 +13,7 @@ from `settings.gradle`. That is what keeps repository declarations out of the pr
## Why plugin versions live here
-`build-logic/build.gradle` declares the IntelliJ Platform, Kotlin, RAT and Sonatype scan plugins as
+`build-logic/build.gradle` declares the IntelliJ Platform, Kotlin, RAT and CycloneDX plugins as
`implementation` dependencies. That is what lets the convention plugins apply them **without a
version**, and it removes the previous fragility where `org.jetbrains.intellij.platform.module` was
applied version-free in every module and resolved only by inheriting the root build script's plugin
@@ -41,14 +41,42 @@ build still come from the root `gradle.properties` via `providers.gradleProperty
| `rat` | root only ā the licence audit |
| `coverage-aggregation` | root only ā cross-project JaCoCo |
| `validate-actions` | root only ā `validateActions`, the ASF approved-actions check on `.github/workflows` |
+| `vulnerability-scan-report` | root only ā `vulnerabilityScanReport`, the Markdown summary of every project's scan at `build/reports/vulnerability-scan/summary.md` |
+| `sbom` | the plugin project (via `intellij-plugin`) ā `sbom`, the reproducible CycloneDX SBOM packaged into the ZIP and the composed jar |
| `reproducible`, `jacoco`, `vulnerability-scan` | applied transitively |
| `repositories` | **settings** plugin ā applied from `settings.gradle`, not by a project |
+## Vulnerability scan
+
+`vulnerability-scan` (applied by `java`, so by every project that compiles) registers
+`vulnerabilityScan`, which looks the resolved `runtimeClasspath` and `compileClasspath` up in the
+[OSV](https://osv.dev) database and, when `SONATYPE_GUIDE_USERNAME` and `SONATYPE_GUIDE_TOKEN` are
+set, in Sonatype Guide. The scanner is this build's own code in `org.apache.grails.intellij.build.scan`,
+ported from grails-core's `build-logic/vulnerability-scan`; it replaced the Sonatype scan-gradle-plugin,
+whose task is incompatible with the configuration cache and discarded the entry of every build that
+ran it. Points that differ from a plain dependency scan:
+
+- **The IntelliJ Platform is left out.** IPGP puts the IDE's modules and bundled plugins on every
+ compile classpath as Maven-like components (`bundledModule:intellij.platform.core:IU-ā¦`) that no
+ database knows. `intellij-platform` sets `vulnerabilityScan.ignoredGroups` to those groups; a
+ real Maven artifact the platform pulls in stays scanned.
+- **`java-legacy` projects scan `runtimeClasspath` only.** Their `compileOnly` dependencies are
+ era-pinned stubs of the Grails/Groovy they run inside, never shipped.
+- **Credentials are read when a scan runs**, never at configuration time, so they are not in the
+ configuration cache entry and a rotated token reuses it. Answers are cached in the Gradle user
+ home for an hour (`-PvulnerabilityScan.cacheTtl=PT0S` asks again), in the directory grails-core
+ uses, so a machine that builds both asks once.
+- **Exclusions need a reason** and are limited to findings with no fix available; the built-in list
+ is `BuiltInExclusions`, a project adds its own with `vulnerabilityScan { exclude(id, module, reason) }`,
+ and the summary calls out exclusions that no longer match anything.
+
## Tests
Task classes with real logic are tested with Gradle TestKit under `src/test/groovy`, on the same
JUnit 4 + AssertJ stack as the plugin. `./gradlew :build-logic:test` runs them; the root `check`
-depends on build-logic's `check`, so CI runs them (and `validatePlugins`) on every build.
+depends on build-logic's `check`, so CI runs them (and `validatePlugins`) on every build. The scan
+tests run the convention plugins against in-process stubs of the OSV and Sonatype Guide APIs and a
+local Maven repository, with the configuration cache on and its problems fatal.
## Groovy DSL gotchas
diff --git a/build-logic/build.gradle b/build-logic/build.gradle
index aefa2b0..3c334d3 100644
--- a/build-logic/build.gradle
+++ b/build-logic/build.gradle
@@ -36,7 +36,9 @@ dependencies {
implementation 'org.jetbrains.intellij.platform:intellij-platform-gradle-plugin:2.19.0'
implementation 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.4.20'
implementation 'org.nosphere.apache.rat:org.nosphere.apache.rat.gradle.plugin:0.11.0'
- implementation 'org.sonatype.gradle.plugins:scan-gradle-plugin:4.1.0-02'
+ // The CycloneDX SBOM generator behind the sbom convention plugin. The vulnerability scan itself
+ // has no plugin dependency: it is this build's own code under org.apache.grails.intellij.build.scan.
+ implementation 'org.cyclonedx.bom:org.cyclonedx.bom.gradle.plugin:3.5.1'
// Gradle TestKit tests for the build-logic task classes; the same JUnit 4 + AssertJ stack as
// the plugin's own tests.
@@ -44,3 +46,11 @@ dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.assertj:assertj-core:4.0.0-M1'
}
+
+tasks.named('test', Test) { task ->
+ // The credentials the Sonatype Guide stub accepts, which the service under test reads from the
+ // environment variables these name (never the real SONATYPE_GUIDE_* ones, so a developer's
+ // account is not consulted by a test).
+ task.environment('TEST_SONATYPE_GUIDE_USERNAME', 'test-user')
+ task.environment('TEST_SONATYPE_GUIDE_TOKEN', 'test-token')
+}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-platform.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-platform.gradle
index 7803dd5..b7830c3 100644
--- a/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-platform.gradle
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-platform.gradle
@@ -37,3 +37,17 @@ dependencies {
intellijIdea providers.gradleProperty('platformVersion')
}
}
+
+// The platform puts its own modules and bundled plugins on every compile classpath as Maven-like
+// components in groups of IPGP's making (bundledModule:intellij.platform.core:IU-262..., see
+// Constants.Configurations.Dependencies in the plugin), plus Marketplace plugins under
+// com.jetbrains.plugins. They are the host IDE, not dependencies this plugin ships or chooses, and
+// no vulnerability database knows them: looking the ~800 of them up only costs Sonatype Guide
+// credits. The scan leaves them out; everything the platform pulls from Maven stays in.
+vulnerabilityScan {
+ ignoredGroups = [
+ 'bundledModule', 'bundledPlugin',
+ 'localIde', 'localPlugin', 'localJetBrainsRuntime',
+ 'com.jetbrains.plugins',
+ ]
+}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-plugin.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-plugin.gradle
index 54f6a39..e0141ef 100644
--- a/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-plugin.gradle
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.intellij-plugin.gradle
@@ -28,11 +28,21 @@ import org.jetbrains.intellij.platform.gradle.tasks.VerifyPluginTask
plugins {
id 'org.apache.grails.intellij.build.intellij-platform'
id 'org.apache.grails.intellij.build.kotlin'
+ id 'org.apache.grails.intellij.build.sbom'
id 'org.jetbrains.intellij.platform'
}
group = 'org.apache.grails.intellij.plugin'
+// The SBOM describes the ZIP, the one unit of distribution, so it is named after it and lists
+// everything in it: the runtime classpath (the libraries and compiler jars in lib/) and the content
+// modules (lib/modules/), which IPGP carries in a configuration of its own. The platform itself is on
+// no runtime configuration, so the host IDE is not listed as a dependency.
+sbom {
+ componentName = 'apache-grails-intellij-plugin'
+ configurations = ['runtimeClasspath', 'intellijPlatformPluginModule']
+}
+
intellijPlatform {
// Pinned explicitly. This drives the distribution ZIP name, the plugin directory inside it,
// and the sandbox directory; its convention is project.name, which would make all three
@@ -186,6 +196,10 @@ tasks.named('publishPlugin') { task ->
// ignores archivesName, so it is pinned for the same reason projectName is.
tasks.named('composedJar') { task ->
task.archiveBaseName = 'apache-grails-intellij-plugin'
+ // The composed jar carries the jar's META-INF/sbom.json, but its manifest is IPGP's generated
+ // one rather than the jar task's, so the attributes the sbom convention sets on `jar` are
+ // repeated here for the jar that actually ships.
+ task.manifest.attributes('Sbom-Location': 'META-INF/sbom.json', 'Sbom-Format': 'CycloneDX')
}
// ASF policy: ship LICENSE and NOTICE inside the plugin jar. They live at the repository root,
@@ -204,10 +218,17 @@ tasks.named('processResources') { task ->
// files in every unit of distribution "whether the unit of distribution is a .jar, .msi, .tar.gz,
// .zip, .exe installer, or any other file format" -- having them only in the composed jar's
// META-INF, as processResources does above, does not satisfy that for the ZIP itself.
+//
+// The SBOM goes in next to them as sbom.json, so a tool fed the ZIP finds it without opening the
+// composed jar, which carries the same file at META-INF/sbom.json.
tasks.withType(PrepareSandboxTask).configureEach { task ->
task.from(layout.projectDirectory.dir('standardDsls')) {
into task.pluginName.map { "$it/lib/standardDsls/" }
}
task.from(layout.settingsDirectory.file('LICENSE')) { into task.pluginName }
task.from(layout.settingsDirectory.file('NOTICE')) { into task.pluginName }
+ task.from(tasks.named('sbom').flatMap { it.sbom }) {
+ into task.pluginName
+ rename { 'sbom.json' }
+ }
}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.java-legacy.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.java-legacy.gradle
index 8cc4b87..801111b 100644
--- a/build-logic/src/main/groovy/org.apache.grails.intellij.build.java-legacy.gradle
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.java-legacy.gradle
@@ -37,3 +37,11 @@ legacyBytecode.release.convention(8)
tasks.withType(JavaCompile).configureEach { task ->
task.options.release.set(legacyBytecode.release)
}
+
+// These jars compile against era-pinned stubs of the environment they run inside (Grails 1.x/2.x,
+// Groovy 2.4: compileOnly, and deliberately never bumped, see .github/dependabot.yml). The stubs are
+// the end user's own installation, never shipped, and their decade-old advisories would be reported
+// forever, so only what the jar carries at runtime is scanned.
+vulnerabilityScan {
+ configurations = ['runtimeClasspath']
+}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.sbom.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.sbom.gradle
new file mode 100644
index 0000000..704232f
--- /dev/null
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.sbom.gradle
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.time.Instant
+import java.time.format.DateTimeFormatter
+import java.time.temporal.ChronoUnit
+
+import org.apache.grails.intellij.build.sbom.ReproducibleSbomTask
+import org.apache.grails.intellij.build.sbom.SbomExtension
+import org.cyclonedx.gradle.CyclonedxDirectTask
+import org.cyclonedx.model.Component
+import org.cyclonedx.model.ExternalReference
+import org.cyclonedx.model.License
+import org.cyclonedx.model.LicenseChoice
+import org.cyclonedx.model.OrganizationalContact
+import org.cyclonedx.model.OrganizationalEntity
+
+// A CycloneDX software bill of materials for the component a project ships, as grails-core produces
+// for its jars: `cyclonedxDirectBom` generates it from the resolved dependencies, and `sbom` turns
+// that into the reproducible file that is packaged -- into the jar at META-INF/sbom.json, named by
+// the Sbom-Location and Sbom-Format manifest attributes, and wherever the consuming convention puts
+// it besides (the plugin ZIP's root). The license pass in `sbom` is also the check that nothing
+// under a license ASF policy forbids gets packaged: the jar depends on it, so a forbidden license
+// fails the build before anything ships.
+//
+// Only the CycloneDX direct task is registered, not the CycloneDX plugin itself: the plugin would
+// also register an aggregate SBOM of every project, which is misleading for a build whose unit of
+// distribution is one ZIP.
+//
+// The `sbom { }` extension names the component (the project name unless set) and the configurations
+// whose dependencies it lists (runtimeClasspath unless set).
+
+def extension = extensions.create('sbom', SbomExtension)
+extension.componentName.convention(project.name)
+extension.configurations.convention(['runtimeClasspath'])
+
+// Evaluated when the task inputs are computed rather than here: a build script may still set the
+// version after this plugin is applied.
+def projectVersion = provider { project.version.toString() }
+def projectPath = project.path
+
+// Byte-for-byte reproducible, so the SBOM is dated as the rest of the archive is: at the epoch
+// unless SOURCE_DATE_EPOCH names the build time, as release verification does.
+def timestamp = providers.environmentVariable('SOURCE_DATE_EPOCH')
+ .map { Instant.ofEpochSecond(it.toLong()) }
+ .orElse(Instant.EPOCH)
+ .map { DateTimeFormatter.ISO_INSTANT.format(it.truncatedTo(ChronoUnit.SECONDS)) }
+
+def generateBom = tasks.register('cyclonedxDirectBom', CyclonedxDirectTask) { CyclonedxDirectTask task ->
+ task.description = 'Generates the CycloneDX SBOM that the sbom task makes reproducible'
+ // JSON only, at a reports path: the file that ships is the sbom task's output
+ task.jsonOutput.set(layout.buildDirectory.file('reports/cyclonedx/bom.json'))
+ task.componentName.set(extension.componentName)
+ task.includeConfigs.set(extension.configurations)
+ task.projectType.set(Component.Type.APPLICATION)
+ task.organizationalEntity.set(new OrganizationalEntity(
+ name: 'Apache Software Foundation',
+ urls: ['https://www.apache.org/', 'https://security.apache.org/'],
+ contacts: [new OrganizationalContact(name: 'Apache Grails Development Team', email: 'dev@grails.apache.org')],
+ ))
+ task.licenseChoice.set(new LicenseChoice(
+ licenses: [new License(id: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0.txt')],
+ ))
+ task.externalReferences.set(projectVersion.map { String version ->
+ boolean snapshot = version.endsWith('SNAPSHOT')
+ [
+ new ExternalReference(url: 'https://grails.apache.org', type: ExternalReference.Type.WEBSITE),
+ new ExternalReference(url: 'https://github.com/apache/grails-intellij-plugin', type: ExternalReference.Type.VCS),
+ new ExternalReference(url: snapshot ? 'dev@grails.apache.org' : 'users@grails.apache.org',
+ type: ExternalReference.Type.MAILING_LIST),
+ ]
+ })
+ // license texts are base64-encoded into the file and only inflate it
+ task.includeLicenseText.set(false)
+ // the build system reference is the CI run URL and the build environment the host's JDK and
+ // Gradle; neither can agree between CI and a release verifier's rebuild
+ task.includeBuildSystem.set(false)
+ task.includeBuildEnvironment.set(false)
+}
+
+def sbom = tasks.register('sbom', ReproducibleSbomTask) { ReproducibleSbomTask task ->
+ task.group = 'build'
+ task.description = 'Writes the reproducible CycloneDX SBOM that ships with the component'
+ task.bom.set(generateBom.flatMap { it.jsonOutput })
+ task.componentName.set(extension.componentName)
+ task.projectPath.set(projectPath)
+ task.timestamp.set(timestamp)
+ task.sbom.set(layout.buildDirectory.file(extension.componentName.zip(projectVersion) { String name, String version ->
+ "sbom/${name}-${version}-sbom.json".toString()
+ }))
+}
+
+pluginManager.withPlugin('java') {
+ tasks.named('jar', Jar) { Jar jar ->
+ jar.from(sbom.flatMap { it.sbom }) { spec ->
+ spec.into('META-INF')
+ spec.rename { 'sbom.json' }
+ }
+ jar.manifest.attributes('Sbom-Location': 'META-INF/sbom.json', 'Sbom-Format': 'CycloneDX')
+ }
+ // the SBOM changes with the dependency versions, not the code, so a consumer of the jar need
+ // not recompile for it
+ normalization.runtimeClasspath.ignore('META-INF/sbom.json')
+}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan-report.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan-report.gradle
new file mode 100644
index 0000000..da05bdd
--- /dev/null
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan-report.gradle
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.grails.intellij.build.scan.VulnerabilityScanReportTask
+import org.apache.grails.intellij.build.scan.VulnerabilityScanTask
+
+// Registers the `vulnerabilityScanReport` task, which summarizes the reports of the
+// `vulnerabilityScan` tasks of every project in Markdown at build/reports/vulnerability-scan/summary.md.
+// It runs after the scans of the same build but does not depend on them, so with --continue it also
+// summarizes a scan that failed. Applied to the root project only: it collects from every project.
+//
+// -PvulnerabilityScan.reportMaxBytes=<bytes> keeps the summary within that size, for a pull request
+// comment.
+
+if (project != rootProject) {
+ throw new GradleException('org.apache.grails.intellij.build.vulnerability-scan-report must be applied to the root project')
+}
+
+tasks.register(VulnerabilityScanReportTask.TASK_NAME, VulnerabilityScanReportTask) { VulnerabilityScanReportTask task ->
+ task.group = 'verification'
+ task.description = 'Summarizes the vulnerability scans of every project in Markdown'
+ task.reports.from(provider {
+ allprojects.collect { Project p -> p.layout.buildDirectory.file(VulnerabilityScanTask.REPORT_PATH).get() }
+ })
+ task.mustRunAfter(provider {
+ allprojects.findAll { Project p -> p.tasks.names.contains(VulnerabilityScanTask.TASK_NAME) }
+ .collect { Project p -> p.tasks.named(VulnerabilityScanTask.TASK_NAME) }
+ })
+ task.maxBytes.convention(providers.gradleProperty('vulnerabilityScan.reportMaxBytes').map { it.toInteger() }.orElse(0))
+ task.summaryFile.set(layout.buildDirectory.file(VulnerabilityScanReportTask.SUMMARY_PATH))
+}
diff --git a/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan.gradle b/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan.gradle
index caa392c..879e7e4 100644
--- a/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan.gradle
+++ b/build-logic/src/main/groovy/org.apache.grails.intellij.build.vulnerability-scan.gradle
@@ -17,61 +17,99 @@
* under the License.
*/
-import org.apache.grails.intellij.build.OssIndexAuditThrottle
-import org.sonatype.gradle.plugins.scan.ossindex.OssIndexPluginExtension
+import java.time.Duration
-// Sonatype OSS Index / Guide vulnerability scanning. Credentials come from the environment:
-// SONATYPE_GUIDE_USERNAME - Guide account email / user token username
-// SONATYPE_GUIDE_TOKEN - Guide Personal Access Token (PAT)
-// The `ossIndexAudit` task fails fast when SONATYPE_GUIDE_TOKEN is absent.
+import org.apache.grails.intellij.build.scan.BuiltInExclusions
+import org.apache.grails.intellij.build.scan.OsvVulnerabilityService
+import org.apache.grails.intellij.build.scan.SonatypeGuideVulnerabilityService
+import org.apache.grails.intellij.build.scan.VulnerabilityScanExtension
+import org.apache.grails.intellij.build.scan.VulnerabilityScanTask
-plugins {
- id 'org.sonatype.gradle.plugins.scan'
-}
+// Registers the `vulnerabilityScan` task, which fails when the external dependencies of the project
+// have known vulnerabilities in the OSV database (https://osv.dev) or, when the SONATYPE_GUIDE_USERNAME
+// and SONATYPE_GUIDE_TOKEN environment variables hold the credentials of an account, in Sonatype Guide.
+// The credentials are read when a scan runs, never at configuration time, so they are not part of
+// the configuration cache entry and a rotated token reuses it.
+//
+// This replaced the Sonatype scan-gradle-plugin, whose ossIndexAudit task is marked incompatible
+// with the configuration cache and discarded the entry of every build that ran it. The scanner is
+// a port of grails-core's build-logic/vulnerability-scan, in the org.apache.grails.intellij.build.scan
+// package, and shares its on-disk cache of answers: both builds keep them in the Gradle user home
+// for an hour, so a machine that builds both asks the databases once. Gradle properties adjust that:
+// vulnerabilityScan.cacheTtl how long an answer is used, as an ISO-8601 duration such as
+// PT1H; PT0S asks the APIs again every time
+// vulnerabilityScan.cacheDir where the answers are kept
+// vulnerabilityScan.apiUrl the OSV API
+// vulnerabilityScan.sonatypeGuide.apiUrl the Sonatype Guide API
+// vulnerabilityScan.ignoreFailures only report what was found
+//
+// The cache keeps one small file per dependency and per vulnerability it has looked up, and nothing
+// removes them: an entry older than the time to live is fetched again and overwritten. Delete the
+// directory to start over.
+//
+// The scans of a build run one after another, since each asks the databases through a service that
+// admits one scan at a time and so stays within their rate limits; --parallel does not shorten a
+// scan, the cache does.
+//
+// The `vulnerabilityScan { }` extension names the configurations to scan (runtimeClasspath and
+// compileClasspath unless set), the dependency groups to leave out (the IntelliJ Platform's own
+// components, set by the intellij-platform convention), and the vulnerabilities to exclude, each
+// with a reason. The built-in exclusions live in BuiltInExclusions, with the policy for adding one.
-// The OSS Index plugin guards its shared on-disk response cache with a file lock, so audit
-// tasks cannot run concurrently without hitting OverlappingFileLockException. Gate every
-// audit task on a single-usage build service to serialize them while leaving parallel
-// execution enabled for the rest of the build.
-def throttle = gradle.sharedServices.registerIfAbsent('ossIndexAuditThrottle', OssIndexAuditThrottle) {
- maxParallelUsages = 1
-}
+def extension = extensions.create('vulnerabilityScan', VulnerabilityScanExtension)
+extension.configurations.convention(['runtimeClasspath', 'compileClasspath'])
+extension.ignoredGroups.convention([])
+// the built-in exclusions are the value, not a convention, so exclude(...) adds to them: add ignores a convention
+extension.exclusions.set(BuiltInExclusions.EXCLUSIONS)
+extension.ignoreFailures.convention(
+ providers.gradleProperty('vulnerabilityScan.ignoreFailures').map { it.isEmpty() || it.toBoolean() }.orElse(false))
-// Read through Providers rather than System.getenv so the values are tracked inputs.
-def guideUsername = providers.environmentVariable('SONATYPE_GUIDE_USERNAME')
-def guideToken = providers.environmentVariable('SONATYPE_GUIDE_TOKEN')
+def cacheTtl = providers.gradleProperty('vulnerabilityScan.cacheTtl')
+ .map { Duration.parse(it) }
+ .orElse(OsvVulnerabilityService.DEFAULT_CACHE_TTL)
+def cacheDir = providers.gradleProperty('vulnerabilityScan.cacheDir')
+File cacheDirectory = cacheDir.isPresent() ?
+ layout.settingsDirectory.dir(cacheDir.get()).asFile :
+ new File(gradle.gradleUserHomeDir, 'caches/grails-vulnerability-scan')
-// The extension is named explicitly rather than configured via a bare closure: Groovy
-// closures resolve owner-first, so `username = ...` would be set on the Project instead of
-// the extension (Kotlin's configure<T> {} has no such fallback).
-extensions.configure(OssIndexPluginExtension) { OssIndexPluginExtension ossIndex ->
- ossIndex.username = guideUsername.getOrElse('')
- ossIndex.password = guideToken.getOrElse('')
- // Exemptions are limited to vulnerabilities with NO available upstream fix. Everything
- // with a published fix must be bumped instead. Each entry must name the CVE and the
- // removal condition, and be revisited whenever a fix ships. Empty until a real,
- // unfixable CVE is encountered.
- ossIndex.excludeCoordinates = [] as Set
+// one scan at a time asks each API, so a build of many projects stays within its rate limits
+def osv = gradle.sharedServices.registerIfAbsent('osvVulnerabilityService', OsvVulnerabilityService) { spec ->
+ spec.parameters.apiUrl.set(providers.gradleProperty('vulnerabilityScan.apiUrl')
+ .orElse(OsvVulnerabilityService.DEFAULT_API_URL))
+ spec.parameters.cacheTtl.set(cacheTtl)
+ spec.parameters.cacheDirectory.set(cacheDirectory)
+ spec.maxParallelUsages.set(1)
+}
+def sonatypeGuide = gradle.sharedServices.registerIfAbsent('sonatypeGuideVulnerabilityService', SonatypeGuideVulnerabilityService) { spec ->
+ spec.parameters.apiUrl.set(providers.gradleProperty('vulnerabilityScan.sonatypeGuide.apiUrl')
+ .orElse(SonatypeGuideVulnerabilityService.DEFAULT_API_URL))
+ spec.parameters.cacheTtl.set(cacheTtl)
+ spec.parameters.cacheDirectory.set(cacheDirectory)
+ // only the names: the service reads the credentials when a scan runs, keeping them out of the configuration cache
+ spec.parameters.usernameVariable.set(SonatypeGuideVulnerabilityService.USERNAME_VARIABLE)
+ spec.parameters.tokenVariable.set(SonatypeGuideVulnerabilityService.TOKEN_VARIABLE)
+ spec.maxParallelUsages.set(1)
}
// Captured at configuration time: Task.project is unavailable at execution time under the
-// configuration cache, so the task actions below must not reach for it.
+// configuration cache, and the configurations are looked up when the task's inputs are computed.
def projectPath = project.path
-def projectName = project.name
+def configurationContainer = configurations
-tasks.named('ossIndexAudit') {
- group = 'verification'
- description = "Scans $projectName runtime dependencies for known vulnerabilities via Sonatype Guide"
- usesService(throttle)
- doFirst {
- if (!guideToken.isPresent() || guideToken.get().isEmpty()) {
- throw new GradleException(
- 'SONATYPE_GUIDE_TOKEN environment variable is not set. ' +
- 'A Sonatype Guide Personal Access Token is required to run the vulnerability scan.')
- }
- println "##[ossIndexAudit:begin] $projectPath"
- }
- doLast {
- println "##[ossIndexAudit:end] $projectPath"
- }
+tasks.register(VulnerabilityScanTask.TASK_NAME, VulnerabilityScanTask) { VulnerabilityScanTask task ->
+ task.group = 'verification'
+ task.description = "Scans the dependencies of $projectPath for known vulnerabilities"
+ task.projectPath.set(projectPath)
+ task.ignoredGroups.set(extension.ignoredGroups)
+ task.exclusions.set(extension.exclusions)
+ task.ignoreFailures.set(extension.ignoreFailures)
+ task.reportFile.set(layout.buildDirectory.file(VulnerabilityScanTask.REPORT_PATH))
+ task.vulnerabilityService.set(osv)
+ task.usesService(osv)
+ task.sonatypeGuideService.set(sonatypeGuide)
+ task.usesService(sonatypeGuide)
+ // mapped, not read here: a build script may still name the configurations after the task is realized
+ task.configurations.set(extension.configurations.map { List<String> names ->
+ VulnerabilityScanTask.resolutionRoots(configurationContainer, names)
+ })
}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTask.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTask.groovy
new file mode 100644
index 0000000..31647c5
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTask.groovy
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.sbom
+
+import java.nio.charset.StandardCharsets
+
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.logging.Logger
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.CacheableTask
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.InputFile
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+
+/**
+ * Turns the CycloneDX SBOM the {@code cyclonedxDirectBom} task wrote into the one that ships: byte-for-byte
+ * reproducible, and with every dependency recorded under the one license {@link SbomLicensePolicy} picks for it.
+ *
+ * <p>What the CycloneDX plugin writes is not reproducible: its timestamp is the build time, its serial number is a
+ * random UUID, and the order of a component's dependencies follows resolution. The timestamp is pinned, the
+ * dependency lists are sorted, the hashes of the build's own project components are dropped (they are the hashes of
+ * jars that may not exist yet when a parallel build generates the SBOM), and the serial number is derived from the
+ * content, so the same dependencies always give the same file. The license pass runs on every build, so a
+ * dependency under a license ASF policy does not permit fails the build that would ship it.</p>
+ *
+ * <p>Ported from the {@code doLast} of grails-core's {@code SbomPlugin}, as a task with declared inputs and
+ * outputs so it is cacheable and the jar depends on its output rather than on the generator.</p>
+ */
+@CompileStatic
+@CacheableTask
+abstract class ReproducibleSbomTask extends DefaultTask {
+
+ /** The SBOM as the CycloneDX plugin wrote it. */
+ @InputFile
+ @PathSensitive(PathSensitivity.NONE)
+ abstract RegularFileProperty getBom()
+
+ /** The name of the component the SBOM describes; the license exemptions are keyed by it. */
+ @Input
+ abstract Property<String> getComponentName()
+
+ /** The path of the project, mixed into the serial number so identical SBOMs of two projects still differ. */
+ @Input
+ abstract Property<String> getProjectPath()
+
+ /** The ISO-8601 instant recorded as the SBOM's timestamp. */
+ @Input
+ abstract Property<String> getTimestamp()
+
+ @OutputFile
+ abstract RegularFileProperty getSbom()
+
+ @TaskAction
+ void write() {
+ Map bom = (Map) new JsonSlurper().parse(getBom().get().asFile, StandardCharsets.UTF_8.name())
+ String content = render(bom, projectPath.get(), componentName.get(), timestamp.get(), logger)
+ File output = sbom.get().asFile
+ output.parentFile.mkdirs()
+ output.setText(content, StandardCharsets.UTF_8.name())
+ logger.info('Wrote the reproducible SBOM of {} to {}', componentName.get(), output)
+ }
+
+ /**
+ * The reproducible SBOM, as pretty-printed JSON (https://cyclonedx.org/docs/1.6/json/).
+ *
+ * @param bom the SBOM as the CycloneDX plugin wrote it; it is modified in place
+ * @param projectPath the path of the project, mixed into the serial number
+ * @param component the name of the component the SBOM describes
+ * @param timestamp the ISO-8601 instant to record
+ * @param logger where the license choices are logged
+ */
+ @CompileDynamic
+ static String render(Map bom, String projectPath, String component, String timestamp, Logger logger) {
+ bom.metadata = (bom.metadata instanceof Map ? bom.metadata : [:]) as Map
+ bom.metadata.timestamp = timestamp
+
+ List components = bom.components instanceof List ? bom.components : []
+ components.each { Object entry ->
+ if (!(entry instanceof Map)) {
+ return
+ }
+ Map c = (Map) entry
+ // one license per dependency, the one ASF policy prefers; a dependency without any is left as it is
+ if (c.licenses instanceof List && !((List) c.licenses).empty) {
+ Object chosen = SbomLicensePolicy.pickLicense(logger, component, c['bom-ref'] as String, (List) c.licenses)
+ if (chosen != null) {
+ c.licenses = [chosen]
+ }
+ }
+ // the build's own projects are listed with the hashes of their jars, which a parallel build may not
+ // have produced yet when the SBOM is generated; nothing reproducible can be recorded for them
+ if (c.hashes instanceof List && (c['bom-ref'] as String)?.contains('?project_path=')) {
+ c.remove('hashes')
+ }
+ }
+
+ List dependencies = bom.dependencies instanceof List ? bom.dependencies : []
+ dependencies.each { Object entry ->
+ if (entry instanceof Map && ((Map) entry).dependsOn instanceof List) {
+ ((Map) entry).dependsOn = (((Map) entry).dependsOn as List).sort(false)
+ }
+ }
+
+ // The serial number is derived from the content, with the project path mixed in so two projects whose
+ // SBOMs happen to be identical (empty ones, say) still get the distinct serial numbers the specification
+ // requires, see https://cyclonedx.org/docs/1.6/json/#serialNumber
+ bom.serialNumber = ''
+ String withoutSerial = JsonOutput.prettyPrint(JsonOutput.toJson(bom))
+ bom.serialNumber = "urn:uuid:${UUID.nameUUIDFromBytes("${projectPath}\n${withoutSerial}".getBytes(StandardCharsets.UTF_8))}".toString()
+ JsonOutput.prettyPrint(JsonOutput.toJson(bom)) + '\n'
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/OssIndexAuditThrottle.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomExtension.groovy
similarity index 55%
rename from build-logic/src/main/groovy/org/apache/grails/intellij/build/OssIndexAuditThrottle.groovy
rename to build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomExtension.groovy
index 9088e7b..88f9030 100644
--- a/build-logic/src/main/groovy/org/apache/grails/intellij/build/OssIndexAuditThrottle.groovy
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomExtension.groovy
@@ -17,18 +17,23 @@
* under the License.
*/
-package org.apache.grails.intellij.build
+package org.apache.grails.intellij.build.sbom
-import org.gradle.api.services.BuildService
-import org.gradle.api.services.BuildServiceParameters
+import groovy.transform.CompileStatic
+
+import org.gradle.api.provider.ListProperty
+import org.gradle.api.provider.Property
/**
- * Shared build service used solely as a concurrency gate for {@code ossIndexAudit} tasks.
- *
- * <p>The Sonatype OSS Index plugin guards its shared on-disk response cache with a file lock,
- * so concurrent audit tasks hit OverlappingFileLockException. Registering this service with
- * {@code maxParallelUsages = 1} serializes the audits while leaving the rest of the build
- * free to run in parallel.
+ * Configures the SBOM of a project, as the {@code sbom} extension registered by the
+ * {@code org.apache.grails.intellij.build.sbom} convention plugin.
*/
-abstract class OssIndexAuditThrottle implements BuildService<BuildServiceParameters.None> {
+@CompileStatic
+abstract class SbomExtension {
+
+ /** The name of the component the SBOM describes, the project name unless set. */
+ abstract Property<String> getComponentName()
+
+ /** The configurations whose resolved dependencies the SBOM lists, {@code runtimeClasspath} unless set. */
+ abstract ListProperty<String> getConfigurations()
}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicy.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicy.groovy
new file mode 100644
index 0000000..6d64fb2
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicy.groovy
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.sbom
+
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.logging.Logger
+
+/**
+ * Chooses, for each dependency in an SBOM, the one license it is recorded under, as ASF policy
+ * (https://www.apache.org/legal/resolved.html) wants it: a dependency offered under several licenses is recorded
+ * under the most preferred one, a dependency whose published metadata is wrong is corrected from a mapping, and a
+ * dependency under a license the policy does not permit fails the build unless it is explicitly exempted.
+ *
+ * <p>Ported from grails-core's {@code SbomPlugin}. The tables are the policy of this build: add to
+ * {@link #LICENSE_MAPPING} when CycloneDX reads a dependency's license wrongly, and to {@link #LICENSE_EXCEPTIONS}
+ * only for a dependency that is not distributed, or whose use ASF legal has approved.</p>
+ */
+@CompileStatic
+final class SbomLicensePolicy {
+
+ /** Ordered so that the first value is the most preferred, from https://www.apache.org/legal/resolved.html */
+ static final List<String> PREFERRED_LICENSES = [
+ 'Apache-2.0', 'EPL-1.0', 'BSD-3-Clause', 'EPL-2.0', 'MIT', 'MIT-0', '0BSD', 'UPL-1.0',
+ 'CC0-1.0', 'ICU', 'Xnet', 'NCSA', 'W3C', 'Zlib', 'AFL-3.0', 'MS-PL', 'PSF-2.0', 'APAFML',
+ 'BSL-1.0', 'WTFPL', 'Unlicense', 'HPND', 'EPICS', 'TCL',
+ ].asImmutable()
+
+ /** The license blocks a mapping can record a dependency under; ids are the SPDX ones, https://spdx.org/licenses/ */
+ static final Map<String, Map<String, String>> LICENSES = [
+ 'Apache-2.0' : [id: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0'],
+ 'BSD-2-Clause': [id: 'BSD-2-Clause', url: 'https://opensource.org/license/bsd-2-clause/'],
+ 'BSD-3-Clause': [id: 'BSD-3-Clause', url: 'https://opensource.org/license/bsd-3-clause/'],
+ 'CC0-1.0' : [id: 'CC0-1.0', url: 'https://creativecommons.org/publicdomain/zero/1.0/'],
+ 'MIT' : [id: 'MIT', url: 'https://opensource.org/license/mit/'],
+ 'UPL-1.0' : [id: 'UPL-1.0', url: 'https://oss.oracle.com/licenses/upl/'],
+ ].asImmutable() as Map<String, Map<String, String>>
+
+ /**
+ * Dependencies whose published license metadata CycloneDX reads wrongly, by bom-ref (a package URL), and the
+ * license they are actually under. Each entry says why, with a link; most are the name-only "The BSD License"
+ * problem of https://github.com/CycloneDX/cyclonedx-core-java/issues/205. Empty until the plugin ships a
+ * dependency that needs one: everything in its distribution is currently built from this repository.
+ */
+ static final Map<String, String> LICENSE_MAPPING = [:].asImmutable() as Map<String, String>
+
+ /**
+ * Dependencies under a license outside {@link #PREFERRED_LICENSES} that a component may nevertheless list, by
+ * component name and then bom-ref, with the license id that is permitted. A Category X license may appear here
+ * only for a dependency that is not distributed, or whose use ASF legal has approved in a LEGAL ticket named in
+ * the entry. The entries are version-specific on purpose, so a dependency bump revisits them.
+ */
+ static final Map<String, Map<String, String>> LICENSE_EXCEPTIONS = [:].asImmutable() as Map<String, Map<String, String>>
+
+ private SbomLicensePolicy() {
+ }
+
+ /**
+ * Picks the license a dependency is recorded under, from the choices CycloneDX found for it.
+ *
+ * @param logger where the choice is logged
+ * @param component the name of the component the SBOM describes, which the exemptions are keyed by
+ * @param bomRef the bom-ref of the dependency, a package URL
+ * @param licenseChoices the {@code licenses} entries of the dependency in the SBOM
+ * @return the license entry to keep
+ * @throws GradleException when the dependency has no license, or one the policy does not permit
+ */
+ @CompileDynamic
+ static Object pickLicense(Logger logger, String component, String bomRef, List licenseChoices) {
+ if (!bomRef) {
+ throw new GradleException("No bom-ref found for a dependency of ${component}, cannot pick its license")
+ }
+
+ logger.info('Picking the license of {} from {} choices', bomRef, licenseChoices.size())
+ if (LICENSE_MAPPING.containsKey(bomRef)) {
+ String licenseId = LICENSE_MAPPING[bomRef]
+ logger.info('Recording {} under {} as the mapping says', bomRef, licenseId)
+ Map<String, String> license = LICENSES[licenseId]
+ if (!license) {
+ throw new GradleException("No license block for the id ${licenseId} that ${bomRef} of ${component} is mapped to")
+ }
+ return [license: license]
+ }
+
+ if (!(licenseChoices instanceof List) || licenseChoices.isEmpty()) {
+ throw new GradleException("No license was found for the dependency ${bomRef} of ${component}")
+ }
+
+ List identified = licenseChoices.findAll { it instanceof Map && it.license instanceof Map && it.license.id }
+ String preferred = PREFERRED_LICENSES.find { String candidate -> identified.any { it.license.id == candidate } }
+ if (preferred) {
+ return identified.find { it.license.id == preferred }
+ }
+
+ Object first = licenseChoices[0]
+ String firstId = first instanceof Map && first.license instanceof Map ? first.license.id as String : null
+ if (firstId == null) {
+ throw new GradleException("Could not determine the license id of the dependency ${bomRef} of ${component} from ${first}")
+ }
+ if (!(firstId in PREFERRED_LICENSES)) {
+ Map<String, String> exemptions = LICENSE_EXCEPTIONS[component] ?: [:]
+ if (exemptions.get(bomRef) != firstId) {
+ throw new GradleException("Unpermitted license ${firstId} for the dependency ${bomRef} of ${component}")
+ }
+ }
+ first
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiCache.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiCache.groovy
new file mode 100644
index 0000000..b76067f
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiCache.groovy
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.charset.StandardCharsets
+import java.nio.file.AtomicMoveNotSupportedException
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.StandardCopyOption
+import java.security.MessageDigest
+import java.time.Duration
+
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+import groovy.transform.CompileStatic
+
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+
+/**
+ * Keeps the answers of a vulnerability database on disk, one JSON file per key, and hands them out again while
+ * they are younger than the time to live.
+ *
+ * <p>Entries are written atomically, so builds sharing the directory never read half of one. Nothing removes them:
+ * an entry older than the time to live is simply fetched again and overwritten.</p>
+ *
+ * <p>Ported from grails-core's build-logic ({@code vulnerability-scan}), with which this build shares the cache
+ * directory and entry format.</p>
+ */
+@CompileStatic
+class ApiCache {
+
+ private static final Logger LOG = Logging.getLogger(ApiCache)
+
+ private final Path directory
+ private final Duration ttl
+ private boolean warned
+
+ ApiCache(Path directory, Duration ttl) {
+ this.directory = directory
+ this.ttl = ttl
+ }
+
+ /**
+ * Returns the entry kept for the key, or {@code null} when there is none younger than the time to live.
+ */
+ Map<String, Object> read(String key) {
+ Path file = file(key)
+ if (!Files.isRegularFile(file)) {
+ return null
+ }
+ try {
+ Map<String, Object> entry = (Map<String, Object>) new JsonSlurper().parse(file.toFile())
+ long fetchedAt = (entry.get('fetchedAt') as Long) ?: 0L
+ System.currentTimeMillis() - fetchedAt < ttl.toMillis() ? entry : null
+ }
+ catch (RuntimeException e) {
+ LOG.info('Ignoring the unreadable cache entry {}', file, e)
+ null
+ }
+ }
+
+ /**
+ * Keeps the entry for the key, stamped with the time it was fetched. Keeping it is best effort: an entry that
+ * cannot be written is fetched again next time, which must not fail the scan it was fetched for.
+ */
+ void write(String key, Map<String, Object> entry) {
+ Path file = file(key)
+ Path temporary = null
+ try {
+ Files.createDirectories(file.parent)
+ temporary = Files.createTempFile(file.parent, file.fileName.toString(), '.tmp')
+ Map<String, Object> stamped = [fetchedAt: (Object) System.currentTimeMillis()]
+ stamped.putAll(entry)
+ Files.writeString(temporary, JsonOutput.toJson(stamped))
+ move(temporary, file)
+ }
+ catch (IOException e) {
+ // once at warn level: the same cause fails every entry of a build, and the answers are still used
+ if (warned) {
+ LOG.info('Could not keep the answer for {} in {}', key, directory, e)
+ }
+ else {
+ warned = true
+ LOG.warn('Could not keep the answer for {} in {}, so it will be asked for again: {}', key, directory, e.toString())
+ }
+ discard(temporary)
+ }
+ }
+
+ private static void move(Path temporary, Path file) {
+ try {
+ Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
+ }
+ catch (AtomicMoveNotSupportedException ignored) {
+ Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING)
+ }
+ }
+
+ private static void discard(Path temporary) {
+ if (temporary == null) {
+ return
+ }
+ try {
+ Files.deleteIfExists(temporary)
+ }
+ catch (IOException e) {
+ LOG.info('Could not delete the temporary cache file {}', temporary, e)
+ }
+ }
+
+ private Path file(String key) {
+ directory.resolve("${MessageDigest.getInstance('SHA-256').digest(key.getBytes(StandardCharsets.UTF_8)).encodeHex()}.json")
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiClient.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiClient.groovy
new file mode 100644
index 0000000..7176436
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/ApiClient.groovy
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.net.http.HttpClient
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+import java.time.Duration
+
+import groovy.json.JsonSlurper
+import groovy.transform.CompileStatic
+
+import org.gradle.api.BuildCancelledException
+import org.gradle.api.GradleException
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+
+/**
+ * Sends the requests to a vulnerability database, retrying those that were throttled or failed on the way.
+ */
+@CompileStatic
+class ApiClient implements AutoCloseable {
+
+ private static final Logger LOG = Logging.getLogger(ApiClient)
+ private static final int MAX_ATTEMPTS = 4
+ private static final int MAX_ERROR_BODY = 500
+
+ private final String name
+ private HttpClient httpClient
+
+ /**
+ * @param name what the API is called in messages, such as {@code OSV API}
+ */
+ ApiClient(String name) {
+ this.name = name
+ }
+
+ /**
+ * Sends the request and returns the answer, once it is a {@code 200}. A request that was throttled, failed
+ * with a server error or did not get through is sent again, after the time the API asks for if it does.
+ *
+ * @param hints what to tell the user when the API answers with one of these statuses
+ */
+ HttpResponse<String> send(HttpRequest request, Map<Integer, String> hints = [:]) {
+ IOException failure = null
+ HttpResponse<String> lastResponse = null
+ for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
+ try {
+ HttpResponse<String> response = client().send(request, HttpResponse.BodyHandlers.ofString())
+ int status = response.statusCode()
+ if (status == 200) {
+ return response
+ }
+ if (status != 429 && status < 500) {
+ throw new GradleException("The ${name} answered ${request.method()} ${request.uri()} with ${status}" +
+ "${hints.get(status) ? " (${hints.get(status)})" : ''}: ${body(response)}")
+ }
+ lastResponse = response
+ failure = null
+ LOG.info('The {} answered {} {} with {}, attempt {} of {}', name, request.method(), request.uri(),
+ status, attempt, MAX_ATTEMPTS)
+ if (attempt < MAX_ATTEMPTS) {
+ pause(retryDelay(response, attempt))
+ }
+ }
+ catch (IOException e) {
+ failure = e
+ lastResponse = null
+ LOG.info('Could not reach the {} at {}, attempt {} of {}', name, request.uri(), attempt, MAX_ATTEMPTS, e)
+ if (attempt < MAX_ATTEMPTS) {
+ pause(Duration.ofSeconds(1L << attempt).toMillis())
+ }
+ }
+ }
+ if (lastResponse != null) {
+ // a rate limit or an outage of the API itself, which the status and body tell apart
+ throw new GradleException("The ${name} still answered ${request.method()} ${request.uri()} with " +
+ "${lastResponse.statusCode()} after ${MAX_ATTEMPTS} attempts: ${body(lastResponse)}")
+ }
+ throw new GradleException("The ${name} did not answer ${request.method()} ${request.uri()} after " +
+ "${MAX_ATTEMPTS} attempts", failure)
+ }
+
+ /**
+ * The JSON body of an answer.
+ */
+ static Object json(HttpResponse<String> response) {
+ new JsonSlurper().parseText(response.body())
+ }
+
+ @Override
+ void close() {
+ // HttpClient can be closed from Java 21 on; on older JDKs its resources are released when it is collected
+ if (httpClient instanceof AutoCloseable) {
+ ((AutoCloseable) httpClient).close()
+ }
+ httpClient = null
+ }
+
+ private static String body(HttpResponse<String> response) {
+ String body = response.body() ?: ''
+ body.length() > MAX_ERROR_BODY ? body.substring(0, MAX_ERROR_BODY) + 'ā¦' : body
+ }
+
+ /**
+ * Waits before the next attempt. Unlike Groovy's {@code sleep}, it stops when the build is cancelled.
+ */
+ private static void pause(long millis) {
+ try {
+ Thread.sleep(millis)
+ }
+ catch (InterruptedException e) {
+ Thread.currentThread().interrupt()
+ throw new BuildCancelledException('Cancelled while waiting to ask the API again', e)
+ }
+ }
+
+ private static long retryDelay(HttpResponse<String> response, int attempt) {
+ String retryAfter = response.headers().firstValue('Retry-After').orElse(null)
+ long seconds = retryAfter?.isLong() ? retryAfter.toLong() : (1L << attempt)
+ Duration.ofSeconds(Math.min(seconds, 60L)).toMillis()
+ }
+
+ private synchronized HttpClient client() {
+ if (httpClient == null) {
+ httpClient = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .connectTimeout(Duration.ofSeconds(30))
+ .proxy(ProxySelector.default)
+ .build()
+ }
+ httpClient
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/BuiltInExclusions.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/BuiltInExclusions.groovy
new file mode 100644
index 0000000..37125ea
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/BuiltInExclusions.groovy
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import groovy.transform.CompileStatic
+
+/**
+ * The vulnerabilities no project of this build reports.
+ *
+ * <p>Exclusions are limited to vulnerabilities with no available upstream fix, a breaking major-version upgrade, or
+ * a maintainer-approved false positive backed by an upstream advisory. Everything with a published compatible fix
+ * must be bumped instead. Each entry names the vulnerability, the module, the reason and the removal condition, and
+ * is revisited whenever the dependency moves. The list is empty until a real, unfixable finding is encountered.</p>
+ *
+ * <p>A single project excludes a vulnerability of its own with {@code vulnerabilityScan { exclude(...) }} in its
+ * build file, which adds to this list.</p>
+ */
+@CompileStatic
+final class BuiltInExclusions {
+
+ static final List<VulnerabilityExclusion> EXCLUSIONS = [].asImmutable() as List<VulnerabilityExclusion>
+
+ private BuiltInExclusions() {
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/CvssV3.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/CvssV3.groovy
new file mode 100644
index 0000000..373c9ba
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/CvssV3.groovy
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.math.RoundingMode
+
+import groovy.transform.CompileStatic
+
+/**
+ * Scores a CVSS v3.0 or v3.1 vector string, such as {@code CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H}, as the
+ * <a href="https://www.first.org/cvss/v3.1/specification-document">specification</a> defines the base score. OSV
+ * records often carry only the vector, so this is what their severity is rated from.
+ */
+@CompileStatic
+final class CvssV3 {
+
+ private static final Map<String, Map<String, Double>> METRICS = [
+ AV: [N: 0.85d, A: 0.62d, L: 0.55d, P: 0.2d],
+ AC: [L: 0.77d, H: 0.44d],
+ PR: [N: 0.85d, L: 0.62d, H: 0.27d],
+ UI: [N: 0.85d, R: 0.62d],
+ C : [H: 0.56d, L: 0.22d, N: 0d],
+ I : [H: 0.56d, L: 0.22d, N: 0d],
+ A : [H: 0.56d, L: 0.22d, N: 0d],
+ ]
+ /** The privileges required when the scope changes. */
+ private static final Map<String, Double> PR_CHANGED = [N: 0.85d, L: 0.68d, H: 0.5d]
+
+ private CvssV3() {
+ }
+
+ /**
+ * The base score of the vector, or {@code null} when it is not a complete CVSS v3 vector.
+ */
+ static BigDecimal baseScore(String vector) {
+ if (!vector?.startsWith('CVSS:3.')) {
+ return null
+ }
+ Map<String, String> values = [:]
+ for (String metric : vector.split('/').drop(1)) {
+ int separator = metric.indexOf(':')
+ if (separator > 0) {
+ values.put(metric.substring(0, separator), metric.substring(separator + 1))
+ }
+ }
+ String scope = values.get('S')
+ if (!(scope in ['U', 'C']) || !METRICS.keySet().every { String name -> METRICS.get(name).containsKey(values.get(name)) }) {
+ return null
+ }
+ boolean changed = scope == 'C'
+ double impactSubScore = 1 - (1 - metric('C', values)) * (1 - metric('I', values)) * (1 - metric('A', values))
+ double impact = changed ?
+ 7.52d * (impactSubScore - 0.029d) - 3.25d * Math.pow(impactSubScore - 0.02d, 15) :
+ 6.42d * impactSubScore
+ double privileges = changed ? PR_CHANGED.get(values.get('PR')) : metric('PR', values)
+ double exploitability = 8.22d * metric('AV', values) * metric('AC', values) * privileges * metric('UI', values)
+ if (impact <= 0) {
+ return BigDecimal.ZERO
+ }
+ roundUp(Math.min(changed ? 1.08d * (impact + exploitability) : impact + exploitability, 10d))
+ }
+
+ private static double metric(String name, Map<String, String> values) {
+ METRICS.get(name).get(values.get(name))
+ }
+
+ /**
+ * Rounds up to one decimal place the way CVSS v3.1 specifies, which keeps floating point noise from pushing a
+ * score such as 4.0 up to 4.1.
+ */
+ private static BigDecimal roundUp(double value) {
+ long scaled = Math.round(value * 100_000d)
+ if (scaled % 10_000 == 0) {
+ return BigDecimal.valueOf(scaled, 5).setScale(1, RoundingMode.UNNECESSARY)
+ }
+ BigDecimal.valueOf((long) Math.floor(scaled / 10_000d) + 1, 1)
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityService.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityService.groovy
new file mode 100644
index 0000000..0c70167
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityService.groovy
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.net.http.HttpRequest
+import java.nio.charset.StandardCharsets
+import java.nio.file.Path
+import java.time.Duration
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.json.JsonOutput
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.services.BuildService
+import org.gradle.api.services.BuildServiceParameters
+
+/**
+ * Looks the vulnerabilities of Maven artifacts up in the <a href="https://osv.dev">OSV</a> database.
+ *
+ * <p>Every answer is kept on disk for {@link Parameters#getCacheTtl() a while}, so builds that run again shortly
+ * after, in this or another checkout sharing the cache directory, do not ask the API again. Entries older than that
+ * are fetched again.</p>
+ *
+ * <p>The service is shared by the scan tasks of every project and asks the API one task at a time, which keeps the
+ * build well under the API's rate limits.</p>
+ */
+@CompileStatic
+abstract class OsvVulnerabilityService implements BuildService<Parameters>, AutoCloseable {
+
+ static final String NAME = 'OSV'
+ static final String DEFAULT_API_URL = 'https://api.osv.dev'
+ static final Duration DEFAULT_CACHE_TTL = Duration.ofHours(1)
+
+ private static final int BATCH_SIZE = 1000
+
+ interface Parameters extends BuildServiceParameters {
+
+ /** The OSV API, {@value OsvVulnerabilityService#DEFAULT_API_URL} unless a test points it elsewhere. */
+ Property<String> getApiUrl()
+
+ /** Where the answers of the API are kept between builds, shared with the other databases. */
+ DirectoryProperty getCacheDirectory()
+
+ /** How long an answer is used before the API is asked again. */
+ Property<Duration> getCacheTtl()
+ }
+
+ private final Map<String, List<String>> idsByCoordinate = new ConcurrentHashMap<>()
+ private final Map<String, Map<String, Object>> vulnerabilitiesById = new ConcurrentHashMap<>()
+ private final ApiClient client = new ApiClient('OSV API')
+ private ApiCache queryCache
+ private ApiCache vulnerabilityCache
+
+ /**
+ * Returns the vulnerabilities known for each of the given {@code group:artifact:version} coordinates, as the
+ * OSV records of them.
+ */
+ synchronized Map<String, List<Map<String, Object>>> vulnerabilities(Collection<String> coordinates) {
+ Collection<String> unique = coordinates.toUnique()
+ List<String> missing = unique.findAll { String coordinate -> idsFor(coordinate) == null }.toList()
+ if (missing) {
+ queryIds(missing)
+ }
+
+ Map<String, List<Map<String, Object>>> vulnerabilities = [:]
+ for (String coordinate : unique) {
+ vulnerabilities.put(coordinate, idsByCoordinate.get(coordinate).collect { String id -> vulnerability(id) })
+ }
+ vulnerabilities
+ }
+
+ @Override
+ void close() {
+ client.close()
+ }
+
+ private List<String> idsFor(String coordinate) {
+ List<String> ids = idsByCoordinate.get(coordinate)
+ if (ids == null) {
+ Map<String, Object> cached = queryCache().read(coordinate)
+ if (cached != null) {
+ ids = (List<String>) cached.get('ids')
+ idsByCoordinate.put(coordinate, ids)
+ }
+ }
+ ids
+ }
+
+ private void queryIds(List<String> coordinates) {
+ coordinates.collate(BATCH_SIZE).each { List<String> batch ->
+ Map<String, List<String>> ids = batch.collectEntries { [(it): new ArrayList<String>()] }
+ Map<String, String> pageTokens = [:]
+ List<String> pending = batch
+ while (pending) {
+ List<Map<String, Object>> queries = pending.collect { String coordinate -> query(coordinate, pageTokens.get(coordinate)) }
+ List<Map<String, Object>> results = resultsOf(ApiClient.json(client.send(post('/v1/querybatch', [queries: queries]))))
+ if (results.size() != pending.size()) {
+ // recording the coordinates without a result as clean would cache that for every build
+ throw new GradleException("The OSV API answered ${pending.size()} queries with ${results.size()} results")
+ }
+ pageTokens.clear()
+ pending.eachWithIndex { String coordinate, int index ->
+ Map<String, Object> result = results[index] ?: [:]
+ ids.get(coordinate).addAll(((List<Map<String, Object>>) result.get('vulns') ?: []).collect { it.get('id') as String })
+ if (result.get('next_page_token')) {
+ pageTokens.put(coordinate, result.get('next_page_token') as String)
+ }
+ }
+ pending = pending.findAll { pageTokens.containsKey(it) }
+ }
+ ids.each { String coordinate, List<String> found ->
+ List<String> sorted = found.toUnique().sort()
+ idsByCoordinate.put(coordinate, sorted)
+ queryCache().write(coordinate, [coordinate: coordinate, ids: sorted])
+ }
+ }
+ }
+
+ private Map<String, Object> vulnerability(String id) {
+ Map<String, Object> vulnerability = vulnerabilitiesById.get(id)
+ if (vulnerability == null) {
+ Map<String, Object> cached = vulnerabilityCache().read(id)
+ vulnerability = cached != null ? (Map<String, Object>) cached.get('vulnerability') : null
+ if (vulnerability == null) {
+ vulnerability = (Map<String, Object>) ApiClient.json(client.send(
+ request("/v1/vulns/${URLEncoder.encode(id, StandardCharsets.UTF_8)}").GET().build()))
+ vulnerabilityCache().write(id, [vulnerability: vulnerability])
+ }
+ vulnerabilitiesById.put(id, vulnerability)
+ }
+ vulnerability
+ }
+
+ private static Map<String, Object> query(String coordinate, String pageToken) {
+ int versionSeparator = coordinate.lastIndexOf(':')
+ Map<String, Object> query = [
+ package: [ecosystem: 'Maven', name: coordinate.substring(0, versionSeparator)],
+ version: coordinate.substring(versionSeparator + 1),
+ ] as Map<String, Object>
+ if (pageToken) {
+ query.put('page_token', pageToken)
+ }
+ query
+ }
+
+ @CompileDynamic
+ private static List<Map<String, Object>> resultsOf(Object response) {
+ response?.results ?: []
+ }
+
+ private HttpRequest post(String path, Object body) {
+ request(path)
+ .header('Content-Type', 'application/json')
+ .POST(HttpRequest.BodyPublishers.ofString(JsonOutput.toJson(body)))
+ .build()
+ }
+
+ private HttpRequest.Builder request(String path) {
+ HttpRequest.newBuilder(URI.create(parameters.apiUrl.get().replaceAll('/+$', '') + path))
+ .timeout(Duration.ofSeconds(60))
+ .header('Accept', 'application/json')
+ }
+
+ private synchronized ApiCache queryCache() {
+ queryCache = queryCache ?: new ApiCache(cacheRoot().resolve('queries'), parameters.cacheTtl.get())
+ }
+
+ private synchronized ApiCache vulnerabilityCache() {
+ vulnerabilityCache = vulnerabilityCache ?: new ApiCache(cacheRoot().resolve('vulns'), parameters.cacheTtl.get())
+ }
+
+ private Path cacheRoot() {
+ parameters.cacheDirectory.get().asFile.toPath().resolve('osv')
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityService.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityService.groovy
new file mode 100644
index 0000000..c2aa0fe
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityService.groovy
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+import java.nio.charset.StandardCharsets
+import java.time.Duration
+import java.util.concurrent.ConcurrentHashMap
+
+import groovy.json.JsonOutput
+import groovy.transform.CompileStatic
+
+import org.gradle.api.GradleException
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.gradle.api.provider.Property
+import org.gradle.api.services.BuildService
+import org.gradle.api.services.BuildServiceParameters
+
+/**
+ * Looks the vulnerabilities of Maven artifacts up in <a href="https://guide.sonatype.com">Sonatype Guide</a>, the
+ * successor of OSS Index, through its component report API.
+ *
+ * <p>The API needs an account: the user name and personal access token are read from the
+ * {@value #USERNAME_VARIABLE} and {@value #TOKEN_VARIABLE} environment variables when a scan runs, so they never
+ * become part of the configuration cache. Without a token the database is not consulted.</p>
+ *
+ * <p>Every lookup costs credits of the account, so the answers are kept on disk for
+ * {@link Parameters#getCacheTtl() a while} and each component is looked up once however many projects use it. The
+ * credits a build used are logged when it finishes.</p>
+ */
+@CompileStatic
+abstract class SonatypeGuideVulnerabilityService implements BuildService<Parameters>, AutoCloseable {
+
+ static final String NAME = 'Sonatype Guide'
+ static final String DEFAULT_API_URL = 'https://ossindex.sonatype.org'
+ static final String USERNAME_VARIABLE = 'SONATYPE_GUIDE_USERNAME'
+ static final String TOKEN_VARIABLE = 'SONATYPE_GUIDE_TOKEN'
+
+ private static final Logger LOG = Logging.getLogger(SonatypeGuideVulnerabilityService)
+ private static final int BATCH_SIZE = 128
+ private static final String REQUEST_TYPE = 'application/vnd.ossindex.component-report-request.v1+json'
+ private static final String REPORT_TYPE = 'application/vnd.ossindex.component-report.v1+json'
+
+ interface Parameters extends BuildServiceParameters {
+
+ /** The API, {@value SonatypeGuideVulnerabilityService#DEFAULT_API_URL} unless a test points it elsewhere. */
+ Property<String> getApiUrl()
+
+ /** Where the answers of the API are kept between builds, shared with the other databases. */
+ DirectoryProperty getCacheDirectory()
+
+ /** How long an answer is used before the API is asked again. */
+ Property<Duration> getCacheTtl()
+
+ /** The environment variable holding the user name, {@value SonatypeGuideVulnerabilityService#USERNAME_VARIABLE}. */
+ Property<String> getUsernameVariable()
+
+ /** The environment variable holding the personal access token, {@value SonatypeGuideVulnerabilityService#TOKEN_VARIABLE}. */
+ Property<String> getTokenVariable()
+ }
+
+ private final Map<String, List<Map<String, Object>>> vulnerabilitiesByCoordinate = new ConcurrentHashMap<>()
+ private final ApiClient client = new ApiClient('Sonatype Guide API')
+ private ApiCache cache
+ private int lookedUp
+ private BigDecimal creditsUsed = BigDecimal.ZERO
+ private String creditsRemaining
+
+ /**
+ * Why the database cannot be consulted, or {@code null} when it can.
+ */
+ String unavailableReason() {
+ variable(parameters.tokenVariable.get()) ? null : "${parameters.tokenVariable.get()} is not set"
+ }
+
+ /**
+ * Returns the vulnerabilities known for each of the given {@code group:artifact:version} coordinates, as the
+ * component report entries of them.
+ */
+ synchronized Map<String, List<Map<String, Object>>> vulnerabilities(Collection<String> coordinates) {
+ String unavailable = unavailableReason()
+ if (unavailable) {
+ throw new IllegalStateException("${NAME} cannot be consulted: ${unavailable}")
+ }
+ Collection<String> unique = coordinates.toUnique()
+ List<String> missing = unique.findAll { String coordinate -> cached(coordinate) == null }.toList()
+ missing.collate(BATCH_SIZE).each { List<String> batch -> report(batch) }
+
+ Map<String, List<Map<String, Object>>> vulnerabilities = [:]
+ for (String coordinate : unique) {
+ vulnerabilities.put(coordinate, vulnerabilitiesByCoordinate.get(coordinate))
+ }
+ vulnerabilities
+ }
+
+ @Override
+ void close() {
+ client.close()
+ if (lookedUp) {
+ LOG.lifecycle('{} looked up {} {}, using {} credits{}', NAME, lookedUp,
+ lookedUp == 1 ? 'component' : 'components', creditsUsed.stripTrailingZeros().toPlainString(),
+ creditsRemaining != null ? "; ${creditsRemaining} remain" : '')
+ }
+ }
+
+ /**
+ * The package URL Sonatype Guide knows a {@code group:artifact:version} coordinate by.
+ */
+ static String packageUrl(String coordinate) {
+ List<String> parts = coordinate.split(':').toList()
+ "pkg:maven/${encode(parts[0])}/${encode(parts[1])}@${encode(parts[2])}"
+ }
+
+ private List<Map<String, Object>> cached(String coordinate) {
+ List<Map<String, Object>> vulnerabilities = vulnerabilitiesByCoordinate.get(coordinate)
+ if (vulnerabilities == null) {
+ Map<String, Object> entry = cache().read(coordinate)
+ if (entry != null) {
+ vulnerabilities = (List<Map<String, Object>>) entry.get('vulnerabilities')
+ vulnerabilitiesByCoordinate.put(coordinate, vulnerabilities)
+ }
+ }
+ vulnerabilities
+ }
+
+ private void report(List<String> batch) {
+ List<String> packageUrls = batch.collect { packageUrl(it) }
+ HttpResponse<String> response = client.send(HttpRequest.newBuilder(
+ URI.create(parameters.apiUrl.get().replaceAll('/+$', '') + '/api/v3/component-report'))
+ .timeout(Duration.ofSeconds(60))
+ .header('Content-Type', REQUEST_TYPE)
+ .header('Accept', REPORT_TYPE)
+ .header('Authorization', authorization())
+ .POST(HttpRequest.BodyPublishers.ofString(JsonOutput.toJson([coordinates: packageUrls])))
+ .build(), [
+ 401: credentialsHint(),
+ 402: 'the account has no credits left',
+ 403: credentialsHint(),
+ ])
+ countCredits(response, batch.size())
+
+ List<Map<String, Object>> reports = (List<Map<String, Object>>) ApiClient.json(response)
+ // the API may echo a package URL in another case or encoding, and in another order than it was asked
+ Map<String, Map<String, Object>> reportsByPackageUrl = [:]
+ for (Map<String, Object> report : reports) {
+ String echoed = report.get('coordinates') as String
+ if (echoed) {
+ reportsByPackageUrl.put(normalize(echoed), report)
+ }
+ }
+ batch.eachWithIndex { String coordinate, int index ->
+ Map<String, Object> report = reportsByPackageUrl.get(normalize(packageUrls[index]))
+ if (report == null) {
+ // not the report at the same position: that would attribute another component's vulnerabilities
+ throw new GradleException("The ${NAME} API did not report on ${packageUrls[index]}")
+ }
+ List<Map<String, Object>> vulnerabilities = (List<Map<String, Object>>) report.get('vulnerabilities') ?: []
+ vulnerabilitiesByCoordinate.put(coordinate, vulnerabilities)
+ cache().write(coordinate, [coordinate: coordinate, vulnerabilities: vulnerabilities])
+ }
+ }
+
+ /**
+ * The form in which the package URL that was sent and the one the API echoes compare equal: percent-decoded, in
+ * lower case.
+ */
+ static String normalize(String packageUrl) {
+ try {
+ // a literal plus stays one: URLDecoder would turn it into a space
+ URLDecoder.decode(packageUrl.replace('+', '%2B'), StandardCharsets.UTF_8).toLowerCase(Locale.ROOT)
+ }
+ catch (IllegalArgumentException ignored) {
+ packageUrl.toLowerCase(Locale.ROOT)
+ }
+ }
+
+ private void countCredits(HttpResponse<String> response, int components) {
+ lookedUp += components
+ String used = response.headers().firstValue('x-credits-used').orElse(null)
+ if (used?.isBigDecimal()) {
+ creditsUsed += used.toBigDecimal()
+ }
+ creditsRemaining = response.headers().firstValue('x-credits-remaining').orElse(creditsRemaining)
+ }
+
+ private String credentialsHint() {
+ "check ${parameters.usernameVariable.get()} and ${parameters.tokenVariable.get()}".toString()
+ }
+
+ private String authorization() {
+ String credentials = "${variable(parameters.usernameVariable.get()) ?: ''}:${variable(parameters.tokenVariable.get())}"
+ "Basic ${credentials.getBytes(StandardCharsets.UTF_8).encodeBase64()}"
+ }
+
+ private synchronized ApiCache cache() {
+ cache = cache ?: new ApiCache(parameters.cacheDirectory.get().asFile.toPath().resolve('sonatype-guide'),
+ parameters.cacheTtl.get())
+ }
+
+ private static String variable(String name) {
+ System.getenv(name) ?: null
+ }
+
+ private static String encode(String value) {
+ StringBuilder encoded = new StringBuilder()
+ for (byte b : value.getBytes(StandardCharsets.UTF_8)) {
+ char c = (char) (b & 0xff)
+ if ((c >= ('a' as char) && c <= ('z' as char)) || (c >= ('A' as char) && c <= ('Z' as char)) ||
+ (c >= ('0' as char) && c <= ('9' as char)) || '.-_~'.indexOf((int) c) >= 0) {
+ encoded.append(c)
+ }
+ else {
+ encoded.append('%').append(String.format('%02X', b & 0xff))
+ }
+ }
+ encoded.toString()
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusion.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusion.groovy
new file mode 100644
index 0000000..3534129
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusion.groovy
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import groovy.transform.CompileStatic
+import groovy.transform.EqualsAndHashCode
+import groovy.transform.ToString
+
+/**
+ * A known vulnerability the scan does not report.
+ *
+ * <p>An exclusion names a vulnerability by any of its identifiers (its OSV or Sonatype Guide id, or an alias such as
+ * its CVE), the module ({@code group:artifact}) it is excluded for, or {@code null} for every module, and the reason
+ * it is excluded. It applies to every version of the module, so a dependency upgrade does not leave it behind
+ * unnoticed: the report lists the exclusions that no longer match anything.</p>
+ */
+@CompileStatic
+@EqualsAndHashCode
+@ToString(includeNames = true)
+final class VulnerabilityExclusion implements Serializable {
+
+ private static final long serialVersionUID = 1L
+
+ final String vulnerabilityId
+ final String module
+ final String reason
+
+ VulnerabilityExclusion(String vulnerabilityId, String module, String reason) {
+ if (!vulnerabilityId) {
+ throw new IllegalArgumentException('An exclusion must name the vulnerability it excludes')
+ }
+ if (!reason) {
+ throw new IllegalArgumentException("The exclusion of ${vulnerabilityId} must give its reason")
+ }
+ this.vulnerabilityId = vulnerabilityId
+ this.module = module
+ this.reason = reason
+ }
+
+ /**
+ * Whether this excludes a vulnerability of the module. Ids are compared regardless of case, as the databases
+ * that report them are merged.
+ *
+ * @param module the {@code group:artifact} of the vulnerable dependency
+ * @param vulnerabilityIds the ids of the vulnerability in the databases that reported it, and its aliases
+ */
+ boolean matches(String module, Collection<String> vulnerabilityIds) {
+ (this.module == null || this.module == module) && vulnerabilityIds.any { String id -> id.equalsIgnoreCase(vulnerabilityId) }
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanExtension.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanExtension.groovy
new file mode 100644
index 0000000..d39e896
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanExtension.groovy
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import groovy.transform.CompileStatic
+
+import org.gradle.api.provider.ListProperty
+import org.gradle.api.provider.Property
+
+/**
+ * Configures the {@link VulnerabilityScanTask vulnerability scan} of a project, as the {@code vulnerabilityScan}
+ * extension registered by the {@code org.apache.grails.intellij.build.vulnerability-scan} convention plugin.
+ */
+@CompileStatic
+abstract class VulnerabilityScanExtension {
+
+ /** The configurations whose dependencies are scanned, {@code runtimeClasspath} and {@code compileClasspath} unless set. */
+ abstract ListProperty<String> getConfigurations()
+
+ /**
+ * The dependency groups the scan leaves out. The IntelliJ Platform Gradle Plugin presents the IDE's own modules
+ * and bundled plugins as Maven-like components ({@code bundledModule:intellij.platform.core:IU-...}) that no
+ * vulnerability database knows; looking them up only costs Sonatype Guide credits.
+ */
+ abstract ListProperty<String> getIgnoredGroups()
+
+ /** The vulnerabilities the scan does not report. */
+ abstract ListProperty<VulnerabilityExclusion> getExclusions()
+
+ /** Whether to only report the vulnerabilities instead of failing the build. */
+ abstract Property<Boolean> getIgnoreFailures()
+
+ /**
+ * Excludes a vulnerability from the scan.
+ *
+ * @param vulnerabilityId the OSV or Sonatype Guide id of the vulnerability, or one of its aliases such as its CVE
+ * @param module the {@code group:artifact} it is excluded for, or {@code null} for every module
+ * @param reason why it is excluded and when the exclusion can be removed
+ */
+ void exclude(String vulnerabilityId, String module, String reason) {
+ exclusions.add(new VulnerabilityExclusion(vulnerabilityId, module, reason))
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTask.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTask.groovy
new file mode 100644
index 0000000..70d988b
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTask.groovy
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.charset.StandardCharsets
+
+import groovy.json.JsonSlurper
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.InputFiles
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+import org.gradle.api.tasks.UntrackedTask
+
+/**
+ * Summarizes the reports of {@link VulnerabilityScanTask vulnerability scans} in Markdown: each vulnerable
+ * dependency once, with the projects it was found in and the databases that know of each vulnerability, the
+ * vulnerabilities that were excluded, and the exclusions that no longer match anything. The last are only listed
+ * when every database was consulted.
+ */
+@CompileStatic
+@UntrackedTask(because = 'It summarizes scans whose results change without the build changing')
+abstract class VulnerabilityScanReportTask extends DefaultTask {
+
+ static final String TASK_NAME = 'vulnerabilityScanReport'
+
+ /** Where the summary is written, relative to the root project's build directory. */
+ static final String SUMMARY_PATH = 'reports/vulnerability-scan/summary.md'
+
+ private static final String TRUNCATED = '\n⦠truncated; the workflow run has the complete report.\n'
+
+ /** The reports of the scans; those that do not exist are skipped. */
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ abstract ConfigurableFileCollection getReports()
+
+ /** Keeps the whole summary within this many bytes; {@code 0} keeps all of it. */
+ @Input
+ abstract Property<Integer> getMaxBytes()
+
+ @OutputFile
+ abstract RegularFileProperty getSummaryFile()
+
+ @TaskAction
+ void summarize() {
+ List<Map<String, Object>> scans = reports.files.findAll { it.isFile() }.sort().collect { File file ->
+ (Map<String, Object>) new JsonSlurper().parse(file)
+ }
+ File summary = summaryFile.get().asFile
+ summary.parentFile.mkdirs()
+ summary.text = render(scans, maxBytes.get())
+ logger.lifecycle('Vulnerability scan summary: {}', summary)
+ }
+
+ @CompileDynamic
+ static String render(List<Map<String, Object>> scans, int maxBytes) {
+ if (!scans) {
+ return 'No vulnerability scan reports were found. Run the `vulnerabilityScan` tasks first.\n'
+ }
+
+ Map<String, Map<String, Object>> findings = [:]
+ scans.each { scan ->
+ scan.findings.each { finding ->
+ Map<String, Object> merged = findings.computeIfAbsent("${finding.dependency} ${finding.id}" as String) {
+ finding + [projects: new TreeSet<String>()]
+ }
+ merged.projects << scan.project
+ }
+ }
+
+ // a scan whose lookup failed reports an error instead of findings: its dependencies were not checked
+ List<Map<String, Object>> failed = scans.findAll { it.error }
+ int scanned = scans.count { !it.error } as int
+ String sources = sourcesLine(scans) + failedLine(failed)
+ StringBuilder head = new StringBuilder()
+ StringBuilder listing = new StringBuilder()
+ if (findings) {
+ Map<String, List<Map<String, Object>>> byDependency = findings.values().groupBy { it.dependency }.sort()
+ head << "ā ${findings.size()} known ${findings.size() == 1 ? 'vulnerability' : 'vulnerabilities'} in " +
+ "${byDependency.size()} ${byDependency.size() == 1 ? 'dependency' : 'dependencies'} " +
+ "of ${scanned} scanned ${scanned == 1 ? 'project' : 'projects'}.\n"
+ head << sources
+ byDependency.each { String dependency, List<Map<String, Object>> found ->
+ listing << "\n### ${dependency}\n\n"
+ listing << '| Vulnerability | Severity | Fixed in | Found by | Summary |\n'
+ listing << '| --- | --- | --- | --- | --- |\n'
+ found.sort { it.id }.each { finding ->
+ String aliases = finding.aliases ? " (${finding.aliases.join(', ')})" : ''
+ String foundBy = (finding.sources ?: []).collect { "[${it.name}](${it.url})" }.join(', ')
+ listing << "| [${finding.id}](${finding.url})${aliases} | ${finding.severity} | " +
+ "${finding.fixedVersions ? finding.fixedVersions.join(', ') : 'none known'} | ${foundBy} | " +
+ "${cell(finding.summary)} |\n"
+ }
+ Set<String> projects = found.collectMany { it.projects } as TreeSet<String>
+ listing << "\nFound in ${projects.collect { '`' + it + '`' }.join(', ')}, " +
+ "via `${found.first().path.join(' āŗ ')}`\n"
+ }
+ }
+ else if (failed) {
+ head << "ā ļø No known vulnerabilities in the dependencies of ${scanned} scanned " +
+ "${scanned == 1 ? 'project' : 'projects'}, but not every project could be scanned.\n"
+ head << sources
+ }
+ else {
+ head << "ā
No known vulnerabilities in the dependencies of ${scanned} scanned " +
+ "${scanned == 1 ? 'project' : 'projects'}.\n"
+ head << sources
+ }
+
+ Map<String, Map<String, Object>> excluded = [:]
+ scans.each { scan ->
+ scan.excluded.each { finding -> excluded.putIfAbsent("${finding.dependency} ${finding.id}" as String, finding) }
+ }
+ StringBuilder excludedSection = new StringBuilder()
+ if (excluded) {
+ excludedSection << '\n### Excluded\n\n'
+ excluded.values().sort { "${it.dependency} ${it.id}" }.each { finding ->
+ excludedSection << "- ${finding.dependency}: [${finding.id}](${finding.url}) - ${finding.reason}\n"
+ }
+ }
+
+ Set<String> used = excluded.values().collect { "${it.exclusion} ${it.dependency.split(':').take(2).join(':')}" } as Set<String>
+ List<Map<String, Object>> unused = scans.collectMany { it.exclusions ?: [] }.unique().findAll { exclusion ->
+ !used.any { it.startsWith("${exclusion.vulnerabilityId} ") && (exclusion.module == null || it.endsWith(" ${exclusion.module}")) }
+ }
+ // an exclusion of a vulnerability only a database that was not consulted knows of matches nothing either
+ // nor does one that only matched in a project whose scan failed
+ boolean allConsulted = !scans.any { it.unavailableSources } && !failed
+ StringBuilder unusedSection = new StringBuilder()
+ if (unused && allConsulted) {
+ unusedSection << '\n### Exclusions that match nothing\n\n'
+ unused.each { exclusion ->
+ unusedSection << "- ${exclusion.vulnerabilityId}${exclusion.module ? " for ${exclusion.module}" : ''}: " +
+ 'remove it, the scanned dependencies no longer have this vulnerability\n'
+ }
+ }
+ fit([head.toString(), listing.toString(), excludedSection.toString(), unusedSection.toString()], maxBytes)
+ }
+
+ /**
+ * Joins the sections of the summary, keeping the whole of it within the limit so that it fits where it is posted.
+ * The first section that does not fit is cut at a line and those after it are left out: the findings come
+ * before the exclusions, so a long list of exclusions never pushes them out.
+ */
+ static String fit(List<String> sections, int maxBytes) {
+ if (maxBytes <= 0) {
+ return sections.join('')
+ }
+ StringBuilder text = new StringBuilder()
+ for (String section : sections) {
+ if (utf8Length(text.toString() + section) <= maxBytes) {
+ text << section
+ continue
+ }
+ // the notice takes the place of the end of the text, so that it still fits
+ byte[] bytes = (text.toString() + section).getBytes(StandardCharsets.UTF_8)
+ int budget = maxBytes - utf8Length(TRUNCATED)
+ // whole lines only: the cut may land inside a table row or a multi-byte character
+ String kept = budget > 0 ? new String(bytes, 0, Math.min(budget, bytes.length), StandardCharsets.UTF_8).replaceAll(/[^\n]*$/, '') : ''
+ return kept + TRUNCATED
+ }
+ text.toString()
+ }
+
+ private static int utf8Length(String text) {
+ text.getBytes(StandardCharsets.UTF_8).length
+ }
+
+ /**
+ * Which databases the scans consulted, and why the others were not.
+ */
+ @CompileDynamic
+ static String sourcesLine(List<Map<String, Object>> scans) {
+ Set<String> consulted = scans.collectMany { it.sources ?: [] } as LinkedHashSet<String>
+ Map<String, String> unavailable = [:]
+ scans.each { scan -> (scan.unavailableSources ?: []).each { unavailable.putIfAbsent(it.name, it.reason) } }
+ StringBuilder line = new StringBuilder()
+ if (consulted) {
+ line << "\nChecked against ${consulted.join(' and ')}.\n"
+ }
+ unavailable.each { String name, String reason ->
+ line << "\nā ļø ${name} was not consulted: ${reason}.\n"
+ }
+ line.toString()
+ }
+
+ /**
+ * The scans that failed, so their projects' dependencies were not checked.
+ */
+ @CompileDynamic
+ static String failedLine(List<Map<String, Object>> failed) {
+ if (!failed) {
+ return ''
+ }
+ StringBuilder line = new StringBuilder("\nā ļø The ${failed.size() == 1 ? 'scan of 1 project' : "scans of ${failed.size()} projects"} " +
+ 'failed, so ' + (failed.size() == 1 ? 'its dependencies were' : 'their dependencies were') + ' not checked:\n\n')
+ failed.sort { it.project }.each { scan ->
+ String error = cell(scan.error)
+ line << "- `${scan.project}`: ${error.length() > 300 ? error.substring(0, 300) + 'ā¦' : error}\n"
+ }
+ line.toString()
+ }
+
+ private static String cell(Object value) {
+ String.valueOf(value ?: '').replace('|', '\\|').replace('\n', ' ')
+ }
+}
diff --git a/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTask.groovy b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTask.groovy
new file mode 100644
index 0000000..84c1f29
--- /dev/null
+++ b/build-logic/src/main/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTask.groovy
@@ -0,0 +1,415 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.file.Files
+
+import groovy.json.JsonOutput
+import groovy.transform.CompileDynamic
+import groovy.transform.CompileStatic
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.GradleException
+import org.gradle.api.artifacts.Configuration
+import org.gradle.api.artifacts.ConfigurationContainer
+import org.gradle.api.artifacts.component.ModuleComponentIdentifier
+import org.gradle.api.artifacts.result.DependencyResult
+import org.gradle.api.artifacts.result.ResolvedComponentResult
+import org.gradle.api.artifacts.result.ResolvedDependencyResult
+import org.gradle.api.artifacts.result.UnresolvedDependencyResult
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.ListProperty
+import org.gradle.api.provider.MapProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.Internal
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.TaskAction
+import org.gradle.api.tasks.UntrackedTask
+
+/**
+ * Reports the known vulnerabilities of the external dependencies a project resolves, and fails when there are any
+ * that are not {@link #getExclusions() excluded}.
+ *
+ * <p>The dependencies come from the resolved dependency graphs of the {@link #getConfigurations() configurations}.
+ * Their vulnerabilities come from two databases, which each know of vulnerabilities the other does not yet: the
+ * <a href="https://osv.dev">OSV</a> database through the {@link OsvVulnerabilityService}, and Sonatype Guide through
+ * the {@link SonatypeGuideVulnerabilityService} when its credentials are set. A vulnerability both know of, by its
+ * id or one of its aliases such as its CVE, is reported once. The task writes what it found to
+ * {@link #getReportFile()}.</p>
+ *
+ * <p>Ported from grails-core's build-logic ({@code vulnerability-scan}); the {@link #getIgnoredGroups() ignored
+ * groups} are this build's addition, for the IntelliJ Platform components on every compile classpath.</p>
+ */
+@CompileStatic
+@UntrackedTask(because = 'The vulnerabilities known for a dependency change without the build changing')
+abstract class VulnerabilityScanTask extends DefaultTask {
+
+ static final String TASK_NAME = 'vulnerabilityScan'
+
+ /** Where each project's scan writes its report, relative to the project's build directory. */
+ static final String REPORT_PATH = 'reports/vulnerability-scan/vulnerabilities.json'
+
+ /** The resolved dependency graph of each scanned configuration, by configuration name. */
+ @Internal
+ abstract MapProperty<String, ResolvedComponentResult> getConfigurations()
+
+ /** The dependency groups that are not scanned, see {@link VulnerabilityScanExtension#getIgnoredGroups()}. */
+ @Input
+ abstract ListProperty<String> getIgnoredGroups()
+
+ @Input
+ abstract ListProperty<VulnerabilityExclusion> getExclusions()
+
+ @Input
+ abstract Property<String> getProjectPath()
+
+ /** Whether to only report the vulnerabilities instead of failing. */
+ @Input
+ abstract Property<Boolean> getIgnoreFailures()
+
+ @OutputFile
+ abstract RegularFileProperty getReportFile()
+
+ @Internal
+ abstract Property<OsvVulnerabilityService> getVulnerabilityService()
+
+ @Internal
+ abstract Property<SonatypeGuideVulnerabilityService> getSonatypeGuideService()
+
+ VulnerabilityScanTask() {
+ ignoreFailures.convention(false)
+ ignoredGroups.convention([])
+ }
+
+ /**
+ * The resolved dependency graphs of the named configurations, leaving out those that do not exist or cannot be
+ * resolved. Only the graph is resolved, never the artifacts, and the result is what the configuration cache
+ * stores for the task.
+ */
+ static Map<String, ResolvedComponentResult> resolutionRoots(ConfigurationContainer configurations, List<String> names) {
+ Map<String, ResolvedComponentResult> roots = [:]
+ for (String name : names) {
+ Configuration configuration = configurations.findByName(name)
+ if (configuration?.canBeResolved) {
+ roots.put(name, configuration.incoming.resolutionResult.rootComponent.get())
+ }
+ }
+ roots
+ }
+
+ @TaskAction
+ void scan() {
+ // a report an earlier run left behind must not stand in for this run's if the scan fails before writing its own
+ Files.deleteIfExists(reportFile.get().asFile.toPath())
+
+ Map<String, List<String>> pathsByCoordinate = [:]
+ List<String> sources = [OsvVulnerabilityService.NAME]
+ List<Map<String, String>> unavailableSources = []
+ Map<String, List<Map<String, Object>>> osv
+ Map<String, List<Map<String, Object>>> sonatype = [:]
+ try {
+ // resolving the graphs is part of the scan: a failure here is reported like one of the lookups
+ Map<String, List<UnresolvedDependencyResult>> unresolved = [:]
+ Set<String> ignored = ignoredGroups.get() as Set<String>
+ int ignoredDependencies = 0
+ configurations.get().each { String configuration, ResolvedComponentResult root ->
+ List<UnresolvedDependencyResult> failures = []
+ collectPaths(root, failures).each { String coordinate, List<String> path ->
+ if (ignored.contains(coordinate.substring(0, coordinate.indexOf(':')))) {
+ ignoredDependencies++
+ return
+ }
+ pathsByCoordinate.putIfAbsent(coordinate, [configuration] + path)
+ }
+ if (failures) {
+ unresolved.put(configuration, failures)
+ }
+ }
+ if (ignoredDependencies) {
+ logger.info('{} left {} {} of the ignored groups {} out of the scan', projectPath.get(), ignoredDependencies,
+ ignoredDependencies == 1 ? 'dependency' : 'dependencies', ignored)
+ }
+ if (unresolved) {
+ // the graph leaves a dependency it could not resolve out, so the scan cannot vouch for the project
+ throw new GradleException(describeUnresolved(unresolved))
+ }
+ osv = vulnerabilityService.get().vulnerabilities(pathsByCoordinate.keySet())
+ SonatypeGuideVulnerabilityService sonatypeGuide = sonatypeGuideService.getOrNull()
+ String sonatypeUnavailable = sonatypeGuide ? sonatypeGuide.unavailableReason() : 'it is not configured'
+ if (sonatypeUnavailable) {
+ unavailableSources << [name: SonatypeGuideVulnerabilityService.NAME, reason: sonatypeUnavailable]
+ logger.info('{} was not consulted for {}: {}', SonatypeGuideVulnerabilityService.NAME, projectPath.get(),
+ sonatypeUnavailable)
+ }
+ else {
+ sources << SonatypeGuideVulnerabilityService.NAME
+ sonatype = sonatypeGuide.vulnerabilities(pathsByCoordinate.keySet())
+ }
+ }
+ catch (Exception e) {
+ // the report tells the summary that this project was not checked, instead of leaving no trace of it
+ writeReport([
+ project : projectPath.get(),
+ dependencies: pathsByCoordinate.size(),
+ error : e.message ?: e.class.name,
+ exclusions : exclusionsOf(),
+ ])
+ throw e
+ }
+
+ List<Map<String, Object>> findings = []
+ List<Map<String, Object>> excluded = []
+ pathsByCoordinate.keySet().sort().each { String coordinate ->
+ String module = coordinate.substring(0, coordinate.lastIndexOf(':'))
+ List<String> path = pathsByCoordinate.get(coordinate)
+ List<Map<String, Object>> found = merge(
+ (osv.get(coordinate) ?: []).collect { finding(coordinate, module, it, path) },
+ (sonatype.get(coordinate) ?: []).collect { sonatypeFinding(coordinate, it, path) })
+ found.each { Map<String, Object> finding ->
+ VulnerabilityExclusion exclusion = exclusions.get().find {
+ it.matches(module, (List<String>) finding.get('ids'))
+ }
+ if (exclusion) {
+ Map<String, Object> excludedFinding = new LinkedHashMap<String, Object>(finding)
+ excludedFinding.put('exclusion', exclusion.vulnerabilityId)
+ excludedFinding.put('reason', exclusion.reason)
+ excluded << excludedFinding
+ }
+ else {
+ findings << finding
+ }
+ }
+ }
+
+ File report = writeReport([
+ project : projectPath.get(),
+ dependencies : pathsByCoordinate.size(),
+ sources : sources,
+ unavailableSources: unavailableSources,
+ findings : findings,
+ excluded : excluded,
+ exclusions : exclusionsOf(),
+ ])
+
+ if (findings) {
+ logger.lifecycle(describe(findings))
+ if (!ignoreFailures.get()) {
+ throw new GradleException("${findings.size()} known ${findings.size() == 1 ? 'vulnerability' : 'vulnerabilities'} " +
+ "in the dependencies of ${projectPath.get()}, see ${report}")
+ }
+ }
+ else {
+ logger.info('No known vulnerabilities in the {} dependencies of {}', pathsByCoordinate.size(), projectPath.get())
+ }
+ }
+
+ private File writeReport(Map<String, Object> content) {
+ File report = reportFile.get().asFile
+ report.parentFile.mkdirs()
+ report.text = JsonOutput.prettyPrint(JsonOutput.toJson(content))
+ report
+ }
+
+ private List<Map<String, String>> exclusionsOf() {
+ exclusions.get().collect { VulnerabilityExclusion it ->
+ [vulnerabilityId: it.vulnerabilityId, module: it.module, reason: it.reason] as Map<String, String>
+ }
+ }
+
+ /**
+ * The external modules of a resolved dependency graph, each with the shortest path the graph reaches it by. A
+ * dependency that could not be resolved is not in the graph, so it cannot be scanned: it is added to
+ * {@code unresolved}.
+ */
+ static Map<String, List<String>> collectPaths(ResolvedComponentResult root, List<UnresolvedDependencyResult> unresolved) {
+ Map<String, List<String>> paths = [:]
+ Set<ResolvedComponentResult> visited = [root] as Set
+ Deque<Tuple2<ResolvedComponentResult, List<String>>> queue = new ArrayDeque<>()
+ queue.add(new Tuple2(root, []))
+ while (!queue.empty) {
+ Tuple2<ResolvedComponentResult, List<String>> next = queue.poll()
+ for (DependencyResult dependency : next.v1.dependencies) {
+ if (dependency instanceof UnresolvedDependencyResult) {
+ unresolved << (UnresolvedDependencyResult) dependency
+ continue
+ }
+ if (!(dependency instanceof ResolvedDependencyResult)) {
+ continue
+ }
+ ResolvedComponentResult selected = ((ResolvedDependencyResult) dependency).selected
+ if (!visited.add(selected)) {
+ continue
+ }
+ List<String> path = next.v2 + [selected.id.displayName]
+ if (selected.id instanceof ModuleComponentIdentifier) {
+ ModuleComponentIdentifier id = (ModuleComponentIdentifier) selected.id
+ paths.put("${id.group}:${id.module}:${id.version}" as String, path)
+ }
+ queue.add(new Tuple2(selected, path))
+ }
+ }
+ paths
+ }
+
+ /**
+ * Names the dependencies that could not be resolved, each once with the configurations it is missing from and
+ * the first line of the reason.
+ */
+ private String describeUnresolved(Map<String, List<UnresolvedDependencyResult>> unresolvedByConfiguration) {
+ Map<String, List<String>> configurationsByDependency = [:]
+ Map<String, String> reasons = [:]
+ unresolvedByConfiguration.each { String configuration, List<UnresolvedDependencyResult> failures ->
+ failures.each { UnresolvedDependencyResult failure ->
+ String dependency = failure.attempted.displayName
+ configurationsByDependency.computeIfAbsent(dependency) { [] } << configuration
+ reasons.putIfAbsent(dependency, failure.failure.message?.readLines()?.find { it.trim() } ?: failure.failure.class.name)
+ }
+ }
+ int count = configurationsByDependency.size()
+ String described = configurationsByDependency.collect { String dependency, List<String> configurations ->
+ "${dependency} of ${configurations.join(' and ')} (${reasons.get(dependency)})"
+ }.join('; ')
+ "${projectPath.get()} could not resolve ${count} ${count == 1 ? 'dependency' : 'dependencies'}, which cannot be scanned: ${described}"
+ }
+
+ @CompileDynamic
+ static Map<String, Object> finding(String coordinate, String module, Map<String, Object> vulnerability, List<String> path) {
+ List<String> ids = ([vulnerability.id] + (vulnerability.aliases ?: [])).findAll().unique() as List<String>
+ [
+ dependency : coordinate,
+ id : vulnerability.id,
+ ids : ids,
+ aliases : (vulnerability.aliases ?: []).sort(),
+ summary : vulnerability.summary ?: (vulnerability.details?.readLines()?.find { it.trim() } ?: ''),
+ severity : severity(vulnerability),
+ fixedVersions : fixedVersions(module, vulnerability),
+ url : "https://osv.dev/vulnerability/${vulnerability.id}" as String,
+ sources : [[name: OsvVulnerabilityService.NAME, url: "https://osv.dev/vulnerability/${vulnerability.id}" as String]],
+ path : path ?: [],
+ ] as Map<String, Object>
+ }
+
+ /**
+ * The finding of a vulnerability Sonatype Guide reported, which it identifies by its CVE where there is one.
+ */
+ @CompileDynamic
+ static Map<String, Object> sonatypeFinding(String coordinate, Map<String, Object> vulnerability, List<String> path) {
+ String id = vulnerability.cve ?: vulnerability.id
+ List<String> ids = [id, vulnerability.id, vulnerability.cve].findAll().unique() as List<String>
+ String url = vulnerability.reference ?: "https://guide.sonatype.com/vulnerability/${id}"
+ String description = vulnerability.description?.readLines()?.find { it.trim() }?.trim()
+ String title = (vulnerability.title ?: '').replaceFirst(/^\[[^\]]*\]\s*/, '')
+ [
+ dependency : coordinate,
+ id : id,
+ ids : ids,
+ aliases : (ids - id).sort(),
+ summary : description ? (description.length() > 200 ? description.substring(0, 200) + 'ā¦' : description) : title,
+ severity : cvssSeverity(vulnerability.cvssScore),
+ fixedVersions : [],
+ url : url,
+ sources : [[name: SonatypeGuideVulnerabilityService.NAME, url: url]],
+ path : path ?: [],
+ ] as Map<String, Object>
+ }
+
+ /**
+ * Adds the findings of Sonatype Guide to those of OSV. One that shares an id or alias with an OSV finding is
+ * merged into it, keeping what OSV knows of the fixed versions; the others are added as they are.
+ */
+ @CompileDynamic
+ static List<Map<String, Object>> merge(List<Map<String, Object>> osv, List<Map<String, Object>> sonatype) {
+ List<Map<String, Object>> merged = osv.collect { new LinkedHashMap<String, Object>(it) }
+ sonatype.each { Map<String, Object> finding ->
+ Set<String> ids = finding.ids*.toUpperCase() as Set<String>
+ Map<String, Object> same = merged.find { existing -> existing.ids.any { ids.contains(it.toUpperCase()) } }
+ if (same) {
+ List<String> newIds = finding.ids.findAll { id -> !same.ids.any { it.equalsIgnoreCase(id) } }
+ same.ids = same.ids + newIds
+ same.aliases = (same.aliases + newIds).sort()
+ same.sources = same.sources + finding.sources
+ if (same.severity == 'UNKNOWN') {
+ same.severity = finding.severity
+ }
+ }
+ else {
+ merged << finding
+ }
+ }
+ merged
+ }
+
+ /**
+ * The qualitative rating of a CVSS score.
+ */
+ static String cvssSeverity(Object score) {
+ if (score == null || !String.valueOf(score).isBigDecimal()) {
+ return 'UNKNOWN'
+ }
+ BigDecimal value = String.valueOf(score).toBigDecimal()
+ String rating = value >= 9 ? 'CRITICAL' : value >= 7 ? 'HIGH' : value >= 4 ? 'MEDIUM' : value > 0 ? 'LOW' : 'NONE'
+ "${rating} (CVSS ${value.stripTrailingZeros().toPlainString()})"
+ }
+
+ /**
+ * The severity of an OSV record: the rating its database gives, or else one computed from a CVSS v3 vector it
+ * carries. A record with only a vector that cannot be scored names the vector's type.
+ */
+ @CompileDynamic
+ static String severity(Map<String, Object> vulnerability) {
+ vulnerability.database_specific?.severity ?:
+ vulnerability.affected?.findResult { it.ecosystem_specific?.severity } ?:
+ vulnerability.severity?.findResult { Map<String, Object> entry ->
+ BigDecimal score = CvssV3.baseScore(entry.score as String)
+ score != null ? cvssSeverity(score) : null
+ } ?:
+ vulnerability.severity?.find()?.type ?:
+ 'UNKNOWN'
+ }
+
+ @CompileDynamic
+ static List<String> fixedVersions(String module, Map<String, Object> vulnerability) {
+ (vulnerability.affected ?: [])
+ .findAll { it.package?.ecosystem == 'Maven' && it.package?.name == module }
+ .collectMany { it.ranges ?: [] }
+ .collectMany { it.events ?: [] }
+ .findResults { it.fixed }
+ .unique() as List<String>
+ }
+
+ private String describe(List<Map<String, Object>> findings) {
+ StringBuilder description = new StringBuilder("${projectPath.get()} - ${findings.size()} known " +
+ "${findings.size() == 1 ? 'vulnerability' : 'vulnerabilities'}:")
+ findings.groupBy { it.get('dependency') }.each { Object dependency, List<Map<String, Object>> found ->
+ description << "\n ${dependency}"
+ found.each { Map<String, Object> finding ->
+ List<String> aliases = (List<String>) finding.get('aliases')
+ description << "\n ${finding.get('id')}${aliases ? " (${aliases.join(', ')})" : ''} " +
+ "${finding.get('severity')}: ${finding.get('summary')}"
+ List<String> fixed = (List<String>) finding.get('fixedVersions')
+ description << "\n ${fixed ? "fixed in ${fixed.join(', ')}" : 'no fixed version known'}; " +
+ "${((List<Map<String, String>>) finding.get('sources')).collect { "${it.name}: ${it.url}" }.join('; ')}"
+ description << "\n via ${((List<String>) finding.get('path')).join(' > ')}"
+ }
+ }
+ description.toString()
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTaskTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTaskTest.groovy
new file mode 100644
index 0000000..98375b3
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/ReproducibleSbomTaskTest.groovy
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.sbom
+
+import groovy.json.JsonSlurper
+import org.gradle.api.GradleException
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+
+/**
+ * The rewrite the task applies to what CycloneDX wrote. The task itself runs in {@link SbomPluginTest}.
+ */
+class ReproducibleSbomTaskTest {
+
+ private static final Logger LOGGER = Logging.getLogger(ReproducibleSbomTaskTest)
+ private static final String TIMESTAMP = '1970-01-01T00:00:00Z'
+
+ @Test
+ void 'the rewritten SBOM is dated as told, records one license per dependency and sorts what resolution ordered'() {
+ Map rendered = render(bom(), ':plugin')
+
+ assertThat(rendered.metadata.timestamp).isEqualTo(TIMESTAMP)
+ Map library = rendered.components.find { it.name == 'library' }
+ assertThat(library.licenses).isEqualTo([[license: [id: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0.txt']]])
+ // an external dependency keeps the hashes of its jar
+ assertThat(library.hashes).isNotEmpty()
+ assertThat(rendered.dependencies.find { it.ref == 'pkg:maven/org.example/app@1.0' }.dependsOn)
+ .isEqualTo(['pkg:maven/org.example/library@1.0?type=jar', 'pkg:maven/org.example/module@1.0?project_path=%3Amodule'])
+ assertThat(rendered.serialNumber as String).startsWith('urn:uuid:')
+ }
+
+ @Test
+ void 'the hashes of the build\'s own projects are dropped, since their jars may not exist yet'() {
+ Map rendered = render(bom(), ':plugin')
+
+ Map module = rendered.components.find { it.name == 'module' }
+ assertThat(module).doesNotContainKey('hashes')
+ assertThat(module).doesNotContainKey('licenses')
+ }
+
+ @Test
+ void 'the same content gives the same file, and another project the same content gives another serial number'() {
+ String first = ReproducibleSbomTask.render(bom(), ':plugin', 'app', TIMESTAMP, LOGGER)
+ String again = ReproducibleSbomTask.render(bom(), ':plugin', 'app', TIMESTAMP, LOGGER)
+ String other = ReproducibleSbomTask.render(bom(), ':other', 'app', TIMESTAMP, LOGGER)
+
+ assertThat(again).isEqualTo(first)
+ assertThat(first).endsWith('}\n')
+ assertThat(((Map) new JsonSlurper().parseText(other)).serialNumber)
+ .isNotEqualTo(((Map) new JsonSlurper().parseText(first)).serialNumber)
+ }
+
+ @Test
+ void 'a dependency under a license the policy does not permit fails the rewrite'() {
+ Map bom = bom()
+ ((List) bom.components).find { it.name == 'library' }.licenses = [[license: [id: 'GPL-2.0-only']]]
+
+ assertThatThrownBy { ReproducibleSbomTask.render(bom, ':plugin', 'app', TIMESTAMP, LOGGER) }
+ .isInstanceOf(GradleException)
+ .hasMessage('Unpermitted license GPL-2.0-only for the dependency pkg:maven/org.example/library@1.0?type=jar of app')
+ }
+
+ private static Map render(Map bom, String projectPath) {
+ (Map) new JsonSlurper().parseText(ReproducibleSbomTask.render(bom, projectPath, 'app', TIMESTAMP, LOGGER))
+ }
+
+ /** What the CycloneDX plugin writes for an application with one external and one project dependency. */
+ private static Map bom() {
+ [
+ bomFormat : 'CycloneDX',
+ specVersion : '1.6',
+ serialNumber: 'urn:uuid:' + UUID.randomUUID(),
+ version : 1,
+ metadata : [
+ timestamp: '2026-10-20T17:00:00Z',
+ component: [type: 'application', 'bom-ref': 'pkg:maven/org.example/app@1.0', name: 'app', version: '1.0'],
+ ],
+ components : [
+ [type : 'library', 'bom-ref': 'pkg:maven/org.example/library@1.0?type=jar', group: 'org.example',
+ name : 'library', version: '1.0',
+ hashes : [[alg: 'SHA-256', content: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855']],
+ licenses : [[license: [id: 'LGPL-2.1-only']],
+ [license: [id: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0.txt']]],
+ purl : 'pkg:maven/org.example/library@1.0?type=jar'],
+ [type : 'library', 'bom-ref': 'pkg:maven/org.example/module@1.0?project_path=%3Amodule', group: 'org.example',
+ name : 'module', version: '1.0',
+ hashes: [[alg: 'SHA-256', content: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855']]],
+ ],
+ dependencies: [
+ [ref : 'pkg:maven/org.example/app@1.0',
+ dependsOn: ['pkg:maven/org.example/module@1.0?project_path=%3Amodule', 'pkg:maven/org.example/library@1.0?type=jar']],
+ [ref: 'pkg:maven/org.example/library@1.0?type=jar', dependsOn: []],
+ [ref: 'pkg:maven/org.example/module@1.0?project_path=%3Amodule', dependsOn: []],
+ ],
+ ]
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicyTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicyTest.groovy
new file mode 100644
index 0000000..0141296
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomLicensePolicyTest.groovy
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.sbom
+
+import org.gradle.api.GradleException
+import org.gradle.api.logging.Logger
+import org.gradle.api.logging.Logging
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+
+class SbomLicensePolicyTest {
+
+ private static final Logger LOGGER = Logging.getLogger(SbomLicensePolicyTest)
+ private static final String BOM_REF = 'pkg:maven/org.example/library@1.0?type=jar'
+
+ @Test
+ void 'of several licenses the most preferred one is recorded'() {
+ List choices = [[license: [id: 'LGPL-2.1-only']], [license: [id: 'MIT']], [license: [id: 'EPL-2.0']]]
+
+ assertThat(SbomLicensePolicy.pickLicense(LOGGER, 'app', BOM_REF, choices)).isEqualTo([license: [id: 'EPL-2.0']])
+ }
+
+ @Test
+ void 'a single permitted license is kept as it is, with its url'() {
+ Map choice = [license: [id: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0.txt']]
+
+ assertThat(SbomLicensePolicy.pickLicense(LOGGER, 'app', BOM_REF, [choice])).isSameAs(choice)
+ }
+
+ @Test
+ void 'a license the policy does not permit fails, naming the dependency and the component'() {
+ assertThatThrownBy { SbomLicensePolicy.pickLicense(LOGGER, 'app', BOM_REF, [[license: [id: 'GPL-2.0-only']]]) }
+ .isInstanceOf(GradleException)
+ .hasMessage("Unpermitted license GPL-2.0-only for the dependency ${BOM_REF} of app")
+ }
+
+ @Test
+ void 'a dependency without a license, or with one that has no id, fails'() {
+ assertThatThrownBy { SbomLicensePolicy.pickLicense(LOGGER, 'app', BOM_REF, []) }
+ .isInstanceOf(GradleException)
+ .hasMessage("No license was found for the dependency ${BOM_REF} of app")
+ assertThatThrownBy { SbomLicensePolicy.pickLicense(LOGGER, 'app', BOM_REF, [[license: [name: 'The BSD License']]]) }
+ .isInstanceOf(GradleException)
+ .hasMessageStartingWith("Could not determine the license id of the dependency ${BOM_REF} of app")
+ assertThatThrownBy { SbomLicensePolicy.pickLicense(LOGGER, 'app', null, [[license: [id: 'MIT']]]) }
+ .isInstanceOf(GradleException)
+ .hasMessage('No bom-ref found for a dependency of app, cannot pick its license')
+ }
+
+ @Test
+ void 'the policy tables name only licenses the preferred list and the license blocks know'() {
+ SbomLicensePolicy.LICENSE_MAPPING.each { String bomRef, String id ->
+ assertThat(SbomLicensePolicy.LICENSES).describedAs(bomRef).containsKey(id)
+ }
+ SbomLicensePolicy.LICENSES.each { String id, Map<String, String> license ->
+ assertThat(license.id).isEqualTo(id)
+ assertThat(SbomLicensePolicy.PREFERRED_LICENSES + ['BSD-2-Clause']).describedAs(id).contains(id)
+ }
+ // nothing in the plugin's distribution comes from outside this repository yet
+ assertThat(SbomLicensePolicy.LICENSE_MAPPING).isEmpty()
+ assertThat(SbomLicensePolicy.LICENSE_EXCEPTIONS).isEmpty()
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomPluginTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomPluginTest.groovy
new file mode 100644
index 0000000..9c26d44
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/sbom/SbomPluginTest.groovy
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.sbom
+
+import java.util.jar.JarFile
+import java.util.jar.JarOutputStream
+import java.util.jar.Manifest
+
+import groovy.json.JsonSlurper
+import org.gradle.testkit.runner.BuildResult
+import org.gradle.testkit.runner.GradleRunner
+import org.gradle.testkit.runner.TaskOutcome
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+import static org.assertj.core.api.Assertions.assertThat
+
+/**
+ * Runs the {@code sbom} convention plugin through Gradle TestKit on a library with a dependency from a local Maven
+ * repository, with the configuration cache on and its problems fatal, as the real build runs.
+ */
+class SbomPluginTest {
+
+ private static final String SBOM_PLUGIN = 'org.apache.grails.intellij.build.sbom'
+
+ @Rule
+ public final TemporaryFolder tmp = new TemporaryFolder()
+
+ private File projectDir
+ private File repositoryDir
+
+ @Before
+ void setUp() {
+ projectDir = tmp.newFolder('project')
+ repositoryDir = tmp.newFolder('repository')
+ publish('org.example', 'library', '1.0', 'Apache License, Version 2.0', 'https://www.apache.org/licenses/LICENSE-2.0.txt')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ new File(projectDir, 'gradle.properties').text = '''\
+ org.gradle.configuration-cache=true
+ org.gradle.configuration-cache.problems=fail
+ version=1.0.0
+ '''.stripIndent()
+ }
+
+ @Test
+ void 'the SBOM ships in the jar, reproducibly, with the configuration cache stored and then reused'() {
+ writeProject(['org.example:library:1.0'])
+
+ BuildResult stored = runner('clean', 'jar').build()
+ File sbom = new File(projectDir, 'build/sbom/app-1.0.0-sbom.json')
+ String first = sbom.text
+ byte[] firstJar = new File(projectDir, 'build/libs/app-1.0.0.jar').bytes
+ BuildResult reused = runner('clean', 'jar').build()
+
+ assertThat(stored.output).contains('Configuration cache entry stored')
+ assertThat(reused.output).contains('Configuration cache entry reused')
+ assertThat(stored.task(':sbom').outcome).isEqualTo(TaskOutcome.SUCCESS)
+
+ // reproducible: dated at the epoch, with a serial number derived from the content, so a rebuild is identical
+ assertThat(first)
+ .contains('"timestamp": "1970-01-01T00:00:00Z"')
+ .contains('"serialNumber": "urn:uuid:')
+ assertThat(sbom.text).isEqualTo(first)
+ assertThat(new File(projectDir, 'build/libs/app-1.0.0.jar').bytes).isEqualTo(firstJar)
+
+ // what it describes: the application and its one dependency, under the one license ASF policy prefers
+ Map bom = (Map) new JsonSlurper().parseText(first)
+ assertThat(bom.metadata.component.name).isEqualTo('app')
+ assertThat(bom.metadata.component.type).isEqualTo('application')
+ assertThat(bom.metadata.component.version).isEqualTo('1.0.0')
+ Map library = bom.components.find { it.name == 'library' }
+ assertThat(library.licenses*.license*.id).containsExactly('Apache-2.0')
+ assertThat(bom.metadata.manufacturer.name).isEqualTo('Apache Software Foundation')
+ assertThat(bom.metadata.licenses*.license*.id).containsExactly('Apache-2.0')
+ assertThat(bom.metadata.component.externalReferences*.type).contains('website', 'vcs', 'mailing-list')
+ assertThat(bom.metadata.component.externalReferences.find { it.type == 'mailing-list' }.url).isEqualTo('users@grails.apache.org')
+
+ // packaged into the jar, named by the manifest
+ new JarFile(new File(projectDir, 'build/libs/app-1.0.0.jar')).withCloseable { JarFile jar ->
+ assertThat(jar.getInputStream(jar.getJarEntry('META-INF/sbom.json')).text).isEqualTo(first)
+ assertThat(jar.manifest.mainAttributes.getValue('Sbom-Location')).isEqualTo('META-INF/sbom.json')
+ assertThat(jar.manifest.mainAttributes.getValue('Sbom-Format')).isEqualTo('CycloneDX')
+ }
+ }
+
+ @Test
+ void 'a snapshot is referred to the development list, and SOURCE_DATE_EPOCH dates the SBOM'() {
+ writeProject(['org.example:library:1.0'])
+ new File(projectDir, 'gradle.properties') << 'version=1.0.1-SNAPSHOT\n'
+
+ runner('sbom').withEnvironment(System.getenv() + [SOURCE_DATE_EPOCH: '1700000000']).build()
+
+ Map bom = (Map) new JsonSlurper().parse(new File(projectDir, 'build/sbom/app-1.0.1-SNAPSHOT-sbom.json'))
+ assertThat(bom.metadata.timestamp).isEqualTo('2023-11-14T22:13:20Z')
+ assertThat(bom.metadata.component.externalReferences.find { it.type == 'mailing-list' }.url).isEqualTo('dev@grails.apache.org')
+ }
+
+ @Test
+ void 'a dependency whose license the policy cannot place fails the build before anything is packaged'() {
+ // a license CycloneDX cannot map to an SPDX id is recorded by name only, and a name is not a verdict
+ publish('org.example', 'copyleft', '1.0', 'GNU General Public License, version 2', 'https://www.gnu.org/licenses/gpl-2.0.html')
+ writeProject(['org.example:library:1.0', 'org.example:copyleft:1.0'])
+
+ BuildResult result = runner('jar').buildAndFail()
+
+ assertThat(result.task(':sbom').outcome).isEqualTo(TaskOutcome.FAILED)
+ assertThat(result.task(':jar')).isNull()
+ assertThat(result.output).contains('Could not determine the license id of the dependency ' +
+ 'pkg:maven/org.example/copyleft@1.0?type=jar of app from [license:[name:GNU General Public License, version 2')
+ }
+
+ private GradleRunner runner(String... arguments) {
+ GradleRunner.create()
+ .withProjectDir(projectDir)
+ .withArguments(arguments.toList() + ['--stacktrace'])
+ .withPluginClasspath()
+ }
+
+ private void writeProject(List<String> dependencies) {
+ new File(projectDir, 'build.gradle').text = """
+ plugins {
+ id 'java-library'
+ id '$SBOM_PLUGIN'
+ }
+ group = 'org.example'
+ repositories {
+ maven { url = uri('${repositoryDir.toURI()}') }
+ }
+ dependencies {
+ ${dependencies.collect { "implementation '${it}'" }.join('\n ')}
+ }
+ """
+ }
+
+ private void publish(String group, String artifact, String version, String licenseName, String licenseUrl) {
+ File dir = new File(repositoryDir, "${group.replace('.', '/')}/${artifact}/${version}")
+ dir.mkdirs()
+ new File(dir, "${artifact}-${version}.pom").text = """<?xml version="1.0" encoding="UTF-8"?>
+ <project xmlns="http://maven.apache.org/POM/4.0.0">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>${group}</groupId>
+ <artifactId>${artifact}</artifactId>
+ <version>${version}</version>
+ <licenses>
+ <license>
+ <name>${licenseName}</name>
+ <url>${licenseUrl}</url>
+ </license>
+ </licenses>
+ </project>
+ """.stripIndent().trim()
+ // a valid, empty jar: CycloneDX opens each artifact to look for a POM inside it
+ new JarOutputStream(new File(dir, "${artifact}-${version}.jar").newOutputStream(), new Manifest()).close()
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/CvssV3Test.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/CvssV3Test.groovy
new file mode 100644
index 0000000..e7b9140
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/CvssV3Test.groovy
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+
+class CvssV3Test {
+
+ @Test
+ void 'the base score of a vector is the one the specification gives'() {
+ Map<String, BigDecimal> scores = [
+ 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H': 9.8,
+ 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H': 7.5,
+ 'CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N': 5.4,
+ 'CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H': 9.9,
+ 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H': 10.0,
+ 'CVSS:3.1/AV:A/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L': 4.6,
+ 'CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N': 3.1,
+ 'CVSS:3.0/AV:L/AC:H/PR:H/UI:R/S:U/C:L/I:N/A:N': 1.8,
+ 'CVSS:3.1/AV:P/AC:H/PR:H/UI:R/S:U/C:N/I:N/A:N': 0,
+ ]
+ scores.each { String vector, BigDecimal score ->
+ assertThat(CvssV3.baseScore(vector)).describedAs(vector).isEqualByComparingTo(score)
+ }
+ }
+
+ @Test
+ void 'what is not a complete CVSS v3 vector has no score'() {
+ [
+ null,
+ '',
+ 'HIGH',
+ 'CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N',
+ 'AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H',
+ 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H',
+ 'CVSS:3.1/AV:X/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H',
+ 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:X/C:H/I:H/A:H',
+ ].each { String vector ->
+ assertThat(CvssV3.baseScore(vector)).describedAs(String.valueOf(vector)).isNull()
+ }
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvStub.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvStub.groovy
new file mode 100644
index 0000000..4126be2
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvStub.groovy
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.atomic.AtomicInteger
+
+import com.sun.net.httpserver.HttpExchange
+import com.sun.net.httpserver.HttpServer
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+
+/**
+ * Answers the OSV API requests the scan makes from what a test registered, and counts them.
+ */
+class OsvStub implements AutoCloseable {
+
+ final HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.loopbackAddress, 0), 0)
+ final AtomicInteger queryRequests = new AtomicInteger()
+ final AtomicInteger vulnerabilityRequests = new AtomicInteger()
+ final Map<String, List<String>> idsByCoordinate = [:]
+ final Map<String, Map> vulnerabilities = [:]
+ /** Answers the next requests with 429 before answering them properly. */
+ final AtomicInteger throttle = new AtomicInteger()
+ /** How many ids a page of a query result holds. */
+ int pageSize = Integer.MAX_VALUE
+ /** The coordinates whose queries the stub answers with 503, as an API that is down. */
+ final Set<String> unavailable = Collections.synchronizedSet(new HashSet<String>())
+ /** Answers a query batch with at most this many results, as a broken API would. */
+ Integer resultsLimit
+
+ OsvStub() {
+ server.createContext('/v1/querybatch') { HttpExchange exchange -> handle(exchange) { querybatch(exchange) } }
+ server.createContext('/v1/vulns/') { HttpExchange exchange -> handle(exchange) { vulnerability(exchange) } }
+ server.start()
+ }
+
+ String getUrl() {
+ "http://${server.address.hostString}:${server.address.port}"
+ }
+
+ /**
+ * Registers a vulnerability of a {@code group:artifact:version}, fixed in the given version.
+ */
+ void vulnerable(String coordinate, String id, String fixedIn, List<String> aliases = []) {
+ idsByCoordinate.computeIfAbsent(coordinate) { [] } << id
+ String module = coordinate.substring(0, coordinate.lastIndexOf(':'))
+ vulnerabilities.put(id, [
+ id : id,
+ aliases : aliases,
+ summary : "Vulnerability ${id}",
+ database_specific: [severity: 'HIGH'],
+ affected : [[package: [ecosystem: 'Maven', name: module],
+ ranges : [[type: 'ECOSYSTEM', events: [[introduced: '0'], [fixed: fixedIn]]]]]],
+ ])
+ }
+
+ private void handle(HttpExchange exchange, Closure<Object> answer) {
+ if (throttle.getAndUpdate { it > 0 ? it - 1 : 0 } > 0) {
+ exchange.responseHeaders.add('Retry-After', '0')
+ exchange.sendResponseHeaders(429, -1)
+ exchange.close()
+ return
+ }
+ byte[] body
+ try {
+ body = JsonOutput.toJson(answer.call()).getBytes(StandardCharsets.UTF_8)
+ } catch (Unavailable ignored) {
+ body = 'Service Unavailable'.getBytes(StandardCharsets.UTF_8)
+ exchange.responseHeaders.add('Retry-After', '0')
+ exchange.sendResponseHeaders(503, body.length)
+ exchange.responseBody.withStream { it.write(body) }
+ return
+ } catch (Throwable failure) {
+ StringWriter trace = new StringWriter()
+ failure.printStackTrace(new PrintWriter(trace))
+ body = trace.toString().getBytes(StandardCharsets.UTF_8)
+ exchange.sendResponseHeaders(500, body.length)
+ exchange.responseBody.withStream { it.write(body) }
+ return
+ }
+ exchange.sendResponseHeaders(200, body.length)
+ exchange.responseBody.withStream { it.write(body) }
+ }
+
+ private Map querybatch(HttpExchange exchange) {
+ queryRequests.incrementAndGet()
+ Map request = (Map) new JsonSlurper().parse(exchange.requestBody)
+ if (request.queries.any { Map query -> "${query.package.name}:${query.version}".toString() in unavailable }) {
+ throw new Unavailable()
+ }
+ List<Map> queries = resultsLimit == null ? request.queries : request.queries.take(resultsLimit)
+ [results: queries.collect { Map query ->
+ List<String> ids = idsByCoordinate.get("${query.package.name}:${query.version}" as String) ?: []
+ int start = query.page_token ? query.page_token.toString().toInteger() : 0
+ int end = (int) Math.min((long) start + pageSize, (long) ids.size())
+ List<String> page = ids.subList(start, end)
+ Map result = page ? [vulns: page.collect { [id: it, modified: '2026-01-01T00:00:00Z'] }] : [:]
+ if (end < ids.size()) {
+ result.next_page_token = String.valueOf(end)
+ }
+ result
+ }]
+ }
+
+ private Map vulnerability(HttpExchange exchange) {
+ vulnerabilityRequests.incrementAndGet()
+ vulnerabilities.get(URLDecoder.decode(exchange.requestURI.path - '/v1/vulns/', StandardCharsets.UTF_8))
+ }
+
+ @Override
+ void close() {
+ server.stop(0)
+ }
+
+ private static class Unavailable extends RuntimeException {
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityServiceTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityServiceTest.groovy
new file mode 100644
index 0000000..b3f7218
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/OsvVulnerabilityServiceTest.groovy
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.time.Duration
+
+import org.gradle.api.GradleException
+import org.gradle.api.Project
+import org.gradle.testfixtures.ProjectBuilder
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+
+class OsvVulnerabilityServiceTest {
+
+ @Rule
+ public final TemporaryFolder tmp = new TemporaryFolder()
+
+ private OsvStub osv
+ private File cacheDir
+ private File projectDir
+
+ @Before
+ void setUp() {
+ osv = new OsvStub()
+ cacheDir = tmp.newFolder('cache')
+ projectDir = tmp.newFolder('projects')
+ }
+
+ @After
+ void tearDown() {
+ osv.close()
+ }
+
+ private OsvVulnerabilityService service(Duration ttl = Duration.ofHours(1)) {
+ // a project of its own each time, so each service starts with nothing in memory
+ Project project = ProjectBuilder.builder().withProjectDir(new File(projectDir, UUID.randomUUID().toString())).build()
+ project.gradle.sharedServices.registerIfAbsent('osv', OsvVulnerabilityService) { spec ->
+ spec.parameters.apiUrl.set(osv.url)
+ spec.parameters.cacheDirectory.set(cacheDir)
+ spec.parameters.cacheTtl.set(ttl)
+ }.get()
+ }
+
+ @Test
+ void 'the vulnerabilities of each coordinate are looked up in one batch and their records fetched'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1', ['CVE-2026-0001'])
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-2222', '1.2')
+
+ def found = service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.id).containsExactly('GHSA-1111', 'GHSA-2222')
+ assertThat(found['org.example:vulnerable:1.0'][0].aliases).isEqualTo(['CVE-2026-0001'])
+ assertThat(found['org.example:safe:1.0']).isEmpty()
+ assertThat(osv.queryRequests.get()).isEqualTo(1)
+ assertThat(osv.vulnerabilityRequests.get()).isEqualTo(2)
+ }
+
+ @Test
+ void 'another build within the cache time asks the API nothing, also for a coordinate without vulnerabilities'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1')
+ service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ def found = service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.id).containsExactly('GHSA-1111')
+ assertThat(found['org.example:safe:1.0']).isEmpty()
+ assertThat(osv.queryRequests.get()).isEqualTo(1)
+ assertThat(osv.vulnerabilityRequests.get()).isEqualTo(1)
+ }
+
+ @Test
+ void 'an answer older than the cache time is fetched again'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1')
+ service(Duration.ZERO).vulnerabilities(['org.example:vulnerable:1.0'])
+ // a vulnerability published since
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-3333', '1.3')
+
+ def found = service(Duration.ZERO).vulnerabilities(['org.example:vulnerable:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.id).containsExactly('GHSA-1111', 'GHSA-3333')
+ assertThat(osv.queryRequests.get()).isEqualTo(2)
+ }
+
+ @Test
+ void 'every page of a long result is fetched'() {
+ osv.pageSize = 2
+ (1..5).each { osv.vulnerable('org.example:vulnerable:1.0', "GHSA-000${it}", '2.0') }
+
+ assertThat(service().vulnerabilities(['org.example:vulnerable:1.0'])['org.example:vulnerable:1.0']*.id)
+ .isEqualTo((1..5).collect { "GHSA-000${it}".toString() })
+ }
+
+ @Test
+ void 'a throttled request is retried'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1')
+ osv.throttle.set(2)
+
+ assertThat(service().vulnerabilities(['org.example:vulnerable:1.0'])['org.example:vulnerable:1.0']*.id)
+ .containsExactly('GHSA-1111')
+ }
+
+ @Test
+ void 'an answer that cannot be kept in the cache is still returned, and asked for again by the next build'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1')
+ // a file where the cache directory should be
+ new File(cacheDir, 'osv').text = 'not a directory'
+
+ def found = service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.id).containsExactly('GHSA-1111')
+ assertThat(found['org.example:safe:1.0']).isEmpty()
+
+ found = service().vulnerabilities(['org.example:vulnerable:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.id).containsExactly('GHSA-1111')
+ assertThat(osv.queryRequests.get()).isEqualTo(2)
+ assertThat(osv.vulnerabilityRequests.get()).isEqualTo(2)
+ }
+
+ @Test
+ void 'a request the API keeps throttling fails with the last status, so a rate limit is told apart from an outage'() {
+ osv.throttle.set(10)
+
+ assertThatThrownBy { service().vulnerabilities(['org.example:vulnerable:1.0']) }
+ .isInstanceOf(GradleException)
+ .hasMessageContaining('still answered POST')
+ .hasMessageContaining('with 429 after 4 attempts')
+ }
+
+ @Test
+ void 'an answer with fewer results than queries fails, rather than recording the rest as clean'() {
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1')
+ osv.resultsLimit = 1
+
+ assertThatThrownBy { service().vulnerabilities(['org.example:safe:1.0', 'org.example:vulnerable:1.0']) }
+ .isInstanceOf(GradleException)
+ .hasMessage('The OSV API answered 2 queries with 1 results')
+
+ // the API answers properly again: nothing was cached for the coordinates the broken answer left out
+ osv.resultsLimit = null
+ assertThat(service().vulnerabilities(['org.example:vulnerable:1.0'])['org.example:vulnerable:1.0']*.id)
+ .containsExactly('GHSA-1111')
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideStub.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideStub.groovy
new file mode 100644
index 0000000..9c9b3df
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideStub.groovy
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.atomic.AtomicInteger
+
+import com.sun.net.httpserver.HttpExchange
+import com.sun.net.httpserver.HttpServer
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+
+/**
+ * Answers the component report requests the scan makes to Sonatype Guide from what a test registered, checks their
+ * credentials, and counts them.
+ */
+class SonatypeGuideStub implements AutoCloseable {
+
+ static final String USERNAME = 'test-user'
+ static final String TOKEN = 'test-token'
+
+ final HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.loopbackAddress, 0), 0)
+ final AtomicInteger requests = new AtomicInteger()
+ final List<Integer> batchSizes = Collections.synchronizedList([])
+ final Map<String, List<Map>> vulnerabilitiesByPackageUrl = [:]
+ /** Answers the next requests with 429 before answering them properly. */
+ final AtomicInteger throttle = new AtomicInteger()
+ /** The token the stub accepts. */
+ String token = TOKEN
+ /** Rewrites the package URL each report names, as an API that normalizes what it was sent would. */
+ Closure<String> echo = Closure.IDENTITY
+ /** Answers the reports in the reverse of the order they were asked in. */
+ boolean reverse
+ /** The package URLs the stub leaves out of its answer. */
+ final Set<String> omit = []
+
+ SonatypeGuideStub() {
+ server.createContext('/api/v3/component-report') { HttpExchange exchange -> handle(exchange) }
+ server.start()
+ }
+
+ String getUrl() {
+ "http://${server.address.hostString}:${server.address.port}"
+ }
+
+ /**
+ * Registers a vulnerability of a {@code group:artifact:version}.
+ */
+ void vulnerable(String coordinate, String cve, String cvssScore, String title) {
+ vulnerabilitiesByPackageUrl.computeIfAbsent(SonatypeGuideVulnerabilityService.packageUrl(coordinate)) { [] } << [
+ id : cve,
+ displayName: cve,
+ title : "[${cve}] ${title}",
+ description: "${title} in ${coordinate}",
+ cvssScore : cvssScore,
+ cvssVector : 'CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N',
+ cwe : 'CWE-400',
+ cve : cve,
+ reference : "https://guide.sonatype.com/vulnerability/${cve}",
+ ]
+ }
+
+ private void handle(HttpExchange exchange) {
+ try {
+ if (throttle.getAndUpdate { it > 0 ? it - 1 : 0 } > 0) {
+ exchange.responseHeaders.add('Retry-After', '0')
+ exchange.sendResponseHeaders(429, -1)
+ return
+ }
+ String expected = "Basic ${"${USERNAME}:${token}".getBytes(StandardCharsets.UTF_8).encodeBase64()}"
+ if (exchange.requestHeaders.getFirst('Authorization') != expected) {
+ respond(exchange, 401, [code: 401, message: 'Unauthorized'])
+ return
+ }
+ requests.incrementAndGet()
+ List<String> coordinates = ((Map) new JsonSlurper().parse(exchange.requestBody)).coordinates
+ batchSizes << coordinates.size()
+ exchange.responseHeaders.add('x-credits-used', String.valueOf(coordinates.size() / 10))
+ exchange.responseHeaders.add('x-credits-remaining', '100')
+ List<Map> reports = coordinates.findAll { !(it in omit) }.collect { String packageUrl ->
+ [coordinates : echo.call(packageUrl),
+ description : '',
+ reference : "https://guide.sonatype.com/component/${packageUrl}",
+ vulnerabilities: vulnerabilitiesByPackageUrl.get(packageUrl) ?: []]
+ }
+ respond(exchange, 200, reverse ? reports.reverse() : reports)
+ }
+ catch (Throwable failure) {
+ StringWriter trace = new StringWriter()
+ failure.printStackTrace(new PrintWriter(trace))
+ respond(exchange, 500, [message: trace.toString()])
+ }
+ finally {
+ exchange.close()
+ }
+ }
+
+ private static void respond(HttpExchange exchange, int status, Object body) {
+ byte[] bytes = JsonOutput.toJson(body).getBytes(StandardCharsets.UTF_8)
+ exchange.responseHeaders.add('Content-Type', 'application/vnd.ossindex.component-report.v1+json')
+ exchange.sendResponseHeaders(status, bytes.length)
+ exchange.responseBody.write(bytes)
+ }
+
+ @Override
+ void close() {
+ server.stop(0)
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityServiceTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityServiceTest.groovy
new file mode 100644
index 0000000..6809ca1
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/SonatypeGuideVulnerabilityServiceTest.groovy
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.time.Duration
+
+import org.gradle.api.GradleException
+import org.gradle.api.Project
+import org.gradle.testfixtures.ProjectBuilder
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+
+class SonatypeGuideVulnerabilityServiceTest {
+
+ /** Set by the test task (build-logic/build.gradle) to the credentials the stub accepts. */
+ static final String USERNAME_VARIABLE = 'TEST_SONATYPE_GUIDE_USERNAME'
+ static final String TOKEN_VARIABLE = 'TEST_SONATYPE_GUIDE_TOKEN'
+
+ @Rule
+ public final TemporaryFolder tmp = new TemporaryFolder()
+
+ private SonatypeGuideStub sonatype
+ private File cacheDir
+ private File projectDir
+
+ @Before
+ void setUp() {
+ assertThat(System.getenv(TOKEN_VARIABLE)).describedAs('the test task sets the stub credentials').isEqualTo(SonatypeGuideStub.TOKEN)
+ sonatype = new SonatypeGuideStub()
+ cacheDir = tmp.newFolder('cache')
+ projectDir = tmp.newFolder('projects')
+ }
+
+ @After
+ void tearDown() {
+ sonatype.close()
+ }
+
+ private SonatypeGuideVulnerabilityService service(Duration ttl = Duration.ofHours(1), String tokenVariable = TOKEN_VARIABLE) {
+ // a project of its own each time, so each service starts with nothing in memory
+ Project project = ProjectBuilder.builder().withProjectDir(new File(projectDir, UUID.randomUUID().toString())).build()
+ project.gradle.sharedServices.registerIfAbsent('sonatypeGuide', SonatypeGuideVulnerabilityService) { spec ->
+ spec.parameters.apiUrl.set(sonatype.url)
+ spec.parameters.cacheDirectory.set(cacheDir)
+ spec.parameters.cacheTtl.set(ttl)
+ spec.parameters.usernameVariable.set(USERNAME_VARIABLE)
+ spec.parameters.tokenVariable.set(tokenVariable)
+ }.get()
+ }
+
+ @Test
+ void 'components are reported in batches of 128, with the credentials of the environment'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ List<String> coordinates = ['org.example:vulnerable:1.0'] + (1..199).collect { "org.example:safe:${it}" as String }
+
+ def found = service().vulnerabilities(coordinates)
+
+ assertThat(found['org.example:vulnerable:1.0']*.cve).containsExactly('CVE-2026-0001')
+ assertThat(found['org.example:safe:1']).isEmpty()
+ assertThat(found).hasSize(200)
+ assertThat(sonatype.batchSizes).containsExactly(128, 72)
+ }
+
+ @Test
+ void 'another build within the cache time asks the API nothing'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ def found = service().vulnerabilities(['org.example:vulnerable:1.0', 'org.example:safe:1.0'])
+
+ assertThat(found['org.example:vulnerable:1.0']*.cve).containsExactly('CVE-2026-0001')
+ assertThat(found['org.example:safe:1.0']).isEmpty()
+ assertThat(sonatype.requests.get()).isEqualTo(1)
+ }
+
+ @Test
+ void 'an answer older than the cache time is fetched again'() {
+ service(Duration.ZERO).vulnerabilities(['org.example:vulnerable:1.0'])
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0002', '9.8', 'Remote code execution')
+
+ assertThat(service(Duration.ZERO).vulnerabilities(['org.example:vulnerable:1.0'])['org.example:vulnerable:1.0']*.cve)
+ .containsExactly('CVE-2026-0002')
+ assertThat(sonatype.requests.get()).isEqualTo(2)
+ }
+
+ @Test
+ void 'without a token the database is not consulted'() {
+ SonatypeGuideVulnerabilityService service = service(Duration.ofHours(1), 'TEST_SONATYPE_GUIDE_TOKEN_THAT_IS_NOT_SET')
+
+ assertThat(service.unavailableReason()).isEqualTo('TEST_SONATYPE_GUIDE_TOKEN_THAT_IS_NOT_SET is not set')
+ assertThatThrownBy { service.vulnerabilities(['org.example:vulnerable:1.0']) }.isInstanceOf(IllegalStateException)
+ assertThat(sonatype.requests.get()).isEqualTo(0)
+ }
+
+ @Test
+ void 'rejected credentials fail the lookup with a hint, without revealing the token'() {
+ sonatype.token = 'another-token'
+
+ assertThatThrownBy { service().vulnerabilities(['org.example:vulnerable:1.0']) }
+ .isInstanceOf(GradleException)
+ .hasMessageContaining('with 401 (check TEST_SONATYPE_GUIDE_USERNAME and TEST_SONATYPE_GUIDE_TOKEN)')
+ .hasMessageNotContaining(SonatypeGuideStub.TOKEN)
+ }
+
+ @Test
+ void 'a throttled request is retried'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ sonatype.throttle.set(2)
+
+ assertThat(service().vulnerabilities(['org.example:vulnerable:1.0'])['org.example:vulnerable:1.0']*.cve)
+ .containsExactly('CVE-2026-0001')
+ }
+
+ @Test
+ void 'a report is matched to its component by package URL even when the API echoes it in another form and order'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0+build.1', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ sonatype.echo = { String packageUrl -> packageUrl.replace('%2B', '+').toUpperCase() }
+ sonatype.reverse = true
+
+ def found = service().vulnerabilities(['org.example:safe:1.0', 'org.example:vulnerable:1.0+build.1'])
+
+ assertThat(found['org.example:vulnerable:1.0+build.1']*.cve).containsExactly('CVE-2026-0001')
+ assertThat(found['org.example:safe:1.0']).isEmpty()
+ }
+
+ @Test
+ void 'a component the API does not report on fails the lookup instead of being given the report of another'() {
+ [
+ // one report fewer than components
+ { SonatypeGuideStub stub -> stub.omit << 'pkg:maven/org.example/safe@1.0' },
+ // as many reports, but not on what was asked
+ { SonatypeGuideStub stub -> stub.echo = { String packageUrl -> packageUrl + '?type=jar' } },
+ ].eachWithIndex { Closure configure, int i ->
+ // a fresh stub and cache for each case, so one case's answers are not the next one's
+ sonatype.close()
+ sonatype = new SonatypeGuideStub()
+ cacheDir = tmp.newFolder("cache-$i")
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ configure.call(sonatype)
+
+ assertThatThrownBy { service().vulnerabilities(['org.example:safe:1.0', 'org.example:vulnerable:1.0']) }
+ .describedAs("case $i")
+ .isInstanceOf(GradleException)
+ .hasMessage('The Sonatype Guide API did not report on pkg:maven/org.example/safe@1.0')
+
+ // the API answers properly again: nothing was recorded for the components of the broken answer
+ sonatype.echo = Closure.IDENTITY
+ sonatype.omit.clear()
+ assertThat(service().vulnerabilities(['org.example:safe:1.0', 'org.example:vulnerable:1.0'])['org.example:safe:1.0'])
+ .describedAs("case $i").isEmpty()
+ assertThat(sonatype.requests.get()).describedAs("case $i").isEqualTo(2)
+ }
+ }
+
+ @Test
+ void 'a coordinate is known by its package URL, with the characters a package URL reserves encoded'() {
+ assertThat(SonatypeGuideVulnerabilityService.packageUrl('org.example:library:1.0+build.1'))
+ .isEqualTo('pkg:maven/org.example/library@1.0%2Bbuild.1')
+ assertThat(SonatypeGuideVulnerabilityService.packageUrl('com.google.guava:guava:33.7.1-jre'))
+ .isEqualTo('pkg:maven/com.google.guava/guava@33.7.1-jre')
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusionTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusionTest.groovy
new file mode 100644
index 0000000..c3d69cb
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityExclusionTest.groovy
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+
+class VulnerabilityExclusionTest {
+
+ @Test
+ void 'an exclusion matches a vulnerability of its module by any of its ids, regardless of case'() {
+ ['CVE-2026-0001', 'cve-2026-0001', 'GHSA-1111', 'ghsa-1111'].each { String id ->
+ VulnerabilityExclusion exclusion = new VulnerabilityExclusion(id, 'org.example:vulnerable', 'No fixed release exists')
+
+ assertThat(exclusion.matches('org.example:vulnerable', ['GHSA-1111', 'CVE-2026-0001'])).describedAs(id).isTrue()
+ assertThat(exclusion.matches('org.example:other', ['GHSA-1111', 'CVE-2026-0001'])).describedAs(id).isFalse()
+ assertThat(exclusion.matches('org.example:vulnerable', ['GHSA-2222', 'CVE-2026-0002'])).describedAs(id).isFalse()
+ }
+ }
+
+ @Test
+ void 'an exclusion without a module matches the vulnerability in every module'() {
+ VulnerabilityExclusion exclusion = new VulnerabilityExclusion('CVE-2026-0001', null, 'Flagged against every version')
+
+ ['org.example:vulnerable', 'org.example:other'].each { String module ->
+ assertThat(exclusion.matches(module, ['CVE-2026-0001'])).describedAs(module).isTrue()
+ }
+ }
+
+ @Test
+ void 'an exclusion must name the vulnerability and give its reason'() {
+ [
+ [null, 'No fix', 'An exclusion must name the vulnerability it excludes'],
+ ['', 'No fix', 'An exclusion must name the vulnerability it excludes'],
+ ['CVE-2026-0001', null, 'The exclusion of CVE-2026-0001 must give its reason'],
+ ['CVE-2026-0001', '', 'The exclusion of CVE-2026-0001 must give its reason'],
+ ].each { List<String> example ->
+ assertThatThrownBy { new VulnerabilityExclusion(example[0], 'org.example:vulnerable', example[1]) }
+ .describedAs("${example[0]} / ${example[1]}")
+ .isInstanceOf(IllegalArgumentException)
+ .hasMessage(example[2])
+ }
+ }
+
+ @Test
+ void 'exclusions compare by value, as task inputs must'() {
+ assertThat(new VulnerabilityExclusion('CVE-2026-0001', 'org.example:vulnerable', 'No fix'))
+ .isEqualTo(new VulnerabilityExclusion('CVE-2026-0001', 'org.example:vulnerable', 'No fix'))
+ .hasSameHashCodeAs(new VulnerabilityExclusion('CVE-2026-0001', 'org.example:vulnerable', 'No fix'))
+ .isNotEqualTo(new VulnerabilityExclusion('CVE-2026-0001', null, 'No fix'))
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanPluginTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanPluginTest.groovy
new file mode 100644
index 0000000..4158989
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanPluginTest.groovy
@@ -0,0 +1,467 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import groovy.json.JsonSlurper
+import org.gradle.testkit.runner.BuildResult
+import org.gradle.testkit.runner.GradleRunner
+import org.gradle.testkit.runner.TaskOutcome
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+import static org.assertj.core.api.Assertions.assertThat
+
+/**
+ * Runs the {@code vulnerabilityScan} and {@code vulnerabilityScanReport} tasks through Gradle TestKit against stubs
+ * of the OSV and Sonatype Guide APIs and a local Maven repository. Every build runs with the configuration cache on
+ * and its problems fatal, as the real build does: the point of this scanner over the Sonatype plugin it replaced
+ * is that it keeps the configuration cache usable.
+ */
+class VulnerabilityScanPluginTest {
+
+ private static final String SCAN_PLUGIN = 'org.apache.grails.intellij.build.vulnerability-scan'
+ private static final String REPORT_PLUGIN = 'org.apache.grails.intellij.build.vulnerability-scan-report'
+
+ @Rule
+ public final TemporaryFolder tmp = new TemporaryFolder()
+
+ private OsvStub osv
+ private SonatypeGuideStub sonatype
+ private File projectDir
+ private File repositoryDir
+ private File cacheDir
+
+ /** The environment of the builds: that of the tests, without any Sonatype Guide credentials. */
+ private Map<String, String> environment = System.getenv().findAll { !it.key.startsWith('SONATYPE_GUIDE_') }
+
+ @Before
+ void setUp() {
+ osv = new OsvStub()
+ sonatype = new SonatypeGuideStub()
+ projectDir = tmp.newFolder('project')
+ repositoryDir = tmp.newFolder('repository')
+ cacheDir = tmp.newFolder('cache')
+
+ publish('org.example', 'vulnerable', '1.0')
+ publish('org.example', 'safe', '1.0')
+ publish('org.example', 'library', '1.0', ['org.example:vulnerable:1.0'])
+ osv.vulnerable('org.example:vulnerable:1.0', 'GHSA-1111', '1.1', ['CVE-2026-0001'])
+
+ new File(projectDir, 'gradle.properties').text = """\
+ org.gradle.configuration-cache=true
+ org.gradle.configuration-cache.problems=fail
+ vulnerabilityScan.apiUrl=${osv.url}
+ vulnerabilityScan.sonatypeGuide.apiUrl=${sonatype.url}
+ vulnerabilityScan.cacheDir=${cacheDir.absolutePath.replace('\\', '/')}
+ """.stripIndent()
+ }
+
+ @After
+ void tearDown() {
+ osv.close()
+ sonatype.close()
+ }
+
+ @Test
+ void 'a vulnerable dependency fails the scan and is reported with the path that brings it in'() {
+ writeProject(projectDir, ['org.example:library:1.0', 'org.example:safe:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(result.task(':vulnerabilityScan').outcome).isEqualTo(TaskOutcome.FAILED)
+ assertThat(result.output)
+ .contains('1 known vulnerability in the dependencies of :')
+ .contains('org.example:vulnerable:1.0')
+ .contains('GHSA-1111 (CVE-2026-0001) HIGH: Vulnerability GHSA-1111')
+ .contains('fixed in 1.1; OSV: https://osv.dev/vulnerability/GHSA-1111')
+ .contains('via runtimeClasspath > org.example:library:1.0 > org.example:vulnerable:1.0')
+
+ // the report holds what was found, and that Sonatype Guide was not consulted without a token
+ Map report = report(projectDir)
+ assertThat(report.findings*.dependency).containsExactly('org.example:vulnerable:1.0')
+ assertThat(report.findings[0].fixedVersions).isEqualTo(['1.1'])
+ assertThat(report.dependencies).isEqualTo(3)
+ assertThat(report.sources).isEqualTo(['OSV'])
+ assertThat(report.unavailableSources).isEqualTo([[name: 'Sonatype Guide', reason: 'SONATYPE_GUIDE_TOKEN is not set']])
+ }
+
+ @Test
+ void 'a dependency only on the compile classpath is scanned too'() {
+ writeProject(projectDir, ['org.example:safe:1.0'], '''
+ dependencies {
+ compileOnly 'org.example:vulnerable:1.0'
+ }
+ ''')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(result.output).contains('via compileClasspath > org.example:vulnerable:1.0')
+ }
+
+ @Test
+ void 'dependencies of the ignored groups are left out of the scan'() {
+ // what the IntelliJ Platform Gradle Plugin puts on every compile classpath: IDE modules under groups of its own
+ publish('bundledModule', 'intellij.platform.core', 'IU-262.1')
+ osv.vulnerable('bundledModule:intellij.platform.core:IU-262.1', 'GHSA-9999', 'IU-262.2')
+ writeProject(projectDir, ['org.example:safe:1.0'], '''
+ dependencies {
+ compileOnly 'bundledModule:intellij.platform.core:IU-262.1'
+ }
+ vulnerabilityScan {
+ ignoredGroups = ['bundledModule', 'bundledPlugin']
+ }
+ ''')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ BuildResult result = runner('vulnerabilityScan', '--info').build()
+
+ assertThat(result.task(':vulnerabilityScan').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ assertThat(result.output).contains(': left 1 dependency of the ignored groups [bundledModule, bundledPlugin] out of the scan')
+ Map report = report(projectDir)
+ assertThat(report.dependencies).isEqualTo(1)
+ assertThat(report.findings).isEmpty()
+ // never asked about: an ignored component is not merely filtered from the findings
+ assertThat(osv.vulnerabilityRequests.get()).isEqualTo(0)
+ }
+
+ @Test
+ void 'with Sonatype Guide credentials both databases are consulted, and a vulnerability both know of is reported once'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0001', '7.5', 'Resource exhaustion')
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0002', '6.3', 'Off-by-one error')
+ writeProject(projectDir, ['org.example:library:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ withSonatypeGuideCredentials()
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(result.output)
+ .contains('2 known vulnerabilities in the dependencies of :')
+ .contains('CVE-2026-0002 MEDIUM (CVSS 6.3): Off-by-one error in org.example:vulnerable:1.0')
+ .contains('no fixed version known; Sonatype Guide: https://guide.sonatype.com/vulnerability/CVE-2026-0002')
+ .contains('fixed in 1.1; OSV: https://osv.dev/vulnerability/GHSA-1111; ' +
+ 'Sonatype Guide: https://guide.sonatype.com/vulnerability/CVE-2026-0001')
+ .contains('Sonatype Guide looked up 2 components, using 0.2 credits; 100 remain')
+ .doesNotContain(SonatypeGuideStub.TOKEN)
+
+ Map report = report(projectDir)
+ assertThat(report.sources).isEqualTo(['OSV', 'Sonatype Guide'])
+ assertThat(report.unavailableSources).isEmpty()
+ assertThat(report.findings*.id).containsExactly('GHSA-1111', 'CVE-2026-0002')
+ assertThat(report.findings[0].sources*.name).containsExactly('OSV', 'Sonatype Guide')
+ assertThat(report.findings[1].sources*.name).containsExactly('Sonatype Guide')
+ }
+
+ @Test
+ void 'the credentials are read when the scan runs, so a new token keeps the configuration cache entry'() {
+ new File(projectDir, 'gradle.properties') << 'vulnerabilityScan.cacheTtl=PT0S\n'
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0002', '6.3', 'Off-by-one error')
+ writeProject(projectDir, ['org.example:library:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ withSonatypeGuideCredentials()
+ BuildResult stored = runner('vulnerabilityScan').buildAndFail()
+
+ // the token is replaced
+ sonatype.token = 'rotated-token'
+ withSonatypeGuideCredentials('rotated-token')
+ BuildResult reused = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(stored.output).contains('Configuration cache entry stored')
+ assertThat(reused.output)
+ .contains('Configuration cache entry reused')
+ .contains('CVE-2026-0002 MEDIUM (CVSS 6.3)')
+ assertThat(sonatype.requests.get()).isEqualTo(2)
+ }
+
+ @Test
+ void 'credentials Sonatype Guide rejects fail the scan without revealing the token'() {
+ sonatype.token = 'another-token'
+ writeProject(projectDir, ['org.example:safe:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ withSonatypeGuideCredentials()
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(result.output)
+ .contains('with 401 (check SONATYPE_GUIDE_USERNAME and SONATYPE_GUIDE_TOKEN)')
+ .doesNotContain(SonatypeGuideStub.TOKEN)
+ }
+
+ @Test
+ void 'an excluded vulnerability is reported as excluded and does not fail the scan'() {
+ writeProject(projectDir, ['org.example:library:1.0'], '''
+ vulnerabilityScan {
+ exclude('CVE-2026-0001', 'org.example:vulnerable', 'No fixed release exists yet')
+ }
+ ''')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ BuildResult result = runner('vulnerabilityScan').build()
+
+ assertThat(result.task(':vulnerabilityScan').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ Map report = report(projectDir)
+ assertThat(report.findings).isEmpty()
+ assertThat(report.excluded*.id).containsExactly('GHSA-1111')
+ assertThat(report.excluded[0].reason).isEqualTo('No fixed release exists yet')
+ }
+
+ @Test
+ void 'a reused configuration cache entry scans again, and answers within the cache time are not asked again'() {
+ writeProject(projectDir, ['org.example:library:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ withSonatypeGuideCredentials()
+
+ BuildResult stored = runner('vulnerabilityScan').buildAndFail()
+ BuildResult reused = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(stored.output).contains('Configuration cache entry stored')
+ assertThat(reused.output)
+ .contains('Configuration cache entry reused')
+ .contains('GHSA-1111 (CVE-2026-0001)')
+ // the second scan was answered from the cache
+ .doesNotContain('Sonatype Guide looked up')
+ assertThat(osv.queryRequests.get()).isEqualTo(1)
+ assertThat(osv.vulnerabilityRequests.get()).isEqualTo(1)
+ assertThat(sonatype.requests.get()).isEqualTo(1)
+ }
+
+ @Test
+ void 'the report summarizes the scans of every project, including the ones that failed'() {
+ sonatype.vulnerable('org.example:vulnerable:1.0', 'CVE-2026-0002', '9.1', 'Remote code execution')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'root'\ninclude 'a', 'b'"
+ new File(projectDir, 'build.gradle').text = """
+ plugins {
+ id '$REPORT_PLUGIN'
+ }
+ """
+ writeProject(new File(projectDir, 'a'), ['org.example:library:1.0'])
+ writeProject(new File(projectDir, 'b'), ['org.example:safe:1.0'], '''
+ vulnerabilityScan {
+ exclude('CVE-2026-9999', null, 'Flagged against every version of a library this build no longer uses')
+ }
+ ''')
+ withSonatypeGuideCredentials()
+
+ BuildResult result = runner('vulnerabilityScan', 'vulnerabilityScanReport', '--continue').buildAndFail()
+
+ assertThat(result.task(':a:vulnerabilityScan').outcome).isEqualTo(TaskOutcome.FAILED)
+ assertThat(result.task(':b:vulnerabilityScan').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ assertThat(result.task(':vulnerabilityScanReport').outcome).isEqualTo(TaskOutcome.SUCCESS)
+
+ String summary = new File(projectDir, 'build/reports/vulnerability-scan/summary.md').text
+ assertThat(summary)
+ .contains('ā 2 known vulnerabilities in 1 dependency of 2 scanned projects.\n\nChecked against OSV and Sonatype Guide.\n')
+ .contains('### org.example:vulnerable:1.0')
+ .contains('| [GHSA-1111](https://osv.dev/vulnerability/GHSA-1111) (CVE-2026-0001) | HIGH | 1.1 | ' +
+ '[OSV](https://osv.dev/vulnerability/GHSA-1111) | Vulnerability GHSA-1111 |')
+ .contains('| [CVE-2026-0002](https://guide.sonatype.com/vulnerability/CVE-2026-0002) | CRITICAL (CVSS 9.1) | none known | ' +
+ '[Sonatype Guide](https://guide.sonatype.com/vulnerability/CVE-2026-0002) | Remote code execution in org.example:vulnerable:1.0 |')
+ .contains('Found in `:a`, via `runtimeClasspath āŗ org.example:library:1.0 āŗ org.example:vulnerable:1.0`')
+ // an exclusion that no longer matches anything is called out
+ .contains('- CVE-2026-9999: remove it, the scanned dependencies no longer have this vulnerability')
+ }
+
+ @Test
+ void 'without Sonatype Guide the report says so, and does not call its exclusions unused'() {
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'root'\ninclude 'a'"
+ new File(projectDir, 'build.gradle').text = """
+ plugins {
+ id '$REPORT_PLUGIN'
+ }
+ """
+ writeProject(new File(projectDir, 'a'), ['org.example:safe:1.0'], '''
+ vulnerabilityScan {
+ exclude('CVE-2026-9999', null, 'Only Sonatype Guide flags this')
+ }
+ ''')
+
+ BuildResult result = runner('vulnerabilityScan', 'vulnerabilityScanReport').build()
+
+ assertThat(result.task(':a:vulnerabilityScan').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ assertThat(new File(projectDir, 'build/reports/vulnerability-scan/summary.md').text).isEqualTo(
+ 'ā
No known vulnerabilities in the dependencies of 1 scanned project.\n\n' +
+ 'Checked against OSV.\n\n' +
+ 'ā ļø Sonatype Guide was not consulted: SONATYPE_GUIDE_TOKEN is not set.\n')
+ }
+
+ @Test
+ void 'the report plugin only applies to the root project'() {
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'root'\ninclude 'a'"
+ writeProject(new File(projectDir, 'a'), ['org.example:safe:1.0'], """
+ apply plugin: '$REPORT_PLUGIN'
+ """)
+
+ BuildResult result = runner('help').buildAndFail()
+
+ assertThat(result.output).contains("$REPORT_PLUGIN must be applied to the root project")
+ }
+
+ @Test
+ void 'an exclusion a project adds keeps the built-in exclusions'() {
+ writeProject(projectDir, ['org.example:library:1.0'], '''
+ vulnerabilityScan {
+ exclude('CVE-2026-0001', 'org.example:vulnerable', 'No fixed release exists yet')
+ }
+ ''')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ runner('vulnerabilityScan').build()
+
+ List<String> exclusions = report(projectDir).exclusions*.vulnerabilityId
+ assertThat(exclusions).isEqualTo(BuiltInExclusions.EXCLUSIONS*.vulnerabilityId + ['CVE-2026-0001'])
+ }
+
+ @Test
+ void 'a scan that fails to look its dependencies up is listed in the summary, which then claims nothing is clean'() {
+ publish('org.example', 'unknown', '1.0')
+ osv.unavailable << 'org.example:unknown:1.0'
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'root'\ninclude 'a', 'b'"
+ new File(projectDir, 'build.gradle').text = """
+ plugins {
+ id '$REPORT_PLUGIN'
+ }
+ """
+ writeProject(new File(projectDir, 'a'), ['org.example:unknown:1.0'])
+ writeProject(new File(projectDir, 'b'), ['org.example:safe:1.0'], '''
+ vulnerabilityScan {
+ exclude('CVE-2026-9999', null, 'Matched only in the project whose scan failed')
+ }
+ ''')
+ withSonatypeGuideCredentials()
+
+ BuildResult result = runner('vulnerabilityScan', 'vulnerabilityScanReport', '--continue').buildAndFail()
+
+ assertThat(result.task(':a:vulnerabilityScan').outcome).isEqualTo(TaskOutcome.FAILED)
+ assertThat(result.task(':b:vulnerabilityScan').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ assertThat(result.task(':vulnerabilityScanReport').outcome).isEqualTo(TaskOutcome.SUCCESS)
+ assertThat(report(new File(projectDir, 'a')).error as String).contains('still answered POST')
+
+ String summary = new File(projectDir, 'build/reports/vulnerability-scan/summary.md').text
+ assertThat(summary)
+ .startsWith('ā ļø No known vulnerabilities in the dependencies of 1 scanned project, but not every project could be scanned.\n')
+ .contains('ā ļø The scan of 1 project failed, so its dependencies were not checked:\n\n- `:a`: The OSV API still answered POST')
+ .doesNotContain('ā
')
+ .doesNotContain('Exclusions that match nothing')
+ }
+
+ @Test
+ void 'a dependency that cannot be resolved fails the scan with an error report, replacing the report of an earlier run'() {
+ // a run that found a vulnerability
+ writeProject(projectDir, ['org.example:library:1.0'])
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+ runner('vulnerabilityScan').buildAndFail()
+ assertThat(report(projectDir).findings*.id).containsExactly('GHSA-1111')
+
+ // a dependency the repository does not have, which the dependency graph leaves out instead of failing
+ writeProject(projectDir, ['org.example:library:1.0', 'org.example:missing:1.0'])
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ // the scan does not pass over it, as the summary would then vouch for the project
+ assertThat(result.task(':vulnerabilityScan').outcome).isEqualTo(TaskOutcome.FAILED)
+ String error = ': could not resolve 1 dependency, which cannot be scanned: ' +
+ 'org.example:missing:1.0 of runtimeClasspath and compileClasspath (Could not find org.example:missing:1.0.)'
+ assertThat(result.output).contains(error)
+ Map report = report(projectDir)
+ assertThat(report.error).isEqualTo(error)
+ assertThat(report.findings).isNull()
+ // nothing was looked up for it
+ assertThat(osv.queryRequests.get()).isEqualTo(1)
+ }
+
+ @Test
+ void 'the configurations a build script names after the task is realized are the ones scanned'() {
+ writeProject(projectDir, ['org.example:safe:1.0'], '''
+ configurations {
+ scanned
+ }
+ dependencies {
+ scanned 'org.example:vulnerable:1.0'
+ }
+ tasks.getByName('vulnerabilityScan')
+ vulnerabilityScan {
+ configurations = ['scanned']
+ }
+ ''')
+ new File(projectDir, 'settings.gradle').text = "rootProject.name = 'app'"
+
+ BuildResult result = runner('vulnerabilityScan').buildAndFail()
+
+ assertThat(result.output).contains('via scanned > org.example:vulnerable:1.0')
+ assertThat(report(projectDir).dependencies).isEqualTo(1)
+ }
+
+ private void withSonatypeGuideCredentials(String token = SonatypeGuideStub.TOKEN) {
+ environment = environment + [SONATYPE_GUIDE_USERNAME: SonatypeGuideStub.USERNAME, SONATYPE_GUIDE_TOKEN: token]
+ }
+
+ private GradleRunner runner(String... arguments) {
+ GradleRunner.create()
+ .withProjectDir(projectDir)
+ .withArguments(arguments.toList() + ['--stacktrace'])
+ .withEnvironment(environment)
+ .withPluginClasspath()
+ }
+
+ private void writeProject(File dir, List<String> dependencies, String extra = '') {
+ dir.mkdirs()
+ new File(dir, 'build.gradle').text = """
+ plugins {
+ id 'java'
+ id '$SCAN_PLUGIN'
+ }
+ repositories {
+ maven { url = uri('${repositoryDir.toURI()}') }
+ }
+ dependencies {
+ ${dependencies.collect { "implementation '${it}'" }.join('\n ')}
+ }
+ ${extra}
+ """
+ }
+
+ private void publish(String group, String artifact, String version, List<String> dependencies = []) {
+ File dir = new File(repositoryDir, "${group.replace('.', '/')}/${artifact}/${version}")
+ dir.mkdirs()
+ new File(dir, "${artifact}-${version}.pom").text = """<?xml version="1.0" encoding="UTF-8"?>
+ <project xmlns="http://maven.apache.org/POM/4.0.0">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>${group}</groupId>
+ <artifactId>${artifact}</artifactId>
+ <version>${version}</version>
+ <dependencies>
+ ${dependencies.collect { String coordinate ->
+ List<String> parts = coordinate.tokenize(':')
+ "<dependency><groupId>${parts[0]}</groupId><artifactId>${parts[1]}</artifactId><version>${parts[2]}</version></dependency>"
+ }.join('\n')}
+ </dependencies>
+ </project>
+ """.stripIndent().trim()
+ new File(dir, "${artifact}-${version}.jar").bytes = [] as byte[]
+ }
+
+ private static Map report(File dir) {
+ (Map) new JsonSlurper().parse(new File(dir, 'build/reports/vulnerability-scan/vulnerabilities.json'))
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTaskTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTaskTest.groovy
new file mode 100644
index 0000000..b250f61
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanReportTaskTest.groovy
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import java.nio.charset.StandardCharsets
+
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+
+class VulnerabilityScanReportTaskTest {
+
+ @Test
+ void 'without a limit the summary lists every finding and exclusion'() {
+ String summary = VulnerabilityScanReportTask.render([scan(':a', 3, 30)], 0)
+
+ assertThat(summary).startsWith('ā 3 known vulnerabilities in 3 dependencies of 1 scanned project.\n\nChecked against OSV and Sonatype Guide.\n')
+ (1..3).each { assertThat(summary).contains("### org.example:vulnerable-00${it}:1.0\n") }
+ assertThat(summary).contains('\n### Excluded\n\n')
+ (1..30).each { assertThat(summary).contains("- org.example:excluded-${pad(it)}:1.0: [CVE-2026-${1000 + it}]") }
+ assertThat(summary).doesNotContain('truncated')
+ }
+
+ @Test
+ void 'the limit bounds the whole summary, so a long list of exclusions cannot push it over'() {
+ // exclusions that alone take more than the limit
+ List<Map<String, Object>> scans = [scan(':a', 3, 200)]
+ int unlimited = utf8Length(VulnerabilityScanReportTask.render(scans, 0))
+ assertThat(unlimited).isGreaterThan(6000)
+
+ String summary = VulnerabilityScanReportTask.render(scans, 6000)
+
+ assertThat(utf8Length(summary)).isLessThanOrEqualTo(6000)
+ // the findings are all there, and the exclusions are what was cut
+ assertThat(summary).startsWith('ā 3 known vulnerabilities in 3 dependencies of 1 scanned project.\n')
+ (1..3).each { assertThat(summary).contains("### org.example:vulnerable-00${it}:1.0\n") }
+ assertThat(summary).contains('\n### Excluded\n\n- org.example:excluded-001:1.0: ')
+ assertThat(summary).endsWith('\n⦠truncated; the workflow run has the complete report.\n')
+ }
+
+ @Test
+ void 'a listing of findings that does not fit is cut at a line, and the sections after it are left out'() {
+ String summary = VulnerabilityScanReportTask.render([scan(':a', 100, 5)], 8000)
+
+ assertThat(utf8Length(summary)).isLessThanOrEqualTo(8000)
+ assertThat(summary).startsWith('ā 100 known vulnerabilities in 100 dependencies of 1 scanned project.\n')
+ assertThat(summary).contains('### org.example:vulnerable-001:1.0\n')
+ assertThat(summary).doesNotContain('### org.example:vulnerable-100:1.0\n')
+ assertThat(summary).doesNotContain('### Excluded')
+ assertThat(summary).endsWith('|\n\n⦠truncated; the workflow run has the complete report.\n')
+ }
+
+ @Test
+ void 'the sections are cut at a line boundary, never inside a character'() {
+ // lines of multi-byte characters, so most cuts would land inside one
+ List<String> sections = ['head\n', (1..50).collect { "āŗ line ${it} āŗ" }.join('\n') + '\n', 'tail\n']
+
+ (60..400).each { int maxBytes ->
+ String text = VulnerabilityScanReportTask.fit(sections, maxBytes)
+ assertThat(utf8Length(text)).describedAs("$maxBytes bytes").isLessThanOrEqualTo(maxBytes)
+ assertThat(text).describedAs("$maxBytes bytes")
+ .doesNotContain('ļæ½')
+ .endsWith('⦠truncated; the workflow run has the complete report.\n')
+ assertThat(text.readLines().findAll { it.startsWith('āŗ') }).describedAs("$maxBytes bytes").allMatch { it.endsWith('āŗ') }
+ }
+ assertThat(VulnerabilityScanReportTask.fit(sections, 0)).isEqualTo(sections.join(''))
+ assertThat(VulnerabilityScanReportTask.fit(sections, 10_000)).isEqualTo(sections.join(''))
+ }
+
+ @Test
+ void 'a clean scan says which databases it checked against and which it could not'() {
+ Map<String, Object> scan = scan(':a', 0, 0)
+ scan.sources = ['OSV']
+ scan.unavailableSources = [[name: 'Sonatype Guide', reason: 'SONATYPE_GUIDE_TOKEN is not set']]
+
+ assertThat(VulnerabilityScanReportTask.render([scan], 0)).isEqualTo(
+ 'ā
No known vulnerabilities in the dependencies of 1 scanned project.\n\n' +
+ 'Checked against OSV.\n\n' +
+ 'ā ļø Sonatype Guide was not consulted: SONATYPE_GUIDE_TOKEN is not set.\n')
+ }
+
+ private static String pad(int i) {
+ String.format('%03d', i)
+ }
+
+ private static int utf8Length(String text) {
+ text.getBytes(StandardCharsets.UTF_8).length
+ }
+
+ /**
+ * The report of a scan with the given number of vulnerable dependencies, each with one finding, and of
+ * excluded ones.
+ */
+ private static Map<String, Object> scan(String project, int findings, int excluded) {
+ [
+ project : project,
+ dependencies : findings + excluded + 1,
+ sources : ['OSV', 'Sonatype Guide'],
+ unavailableSources: [],
+ findings : (findings ? (1..findings) : []).collect { int i ->
+ [dependency : "org.example:vulnerable-${pad(i)}:1.0" as String, id: "GHSA-${i}" as String, ids: ["GHSA-${i}" as String],
+ aliases : [], summary: "Vulnerability ${i}" as String, severity: 'HIGH', fixedVersions: ['1.1'],
+ url : "https://osv.dev/vulnerability/GHSA-${i}" as String,
+ sources : [[name: 'OSV', url: "https://osv.dev/vulnerability/GHSA-${i}" as String]],
+ path : ['runtimeClasspath', "org.example:vulnerable-${pad(i)}:1.0" as String]]
+ },
+ excluded : (excluded ? (1..excluded) : []).collect { int i ->
+ [dependency: "org.example:excluded-${pad(i)}:1.0" as String, id: "CVE-2026-${1000 + i}" as String,
+ url : "https://osv.dev/vulnerability/CVE-2026-${1000 + i}" as String,
+ exclusion : "CVE-2026-${1000 + i}" as String,
+ reason : 'No fixed release exists upstream; remove the exclusion once one does and the dependency has been upgraded']
+ },
+ exclusions : [],
+ ] as Map<String, Object>
+ }
+}
diff --git a/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTaskTest.groovy b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTaskTest.groovy
new file mode 100644
index 0000000..45bab81
--- /dev/null
+++ b/build-logic/src/test/groovy/org/apache/grails/intellij/build/scan/VulnerabilityScanTaskTest.groovy
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.grails.intellij.build.scan
+
+import org.junit.Test
+
+import static org.assertj.core.api.Assertions.assertThat
+
+/**
+ * The pure functions of the scan task: how a record is rated and how the two databases' findings are merged. The
+ * task itself runs in {@link VulnerabilityScanPluginTest}.
+ */
+class VulnerabilityScanTaskTest {
+
+ private static final String CVSS_V4 = 'CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N'
+
+ @Test
+ void 'the severity of an OSV record is the rating its database gives, else one scored from a CVSS v3 vector it carries'() {
+ Map<Map, String> examples = [
+ ([database_specific: [severity: 'MODERATE']] as Map) : 'MODERATE',
+ ([affected: [[ecosystem_specific: [severity: 'LOW']]]] as Map) : 'LOW',
+ ([severity: [[type: 'CVSS_V3', score: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H']]] as Map) : 'HIGH (CVSS 7.5)',
+ ([severity: [[type: 'CVSS_V4', score: CVSS_V4],
+ [type: 'CVSS_V3', score: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H']]] as Map) : 'CRITICAL (CVSS 9.8)',
+ ([severity: [[type: 'CVSS_V4', score: CVSS_V4]]] as Map) : 'CVSS_V4',
+ ([database_specific: [severity: 'HIGH'],
+ severity : [[type: 'CVSS_V3', score: 'CVSS:3.1/AV:P/AC:H/PR:H/UI:R/S:U/C:N/I:N/A:N']]] as Map): 'HIGH',
+ ([:] as Map) : 'UNKNOWN',
+ ]
+ examples.each { Map record, String severity ->
+ assertThat(VulnerabilityScanTask.severity(record)).describedAs(record.toString()).isEqualTo(severity)
+ }
+ }
+
+ @Test
+ void 'a CVSS score is rated as the specification does'() {
+ [
+ ['9.8', 'CRITICAL (CVSS 9.8)'],
+ [9.0, 'CRITICAL (CVSS 9)'],
+ ['7.5', 'HIGH (CVSS 7.5)'],
+ ['4.0', 'MEDIUM (CVSS 4)'],
+ ['3.9', 'LOW (CVSS 3.9)'],
+ ['0.0', 'NONE (CVSS 0)'],
+ [null, 'UNKNOWN'],
+ ['high', 'UNKNOWN'],
+ ].each { List example ->
+ assertThat(VulnerabilityScanTask.cvssSeverity(example[0])).describedAs(String.valueOf(example[0])).isEqualTo(example[1])
+ }
+ }
+
+ @Test
+ void 'a finding both databases know of is reported once, keeping what OSV knows of the fix'() {
+ List<String> path = ['runtimeClasspath', 'org.example:vulnerable:1.0']
+ Map<String, Object> osv = VulnerabilityScanTask.finding('org.example:vulnerable:1.0', 'org.example:vulnerable', [
+ id : 'GHSA-1111', aliases: ['CVE-2026-0001'], summary: 'Resource exhaustion',
+ affected: [[package: [ecosystem: 'Maven', name: 'org.example:vulnerable'],
+ ranges : [[type: 'ECOSYSTEM', events: [[introduced: '0'], [fixed: '1.1']]]]]],
+ ] as Map<String, Object>, path)
+ Map<String, Object> same = VulnerabilityScanTask.sonatypeFinding('org.example:vulnerable:1.0', [
+ id: 'CVE-2026-0001', cve: 'CVE-2026-0001', title: '[CVE-2026-0001] Resource exhaustion', cvssScore: '7.5',
+ ] as Map<String, Object>, path)
+ Map<String, Object> other = VulnerabilityScanTask.sonatypeFinding('org.example:vulnerable:1.0', [
+ id: 'CVE-2026-0002', cve: 'CVE-2026-0002', title: '[CVE-2026-0002] Off-by-one error', cvssScore: '6.3',
+ ] as Map<String, Object>, path)
+
+ List<Map<String, Object>> merged = VulnerabilityScanTask.merge([osv], [same, other])
+
+ assertThat(merged*.id).containsExactly('GHSA-1111', 'CVE-2026-0002')
+ assertThat(merged[0].fixedVersions).isEqualTo(['1.1'])
+ assertThat(merged[0].sources*.name).containsExactly('OSV', 'Sonatype Guide')
+ // OSV rated nothing, so Sonatype Guide's score stands in
+ assertThat(merged[0].severity).isEqualTo('HIGH (CVSS 7.5)')
+ assertThat(merged[1].sources*.name).containsExactly('Sonatype Guide')
+ assertThat(merged[1].summary).isEqualTo('Off-by-one error')
+ assertThat(merged[1].fixedVersions).isEmpty()
+ }
+}
diff --git a/build.gradle b/build.gradle
index 09d40cb..561162b 100644
--- a/build.gradle
+++ b/build.gradle
@@ -20,14 +20,16 @@
// The root project is a pure aggregator: it compiles nothing and produces no artifact. It owns
// only the things that must run from the repository root -- the licence audit, whose exclude
// patterns are anchored at the audited directory, the cross-project coverage aggregation, which
-// keeps its report at the path CI uploads, and the GitHub Actions policy check, which scans the
-// repository's .github/workflows.
+// keeps its report at the path CI uploads, the GitHub Actions policy check, which scans the
+// repository's .github/workflows, and the vulnerability scan summary, which collects every
+// project's scan report.
//
// Deliberately no allprojects/subprojects block: every project applies its own convention plugins.
plugins {
id 'org.apache.grails.intellij.build.rat'
id 'org.apache.grails.intellij.build.coverage-aggregation'
id 'org.apache.grails.intellij.build.validate-actions'
+ id 'org.apache.grails.intellij.build.vulnerability-scan-report'
}
// build-logic is an included build, so the root `check` does not reach its tests and plugin
diff --git a/libs/testFramework/build.gradle b/libs/testFramework/build.gradle
index 4e0054d..6811b72 100644
--- a/libs/testFramework/build.gradle
+++ b/libs/testFramework/build.gradle
@@ -50,3 +50,13 @@ dependencies {
compileOnly project(':plugin')
}
+
+// The test frameworks above are JetBrains' own test-framework jars at the platform version, with
+// the Jackson, Bouncy Castle and friends they were built against. They are test infrastructure --
+// on no runtime classpath and in no distribution -- and move only when the platform does, so the
+// scan would report advisories against them that only a platform bump can clear. Only what this
+// jar carries at runtime is scanned; the platform bump itself is where those versions are
+// reviewed.
+vulnerabilityScan {
+ configurations = ['runtimeClasspath']
+}