policy

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package policy parses, validates, and compiles policy into agentgateway configuration.

Index

Constants

View Source
const SecretPlaceholderPrefix = "__agentpaas_secret:"

SecretPlaceholderPrefix marks compiler-emitted apiKey keys that the daemon must rewrite with Keychain values before starting agentgateway. This form is intentionally not "$NAME" so the gateway will not expand it as an env var.

Variables

This section is empty.

Functions

func CompileCredentialRules

func CompileCredentialRules(p *Policy) ([]byte, error)

CompileCredentialRules returns credential injection rules by id only. Secret VALUES are NOT included — only the credential id and injection header name. The actual secret values are injected at runtime by the secrets broker.

func CompileDNSAllowList

func CompileDNSAllowList(p *Policy) ([]byte, error)

CompileDNSAllowList returns a sorted, unique list of allowed egress domains. Each line is one domain. Empty policy returns empty output.

func CompileGatewayConfig

func CompileGatewayConfig(p *Policy) ([]byte, error)

CompileGatewayConfig compiles a *Policy into an agentgateway YAML configuration.

func ContainsInjectionPattern

func ContainsInjectionPattern(s string) bool

ContainsInjectionPattern checks for common HTTP injection characters in a string. Exported for use by higher-level validation layers.

func Digest

func Digest(p *Policy) (string, error)

Digest computes the stable sha256 hex digest of a Policy. The digest is computed over the canonical JSON representation of the policy, which ensures that comments, key order, and white space do not affect the digest, while semantically meaningful changes do.

func GetErrorCount

func GetErrorCount(errs []ValidationError) int

GetErrorCount returns the number of error-severity findings.

func HasErrors

func HasErrors(errs []ValidationError) bool

HasErrors returns true if any validation errors exist (excluding warnings).

func IsLoopbackAddress

func IsLoopbackAddress(host string) bool

IsLoopbackAddress checks if a hostname is a loopback address.

func MustDigest

func MustDigest(p *Policy) string

MustDigest computes the digest or panics. Useful for test helpers.

func SecretPlaceholder added in v0.2.0

func SecretPlaceholder(credentialID string) string

SecretPlaceholder returns the compiler placeholder for a Keychain credential id.

Types

type APIKeyAuth added in v0.2.0

type APIKeyAuth struct {
	Header     string `yaml:"header"`     // HTTP header name (e.g. X-API-Key)
	Credential string `yaml:"credential"` // Keychain secret name
}

APIKeyAuth defines API key validation parameters.

type AgentConfig

type AgentConfig struct {
	Name        string `yaml:"name"`
	Description string `yaml:"description"`
}

AgentConfig describes the agent identity.

type CanonicalAgentConfig

type CanonicalAgentConfig struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

CanonicalAgentConfig is the canonical form of AgentConfig.

type CanonicalCredential

type CanonicalCredential struct {
	ID      string `json:"id"`
	Type    string `json:"type,omitempty"`
	Header  string `json:"header,omitempty"`
	Service string `json:"service,omitempty"`
	Path    string `json:"path,omitempty"`
}

CanonicalCredential is the canonical form of Credential. Secret values (Value) are redacted — only the ID and non-secret metadata remain.

type CanonicalEgressRule

type CanonicalEgressRule struct {
	Domain        string `json:"domain,omitempty"`
	CIDR          string `json:"cidr,omitempty"`
	Ports         []int  `json:"ports"`
	AllowWildcard *bool  `json:"allow_wildcard,omitempty"`
	AllowPrivate  *bool  `json:"allow_private,omitempty"`
}

CanonicalEgressRule is the canonical form of EgressRule.

type CanonicalHook

type CanonicalHook struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

CanonicalHook is the canonical form of Hook. Secret values (Secret) are redacted.

type CanonicalIngressRule

type CanonicalIngressRule struct {
	Path string `json:"path"`
	Port int    `json:"port"`
}

CanonicalIngressRule is the canonical form of IngressRule.

type CanonicalMCPServer

type CanonicalMCPServer struct {
	Name         string            `json:"name"`
	URL          string            `json:"url,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	Transport    string            `json:"transport,omitempty"`
	AllowedTools []string          `json:"allowed_tools,omitempty"`
	AuthMode     string            `json:"auth_mode,omitempty"`
}

CanonicalMCPServer is the canonical form of MCPServer.

type CanonicalPolicy

type CanonicalPolicy struct {
	Version     string                 `json:"version"`
	Agent       CanonicalAgentConfig   `json:"agent"`
	Egress      []CanonicalEgressRule  `json:"egress,omitempty"`
	Credentials []CanonicalCredential  `json:"credentials,omitempty"`
	MCPServers  []CanonicalMCPServer   `json:"mcp_servers,omitempty"`
	Hooks       []CanonicalHook        `json:"hooks,omitempty"`
	Ingress     []CanonicalIngressRule `json:"ingress,omitempty"`
}

CanonicalPolicy is the deterministic, canonical form of Policy used for digest computation. All slices are sorted by their natural key, maps are sorted by key (guaranteed by JSON encoding), secret values are redacted, domains are lowercased and punycode-normalized, and duplicate entries are removed with warnings.

func Canonicalize

func Canonicalize(p *Policy) (*CanonicalPolicy, []string)

Canonicalize converts a parsed Policy to its canonical form. It returns the canonical policy and any deduplication warnings. The canonical form:

  • Sorts all slices by their natural key
  • Lowercases and punycode-normalizes domains
  • Redacts secret values (credential.value, hook.secret)
  • Deduplicates equivalent entries with warnings
  • Removes comments (comments are already absent from the parsed struct)
  • Expands defaults (inferred transport, etc.)

type Credential

type Credential struct {
	ID      string `yaml:"id"`
	Type    string `yaml:"type"`
	Header  string `yaml:"header"`
	Value   string `yaml:"value"`
	Service string `yaml:"service"`
	Path    string `yaml:"path"`
	// Mode is required for direct-lease credentials: "file" or "env".
	Mode string `yaml:"mode"`
	// Reason is required for direct-lease credentials.
	Reason string `yaml:"reason"`
	// OAuth fields (type: oauth).
	TokenEndpoint          string `yaml:"token_endpoint,omitempty"`
	ClientID               string `yaml:"client_id,omitempty"`
	RefreshTokenCredential string `yaml:"refresh_token_credential,omitempty"`
}

Credential defines a credential source for the agent. Type may be "header", "brokered", "oauth", or "direct_lease".

type CredentialRule

type CredentialRule struct {
	ID     string               `yaml:"id"`
	Header string               `yaml:"header,omitempty"`
	Value  string               `yaml:"value,omitempty"`
	OAuth  *OAuthCredentialRule `yaml:"oauth,omitempty"`
}

----- credential injection rules ----- CredentialRule represents a credential injection rule by id only. The actual secret values are injected at runtime by the secrets broker.

type EgressRule

type EgressRule struct {
	Domain        string       `yaml:"domain"`
	CIDR          string       `yaml:"cidr"`
	Ports         []int        `yaml:"ports"`
	Methods       []string     `yaml:"methods"`
	AllowWildcard *bool        `yaml:"allow_wildcard"`
	AllowPrivate  *bool        `yaml:"allow_private"`
	Credential    string       `yaml:"credential"`
	MCPServerID   string       `yaml:"mcp_server_id"` // if set, this rule applies to MCP server egress
	Timeout       string       `yaml:"timeout,omitempty"`
	Retry         *RetryConfig `yaml:"retry,omitempty"`
}

EgressRule defines an outbound network access rule.

type Guardrail added in v0.2.0

type Guardrail struct {
	Type       string `yaml:"type"`
	Pattern    string `yaml:"pattern,omitempty"`
	Action     string `yaml:"action,omitempty"`
	Provider   string `yaml:"provider,omitempty"`
	Credential string `yaml:"credential,omitempty"`
	URL        string `yaml:"url,omitempty"`
}

Guardrail defines a content filtering rule for LLM prompts and responses.

type Hook

type Hook struct {
	Name   string `yaml:"name"`
	URL    string `yaml:"url"`
	Secret string `yaml:"secret"`
}

Hook defines an outbound webhook destination.

type IngressAuth added in v0.2.0

type IngressAuth struct {
	Type   string      `yaml:"type"`              // "jwt" or "api_key"
	JWT    *JWTAuth    `yaml:"jwt,omitempty"`     // JWT auth config
	APIKey *APIKeyAuth `yaml:"api_key,omitempty"` // API key auth config
}

IngressAuth defines authentication for incoming trigger requests.

type IngressRule

type IngressRule struct {
	Path string `yaml:"path"`
	Port int    `yaml:"port"`
}

IngressRule defines an inbound webhook listener.

type JWTAuth added in v0.2.0

type JWTAuth struct {
	Issuer   string `yaml:"issuer"`
	Audience string `yaml:"audience"`
	JWKSURL  string `yaml:"jwks_url"`
}

JWTAuth defines JWT validation parameters.

type LLMBudget added in v0.2.0

type LLMBudget struct {
	MaxTokens           int `yaml:"max_tokens"`             // total tokens per invoke
	MaxTokensPerRequest int `yaml:"max_tokens_per_request"` // per-LLM-call limit
}

LLMBudget defines per-invoke and per-request token budget limits. The gateway enforces these via budget limit policies on the LLM route.

type LLMProviderLock added in v0.2.0

type LLMProviderLock struct {
	AllowedEndpoints []string `yaml:"allowed_endpoints"`
}

LLMProviderLock restricts LLM egress to specific provider endpoint URLs. When set, the compiler adds path-based route matches to LLM provider domain routes, ensuring calls are restricted to the exact API endpoints listed. This is defense-in-depth beyond hostname-based egress rules.

type LLMRateLimit added in v0.2.0

type LLMRateLimit struct {
	RequestsPerMinute int `yaml:"requests_per_minute"`
	TokensPerMinute   int `yaml:"tokens_per_minute"`
}

LLMRateLimit defines rate limiting for LLM calls. The gateway enforces these via localRateLimit policies on the LLM route.

type MCPServer

type MCPServer struct {
	Name          string            `yaml:"name"`
	URL           string            `yaml:"url"`
	Headers       map[string]string `yaml:"headers"`
	Transport     string            `yaml:"transport"`
	Command       string            `yaml:"command"`
	Args          []string          `yaml:"args"`
	Endpoint      string            `yaml:"endpoint"`
	AllowedTools  []string          `yaml:"allowed_tools"`
	DeniedTools   []string          `yaml:"denied_tools,omitempty"`
	Env           map[string]string `yaml:"env"`
	AuthMode      string            `yaml:"auth_mode"`
	EgressBinding string            `yaml:"egress_binding"`
}

MCPServer defines an MCP (Model Context Protocol) server endpoint.

type OAuthCredentialRule added in v0.2.0

type OAuthCredentialRule struct {
	TokenEndpoint          string `yaml:"tokenEndpoint"`
	ClientID               string `yaml:"clientId"`
	RefreshTokenCredential string `yaml:"refreshTokenCredential"`
}

OAuthCredentialRule carries the OAuth metadata needed by the gateway to obtain and refresh OAuth tokens at runtime.

type Observability added in v0.2.0

type Observability struct {
	CostTracking bool   `yaml:"cost_tracking"`
	OTelEndpoint string `yaml:"otel_endpoint,omitempty"`
}

Observability defines cost tracking and OTel tracing configuration for the gateway. When set, the compiler emits tracing config in the gateway YAML so the gateway sends OTel data to the specified endpoint.

type Policy

type Policy struct {
	Version         string           `yaml:"version"`
	Agent           AgentConfig      `yaml:"agent"`
	Egress          []EgressRule     `yaml:"egress"`
	Credentials     []Credential     `yaml:"credentials"`
	MCPServers      []MCPServer      `yaml:"mcp_servers"`
	Hooks           []Hook           `yaml:"hooks"`
	Ingress         []IngressRule    `yaml:"ingress"`
	LLMBudget       *LLMBudget       `yaml:"llm_budget,omitempty"`
	LLMRateLimit    *LLMRateLimit    `yaml:"llm_rate_limit,omitempty"`
	LLMProviderLock *LLMProviderLock `yaml:"llm_provider_lock,omitempty"`
	IngressAuth     *IngressAuth     `yaml:"ingress_auth,omitempty"`
	Guardrails      []Guardrail      `yaml:"guardrails,omitempty"`
	Transformations *Transformation  `yaml:"transformations,omitempty"`
	Observability   *Observability   `yaml:"observability,omitempty"`
}

Policy represents the canonical agent policy configuration. Unknown fields in the YAML are rejected via strict decoding.

func MustParse

func MustParse(r io.Reader) *Policy

MustParse parses the policy or panics. Useful for test helpers.

func ParsePolicy

func ParsePolicy(r io.Reader) (*Policy, error)

ParsePolicy reads a policy.yaml from r and returns the parsed Policy struct. It rejects unknown fields at every nesting level via strict YAML decoding, and validates credential type fields against the enum set at parse time (rejecting non-string scalars and invalid values).

type PolicyDelta added in v0.2.0

type PolicyDelta struct {
	EgressAdded        []string `json:"egress_added,omitempty"`
	EgressRemoved      []string `json:"egress_removed,omitempty"`
	CredentialsAdded   []string `json:"credentials_added,omitempty"`
	CredentialsRemoved []string `json:"credentials_removed,omitempty"`
	MCPToolsAdded      []string `json:"mcp_tools_added,omitempty"`
	MCPToolsRemoved    []string `json:"mcp_tools_removed,omitempty"`
	IngressAdded       []string `json:"ingress_added,omitempty"`
	IngressRemoved     []string `json:"ingress_removed,omitempty"`
	HooksAdded         []string `json:"hooks_added,omitempty"`
	HooksRemoved       []string `json:"hooks_removed,omitempty"`
}

PolicyDelta records additions and removals between parent and child canonical policies. Field names and JSON tags match pack.PolicyDelta for trivial conversion.

func ComputeDelta added in v0.2.0

func ComputeDelta(parentYAML, childYAML []byte) (*PolicyDelta, error)

ComputeDelta compares canonical forms of parent and child policy YAML. It returns nil (JSON null) when there is no difference.

type RequestTransform added in v0.2.0

type RequestTransform struct {
	InjectHeaders      map[string]string `yaml:"inject_headers,omitempty"`
	InjectSystemPrompt string            `yaml:"inject_system_prompt,omitempty"`
}

RequestTransform defines request-level transformations.

type ResponseTransform added in v0.2.0

type ResponseTransform struct {
	RemoveHeaders []string `yaml:"remove_headers,omitempty"`
}

ResponseTransform defines response-level transformations.

type RetryConfig added in v0.2.0

type RetryConfig struct {
	MaxAttempts int    `yaml:"max_attempts"`
	Backoff     string `yaml:"backoff"`     // "exponential", "linear", or "fixed"
	MaxBackoff  string `yaml:"max_backoff"` // max backoff duration
}

RetryConfig defines retry behavior for failed upstream requests.

type Transformation added in v0.2.0

type Transformation struct {
	Request  *RequestTransform  `yaml:"request,omitempty"`
	Response *ResponseTransform `yaml:"response,omitempty"`
}

Transformation defines request/response transformations applied by the gateway. Request transforms inject headers or system prompts before the LLM sees the request. Response transforms strip headers from LLM responses before they reach the agent.

type ValidationError

type ValidationError struct {
	Field    string `json:"field"`
	Message  string `json:"message"`
	Severity string `json:"severity"` // "error" or "warning"
}

ValidationError represents a policy semantic validation finding.

func ValidatePolicy

func ValidatePolicy(p *Policy) []ValidationError

ValidatePolicy checks semantic validation rules on a parsed Policy and returns all errors and warnings found. Validation is idempotent and does not mutate the Policy.

func (ValidationError) Error

func (ve ValidationError) Error() string

Jump to

Keyboard shortcuts

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