Movatterモバイル変換


[0]ホーム

URL:


rego

package
v1.11.0Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2025 License:Apache-2.0Imports:32Imported by:103

Details

Repository

github.com/open-policy-agent/opa

Links

Documentation

Overview

Package rego exposes high level APIs for evaluating Rego policies.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcBuiltinErrorList

func BuiltinErrorList(list *[]topdown.Error) func(r *Rego)

BuiltinErrorList supplies an error slice to store built-in function errors.

funcBundleActivatorPluginadded inv1.7.0

func BundleActivatorPlugin(namestring) func(r *Rego)

BundleActivatorPlugin sets the name of the activator plugin used to load bundles into the store.

funcBundleLazyLoadingModeadded inv1.7.0

func BundleLazyLoadingMode(yesbool) func(r *Rego)

BundleLazyLoadingMode sets the bundle loading mode. If true, bundles will beread in lazy mode. In this mode, data files in the bundle will not bedeserialized and the check to validate that the bundle data does not containpaths outside the bundle's roots will not be performed while reading the bundle.

funcCapabilities

func Capabilities(c *ast.Capabilities) func(r *Rego)

Capabilities configures the underlying compiler's capabilities.This option is ignored for module compilation if the caller supplies thecompiler.

funcCompiler

func Compiler(c *ast.Compiler) func(r *Rego)

Compiler returns an argument that sets the Rego compiler.

funcCompilerHookadded inv1.7.0

func CompilerHook(hook func(*ast.Compiler)) func(r *Rego)

CompilerHook sets a hook function that will be called after the compiler is initialized.This is only called if the compiler has not been provided already.

funcDisableInlining

func DisableInlining(paths []string) func(r *Rego)

DisableInlining adds a set of paths to exclude from partial evaluation inlining.

funcDistributedTracingOpts

func DistributedTracingOpts(trtracing.Options) func(r *Rego)

DistributedTracingOpts sets the options to be used by distributed tracing.

funcDump

func Dump(wio.Writer) func(r *Rego)

Dump returns an argument that sets the writer to dump debugging information to.

funcEnablePrintStatements

func EnablePrintStatements(yesbool) func(r *Rego)

EnablePrintStatements enables print() calls. If this option is not provided,print() calls will be erased from the policy. This option only applies toqueries and policies that passed as raw strings, i.e., this function will nothave any affect if the caller supplies the ast.Compiler instance.

funcEvalModeadded inv1.7.0

func EvalMode(modeast.CompilerEvalMode) func(r *Rego)

EvalMode lets you override the evaluation mode.

funcFunction1

func Function1(decl *Function, fBuiltin1) func(*Rego)

Function1 returns an option that adds a built-in function to the Rego object.

funcFunction2

func Function2(decl *Function, fBuiltin2) func(*Rego)

Function2 returns an option that adds a built-in function to the Rego object.

funcFunction3

func Function3(decl *Function, fBuiltin3) func(*Rego)

Function3 returns an option that adds a built-in function to the Rego object.

funcFunction4

func Function4(decl *Function, fBuiltin4) func(*Rego)

Function4 returns an option that adds a built-in function to the Rego object.

funcFunctionDecl

func FunctionDecl(decl *Function) func(*Rego)

FunctionDecl returns an option that adds a custom-built-in function__declaration__. NO implementation is provided. This is used fornon-interpreter execution envs (e.g., Wasm).

funcFunctionDyn

func FunctionDyn(decl *Function, fBuiltinDyn) func(*Rego)

FunctionDyn returns an option that adds a built-in function to the Rego object.

funcGenerateJSON

func GenerateJSON(f func(*ast.Term, *EvalContext) (any,error)) func(r *Rego)

GenerateJSON sets the AST to JSON converter for the results.

funcImports

func Imports(p []string) func(r *Rego)

Imports returns an argument that adds a Rego import to the query's context.

funcInput

func Input(xany) func(r *Rego)

Input returns an argument that sets the Rego input document. Input should bea native Go value representing the input document.

funcInstrument

func Instrument(yesbool) func(r *Rego)

Instrument returns an argument that enables instrumentation for diagnosingperformance issues.

funcInterQueryBuiltinCache

func InterQueryBuiltinCache(ccache.InterQueryCache) func(r *Rego)

InterQueryBuiltinCache sets the inter-query cache that built-in functions can utilizeduring evaluation.

funcInterQueryBuiltinValueCache

func InterQueryBuiltinValueCache(ccache.InterQueryValueCache) func(r *Rego)

InterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilizeduring evaluation.

funcIsPartialEvaluationNotEffectiveErr

func IsPartialEvaluationNotEffectiveErr(errerror)bool

IsPartialEvaluationNotEffectiveErr returns true if err is an error returned bythis package to indicate that partial evaluation was ineffective.

funcLoad

func Load(paths []string, filterloader.Filter) func(r *Rego)

Load returns an argument that adds a filesystem path to load dataand Rego modules from. Any file with a *.rego, *.yaml, or *.jsonextension will be loaded. The path can be either a directory or file,directories are loaded recursively. The optional ignore string patternscan be used to filter which files are used.The Load option can only be used once.Note: Loading files will require a write transaction on the store.

funcLoadBundle

func LoadBundle(pathstring) func(r *Rego)

LoadBundle returns an argument that adds a filesystem path to loada bundle from. The path can be a compressed bundle file or a directoryto be loaded as a bundle.Note: Loading bundles will require a write transaction on the store.

funcMetrics

func Metrics(mmetrics.Metrics) func(r *Rego)

Metrics returns an argument that sets the metrics collection.

funcModule

func Module(filename, inputstring) func(r *Rego)

Module returns an argument that adds a Rego module.

funcNDBuiltinCache

func NDBuiltinCache(cbuiltins.NDBCache) func(r *Rego)

NDBuiltinCache sets the non-deterministic builtins cache.

funcNewHaltError

func NewHaltError(errerror)error

NewHaltError wraps an error such that the evaluation process will stopwhen it occurs.

funcNondeterministicBuiltinsadded inv1.1.0

func NondeterministicBuiltins(yesbool) func(r *Rego)

NondeterministicBuiltins causes non-deterministic builtins to be evalued duringpartial evaluation. This is needed to pull in external data, or validate a JWT,during PE, so that the result informs what queries are returned.

funcPackage

func Package(pstring) func(r *Rego)

Package returns an argument that sets the Rego package on the query'scontext.

funcParsedBundle

func ParsedBundle(namestring, b *bundle.Bundle) func(r *Rego)

ParsedBundle returns an argument that adds a bundle to be loaded.

funcParsedImports

func ParsedImports(imp []*ast.Import) func(r *Rego)

ParsedImports returns an argument that adds Rego imports to the query'scontext.

funcParsedInput

func ParsedInput(xast.Value) func(r *Rego)

ParsedInput returns an argument that sets the Rego input document.

funcParsedModule

func ParsedModule(module *ast.Module) func(*Rego)

ParsedModule returns an argument that adds a parsed Rego module. If a stringmodule with the same filename name is added, it will override the parsedmodule.

funcParsedPackage

func ParsedPackage(pkg *ast.Package) func(r *Rego)

ParsedPackage returns an argument that sets the Rego package on the query'scontext.

funcParsedQuery

func ParsedQuery(qast.Body) func(r *Rego)

ParsedQuery returns an argument that sets the Rego query.

funcParsedUnknowns

func ParsedUnknowns(unknowns []*ast.Term) func(r *Rego)

ParsedUnknowns returns an argument that sets the values to treat as unknownduring partial evaluation.

funcPartialNamespace

func PartialNamespace(nsstring) func(r *Rego)

PartialNamespace returns an argument that sets the namespace to use forpartial evaluation results. The namespace must be a valid package pathcomponent.

funcPrintHook

func PrintHook(hprint.Hook) func(r *Rego)

PrintHook sets the object to use for handling print statement outputs.

funcPrintTrace

func PrintTrace(wio.Writer, r *Rego)

PrintTrace is a helper function to write a human-readable version of thetrace to the writer w.

funcPrintTraceWithLocation

func PrintTraceWithLocation(wio.Writer, r *Rego)

PrintTraceWithLocation is a helper function to write a human-readable version of thetrace to the writer w.

funcQuery

func Query(qstring) func(r *Rego)

Query returns an argument that sets the Rego query.

funcQueryTracer

func QueryTracer(ttopdown.QueryTracer) func(r *Rego)

QueryTracer returns an argument that adds a query tracer to r.

funcRegisterBuiltin1

func RegisterBuiltin1(decl *Function, implBuiltin1)

RegisterBuiltin1 adds a built-in function globally inside the OPA runtime.

funcRegisterBuiltin2

func RegisterBuiltin2(decl *Function, implBuiltin2)

RegisterBuiltin2 adds a built-in function globally inside the OPA runtime.

funcRegisterBuiltin3

func RegisterBuiltin3(decl *Function, implBuiltin3)

RegisterBuiltin3 adds a built-in function globally inside the OPA runtime.

funcRegisterBuiltin4

func RegisterBuiltin4(decl *Function, implBuiltin4)

RegisterBuiltin4 adds a built-in function globally inside the OPA runtime.

funcRegisterBuiltinDyn

func RegisterBuiltinDyn(decl *Function, implBuiltinDyn)

RegisterBuiltinDyn adds a built-in function globally inside the OPA runtime.

funcRegisterPlugin

func RegisterPlugin(namestring, pTargetPlugin)

funcResolver

func Resolver(refast.Ref, rresolver.Resolver) func(r *Rego)

Resolver sets a Resolver for a specified ref path.

funcRuntime

func Runtime(term *ast.Term) func(r *Rego)

Runtime returns an argument that sets the runtime data to provide to theevaluation engine.

funcSchemas

func Schemas(x *ast.SchemaSet) func(r *Rego)

Schemas sets the schemaSet

funcSeed

func Seed(rio.Reader) func(*Rego)

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

funcSetRegoVersion

func SetRegoVersion(versionast.RegoVersion) func(r *Rego)

funcShallowInlining

func ShallowInlining(yesbool) func(r *Rego)

ShallowInlining prevents rules that depend on unknown values from being inlined.Rules that only depend on known values are inlined.

funcSkipBundleVerification

func SkipBundleVerification(yesbool) func(r *Rego)

SkipBundleVerification skips verification of a signed bundle.

funcSkipPartialNamespace

func SkipPartialNamespace(yesbool) func(r *Rego)

SkipPartialNamespace disables namespacing of partial evalution results for supportrules generated from policy. Synthetic support rules are still namespaced.

funcStore

func Store(sstorage.Store) func(r *Rego)

Store returns an argument that sets the policy engine's data storage layer.

If using the Load, LoadBundle, or ParsedBundle options then a transactionmust also be provided via the Transaction() option. After loading filesor bundles the transaction should be aborted or committed.

funcStoreReadAST

func StoreReadAST(enabledbool) func(r *Rego)

StoreReadAST returns an argument that sets whether the store should eagerly convert data to AST values.

Only applicable when no store has been set on the Rego object through the Store option.

funcStrict

func Strict(yesbool) func(r *Rego)

Strict enables or disables strict-mode in the compiler

funcStrictBuiltinErrors

func StrictBuiltinErrors(yesbool) func(r *Rego)

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

funcTarget

func Target(tstring) func(r *Rego)

Target sets the runtime to exercise.

funcTime

func Time(xtime.Time) func(r *Rego)

Time sets the wall clock time to use during policy evaluation. Prepared queriesdo not inherit this parameter. Use EvalTime to set the wall clock time whenexecuting a prepared query.

funcTrace

func Trace(yesbool) func(r *Rego)

Trace returns an argument that enables tracing on r.

funcTracerdeprecated

func Tracer(ttopdown.Tracer) func(r *Rego)

Tracer returns an argument that adds a query tracer to r.

Deprecated: Use QueryTracer instead.

funcTransaction

func Transaction(txnstorage.Transaction) func(r *Rego)

Transaction returns an argument that sets the transaction to use for storagelayer operations.

Requires the store associated with the transaction to be provided via theStore() option. If using Load(), LoadBundle(), or ParsedBundle() optionsthe transaction will likely require write params.

funcUnknowns

func Unknowns(unknowns []string) func(r *Rego)

Unknowns returns an argument that sets the values to treat as unknown duringpartial evaluation.

funcUnsafeBuiltins

func UnsafeBuiltins(unsafeBuiltins map[string]struct{}) func(r *Rego)

UnsafeBuiltins sets the built-in functions to treat as unsafe and not allow.This option is ignored for module compilation if the caller supplies thecompiler. This option is always honored for query compilation. Provide anempty (non-nil) map to disable checks on queries.

funcWithFilteradded inv1.11.0

func WithFilter(ffilter.LoaderFilter) func(r *Rego)

Types

typeBuiltin1

type Builtin1 func(bctxBuiltinContext, op1 *ast.Term) (*ast.Term,error)

Builtin1 defines a built-in function that accepts 1 argument.

typeBuiltin2

type Builtin2 func(bctxBuiltinContext, op1, op2 *ast.Term) (*ast.Term,error)

Builtin2 defines a built-in function that accepts 2 arguments.

typeBuiltin3

type Builtin3 func(bctxBuiltinContext, op1, op2, op3 *ast.Term) (*ast.Term,error)

Builtin3 defines a built-in function that accepts 3 argument.

typeBuiltin4

type Builtin4 func(bctxBuiltinContext, op1, op2, op3, op4 *ast.Term) (*ast.Term,error)

Builtin4 defines a built-in function that accepts 4 argument.

typeBuiltinContext

type BuiltinContext =topdown.BuiltinContext

BuiltinContext contains additional attributes from the evaluator thatbuilt-in functions can use, e.g., the request context.Context, caches, etc.

typeBuiltinDyn

type BuiltinDyn func(bctxBuiltinContext, terms []*ast.Term) (*ast.Term,error)

BuiltinDyn defines a built-in function that accepts a list of arguments.

typeCompileContext

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

CompileContext contains options for Compile calls.

typeCompileOption

type CompileOption func(*CompileContext)

CompileOption defines a function to set options on Compile calls.

funcCompilePartial

func CompilePartial(yesbool)CompileOption

CompilePartial defines an option to control whether partial evaluation is runbefore the query is planned and compiled.

typeCompileResult

type CompileResult struct {Bytes []byte `json:"bytes"`}

CompileResult represents the result of compiling a Rego query, zero or moreRego modules, and arbitrary contextual data into an executable.

typeErrorDetails

type ErrorDetails interface {Lines() []string}

ErrorDetails interface is satisfied by an error that provides furtherdetails.

typeErrors

type Errors []error

Errors represents a collection of errors returned when evaluating Rego.

func (Errors)Error

func (errsErrors) Error()string

typeEvalContext

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

EvalContext defines the set of options allowed to be set at evaluationtime. Any other options will need to be set on a new Rego object.

func (*EvalContext)Capabilities

func (e *EvalContext) Capabilities() *ast.Capabilities

func (*EvalContext)CompiledQuery

func (e *EvalContext) CompiledQuery()ast.Body

func (*EvalContext)ExternalCanceladded inv1.7.0

func (e *EvalContext) ExternalCancel()topdown.Cancel

func (*EvalContext)InterQueryBuiltinCache

func (e *EvalContext) InterQueryBuiltinCache()cache.InterQueryCache

func (*EvalContext)InterQueryBuiltinValueCache

func (e *EvalContext) InterQueryBuiltinValueCache()cache.InterQueryValueCache

func (*EvalContext)Metrics

func (e *EvalContext) Metrics()metrics.Metrics

func (*EvalContext)NDBCache

func (e *EvalContext) NDBCache()builtins.NDBCache

func (*EvalContext)ParsedInput

func (e *EvalContext) ParsedInput()ast.Value

func (*EvalContext)PrintHook

func (e *EvalContext) PrintHook()print.Hook

func (*EvalContext)QueryTracersadded inv1.7.0

func (e *EvalContext) QueryTracers() []topdown.QueryTracer

func (*EvalContext)RawInput

func (e *EvalContext) RawInput() *any

func (*EvalContext)Seed

func (e *EvalContext) Seed()io.Reader

func (*EvalContext)StrictBuiltinErrors

func (e *EvalContext) StrictBuiltinErrors()bool

func (*EvalContext)Time

func (e *EvalContext) Time()time.Time

func (*EvalContext)TracingOptsadded inv1.7.0

func (e *EvalContext) TracingOpts()tracing.Options

func (*EvalContext)Transaction

func (e *EvalContext) Transaction()storage.Transaction

typeEvalOption

type EvalOption func(*EvalContext)

EvalOption defines a function to set an option on an EvalConfig

funcEvalBaseCacheadded inv1.2.0

func EvalBaseCache(bctopdown.BaseCache)EvalOption

EvalBaseCache sets the topdown.BaseCache to use for evaluation.This is optional, and if not set, the default cache is used.

funcEvalCopyMaps

func EvalCopyMaps(yesbool)EvalOption

EvalCopyMaps causes the evaluator to copy `map[string]any`s before returning them.

funcEvalDisableInlining

func EvalDisableInlining(paths []ast.Ref)EvalOption

EvalDisableInlining returns an argument that adds a set of paths to exclude frompartial evaluation inlining.

funcEvalEarlyExit

func EvalEarlyExit(enabledbool)EvalOption

EvalEarlyExit will disable 'early exit' optimizations for theevaluation. This should only be used when tracing in debug mode.

funcEvalExternalCanceladded inv1.7.0

func EvalExternalCancel(ectopdown.Cancel)EvalOption

EvalExternalCancel sets an external topdown.Cancel for the interpreter to usefor cancellation. This is useful for batch-evaluation of many rego queries.

funcEvalHTTPRoundTripper

func EvalHTTPRoundTripper(ttopdown.CustomizeRoundTripper)EvalOption

EvalHTTPRoundTripper allows customizing the http.RoundTripper for this evaluation.

funcEvalInput

func EvalInput(inputany)EvalOption

EvalInput configures the input for a Prepared Query's evaluation

funcEvalInstrument

func EvalInstrument(instrumentbool)EvalOption

EvalInstrument enables or disables instrumenting for a Prepared Query's evaluation

funcEvalInterQueryBuiltinCache

func EvalInterQueryBuiltinCache(ccache.InterQueryCache)EvalOption

EvalInterQueryBuiltinCache sets the inter-query cache that built-in functions can utilizeduring evaluation.

funcEvalInterQueryBuiltinValueCache

func EvalInterQueryBuiltinValueCache(ccache.InterQueryValueCache)EvalOption

EvalInterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilizeduring evaluation.

funcEvalMetrics

func EvalMetrics(metricmetrics.Metrics)EvalOption

EvalMetrics configures the metrics for a Prepared Query's evaluation

funcEvalNDBuiltinCache

func EvalNDBuiltinCache(cbuiltins.NDBCache)EvalOption

EvalNDBuiltinCache sets the non-deterministic builtin cache that built-in functions canuse during evaluation.

funcEvalNondeterministicBuiltinsadded inv1.1.0

func EvalNondeterministicBuiltins(yesbool)EvalOption

EvalNondeterministicBuiltins causes non-deterministic builtins to be evaluedduring partial evaluation. This is needed to pull in external data, or validatea JWT, during PE, so that the result informs what queries are returned.

funcEvalParsedInput

func EvalParsedInput(inputast.Value)EvalOption

EvalParsedInput configures the input for a Prepared Query's evaluation

funcEvalParsedUnknowns

func EvalParsedUnknowns(unknowns []*ast.Term)EvalOption

EvalParsedUnknowns returns an argument that sets the values to treatas unknown during partial evaluation.

funcEvalPartialNamespace

func EvalPartialNamespace(nsstring)EvalOption

EvalPartialNamespace returns an argument that sets the namespace to use forpartial evaluation results. The namespace must be a valid package pathcomponent.

funcEvalPrintHook

func EvalPrintHook(phprint.Hook)EvalOption

EvalPrintHook sets the object to use for handling print statement outputs.

funcEvalQueryTracer

func EvalQueryTracer(tracertopdown.QueryTracer)EvalOption

EvalQueryTracer configures a tracer for a Prepared Query's evaluation

funcEvalResolver

func EvalResolver(refast.Ref, rresolver.Resolver)EvalOption

EvalResolver sets a Resolver for a specified ref path for this evaluation.

funcEvalRuleIndexing

func EvalRuleIndexing(enabledbool)EvalOption

EvalRuleIndexing will disable indexing optimizations for theevaluation. This should only be used when tracing in debug mode.

funcEvalSeed

func EvalSeed(rio.Reader)EvalOption

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

funcEvalSortSets

func EvalSortSets(yesbool)EvalOption

EvalSortSets causes the evaluator to sort sets before returning them as JSON arrays.

funcEvalTime

func EvalTime(xtime.Time)EvalOption

EvalTime sets the wall clock time to use during policy evaluation.time.now_ns() calls will return this value.

funcEvalTracerdeprecated

func EvalTracer(tracertopdown.Tracer)EvalOption

EvalTracer configures a tracer for a Prepared Query's evaluation

Deprecated: Use EvalQueryTracer instead.

funcEvalTransaction

func EvalTransaction(txnstorage.Transaction)EvalOption

EvalTransaction configures the Transaction for a Prepared Query's evaluation

funcEvalUnknowns

func EvalUnknowns(unknowns []string)EvalOption

EvalUnknowns returns an argument that sets the values to treat asunknown during partial evaluation.

funcEvalVirtualCache

func EvalVirtualCache(vctopdown.VirtualCache)EvalOption

EvalVirtualCache sets the topdown.VirtualCache to use for evaluation.This is optional, and if not set, the default cache is used.

typeExpressionValue

type ExpressionValue struct {Valueany       `json:"value"`Textstring    `json:"text"`Location *Location `json:"location"`}

ExpressionValue defines the value of an expression in a Rego query.

func (*ExpressionValue)String

func (ev *ExpressionValue) String()string

typeFunction

type Function struct {NamestringDescriptionstringDecl             *types.FunctionMemoizeboolNondeterministicbool}

Function represents a built-in function that is callable in Rego.

typeHaltError

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

HaltError is an error type to return from a custom function implementationthat will abort the evaluation process (analogous to topdown.Halt).

func (*HaltError)Error

func (h *HaltError) Error()string

Error delegates to the wrapped error

typeLocation

type Location struct {Rowint `json:"row"`Colint `json:"col"`}

Location defines a position in a Rego query or module.

typePartialQueries

type PartialQueries struct {Queries []ast.Body    `json:"queries,omitempty"`Support []*ast.Module `json:"modules,omitempty"`}

PartialQueries contains the queries and support modules produced by partialevaluation.

typePartialResult

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

PartialResult represents the result of partial evaluation. The result can beused to generate a new query that can be run when inputs are known.

func (PartialResult)Rego

func (prPartialResult) Rego(options ...func(*Rego)) *Rego

Rego returns an object that can be evaluated to produce a query result.

typePrepareConfig

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

PrepareConfig holds settings to control the behavior of thePrepare call.

func (*PrepareConfig)BuiltinFuncs

func (p *PrepareConfig) BuiltinFuncs() map[string]*topdown.Builtin

BuiltinFuncs allows retrieving the builtin funcs set via PrepareOptionWithBuiltinFuncs.

typePrepareOption

type PrepareOption func(*PrepareConfig)

PrepareOption defines a function to set an option to controlthe behavior of the Prepare call.

funcWithBuiltinFuncs

func WithBuiltinFuncs(bis map[string]*topdown.Builtin)PrepareOption

WithBuiltinFuncs carries the rego.Function{1,2,3} per-query function definitionsto the target plugins.

funcWithNoInline

func WithNoInline(paths []string)PrepareOption

WithNoInline adds a set of paths to exclude from partial evaluation inlining.

funcWithPartialEval

func WithPartialEval()PrepareOption

WithPartialEval configures an option for PrepareForEvalwhich will have it perform partial evaluation while preparingthe query (similar to rego.Rego#PartialResult)

typePreparedEvalQuery

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

PreparedEvalQuery holds the prepared Rego state that has been pre-processedfor subsequent evaluations.

func (PreparedEvalQuery)Eval

func (pqPreparedEvalQuery) Eval(ctxcontext.Context, options ...EvalOption) (ResultSet,error)

Eval evaluates this PartialResult's Rego object with additional eval optionsand returns a ResultSet.If options are provided they will override the original Rego options respective value.The original Rego object transaction will *not* be re-used. A new transaction will be openedif one is not provided with an EvalOption.

func (PreparedEvalQuery)Modules

func (pq PreparedEvalQuery) Modules() map[string]*ast.Module

typePreparedPartialQuery

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

PreparedPartialQuery holds the prepared Rego state that has been pre-processedfor partial evaluations.

func (PreparedPartialQuery)Modules

func (pq PreparedPartialQuery) Modules() map[string]*ast.Module

func (PreparedPartialQuery)Partial

Partial runs partial evaluation on the prepared query and returns the result.The original Rego object transaction will *not* be re-used. A new transaction will be openedif one is not provided with an EvalOption.

typeRego

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

Rego constructs a query and can be evaluated to obtain results.

Example (Custom_function_caching)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/topdown""github.com/open-policy-agent/opa/v1/types")func main() {i := 0r := rego.New(// An example query that uses a custom function.rego.Query(`x = mycounter("foo"); y = mycounter("foo")`),// A custom function that uses caching.rego.FunctionDyn(&rego.Function{Name:    "mycounter",Memoize: true,Decl: types.NewFunction(types.Args(types.S), // one string inputtypes.N,             // one number output),},func(_ topdown.BuiltinContext, args []*ast.Term) (*ast.Term, error) {i++return ast.IntNumberTerm(i), nil},),)rs, err := r.Eval(context.Background())if err != nil {// handle error}fmt.Println("x:", rs[0].Bindings["x"])fmt.Println("y:", rs[0].Bindings["y"])}
Output:x: 1y: 1

Example (Custom_function_global)
package mainimport ("context""fmt""strings""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/types")func main() {decl := &rego.Function{Name: "trim_and_split",Decl: types.NewFunction(types.Args(types.S, types.S), // two string inputstypes.NewArray(nil, types.S), // variable-length string array output),}impl := func(_ rego.BuiltinContext, a, b *ast.Term) (*ast.Term, error) {str, ok1 := a.Value.(ast.String)delim, ok2 := b.Value.(ast.String)// The function is undefined for non-string inputs. Built-in// functions should only return errors in unrecoverable cases.if !ok1 || !ok2 {return nil, nil}result := strings.Split(strings.Trim(string(str), string(delim)), string(delim))arr := make([]*ast.Term, len(result))for i := range result {arr[i] = ast.StringTerm(result[i])}return ast.ArrayTerm(arr...), nil}// The rego package exports helper functions for different arities and a// special version of the function that accepts a dynamic number.rego.RegisterBuiltin2(decl, impl)r := rego.New(// An example query that uses a custom function.rego.Query(`x = trim_and_split("/foo/bar/baz/", "/")`),)rs, err := r.Eval(context.Background())if err != nil {// handle error}fmt.Println(rs[0].Bindings["x"])}
Output:[foo bar baz]

Example (Custom_function_nondeterministic)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/topdown/builtins""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/topdown""github.com/open-policy-agent/opa/v1/types")func main() {ndbCache := builtins.NDBCache{}r := rego.New(// An example query that uses a custom function.rego.Query(`x = myrandom()`),// A custom function that uses caching.rego.FunctionDyn(&rego.Function{Name:             "myrandom",Memoize:          true,Nondeterministic: true,Decl: types.NewFunction(nil,     // one string inputtypes.N, // one number output),},func(_ topdown.BuiltinContext, args []*ast.Term) (*ast.Term, error) {i := 55555return ast.IntNumberTerm(i), nil},),rego.NDBuiltinCache(ndbCache),)rs, err := r.Eval(context.Background())if err != nil {// handle error}// Check the binding, and what the NDBCache saw.// This ensures the Nondeterministic flag propagated through correctly.fmt.Println("x:", rs[0].Bindings["x"])fmt.Println("NDBCache:", ndbCache["myrandom"])}
Output:x: 55555NDBCache: {[]: 55555}

Example (Custom_functional_builtin)
package mainimport ("context""fmt""strings""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/types")func main() {r := rego.New(// An example query that uses a custom function.rego.Query(`x = trim_and_split("/foo/bar/baz/", "/")`),// A custom function that trims and splits strings on the same delimiter.rego.Function2(&rego.Function{Name: "trim_and_split",Decl: types.NewFunction(types.Args(types.S, types.S), // two string inputstypes.NewArray(nil, types.S), // variable-length string array output),},func(_ rego.BuiltinContext, a, b *ast.Term) (*ast.Term, error) {str, ok1 := a.Value.(ast.String)delim, ok2 := b.Value.(ast.String)// The function is undefined for non-string inputs. Built-in// functions should only return errors in unrecoverable cases.if !ok1 || !ok2 {return nil, nil}result := strings.Split(strings.Trim(string(str), string(delim)), string(delim))arr := make([]*ast.Term, len(result))for i := range result {arr[i] = ast.StringTerm(result[i])}return ast.ArrayTerm(arr...), nil},),)rs, err := r.Eval(context.Background())if err != nil {// handle error}fmt.Println(rs[0].Bindings["x"])}
Output:[foo bar baz]

Example (Print_statements)
package mainimport ("bytes""context""fmt""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/topdown")func main() {var buf bytes.Bufferr := rego.New(rego.Query("data.example.rule_containing_print_call"),rego.Module("example.rego", `package exampleimport rego.v1rule_containing_print_call if {print("input.foo is:", input.foo, "and input.bar is:", input.bar)}`),rego.Input(map[string]any{"foo": 7,}),rego.EnablePrintStatements(true),rego.PrintHook(topdown.NewPrintHook(&buf)),)_, err := r.Eval(context.Background())if err != nil {// handle error}fmt.Println("buf:", buf.String())}
Output:buf: input.foo is: 7 and input.bar is: <undefined>

funcNew

func New(options ...func(r *Rego)) *Rego

New returns a new Rego object.

func (*Rego)Compile

func (r *Rego) Compile(ctxcontext.Context, opts ...CompileOption) (*CompileResult,error)

Compile returns a compiled policy query.

func (*Rego)Eval

func (r *Rego) Eval(ctxcontext.Context) (ResultSet,error)

Eval evaluates this Rego object and returns a ResultSet.

Example (Allowed)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create query that returns a single boolean value.rego := rego.New(rego.Query("data.authz.allow"),rego.Module("example.rego",`package authzimport rego.v1default allow = falseallow if {input.open == "sesame"}`,),rego.Input(map[string]any{"open": "sesame"}),)// Run evaluation.rs, err := rego.Eval(ctx)if err != nil {panic(err)}// Inspect result.fmt.Println("allowed:", rs.Allowed())}
Output:allowed: true

Example (Compiler)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Define a simple policy.module := `package exampleimport rego.v1default allow = falseallow if {input.identity = "admin"}allow if {input.method = "GET"}`// Compile the module. The keys are used as identifiers in error messages.compiler, err := ast.CompileModules(map[string]string{"example.rego": module,})// Create a new query that uses the compiled policy from above.rego := rego.New(rego.Query("data.example.allow"),rego.Compiler(compiler),rego.Input(map[string]any{"identity": "bob","method":   "GET",},),)// Run evaluation.rs, err := rego.Eval(ctx)if err != nil {// Handle error.}// Inspect results.fmt.Println("len:", len(rs))fmt.Println("value:", rs[0].Expressions[0].Value)fmt.Println("allowed:", rs.Allowed()) // helper method}
Output:len: 1value: trueallowed: true

Example (Errors)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()r := rego.New(rego.Query("data.example.p"),rego.Module("example_error.rego",`package exampleimport rego.v1p = true if { not q[x] }q = {1, 2, 3} if { true }`,))_, err := r.Eval(ctx)switch err := err.(type) {case ast.Errors:for _, e := range err {fmt.Println("code:", e.Code)fmt.Println("row:", e.Location.Row)fmt.Println("filename:", e.Location.File)}default:// Some other error occurred.}}
Output:code: rego_unsafe_var_errorrow: 4filename: example_error.rego

Example (Input)
package mainimport ("bytes""context""encoding/json""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Raw input data that will be used in evaluation.raw := `{"users": [{"id": "bob"}, {"id": "alice"}]}`d := json.NewDecoder(bytes.NewBufferString(raw))// Numeric values must be represented using json.Number.d.UseNumber()var input anyif err := d.Decode(&input); err != nil {panic(err)}// Create a simple query over the input.rego := rego.New(rego.Query("input.users[idx].id = user_id"),rego.Input(input))//Run evaluation.rs, err := rego.Eval(ctx)if err != nil {// Handle error.}// Inspect results.fmt.Println("len:", len(rs))fmt.Println("bindings.idx:", rs[1].Bindings["idx"])fmt.Println("bindings.user_id:", rs[1].Bindings["user_id"])}
Output:len: 2bindings.idx: 1bindings.user_id: alice

Example (MultipleBindings)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create query that produces multiple bindings for variable.rego := rego.New(rego.Query(`a = ["ex", "am", "ple"]; x = a[_]; not p[x]`),rego.Package(`example`),rego.Module("example.rego", `package exampleimport rego.v1p contains "am" if { true }`),)// Run evaluation.rs, err := rego.Eval(ctx)// Inspect results.fmt.Println("len:", len(rs))fmt.Println("err:", err)for i := range rs {fmt.Printf("bindings[\"x\"]: %v (i=%d)\n", rs[i].Bindings["x"], i)}}
Output:len: 2err: <nil>bindings["x"]: ex (i=0)bindings["x"]: ple (i=1)

Example (MultipleDocuments)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create query that produces multiple documents.rego := rego.New(rego.Query("data.example.p[x]"),rego.Module("example.rego",`package exampleimport rego.v1p = {"hello": "alice", "goodbye": "bob"} if { true }`,))// Run evaluation.rs, err := rego.Eval(ctx)// Inspect results.fmt.Println("len:", len(rs))fmt.Println("err:", err)for i := range rs {fmt.Printf("bindings[\"x\"]: %v (i=%d)\n", rs[i].Bindings["x"], i)fmt.Printf("value: %v (i=%d)\n", rs[i].Expressions[0].Value, i)}}
Output:len: 2err: <nil>bindings["x"]: goodbye (i=0)value: bob (i=0)bindings["x"]: hello (i=1)value: alice (i=1)

Example (Persistent_storage)
package mainimport ("context""fmt""os""github.com/open-policy-agent/opa/v1/logging""github.com/open-policy-agent/opa/v1/storage/disk""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/storage""github.com/open-policy-agent/opa/v1/util")func main() {ctx := context.Background()data := `{        "example": {            "users": {"alice": {"likes": ["dogs", "clouds"]},"bob": {"likes": ["pizza", "cats"]}}        }    }`var json map[string]anyerr := util.UnmarshalJSON([]byte(data), &json)if err != nil {// Handle error.}// Manually create a persistent storage-layer in a temporary directory.rootDir, err := os.MkdirTemp("", "rego_example")if err != nil {panic(err)}defer os.RemoveAll(rootDir)// Configure the store to partition data at `/example/users` so that each// user's data is stored on a different row. Assuming the policy only reads// data for a single user to process the policy query, OPA can avoid loading// _all_ user data into memory this way.store, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir:        rootDir,Partitions: []storage.Path{{"example", "user"}},})if err != nil {// Handle error.}err = storage.WriteOne(ctx, store, storage.AddOp, storage.RootPath, json)if err != nil {// Handle error}// Run a query that returns the valuers, err := rego.New(rego.Query(`data.example.users["alice"].likes`),rego.Store(store)).Eval(ctx)if err != nil {// Handle error.}// Inspect the result.fmt.Println("value:", rs[0].Expressions[0].Value)// Re-open the store in the same directory.store.Close(ctx)store2, err := disk.New(ctx, logging.NewNoOpLogger(), nil, disk.Options{Dir:        rootDir,Partitions: []storage.Path{{"example", "user"}},})if err != nil {// Handle error.}// Run the same query with a new store.rs, err = rego.New(rego.Query(`data.example.users["alice"].likes`),rego.Store(store2)).Eval(ctx)if err != nil {// Handle error.}// Inspect the result and observe the same result.fmt.Println("value:", rs[0].Expressions[0].Value)}
Output:value: [dogs clouds]value: [dogs clouds]

Example (Simple)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create very simple query that binds a single variable.rego := rego.New(rego.Query("x = 1"))// Run evaluation.rs, err := rego.Eval(ctx)// Inspect results.fmt.Println("len:", len(rs))fmt.Println("bindings:", rs[0].Bindings)fmt.Println("err:", err)}
Output:len: 1bindings: map[x:1]err: <nil>

Example (SingleDocument)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create query that produces a single document.rego := rego.New(rego.Query("data.example.p"),rego.Module("example.rego",`package exampleimport rego.v1p = ["hello", "world"] if { true }`,))// Run evaluation.rs, err := rego.Eval(ctx)// Inspect result.fmt.Println("value:", rs[0].Expressions[0].Value)fmt.Println("err:", err)}
Output:value: [hello world]err: <nil>

Example (Storage)
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/storage/inmem""github.com/open-policy-agent/opa/v1/util")func main() {ctx := context.Background()data := `{        "example": {            "users": [                {                    "name": "alice",                    "likes": ["dogs", "clouds"]                },                {                    "name": "bob",                    "likes": ["pizza", "cats"]                }            ]        }    }`var json map[string]anyerr := util.UnmarshalJSON([]byte(data), &json)if err != nil {// Handle error.}// Manually create the storage layer. inmem.NewFromObject returns an// in-memory store containing the supplied data.store := inmem.NewFromObject(json)// Create new query that returns the valuerego := rego.New(rego.Query("data.example.users[0].likes"),rego.Store(store))// Run evaluation.rs, err := rego.Eval(ctx)if err != nil {// Handle error.}// Inspect the result.fmt.Println("value:", rs[0].Expressions[0].Value)}
Output:value: [dogs clouds]

Example (Trace_simple)
package mainimport ("context""os""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create very simple query that binds a single variable and enables tracing.r := rego.New(rego.Query("x = 1"),rego.Trace(true),)// Run evaluation.r.Eval(ctx)// Inspect results.rego.PrintTraceWithLocation(os.Stdout, r)}
Output:query:1     Enter x = 1query:1     | Eval x = 1query:1     | Unify x = 1query:1     | Exit x = 1query:1     Redo x = 1query:1     | Redo x = 1

Example (Tracer)
package mainimport ("context""os""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/topdown")func main() {ctx := context.Background()buf := topdown.NewBufferTracer()// Create very simple query that binds a single variable and provides a tracer.rego := rego.New(rego.Query("x = 1"),rego.QueryTracer(buf),)// Run evaluation.rego.Eval(ctx)// Inspect results.topdown.PrettyTraceWithLocation(os.Stdout, *buf)}
Output:query:1     Enter x = 1query:1     | Eval x = 1query:1     | Unify x = 1query:1     | Exit x = 1query:1     Redo x = 1query:1     | Redo x = 1

Example (Transactions)
package mainimport ("bytes""context""fmt""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/storage""github.com/open-policy-agent/opa/v1/storage/inmem")func main() {ctx := context.Background()// Create storage layer and load dummy data.store := inmem.NewFromReader(bytes.NewBufferString(`{"favourites": {"pizza": "cheese","colour": "violet"}}`))// Open a write transaction on the store that will perform write operations.txn, err := store.NewTransaction(ctx, storage.WriteParams)if err != nil {// Handle error.}// Create rego query that uses the transaction created above.inside := rego.New(rego.Query("data.favourites.pizza"),rego.Store(store),rego.Transaction(txn),)// Create rego query that DOES NOT use the transaction created above. Under// the hood, the rego package will create it's own transaction to// ensure it evaluates over a consistent snapshot of the storage layer.outside := rego.New(rego.Query("data.favourites.pizza"),rego.Store(store),)// Write change to storage layer inside the transaction.err = store.Write(ctx, txn, storage.AddOp, storage.MustParsePath("/favourites/pizza"), "pepperoni")if err != nil {// Handle error.}// Run evaluation INSIDE the transaction.rs, err := inside.Eval(ctx)if err != nil {// Handle error.}fmt.Println("value (inside txn):", rs[0].Expressions[0].Value)// Run evaluation OUTSIDE the transaction.rs, err = outside.Eval(ctx)if err != nil {// Handle error.}fmt.Println("value (outside txn):", rs[0].Expressions[0].Value)if err := store.Commit(ctx, txn); err != nil {// Handle error.}// Run evaluation AFTER the transaction commits.rs, err = outside.Eval(ctx)if err != nil {// Handle error.}fmt.Println("value (after txn):", rs[0].Expressions[0].Value)}
Output:value (inside txn): pepperonivalue (outside txn): cheesevalue (after txn): pepperoni

func (*Rego)Partial

func (r *Rego) Partial(ctxcontext.Context) (*PartialQueries,error)

Partial runs partial evaluation on r and returns the result.

Example
package mainimport ("context""fmt""sort""strings""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Define a simple policy for example purposes.module := `package testimport rego.v1allow if {input.method = read_methods[_]input.path = ["reviews", user]input.user = user}allow if {input.method = read_methods[_]input.path = ["reviews", _]input.is_admin}read_methods = ["GET"]`r := rego.New(rego.Query("data.test.allow == true"), rego.Module("example.rego", module))pq, err := r.Partial(ctx)if err != nil {// Handle error.}makeStable(pq.Queries)// Inspect result.for i := range pq.Queries {fmt.Printf("Query #%d: %v\n", i+1, pq.Queries[i])}}// This is typically not needed, but we do it here to ensure that our// example output is stable. We sort the result bodies, and rename the// variable that's `userX` for some number X to `user`.func makeStable(bodies []ast.Body) {for i := range bodies {ast.WalkTerms(bodies[i], func(t *ast.Term) bool {if v, ok := t.Value.(ast.Var); ok && strings.HasPrefix(string(v), "user") {t.Value = ast.Var("user")}return false})}sort.Slice(bodies, func(i, j int) bool { return bodies[i].Compare(bodies[j]) < 0 })}
Output:Query #1: "GET" = input.method; input.path = ["reviews", _]; input.is_adminQuery #2: "GET" = input.method; input.path = ["reviews", user]; user = input.user

func (*Rego)PartialEval

func (r *Rego) PartialEval(ctxcontext.Context) (PartialResult,error)

PartialEval has been deprecated and renamed to PartialResult.

func (*Rego)PartialResult

func (r *Rego) PartialResult(ctxcontext.Context) (PartialResult,error)

PartialResult partially evaluates this Rego object and returns a PartialResult.

Example
package mainimport ("bytes""context""fmt""github.com/open-policy-agent/opa/v1/rego""github.com/open-policy-agent/opa/v1/storage/inmem")func main() {ctx := context.Background()// Define a role-based access control (RBAC) policy that decides whether to// allow or deny requests. Requests are allowed if the user is bound to a// role that grants permission to perform the operation on the resource.module := `package exampleimport rego.v1import data.bindingsimport data.rolesdefault allow = falseallow if {user_has_role[role_name]role_has_permission[role_name]}user_has_role contains role_name if {b = bindings[_]b.role = role_nameb.user = input.subject.user}role_has_permission contains role_name if {r = roles[_]r.name = role_namematch_with_wildcard(r.operations, input.operation)match_with_wildcard(r.resources, input.resource)}match_with_wildcard(allowed, value) if {allowed[_] = "*"}match_with_wildcard(allowed, value) if {allowed[_] = value}`// Define dummy roles and role bindings for the example. In real-world// scenarios, this data would be pushed or pulled into the service// embedding OPA either from an external API or configuration file.store := inmem.NewFromReader(bytes.NewBufferString(`{"roles": [{"resources": ["documentA", "documentB"],"operations": ["read"],"name": "analyst"},{"resources": ["*"],"operations": ["*"],"name": "admin"}],"bindings": [{"user": "bob","role": "admin"},{"user": "alice","role": "analyst"}]}`))// Prepare and run partial evaluation on the query. The result of partial// evaluation can be cached for performance. When the data or policy// change, partial evaluation should be re-run.r := rego.New(rego.Query("data.example.allow"),rego.Module("example.rego", module),rego.Store(store),)pr, err := r.PartialResult(ctx)if err != nil {// Handle error.}// Define example inputs (representing requests) that will be used to test// the policy.examples := []map[string]any{{"resource":  "documentA","operation": "write","subject": map[string]any{"user": "bob",},},{"resource":  "documentB","operation": "write","subject": map[string]any{"user": "alice",},},{"resource":  "documentB","operation": "read","subject": map[string]any{"user": "alice",},},}for i := range examples {// Prepare and run normal evaluation from the result of partial// evaluation.r := pr.Rego(rego.Input(examples[i]),)rs, err := r.Eval(ctx)if err != nil || len(rs) != 1 || len(rs[0].Expressions) != 1 {// Handle erorr.} else {fmt.Printf("input %d allowed: %v\n", i+1, rs[0].Expressions[0].Value)}}}
Output:input 1 allowed: trueinput 2 allowed: falseinput 3 allowed: true

func (*Rego)PrepareForEval

func (r *Rego) PrepareForEval(ctxcontext.Context, opts ...PrepareOption) (PreparedEvalQuery,error)

PrepareForEval will parse inputs, modules, and query arguments in preparationof evaluating them.

Example
package mainimport ("context""fmt""github.com/open-policy-agent/opa/v1/rego")func main() {ctx := context.Background()// Create a simple queryr := rego.New(rego.Query("input.x == 1"),)// Prepare for evaluationpq, err := r.PrepareForEval(ctx)if err != nil {// Handle error.}// Raw input data that will be used in the first evaluationinput := map[string]any{"x": 2}// Run the evaluationrs, err := pq.Eval(ctx, rego.EvalInput(input))if err != nil {// Handle error.}// Inspect results.fmt.Println("initial result:", rs[0].Expressions[0])// Update inputinput["x"] = 1// Run the evaluation with new inputrs, err = pq.Eval(ctx, rego.EvalInput(input))if err != nil {// Handle error.}// Inspect results.fmt.Println("updated result:", rs[0].Expressions[0])}
Output:initial result: falseupdated result: true

func (*Rego)PrepareForPartial

func (r *Rego) PrepareForPartial(ctxcontext.Context, opts ...PrepareOption) (PreparedPartialQuery,error)

PrepareForPartial will parse inputs, modules, and query arguments in preparationof partially evaluating them.

Example
package mainimport ("context""fmt""sort""strings""github.com/open-policy-agent/opa/v1/ast""github.com/open-policy-agent/opa/v1/rego")// This is typically not needed, but we do it here to ensure that our// example output is stable. We sort the result bodies, and rename the// variable that's `userX` for some number X to `user`.func makeStable(bodies []ast.Body) {for i := range bodies {ast.WalkTerms(bodies[i], func(t *ast.Term) bool {if v, ok := t.Value.(ast.Var); ok && strings.HasPrefix(string(v), "user") {t.Value = ast.Var("user")}return false})}sort.Slice(bodies, func(i, j int) bool { return bodies[i].Compare(bodies[j]) < 0 })}func main() {ctx := context.Background()// Define a simple policy for example purposes.module := `package testimport rego.v1allow if {input.method = read_methods[_]input.path = ["reviews", user]input.user = user}allow if {input.method = read_methods[_]input.path = ["reviews", _]input.is_admin}read_methods = ["GET"]`r := rego.New(rego.Query("data.test.allow"),rego.Module("example.rego", module),)pq, err := r.PrepareForPartial(ctx)if err != nil {// Handle error.}pqs, err := pq.Partial(ctx)if err != nil {// Handle error.}makeStable(pqs.Queries)// Inspect resultfmt.Println("First evaluation")for i := range pqs.Queries {fmt.Printf("Query #%d: %v\n", i+1, pqs.Queries[i])}// Evaluate with specified inputexampleInput := map[string]string{"method": "GET",}// Evaluate again with different input and unknownspqs, err = pq.Partial(ctx,rego.EvalInput(exampleInput),rego.EvalUnknowns([]string{"input.user", "input.is_admin", "input.path"}),)if err != nil {// Handle error.}makeStable(pqs.Queries)// Inspect resultfmt.Println("Second evaluation")for i := range pqs.Queries {fmt.Printf("Query #%d: %v\n", i+1, pqs.Queries[i])}}
Output:First evaluationQuery #1: "GET" = input.method; input.path = ["reviews", _]; input.is_adminQuery #2: "GET" = input.method; input.path = ["reviews", user]; user = input.userSecond evaluationQuery #1: input.path = ["reviews", _]; input.is_adminQuery #2: input.path = ["reviews", user]; user = input.user

func (*Rego)RegoVersion

func (r *Rego) RegoVersion()ast.RegoVersion

typeResult

type Result struct {Expressions []*ExpressionValue `json:"expressions"`BindingsVars               `json:"bindings,omitempty"`}

Result defines the output of Rego evaluation.

typeResultSet

type ResultSet []Result

ResultSet represents a collection of output from Rego evaluation. An emptyresult set represents an undefined query.

func (ResultSet)Allowed

func (rsResultSet) Allowed()bool

Allowed is a helper method that'll return true if all of these conditions hold:- the result set only has one element- there is only one expression in the result set's only element- that expression has the value `true`- there are no bindings.

If bindings are present, this will yield `false`: it would be a pitfall toreturn `true` for a query like `data.authz.allow = x`, which always has resultset element with value true, but could also have a binding `x: false`.

typeTargetPlugin

type TargetPlugin interface {IsTarget(string)boolPrepareForEval(context.Context, *ir.Policy, ...PrepareOption) (TargetPluginEval,error)}

typeTargetPluginEval

type TargetPluginEval interface {Eval(context.Context, *EvalContext,ast.Value) (ast.Value,error)}

typeVars

type Vars map[string]any

Vars represents a collection of variable bindings. The keys are the variablenames and the values are the binding values.

func (Vars)WithoutWildcards

func (vVars) WithoutWildcards()Vars

WithoutWildcards returns a copy of v with wildcard variables removed.

Source Files

View all Source files

Directories

PathSynopsis
Package compile collects a specialized interface to package rego, built for compiling policies into filters.
Package compile collects a specialized interface to package rego, built for compiling policies into filters.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp