Phase 4: policy engine with deny-wins, default-deny evaluation
internal/policy/: Priority-based policy engine per ARCHITECTURE.md §4. Stateless Evaluate() sorts rules by priority, collects all matches, deny-wins over allow, default-deny if no match. Rule matching: all populated fields ANDed, empty fields are wildcards, repository glob via path.Match. Built-in defaults: admin wildcard (all actions), human user content access (pull/push/delete/catalog), version check (always accessible). Engine wrapper with sync.RWMutex-protected cache, SetRules merges with defaults, Reload loads from RuleStore. internal/db/: LoadEnabledPolicyRules() parses rule_json column from policy_rules table into []policy.Rule, filtered by enabled=1, ordered by priority. internal/server/: RequirePolicy middleware extracts claims from context, repo from chi URL param, evaluates policy, returns OCI DENIED (403) on deny with optional audit callback. 69 tests passing across all packages. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
55
internal/policy/engine.go
Normal file
55
internal/policy/engine.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// RuleStore loads policy rules from a backing store.
|
||||
type RuleStore interface {
|
||||
LoadEnabledPolicyRules() ([]Rule, error)
|
||||
}
|
||||
|
||||
// Engine wraps stateless Evaluate with an in-memory rule cache and
|
||||
// thread-safe access.
|
||||
type Engine struct {
|
||||
mu sync.RWMutex
|
||||
rules []Rule
|
||||
}
|
||||
|
||||
// NewEngine creates an Engine pre-loaded with the built-in default rules.
|
||||
func NewEngine() *Engine {
|
||||
return &Engine{rules: DefaultRules()}
|
||||
}
|
||||
|
||||
// SetRules replaces the cached rule set. The provided rules are merged
|
||||
// with the built-in defaults.
|
||||
func (e *Engine) SetRules(rules []Rule) {
|
||||
merged := make([]Rule, 0, len(DefaultRules())+len(rules))
|
||||
merged = append(merged, DefaultRules()...)
|
||||
merged = append(merged, rules...)
|
||||
|
||||
e.mu.Lock()
|
||||
e.rules = merged
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
// Evaluate runs the policy engine against the cached rule set.
|
||||
func (e *Engine) Evaluate(input PolicyInput) (Effect, *Rule) {
|
||||
e.mu.RLock()
|
||||
rules := make([]Rule, len(e.rules))
|
||||
copy(rules, e.rules)
|
||||
e.mu.RUnlock()
|
||||
|
||||
return Evaluate(input, rules)
|
||||
}
|
||||
|
||||
// Reload loads enabled rules from the store and updates the cache.
|
||||
func (e *Engine) Reload(store RuleStore) error {
|
||||
rules, err := store.LoadEnabledPolicyRules()
|
||||
if err != nil {
|
||||
return fmt.Errorf("policy: reload rules: %w", err)
|
||||
}
|
||||
e.SetRules(rules)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user