policy

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: GPL-3.0 Imports: 11 Imported by: 0 modules, 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 policy contains the agentgate rule model and its evaluator.

Evaluation is deliberately pure: Evaluate takes a Policy and a Call and returns a Decision. It performs no I/O, reads no clock and touches no global state, so a decision can be reproduced from a recorded call at any later time (see the replay package). Everything a decision depends on — the time of the call, the session's counters, whether the gateway is frozen — is carried on the Call, put there by whoever asks.

Index

Constants

View Source
const (
	// LabelCanaryRead marks a session that got a canary token back from a
	// tool.
	LabelCanaryRead = "canary-read"
	// LabelInjectionSuspected marks a session that got a tool result with
	// hidden text or instructions addressed to the model.
	LabelInjectionSuspected = "injection-suspected"
)

Labels agentgate itself attaches to a session, next to the ones label rules attach.

View Source
const (
	RuleFrozen    = "frozen"
	RuleLoopGuard = "loop-guard"
	RuleBudget    = "budget"
	RuleHoneypot  = "honeypot"
	// RuleQuarantine denies calls to a tool whose definition changed since
	// it was pinned, or that the definition scan flagged.
	RuleQuarantine = "quarantine"
	// RuleCanary denies a call that carries a canary token out.
	RuleCanary = "canary"
)

Ids used for decisions that do not come from a rule in the rules list.

Variables

This section is empty.

Functions

func CompileGlob added in v0.4.0

func CompileGlob(glob string) (*regexp.Regexp, error)

CompileGlob compiles a glob in the syntax tool patterns use — * and ? are wildcards, every other character is literal — into an expression that matches whole names only.

func LabelsFor added in v0.4.0

func LabelsFor(p *Policy, call *Call) []string

LabelsFor returns the labels a call earns for its session: those of every label rule it matches, in the order the rules are written, without duplicates. It is pure, like Evaluate, and meant to be applied once the call has actually been forwarded, with call.Result set when there is one.

func ValidLabel added in v0.4.0

func ValidLabel(s string) bool

ValidLabel reports whether s may be used as a label name: lower-case letters, digits, dashes and underscores, starting with a letter or digit.

Types

type Action

type Action string

Action is the verdict a rule can hand down.

const (
	// ActionAllow forwards the call to the upstream server.
	ActionAllow Action = "allow"
	// ActionDeny answers the call with an MCP error result.
	ActionDeny Action = "deny"
	// ActionAsk suspends the call until a human approves or rejects it.
	ActionAsk Action = "ask"
)

func (Action) Valid

func (a Action) Valid() bool

Valid reports whether a is one of the three known actions.

type Annotations

type Annotations struct {
	Title       string `json:"title,omitempty"`
	ReadOnly    *bool  `json:"read_only,omitempty"`
	Destructive *bool  `json:"destructive,omitempty"`
	Idempotent  *bool  `json:"idempotent,omitempty"`
	OpenWorld   *bool  `json:"open_world,omitempty"`
}

Annotations mirror the MCP tool annotations. A nil field means the server said nothing, which is different from saying false.

type Budget

type Budget struct {
	// CallsPerSession caps calls across every tool. Zero means unlimited.
	CallsPerSession int `yaml:"calls_per_session" json:"calls_per_session,omitempty"`
	// CallsPerTool caps calls per exposed tool name. A missing entry means
	// unlimited. Keys are matched with the same separator tolerance as rule
	// patterns, so "fs.write_file" also caps "fs__write_file".
	CallsPerTool map[string]int `yaml:"calls_per_tool" json:"calls_per_tool,omitempty"`
	// CallsPerMinute caps the rate: more than this many calls in any trailing
	// sixty seconds and the session is throttled. Zero means unlimited.
	CallsPerMinute int `yaml:"calls_per_minute" json:"calls_per_minute,omitempty"`
	// TokensPerSession caps the estimated tokens (arguments plus results)
	// a session may push through its tools. Zero means unlimited.
	TokensPerSession int `yaml:"tokens_per_session" json:"tokens_per_session,omitempty"`
}

Budget caps what a single session may do. Every cap is a hard stop checked before the rules, so no rule can lift one.

type Call

type Call struct {
	// Tool is the name as the downstream host sees it, including the upstream
	// prefix ("fs__write_file").
	Tool string `json:"tool"`
	// Upstream is the name of the upstream server that owns the tool.
	Upstream string `json:"upstream"`
	// ToolName is the name the upstream server itself uses ("write_file").
	ToolName string `json:"tool_name"`
	// Args is the decoded arguments object, or nil when the host sent none.
	Args map[string]any `json:"args,omitempty"`
	// Counts carries the session counters the budgets and the loop guard use.
	Counts Counts `json:"counts,omitzero"`
	// Annotations are the hints the upstream server attached to the tool.
	// They are the server's claims about itself, which is exactly as
	// trustworthy as the server.
	Annotations Annotations `json:"annotations,omitzero"`
	// At is when the call was made. The zero value means "unknown", and makes
	// every time.* condition false.
	At time.Time `json:"at,omitzero"`
	// Frozen is set when the gateway's kill switch is on.
	Frozen bool `json:"frozen,omitempty"`
	// Host is the MCP client that opened the session.
	Host Host `json:"host,omitzero"`
	// Session is what the session has done before this call.
	Session History `json:"session,omitzero"`
	// Result is what the upstream answered. It is only known once the call
	// has been forwarded, so only label rules get to look at it; Compile
	// rejects a result.* condition in a rule.
	Result *Result `json:"result,omitempty"`
}

Call is everything the evaluator knows about a pending tools/call request.

func (*Call) Names added in v0.4.0

func (c *Call) Names() []string

Names returns the spellings rule patterns are matched against: the exposed name and, when it differs, the canonical upstream.tool name. session.called holds both, so that either spelling works in a condition on it.

type Condition

type Condition struct {
	Path    string  `json:"path"`
	Matcher Matcher `json:"matcher"`
	// contains filtered or unexported fields
}

Condition pairs a selector with the matcher that must hold for it.

type Conditions

type Conditions []Condition

Conditions is the "when:" block of a rule. It keeps the order the conditions were written in so that validation errors and traces are stable.

func (*Conditions) UnmarshalYAML

func (c *Conditions) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML preserves the order of the conditions in the file. Two spellings are accepted: a mapping of path to matcher, and a list of such mappings. The list form exists for the one thing a mapping cannot say — two conditions on the same path:

when:
  - args.path: { prefix: "/" }
  - args.path: { not_prefix: "/home/me/repo/" }

type Counts

type Counts struct {
	// Session is the number of allowed calls so far.
	Session int `json:"session,omitempty"`
	// Tool is the number of allowed calls to this tool so far.
	Tool int `json:"tool,omitempty"`
	// LastMinute is the number of allowed calls in the trailing sixty seconds.
	LastMinute int `json:"last_minute,omitempty"`
	// Repeats is how many times in a row this identical call was just made.
	Repeats int `json:"repeats,omitempty"`
	// Tokens is the estimated number of tokens spent so far.
	Tokens int `json:"tokens,omitempty"`
}

Counts are the calls already recorded for this session, not counting the call being evaluated.

type Decision

type Decision struct {
	Action Action `json:"action"`
	Reason string `json:"reason"`
	// RuleID is the id of the rule that produced this decision. Hard stops
	// that are not rules — budgets, the loop guard, a freeze — use a fixed id
	// so that they can still be told apart in the audit log.
	RuleID string `json:"rule_id,omitempty"`
}

Decision is the typed outcome of evaluating a call. Every decision carries a human-readable reason; decisions produced by a rule also carry its id.

func Evaluate

func Evaluate(p *Policy, call *Call) Decision

Evaluate applies p to call and returns the decision. It is pure: the same policy and call always produce the same decision.

Order of operations:

  1. the kill switch, because a frozen gateway does nothing else;
  2. the loop guard;
  3. budgets, because a budget is a hard cap the rules must not be able to lift;
  4. rules, top to bottom, first match wins;
  5. the default action.

Mode is not applied here. A shadow-mode gateway still wants the real decision, so that it can record it; turning it into an allow is the caller's job.

func (Decision) Allowed

func (d Decision) Allowed() bool

Allowed reports whether the call may be forwarded without further ado.

func (Decision) String

func (d Decision) String() string

String renders the decision the way the CLI and the audit log show it.

type History added in v0.4.0

type History struct {
	// Labels are the labels the session has picked up, sorted.
	Labels []string `json:"labels,omitempty"`
	// Called lists the tools the session has already called, in both the
	// exposed and the canonical upstream.tool spelling.
	Called []string `json:"called,omitempty"`
}

History is the part of a session's past the evaluator may look at.

func (History) HasLabel added in v0.4.0

func (h History) HasLabel(label string) bool

HasLabel reports whether the history carries a label.

type Host added in v0.4.0

type Host struct {
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
}

Host identifies the MCP client on the other end of a session, as it introduced itself.

type LabelRule added in v0.4.0

type LabelRule struct {
	Label string     `yaml:"label" json:"label"`
	Tool  string     `yaml:"tool" json:"tool,omitempty"`
	When  Conditions `yaml:"when" json:"when,omitempty"`
	// Pack names the pack the label rule came from, if any.
	Pack string `yaml:"-" json:"pack,omitempty"`
	// contains filtered or unexported fields
}

LabelRule attaches a label to the session when a call it matches has been forwarded. It matches like a rule — tool pattern plus conditions — but has no action of its own.

type LintContext added in v0.4.0

type LintContext struct {
	// Tools are the exposed and upstream.tool names the servers offer, when
	// known; a rule whose pattern matches none of them is reported.
	Tools []string
	// ApprovalMode is approval.mode from the config.
	ApprovalMode string
}

LintContext is what lint knows beyond the policy itself.

type LintFinding added in v0.4.0

type LintFinding struct {
	Severity Severity `json:"severity"`
	// Rule is the id of the rule it is about; empty for the policy as a whole.
	Rule    string `json:"rule,omitempty"`
	Check   string `json:"check"`
	Message string `json:"message"`
}

LintFinding is one thing policy lint noticed.

func Lint added in v0.4.0

func Lint(p *Policy, ctx LintContext) []LintFinding

Lint looks for rules that cannot fire, rules that let more through than they seem to, and conditions that can never hold. The policy must be compiled.

type LoopGuard

type LoopGuard struct {
	// Repeats is how many times in a row the identical call — same tool, same
	// arguments — may be made before the next one is denied. Zero disables
	// the guard.
	Repeats int `yaml:"repeats" json:"repeats,omitempty"`
}

LoopGuard stops an agent that is stuck repeating itself.

type Matcher

type Matcher struct {
	Equals    *any     `yaml:"equals" json:"equals,omitempty"`
	NotEquals *any     `yaml:"not_equals" json:"not_equals,omitempty"`
	Regex     *string  `yaml:"regex" json:"regex,omitempty"`
	NotRegex  *string  `yaml:"not_regex" json:"not_regex,omitempty"`
	Prefix    *string  `yaml:"prefix" json:"prefix,omitempty"`
	NotPrefix *string  `yaml:"not_prefix" json:"not_prefix,omitempty"`
	In        []any    `yaml:"in" json:"in,omitempty"`
	Gt        *float64 `yaml:"gt" json:"gt,omitempty"`
	Lt        *float64 `yaml:"lt" json:"lt,omitempty"`
	Exists    *bool    `yaml:"exists" json:"exists,omitempty"`
	Includes  *any     `yaml:"includes" json:"includes,omitempty"`
	Excludes  *any     `yaml:"excludes" json:"excludes,omitempty"`
	// contains filtered or unexported fields
}

Matcher is the right hand side of a condition. Exactly one of its fields may be set; which one is checked by Compile.

A condition holds when *at least one* of the values its selector resolves to matches. For a plain path that is the obvious reading; for a wildcard path like args.items[*].sku it is also the safe one. Take

when: { "args.items[*].path": { not_prefix: "/srv/app/" } }
action: deny

which denies as soon as a single item points outside the directory. Requiring every item to match would let a batch through because one entry in it was fine, and a guardrail that under-blocks is worse than one that over-blocks.

includes and excludes are the exception: they look at all the values at once, with any list among them opened up, and ask whether one item is among them. That is the question to put to a list like session.called — "has the session run the tests?" — which not_equals cannot answer, because any other tool in the list is not equal to the tests.

func (*Matcher) UnmarshalYAML

func (m *Matcher) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML accepts the full mapping form as well as two shorthands:

args.dryRun: false          equals
args.env: [prod, staging]   in

type Mode

type Mode string

Mode is how a decision is applied.

const (
	// ModeEnforce applies decisions: a deny denies, an ask asks.
	ModeEnforce Mode = "enforce"
	// ModeShadow records what the policy would have done and forwards the call
	// anyway. It is how you test a policy against live traffic before you
	// trust it with live traffic.
	ModeShadow Mode = "shadow"
)

type PackFile added in v0.4.0

type PackFile struct {
	Name        string               `yaml:"name" json:"name"`
	Description string               `yaml:"description" json:"description"`
	Params      map[string]PackParam `yaml:"params" json:"params,omitempty"`
	Labels      []*LabelRule         `yaml:"labels" json:"labels,omitempty"`
	Rules       []*Rule              `yaml:"rules" json:"rules"`
}

PackFile is the format of a pack: a name, a description, the parameters it takes, and the label rules and rules it contributes.

func ExpandPack added in v0.4.0

func ExpandPack(src []byte, ref PackRef, cleanPath func(string) (string, error)) (*PackFile, error)

ExpandPack fills in a pack's parameters and returns its rules and label rules, ready to be appended to a policy. Rule ids are prefixed with the pack name ("baseline/no-rm-rf") so they stay unique and say where they came from; label names are left alone, because labels are a vocabulary shared between packs and your own rules.

cleanPath normalises the values of parameters marked as paths. The substitution happens on the parsed YAML, value by value, so a parameter value can never change the structure of the pack.

func ReadPackHeader added in v0.4.0

func ReadPackHeader(src []byte) (*PackFile, error)

ReadPackHeader parses a pack for listing: name, description, parameters. Placeholders are left as they are.

type PackParam added in v0.4.0

type PackParam struct {
	Description string `yaml:"description" json:"description"`
	Default     string `yaml:"default" json:"default,omitempty"`
	Required    bool   `yaml:"required" json:"required,omitempty"`
	// Path marks the value as a filesystem path: it is expanded (~, ${ENV})
	// and cleaned, so "/home/me/repo/" and "/home/me/repo" mean the same.
	Path bool `yaml:"path" json:"path,omitempty"`
}

PackParam describes one parameter of a pack.

type PackRef added in v0.4.0

type PackRef struct {
	Name string            `yaml:"name" json:"name"`
	With map[string]string `yaml:"with" json:"with,omitempty"`
}

PackRef is one entry of policy.packs: a pack name, or a path to a pack file, with the values for the pack's parameters.

packs:
  - baseline
  - name: filesystem
    with: { workspace: /home/me/repo }
  - ./packs/company.yaml

func (PackRef) IsFile added in v0.4.0

func (r PackRef) IsFile() bool

IsFile reports whether the reference points at a pack file rather than a pack that ships with agentgate.

func (*PackRef) UnmarshalYAML added in v0.4.0

func (r *PackRef) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML accepts the bare-name shorthand as well as the mapping.

type Policy

type Policy struct {
	// Default is applied when no rule matches. Only allow and deny are
	// meaningful here; ask is rejected by Compile.
	Default Action `yaml:"default" json:"default"`
	// Mode is enforce (the default) or shadow.
	Mode Mode `yaml:"mode" json:"mode,omitempty"`
	// RedactResults applies the audit redaction patterns to tool results
	// before they reach the agent, not only before they reach the audit log.
	// It is the one place agentgate deliberately changes a result, and it is
	// off unless you turn it on.
	RedactResults bool `yaml:"redact_results" json:"redact_results,omitempty"`
	// StripInvisible removes characters that render as nothing — Unicode tag
	// characters, zero-width and bidirectional controls — from tool results
	// before the agent reads them. They are how a web page or an issue
	// comment smuggles instructions past the person looking at it. Off
	// unless you turn it on; the audit log keeps the result as it came.
	StripInvisible bool      `yaml:"strip_invisible" json:"strip_invisible,omitempty"`
	Budget         Budget    `yaml:"budget" json:"budget"`
	LoopGuard      LoopGuard `yaml:"loop_guard" json:"loop_guard"`
	// Labels attach names to a session once a matching call has gone
	// through, so that later rules can ask what the session has done
	// ("session.label.untrusted-input"). See LabelsFor.
	Labels []*LabelRule `yaml:"labels" json:"labels,omitempty"`
	// Packs are named rule sets that ship with agentgate or live in a file
	// next to the config. Their rules are evaluated after the rules below, so
	// your own rules can always make an exception.
	Packs []PackRef `yaml:"packs" json:"packs,omitempty"`
	// Rules are evaluated top to bottom; the first match wins.
	Rules []*Rule `yaml:"rules" json:"rules"`
	// contains filtered or unexported fields
}

Policy is the "policy:" section of an agentgate config file.

func (*Policy) Compile

func (p *Policy) Compile() error

Compile validates the policy and precompiles every pattern and regex it contains, so that Evaluate can stay free of error paths. It must be called once after loading a policy; Evaluate on an uncompiled policy will not match any rule.

All problems are reported at once, so "agentgate policy validate" can show a complete list instead of one error per run.

func (*Policy) IsShadow

func (p *Policy) IsShadow() bool

IsShadow reports whether the policy only observes.

func (*Policy) LabelsReadResult added in v0.4.0

func (p *Policy) LabelsReadResult() bool

LabelsReadResult reports whether any label rule has a result.* condition.

func (*Policy) Summary

func (p *Policy) Summary() string

Summary is a short human-readable description of the policy, used by "agentgate policy validate" and the web UI.

type Result added in v0.4.0

type Result struct {
	// IsError is the result's isError flag: the tool ran and failed.
	IsError bool `json:"is_error,omitempty"`
	// Text is what the agent reads: the text content and embedded text
	// resources, one per line, or the structured content as JSON when there
	// is no text.
	Text string `json:"text,omitempty"`
}

Result is the part of a tool result a label rule can match on.

func ResultFromJSON added in v0.4.0

func ResultFromJSON(raw []byte) *Result

ResultFromJSON extracts a Result from a tools/call result as it travels on the wire, which is also how the audit log stores it. It returns nil for anything that does not parse, such as a result the audit log truncated.

type Rule

type Rule struct {
	ID     string     `yaml:"id" json:"id"`
	Tool   string     `yaml:"tool" json:"tool,omitempty"`
	When   Conditions `yaml:"when" json:"when,omitempty"`
	Action Action     `yaml:"action" json:"action"`
	Reason string     `yaml:"reason" json:"reason,omitempty"`
	// Pack names the pack the rule came from; empty for your own rules.
	Pack string `yaml:"-" json:"pack,omitempty"`
	// contains filtered or unexported fields
}

Rule is a single entry of the "rules:" list.

type Severity added in v0.4.0

type Severity string

Severity of a lint finding.

const (
	// SeverityWarn is something that is probably not what was meant.
	SeverityWarn Severity = "warn"
	// SeverityInfo is worth knowing, and may well be intended.
	SeverityInfo Severity = "info"
)

type Tracker added in v0.4.0

type Tracker struct {
	// contains filtered or unexported fields
}

Tracker keeps the part of a session the evaluator reads: the counters behind budgets and the loop guard, the labels the session has earned, and the tools it has called. The proxy keeps one per downstream session; replay keeps one while it walks a recorded session, which is how a replayed decision sees the same budgets, streaks and labels the live one did.

A Tracker is not safe for concurrent use; the proxy guards it with the session's lock. Like Evaluate it reads no clock: the time of each call is passed in.

func (*Tracker) Calls added in v0.4.0

func (t *Tracker) Calls() int

Calls is the number of calls forwarded so far.

func (*Tracker) Earn added in v0.4.0

func (t *Tracker) Earn(labels ...string) []string

Earn adds labels to the session and returns the ones it did not have yet.

func (*Tracker) Forwarded added in v0.4.0

func (t *Tracker) Forwarded(call *Call, tokens int, now time.Time)

Forwarded records that call reached its upstream: it counts towards the budgets and joins session.called under each of its names.

func (*Tracker) History added in v0.4.0

func (t *Tracker) History() History

History returns a copy of the session's labels and called tools, for a Call.

func (*Tracker) Observe added in v0.4.0

func (t *Tracker) Observe(tool, sig string, now time.Time) Counts

Observe notes that a call with the given signature (tool plus a hash of its arguments) is about to be evaluated, and returns the counters as they stood before it. Every evaluated call counts towards the loop guard, denied ones included: an agent retrying a denied call is exactly the loop to stop.

Jump to

Keyboard shortcuts

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