From 6109e6a222b77f88f08a64124f4f5f87986364fb Mon Sep 17 00:00:00 2001 From: Johan Fylling Date: Thu, 25 May 2023 19:38:21 +0200 Subject: [PATCH] Aborting query-eval if the compiler has errors (#5949) Fixes: #5947 Signed-off-by: Johan Fylling --- topdown/query.go | 8 ++++++++ topdown/query_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/topdown/query.go b/topdown/query.go index 6d5bb4b197..2b540c58a5 100644 --- a/topdown/query.go +++ b/topdown/query.go @@ -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 } diff --git a/topdown/query_test.go b/topdown/query_test.go index 9e8760b362..68ed4ee8d8 100644 --- a/topdown/query_test.go +++ b/topdown/query_test.go @@ -7,6 +7,7 @@ package topdown import ( "context" "reflect" + "strings" "testing" "github.com/open-policy-agent/opa/ast" @@ -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()