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

fix(misconf): skip Rego errors with a nil location #6666

Merged
merged 1 commit into from
May 11, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion pkg/iac/rego/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}

Expand Down Expand Up @@ -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)
}
Expand Down
39 changes: 39 additions & 0 deletions pkg/iac/rego/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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)
}