gnodet-bot commented on code in PR #14093: URL: https://github.com/apache/maven/pull/14093#discussion_r4657439495
########## impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java: ########## @@ -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 + * + * 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.time.ZoneOffset; +import java.util.Map; +import java.util.TreeMap; + +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: + * component name, version and a synthesised purl. Supplier, license and hash are + * omitted, never fabricated. Components are sorted by purl 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[]> components = new TreeMap<>(); + for (MavenProject project : result.getTopologicallySortedProjects()) { + addComponent(components, project.getGroupId(), project.getArtifactId(), project.getVersion()); + for (Artifact artifact : project.getArtifacts()) { + addComponent(components, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + } + } + + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" \"sbomFormat\": \"protobom-json\",\n"); Review Comment: 🚫 **`"protobom-json"` is not a real SBOM format.** Protobom is a protocol-buffers schema (see [protobom/protobom](https://github.com/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. ########## impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java: ########## @@ -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 + * + * 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.time.ZoneOffset; +import java.util.Map; +import java.util.TreeMap; + +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: + * component name, version and a synthesised purl. Supplier, license and hash are + * omitted, never fabricated. Components are sorted by purl 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[]> components = new TreeMap<>(); + for (MavenProject project : result.getTopologicallySortedProjects()) { + addComponent(components, project.getGroupId(), project.getArtifactId(), project.getVersion()); + for (Artifact artifact : project.getArtifacts()) { + addComponent(components, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + } + } + + 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(" \"components\": [\n"); + int i = 0; + for (String[] c : components.values()) { + sb.append(" {\"name\": \"").append(escape(c[0])) + .append("\", \"version\": \"").append(escape(c[1])) + .append("\", \"purl\": \"").append(escape(c[2])).append("\"}"); + sb.append(++i < components.size() ? ",\n" : "\n"); + } + sb.append(" ]\n"); + sb.append("}\n"); + Files.writeString(file, sb.toString(), StandardCharsets.UTF_8); + } + + private static void addComponent(Map<String, String[]> components, String groupId, String artifactId, String version) { + if (groupId == null || artifactId == null || version == null) { + return; + } + String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; + components.putIfAbsent(purl, new String[] {artifactId, version, purl}); Review 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`. ```suggestion String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; components.putIfAbsent(purl, new String[] {groupId + ":" + artifactId, version, purl}); ``` ########## impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/SbomReportWriter.java: ########## @@ -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 + * + * 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.time.ZoneOffset; +import java.util.Map; +import java.util.TreeMap; + +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: + * component name, version and a synthesised purl. Supplier, license and hash are + * omitted, never fabricated. Components are sorted by purl 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[]> components = new TreeMap<>(); + for (MavenProject project : result.getTopologicallySortedProjects()) { + addComponent(components, project.getGroupId(), project.getArtifactId(), project.getVersion()); + for (Artifact artifact : project.getArtifacts()) { + addComponent(components, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + } + } + + 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(" \"components\": [\n"); + int i = 0; + for (String[] c : components.values()) { + sb.append(" {\"name\": \"").append(escape(c[0])) + .append("\", \"version\": \"").append(escape(c[1])) + .append("\", \"purl\": \"").append(escape(c[2])).append("\"}"); + sb.append(++i < components.size() ? ",\n" : "\n"); + } + sb.append(" ]\n"); + sb.append("}\n"); + Files.writeString(file, sb.toString(), StandardCharsets.UTF_8); + } + + private static void addComponent(Map<String, String[]> components, String groupId, String artifactId, String version) { + if (groupId == null || artifactId == null || version == null) { + return; + } + String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; + components.putIfAbsent(purl, new String[] {artifactId, version, purl}); + } + + private static String timestamp() { + String epoch = System.getenv("SOURCE_DATE_EPOCH"); + Instant instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); Review 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: ```suggestion Instant instant; try { instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); } catch (NumberFormatException e) { instant = Instant.now(); } ``` ########## 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: 💡 **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. ########## 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: 💡 **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`. ```suggestion * @return an {@link Optional} containing the SBOM output path relative to the top-level * project directory, or empty if {@code --sbom} was not passed ``` ########## 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 -> { + try { + SbomReportWriter.write(request.getTopDirectory().resolve(file), result); + } catch (IOException e) { + context.logger.warn("Failed to write SBOM report: " + e.getMessage()); + } + }); Review Comment: ⚠️ **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: ```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,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 + * + * 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.time.ZoneOffset; +import java.util.Map; +import java.util.TreeMap; + +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: + * component name, version and a synthesised purl. Supplier, license and hash are + * omitted, never fabricated. Components are sorted by purl 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[]> components = new TreeMap<>(); + for (MavenProject project : result.getTopologicallySortedProjects()) { + addComponent(components, project.getGroupId(), project.getArtifactId(), project.getVersion()); + for (Artifact artifact : project.getArtifacts()) { + addComponent(components, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + } + } + + 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(" \"components\": [\n"); + int i = 0; + for (String[] c : components.values()) { + sb.append(" {\"name\": \"").append(escape(c[0])) + .append("\", \"version\": \"").append(escape(c[1])) + .append("\", \"purl\": \"").append(escape(c[2])).append("\"}"); + sb.append(++i < components.size() ? ",\n" : "\n"); + } + sb.append(" ]\n"); + sb.append("}\n"); + Files.writeString(file, sb.toString(), StandardCharsets.UTF_8); + } + + private static void addComponent(Map<String, String[]> components, String groupId, String artifactId, String version) { + if (groupId == null || artifactId == null || version == null) { + return; + } + String purl = "pkg:maven/" + groupId + "/" + artifactId + "@" + version; + components.putIfAbsent(purl, new String[] {artifactId, version, purl}); + } + + private static String timestamp() { + String epoch = System.getenv("SOURCE_DATE_EPOCH"); + Instant instant = epoch != null ? Instant.ofEpochSecond(Long.parseLong(epoch)) : Instant.now(); + return instant.atOffset(ZoneOffset.UTC).toInstant().toString(); + } + + private static String escape(String value) { + return value.replace("\\", "\\\\").replace("\"", "\\\""); + } Review Comment: ⚠️ **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: ```suggestion 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(); } ``` -- 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]
