Skip to content

Commit 0b1e3a9

Browse files
JAVA-3738 fixed manual tests and sdk connections
1 parent 30a76df commit 0b1e3a9

File tree

8 files changed

+261
-84
lines changed

8 files changed

+261
-84
lines changed

gradle-plugin/build.gradle

+13
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ plugins {
22
id 'java'
33
id 'java-gradle-plugin'
44
id 'com.diffplug.spotless' version("6.10.0")
5+
id 'maven-publish'
56
}
67

78
version = '0.1'
@@ -53,6 +54,18 @@ dependencies {
5354
testImplementation 'org.junit.jupiter:junit-jupiter'
5455
}
5556

57+
var e2eTests = "com/contrastsecurity/gradle.plugin/e2e/EndToEndTests.*"
58+
59+
5660
test {
61+
if(!project.hasProperty("e2e")){
62+
exclude(e2eTests)
63+
}
64+
5765
useJUnitPlatform()
66+
environment = ["CONTRAST__API__USER_NAME" : System.getenv("CONTRAST__API__USER_NAME"),
67+
"CONTRAST__API__URL" : System.getenv("CONTRAST__API__URL"),
68+
"CONTRAST__API__SERVICE_KEY" : System.getenv("CONTRAST__API__SERVICE_KEY"),
69+
"CONTRAST__API__API_KEY" : System.getenv("CONTRAST__API__API_KEY"),
70+
"CONTRAST__API__ORGANIZATION_ID": System.getenv("CONTRAST__API__ORGANIZATION_ID")]
5871
}

gradle-plugin/src/main/java/com/contrastsecurity/gradle/plugin/ContrastConfigurationExtension.java

+44-34
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,57 @@
22

33
/** Extension for configuring TeamServer API Credentials for downloading agent */
44
public class ContrastConfigurationExtension {
5-
final String username;
6-
final String apiKey;
7-
final String serviceKey;
8-
final String apiUrl;
9-
final String orgUuid;
10-
final String appName;
11-
final String serverName;
12-
final String jarPath;
13-
final String appVersion;
14-
15-
// default constructor with null values
16-
// this is shit figure out what gradle wants
17-
public ContrastConfigurationExtension() {
18-
this.username = null;
19-
this.apiKey = null;
20-
this.serviceKey = null;
21-
this.apiUrl = null;
22-
this.orgUuid = null;
23-
this.appName = null;
24-
this.serverName = null;
25-
this.jarPath = null;
26-
this.appVersion = null;
27-
}
28-
29-
public ContrastConfigurationExtension(
30-
final String username,
31-
final String apiKey,
32-
final String serviceKey,
33-
final String apiUrl,
34-
final String orgUuid,
35-
final String appName,
36-
final String serverName,
37-
final String jarPath,
38-
final String appVersion) {
5+
private String username;
6+
private String apiKey;
7+
private String serviceKey;
8+
private String apiUrl;
9+
private String orgUuid;
10+
private String appName;
11+
private String serverName;
12+
private String jarPath;
13+
private String appVersion;
14+
private boolean attachToTests;
15+
16+
public void setUsername(final String username) {
3917
this.username = username;
18+
}
19+
20+
public void setApiKey(final String apiKey) {
4021
this.apiKey = apiKey;
22+
}
23+
24+
public void setServiceKey(final String serviceKey) {
4125
this.serviceKey = serviceKey;
26+
}
27+
28+
public void setApiUrl(final String apiUrl) {
4229
this.apiUrl = apiUrl;
30+
}
31+
32+
public void setOrgUuid(final String orgUuid) {
4333
this.orgUuid = orgUuid;
34+
}
35+
36+
public void setAppName(final String appName) {
4437
this.appName = appName;
38+
}
39+
40+
public void setServerName(final String serverName) {
4541
this.serverName = serverName;
42+
}
43+
44+
public void setJarPath(final String jarPath) {
4645
this.jarPath = jarPath;
46+
}
47+
48+
public void setAppVersion(final String appVersion) {
4749
this.appVersion = appVersion;
4850
}
4951

52+
public void setAttachToTests(final boolean attachToTests) {
53+
this.attachToTests = attachToTests;
54+
}
55+
5056
public String getUsername() {
5157
return username;
5258
}
@@ -82,4 +88,8 @@ public String getJarPath() {
8288
public String getAppVersion() {
8389
return appVersion;
8490
}
91+
92+
public boolean getAttachToTests() {
93+
return attachToTests;
94+
}
8595
}

gradle-plugin/src/main/java/com/contrastsecurity/gradle/plugin/ContrastGradlePlugin.java

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import org.gradle.api.Plugin;
44
import org.gradle.api.Project;
5+
import org.gradle.api.tasks.testing.Test;
56

67
/**
78
* Gradle plugin for contrast utilities. The goals for this plugin are defined here <a
@@ -18,7 +19,17 @@ public void apply(final Project target) {
1819
.getTasks()
1920
.register("hello", task -> task.doLast(s -> System.out.println("HelloWorld!")));
2021

21-
target.getTasks().register("empty", EmptyTask.class);
22+
target
23+
.getTasks()
24+
.register("testWithContrast")
25+
.configure(
26+
task -> {
27+
target
28+
.getTasks()
29+
.withType(Test.class)
30+
.configureEach(s -> s.dependsOn("installAgent"));
31+
task.doFirst(s -> target.getTasks().withType(Test.class));
32+
});
2233

2334
target.getTasks().register("installAgent", InstallAgentTask.class);
2435
}

gradle-plugin/src/main/java/com/contrastsecurity/gradle/plugin/InstallAgentTask.java

+74-28
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,21 @@
77
import com.contrastsecurity.sdk.ContrastSDK;
88
import com.contrastsecurity.sdk.UserAgentProduct;
99
import java.io.IOException;
10+
import java.nio.file.FileAlreadyExistsException;
1011
import java.nio.file.Files;
1112
import java.nio.file.Path;
1213
import java.nio.file.Paths;
1314
import java.nio.file.StandardOpenOption;
1415
import java.text.SimpleDateFormat;
1516
import java.util.Collection;
16-
import java.util.Collections;
1717
import java.util.Date;
18+
import java.util.HashSet;
19+
import java.util.Objects;
1820
import org.gradle.api.DefaultTask;
19-
import org.gradle.api.tasks.JavaExec;
21+
import org.gradle.api.Project;
2022
import org.gradle.api.tasks.TaskAction;
21-
import org.gradle.internal.impldep.org.apache.commons.io.FileUtils;
23+
import org.gradle.api.tasks.testing.Test;
24+
import org.jetbrains.annotations.VisibleForTesting;
2225

2326
/**
2427
* Downloads the current java agent from TeamServer using Credentials provided by the
@@ -31,25 +34,48 @@ public class InstallAgentTask extends DefaultTask {
3134

3235
@TaskAction
3336
void installAgent() {
37+
System.out.println("Running installAgent task");
3438

3539
// create sdk object for connecting to Contrast
3640
final ContrastSDK sdk = connectToContrast();
41+
System.out.println("Connected to Contrast at: " + sdk.getRestApiURL());
3742

3843
// get agent, either from configured jar path or from TS
39-
final Path agent = retrieveAgent(sdk);
44+
final Path agent = retrieveAgent(sdk, config.getJarPath(), config.getOrgUuid(), getProject());
4045

46+
System.out.println("preparing to attach agent");
4147
attachAgentToTasks(agent.toAbsolutePath());
4248
}
4349

44-
/** Configures JavaExec tasks to run with the agent attached */
50+
/**
51+
* Configures tasks to run with the agent attached Should be configurable via the plugin
52+
* configurations to determine which tasks we attach to. For now, this configuration is just a
53+
* boolean and only attaches to Test tasks.
54+
*/
4555
private void attachAgentToTasks(final Path agentPath) {
46-
getProject()
47-
.getTasks()
48-
.withType(JavaExec.class)
49-
.configureEach(
50-
task -> {
51-
task.jvmArgs(createContrastArgs(agentPath));
52-
});
56+
if (config.getAttachToTests()) {
57+
getProject()
58+
.getTasks()
59+
.withType(Test.class)
60+
.configureEach(
61+
task -> {
62+
System.out.println("Attaching agent arguments to Test Tasks");
63+
task.jvmArgs(
64+
createContrastArgs(
65+
agentPath,
66+
config.getAppName(),
67+
config.getServerName(),
68+
config.getAppVersion()));
69+
System.out.println("ADDED ARGS " + task.getName() + ":");
70+
Objects.requireNonNull(task.getAllJvmArgs()).forEach(System.out::println);
71+
System.out.println("-----------------------------\n");
72+
});
73+
74+
getProject()
75+
.getTasks()
76+
.withType(Test.class)
77+
.forEach(s -> System.out.println(s.getAllJvmArgs()));
78+
}
5379
}
5480

5581
/**
@@ -58,16 +84,17 @@ private void attachAgentToTasks(final Path agentPath) {
5884
* @param agentPath preconfigured path to an agent defined by the ContrastConfigurationExtension
5985
* @return Set of arguments
6086
*/
61-
private Collection<String> createContrastArgs(final Path agentPath) {
62-
final Collection<String> args = Collections.emptySet();
87+
@VisibleForTesting
88+
public static Collection<String> createContrastArgs(
89+
final Path agentPath, final String appName, final String serverName, String appVersion) {
90+
final Collection<String> args = new HashSet<String>();
6391
args.add("-javaagent:" + agentPath.toAbsolutePath());
64-
args.add("-Dcontrast.override.appname=" + config.appName);
65-
args.add("-Dcontrast.server=" + config.serverName);
92+
args.add("-Dcontrast.override.appname=" + appName);
93+
args.add("-Dcontrast.server=" + serverName);
6694
args.add("-Dcontrast.env=qa");
6795

68-
String appVersion = config.getAppVersion();
6996
if (appVersion == null) {
70-
appVersion = computeAppVersion();
97+
appVersion = computeAppVersion(appName);
7198
}
7299

73100
args.add("-Dcontrast.override.appversion=" + appVersion);
@@ -81,7 +108,8 @@ private Collection<String> createContrastArgs(final Path agentPath) {
81108
*
82109
* @return computed AppVersion
83110
*/
84-
private String computeAppVersion() {
111+
@VisibleForTesting
112+
public static String computeAppVersion(final String appName) {
85113
final Date currentDate = new Date();
86114
String travisBuildNumber = System.getenv("TRAVIS_BUILD_NUMBER");
87115
String circleBuildNum = System.getenv("CIRCLE_BUILD_NUM");
@@ -94,25 +122,40 @@ private String computeAppVersion() {
94122
} else {
95123
appVersionQualifier = new SimpleDateFormat("yyyyMMddHHmmss").format(currentDate);
96124
}
97-
return config.getAppName() + "-" + appVersionQualifier;
125+
return appName + "-" + appVersionQualifier;
98126
}
99127

100128
/** Use ContrastSDK to download agent and return the path where agent jar is stored */
101-
private Path retrieveAgent(final ContrastSDK connection) {
129+
@VisibleForTesting
130+
public static Path retrieveAgent(
131+
final ContrastSDK connection,
132+
final String jarPath,
133+
final String uuid,
134+
final Project project) {
102135
// Initially attempt to run agent from the previously configured location
103-
final String jarPath = config.getJarPath();
104136
if (jarPath != null) {
105137
final Path agent = Paths.get(jarPath);
106138
if (!Files.exists(agent)) {
107139
throw new RuntimeException("Unable to find java agent at " + jarPath);
108140
}
141+
System.out.println("Agent provided via configuration retrieved");
142+
return agent;
143+
}
144+
145+
System.out.println("No agent path provided or agent does not exist, checking for cached agent");
146+
147+
final Path agent = Paths.get(project.getProjectDir().getPath()).resolve(AGENT_NAME);
148+
if (Files.exists(agent)) {
149+
System.out.println("Agent jar found at " + project.getProjectDir().getPath());
109150
return agent;
110151
}
152+
System.out.println("Connected to Contrast at: " + connection.getRestApiURL());
111153

154+
System.out.println("Attempting to retrieve agent from TeamServer");
112155
// If no jar is provided, and no jarpath configured, attempt to retrieve the agent from TS
113156
final byte[] bytes;
114157
try {
115-
bytes = connection.getAgent(AgentType.JAVA, config.getOrgUuid());
158+
bytes = connection.getAgent(AgentType.JAVA, uuid);
116159
} catch (IOException e) {
117160
throw new RuntimeException("Failed to retrieve Contrast Java Agent: " + e);
118161
} catch (UnauthorizedException e) {
@@ -122,20 +165,23 @@ private Path retrieveAgent(final ContrastSDK connection) {
122165
}
123166

124167
// Save the jar to the 'target' directory
125-
final Path target = Paths.get(getProject().getProjectDir().getPath());
168+
final Path target = Paths.get(project.getProjectDir().getPath());
126169
try {
127-
FileUtils.forceMkdir(target.toFile());
170+
Files.createFile(target);
171+
} catch (final FileAlreadyExistsException e) {
172+
System.out.println("Project directory already exists");
128173
} catch (final IOException e) {
129174
throw new RuntimeException("Unable to create directory " + target, e);
130175
}
131176

132-
final Path agent = target.resolve(AGENT_NAME);
177+
final Path downloadedAgent = target.resolve(AGENT_NAME);
133178
try {
134-
Files.write(agent, bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
179+
Files.write(downloadedAgent, bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
135180
} catch (final IOException e) {
136181
throw new RuntimeException("Unable to save the latest java agent.", e);
137182
}
138-
return agent;
183+
System.out.println("Agent retrieved from TeamServer");
184+
return downloadedAgent;
139185
}
140186

141187
/** Use ContrastSDK to download agent creds for running the agent */

0 commit comments

Comments
 (0)