Repository navigation
Conversation
gnodet-bot
left a comment
There was a problem hiding this comment.
Several issues need addressing before this can merge.
Core concern: The output claims "sbomFormat": "protobom-json" but protobom is a protocol-buffers schema (not a JSON format). No existing SBOM toolchain — CycloneDX, SPDX, Grype, Trivy, Dependency-Track — can parse this output. The PR's stated motivation (NTIA minimum elements, EO 14028, EU CRA) requires a recognized format. As-is, users who run --sbom for compliance will produce a file that every scanner rejects.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| context.options().sbomFile().ifPresent(file -> { | ||
| try { | ||
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); | ||
| } catch (IOException e) { | ||
| context.logger.warn("Failed to write SBOM report: " + e.getMessage()); | ||
| } | ||
| }); |
There was a problem hiding this comment.
result.hasExceptions() is checked — a build that fails midway produces sbom.json with partially-resolved or missing dependency data. A compliance consumer has no way to know the SBOM is incomplete.
Guard with a success check:
| context.options().sbomFile().ifPresent(file -> { | |
| try { | |
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); | |
| } catch (IOException e) { | |
| context.logger.warn("Failed to write SBOM report: " + e.getMessage()); | |
| } | |
| }); | |
| if (!result.hasExceptions()) { | |
| context.options().sbomFile().ifPresent(file -> { | |
| try { | |
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); | |
| } catch (IOException e) { | |
| context.logger.warn("Failed to write SBOM report: " + e.getMessage()); | |
| } | |
| }); | |
| } |
There was a problem hiding this comment.
Fixed in 2b36806: the SBOM write is now gated by !result.hasExceptions().
|
|
||
| StringBuilder sb = new StringBuilder(); | ||
| sb.append("{\n"); | ||
| sb.append(" \"sbomFormat\": \"protobom-json\",\n"); |
There was a problem hiding this comment.
🚫 "protobom-json" is not a real SBOM format. Protobom is a protocol-buffers schema (see protobom/protobom) with Go serializers for SPDX and CycloneDX — it has no "protobom-json" JSON serialization. Existing tools (Grype, Trivy, GUAC, Dependency-Track) will not parse this output.
For the stated compliance goals (NTIA, EO 14028, EU CRA), the output must be CycloneDX JSON (bomFormat: "CycloneDX") or SPDX JSON. CycloneDX 1.6 is the simpler option — a hand-rolled minimal BOM with bomFormat, specVersion, version, and a components array is parseable by the entire CycloneDX ecosystem without adding any dependencies.
There was a problem hiding this comment.
Fixed in 2b36806: output is now CycloneDX 1.6 JSON (bomFormat, specVersion, components, dependencies) instead of protobom-json.
| return; | ||
| } | ||
| String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; | ||
| components.putIfAbsent(purl, new String[] {artifactId, version, purl}); |
There was a problem hiding this comment.
name drops the groupId. Two artifacts like com.google.guava:guava and org.codehaus.plexus:guava will both appear as "name": "guava" in the SBOM — indistinguishable without reading the purl. SBOM dashboards display name as the primary identifier. Use Maven's canonical coordinate: groupId + ":" + artifactId.
| components.putIfAbsent(purl, new String[] {artifactId, version, purl}); | |
| String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; | |
| components.putIfAbsent(purl, new String[] {groupId + ":" + artifactId, version, purl}); |
There was a problem hiding this comment.
Fixed in 2b36806: each component now emits separate group and name; the purl disambiguates artifacts with the same artifactId.
|
|
||
| private static String timestamp() { | ||
| String epoch = System.getenv("SOURCE_DATE_EPOCH"); | ||
| Instant instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); |
There was a problem hiding this comment.
Long.parseLong(epoch) is not guarded. A malformed or empty SOURCE_DATE_EPOCH value throws NumberFormatException that propagates up through write() and prevents SBOM generation with a confusing error. Fall back to Instant.now() on parse failure:
| Instant instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); | |
| Instant instant; | |
| try { | |
| instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); | |
| } catch (NumberFormatException e) { | |
| instant = Instant.now(); | |
| } |
There was a problem hiding this comment.
Fixed in 2b36806: invalid SOURCE_DATE_EPOCH falls back to Instant.now().
| private static String escape(String value) { | ||
| return value.replace("\\", "\\\\").replace("\"", "\\\""); | ||
| } |
There was a problem hiding this comment.
\\ and \" are handled. JSON RFC 8259 requires escaping all control characters U+0000–U+001F (\n, \r, \t, etc.). Maven coordinates don't use control characters in practice, but this method is factually incorrect as a JSON escape helper:
| private static String escape(String value) { | |
| return value.replace("\\", "\\\\").replace("\"", "\\\""); | |
| } | |
| private static String escape(String value) { | |
| StringBuilder out = new StringBuilder(value.length()); | |
| for (int i = 0; i < value.length(); i++) { | |
| char c = value.charAt(i); | |
| if (c == '\\') out.append("\\\\"); | |
| else if (c == '"') out.append("\\\""); | |
| else if (c < 0x20) out.append(String.format("\\u%04x", (int) c)); | |
| else out.append(c); | |
| } | |
| return out.toString(); | |
| } |
There was a problem hiding this comment.
Fixed in 2b36806: escape() now escapes control characters U+0000-U+001F.
| * components; supplier, license and hash are omitted as Maven does not retain them | ||
| * in the resolved artifact set. | ||
| * | ||
| * @return an {@link Optional} containing the report file name, or empty if not specified |
There was a problem hiding this comment.
💡 Minor Javadoc imprecision. @return says "report file name" but the value is used as request.getTopDirectory().resolve(file) — a path relative to the top directory. Also, the return type Optional<String> implies the caller could supply a custom path, but CommonsCliMavenOptions always returns "sbom.json" unconditionally. If the filename is fixed, Optional<Boolean> (consistent with listAliases()) would be a cleaner contract, with the path constructed in MavenInvoker.
| * @return an {@link Optional} containing the report file name, or empty if not specified | |
| * @return an {@link Optional} containing the SBOM output path relative to the top-level | |
| * project directory, or empty if {@code --sbom} was not passed |
There was a problem hiding this comment.
Fixed in 2b36806: Javadoc now says the report path is relative to the top-level project directory.
|
|
||
| assertTrue(options.sbomFile().isEmpty(), "sbomFile must be empty without the flag"); | ||
| } | ||
| } |
There was a problem hiding this comment.
💡 Missing writer test. This class only tests CLI option parsing. SbomReportWriter.write() has no test: no verification that the output is valid JSON, that component deduplication works across projects, that null groupId/artifactId/version are skipped, or that SOURCE_DATE_EPOCH produces a deterministic timestamp. A unit test with a minimal mock MavenExecutionResult would be straightforward.
There was a problem hiding this comment.
Fixed in 2b36806: added SbomReportWriterTest; Docker Maven tests pass 3/3.
gnodet-bot
left a comment
There was a problem hiding this comment.
Several issues need addressing before this can merge.
[HIGH] SBOM written before exception check — failed builds produce misleading partial SBOMs
The sbomFile().ifPresent() block executes unconditionally before result.hasExceptions(). A build that compiles some modules and then fails partway through will still emit an SBOM that looks complete but represents only the modules that ran. Callers who run --sbom for compliance audits will receive a structurally-valid file that silently under-reports the project's dependency set.
Wrap the block:
if (!result.hasExceptions()) {
context.options().sbomFile().ifPresent(file -> {
try {
SbomReportWriter.write(request.getTopDirectory().resolve(file), result);
} catch (IOException e) {
context.logger.warn("Failed to write SBOM report: " + e.getMessage());
}
});
}
[HIGH] "protobom-json" is not a recognized SBOM format
Protobom is a protocol-buffers binary schema (with Go serializers for SPDX and CycloneDX) — it has no JSON serialization format. No existing SBOM toolchain (Grype, Trivy, Dependency-Track, GUAC, bomctl) can parse "sbomFormat": "protobom-json". The PR's stated motivation (NTIA minimum elements, EO 14028, EU CRA) requires a recognized format; this custom label provides zero compliance value.
Recommended alternatives:
- CycloneDX 1.6 JSON — simpler schema than SPDX, hand-rollable, widest toolchain support
- SPDX 2.3 JSON — well-specified, also hand-rollable
[MEDIUM] name field drops groupId — artifact name collisions
c[0] is artifactId only. Two artifacts from different groups with the same artifactId (e.g. com.google.guava:guava and org.codehaus.plexus:guava) produce identical "name": "guava" entries. The id field (purl) disambiguates at the data level, but dashboards and human readers rely on name. Maven's canonical coordinate is groupId:artifactId; use that.
nodes.put(rootPurl, new String[] {project.getGroupId() + ":" + project.getArtifactId(), project.getVersion(), rootPurl});
(and the same for artifact.getGroupId() + ":" + artifact.getArtifactId() at line 65)
[MEDIUM] Incomplete JSON escaping — RFC 8259 §7 violation
escape() handles only \ and ". RFC 8259 §7 requires escaping control characters U+0000–U+001F (tab \t, newline \n, carriage return \r, etc.). Maven coordinates do not normally contain control characters, but artifact descriptions or metadata attached to name/version fields that flow through escape() might. A hand-rolled JSON encoder must be complete.
[MEDIUM] No test for SbomReportWriter.write()
The test file only exercises CLI parsing (flag presence/absence). The 134-line hand-rolled JSON encoder — including the SBOM graph traversal, purl construction, edge emission, and escape() function — has zero test coverage. Add at least one integration-level test that calls SbomReportWriter.write() with a minimal MavenExecutionResult and asserts the structure of the emitted JSON.
[LOW] @return Javadoc says "file name" but value is used as a path
The option value "sbom.json" is resolved via request.getTopDirectory().resolve(file), making it a path relative to the top directory. @return should say "path relative to the top-level project directory" rather than "report file name" to match how the value is actually consumed.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
|
||
| StringBuilder sb = new StringBuilder(); | ||
| sb.append("{\n"); | ||
| sb.append(" \"sbomFormat\": \"protobom-json\",\n"); |
| context.eventSpyDispatcher.close(); | ||
| } | ||
|
|
||
| context.options().sbomFile().ifPresent(file -> { |
There was a problem hiding this comment.
[HIGH] SBOM written before exception check. This block executes before result.hasExceptions() at line 582. A partially-failed build emits an incomplete SBOM that callers may treat as authoritative.
Wrap the block:
| context.options().sbomFile().ifPresent(file -> { | |
| if (!result.hasExceptions()) { | |
| context.options().sbomFile().ifPresent(file -> { | |
| try { | |
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); | |
| } catch (IOException e) { | |
| context.logger.warn("Failed to write SBOM report: " + e.getMessage()); | |
| } | |
| }); | |
| } |
There was a problem hiding this comment.
Fixed in 2b36806: SBOM write is now gated by !result.hasExceptions().
|
|
||
| StringBuilder sb = new StringBuilder(); | ||
| sb.append("{\n"); | ||
| sb.append(" \"sbomFormat\": \"protobom-json\",\n"); |
There was a problem hiding this comment.
[HIGH] "protobom-json" is not a recognized SBOM format. Protobom is a protocol-buffers binary schema — it has no JSON serialization format. Compliance tools (Grype, Trivy, Dependency-Track) will reject this output. Use a recognized format like CycloneDX 1.6 JSON ("CycloneDX" with "specVersion": "1.6") or SPDX 2.3 JSON instead.
There was a problem hiding this comment.
Fixed in 2b36806: output is CycloneDX 1.6 JSON, not protobom-json.
| if (rootPurl == null) { | ||
| continue; | ||
| } | ||
| nodes.put(rootPurl, new String[] {project.getArtifactId(), project.getVersion(), rootPurl}); |
There was a problem hiding this comment.
[MEDIUM] name drops groupId. c[0] is artifactId only. Two artifacts from different groups with the same artifactId (e.g. com.google.guava:guava and org.codehaus.plexus:guava) produce identical name values. Use groupId + ":" + artifactId as Maven's canonical coordinate.
| nodes.put(rootPurl, new String[] {project.getArtifactId(), project.getVersion(), rootPurl}); | |
| nodes.put(rootPurl, new String[] {project.getGroupId() + ":" + project.getArtifactId(), project.getVersion(), rootPurl}); |
There was a problem hiding this comment.
Fixed in 2b36806: components emit separate group and name.
| if (depPurl == null || depPurl.equals(rootPurl)) { | ||
| continue; | ||
| } | ||
| nodes.put(depPurl, new String[] {artifact.getArtifactId(), artifact.getVersion(), depPurl}); |
There was a problem hiding this comment.
Same issue: c[0] is artifactId only — use artifact.getGroupId() + ":" + artifact.getArtifactId().
| nodes.put(depPurl, new String[] {artifact.getArtifactId(), artifact.getVersion(), depPurl}); | |
| nodes.put(depPurl, new String[] {artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getVersion(), depPurl}); |
There was a problem hiding this comment.
Fixed in 2b36806: dependency components also emit separate group and name.
| } | ||
|
|
||
| private static String escape(String value) { | ||
| return value.replace("\\", "\\\\").replace("\"", "\\\""); |
There was a problem hiding this comment.
[MEDIUM] Incomplete JSON escaping — RFC 8259 §7 violation. Only \\ and " are handled. Control characters U+0000–U+001F (tab, newline, carriage return, etc.) must also be escaped. At minimum add .replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r").
There was a problem hiding this comment.
Fixed in 2b36806: escape() handles control characters U+0000-U+001F.
| * components; supplier, license and hash are omitted as Maven does not retain them | ||
| * in the resolved artifact set. | ||
| * | ||
| * @return an {@link Optional} containing the report file name, or empty if not specified |
There was a problem hiding this comment.
[LOW] Javadoc says "file name" but value is used as a relative path. The value is resolved via request.getTopDirectory().resolve(file) in MavenInvoker. Suggest: @return an {@link Optional} containing the report path relative to the top-level project directory, or empty if not specified
There was a problem hiding this comment.
Fixed in 2b36806: Javadoc says report path relative to top-level project directory.
|
|
||
| assertTrue(options.sbomFile().isEmpty(), "sbomFile must be empty without the flag"); | ||
| } | ||
| } |
There was a problem hiding this comment.
[MEDIUM] No test for SbomReportWriter.write(). This file only tests CLI flag parsing. The 134-line hand-rolled JSON encoder — graph traversal, purl construction, edge emission, escape() — has zero test coverage. Please add at least one test that invokes SbomReportWriter.write() and asserts the structure of the emitted JSON.
There was a problem hiding this comment.
Fixed in 2b36806: added SbomReportWriterTest; Docker Maven tests pass 3/3.
gnodet-bot
left a comment
There was a problem hiding this comment.
Following up on my earlier review — all 6 previous issues have been addressed. ✅
- [HIGH] SBOM written before exception check — ✅ fixed:
if (!result.hasExceptions())guard is now in place. - [HIGH]
"protobom-json"not a recognized format — ✅ fixed: now emits"bomFormat": "CycloneDX","specVersion": "1.6". - [MEDIUM]
namedrops groupId — ✅ fixed: components now emit separate"group"and"name"fields. - [MEDIUM] Incomplete JSON escaping — ✅ fixed:
escape()now handles control charactersc < 0x20. - [MEDIUM] No test for
SbomReportWriter.write()— ✅ fixed:SbomReportWriterTestadded. - [LOW]
@returnsays "file name" — ✅ fixed: Javadoc now says "path relative to the top-level project directory".
Two remaining issues found in the new commits:
[MEDIUM] Components with no dependencies are absent from dependencies[]
The CycloneDX 1.6 specification states that every component and service should appear in the dependencies array, even if its dependsOn list is empty. The current code uses computeIfAbsent only when a dependency edge is added, so a module with no resolved artifacts is silently omitted from the dependencies block.
Dependency-Track and other graph-analysis tools use dependencies for completeness checks. A module that is present in components but absent from dependencies is treated as an orphan and may be excluded from vulnerability correlation.
Fix: after building the components and dependencies maps, ensure every component purl has an entry in dependencies (possibly with an empty dependsOn):
for (String purl : components.keySet()) {
dependencies.putIfAbsent(purl, new TreeSet<>());
}
(Add this line after the outer for (MavenProject project …) loop, before the JSON serialisation.)
[LOW] tools array format is deprecated in CycloneDX 1.6
The CycloneDX 1.6 schema defines tools as a oneOf: the new form is {"components": [...], "services": [...]} and the legacy array form is [Deprecated]. The current code uses the deprecated array form. The output is still schema-valid (the array form is in the oneOf), but validators like cyclonedx-cli will warn, and the format will be rejected in a future spec version.
Preferred form for 1.6:
sb.append(" "tools": {"components": [{"type": "application", "name": "mvn"}]},\n");
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| sb.append(" \"version\": 1,\n"); | ||
| sb.append(" \"metadata\": {\n"); | ||
| sb.append(" \"timestamp\": \"").append(timestamp()).append("\",\n"); | ||
| sb.append(" \"tools\": [{\"name\": \"mvn\"}],\n"); |
There was a problem hiding this comment.
tools field uses the deprecated array format. CycloneDX 1.6 defines tools as a oneOf; the array form is [Deprecated] in the schema. Use the new object form instead:
| sb.append(" \"tools\": [{\"name\": \"mvn\"}],\n"); | |
| sb.append(" \"tools\": {\"components\": [{\"type\": \"application\", \"name\": \"mvn\"}]},\n"); |
|
warning: SBOM is a very diverse expectations world whatever this option will do won't match expectations from many people just for an idea, see the CycloneDX issue where I started to find a solution to the usefulness of SBOMs we generate for years, with already a lot of config optons, and that do not match expectations from many people (particularly me :) ) CycloneDX/cyclonedx-maven-plugin#696 of course, we can say "Maven can provide an opinionated default SBOM by default", but we'll have to define a common opinion first |
gnodet-bot
left a comment
There was a problem hiding this comment.
⛔ COMMENT (Blocking Issues Found)
SBOM generation is a valuable feature for Maven 4.2 — the concept is sound, but this implementation has several issues that need to be addressed before merging.
🏗️ Architectural concern: SBOM belongs in a plugin, not maven-cli
Adding sbomFile() to the MavenOptions SPI and the SbomReportWriter directly into maven-cli hardcodes CycloneDX generation into the Maven core. This is the wrong layer. SBOM generation is an ecosystem concern that should be a Maven plugin (similar to how maven-dependency-plugin handles dependency analysis). The PMC has already flagged this design concern. Consider contributing to or extending the existing cyclonedx-maven-plugin instead, or implementing this as a lifecycle-bound Maven extension.
🐛 Generated JSON fails CycloneDX 1.6 schema validation — bom-ref missing
Components are emitted without a bom-ref field, but the dependencies section references those same components by their purl. Per the CycloneDX 1.6 spec, dependencies[].ref must reference a component's bom-ref, not any arbitrary string. As written, every validator will reject this output as schema-invalid. Each component needs a stable bom-ref (conventionally the same as the purl), and dependencies[].ref must match it:
{"type": "library", "bom-ref": "pkg:maven/org.example/lib@2.0", "group": "org.example", "name": "lib", "version": "2.0", "purl": "pkg:maven/org.example/lib@2.0"}🐛 --sbom flag ignores its argument — always writes to sbom.json
The Javadoc on sbomFile() says it returns "the report path relative to the top-level project directory", implying --sbom=<path> is configurable. But the implementation in CommonsCliMavenOptions unconditionally returns Optional.of("sbom.json"), and the Option.builder() has no .hasArg() — it's a boolean flag. The API contract and the CLI definition are misaligned. Either drop the path hint from the Javadoc and update the return type to Optional<Boolean>, or add .hasArg() and use commandLine.getOptionValue(CLIManager.SBOM).
⚠️ Only IOException caught — RuntimeException propagates uncaught from non-critical code
The ifPresent lambda only catches IOException. Any RuntimeException from SbomReportWriter.write() — or even from System.getenv() in timestamp() — propagates uncaught out of the lambda and up through doExecute, failing the build for what should be a non-critical reporting step. At minimum, catch Exception here.
⚠️ project.getArtifacts() returns empty when dependency resolution hasn't run
project.getArtifacts() only contains artifacts populated after the dependency resolution phase. Running mvn --sbom validate or mvn --sbom compile will silently produce an SBOM with zero dependencies — no warning, no error. Add a check and warn if the artifact set is empty when projects have declared dependencies.
⚠️ metadata.authors deprecated in CycloneDX 1.6 — use metadata.manufacturer
CycloneDX 1.6 deprecated metadata.authors in favour of metadata.manufacturer. The generated SBOM uses the deprecated field. Use manufacturer instead:
"manufacturer": {"name": "Apache Maven"}ℹ️ purl values not percent-encoded per purl-spec
The purl() method concatenates groupId/artifactId/version into the purl string without percent-encoding. The purl specification requires encoding of special characters in namespace and name segments. While Maven coordinates are typically safe, edge cases (e.g. classifiers or non-standard artifacts) can produce invalid purls.
ℹ️ Test: use @TempDir instead of manual temp file cleanup
SbomReportWriterTest uses Files.createTempFile() with a manual Files.delete() at the end. If the test fails mid-way, the temp file leaks. JUnit 5 @TempDir handles cleanup automatically and is more robust.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| */ | ||
| @Nonnull | ||
| Optional<String> sbomFile(); | ||
| } |
There was a problem hiding this comment.
🏗️ Architectural concern: Adding sbomFile() to the core MavenOptions SPI bakes CycloneDX generation into the Maven API. SBOM generation is a plugin concern — this method exposes implementation detail into the public API surface. The cyclonedx-maven-plugin already does this in the right layer.
| @Override | ||
| public Optional<String> sbomFile() { | ||
| if (commandLine.hasOption(CLIManager.SBOM)) { | ||
| return Optional.of("sbom.json"); |
There was a problem hiding this comment.
🐛 The sbomFile() Javadoc says it returns the report path, implying --sbom=<path> is supported. But sbomFile() unconditionally returns "sbom.json" and the Option.builder() has no .hasArg() — it's a boolean flag only. The API contract and the CLI definition are inconsistent. Either:
- Drop path semantics from the Javadoc, rename return to
Optional<Boolean> sbom(), or - Add
.hasArg()and usecommandLine.getOptionValue(CLIManager.SBOM).
| if (!result.hasExceptions()) { | ||
| context.options().sbomFile().ifPresent(file -> { | ||
| try { | ||
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); |
There was a problem hiding this comment.
IOException is caught here. A RuntimeException from SbomReportWriter.write() (e.g. from System.getenv() in timestamp()) propagates uncaught and kills the build — wrong for a non-critical reporting step. Catch Exception instead:
| SbomReportWriter.write(request.getTopDirectory().resolve(file), result); | |
| } catch (Exception e) { | |
| context.logger.warn("Failed to write SBOM report: " + e.getMessage()); | |
| } |
| components.put( | ||
| rootPurl, | ||
| new String[] {project.getGroupId(), project.getArtifactId(), project.getVersion(), rootPurl}); | ||
| for (Artifact artifact : project.getArtifacts()) { |
There was a problem hiding this comment.
project.getArtifacts() only contains artifacts populated after dependency resolution. Running mvn --sbom validate or mvn --sbom compile silently produces an SBOM with zero dependencies. Add a check:
if (project.getArtifacts().isEmpty() && !project.getDependencies().isEmpty()) {
// warn: SBOM may be incomplete — run a lifecycle phase that includes dependency resolution
}| sb.append(" \"components\": [\n"); | ||
| int i = 0; | ||
| for (String[] c : components.values()) { | ||
| sb.append(" {\"type\": \"library\", \"group\": \"") |
There was a problem hiding this comment.
🐛 Components are emitted without a bom-ref field. The dependencies section uses purl values as ref, but the CycloneDX 1.6 spec requires dependencies[].ref to match a component's bom-ref. As written, any CycloneDX validator will reject this as schema-invalid. Add "bom-ref" to each component:
sb.append(" {\"type\": \"library\", \"bom-ref\": \"")
.append(escape(c[3])) // purl as bom-ref
.append("\", \"group\": \"")| sb.append(" \"metadata\": {\n"); | ||
| sb.append(" \"timestamp\": \"").append(timestamp()).append("\",\n"); | ||
| sb.append(" \"tools\": {\"components\": [{\"type\": \"application\", \"name\": \"mvn\"}]},\n"); | ||
| sb.append(" \"authors\": [{\"name\": \"Apache Maven\"}]\n"); |
There was a problem hiding this comment.
metadata.authors is deprecated in CycloneDX 1.6 in favour of metadata.manufacturer. Use:
| sb.append(" \"authors\": [{\"name\": \"Apache Maven\"}]\n"); | |
| sb.append(" \"manufacturer\": {\"name\": \"Apache Maven\"}\n"); |
| if (groupId == null || artifactId == null || version == null) { | ||
| return null; | ||
| } | ||
| return "pkg:maven/" + groupId + "/" + artifactId + "@" + version; |
There was a problem hiding this comment.
ℹ️ The purl-spec requires percent-encoding of special characters in namespace/name/version segments. Plain string concatenation here produces potentially invalid purls for coordinates containing unusual characters. Consider using java.net.URLEncoder or a dedicated purl library for the encoding.
| Path file = Files.createTempFile("sbom", ".json"); | ||
| SbomReportWriter.write(file, result); | ||
| String json = Files.readString(file); | ||
|
|
||
| assertTrue(json.contains("\"bomFormat\": \"CycloneDX\""), "must be CycloneDX JSON"); | ||
| assertTrue(json.contains("\"group\": \"org.example\""), "group must be emitted"); | ||
| assertTrue(json.contains("\"name\": \"lib\""), "artifact name must be emitted"); | ||
| assertTrue(json.contains("\"ref\": \"pkg:maven/com.example/app@1.0\""), "root ref must be emitted"); | ||
| assertTrue(json.contains("\"dependsOn\": [\"pkg:maven/org.example/lib@2.0\"]"), "edge must be emitted"); | ||
| assertTrue( | ||
| json.contains("{\"ref\": \"pkg:maven/org.example/lib@2.0\", \"dependsOn\": []}"), | ||
| "dependency component must appear in dependencies with empty dependsOn"); | ||
|
|
||
| Files.delete(file); |
There was a problem hiding this comment.
ℹ️ Prefer @TempDir over manual temp file management. If the test fails between createTempFile and Files.delete, the file leaks:
| Path file = Files.createTempFile("sbom", ".json"); | |
| SbomReportWriter.write(file, result); | |
| String json = Files.readString(file); | |
| assertTrue(json.contains("\"bomFormat\": \"CycloneDX\""), "must be CycloneDX JSON"); | |
| assertTrue(json.contains("\"group\": \"org.example\""), "group must be emitted"); | |
| assertTrue(json.contains("\"name\": \"lib\""), "artifact name must be emitted"); | |
| assertTrue(json.contains("\"ref\": \"pkg:maven/com.example/app@1.0\""), "root ref must be emitted"); | |
| assertTrue(json.contains("\"dependsOn\": [\"pkg:maven/org.example/lib@2.0\"]"), "edge must be emitted"); | |
| assertTrue( | |
| json.contains("{\"ref\": \"pkg:maven/org.example/lib@2.0\", \"dependsOn\": []}"), | |
| "dependency component must appear in dependencies with empty dependsOn"); | |
| Files.delete(file); | |
| @org.junit.jupiter.api.io.TempDir | |
| Path tempDir; | |
| @Test | |
| void writesCycloneDxWithGroupsAndDependencies() throws Exception { |
Then use tempDir.resolve("sbom.json") instead of Files.createTempFile, and drop the final Files.delete(file) call.
PR: maven
PR: #14093 (open)
Title:
Add opt-in SBOM generation (--sbom)Branch:
sbom-support, commits280635bc,fc81e18,2b36806and635b898, 309 insertions across 7 files.Motivation
Regulations (NTIA minimum elements, EO 14028, EU CRA) require an SBOM. Maven
already resolves every artifact in the session;
mvn --sbomwrites it out sono external plugin or scanner is needed.
Design
mvninvoker, not a new invoker:sbomFile()onMavenOptions, theOptionon the mvn-specificCommonsCliMavenOptionsCLIManager (not the shared one, so a following goal is not swallowed), the
accessor wired through
LayeredMavenOptions.SbomReportWriter.java(new, 148 LOC) runs after the build request completesin
MavenInvoker, only when!result.hasExceptions(), walksMavenExecutionResult.getTopologicallySortedProjects()and emits each projectand resolved artifact as a CycloneDX component with a dependency edge — zero
new resolution,
ProjectArtifactsCachealready holds the set.<topDirectory>/sbom.json.bomFormat,specVersion,version,metadata, sortedcomponentswithgroup,name,version,purl, and sorteddependencieswithref/dependsOn.maven-core has zero protobuf or JSON dependency; adding one for a report is the
change most likely to be rejected.
SOURCE_DATE_EPOCHis honoured; an invalid value falls back to the currenttimestamp instead of throwing.
Alternatives considered
sbomgoal: belongs in the separatemaven-pluginsrepo (core bindsonly external plugins,
JarLifecycleMappingProvider.java:33-44); theinvoker-flag fallback is used here per design.
mvnsbominvoker (mvnenc/mvnup precedent): more boilerplate for no gain,the data lives in the session
mvnalready builds.the diff minimal.
Test plan
CommonsCliMavenOptionsSbomTest.java: parses--sbomand asserts theoption is present; existing parse tests unaffected.
SbomReportWriterTest.java: invokesSbomReportWriter.write()with a minimalMavenExecutionResult, asserts CycloneDXbomFormat, componentgroup,name,root
ref,dependsOnedge, and an emptydependsOnentry for a leaf component.mvn -pl impl/maven-cli -am -Dtest=CommonsCliMavenOptionsSbomTest,SbomReportWriterTest -Dsurefire.failIfNoSpecifiedTests=false testpasses 3/3.Backwards compatibility
--sbomis passed; no lifecycle binding, no default-buildcost, no new dependency.
Review comments
!result.hasExceptions()inMavenInvoker.protobom-jsonnot a real format: switched to CycloneDX 1.6 JSON.namedropsgroupId: components now emitgroupandnameseparately.directory.
SbomReportWriterTestadded.dependencies[], with an emptydependsOnfor leaf components.toolsarray: switched to the CycloneDX 1.6 object form,{"components": [{"type": "application", "name": "mvn"}]}.Final commit
635b898.Gaps (documented, never fabricated)
Artifact— omitted.Artifact— omitted.