Skip to content

Commit

Permalink
Setup elasticsearch dependency monitoring with Snyk for production co…
Browse files Browse the repository at this point in the history
…de (elastic#88036)

This adds the generation and upload logic of Gradle dependency graphs to snyk

We directly implemented a rest api based snyk plugin as:

the existing snyk gradle plugin delegates to the snyk command line tool the command line tool
uses custom gradle logic by injecting a init file that is

a) using deprecated build logic which we definitely want to avoid
b) uses gradle api we avoid like eager task creation.

Shipping this as a internal gradle plugin gives us the most flexibility as we only want to monitor
production code for now we apply this plugin as part of the elasticsearch.build plugin,
that usage has been for now the de-facto indicator if a project is considered a "production" project
that ends up in our distribution or public maven repositories. This isnt yet ideal and we will revisit
the distinction between production and non production code / projects in a separate effort.

As part of this effort we added the elasticsearch.build plugin to more projects that actually end up
in the distribution. To unblock us on this we for now disabled a few check tasks that started failing by applying elasticsearch.build.

Addresses  elastic#87620
# Conflicts:
#	build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BuildPlugin.java
#	client/benchmark/build.gradle
#	client/test/build.gradle
#	distribution/tools/cli-launcher/build.gradle
#	distribution/tools/java-version-checker/build.gradle
#	distribution/tools/windows-service-cli/build.gradle
#	rest-api-spec/build.gradle
#	test/framework/build.gradle
  • Loading branch information
breskeby committed Jun 30, 2022
1 parent aee549b commit a66239a
Show file tree
Hide file tree
Showing 21 changed files with 933 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ private static String readFirstLine(final Path path) throws IOException {

/** Find the reponame. */
public String urlFromOrigin() {
String oritin = getOrigin();
if (origin == null) {
return null; // best effort, the url doesnt really matter, it is just required by maven central
}
Expand Down
3 changes: 3 additions & 0 deletions build-tools-internal/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ dependencies {
// for our ide tweaking
api buildLibs.idea.ext
// When upgrading forbidden apis, ensure dependency version is bumped in ThirdPartyPrecommitPlugin as well
api buildLibs.httpclient
api buildLibs.httpcore
api buildLibs.forbiddenApis
api buildLibs.docker.compose
api buildLibs.maven.model
Expand Down Expand Up @@ -283,6 +285,7 @@ dependencies {
exclude module: "groovy"
}
testImplementation buildLibs.spock.junit4
testImplementation buildLibs.json.assert
integTestImplementation buildLibs.xmlunit.core
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

package org.elasticsearch.gradle.internal.snyk

import org.elasticsearch.gradle.fixtures.AbstractGradleInternalPluginFuncTest
import org.gradle.api.Plugin
import org.gradle.testkit.runner.TaskOutcome
import org.skyscreamer.jsonassert.JSONAssert

import static java.net.HttpURLConnection.HTTP_CREATED
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR
import static org.elasticsearch.gradle.fixtures.WiremockFixture.PUT
import static org.elasticsearch.gradle.fixtures.WiremockFixture.withWireMock
import static org.elasticsearch.gradle.internal.snyk.UploadSnykDependenciesGraph.GRADLE_GRAPH_ENDPOINT

class SnykDependencyMonitoringGradlePluginFuncTest extends AbstractGradleInternalPluginFuncTest {

Class<? extends Plugin> pluginClassUnderTest = SnykDependencyMonitoringGradlePlugin.class

def setup() {
configurationCacheCompatible = false // configuration is not cc compliant
}

def "can calculate snyk dependency graph"() {
given:
buildFile << """
apply plugin:'java'
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation 'org.apache.lucene:lucene-monitor:9.2.0'
}
"""
when:
def build = gradleRunner("generateSnykDependencyGraph").build()
then:
build.task(":generateSnykDependencyGraph").outcome == TaskOutcome.SUCCESS
JSONAssert.assertEquals(file( "build/snyk/dependencies.json").text, """{
"meta": {
"method": "custom gradle",
"id": "gradle",
"node": "v16.15.1",
"name": "gradle",
"plugin": "extern:gradle",
"pluginRuntime": "unknown",
"monitorGraph": true
},
"depGraphJSON": {
"pkgManager": {
"version": "7.4.2",
"name": "gradle"
},
"schemaVersion": "1.2.0",
"graph": {
"rootNodeId": "root-node",
"nodes": [
{
"nodeId": "root-node",
"deps": [
{
"nodeId": "org.apache.lucene:[email protected]"
}
],
"pkgId": "[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]",
"deps": [
{
"nodeId": "org.apache.lucene:[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]"
}
],
"pkgId": "org.apache.lucene:[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]",
"deps": [
{
"nodeId": "org.apache.lucene:[email protected]"
}
],
"pkgId": "org.apache.lucene:[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]",
"deps": [
],
"pkgId": "org.apache.lucene:[email protected]"
},
{
"nodeId": "org.apache.lucene:[email protected]",
"deps": [
{
"nodeId": "org.apache.lucene:[email protected]"
}
],
"pkgId": "org.apache.lucene:[email protected]"
}
]
},
"pkgs": [
{
"id": "[email protected]",
"info": {
"name": "hello-world",
"version": "1.0-SNAPSHOT"
}
},
{
"id": "org.apache.lucene:[email protected]",
"info": {
"name": "org.apache.lucene:lucene-monitor",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:[email protected]",
"info": {
"name": "org.apache.lucene:lucene-memory",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:[email protected]",
"info": {
"name": "org.apache.lucene:lucene-core",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:[email protected]",
"info": {
"name": "org.apache.lucene:lucene-analysis-common",
"version": "9.2.0"
}
}
]
},
"target": {
"remoteUrl": "http://github.com/elastic/elasticsearch.git",
"branch": "unknown"
}
}""", true)
}

def "upload fails with reasonable error message"() {
given:
buildFile << """
apply plugin:'java'
"""
when:
def result = withWireMock(PUT, "/api/v1/monitor/gradle/graph", "OK", HTTP_CREATED) { server ->
buildFile << """
tasks.named('uploadSnykDependencyGraph').configure {
getUrl().set('${server.baseUrl()}/api/v1/monitor/gradle/graph')
getToken().set("myToken")
}
"""
gradleRunner("uploadSnykDependencyGraph", '-i', '--stacktrace').build()
}
then:
result.task(":uploadSnykDependencyGraph").outcome == TaskOutcome.SUCCESS
result.output.contains("Snyk API call response status: 201")

when:
result = withWireMock(PUT, GRADLE_GRAPH_ENDPOINT, "Internal Error", HTTP_INTERNAL_ERROR) { server ->
buildFile << """
tasks.named('uploadSnykDependencyGraph').configure {
getUrl().set('${server.baseUrl()}/api/v1/monitor/gradle/graph')
}
"""
gradleRunner("uploadSnykDependencyGraph", '-i').buildAndFail()
}

then:
result.task(":uploadSnykDependencyGraph").outcome == TaskOutcome.FAILED
result.output.contains("Uploading Snyk Graph failed with http code 500: Internal Error")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import org.elasticsearch.gradle.internal.info.GlobalBuildInfoPlugin;
import org.elasticsearch.gradle.internal.precommit.InternalPrecommitTasks;
import org.elasticsearch.gradle.internal.snyk.SnykDependencyMonitoringGradlePlugin;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
Expand Down Expand Up @@ -59,6 +60,7 @@ public void apply(final Project project) {
project.getPluginManager().apply("elasticsearch.publish");
project.getPluginManager().apply(ElasticsearchJavadocPlugin.class);
project.getPluginManager().apply(DependenciesInfoPlugin.class);
project.getPluginManager().apply(SnykDependencyMonitoringGradlePlugin.class);
InternalPrecommitTasks.create(project, true);
configureLicenseAndNotice(project);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

package org.elasticsearch.gradle.internal.snyk;

import groovy.json.JsonOutput;

import org.elasticsearch.gradle.internal.info.BuildParams;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ResolvedDependency;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.initialization.layout.BuildLayout;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

public class GenerateSnykDependencyGraph extends DefaultTask {

private static final Map<String, Object> FIXED_META_DATA = Map.of(
"method",
"custom gradle",
"id",
"gradle",
"node",
"v16.15.1",
"name",
"gradle",
"plugin",
"extern:gradle",
"pluginRuntime",
"unknown",
"monitorGraph",
true
);
private final Property<Configuration> configuration;
private final Property<String> projectName;
private final Property<String> projectPath;
private final Property<String> version;
private final Property<String> gradleVersion;
private final RegularFileProperty outputFile;
private final BuildLayout buildLayout;

@Inject
public GenerateSnykDependencyGraph(ObjectFactory objectFactory, BuildLayout buildLayout) {
configuration = objectFactory.property(Configuration.class);
projectName = objectFactory.property(String.class);
projectPath = objectFactory.property(String.class);
version = objectFactory.property(String.class);
gradleVersion = objectFactory.property(String.class);
outputFile = objectFactory.fileProperty();
this.buildLayout = buildLayout;
}

@TaskAction
void resolveGraph() {
Map<String, Object> payload = generateGradleGraphPayload();
String jsonOutput = JsonOutput.prettyPrint(JsonOutput.toJson(payload));
try {
Files.writeString(
getOutputFile().getAsFile().get().toPath(),
jsonOutput,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING
);
} catch (IOException e) {
throw new GradleException("Cannot generate dependencies json file", e);
}
}

private Map<String, Object> generateGradleGraphPayload() {
Set<ResolvedDependency> firstLevelModuleDependencies = configuration.get()
.getResolvedConfiguration()
.getFirstLevelModuleDependencies();
SnykDependencyGraphBuilder builder = new SnykDependencyGraphBuilder(gradleVersion.get());
String effectiveProjectPath = projectPath.get();
builder.walkGraph(
(effectiveProjectPath.equals(":") ? projectName.get() : effectiveProjectPath),
version.get(),
firstLevelModuleDependencies
);
return Map.of("meta", FIXED_META_DATA, "depGraphJSON", builder.build(), "target", buildTargetData());
}

private Object buildTargetData() {
return Map.of("remoteUrl", "http://github.com/elastic/elasticsearch.git", "branch", BuildParams.getGitRevision());
}

@InputFiles
public Property<Configuration> getConfiguration() {
return configuration;
}

@OutputFile
public RegularFileProperty getOutputFile() {
return outputFile;
}

@Input
public Property<String> getProjectPath() {
return projectPath;
}

@Input
public Property<String> getVersion() {
return version;
}

@Input
public Property<String> getProjectName() {
return projectName;
}

@Input
public Property<String> getGradleVersion() {
return gradleVersion;
}

}
Loading

0 comments on commit a66239a

Please sign in to comment.