Debian Codegraph @

policy/parser.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
16
17 import (
18 "fmt"
19 "strings"
20
21 "go.yaml.in/yaml/v3"
22
23 "github.com/google/cel-go/cel"
24 "github.com/google/cel-go/common"
25 "github.com/google/cel-go/common/ast"
26 )
27
28 type semanticType int
29
30 const (
31 unspecified semanticType = iota
32 firstMatch
33 )
34
35 // NewPolicy creates a policy object which references a policy source and source information.
36 func NewPolicy(src *Source, info *ast.SourceInfo) *Policy {
37 return &Policy{
38 metadata: map[string]any{},
39 source: src,
40 info: info,
41 semantic: firstMatch,
42 imports: []*Import{},
43 }
44 }
45
46 // Policy declares a name, rule, and evaluation semantic for a given expression graph.
47 type Policy struct {
48 name ValueString
49 description ValueString
50 imports []*Import
51 rule *Rule
52 semantic semanticType
53 info *ast.SourceInfo
54 source *Source
55
56 metadata map[string]any
57 }
58
59 // Source returns the policy file contents as a CEL source object.
60 func (p *Policy) Source() *Source {
61 return p.source
62 }
63
64 // SourceInfo returns the policy file metadata about expression positions.
65 func (p *Policy) SourceInfo() *ast.SourceInfo {
66 return p.info
67 }
68
69 // Imports returns the list of imports associated with the policy.
70 func (p *Policy) Imports() []*Import {
71 return p.imports
72 }
73
74 // Name returns the name of the policy.
75 func (p *Policy) Name() ValueString {
76 return p.name
77 }
78
79 // Description returns the description for the policy.
80 func (p *Policy) Description() ValueString {
81 return p.description
82 }
83
84 // Rule returns the rule entry point of the policy.
85 func (p *Policy) Rule() *Rule {
86 return p.rule
87 }
88
89 // Metadata returns a named metadata object if one exists within the policy.
90 func (p *Policy) Metadata(name string) (any, bool) {
91 value, found := p.metadata[name]
92 return value, found
93 }
94
95 // MetadataKeys returns a list of metadata keys set on the policy.
96 func (p *Policy) MetadataKeys() []string {
97 keys := make([]string, 0, len(p.metadata))
98 for k := range p.metadata {
99 keys = append(keys, k)
100 }
101 return keys
102 }
103
104 // AddImport adds an import to the policy.
105 func (p *Policy) AddImport(i *Import) {
106 p.imports = append(p.imports, i)
107 }
108
109 // SetName configures the policy name.
110 func (p *Policy) SetName(name ValueString) {
111 p.name = name
112 }
113
114 // SetDescription configures the policy description.
115 func (p *Policy) SetDescription(description ValueString) {
116 p.description = description
117 }
118
119 // SetRule configures the policy rule entry point.
120 func (p *Policy) SetRule(r *Rule) {
121 p.rule = r
122 }
123
124 // SetMetadata updates a named metadata key with the given value.
125 func (p *Policy) SetMetadata(name string, value any) {
126 p.metadata[name] = value
127 }
128
129 // GetExplanationOutputPolicy returns a copy of the policy, except the output of each match block
130 // is replaced by the expression in the explanation field.
131 func (p *Policy) GetExplanationOutputPolicy() *Policy {
132 ep := Policy{
133 name: p.name,
134 semantic: p.semantic,
135 info: p.info,
136 metadata: p.metadata,
137 source: p.source,
138 }
139 if p.rule != nil {
140 ep.rule = p.rule.getExplanationOutputRule()
141 }
142 return &ep
143 }
144
145 // NewImport creates a new typename import node
146 func NewImport(exprID int64) *Import {
147 return &Import{exprID: exprID}
148 }
149
150 // Import represents an imported type name which is aliased within CEL expressions.
151 type Import struct {
152 exprID int64
153 name ValueString
154 }
155
156 // SourceID returns the source identifier associated with the import.
157 func (i *Import) SourceID() int64 {
158 return i.exprID
159 }
160
161 // Name returns the fully qualified type name.
162 func (i *Import) Name() ValueString {
163 return i.name
164 }
165
166 // SetName updates the fully qualified type name for the import.
167 func (i *Import) SetName(name ValueString) {
168 i.name = name
169 }
170
171 // NewRule creates a Rule instance.
172 func NewRule(exprID int64) *Rule {
173 return &Rule{
174 exprID: exprID,
175 variables: []*Variable{},
176 matches: []*Match{},
177 }
178 }
179
180 // Rule declares a rule identifier, description, along with a set of variables and match statements.
181 type Rule struct {
182 exprID int64
183 id *ValueString
184 description *ValueString
185 variables []*Variable
186 matches []*Match
187 }
188
189 // ID returns the id value of the rule if it is set.
190 func (r *Rule) ID() ValueString {
191 if r.id != nil {
192 return *r.id
193 }
194 return ValueString{}
195 }
196
197 // Description returns the rule description if it is set.
198 func (r *Rule) Description() ValueString {
199 if r.description != nil {
200 return *r.description
201 }
202 return ValueString{}
203 }
204
205 // Matches returns the ordered set of Match declarations.
206 func (r *Rule) Matches() []*Match {
207 return r.matches[:]
208 }
209
210 // Variables returns the order set of Variable tuples.
211 func (r *Rule) Variables() []*Variable {
212 return r.variables[:]
213 }
214
215 // SetID configures the id for the rule.
216 func (r *Rule) SetID(id ValueString) {
217 r.id = &id
218 }
219
220 // SetDescription configures the description for the rule.
221 func (r *Rule) SetDescription(desc ValueString) {
222 r.description = &desc
223 }
224
225 // AddMatch addes a Match to the rule.
226 func (r *Rule) AddMatch(m *Match) {
227 r.matches = append(r.matches, m)
228 }
229
230 // AddVariable adds a variable to the rule.
231 func (r *Rule) AddVariable(v *Variable) {
232 r.variables = append(r.variables, v)
233 }
234
235 func (r *Rule) getExplanationOutputRule() *Rule {
236 if r == nil {
237 return nil
238 }
239 er := Rule{
240 id: r.id,
241 description: r.description,
242 }
243 for _, variable := range r.variables {
244 er.variables = append(er.variables, variable)
245 }
246 for _, match := range r.matches {
247 em := Match{
248 condition: match.condition,
249 output: match.explanation,
250 rule: match.rule.getExplanationOutputRule(),
251 }
252 er.matches = append(er.matches, &em)
253 }
254 return &er
255 }
256
257 // NewVariable creates a variable instance.
258 func NewVariable(exprID int64) *Variable {
259 return &Variable{exprID: exprID}
260 }
261
262 // Variable is a named expression which may be referenced in subsequent expressions.
263 type Variable struct {
264 exprID int64
265 name ValueString
266 expression ValueString
267 }
268
269 // Name returns the variable name.
270 func (v *Variable) Name() ValueString {
271 return v.name
272 }
273
274 // Expression returns the variable expression.
275 func (v *Variable) Expression() ValueString {
276 return v.expression
277 }
278
279 // SetName sets the variable name.
280 func (v *Variable) SetName(name ValueString) {
281 v.name = name
282 }
283
284 // SetExpression sets the variable expression.
285 func (v *Variable) SetExpression(e ValueString) {
286 v.expression = e
287 }
288
289 // NewMatch creates a match instance.
290 func NewMatch(exprID int64) *Match {
291 return &Match{exprID: exprID}
292 }
293
294 // Match declares a condition (defaults to true) as well as an output or a rule.
295 // Either the output or the rule field may be set, but not both.
296 type Match struct {
297 exprID int64
298 condition ValueString
299 output *ValueString
300 explanation *ValueString
301 rule *Rule
302 }
303
304 // SourceID returns the source identifier associated with the match.
305 func (m *Match) SourceID() int64 {
306 return m.exprID
307 }
308
309 // Condition returns the condition CEL expression.
310 func (m *Match) Condition() ValueString {
311 return m.condition
312 }
313
314 // HasOutput indicates whether the output field is set of the match.
315 func (m *Match) HasOutput() bool {
316 return m.output != nil
317 }
318
319 // Output returns the output expression, or empty expression if output is not set.
320 func (m *Match) Output() ValueString {
321 if m.HasOutput() {
322 return *m.output
323 }
324 return ValueString{}
325 }
326
327 // HasExplanation indicates whether the explanation field is set of the match.
328 func (m *Match) HasExplanation() bool {
329 return m.explanation != nil
330 }
331
332 // Explanation returns the explanation expression, or empty expression if output is not set.
333 func (m *Match) Explanation() ValueString {
334 if m.HasExplanation() {
335 return *m.explanation
336 }
337 return ValueString{}
338 }
339
340 // HasRule indicates whether the rule field is set on a match.
341 func (m *Match) HasRule() bool {
342 return m.rule != nil
343 }
344
345 // Rule returns the rule value, or nil if the rule is not set.
346 func (m *Match) Rule() *Rule {
347 return m.rule
348 }
349
350 // SetCondition sets the CEL condition for the match.
351 func (m *Match) SetCondition(c ValueString) {
352 m.condition = c
353 }
354
355 // SetOutput sets the output expression for the match.
356 func (m *Match) SetOutput(o ValueString) {
357 m.output = &o
358 }
359
360 // SetExplanation sets the explanation expression for the match.
361 func (m *Match) SetExplanation(e ValueString) {
362 m.explanation = &e
363 }
364
365 // SetRule sets the rule for the match.
366 func (m *Match) SetRule(r *Rule) {
367 m.rule = r
368 }
369
370 // ValueString contains an identifier corresponding to source metadata and a simple string.
371 type ValueString struct {
372 ID int64
373 Value string
374 }
375
376 // ParserContext declares a set of interfaces for creating and managing metadata for parsed policies.
377 type ParserContext interface {
378 // NextID returns a monotonically increasing identifier for a source fragment.
379 // This ID is implicitly created and tracked within the CollectMetadata method.
380 NextID() int64
381
382 // CollectMetadata records the source position information of a given YAML node, and returns
383 // the id associated with the source metadata which is returned in the Policy SourceInfo object.
384 CollectMetadata(*yaml.Node) int64
385
386 // NewPolicy creates a new Policy instance with an ID associated with the YAML node.
387 NewPolicy(*yaml.Node) (*Policy, int64)
388
389 // NewRule creates a new Rule instance with an ID associated with the YAML node.
390 NewRule(*yaml.Node) (*Rule, int64)
391
392 // NewVariable creates a new Variable instance with an ID associated with the YAML node.
393 NewVariable(*yaml.Node) (*Variable, int64)
394
395 // NewMatch creates a new Match instance with an ID associated with the YAML node.
396 NewMatch(*yaml.Node) (*Match, int64)
397
398 // NewString creates a new ValueString from the YAML node.
399 NewString(*yaml.Node) ValueString
400
401 // ParsePolicy will parse the target yaml node as though it is the top-level policy.
402 ParsePolicy(ParserContext, *yaml.Node) *Policy
403
404 // ParseRule will parse the current yaml node as though it is the entry point to a rule.
405 ParseRule(ParserContext, *Policy, *yaml.Node) *Rule
406
407 // ParseMatch will parse the current yaml node as though it is the entry point to a match.
408 ParseMatch(ParserContext, *Policy, *yaml.Node) *Match
409
410 // ParseVariable will parse the current yaml node as though it is the entry point to a variable.
411 ParseVariable(ParserContext, *Policy, *yaml.Node) *Variable
412
413 // ReportErrorAtID logs an error during parsing which is included in the issue set returned from
414 // a failed parse.
415 ReportErrorAtID(id int64, msg string, args ...any)
416 }
417
418 // TagVisitor declares a set of interfaces for handling custom tags which would otherwise be unsupported
419 // within the policy, rule, match, or variable objects.
420 type TagVisitor interface {
421 // PolicyTag accepts a parser context, field id, tag name, yaml node, and parent Policy to allow for
422 // continued parsing within a custom tag.
423 PolicyTag(ParserContext, int64, string, *yaml.Node, *Policy)
424
425 // RuleTag accepts a parser context, field id, tag name, yaml node, as well as the parent policy and
426 // current rule to allow for continued parsing within custom tags.
427 RuleTag(ParserContext, int64, string, *yaml.Node, *Policy, *Rule)
428
429 // MatchTag accepts a parser context, field id, tag name, yaml node, as well as the parent policy and
430 // current match to allow for continued parsing within custom tags.
431 MatchTag(ParserContext, int64, string, *yaml.Node, *Policy, *Match)
432
433 // VariableTag accepts a parser context, field id, tag name, yaml node, as well as the parent policy and
434 // current variable to allow for continued parsing within custom tags.
435 VariableTag(ParserContext, int64, string, *yaml.Node, *Policy, *Variable)
436 }
437
438 // DefaultTagVisitor creates a tag visitor which produces errors for any non-canonical YAML tag.
439 func DefaultTagVisitor() TagVisitor {
440 return defaultTagVisitor{}
441 }
442
443 type defaultTagVisitor struct{}
444
445 func (defaultTagVisitor) PolicyTag(ctx ParserContext, id int64, tagName string, node *yaml.Node, p *Policy) {
446 if tagName == "description" {
447 return
448 }
449 ctx.ReportErrorAtID(id, "unsupported policy tag: %s", tagName)
450 }
451
452 func (defaultTagVisitor) RuleTag(ctx ParserContext, id int64, tagName string, node *yaml.Node, p *Policy, r *Rule) {
453 ctx.ReportErrorAtID(id, "unsupported rule tag: %s", tagName)
454 }
455
456 func (defaultTagVisitor) MatchTag(ctx ParserContext, id int64, tagName string, node *yaml.Node, p *Policy, m *Match) {
457 ctx.ReportErrorAtID(id, "unsupported match tag: %s", tagName)
458 }
459
460 func (defaultTagVisitor) VariableTag(ctx ParserContext, id int64, tagName string, node *yaml.Node, p *Policy, v *Variable) {
461 ctx.ReportErrorAtID(id, "unsupported variable tag: %s", tagName)
462 }
463
464 // Parser parses policy files into a canonical Policy representation.
465 type Parser struct {
466 TagVisitor
467 }
468
469 // ParserOption is a function parser option for configuring Parser behavior.
470 type ParserOption func(*Parser) (*Parser, error)
471
472 // NewParser creates a new Parser object with a set of functional options.
473 func NewParser(opts ...ParserOption) (*Parser, error) {
474 p := &Parser{TagVisitor: defaultTagVisitor{}}
475 var err error
476 for _, o := range opts {
477 p, err = o(p)
478 if err != nil {
479 return nil, err
480 }
481 }
482 return p, nil
483 }
484
485 // Parse generates an internal parsed policy representation from a YAML input file.
486 // The internal representation ensures that CEL expressions are tracked relative to
487 // where they occur within the file, thus making error messages relative to the whole
488 // file rather than the individual expression.
489 func (parser *Parser) Parse(src *Source) (*Policy, *cel.Issues) {
490 info := ast.NewSourceInfo(src)
491 errs := common.NewErrors(src)
492 iss := cel.NewIssuesWithSourceInfo(errs, info)
493 p := newParserImpl(parser.TagVisitor, info, src, iss)
494 policy := p.parseYAML(src)
495 if iss.Err() != nil {
496 return nil, iss
497 }
498 return policy, nil
499 }
500
501 // normalizeEntry extracts a key, value pair as the next two elements from the
502 // content slice. val source position information is normalized depending on style.
503 func normalizeEntry(content []*yaml.Node, i int) (key *yaml.Node, val *yaml.Node) {
504 key = content[i]
505 val = content[i+1]
506 if val.Style == yaml.FoldedStyle || val.Style == yaml.LiteralStyle {
507 val.Line++
508 val.Column = key.Column + 1
509 }
510 return key, val
511 }
512
513 func (p *parserImpl) parseYAML(src *Source) *Policy {
514 // Parse yaml representation from the source to an object model.
515 var docNode yaml.Node
516 err := sourceToYAML(src, &docNode)
517 if err != nil {
518 p.iss.ReportErrorAtID(0, "%s", err.Error())
519 return nil
520 }
521 // Entry point always has a single Content node
522 return p.ParsePolicy(p, docNode.Content[0])
523 }
524
525 func sourceToYAML(src *Source, docNode *yaml.Node) error {
526 err := yaml.Unmarshal([]byte(src.Content()), docNode)
527 if err != nil {
528 return err
529 }
530 if docNode.Kind != yaml.DocumentNode {
531 return fmt.Errorf("got yaml node of kind %v, wanted mapping node", docNode.Kind)
532 }
533 return nil
534 }
535
536 func newParserImpl(visitor TagVisitor, info *ast.SourceInfo, src *Source, iss *cel.Issues) *parserImpl {
537 return &parserImpl{
538 visitor: visitor,
539 info: info,
540 src: src,
541 iss: iss,
542 }
543 }
544
545 type parserImpl struct {
546 id int64
547 visitor TagVisitor
548 info *ast.SourceInfo
549 src *Source
550 iss *cel.Issues
551 }
552
553 // NextID returns a monotonically increasing identifier for a source fragment.
554 // This ID is implicitly created and tracked within the CollectMetadata method.
555 func (p *parserImpl) NextID() int64 {
556 p.id++
557 return p.id
558 }
559
560 // NewPolicy creates a new Policy instance with an ID associated with the YAML node.
561 func (p *parserImpl) NewPolicy(node *yaml.Node) (*Policy, int64) {
562 policy := NewPolicy(p.src, p.info)
563 id := p.CollectMetadata(node)
564 return policy, id
565 }
566
567 // NewRule creates a new Rule instance with an ID associated with the YAML node.
568 func (p *parserImpl) NewRule(node *yaml.Node) (*Rule, int64) {
569 id := p.CollectMetadata(node)
570 r := NewRule(id)
571 return r, id
572 }
573
574 // NewVariable creates a new Variable instance with an ID associated with the YAML node.
575 func (p *parserImpl) NewVariable(node *yaml.Node) (*Variable, int64) {
576 id := p.CollectMetadata(node)
577 v := NewVariable(id)
578 return v, id
579 }
580
581 // NewMatch creates a new Match instance with an ID associated with the YAML node.
582 func (p *parserImpl) NewMatch(node *yaml.Node) (*Match, int64) {
583 id := p.CollectMetadata(node)
584 m := NewMatch(id)
585 return m, id
586 }
587
588 // NewString creates a new ValueString from the YAML node.
589 func (p *parserImpl) NewString(node *yaml.Node) ValueString {
590 id := p.CollectMetadata(node)
591 nodeType := p.assertYamlType(id, node, yamlString, yamlText)
592 if nodeType == nil {
593 return ValueString{ID: id, Value: "*error*"}
594 }
595 if *nodeType == yamlText {
596 return ValueString{ID: id, Value: node.Value}
597 }
598 if node.Style == yaml.FoldedStyle || node.Style == yaml.LiteralStyle {
599 col := node.Column
600 line := node.Line
601 txt, found := p.src.Snippet(line)
602 indent := ""
603 for len(indent) < col-1 {
604 indent += " "
605 }
606 var raw strings.Builder
607 for found && strings.HasPrefix(txt, indent) {
608 line++
609 raw.WriteString(txt)
610 txt, found = p.src.Snippet(line)
611 if found && strings.HasPrefix(txt, indent) {
612 raw.WriteString("\n")
613 }
614 }
615 offset := p.info.OffsetRanges()[p.id]
616 offsetStart := offset.Start - (int32(node.Column) - 1)
617 p.info.SetOffsetRange(p.id, ast.OffsetRange{Start: offsetStart, Stop: offsetStart})
618 return ValueString{ID: id, Value: raw.String()}
619 }
620 return ValueString{ID: id, Value: node.Value}
621 }
622
623 // newStrictString creates a new ValueString from the YAML node, but as a string with no special
624 // source position information. Intended for use in descriptions, where the string is just
625 // a human-readable string for presentation.
626 func (p *parserImpl) newStrictString(node *yaml.Node) ValueString {
627 id := p.CollectMetadata(node)
628 nodeType := p.assertYamlType(id, node, yamlString, yamlText)
629 if nodeType == nil {
630 return ValueString{ID: id, Value: "*error*"}
631 }
632 return ValueString{ID: id, Value: node.Value}
633 }
634
635 // CollectMetadata records the source position information of a given YAML node, and returns
636 // the id associated with the source metadata which is returned in the Policy SourceInfo object.
637 func (p *parserImpl) CollectMetadata(node *yaml.Node) int64 {
638 id := p.NextID()
639 line := node.Line
640 col := int32(node.Column)
641 switch node.Style {
642 case yaml.DoubleQuotedStyle, yaml.SingleQuotedStyle:
643 col++
644 }
645 offsetStart := int32(0)
646 if line > 1 {
647 offsetStart = p.info.LineOffsets()[line-2]
648 }
649 p.info.SetOffsetRange(id, ast.OffsetRange{Start: offsetStart + col - 1, Stop: offsetStart + col - 1})
650 return id
651 }
652
653 // ParsePolicy will parse the target yaml node as though it is the top-level policy.
654 func (p *parserImpl) ParsePolicy(ctx ParserContext, node *yaml.Node) *Policy {
655 ctx.CollectMetadata(node)
656 policy, id := ctx.NewPolicy(node)
657 if p.assertYamlType(id, node, yamlMap) == nil || !p.checkMapValid(ctx, id, node) {
658 return policy
659 }
660 for i := 0; i < len(node.Content); i += 2 {
661 key, val := normalizeEntry(node.Content, i)
662 keyID := p.CollectMetadata(key)
663 fieldName := key.Value
664 switch fieldName {
665 case "imports":
666 p.parseImports(ctx, policy, val)
667 case "name":
668 policy.SetName(ctx.NewString(val))
669 case "description":
670 policy.SetDescription(p.newStrictString(val))
671 // Since the description field was not supported initially, some
672 // clients rely on the ability to intercept it.
673 p.visitor.PolicyTag(ctx, keyID, fieldName, val, policy)
674 case "rule":
675 policy.SetRule(p.ParseRule(ctx, policy, val))
676 default:
677 p.visitor.PolicyTag(ctx, keyID, fieldName, val, policy)
678 }
679 }
680 return policy
681 }
682
683 func (p *parserImpl) parseImports(ctx ParserContext, policy *Policy, node *yaml.Node) {
684 id := ctx.CollectMetadata(node)
685 if p.assertYamlType(id, node, yamlList) == nil {
686 return
687 }
688 for _, val := range node.Content {
689 policy.AddImport(p.parseImport(ctx, policy, val))
690 }
691 }
692
693 func (p *parserImpl) parseImport(ctx ParserContext, _ *Policy, node *yaml.Node) *Import {
694 id := ctx.CollectMetadata(node)
695 imp := NewImport(id)
696 if p.assertYamlType(id, node, yamlMap) == nil || !p.checkMapValid(ctx, id, node) {
697 return imp
698 }
699 for i := 0; i < len(node.Content); i += 2 {
700 key, val := normalizeEntry(node.Content, i)
701 ctx.CollectMetadata(key)
702 fieldName := key.Value
703 switch fieldName {
704 case "name":
705 imp.SetName(ctx.NewString(val))
706 }
707 }
708 return imp
709 }
710
711 // ParseRule will parse the current yaml node as though it is the entry point to a rule.
712 func (p *parserImpl) ParseRule(ctx ParserContext, policy *Policy, node *yaml.Node) *Rule {
713 r, id := ctx.NewRule(node)
714 if p.assertYamlType(id, node, yamlMap) == nil || !p.checkMapValid(ctx, id, node) {
715 return r
716 }
717 for i := 0; i < len(node.Content); i += 2 {
718 key, val := normalizeEntry(node.Content, i)
719 tagID := ctx.CollectMetadata(key)
720 fieldName := key.Value
721 switch fieldName {
722 case "id":
723 r.SetID(ctx.NewString(val))
724 case "description":
725 r.SetDescription(ctx.NewString(val))
726 case "variables":
727 p.parseVariables(ctx, policy, r, val)
728 case "match":
729 p.parseMatches(ctx, policy, r, val)
730 default:
731 p.visitor.RuleTag(ctx, tagID, fieldName, val, policy, r)
732 }
733 }
734 return r
735 }
736
737 func (p *parserImpl) parseVariables(ctx ParserContext, policy *Policy, r *Rule, node *yaml.Node) {
738 id := ctx.CollectMetadata(node)
739 if p.assertYamlType(id, node, yamlList) == nil {
740 return
741 }
742 for _, val := range node.Content {
743 r.AddVariable(p.ParseVariable(ctx, policy, val))
744 }
745 }
746
747 // ParseVariable will parse the current yaml node as though it is the entry point to a variable.
748 func (p *parserImpl) ParseVariable(ctx ParserContext, policy *Policy, node *yaml.Node) *Variable {
749 v, id := ctx.NewVariable(node)
750 if p.assertYamlType(id, node, yamlMap) == nil || !p.checkMapValid(ctx, id, node) {
751 return v
752 }
753 for i := 0; i < len(node.Content); i += 2 {
754 key, val := normalizeEntry(node.Content, i)
755 keyID := ctx.CollectMetadata(key)
756 fieldName := key.Value
757 switch fieldName {
758 case "name":
759 v.SetName(ctx.NewString(val))
760 case "expression":
761 v.SetExpression(ctx.NewString(val))
762 default:
763 p.visitor.VariableTag(ctx, keyID, fieldName, val, policy, v)
764 }
765 }
766 return v
767 }
768
769 func (p *parserImpl) parseMatches(ctx ParserContext, policy *Policy, r *Rule, node *yaml.Node) {
770 id := ctx.CollectMetadata(node)
771 if p.assertYamlType(id, node, yamlList) == nil {
772 return
773 }
774 for _, val := range node.Content {
775 r.AddMatch(p.ParseMatch(ctx, policy, val))
776 }
777 }
778
779 // ParseMatch will parse the current yaml node as though it is the entry point to a match.
780 func (p *parserImpl) ParseMatch(ctx ParserContext, policy *Policy, node *yaml.Node) *Match {
781 m, id := ctx.NewMatch(node)
782 if p.assertYamlType(id, node, yamlMap) == nil || !p.checkMapValid(ctx, id, node) {
783 return m
784 }
785 m.SetCondition(ValueString{ID: ctx.NextID(), Value: "true"})
786 for i := 0; i < len(node.Content); i += 2 {
787 key, val := normalizeEntry(node.Content, i)
788 keyID := ctx.CollectMetadata(key)
789 fieldName := key.Value
790 switch fieldName {
791 case "condition":
792 m.SetCondition(ctx.NewString(val))
793 case "output":
794 if m.HasRule() {
795 p.ReportErrorAtID(keyID, "only the rule or the output may be set")
796 }
797 m.SetOutput(ctx.NewString(val))
798 case "explanation":
799 if m.HasRule() {
800 p.ReportErrorAtID(keyID, "explanation can only be set on output match cases, not nested rules")
801 }
802 m.SetExplanation(ctx.NewString(val))
803 case "rule":
804 if m.HasOutput() {
805 p.ReportErrorAtID(keyID, "only the rule or the output may be set")
806 }
807 if m.HasExplanation() {
808 p.ReportErrorAtID(keyID, "explanation can only be set on output match cases, not nested rules")
809 }
810 m.SetRule(p.ParseRule(ctx, policy, val))
811 default:
812 p.visitor.MatchTag(ctx, keyID, fieldName, val, policy, m)
813 }
814 }
815 if !m.HasOutput() && !m.HasRule() {
816 p.ReportErrorAtID(id, "match does not specify a rule or output")
817 }
818 return m
819 }
820
821 func (p *parserImpl) assertYamlType(id int64, node *yaml.Node, nodeTypes ...yamlNodeType) *yamlNodeType {
822 nt, found := yamlTypes[node.LongTag()]
823 if !found {
824 p.ReportErrorAtID(id, "unsupported map key type: %v", node.LongTag())
825 return nil
826 }
827 for _, nodeType := range nodeTypes {
828 if nt == nodeType {
829 return &nt
830 }
831 }
832 p.ReportErrorAtID(id, "got yaml node type %v, wanted type(s) %v", node.LongTag(), nodeTypes)
833 return nil
834 }
835
836 // ReportErrorAtID logs an error during parsing which is included in the issue set returned from
837 // a failed parse.
838 func (p *parserImpl) ReportErrorAtID(id int64, format string, args ...any) {
839 p.iss.ReportErrorAtID(id, format, args...)
840 }
841
842 func (p *parserImpl) checkMapValid(ctx ParserContext, id int64, node *yaml.Node) bool {
843 valid := len(node.Content)%2 == 0
844 if !valid {
845 ctx.ReportErrorAtID(id, "mismatched key-value pairs in map")
846 }
847 return valid
848 }
849
850 type yamlNodeType int
851
852 const (
853 yamlText yamlNodeType = iota + 1
854 yamlBool
855 yamlNull
856 yamlString
857 yamlInt
858 yamlDouble
859 yamlList
860 yamlMap
861 yamlTimestamp
862 )
863
864 func (yt yamlNodeType) String() string {
865 for k, v := range yamlTypes {
866 if v == yt {
867 return k
868 }
869 }
870 return fmt.Sprintf("%d", yt)
871 }
872
873 var (
874 // yamlTypes map of the long tag names supported by the Go YAML v3 library.
875 yamlTypes = map[string]yamlNodeType{
876 "!txt": yamlText,
877 "tag:yaml.org,2002:bool": yamlBool,
878 "tag:yaml.org,2002:null": yamlNull,
879 "tag:yaml.org,2002:str": yamlString,
880 "tag:yaml.org,2002:int": yamlInt,
881 "tag:yaml.org,2002:float": yamlDouble,
882 "tag:yaml.org,2002:seq": yamlList,
883 "tag:yaml.org,2002:map": yamlMap,
884 "tag:yaml.org,2002:timestamp": yamlTimestamp,
885 }
886 )