Skip to content

Commit 16dd986

Browse files
checked-lint
1 parent 74f05d0 commit 16dd986

File tree

5 files changed

+92
-69
lines changed

5 files changed

+92
-69
lines changed

internal/commands/predicates.go

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ func triageShowSubCommand(resultsPredicatesWrapper wrappers.ResultsPredicatesWra
9999
triageShowCmd.PersistentFlags().String(params.ScanTypeFlag, "", "Scan Type")
100100
triageShowCmd.PersistentFlags().StringSlice(params.VulnerabilitiesFlag, []string{}, "List Vulnerabilities string")
101101

102-
// markFlagAsRequired(triageShowCmd, params.SimilarityIDFlag)
103102
markFlagAsRequired(triageShowCmd, params.ProjectIDFlag)
104103
markFlagAsRequired(triageShowCmd, params.ScanTypeFlag)
105104

@@ -158,23 +157,25 @@ func runTriageShow(resultsPredicatesWrapper wrappers.ResultsPredicatesWrapper) f
158157
}
159158

160159
if strings.EqualFold(scanType, params.ScaType) {
161-
//SCA
160+
// SCA
162161
if len(vulnerabilityDetails) == 0 {
163162
return errors.Errorf("%s", "Failed showing the predicate. Vulnerabilities are required for SCA triage")
164163
}
165164
scaResponse, err := resultsPredicatesWrapper.ScaPredicateResult(vulnerabilityDetails, projectID)
166165
if err != nil {
167166
return errors.Wrapf(err, "%s", "Failed showing the predicate")
168167
}
169-
err = printByFormat(cmd, toScaPredicateResultView(*scaResponse))
168+
err = printByFormat(cmd, toScaPredicateResultView(scaResponse))
170169
if err != nil {
171170
return err
172171
}
173172
return nil
174173
} else {
175-
//other than SCA
174+
// other than SCA
176175
predicatesCollection, errorModel, err = resultsPredicatesWrapper.GetAllPredicatesForSimilarityID(similarityID, projectID, scanType)
177-
176+
if err != nil {
177+
return errors.Wrapf(err, "%s", "Failed showing the predicate")
178+
}
178179
// Checking the response
179180
if errorModel != nil {
180181
return errors.Errorf(
@@ -227,7 +228,7 @@ func runTriageUpdate(resultsPredicatesWrapper wrappers.ResultsPredicatesWrapper,
227228
}
228229
}
229230

230-
func preparePredicateRequest(vulnerabilityDetails []string, similarityID string, projectID string, severity string, state string, customStateID int, comment string, scanType string) (interface{}, error) {
231+
func preparePredicateRequest(vulnerabilityDetails []string, similarityID, projectID, severity, state string, customStateID int, comment, scanType string) (interface{}, error) {
231232
scanType = strings.ToLower(scanType)
232233
scanType = strings.TrimSpace(scanType)
233234
if strings.EqualFold(scanType, Sca) {
@@ -270,13 +271,13 @@ func transformState(state string) string {
270271
return ""
271272
}
272273

273-
func prepareScaTriagePayload(vulnerabilityDetails []string, comment string, state string, projectId string) (interface{}, error) {
274+
func prepareScaTriagePayload(vulnerabilityDetails []string, comment, state, projectID string) (interface{}, error) {
274275
if len(vulnerabilityDetails) == 0 {
275276
return nil, errors.Errorf("Vulnerabilities details are required.")
276277
}
277278
scaTriageInfo := make(map[string]interface{})
278279
for _, vulnerability := range vulnerabilityDetails {
279-
vulnerabilityKeyVal := strings.SplitN(vulnerability, "=", 2)
280+
vulnerabilityKeyVal := strings.Split(vulnerability, "=")
280281
err := validateVulnerabilityDetails(vulnerabilityKeyVal)
281282
if err != nil {
282283
return nil, err
@@ -295,7 +296,7 @@ func prepareScaTriagePayload(vulnerabilityDetails []string, comment string, stat
295296
return nil, errors.Errorf("Package manager is required")
296297
}
297298

298-
scaTriageInfo["projectIds"] = []string{projectId}
299+
scaTriageInfo["projectIds"] = []string{projectID}
299300
actionInfo := make(map[string]interface{})
300301
actionInfo["actionType"] = params.ChangeState
301302
actionInfo["value"] = state
@@ -307,7 +308,7 @@ func prepareScaTriagePayload(vulnerabilityDetails []string, comment string, stat
307308
return nil, errors.Errorf("Failed to prepare SCA triage request")
308309
}
309310
payload := wrappers.ScaPredicateRequest{}
310-
err = json.Unmarshal(b, payload)
311+
err = json.Unmarshal(b, &payload)
311312
if err != nil {
312313
logger.PrintIfVerbose(fmt.Sprintf("Failed to deserialize vulnerabilities %s", string(b)))
313314
return nil, errors.Errorf("Failed to prepare SCA triage request")
@@ -319,9 +320,6 @@ func validateVulnerabilityDetails(vulnerability []string) error {
319320
if len(vulnerability) != params.KeyValuePairSize {
320321
return errors.Errorf("Invalid vulnerabilities. It should be in a KEY=VALUE format")
321322
}
322-
if len(strings.Split(vulnerability[1], ",")) > params.SingleValueSize || len(strings.Split(vulnerability[1], ",")) > params.SingleValueSize {
323-
return errors.Errorf("Cannot specify multiple values to key %s", vulnerability[0])
324-
}
325323
return nil
326324
}
327325

@@ -397,12 +395,12 @@ type scaPredicateResultView struct {
397395
CreatedAt time.Time `format:"name:Created at;time:01-02-06 15:04:05"`
398396
}
399397

400-
func toScaPredicateResultView(scaPredicateResult wrappers.ScaPredicateResult) []scaPredicateResultView {
398+
func toScaPredicateResultView(scaPredicateResult *wrappers.ScaPredicateResult) []scaPredicateResultView {
401399
view := []scaPredicateResultView{}
402400
if len(scaPredicateResult.Actions) > 0 {
403401
for _, action := range scaPredicateResult.Actions {
404402
view = append(view, scaPredicateResultView{
405-
VulnerabilityID: scaPredicateResult.Context.VulnerabilityId,
403+
VulnerabilityID: scaPredicateResult.Context.VulnerabilityID,
406404
PackageName: scaPredicateResult.Context.PackageName,
407405
PackageVersion: scaPredicateResult.Context.PackageVersion,
408406
PackageManager: scaPredicateResult.Context.PackageManager,

internal/commands/predicates_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ func TestPrepareScaTriagePayload(t *testing.T) {
347347
vulnerabilityDetails []string
348348
comment string
349349
state string
350-
projectId string
350+
projectID string
351351
expectedError string
352352
}{
353353
{
@@ -359,7 +359,7 @@ func TestPrepareScaTriagePayload(t *testing.T) {
359359
},
360360
comment: "Testing missing package name",
361361
state: "NOT_EXPLOITABLE",
362-
projectId: "test-project-123",
362+
projectID: "test-project-123",
363363
expectedError: "Package name is required",
364364
},
365365
{
@@ -371,7 +371,7 @@ func TestPrepareScaTriagePayload(t *testing.T) {
371371
},
372372
comment: "Testing missing package version",
373373
state: "NOT_EXPLOITABLE",
374-
projectId: "test-project-123",
374+
projectID: "test-project-123",
375375
expectedError: "Package version is required",
376376
},
377377
{
@@ -383,7 +383,7 @@ func TestPrepareScaTriagePayload(t *testing.T) {
383383
},
384384
comment: "Testing missing package manager",
385385
state: "NOT_EXPLOITABLE",
386-
projectId: "test-project-123",
386+
projectID: "test-project-123",
387387
expectedError: "Package manager is required",
388388
},
389389
{
@@ -395,15 +395,15 @@ func TestPrepareScaTriagePayload(t *testing.T) {
395395
},
396396
comment: "Testing invalid format",
397397
state: "NOT_EXPLOITABLE",
398-
projectId: "test-project-123",
398+
projectID: "test-project-123",
399399
expectedError: "Invalid vulnerabilities. It should be in a KEY=VALUE format",
400400
},
401401
}
402402

403403
for _, tt := range tests {
404404
tt := tt
405405
t.Run(tt.name, func(t *testing.T) {
406-
payload, err := prepareScaTriagePayload(tt.vulnerabilityDetails, tt.comment, tt.state, tt.projectId)
406+
payload, err := prepareScaTriagePayload(tt.vulnerabilityDetails, tt.comment, tt.state, tt.projectID)
407407
if tt.expectedError != "" {
408408
assert.ErrorContains(t, err, tt.expectedError)
409409
} else {
@@ -454,9 +454,9 @@ func TestToScaPredicateResultView(t *testing.T) {
454454
createdAt1, _ := time.Parse(time.RFC3339, "2024-01-15T10:00:00Z")
455455
createdAt2, _ := time.Parse(time.RFC3339, "2024-01-16T12:00:00Z")
456456

457-
scaPredicateResult := wrappers.ScaPredicateResult{
457+
scaPredicateResult := &wrappers.ScaPredicateResult{
458458
Context: wrappers.Context{
459-
VulnerabilityId: "CVE-2021-23337",
459+
VulnerabilityID: "CVE-2021-23337",
460460
PackageName: "lodash",
461461
PackageVersion: "4.17.20",
462462
PackageManager: "npm",
@@ -505,9 +505,9 @@ func TestToScaPredicateResultView(t *testing.T) {
505505

506506
func TestToScaPredicateResultView_EmptyActions(t *testing.T) {
507507
// Arrange: Create SCA predicate result with no actions
508-
scaPredicateResult := wrappers.ScaPredicateResult{
508+
scaPredicateResult := &wrappers.ScaPredicateResult{
509509
Context: wrappers.Context{
510-
VulnerabilityId: "CVE-2021-23337",
510+
VulnerabilityID: "CVE-2021-23337",
511511
PackageName: "lodash",
512512
PackageVersion: "4.17.20",
513513
PackageManager: "npm",

internal/wrappers/mock/predicates-mock.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func (r ResultsPredicatesWrapper) GetAllPredicatesForSimilarityID(similarityID,
4444
}, nil, nil
4545
}
4646

47-
func (r ResultsPredicatesWrapper) ScaPredicateResult(vulnerabilityDetails []string, projectId string) (*wrappers.ScaPredicateResult, error) {
47+
func (r ResultsPredicatesWrapper) ScaPredicateResult(vulnerabilityDetails []string, projectID string) (*wrappers.ScaPredicateResult, error) {
4848
fmt.Println("Called 'ScaPredicateResult' in ResultsPredicatesMockWrapper")
4949
return nil, nil
5050
}

internal/wrappers/predicates-http.go

Lines changed: 65 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"encoding/json"
66
"fmt"
7+
"io"
78
"net/http"
89
"strings"
910

@@ -26,18 +27,21 @@ func NewResultsPredicatesHTTPWrapper() ResultsPredicatesWrapper {
2627
return &ResultsPredicatesHTTPWrapper{}
2728
}
2829

29-
func (r *ResultsPredicatesHTTPWrapper) ScaPredicateResult(vulnerabilityDetails []string, projectId string) (*ScaPredicateResult, error) {
30+
func (r *ResultsPredicatesHTTPWrapper) ScaPredicateResult(vulnerabilityDetails []string, projectID string) (*ScaPredicateResult, error) {
3031
clientTimeout := viper.GetUint(params.ClientTimeoutKey)
3132
r.SetPath(viper.GetString(params.ScaResultsPredicatesPathEnv))
3233
var request = "/entity-profile/search"
3334
logger.PrintIfVerbose(fmt.Sprintf("Sending POST request to %s", r.path+request))
3435

3536
scaPredicateRequest := make(map[string]interface{})
3637
for _, vulnerability := range vulnerabilityDetails {
37-
vulnerabilityKeyVal := strings.SplitN(vulnerability, "=", 2)
38+
vulnerabilityKeyVal := strings.Split(vulnerability, "=")
39+
if len(vulnerabilityKeyVal) != params.KeyValuePairSize {
40+
return nil, errors.Errorf("Invalid vulnerability details format: %s", vulnerability)
41+
}
3842
scaPredicateRequest[vulnerabilityKeyVal[0]] = vulnerabilityKeyVal[1]
3943
}
40-
scaPredicateRequest["projectId"] = projectId
44+
scaPredicateRequest["projectId"] = projectID
4145
scaPredicateRequest["actionType"] = params.ChangeState
4246
jsonBody, err := json.Marshal(scaPredicateRequest)
4347
if err != nil {
@@ -55,7 +59,6 @@ func (r *ResultsPredicatesHTTPWrapper) ScaPredicateResult(vulnerabilityDetails [
5559
if resp.StatusCode != http.StatusOK {
5660
return nil, errors.Errorf("Failed to get SCA predicate result.")
5761
}
58-
fmt.Println("HM Response: ", resp.Body)
5962
decoder := json.NewDecoder(resp.Body)
6063
var scaPredicates ScaPredicateResult
6164
err = decoder.Decode(&scaPredicates)
@@ -147,27 +150,16 @@ func (r ResultsPredicatesHTTPWrapper) PredicateSeverityAndState(predicate interf
147150
*WebError, error,
148151
) {
149152
clientTimeout := viper.GetUint(params.ClientTimeoutKey)
150-
var predicateModel interface{}
151-
if !strings.EqualFold(strings.TrimSpace(scanType), params.ScaType) {
152-
predicateModel = []interface{}{predicate}
153-
} else {
154-
predicateModel = predicate
155-
}
153+
154+
predicateModel := preparePredicateModel(predicate, scanType)
156155
jsonBytes, err := json.Marshal(predicateModel)
157156
if err != nil {
158157
return nil, err
159158
}
160-
var triageAPIPath string
161-
if strings.EqualFold(strings.TrimSpace(scanType), params.SastType) {
162-
triageAPIPath = viper.GetString(params.SastResultsPredicatesPathKey)
163-
} else if strings.EqualFold(strings.TrimSpace(scanType), params.KicsType) || strings.EqualFold(strings.TrimSpace(scanType), params.IacType) {
164-
triageAPIPath = viper.GetString(params.KicsResultsPredicatesPathKey)
165-
} else if strings.EqualFold(strings.TrimSpace(scanType), params.ScsType) {
166-
triageAPIPath = viper.GetString(params.ScsResultsWritePredicatesPathKey)
167-
} else if strings.EqualFold(strings.TrimSpace(scanType), params.ScaType) {
168-
triageAPIPath = viper.GetString(params.ScaResultsPredicatesPathEnv)
169-
} else {
170-
return nil, errors.Errorf(invalidScanType, scanType)
159+
160+
triageAPIPath, err := getTriageAPIPath(scanType)
161+
if err != nil {
162+
return nil, err
171163
}
172164

173165
logger.PrintIfVerbose(fmt.Sprintf("Sending POST request to %s", triageAPIPath))
@@ -186,38 +178,71 @@ func (r ResultsPredicatesHTTPWrapper) PredicateSeverityAndState(predicate interf
186178
_ = resp.Body.Close()
187179
}()
188180

189-
// in case of ne/pne when mandatory comment arent provided, cli is not transforming error message
181+
if err := checkMandatoryCommentError(resp.Body, scanType); err != nil {
182+
return nil, err
183+
}
184+
185+
return nil, handlePredicateStatusCode(resp.StatusCode)
186+
}
187+
188+
func preparePredicateModel(predicate interface{}, scanType string) interface{} {
189+
if !strings.EqualFold(strings.TrimSpace(scanType), params.ScaType) {
190+
return []interface{}{predicate}
191+
}
192+
return predicate
193+
}
194+
195+
func getTriageAPIPath(scanType string) (string, error) {
196+
ScanType := strings.ToLower(strings.TrimSpace(scanType))
197+
198+
switch ScanType {
199+
case strings.ToLower(params.SastType):
200+
return viper.GetString(params.SastResultsPredicatesPathKey), nil
201+
case strings.ToLower(params.KicsType), strings.ToLower(params.IacType):
202+
return viper.GetString(params.KicsResultsPredicatesPathKey), nil
203+
case strings.ToLower(params.ScsType):
204+
return viper.GetString(params.ScsResultsWritePredicatesPathKey), nil
205+
case strings.ToLower(params.ScaType):
206+
return viper.GetString(params.ScaResultsPredicatesPathEnv), nil
207+
default:
208+
return "", errors.Errorf(invalidScanType, scanType)
209+
}
210+
}
211+
212+
func checkMandatoryCommentError(body io.ReadCloser, scanType string) error {
190213
responseMap := make(map[string]interface{})
191-
if err := json.NewDecoder(resp.Body).Decode(&responseMap); err != nil {
192-
if scanType != params.ScaType { // for sca, we are not getting any response in the response body, so we are not logging the error
214+
if err := json.NewDecoder(body).Decode(&responseMap); err != nil {
215+
if scanType != params.ScaType {
193216
logger.PrintIfVerbose(fmt.Sprintf("failed to read the response, %v", err.Error()))
194217
}
195-
} else {
196-
if val, ok := responseMap["code"].(float64); ok {
197-
if val == 4002 && responseMap["message"] != nil {
198-
if errMsg, ok := responseMap["message"].(string); ok {
199-
if errMsg == "A comment is required to make changes to the result state" {
200-
return nil, errors.Errorf(errMsg)
201-
}
202-
}
218+
return nil
219+
}
220+
221+
if val, ok := responseMap["code"].(float64); ok && val == 4002 {
222+
if errMsg, ok := responseMap["message"].(string); ok {
223+
if errMsg == "A comment is required to make changes to the result state" {
224+
return errors.Errorf(errMsg)
203225
}
204226
}
205227
}
228+
return nil
229+
}
206230

207-
switch resp.StatusCode {
208-
case http.StatusBadRequest, http.StatusInternalServerError:
209-
return nil, errors.Errorf("Predicate bad request.")
231+
func handlePredicateStatusCode(statusCode int) error {
232+
switch statusCode {
210233
case http.StatusOK, http.StatusCreated:
211234
fmt.Println("Predicate updated successfully.")
212-
return nil, nil
235+
return nil
213236
case http.StatusNotModified:
214-
return nil, errors.Errorf("No changes to update.")
237+
return errors.Errorf("No changes to update.")
215238
case http.StatusForbidden:
216-
return nil, errors.Errorf("No permission to update predicate.")
239+
return errors.Errorf("No permission to update predicate.")
217240
case http.StatusNotFound:
218-
return nil, errors.Errorf("Predicate not found.")
241+
return errors.Errorf("Predicate not found.")
242+
case http.StatusBadRequest, http.StatusInternalServerError:
243+
return errors.Errorf("Predicate bad request.")
219244
default:
220-
return nil, errors.Errorf("response status code %d", resp.StatusCode)
245+
return errors.Errorf("response status code %d", statusCode)
221246
}
222247
}
223248

internal/wrappers/predicates.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ type ScaPredicateRequest struct {
2626
PackageName string `json:"packageName"`
2727
PackageVersion string `json:"packageVersion"`
2828
PackageManager string `json:"packageManager"`
29-
VulnerabilityId string `json:"vulnerabilityId"`
29+
VulnerabilityID string `json:"vulnerabilityId"`
3030
ProjectIds []string `json:"projectIds"`
3131
Actions []ScaAction `json:"actions"`
3232
}
@@ -81,7 +81,7 @@ type Context struct {
8181
PackageManager string `json:"PackageManager"`
8282
PackageName string `json:"PackageName"`
8383
PackageVersion string `json:"PackageVersion"`
84-
VulnerabilityId string `json:"VulnerabilityId"`
84+
VulnerabilityID string `json:"VulnerabilityId"`
8585
}
8686

8787
type Action struct {
@@ -104,7 +104,7 @@ type CustomStatesWrapper interface {
104104
}
105105

106106
type ResultsPredicatesWrapper interface {
107-
ScaPredicateResult(vulnerabilityDetails []string, projectId string) (*ScaPredicateResult, error)
107+
ScaPredicateResult(vulnerabilityDetails []string, projectID string) (*ScaPredicateResult, error)
108108
PredicateSeverityAndState(predicate interface{}, scanType string) (*WebError, error)
109109
GetAllPredicatesForSimilarityID(
110110
similarityID string, projectID string, scannerType string,

0 commit comments

Comments
 (0)