GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(config): add defs section to rule files · majorcontext/keep@2e28fea

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/config
    • config.go
    • load_test.go
    • testdata/rules-with-defs
      • test.yaml
    • validate.go
    • validate_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/config/config.go‎

Copy file name to clipboardExpand all lines: internal/config/config.go
+7-6Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ package config
33

44
// RuleFile is the parsed representation of a single YAML rule file.
55
type RuleFile struct {
6-
Scope string `yaml:"scope"`
7-
Profile string `yaml:"profile,omitempty"`
8-
Mode Mode `yaml:"mode,omitempty"`
9-
OnError ErrorMode `yaml:"on_error,omitempty"`
10-
Packs []PackRef `yaml:"packs,omitempty"`
11-
Rules []Rule `yaml:"rules"`
6+
Scope string `yaml:"scope"`
7+
Profile string `yaml:"profile,omitempty"`
8+
Mode Mode `yaml:"mode,omitempty"`
9+
OnError ErrorMode `yaml:"on_error,omitempty"`
10+
Defs map[string]string `yaml:"defs,omitempty"`
11+
Packs []PackRef `yaml:"packs,omitempty"`
12+
Rules []Rule `yaml:"rules"`
1213
}
1314

1415
// Mode controls whether rules are enforced or only audited.
Collapse file

‎internal/config/load_test.go‎

Copy file name to clipboardExpand all lines: internal/config/load_test.go
+20Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,26 @@ rules:
126126
}
127127
}
128128

129+
func TestLoadRules_WithDefs(t *testing.T) {
130+
result, err := LoadRules("testdata/rules-with-defs")
131+
if err != nil {
132+
t.Fatalf("unexpected error: %v", err)
133+
}
134+
rf, ok := result["test-defs"]
135+
if !ok {
136+
t.Fatal("expected scope test-defs to be present")
137+
}
138+
if len(rf.Defs) != 2 {
139+
t.Fatalf("expected 2 defs, got %d", len(rf.Defs))
140+
}
141+
if rf.Defs["allowed_teams"] != "['TEAM-ENG', 'TEAM-INFRA']" {
142+
t.Errorf("allowed_teams = %q, want %q", rf.Defs["allowed_teams"], "['TEAM-ENG', 'TEAM-INFRA']")
143+
}
144+
if rf.Defs["max_priority"] != "1" {
145+
t.Errorf("max_priority = %q, want %q", rf.Defs["max_priority"], "1")
146+
}
147+
}
148+
129149
func TestLoadRules_FileSizeCap(t *testing.T) {
130150
dir := t.TempDir()
131151

Collapse file

‎internal/config/testdata/rules-with-defs/test.yaml‎

Copy file name to clipboard
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
scope: test-defs
2+
mode: enforce
3+
defs:
4+
allowed_teams: "['TEAM-ENG', 'TEAM-INFRA']"
5+
max_priority: "1"
6+
rules:
7+
- name: team-check
8+
match:
9+
operation: "create"
10+
when: "!(params.team in allowed_teams)"
11+
action: deny
12+
message: "Team not allowed."
Collapse file

‎internal/config/validate.go‎

Copy file name to clipboardExpand all lines: internal/config/validate.go
+66Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
)
88

99
var nameRe = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
10+
var defNameRe = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
1011

1112
const (
1213
maxNameLen = 64
@@ -53,6 +54,11 @@ func Validate(rf *RuleFile) error {
5354
}
5455
}
5556

57+
// defs validation
58+
if len(rf.Defs) > 0 {
59+
errs = append(errs, validateDefs(rf.Defs)...)
60+
}
61+
5662
// 9. mode if set must be "enforce" or "audit_only"
5763
if rf.Mode != "" && rf.Mode != ModeEnforce && rf.Mode != ModeAuditOnly {
5864
errs = append(errs, fmt.Errorf("mode: invalid value %q (must be %q or %q)", rf.Mode, ModeEnforce, ModeAuditOnly))
@@ -106,6 +112,66 @@ func validateRule(i int, rule Rule) []error {
106112
return errs
107113
}
108114

115+
// reservedDefNames are identifiers that must not be used as def names because
116+
// they shadow CEL built-in variables or functions used by Keep.
117+
var reservedDefNames = map[string]bool{
118+
"params": true,
119+
"context": true,
120+
"now": true,
121+
"size": true,
122+
"has": true,
123+
"matches": true,
124+
"startsWith": true,
125+
"endsWith": true,
126+
"contains": true,
127+
"containsAny": true,
128+
"estimateTokens": true,
129+
"inTimeWindow": true,
130+
"rateCount": true,
131+
"lower": true,
132+
"upper": true,
133+
"matchesDomain": true,
134+
"dayOfWeek": true,
135+
"int": true,
136+
"uint": true,
137+
"double": true,
138+
"bool": true,
139+
"string": true,
140+
"bytes": true,
141+
"list": true,
142+
"map": true,
143+
"type": true,
144+
"null_type": true,
145+
"true": true,
146+
"false": true,
147+
"null": true,
148+
}
149+
150+
func validateDefs(defs map[string]string) []error {
151+
var errs []error
152+
for name, value := range defs {
153+
// Name must match [a-z][a-z0-9_]*
154+
if !defNameRe.MatchString(name) {
155+
errs = append(errs, fmt.Errorf("defs: name %q is invalid (must match [a-z][a-z0-9_]*)", name))
156+
} else if len(name) > maxNameLen {
157+
errs = append(errs, fmt.Errorf("defs: name %q exceeds maximum length of %d", name, maxNameLen))
158+
}
159+
160+
// Name must not shadow built-in variables or functions
161+
if reservedDefNames[name] {
162+
errs = append(errs, fmt.Errorf("defs: name %q shadows a built-in variable or function", name))
163+
}
164+
165+
// Value must be non-empty
166+
if value == "" {
167+
errs = append(errs, fmt.Errorf("defs: value for %q must not be empty", name))
168+
} else if len(value) > maxWhenLen {
169+
errs = append(errs, fmt.Errorf("defs: value for %q exceeds maximum length of %d", name, maxWhenLen))
170+
}
171+
}
172+
return errs
173+
}
174+
109175
func validateRedact(i int, spec *RedactSpec) []error {
110176
var errs []error
111177

Collapse file

‎internal/config/validate_test.go‎

Copy file name to clipboardExpand all lines: internal/config/validate_test.go
+93Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,3 +416,96 @@ func TestValidate_TooManyPatternsPerRedact(t *testing.T) {
416416
}
417417
}
418418

419+
func TestValidate_DefsValid(t *testing.T) {
420+
rf := &RuleFile{
421+
Scope: "my-scope",
422+
Defs: map[string]string{
423+
"allowed_teams": "['TEAM-ENG', 'TEAM-INFRA']",
424+
"max_priority": "1",
425+
},
426+
Rules: []Rule{
427+
{Name: "my-rule", Action: ActionDeny},
428+
},
429+
}
430+
if err := Validate(rf); err != nil {
431+
t.Fatalf("Validate() = %v, want nil", err)
432+
}
433+
}
434+
435+
func TestValidate_DefsBadName(t *testing.T) {
436+
tests := []struct {
437+
name string
438+
defName string
439+
errContains string
440+
}{
441+
{"uppercase", "MyDef", "invalid"},
442+
{"starts with number", "1abc", "invalid"},
443+
{"contains hyphen", "my-def", "invalid"},
444+
}
445+
for _, tt := range tests {
446+
t.Run(tt.name, func(t *testing.T) {
447+
rf := &RuleFile{
448+
Scope: "my-scope",
449+
Defs: map[string]string{tt.defName: "'value'"},
450+
Rules: []Rule{{Name: "my-rule", Action: ActionDeny}},
451+
}
452+
err := Validate(rf)
453+
if err == nil {
454+
t.Fatalf("Validate() = nil, want error containing %q", tt.errContains)
455+
}
456+
if !strings.Contains(err.Error(), tt.errContains) {
457+
t.Errorf("Validate() error = %q, want it to contain %q", err.Error(), tt.errContains)
458+
}
459+
})
460+
}
461+
}
462+
463+
func TestValidate_DefsShadowsBuiltin(t *testing.T) {
464+
for _, name := range []string{"params", "context", "now", "size", "true", "false"} {
465+
t.Run(name, func(t *testing.T) {
466+
rf := &RuleFile{
467+
Scope: "my-scope",
468+
Defs: map[string]string{name: "'value'"},
469+
Rules: []Rule{{Name: "my-rule", Action: ActionDeny}},
470+
}
471+
err := Validate(rf)
472+
if err == nil {
473+
t.Fatalf("Validate() = nil, want error for shadowed name %q", name)
474+
}
475+
if !strings.Contains(err.Error(), "shadows") {
476+
t.Errorf("Validate() error = %q, want it to contain %q", err.Error(), "shadows")
477+
}
478+
})
479+
}
480+
}
481+
482+
func TestValidate_DefsEmptyValue(t *testing.T) {
483+
rf := &RuleFile{
484+
Scope: "my-scope",
485+
Defs: map[string]string{"my_def": ""},
486+
Rules: []Rule{{Name: "my-rule", Action: ActionDeny}},
487+
}
488+
err := Validate(rf)
489+
if err == nil {
490+
t.Fatal("Validate() = nil, want error for empty def value")
491+
}
492+
if !strings.Contains(err.Error(), "must not be empty") {
493+
t.Errorf("Validate() error = %q, want it to contain %q", err.Error(), "must not be empty")
494+
}
495+
}
496+
497+
func TestValidate_DefsValueTooLong(t *testing.T) {
498+
rf := &RuleFile{
499+
Scope: "my-scope",
500+
Defs: map[string]string{"my_def": strings.Repeat("x", 2049)},
501+
Rules: []Rule{{Name: "my-rule", Action: ActionDeny}},
502+
}
503+
err := Validate(rf)
504+
if err == nil {
505+
t.Fatal("Validate() = nil, want error for too-long def value")
506+
}
507+
if !strings.Contains(err.Error(), "exceeds maximum") {
508+
t.Errorf("Validate() error = %q, want it to contain %q", err.Error(), "exceeds maximum")
509+
}
510+
}
511+

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.