topdown

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 21, 2025 License: Apache-2.0 Imports: 73 Imported by: 6

Documentation

Overview

Package topdown provides low-level query evaluation support.

The topdown implementation is a modified version of the standard top-down evaluation algorithm used in Datalog. References and comprehensions are evaluated eagerly while all other terms are evaluated lazily.

Index

Examples

Constants

View Source
const (

	// InternalErr represents an unknown evaluation error.
	InternalErr string = "eval_internal_error"

	// CancelErr indicates the evaluation process was cancelled.
	CancelErr string = "eval_cancel_error"

	// ConflictErr indicates a conflict was encountered during evaluation. For
	// instance, a conflict occurs if a rule produces multiple, differing values
	// for the same key in an object. Conflict errors indicate the policy does
	// not account for the data loaded into the policy engine.
	ConflictErr string = "eval_conflict_error"

	// TypeErr indicates evaluation stopped because an expression was applied to
	// a value of an inappropriate type.
	TypeErr string = "eval_type_error"

	// BuiltinErr indicates a built-in function received a semantically invalid
	// input or encountered some kind of runtime error, e.g., connection
	// timeout, connection refused, etc.
	BuiltinErr string = "eval_builtin_error"

	// WithMergeErr indicates that the real and replacement data could not be merged.
	WithMergeErr string = "eval_with_merge_error"
)
View Source
const (

	// HTTPSendInternalErr represents a runtime evaluation error.
	HTTPSendInternalErr string = "eval_http_send_internal_error"

	// HTTPSendNetworkErr represents a network error.
	HTTPSendNetworkErr string = "eval_http_send_network_error"
)

Variables

This section is empty.

Functions

func IsCancel

func IsCancel(err error) bool

IsCancel returns true if err was caused by cancellation.

func IsError

func IsError(err error) bool

IsError returns true if the err is an Error.

func NewPrintHook

func NewPrintHook(w io.Writer) print.Hook

func PrettyEvent

func PrettyEvent(w io.Writer, e *Event, opts PrettyEventOpts) error

func PrettyTrace

func PrettyTrace(w io.Writer, trace []*Event)

PrettyTrace pretty prints the trace to the writer.

func PrettyTraceWithLocation

func PrettyTraceWithLocation(w io.Writer, trace []*Event)

PrettyTraceWithLocation prints the trace to the writer and includes location information

func PrettyTraceWithOpts

func PrettyTraceWithOpts(w io.Writer, trace []*Event, opts PrettyTraceOptions)

func RegisterBuiltinFunc

func RegisterBuiltinFunc(name string, f BuiltinFunc)

RegisterBuiltinFunc adds a new built-in function to the evaluation engine.

func RegisterFunctionalBuiltin1 deprecated

func RegisterFunctionalBuiltin1(name string, fun FunctionalBuiltin1)

Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead.

func RegisterFunctionalBuiltin2 deprecated

func RegisterFunctionalBuiltin2(name string, fun FunctionalBuiltin2)

Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead.

func RegisterFunctionalBuiltin3 deprecated

func RegisterFunctionalBuiltin3(name string, fun FunctionalBuiltin3)

Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead.

func RegisterFunctionalBuiltin4 deprecated

func RegisterFunctionalBuiltin4(name string, fun FunctionalBuiltin4)

Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead.

Types

type BufferTracer

type BufferTracer []*Event

BufferTracer implements the Tracer and QueryTracer interface by simply buffering all events received.

func NewBufferTracer

func NewBufferTracer() *BufferTracer

NewBufferTracer returns a new BufferTracer.

func (*BufferTracer) Config

func (b *BufferTracer) Config() TraceConfig

Config returns the Tracers standard configuration

func (*BufferTracer) Enabled

func (b *BufferTracer) Enabled() bool

Enabled always returns true if the BufferTracer is instantiated.

func (*BufferTracer) Trace

func (b *BufferTracer) Trace(evt *Event)

Trace adds the event to the buffer. Deprecated: Use TraceEvent instead.

func (*BufferTracer) TraceEvent

func (b *BufferTracer) TraceEvent(evt Event)

TraceEvent adds the event to the buffer.

type Builtin

type Builtin struct {
	Decl *ast.Builtin
	Func BuiltinFunc
}

Builtin represents a built-in function that queries can call.

type BuiltinContext

type BuiltinContext struct {
	Context                     context.Context            // request context that was passed when query started
	Metrics                     metrics.Metrics            // metrics registry for recording built-in specific metrics
	Seed                        io.Reader                  // randomization source
	Time                        *ast.Term                  // wall clock time
	Cancel                      Cancel                     // atomic value that signals evaluation to halt
	Runtime                     *ast.Term                  // runtime information on the OPA instance
	Cache                       builtins.Cache             // built-in function state cache
	InterQueryBuiltinCache      cache.InterQueryCache      // cross-query built-in function state cache
	InterQueryBuiltinValueCache cache.InterQueryValueCache // cross-query built-in function state value cache. this cache is useful for scenarios where the entry size cannot be calculated
	NDBuiltinCache              builtins.NDBCache          // cache for non-deterministic built-in state
	Location                    *ast.Location              // location of built-in call
	Tracers                     []Tracer                   // Deprecated: Use QueryTracers instead
	QueryTracers                []QueryTracer              // tracer objects for trace() built-in function
	TraceEnabled                bool                       // indicates whether tracing is enabled for the evaluation
	QueryID                     uint64                     // identifies query being evaluated
	ParentID                    uint64                     // identifies parent of query being evaluated
	PrintHook                   print.Hook                 // provides callback function to use for printing
	RoundTripper                CustomizeRoundTripper      // customize transport to use for HTTP requests
	DistributedTracingOpts      tracing.Options            // options to be used by distributed tracing.

	Capabilities *ast.Capabilities
	// contains filtered or unexported fields
}

BuiltinContext contains context from the evaluator that may be used by built-in functions.

func (*BuiltinContext) Rand

func (bctx *BuiltinContext) Rand() (*rand.Rand, error)

Rand returns a random number generator based on the Seed for this built-in context. The random number will be re-used across multiple calls to this function. If a random number generator cannot be created, an error is returned.

type BuiltinEmpty deprecated

type BuiltinEmpty struct{}

Deprecated: The BuiltinEmpty type is no longer needed. Use nil return values instead.

func (BuiltinEmpty) Error

func (BuiltinEmpty) Error() string

type BuiltinFunc

type BuiltinFunc func(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error

BuiltinFunc defines an interface for implementing built-in functions. The built-in function is called with the plugged operands from the call (including the output operands.) The implementation should evaluate the operands and invoke the iterator for each successful/defined output value.

func GetBuiltin

func GetBuiltin(name string) BuiltinFunc

GetBuiltin returns a built-in function implementation, nil if no built-in found.

type Cancel

type Cancel interface {
	Cancel()
	Cancelled() bool
}

Cancel defines the interface for cancelling topdown queries. Cancel operations are thread-safe and idempotent.

func NewCancel

func NewCancel() Cancel

NewCancel returns a new Cancel object.

type CustomizeRoundTripper

type CustomizeRoundTripper func(*http.Transport) http.RoundTripper

CustomizeRoundTripper allows customizing an existing http.Transport, to the returned value, which could be the same Transport or a new one.

type Error

type Error struct {
	Code     string        `json:"code"`
	Message  string        `json:"message"`
	Location *ast.Location `json:"location,omitempty"`
	// contains filtered or unexported fields
}

Error is the error type returned by the Eval and Query functions when an evaluation error occurs.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is allows matching topdown errors using errors.Is (see IsCancel).

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) Wrap

func (e *Error) Wrap(err error) *Error

type Event

type Event struct {
	Op            Op                      // Identifies type of event.
	Node          ast.Node                // Contains AST node relevant to the event.
	Location      *ast.Location           // The location of the Node this event relates to.
	QueryID       uint64                  // Identifies the query this event belongs to.
	ParentID      uint64                  // Identifies the parent query this event belongs to.
	Locals        *ast.ValueMap           // Contains local variable bindings from the query context. Nil if variables were not included in the trace event.
	LocalMetadata map[ast.Var]VarMetadata // Contains metadata for the local variable bindings. Nil if variables were not included in the trace event.
	Message       string                  // Contains message for Note events.
	Ref           *ast.Ref                // Identifies the subject ref for the event. Only applies to Index and Wasm operations.
	// contains filtered or unexported fields
}

Event contains state associated with a tracing event.

func (*Event) Equal

func (evt *Event) Equal(other *Event) bool

Equal returns true if this event is equal to the other event.

func (*Event) HasBody

func (evt *Event) HasBody() bool

HasBody returns true if the Event contains an ast.Body.

func (*Event) HasExpr

func (evt *Event) HasExpr() bool

HasExpr returns true if the Event contains an ast.Expr.

func (*Event) HasRule

func (evt *Event) HasRule() bool

HasRule returns true if the Event contains an ast.Rule.

func (*Event) Input

func (evt *Event) Input() *ast.Term

Input returns the input object as it was at the event.

func (*Event) Plug

func (evt *Event) Plug(term *ast.Term) *ast.Term

Plug plugs event bindings into the provided ast.Term. Because bindings are mutable, this only makes sense to do when the event is emitted rather than on recorded trace events as the bindings are going to be different by then.

func (*Event) String

func (evt *Event) String() string

func (*Event) WithInput

func (evt *Event) WithInput(input *ast.Term) *Event

type FunctionalBuiltin1 deprecated

type FunctionalBuiltin1 func(op1 ast.Value) (output ast.Value, err error)

Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead.

type FunctionalBuiltin2 deprecated

type FunctionalBuiltin2 func(op1, op2 ast.Value) (output ast.Value, err error)

Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead.

type FunctionalBuiltin3 deprecated

type FunctionalBuiltin3 func(op1, op2, op3 ast.Value) (output ast.Value, err error)

Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead.

type FunctionalBuiltin4 deprecated

type FunctionalBuiltin4 func(op1, op2, op3, op4 ast.Value) (output ast.Value, err error)

Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead.

type Halt

type Halt struct {
	Err error
}

Halt is a special error type that built-in function implementations return to indicate that policy evaluation should stop immediately.

func (Halt) Error

func (h Halt) Error() string

func (Halt) Unwrap

func (h Halt) Unwrap() error

type Instrumentation

type Instrumentation struct {
	// contains filtered or unexported fields
}

Instrumentation implements helper functions to instrument query evaluation to diagnose performance issues. Instrumentation may be expensive in some cases, so it is disabled by default.

func NewInstrumentation

func NewInstrumentation(m metrics.Metrics) *Instrumentation

NewInstrumentation returns a new Instrumentation object. Performance diagnostics recorded on this Instrumentation object will stored in m.

type JSONWebToken

type JSONWebToken struct {
	// contains filtered or unexported fields
}

JSONWebToken represent the 3 parts (header, payload & signature) of

a JWT in Base64.

type Op

type Op string

Op defines the types of tracing events.

const (
	// EnterOp is emitted when a new query is about to be evaluated.
	EnterOp Op = "Enter"

	// ExitOp is emitted when a query has evaluated to true.
	ExitOp Op = "Exit"

	// EvalOp is emitted when an expression is about to be evaluated.
	EvalOp Op = "Eval"

	// RedoOp is emitted when an expression, rule, or query is being re-evaluated.
	RedoOp Op = "Redo"

	// SaveOp is emitted when an expression is saved instead of evaluated
	// during partial evaluation.
	SaveOp Op = "Save"

	// FailOp is emitted when an expression evaluates to false.
	FailOp Op = "Fail"

	// DuplicateOp is emitted when a query has produced a duplicate value. The search
	// will stop at the point where the duplicate was emitted and backtrack.
	DuplicateOp Op = "Duplicate"

	// NoteOp is emitted when an expression invokes a tracing built-in function.
	NoteOp Op = "Note"

	// IndexOp is emitted during an expression evaluation to represent lookup
	// matches.
	IndexOp Op = "Index"

	// WasmOp is emitted when resolving a ref using an external
	// Resolver.
	WasmOp Op = "Wasm"

	// UnifyOp is emitted when two terms are unified.  Node will be set to an
	// equality expression with the two terms.  This Node will not have location
	// info.
	UnifyOp           Op = "Unify"
	FailedAssertionOp Op = "FailedAssertion"
)

type PrettyEventOpts

type PrettyEventOpts struct {
	PrettyVars bool
}

type PrettyTraceOptions

type PrettyTraceOptions struct {
	Locations      bool // Include location information
	ExprVariables  bool // Include variables found in the expression
	LocalVariables bool // Include all local variables
}

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query provides a configurable interface for performing query evaluation.

func NewQuery

func NewQuery(query ast.Body) *Query

NewQuery returns a new Query object that can be run.

func (*Query) Iter

func (q *Query) Iter(ctx context.Context, iter func(QueryResult) error) error

Iter executes the query and invokes the iter function with query results produced by evaluating the query.

Example
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/open-policy-agent/opa/v1/ast"
	"github.com/open-policy-agent/opa/v1/storage/inmem"
	"github.com/open-policy-agent/opa/v1/topdown"
)

func main() {
	// Initialize context for the example. Normally the caller would obtain the
	// context from an input parameter or instantiate their own.
	ctx := context.Background()

	compiler := ast.NewCompiler()

	// Define a dummy query and some data that the query will execute against.
	query, err := compiler.QueryCompiler().Compile(ast.MustParseBody(`data.a[_] = x; x >= 2`))
	if err != nil {
		// Handle error.
	}

	var data map[string]interface{}

	// OPA uses Go's standard JSON library but assumes that numbers have been
	// decoded as json.Number instead of float64. You MUST decode with UseNumber
	// enabled.
	decoder := json.NewDecoder(bytes.NewBufferString(`{"a": [1,2,3,4]}`))
	decoder.UseNumber()

	if err := decoder.Decode(&data); err != nil {
		// Handle error.
	}

	// Instantiate the policy engine's storage layer.
	store := inmem.NewFromObject(data)

	// Create a new transaction. Transactions allow the policy engine to
	// evaluate the query over a consistent snapshot fo the storage layer.
	txn, err := store.NewTransaction(ctx)
	if err != nil {
		// Handle error.
	}

	defer store.Abort(ctx, txn)

	// Prepare the evaluation parameters. Evaluation executes against the policy
	// engine's storage. In this case, we seed the storage with a single array
	// of number. Other parameters such as the input, tracing configuration,
	// etc. can be set on the query object.
	q := topdown.NewQuery(query).
		WithCompiler(compiler).
		WithStore(store).
		WithTransaction(txn)

	result := []interface{}{}

	// Execute the query and provide a callback function to accumulate the results.
	err = q.Iter(ctx, func(qr topdown.QueryResult) error {

		// Each variable in the query will have an associated binding.
		x := qr[ast.Var("x")]

		// The bindings are ast.Value types so we will convert to a native Go value here.
		v, err := ast.JSON(x.Value)
		if err != nil {
			return err
		}

		result = append(result, v)
		return nil
	})

	// Inspect the query result.
	fmt.Println("result:", result)
	fmt.Println("err:", err)

}
Output:

result: [2 3 4]
err: <nil>

func (*Query) PartialRun

func (q *Query) PartialRun(ctx context.Context) (partials []ast.Body, support []*ast.Module, err error)

PartialRun executes partial evaluation on the query with respect to unknown values. Partial evaluation attempts to evaluate as much of the query as possible without requiring values for the unknowns set on the query. The result of partial evaluation is a new set of queries that can be evaluated once the unknown value is known. In addition to new queries, partial evaluation may produce additional support modules that should be used in conjunction with the partially evaluated queries.

Example
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/open-policy-agent/opa/v1/ast"
	"github.com/open-policy-agent/opa/v1/storage/inmem"
	"github.com/open-policy-agent/opa/v1/topdown"
)

func main() {

	// Initialize context for the example. Normally the caller would obtain the
	// context from an input parameter or instantiate their own.
	ctx := context.Background()

	var data map[string]interface{}
	decoder := json.NewDecoder(bytes.NewBufferString(`{
		"roles": [
			{
				"permissions": ["read_bucket"],
				"groups": ["dev", "test", "sre"]
			},
			{
				"permissions": ["write_bucket", "delete_bucket"],
				"groups": ["sre"]
			}
		]
	}`))
	if err := decoder.Decode(&data); err != nil {
		// Handle error.
	}

	// Instantiate the policy engine's storage layer.
	store := inmem.NewFromObject(data)

	// Create a new transaction. Transactions allow the policy engine to
	// evaluate the query over a consistent snapshot fo the storage layer.
	txn, err := store.NewTransaction(ctx)
	if err != nil {
		// Handle error.
	}

	defer store.Abort(ctx, txn)

	// Define policy that searches for roles that match input request. If no
	// roles are found, allow is undefined and the caller will reject the
	// request. This is the user supplied policy that OPA will partially
	// evaluate.
	modules := map[string]*ast.Module{
		"authz.rego": ast.MustParseModule(`
			package example
			import rego.v1

			default allow = false

			allow if {
				role = data.roles[i]
				input.group = role.groups[j]
				input.permission = role.permissions[k]
			}
		`),
	}

	// Compile policy.
	compiler := ast.NewCompiler()
	if compiler.Compile(modules); compiler.Failed() {
		// Handle error.
	}

	// Construct query and mark the entire input document as partial.
	q := topdown.NewQuery(ast.MustParseBody("data.example.allow = true")).
		WithCompiler(compiler).
		WithUnknowns([]*ast.Term{
			ast.MustParseTerm("input"),
		}).
		WithStore(store).
		WithTransaction(txn)

	// Execute partial evaluation.
	partial, _, err := q.PartialRun(ctx)
	if err != nil {
		// Handle error.
	}

	// Show result of partially evaluating the policy.
	fmt.Printf("# partial evaluation result (%d items):\n", len(partial))
	for i := range partial {
		fmt.Println(partial[i])
	}

	// Construct a new policy to contain the result of partial evaluation.
	module := ast.MustParseModule("package partial")

	for i := range partial {
		rule := &ast.Rule{
			Head: &ast.Head{
				Name:  ast.Var("allow"),
				Value: ast.BooleanTerm(true),
			},
			Body:   partial[i],
			Module: module,
		}
		module.Rules = append(module.Rules, rule)
	}

	// Compile the partially evaluated policy with the original policy.
	modules["partial"] = module

	if compiler.Compile(modules); compiler.Failed() {
		// Handle error.
	}

	// Test different inputs against partially evaluated policy.
	inputs := []string{
		`{"group": "dev", "permission": "read_bucket"}`,  // allow
		`{"group": "dev", "permission": "write_bucket"}`, // deny
		`{"group": "sre", "permission": "write_bucket"}`, // allow
	}

	fmt.Println()
	fmt.Println("# evaluation results:")

	for i := range inputs {

		// Query partially evaluated policy.
		q = topdown.NewQuery(ast.MustParseBody("data.partial.allow = true")).
			WithCompiler(compiler).
			WithStore(store).
			WithTransaction(txn).
			WithInput(ast.MustParseTerm(inputs[i]))

		qrs, err := q.Run(ctx)
		if err != nil {
			// Handle error.
		}

		// Check if input is allowed.
		allowed := len(qrs) == 1

		fmt.Printf("input %d allowed: %v\n", i+1, allowed)
	}

}
Output:


# partial evaluation result (5 items):
"dev" = input.group; "read_bucket" = input.permission
"test" = input.group; "read_bucket" = input.permission
"sre" = input.group; "read_bucket" = input.permission
"sre" = input.group; "write_bucket" = input.permission
"sre" = input.group; "delete_bucket" = input.permission

# evaluation results:
input 1 allowed: true
input 2 allowed: false
input 3 allowed: true

func (*Query) Run

func (q *Query) Run(ctx context.Context) (QueryResultSet, error)

Run is a wrapper around Iter that accumulates query results and returns them in one shot.

Example
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/open-policy-agent/opa/v1/ast"
	"github.com/open-policy-agent/opa/v1/storage/inmem"
	"github.com/open-policy-agent/opa/v1/topdown"
)

func main() {
	// Initialize context for the example. Normally the caller would obtain the
	// context from an input parameter or instantiate their own.
	ctx := context.Background()

	compiler := ast.NewCompiler()

	// Define a dummy query and some data that the query will execute against.
	query, err := compiler.QueryCompiler().Compile(ast.MustParseBody(`data.a[_] = x; x >= 2`))
	if err != nil {
		// Handle error.
	}

	var data map[string]interface{}

	// OPA uses Go's standard JSON library but assumes that numbers have been
	// decoded as json.Number instead of float64. You MUST decode with UseNumber
	// enabled.
	decoder := json.NewDecoder(bytes.NewBufferString(`{"a": [1,2,3,4]}`))
	decoder.UseNumber()

	if err := decoder.Decode(&data); err != nil {
		// Handle error.
	}

	// Instantiate the policy engine's storage layer.
	store := inmem.NewFromObject(data)

	// Create a new transaction. Transactions allow the policy engine to
	// evaluate the query over a consistent snapshot fo the storage layer.
	txn, err := store.NewTransaction(ctx)
	if err != nil {
		// Handle error.
	}

	defer store.Abort(ctx, txn)

	// Prepare the evaluation parameters. Evaluation executes against the policy
	// engine's storage. In this case, we seed the storage with a single array
	// of number. Other parameters such as the input, tracing configuration,
	// etc. can be set on the query object.
	q := topdown.NewQuery(query).
		WithCompiler(compiler).
		WithStore(store).
		WithTransaction(txn)

	rs, err := q.Run(ctx)

	// Inspect the query result set.
	fmt.Println("len:", len(rs))
	for i := range rs {
		fmt.Printf("rs[%d][\"x\"]: %v\n", i, rs[i]["x"])
	}
	fmt.Println("err:", err)

}
Output:

len: 3
rs[0]["x"]: 2
rs[1]["x"]: 3
rs[2]["x"]: 4
err: <nil>

func (*Query) WithBuiltinErrorList

func (q *Query) WithBuiltinErrorList(list *[]Error) *Query

WithBuiltinErrorList supplies a pointer to an Error slice to store built-in function errors encountered during evaluation. This error slice can be inspected after evaluation to determine which built-in function errors occurred.

func (*Query) WithBuiltins

func (q *Query) WithBuiltins(builtins map[string]*Builtin) *Query

WithBuiltins adds a set of built-in functions that can be called by the query.

func (*Query) WithCancel

func (q *Query) WithCancel(cancel Cancel) *Query

WithCancel sets the cancellation object to use for the query. Set this if you need to abort queries based on a deadline. This is optional.

func (*Query) WithCompiler

func (q *Query) WithCompiler(compiler *ast.Compiler) *Query

WithCompiler sets the compiler to use for the query.

func (*Query) WithDisableInlining

func (q *Query) WithDisableInlining(paths []ast.Ref) *Query

WithDisableInlining adds a set of paths to the query that should be excluded from inlining. Inlining during partial evaluation can be expensive in some cases (e.g., when a cross-product is computed.) Disabling inlining avoids expensive computation at the cost of generating support rules.

func (*Query) WithDistributedTracingOpts

func (q *Query) WithDistributedTracingOpts(tr tracing.Options) *Query

WithDistributedTracingOpts sets the options to be used by distributed tracing.

func (*Query) WithEarlyExit

func (q *Query) WithEarlyExit(enabled bool) *Query

WithEarlyExit will enable or disable using 'early exit' for the evaluation of the query. The default is enabled.

func (*Query) WithHTTPRoundTripper

func (q *Query) WithHTTPRoundTripper(t CustomizeRoundTripper) *Query

WithHTTPRoundTripper configures a custom HTTP transport for built-in functions that make HTTP requests.

func (*Query) WithIndexing

func (q *Query) WithIndexing(enabled bool) *Query

WithIndexing will enable or disable using rule indexing for the evaluation of the query. The default is enabled.

func (*Query) WithInput

func (q *Query) WithInput(input *ast.Term) *Query

WithInput sets the input object to use for the query. References rooted at input will be evaluated against this value. This is optional.

func (*Query) WithInstrumentation

func (q *Query) WithInstrumentation(instr *Instrumentation) *Query

WithInstrumentation sets the instrumentation configuration to enable on the evaluation process. By default, instrumentation is turned off.

func (*Query) WithInterQueryBuiltinCache

func (q *Query) WithInterQueryBuiltinCache(c cache.InterQueryCache) *Query

WithInterQueryBuiltinCache sets the inter-query cache that built-in functions can utilize.

func (*Query) WithInterQueryBuiltinValueCache

func (q *Query) WithInterQueryBuiltinValueCache(c cache.InterQueryValueCache) *Query

WithInterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize.

func (*Query) WithMetrics

func (q *Query) WithMetrics(m metrics.Metrics) *Query

WithMetrics sets the metrics collection to add evaluation metrics to. This is optional.

func (*Query) WithNDBuiltinCache

func (q *Query) WithNDBuiltinCache(c builtins.NDBCache) *Query

WithNDBuiltinCache sets the non-deterministic builtin cache.

func (*Query) WithPartialNamespace

func (q *Query) WithPartialNamespace(ns string) *Query

WithPartialNamespace sets the namespace to use for supporting rules generated as part of the partial evaluation process. The ns value must be a valid package path component.

func (*Query) WithPrintHook

func (q *Query) WithPrintHook(h print.Hook) *Query

func (*Query) WithQueryCompiler

func (q *Query) WithQueryCompiler(queryCompiler ast.QueryCompiler) *Query

WithQueryCompiler sets the queryCompiler used for the query.

func (*Query) WithQueryTracer

func (q *Query) WithQueryTracer(tracer QueryTracer) *Query

WithQueryTracer adds a query tracer to use during evaluation. This is optional. Disabled QueryTracers will be ignored.

func (*Query) WithResolver

func (q *Query) WithResolver(ref ast.Ref, r resolver.Resolver) *Query

WithResolver configures an external resolver to use for the given ref.

func (*Query) WithRuntime

func (q *Query) WithRuntime(runtime *ast.Term) *Query

WithRuntime sets the runtime data to execute the query with. The runtime data can be returned by the `opa.runtime` built-in function.

func (*Query) WithSeed

func (q *Query) WithSeed(r io.Reader) *Query

WithSeed sets a reader that will seed randomization required by built-in functions. If a seed is not provided crypto/rand.Reader is used.

func (*Query) WithShallowInlining

func (q *Query) WithShallowInlining(yes bool) *Query

WithShallowInlining disables aggressive inlining performed during partial evaluation. When shallow inlining is enabled rules that depend (transitively) on unknowns are not inlined. Only rules/values that are completely known will be inlined.

func (*Query) WithSkipPartialNamespace

func (q *Query) WithSkipPartialNamespace(yes bool) *Query

WithSkipPartialNamespace disables namespacing of saved support rules that are generated from the original policy (rules which are completely synthetic are still namespaced.)

func (*Query) WithStore

func (q *Query) WithStore(store storage.Store) *Query

WithStore sets the store to use for the query.

func (*Query) WithStrictBuiltinErrors

func (q *Query) WithStrictBuiltinErrors(yes bool) *Query

WithStrictBuiltinErrors tells the evaluator to treat all built-in function errors as fatal errors.

func (*Query) WithStrictObjects

func (q *Query) WithStrictObjects(yes bool) *Query

WithStrictObjects tells the evaluator to avoid the "lazy object" optimization applied when reading objects from the store. It will result in higher memory usage and should only be used temporarily while adjusting code that breaks because of the optimization.

func (*Query) WithTime

func (q *Query) WithTime(x time.Time) *Query

WithTime sets the time that will be returned by the time.now_ns() built-in function.

func (*Query) WithTracer

func (q *Query) WithTracer(tracer Tracer) *Query

WithTracer adds a query tracer to use during evaluation. This is optional. Deprecated: Use WithQueryTracer instead.

func (*Query) WithTransaction

func (q *Query) WithTransaction(txn storage.Transaction) *Query

WithTransaction sets the transaction to use for the query. All queries should be performed over a consistent snapshot of the storage layer.

func (*Query) WithUnknowns

func (q *Query) WithUnknowns(terms []*ast.Term) *Query

WithUnknowns sets the initial set of variables or references to treat as unknown during query evaluation. This is required for partial evaluation.

func (*Query) WithVirtualCache

func (q *Query) WithVirtualCache(vc VirtualCache) *Query

WithVirtualCache sets the VirtualCache to use during evaluation. This is optional, and if not set, the default cache is used.

type QueryResult

type QueryResult map[ast.Var]*ast.Term

QueryResult represents a single result returned by a query. The result contains bindings for all variables that appear in the query.

type QueryResultSet

type QueryResultSet []QueryResult

QueryResultSet represents a collection of results returned by a query.

type QueryTracer

type QueryTracer interface {
	Enabled() bool
	TraceEvent(Event)
	Config() TraceConfig
}

QueryTracer defines the interface for tracing in the top-down evaluation engine. The implementation can provide additional configuration to modify the tracing behavior for query evaluations.

func WrapLegacyTracer

func WrapLegacyTracer(tracer Tracer) QueryTracer

WrapLegacyTracer will create a new QueryTracer which wraps an older Tracer instance.

type TraceConfig

type TraceConfig struct {
	PlugLocalVars bool // Indicate whether to plug local variable bindings before calling into the tracer.
}

TraceConfig defines some common configuration for Tracer implementations

type Tracer

type Tracer interface {
	Enabled() bool
	Trace(*Event)
}

Tracer defines the interface for tracing in the top-down evaluation engine. Deprecated: Use QueryTracer instead.

type VarMetadata

type VarMetadata struct {
	Name     ast.Var       `json:"name"`
	Location *ast.Location `json:"location"`
}

VarMetadata provides some user facing information about a variable in some policy.

type VirtualCache

type VirtualCache interface {
	// Push pushes a new, empty frame of value mappings onto the stack.
	Push()

	// Pop pops the top frame of value mappings from the stack, removing all associated entries.
	Pop()

	// Get returns the value associated with the given reference. The second return value
	// indicates whether the reference has a recorded 'undefined' result.
	Get(ref ast.Ref) (*ast.Term, bool)

	// Put associates the given reference with the given value. If the value is nil, the reference
	// is marked as having an 'undefined' result.
	Put(ref ast.Ref, value *ast.Term)

	// Keys returns the set of keys that have been cached for the active frame.
	Keys() []ast.Ref
}

VirtualCache defines the interface for a cache that stores the results of evaluated virtual documents (rules). The cache is a stack of frames, where each frame is a mapping from references to values.

func NewVirtualCache

func NewVirtualCache() VirtualCache

Directories

Path Synopsis
Package builtins contains utilities for implementing built-in functions.
Package builtins contains utilities for implementing built-in functions.
Package cache defines the inter-query cache interface that can cache data across queries
Package cache defines the inter-query cache interface that can cache data across queries

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL