-
Notifications
You must be signed in to change notification settings - Fork 2
/
UploadBinaryScanRecorder.java
475 lines (407 loc) · 17.2 KB
/
UploadBinaryScanRecorder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package com.finitestate.uploadbinaryscan;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.BuildImageCmd;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.command.WaitContainerResultCallback;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.BuildImageResultCallback;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.security.ACL;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
public class UploadBinaryScanRecorder extends Recorder {
private String finiteStateClientId;
private String finiteStateSecret;
private String finiteStateOrganizationContext;
private String assetId;
private String version;
private Boolean externalizableId;
private String filePath;
private Boolean quickScan;
private String businessUnitId;
private String createdByUserId;
private String productId;
private String artifactDescription;
private String parsedVersion;
@DataBoundConstructor
public UploadBinaryScanRecorder(
String finiteStateClientId,
String finiteStateSecret,
String finiteStateOrganizationContext,
String assetId,
String version,
Boolean externalizableId,
String filePath,
String businessUnitId,
String createdByUserId,
String productId,
String artifactDescription,
Boolean quickScan) {
this.finiteStateClientId = finiteStateClientId;
this.finiteStateSecret = finiteStateSecret;
this.finiteStateOrganizationContext = finiteStateOrganizationContext;
this.assetId = assetId;
this.quickScan = quickScan;
this.version = version;
this.externalizableId = externalizableId;
this.filePath = filePath;
this.businessUnitId = businessUnitId;
this.createdByUserId = createdByUserId;
this.productId = productId;
this.artifactDescription = artifactDescription;
}
public String getFiniteStateClientId() {
return finiteStateClientId;
}
public String getFiniteStateSecret() {
return finiteStateSecret;
}
public String getFiniteStateOrganizationContext() {
return finiteStateOrganizationContext;
}
public String getAssetId() {
return assetId;
}
public String getVersion() {
return version;
}
public boolean getExternalizableId() {
return externalizableId;
}
public String getFilePath() {
return filePath;
}
public String getBusinessUnitId() {
return businessUnitId;
}
public String getCreatedByUserId() {
return createdByUserId;
}
public String getProductId() {
return productId;
}
public String getArtifactDescription() {
return artifactDescription;
}
public boolean getQuickScan() {
return quickScan;
}
public boolean isQuickScan() {
return quickScan;
}
@DataBoundSetter
public void setFiniteStateClientId(String finiteStateClientId) {
this.finiteStateClientId = finiteStateClientId;
}
@DataBoundSetter
public void setFiniteStateSecret(String finiteStateSecret) {
this.finiteStateSecret = finiteStateSecret;
}
@DataBoundSetter
public void setFiniteStateOrganizationContext(String finiteStateOrganizationContext) {
this.finiteStateOrganizationContext = finiteStateOrganizationContext;
}
@DataBoundSetter
public void setAssetId(String assetId) {
this.assetId = assetId;
}
@DataBoundSetter
public void setVersion(String version) {
this.version = version;
}
@DataBoundSetter
public void setExternalizableId(boolean externalizableId) {
this.externalizableId = externalizableId;
}
@DataBoundSetter
public void setFilePath(String filePath) {
this.filePath = filePath;
}
@DataBoundSetter
public void setQuickScan(boolean quickScan) {
this.quickScan = quickScan;
}
@DataBoundSetter
public void setBusinessUnitId(String businessUnitId) {
this.businessUnitId = businessUnitId;
}
@DataBoundSetter
public void setCreatedByUserId(String createdByUserId) {
this.createdByUserId = createdByUserId;
}
@DataBoundSetter
public void setProductId(String productId) {
this.productId = productId;
}
@DataBoundSetter
public void setArtifactDescription(String artifactDescription) {
this.artifactDescription = artifactDescription;
}
private File getFileFromWorkspace(AbstractBuild build, String relativeFilePath, BuildListener listener) {
// Get the workspace directory for the current build
FilePath workspace = build.getWorkspace();
if (workspace != null) {
String workspaceRemote = workspace.getRemote();
// Construct the absolute path to the file
// Return the file
return new File(workspaceRemote, relativeFilePath);
}
return null;
}
/**
* get secret values from form
*
* @param build
* @param credentialId
* @return
*/
public String getSecretTextValue(AbstractBuild build, String credentialId) {
// Retrieve the credentials by ID
StandardCredentials credentials =
CredentialsProvider.findCredentialById(credentialId, StringCredentials.class, build);
// Check if the credential is of type StringCredentials
if (credentials instanceof StringCredentials) {
StringCredentials stringCredentials = (StringCredentials) credentials;
// Get the secret value
String secretValue = stringCredentials.getSecret().getPlainText();
return secretValue;
} else {
return null;
}
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
if (getExternalizableId()) {
parsedVersion = build.getExternalizableId();
} else {
parsedVersion = version;
}
String parsedFiniteStateClientId = getSecretTextValue(build, finiteStateClientId);
String parsedFiniteStateSecret = getSecretTextValue(build, finiteStateSecret);
String parsedFiniteStateOrganizationContext = getSecretTextValue(build, finiteStateOrganizationContext);
// Create a map to hold environment variables
List<String> envList = new ArrayList<>();
envList.add("INPUT_FINITE-STATE-CLIENT-ID=" + parsedFiniteStateClientId);
envList.add("INPUT_FINITE-STATE-SECRET=" + parsedFiniteStateSecret);
envList.add("INPUT_FINITE-STATE-ORGANIZATION-CONTEXT=" + parsedFiniteStateOrganizationContext);
envList.add("INPUT_ASSET-ID=" + assetId);
envList.add("INPUT_VERSION=" + parsedVersion);
envList.add("INPUT_QUICK-SCAN=" + (quickScan ? "true" : "false"));
// non required parameters:
envList.add("INPUT_BUSINESS-UNIT-ID=" + businessUnitId);
envList.add("INPUT_CREATED-BY-USER-ID=" + createdByUserId);
envList.add("INPUT_PRODUCT-ID=" + productId);
envList.add("INPUT_ARTIFACT-DESCRIPTION=" + artifactDescription);
// Docker client configuration
DefaultDockerClientConfig config =
DefaultDockerClientConfig.createDefaultConfigBuilder().build();
DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
URL resourceUrl =
UploadBinaryScanRecorder.class.getClassLoader().getResource("com/finitestate/docker/Dockerfile");
BuildImageCmd buildImageCmd = dockerClient.buildImageCmd();
// Step 2: Set the Dockerfile
buildImageCmd.withDockerfile(new File(resourceUrl.getFile()));
// Step 3: Execute the build and get the result callback
BuildImageResultCallback resultCallback = new BuildImageResultCallback() {
@Override
public void onNext(com.github.dockerjava.api.model.BuildResponseItem item) {
// Handle build response
System.out.println(item.getStream());
super.onNext(item);
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
}
};
buildImageCmd.exec(resultCallback);
// Step 4: Await the image ID
String imageId = resultCallback.awaitImageId();
System.out.println("Built image ID: " + imageId);
listener.getLogger().println("imageId: " + imageId);
File file = getFileFromWorkspace(build, filePath, listener);
if (file == null || !file.exists()) {
// File not found
listener.getLogger().println("File specified in file path not found: " + filePath);
return false;
} else {
// Process the file
listener.getLogger().println("Found file: " + file.getAbsolutePath());
}
envList.add("INPUT_FILE-PATH=/tmp/" + file.getName()); // set env filename
// Create a list to hold volume mappings
// String hostFilePath = file.getAbsolutePath();
String hostDirectory = file.getParent();
String containerDirectoryPath = "/tmp/";
Bind volumeBind = new Bind(hostDirectory, new Volume(containerDirectoryPath));
// Create a Volume object for the mapping
// Run Docker container from the built image
CreateContainerCmd createContainerCmd =
dockerClient.createContainerCmd(imageId).withBinds(volumeBind).withEnv(envList);
String containerId = createContainerCmd.exec().getId();
dockerClient.startContainerCmd(containerId).exec();
// Retrieve and log container logs
LogContainerCmd logContainerCmd = dockerClient
.logContainerCmd(containerId)
.withStdErr(true)
.withStdOut(true)
.withFollowStream(true)
.withTailAll();
// Retrieve and log container logs
ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
listener.getLogger().println(frame.toString());
}
};
logContainerCmd.exec(callback).awaitCompletion();
// Wait for the container to finish
dockerClient
.waitContainerCmd(containerId)
.exec(new WaitContainerResultCallback())
.awaitCompletion(5, TimeUnit.MINUTES);
build.addAction(new UploadBinaryScanAction(assetId));
// dockerClient.close();
return true;
}
@Symbol("fs-upload-binary-scan")
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public ListBoxModel doFillFiniteStateClientIdItems(
@AncestorInPath Item item, @QueryParameter String finiteStateClientId) {
StandardListBoxModel items = new StandardListBoxModel();
if (item == null) {
// Check if the user has the ADMINISTER permission at the Jenkins root level
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
// If not, return the current value without adding any new items
return items.includeCurrentValue(finiteStateClientId);
}
} else {
// Check if the user has the EXTENDED_READ or USE_ITEM permissions on the item
if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
// If not, return the current value without adding any new item
return items.includeCurrentValue(finiteStateClientId);
}
}
// Retrieve a list of credentails in a global context:
for (StandardCredentials credential : CredentialsProvider.lookupCredentials(
StandardCredentials.class, (Item) null, ACL.SYSTEM, Collections.emptyList())) {
items.add(credential.getId());
}
// Return the populated StandardListBoxModel
return items;
}
public ListBoxModel doFillFiniteStateSecretItems(
@AncestorInPath Item item, @QueryParameter String finiteStateSecret) {
StandardListBoxModel items = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return items.includeCurrentValue(finiteStateSecret);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return items.includeCurrentValue(finiteStateSecret);
}
}
for (StandardCredentials credential : CredentialsProvider.lookupCredentials(
StandardCredentials.class, (Item) null, ACL.SYSTEM, Collections.emptyList())) {
items.add(credential.getId());
}
return items;
}
public ListBoxModel doFillFiniteStateOrganizationContextItems(
@AncestorInPath Item item, @QueryParameter String finiteStateOrganizationContext) {
StandardListBoxModel items = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return items.includeCurrentValue(finiteStateOrganizationContext);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return items.includeCurrentValue(finiteStateOrganizationContext);
}
}
for (StandardCredentials credential : CredentialsProvider.lookupCredentials(
StandardCredentials.class, (Item) null, ACL.SYSTEM, Collections.emptyList())) {
items.add(credential.getId());
}
return items;
}
private FormValidation checkRequiredValue(String value) {
if (value.length() == 0) {
return FormValidation.error("This value is required");
}
return FormValidation.ok();
}
@RequirePOST
public FormValidation doCheckFiniteStateClientId(@QueryParameter String value)
throws IOException, ServletException {
return checkRequiredValue(value);
}
@RequirePOST
public FormValidation doCheckFiniteStateSecret(@QueryParameter String value)
throws IOException, ServletException {
return checkRequiredValue(value);
}
@RequirePOST
public FormValidation doCheckFiniteStateOrganizationContext(@QueryParameter String value)
throws IOException, ServletException {
return checkRequiredValue(value);
}
@RequirePOST
public FormValidation doCheckAssetId(@QueryParameter String value) throws IOException, ServletException {
return checkRequiredValue(value);
}
@RequirePOST
public FormValidation doCheckVersion(@QueryParameter String value) throws IOException, ServletException {
return checkRequiredValue(value);
}
@RequirePOST
public FormValidation doCheckFilePath(@QueryParameter String value) throws IOException, ServletException {
return checkRequiredValue(value);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public String getDisplayName() {
return "Finite State - Upload Binary Scan";
}
}
}