Skip to content

Commit

Permalink
[7.17] Setup elasticsearch dependency monitoring with Snyk for produc…
Browse files Browse the repository at this point in the history
…tion code (#88036) (#88223)

Backports the following commits to 7.17:
 - Setup elasticsearch dependency monitoring with Snyk for production code (#88036)
  • Loading branch information
breskeby committed Jul 4, 2022
1 parent aee549b commit 98d1818
Show file tree
Hide file tree
Showing 24 changed files with 1,084 additions and 39 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,31 @@
/*
* 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.fixtures

import org.gradle.api.Plugin

abstract class AbstractGradleInternalPluginFuncTest extends AbstractJavaGradleFuncTest {

abstract <T extends Plugin> Class<T> getPluginClassUnderTest();

def setup() {
buildFile << """
import ${getPluginClassUnderTest().getName()}
plugins {
// bring in build-tools-internal onto the classpath
id 'elasticsearch.global-build-info'
}
// internally used plugins do not have a plugin id as they are
// not intended to be used directly from build scripts
plugins.apply(${getPluginClassUnderTest().getSimpleName()})
"""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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.fixtures

class AbstractJavaGradleFuncTest extends AbstractGradleFuncTest {

File testClazz(String testClassName) {
testClazz(testClassName, null)
}

File testClazz(String testClassName, String parent) {
testClazz(testClassName, parent, null)
}

File testClazz(String testClassName, Closure<String> content) {
testClazz(testClassName, null, content)
}

File testClazz(String testClassName, String parent, Closure<String> content) {
clazz(dir("src/test/java"), testClassName, parent, content)
}

File clazz(File sourceDir, String className, String parent = null, Closure<String> content = null) {
def classFile = new File(sourceDir, "${className.replace('.', '/')}.java")
classFile.getParentFile().mkdirs()
writeClazz(className, parent, classFile, content)
}

File clazz(String className, parent = null, Closure<String> content = null) {
def classFile = file("src/main/java/${className.replace('.', '/')}.java")
writeClazz(className, parent, classFile, content)
}

static File writeClazz(String className, String parent, File classFile, Closure<String> content) {
def packageName = className.substring(0, className.lastIndexOf('.'))
def simpleClassName = className.substring(className.lastIndexOf('.') + 1)

classFile << """
package ${packageName};
public class ${simpleClassName} ${parent == null ? "" : "extends $parent"} {
${content == null ? "" : content.call()}
}
"""
classFile
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/*
* 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 = "$version"
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:lucene-monitor@9.2.0"
}
],
"pkgId": "hello-world@$version"
},
{
"nodeId": "org.apache.lucene:lucene-monitor@9.2.0",
"deps": [
{
"nodeId": "org.apache.lucene:lucene-memory@9.2.0"
},
{
"nodeId": "org.apache.lucene:lucene-analysis-common@9.2.0"
},
{
"nodeId": "org.apache.lucene:lucene-core@9.2.0"
}
],
"pkgId": "org.apache.lucene:lucene-monitor@9.2.0"
},
{
"nodeId": "org.apache.lucene:lucene-memory@9.2.0",
"deps": [
{
"nodeId": "org.apache.lucene:lucene-core@9.2.0"
}
],
"pkgId": "org.apache.lucene:lucene-memory@9.2.0"
},
{
"nodeId": "org.apache.lucene:lucene-core@9.2.0",
"deps": [
],
"pkgId": "org.apache.lucene:lucene-core@9.2.0"
},
{
"nodeId": "org.apache.lucene:lucene-analysis-common@9.2.0",
"deps": [
{
"nodeId": "org.apache.lucene:lucene-core@9.2.0"
}
],
"pkgId": "org.apache.lucene:lucene-analysis-common@9.2.0"
}
]
},
"pkgs": [
{
"id": "hello-world@$version",
"info": {
"name": "hello-world",
"version": "$version"
}
},
{
"id": "org.apache.lucene:lucene-monitor@9.2.0",
"info": {
"name": "org.apache.lucene:lucene-monitor",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:lucene-memory@9.2.0",
"info": {
"name": "org.apache.lucene:lucene-memory",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:lucene-core@9.2.0",
"info": {
"name": "org.apache.lucene:lucene-core",
"version": "9.2.0"
}
},
{
"id": "org.apache.lucene:lucene-analysis-common@9.2.0",
"info": {
"name": "org.apache.lucene:lucene-analysis-common",
"version": "9.2.0"
}
}
]
},
"target": {
"remoteUrl": "http://github.com/elastic/elasticsearch.git",
"branch": "unknown"
},
"targetReference": "$version",
"projectAttributes": {
"lifecycle": [
"$expectedLifecycle"
]
}
}""", true)

where:
version | expectedLifecycle
'1.0-SNAPSHOT' | 'development'
'1.0' | 'production'
}

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

0 comments on commit 98d1818

Please sign in to comment.