|
| 1 | +// Package keep is an API-level policy engine for AI agents. |
| 2 | +package keep |
| 3 | + |
| 4 | +import ( |
| 5 | + "fmt" |
| 6 | + "sort" |
| 7 | + "sync" |
| 8 | + |
| 9 | + keepcel "github.com/majorcontext/keep/internal/cel" |
| 10 | + "github.com/majorcontext/keep/internal/config" |
| 11 | + "github.com/majorcontext/keep/internal/engine" |
| 12 | + "github.com/majorcontext/keep/internal/rate" |
| 13 | + "github.com/majorcontext/keep/internal/redact" |
| 14 | +) |
| 15 | + |
| 16 | +// Type aliases re-exported from internal packages. |
| 17 | +type Call = engine.Call |
| 18 | +type CallContext = engine.CallContext |
| 19 | +type EvalResult = engine.EvalResult |
| 20 | +type Decision = engine.Decision |
| 21 | +type AuditEntry = engine.AuditEntry |
| 22 | +type RuleResult = engine.RuleResult |
| 23 | +type Mutation = redact.Mutation |
| 24 | + |
| 25 | +// Decision constants re-exported from the engine package. |
| 26 | +const ( |
| 27 | + Allow = engine.Allow |
| 28 | + Deny = engine.Deny |
| 29 | + Redact = engine.Redact |
| 30 | +) |
| 31 | + |
| 32 | +// Engine holds compiled evaluators for each policy scope. |
| 33 | +type Engine struct { |
| 34 | + mu sync.RWMutex |
| 35 | + evaluators map[string]*engine.Evaluator |
| 36 | + rateStore *rate.Store |
| 37 | + cfg engineConfig |
| 38 | +} |
| 39 | + |
| 40 | +type engineConfig struct { |
| 41 | + rulesDir string |
| 42 | + profilesDir string |
| 43 | + packsDir string |
| 44 | + forceEnforce bool |
| 45 | +} |
| 46 | + |
| 47 | +// Option configures Load behavior. |
| 48 | +type Option func(*engineConfig) |
| 49 | + |
| 50 | +// WithProfilesDir sets the directory to load profile YAML files from. |
| 51 | +func WithProfilesDir(dir string) Option { return func(c *engineConfig) { c.profilesDir = dir } } |
| 52 | + |
| 53 | +// WithPacksDir sets the directory to load starter pack YAML files from. |
| 54 | +func WithPacksDir(dir string) Option { return func(c *engineConfig) { c.packsDir = dir } } |
| 55 | + |
| 56 | +// WithForceEnforce overrides every scope's mode to "enforce". |
| 57 | +func WithForceEnforce() Option { return func(c *engineConfig) { c.forceEnforce = true } } |
| 58 | + |
| 59 | +// Load reads rule files from rulesDir, compiles all CEL expressions and |
| 60 | +// redact patterns, and returns a ready-to-use Engine. |
| 61 | +func Load(rulesDir string, opts ...Option) (*Engine, error) { |
| 62 | + cfg := engineConfig{rulesDir: rulesDir} |
| 63 | + for _, opt := range opts { |
| 64 | + opt(&cfg) |
| 65 | + } |
| 66 | + |
| 67 | + // 1. Load config. |
| 68 | + loadResult, err := config.LoadAll(rulesDir, cfg.profilesDir, cfg.packsDir) |
| 69 | + if err != nil { |
| 70 | + return nil, fmt.Errorf("keep: load config: %w", err) |
| 71 | + } |
| 72 | + |
| 73 | + // 2. Create rate store. |
| 74 | + store := rate.NewStore() |
| 75 | + |
| 76 | + // 3. Create CEL environment. |
| 77 | + celEnv, err := keepcel.NewEnv(keepcel.WithRateStore(store)) |
| 78 | + if err != nil { |
| 79 | + return nil, fmt.Errorf("keep: create cel env: %w", err) |
| 80 | + } |
| 81 | + |
| 82 | + // 4. Build evaluators for each scope. |
| 83 | + evaluators, err := buildEvaluators(loadResult, celEnv, cfg) |
| 84 | + if err != nil { |
| 85 | + return nil, err |
| 86 | + } |
| 87 | + |
| 88 | + return &Engine{ |
| 89 | + evaluators: evaluators, |
| 90 | + rateStore: store, |
| 91 | + cfg: cfg, |
| 92 | + }, nil |
| 93 | +} |
| 94 | + |
| 95 | +// Evaluate runs all rules in the given scope against the call and returns |
| 96 | +// the policy decision. |
| 97 | +func (e *Engine) Evaluate(call Call, scope string) (EvalResult, error) { |
| 98 | + e.mu.RLock() |
| 99 | + ev, ok := e.evaluators[scope] |
| 100 | + e.mu.RUnlock() |
| 101 | + |
| 102 | + if !ok { |
| 103 | + return EvalResult{}, fmt.Errorf("keep: scope %q not found", scope) |
| 104 | + } |
| 105 | + |
| 106 | + return ev.Evaluate(call), nil |
| 107 | +} |
| 108 | + |
| 109 | +// Scopes returns the sorted list of loaded scope names. |
| 110 | +func (e *Engine) Scopes() []string { |
| 111 | + e.mu.RLock() |
| 112 | + defer e.mu.RUnlock() |
| 113 | + scopes := make([]string, 0, len(e.evaluators)) |
| 114 | + for name := range e.evaluators { |
| 115 | + scopes = append(scopes, name) |
| 116 | + } |
| 117 | + sort.Strings(scopes) |
| 118 | + return scopes |
| 119 | +} |
| 120 | + |
| 121 | +// Reload re-reads all configuration from disk and recompiles evaluators. |
| 122 | +// The rate store is preserved across reloads. |
| 123 | +func (e *Engine) Reload() error { |
| 124 | + loadResult, err := config.LoadAll(e.cfg.rulesDir, e.cfg.profilesDir, e.cfg.packsDir) |
| 125 | + if err != nil { |
| 126 | + return fmt.Errorf("keep: reload: %w", err) |
| 127 | + } |
| 128 | + |
| 129 | + celEnv, err := keepcel.NewEnv(keepcel.WithRateStore(e.rateStore)) |
| 130 | + if err != nil { |
| 131 | + return fmt.Errorf("keep: reload cel env: %w", err) |
| 132 | + } |
| 133 | + |
| 134 | + evaluators, err := buildEvaluators(loadResult, celEnv, e.cfg) |
| 135 | + if err != nil { |
| 136 | + return fmt.Errorf("keep: reload: %w", err) |
| 137 | + } |
| 138 | + |
| 139 | + e.mu.Lock() |
| 140 | + e.evaluators = evaluators |
| 141 | + e.mu.Unlock() |
| 142 | + |
| 143 | + return nil |
| 144 | +} |
| 145 | + |
| 146 | +// ApplyMutations returns a new params map with the given mutations applied. |
| 147 | +// The original map is not modified. |
| 148 | +func ApplyMutations(params map[string]any, mutations []Mutation) map[string]any { |
| 149 | + return redact.ApplyMutations(params, mutations) |
| 150 | +} |
| 151 | + |
| 152 | +// buildEvaluators creates compiled evaluators for every scope in the load result. |
| 153 | +func buildEvaluators(lr *config.LoadResult, celEnv *keepcel.Env, cfg engineConfig) (map[string]*engine.Evaluator, error) { |
| 154 | + evaluators := make(map[string]*engine.Evaluator, len(lr.Scopes)) |
| 155 | + for scopeName, rf := range lr.Scopes { |
| 156 | + rules := lr.ResolvedRules[scopeName] |
| 157 | + |
| 158 | + // Get profile aliases if scope has a profile. |
| 159 | + var aliases map[string]string |
| 160 | + if rf.Profile != "" { |
| 161 | + if p, ok := lr.Profiles[rf.Profile]; ok { |
| 162 | + aliases = p.Aliases |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + mode := rf.Mode |
| 167 | + if cfg.forceEnforce { |
| 168 | + mode = config.ModeEnforce |
| 169 | + } |
| 170 | + if mode == "" { |
| 171 | + mode = config.ModeAuditOnly // default |
| 172 | + } |
| 173 | + |
| 174 | + onError := rf.OnError |
| 175 | + if onError == "" { |
| 176 | + onError = config.ErrorModeClosed // default |
| 177 | + } |
| 178 | + |
| 179 | + ev, err := engine.NewEvaluator(celEnv, scopeName, mode, onError, rules, aliases) |
| 180 | + if err != nil { |
| 181 | + return nil, fmt.Errorf("keep: compile scope %q: %w", scopeName, err) |
| 182 | + } |
| 183 | + evaluators[scopeName] = ev |
| 184 | + } |
| 185 | + return evaluators, nil |
| 186 | +} |