From 413766d4230709504e67625f0ec6c030ed99bda5 Mon Sep 17 00:00:00 2001 From: nikpivkin Date: Fri, 19 Apr 2024 21:36:47 +0700 Subject: [PATCH] refactor(misconf): improve error handling in the Rego scanner --- pkg/iac/rego/scanner.go | 10 ++++++++-- pkg/iac/rego/scanner_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/pkg/iac/rego/scanner.go b/pkg/iac/rego/scanner.go index aff5813d191b..6c1fc04c5065 100644 --- a/pkg/iac/rego/scanner.go +++ b/pkg/iac/rego/scanner.go @@ -241,7 +241,10 @@ func (s *Scanner) ScanInput(ctx context.Context, inputs ...Input) (scan.Results, staticMeta, err := s.retriever.RetrieveMetadata(ctx, module, GetInputsContents(inputs)...) if err != nil { - return nil, err + s.debug.Log( + "Error occurred while retrieving metadata from check %q: %s", + module.Package.Location.File, err) + continue } if isPolicyWithSubtype(s.sourceType) { @@ -267,7 +270,10 @@ func (s *Scanner) ScanInput(ctx context.Context, inputs ...Input) (scan.Results, if isEnforcedRule(ruleName) { ruleResults, err := s.applyRule(ctx, namespace, ruleName, inputs, staticMeta.InputOptions.Combined) if err != nil { - return nil, err + s.debug.Log( + "Error occurred while applying rule %q from check %q: %s", + ruleName, module.Package.Location.File, err) + continue } results = append(results, s.embellishResultsWithRuleMetadata(ruleResults, *staticMeta)...) } diff --git a/pkg/iac/rego/scanner_test.go b/pkg/iac/rego/scanner_test.go index 5a2c96ccb13e..d2868764eda8 100644 --- a/pkg/iac/rego/scanner_test.go +++ b/pkg/iac/rego/scanner_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "testing" + "testing/fstest" "github.com/aquasecurity/trivy/pkg/iac/severity" "github.com/aquasecurity/trivy/pkg/iac/types" @@ -976,3 +977,37 @@ deny { assert.Equal(t, 0, len(results.GetPassed())) assert.Equal(t, 0, len(results.GetIgnored())) } + +func Test_NoErrorsWhenUsingBadRegoCheck(t *testing.T) { + + // this check cause eval_conflict_error + // https://www.openpolicyagent.org/docs/latest/policy-language/#functions + fsys := fstest.MapFS{ + "checks/bad.rego": { + Data: []byte(`package defsec.test + +p(x) = y { + y := x[_] +} + +deny { + p([1, 2, 3]) +} +`), + }, + } + + var buf bytes.Buffer + scanner := NewScanner( + types.SourceYAML, + options.ScannerWithDebug(&buf), + ) + require.NoError( + t, + scanner.LoadPolicies(false, false, fsys, []string{"checks"}, nil), + ) + _, err := scanner.ScanInput(context.TODO(), Input{}) + assert.NoError(t, err) + assert.Contains(t, buf.String(), + `Error occurred while applying rule "deny" from check "checks/bad.rego"`) +}