Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

9.4 KB
Raw Blame
package threatrules

import (
	"encoding/json"
	"fmt"
	"regexp"
	"time"

	"gopkg.in/yaml.v3"

	"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)

// idPattern constrains rule ids to a stable kebab slug.
var idPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)

// ValidID reports whether id is a well-formed rule id. The pattern admits no
// path separators or "." segments, so a valid id is always a safe single
// filename component when joined with the store directory.
func ValidID(id string) bool { return idPattern.MatchString(id) }

// Status is a rule's maturity level; it drives the conformance gates (see lint.go).
type Status string

const (
	StatusExperimental Status = "experimental"
	StatusStable       Status = "stable"
	StatusDeprecated   Status = "deprecated"
)

// Posture declares whether a rule is observe-only or eligible for enforcement. It maps
// onto PolicyInfo.Enforcement; only "detect" is acted on in this phase.
type Posture string

const (
	PostureDetect         Posture = "detect"
	PostureEnforceCapable Posture = "enforce-capable"
)

// Scope is the correlation grouping key. v1 supports session only.
type Scope string

const ScopeSession Scope = "session"

// Rule is a single threat-detection rule. Exactly one of Match or Correlation is set.
type Rule struct {
	ID string `yaml:"id"`
	// Spec is the minimum Threat Rules spec version the rule needs, such as
	// "threat-rules/v1.1". Empty means the original v1. A rule that uses a feature added
	// after v1 must declare it, so an engine that predates the feature can tell the rule
	// is too new instead of failing on an unknown field.
	Spec        string                    `yaml:"spec,omitempty"`
	Version     int                       `yaml:"version"`
	Title       string                    `yaml:"title"`
	Description string                    `yaml:"description,omitempty"`
	Severity    asymptoteobserve.Severity `yaml:"severity"`
	Status      Status                    `yaml:"status"`
	Posture     Posture                   `yaml:"posture"`
	Taxonomy    map[string]string         `yaml:"taxonomy,omitempty"`
	Match       string                    `yaml:"match,omitempty"`
	Correlation *Correlation              `yaml:"correlation,omitempty"`
	Emit        Emit                      `yaml:"emit"`
	Tests       []Fixture                 `yaml:"tests"`
}

// Order says whether a correlation's steps must occur in the order they are listed.
type Order string

const (
	// OrderSequence is the default: each step must occur at or after the previous
	// matched step. An omitted order means sequence, so existing rules keep their
	// semantics.
	OrderSequence Order = "sequence"
	// OrderAny matches when every step is satisfied by a distinct event inside the
	// window, in whatever order those events occurred.
	OrderAny Order = "any"
)

// Correlation is the windowed, session-scoped form of a rule.
type Correlation struct {
	Scope  Scope             `yaml:"scope"`
	Window string            `yaml:"window"`
	Order  Order             `yaml:"order,omitempty"`
	Steps  []CorrelationStep `yaml:"steps"`
}

// AnyOrder reports whether the steps may be satisfied in any order.
func (c *Correlation) AnyOrder() bool { return c.Order == OrderAny }

// ParseWindow parses the raw Window duration. Valid to call after Validate succeeds.
func (c *Correlation) ParseWindow() (time.Duration, error) {
	return time.ParseDuration(c.Window)
}

// CorrelationStep is one step of a correlation rule.
type CorrelationStep struct {
	ID    string `yaml:"id"`
	Match string `yaml:"match"`
}

// Emit describes the finding produced when a rule matches. The rest of a PolicyInfo is
// derived from the rule (id, title, posture); only the human-readable reason is authored.
type Emit struct {
	Reason string `yaml:"reason"`
}

// Fixture is an embedded conformance test case: feed Events through an evaluator and the
// produced verdict must equal Verdict.
type Fixture struct {
	Name    string         `yaml:"name"`
	Verdict Verdict        `yaml:"verdict"`
	Events  []FixtureEvent `yaml:"events"`
}

// EventList returns the fixture's events as plain Beacon events for evaluation.
func (f Fixture) EventList() []asymptoteobserve.Event {
	events := make([]asymptoteobserve.Event, len(f.Events))
	for i := range f.Events {
		events[i] = f.Events[i].Event
	}
	return events
}

// FixtureEvent wraps a Beacon Event so fixture YAML can use the event's JSON field names
// (e.g. event.action, command.command, gen_ai.usage.input_tokens) — the same names a
// rule's CEL expression references. yaml.v3 keys off Go field names, not json tags, so we
// decode each event through a YAML->generic->JSON bridge to honor the json tags.
type FixtureEvent struct {
	Event asymptoteobserve.Event
}

// UnmarshalYAML decodes one fixture event via the YAML->JSON bridge described above.
func (fe *FixtureEvent) UnmarshalYAML(node *yaml.Node) error {
	var raw map[string]any
	if err := node.Decode(&raw); err != nil {
		return err
	}
	data, err := json.Marshal(raw)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, &fe.Event)
}

func validSeverity(s asymptoteobserve.Severity) bool {
	switch s {
	case asymptoteobserve.SeverityInfo, asymptoteobserve.SeverityLow, asymptoteobserve.SeverityMedium,
		asymptoteobserve.SeverityHigh, asymptoteobserve.SeverityCritical:
		return true
	}
	return false
}

// Validate checks a rule against the spec: structural constraints plus every CEL match
// expression compiling to bool against the event schema. A nil return means the rule is
// loadable; it does not by itself assert maturity-ladder gates (see CheckMaturity).
func (r *Rule) Validate() error {
	if !idPattern.MatchString(r.ID) {
		return fmt.Errorf("id %q must match %s", r.ID, idPattern.String())
	}
	if err := checkSpecSupported(r.ID, r.Spec); err != nil {
		return err
	}
	if r.Version < 1 {
		return fmt.Errorf("version must be >= 1, got %d", r.Version)
	}
	if r.Title == "" {
		return fmt.Errorf("title is required")
	}
	if !validSeverity(r.Severity) {
		return fmt.Errorf("invalid severity %q", r.Severity)
	}
	switch r.Status {
	case StatusExperimental, StatusStable, StatusDeprecated:
	default:
		return fmt.Errorf("invalid status %q", r.Status)
	}
	switch r.Posture {
	case PostureDetect, PostureEnforceCapable:
	default:
		return fmt.Errorf("invalid posture %q", r.Posture)
	}
	if r.Emit.Reason == "" {
		return fmt.Errorf("emit.reason is required")
	}
	if len(r.Tests) == 0 {
		return fmt.Errorf("at least one test fixture is required")
	}

	hasMatch := r.Match != ""
	hasCorrelation := r.Correlation != nil
	switch {
	case hasMatch && hasCorrelation:
		return fmt.Errorf("exactly one of match or correlation may be set, both are present")
	case !hasMatch && !hasCorrelation:
		return fmt.Errorf("exactly one of match or correlation must be set, neither is present")
	}

	if err := r.validateExpressions(); err != nil {
		return err
	}
	if hasCorrelation {
		if err := r.validateCorrelation(); err != nil {
			return err
		}
	}
	if err := r.validateFixtures(); err != nil {
		return err
	}
	return nil
}

// validateExpressions compiles every CEL match in the rule, surfacing unknown-field and
// non-bool errors at load time, and requires the spec version of any field the rule uses that
// an earlier version lacks.
func (r *Rule) validateExpressions() error {
	if r.Match != "" {
		if err := r.validateExpression(r.Match); err != nil {
			return fmt.Errorf("match: %w", err)
		}
	}
	if r.Correlation != nil {
		for i, step := range r.Correlation.Steps {
			if err := r.validateExpression(step.Match); err != nil {
				return fmt.Errorf("correlation.steps[%d] (%s): %w", i, step.ID, err)
			}
		}
	}
	return nil
}

func (r *Rule) validateExpression(expr string) error {
	_, ast, err := compileMatch(expr)
	if err != nil {
		return err
	}
	// Already known to be parseable and supported (Validate checked it first).
	if v, _ := parseSpec(r.Spec); specV1_2.newerThan(v) && selectsField(ast, "parsed_commands") {
		return fmt.Errorf("e.%s requires spec: threat-rules/v1.2 or later (engines before v1.2 reject the field)", ParsedCommandsPath)
	}
	return nil
}

func (r *Rule) validateCorrelation() error {
	c := r.Correlation
	if c.Scope != ScopeSession {
		return fmt.Errorf("correlation.scope %q unsupported (only %q)", c.Scope, ScopeSession)
	}
	if _, err := c.ParseWindow(); err != nil {
		return fmt.Errorf("correlation.window %q: %w", c.Window, err)
	}
	switch c.Order {
	case "", OrderSequence, OrderAny:
	default:
		return fmt.Errorf("correlation.order %q unsupported (%q or %q)", c.Order, OrderSequence, OrderAny)
	}
	if c.Order != "" {
		// Already known to be parseable and supported (Validate checked it first).
		if v, _ := parseSpec(r.Spec); specV1_1.newerThan(v) {
			return fmt.Errorf("correlation.order requires spec: threat-rules/v1.1 or later (engines before v1.1 reject the field)")
		}
	}
	if len(c.Steps) < 2 {
		return fmt.Errorf("correlation requires >= 2 steps, got %d", len(c.Steps))
	}
	for i, step := range c.Steps {
		if step.ID == "" {
			return fmt.Errorf("correlation.steps[%d] missing id", i)
		}
		if step.Match == "" {
			return fmt.Errorf("correlation.steps[%d] (%s) missing match", i, step.ID)
		}
	}
	return nil
}

func (r *Rule) validateFixtures() error {
	for i, f := range r.Tests {
		if f.Name == "" {
			return fmt.Errorf("tests[%d] missing name", i)
		}
		if !f.Verdict.valid() {
			return fmt.Errorf("tests[%d] (%s) invalid verdict %q", i, f.Name, f.Verdict)
		}
		if len(f.Events) == 0 {
			return fmt.Errorf("tests[%d] (%s) requires at least one event", i, f.Name)
		}
	}
	return nil
}