Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Native Image SBOM Generation #623

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import static org.graalvm.buildtools.utils.SharedConstants.GRAALVM_EXE_EXTENSION;

public class NativeImageUtils {
public static final String ORACLE_GRAALVM_IDENTIFIER = "Oracle GraalVM";

private static final Pattern requiredVersionPattern = Pattern.compile("^([0-9]+)(?:\\.([0-9]+)?)?(?:\\.([0-9]+)?)?$");

Expand Down
5 changes: 5 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ groovy = "3.0.11"
jetty = "11.0.11"
plexusUtils = "4.0.0"
plexusXml = "4.0.2"
cyclonedxMaven = "2.8.1"
pluginExecutorMaven = "2.4.0"

[libraries]
# Local projects
Expand Down Expand Up @@ -61,3 +63,6 @@ jetty-server = { module = "org.eclipse.jetty:jetty-server", version.ref = "jetty
plexus-utils = { module = "org.codehaus.plexus:plexus-utils", version.ref = "plexusUtils" }

plexus-xml = { module = "org.codehaus.plexus:plexus-xml", version.ref = "plexusXml" }

cyclonedx-maven-plugin = { module = "org.cyclonedx:cyclonedx-maven-plugin", version.ref="cyclonedxMaven" }
plugin-executor-maven = { module = "org.twdata.maven:mojo-executor", version.ref="pluginExecutorMaven" }
rudsberg marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 3 additions & 0 deletions native-maven-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ dependencies {
implementation(libs.jvmReachabilityMetadata)
implementation(libs.plexus.utils)
implementation(libs.plexus.xml)
implementation(libs.cyclonedx.maven.plugin)
implementation(libs.plugin.executor.maven)

compileOnly(libs.maven.pluginApi)
compileOnly(libs.maven.core)
Expand Down Expand Up @@ -178,3 +180,4 @@ tasks.withType<Checkstyle>().configureEach {
// generated code
exclude("**/RuntimeMetadata*")
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package org.graalvm.buildtools.maven

import com.fasterxml.jackson.databind.node.ObjectNode
import org.graalvm.buildtools.maven.sbom.SBOMGenerator
import org.graalvm.buildtools.utils.NativeImageUtils
import spock.lang.Requires
import com.fasterxml.jackson.databind.ObjectMapper

class SBOMFunctionalTest extends AbstractGraalVMMavenFunctionalTest {
private static boolean EE() {
NativeCompileNoForkMojo.isOracleGraalVM(null)
}

private static boolean CE() {
!EE()
}

private static boolean jdkVersionSupportsAugmentedSBOM() {
NativeImageUtils.getMajorJDKVersion(NativeCompileNoForkMojo.getVersionInformation(null)) >= SBOMGenerator.requiredNativeImageVersion
}

private static boolean unsupportedJDKVersion() {
!jdkVersionSupportsAugmentedSBOM()
}

private static boolean supportedAugmentedSBOMVersion() {
EE() && jdkVersionSupportsAugmentedSBOM()
}

@Requires({ supportedAugmentedSBOMVersion() })
def "sbom is created when buildArg '--enable-sbom=export,embed' is used"() {
withSample 'java-application'

when:
/* The 'native-sbom' profile sets the '--enable-sbom' argument. */
mvn '-Pnative-sbom', '-DquickBuild', '-DskipTests', 'package', 'exec:exec@native'

def sbom = file("target/example-app.sbom.json")

then:
buildSucceeded
outputContainsPattern".*CycloneDX SBOM with \\d+ component\\(s\\) is embedded in binary \\(.*?\\) and exported as JSON \\(see build artifacts\\)\\."
outputDoesNotContain "Use '--enable-sbom' to assemble a Software Bill of Materials (SBOM)"
validateSbom sbom
!file(String.format("target/%s", SBOMGenerator.SBOM_FILENAME)).exists()
outputContains "Hello, native!"
}

/**
* If user sets {@link NativeCompileNoForkMojo#AUGMENTED_SBOM_PARAM_NAME} to true then an SBOM should be generated
* with default SBOM arguments even if user did not explicitly specify '--enable-sbom' as a buildArg.
*/
@Requires({ supportedAugmentedSBOMVersion() })
def "sbom is created when only the augmented sbom parameter is used (but not the '--enable-sbom' buildArg)"() {
withSample 'java-application'

when:
mvn '-Pnative-augmentedSBOM-only', '-DquickBuild', '-DskipTests', 'package', 'exec:exec@native'

def sbom = file("target/example-app.sbom.json")

then:
buildSucceeded
outputContainsPattern".*CycloneDX SBOM with \\d+ component\\(s\\) is embedded in binary \\(.*?\\)."
outputDoesNotContain "Use '--enable-sbom' to assemble a Software Bill of Materials (SBOM)"
validateSbom sbom
!file(String.format("target/%s", SBOMGenerator.SBOM_FILENAME)).exists()
outputContains "Hello, native!"
}

@Requires({ CE() })
def "error is thrown when augmented sbom parameter is used with CE"() {
withSample 'java-application'

when:
mvn '-Pnative-augmentedSBOM-only', '-DquickBuild', '-DskipTests', 'package'

then:
buildFailed
}

@Requires({ EE() && unsupportedJDKVersion() })
def "error is thrown when augmented sbom parameter is used with EE but not with an unsupported JDK version"() {
withSample 'java-application'

when:
mvn '-Pnative-augmentedSBOM-only', '-DquickBuild', '-DskipTests', 'package'

then:
buildFailed
}

/**
* Validates the SBOM produced from 'java-application'.
* @param sbom path to the SBOM.
* @return true if validation succeeded.
*/
private static boolean validateSbom(File sbom) {
try {
if (!sbom.exists()) {
println "SBOM not found: ${sbom}"
return false
}

def mapper = new ObjectMapper()
def rootNode = mapper.readTree(sbom)

// Check root fields
assert rootNode.has('bomFormat')
assert rootNode.get('bomFormat').asText() == 'CycloneDX'
assert rootNode.has('specVersion')
assert rootNode.has('serialNumber')
assert rootNode.has('version')
assert rootNode.has('metadata')
assert rootNode.has('components')
assert rootNode.has('dependencies')

// Check metadata/component
def metadataComponent = rootNode.path('metadata').path('component')
assert metadataComponent.has('group')
assert metadataComponent.get('group').asText() == 'org.graalvm.buildtools.examples'
assert metadataComponent.has('name')
assert metadataComponent.get('name').asText() == 'maven'

// Check that components and dependencies are non-empty
assert !rootNode.get('components').isEmpty()
assert !rootNode.get('dependencies').isEmpty()

// Check that the main component has no dependencies
def mainComponentId = metadataComponent.get('bom-ref').asText()
def mainComponentDependency = rootNode.get('dependencies').find { it.get('ref').asText() == mainComponentId } as ObjectNode
assert mainComponentDependency.get('dependsOn').isEmpty()

// Check that the main component is not found in "components"
assert !rootNode.get('components').any { it.get('bom-ref').asText() == mainComponentId }

return true
} catch (AssertionError | Exception e) {
println "SBOM validation failed: ${e.message}"
return false
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,44 +49,33 @@
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.logging.Logger;
import org.graalvm.buildtools.maven.config.ExcludeConfigConfiguration;
import org.graalvm.buildtools.utils.NativeImageConfigurationUtils;
import org.graalvm.buildtools.utils.NativeImageUtils;
import org.graalvm.buildtools.utils.SharedConstants;

import javax.inject.Inject;
import java.io.File;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.nio.file.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.graalvm.buildtools.utils.NativeImageUtils.ORACLE_GRAALVM_IDENTIFIER;

/**
* @author Sebastien Deleuze
*/
public abstract class AbstractNativeImageMojo extends AbstractNativeMojo {
protected static final String NATIVE_IMAGE_META_INF = "META-INF/native-image";
protected static final String NATIVE_IMAGE_PROPERTIES_FILENAME = "native-image.properties";
protected static final String NATIVE_IMAGE_DRY_RUN = "nativeDryRun";
private static String nativeImageVersionInformation = null;

@Parameter(defaultValue = "${plugin}", readonly = true) // Maven 3 only
protected PluginDescriptor plugin;
Expand Down Expand Up @@ -447,6 +436,24 @@ protected void checkRequiredVersionIfNeeded() throws MojoExecutionException {
if (requiredVersion == null) {
return;
}
NativeImageUtils.checkVersion(requiredVersion, getVersionInformation(logger));
}

static protected boolean isOracleGraalVM(Logger logger) throws MojoExecutionException {
return getVersionInformation(logger).contains(ORACLE_GRAALVM_IDENTIFIER);
}

/**
* Returns the output of calling "native-image --version".
* @param logger a logger, that may be null, to print warnings or useful information.
* @return the output as a string joined by "\n".
* @throws MojoExecutionException when any errors occurred.
*/
static protected String getVersionInformation(Logger logger) throws MojoExecutionException {
if (nativeImageVersionInformation != null) {
return nativeImageVersionInformation;
}

Path nativeImageExecutable = NativeImageConfigurationUtils.getNativeImage(logger);
try {
ProcessBuilder processBuilder = new ProcessBuilder(nativeImageExecutable.toString());
Expand All @@ -457,12 +464,11 @@ protected void checkRequiredVersionIfNeeded() throws MojoExecutionException {
throw new MojoExecutionException("Execution of " + commandString + " returned non-zero result");
}
InputStream inputStream = versionCheckProcess.getInputStream();
String versionToCheck = new BufferedReader(
nativeImageVersionInformation = new BufferedReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
NativeImageUtils.checkVersion(requiredVersion, versionToCheck);

return nativeImageVersionInformation;
} catch (IOException | InterruptedException e) {
throw new MojoExecutionException("Checking GraalVM version with " + nativeImageExecutable + " failed", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
Expand Down Expand Up @@ -122,6 +123,12 @@ public abstract class AbstractNativeMojo extends AbstractMojo {
@Component
protected MavenSession mavenSession;

@Component
protected MavenProject mavenProject;

@Component
protected BuildPluginManager pluginManager;

@Component
protected RepositorySystem repositorySystem;

Expand Down
Loading
Loading