-
Notifications
You must be signed in to change notification settings - Fork 10
/
CodeDxPublisher.java
1019 lines (835 loc) · 35.5 KB
/
CodeDxPublisher.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* © 2023 Synopsys, Inc. All rights reserved worldwide.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package org.jenkinsci.plugins.codedx;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.*;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.codedx.api.client.*;
import com.codedx.api.client.Job;
import com.codedx.api.client.Project;
import com.codedx.security.JenkinsSSLConnectionSocketFactoryFactory;
import com.codedx.util.CodeDxVersion;
import hudson.AbortException;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Extension;
import hudson.model.*;
import hudson.model.queue.Tasks;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.acegisecurity.Authentication;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jenkinsci.plugins.codedx.model.CodeDxReportStatistics;
import org.jenkinsci.plugins.codedx.model.CodeDxGroupStatistics;
import org.jenkinsci.plugins.codedx.monitor.AnalysisMonitor;
import org.jenkinsci.plugins.codedx.monitor.DirectAnalysisMonitor;
import org.jenkinsci.plugins.codedx.monitor.GitJobAnalysisMonitor;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.verb.POST;
import javax.net.ssl.SSLHandshakeException;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.*;
import java.util.logging.Logger;
/**
* Jenkins publisher that publishes project source, binaries, and
* analysis tool output files to a CodeDx server.
*
* @author anthonyd
*/
public class CodeDxPublisher extends Recorder implements SimpleBuildStep {
private final String url;
private final String keyCredentialId;
private final String projectId;
// Comma separated list of source/binary file Ant GLOB patterns
private String sourceAndBinaryFiles;
// List of paths to tool output files
private String toolOutputFiles;
// Comma separated list of source/binary file Ant GLOB patterns to exclude
private String excludedSourceAndBinaryFiles;
private String analysisName;
// Contains the fields applicable when the user chooses to have Jenkins wait for
// analysis runs to complete.
private AnalysisResultConfiguration analysisResultConfiguration;
private transient CodeDxClient client;
private String selfSignedCertificateFingerprint;
private String targetBranchName, baseBranchName;
private BuildErrorBehavior errorHandlingBehavior;
private GitFetchConfiguration gitFetchConfiguration;
private final static Logger logger = Logger.getLogger(CodeDxPublisher.class.getName());
/**
* @param url URL of the Code Dx server
* @param keyCredentialId ID of a Secret Text Credential containing the API key of the Code Dx server
* @param projectId Code Dx project ID
* @param analysisName The name to use for the analysis
*/
@DataBoundConstructor
public CodeDxPublisher(
final String url,
final String keyCredentialId,
final String projectId,
final String analysisName
) {
this.projectId = projectId;
this.url = url;
this.keyCredentialId = keyCredentialId;
this.analysisName = analysisName.trim();
this.sourceAndBinaryFiles = "";
this.excludedSourceAndBinaryFiles = "";
this.toolOutputFiles = "";
this.analysisResultConfiguration = null;
this.selfSignedCertificateFingerprint = null;
this.targetBranchName = null;
this.baseBranchName = null;
this.errorHandlingBehavior = BuildErrorBehavior.MarkFailed;
this.gitFetchConfiguration = null;
}
public AnalysisResultConfiguration getAnalysisResultConfiguration() {
return analysisResultConfiguration;
}
@DataBoundSetter
public void setAnalysisResultConfiguration(AnalysisResultConfiguration analysisResultConfiguration) {
this.analysisResultConfiguration = analysisResultConfiguration;
}
public String getProjectId() {
return projectId;
}
public String getUrl() {
return url;
}
public String getKeyCredentialId() {
return keyCredentialId;
}
public String getSourceAndBinaryFiles() {
return sourceAndBinaryFiles;
}
@DataBoundSetter
public void setSourceAndBinaryFiles(String sourceAndBinaryFiles) {
this.sourceAndBinaryFiles = sourceAndBinaryFiles;
}
public String getToolOutputFiles() {
return toolOutputFiles;
}
@DataBoundSetter
public void setToolOutputFiles(String toolOutputFiles) {
this.toolOutputFiles = toolOutputFiles;
}
public String getExcludedSourceAndBinaryFiles() {
return excludedSourceAndBinaryFiles;
}
@DataBoundSetter
public void setExcludedSourceAndBinaryFiles(String excludedSourceAndBinaryFiles) {
this.excludedSourceAndBinaryFiles = excludedSourceAndBinaryFiles;
}
public String getSelfSignedCertificateFingerprint() {
return selfSignedCertificateFingerprint;
}
@DataBoundSetter
public void setSelfSignedCertificateFingerprint(String selfSignedCertificateFingerprint) {
this.selfSignedCertificateFingerprint = selfSignedCertificateFingerprint;
this.client = null;
}
public String getAnalysisName(){ return analysisName; }
private String getLatestAnalysisUrl() {
if (projectId.length() != 0 && !projectId.equals("-1")) {
return client.buildLatestFindingsUrl(Integer.parseInt(projectId));
} else {
return null;
}
}
public String getTargetBranchName() {
return targetBranchName;
}
@DataBoundSetter
public void setTargetBranchName(String targetBranchName) {
if (targetBranchName != null) targetBranchName = targetBranchName.trim();
if (targetBranchName != null && targetBranchName.length() > 0)
this.targetBranchName = targetBranchName;
else
this.targetBranchName = null;
}
public String getBaseBranchName() {
return baseBranchName;
}
@DataBoundSetter
public void setBaseBranchName(String baseBranchName) {
if (baseBranchName != null) baseBranchName = baseBranchName.trim();
if (baseBranchName != null && baseBranchName.length() > 0)
this.baseBranchName = baseBranchName;
else
this.baseBranchName = null;
}
public BuildErrorBehavior getErrorHandlingBehavior() {
return errorHandlingBehavior;
}
@DataBoundSetter
public void setErrorHandlingBehavior(BuildErrorBehavior behavior) {
errorHandlingBehavior = behavior;
}
public GitFetchConfiguration getGitFetchConfiguration() {
return gitFetchConfiguration;
}
@DataBoundSetter
public void setGitFetchConfiguration(GitFetchConfiguration config) {
gitFetchConfiguration = config;
}
// Sets the build status based on `errorHandlingBehavior`. Only meant to be used for Code Dx-specific
// errors, eg analysis failure and connection issues. Configuration errors will be thrown as usual
// since those issues aren't related to Code Dx itself.
//
// returns true if we ignore the error, false if we want to exit prematurely
private Boolean handleCodeDxError(Run<?, ?> build, PrintStream buildOutput, String cause) throws AbortException {
buildOutput.println(cause);
BuildErrorBehavior behavior = errorHandlingBehavior;
if (behavior == null) behavior = BuildErrorBehavior.Default;
if (behavior != BuildErrorBehavior.None) {
build.setResult(behavior.getEquivalentResult());
return false;
} else {
buildOutput.println("This will be ignored since errorHandlingBehavior is set to " + behavior.getLabel());
return true;
}
}
@Override
public void perform(
final Run<?, ?> build,
final FilePath workspace,
final Launcher launcher,
final TaskListener listener) throws InterruptedException, IOException {
Date startingDate = new Date();
StringCredentials apiCredentials = CredentialsProvider.findCredentialById(
keyCredentialId,
StringCredentials.class,
build,
URIRequirementBuilder.fromUri(url).build()
);
if (apiCredentials == null) {
throw new AbortException("Unable to load credential for API Key");
}
String apiKey = apiCredentials.getSecret().getPlainText();
this.client = buildClient(url, apiKey, selfSignedCertificateFingerprint);
final Map<String, InputStream> toSend = new HashMap<String, InputStream>();
final PrintStream buildOutput = listener.getLogger();
buildOutput.println("Publishing build to Code Dx:");
if (errorHandlingBehavior == null) {
errorHandlingBehavior = BuildErrorBehavior.Default;
}
buildOutput.println("Error handling set to: " + errorHandlingBehavior.getLabel());
if (projectId.length() == 0 || projectId.equals("-1")) {
buildOutput.println("No project has been selected");
return;
}
ProjectContext project;
try {
project = new ProjectContext(Integer.parseInt(projectId));
} catch (NumberFormatException e) {
throw new AbortException("Invalid project ID: " + projectId);
}
buildOutput.println(String.format("Publishing to Code Dx server at %s to Code Dx project %s: ", url, projectId));
final CodeDxClient repeatingClient = new CodeDxRepeatingClient(this.client, buildOutput);
CodeDxVersion cdxVersion = null;
try {
cdxVersion = repeatingClient.getCodeDxVersion();
buildOutput.println("Got Code Dx version: " + cdxVersion);
} catch (Exception e) {
e.printStackTrace(buildOutput);
if (handleCodeDxError(build, buildOutput, "An error occurred fetching the Code Dx version")) {
buildOutput.println("The Code Dx plugin cannot continue without verifying the Code Dx version, exiting");
}
// we can't continue without a version since we don't want to accidentally put data into the wrong target
// by eg using a placeholder version which skips over the Code Dx branch
return;
}
ValueResolver valueResolver = new ValueResolver(build, workspace, listener, buildOutput);
TargetBranchChecker branchChecker = new TargetBranchChecker(project, repeatingClient, valueResolver, buildOutput);
try {
branchChecker.validate(cdxVersion, targetBranchName, baseBranchName);
} catch (AbortException e) {
// configuration error
throw e;
} catch (IOException e) {
e.printStackTrace(buildOutput);
handleCodeDxError(build, buildOutput, "An error occurred while validating branch selection");
// connection error; this will only happen if a target branch was specified. we can't continue without
// applying that target branch, or we might cause data to be written to an unexpected target branch
return;
}
project = project.withBranch(branchChecker.getTargetBranchName());
buildOutput.println("Creating source/binary zip...");
FilePath sourceAndBinaryZip = Archiver.archive(workspace,
Util.commaSeparatedToArray(sourceAndBinaryFiles),
Util.commaSeparatedToArray(excludedSourceAndBinaryFiles),
"source");
if (sourceAndBinaryZip != null) {
buildOutput.println("Adding source/binary zip...");
toSend.put("Jenkins-SourceAndBinary.zip", new DeferredFilePathInputStream(sourceAndBinaryZip));
} else {
buildOutput.println("No matching source/binary files.");
}
String[] files = Util.commaSeparatedToArray(toolOutputFiles);
for (String file : files) {
if (file.length() != 0) {
FilePath path = workspace.child(file);
if (path.exists()) {
buildOutput.println("Add tool output file " + path.getRemote() + " to request.");
toSend.put(path.getName(), new DeferredFilePathInputStream(path));
} else {
buildOutput.println("Path specified but could not be found: " + path);
}
}
}
GitFetchConfiguration effectiveGitConfig = gitFetchConfiguration;
if (effectiveGitConfig != null) {
buildOutput.println("Verifying git config for Code Dx project...");
try {
GitConfigResponse response = repeatingClient.getProjectGitConfig(project);
if (response.getUrl().isEmpty()) {
buildOutput.println("'Include Git Source' was enabled but the project does not have a Git config assigned. 'Include Git Source' will be disabled for this run.");
effectiveGitConfig = null;
}
} catch (Exception e) {
if (!handleCodeDxError(build, buildOutput, "There was a problem fetching the project's Git config")) {
return;
}
buildOutput.println("'Include Git Source' will be disabled for this run.");
effectiveGitConfig = null;
}
}
if (toSend.size() > 0 || effectiveGitConfig != null) {
try {
buildOutput.println("Submitting files to Code Dx for analysis");
AnalysisMonitor analysisMonitor;
StartAnalysisResponse response;
try {
boolean includeGitSource = effectiveGitConfig != null;
String targetGitBranch = null;
if (includeGitSource) {
targetGitBranch = effectiveGitConfig.getSpecificBranch();
if (targetGitBranch != null) {
targetGitBranch = valueResolver.resolve("Git branch", targetGitBranch);
buildOutput.println("Using Git branch for Code Dx: " + targetGitBranch);
} else {
buildOutput.println("No Git branch specified, using Code Dx project's default Git branch");
}
}
response = repeatingClient.startAnalysis(
project.getProjectId(),
includeGitSource,
targetGitBranch,
branchChecker.getBaseBranchName(),
branchChecker.getTargetBranchName(),
toSend
);
// (shouldn't be necessary, but this condition was checked in previous impl., so it will be preserved)
if (response == null) {
handleCodeDxError(build, buildOutput, "Received null data for the analysis job");
// everything else has to do with checking for the analysis indicated by the response, nothing
// else to do if this fails
return;
}
analysisMonitor = effectiveGitConfig != null
? new GitJobAnalysisMonitor(response, buildOutput)
: new DirectAnalysisMonitor(response, buildOutput);
} catch (CodeDxClientException e) {
String errorSpecificMessage;
switch(e.getHttpCode()) {
case 400:
errorSpecificMessage =
" (Bad Request: have you included files from unsupported Tools? " +
"Code Dx Standard Edition does not support uploading tool results)";
break;
case 403:
errorSpecificMessage = " (Forbidden: have you configured your key and permissions correctly?)";
break;
case 404:
errorSpecificMessage = " (Project Not Found: is it possible it was deleted?)";
break;
case 500:
errorSpecificMessage = " (Internal Server Error: Please check your Code Dx server logs for more details)";
break;
default:
errorSpecificMessage = "";
}
String message =
String.format("Failed to start analysis%s.", errorSpecificMessage) + '\n' +
String.format("Response Status: %d: %s", e.getHttpCode(), e.getResponseMessage()) + '\n' +
String.format("Response Content: %s", e.getResponseContent()) + '\n' +
Util.getStackTrace(e);
buildOutput.println(message);
handleCodeDxError(build, buildOutput, "Failed to start analysis");
return; // nothing else to do if we can't start the analysis, everything else relies on it
} finally {
// close streams after we're done sending them
for(Map.Entry<String, InputStream> entry : toSend.entrySet()){
IOUtils.closeQuietly(entry.getValue());
}
}
buildOutput.println("Code Dx accepted files for analysis");
int analysisId = analysisMonitor.waitForStart(repeatingClient);
// Set the analysis name on the server
if(analysisName == null || analysisName.length() == 0) {
buildOutput.println("No 'Analysis Name' was chosen.");
} else if (analysisId == -1) {
buildOutput.println("Code Dx did not provide an analysis ID - the 'Analysis Name' will not be applied.");
} else {
String expandedAnalysisName = valueResolver.resolve("analysis name", analysisName);
buildOutput.println("Analysis Name: " + expandedAnalysisName);
buildOutput.println("Analysis Id: " + analysisId);
if(cdxVersion.compareTo(CodeDxVersion.MIN_FOR_ANALYSIS_NAMES) < 0){
buildOutput.println("The connected Code Dx server is only version " + cdxVersion +
", which doesn't support naming analyses (minimum supported version is " +
CodeDxVersion.MIN_FOR_ANALYSIS_NAMES + "). The analysis name will not be set.");
} else {
try {
repeatingClient.setAnalysisName(project, analysisId, expandedAnalysisName);
buildOutput.println("Successfully updated analysis name.");
} catch (CodeDxClientException e) {
e.printStackTrace(buildOutput);
// this doesn't affect anything else in the plugin, only exit early if we're meant to fail
if (!handleCodeDxError(build, buildOutput, "Got error from Code Dx API Client while trying to set the analysis name")) {
return;
}
}
}
}
if (analysisResultConfiguration == null) {
logger.info("Project not configured to wait on analysis results");
return;
}
String status;
try {
status = analysisMonitor.waitForFinish(repeatingClient);
} catch (CodeDxClientException e) {
e.printStackTrace(buildOutput);
handleCodeDxError(build, buildOutput, "There was an error querying for the analysis status");
return; // nothing else to do if the analysis failed
}
if (Job.COMPLETED.equals(status)) {
try {
buildOutput.println("Analysis succeeded");
buildOutput.println("Fetching severity counts");
Filter notGoneFilter = new Filter();
notGoneFilter.setNotStatus(new String[]{Filter.STATUS_GONE});
List<CountGroup> severityCounts = repeatingClient.getFindingsGroupedCounts(project, notGoneFilter, "severity");
buildOutput.println("Fetching status counts");
Filter notAssignedFilter = new Filter();
notAssignedFilter.setNotStatus(new String[]{ Filter.STATUS_ASSIGNED, Filter.STATUS_GONE });
List<CountGroup> statusCounts = repeatingClient.getFindingsGroupedCounts(project, notAssignedFilter, "status");
Filter assignedFilter = new Filter();
assignedFilter.setStatus(new String[]{Filter.STATUS_ASSIGNED});
buildOutput.println("Fetching assigned count");
//Since CodeDx splits assigned status into different statuses (one per user),
//we need to get the total assigned count and add our own CountGroup.
int assignedCount = repeatingClient.getFindingsCount(project, assignedFilter);
if (assignedCount > 0) {
CountGroup assignedGroup = new CountGroup();
assignedGroup.setName("Assigned");
assignedGroup.setCount(assignedCount);
statusCounts.add(assignedGroup);
}
buildOutput.println("Building table and charts");
Map<String, CodeDxReportStatistics> statMap = new HashMap<String, CodeDxReportStatistics>();
statMap.put("severity", createStatistics(severityCounts));
statMap.put("status", createStatistics(statusCounts));
CodeDxResult result = new CodeDxResult(statMap, build);
buildOutput.println("Adding CodeDx build action");
build.addAction(new CodeDxBuildAction(build, analysisResultConfiguration, getLatestAnalysisUrl(), result));
AnalysisResultChecker checker = new AnalysisResultChecker(repeatingClient,
cdxVersion,
analysisResultConfiguration.getFailureSeverity(),
analysisResultConfiguration.getUnstableSeverity(),
startingDate, // the time this process started is the "new" threshold for filtering
analysisResultConfiguration.isFailureOnlyNew(),
analysisResultConfiguration.isUnstableOnlyNew(),
analysisResultConfiguration.getPolicyBreakBuildBehavior(),
project,
buildOutput);
Result buildResult = checker.checkResult();
build.setResult(buildResult);
} catch (CodeDxClientException e) {
e.printStackTrace(buildOutput);
handleCodeDxError(build, buildOutput, "There was an error fetching/processing analysis results");
}
} else {
buildOutput.println("Analysis status: " + status);
handleCodeDxError(build, buildOutput, "Analysis status was non-success");
}
}
catch (AbortException e) {
// re-throw any "expected" exceptions; if we didn't want these to be thrown due to error
// handling behavior, they wouldn't have been thrown in the first place
throw e;
} catch (Exception e) {
// any remaining exceptions from this `try` block should be related to comms with Code Dx
e.printStackTrace(buildOutput);
handleCodeDxError(build, buildOutput, "An unexpected error occurred");
} finally {
if(sourceAndBinaryZip != null){
sourceAndBinaryZip.delete();
}
}
} else {
throw new AbortException("Nothing to send, this doesn't seem right! Please check your 'Code Dx > Source and Binary Files' configuration.");
}
}
public static CodeDxClient buildClient(String url, String key, String fingerprint) {
CodeDxClient client = new CodeDxClient(url, key);
try {
if (fingerprint != null) {
fingerprint = fingerprint.replaceAll("[^a-fA-F0-9]", "");
}
URL parsedUrl = new URL(url);
SSLConnectionSocketFactory socketFactory = JenkinsSSLConnectionSocketFactoryFactory.getFactory(fingerprint, parsedUrl.getHost());
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setSSLSocketFactory(socketFactory);
client = new CodeDxClient(url, key, builder);
} catch (MalformedURLException e) {
logger.warning("A valid CodeDxClient could not be built. Malformed URL: " + url);
} catch (GeneralSecurityException e) {
logger.warning("A valid CodeDxClient could not be built. GeneralSecurityException: url: " + url + ", fingerprint: " + fingerprint);
} catch (Exception e) {
logger.warning("An exception was thrown while building the client " + e);
e.printStackTrace();
}
return client;
}
private String[] getUsers(Map<String, TriageStatus> assignedStatuses) {
List<String> users = new ArrayList<String>();
for (TriageStatus status : assignedStatuses.values()) {
if (status.getType().equals(TriageStatus.TYPE_USER)) {
users.add(status.getDisplay());
}
}
return users.toArray(new String[0]);
}
private CodeDxReportStatistics createStatistics(List<CountGroup> countGroups) {
List<CodeDxGroupStatistics> groupStatsList = new ArrayList<CodeDxGroupStatistics>();
for (CountGroup group : countGroups) {
CodeDxGroupStatistics stats = new CodeDxGroupStatistics(group.getName(), group.getCount());
groupStatsList.add(stats);
}
return new CodeDxReportStatistics(groupStatsList);
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE; // NONE since this is not dependent on the last step
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* Descriptor for {@link CodeDxPublisher}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
/*
Note: Endpoints which make HTTP requests have `Job` as a path parameter so we can do permission
checks whether it's a project (freestyle) or job (pipeline syntax gen.) being tested
Endpoints which access workspace contents have `AbstractProject` instead since we need
it to get a workspace path. These endpoints will get `null` for the project in the
pipeline syntax gen. and no-op, which is expected since there's no way to get a workspace
while running in the syntax gen.
*/
private void checkPermissionForRemoteRequests(Item item)
{
if (item != null) item.checkPermission(Item.CONFIGURE);
else Jenkins.get().checkPermission(Jenkins.ADMINISTER);
}
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
/**
* In order to load the persisted global configuration, you have to
* call load() in the constructor.
*/
public DescriptorImpl() {
load();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Publish to Code Dx";
}
public FormValidation doCheckProjectId(@QueryParameter final String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please set a project. If none are shown above, then be sure that system settings are configured correctly.");
if (Integer.parseInt(value) == -1)
return FormValidation.error("Failed to get available projects, please ensure systems settings are configured correctly.");
return FormValidation.ok();
}
public FormValidation doCheckKey(@QueryParameter final Secret value)
throws IOException, ServletException {
if (value.getPlainText().length() == 0)
return FormValidation.error("Please set a Key.");
return FormValidation.ok();
}
public ListBoxModel doFillKeyCredentialIdItems(@QueryParameter String url, @QueryParameter String keyCredentialId, @AncestorInPath Item item) {
if (url == null || url.trim().isEmpty()) {
return new StandardListBoxModel();
}
StandardListBoxModel result = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(keyCredentialId);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return result.includeCurrentValue(keyCredentialId);
}
}
return result
.includeMatchingAs(
ACL.SYSTEM,
item,
StringCredentials.class,
URIRequirementBuilder.fromUri(url).build(),
CredentialsMatchers.always()
)
.includeCurrentValue(keyCredentialId);
}
public FormValidation doCheckKeyCredentialId(@QueryParameter String url, @QueryParameter String keyCredentialId, @AncestorInPath Item item)
throws IOException, ServletException {
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return FormValidation.ok();
}
}
if (StringUtils.isBlank(keyCredentialId)) {
return FormValidation.error("API Key credential cannot be blank");
}
if (keyCredentialId.startsWith("${") && keyCredentialId.endsWith("}")) {
return FormValidation.warning("Cannot validate expression based credentials");
}
if (CredentialsProvider.listCredentials(StringCredentials.class, item, ACL.SYSTEM, URIRequirementBuilder.fromUri(url).build(), CredentialsMatchers.withId(keyCredentialId)).isEmpty()) {
return FormValidation.error("Cannot find currently selected credentials");
}
return FormValidation.ok();
}
@POST
public FormValidation doCheckUrl(@QueryParameter final String value, @QueryParameter final String selfSignedCertificateFingerprint, @AncestorInPath Item item)
throws IOException, ServletException {
checkPermissionForRemoteRequests(item);
CodeDxClient client = buildClient(value, "", selfSignedCertificateFingerprint);
if (value.length() == 0)
return FormValidation.error("Please set a URL.");
try {
new URL(value);
} catch (MalformedURLException malformedURLException) {
return FormValidation.error("Malformed URL");
}
if (value.toLowerCase().startsWith("http:")) {
return FormValidation.warning("HTTP is considered insecure, it is recommended that you use HTTPS.");
} else if (value.toLowerCase().startsWith("https:")) {
try {
client.getProjects();
} catch (Exception e) {
if (e instanceof SSLHandshakeException) {
return FormValidation.warning("The SSL Certificate presented by the server is invalid. If this is expected, please input an SHA1 Fingerprint in the \"Advanced\" option");
}
}
return FormValidation.ok();
} else {
return FormValidation.error("Invalid protocol, please use HTTPS or HTTP.");
}
}
@POST
public FormValidation doCheckSelfSignedCertificateFingerprint(@QueryParameter final String value, @QueryParameter final String url, @AncestorInPath Item item) {
checkPermissionForRemoteRequests(item);
if (url != null && ! url.isEmpty() && value != null && ! value.isEmpty()) {
CodeDxClient client = buildClient(url, "", value);
try {
client.getProjects();
} catch (Exception e) {
if (e instanceof SSLHandshakeException) {
logger.warning("When retrieving projects: " + e);
e.printStackTrace();
if (isFingerprintMismatch((SSLHandshakeException)e)) {
return FormValidation.warning("The fingerprint doesn't match the fingerprint of the certificate presented by the server");
} else {
return FormValidation.warning("A secure connection to the server could not be established");
}
}
}
}
return FormValidation.ok();
}
@POST
public FormValidation doCheckSourceAndBinaryFiles(@QueryParameter final String value, @QueryParameter final boolean gitFetchConfiguration, @QueryParameter final String toolOutputFiles, @AncestorInPath AbstractProject project) {
if (project == null) {
return FormValidation.ok();
}
project.checkPermission(AbstractProject.CONFIGURE);
if (value.length() == 0) {
if (gitFetchConfiguration)
return FormValidation.ok();
else if (toolOutputFiles.length() == 0)
return FormValidation.error("You must specify \"Tool Output Files\" and/or \"Source and Binary Files\", or enable \"Include Git Source\"");
else
return FormValidation.warning("It is recommended that at least source files are provided to Code Dx.");
}
return Util.checkCSVGlobMatches(value, project.getSomeWorkspace());
}
@POST
public FormValidation doCheckExcludedSourceAndBinaryFiles(@QueryParameter final String value, @AncestorInPath AbstractProject project) {
if (project == null) {
return FormValidation.ok();
} else {
project.checkPermission(AbstractProject.CONFIGURE);
return Util.checkCSVGlobMatches(value, project.getSomeWorkspace());
}
}
@POST
public FormValidation doCheckToolOutputFiles(@QueryParameter final String value, @QueryParameter final String sourceAndBinaryFiles, @QueryParameter final boolean gitFetchConfiguration, @AncestorInPath AbstractProject project) {
if (project == null) {
return FormValidation.ok();
}
project.checkPermission(AbstractProject.CONFIGURE);
if (value.length() == 0 && sourceAndBinaryFiles.length() == 0 && !gitFetchConfiguration) {
return FormValidation.error("You must specify \"Tool Output Files\" and/or \"Source and Binary Files\", or enable \"Include Git Source\"");
}
return Util.checkCSVFileMatches(value, project.getSomeWorkspace());
}
@POST
public ListBoxModel doFillProjectIdItems(@QueryParameter final String url, @QueryParameter final String selfSignedCertificateFingerprint, @QueryParameter final String keyCredentialId, @AncestorInPath Item item) {
checkPermissionForRemoteRequests(item);
ListBoxModel listBox = new ListBoxModel();
if (StringUtils.isBlank(keyCredentialId) || StringUtils.isBlank(url)) {
return listBox;
}
StringCredentials keyCredential = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StringCredentials.class,
item,
ACL.SYSTEM,
URIRequirementBuilder.fromUri(url).build()
),
CredentialsMatchers.withId(keyCredentialId)
);
if (keyCredential == null) {
return listBox;
}
CodeDxClient client = buildClient(url, keyCredential.getSecret().getPlainText(), selfSignedCertificateFingerprint);
try {
final List<Project> projects = client.getProjects();
Map<String, Boolean> duplicates = new HashMap<String, Boolean>();
for (Project proj : projects) {
if (!duplicates.containsKey(proj.getName())) {
duplicates.put(proj.getName(), false);
} else {
duplicates.put(proj.getName(), true);
}
}
for (Project proj : projects) {
if (!duplicates.get(proj.getName())) {
listBox.add(proj.getName(), Integer.toString(proj.getId()));
} else {
listBox.add(proj.getName() + " (id:" + proj.getId() + ")", Integer.toString(proj.getId()));
}
}
} catch (Exception e) {
logger.warning("Exception when populating projects dropdown " + e);
listBox.add("", "-1");
}
return listBox;
}
public ListBoxModel doFillErrorHandlingBehaviorItems() {
ListBoxModel listBox = new ListBoxModel();
listBox.add(BuildErrorBehavior.None.getLabel(), BuildErrorBehavior.None.name());
listBox.add(BuildErrorBehavior.MarkUnstable.getLabel(), BuildErrorBehavior.MarkUnstable.name());
listBox.add(BuildErrorBehavior.MarkFailed.getLabel(), BuildErrorBehavior.MarkFailed.name());
return listBox;
}
public ListBoxModel doFillPolicyBreakBuildBehaviorItems() {
ListBoxModel listBox = new ListBoxModel();
listBox.add(BuildPolicyBehavior.NoAction.getLabel(), BuildPolicyBehavior.NoAction.name());
listBox.add(BuildPolicyBehavior.MarkUnstable.getLabel(), BuildPolicyBehavior.MarkUnstable.name());
listBox.add(BuildPolicyBehavior.MarkFailed.getLabel(), BuildPolicyBehavior.MarkFailed.name());
return listBox;
}
public ListBoxModel doFillFailureSeverityItems() {
return getSeverityItems();
}
public ListBoxModel doFillUnstableSeverityItems() {
return getSeverityItems();
}
private ListBoxModel getSeverityItems() {
final ListBoxModel listBox = new ListBoxModel();
listBox.add("None", "None");
listBox.add("Info or Higher", "Info");
listBox.add("Low or Higher", "Low");
listBox.add("Medium or Higher", "Medium");
listBox.add("High or Higher", "High");
listBox.add("Critical", "Critical");
return listBox;
}
@Override
public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().