Skip to content

Add opt-in SBOM generation (--sbom) - #14093

Open
dineshr93 wants to merge 4 commits into
apache:masterfrom
dineshr93:sbom-support
Open

dineshr93 wants to merge 4 commits into
apache:masterfrom
dineshr93:sbom-support

Conversation

@dineshr93

@dineshr93 dineshr93 commented Nov 22, 2026 •

Copy link
Copy Markdown

PR: maven

PR: #14093 (open)

Title: Add opt-in SBOM generation (--sbom)

Branch: sbom-support, commits 280635bc, fc81e18, 2b36806 and 635b898, 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 --sbom writes it out so
no external plugin or scanner is needed.

Design

  • A flag on the existing mvn invoker, not a new invoker: sbomFile() on
    MavenOptions, the Option on the mvn-specific CommonsCliMavenOptions
    CLIManager (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 completes
    in MavenInvoker, only when !result.hasExceptions(), walks
    MavenExecutionResult.getTopologicallySortedProjects() and emits each project
    and resolved artifact as a CycloneDX component with a dependency edge — zero
    new resolution, ProjectArtifactsCache already holds the set.
  • Flag is no-arg; output path fixed to <topDirectory>/sbom.json.
  • Format: CycloneDX 1.6 JSON via a hand-rolled encoder: bomFormat,
    specVersion, version, metadata, sorted components with group, name,
    version, purl, and sorted dependencies with ref / dependsOn.
    maven-core has zero protobuf or JSON dependency; adding one for a report is the
    change most likely to be rejected.
  • SOURCE_DATE_EPOCH is honoured; an invalid value falls back to the current
    timestamp instead of throwing.

Alternatives considered

  • A real sbom goal: belongs in the separate maven-plugins repo (core binds
    only external plugins, JarLifecycleMappingProvider.java:33-44); the
    invoker-flag fallback is used here per design.
  • mvnsbom invoker (mvnenc/mvnup precedent): more boilerplate for no gain,
    the data lives in the session mvn already builds.
  • Protobuf binary: ~60 extra LOC with no dependency, but JSON first to keep
    the diff minimal.

Test plan

  • CommonsCliMavenOptionsSbomTest.java: parses --sbom and asserts the
    option is present; existing parse tests unaffected.
  • SbomReportWriterTest.java: invokes SbomReportWriter.write() with a minimal
    MavenExecutionResult, asserts CycloneDX bomFormat, component group, name,
    root ref, dependsOn edge, and an empty dependsOn entry for a leaf component.
  • Local Maven 4.2.0-SNAPSHOT: mvn -pl impl/maven-cli -am -Dtest=CommonsCliMavenOptionsSbomTest,SbomReportWriterTest -Dsurefire.failIfNoSpecifiedTests=false test passes 3/3.

Backwards compatibility

  • Nothing runs unless --sbom is passed; no lifecycle binding, no default-build
    cost, no new dependency.

Review comments

  • SBOM write before exception check: guarded by !result.hasExceptions() in
    MavenInvoker.
  • protobom-json not a real format: switched to CycloneDX 1.6 JSON.
  • name drops groupId: components now emit group and name separately.
  • Incomplete JSON escaping: control characters U+0000–U+001F are escaped.
  • Javadoc said "file name": now says path relative to the top-level project
    directory.
  • No writer test: SbomReportWriterTest added.
  • Components with no dependencies: every component now has an entry in
    dependencies[], with an empty dependsOn for leaf components.
  • Deprecated tools array: switched to the CycloneDX 1.6 object form,
    {"components": [{"type": "application", "name": "mvn"}]}.
    Final commit 635b898.

Gaps (documented, never fabricated)

  • supplier: not on Artifact — omitted.
  • license: not on Artifact — omitted.
  • hash: not retained in the resolved set — omitted.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +574 to +580
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());
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ SBOM written even on failed builds. The write occurs before 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:

Suggested change
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());
}
});
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚫 "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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 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.

Suggested change
components.putIfAbsent(purl, new String[] {artifactId, version, purl});
String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version;
components.putIfAbsent(purl, new String[] {groupId + ":" + artifactId, version, purl});

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 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:

Suggested change
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();
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: invalid SOURCE_DATE_EPOCH falls back to Instant.now().

Comment on lines +91 to +93
private static String escape(String value) {
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Incomplete JSON escaping. Only \\ 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:

Suggested change
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();
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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.

Suggested change
* @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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: added SbomReportWriterTest; Docker Maven tests pass 3/3.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gnodet-bot gnodet-bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Disregard — posted in error.)


StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" \"sbomFormat\": \"protobom-json\",\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

context.eventSpyDispatcher.close();
}

context.options().sbomFile().ifPresent(file -> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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());
}
});
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: SBOM write is now gated by !result.hasExceptions().


StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" \"sbomFormat\": \"protobom-json\",\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
nodes.put(rootPurl, new String[] {project.getArtifactId(), project.getVersion(), rootPurl});
nodes.put(rootPurl, new String[] {project.getGroupId() + ":" + project.getArtifactId(), project.getVersion(), rootPurl});

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue: c[0] is artifactId only — use artifact.getGroupId() + ":" + artifact.getArtifactId().

Suggested change
nodes.put(depPurl, new String[] {artifact.getArtifactId(), artifact.getVersion(), depPurl});
nodes.put(depPurl, new String[] {artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getVersion(), depPurl});

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: dependency components also emit separate group and name.

}

private static String escape(String value) {
return value.replace("\\", "\\\\").replace("\"", "\\\"");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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").

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: Javadoc says report path relative to top-level project directory.


assertTrue(options.sbomFile().isEmpty(), "sbomFile must be empty without the flag");
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b36806: added SbomReportWriterTest; Docker Maven tests pass 3/3.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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] name drops groupId — ✅ fixed: components now emit separate "group" and "name" fields.
  • [MEDIUM] Incomplete JSON escaping — ✅ fixed: escape() now handles control characters c < 0x20.
  • [MEDIUM] No test for SbomReportWriter.write() — ✅ fixed: SbomReportWriterTest added.
  • [LOW] @return says "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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ [LOW] The 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:

Suggested change
sb.append(" \"tools\": [{\"name\": \"mvn\"}],\n");
sb.append(" \"tools\": {\"components\": [{\"type\": \"application\", \"name\": \"mvn\"}]},\n");

@hboutemy

Copy link
Copy Markdown
Member

warning: SBOM is a very diverse expectations world
= exactly where Maven's structure around plugins makes A LOT of sense

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 gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛔ 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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏗️ 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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐛 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:

  1. Drop path semantics from the Javadoc, rename return to Optional<Boolean> sbom(), or
  2. Add .hasArg() and use commandLine.getOptionValue(CLIManager.SBOM).

if (!result.hasExceptions()) {
context.options().sbomFile().ifPresent(file -> {
try {
SbomReportWriter.write(request.getTopDirectory().resolve(file), result);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Only 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:

Suggested change
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()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 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\": \"")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐛 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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ metadata.authors is deprecated in CycloneDX 1.6 in favour of metadata.manufacturer. Use:

Suggested change
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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.

Comment on lines +53 to +66
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ Prefer @TempDir over manual temp file management. If the test fails between createTempFile and Files.delete, the file leaks:

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants