policyeval

package
v0.111.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package policyeval is a pure-Go rule engine for in-process policy evaluation. Rules are declared as Go literals (no YAML/JSON files at runtime), executed against a map[string]any Fact, and return the winning Decision plus an explanation string.

Package policyeval is a small, pure-Go rule engine used by fleet services that need to take a fact (a typed input flattened to a map) and a static ruleset, and decide an outcome (channel, priority, tags, …) plus a human-readable explanation of which rules fired.

It exists because at least five services in the fleet had each rolled their own near-identical "if severity in [critical,high] and env eq prod then route to slack-incident" decision engine — scope-guard, leak-bounty-policy, target-reputation (ADR-0021), fleet-priority-queue (ADR-0019), and finding-triage. Centralising the engine means adding a new operator or fact shape touches one repo, not five.

Design choices, called out so callers can plan around them:

  • Pure stdlib. No Rego runtime, no YAML loader, no plugin surface. Rules are expressed as Go literals (`[]Rule{…}`) in the service's own code. If you need rules-from-config, decode your config into `[]Rule` yourself and pass it in.
  • `Decision` is `any` — the engine treats it opaquely. Callers define their own decision struct.
  • `Fact` is `map[string]any`. Build it from your typed input by hand or via reflection — the engine itself only needs the map.
  • Dotted field access (`target.severity`) walks `map[string]any` and exported struct fields. A missing intermediate hop makes the predicate false, except for `NotExists`, where it makes the predicate true.
  • Numeric ordering (`Lt`/`Le`/`Gt`/`Ge`) accepts mixed int / int64 / float64; a `time.Time` on both sides is compared chronologically. Mismatched kinds (string vs int) return an error from `Evaluate` rather than silently failing.
  • Regexps are compiled on first use and cached by pattern string. Bad patterns surface from `Evaluate` as errors, not panics.
  • A `[]Rule` is read-only after construction. `Evaluate` is safe to call concurrently against the same ruleset.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownOp = errors.New("policyeval: unknown operator")

ErrUnknownOp is returned (wrapped) when a Predicate carries an Op that the engine does not implement. Callers can `errors.Is` against it if they want to distinguish from data-shape errors.

Functions

func SetDefaultObserver

func SetDefaultObserver(o Observer)

SetDefaultObserver installs a process-wide observer. Pass nil to disable. Set by go-common/server.AutoWire when promx is in use so every Evaluate call in the process produces fleet metrics.

Types

type Decision

type Decision any

Decision is opaque to the engine. Callers define their own struct, e.g. `type Decision struct{ Channel string; Priority int; Tags []string }`.

type Event

type Event struct {
	// Ruleset identifies the caller's logical ruleset, e.g.
	// "leak-bounty-policy" or "target-reputation". Empty when the
	// caller used Evaluate without labelling.
	Ruleset string
	// Matched is the ordered list of rule names that fired. Empty
	// when no rule matched.
	Matched []string
	// Winner is the rule whose decision was returned, or "" when no
	// rule matched.
	Winner string
	// Err carries any evaluation error (bad regex, type mismatch).
	// Non-nil errors abort evaluation and Matched/Winner are empty.
	Err error
}

Event is the per-Evaluate payload handed to an Observer. Matched carries every rule that fired (same as Result.Matched); the observer can fan it out into per-rule counters.

type Fact

type Fact map[string]any

Fact is the input to evaluation: a map keyed on field name. Values can be string, bool, int / int64 / float64, time.Time, []string, []any, nested map[string]any, or a struct (exported fields only). Callers wrap their typed input into a Fact via reflection or by hand. The engine does not care how the map was built.

type Observer

type Observer interface {
	ObservePolicy(Event)
}

Observer receives one event per Evaluate call. Implementations MUST NOT block — callbacks run inline on the decision hot path. The canonical implementation lives in go-common/promx.

policyeval deliberately defines the contract here rather than importing a metrics library: policyeval keeps zero metric-stack deps.

func DefaultObserver

func DefaultObserver() Observer

DefaultObserver returns the current process-wide observer or nil.

type Op

type Op string

Op is the comparison kind in a Predicate.

const (
	// Eq returns true when the field value equals Value. For slices,
	// equality is element-wise via reflect.DeepEqual.
	Eq Op = "eq"
	// Ne is the negation of Eq.
	Ne Op = "ne"
	// Lt / Le / Gt / Ge compare numerics (int/int64/float64) or
	// chronological time.Time values. Mixed kinds (string vs int)
	// return an error from Evaluate.
	Lt Op = "lt"
	Le Op = "le"
	Gt Op = "gt"
	Ge Op = "ge"
	// In matches when the fact value equals any element of Value.
	// Value must be []any (or a typed slice — the engine converts).
	In Op = "in"
	// NotIn is the negation of In.
	NotIn Op = "not_in"
	// Contains matches:
	//   * substring: fact is string, Value is string
	//   * slice membership: fact is a slice, Value is any element
	Contains Op = "contains"
	// Matches runs Value (a string regexp) against a string fact.
	// Bad patterns return an error from Evaluate.
	Matches Op = "matches"
	// Exists is true when the dotted field resolves to a non-nil value.
	Exists Op = "exists"
	// NotExists is the negation of Exists. Unlike most predicates,
	// it is *true* when an intermediate dotted hop is missing.
	NotExists Op = "not_exists"
)

Supported operators.

type Predicate

type Predicate struct {
	// Field is the fact key. Dotted paths walk nested
	// map[string]any / struct values: `target.severity`,
	// `request.headers.x_api_key`.
	Field string
	// Op is the comparison.
	Op Op
	// Value is the right-hand operand. Shape depends on Op (see the
	// per-op docs above). Ignored for Exists / NotExists.
	Value any
}

Predicate is one term in a Rule's When list.

type Result

type Result struct {
	// Decision is the winning rule's Then. Nil interface when no
	// rule matched.
	Decision Decision
	// Matched lists every rule that fired, in evaluation order.
	Matched []string
	// Explanation is a concise human-readable trail. Example:
	//   `matched 2 rule(s): high-sev (severity in [critical high] AND env eq prod); ...`
	// Format is intentionally informal — for logs and `/explain`
	// endpoints, not machine parsing.
	Explanation string
}

Result is what Evaluate returns.

func Evaluate

func Evaluate(rules []Rule, fact Fact) (Result, error)

Evaluate runs the ruleset against fact and returns the winning decision plus a trail. Selection rules:

  • If no rule matches, Result has zero-value Decision (nil interface), empty Matched, and an empty Explanation; no error.
  • If a matched rule has Stop=true, evaluation halts there and that rule wins.
  • Otherwise the LAST matching rule wins.

Evaluation errors (bad regex, type mismatch in ordered compare, unknown operator) abort evaluation and are returned as the error value. The caller decides whether to treat construction errors as fail-open or fail-closed.

Evaluate is safe to call from multiple goroutines against the same ruleset.

func EvaluateLabeled

func EvaluateLabeled(ruleset string, rules []Rule, fact Fact) (Result, error)

EvaluateLabeled is Evaluate with an explicit ruleset label that flows into the Observer. Use this in production code — it lets the promx collector emit `policyeval_rule_fires_total{ruleset,rule}` with stable, low-cardinality labels.

type Rule

type Rule struct {
	// Name identifies the rule in the explanation trail. Keep it
	// short and human-readable (`high-severity-prod`,
	// `noisy-source-throttle`).
	Name string
	// When is the AND-joined predicate list. Empty = always match.
	When []Predicate
	// Then is the decision returned when the rule matches.
	Then Decision
	// Stop, when true, halts evaluation after this rule fires. The
	// rule's decision becomes the final one. Without Stop, the last
	// matching rule wins (later rules override earlier ones).
	Stop bool
}

Rule is a single decision: a list of predicates joined with AND, plus the Decision to emit if every predicate matches. An empty When list is treated as always-match.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL