Skip to content

Commit

Permalink
fix(misconf): skip Rego errors with a nil location (#6666)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikpivkin authored and knqyf263 committed May 20, 2024
1 parent 8c27430 commit 6f64d55
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
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)
}

0 comments on commit 6f64d55

Please sign in to comment.