Skip to content

Commit

Permalink
Aborting query-eval if the compiler has errors (#5949)
Browse files Browse the repository at this point in the history
Fixes: #5947

Signed-off-by: Johan Fylling <[email protected]>
  • Loading branch information
johanfylling authored May 25, 2023
1 parent d3811e2 commit 6109e6a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions topdown/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,14 @@ func (q *Query) Run(ctx context.Context) (QueryResultSet, error) {
// Iter executes the query and invokes the iter function with query results
// produced by evaluating the query.
func (q *Query) Iter(ctx context.Context, iter func(QueryResult) error) error {
// Query evaluation must not be allowed if the compiler has errors and is in an undefined, possibly inconsistent state
if q.compiler != nil && len(q.compiler.Errors) > 0 {
return &Error{
Code: InternalErr,
Message: "compiler has errors",
}
}

if q.seed == nil {
q.seed = rand.Reader
}
Expand Down
30 changes: 30 additions & 0 deletions topdown/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package topdown
import (
"context"
"reflect"
"strings"
"testing"

"github.com/open-policy-agent/opa/ast"
Expand Down Expand Up @@ -214,6 +215,35 @@ func TestRegoMetadataBuiltinCall(t *testing.T) {
}
}

func TestWithCompilerErrors(t *testing.T) {
store := inmem.New()
ctx := context.Background()
txn := storage.NewTransactionOrDie(ctx, store)
defer store.Abort(ctx, txn)

// Policy with reference to non-existing function
modules := map[string]*ast.Module{
"tst": ast.MustParseModule(`package test
p := data.q(42)`),
}

c := ast.NewCompiler()
c.Compile(modules)
q := NewQuery(ast.MustParseBody("data.a = 1")).
WithCompiler(c).
WithStore(store).
WithTransaction(txn)

_, err := q.Run(context.Background())
if err == nil {
t.Fatalf("expected error, got nil")
}
expected := "eval_internal_error: compiler has errors"
if !strings.Contains(err.Error(), expected) {
t.Fatalf("expected error to contain '%s', got: %v", expected, err)
}
}

func initTracerTestQuery() *Query {
ctx := context.Background()
store := inmem.New()
Expand Down

0 comments on commit 6109e6a

Please sign in to comment.