GeezerVison is showing github.com — feat(engine): add LoadFromBytes for embedded use · majorcontext/keep@d91b78b
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +34Lines changed: 34 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package config | | 2 | + | | 3 | +import ( | | 4 | + "fmt" | | 5 | + | | 6 | + "gopkg.in/yaml.v3" | | 7 | +) | | 8 | + | | 9 | +// ParseRuleFile parses and validates a single rule file from raw YAML bytes. | | 10 | +// It does not resolve pack references — callers that need pack resolution | | 11 | +// should use LoadAll instead. | | 12 | +func ParseRuleFile(data []byte) (*RuleFile, error) { | | 13 | + if len(data) == 0 { | | 14 | + return nil, fmt.Errorf("parse rule file: empty input") | | 15 | + } | | 16 | + if len(data) > maxFileBytes { | | 17 | + return nil, fmt.Errorf("parse rule file: input size %d exceeds maximum of %d bytes", len(data), maxFileBytes) | | 18 | + } | | 19 | + | | 20 | + var rf RuleFile | | 21 | + if err := yaml.Unmarshal(data, &rf); err != nil { | | 22 | + return nil, fmt.Errorf("parse rule file: invalid YAML: %w", err) | | 23 | + } | | 24 | + | | 25 | + if err := Validate(&rf); err != nil { | | 26 | + return nil, fmt.Errorf("parse rule file: %w", err) | | 27 | + } | | 28 | + | | 29 | + if len(rf.Packs) > 0 { | | 30 | + return nil, fmt.Errorf("parse rule file: pack references are not supported when loading from bytes (scope %q references %d packs)", rf.Scope, len(rf.Packs)) | | 31 | + } | | 32 | + | | 33 | + return &rf, nil | | 34 | +} |
Collapse file Copy file name to clipboard +91Lines changed: 91 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package config | | 2 | + | | 3 | +import ( | | 4 | + "strings" | | 5 | + "testing" | | 6 | +) | | 7 | + | | 8 | +func TestParseRuleFile_Valid(t *testing.T) { | | 9 | + data := []byte(` | | 10 | +scope: test-scope | | 11 | +mode: enforce | | 12 | +rules: | | 13 | + - name: block-deletes | | 14 | + match: | | 15 | + operation: "delete_*" | | 16 | + action: deny | | 17 | + message: "no deletes" | | 18 | +`) | | 19 | + rf, err := ParseRuleFile(data) | | 20 | + if err != nil { | | 21 | + t.Fatalf("ParseRuleFile() error: %v", err) | | 22 | + } | | 23 | + if rf.Scope != "test-scope" { | | 24 | + t.Errorf("Scope = %q, want test-scope", rf.Scope) | | 25 | + } | | 26 | + if rf.Mode != ModeEnforce { | | 27 | + t.Errorf("Mode = %q, want enforce", rf.Mode) | | 28 | + } | | 29 | + if len(rf.Rules) != 1 { | | 30 | + t.Fatalf("len(Rules) = %d, want 1", len(rf.Rules)) | | 31 | + } | | 32 | + if rf.Rules[0].Name != "block-deletes" { | | 33 | + t.Errorf("Rules[0].Name = %q, want block-deletes", rf.Rules[0].Name) | | 34 | + } | | 35 | +} | | 36 | + | | 37 | +func TestParseRuleFile_Empty(t *testing.T) { | | 38 | + _, err := ParseRuleFile([]byte{}) | | 39 | + if err == nil { | | 40 | + t.Fatal("expected error for empty input") | | 41 | + } | | 42 | + if !strings.Contains(err.Error(), "empty input") { | | 43 | + t.Errorf("error = %q, want mention of empty input", err) | | 44 | + } | | 45 | +} | | 46 | + | | 47 | +func TestParseRuleFile_InvalidYAML(t *testing.T) { | | 48 | + _, err := ParseRuleFile([]byte("{{{}}}")) | | 49 | + if err == nil { | | 50 | + t.Fatal("expected error for invalid YAML") | | 51 | + } | | 52 | + if !strings.Contains(err.Error(), "invalid YAML") { | | 53 | + t.Errorf("error = %q, want mention of invalid YAML", err) | | 54 | + } | | 55 | +} | | 56 | + | | 57 | +func TestParseRuleFile_ValidationError(t *testing.T) { | | 58 | + // Missing scope. | | 59 | + _, err := ParseRuleFile([]byte(` | | 60 | +rules: | | 61 | + - name: test | | 62 | + match: | | 63 | + operation: "foo" | | 64 | + action: deny | | 65 | +`)) | | 66 | + if err == nil { | | 67 | + t.Fatal("expected error for missing scope") | | 68 | + } | | 69 | + if !strings.Contains(err.Error(), "scope") { | | 70 | + t.Errorf("error = %q, want mention of scope", err) | | 71 | + } | | 72 | +} | | 73 | + | | 74 | +func TestParseRuleFile_PacksRejected(t *testing.T) { | | 75 | + _, err := ParseRuleFile([]byte(` | | 76 | +scope: test-scope | | 77 | +packs: | | 78 | + - name: some-pack | | 79 | +rules: | | 80 | + - name: test | | 81 | + match: | | 82 | + operation: "foo" | | 83 | + action: deny | | 84 | +`)) | | 85 | + if err == nil { | | 86 | + t.Fatal("expected error for pack references") | | 87 | + } | | 88 | + if !strings.Contains(err.Error(), "pack references are not supported") { | | 89 | + t.Errorf("error = %q, want mention of pack references", err) | | 90 | + } | | 91 | +} |
Collapse file Copy file name to clipboardExpand all lines: keep.go +60-29Lines changed: 60 additions & 29 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -74,52 +74,54 @@ func WithAuditHook(hook func(AuditEntry)) Option { | 74 | 74 | // Deprecated: Use WithMode("enforce") instead. | 75 | 75 | func WithForceEnforce() Option { return WithMode("enforce") } | 76 | 76 |
| 77 | | -// Load reads rule files from rulesDir, compiles all CEL expressions and | 78 | | -// redact patterns, and returns a ready-to-use Engine. | 79 | | -func Load(rulesDir string, opts ...Option) (*Engine, error) { | 80 | | - cfg := engineConfig{rulesDir: rulesDir} | | 77 | +// LoadFromBytes creates an Engine from raw YAML bytes representing a single | | 78 | +// rule file. The YAML must contain a valid Keep rule file with a scope field. | | 79 | +// Pack references are not supported — all rules must be inline. | | 80 | +// | | 81 | +// The returned Engine is safe for concurrent use. Call Close when done. | | 82 | +// | | 83 | +// This constructor is intended for embedding Keep in other programs (e.g. Moat) | | 84 | +// where the caller controls configuration and does not use the filesystem. | | 85 | +func LoadFromBytes(data []byte, opts ...Option) (*Engine, error) { | | 86 | + var cfg engineConfig | 81 | 87 | for _, opt := range opts { | 82 | 88 | opt(&cfg) | 83 | 89 | } | 84 | 90 | if err := cfg.validate(); err != nil { | 85 | 91 | return nil, err | 86 | 92 | } | 87 | 93 |
| 88 | | - // 1. Load config. | 89 | | - loadResult, err := config.LoadAll(rulesDir, cfg.profilesDir, cfg.packsDir) | | 94 | + rf, err := config.ParseRuleFile(data) | 90 | 95 | if err != nil { | 91 | | - return nil, fmt.Errorf("keep: load config: %w", err) | | 96 | + return nil, fmt.Errorf("keep: %w", err) | 92 | 97 | } | 93 | 98 |
| 94 | | - // 2. Create rate store. | 95 | | - store := rate.NewStore() | 96 | | - | 97 | | - // 2b. Create secrets detector. | 98 | | - detector, err := secrets.NewDetector() | 99 | | - if err != nil { | 100 | | - return nil, fmt.Errorf("keep: init secrets detector: %w", err) | | 99 | + lr := &config.LoadResult{ | | 100 | + Scopes: map[string]*config.RuleFile{rf.Scope: rf}, | | 101 | + ResolvedRules: map[string][]config.Rule{rf.Scope: rf.Rules}, | | 102 | + Profiles: map[string]*config.Profile{}, | 101 | 103 | } | 102 | 104 |
| 103 | | - // 3. Create CEL environment. | 104 | | - celEnv, err := keepcel.NewEnv(keepcel.WithRateStore(store), keepcel.WithSecretDetector(detector)) | 105 | | - if err != nil { | 106 | | - return nil, fmt.Errorf("keep: create cel env: %w", err) | 107 | | - } | | 105 | + return buildEngine(lr, cfg) | | 106 | +} | 108 | 107 |
| 109 | | - // 4. Build evaluators for each scope. | 110 | | - evaluators, err := buildEvaluators(loadResult, celEnv, cfg, detector) | 111 | | - if err != nil { | | 108 | +// Load reads rule files from rulesDir, compiles all CEL expressions and | | 109 | +// redact patterns, and returns a ready-to-use Engine. | | 110 | +func Load(rulesDir string, opts ...Option) (*Engine, error) { | | 111 | + cfg := engineConfig{rulesDir: rulesDir} | | 112 | + for _, opt := range opts { | | 113 | + opt(&cfg) | | 114 | + } | | 115 | + if err := cfg.validate(); err != nil { | 112 | 116 | return nil, err | 113 | 117 | } | 114 | 118 |
| 115 | | - store.StartGC(60*time.Second, 24*time.Hour) | | 119 | + loadResult, err := config.LoadAll(rulesDir, cfg.profilesDir, cfg.packsDir) | | 120 | + if err != nil { | | 121 | + return nil, fmt.Errorf("keep: load config: %w", err) | | 122 | + } | 116 | 123 |
| 117 | | - return &Engine{ | 118 | | - evaluators: evaluators, | 119 | | - rateStore: store, | 120 | | - secrets: detector, | 121 | | - cfg: cfg, | 122 | | - }, nil | | 124 | + return buildEngine(loadResult, cfg) | 123 | 125 | } | 124 | 126 |
| 125 | 127 | // Close stops the rate counter GC goroutine. Call this when the engine | @@ -211,6 +213,35 @@ func (c *engineConfig) validate() error { | 211 | 213 | return nil | 212 | 214 | } | 213 | 215 |
| | 216 | +// buildEngine creates a ready-to-use Engine from a LoadResult and config. | | 217 | +func buildEngine(lr *config.LoadResult, cfg engineConfig) (*Engine, error) { | | 218 | + store := rate.NewStore() | | 219 | + | | 220 | + detector, err := secrets.NewDetector() | | 221 | + if err != nil { | | 222 | + return nil, fmt.Errorf("keep: init secrets detector: %w", err) | | 223 | + } | | 224 | + | | 225 | + celEnv, err := keepcel.NewEnv(keepcel.WithRateStore(store), keepcel.WithSecretDetector(detector)) | | 226 | + if err != nil { | | 227 | + return nil, fmt.Errorf("keep: create cel env: %w", err) | | 228 | + } | | 229 | + | | 230 | + evaluators, err := buildEvaluators(lr, celEnv, cfg, detector) | | 231 | + if err != nil { | | 232 | + return nil, err | | 233 | + } | | 234 | + | | 235 | + store.StartGC(60*time.Second, 24*time.Hour) | | 236 | + | | 237 | + return &Engine{ | | 238 | + evaluators: evaluators, | | 239 | + rateStore: store, | | 240 | + secrets: detector, | | 241 | + cfg: cfg, | | 242 | + }, nil | | 243 | +} | | 244 | + | 214 | 245 | // buildEvaluators creates compiled evaluators for every scope in the load result. | 215 | 246 | func buildEvaluators(lr *config.LoadResult, celEnv *keepcel.Env, cfg engineConfig, detector *secrets.Detector) (map[string]*engine.Evaluator, error) { | 216 | 247 | evaluators := make(map[string]*engine.Evaluator, len(lr.Scopes)) | |
Collapse file Copy file name to clipboardExpand all lines: keep_test.go +122Lines changed: 122 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -592,3 +592,125 @@ func TestWithAuditHook_NotCalledOnError(t *testing.T) { | 592 | 592 | t.Error("audit hook should not be called on scope-not-found error") | 593 | 593 | } | 594 | 594 | } | | 595 | + | | 596 | +func TestLoadFromBytes_Basic(t *testing.T) { | | 597 | + data := []byte(` | | 598 | +scope: embedded | | 599 | +mode: enforce | | 600 | +rules: | | 601 | + - name: no-delete | | 602 | + match: | | 603 | + operation: "delete_*" | | 604 | + action: deny | | 605 | + message: "deletes blocked" | | 606 | +`) | | 607 | + eng, err := keep.LoadFromBytes(data) | | 608 | + if err != nil { | | 609 | + t.Fatal(err) | | 610 | + } | | 611 | + defer eng.Close() | | 612 | + | | 613 | + scopes := eng.Scopes() | | 614 | + if len(scopes) != 1 || scopes[0] != "embedded" { | | 615 | + t.Fatalf("Scopes() = %v, want [embedded]", scopes) | | 616 | + } | | 617 | + | | 618 | + result, err := eng.Evaluate(keep.Call{Operation: "delete_issue"}, "embedded") | | 619 | + if err != nil { | | 620 | + t.Fatal(err) | | 621 | + } | | 622 | + if result.Decision != keep.Deny { | | 623 | + t.Errorf("Decision = %q, want deny", result.Decision) | | 624 | + } | | 625 | + | | 626 | + result, err = eng.Evaluate(keep.Call{Operation: "get_issue"}, "embedded") | | 627 | + if err != nil { | | 628 | + t.Fatal(err) | | 629 | + } | | 630 | + if result.Decision != keep.Allow { | | 631 | + t.Errorf("Decision = %q, want allow", result.Decision) | | 632 | + } | | 633 | +} | | 634 | + | | 635 | +func TestLoadFromBytes_InvalidYAML(t *testing.T) { | | 636 | + _, err := keep.LoadFromBytes([]byte("{{{}}}")) | | 637 | + if err == nil { | | 638 | + t.Fatal("expected error for invalid YAML") | | 639 | + } | | 640 | +} | | 641 | + | | 642 | +func TestLoadFromBytes_Empty(t *testing.T) { | | 643 | + _, err := keep.LoadFromBytes(nil) | | 644 | + if err == nil { | | 645 | + t.Fatal("expected error for nil input") | | 646 | + } | | 647 | +} | | 648 | + | | 649 | +func TestLoadFromBytes_WithOptions(t *testing.T) { | | 650 | + var events []keep.AuditEntry | | 651 | + data := []byte(` | | 652 | +scope: embedded | | 653 | +mode: enforce | | 654 | +rules: | | 655 | + - name: block-all | | 656 | + match: | | 657 | + operation: "*" | | 658 | + action: deny | | 659 | +`) | | 660 | + eng, err := keep.LoadFromBytes(data, | | 661 | + keep.WithMode("audit_only"), | | 662 | + keep.WithAuditHook(func(e keep.AuditEntry) { events = append(events, e) }), | | 663 | + ) | | 664 | + if err != nil { | | 665 | + t.Fatal(err) | | 666 | + } | | 667 | + defer eng.Close() | | 668 | + | | 669 | + result, _ := eng.Evaluate(keep.Call{Operation: "anything"}, "embedded") | | 670 | + if result.Decision != keep.Allow { | | 671 | + t.Errorf("want allow in audit mode, got %q", result.Decision) | | 672 | + } | | 673 | + if len(events) != 1 { | | 674 | + t.Fatalf("got %d audit events, want 1", len(events)) | | 675 | + } | | 676 | + if events[0].Decision != keep.Deny { | | 677 | + t.Errorf("audit event Decision = %q, want deny", events[0].Decision) | | 678 | + } | | 679 | +} | | 680 | + | | 681 | +func TestLoadFromBytes_CELExpression(t *testing.T) { | | 682 | + data := []byte(` | | 683 | +scope: cel-test | | 684 | +mode: enforce | | 685 | +rules: | | 686 | + - name: no-p0 | | 687 | + match: | | 688 | + operation: "create_issue" | | 689 | + when: "params.priority == 0" | | 690 | + action: deny | | 691 | + message: "P0 not allowed" | | 692 | +`) | | 693 | + eng, err := keep.LoadFromBytes(data) | | 694 | + if err != nil { | | 695 | + t.Fatal(err) | | 696 | + } | | 697 | + defer eng.Close() | | 698 | + | | 699 | + // P0 denied. | | 700 | + result, _ := eng.Evaluate(keep.Call{ | | 701 | + Operation: "create_issue", | | 702 | + Params: map[string]any{"priority": int64(0)}, | | 703 | + }, "cel-test") | | 704 | + if result.Decision != keep.Deny { | | 705 | + t.Errorf("Decision = %q, want deny for P0", result.Decision) | | 706 | + } | | 707 | + | | 708 | + // P1 allowed. | | 709 | + result, _ = eng.Evaluate(keep.Call{ | | 710 | + Operation: "create_issue", | | 711 | + Params: map[string]any{"priority": int64(1)}, | | 712 | + }, "cel-test") | | 713 | + if result.Decision != keep.Allow { | | 714 | + t.Errorf("Decision = %q, want allow for P1", result.Decision) | | 715 | + } | | 716 | +} |
|