policy

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 24 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 is the control-plane PolicyProvider: static grants, optional argument predicates on MCP tools/call, and an optional sync webhook gate for connector session mint and MCP tools/call. Absent config preserves V1 open behavior; when any grant, predicate, or webhook is configured, unmatched requests default to deny.

Index

Constants

View Source
const (
	StageConnectorSession = "connector.session"
	StageToolCall         = "tool.call"
	StageRunCreate        = "run.create"
)

Stages evaluated by Decide. Connector stages use static grants; run.create skips connector matching (authz + kill switches run in the admission Gate; optional webhook still applies here).

View Source
const (
	EffectAllow   = "allow"
	EffectDeny    = "deny"
	EffectPending = "pending" // connector HITL: Admin approve → one-shot retry
)

Effects returned by Decide.

View Source
const (
	ReasonPolicyDeny           = "policy_deny"
	ReasonPolicyNoGrant        = "policy_no_grant"
	ReasonPolicyToolDenied     = "policy_tool_denied"
	ReasonPolicyWebhookDeny    = "policy_webhook_deny"
	ReasonPolicyWebhookFailed  = "policy_webhook_failed"
	ReasonPolicyDefaultDeny    = "policy_default_deny"
	ReasonPolicyMissingBinding = "policy_missing_binding"
	ReasonPolicyPending        = "policy_pending"
	ReasonPolicyAdmissionDeny  = "policy_admission_deny"
	ReasonPolicyAuditFailed    = "policy_audit_failed"
	ReasonBreakGlass           = "break_glass"
	ReasonKillActive           = "kill_active"
	ReasonKillActivate         = "kill_activate"
	ReasonKillClear            = "kill_clear"
	ReasonAuthzDeny            = "authz_deny"
	ReasonBudgetExceeded       = "budget_exceeded"
	ReasonBudgetSoft           = "budget_soft"
	ReasonBudgetAlert          = "budget_alert"    // soft_pct approach (under hard cap)
	ReasonBudgetKill           = "budget_kill"     // cancel_inflight on hard breach
	ReasonUsageUnpriced        = "usage_unpriced"  // tokens > 0, no cost_usd, non-empty pricebook missing this model
	ReasonUsageUnmetered       = "usage_unmetered" // runner saw an AI reply but extracted zero usage in any recognized shape
)

Stable reason codes for denials / failures.

View Source
const ReasonMandatoryHITL = "mandatory_hitl"

ReasonMandatoryHITL is returned when a config mandatory_hitl rule forces tool.call to pending despite an underlying allow.

View Source
const ReasonPolicyPredicate = "policy_predicate"

ReasonPolicyPredicate is the default reason_code when a predicate denies and the config row omitted reason_code. Pending with an empty code uses ReasonPolicyPending so Admin HITL stays on the existing path.

Variables

This section is empty.

Functions

func BindArgs

func BindArgs(raw json.RawMessage) (parsed any, digest string, meta map[string]any)

BindArgs turns MCP tools/call params.arguments into the three PolicyInput fields: full value for predicate eval, SHA-256 digest for the decision cache, and a size-capped redacted map for audit/webhook display.

Missing or empty arguments digest as the JSON object {}. The digest is a versioned sha256 of sorted-key JSON with exact normalized numbers. This is not RFC 8785. Secret-looking keys are stripped from the display map only; they still feed the digest.

func BindArgsStrict

func BindArgsStrict(raw json.RawMessage) (parsed any, digest string, meta map[string]any, err error)

BindArgsStrict rejects ambiguous arguments instead of authorizing a different interpretation from the downstream service. HTTP callers must handle its error.

Types

type ApprovalRequirements added in v0.7.0

type ApprovalRequirements struct {
	RequiredApprovals int  `json:"required_approvals"`
	ExcludeRequester  bool `json:"exclude_requester"`
}

ApprovalRequirements applies to held operations. It does not create an allow or require approval for a call that current policy already permits.

func (ApprovalRequirements) Valid added in v0.7.0

func (a ApprovalRequirements) Valid() bool

type AuditStore

type AuditStore interface {
	WriteAuditEvent(ctx context.Context, ev *models.AuditEvent) error
}

AuditStore is the narrow write path for policy decisions. Implemented by SQL state stores (Postgres/MySQL/SQLite); Mongo omits it.

type Auditor

type Auditor interface {
	WritePolicyDecision(ctx context.Context, in PolicyInput, dec PolicyDecision) error
}

Auditor persists a decision. Nil/no-op is fine (Compatible backends).

func NewStoreAuditor

func NewStoreAuditor(store AuditStore) Auditor

NewStoreAuditor wraps a durable AuditStore.

type Config

type Config struct {
	DefaultEffect string // "allow" | "deny"; default "deny" when enabled
	FailClosed    *bool  // webhook errors; default true
	CacheTTL      time.Duration
	Grants        []Grant // deployment defaults (baseline)
	Overlays      []Grant // DB grants loaded at startup
	// MandatoryHITL forces matching tool.call allows to pending (config-only).
	MandatoryHITL []MandatoryHITLRule
	// Predicates deny or pending a tools/call from argument values.
	// They never allow; invalid rows are skipped at New.
	Predicates []Predicate
	Webhook    *WebhookConfig
	Auditor    Auditor
	// AuditRequired refuses allow/pending when durable decision persistence
	// fails or no auditor is present. Deployment wiring validates the backend.
	AuditRequired bool
	// ActionEvidence enables managed MCP action records. Deployment wiring
	// requires required auditing and a SQL protected-action store.
	ActionEvidence       bool
	ApprovalRequirements ApprovalRequirements
	Exporter             Exporter
	// ForceEnable builds an engine even with no grants/webhook (empty
	// "policy": {} for Admin-API-only grant management).
	ForceEnable bool
}

Config builds an Engine from langgraph.json's policy section.

type Engine

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

Engine chains static grants then optional webhook. First deny wins. When Enabled() is false, callers must skip Decide (V1 open).

func New

func New(cfg Config) *Engine

New returns an Engine, or nil when nothing is configured (V1 open).

func (*Engine) ActionEvidenceEnabled added in v0.7.0

func (e *Engine) ActionEvidenceEnabled() bool

ActionEvidenceEnabled reports whether managed MCP attempts require evidence.

func (*Engine) ApprovalRequirements added in v0.7.0

func (e *Engine) ApprovalRequirements() ApprovalRequirements

func (*Engine) AuditRequired added in v0.7.0

func (e *Engine) AuditRequired() bool

AuditRequired reports whether every policy decision requires a durable write.

func (*Engine) CacheLen

func (e *Engine) CacheLen() int

CacheLen is the current decision-cache occupancy (tests / ops). 0 when caching is off.

func (*Engine) Decide

func (e *Engine) Decide(ctx context.Context, in PolicyInput) PolicyDecision

Decide evaluates static grants, then argument predicates, then webhook. Call only when Enabled(). Every call (including cache hits) emits an OTel span event, writes audit when configured, and fans out to Exporter (SIEM) when set.

func (*Engine) Enabled

func (e *Engine) Enabled() bool

Enabled reports whether the policy engine is attached. An empty ForceEnable engine (no grants/webhook/predicates yet) is still enabled — Decide applies default_effect until Admin overlays or config grants appear.

func (*Engine) MatchMandatoryHITL

func (e *Engine) MatchMandatoryHITL(in PolicyInput) *MandatoryHITLRule

MatchMandatoryHITL reports whether a rule would force pending for this input (observability / break-glass audit). Nil when none match.

func (*Engine) ReplaceMandatoryHITL

func (e *Engine) ReplaceMandatoryHITL(overlays []MandatoryHITLRule)

ReplaceMandatoryHITL swaps durable SQL mandatory-HITL overlays and rebuilds the active rule list. Overlay rows win over baseline on (tenant_id, agent_id, connector).

func (*Engine) ReplaceOverlays

func (e *Engine) ReplaceOverlays(overlays []Grant)

ReplaceOverlays swaps durable DB grants and rebuilds the static layer. Overlay rows win over baseline on (tenant_id, agent_id, connector).

func (*Engine) Revision added in v0.7.0

func (e *Engine) Revision() string

Revision fingerprints the effective configured policy. A webhook's remote rules are represented only by its operator-declared revision, not attested. HMAC credentials never enter this descriptor.

func (*Engine) SetExporter

func (e *Engine) SetExporter(exp Exporter)

SetExporter attaches (or clears) the async SIEM/export sink after New.

type Exporter

type Exporter interface {
	ExportPolicyDecision(ctx context.Context, in PolicyInput, dec PolicyDecision)
}

Exporter fans a decision out asynchronously (SIEM webhook, etc.). Must not block; nil is a no-op.

type Grant

type Grant struct {
	ID        string      `json:"id,omitempty"`
	TenantID  string      `json:"tenant_id"`
	AgentID   string      `json:"agent_id"`
	Connector string      `json:"connector"` // connector name
	Tools     *ToolFilter `json:"tools,omitempty"`
}

Grant is one connector grant from langgraph.json policy.grants.

type MandatoryHITLRule

type MandatoryHITLRule struct {
	ID        string   `json:"id,omitempty"`
	TenantID  string   `json:"tenant_id"`
	AgentID   string   `json:"agent_id,omitempty"` // empty = whole tenant
	Connector string   `json:"connector"`
	Tools     []string `json:"tools,omitempty"` // empty = all tools
}

MandatoryHITLRule forces connector tool.call decisions to pending when they would otherwise allow. Empty AgentID matches every agent in the tenant; empty Tools matches every tool on the connector. Hard deny from Decide is never elevated to pending.

type PolicyDecision

type PolicyDecision struct {
	Effect     string
	Reason     string
	ReasonCode string
	RuleID     string
	LatencyMs  int
	// AuditFailed marks a required persistence failure independently of the
	// policy reason. Callers must not bypass it with approval or break-glass.
	AuditFailed    bool   `json:"-"`
	PolicyRevision string `json:"policy_revision,omitempty"`
}

PolicyDecision is the allow/deny answer for one Decide call.

type PolicyInput

type PolicyInput struct {
	Stage      string
	TenantID   string
	Principal  string
	AgentID    string
	RunID      string
	Generation int64
	Connector  string
	Tool       string
	// TargetRevision is the plane-resolved managed connector target identity.
	// Standalone decisions do not claim a Runkite-owned execution target.
	TargetRevision string
	PolicyRevision string
	ToolRevision   string
	// Args is the full parsed tools/call arguments (predicate eval).
	// Secret-looking keys stay here; ArgsMeta is the redacted display copy.
	Args       any
	ArgsMeta   map[string]any
	ArgsDigest string
	// ConnectorActionID is generated by the plane for managed MCP evidence.
	// It is not a caller operation key or a pending approval capability.
	ConnectorActionID string
	Claims            map[string]any
	Labels            map[string]string
}

PolicyInput is the decision context for one gate check.

type Predicate

type Predicate struct {
	ID         string
	TenantID   string
	AgentID    string
	Connector  string
	Tool       string
	Path       string
	Op         string
	Value      any
	Effect     string
	Reason     string
	ReasonCode string
}

Predicate is one config-declared argument check. Effect is deny or pending only — predicates never grant access. Empty AgentID matches the whole tenant; empty Tool matches every tool on the connector. Missing When.Path does not match (not fail-closed).

func ValidatePredicate

func ValidatePredicate(p Predicate) (Predicate, error)

ValidatePredicate returns a normalized copy or an error if the row cannot be enforced. Callers skip invalid rows rather than fail-open.

type Provider

type Provider interface {
	Decide(ctx context.Context, in PolicyInput) (PolicyDecision, error)
}

Provider evaluates one policy layer.

type Static

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

Static evaluates in-process grants. Unmatched → Deny (caller applies default_effect only when no static layer exists).

func NewStatic

func NewStatic(grants []Grant) *Static

NewStatic copies grants for evaluation.

func (*Static) Decide

func (s *Static) Decide(_ context.Context, in PolicyInput) (PolicyDecision, error)

Decide implements Provider for static grants.

type ToolFilter

type ToolFilter struct {
	Allow []string `json:"allow,omitempty"`
	Deny  []string `json:"deny,omitempty"`
}

ToolFilter mirrors connector.ToolFilter semantics for per-grant tools.

type Webhook

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

Webhook POSTs a decision request and parses allow/deny.

func NewWebhook

func NewWebhook(cfg WebhookConfig) *Webhook

NewWebhook builds a webhook provider. Timeout defaults to hooks.DefaultPreflightTimeout.

func (*Webhook) Decide

func (w *Webhook) Decide(ctx context.Context, in PolicyInput, failClosed bool) PolicyDecision

Decide calls the webhook. failClosed=true → errors become deny.

type WebhookConfig

type WebhookConfig struct {
	URL      string
	Revision string
	Secret   string
	Timeout  time.Duration
}

WebhookConfig is the sync policy webhook (WebhookGate-shaped, not the async Dispatcher/Sink path).

Jump to

Keyboard shortcuts

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