gnodet-bot commented on code in PR #14093:
URL: https://github.com/apache/maven/pull/14093#discussion_r4657889926
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/MavenInvoker.java:
##########
@@ -570,6 +571,14 @@ protected int doExecute(MavenContext context,
MavenExecutionRequest request) thr
context.eventSpyDispatcher.close();
}
+ context.options().sbomFile().ifPresent(file -> {
Review 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:
```suggestion
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());
}
});
}
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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
+ *
+ * http://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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * node id/name/version and a synthesised purl, plus dependency edges and root
+ * elements. Supplier, license and hash are omitted, never fabricated. Nodes,
+ * edges and roots are sorted and the timestamp honours {@code
SOURCE_DATE_EPOCH},
+ * so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> nodes = new TreeMap<>();
+ Map<String, Set<String>> edges = new TreeMap<>();
+ Set<String> roots = new TreeSet<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ String rootPurl = purl(project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ if (rootPurl == null) {
+ continue;
+ }
+ nodes.put(rootPurl, new String[] {project.getArtifactId(),
project.getVersion(), rootPurl});
Review 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.
```suggestion
nodes.put(rootPurl, new String[] {project.getGroupId() + ":" +
project.getArtifactId(), project.getVersion(), rootPurl});
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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
+ *
+ * http://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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * node id/name/version and a synthesised purl, plus dependency edges and root
+ * elements. Supplier, license and hash are omitted, never fabricated. Nodes,
+ * edges and roots are sorted and the timestamp honours {@code
SOURCE_DATE_EPOCH},
+ * so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> nodes = new TreeMap<>();
+ Map<String, Set<String>> edges = new TreeMap<>();
+ Set<String> roots = new TreeSet<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ String rootPurl = purl(project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ if (rootPurl == null) {
+ continue;
+ }
+ nodes.put(rootPurl, new String[] {project.getArtifactId(),
project.getVersion(), rootPurl});
+ roots.add(rootPurl);
+ for (Artifact artifact : project.getArtifacts()) {
+ String depPurl = purl(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ if (depPurl == null || depPurl.equals(rootPurl)) {
+ continue;
+ }
+ nodes.put(depPurl, new String[] {artifact.getArtifactId(),
artifact.getVersion(), depPurl});
+ edges.computeIfAbsent(rootPurl, k -> new
TreeSet<>()).add(depPurl);
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
Review 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.
##########
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/CommonsCliMavenOptionsSbomTest.java:
##########
@@ -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
+ *
+ * http://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.maven.cling.invoker.mvn;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Guards the {@code --sbom} option: it takes no argument, so a following goal
must
+ * not be swallowed as its value.
+ */
+class CommonsCliMavenOptionsSbomTest {
+
+ @Test
+ void testSbomFlagDoesNotSwallowFollowingGoal() throws Exception {
+ CommonsCliMavenOptions options = CommonsCliMavenOptions.parse("test",
new String[] {"--sbom", "package"});
+
+ assertTrue(options.sbomFile().isPresent(), "sbomFile must be present");
+ assertEquals("sbom.json", options.sbomFile().get());
+ assertEquals(java.util.List.of("package"),
options.goals().orElseThrow(), "goal must survive");
+ }
+
+ @Test
+ void testSbomAbsentByDefault() throws Exception {
+ CommonsCliMavenOptions options = CommonsCliMavenOptions.parse("test",
new String[] {"package"});
+
+ assertTrue(options.sbomFile().isEmpty(), "sbomFile must be empty
without the flag");
+ }
+}
Review 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.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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
+ *
+ * http://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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * node id/name/version and a synthesised purl, plus dependency edges and root
+ * elements. Supplier, license and hash are omitted, never fabricated. Nodes,
+ * edges and roots are sorted and the timestamp honours {@code
SOURCE_DATE_EPOCH},
+ * so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> nodes = new TreeMap<>();
+ Map<String, Set<String>> edges = new TreeMap<>();
+ Set<String> roots = new TreeSet<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ String rootPurl = purl(project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ if (rootPurl == null) {
+ continue;
+ }
+ nodes.put(rootPurl, new String[] {project.getArtifactId(),
project.getVersion(), rootPurl});
+ roots.add(rootPurl);
+ for (Artifact artifact : project.getArtifacts()) {
+ String depPurl = purl(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ if (depPurl == null || depPurl.equals(rootPurl)) {
+ continue;
+ }
+ nodes.put(depPurl, new String[] {artifact.getArtifactId(),
artifact.getVersion(), depPurl});
Review Comment:
Same issue: `c[0]` is `artifactId` only — use `artifact.getGroupId() + ":" +
artifact.getArtifactId()`.
```suggestion
nodes.put(depPurl, new String[] {artifact.getGroupId() + ":"
+ artifact.getArtifactId(), artifact.getVersion(), depPurl});
```
##########
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/mvn/MavenOptions.java:
##########
@@ -253,4 +253,17 @@ public interface MavenOptions extends Options {
*/
@Nonnull
Optional<Boolean> listAliases();
+
+ /**
+ * Indicates that an SBOM report should be written after the build
completes.
+ * The report is written to {@code sbom.json} in the top-level project
directory.
+ * The report lists the resolved dependencies of every built project as
protobom-style
+ * 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
Review 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`
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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
+ *
+ * http://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.maven.cling.invoker.mvn;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Writes an SBOM report in a protobom-style JSON document from the resolved
+ * artifacts of the build. Hand-rolled encoder: maven-cli has no JSON library
+ * dependency, and adding one for a single report is not justified.
+ *
+ * <p>Only fields Maven actually retains in the resolved artifact set are
emitted:
+ * node id/name/version and a synthesised purl, plus dependency edges and root
+ * elements. Supplier, license and hash are omitted, never fabricated. Nodes,
+ * edges and roots are sorted and the timestamp honours {@code
SOURCE_DATE_EPOCH},
+ * so the output is deterministic.</p>
+ */
+final class SbomReportWriter {
+ private SbomReportWriter() {}
+
+ static void write(Path file, MavenExecutionResult result) throws
IOException {
+ Map<String, String[]> nodes = new TreeMap<>();
+ Map<String, Set<String>> edges = new TreeMap<>();
+ Set<String> roots = new TreeSet<>();
+ for (MavenProject project : result.getTopologicallySortedProjects()) {
+ String rootPurl = purl(project.getGroupId(),
project.getArtifactId(), project.getVersion());
+ if (rootPurl == null) {
+ continue;
+ }
+ nodes.put(rootPurl, new String[] {project.getArtifactId(),
project.getVersion(), rootPurl});
+ roots.add(rootPurl);
+ for (Artifact artifact : project.getArtifacts()) {
+ String depPurl = purl(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion());
+ if (depPurl == null || depPurl.equals(rootPurl)) {
+ continue;
+ }
+ nodes.put(depPurl, new String[] {artifact.getArtifactId(),
artifact.getVersion(), depPurl});
+ edges.computeIfAbsent(rootPurl, k -> new
TreeSet<>()).add(depPurl);
+ }
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"sbomFormat\": \"protobom-json\",\n");
+ sb.append(" \"metadata\": {\n");
+ sb.append(" \"authors\": [\"Apache Maven\"],\n");
+ sb.append(" \"tools\": [\"mvn\"],\n");
+ sb.append(" \"date\": \"").append(timestamp()).append("\"\n");
+ sb.append(" },\n");
+ sb.append(" \"nodeList\": {\n");
+ sb.append(" \"nodes\": [\n");
+ int i = 0;
+ for (String[] c : nodes.values()) {
+ sb.append(" {\"id\": \"").append(escape(c[2]))
+ .append("\", \"name\": \"").append(escape(c[0]))
+ .append("\", \"version\":
\"").append(escape(c[1])).append("\"}");
+ sb.append(++i < nodes.size() ? ",\n" : "\n");
+ }
+ sb.append(" ],\n");
+ sb.append(" \"edges\": [\n");
+ int e = 0;
+ for (Map.Entry<String, Set<String>> edge : edges.entrySet()) {
+ sb.append(" {\"type\": \"dependsOn\", \"from\":
\"").append(escape(edge.getKey())).append("\", \"to\": [");
+ int t = 0;
+ for (String to : edge.getValue()) {
+ sb.append(t++ > 0 ? ", " :
"").append("\"").append(escape(to)).append("\"");
+ }
+ sb.append("]}");
+ sb.append(++e < edges.size() ? ",\n" : "\n");
+ }
+ sb.append(" ],\n");
+ sb.append(" \"rootElements\": [\n");
+ int r = 0;
+ for (String root : roots) {
+ sb.append(" \"").append(escape(root)).append("\"");
+ sb.append(++r < roots.size() ? ",\n" : "\n");
+ }
+ sb.append(" ]\n");
+ sb.append(" }\n");
+ sb.append("}\n");
+ Files.writeString(file, sb.toString(), StandardCharsets.UTF_8);
+ }
+
+ private static String purl(String groupId, String artifactId, String
version) {
+ if (groupId == null || artifactId == null || version == null) {
+ return null;
+ }
+ return "pkg:maven/" + groupId + "/" + artifactId + "@" + version;
+ }
+
+ private static String timestamp() {
+ String epoch = System.getenv("SOURCE_DATE_EPOCH");
+ if (epoch != null && !epoch.isBlank()) {
+ try {
+ return Instant.ofEpochSecond(Long.parseLong(epoch)).toString();
+ } catch (NumberFormatException e) {
+ // Invalid SOURCE_DATE_EPOCH: fall back to current time.
+ }
+ }
+ return Instant.now().toString();
+ }
+
+ private static String escape(String value) {
+ return value.replace("\\", "\\\\").replace("\"", "\\\"");
Review 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")`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]