policy

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package policy is the gateway authorization model: policy documents, compilation and per-request decisions.

A rendered Document holds tools, grants and session bindings. Compile indexes it, and Authorize evaluates one MCP request into a Decision with a status, reason, required and effective trust, risk level, and the matched grant and session. It supports monitor mode (would-deny), delegated-header policies and a revision stamp. Schema versions v1 to v6 each gate one feature.

It is pure data and rules, shared by the operator that renders policy, the gateway that enforces it and the CLI that inspects it.

Index

Constants

View Source
const (
	ModeAllowList    = "allow-list"
	ModeObserve      = "observe"
	DecisionDeny     = "deny"
	DecisionAllow    = "allow"
	DefaultMode      = ModeAllowList
	DefaultDecision  = DecisionDeny
	DefaultEnforceOn = "call_tool"
	// DefaultVersion is a governance policy label, not an MCP protocol revision.
	DefaultVersion         = "v1"
	ObservabilityMode      = ModeObserve
	ObservabilityDecision  = DecisionAllow
	DefaultSessionStore    = "platform"
	DefaultSessionMaxLife  = "24h"
	DefaultSessionIdleTime = "1h"
	DefaultSessionUpstream = identity.AuthTokenHeader
)

Policy enum values are independent from the defaults below.

View Source
const (
	// MaxPublicPaths is the most public path prefixes one server may declare.
	MaxPublicPaths = 8
	// MaxPublicPathBodyBytes caps a request body on a public path (4 GiB).
	MaxPublicPathBodyBytes int64 = 4 << 30
	// MaxPublicPathDurationSeconds caps how long one public request may take.
	MaxPublicPathDurationSeconds = 3600
)

Limits for a server's public paths. They bound what an unauthenticated route can cost: a handful of prefixes, a body cap, and a time cap.

View Source
const (
	SideEffectRead        = "read"
	SideEffectWrite       = "write"
	SideEffectDestructive = "destructive"
)
View Source
const (
	TrustLevelLow    = "low"
	TrustLevelMedium = "medium"
	TrustLevelHigh   = "high"
)

Trust level constants matching the API definitions.

View Source
const (
	PrimitiveResource = "resource"
	PrimitivePrompt   = "prompt"
	PrimitiveSkill    = "skill"
	// PrimitiveTask is an internal kind for the tasks extension. Tasks have no
	// per-item rules; they need an active matching grant. It is not valid in a
	// PrimitiveRule.
	PrimitiveTask = "task"
	// PrimitiveEvent is the internal kind for the events extension. Like tasks it
	// has no per-item rules and is not valid in a PrimitiveRule.
	PrimitiveEvent = "event"
)

Primitive kinds a PrimitiveRule can scope.

View Source
const SchemaVersion = "v1"

SchemaVersion is the current gateway policy contract schema version. It is document-level metadata distinct from the authorization PolicyVersion: it identifies the compatibility of the rendered JSON contract itself, not the grant/session policy generation. Bump it only when the rendered JSON shape changes in a way the consumer must understand.

View Source
const SchemaVersionCredentialBroker = "v6"

SchemaVersionCredentialBroker requires authenticated per-call secret delivery. Older gateways must reject this policy rather than forward without resolving.

View Source
const SchemaVersionDelegatedHeaders = "v3"

SchemaVersionDelegatedHeaders is required when auth.mode is header. Older gateways reject the document instead of ignoring delegated header fields.

View Source
const SchemaVersionGrantExpiry = "v2"

SchemaVersionGrantExpiry is stamped on documents in which any grant sets expires_at. Grant expiry is a field the consumer must understand: a gateway that predates it would decode the document, drop the unknown field, and keep honoring expired grants. Under v2 such a gateway rejects the document and reports the reload failure instead. Documents without expiring grants stay at SchemaVersion so they remain readable by older gateways.

View Source
const SchemaVersionGrantMonitor = "v5"

SchemaVersionGrantMonitor requires consumers to honor per-grant monitor mode.

View Source
const SchemaVersionPrimitiveRules = "v8"

SchemaVersionPrimitiveRules is required when any grant sets primitive_rules. A gateway that predates it would ignore the rules and let those reads through unrestricted; under v8 it rejects the document and reports the reload failure.

View Source
const SchemaVersionPublicPaths = "v7"

SchemaVersionPublicPaths is required when auth.public_paths is set. A gateway that predates it would ignore the field and keep every path behind a bearer; under v7 it rejects the document and reports the reload failure instead.

View Source
const SchemaVersionSessionSync = "v4"

SchemaVersionSessionSync requires externally synchronized sessions. Older gateways reject it rather than activating a policy without session state.

Variables

This section is empty.

Functions

func ChoosePolicyVersion

func ChoosePolicyVersion(values ...string) string

ChoosePolicyVersion returns the first non-empty policy version from the provided values, or empty string if none found. Callers should pass their own default as the last value.

func ComputeRevision

func ComputeRevision(doc *Document) (string, error)

ComputeRevision returns a deterministic SHA-256 digest of the canonical rendered policy content. The Revision and GeneratedAt fields are excluded from the digest so that the revision depends only on policy content and neither the previously stamped revision nor the (informational) generation timestamp can change it. SchemaVersion is included: a schema bump is a meaningful contract change and must produce a new revision.

Determinism relies on encoding/json marshaling struct fields in declaration order and map keys in sorted order, which the standard library guarantees.

func ConfigMapName

func ConfigMapName(serverName string) string

ConfigMapName is the rendered policy ConfigMap for a managed server.

func DelegatedHeaderConfigured

func DelegatedHeaderConfigured(policy *Document, name string) bool

DelegatedHeaderConfigured reports whether name is an accepted credential header.

func ExtensionForMethod

func ExtensionForMethod(method string) string

ExtensionForMethod returns the identifier of the protocol extension that adds a gated method, or "" for core and unknown methods. The gateway's extension registry is checked against it so the two cannot drift.

func FirstNonEmpty

func FirstNonEmpty(values ...string) string

FirstNonEmpty returns the first non-empty string from the provided values.

func IsPrimitiveMethod

func IsPrimitiveMethod(method string) bool

IsPrimitiveMethod reports whether a method reads a resource, prompt or skill.

func IsToolCallMethod

func IsToolCallMethod(method string) bool

IsToolCallMethod returns true if the method is a tool invocation method.

func NormalizeRiskLevel

func NormalizeRiskLevel(risk, trust, sideEffect string) string

func NormalizeSideEffect

func NormalizeSideEffect(value string) string

NormalizeSideEffect normalizes known side-effect values and returns empty for unknown values.

func NormalizeTrust

func NormalizeTrust(value string) string

NormalizeTrust normalizes a trust level string to one of the standard values. Defaults to "low" if the value is unrecognized.

func PolicyServerCluster

func PolicyServerCluster(policy *Document) string

PolicyServerCluster returns the cluster name from a policy document.

func PolicyServerName

func PolicyServerName(policy *Document) string

PolicyServerName returns the server name from a policy document.

func PolicyServerNamespace

func PolicyServerNamespace(policy *Document) string

PolicyServerNamespace returns the server namespace from a policy document.

func PolicyServerTeamID

func PolicyServerTeamID(policy *Document) string

PolicyServerTeamID returns the owning team ID from a policy document.

func PolicyUsesOAuth

func PolicyUsesOAuth(policy *Document) bool

PolicyUsesOAuth returns true if the policy uses OAuth authentication.

func PolicyVersion

func PolicyVersion(policy *Document) string

PolicyVersion returns the policy version from a policy document.

func PrimitiveMethod

func PrimitiveMethod(method string) (kind string, targeted, ok bool)

PrimitiveMethod classifies the MCP methods that read resources, prompts and skills, and the methods that stream or poll their data. targeted is false for methods that name no single item.

func RankToTrust

func RankToTrust(value int) string

RankToTrust converts a numeric rank back to a trust level string.

func RequiredSchemaVersion

func RequiredSchemaVersion(doc *Document) string

RequiredSchemaVersion returns the lowest schema version that can carry doc.

func Stamp

func Stamp(doc *Document, generatedAt string) error

Stamp sets the document-level metadata on doc: the schema version it requires (see RequiredSchemaVersion), the supplied (informational) generatedAt timestamp, and a freshly computed deterministic Revision. generatedAt may be empty; it never affects Revision.

func ToolRiskLevel

func ToolRiskLevel(policy *Document, toolName string) string

func TrustRank

func TrustRank(value string) int

TrustRank returns a numeric rank for a trust level (1=low, 2=medium, 3=high). Higher ranks indicate higher trust.

func UsesDelegatedHeaders

func UsesDelegatedHeaders(policy *Document) bool

UsesDelegatedHeaders reports upstream-owned credential authentication.

func Validate

func Validate(doc *Document) error

Validate checks that a rendered gateway policy document is structurally sound and safe to activate. It is the shared contract used by both the producer (operator, before writing the policy ConfigMap) and the consumer (gateway, after decoding and before activating a snapshot).

Validation is strict and fails closed: unknown trust, side-effect, decision, auth or policy values are rejected rather than silently normalized, and incomplete combinations (such as OAuth without an issuer) are errors. A document that does not validate must never replace a known-good policy.

func ValidatePublicPaths

func ValidatePublicPaths(auth *Auth) error

ValidatePublicPaths checks the public paths on auth. The operator's admission validation and the rendered-policy validator share it.

Types

type AgentID

type AgentID string

AgentID identifies an authenticated agent or OAuth client principal.

type Auth

type Auth struct {
	// Mode is "header" for upstream-delegated credentials. Empty keeps OAuth
	// or adapter-certificate authentication.
	Mode               string   `json:"mode,omitempty"`
	Headers            []string `json:"headers,omitempty"`
	CredentialPresence string   `json:"credential_presence,omitempty"`
	TokenHeader        string   `json:"token_header,omitempty"`
	IssuerURL          string   `json:"issuer_url,omitempty"`
	Audience           string   `json:"audience,omitempty"`
	Scopes             []string `json:"scopes,omitempty"`
	TrustDomain        string   `json:"trust_domain,omitempty"`
	// PublicPaths are bearer-less POST routes for single-use signed URLs.
	PublicPaths []PublicPath `json:"public_paths,omitempty"`
}

Auth configures authentication settings for the gateway.

type Binding

type Binding struct {
	Name             SessionID `json:"name"`
	Namespace        Namespace `json:"namespace,omitempty"`
	HumanID          HumanID   `json:"human_id,omitempty"`
	AgentID          AgentID   `json:"agent_id,omitempty"`
	TeamID           TeamID    `json:"team_id,omitempty"`
	ConsentedTrust   string    `json:"consented_trust,omitempty"`
	Revoked          bool      `json:"revoked,omitempty"`
	ExpiresAt        string    `json:"expires_at,omitempty"`
	PolicyVersion    string    `json:"policy_version,omitempty"`
	UpstreamTokenRef string    `json:"upstream_token_ref,omitempty"`
}

Binding represents an agent session binding.

type Config

type Config struct {
	Mode               string              `json:"mode,omitempty"`
	DefaultDecision    string              `json:"default_decision,omitempty"`
	EnforceOn          string              `json:"enforce_on,omitempty"`
	PolicyVersion      string              `json:"policy_version,omitempty"`
	DelegatedToolRules []DelegatedToolRule `json:"delegated_tool_rules,omitempty"`
	MaxSideEffect      string              `json:"max_side_effect,omitempty"`
}

Config contains policy enforcement configuration.

type Decision

type Decision struct {
	Allowed bool
	Status  int
	Reason  string
	// WouldDeny is true when a matched monitor-mode grant would have denied this
	// request. The request is allowed only after the normal identity and session
	// checks have succeeded.
	WouldDeny          bool
	WouldDenyReason    string
	PolicyVersion      string
	RequiredTrust      string
	RequiredSideEffect string
	RiskLevel          string
	AdminTrust         string
	ConsentedTrust     string
	EffectiveTrust     string
	// MatchedGrant is the name of the grant that determined this decision,
	// empty when no grant applied (e.g. no_matching_grant, default decisions).
	// MatchedGrantNamespace qualifies it: cross-namespace grants targeting the
	// same server may share a name.
	MatchedGrant          string
	MatchedGrantNamespace string
	// MatchedSession is the name of the session binding the request resolved
	// to, empty when no live session applied to the decision.
	// MatchedSessionNamespace qualifies it for the same reason.
	MatchedSession          string
	MatchedSessionNamespace string
	// ConsideredGrantCount and ConsideredGrantNames are set only for a
	// no_matching_grant denial. They report how many grants targeted this
	// server and the first few names, so an operator can compare them with the
	// presented identity. They are for logs and audit only and are never
	// written to the client response.
	ConsideredGrantCount int
	ConsideredGrantNames string
}

Decision is the result of evaluating a rendered policy document.

func Allow

func Allow(reason, policyVersion string) Decision

Allow builds an allowed decision with an explicit reason. It is used for requests that are intentionally not subject to grant/session evaluation (non-tool-call passthrough, OAuth metadata) so that the gateway's default decision can be deny — making any path that reaches upstream without an explicit decision fail closed.

func Authorize

func Authorize(policy *Document, request Request, now time.Time) Decision

Authorize evaluates a rendered gateway policy document for a single MCP RPC request.

func Deny

func Deny(status int, reason, policyVersion string) Decision

Deny builds a denied authorization decision.

type DelegatedToolRule

type DelegatedToolRule struct {
	Name     ToolName `json:"name"`
	Decision string   `json:"decision"`
}

DelegatedToolRule is a server-scoped allow or deny used when auth.mode is header.

type Document

type Document struct {
	CredentialBindings []string `json:"credential_bindings,omitempty"`

	// SchemaVersion identifies the compatibility of the rendered JSON contract.
	SchemaVersion string `json:"schema_version"`
	// Revision is a deterministic SHA-256 digest of the canonical rendered
	// policy content. It is computed with SchemaVersion included and with
	// Revision and GeneratedAt excluded, so identical policy content always
	// produces the same revision regardless of when it was generated.
	Revision string `json:"revision"`
	// GeneratedAt is informational only and must not affect Revision.
	GeneratedAt string    `json:"generated_at,omitempty"`
	Server      Server    `json:"server"`
	Auth        *Auth     `json:"auth,omitempty"`
	Policy      *Config   `json:"policy,omitempty"`
	Session     *Session  `json:"session,omitempty"`
	Tools       []Tool    `json:"tools,omitempty"`
	Grants      []Grant   `json:"grants,omitempty"`
	Sessions    []Binding `json:"sessions,omitempty"`
	// contains filtered or unexported fields
}

Document is the root gateway policy document that contains all policy configuration.

func Compile

func Compile(doc *Document) (*Document, error)

Compile copies a policy into an immutable authorization snapshot. Callers validate file integrity before applying runtime defaults and compiling. Never mutate the returned document; publish a new snapshot when policy changes. The private indexes do not change JSON, revision digests or schema versions.

type Grant

type Grant struct {
	Name               string       `json:"name"`
	Mode               string       `json:"mode,omitempty"`
	Namespace          Namespace    `json:"namespace,omitempty"`
	HumanID            HumanID      `json:"human_id,omitempty"`
	AgentID            AgentID      `json:"agent_id,omitempty"`
	TeamID             TeamID       `json:"team_id,omitempty"`
	MaxTrust           string       `json:"max_trust,omitempty"`
	AllowedSideEffects []string     `json:"allowed_side_effects,omitempty"`
	PolicyVersion      string       `json:"policy_version,omitempty"`
	Disabled           bool         `json:"disabled,omitempty"`
	ExpiresAt          string       `json:"expires_at,omitempty"`
	ToolRules          []ToolAccess `json:"tool_rules,omitempty"`
	// PrimitiveRules scope resource, prompt and skill access. A grant with no
	// rule of a kind allows every item of that kind, like an empty ToolRules.
	PrimitiveRules []PrimitiveRule `json:"primitive_rules,omitempty"`
}

Grant defines access grants for subjects (humans/agents).

type HumanID

type HumanID string

HumanID identifies an authenticated human principal.

type Identity

type Identity struct {
	HumanID   HumanID
	AgentID   AgentID
	TeamID    TeamID
	SessionID SessionID
}

Identity is the subject context used to evaluate a rendered policy document.

type Namespace

type Namespace string

Namespace identifies the Kubernetes namespace that owns policy resources.

type PrimitiveRule

type PrimitiveRule struct {
	Kind     string `json:"kind"`
	Pattern  string `json:"pattern"`
	Decision string `json:"decision,omitempty"`
}

PrimitiveRule allows or denies one resource URI, prompt name or skill name. Pattern is exact, or a prefix when it ends in "*".

type PublicPath

type PublicPath struct {
	// PathPrefix is the path as the upstream server sees it (after the gateway
	// strips its public prefix). It must start and end with "/".
	PathPrefix string `json:"path_prefix"`
	// MaxBodyBytes is the largest request body accepted.
	MaxBodyBytes int64 `json:"max_body_bytes"`
	// MaxDurationSeconds bounds the whole request, from first byte to response.
	MaxDurationSeconds int `json:"max_duration_seconds"`
}

PublicPath opens one narrow, bearer-less route to the upstream MCP server.

It exists for single-use signed upload URLs: the server authenticates a request by the secret inside the path, so the gateway cannot demand an OAuth token. Only POST to a path under PathPrefix skips authentication and authorization; the gateway still bounds the body and the duration, strips credentials and identity headers, and audits the request. Every other path, including the MCP endpoint, stays on the full bearer and policy pipeline.

func MatchPublicPath

func MatchPublicPath(doc *Document, method, path string) (PublicPath, bool)

MatchPublicPath returns the public path rule that admits method and path, if any. path is the upstream-visible request path. It fails closed: a path that is not already in clean form, or that has nothing after the prefix, never matches, so "..", "//" and the bare prefix cannot widen a rule.

type Request

type Request struct {
	Identity  Identity
	RPCMethod string
	ToolName  ToolName
	// Target is the resource URI, prompt name or skill URI of a primitive request.
	Target string
	// Targets are the resource URIs a subscriptions/listen request opts into.
	Targets []string
	// Session is the binding resolved from the synchronized platform store.
	// It is request-scoped and never changes the immutable policy document.
	Session *Binding
}

Request describes the MCP RPC request being evaluated.

type Server

type Server struct {
	UID       string     `json:"uid,omitempty"`
	Name      ServerName `json:"name"`
	Namespace Namespace  `json:"namespace"`
	TeamID    TeamID     `json:"team_id,omitempty"`
	Cluster   string     `json:"cluster,omitempty"`
}

Server identifies the MCP server this policy applies to.

type ServerName

type ServerName string

ServerName identifies an MCP server in a rendered gateway policy.

type Session

type Session struct {
	Required            bool   `json:"required,omitempty"`
	Store               string `json:"store,omitempty"`
	MaxLifetime         string `json:"max_lifetime,omitempty"`
	IdleTimeout         string `json:"idle_timeout,omitempty"`
	UpstreamTokenHeader string `json:"upstream_token_header,omitempty"`
}

Session configures session management settings.

type SessionID

type SessionID string

SessionID identifies an MCP agent session binding.

type TeamID

type TeamID string

TeamID identifies a stable platform team principal.

type Tool

type Tool struct {
	Name          ToolName          `json:"name"`
	Description   string            `json:"description,omitempty"`
	RequiredTrust string            `json:"required_trust,omitempty"`
	SideEffect    string            `json:"side_effect,omitempty"`
	RiskLevel     string            `json:"risk_level,omitempty"`
	Labels        map[string]string `json:"labels,omitempty"`
}

Tool describes an MCP tool and its trust requirements.

type ToolAccess

type ToolAccess struct {
	Name          ToolName `json:"name"`
	Decision      string   `json:"decision,omitempty"`
	RequiredTrust string   `json:"required_trust,omitempty"`
}

ToolAccess defines access rules for a specific tool.

type ToolName

type ToolName string

ToolName identifies an MCP tool in a rendered gateway policy.

Jump to

Keyboard shortcuts

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