From 6f64d551808707056592b9d1f7855b57d1c5f4dd Mon Sep 17 00:00:00 2001 From: Nikita Pivkin Date: Sat, 11 May 2024 06:01:40 +0600 Subject: [PATCH] fix(misconf): skip Rego errors with a nil location (#6666) --- pkg/iac/rego/load.go | 5 ++++- pkg/iac/rego/load_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/pkg/iac/rego/load.go b/pkg/iac/rego/load.go index 284fd2f653a2..2fd3955ce38f 100644 --- a/pkg/iac/rego/load.go +++ b/pkg/iac/rego/load.go @@ -184,7 +184,7 @@ func (s *Scanner) fallbackChecks(compiler *ast.Compiler) { } compiler.Errors = lo.Filter(compiler.Errors, func(e *ast.Error, _ int) bool { - return !lo.Contains(excludedFiles, e.Location.File) + return e.Location == nil || !lo.Contains(excludedFiles, e.Location.File) }) } @@ -219,6 +219,9 @@ func (s *Scanner) prunePoliciesWithError(compiler *ast.Compiler) error { } for _, e := range compiler.Errors { + if e.Location == nil { + continue + } s.debug.Log("Error occurred while parsing: %s, %s", e.Location.File, e.Error()) delete(s.policies, e.Location.File) } diff --git a/pkg/iac/rego/load_test.go b/pkg/iac/rego/load_test.go index 984fec9c4caf..1658fdefc467 100644 --- a/pkg/iac/rego/load_test.go +++ b/pkg/iac/rego/load_test.go @@ -3,12 +3,14 @@ package rego_test import ( "bytes" "embed" + "fmt" "io" "strings" "testing" "testing/fstest" checks "github.com/aquasecurity/trivy-checks" + "github.com/open-policy-agent/opa/ast" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -208,3 +210,40 @@ deny { }) } } + +func Test_FallbackErrorWithoutLocation(t *testing.T) { + fsys := fstest.MapFS{ + "schemas/fooschema.json": { + Data: []byte(`{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "foo": { + "type": "string" + } + } + }`), + }, + } + + for i := 0; i < ast.CompileErrorLimitDefault+1; i++ { + src := `# METADATA +# schemas: +# - input: schema["fooschema"] +package builtin.test%d + +deny { + input.evil == "foo bar" +}` + fsys[fmt.Sprintf("policies/my-check%d.rego", i)] = &fstest.MapFile{ + Data: []byte(fmt.Sprintf(src, i)), + } + } + + scanner := rego.NewScanner( + types.SourceDockerfile, + options.ScannerWithEmbeddedPolicies(false), + ) + err := scanner.LoadPolicies(false, false, fsys, []string{"."}, nil) + assert.Error(t, err) +}