forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrego.go
2534 lines (2157 loc) · 67.6 KB
/
rego.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
// Package rego exposes high level APIs for evaluating Rego policies.
package rego
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
bundleUtils "github.com/open-policy-agent/opa/internal/bundle"
"github.com/open-policy-agent/opa/internal/compiler/wasm"
"github.com/open-policy-agent/opa/internal/future"
"github.com/open-policy-agent/opa/internal/ir"
"github.com/open-policy-agent/opa/internal/planner"
"github.com/open-policy-agent/opa/internal/rego/opa"
"github.com/open-policy-agent/opa/internal/wasm/encoding"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/resolver"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/storage/inmem"
"github.com/open-policy-agent/opa/topdown"
"github.com/open-policy-agent/opa/topdown/cache"
"github.com/open-policy-agent/opa/topdown/print"
"github.com/open-policy-agent/opa/tracing"
"github.com/open-policy-agent/opa/types"
"github.com/open-policy-agent/opa/util"
)
const (
defaultPartialNamespace = "partial"
wasmVarPrefix = "^"
)
// nolint: deadcode,varcheck
const (
targetWasm = "wasm"
targetRego = "rego"
)
// CompileResult represents the result of compiling a Rego query, zero or more
// Rego modules, and arbitrary contextual data into an executable.
type CompileResult struct {
Bytes []byte `json:"bytes"`
}
// PartialQueries contains the queries and support modules produced by partial
// evaluation.
type PartialQueries struct {
Queries []ast.Body `json:"queries,omitempty"`
Support []*ast.Module `json:"modules,omitempty"`
}
// PartialResult represents the result of partial evaluation. The result can be
// used to generate a new query that can be run when inputs are known.
type PartialResult struct {
compiler *ast.Compiler
store storage.Store
body ast.Body
builtinDecls map[string]*ast.Builtin
builtinFuncs map[string]*topdown.Builtin
}
// Rego returns an object that can be evaluated to produce a query result.
func (pr PartialResult) Rego(options ...func(*Rego)) *Rego {
options = append(options, Compiler(pr.compiler), Store(pr.store), ParsedQuery(pr.body))
r := New(options...)
// Propagate any custom builtins.
for k, v := range pr.builtinDecls {
r.builtinDecls[k] = v
}
for k, v := range pr.builtinFuncs {
r.builtinFuncs[k] = v
}
return r
}
// preparedQuery is a wrapper around a Rego object which has pre-processed
// state stored on it. Once prepared there are a more limited number of actions
// that can be taken with it. It will, however, be able to evaluate faster since
// it will not have to re-parse or compile as much.
type preparedQuery struct {
r *Rego
cfg *PrepareConfig
}
// EvalContext defines the set of options allowed to be set at evaluation
// time. Any other options will need to be set on a new Rego object.
type EvalContext struct {
hasInput bool
time time.Time
seed io.Reader
rawInput *interface{}
parsedInput ast.Value
metrics metrics.Metrics
txn storage.Transaction
instrument bool
instrumentation *topdown.Instrumentation
partialNamespace string
queryTracers []topdown.QueryTracer
compiledQuery compiledQuery
unknowns []string
disableInlining []ast.Ref
parsedUnknowns []*ast.Term
indexing bool
earlyExit bool
interQueryBuiltinCache cache.InterQueryCache
resolvers []refResolver
sortSets bool
printHook print.Hook
capabilities *ast.Capabilities
}
// EvalOption defines a function to set an option on an EvalConfig
type EvalOption func(*EvalContext)
// EvalInput configures the input for a Prepared Query's evaluation
func EvalInput(input interface{}) EvalOption {
return func(e *EvalContext) {
e.rawInput = &input
e.hasInput = true
}
}
// EvalParsedInput configures the input for a Prepared Query's evaluation
func EvalParsedInput(input ast.Value) EvalOption {
return func(e *EvalContext) {
e.parsedInput = input
e.hasInput = true
}
}
// EvalMetrics configures the metrics for a Prepared Query's evaluation
func EvalMetrics(metric metrics.Metrics) EvalOption {
return func(e *EvalContext) {
e.metrics = metric
}
}
// EvalTransaction configures the Transaction for a Prepared Query's evaluation
func EvalTransaction(txn storage.Transaction) EvalOption {
return func(e *EvalContext) {
e.txn = txn
}
}
// EvalInstrument enables or disables instrumenting for a Prepared Query's evaluation
func EvalInstrument(instrument bool) EvalOption {
return func(e *EvalContext) {
e.instrument = instrument
}
}
// EvalTracer configures a tracer for a Prepared Query's evaluation
// Deprecated: Use EvalQueryTracer instead.
func EvalTracer(tracer topdown.Tracer) EvalOption {
return func(e *EvalContext) {
if tracer != nil {
e.queryTracers = append(e.queryTracers, topdown.WrapLegacyTracer(tracer))
}
}
}
// EvalQueryTracer configures a tracer for a Prepared Query's evaluation
func EvalQueryTracer(tracer topdown.QueryTracer) EvalOption {
return func(e *EvalContext) {
if tracer != nil {
e.queryTracers = append(e.queryTracers, tracer)
}
}
}
// EvalPartialNamespace returns an argument that sets the namespace to use for
// partial evaluation results. The namespace must be a valid package path
// component.
func EvalPartialNamespace(ns string) EvalOption {
return func(e *EvalContext) {
e.partialNamespace = ns
}
}
// EvalUnknowns returns an argument that sets the values to treat as
// unknown during partial evaluation.
func EvalUnknowns(unknowns []string) EvalOption {
return func(e *EvalContext) {
e.unknowns = unknowns
}
}
// EvalDisableInlining returns an argument that adds a set of paths to exclude from
// partial evaluation inlining.
func EvalDisableInlining(paths []ast.Ref) EvalOption {
return func(e *EvalContext) {
e.disableInlining = paths
}
}
// EvalParsedUnknowns returns an argument that sets the values to treat
// as unknown during partial evaluation.
func EvalParsedUnknowns(unknowns []*ast.Term) EvalOption {
return func(e *EvalContext) {
e.parsedUnknowns = unknowns
}
}
// EvalRuleIndexing will disable indexing optimizations for the
// evaluation. This should only be used when tracing in debug mode.
func EvalRuleIndexing(enabled bool) EvalOption {
return func(e *EvalContext) {
e.indexing = enabled
}
}
// EvalEarlyExit will disable 'early exit' optimizations for the
// evaluation. This should only be used when tracing in debug mode.
func EvalEarlyExit(enabled bool) EvalOption {
return func(e *EvalContext) {
e.earlyExit = enabled
}
}
// EvalTime sets the wall clock time to use during policy evaluation.
// time.now_ns() calls will return this value.
func EvalTime(x time.Time) EvalOption {
return func(e *EvalContext) {
e.time = x
}
}
// EvalSeed sets a reader that will seed randomization required by built-in functions.
// If a seed is not provided crypto/rand.Reader is used.
func EvalSeed(r io.Reader) EvalOption {
return func(e *EvalContext) {
e.seed = r
}
}
// EvalInterQueryBuiltinCache sets the inter-query cache that built-in functions can utilize
// during evaluation.
func EvalInterQueryBuiltinCache(c cache.InterQueryCache) EvalOption {
return func(e *EvalContext) {
e.interQueryBuiltinCache = c
}
}
// EvalResolver sets a Resolver for a specified ref path for this evaluation.
func EvalResolver(ref ast.Ref, r resolver.Resolver) EvalOption {
return func(e *EvalContext) {
e.resolvers = append(e.resolvers, refResolver{ref, r})
}
}
// EvalSortSets causes the evaluator to sort sets before returning them as JSON arrays.
func EvalSortSets(yes bool) EvalOption {
return func(e *EvalContext) {
e.sortSets = yes
}
}
// EvalPrintHook sets the object to use for handling print statement outputs.
func EvalPrintHook(ph print.Hook) EvalOption {
return func(e *EvalContext) {
e.printHook = ph
}
}
func (pq preparedQuery) Modules() map[string]*ast.Module {
mods := make(map[string]*ast.Module)
for name, mod := range pq.r.parsedModules {
mods[name] = mod
}
for _, b := range pq.r.bundles {
for _, mod := range b.Modules {
mods[mod.Path] = mod.Parsed
}
}
return mods
}
// newEvalContext creates a new EvalContext overlaying any EvalOptions over top
// the Rego object on the preparedQuery. The returned function should be called
// once the evaluation is complete to close any transactions that might have
// been opened.
func (pq preparedQuery) newEvalContext(ctx context.Context, options []EvalOption) (*EvalContext, func(context.Context), error) {
ectx := &EvalContext{
hasInput: false,
rawInput: nil,
parsedInput: nil,
metrics: nil,
txn: nil,
instrument: false,
instrumentation: nil,
partialNamespace: pq.r.partialNamespace,
queryTracers: nil,
unknowns: pq.r.unknowns,
parsedUnknowns: pq.r.parsedUnknowns,
compiledQuery: compiledQuery{},
indexing: true,
earlyExit: true,
resolvers: pq.r.resolvers,
printHook: pq.r.printHook,
capabilities: pq.r.capabilities,
}
for _, o := range options {
o(ectx)
}
if ectx.metrics == nil {
ectx.metrics = metrics.New()
}
if ectx.instrument {
ectx.instrumentation = topdown.NewInstrumentation(ectx.metrics)
}
// Default to an empty "finish" function
finishFunc := func(context.Context) {}
var err error
ectx.disableInlining, err = parseStringsToRefs(pq.r.disableInlining)
if err != nil {
return nil, finishFunc, err
}
if ectx.txn == nil {
ectx.txn, err = pq.r.store.NewTransaction(ctx)
if err != nil {
return nil, finishFunc, err
}
finishFunc = func(ctx context.Context) {
pq.r.store.Abort(ctx, ectx.txn)
}
}
// If we didn't get an input specified in the Eval options
// then fall back to the Rego object's input fields.
if !ectx.hasInput {
ectx.rawInput = pq.r.rawInput
ectx.parsedInput = pq.r.parsedInput
}
if ectx.parsedInput == nil {
if ectx.rawInput == nil {
// Fall back to the original Rego objects input if none was specified
// Note that it could still be nil
ectx.rawInput = pq.r.rawInput
}
if pq.r.target != targetWasm {
ectx.parsedInput, err = pq.r.parseRawInput(ectx.rawInput, ectx.metrics)
if err != nil {
return nil, finishFunc, err
}
}
}
return ectx, finishFunc, nil
}
// PreparedEvalQuery holds the prepared Rego state that has been pre-processed
// for subsequent evaluations.
type PreparedEvalQuery struct {
preparedQuery
}
// Eval evaluates this PartialResult's Rego object with additional eval options
// and 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 opened
// if one is not provided with an EvalOption.
func (pq PreparedEvalQuery) Eval(ctx context.Context, options ...EvalOption) (ResultSet, error) {
ectx, finish, err := pq.newEvalContext(ctx, options)
if err != nil {
return nil, err
}
defer finish(ctx)
ectx.compiledQuery = pq.r.compiledQueries[evalQueryType]
return pq.r.eval(ctx, ectx)
}
// PreparedPartialQuery holds the prepared Rego state that has been pre-processed
// for partial evaluations.
type PreparedPartialQuery struct {
preparedQuery
}
// 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 opened
// if one is not provided with an EvalOption.
func (pq PreparedPartialQuery) Partial(ctx context.Context, options ...EvalOption) (*PartialQueries, error) {
ectx, finish, err := pq.newEvalContext(ctx, options)
if err != nil {
return nil, err
}
defer finish(ctx)
ectx.compiledQuery = pq.r.compiledQueries[partialQueryType]
return pq.r.partial(ctx, ectx)
}
// Errors represents a collection of errors returned when evaluating Rego.
type Errors []error
func (errs Errors) Error() string {
if len(errs) == 0 {
return "no error"
}
if len(errs) == 1 {
return fmt.Sprintf("1 error occurred: %v", errs[0].Error())
}
buf := []string{fmt.Sprintf("%v errors occurred", len(errs))}
for _, err := range errs {
buf = append(buf, err.Error())
}
return strings.Join(buf, "\n")
}
var errPartialEvaluationNotEffective = errors.New("partial evaluation not effective")
// IsPartialEvaluationNotEffectiveErr returns true if err is an error returned by
// this package to indicate that partial evaluation was ineffective.
func IsPartialEvaluationNotEffectiveErr(err error) bool {
errs, ok := err.(Errors)
if !ok {
return false
}
return len(errs) == 1 && errs[0] == errPartialEvaluationNotEffective
}
type compiledQuery struct {
query ast.Body
compiler ast.QueryCompiler
}
type queryType int
// Define a query type for each of the top level Rego
// API's that compile queries differently.
const (
evalQueryType queryType = iota
partialResultQueryType queryType = iota
partialQueryType queryType = iota
compileQueryType queryType = iota
)
type loadPaths struct {
paths []string
filter loader.Filter
}
// Rego constructs a query and can be evaluated to obtain results.
type Rego struct {
query string
parsedQuery ast.Body
compiledQueries map[queryType]compiledQuery
pkg string
parsedPackage *ast.Package
imports []string
parsedImports []*ast.Import
rawInput *interface{}
parsedInput ast.Value
unknowns []string
parsedUnknowns []*ast.Term
disableInlining []string
shallowInlining bool
skipPartialNamespace bool
partialNamespace string
modules []rawModule
parsedModules map[string]*ast.Module
compiler *ast.Compiler
store storage.Store
ownStore bool
txn storage.Transaction
metrics metrics.Metrics
queryTracers []topdown.QueryTracer
tracebuf *topdown.BufferTracer
trace bool
instrumentation *topdown.Instrumentation
instrument bool
capture map[*ast.Expr]ast.Var // map exprs to generated capture vars
termVarID int
dump io.Writer
runtime *ast.Term
time time.Time
seed io.Reader
capabilities *ast.Capabilities
builtinDecls map[string]*ast.Builtin
builtinFuncs map[string]*topdown.Builtin
unsafeBuiltins map[string]struct{}
loadPaths loadPaths
bundlePaths []string
bundles map[string]*bundle.Bundle
skipBundleVerification bool
interQueryBuiltinCache cache.InterQueryCache
strictBuiltinErrors bool
resolvers []refResolver
schemaSet *ast.SchemaSet
target string // target type (wasm, rego, etc.)
opa opa.EvalEngine
generateJSON func(*ast.Term, *EvalContext) (interface{}, error)
printHook print.Hook
enablePrintStatements bool
distributedTacingOpts tracing.Options
}
// Function represents a built-in function that is callable in Rego.
type Function struct {
Name string
Decl *types.Function
Memoize bool
}
// BuiltinContext contains additional attributes from the evaluator that
// built-in functions can use, e.g., the request context.Context, caches, etc.
type BuiltinContext = topdown.BuiltinContext
type (
// Builtin1 defines a built-in function that accepts 1 argument.
Builtin1 func(bctx BuiltinContext, op1 *ast.Term) (*ast.Term, error)
// Builtin2 defines a built-in function that accepts 2 arguments.
Builtin2 func(bctx BuiltinContext, op1, op2 *ast.Term) (*ast.Term, error)
// Builtin3 defines a built-in function that accepts 3 argument.
Builtin3 func(bctx BuiltinContext, op1, op2, op3 *ast.Term) (*ast.Term, error)
// Builtin4 defines a built-in function that accepts 4 argument.
Builtin4 func(bctx BuiltinContext, op1, op2, op3, op4 *ast.Term) (*ast.Term, error)
// BuiltinDyn defines a built-in function that accepts a list of arguments.
BuiltinDyn func(bctx BuiltinContext, terms []*ast.Term) (*ast.Term, error)
)
// RegisterBuiltin1 adds a built-in function globally inside the OPA runtime.
func RegisterBuiltin1(decl *Function, impl Builtin1) {
ast.RegisterBuiltin(&ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
})
topdown.RegisterBuiltinFunc(decl.Name, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return impl(bctx, terms[0]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// RegisterBuiltin2 adds a built-in function globally inside the OPA runtime.
func RegisterBuiltin2(decl *Function, impl Builtin2) {
ast.RegisterBuiltin(&ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
})
topdown.RegisterBuiltinFunc(decl.Name, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return impl(bctx, terms[0], terms[1]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// RegisterBuiltin3 adds a built-in function globally inside the OPA runtime.
func RegisterBuiltin3(decl *Function, impl Builtin3) {
ast.RegisterBuiltin(&ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
})
topdown.RegisterBuiltinFunc(decl.Name, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return impl(bctx, terms[0], terms[1], terms[2]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// RegisterBuiltin4 adds a built-in function globally inside the OPA runtime.
func RegisterBuiltin4(decl *Function, impl Builtin4) {
ast.RegisterBuiltin(&ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
})
topdown.RegisterBuiltinFunc(decl.Name, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return impl(bctx, terms[0], terms[1], terms[2], terms[3]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// RegisterBuiltinDyn adds a built-in function globally inside the OPA runtime.
func RegisterBuiltinDyn(decl *Function, impl BuiltinDyn) {
ast.RegisterBuiltin(&ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
})
topdown.RegisterBuiltinFunc(decl.Name, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return impl(bctx, terms) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// Function1 returns an option that adds a built-in function to the Rego object.
func Function1(decl *Function, f Builtin1) func(*Rego) {
return newFunction(decl, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return f(bctx, terms[0]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// Function2 returns an option that adds a built-in function to the Rego object.
func Function2(decl *Function, f Builtin2) func(*Rego) {
return newFunction(decl, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return f(bctx, terms[0], terms[1]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// Function3 returns an option that adds a built-in function to the Rego object.
func Function3(decl *Function, f Builtin3) func(*Rego) {
return newFunction(decl, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return f(bctx, terms[0], terms[1], terms[2]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// Function4 returns an option that adds a built-in function to the Rego object.
func Function4(decl *Function, f Builtin4) func(*Rego) {
return newFunction(decl, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return f(bctx, terms[0], terms[1], terms[2], terms[3]) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// FunctionDyn returns an option that adds a built-in function to the Rego object.
func FunctionDyn(decl *Function, f BuiltinDyn) func(*Rego) {
return newFunction(decl, func(bctx BuiltinContext, terms []*ast.Term, iter func(*ast.Term) error) error {
result, err := memoize(decl, bctx, terms, func() (*ast.Term, error) { return f(bctx, terms) })
return finishFunction(decl.Name, bctx, result, err, iter)
})
}
// FunctionDecl returns an option that adds a custom-built-in function
// __declaration__. NO implementation is provided. This is used for
// non-interpreter execution envs (e.g., Wasm).
func FunctionDecl(decl *Function) func(*Rego) {
return newDecl(decl)
}
func newDecl(decl *Function) func(*Rego) {
return func(r *Rego) {
r.builtinDecls[decl.Name] = &ast.Builtin{
Name: decl.Name,
Decl: decl.Decl,
}
}
}
type memo struct {
term *ast.Term
err error
}
type memokey string
func memoize(decl *Function, bctx BuiltinContext, terms []*ast.Term, ifEmpty func() (*ast.Term, error)) (*ast.Term, error) {
if !decl.Memoize {
return ifEmpty()
}
// NOTE(tsandall): we assume memoization is applied to infrequent built-in
// calls that do things like fetch data from remote locations. As such,
// converting the terms to strings is acceptable for now.
var b strings.Builder
if _, err := b.WriteString(decl.Name); err != nil {
return nil, err
}
// The term slice _may_ include an output term depending on how the caller
// referred to the built-in function. Only use the arguments as the cache
// key. Unification ensures we don't get false positive matches.
for i := 0; i < len(decl.Decl.Args()); i++ {
if _, err := b.WriteString(terms[i].String()); err != nil {
return nil, err
}
}
key := memokey(b.String())
hit, ok := bctx.Cache.Get(key)
var m memo
if ok {
m = hit.(memo)
} else {
m.term, m.err = ifEmpty()
bctx.Cache.Put(key, m)
}
return m.term, m.err
}
// Dump returns an argument that sets the writer to dump debugging information to.
func Dump(w io.Writer) func(r *Rego) {
return func(r *Rego) {
r.dump = w
}
}
// Query returns an argument that sets the Rego query.
func Query(q string) func(r *Rego) {
return func(r *Rego) {
r.query = q
}
}
// ParsedQuery returns an argument that sets the Rego query.
func ParsedQuery(q ast.Body) func(r *Rego) {
return func(r *Rego) {
r.parsedQuery = q
}
}
// Package returns an argument that sets the Rego package on the query's
// context.
func Package(p string) func(r *Rego) {
return func(r *Rego) {
r.pkg = p
}
}
// ParsedPackage returns an argument that sets the Rego package on the query's
// context.
func ParsedPackage(pkg *ast.Package) func(r *Rego) {
return func(r *Rego) {
r.parsedPackage = pkg
}
}
// Imports returns an argument that adds a Rego import to the query's context.
func Imports(p []string) func(r *Rego) {
return func(r *Rego) {
r.imports = append(r.imports, p...)
}
}
// ParsedImports returns an argument that adds Rego imports to the query's
// context.
func ParsedImports(imp []*ast.Import) func(r *Rego) {
return func(r *Rego) {
r.parsedImports = append(r.parsedImports, imp...)
}
}
// Input returns an argument that sets the Rego input document. Input should be
// a native Go value representing the input document.
func Input(x interface{}) func(r *Rego) {
return func(r *Rego) {
r.rawInput = &x
}
}
// ParsedInput returns an argument that sets the Rego input document.
func ParsedInput(x ast.Value) func(r *Rego) {
return func(r *Rego) {
r.parsedInput = x
}
}
// Unknowns returns an argument that sets the values to treat as unknown during
// partial evaluation.
func Unknowns(unknowns []string) func(r *Rego) {
return func(r *Rego) {
r.unknowns = unknowns
}
}
// ParsedUnknowns returns an argument that sets the values to treat as unknown
// during partial evaluation.
func ParsedUnknowns(unknowns []*ast.Term) func(r *Rego) {
return func(r *Rego) {
r.parsedUnknowns = unknowns
}
}
// DisableInlining adds a set of paths to exclude from partial evaluation inlining.
func DisableInlining(paths []string) func(r *Rego) {
return func(r *Rego) {
r.disableInlining = paths
}
}
// ShallowInlining prevents rules that depend on unknown values from being inlined.
// Rules that only depend on known values are inlined.
func ShallowInlining(yes bool) func(r *Rego) {
return func(r *Rego) {
r.shallowInlining = yes
}
}
// SkipPartialNamespace disables namespacing of partial evalution results for support
// rules generated from policy. Synthetic support rules are still namespaced.
func SkipPartialNamespace(yes bool) func(r *Rego) {
return func(r *Rego) {
r.skipPartialNamespace = yes
}
}
// PartialNamespace returns an argument that sets the namespace to use for
// partial evaluation results. The namespace must be a valid package path
// component.
func PartialNamespace(ns string) func(r *Rego) {
return func(r *Rego) {
r.partialNamespace = ns
}
}
// Module returns an argument that adds a Rego module.
func Module(filename, input string) func(r *Rego) {
return func(r *Rego) {
r.modules = append(r.modules, rawModule{
filename: filename,
module: input,
})
}
}
// ParsedModule returns an argument that adds a parsed Rego module. If a string
// module with the same filename name is added, it will override the parsed
// module.
func ParsedModule(module *ast.Module) func(*Rego) {
return func(r *Rego) {
var filename string
if module.Package.Location != nil {
filename = module.Package.Location.File
} else {
filename = fmt.Sprintf("module_%p.rego", module)
}
r.parsedModules[filename] = module
}
}
// Load returns an argument that adds a filesystem path to load data
// and Rego modules from. Any file with a *.rego, *.yaml, or *.json
// extension will be loaded. The path can be either a directory or file,
// directories are loaded recursively. The optional ignore string patterns
// can 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.
func Load(paths []string, filter loader.Filter) func(r *Rego) {
return func(r *Rego) {
r.loadPaths = loadPaths{paths, filter}
}
}
// LoadBundle returns an argument that adds a filesystem path to load
// a bundle from. The path can be a compressed bundle file or a directory
// to be loaded as a bundle.
// Note: Loading bundles will require a write transaction on the store.
func LoadBundle(path string) func(r *Rego) {
return func(r *Rego) {
r.bundlePaths = append(r.bundlePaths, path)
}
}
// ParsedBundle returns an argument that adds a bundle to be loaded.
func ParsedBundle(name string, b *bundle.Bundle) func(r *Rego) {
return func(r *Rego) {
r.bundles[name] = b
}
}
// Compiler returns an argument that sets the Rego compiler.
func Compiler(c *ast.Compiler) func(r *Rego) {
return func(r *Rego) {
r.compiler = c
}
}
// Store returns an argument that sets the policy engine's data storage layer.
//
// If using the Load, LoadBundle, or ParsedBundle options then a transaction
// must also be provided via the Transaction() option. After loading files
// or bundles the transaction should be aborted or committed.
func Store(s storage.Store) func(r *Rego) {
return func(r *Rego) {
r.store = s
}
}
// Transaction returns an argument that sets the transaction to use for storage
// layer operations.
//
// Requires the store associated with the transaction to be provided via the
// Store() option. If using Load(), LoadBundle(), or ParsedBundle() options
// the transaction will likely require write params.
func Transaction(txn storage.Transaction) func(r *Rego) {
return func(r *Rego) {
r.txn = txn
}
}
// Metrics returns an argument that sets the metrics collection.
func Metrics(m metrics.Metrics) func(r *Rego) {
return func(r *Rego) {
r.metrics = m
}
}
// Instrument returns an argument that enables instrumentation for diagnosing
// performance issues.
func Instrument(yes bool) func(r *Rego) {
return func(r *Rego) {
r.instrument = yes
}
}
// Trace returns an argument that enables tracing on r.
func Trace(yes bool) func(r *Rego) {
return func(r *Rego) {
r.trace = yes
}
}
// Tracer returns an argument that adds a query tracer to r.
// Deprecated: Use QueryTracer instead.
func Tracer(t topdown.Tracer) func(r *Rego) {
return func(r *Rego) {
if t != nil {
r.queryTracers = append(r.queryTracers, topdown.WrapLegacyTracer(t))
}
}
}
// QueryTracer returns an argument that adds a query tracer to r.
func QueryTracer(t topdown.QueryTracer) func(r *Rego) {
return func(r *Rego) {
if t != nil {
r.queryTracers = append(r.queryTracers, t)
}
}
}
// Runtime returns an argument that sets the runtime data to provide to the
// evaluation engine.
func Runtime(term *ast.Term) func(r *Rego) {
return func(r *Rego) {
r.runtime = term
}
}
// Time sets the wall clock time to use during policy evaluation. Prepared queries
// do not inherit this parameter. Use EvalTime to set the wall clock time when
// executing a prepared query.
func Time(x time.Time) func(r *Rego) {
return func(r *Rego) {
r.time = x
}
}
// Seed sets a reader that will seed randomization required by built-in functions.
// If a seed is not provided crypto/rand.Reader is used.
func Seed(r io.Reader) func(*Rego) {
return func(e *Rego) {
e.seed = r
}
}
// PrintTrace is a helper function to write a human-readable version of the
// trace to the writer w.
func PrintTrace(w io.Writer, r *Rego) {
if r == nil || r.tracebuf == nil {
return
}
topdown.PrettyTrace(w, *r.tracebuf)
}
// PrintTraceWithLocation is a helper function to write a human-readable version of the
// trace to the writer w.
func PrintTraceWithLocation(w io.Writer, r *Rego) {
if r == nil || r.tracebuf == nil {
return
}
topdown.PrettyTraceWithLocation(w, *r.tracebuf)
}
// UnsafeBuiltins sets the built-in functions to treat as unsafe and not allow.
// This option is ignored for module compilation if the caller supplies the
// compiler. This option is always honored for query compilation. Provide an
// empty (non-nil) map to disable checks on queries.
func UnsafeBuiltins(unsafeBuiltins map[string]struct{}) func(r *Rego) {
return func(r *Rego) {
r.unsafeBuiltins = unsafeBuiltins
}