Skip to main content

Sonatype Platform Plugin for Jenkins

Sonatype Platform Plugin for Jenkins (previously known as the Nexus Platform Plugin for Jenkins) integrates Jenkins with Lifecycle and Nexus Repository.

  • Perform SCA open-source evaluations during the application build

  • Push the CI analysis back to CSM pull request

  • Publish build artifacts to Repository Manager 3

Installation

Install through the Jenkins UI

  1. Download the most recent version of the Sonatype Platform Plugin

  2. Sign in to Jenkins as an administrator

  3. Navigate to the Manage Jenkins > Plugins page

  4. Click on the Advanced tab

  5. Choose the .hpi file you previously downloaded

  6. Optionally you may enter the URL to the archive file under the Deploy Plugin section

  7. Deploy the plugin

Install through the Jenkins Plugin Manager

  1. Sign in to Jenkins as an administrator

  2. Navigate to Manage Jenkins

  3. In the System Configuration section, click on Plugins

  4. In available plugins, search and install the UpdateSites Manager plugin

  5. Once installed, navigate to Manage Jenkins

  6. In the Uncategorized section, click on Manage UpdateSites

  7. Click on AddUpdate Site, and enter the required information:

    1. ID: sonatype-update-site

      Note

      'sonatype-update-site' must be used as stated. This ID is essential for system functionality and must not be altered or renamed.

    2. URL: https://download.sonatype.com/integrations/jenkins-uc/update-center.json

    3. Mark the checkbox "Need CA Certificate" and paste the following certificate:

      -----BEGIN CERTIFICATE-----
      MIIDHzCCAgegAwIBAgIJAP+lqAK85t4HMA0GCSqGSIb3DQEBCwUAMCYxCzAJBgNVBAYTAlVTMRcwFQYDVQQKDA5Tb25hdHlwZSwgSW5jLjAeFw0yNDA0MTYyMDI3MzNaFw0yNzA0MTYyMDI3MzNaMCYxCzAJBgNVBAYTAlVTMRcwFQYDVQQKDA5Tb25hdHlwZSwgSW5jLjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOSSYo277GaxCRlk9/waQ+ytNU/suCqb8SlGeAWHpleZFwvFVxxG0MU1nEI7tgKCXoyXMdbM/bXFgTzjthAOcgNQaAFDY4aUO6DPjPxMv3FTHn4FqdCfL+zEBSzmMD9R3wwblRjcnhc0c5pq+2+jopu0no0nmvEo/KczPnDfmCS90v87ACkNMcVEaIe+AYDgBGMLcY3QeouEsLnKE6FNnovzyW8h8kBRHWiolgDlA6J0KRpqOKfpdtYrA22YzhsSw7WX4Tj2rZDhHmlZ6tT3zkXHM5evXR7H9aMalF+LVhg2ShUhCIfxVpKgvLd80N39+iBOvT02/7DsB2WaYvr6TxECAwEAAaNQME4wHQYDVR0OBBYEFIzUBWpQAwcpuPr94D7k9SMTGEV2MB8GA1UdIwQYMBaAFIzUBWpQAwcpuPr94D7k9SMTGEV2MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFkrkGZ+PoZ5JGM0rin7pCk/1e2dCeeh3/uMaQQ0QYyC4jMbsYfid/V8io2AQLujOUt9TLhNvRDIaFanUBfBdw9deHTrJf4Zm45FQGbytDOgOcF4hZ58yBjJv+Fs9ARFmF3rkWjWDcnIE9eNeXv82UD+lDyTEVH88Sb6qddkOHnAMT7dwCVDpxycWYWpPmwPM7Yf6a+shshPJqveD65RyJbolk4u49owJ3hYpLwmPvDfN9sxaqRVrdKg3RnYWf+faU1bMGXQEj/0tIipHvYuDzOCTGC587zByu589SHYjEPg2i7ud1EYXkeb7nEjfsYUzum3jGx7u1MDQ5RaxPyNxyA=
      -----END CERTIFICATE-----
    4. Click Apply and Save

  8. Navigate to Manage Jenkins → Plugins page

  9. In the Plugin Manager window, select the Available plugins tab and enter "Nexus Platform" in the search box

    Note

    If the plugin does not appear after adding the new site, try clicking the refresh button at the top right corner

  10. Mark the Install checkbox to select the Nexus Platform Plugin and click the Install button at the top right corner.

    Success messages will appear as the plugin and its extensions are installed.

Install Using Alternative Methods

Sonatype Platform Plugin for Jenkins can be installed using the Jenkins CLI.

Java Version

The Sonatype Platform Plugin for Jenkins expects Java versions 8 or 11. Other versions are not supported.

HTTP Proxying

Sonatype Platform Plugin for Jenkins uses the HTTP proxy setting defined in Jenkins under Manage Jenkins > Manage Plugins > Advanced. To bypass the HTTP proxy server you must update the non-proxy host to include the IQ Server.

Configuration

Connecting Jenkins to the IQ Server

Jenkins can be configured to connect with one or more instances of IQ Server to use when evaluating your application builds. The first instance in the list is used by default.

The configured user for IQ Server must have the Evaluate Applications' permission for any applications to be evaluated. We recommend creating a Jenkins service account and using tokens to reduce the risk of exposing credentials.

  1. Sign in to Jenkins as an administrator

  2. Navigate to the Manage Jenkins > Configure System

  3. In the Sonatype section, select IQ Server from the Add IQ Server dropdown menu

    1. Display Name: The name used to select an IQ Server instance

    2. Server ID: ID to specify an IQ Server instance in pipeline builds

    3. Server URL: The location of the IQ Server

    4. Credentials: Enter the IQ Server username and password using the Jenkins Provider Credentials: Jenkins

  4. Select the credentials from the dropdown list and select 'Test Connection'

  5. The IQ report summary is embedded in Jenkins build reports. Optionally, select the 'Hide embedded reports in Jenkins' to only link to the report

  6. Select the Save button

Defining Sonatype Platform Plugin Build Steps

Pipeline refers to both Declarative and Scripted Jenkins Pipelines.

Project (or Job) refers to a Jenkins item, such as a Freestyle project, Multi-configuration project, or Maven project, that allows selecting an explicit build step from a drop-down menu and filling in form field values inside the build configuration.

The scan patterns supported by default are **/*.jar, **/*.war, **/*.ear, **/*.zip, **/*.tar.gz.

To use other patterns, a manual override of iqScanPatterns is required, as described in the pipeline build step below.

The Step user interface is identical for Jenkins Projects Build configuration and Pipeline Snippet Generator. Use the available Step names for the latest version of the plugin listed on the Sonatype Platform Plugin Steps Reference page.

Defining Steps for Pipeline

  1. In the Pipeline section of a Pipeline project configuration screen, open the Snippet Generator by clicking the Pipeline Syntax link.

  2. In the Steps section of the Snippet Generator window, select one of the Sonatype Platform Plugin-defined steps.

  3. After filling in the step field values, you can copy the generated snippet into your pipeline script.

Defining Steps for Projects

  1. In the Build section of your project configuration screen, click the Add Build Step drop-down and select a Sonatype Platform Plugin step from the list.

  2. Fill in the step field values and save your project.

Adding an Evaluation to a Build

Invoking a Lifecycle Policy Evaluation

Adding Pipeline Build Step

Jenkins pipelines allow for a Lifecycle Policy Evaluation at any point during the build. This allows for a policy gate to be set anywhere along the build and delivery process.

Use the following steps to add a Lifecycle Policy Evaluation build step to a pipeline build:

  1. In the Pipeline section of the project configuration screen, click the Pipeline Syntax link.

  2. In the Steps section of the Snippet Generator window, select the following:

    1. Sample Step: Select nexusPolicyEvaluation: Invoke Lifecycle Policy Evaluation.

    2. IQ Instance: Select an IQ Server that will be used to run the policy evaluation.

    3. Stage: Select Develop, Source, Build, Stage Release, Release, or Operate. This controls the stage the policy evaluation is run against on the IQ Server. Only the stages you are licensed to appear in the list. Depending on how your policies are configured in IQ Server, this may impact warning and fail actions.

    4. Organization (optional):Select an organization from the list.If automatic application creation is enabled and the application does not exist, it will be created under the selected organization.

      Note

      If both the application and the organization IDs are provided, and the application already exists under a different organization, the evaluation process stops with an error message. This mechanism is in place to prevent accidental configurations, which could unintentionally alter the evaluation history of existing applications.

    5. Application: Select an application from the list of available IQ Server applications. This determines the policy elements (policies, labels, and license threat groups) to associate with this build and is managed via the IQ Server. If automatic application creation is enabled, an application, that's not in the list can also be specified and an application with the specified ID will automatically be created in IQ Server.

    6. Advanced options: See the Advanced Step Options for details of each option. Use the Jenkins Pipeline Snippet Generator to help generate supported advanced options for your current plugin version.

  3. Click the Generate Pipeline Script button.

  4. Copy the generated script and paste it into the desired stage of your pipeline script.

    Example Pipeline Script

    nexusPolicyEvaluation(
                    iqApplication: 'SampApp',
                    iqInstanceId: 'MyIQServer1',
                    iqStage: 'build'
    )

    Example Pipeline Script with Scan Patterns to Override Defaults

    nexusPolicyEvaluation(
                     iqApplication: 'SampApp',
                     iqInstanceId: 'MyIQServer1',
                     iqScanPatterns: [[scanPattern: '**/*.js'], [scanPattern: '**/*.zip']],
                     iqStage: 'build',
                     iqOrganization: '55040769ec08424e84049356a3362d07'
    )

    The scan patterns support exclude patterns. The exclude patterns start with a '!' character and must be specified after all other included patterns. For example, the following scan patterns will consider for evaluation all files except those under the '.git' directory: 

    iqScanPatterns: [[scanPattern: '**'], [scanPattern: '!.git/**']]

    Example Pipeline Script Overriding Most Advanced Options

    nexusPolicyEvaluation(
                     advancedProperties: 'test=value',
                     enableDebugLogging: true,
                     failBuildOnNetworkError: true,                  
             failBuildOnScanningErrors: true, 
                     iqApplication: selectedApplication('sandbox-application'),
                     iqInstanceId: 'MyIQServer1',
                     iqModuleExcludes: [[moduleExclude: '**/module-2-exclude/module.xml'], [moduleExclude: '**/module-1-exclude/module.xml']],
                     iqScanPatterns: [[scanPattern: '**/other/*.jar'], [scanPattern: '**/special/*.jar']],
                     iqStage: 'build',
                     jobCredentialsId: 'iq-server-localhost'
    )
  5. Complete your pipeline build and click Save.

Adding Project Step

To add a Lifecycle Policy Evaluation build step to the project:

  1. In the build section of the project configuration screen, click the Add Build Step dropdown button and then select Invoke Lifecycle Policy Evaluation.

  2. IQ Instance: Select an IQ Server that will be used to run the policy evaluation.

  3. Stage: Select Develop, Source, Build, Stage Release, Release, or Operate. This controls the stage the policy evaluation is run against on the IQ Server. Only the stages enabled by your IQ Server license appear in the list.

    Note

    The severity of the IQ Server Policy Actions for a Stage determines the final build result. A Warn action equates to an UNSTABLE build. A Fail action equates to a FAILURE.

  4. Organization (optional): Select an organization from the list. If automatic application creation is enabled and the application does not exist, it will be created under the selected organization. If both the application and the organization IDs are provided, and the application already exists under a different organization, the evaluation process stops with an error message. This mechanism is in place to prevent accidental configurations, which could unintentionally alter the evaluation history of existing applications.

  5. Application: Select an application from the list of available IQ Server applications. This determines the policy elements (policies, labels, and license threat groups) to associate with this build and is managed via the IQ Server. An application can also be specified that is not on the list. If automatic application creation is enabled, an application with the specified ID will automatically be created if it does not already exist in the IQ Server.

  6. Advanced options: Click the Advanced button to view the advanced step options. Note that when using custom scan targets only one target is allowed per line.

  7. Complete the rest of your project configuration and click Save.

Reviewing the Evaluation Results

Once the build is complete, a summary is shown on the project page. The three boxes (red, orange, and yellow) located below the link give you counts for policy violations and are based on the associated severities (critical, severe, and moderate).

In addition to the summary, a historical graph is shown to indicate policy health over time.

The Application Report is accessible from the summary by clicking "view report" or "Lifecycle Policy Evaluation" in the left-hand navigation. Additionally, a Build Report is available within Jenkins by clicking the "IQ Build Report" in the left-hand nav. This build report shows which components caused a 'warn' or 'fail' action on a particular build.

126655796.png

If you are looking for previous report results, navigate to a specific build report in the Build History. Click on the link View Report to view the build report in IQ Server.

178717520.png

Advanced Options

Various advanced options allow you more details when configuring your policy evaluation.

Scan Targets: The plugin scans all files in the workspace by default. Any special non-archive files like manifests may incur special handling depending on the version of the plugin used. Each scan target field takes an Apache Ant-styled pattern (i.e. **/*.js). Supplying custom scan targets will limit scanning to only those files matching the scan targets. Only one scan target can be placed on each line.

Modules in the workspace: The Sonatype CLM for Maven has an index goal that can be used to create a module.xml file with all an application's components. By default, any module.xml file within its default directory will be scanned and evaluated for policy evaluation.

The default directories that the Jenkins plugin scans for module.xml files are **/sonatype-clm and **/nexus-iq . Any module.xml file located elsewhere in the scan targets will be ignored.

Note

If using the Sonatype for Maven plugin to index, the Maven path settings in Jenkins must be locally accessible by the IQ Plugin.The IQ plugin relies on the Maven settings defined globally in the Jenkins UI to access the files from the Maven build output to perform the evaluation.

Module excludes:

The Module Excludes feature can be used to exclude any of these module.xml files from evaluation. Module Excludes takes Apache Ant-styled patterns (i.e. **/sonatype-clm/module.xml).

Note

Module Excludes is only for excluding module.xml files generated by Sonatype CLM for Maven and is not an option for excluding scan targets.

Fail build when unable to communicate with IQ Server: Enabling this option will fail the build when the IQ Server is unreachable.

Fail build when there are scanning errors: Enabling this option will fail the build when there are scanning errors, e.g. malformed files that could not be read.

Use job-specific credentials: This allows overriding the global credential configuration with job-specific authentication credentials.

Advanced properties: In a few cases, Sonatype support may provide additional parameters to the plugin using this input.

Enable debug logging: Increase the verbosity of the plugin-specific job logging to aid in diagnosing scanning problems or verifying scanning configuration.

Evaluating Docker Images

Use the container prefix in the scan pattern to scan the docker images you want to scan.

nexusPolicyEvaluation iqApplication: 'appId', iqInstanceId: 'MyIQServer1', iqScanPatterns: [[scanPattern: 'container:namespace/image:image-tag']], iqStage: 'build'

Using the Results of a Policy Evaluation

Utilizing the Sonatype for Jenkins plugin provides full component intelligence and the ability to run policy against your application. Jenkins pipelines let you invoke a build step as part of the build process and use the results for complex workflows. For example, objects returned from a build pipeline step can be used to provide feedback in the application about the process of an evaluation.

Example: Set up a pipeline build that uses the results of a policy evaluation to push data to a GitHub pull request.

  1. Start a new Jenkins pipeline job for a Maven build.

  2. Add a build stage that calls Maven clean package, wrapped in a few GitHub status updates. For this example, consider sending an update pending when we start the build and have it update the status to indicate if the build succeeded:

stage('Build') {
  postGitHub commitId, 'pending', 'build', 'Build is running'

  try {
    sh  "${mvnHome}/bin/mvn clean package"
    postGitHub commitId, 'success', 'build', 'Build succeeded'
  } catch (error) {
    postGitHub commitId, 'failure', 'build', 'Build failed'
    throw error
  }
}

3. Add a call to the GitHub API to update the status. To do this, set and declare the gitHubApiToken and project variables and then create the following function:

def postGitHub(commitId, state, context, description, targetUrl) {
  def payload = JsonOutput.toJson(
    state: state,
    context: context,
    description: description,
    target_url: targetUrl
  )
  sh "curl -H \"Authorization: token ${gitHubApiToken}\" --request POST --data '${payload}'
  https://api.github.com/repos/${project}/statuses/${commitId} > /dev/null"
}

4. After the build, we need to run a Lifecycle Analysis to determine the policy evaluation results. This will let GitHub know Lifecycle Analysis is running and then do the policy evaluation.

The easiest way to do this is by using the Jenkins Pipeline Syntax helper to generate a Groovy script:

Click the Pipeline Syntax link on your build configuration screen to open the Pipeline Syntax helper. Select nexusPolicyEvaluation as the sample step, select the IQ instance, stage and application you’d like to evaluate against, and then click Generate Pipeline Script. Copy the script and paste it into your pipeline script.

5. To process the evaluation results, set a policyEvaluation variable to the result. Like with the build, you’ll want to look at whether the build result is a failure or not to determine how to update your GitHub pull request. You can also add a link to the Application Composition Report. Having this available in your pull request lets you go directly to the evaluation, see why it failed, and perform remediation. An example Lifecycle Analysis script is shown below:

stage('Lifecycle Analysis') {
  postGitHub commitId, 'pending', 'analysis', 'Lifecycle Analysis is running'

  try {
    def policyEvaluation = nexusPolicyEvaluation iqApplication: 'webgoat', iqInstanceId: 'MyIQServer1', iqStage: 'build'
        postGitHub commitId, 'success', 'analysis', 'Lifecycle Analysis succeeded', "${policyEvaluation.applicationCompositionReportUrl}"
  } catch (error) {
    def policyEvaluation = error.policyEvaluation
    postGitHub commitId, 'failure', 'analysis', 'Lifecycle Analysis failed', "${policyEvaluation.applicationCompositionReportUrl}"
    throw error
  }
}

6. Save your pipeline and then run the build. When the build has been completed, you should see successful steps for Build and Lifecycle Analysis. In your GitHub pull request, you will see the successful checks and you can click the details link to view your report and address alerts or reevaluate policy.

Note

When you access various properties on objects in a pipeline build, Jenkins has security permissions that restrict unauthorized use. In Manage Jenkins navigate to In-process Script Approval and approve scripts (ie application composition report, affected component count) for the analysis to run. Lack of script approvals will result in errors like:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to
use method com.sonatype.nexus.api.iq.ApplicationPolicyEvaluation getApplicationCompositionReportUrl

In the above example, we utilized cURL to interact with the GitHub API and provide analysis feedback to GitHub. Many companies use GitHub for code review, and noting the status of CI builds in your pull request is a powerful analysis tool.

In addition to GitHub, you can use the object returned from the policy evaluation with almost anything that provides an interactive API or other Jenkins plugins.

A nexusPolicyEvaluation Pipeline step returns an evaluation result data model from which your Pipeline script may read additional information:

Pipeline application policy evaluation data model

public class ApplicationPolicyEvaluation {
        private final List<PolicyAlert> policyAlerts;
        private final int affectedComponentCount;
        private final int criticalComponentCount;
        private final int severeComponentCount;
        private final int moderateComponentCount;
        private final String applicationCompositionReportUrl;
}

public class PolicyAlert {
        private final PolicyFact trigger;
        private final List<? extends Action> actions;
}

public class Action {
        private final String actionTypeId;
        private final String target;
        private final String targetType;
}

public class PolicyFacts {
        private final String policyId;
        private final String policyName;
        private final int threatLevel;
}

Pipeline stage status returned by the plugin for Jenkins

When an evaluation is performed by the plugin, the stage status depends on the configured policy actions.

  • Jenkins shows unstable for the build when the policy action is set to WARN

  • Jenkins shows failed for the build when the policy action is set to FAIL

  • When the policy action is set to No Action, discovered policy violations will have no effect on the Jenkins build state.

Use the variable currentBuild.result to examine the value returned within the pipeline script.

def evaluation = nexusPolicyEvaluation failBuildOnNetworkError: false, iqApplication: '18776', iqStage: 'build'
echo "currentBuild.result ${currentBuild.result}"