Documentation
¶
Overview ¶
Package detector turns graph changes into investigation signals.
It sits between the change feed and pkg/reasoning, which hands it the previous and current canonical snapshots for a change window. It returns InvestigationSignal values. pkg/reasoning turns an active rule's signal into a finding directly, queues built-in novelty signals for agentic investigation, and only records shadow rule signals (marked RuleModeShadow).
The detector reads only provider-neutral graph data: resolved relationships, typed graph.SecuritySemantics, network roles, and bounded telemetry fingerprints. It never parses provider-native payloads or opens provider watches.
Signal sources ¶
Engine.Detect combines three sources and deduplicates them by signal ID:
- Built-in novelty (DetectNovelChanges): new workload-level communication paths, scored telemetry novelty, new external exposure, changed or removed security semantics, lost governance, sensitive resource creation, and workload identity changes. Instances are folded into the controller that instantiates them, so rollouts and scaling are not novel, and ordinary graph churn emits nothing. See Config for the scoring.
- CEL rules from the active Ruleset. Events derives one Event per new or newly resolved relationship edge and per newly observed telemetry combination; Engine.Evaluate matches each against rules selected by plugin, input type, kind, and optional workload. Each (type, kind) selector compiles in its own CEL environment that declares only the Input fields that selector populates, so a rule that reads an unset field fails to compile instead of silently never matching.
- Resource rules (ResourceRule), such as model-authored Kubernetes resource rules, indexed by resource so each input is matched only against the rules of the resource that is its subject (Event.SubjectIDs); a resource's rules never match inputs where it is only the object. Each runs in RuleModeActive or RuleModeShadow.
Rulesets and reload ¶
A compiled ruleset is immutable. Engine.Reload compiles a newly activated ruleset completely before swapping it in atomically, so every evaluation runs against exactly one pinned ruleset and records its ID, digest, and activation revision. A reload failure keeps the last known-good ruleset and is reported through Engine.Status. Invalid resource rules are skipped and counted rather than unloading the whole overlay. Evaluation errors are returned, never treated as "no match", so reasoning records the window as failed instead of claiming it was evaluated.
Bounds ¶
Rulesets hold at most 256 rules and the resource overlay at most MaxResourceRules. Expressions are at most 8 KiB and 10,000 CEL cost units, with no host I/O functions. An evaluation reads at most MaxEvaluationEvents inputs of 64 KiB each and emits at most MaxEvaluationSignals rule signals; the rest are counted in Result.Omitted rather than failing the evaluation. Raw IP addresses are never exposed to CEL; only their telemetry destination class is.
See https://agent-shield.dev/docs/architecture/detection-rules/ for rule authoring and storage.
Index ¶
- Constants
- Variables
- func CELEnvironment(inputType, kind string) (*cel.Env, error)
- func CELExpressionDescription() string
- func CELSelectorDescription() string
- func CELSelectorDescriptionFor(names []string) string
- func CELSelectorNames() []string
- func CanonicalRuleset(ruleset Ruleset) ([]byte, error)
- func ParseCELSelector(name string) (inputType, kind string, ok bool)
- func ResourceRulesDigest(rules []ResourceRule) (string, error)
- func RulesetDigest(ruleset Ruleset) (string, error)
- func ValidCELRuleKind(inputType, kind string) bool
- func ValidateResourceRules(rules []ResourceRule) error
- func ValidateRuleset(ruleset Ruleset) error
- type Activation
- type CELSelector
- type CELVariable
- type Config
- type Detector
- type Engine
- func (engine *Engine) Detect(ctx context.Context, previous, current graph.Snapshot, observedAt time.Time) (Result, error)
- func (engine *Engine) Evaluate(ctx context.Context, events []Event) (Result, error)
- func (engine *Engine) Reload(ctx context.Context, repository Repository) (err error)
- func (engine *Engine) ReloadResourceRules(ctx context.Context, repository ResourceRuleRepository) error
- func (engine *Engine) RunReloads(ctx context.Context, repository Repository, interval time.Duration, ...) error
- func (engine *Engine) SetResourceRules(rules []ResourceRule) error
- func (engine *Engine) Status() Status
- type Event
- type Input
- type InvestigationSignal
- type Repository
- type ResourceRule
- type ResourceRuleRepository
- type Result
- type Risk
- type Rule
- type RuleMode
- type Ruleset
- type SensitiveResourcePolicy
- type Status
- type TimeWindow
Constants ¶
const ( MaxEvaluationEvents = 100_000 MaxEvaluationSignals = 1000 )
Evaluation bounds. Inputs and signals beyond them are left out and counted in Result.Omitted rather than failing the evaluation, so one oversized window, such as a large rollout, cannot stop detection.
const InputVersion = "v1"
InputVersion is the Input contract version rules must declare. A change to the meaning of any input field requires a new version.
const MaxResourceRules = 30_000
MaxResourceRules bounds the resource rule overlay. A resource loads at most two rule sets (its approved and its current draft) of up to three rules each, so the bound keeps room for about 5,000 resources. Rules over the bound are not loaded; see Engine.SetResourceRules.
Variables ¶
var ErrActivationConflict = errors.New("detector ruleset activation revision conflict")
ErrActivationConflict is returned when an activation's expected revision is not the current one, meaning another activation won the race.
var ErrNoActiveRuleset = errors.New("no active detector ruleset")
ErrNoActiveRuleset is returned by a Repository when no ruleset has been activated. An activated empty ruleset is different: it disables detection.
Functions ¶
func CELEnvironment ¶
CELEnvironment declares only the variables the selector populates.
func CELExpressionDescription ¶
func CELExpressionDescription() string
CELExpressionDescription renders the CEL variable contract, with allowed values, as text for a model authoring schema.
func CELSelectorDescription ¶
func CELSelectorDescription() string
CELSelectorDescription renders the selector catalog as text for a model authoring schema.
func CELSelectorDescriptionFor ¶
CELSelectorDescriptionFor documents the named selectors; nil documents every selector.
func CELSelectorNames ¶
func CELSelectorNames() []string
CELSelectorNames returns the "type:kind" name of every selector.
func CanonicalRuleset ¶
CanonicalRuleset encodes ruleset with rules sorted by ID, so the encoding and RulesetDigest do not depend on rule order.
func ParseCELSelector ¶
ParseCELSelector splits a "type:kind" name and reports whether it names a known selector.
func ResourceRulesDigest ¶
func ResourceRulesDigest(rules []ResourceRule) (string, error)
ResourceRulesDigest returns the canonical digest of a resource rule set.
func RulesetDigest ¶
RulesetDigest returns the hex SHA-256 of the canonical ruleset. Signal IDs include it, so the same input matched under different rulesets yields different signals.
func ValidCELRuleKind ¶
ValidCELRuleKind reports whether (inputType, kind) is a known selector.
func ValidateResourceRules ¶
func ValidateResourceRules(rules []ResourceRule) error
ValidateResourceRules compiles resource rules without loading them. Unlike Engine.SetResourceRules, any rule that would be skipped is an error.
func ValidateRuleset ¶
ValidateRuleset compiles ruleset exactly as activation would, without activating it.
Types ¶
type Activation ¶
Activation is the active ruleset and its monotonically increasing activation revision.
type CELSelector ¶
type CELSelector struct {
Type string
Kind string
Description string
Trigger string
Fields map[string]string
}
CELSelector is one evaluable (input type, kind) pair; only its Fields are declared to CEL.
func CELSelectors ¶
func CELSelectors() []CELSelector
CELSelectors returns every evaluable selector: one relationship selector per registered graph predicate and one telemetry selector per telemetry event kind. It is the single catalog used for rule validation, authoring schemas, and documentation.
func (CELSelector) Name ¶
func (selector CELSelector) Name() string
Name returns the selector as "type:kind".
type CELVariable ¶
type CELVariable struct {
Name string
Description string
// contains filtered or unexported fields
}
CELVariable describes one Input field as a CEL variable.
func CELContractVariables ¶
func CELContractVariables() []CELVariable
CELContractVariables returns every Input field as a CEL variable, named by its JSON tag.
func (CELVariable) Type ¶
func (variable CELVariable) Type() string
Type returns the variable's CEL type name.
type Config ¶
type Config struct {
// Window is the signal half-width for built-in signals and rules that do not set windowSeconds.
Window time.Duration
// SensitiveRoleWeights add to the score of novel communication and telemetry
// toward destinations with the given network/role.
SensitiveRoleWeights map[string]int
// ExternalDestinationWeight adds to the score of a new communication path to a public destination.
ExternalDestinationWeight int
SensitiveResourcePolicies []SensitiveResourcePolicy
// MinimumScore drops built-in signals below this score. Scores of 3 or more are medium risk
// and eligible for agentic investigation; 2 is low risk and recorded only. Values below 1
// are treated as 1.
MinimumScore int
}
Config tunes the built-in novelty detector.
Built-in telemetry novelty scores 1 for a new (kind, endpoints, operation, outcome) combination, adds 1 when the endpoint pair itself is new, and adds the destination role's SensitiveRoleWeights entry. Topology signals use fixed scores: 3 for a changed security envelope or other graph change, 4 for new external exposure, removed security semantics, or lost governance. Scores map to risk as 6+ critical, 4-5 high, 3 medium, and below 3 low.
With the defaults, a new operation between known endpoints (score 1) is dropped, a new pair to an ordinary destination (2) is a low-risk signal that can inform but never promote a finding, and novelty toward a control-plane API, identity provider, or secrets store (4 or more) is high risk. This keeps routine churn below the model-call threshold while still reaching sensitive destinations on first contact.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a five-minute window, weights for sensitive roles, and a minimum score of 2.
type Detector ¶
type Detector interface {
Detect(context.Context, graph.Snapshot, graph.Snapshot, time.Time) (Result, error)
}
Detector compares two snapshots. observedAt centers signal windows; zero uses the latest telemetry first-seen time in the current snapshot.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine evaluates built-in novelty and the active CEL ruleset. It is safe for concurrent use: evaluations load the active ruleset once through an atomic pointer, so a concurrent reload never changes the rules mid-evaluation.
func Load ¶
Load compiles the active ruleset from repository. Unlike Engine.Reload, a ruleset failure is returned: there is no known-good ruleset to fall back to, so invalid operator rules fail startup. The resource rule overlay never fails startup: invalid resource rules are skipped, and if the overlay cannot be read the engine starts without it. Either is recorded for Engine.Status, and the next reload retries.
func New ¶
New compiles ruleset and returns an engine. The activation revision is zero; use Load for a stored activation.
func (*Engine) Detect ¶
func (engine *Engine) Detect(ctx context.Context, previous, current graph.Snapshot, observedAt time.Time) (Result, error)
Detect returns built-in novelty signals plus signals from the active CEL ruleset and resource rules.
func (*Engine) Evaluate ¶
Evaluate matches events against the ruleset active when it starts. It returns an error, rather than a partial result, on cancellation or a CEL runtime error, so callers never mistake a failed evaluation for "no match". Events beyond MaxEvaluationEvents, events over 64 KiB, and rule signals beyond MaxEvaluationSignals are left out deterministically, in the order given, and counted in Result.Omitted.
func (*Engine) Reload ¶
func (engine *Engine) Reload(ctx context.Context, repository Repository) (err error)
Reload reads the active activation and swaps in its ruleset if it is new. When repository also implements ResourceRuleRepository, it then refreshes the resource-scoped rules the same way.
The candidate is compiled completely before the atomic swap, so an evaluation sees either the old ruleset or the new one, never a mix, and in-flight evaluations finish on the ruleset they loaded. An unchanged revision is only checksum-compared, not recompiled. A revision that moves backward, or content that changed without a new revision, is an error.
On any error the current rules stay active (last known good) and the error is recorded for Engine.Status. Reloads are serialized.
func (*Engine) ReloadResourceRules ¶
func (engine *Engine) ReloadResourceRules(ctx context.Context, repository ResourceRuleRepository) error
ReloadResourceRules reads and swaps in resource rules. A read failure retains the current rules; invalid rules are skipped as in Engine.SetResourceRules.
func (*Engine) RunReloads ¶
func (engine *Engine) RunReloads(ctx context.Context, repository Repository, interval time.Duration, report func(error)) error
RunReloads calls Engine.Reload every interval until ctx is cancelled. Reload errors go to report and do not stop the loop. Polling is independent of graph changes, and a reload affects only future evaluations; it never replays history.
func (*Engine) SetResourceRules ¶
func (engine *Engine) SetResourceRules(rules []ResourceRule) error
SetResourceRules compiles rules and then swaps them in atomically. Invalid rules and rules over MaxResourceRules are skipped rather than failing the whole overlay: the valid rules are loaded, Engine.Status counts the skipped ones, and the returned error describes them.
type Event ¶
type Event struct {
ID string `json:"id"`
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Type string `json:"type"`
Kind string `json:"kind"`
AnchorIDs []string `json:"anchorIds"`
SubjectIDs []string `json:"subjectIds,omitempty"`
ObservedAt time.Time `json:"observedAt"`
Input Input `json:"input"`
}
Event is one rule-evaluation input. ID is stable for the same edge owner or telemetry fingerprint. AnchorIDs are the subject and object; SubjectIDs are the subject alone. Both include any supported workload controller that instantiates an anchored Pod, so workload-scoped rules match Pod activity.
func Events ¶
Events returns newly resolved relationship edges and newly observed telemetry combinations.
A relationship yields one event per contributing (plugin, source) the first time it appears resolved; lease refreshes and removals yield none, so an existing edge never re-alerts. Telemetry novelty compares kind, endpoints, neutral operation, and outcome per plugin and source; count, property, and evidence churn alone produce nothing. Events are sorted by ID.
type Input ¶
type Input struct {
Operation string `json:"operation" cel_description:"Normalized operation of the observed activity; values depend on the selector."`
Outcome string `json:"outcome" cel_description:"Normalized outcome of the observed activity; values depend on the selector."`
DestinationIPClass string `json:"destination_ip_class" cel_description:"Class of the destination IP address. The raw address is never exposed."`
DestinationRole string `json:"destination_role" cel_description:"Cluster role of the destination, from the graph's known resource addresses."`
DestinationResourceID string `json:"destination_resource_id" cel_description:"Stable graph resource ID of the destination."`
ProcessClass string `json:"process_class" cel_description:"Class of the process the subject workload started."`
Attributes map[string]string `json:"attributes,omitempty" cel_description:"Bounded normalized attributes of the changed resource."`
}
Input holds every CEL variable; CELEnvironment declares only the subset a selector populates.
type InvestigationSignal ¶
type InvestigationSignal struct {
ID string `json:"id"`
Risk Risk `json:"risk"`
Reasons []string `json:"reasons"`
AnchorIDs []string `json:"anchorIds"`
Window TimeWindow `json:"window"`
RuleID string `json:"ruleId,omitempty"`
RuleRevision uint64 `json:"ruleRevision,omitempty"`
RulesetDigest string `json:"rulesetDigest,omitempty"`
// RuleMode is RuleModeShadow for signals from unreviewed resource rules, which are recorded but never investigated.
RuleMode RuleMode `json:"ruleMode,omitempty"`
}
InvestigationSignal asks reasoning to investigate the anchored resources within Window. ID is a content digest, so the same input and rule produce the same signal across retries. Rule fields are set only for CEL rule signals.
func DetectNovelChanges ¶
func DetectNovelChanges(previous, current graph.Snapshot, observedAt time.Time, config Config) []InvestigationSignal
DetectNovelChanges emits built-in investigation triggers for security-relevant graph changes and bounded telemetry novelty. It does not emit findings.
Communication novelty is compared per workload: Pods are folded into the controller that instantiates them, so rollouts, restarts, and scaling do not look like new behavior. Ordinary topology churn (new or changed Pods, Services, ConfigMaps, labels, and structural edges) emits nothing; only changes with a security meaning do.
func DetectNovelTelemetry ¶
func DetectNovelTelemetry(previous, current graph.Snapshot, config Config) []InvestigationSignal
DetectNovelTelemetry compares workload-level telemetry fingerprints and never returns telemetry IDs or evidence.
type Repository ¶
type Repository interface {
ReadActiveDetectorRuleset(context.Context) (Activation, error)
}
Repository reads the active ruleset. *state.Store implements it and verifies the stored content checksum before returning.
type ResourceRule ¶
ResourceRule is a rule scoped to one resource. Approved rules run in RuleModeActive; unreviewed drafts in RuleModeShadow.
type ResourceRuleRepository ¶
type ResourceRuleRepository interface {
ReadResourceRulesForDetector(context.Context) ([]ResourceRule, error)
}
ResourceRuleRepository supplies resource rules. Engine.Load and Engine.Reload read them when their Repository also implements this interface.
type Result ¶
type Result struct {
Signals []InvestigationSignal
RulesetID string
RulesetDigest string
ActivationRevision uint64
ResourceRulesDigest string
// Omitted counts what an evaluation left out to stay within its bounds:
// "events" beyond [MaxEvaluationEvents], "oversizedEvents" over 64 KiB, and
// rule "signals" beyond [MaxEvaluationSignals]. It is nil when nothing was left out.
Omitted map[string]int
}
Result is the signals from one detection, with the identity of the exact ruleset that produced them, recorded even when there are no signals.
type Risk ¶
type Risk string
Risk orders signal severity. Reasoning promotes only signals of RiskMedium or higher.
type Rule ¶
type Rule struct {
ID string `json:"id"`
Revision uint64 `json:"revision"`
InputVersion string `json:"inputVersion"`
PluginID string `json:"pluginId"`
ScopeResourceID string `json:"scopeResourceId,omitempty"`
Type string `json:"type"`
Kind string `json:"kind"`
Expression string `json:"expression"`
Risk Risk `json:"risk"`
Reasons []string `json:"reasons"`
WindowSeconds int64 `json:"windowSeconds"`
}
Rule matches its CEL Expression against inputs selected by PluginID ("*" for any), Type, Kind, and, when set, ScopeResourceID. (ID, Revision) is immutable once stored. WindowSeconds is the signal half-width; zero uses Config.Window.
type Ruleset ¶
Ruleset is a complete set of rules. Activating one replaces the entire active set; it does not merge with the previous one.
func DefaultRuleset ¶
func DefaultRuleset() Ruleset
DefaultRuleset is builtin/v1, the ruleset bootstrapped when none is active. It has no CEL rules; built-in novelty detection still runs.
type SensitiveResourcePolicy ¶
type Status ¶
type Status struct {
RulesetID string
RulesetDigest string
ActivationRevision uint64
ResourceRulesDigest string
ActiveResourceRules int
ShadowResourceRules int
// SkippedResourceRules counts invalid resource rules, and groups of rules
// over [MaxResourceRules], that the loaded overlay left out.
SkippedResourceRules int
LastReloadError string
}
Status reports the active ruleset and the error from the most recent reload attempt, empty if it succeeded.