Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(misconf): improve error handling in the Rego scanner #6527

Merged
merged 1 commit into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions pkg/iac/rego/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)...)
}
Expand Down
35 changes: 35 additions & 0 deletions pkg/iac/rego/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"`)
}