Debian Codegraph @

policy/compiler.go

raw
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 provides an extensible parser and compiler for composing
16 // a graph of CEL expressions into a single evaluable expression.
17 package policy
18
19 import (
20 "fmt"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/common"
24 "github.com/google/cel-go/common/ast"
25 "github.com/google/cel-go/common/containers"
26 "github.com/google/cel-go/common/decls"
27 "github.com/google/cel-go/common/types"
28 "github.com/google/cel-go/common/types/ref"
29 )
30
31 // CompiledRule represents the variables and match blocks associated with a rule block.
32 type CompiledRule struct {
33 exprID int64
34 id *ValueString
35 variables []*CompiledVariable
36 matches []*CompiledMatch
37 }
38
39 // SourceID returns the source metadata identifier associated with the compiled rule.
40 func (r *CompiledRule) SourceID() int64 {
41 return r.exprID
42 }
43
44 // ID returns the expression id associated with the rule.
45 func (r *CompiledRule) ID() *ValueString {
46 return r.id
47 }
48
49 // Variables rturns the list of CompiledVariable values associated with the rule.
50 func (r *CompiledRule) Variables() []*CompiledVariable {
51 return r.variables[:]
52 }
53
54 // Matches returns the list of matches associated with the rule.
55 func (r *CompiledRule) Matches() []*CompiledMatch {
56 return r.matches[:]
57 }
58
59 // OutputType returns the output type of the first match clause as all match clauses
60 // are validated for agreement prior to construction fo the CompiledRule.
61 func (r *CompiledRule) OutputType() *cel.Type {
62 // It's a compilation error if the output types of the matches don't agree
63 for _, m := range r.Matches() {
64 return m.OutputType()
65 }
66 return cel.DynType
67 }
68
69 // HasOptionalOutput returns whether the rule returns a concrete or optional value.
70 // The rule may return an optional value if all match expressions under the rule are conditional.
71 func (r *CompiledRule) HasOptionalOutput() bool {
72 optionalOutput := false
73 for _, m := range r.Matches() {
74 if m.NestedRule() != nil && m.NestedRule().HasOptionalOutput() {
75 return true
76 }
77 if m.ConditionIsLiteral(types.True) {
78 return false
79 }
80 optionalOutput = true
81 }
82 return optionalOutput
83 }
84
85 // CompiledVariable represents the variable name, expression, and associated type-check declaration.
86 type CompiledVariable struct {
87 exprID int64
88 name string
89 expr *cel.Ast
90 varDecl *decls.VariableDecl
91 }
92
93 // SourceID returns the source metadata identifier associated with the variable.
94 func (v *CompiledVariable) SourceID() int64 {
95 return v.exprID
96 }
97
98 // Name returns the variable name.
99 func (v *CompiledVariable) Name() string {
100 return v.name
101 }
102
103 // Expr returns the compiled expression associated with the variable name.
104 func (v *CompiledVariable) Expr() *cel.Ast {
105 return v.expr
106 }
107
108 // Declaration returns the type-check declaration associated with the variable.
109 func (v *CompiledVariable) Declaration() *decls.VariableDecl {
110 return v.varDecl
111 }
112
113 // CompiledMatch represents a match block which has an optional condition (true, by default) as well
114 // as an output or a nested rule (one or the other, but not both).
115 type CompiledMatch struct {
116 exprID int64
117 cond *cel.Ast
118 output *OutputValue
119 nestedRule *CompiledRule
120 }
121
122 // SourceID returns the source identifier associated with the compiled match.
123 func (m *CompiledMatch) SourceID() int64 {
124 return m.exprID
125 }
126
127 // Condition returns the compiled predicate expression which must evaluate to true before the output
128 // or subrule is entered.
129 func (m *CompiledMatch) Condition() *cel.Ast {
130 return m.cond
131 }
132
133 // ConditionIsLiteral indicates whether the condition for the match is a literal with a given value.
134 func (m *CompiledMatch) ConditionIsLiteral(val ref.Val) bool {
135 c := m.cond.NativeRep().Expr()
136 return c.Kind() == ast.LiteralKind && c.AsLiteral().Equal(val) == types.True
137 }
138
139 // Output returns the compiled output expression associated with the match block, if set.
140 func (m *CompiledMatch) Output() *OutputValue {
141 return m.output
142 }
143
144 // NestedRule returns the nested rule, if set.
145 func (m *CompiledMatch) NestedRule() *CompiledRule {
146 return m.nestedRule
147 }
148
149 // OutputType returns the cel.Type associated with output expression.
150 func (m *CompiledMatch) OutputType() *cel.Type {
151 if m.output != nil {
152 return m.output.Expr().OutputType()
153 }
154 if m.nestedRule != nil {
155 return m.nestedRule.OutputType()
156 }
157 return cel.DynType
158 }
159
160 // OutputValue represents the output expression associated with a match block.
161 type OutputValue struct {
162 exprID int64
163 expr *cel.Ast
164 }
165
166 // SourceID returns the expression id associated with the output expression.
167 func (o *OutputValue) SourceID() int64 {
168 return o.exprID
169 }
170
171 // Expr returns the compiled expression associated with the output.
172 func (o *OutputValue) Expr() *cel.Ast {
173 return o.expr
174 }
175
176 // CompilerOption specifies a functional option to be applied to new RuleComposer instances.
177 type CompilerOption func(*compiler) error
178
179 // MaxNestedExpressions limits the number of variable and nested rule expressions during compilation.
180 //
181 // Defaults to 100 if not set.
182 func MaxNestedExpressions(limit int) CompilerOption {
183 return func(c *compiler) error {
184 if limit <= 0 {
185 return fmt.Errorf("nested expression limit must be non-negative, non-zero value: %d", limit)
186 }
187 c.maxNestedExpressions = limit
188 return nil
189 }
190 }
191
192 // MatchCompiler is an interface that provides the necessary functionality for compiling the output
193 // of a match.
194 type MatchCompiler interface {
195 // Env returns the rule environment for the match compiler.
196 Env() *cel.Env
197 // RelSource returns a RelativeSource for a given expression id.
198 RelSource(ValueString) *RelativeSource
199 // ReportErrorAtID reports an error at the given expression id.
200 ReportErrorAtID(int64, string, ...any)
201 }
202
203 type matchCompilerImpl struct {
204 env *cel.Env
205 c *compiler
206 iss *cel.Issues
207 }
208
209 // Env returns the current environment available to the match expression being compiled.
210 func (mc *matchCompilerImpl) Env() *cel.Env {
211 return mc.env
212 }
213
214 // RelSource exposes the compiler's relative source function.
215 func (mc *matchCompilerImpl) RelSource(pstr ValueString) *RelativeSource {
216 return mc.c.relSource(pstr)
217 }
218
219 // ReportErrorAtID exposes the issue reporter for the match compiler.
220 func (mc *matchCompilerImpl) ReportErrorAtID(id int64, message string, args ...any) {
221 mc.iss.ReportErrorAtID(id, message, args...)
222 }
223
224 // CompileMatchOutputFunc is a function that compiles the output of a match.
225 type CompileMatchOutputFunc func(mc MatchCompiler, m *Match, p *Policy) (*cel.Ast, *cel.Issues)
226
227 // CompileMatchOutput sets a custom match output compiling function.
228 func CompileMatchOutput(f CompileMatchOutputFunc) CompilerOption {
229 return func(c *compiler) error {
230 c.compileMatchOutput = f
231 return nil
232 }
233 }
234
235 // Compile combines the policy compilation and composition steps into a single call.
236 //
237 // This generates a single CEL AST from a collection of policy expressions associated with a
238 // CEL environment.
239 func Compile(env *cel.Env, p *Policy, opts ...CompilerOption) (*cel.Ast, *cel.Issues) {
240 rule, iss := CompileRule(env, p, opts...)
241 if iss.Err() != nil {
242 return nil, iss
243 }
244 // An error cannot happen when composing without supplying options
245 composer, _ := NewRuleComposer(env)
246 return composer.Compose(rule)
247 }
248
249 // CompileRule creates a compiled rules from the policy which contains a set of compiled variables and
250 // match statements. The compiled rule defines an expression graph, which can be composed into a single
251 // expression via the RuleComposer.Compose method.
252 func CompileRule(env *cel.Env, p *Policy, opts ...CompilerOption) (*CompiledRule, *cel.Issues) {
253 c := &compiler{
254 env: env,
255 info: p.SourceInfo(),
256 src: p.Source(),
257 compileMatchOutput: defaultCompileMatchOutput,
258 maxNestedExpressions: defaultMaxNestedExpressions,
259 }
260 var err error
261 errs := common.NewErrors(c.src)
262 iss := cel.NewIssuesWithSourceInfo(errs, c.info)
263 for _, o := range opts {
264 if err = o(c); err != nil {
265 iss.ReportErrorAtID(p.Name().ID, "error configuring compiler option: %s", err)
266 return nil, iss
267 }
268 }
269 c.env, err = c.env.Extend(cel.EagerlyValidateDeclarations(true))
270 if err != nil {
271 iss.ReportErrorAtID(p.Name().ID, "error configuring environment: %s", err)
272 return nil, iss
273 }
274
275 importCount := len(p.Imports())
276 if importCount > 0 {
277 importNames := make([]string, 0, importCount)
278 for _, imp := range p.Imports() {
279 typeName := imp.Name().Value
280 _, err := containers.NewContainer(containers.Abbrevs(typeName))
281 if err != nil {
282 iss.ReportErrorAtID(imp.Name().ID, "error configuring import: %s", err)
283 } else {
284 importNames = append(importNames, typeName)
285 }
286 }
287 env, err := c.env.Extend(cel.Abbrevs(importNames...))
288 if err != nil {
289 // validation happens earlier in the sequence, so this should be unreachable.
290 iss.ReportErrorAtID(p.Imports()[0].SourceID(), "error configuring imports: %s", err)
291 } else {
292 c.env = env
293 }
294 }
295 return c.compileRule(p.Rule(), p, c.env, iss)
296 }
297
298 type compiler struct {
299 env *cel.Env
300 info *ast.SourceInfo
301 src *Source
302
303 compileMatchOutput CompileMatchOutputFunc
304 maxNestedExpressions int
305 nestedCount int
306 }
307
308 func (c *compiler) compileRule(r *Rule, p *Policy, ruleEnv *cel.Env, iss *cel.Issues) (*CompiledRule, *cel.Issues) {
309 compiledVars := make([]*CompiledVariable, len(r.Variables()))
310 for i, v := range r.Variables() {
311 exprSrc := c.relSource(v.Expression())
312 varAST, exprIss := ruleEnv.CompileSource(exprSrc)
313 varName := v.Name().Value
314
315 // Determine the variable type. If the expression is an error then record the error and
316 // mark the variable type as dyn to permit compilation to continue.
317 varType := types.DynType
318 if exprIss.Err() != nil {
319 iss = iss.Append(exprIss)
320 } else {
321 // Otherwise, the expression compiled successfully and we use its output type.
322 varType = varAST.OutputType()
323 }
324
325 // Introduce the variable into the environment. By extending the environment, the variables
326 // are effectively scoped such that they must be declared before use.
327 varDecl := decls.NewVariable(fmt.Sprintf("%s.%s", variablePrefix, varName), varType)
328 varEnv, err := ruleEnv.Extend(cel.Variable(varDecl.Name(), varDecl.Type()))
329 if err != nil {
330 iss.ReportErrorAtID(v.exprID, "invalid variable declaration: %s", err.Error())
331 } else {
332 ruleEnv = varEnv
333 }
334 compiledVar := &CompiledVariable{
335 exprID: v.name.ID,
336 name: v.name.Value,
337 expr: varAST,
338 varDecl: varDecl,
339 }
340 compiledVars[i] = compiledVar
341
342 // Increment the nesting count post-compile.
343 c.nestedCount++
344 if c.nestedCount == c.maxNestedExpressions+1 {
345 iss.ReportErrorAtID(compiledVar.SourceID(), "variable exceeds nested expression limit")
346 }
347 }
348
349 // Compile the set of match conditions under the rule.
350 compiledMatches := []*CompiledMatch{}
351 for _, m := range r.Matches() {
352 condSrc := c.relSource(m.Condition())
353 condAST, condIss := ruleEnv.CompileSource(condSrc)
354 iss = iss.Append(condIss)
355 // This case cannot happen when the Policy object is parsed from yaml, but could happen
356 // with a non-YAML generation of the Policy object.
357 // TODO: Test this case once there's an alternative method of constructing Policy objects
358 if m.HasOutput() && m.HasRule() {
359 iss.ReportErrorAtID(m.Condition().ID, "either output or rule may be set but not both")
360 continue
361 }
362 if m.HasOutput() {
363 mc := &matchCompilerImpl{env: ruleEnv, c: c, iss: iss}
364 outAST, outIss := c.compileMatchOutput(mc, m, p)
365 iss = iss.Append(outIss)
366 compiledMatches = append(compiledMatches, &CompiledMatch{
367 exprID: m.exprID,
368 cond: condAST,
369 output: &OutputValue{
370 exprID: m.Output().ID,
371 expr: outAST,
372 },
373 })
374 continue
375 }
376 if m.HasRule() {
377 nestedRule, ruleIss := c.compileRule(m.Rule(), p, ruleEnv, iss)
378 iss = iss.Append(ruleIss)
379 compiledMatches = append(compiledMatches, &CompiledMatch{
380 exprID: m.exprID,
381 cond: condAST,
382 nestedRule: nestedRule,
383 })
384
385 // Increment the nesting count post-compile.
386 c.nestedCount++
387 if c.nestedCount == c.maxNestedExpressions+1 {
388 iss.ReportErrorAtID(nestedRule.SourceID(), "rule exceeds nested expression limit")
389 }
390 }
391 }
392
393 // Validate that all branches in the rule are reachable
394 rule := &CompiledRule{
395 exprID: r.exprID,
396 id: r.id,
397 variables: compiledVars,
398 matches: compiledMatches,
399 }
400
401 // Note: Consider supporting configurable policy validators that take the policy, rule, and issues
402 // Validate type agreement between the different match outputs
403 c.checkMatchOutputTypesAgree(rule, iss)
404 // Validate that all branches in the policy are reachable
405 c.checkUnreachableCode(rule, iss)
406
407 return rule, iss
408 }
409
410 func defaultCompileMatchOutput(mc MatchCompiler, m *Match, p *Policy) (*cel.Ast, *cel.Issues) {
411 outSrc := mc.RelSource(m.Output())
412 return mc.Env().CompileSource(outSrc)
413 }
414
415 func (c *compiler) checkMatchOutputTypesAgree(rule *CompiledRule, iss *cel.Issues) {
416 var outputType *cel.Type
417 for _, m := range rule.Matches() {
418 if outputType == nil {
419 outputType = m.OutputType()
420 if outputType.TypeName() == "error" {
421 outputType = nil
422 continue
423 }
424 }
425 matchOutputType := m.OutputType()
426 if matchOutputType.TypeName() == "error" {
427 continue
428 }
429 // Handle assignability as the output type is assignable to the match output or vice versa.
430 // During composition, this is roughly how the type-checker will handle the type agreement check.
431 if !(outputType.IsAssignableType(matchOutputType) || matchOutputType.IsAssignableType(outputType)) {
432 sourceID := m.SourceID()
433 if m.Output() != nil {
434 sourceID = m.Output().SourceID()
435 } else if m.NestedRule() != nil {
436 sourceID = m.NestedRule().SourceID()
437 }
438 iss.ReportErrorAtID(sourceID, "incompatible output types: block has output type %s, but previous outputs have type %s", matchOutputType, outputType)
439 return
440 }
441 }
442 }
443
444 func (c *compiler) checkUnreachableCode(rule *CompiledRule, iss *cel.Issues) {
445 ruleHasOptional := rule.HasOptionalOutput()
446 compiledMatches := rule.Matches()
447 matchCount := len(compiledMatches)
448 for i := matchCount - 1; i >= 0; i-- {
449 m := compiledMatches[i]
450 triviallyTrue := m.ConditionIsLiteral(types.True)
451
452 if triviallyTrue && !ruleHasOptional && i != matchCount-1 {
453 if m.Output() != nil {
454 iss.ReportErrorAtID(m.SourceID(), "match creates unreachable outputs")
455 }
456 if m.NestedRule() != nil {
457 iss.ReportErrorAtID(m.NestedRule().SourceID(), "rule creates unreachable outputs")
458 }
459 break
460 }
461 }
462 }
463
464 func (c *compiler) relSource(pstr ValueString) *RelativeSource {
465 line := 0
466 col := 1
467 if offset, found := c.info.GetOffsetRange(pstr.ID); found {
468 if loc, found := c.src.OffsetLocation(offset.Start); found {
469 line = loc.Line()
470 col = loc.Column()
471 }
472 }
473 return c.src.Relative(pstr.Value, line, col)
474 }
475
476 const (
477 // Consider making the variables namespace configurable.
478 variablePrefix = "variables"
479
480 defaultMaxNestedExpressions = 100
481 )