Debian Codegraph @

policy/composer.go

raw symbols SCIP
1 // Copyright 2024 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package policy
16
17 import (
18 "cmp"
19 "fmt"
20 "slices"
21 "strings"
22
23 "github.com/google/cel-go/cel"
24 "github.com/google/cel-go/common"
25 "github.com/google/cel-go/common/ast"
26 "github.com/google/cel-go/common/operators"
27 "github.com/google/cel-go/common/types"
28 )
29
30 // ComposerOption is a functional option used to configure a RuleComposer
31 type ComposerOption func(*RuleComposer) (*RuleComposer, error)
32
33 // ExpressionUnnestHeight determines the height at which nested expressions are split into local
34 // variables within the cel.@block declaration.
35 func ExpressionUnnestHeight(height int) ComposerOption {
36 return func(c *RuleComposer) (*RuleComposer, error) {
37 if height <= 0 {
38 return nil, fmt.Errorf("invalid unnest height: value must be positive: %d", height)
39 }
40 c.exprUnnestHeight = height
41 return c, nil
42 }
43 }
44
45 // NewRuleComposer creates a rule composer which stitches together rules within a policy into
46 // a single CEL expression.
47 func NewRuleComposer(env *cel.Env, opts ...ComposerOption) (*RuleComposer, error) {
48 composer := &RuleComposer{
49 env: env,
50 // set the default nesting height to something reasonable.
51 exprUnnestHeight: 25,
52 }
53 var err error
54 for _, opt := range opts {
55 composer, err = opt(composer)
56 if err != nil {
57 return nil, err
58 }
59 }
60 return composer, nil
61 }
62
63 // RuleComposer optimizes a set of expressions into a single expression.
64 type RuleComposer struct {
65 env *cel.Env
66
67 // exprUnnestHeight determines the height at which nested matches are split into
68 // index variables within a cel.@block index declaration when composing matches under
69 // the first-match semantic.
70 exprUnnestHeight int
71 }
72
73 // Compose stitches together a set of expressions within a CompiledRule into a single CEL ast.
74 func (c *RuleComposer) Compose(r *CompiledRule) (*cel.Ast, *cel.Issues) {
75 ruleRoot, _ := c.env.Compile("true")
76 composer := &ruleComposerImpl{
77 rule: r,
78 varIndices: []varIndex{},
79 }
80 // ruleRoot is a placeholder expression used as the root of the AST before optimization. Because
81 // StaticOptimizer would normally copy the source info from it, we must use OptimizeWithSource
82 // to override the correct source.
83 source := recoverOriginalSource(r)
84 opt, err := cel.NewStaticOptimizer(composer, cel.OptimizeWithSource(source))
85 if err != nil {
86 errs := common.NewErrors(source)
87 errs.ReportErrorString(common.NoLocation, err.Error())
88 return nil, cel.NewIssues(errs)
89 }
90 ast, iss := opt.Optimize(c.env, ruleRoot)
91 if iss.Err() != nil {
92 return nil, iss
93 }
94 unnester := &ruleUnnesterImpl{
95 varIndices: []varIndex{},
96 exprUnnestHeight: c.exprUnnestHeight,
97 }
98 opt, err = cel.NewStaticOptimizer(unnester)
99 if err != nil {
100 errs := common.NewErrors(source)
101 errs.ReportErrorString(common.NoLocation, err.Error())
102 return nil, cel.NewIssues(errs)
103 }
104 return opt.Optimize(c.env, ast)
105 }
106
107 func recoverOriginalSource(r *CompiledRule) cel.Source {
108 match := r.Matches()[0]
109 var source cel.Source
110 if match.Output() != nil {
111 source = match.Output().Expr().Source()
112 } else {
113 source = match.Condition().Source()
114 }
115 if rel, ok := source.(*RelativeSource); ok {
116 source = rel.Source
117 }
118 return source
119 }
120
121 type varIndex struct {
122 index int
123 indexVar string
124 localVar string
125 expr ast.Expr
126 celType *types.Type
127 }
128
129 type ruleComposerImpl struct {
130 rule *CompiledRule
131 nextVarIndex int
132 varIndices []varIndex
133 }
134
135 // Optimize implements an AST optimizer for CEL which composes an expression graph into a single
136 // expression value.
137 func (opt *ruleComposerImpl) Optimize(ctx *cel.OptimizerContext, a *ast.AST) *ast.AST {
138 // The input to optimize is a dummy expression which is completely replaced according
139 // to the configuration of the rule composition graph.
140 ruleExpr := opt.optimizeRule(ctx, opt.rule)
141
142 // If there were no variables, return the expression.
143 if len(opt.varIndices) == 0 {
144 return ctx.NewAST(ruleExpr)
145 }
146
147 // Otherwise populate the cel.@block with the variable declarations and wrap the expression
148 // in the block.
149 varExprs := make([]ast.Expr, len(opt.varIndices))
150 for i, vi := range opt.varIndices {
151 varExprs[i] = vi.expr
152 err := ctx.ExtendEnv(cel.Variable(vi.indexVar, vi.celType))
153 if err != nil {
154 ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error())
155 }
156 }
157 blockExpr := ctx.NewCall("cel.@block", ctx.NewList(varExprs, []int32{}), ruleExpr)
158 return ctx.NewAST(blockExpr)
159 }
160
161 func (opt *ruleComposerImpl) optimizeRule(ctx *cel.OptimizerContext, r *CompiledRule) ast.Expr {
162 // Visitor to rewrite variables-prefixed identifiers with index names.
163 vars := r.Variables()
164 for _, v := range vars {
165 opt.registerVariable(ctx, v)
166 }
167
168 matches := r.Matches()
169 matchCount := len(matches)
170 var output compositionStep = nil
171 // If the rule has an optional output, the last result in the ternary should return
172 // `optional.none`. This output is implicit and created here to reflect the desired
173 // last possible output of this type of rule.
174 if r.HasOptionalOutput() {
175 output = newOptionalCompositionStep(ctx, ctx.NewLiteral(types.True), ctx.NewCall("optional.none"))
176 }
177 // Build the rule subgraph.
178 for i := matchCount - 1; i >= 0; i-- {
179 m := matches[i]
180 cond := ctx.CopyASTAndMetadata(m.Condition().NativeRep())
181
182 // If the output is non-nil, then it is considered a non-optional output since
183 // it is explictly stated. If the rule itself is optional, then the base case value
184 // of output being optional.none() will convert the non-optional value to an optional
185 // one.
186 if m.Output() != nil {
187 out := ctx.CopyASTAndMetadata(m.Output().Expr().NativeRep())
188 step := newNonOptionalCompositionStep(ctx, cond, out)
189 output = step.combine(output)
190 continue
191 }
192
193 // If the match has a nested rule, then compute the rule and whether it has
194 // an optional return value.
195 child := m.NestedRule()
196 nestedRule := opt.optimizeRule(ctx, child)
197 nestedHasOptional := child.HasOptionalOutput()
198 if nestedHasOptional {
199 step := newOptionalCompositionStep(ctx, cond, nestedRule)
200 output = step.combine(output)
201 continue
202 }
203 step := newNonOptionalCompositionStep(ctx, cond, nestedRule)
204 output = step.combine(output)
205 }
206
207 matchExpr := output.expr()
208 identVisitor := opt.rewriteVariableName(ctx)
209 ast.PostOrderVisit(matchExpr, identVisitor)
210
211 return matchExpr
212 }
213
214 func (opt *ruleComposerImpl) rewriteVariableName(ctx *cel.OptimizerContext) ast.Visitor {
215 return ast.NewExprVisitor(func(expr ast.Expr) {
216 if expr.Kind() != ast.IdentKind || !strings.HasPrefix(expr.AsIdent(), "variables.") {
217 return
218 }
219 varName := expr.AsIdent()
220 for i := len(opt.varIndices) - 1; i >= 0; i-- {
221 v := opt.varIndices[i]
222 if v.localVar == varName {
223 ctx.UpdateExpr(expr, ctx.NewIdent(v.indexVar))
224 return
225 }
226 }
227 })
228 }
229
230 // registerVariable creates an entry for a variable name within the cel.@block used to enumerate
231 // variables within composed policy expression.
232 func (opt *ruleComposerImpl) registerVariable(ctx *cel.OptimizerContext, v *CompiledVariable) {
233 varName := fmt.Sprintf("variables.%s", v.Name())
234 indexVar := fmt.Sprintf("@index%d", opt.nextVarIndex)
235 varExpr := ctx.CopyASTAndMetadata(v.Expr().NativeRep())
236 ast.PostOrderVisit(varExpr, opt.rewriteVariableName(ctx))
237 vi := varIndex{
238 index: opt.nextVarIndex,
239 indexVar: indexVar,
240 localVar: varName,
241 expr: varExpr,
242 celType: v.Declaration().Type()}
243 opt.varIndices = append(opt.varIndices, vi)
244 opt.nextVarIndex++
245 }
246
247 type ruleUnnesterImpl struct {
248 nextVarIndex int
249 varIndices []varIndex
250 exprUnnestHeight int
251 }
252
253 func (opt *ruleUnnesterImpl) Optimize(ctx *cel.OptimizerContext, a *ast.AST) *ast.AST {
254 // Since the optimizer is based on the original environment provided to the composer,
255 // a second pass on the `cel.@block` will require a rebuilding of the cel environment
256 ruleExpr := ast.NavigateAST(a)
257 var varExprs []ast.Expr
258 var varDecls []cel.EnvOption
259 if ruleExpr.Kind() == ast.CallKind && ruleExpr.AsCall().FunctionName() == "cel.@block" {
260 // Extract the expr from the cel.@block, args[1], as a navigable expr value.
261 // Also extract the variable declarations and all associated types from the cel.@block as
262 // varIndex values, but without doing any rewrites as the types are all correct already.
263 block := ruleExpr.AsCall()
264 ruleExpr = block.Args()[1].(ast.NavigableExpr)
265
266 // Collect the list of variables associated with the block
267 blockList := block.Args()[0].(ast.NavigableExpr)
268 vars := blockList.AsList()
269 varExprs = make([]ast.Expr, vars.Size())
270 varDecls = make([]cel.EnvOption, vars.Size())
271 copy(varExprs, vars.Elements())
272 for i, v := range varExprs {
273 // Track the variable he varDecls set.
274 indexVar := fmt.Sprintf("@index%d", i)
275 celType := a.GetType(v.ID())
276 varDecls[i] = cel.Variable(indexVar, celType)
277 opt.nextVarIndex++
278 }
279 }
280 if len(varDecls) != 0 {
281 err := ctx.ExtendEnv(varDecls...)
282 if err != nil {
283 ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error())
284 }
285 }
286
287 // Attempt to unnest the rule.
288 ruleExpr = opt.maybeUnnestRule(ctx, ruleExpr)
289 // If there were no variables, return the expression.
290 if len(opt.varIndices) == 0 {
291 return a
292 }
293
294 // Otherwise populate the cel.@block with the variable declarations and wrap the expression
295 // in the block.
296 for i := 0; i < len(opt.varIndices); i++ {
297 vi := opt.varIndices[i]
298 varExprs = append(varExprs, vi.expr)
299 err := ctx.ExtendEnv(cel.Variable(vi.indexVar, vi.celType))
300 if err != nil {
301 ctx.ReportErrorAtID(ruleExpr.ID(), "%s", err.Error())
302 }
303 }
304 blockExpr := ctx.NewCall("cel.@block", ctx.NewList(varExprs, []int32{}), ruleExpr)
305 return ctx.NewAST(blockExpr)
306 }
307
308 func (opt *ruleUnnesterImpl) maybeUnnestRule(ctx *cel.OptimizerContext, ruleExpr ast.NavigableExpr) ast.NavigableExpr {
309 // Unnest expressions are ordered from leaf to root via the ast.MatchDescendants call.
310 heights := ast.Heights(ast.NewAST(ruleExpr, nil))
311 unnestMap := map[int64]bool{}
312 unnestExprs := []ast.NavigableExpr{}
313 ast.MatchDescendants(ruleExpr, func(e ast.NavigableExpr) bool {
314 // If the expression is a comprehension, then all unnest candidates captured previously that relate
315 // to the comprehension body should be removed from the list of candidate branches for unnesting.
316 if e.Kind() == ast.ComprehensionKind {
317 // This only removes branches from the map, but not from the list of branches.
318 removeIneligibleSubExprs(e, unnestMap)
319 return false
320 }
321 // Otherwise, if the expression is not a call, don't include it.
322 if e.Kind() != ast.CallKind {
323 return false
324 }
325 height := heights[e.ID()]
326 if height < opt.exprUnnestHeight {
327 return false
328 }
329 unnestMap[e.ID()] = true
330 unnestExprs = append(unnestExprs, e)
331 return true
332 })
333
334 slices.SortStableFunc(unnestExprs, func(a, b ast.NavigableExpr) int {
335 heightA := heights[a.ID()]
336 heightB := heights[b.ID()]
337 return cmp.Compare(heightA, heightB)
338 })
339
340 // Prune the expression set to unnest down to only those not included in comprehensions.
341 for idx := 0; idx < len(unnestExprs)-1; idx++ {
342 e := unnestExprs[idx]
343 if present, found := unnestMap[e.ID()]; !found || !present {
344 continue
345 }
346 height := heights[e.ID()]
347 if height < opt.exprUnnestHeight {
348 continue
349 }
350 reduceHeight(heights, e, opt.exprUnnestHeight)
351 opt.registerUnnestVariable(ctx, e)
352 }
353 return ruleExpr
354 }
355
356 // registerUnnestVariable creates an entry for a variable name within the cel.@block used to unnest
357 // a deeply nested logical branch or logical operator.
358 func (opt *ruleUnnesterImpl) registerUnnestVariable(ctx *cel.OptimizerContext, varExpr ast.NavigableExpr) {
359 indexVar := fmt.Sprintf("@index%d", opt.nextVarIndex)
360 varExprCopy := ctx.CopyASTAndMetadata(ctx.NewAST(varExpr))
361 vi := varIndex{
362 index: opt.nextVarIndex,
363 indexVar: indexVar,
364 expr: varExprCopy,
365 celType: varExpr.Type(),
366 }
367 ctx.UpdateExpr(varExpr, ctx.NewIdent(vi.indexVar))
368 opt.varIndices = append(opt.varIndices, vi)
369 opt.nextVarIndex++
370 }
371
372 // compositionStep interface represents an intermediate stage of rule and match expression composition
373 //
374 // The CompiledRule and CompiledMatch types are meant to represent standalone tuples of condition
375 // and output expressions, and have no notion of how the order of combination would impact composition
376 // since composition rules may vary based on the policy execution semantic, e.g. first-match versus
377 // logical-or, logical-and, or accumulation.
378 type compositionStep interface {
379 // isOptional indicates whether the output step has an optional result.
380 //
381 // Individual conditional attributes are not optional; however, rules and subrules can have optional output.
382 isOptional() bool
383
384 // condition returns the condition associated with the output.
385 condition() ast.Expr
386
387 // isConditional returns true if the condition expression is not trivially true.
388 isConditional() bool
389
390 // expr returns the output expression for the step.
391 expr() ast.Expr
392
393 // combine assembles two output expressions into a single output step.
394 combine(other compositionStep) compositionStep
395 }
396
397 // baseCompositionStep encapsulates the common features of an compositionStep implementation.
398 type baseCompositionStep struct {
399 ctx *cel.OptimizerContext
400 cond ast.Expr
401 out ast.Expr
402 }
403
404 func (b baseCompositionStep) condition() ast.Expr {
405 return b.cond
406 }
407
408 func (b baseCompositionStep) isConditional() bool {
409 c := b.cond
410 return c.Kind() != ast.LiteralKind || c.AsLiteral() != types.True
411 }
412
413 func (b baseCompositionStep) expr() ast.Expr {
414 return b.out
415 }
416
417 // newNonOptionalCompositionStep returns an output step whose output is not optional.
418 func newNonOptionalCompositionStep(ctx *cel.OptimizerContext, cond, out ast.Expr) nonOptionalCompositionStep {
419 return nonOptionalCompositionStep{
420 baseCompositionStep: &baseCompositionStep{
421 ctx: ctx,
422 cond: cond,
423 out: out,
424 },
425 }
426 }
427
428 type nonOptionalCompositionStep struct {
429 *baseCompositionStep
430 }
431
432 // isOptional returns false
433 func (nonOptionalCompositionStep) isOptional() bool {
434 return false
435 }
436
437 // combine assembles a new compositionStep from the target output step an an input output step.
438 //
439 // non-optional.combine(non-optional) // non-optional
440 // (non-optional && conditional).combine(optional) // optional
441 // (non-optional && unconditional).combine(optional) // non-optional
442 //
443 // The last combination case is unusual, but effectively it means that the non-optional value prunes away
444 // the potential optional output.
445 func (s nonOptionalCompositionStep) combine(step compositionStep) compositionStep {
446 if step == nil {
447 // The input `step` may be nil if this is the first compositionStep
448 return s
449 }
450 ctx := s.ctx
451 trueCondition := ctx.NewLiteral(types.True)
452 if step.isOptional() {
453 // If the step is optional, convert the non-optional value to an optional one and return a ternary
454 if s.isConditional() {
455 return newOptionalCompositionStep(ctx,
456 trueCondition,
457 ctx.NewCall(operators.Conditional,
458 s.condition(),
459 ctx.NewCall("optional.of", s.expr()),
460 step.expr()),
461 )
462 }
463 // The `step` is pruned away by a unconditional non-optional step `s`.
464 // Likely a candidate for dead-code warnings.
465 return s
466 }
467 return newNonOptionalCompositionStep(ctx,
468 trueCondition,
469 ctx.NewCall(operators.Conditional,
470 s.condition(),
471 s.expr(),
472 step.expr()))
473 }
474
475 // newOptionalCompositionStep returns an output step with an optional policy output.
476 func newOptionalCompositionStep(ctx *cel.OptimizerContext, cond, out ast.Expr) optionalCompositionStep {
477 return optionalCompositionStep{
478 baseCompositionStep: &baseCompositionStep{
479 ctx: ctx,
480 cond: cond,
481 out: out,
482 },
483 }
484 }
485
486 type optionalCompositionStep struct {
487 *baseCompositionStep
488 }
489
490 // isOptional returns true.
491 func (optionalCompositionStep) isOptional() bool {
492 return true
493 }
494
495 // combine assembles a new compositionStep from the target output step an an input output step.
496 //
497 // optional.combine(optional) // optional
498 // (optional && conditional).combine(non-optional) // optional
499 // (optional && unconditional).combine(non-optional) // non-optional
500 //
501 // The last combination case indicates that an optional value in one case should be resolved
502 // to a non-optional value as
503 func (s optionalCompositionStep) combine(step compositionStep) compositionStep {
504 if step == nil {
505 // This is likely unreachable for an optional step, but worth adding as a safeguard
506 return s
507 }
508 ctx := s.ctx
509 trueCondition := ctx.NewLiteral(types.True)
510 if step.isOptional() {
511 // Introduce a ternary to capture the conditional return when combining a
512 // conditional optional with another optional.
513 if s.isConditional() {
514 return newOptionalCompositionStep(ctx,
515 trueCondition,
516 ctx.NewCall(operators.Conditional,
517 s.condition(),
518 s.expr(),
519 step.expr()),
520 )
521 }
522 // When an optional is unconditionally combined with another optional, rely
523 // on the optional 'or' to fall-through from one optional to another.
524 if !isOptionalNone(step.expr()) {
525 return newOptionalCompositionStep(ctx,
526 trueCondition,
527 ctx.NewMemberCall("or", s.expr(), step.expr()))
528 }
529 // Otherwise, the current step 's' is unconditional and effectively prunes away
530 // the other input 'step'.
531 return s
532 }
533 if s.isConditional() {
534 // Introduce a ternary to capture the conditional return while wrapping the
535 // non-optional result from a lower step into an optional value.
536 return newOptionalCompositionStep(ctx,
537 trueCondition,
538 ctx.NewCall(operators.Conditional,
539 s.condition(),
540 s.expr(),
541 ctx.NewCall("optional.of", step.expr())))
542 }
543 // If the current step is unconditional and the step is non-optional, attempt
544 // to convert to the optional step 's' to a non-optional value using `orValue`
545 // with the 'step' expression value.
546 return newNonOptionalCompositionStep(ctx,
547 trueCondition,
548 ctx.NewMemberCall("orValue", s.expr(), step.expr()),
549 )
550 }
551
552 func isOptionalNone(e ast.Expr) bool {
553 return e.Kind() == ast.CallKind &&
554 e.AsCall().FunctionName() == "optional.none" &&
555 len(e.AsCall().Args()) == 0
556 }
557
558 func removeIneligibleSubExprs(e ast.NavigableExpr, unnestMap map[int64]bool) {
559 for _, id := range comprehensionSubExprIDs(e) {
560 if _, found := unnestMap[id]; found {
561 delete(unnestMap, id)
562 }
563 }
564 }
565
566 func comprehensionSubExprIDs(e ast.NavigableExpr) []int64 {
567 compre := e.AsComprehension()
568 // Almost the same as e.Children(), but skips the iteration range
569 return enumerateExprIDs(
570 compre.AccuInit().(ast.NavigableExpr),
571 compre.LoopCondition().(ast.NavigableExpr),
572 compre.LoopStep().(ast.NavigableExpr),
573 compre.Result().(ast.NavigableExpr),
574 )
575 }
576
577 func enumerateExprIDs(exprs ...ast.NavigableExpr) []int64 {
578 ids := make([]int64, 0, len(exprs))
579 for _, e := range exprs {
580 ids = append(ids, e.ID())
581 ids = append(ids, enumerateExprIDs(e.Children()...)...)
582 }
583 return ids
584 }
585
586 func reduceHeight(heights map[int64]int, e ast.NavigableExpr, amount int) {
587 height := heights[e.ID()]
588 if height < amount {
589 return
590 }
591 heights[e.ID()] = height - amount
592 if parent, hasParent := e.Parent(); hasParent {
593 reduceHeight(heights, parent, amount)
594 }
595 }