-
Notifications
You must be signed in to change notification settings - Fork 583
/
checkmarxone.go
1395 lines (1173 loc) · 42.7 KB
/
checkmarxone.go
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
package checkmarxOne
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
//"strconv"
"strings"
"time"
//"encoding/xml"
piperHttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ReportsDirectory defines the subfolder for the Checkmarx reports which are generated
const ReportsDirectory = "checkmarxOne"
const cxOrigin = "GolangScript"
// AuthToken - Structure to store OAuth2 token
// Updated for Cx1
type AuthToken struct {
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
// RefreshExpiresIn int `json:"refresh_expires_in"`
// NotBeforePolicy int `json:"not-before-policy"`
// Scope string `json:"scope"`
}
type Application struct {
ApplicationID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Criticality uint `json:"criticality"`
Rules []ApplicationRule `json:"rules"`
Tags map[string]string `json:"tags"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
type ApplicationRule struct {
Type string `json:"type"`
Value string `json:"value"`
}
// Preset - Project's Preset
// Updated for Cx1
type Preset struct {
PresetID int `json:"id"`
Name string `json:"name"`
}
// Project - Project Structure
// Updated for Cx1
type Project struct {
ProjectID string `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
Groups []string `json:"groups"`
Applications []string `json:"applicationIds"`
Tags map[string]string `json:"tags"`
RepoUrl string `json:"repoUrl"`
MainBranch string `json:"mainBranch"`
Origin string `json:"origin"`
Criticality int `json:"criticality"`
}
// New for Cx1
// These settings are higher-level settings that define how an engine should run, for example "multi-language" mode or setting a preset.
type ProjectConfigurationSetting struct {
Key string `json:"key"`
Name string `json:"name"`
Category string `json:"category"`
OriginLevel string `json:"originLevel"`
Value string `json:"value"`
ValueType string `json:"valuetype"`
ValueTypeParams string `json:"valuetypeparams"`
AllowOverride bool `json:"allowOverride"`
}
type Query struct {
QueryID uint64 `json:"queryID,string"`
Name string `json:"queryName"`
Group string
Language string
Severity string
CweID int64
QueryDescriptionID int64
Custom bool
}
// ReportStatus - ReportStatus Structure
// Updated for Cx1
type ReportStatus struct {
ReportID string `json:"reportId"`
Status string `json:"status"`
ReportURL string `json:"url"`
}
type ResultsPredicates struct {
PredicateID string `json:"ID"`
SimilarityID int64 `json:"similarityId,string"`
ProjectID string `json:"projectId"`
State string `json:"state"`
Comment string `json:"comment"`
Severity string `json:"severity"`
CreatedBy string
CreatedAt string
}
// Scan - Scan Structure
// updated for Cx1
type Scan struct {
ScanID string `json:"id"`
Status string `json:"status"`
StatusDetails []ScanStatusDetails `json:"statusDetails"`
Branch string `json:"branch"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
ProjectID string `json:"projectId"`
ProjectName string `json:"projectName"`
UserAgent string `json:"userAgent"`
Initiator string `json:"initiator"`
Tags map[string]string `json:"tags"`
Metadata struct {
Type string `json:"type"`
Configs []ScanConfiguration `json:"configs"`
} `json:"metadata"`
Engines []string `json:"engines"`
SourceType string `json:"sourceType"`
SourceOrigin string `json:"sourceOrigin"`
}
// New for Cx1: ScanConfiguration - list of key:value pairs used to configure the scan for each scan engine
// This is specifically for scan-level configurations like "is incremental" and scan tags
type ScanConfiguration struct {
ScanType string `json:"type"`
Values map[string]string `json:"value"`
}
/*
{"scanId":"bef5d38b-7eb9-4138-b74b-2639fcf49e2e","projectId":"ad34ade3-9bf3-4b5a-91d7-3ad67eca7852","loc":137,"fileCount":12,"isIncremental":false,"isIncrementalCanceled":false,"queryPreset":"ASA Premium"}
*/
type ScanMetadata struct {
ScanID string
ProjectID string
LOC int
FileCount int
IsIncremental bool
IsIncrementalCanceled bool
PresetName string `json:"queryPreset"`
}
type ScanResultData struct {
QueryID uint64
QueryName string
Group string
ResultHash string
LanguageName string
Nodes []ScanResultNodes
}
type ScanResultNodes struct {
ID string
Line int
Name string
Column int
Length int
Method string
NodeID int
DOMType string
FileName string
FullName string
TypeName string
MethodLine int
Definitions string
}
type ScanResult struct {
Type string
ResultID string `json:"id"`
SimilarityID int64 `json:"similarityId,string"`
Status string
State string
Severity string
CreatedAt string `json:"created"`
FirstFoundAt string
FoundAt string
FirstScanId string
Description string
Data ScanResultData
VulnerabilityDetails ScanResultDetails
}
type ScanResultDetails struct {
CweId int
Compliances []string
}
// Cx1: StatusDetails - details of each engine type's scan status for a multi-engine scan
type ScanStatusDetails struct {
Name string `json:"name"`
Status string `json:"status"`
Details string `json:"details"`
}
// Very simplified for now
type ScanSummary struct {
TenantID string
ScanID string
SASTCounters struct {
//QueriesCounters []?
//SinkFileCounters []?
LanguageCounters []struct {
Language string
Counter uint64
}
ComplianceCounters []struct {
Compliance string
Counter uint64
}
SeverityCounters []struct {
Severity string
Counter uint64
}
StatusCounters []struct {
Status string
Counter uint64
}
StateCounters []struct {
State string
Counter uint64
}
TotalCounter uint64
FilesScannedCounter uint64
}
// ignoring the other counters
// KICSCounters
// SCACounters
// SCAPackagesCounters
// SCAContainerCounters
// APISecCounters
}
// Status - Status Structure
type Status struct {
ID int `json:"id"`
Name string `json:"name"`
Details ScanStatusDetails `json:"details"`
}
type VersionInfo struct {
CxOne string `json:"CxOne"`
KICS string `json:"KICS"`
SAST string `json:"SAST"`
}
type WorkflowLog struct {
Source string `json:"Source"`
Info string `json:"Info"`
Timestamp string `json:"Timestamp"`
}
// Cx1 Group/Group - Group Structure
type Group struct {
GroupID string `json:"id"`
Name string `json:"name"`
}
// SystemInstance is the client communicating with the Checkmarx backend
type SystemInstance struct {
serverURL string
iamURL string // New for Cx1
tenant string // New for Cx1
APIKey string // New for Cx1
oauth_client_id string // separate from APIKey
oauth_client_secret string //separate from APIKey
client piperHttp.Uploader
logger *logrus.Entry
}
// System is the interface abstraction of a specific SystemIns
type System interface {
DownloadReport(reportID string) ([]byte, error)
GetReportStatus(reportID string) (ReportStatus, error)
RequestNewReport(scanID, projectID, branch, reportType string) (string, error)
CreateApplication(appname string) (Application, error)
GetApplicationByName(appname string) (Application, error)
GetApplicationByID(appId string) (Application, error)
UpdateApplication(app *Application) error
GetScan(scanID string) (Scan, error)
GetScanMetadata(scanID string) (ScanMetadata, error)
GetScanResults(scanID string, limit uint64) ([]ScanResult, error)
GetScanSummary(scanID string) (ScanSummary, error)
GetResultsPredicates(SimilarityID int64, ProjectID string) ([]ResultsPredicates, error)
GetScanWorkflow(scanID string) ([]WorkflowLog, error)
GetLastScans(projectID string, limit int) ([]Scan, error)
GetLastScansByStatus(projectID string, limit int, status []string) ([]Scan, error)
ScanProject(projectID, sourceUrl, branch, scanType string, settings []ScanConfiguration) (Scan, error)
ScanProjectZip(projectID, sourceUrl, branch string, settings []ScanConfiguration) (Scan, error)
ScanProjectGit(projectID, repoUrl, branch string, settings []ScanConfiguration) (Scan, error)
UploadProjectSourceCode(projectID string, zipFile string) (string, error)
CreateProject(projectName string, groupIDs []string) (Project, error)
CreateProjectInApplication(projectName, applicationID string, groupIDs []string) (Project, error)
GetPresets() ([]Preset, error)
GetProjectByID(projectID string) (Project, error)
GetProjectsByName(projectName string) ([]Project, error)
GetProjectsByNameAndGroup(projectName, groupID string) ([]Project, error)
GetProjects() ([]Project, error)
GetQueries() ([]Query, error)
//GetShortDescription(scanID int, pathID int) (ShortDescription, error)
GetGroups() ([]Group, error)
GetGroupByName(groupName string) (Group, error)
GetGroupByID(groupID string) (Group, error)
SetProjectBranch(projectID, branch string, allowOverride bool) error
SetProjectPreset(projectID, presetName string, allowOverride bool) error
SetProjectLanguageMode(projectID, languageMode string, allowOverride bool) error
SetProjectFileFilter(projectID, filter string, allowOverride bool) error
GetProjectConfiguration(projectID string) ([]ProjectConfigurationSetting, error)
UpdateProjectConfiguration(projectID string, settings []ProjectConfigurationSetting) error
GetVersion() (VersionInfo, error)
}
// NewSystemInstance returns a new Checkmarx client for communicating with the backend
// Updated for Cx1
func NewSystemInstance(client piperHttp.Uploader, serverURL, iamURL, tenant, APIKey, client_id, client_secret string) (*SystemInstance, error) {
loggerInstance := log.Entry().WithField("package", "SAP/jenkins-library/pkg/checkmarxOne")
sys := &SystemInstance{
serverURL: serverURL,
iamURL: iamURL,
tenant: tenant,
APIKey: APIKey,
oauth_client_id: client_id,
oauth_client_secret: client_secret,
client: client,
logger: loggerInstance,
}
var token string
var err error
if APIKey != "" {
token, err = sys.getAPIToken()
if err != nil {
return sys, errors.Wrap(err, fmt.Sprintf("Error fetching oAuth token using API Key: %v", shortenGUID(APIKey)))
}
} else if client_id != "" && client_secret != "" {
token, err = sys.getOAuth2Token()
if err != nil {
return sys, errors.Wrap(err, fmt.Sprintf("Error fetching oAuth token using OIDC client: %v/%v", shortenGUID(client_id), shortenGUID(client_secret)))
}
} else {
return sys, errors.New("No APIKey or client_id/client_secret provided.")
}
log.RegisterSecret(token)
options := piperHttp.ClientOptions{
Token: token,
TransportTimeout: time.Minute * 15,
}
sys.client.SetOptions(options)
return sys, nil
}
// Updated for Cx1
func sendRequest(sys *SystemInstance, method, url string, body io.Reader, header http.Header, acceptedErrorCodes []int) ([]byte, error) {
cx1url := fmt.Sprintf("%v/api%v", sys.serverURL, url)
return sendRequestInternal(sys, method, cx1url, body, header, acceptedErrorCodes)
}
// Updated for Cx1
func sendRequestIAM(sys *SystemInstance, method, base, url string, body io.Reader, header http.Header, acceptedErrorCodes []int) ([]byte, error) {
iamurl := fmt.Sprintf("%v%v/realms/%v%v", sys.iamURL, base, sys.tenant, url)
return sendRequestInternal(sys, method, iamurl, body, header, acceptedErrorCodes)
}
// Updated for Cx1
func sendRequestInternal(sys *SystemInstance, method, url string, body io.Reader, header http.Header, acceptedErrorCodes []int) ([]byte, error) {
var requestBody io.Reader
var reqBody string
if body != nil {
closer := io.NopCloser(body)
bodyBytes, _ := io.ReadAll(closer)
reqBody = string(bodyBytes)
requestBody = bytes.NewBuffer(bodyBytes)
defer closer.Close()
}
if header == nil {
header = http.Header{}
}
header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0")
//header.Set("User-Agent", "Project-Piper.io cicd pipeline") // currently this causes some requests to fail due to unknown UA validation in the backend.
response, err := sys.client.SendRequest(method, url, requestBody, header, nil)
if err != nil && (response == nil || !piperutils.ContainsInt(acceptedErrorCodes, response.StatusCode)) {
var resBodyBytes []byte
if response != nil && response.Body != nil {
resBodyBytes, _ = io.ReadAll(response.Body)
defer response.Body.Close()
resBody := string(resBodyBytes)
sys.recordRequestDetailsInErrorCase(reqBody, resBody)
}
var str string
if len(resBodyBytes) > 0 {
var msg map[string]interface{}
_ = json.Unmarshal(resBodyBytes, &msg)
if msg["message"] != nil {
str = msg["message"].(string)
} else if msg["error_description"] != nil {
str = msg["error_description"].(string)
} else if msg["error"] != nil {
str = msg["error"].(string)
} else {
if len(str) > 20 {
str = string(resBodyBytes[:20])
} else {
str = string(resBodyBytes)
}
}
}
if err != nil {
if str != "" {
err = fmt.Errorf("%s: %v", err, str)
} else {
err = fmt.Errorf("%s", err)
}
sys.logger.Errorf("HTTP request failed with error: %s", err)
return resBodyBytes, err
} else {
if str != "" {
err = fmt.Errorf("HTTP %v: %v", response.Status, str)
} else {
err = fmt.Errorf("HTTP %v", response.Status)
}
sys.logger.Errorf("HTTP response indicates error: %s", err)
return resBodyBytes, err
}
}
data, _ := io.ReadAll(response.Body)
//sys.logger.Debugf("Valid response body: %v", string(data))
defer response.Body.Close()
return data, nil
}
func (sys *SystemInstance) recordRequestDetailsInErrorCase(requestBody string, responseBody string) {
if requestBody != "" {
sys.logger.Errorf("Request body: %s", requestBody)
}
if responseBody != "" {
sys.logger.Errorf("Response body: %s", responseBody)
}
}
/*
CxOne authentication options are:
1. APIKey: post to /protocol/openid-connect/token with client_id ("ast-app"), refresh_token (APIKey generated in the UI), & grant_type ("refresh_token")
2. OAuth Client (service account): post to /protocol/openid-connect/token with client_id (set in the OIDC client in the Cx1 UI), client_secret (set in the UI), grant_type ("client_credentials")
For regular users, the API Key is likely to be used - it is a token tied to the user account.
For service accounts, Administrators will need to create OAuth clients.
*/
// Updated for Cx1
func (sys *SystemInstance) getOAuth2Token() (string, error) {
body := url.Values{
"grant_type": {"client_credentials"},
"client_id": {sys.oauth_client_id},
"client_secret": {sys.oauth_client_secret},
}
header := http.Header{}
header.Add("Content-type", "application/x-www-form-urlencoded")
data, err := sendRequestIAM(sys, http.MethodPost, "/auth", "/protocol/openid-connect/token", strings.NewReader(body.Encode()), header, []int{})
if err != nil {
return "", err
}
var token AuthToken
json.Unmarshal(data, &token)
return token.TokenType + " " + token.AccessToken, nil
}
// Updated for Cx1
func (sys *SystemInstance) getAPIToken() (string, error) {
body := url.Values{
"grant_type": {"refresh_token"},
"client_id": {"ast-app"},
"refresh_token": {sys.APIKey},
}
header := http.Header{}
header.Add("Content-type", "application/x-www-form-urlencoded")
data, err := sendRequestIAM(sys, http.MethodPost, "/auth", "/protocol/openid-connect/token", strings.NewReader(body.Encode()), header, []int{})
if err != nil {
return "", err
}
var token AuthToken
json.Unmarshal(data, &token)
return token.TokenType + " " + token.AccessToken, nil
}
func (sys *SystemInstance) GetApplicationsByName(name string, limit uint64) ([]Application, error) {
sys.logger.Debugf("Get Cx1 Applications by name: %v", name)
var ApplicationResponse struct {
TotalCount uint64
FilteredCount uint64
Applications []Application
}
body := url.Values{
//"offset": {fmt.Sprintf("%d", 0)},
"limit": {fmt.Sprintf("%d", limit)},
"name": {name},
}
response, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/applications?%v", body.Encode()), nil, nil, []int{})
if err != nil {
return ApplicationResponse.Applications, err
}
err = json.Unmarshal(response, &ApplicationResponse)
sys.logger.Tracef("Retrieved %d applications", len(ApplicationResponse.Applications))
return ApplicationResponse.Applications, err
}
func (sys *SystemInstance) GetApplicationByID(appId string) (Application, error) {
sys.logger.Debugf("Get Cx1 Application by ID: %v", appId)
var ret Application
response, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/applications/%v", appId), nil, nil, []int{})
if err != nil {
return ret, err
}
err = json.Unmarshal(response, &ret)
return ret, err
}
func (sys *SystemInstance) GetApplicationByName(name string) (Application, error) {
apps, err := sys.GetApplicationsByName(name, 0)
if err != nil {
return Application{}, err
}
for _, a := range apps {
if a.Name == name {
return a, nil
}
}
return Application{}, fmt.Errorf("no application found named %v", name)
}
func (sys *SystemInstance) CreateApplication(appname string) (Application, error) {
sys.logger.Debugf("Create Application: %v", appname)
data := map[string]interface{}{
"name": appname,
"description": "",
"criticality": 3,
"rules": []ApplicationRule{},
"tags": map[string]string{},
}
var app Application
jsonBody, err := json.Marshal(data)
if err != nil {
return app, err
}
response, err := sendRequest(sys, http.MethodPost, "/applications", bytes.NewReader(jsonBody), nil, []int{})
if err != nil {
sys.logger.Tracef("Error while creating application: %s", err)
return app, err
}
err = json.Unmarshal(response, &app)
return app, err
}
func (a *Application) GetRuleByType(ruletype string) *ApplicationRule {
for id := range a.Rules {
if a.Rules[id].Type == ruletype {
return &(a.Rules[id])
}
}
return nil
}
func (a *Application) AddRule(ruletype, value string) {
rule := a.GetRuleByType(ruletype)
if rule == nil {
var newrule ApplicationRule
newrule.Type = ruletype
newrule.Value = value
a.Rules = append(a.Rules, newrule)
} else {
if rule.Value == value || strings.Contains(rule.Value, fmt.Sprintf(";%v;", value)) || rule.Value[len(rule.Value)-len(value)-1:] == fmt.Sprintf(";%v", value) || rule.Value[:len(value)+1] == fmt.Sprintf("%v;", value) {
return // rule value already contains this value
}
rule.Value = fmt.Sprintf("%v;%v", rule.Value, value)
}
}
func (a *Application) AssignProject(project *Project) {
a.AddRule("project.name.in", project.Name)
}
func (sys *SystemInstance) UpdateApplication(app *Application) error {
sys.logger.Debugf("Updating application: %v", app.Name)
jsonBody, err := json.Marshal(*app)
if err != nil {
return err
}
_, err = sendRequest(sys, http.MethodPut, fmt.Sprintf("/applications/%v", app.ApplicationID), bytes.NewReader(jsonBody), nil, []int{})
if err != nil {
sys.logger.Tracef("Error while updating application: %s", err)
return err
}
return nil
}
// Updated for Cx1
func (sys *SystemInstance) GetGroups() ([]Group, error) {
sys.logger.Debug("Getting Groups...")
var groups []Group
data, err := sendRequestIAM(sys, http.MethodGet, "/auth", "/pip/groups", nil, http.Header{}, []int{})
if err != nil {
sys.logger.Errorf("Fetching groups failed: %s", err)
return groups, err
}
err = json.Unmarshal(data, &groups)
if err != nil {
sys.logger.Errorf("Fetching groups failed: %s", err)
return groups, err
}
return groups, nil
}
// New for Cx1
func (sys *SystemInstance) GetGroupByName(groupName string) (Group, error) {
sys.logger.Debugf("Getting Group named %v...", groupName)
groups, err := sys.GetGroups()
var group Group
if err != nil {
return group, err
}
for _, g := range groups {
if g.Name == groupName {
return g, nil
}
}
return group, errors.New(fmt.Sprintf("No group matching %v", groupName))
}
// New for Cx1
func (sys *SystemInstance) GetGroupByID(groupID string) (Group, error) {
sys.logger.Debugf("Getting Group with ID %v...", groupID)
groups, err := sys.GetGroups()
var group Group
if err != nil {
return group, err
}
for _, g := range groups {
if g.GroupID == groupID {
return g, nil
}
}
return group, errors.New(fmt.Sprintf("No group with ID %v", groupID))
}
// GetProjects returns the projects defined in the Checkmarx backend which the user has access to
func (sys *SystemInstance) GetProjects() ([]Project, error) {
return sys.GetProjectsByNameAndGroup("", "")
}
// GetProjectByID returns the project addressed by projectID from the Checkmarx backend which the user has access to
// Updated for Cx1
func (sys *SystemInstance) GetProjectByID(projectID string) (Project, error) {
sys.logger.Debugf("Getting Project with ID %v...", projectID)
var project Project
data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/%v", projectID), nil, http.Header{}, []int{})
if err != nil {
return project, errors.Wrapf(err, "fetching project %v failed", projectID)
}
err = json.Unmarshal(data, &project)
return project, err
}
// GetProjectsByNameAndGroup returns the project addressed by project name from the Checkmarx backend which the user has access to
// Updated for Cx1
func (sys *SystemInstance) GetProjectsByName(projectName string) ([]Project, error) {
sys.logger.Debugf("Getting projects with name %v", projectName)
var projectResponse struct {
TotalCount int `json:"totalCount"`
FilteredCount int `json:"filteredCount"`
Projects []Project `json:"projects"`
}
header := http.Header{}
header.Set("Accept-Type", "application/json")
var data []byte
var err error
body := url.Values{}
body.Add("name", projectName)
data, err = sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/?%v", body.Encode()), nil, header, []int{404})
if err != nil {
return []Project{}, errors.Wrapf(err, "fetching project %v failed", projectName)
}
err = json.Unmarshal(data, &projectResponse)
return projectResponse.Projects, err
}
// GetProjectsByNameAndGroup returns the project addressed by project name from the Checkmarx backend which the user has access to
// Updated for Cx1
func (sys *SystemInstance) GetProjectsByNameAndGroup(projectName, groupID string) ([]Project, error) {
sys.logger.Debugf("Getting projects with name %v of group %v...", projectName, groupID)
var projectResponse struct {
TotalCount int `json:"totalCount"`
FilteredCount int `json:"filteredCount"`
Projects []Project `json:"projects"`
}
header := http.Header{}
header.Set("Accept-Type", "application/json")
var data []byte
var err error
body := url.Values{}
if len(groupID) > 0 {
body.Add("groups", groupID)
}
if len(projectName) > 0 {
body.Add("name", projectName)
}
if len(body) > 0 {
data, err = sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/?%v", body.Encode()), nil, header, []int{404})
} else {
data, err = sendRequest(sys, http.MethodGet, "/projects/", nil, header, []int{404})
}
if err != nil {
return projectResponse.Projects, errors.Wrapf(err, "fetching project %v failed", projectName)
}
err = json.Unmarshal(data, &projectResponse)
return projectResponse.Projects, err
}
// CreateProject creates a new project in the Checkmarx backend
// Updated for Cx1
func (sys *SystemInstance) CreateProject(projectName string, groupIDs []string) (Project, error) {
var project Project
jsonData := map[string]interface{}{
"name": projectName,
"groups": groupIDs,
"origin": cxOrigin,
"criticality": 3, // default
// multiple additional parameters exist as options
}
jsonValue, err := json.Marshal(jsonData)
if err != nil {
return project, errors.Wrapf(err, "failed to marshal project data")
}
header := http.Header{}
header.Set("Content-Type", "application/json")
data, err := sendRequest(sys, http.MethodPost, "/projects", bytes.NewBuffer(jsonValue), header, []int{})
if err != nil {
return project, errors.Wrapf(err, "failed to create project %v", projectName)
}
err = json.Unmarshal(data, &project)
return project, err
}
func (sys *SystemInstance) CreateProjectInApplication(projectName, applicationID string, groupIDs []string) (Project, error) {
var project Project
jsonData := map[string]interface{}{
"name": projectName,
"groups": groupIDs,
"origin": cxOrigin,
"criticality": 3, // default
"applicationIds": []string{applicationID},
// multiple additional parameters exist as options
}
jsonValue, err := json.Marshal(jsonData)
if err != nil {
return project, errors.Wrapf(err, "failed to marshal project data")
}
header := http.Header{}
header.Set("Content-Type", "application/json")
data, err := sendRequest(sys, http.MethodPost, "/projects", bytes.NewReader(jsonValue), header, []int{})
if err != nil {
return project, errors.Wrapf(err, "failed to create project %v under %v", projectName, applicationID)
}
err = json.Unmarshal(data, &project)
if err != nil {
return project, errors.Wrapf(err, "failed to unmarshal project data")
}
// since there is a delay to assign a project to an application, adding a check to ensure project is ready after creation
// (if project is not ready, 403 will be returned)
projectID := project.ProjectID
project, err = sys.GetProjectByID(projectID)
if err != nil {
const max_retry = 12 // 3 minutes
const delay = 15
retry_counter := 1
for retry_counter <= max_retry && err != nil {
sys.logger.Debug("Waiting for project assignment to application, retry #", retry_counter)
time.Sleep(delay * time.Second)
retry_counter++
project, err = sys.GetProjectByID(projectID)
}
}
return project, err
}
// New for Cx1
func (sys *SystemInstance) GetUploadURI() (string, error) {
sys.logger.Debug("Retrieving upload URI")
header := http.Header{}
header.Set("Content-Type", "application/json")
resp, err := sendRequest(sys, http.MethodPost, "/uploads", nil, header, []int{})
if err != nil {
return "", errors.Wrap(err, "failed to get an upload uri")
}
responseData := make(map[string]string)
json.Unmarshal(resp, &responseData)
sys.logger.Debugf("Upload URI %s", responseData["url"])
return responseData["url"], nil
}
func (sys *SystemInstance) UploadProjectSourceCode(projectID string, zipFile string) (string, error) {
sys.logger.Debugf("Preparing to upload file %v...", zipFile)
// get URI
uploadUri, err := sys.GetUploadURI()
if err != nil {
return "", err
}
header := http.Header{}
header.Add("Accept-Encoding", "gzip,deflate")
header.Add("Content-Type", "application/zip")
header.Add("Accept", "application/json")
zipContents, err := os.ReadFile(zipFile)
if err != nil {
sys.logger.Error("Failed to Read the File " + zipFile + ": " + err.Error())
return "", err
}
response, err := sendRequestInternal(sys, http.MethodPut, uploadUri, bytes.NewReader(zipContents), header, []int{})
if err != nil {
sys.logger.Errorf("Failed to upload file %v: %s", zipFile, err)
return uploadUri, err
}
sys.logger.Debugf("Upload request response: %v", string(response))
return uploadUri, nil
}
func (sys *SystemInstance) scanProject(scanConfig map[string]interface{}) (Scan, error) {
scan := Scan{}
jsonValue, err := json.Marshal(scanConfig)
header := http.Header{}
header.Set("Content-Type", "application/json")
sys.logger.Tracef("Starting scan with settings: " + string(jsonValue))
data, err := sendRequest(sys, http.MethodPost, "/scans/", bytes.NewBuffer(jsonValue), header, []int{})
if err != nil {
return scan, err
}
err = json.Unmarshal(data, &scan)
return scan, err
}
func (sys *SystemInstance) ScanProjectZip(projectID, sourceUrl, branch string, settings []ScanConfiguration) (Scan, error) {
jsonBody := map[string]interface{}{
"project": map[string]interface{}{"id": projectID},
"type": "upload",
"handler": map[string]interface{}{
"uploadurl": sourceUrl,
"branch": branch,
},
"config": settings,
}
scan, err := sys.scanProject(jsonBody)
if err != nil {
return scan, errors.Wrapf(err, "Failed to start a zip scan for project %v", projectID)
}
return scan, err
}
func (sys *SystemInstance) ScanProjectGit(projectID, repoUrl, branch string, settings []ScanConfiguration) (Scan, error) {
jsonBody := map[string]interface{}{
"project": map[string]interface{}{"id": projectID},
"type": "git",
"handler": map[string]interface{}{
"repoUrl": repoUrl,
"branch": branch,
},
"config": settings,
}
scan, err := sys.scanProject(jsonBody)
if err != nil {
return scan, errors.Wrapf(err, "Failed to start a git scan for project %v", projectID)
}
return scan, err
}
func (sys *SystemInstance) ScanProject(projectID, sourceUrl, branch, scanType string, settings []ScanConfiguration) (Scan, error) {
if scanType == "upload" {
return sys.ScanProjectZip(projectID, sourceUrl, branch, settings)
} else if scanType == "git" {
return sys.ScanProjectGit(projectID, sourceUrl, branch, settings)
}
return Scan{}, errors.New("Invalid scanType provided, must be 'upload' or 'git'")
}
func (sys *SystemInstance) GetPresets() ([]Preset, error) {
sys.logger.Debug("Getting Presets...")
var presets []Preset
data, err := sendRequest(sys, http.MethodGet, "/queries/presets", nil, http.Header{}, []int{})
if err != nil {
sys.logger.Errorf("Fetching presets failed: %s", err)
return presets, err
}
err = json.Unmarshal(data, &presets)
return presets, err
}
func (sys *SystemInstance) GetProjectConfiguration(projectID string) ([]ProjectConfigurationSetting, error) {
sys.logger.Debug("Getting project configuration")