evals

package
v0.0.1-rc.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 23 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.

README

Evaluation suite

These evals measure whether AgentShield catches lateral movement without alerting on benign changes. Six longitudinal campaigns pair attacks and controls for a compromised application reaching a secrets manager, a compromised hosted ML workspace build worker reading workspace secrets, and a compromised single sign-on server enumerating private source repositories.

Each campaign records baseline and observed traffic from the disposable cluster. Scoring starts only after the exact plugin-produced observation reaches the graph; synthetic telemetry is rejected. Expected outcomes stay in the scorer and never enter the model context.

The runner uses the production detection service and investigator with a compact initial packet and a pinned MCP graph view. It investigates each observed window inline, so production batching and sampling do not apply. Model-selected MCP calls are uncapped, but each result remains bounded. untruncated means every matching fact in that pinned view fit within the query bounds; it does not claim that provider observation is complete. Truncated context cannot support promotion.

Run

Create the disposable cluster, verify it, and run all campaigns with gpt-6-astra:

make eval-up
make eval-check
make eval-run

Run selected campaigns or the model matrix:

evals/scripts/eval-run.sh --campaigns identity-provider-to-source-control,governed-repository-inventory
make eval-matrix

eval-matrix.sh uses the Responses API with low reasoning effort. It compares model-selected and deterministic retrieval on gpt-5-mini, then tests deterministic retrieval on gpt-5.4-nano, gpt-6-luna, gpt-5.6-sol, and gpt-6-astra.

Delete the cluster with make eval-down. The script verifies local and in-cluster ownership first.

make eval-run makes real model calls through the in-cluster agentgateway, which is billed to OPENAI_API_KEY. External contributors are not expected to run it; maintainers run it for Kubernetes and Istio projector changes.

The in-cluster AgentShield also runs Resource rule authoring (--resource-rule-authoring) against OpenAI with the same key, which make eval-up stores in the agentshield-model Secret. Drafts start after a 10-minute stabilization window instead of the 6-hour default. --rule-review-api serves the unauthenticated rule review and regenerate routes on the cluster listener so the UI's Rules view works through kubectl port-forward. Detector-only runs leave both out.

make eval-up also installs Falco (chart 9.2.1, image 0.45.1, the oldest that works on recent host kernels, unless FALCO_IMAGE_TAG overrides it) with falco-values.yaml. It posts alerts to the collector's webhook_event receiver, which forwards them to AgentShield as process-exec telemetry; see the Falco plugin. To try it, open a shell in a Pod, for example kubectl exec -it deploy/<name> -- sh, and the Pod gains an executes edge to the shell process class. Tracing a shell alert shows where each step appears.

Detector-only runs

Detector-only mode measures deterministic detection without agentgateway, an API key, or model calls. It also lets make eval-up run without OPENAI_API_KEY; rerun make eval-up with the key before a model run.

AGENTSHIELD_EVAL_DETECTOR_ONLY=1 make eval-up
AGENTSHIELD_EVAL_DETECTOR_ONLY=1 make eval-run

Use it for built-in detector changes. A detector change should keep detection.securityPathRecall at 1 and should not add agent invocations to the setup or baseline phases, which contain only expected operational change. Then confirm with a model run.

Rule evals

The rule suite (make eval-rules, or evals/scripts/eval-run.sh --suite rules) scores the deterministic rules engine. It is separate from the mission campaigns above, which measure agentic investigation and predate detection rules. Its campaigns, in rule-campaigns.json, are built around the inputs rules evaluate. Each deploys a source workload whose name implies a narrow role, plus the services it calls, then runs baseline actions (the source's routine calls) and observed actions:

  • request: an HTTP request from the source to a target, checked against an expected status. Waypoint access logs record it as active-probe telemetry with operation METHOD path and outcome allowed or denied. A target's denyPaths become an Istio AuthorizationPolicy, so a denied request is a real 403 from the mesh.
  • restart: a routine rollout of the source, which creates new Pods and edges but no new behavior.

Before the first campaign, the runner deploys a background namespace in the mesh, aseval-<id> for the runtime ID of rule/background. In it, three clients call three services every few seconds. The runner waits until that namespace's telemetry is in the graph and deletes the namespace after the suite. This gives every baseline a cluster where telemetry is visibly collected, as in production. Rules are scoped to each campaign's source, so background traffic cannot produce rule findings.

The catalog covers four kinds of attack, each paired with benign controls:

  • a request outside the workload's API surface
  • a write by a read-only workload
  • a request the mesh denies
  • any outbound call from a workload that should make none

Two rule sources are scored per campaign:

  • policy: the campaign's policies, operator-written CEL rules for the source workload, run as the active ruleset. This checks that rule execution works end to end on live telemetry: selectors, the operation and outcome vocabulary, workload scoping, telemetry and edge novelty, and rule-finding construction. It runs in every mode, including detector-only.
  • authored: at the end of the baseline phase, the production Resource rule author drafts a rule from the context the authoring worker builds once the stabilization window has passed. That context is the queued identity plus the observed behavior read from the current graph through resourceauthoring.WithObservedBehavior. The draft runs as an approved Resource rule. This measures whether automated rule authoring catches the attack. It needs a model, so it is skipped in detector-only runs. The report records the observed behavior the author saw.

Rules run over the setup, baseline, and observed windows. A security campaign is a true positive when a rule finding in the observed window is anchored to the source and its last observed target. A benign campaign is a true negative when no rule fires in any window. A rule finding in the setup or baseline window is a false alarm on expected activity and fails the campaign's rule expectation even when the observed window is scored correctly. An authored rule that cannot fire in this environment, for example a network-flow rule where nothing produces flows, scores as a true negative on benign campaigns, so read benign authored results together with the security recall.

--author-selectors (or AGENTSHIELD_EVAL_AUTHOR_SELECTORS) restricts the selectors offered to the author, for example to the selectors this environment has producers for: every relationship:* selector and telemetry:active-probe. The summary records the list in authorSelectors.

TestRulePoliciesMatchTheirCampaignIntent replays every campaign's requests through the detector offline before a run: no policy may match baseline activity, and a policy must match observed activity exactly for security campaigns. When you add a campaign, give it a policy that passes that test.

Each rule run writes campaigns/<campaign-id>.json and summary.json to the artifact directory, like a mission run. A report has a rules array with one entry per rule source, listing the rules (and, for authored, the author's rationale, observed behavior, or error), the rule signals and findings per window, observedPathMatch, normalPhaseFindings, outcome, and matchesExpectation. The summary's rules section reports, per rule source, true and false positives and negatives, securityRecall, benignSpecificity, normalPhaseFindings, abstentions (the author returned no rule), and errors.

What a run produces

Each run writes to evals/output/<UTC timestamp>/ (override with EVAL_ARTIFACT_DIR):

  • campaigns/<campaign-id>.json: one report per campaign. It holds the campaign definition, each phase's observation evidence and graph checkpoint, the detector signals, the model's retrievals and assessment, the promotion decision, token usage, model latency, and matchesExpectation (whether the decision, and for security campaigns the finding category, matched the expected outcome). If the campaign failed, error says why.
  • Every report also has a detection array with one entry per phase: setup (deploying the campaign workloads until the graph is quiet, capped at one minute and marked unsettled if the graph kept changing), baseline (the source's first call), and observed (the scored window). Each entry lists the detector signals, how many are eligible for investigation, whether the window would invoke agentic investigation, and, for observed, whether an eligible signal is anchored to both observed endpoints (pathSignal).
  • summary.json: the aggregate, written only when every campaign completed. Its detection section reports per-phase windows with signals, agent invocations, and signal counts, and securityPathRecall: the share of security campaigns whose observed window has an eligible signal on the observed path. Promotion is impossible without one. The summary counts decisions only, not categories: a security campaign that produced a promoted finding counts as a true positive, otherwise a false negative; a benign campaign that produced a finding counts as a false positive, otherwise a true negative. From these it reports securityRecall (true positives over security campaigns) and benignSpecificity (true negatives over benign campaigns), plus total token usage and model latency.
  • postgres-port-forward.log: the port-forward the runner uses to reach the in-cluster database.

The run stops at the first campaign that fails. That campaign's report records the error and no summary.json is written, so an observation failure makes the run incomplete instead of counting as a model miss.

make eval-matrix writes one subdirectory per variant under evals/output/<UTC timestamp>-matrix/ (override with EVAL_MATRIX_DIR) and combines their summaries into a top-level summary.json.

To reproduce a result, run the same commit against a fresh make eval-up cluster with the same model and retrieval mode; both are recorded in every report and summary. Model output is not deterministic, so expect some run-to-run variation.

Documentation

Index

Constants

View Source
const (
	// RuleActionRequest sends one HTTP request from the source to a target.
	RuleActionRequest = "request"
	// RuleActionRestart restarts the source Deployment, a routine rollout.
	RuleActionRestart = "restart"
)

Rule action kinds.

View Source
const (
	SuiteMission = "mission"
	SuiteRules   = "rules"
)

Eval suites selected by RunConfig.Suite.

View Source
const (
	// RuleSourcePolicy is the campaign's operator-written policy, run as an active CEL ruleset.
	RuleSourcePolicy = "policy"
	// RuleSourceAuthored is the production resource rule author's draft for the
	// source workload, written from its observed behavior at the end of the
	// baseline phase and run as an approved (active) resource rule.
	RuleSourceAuthored = "authored"
)

Rule sources scored by the rule evals.

View Source
const (
	RuleTruePositive  = "true_positive"
	RuleFalseNegative = "false_negative"
	RuleTrueNegative  = "true_negative"
	RuleFalsePositive = "false_positive"
)

Rule eval outcomes.

View Source
const CatalogSchemaVersion = "agentshield.mission-evals/v1alpha1"
View Source
const RuleCatalogSchemaVersion = "agentshield.rule-evals/v1alpha1"

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, config RunConfig) error

Types

type Campaign

type Campaign struct {
	ID                   string   `json:"id"`
	Class                string   `json:"class"`
	ThreatModel          string   `json:"threatModel"`
	CompromiseAssumption string   `json:"compromiseAssumption"`
	SourceComponent      string   `json:"sourceComponent"`
	BaselineTarget       string   `json:"baselineTarget"`
	BaselineRequest      Request  `json:"baselineRequest"`
	ObservedTarget       string   `json:"observedTarget"`
	ObservedRequest      Request  `json:"observedRequest"`
	Governed             bool     `json:"governed"`
	Expected             Expected `json:"expected"`
}

type CampaignReport

type CampaignReport struct {
	SchemaVersion      string                         `json:"schemaVersion"`
	Campaign           Campaign                       `json:"campaign"`
	StartedAt          time.Time                      `json:"startedAt"`
	FinishedAt         time.Time                      `json:"finishedAt"`
	Phases             []PhaseReport                  `json:"phases"`
	Detection          []PhaseDetection               `json:"detection"`
	Signals            []detector.InvestigationSignal `json:"signals"`
	Retrievals         []reasoning.ContextResult      `json:"retrievals,omitempty"`
	Assessment         reasoning.Assessment           `json:"assessment"`
	Promotion          reasoning.Promotion            `json:"promotion"`
	Usage              reasoning.Usage                `json:"usage"`
	ModelLatencyMillis int64                          `json:"modelLatencyMillis"`
	Variant            string                         `json:"variant"`
	Model              string                         `json:"model,omitempty"`
	RetrievalMode      string                         `json:"retrievalMode,omitempty"`
	DetectorOnly       bool                           `json:"detectorOnly,omitempty"`
	MatchesExpectation bool                           `json:"matchesExpectation"`
	Error              string                         `json:"error,omitempty"`
}

type Catalog

type Catalog struct {
	SchemaVersion string     `json:"schemaVersion"`
	Mission       string     `json:"mission"`
	Campaigns     []Campaign `json:"campaigns"`
}

func LoadCatalog

func LoadCatalog(path string) (Catalog, error)

func (Catalog) Validate

func (catalog Catalog) Validate() error

type DetectionSummary

type DetectionSummary struct {
	// SecurityPathRecall is the share of security campaigns whose observed window has an
	// investigation-eligible signal anchored to the observed path; promotion is impossible without one.
	SecurityPathRecall float64                       `json:"securityPathRecall"`
	Phases             map[string]PhaseDetectionStat `json:"phases"`
}

DetectionSummary aggregates deterministic detection across campaign phases.

type Expected

type Expected struct {
	Decision            string   `json:"decision"`
	Categories          []string `json:"categories"`
	EarliestPhase       string   `json:"earliestPhase"`
	RequiredObservation bool     `json:"requiredObservation"`
}

type ObservationAdapter

type ObservationAdapter interface {
	ID() string
	Manifest(Campaign, WorkloadContract) string
	WaitReady(context.Context, string, WorkloadContract) error
}

type ObservationEvidence

type ObservationEvidence struct {
	PluginID    string   `json:"pluginId"`
	SourceID    string   `json:"sourceId"`
	Kind        string   `json:"kind"`
	SubjectID   string   `json:"subjectId"`
	ObjectID    string   `json:"objectId"`
	EvidenceIDs []string `json:"evidenceIds"`
}

type PhaseDetection

type PhaseDetection struct {
	Phase           string                         `json:"phase"`
	Signals         []detector.InvestigationSignal `json:"signals"`
	SignalCount     int                            `json:"signalCount"`
	EligibleSignals int                            `json:"eligibleSignals"`
	// InvokesAgent reports whether agentic investigation would run for this window.
	InvokesAgent bool `json:"invokesAgent"`
	// PathSignal reports an investigation-eligible signal anchored to both observed endpoints.
	PathSignal bool `json:"pathSignal,omitempty"`
	// Unsettled reports a setup window measured before the graph stopped changing.
	Unsettled bool `json:"unsettled,omitempty"`
}

PhaseDetection records deterministic detection for one graph change window without model calls.

type PhaseDetectionStat

type PhaseDetectionStat struct {
	Windows             int `json:"windows"`
	WindowsWithSignals  int `json:"windowsWithSignals"`
	AgentInvocations    int `json:"agentInvocations"`
	Signals             int `json:"signals"`
	EligibleSignals     int `json:"eligibleSignals"`
	SecurityPathSignals int `json:"securityPathSignals,omitempty"`
}

type PhaseReport

type PhaseReport struct {
	Name                string                    `json:"name"`
	StartedAt           time.Time                 `json:"startedAt"`
	CheckpointSequence  uint64                    `json:"checkpointSequence"`
	ObservationContract string                    `json:"observationContract"`
	Observation         ObservationEvidence       `json:"observation"`
	Incident            reasoning.IncidentContext `json:"incident,omitempty"`
}

type Request

type Request struct {
	Method string `json:"method"`
	Path   string `json:"path"`
}

type RuleAction

type RuleAction struct {
	Kind   string `json:"kind"`
	Target string `json:"target,omitempty"`
	Method string `json:"method,omitempty"`
	Path   string `json:"path,omitempty"`
	// ExpectStatus is the HTTP status the request must receive; zero means 200.
	ExpectStatus int `json:"expectStatus,omitempty"`
}

RuleAction is one step of a campaign phase.

func (RuleAction) Status

func (action RuleAction) Status() int

Status returns the expected HTTP status of a request action.

type RuleCampaign

type RuleCampaign struct {
	ID          string       `json:"id"`
	Class       string       `json:"class"`
	Description string       `json:"description"`
	Source      string       `json:"source"`
	Targets     []RuleTarget `json:"targets"`
	Baseline    []RuleAction `json:"baseline"`
	Observed    []RuleAction `json:"observed"`
	Policies    []RulePolicy `json:"policies"`
}

RuleCampaign deploys one source workload and its targets, runs baseline actions, then observed actions. A security campaign expects a rule finding in the observed window anchored to the source and its last observed target; a benign campaign expects no rule to fire. No rule may fire during setup or the baseline.

type RuleCampaignReport

type RuleCampaignReport struct {
	SchemaVersion string           `json:"schemaVersion"`
	Campaign      RuleCampaign     `json:"campaign"`
	StartedAt     time.Time        `json:"startedAt"`
	FinishedAt    time.Time        `json:"finishedAt"`
	Phases        []PhaseReport    `json:"phases"`
	Rules         []RuleEvaluation `json:"rules"`
	Model         string           `json:"model,omitempty"`
	DetectorOnly  bool             `json:"detectorOnly,omitempty"`
	Error         string           `json:"error,omitempty"`
}

RuleCampaignReport is the result of one rule campaign.

type RuleCatalog

type RuleCatalog struct {
	SchemaVersion string         `json:"schemaVersion"`
	Purpose       string         `json:"purpose"`
	Campaigns     []RuleCampaign `json:"campaigns"`
}

RuleCatalog is the rule-engine eval suite. Unlike the mission campaigns, each campaign is built around inputs detection rules evaluate.

func LoadRuleCatalog

func LoadRuleCatalog(path string) (RuleCatalog, error)

func (RuleCatalog) Validate

func (catalog RuleCatalog) Validate() error

type RuleEvaluation

type RuleEvaluation struct {
	Source    string          `json:"source"`
	Rules     []detector.Rule `json:"rules"`
	Rationale string          `json:"rationale,omitempty"`
	// ObservedBehavior is the baseline profile the author was given, if any.
	ObservedBehavior *state.WorkloadBehavior `json:"observedBehavior,omitempty"`
	// Error records a rule that could not be produced, such as a failed authoring call.
	Error  string      `json:"error,omitempty"`
	Phases []RulePhase `json:"phases"`
	// ObservedPathMatch reports a rule finding in the observed window whose signals
	// anchor both observed endpoints.
	ObservedPathMatch bool `json:"observedPathMatch"`
	// NormalPhaseFindings counts rule findings in the setup and stabilization windows,
	// which contain only expected activity.
	NormalPhaseFindings int    `json:"normalPhaseFindings"`
	Outcome             string `json:"outcome"`
	MatchesExpectation  bool   `json:"matchesExpectation"`
}

RuleEvaluation scores one rule source for one campaign across its windows.

type RulePhase

type RulePhase struct {
	Phase    string                         `json:"phase"`
	Signals  []detector.InvestigationSignal `json:"signals"`
	Findings []state.Finding                `json:"findings"`
}

RulePhase is the rule output for one window.

type RulePolicy

type RulePolicy struct {
	ID         string `json:"id"`
	Selector   string `json:"selector"`
	Expression string `json:"expression"`
	Rationale  string `json:"rationale"`
}

RulePolicy is an operator-written CEL detection rule, scoped to the campaign's source workload when the campaign runs.

func (RulePolicy) Rule

func (policy RulePolicy) Rule(workloadResourceID string) (detector.Rule, error)

Rule returns the policy as an active detector rule scoped to workloadResourceID.

type RuleSuiteSummary

type RuleSuiteSummary struct {
	SchemaVersion string                  `json:"schemaVersion"`
	CompletedAt   time.Time               `json:"completedAt"`
	Campaigns     int                     `json:"campaigns"`
	Rules         map[string]*RuleSummary `json:"rules"`
	Model         string                  `json:"model,omitempty"`
	DetectorOnly  bool                    `json:"detectorOnly,omitempty"`
	Variant       string                  `json:"variant"`
	// AuthorSelectors are explicit selectors offered to the author; empty uses resource-kind defaults.
	AuthorSelectors []string `json:"authorSelectors,omitempty"`
}

RuleSuiteSummary aggregates the rule suite by rule source.

type RuleSummary

type RuleSummary struct {
	Campaigns           int     `json:"campaigns"`
	TruePositive        int     `json:"truePositive"`
	FalseNegative       int     `json:"falseNegative"`
	TrueNegative        int     `json:"trueNegative"`
	FalsePositive       int     `json:"falsePositive"`
	SecurityRecall      float64 `json:"securityRecall"`
	BenignSpecificity   float64 `json:"benignSpecificity"`
	NormalPhaseFindings int     `json:"normalPhaseFindings"`
	// Abstentions counts campaigns where the source produced no rule.
	Abstentions int `json:"abstentions"`
	Errors      int `json:"errors"`
}

RuleSummary aggregates one rule source across campaigns.

type RuleTarget

type RuleTarget struct {
	Name string `json:"name"`
	// DenyPaths are Istio path patterns an AuthorizationPolicy denies at the waypoint with 403.
	DenyPaths []string `json:"denyPaths,omitempty"`
}

RuleTarget is an HTTP service the source can call.

type RunConfig

type RunConfig struct {
	// Suite is SuiteMission (the default) or SuiteRules.
	Suite              string
	CatalogPath        string
	DatabaseURL        string
	ModelEndpoint      string
	Model              string
	ReasoningEffort    string
	RetrievalMode      string
	Variant            string
	Kubeconfig         string
	OutputDir          string
	CampaignIDs        []string
	ObservationAdapter string
	ValidateOnly       bool
	DetectorOnly       bool
	// AuthorSelectors, when set, restricts the selectors the rule suite's
	// Resource rule author may use; empty uses resource-kind defaults.
	AuthorSelectors []string
	Timeout         time.Duration
}

type Summary

type Summary struct {
	SchemaVersion       string           `json:"schemaVersion"`
	CompletedAt         time.Time        `json:"completedAt"`
	Campaigns           int              `json:"campaigns"`
	DetectorOnly        bool             `json:"detectorOnly,omitempty"`
	Detection           DetectionSummary `json:"detection"`
	TruePositive        int              `json:"truePositive"`
	FalseNegative       int              `json:"falseNegative"`
	TrueNegative        int              `json:"trueNegative"`
	FalsePositive       int              `json:"falsePositive"`
	ObservationFailures int              `json:"observationFailures"`
	SecurityRecall      float64          `json:"securityRecall"`
	BenignSpecificity   float64          `json:"benignSpecificity"`
	Usage               reasoning.Usage  `json:"usage"`
	ModelLatencyMillis  int64            `json:"modelLatencyMillis"`
	Variant             string           `json:"variant"`
	Model               string           `json:"model"`
	RetrievalMode       string           `json:"retrievalMode"`
}

type WorkloadContract

type WorkloadContract struct {
	Namespace      string
	RuntimeID      string
	Manifest       string
	Source         string
	BaselineTarget string
	ObservedTarget string
}

func RenderCampaign

func RenderCampaign(campaign Campaign) WorkloadContract

func RenderRuleBackground

func RenderRuleBackground() WorkloadContract

RenderRuleBackground renders the namespace of steady background traffic that runs for the whole rule suite.

func RenderRuleCampaign

func RenderRuleCampaign(campaign RuleCampaign) WorkloadContract

RenderRuleCampaign renders the namespace, source client, and target services of a rule campaign. Targets with deny paths get an Istio AuthorizationPolicy that the namespace waypoint enforces with 403.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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