policy

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: GPL-3.0 Imports: 9 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 (
	RuleFrozen    = "frozen"
	RuleLoopGuard = "loop-guard"
	RuleBudget    = "budget"
	RuleHoneypot  = "honeypot"
)

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

Variables

This section is empty.

Functions

This section is empty.

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"`
}

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

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.

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 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"`
	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"`
	// 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.

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 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"`
	Budget        Budget    `yaml:"budget" json:"budget"`
	LoopGuard     LoopGuard `yaml:"loop_guard" json:"loop_guard"`
	// Rules are evaluated top to bottom; the first match wins.
	Rules []*Rule `yaml:"rules" json:"rules"`
}

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) 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 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"`
	// contains filtered or unexported fields
}

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

Jump to

Keyboard shortcuts

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