policy

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package policy provides helper functions for working with policy documents.

Package policy provides trust level utilities for policy enforcement.

Package policy provides shared gateway policy types used by both the operator and the MCP proxy. This ensures contract compatibility between the operator-rendered policy and the proxy-consumed policy.

Index

Constants

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 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 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.

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 FirstNonEmpty

func FirstNonEmpty(values ...string) string

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

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 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 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.

Types

type AgentID

type AgentID string

AgentID identifies an authenticated agent or OAuth client principal.

type Auth

type Auth struct {
	TokenHeader string `json:"token_header,omitempty"`
	IssuerURL   string `json:"issuer_url,omitempty"`
	Audience    string `json:"audience,omitempty"`
	TrustDomain string `json:"trust_domain,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"`
}

Config contains policy enforcement configuration.

type Decision

type Decision struct {
	Allowed            bool
	Status             int
	Reason             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
}

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 Document

type Document struct {
	// 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"`
}

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

type Grant

type Grant struct {
	Name               string       `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"`
	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"`
}

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 Request

type Request struct {
	Identity  Identity
	RPCMethod string
	ToolName  ToolName
}

Request describes the MCP RPC request being evaluated.

type Server

type Server struct {
	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