Documentation
¶
Overview ¶
Package policy is the deterministic, I/O-free MCP policy-decision engine (PR-6, MCP-POLICY-001..007, MCP-TOOL-004/006, MCP-ID-005/006). It answers a single question — "is this MCP operation permitted, and exactly why?" — over an immutable, caller-supplied decision tuple and an immutable, capability-local policy snapshot, and returns an explainable Decision plus an internal explain trace.
It is PURE: no network, filesystem, database, DNS, environment, clock, secret or logging access happens on the evaluation path. Every fact the evaluator needs is supplied in the immutable DecisionInput, and the evaluation timestamp is an explicit input — the code never calls time.Now(). It is DEFAULT-DENY, bounded, and safe under hostile or incomplete input. Gateway and Management use completely separate policy namespaces that can never cross-match.
It decides only. It never executes a business operation, calls an upstream MCP server, materializes a credential, contacts a credential provider, performs DLP/inspection, or durably commits an event — those are later slices. Even an ALLOW-class decision is metadata here; PR-6 never fabricates execution success.
Index ¶
- func ConditionField(conditionID string) string
- func FieldIsKnown(name string) bool
- type Action
- type Agent
- type Assurance
- type Capability
- type Client
- type CreatedMeta
- type CredentialMeta
- type CredentialPower
- type Decision
- type DecisionInput
- type Destination
- type DestinationMeta
- type Disposition
- type DriftClass
- type Effect
- type Engine
- type EventClass
- type ExplainTrace
- type Inspection
- type LimitConfig
- type Limits
- func (l Limits) MaxCompareSamples() int
- func (l Limits) MaxConditions() int
- func (l Limits) MaxEvalOps() int
- func (l Limits) MaxGroupsScopes() int
- func (l Limits) MaxObligations() int
- func (l Limits) MaxPatternBytes() int
- func (l Limits) MaxPatternSegments() int
- func (l Limits) MaxResourceAttrs() int
- func (l Limits) MaxRulesPerSnap() int
- func (l Limits) MaxSetValues() int
- func (l Limits) MaxSimCases() int
- func (l Limits) MaxSnapHistory() int
- func (l Limits) MaxSnapshotBytes() int
- func (l Limits) MaxStringBytes() int
- func (l Limits) MaxTraceEntries() int
- type LoggingClass
- type ManagedState
- type Obligations
- type ObservationLevel
- type Operation
- type OperationClass
- type OperationNamespace
- type Principal
- type ReasonCode
- type RedactionReq
- type Remediation
- type Resource
- type Reversibility
- type Revision
- type Rule
- func (r *Rule) Action() Action
- func (r *Rule) AllowsDestructive() bool
- func (r *Rule) ConditionFields() []string
- func (r *Rule) Enabled() bool
- func (r *Rule) HasExpiry() bool
- func (r *Rule) ID() RuleID
- func (r *Rule) Obligations() Obligations
- func (r *Rule) Priority() int
- func (r *Rule) Reason() ReasonCode
- func (r *Rule) Remediation() Remediation
- type RuleID
- type SenderBinding
- type Server
- type ServerVerification
- type Session
- type SessionGrant
- type Snapshot
- func (s *Snapshot) Capability() Capability
- func (s *Snapshot) DefaultAction() Action
- func (s *Snapshot) Description() string
- func (s *Snapshot) Hash() string
- func (s *Snapshot) Limits() Limits
- func (s *Snapshot) Revision() Revision
- func (s *Snapshot) Rule(id RuleID) *Rule
- func (s *Snapshot) RuleCount() int
- func (s *Snapshot) RuleIDs() []RuleID
- func (s *Snapshot) SchemaVersion() int
- type Store
- type SubjectKind
- type Tool
- type TraceEntry
- type TraceKind
- type TrustClass
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConditionField ¶ added in v1.0.231
ConditionField extracts the policy field from a stable condition id ("field|op"), as it appears on a compiled condition and on TraceEntry.ConditionID. It returns "" for an id that carries no field — the trace uses a few fixed non-field labels ("expiry", "", override labels), and a caller must not mistake one of those for a bound field.
It is exported so the Canary activation permit reads the SAME id format from the trace and from Rule.ConditionFields through one parser, rather than two that could drift.
func FieldIsKnown ¶ added in v1.0.231
FieldIsKnown reports whether name is a field a compiled condition may read: a member of the closed scalar/set/bool vocabulary above, or a bounded resource-attribute selector ("resource.attr:<key>"). Compile rejects anything else.
It is exported so a caller that reasons about WHICH fields a rule consulted — the Canary activation permit's bound-field set — can prove its own list names real fields. A typo there fails closed (an unrecognised field is treated as unbound), but it would also make the list a lie to the next reader, so the list is checked against this predicate rather than trusted.
Types ¶
type Action ¶
type Action uint8
Action is one of the exactly nine MCP policy-decision actions. The zero value is ActionInvalid so a mis-constructed rule or decision fails closed.
const ( // ActionInvalid is the zero value: not a valid action. Fails closed. ActionInvalid Action = iota // ActionAllow — permitted (requires complete evidence + all mandatory obligations). ActionAllow // ActionDeny — denied; no execution; carries a stable reason + remediation. ActionDeny // ActionMonitor — non-blocking policy intent; still no upstream execution in // PR-6; carries full telemetry obligations. ActionMonitor // ActionQuarantine — no execution; used for unknown tools + privilege expansion. ActionQuarantine // ActionRequireConfirmation — no execution until confirmation evidence exists // (a later slice). ActionRequireConfirmation // ActionRequireApproval — no execution until approval evidence exists (a later // slice). ActionRequireApproval // ActionAllowOnce — carries a one-call obligation, strict scope + short TTL. // PR-6 defines the obligation; redemption state is a later slice. ActionAllowOnce // ActionAllowForSession — carries session-id requirement, max-calls, TTL + revoke. // PR-6 defines the obligation; grant state is a later slice. ActionAllowForSession // ActionAllowWithRedaction — carries a redaction-profile reference + transformed- // evidence obligation. PR-7 supplies the actual redaction evidence. ActionAllowWithRedaction )
func AllActions ¶
func AllActions() []Action
AllActions returns the nine real actions in stable order (for tests + tooling).
func ParseAction ¶
ParseAction resolves a wire code to an Action. It returns (ActionInvalid, false) for an unknown/aliased/empty code — the parser rejects it rather than guessing.
func (Action) Effect ¶
Effect returns the execution-effect classification of the action. An invalid or unknown action is EffectDenied (fail closed).
func (Action) IsAllowClass ¶
IsAllowClass reports whether the action is ALLOW-class — the SINGLE authoritative classification used across the engine and runtime. It is METADATA ONLY in PR-6: an ALLOW-class result never invokes the credential broker, contacts a provider, or authorizes an upstream side effect. Credential planning/materialization only becomes reachable after an ALLOW-class decision in a later execution slice.
ALLOW-class = {ALLOW, MONITOR, ALLOW_ONCE, ALLOW_FOR_SESSION, ALLOW_WITH_REDACTION}. DENY, QUARANTINE, REQUIRE_CONFIRMATION and REQUIRE_APPROVAL are NOT ALLOW-class.
type Agent ¶
type Agent struct {
AgentID string
Owner string // owner reference (PR-3 proves it is the subject)
Version string
Managed ManagedState
Trust TrustClass
}
Agent is an optional agent principal acting on behalf of the subject.
type Assurance ¶
type Assurance uint8
Assurance is the subject's authentication-assurance level.
CAUTION (OVN-05). The labels below describe NIST-AAL-style HUMAN authentication strength — how the person proved who they are. Culvert cannot currently determine that: no token claim carrying it (`amr`/`acr`) is parsed anywhere, so nothing in the product supplies an AAL fact. What the runtime actually derives is the strength of the SENDER BINDING (is the token bound to the presenter's key?), which is a different property: DPoP proves possession of a key, not that a human completed MFA.
Use `principal.sender_binding` / `session.sender_binding` to express a sender-constraint requirement. Do NOT use `assurance` for it, and do not "upgrade" the derivation here to claim an AAL it cannot observe — see docs/design/mcp/OPEN-DECISION-assurance-model.md.
Higher is stronger; the zero value is Unknown (the floor).
type Capability ¶
type Capability uint8
Capability is the policy namespace. Gateway and Management are completely separate; a rule of one namespace can never match an input of the other.
const ( // CapabilityUnset — zero value; rejected by input/snapshot validation. CapabilityUnset Capability = iota // CapGateway — the business MCP Security Gateway surface. CapGateway // CapManagement — the read-only + draft/validate/simulate surface. CapManagement )
func (Capability) Valid ¶
func (c Capability) Valid() bool
Valid reports whether the capability is one of the two real namespaces.
type Client ¶
type Client struct {
ClientID string
AppID string
Tenant string
Trust TrustClass
Capability Capability // MUST equal the input capability
}
Client is the OAuth client / application principal.
type CreatedMeta ¶
type CreatedMeta struct {
Author string
CreatedAt string // caller-supplied RFC3339 string (never a clock read here)
Note string
}
CreatedMeta is caller-supplied, safe creation metadata for a snapshot. It holds no secrets and is carried verbatim (bounded by the document string limits).
type CredentialMeta ¶
type CredentialMeta struct {
ProfileRef string
PowerCeiling CredentialPower
Kind string
}
CredentialMeta is the policy-selected credential profile metadata. It carries NO secret and NO client token — only an opaque profile reference, the profile power ceiling and a credential-kind label.
type CredentialPower ¶
type CredentialPower uint8
CredentialPower is the ordered privilege ceiling of a credential/tool. Higher is more powerful; the zero value is Unset.
const ( // PowerUnset — zero value; unset. PowerUnset CredentialPower = iota // PowerReadOnly — read-only power. PowerReadOnly // PowerWrite — write power. PowerWrite // PowerAdmin — administrative power (the broadest). PowerAdmin )
func (CredentialPower) String ¶
func (p CredentialPower) String() string
String returns the credential-power label.
type Decision ¶
type Decision struct {
Action Action
Effect Effect
Reason ReasonCode
Remediation Remediation
MatchedRule RuleID // "" when no rule matched (hard override / default deny)
Capability Capability
PolicyRevision Revision
CatalogRevision uint64
EventClass EventClass
Obligations Obligations
HardOverride bool // a hard security override produced this decision
}
Decision is the RUNTIME-SAFE result of an evaluation. It is bounded and carries only safe metadata — no raw arguments, tokens, secrets or the full policy document — so it is safe for observe records and wire-level error mapping. Every decision carries a reason code and the policy+catalog revision context.
func (Decision) IsAllowClass ¶
IsAllowClass reports whether the decision permits (metadata only in PR-6).
func (Decision) ObligationIDs ¶
ObligationIDs returns the bounded, safe obligation identifiers of the decision.
type DecisionInput ¶
type DecisionInput struct {
// Capability + revision context (stamped onto every decision).
Capability Capability
PolicyRevision uint64
CatalogRevision uint64
RegistryRevision uint64
RuntimeRevision uint64
// EvalTime is the EXPLICIT evaluation timestamp. The evaluator never calls
// time.Now(); all time-window matching is against this value.
EvalTime time.Time
Principal Principal
Agent *Agent // optional
Client Client
Server *Server // Gateway only
Tool *Tool // Gateway tool operations
Operation Operation
Resource *Resource // optional
Destination DestinationMeta
Credential *CredentialMeta // optional; policy-selected profile metadata only
Session Session
Inspection Inspection // PR-7 placeholders (absence flags)
}
DecisionInput is the immutable, typed decision tuple the evaluator consumes. It is a self-contained value: every fact the pure evaluator needs is present here, so evaluation performs no I/O and never reads a live registry/catalog/clock. It carries NO raw request body and NO raw bearer token BY CONSTRUCTION — only safe opaque ids, one-way fingerprints, bounded enums and the explicit evaluation time. The caller (the runtime) translates PR-2/PR-3 objects into this tuple.
func (DecisionInput) Validate ¶
func (in DecisionInput) Validate(lim Limits) error
Validate checks the decision tuple for structural validity and fails CLOSED. A structurally invalid tuple is distinct from a valid tuple that no rule matched: this returns a typed *mcperr error (mapped to MCP.SYSTEM.INVALID_INPUT), never a misleading no-match default deny. It reads only the input (no I/O).
type Destination ¶
type Destination uint8
Destination is the observed network/resource breadth of the tool (ordered, with DestinationUnknown outside the order).
const ( // DestinationUnknown — not observed (outside the ordering). DestinationUnknown Destination = iota // DestinationNone — no external destination. DestinationNone // DestinationApproved — a single approved upstream service. DestinationApproved // DestinationInternal — the internal network. DestinationInternal // DestinationArbitrary — arbitrary network / any URL (the broadest). DestinationArbitrary )
func (Destination) String ¶
func (d Destination) String() string
String returns the destination label.
type DestinationMeta ¶
type DestinationMeta struct {
Class Destination
Environment string
ApprovedBreadth Destination
}
DestinationMeta is PRE-RESOLVED destination metadata only — no DNS/network resolution happens during evaluation.
type Disposition ¶
type Disposition uint8
Disposition mirrors the catalog eligibility of the resolved tool.
const ( // DispUnset — zero value; a Gateway tool input without a disposition is invalid. DispUnset Disposition = iota // DispQuarantined — quarantined (unknown tool or privilege expansion). DispQuarantined // DispReviewRequired — semantic drift; routed to human review. DispReviewRequired // DispPendingNarrowing — safe narrowing pending disposition. DispPendingNarrowing // DispServerDisabled — the server's identity changed; every tool behind it is unusable. DispServerDisabled // DispUsable — an approved, known tool with no material change. DispUsable )
func (Disposition) String ¶
func (d Disposition) String() string
String returns the disposition label.
func (Disposition) Valid ¶
func (d Disposition) Valid() bool
Valid reports whether the disposition is a real catalog eligibility (never the zero value, never an out-of-range value). Used by input validation so a hostile tuple carrying an unknown disposition fails closed rather than slipping past the hard-override switch.
type DriftClass ¶
type DriftClass uint8
DriftClass mirrors the catalog drift classification of the resolved tool.
const ( // DriftUnset — zero value; a Gateway tool input without a drift class is invalid. DriftUnset DriftClass = iota // DriftNoMaterialChange — the canonical fingerprint is unchanged. DriftNoMaterialChange // DriftSafeNarrowing — every change is mechanically proven restrictive. DriftSafeNarrowing // DriftPrivilegeExpansion — a proven/ambiguous security-relevant broadening. DriftPrivilegeExpansion // DriftSemanticDrift — a behavioral change neither proven narrowing nor expansion. DriftSemanticDrift // DriftIdentityChange — the observed identity differs from the recorded one. DriftIdentityChange // DriftUnknownTool — no prior record for this (server, tool). DriftUnknownTool )
func (DriftClass) String ¶
func (d DriftClass) String() string
String returns the drift-class label.
func (DriftClass) Valid ¶
func (d DriftClass) Valid() bool
Valid reports whether the drift class is a real classification (never an out-of-range value). DriftUnset is intentionally NOT valid: an input carries a concrete drift class unless the tool is quarantined (handled explicitly by input validation).
type Effect ¶
type Effect uint8
Effect is the coarse execution-effect classification of an action. It exists so the runtime can branch on the effect without re-deriving it from the action.
const ( // EffectDenied is the zero value: no execution (fail closed). EffectDenied Effect = iota // EffectPermitted — permitted (possibly with obligations). EffectPermitted // EffectPermittedWithObligations — permitted but carrying mandatory obligations. EffectPermittedWithObligations // EffectPendingConfirmation — no execution until confirmation evidence exists. EffectPendingConfirmation // EffectPendingApproval — no execution until approval evidence exists. EffectPendingApproval // EffectQuarantined — no execution; quarantined. EffectQuarantined )
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine evaluates immutable decision inputs against immutable snapshots. It holds no mutable state, performs NO I/O, and never calls time.Now — the evaluation timestamp is the input's explicit EvalTime. The SAME Engine.Evaluate is used by the runtime AND the simulator (there is no second evaluator).
func (*Engine) Evaluate ¶
func (e *Engine) Evaluate(snap *Snapshot, in *DecisionInput) (Decision, ExplainTrace, error)
Evaluate produces a runtime-safe Decision and an internal ExplainTrace for one input against one snapshot. It is a pure function of (snap, in). It returns a non-nil error ONLY for a structurally invalid input or an unavailable snapshot — a case that must be distinguished from a valid tuple that no rule matched. In every case the returned Decision is fail-closed (a DENY/QUARANTINE), so a caller that ignores the error still cannot permit.
Evaluation order (hard overrides dominate ANY user rule; first-match laundering is impossible because overrides run first):
- snapshot available + capability match
- structural input validity
- cross-tenant resource reference → DENY MCP.AUTH.TENANT_MISMATCH
- missing/ambiguous identity on write/high-risk → DENY MCP.AUTH.IDENTITY_AMBIGUOUS (MCP-ID-005)
- Management mutation/activation → DENY MCP.MANAGEMENT.MUTATION_NOT_APPROVED
- Gateway cross-tenant server → DENY MCP.AUTH.TENANT_MISMATCH (QUAL-5 tenant isolation)
- server identity changed → DENY MCP.SERVER.IDENTITY_CHANGED
- server disabled → DENY MCP.SERVER.DISABLED
- unknown tool → QUARANTINE MCP.TOOL.UNKNOWN
- privilege expansion → QUARANTINE MCP.TOOL.PRIVILEGE_EXPANSION
- ordered first-match over enabled rules (+ destructive contract)
- default deny → DENY MCP.POLICY.NO_MATCH_DEFAULT_DENY
type EventClass ¶
type EventClass uint8
EventClass is the deterministic event classification of a decision (it maps to the EVENT-MODEL category/criticality in a later slice). It is derived purely from the action + whether a hard override fired.
const ( // EventError — an invalid input / unavailable snapshot (fail closed). EventError EventClass = iota // EventAllow — an ALLOW-class permit. EventAllow // EventDeny — an explicit or default deny. EventDeny // EventQuarantine — a quarantine (unknown tool / privilege expansion). EventQuarantine // EventApprovalRequired — approval pending. EventApprovalRequired // EventConfirmationRequired — confirmation pending. EventConfirmationRequired // EventMonitor — a monitored (non-blocking) intent. EventMonitor )
func (EventClass) String ¶
func (e EventClass) String() string
String returns the event-class label.
type ExplainTrace ¶
type ExplainTrace struct {
Entries []TraceEntry
// Truncated reports that the entry cap was reached and later entries were DROPPED.
// It is load-bearing for any caller that reasons about the rules NOT listed: a
// truncated trace is silent about them, so "no entry says otherwise" stops being
// evidence. The Canary activation permit refuses on it for exactly that reason
// (canary.permitVerdictInvariant) — deterministic truncation is a size guard, never
// a proof.
Truncated bool
Winner RuleID // "" for hard override / default deny
Decisive string // decisive condition id or override/default label
Final ReasonCode // the final reason code
Action Action
Capability Capability
PolicyRevision Revision
CatalogRevision uint64
}
ExplainTrace is the internal, deterministic decision explanation the simulator and (later) Management MCP consume. It is bounded and sanitized.
type Inspection ¶
type Inspection struct {
DLPAvailable bool
RedactionAvailable bool
DestInspectAvailable bool
SecretScanAvailable bool
SecretFound bool // meaningful only when SecretScanAvailable
// PR-7 summary facts (all safe booleans; matchable via condition fields).
PIIFound bool // a PII/financial classification was found
InjectionSuspected bool // best-effort injection labeling flagged output content
SchemaInvalid bool // semantic schema validation rejected the arguments
}
Inspection carries the PR-7 inspection summary facts. When no inspector is wired the *Available flags are all false, so a rule requiring inspection evidence never silently passes (fail closed via ReasonInspectionUnavailable). PR-7 populates these from the sanitized inspection summary; every field is a typed fact, never a raw argument/output/secret. The evaluator stays I/O-free (no new imports).
type LimitConfig ¶
type LimitConfig struct {
MaxSnapshotBytes int // strict-parse byte cap for a policy document
MaxRulesPerSnap int // rules per snapshot
MaxConditions int // conditions per rule
MaxSetValues int // values per one-of/set matcher
MaxStringBytes int // bytes of any one policy string value
MaxPatternBytes int // bytes of a glob pattern
MaxPatternSegments int // segments in a glob pattern
MaxResourceAttrs int // resource attributes in an input
MaxGroupsScopes int // groups/scopes in an input
MaxObligations int // obligation entries per rule
MaxTraceEntries int // explain-trace entries
MaxSimCases int // simulator corpus cases
MaxCompareSamples int // sample case ids in a comparison summary
MaxEvalOps int // bounded evaluation-operation budget
MaxSnapHistory int // retained snapshots in a store
}
LimitConfig is the mutable input to NewLimits.
func (LimitConfig) Validate ¶
func (c LimitConfig) Validate() error
Validate enforces positivity and hard-cap ceilings on every bound.
type Limits ¶
type Limits struct {
// contains filtered or unexported fields
}
Limits is the immutable, validated policy bound set. Every dimension a snapshot author or an attacker-influenced input can drive is finite and validated. A zero, negative, inverted or over-ceiling value fails construction (fail closed).
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns a conservative, valid policy bound set.
func NewLimits ¶
func NewLimits(c LimitConfig) (Limits, error)
NewLimits validates c into an immutable Limits.
func (Limits) MaxCompareSamples ¶
MaxCompareSamples returns the comparison-sample cap.
func (Limits) MaxConditions ¶
MaxConditions returns the conditions-per-rule cap.
func (Limits) MaxEvalOps ¶
MaxEvalOps returns the per-evaluation operation budget.
func (Limits) MaxGroupsScopes ¶
MaxGroupsScopes returns the groups/scopes cap.
func (Limits) MaxObligations ¶
MaxObligations returns the obligations-per-rule cap.
func (Limits) MaxPatternBytes ¶
MaxPatternBytes returns the glob-pattern byte cap.
func (Limits) MaxPatternSegments ¶
MaxPatternSegments returns the glob-pattern segment cap.
func (Limits) MaxResourceAttrs ¶
MaxResourceAttrs returns the resource-attribute cap.
func (Limits) MaxRulesPerSnap ¶
MaxRulesPerSnap returns the rules-per-snapshot cap.
func (Limits) MaxSetValues ¶
MaxSetValues returns the values-per-set-matcher cap.
func (Limits) MaxSimCases ¶
MaxSimCases returns the simulator corpus cap.
func (Limits) MaxSnapHistory ¶
MaxSnapHistory returns the retained-snapshot cap for a store.
func (Limits) MaxSnapshotBytes ¶
MaxSnapshotBytes returns the strict-parse byte cap for a policy document.
func (Limits) MaxStringBytes ¶
MaxStringBytes returns the per-string byte cap.
func (Limits) MaxTraceEntries ¶
MaxTraceEntries returns the explain-trace entry cap.
type LoggingClass ¶
type LoggingClass uint8
LoggingClass is the mandated logging/telemetry class for a decision.
const ( // LogUnset — zero value. LogUnset LoggingClass = iota // LogStandard — standard request logging. LogStandard // LogFull — full request logging. LogFull // LogAudit — audit-grade logging (retained). LogAudit )
func (LoggingClass) String ¶
func (l LoggingClass) String() string
String returns the logging-class label.
type ManagedState ¶
type ManagedState uint8
ManagedState is whether an agent runs under managed control.
const ( // ManagedUnknown — not asserted. ManagedUnknown ManagedState = iota // Managed — centrally managed. Managed // Unmanaged — not centrally managed. Unmanaged )
func (ManagedState) String ¶
func (m ManagedState) String() string
String returns the managed-state label.
type Obligations ¶
type Obligations struct {
Logging LoggingClass
Observation ObservationLevel
RateLimitProfile string // opaque rate-limit profile reference (optional)
Destination Destination // bounded destination scope (optional; 0 = unset)
CredentialProfile string // Gateway credential-profile id (opaque; ALLOW-class Gateway only)
OnceCall bool // ALLOW_ONCE: exactly one call permitted
Session *SessionGrant // ALLOW_FOR_SESSION payload
Redaction *RedactionReq // ALLOW_WITH_REDACTION payload
Confirmation bool // REQUIRE_CONFIRMATION: confirmation is required
Approval bool // REQUIRE_APPROVAL: approval is required
TicketRequired bool // an external ticket/reference is required
}
Obligations is the typed, immutable obligation set attached to a rule/decision. Optional action-specific parts are pointers; a nil pointer means "not present". Nothing here is a secret or a raw token — credential profile / rate-limit / redaction references are opaque identifiers only.
func (Obligations) Equal ¶
func (o Obligations) Equal(x Obligations) bool
Equal reports whether two obligation sets are byte-for-byte equivalent, including the full session/redaction payloads. The simulator uses it so a candidate that weakens ONLY an obligation (e.g. a longer session TTL, same action/reason/rule) is still counted as a changed decision in the blast-radius report.
func (Obligations) IDs ¶
func (o Obligations) IDs() []string
IDs returns the bounded, safe obligation identifiers for a runtime decision / observe record — never a secret, only opaque references and typed labels. The order is stable.
type ObservationLevel ¶
type ObservationLevel uint8
ObservationLevel is the mandated decision-observation detail level.
const ( // ObsUnset — zero value (defaults to summary at emit time). ObsUnset ObservationLevel = iota // ObsSummary — summary observation. ObsSummary // ObsDetailed — detailed observation. ObsDetailed )
func (ObservationLevel) String ¶
func (o ObservationLevel) String() string
String returns the observation-level label.
type Operation ¶
type Operation struct {
Method string // admitted protocol method (never a rejected method)
Class OperationClass
Namespace OperationNamespace
Operand string // normalized operand identity
DecisionPoint string // exact decision point from the operation registry
}
Operation is the method / operation-class / namespace / operand identity.
type OperationClass ¶
type OperationClass uint8
OperationClass is the coarse effect class of the operation being evaluated.
const ( // OpUnset — zero value; rejected by input validation. OpUnset OperationClass = iota // OpRead — a read-only operation. OpRead // OpWrite — a state-changing but reversible operation. OpWrite // OpDestructive — an irreversible/destructive operation (never implicitly allowed). OpDestructive // OpDiscovery — a discovery operation (e.g. tools/list). OpDiscovery // OpControl — a control-plane operation. OpControl )
func (OperationClass) String ¶
func (o OperationClass) String() string
String returns the operation-class label.
func (OperationClass) Valid ¶
func (o OperationClass) Valid() bool
Valid reports whether the operation class is a real class.
type OperationNamespace ¶
type OperationNamespace uint8
OperationNamespace distinguishes a Gateway tool operation from a Management operation. It must be consistent with the Capability.
const ( // NamespaceUnset — zero value; rejected by input validation. NamespaceUnset OperationNamespace = iota // NamespaceGatewayTool — a Gateway tool operation. NamespaceGatewayTool // NamespaceManagementOperation — a Management operation. NamespaceManagementOperation )
func (OperationNamespace) String ¶
func (n OperationNamespace) String() string
String returns the namespace label.
type Principal ¶
type Principal struct {
Kind SubjectKind
SubjectID string // stable subject id or safe fingerprint (opaque; never a token)
Tenant string
Groups []string
Assurance Assurance
// SenderBinding is the VERIFIED proof-of-possession binding for this request
// (none / dpop / mtls). Distinct from Assurance — see the OVN-05 note on the
// Assurance type. The zero value is None, so an input that never sets it fails
// a binding requirement closed.
SenderBinding SenderBinding
Issuer string
}
Principal is the authenticated subject (from PR-3 identity.ResolvedContext).
type ReasonCode ¶
type ReasonCode string
ReasonCode is a stable, structured machine reason for a decision — never unbounded free-form text. Its shape is PREFIX.TOKEN(.TOKEN)* where PREFIX is one of the accepted MCP.* domains and every TOKEN is bounded UPPER_SNAKE. Callers branch on the exact code; humans render it elsewhere (Management/UI).
const ( // ReasonNoMatchDefaultDeny — a valid tuple that no enabled rule matched. ReasonNoMatchDefaultDeny ReasonCode = "MCP.POLICY.NO_MATCH_DEFAULT_DENY" // at a decision point (runtime fail-closed). Distinct from SNAPSHOT_INVALID // (an integrity failure): here nothing is published yet. ReasonSnapshotUnavailable ReasonCode = "MCP.POLICY.SNAPSHOT_UNAVAILABLE" // ReasonSnapshotInvalid — a snapshot failed integrity/HA validation (§5 taxonomy). ReasonSnapshotInvalid ReasonCode = "MCP.SYSTEM.SNAPSHOT_INVALID" // ReasonResourceScope — the resource scope did not match (§5). ReasonResourceScope ReasonCode = "MCP.POLICY.RESOURCE_SCOPE" // ReasonTimeWindow — outside the permitted time window (§5). ReasonTimeWindow ReasonCode = "MCP.POLICY.TIME_WINDOW" // ReasonApprovalRequired — the matched rule requires approval (§5). ReasonApprovalRequired ReasonCode = "MCP.POLICY.APPROVAL_REQUIRED" // ReasonToolUnknown — hard override: an unknown tool (no catalog record). ReasonToolUnknown ReasonCode = "MCP.TOOL.UNKNOWN" // ReasonToolPrivilegeExpansion — hard override: privilege-expansion drift. ReasonToolPrivilegeExpansion ReasonCode = "MCP.TOOL.PRIVILEGE_EXPANSION" // ReasonToolSchemaChanged — a tool schema change (§5 / §6 worked example). ReasonToolSchemaChanged ReasonCode = "MCP.TOOL.SCHEMA_CHANGED" // ReasonToolSemanticDrift — a tool semantic drift (§5). ReasonToolSemanticDrift ReasonCode = "MCP.TOOL.SEMANTIC_DRIFT" // ReasonServerIdentityChanged — hard override: the server's verified identity changed. ReasonServerIdentityChanged ReasonCode = "MCP.SERVER.IDENTITY_CHANGED" // ReasonServerDisabled — hard override: the Gateway server is disabled. ReasonServerDisabled ReasonCode = "MCP.SERVER.DISABLED" // ReasonServerUnregistered — hard override: the Gateway server is unregistered (§5). ReasonServerUnregistered ReasonCode = "MCP.SERVER.UNREGISTERED" // ReasonIdentityAmbiguous — missing/ambiguous identity on a write/high-risk op // (MCP-ID-005; §5 MCP.AUTH.IDENTITY_AMBIGUOUS). ReasonIdentityAmbiguous ReasonCode = "MCP.AUTH.IDENTITY_AMBIGUOUS" // ReasonTenantMismatch — hard override: conflicting/cross-tenant reference (MCP-ID-007). ReasonTenantMismatch ReasonCode = "MCP.AUTH.TENANT_MISMATCH" // ReasonCapabilityMismatch — hard override: input crosses the capability namespace. ReasonCapabilityMismatch ReasonCode = "MCP.AUTH.CAPABILITY_MISMATCH" // ReasonManagementMutationNotApproved — hard override: a forbidden Management // activation/publication/mutation/state-affecting operation class (V1 boundary; §5). ReasonManagementMutationNotApproved ReasonCode = "MCP.MANAGEMENT.MUTATION_NOT_APPROVED" // ReasonInvalidInput — the decision tuple is structurally invalid (distinct from // a valid tuple that simply did not match). ReasonInvalidInput ReasonCode = "MCP.SYSTEM.INVALID_INPUT" // ReasonMissingOperand — a required decision operand is absent (input/model failure). ReasonMissingOperand ReasonCode = "MCP.SYSTEM.MISSING_OPERAND" // not yet supplied; the requirement must NOT silently pass. ReasonInspectionUnavailable ReasonCode = "MCP.INSPECTION.UNAVAILABLE" )
Engine-emitted reason codes. These are the codes the hard-override and default-deny paths stamp themselves; rule authors supply their own (validated) codes for ordinary matches. Every string here is part of the package contract. Engine-emitted + doc-taxonomy reason codes (MCP-POLICY-MODEL §5). The hard-override / default-deny paths stamp the engine codes themselves; rule authors supply their own (validated) codes. Every string here is contract.
func (ReasonCode) Valid ¶
func (r ReasonCode) Valid() bool
Valid reports whether the reason code is well-formed: an accepted MCP.* prefix followed by at least one bounded UPPER_SNAKE token, within the size bounds. It never accepts free-form text.
type RedactionReq ¶
type RedactionReq struct {
ProfileRef string // opaque redaction-profile reference (non-empty)
TransformedHashRequired bool // the transformed content must be hash-attested (PR-7)
}
RedactionReq is the ALLOW_WITH_REDACTION obligation payload.
type Remediation ¶
type Remediation string
Remediation is a stable remediation identifier from a CLOSED vocabulary — never arbitrary user-provided prose in the runtime decision. Human-readable rendering belongs to Management/UI in a later slice.
const ( // RemediationNone — no remediation applies (e.g. a plain ALLOW). RemediationNone Remediation = "none" // RemediationRequestAccess — the caller should request access to the operation. RemediationRequestAccess Remediation = "request_access" // RemediationReviewToolDrift — a tool-drift/quarantine remediation. RemediationReviewToolDrift Remediation = "review_tool_drift" // RemediationRequestApproval — an approval-workflow remediation. RemediationRequestApproval Remediation = "request_approval" // RemediationRequestConfirmation — a confirmation-step remediation. RemediationRequestConfirmation Remediation = "request_confirmation" // RemediationUseCorrectResource — the request named a wrong/foreign resource. RemediationUseCorrectResource Remediation = "use_correct_resource" // RemediationIncreaseAssurance — the principal's assurance is below the floor. RemediationIncreaseAssurance Remediation = "increase_assurance" // RemediationContactPolicyOwner — escalate to the policy owner. RemediationContactPolicyOwner Remediation = "contact_policy_owner" // RemediationWaitForPolicyPublication — no snapshot yet; wait for publication. RemediationWaitForPolicyPublication Remediation = "wait_for_policy_publication" // RemediationVerifyServerIdentity — the server identity changed / is disabled. RemediationVerifyServerIdentity Remediation = "verify_server_identity" // RemediationNotPermitted — the operation is structurally not permitted (V1 // Management boundary, cross-capability, invalid input). RemediationNotPermitted Remediation = "not_permitted" )
func (Remediation) String ¶
func (r Remediation) String() string
String returns the raw remediation identifier.
func (Remediation) Valid ¶
func (r Remediation) Valid() bool
Valid reports whether the remediation is in the closed vocabulary.
type Resource ¶
type Resource struct {
Type string
ID string
Tenant string
Attrs map[string]string // bounded scope attributes (e.g. repository, branch)
}
Resource is an optional protected-resource reference with bounded scope attrs.
type Reversibility ¶
type Reversibility uint8
Reversibility is whether the tool operation can be undone.
const ( // ReversibilityUnset — zero value; unset. ReversibilityUnset Reversibility = iota // Reversible — the operation can be undone. Reversible // Irreversible — the operation cannot be undone. Irreversible )
func (Reversibility) String ¶
func (r Reversibility) String() string
String returns the reversibility label.
type Revision ¶
type Revision uint64
Revision is a monotonically increasing policy-snapshot revision.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
Rule is one compiled, immutable policy rule. Its condition closures are pure functions over the input; the rule owns private copies of all mutable data (conditions slice + obligation payloads), so a caller cannot mutate it after compilation. Fields are unexported and read through accessors.
func (*Rule) AllowsDestructive ¶
AllowsDestructive reports whether the rule is explicitly authorized to permit a destructive operation (with the destructive obligation contract).
func (*Rule) ConditionFields ¶ added in v1.0.231
ConditionFields returns the POLICY FIELD each of this rule's conditions reads, in declaration order, deduplicated, sorted. A rule with no conditions returns nil — it matches every input of its namespace and therefore reads nothing.
The values are drawn from the CLOSED field vocabulary in fields.go ("tool.name", "principal.tenant", …); a compiled condition cannot name anything else, because compile rejects an unknown field. No operator-supplied VALUE is exposed — only which field was consulted.
It exists for the Canary activation permit (see Snapshot.Rule): a preflight verdict over one constructed tuple generalises to every request the scope admits ONLY IF the winning rule read nothing the activation does not bind. The caller compares this set against the fields it bound authoritatively and refuses the permit on any field outside it, so a rule conditioned on a request-variable field (session assurance, client id, inspection evidence) can never be certified as an executable permit.
The stable condition id is "field|op" (see compiledCond), so the field is the segment before the first "|". That format is part of the package's explain-trace contract — the same ids appear in TraceEntry.ConditionID, and the permit caller parses them there too.
func (*Rule) HasExpiry ¶ added in v1.0.247
HasExpiry reports whether the rule carries an expiry instant, i.e. whether matches() can stop returning true for an input it matches today purely because the clock moved.
It exposes the PRESENCE of the expiry, never the instant: a caller that needs to know the verdict is time-dependent must not be handed a deadline it could try to reason about, and the operator-facing surfaces this feeds are a closed vocabulary with no room for a timestamp.
It exists for the Canary activation permit's invariance argument. That argument already refuses a rule REJECTED on expiry (the trace reports the fixed label "expiry", which names no bound field); the WINNER's own expiry is the same dependency on the other side of the match, and without this accessor the permit could not see it at all.
func (*Rule) Obligations ¶
func (r *Rule) Obligations() Obligations
Obligations returns the rule's obligation set.
func (*Rule) Priority ¶
Priority returns the rule's unique integer priority (lower = evaluated first).
func (*Rule) Reason ¶
func (r *Rule) Reason() ReasonCode
Reason returns the rule's stable reason code.
func (*Rule) Remediation ¶
func (r *Rule) Remediation() Remediation
Remediation returns the rule's remediation code.
type RuleID ¶
type RuleID string
RuleID is an opaque, stable rule identifier. It is never a display name — the engine stamps it onto a matched decision and the explain trace.
type SenderBinding ¶ added in v1.0.216
type SenderBinding uint8
SenderBinding is the VERIFIED proof-of-possession binding between the access token and the party presenting it. It is a distinct property from Assurance: this says "the presenter proved control of the key the token is bound to", not "the human authenticated strongly" (OVN-05).
const ( // SenderBindingNone — a bearer credential: nothing binds it to its presenter, // so a stolen token is usable by anyone. The zero value, so an unset input // fails a binding requirement closed. SenderBindingNone SenderBinding = iota // SenderBindingDPoP — an RFC 9449 DPoP proof was VERIFIED for this request. SenderBindingDPoP // SenderBindingMTLS — an RFC 8705 mTLS certificate binding was VERIFIED. SenderBindingMTLS )
func (SenderBinding) Bound ¶ added in v1.0.216
func (s SenderBinding) Bound() bool
Bound reports whether ANY proof-of-possession binding was verified. It is the predicate a rule author usually wants ("require a sender-constrained token") without caring which mechanism produced it.
func (SenderBinding) String ¶ added in v1.0.216
func (s SenderBinding) String() string
String returns the sender-binding label used in rule values.
type Server ¶
type Server struct {
ServerID string
Owner string
Environment string
Enabled bool
Verification ServerVerification
}
Server is a registered Gateway server (from PR-2 registry).
type ServerVerification ¶
type ServerVerification uint8
ServerVerification is the server's verified-identity state (mirrors registry).
const ( // ServerVerifyUnset — zero value; a Gateway server input without it is invalid. ServerVerifyUnset ServerVerification = iota // ServerVerified — the pinned identity is the current trusted baseline. ServerVerified // ServerIdentityMismatch — a later verified identity did not match the pin. ServerIdentityMismatch )
func (ServerVerification) String ¶
func (s ServerVerification) String() string
String returns the server-verification label.
func (ServerVerification) Valid ¶
func (s ServerVerification) Valid() bool
Valid reports whether the verification state is a real value (never the unset zero value, never out-of-range). Input validation requires it so a hostile tuple carrying an unknown verification state cannot masquerade as a verified server.
type Session ¶
type Session struct {
Fingerprint string
Assurance Assurance
SenderBinding SenderBinding
PriorConfirmation bool
PriorApproval bool
PriorGrant bool
}
Session is the session/context fingerprint plus prior-decision metadata supplied ONLY when the caller explicitly has it.
type SessionGrant ¶
type SessionGrant struct {
SessionBound bool // the grant is bound to a specific session id
TTLSeconds int // > 0
MaxCalls int // > 0
RevokeRequired bool // the grant must be revocable
}
SessionGrant is the ALLOW_FOR_SESSION obligation payload.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is an immutable, capability-local, compiled policy snapshot. It is the unit of evaluation and publication. It is DEEPLY IMMUTABLE: rules are compiled closures over private copies of all data, so a caller cannot mutate the document (or any slice/map it passed) after construction and change evaluation. Its default posture is always DENY.
func Compile ¶
func Compile(raw []byte, meta CreatedMeta, lim Limits) (*Snapshot, error)
Compile strictly parses and compiles a policy document into an immutable, capability-local Snapshot, or returns a typed *mcperr error. It is PURE (no I/O). It rejects: an unsupported schema version, a wrong/mixed capability, a non-DENY default action, a duplicate RuleID, a duplicate priority, a malformed action/reason/remediation, an invalid condition, an invalid obligation for the action, a Management rule using a non-Management-legal action, and any over-limit size. On success every rule is a compiled closure over private copies of its data (deeply immutable), and the snapshot carries a deterministic canonical hash.
func (*Snapshot) Capability ¶
func (s *Snapshot) Capability() Capability
Capability returns the snapshot's capability namespace.
func (*Snapshot) DefaultAction ¶
DefaultAction returns the default (no-match) action — always ActionDeny.
func (*Snapshot) Description ¶
Description returns the snapshot's safe description metadata.
func (*Snapshot) Hash ¶
Hash returns the deterministic canonical snapshot hash (hex). Two logically identical documents with different object-key ordering hash the same.
func (*Snapshot) Rule ¶ added in v1.0.231
Rule returns the compiled rule with this id, or nil when the snapshot has none.
It exists for the CANARY ACTIVATION PERMIT (blocker #14), which must know which policy FIELDS the winning rule actually consulted. A preflight evaluates one constructed tuple; that verdict generalises to every request the activation scope admits only if the winner was decided entirely by fields the activation BINDS. Without this accessor the caller could observe that a rule won but not what it read, and would have to treat its own tuple as representative — which is a sample, not a proof.
It is READ-ONLY and leaks nothing: *Rule's fields are unexported and its accessors expose only the closed, developer-authored vocabulary (id, priority, action, reason, obligations, condition ids). No rule VALUE — the operator-supplied right-hand side of a condition — is reachable through it.
func (*Snapshot) SchemaVersion ¶
SchemaVersion returns the document schema version.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a bounded, capability-local holder of the CURRENT immutable policy snapshot. Reads are lock-free (an atomic pointer load); publication is serialized by a leaf mutex that enforces monotonic revisions and optimistic (stale-base) concurrency. It keeps NO unbounded history, performs NO filesystem/ database persistence, spawns NO background goroutine, and does NO signed CP→DP distribution (that is PR-10). A reader always sees a fully-published snapshot or none — never partial state.
func NewStore ¶
func NewStore(capability Capability) *Store
NewStore returns an empty capability-local store (no snapshot published yet).
func (*Store) Capability ¶
func (s *Store) Capability() Capability
Capability returns the store's capability namespace.
func (*Store) Current ¶
Current returns the current published snapshot, or nil if none is published. Lock-free.
func (*Store) CurrentRevision ¶
CurrentRevision returns the current published revision, or 0 if none.
func (*Store) Publish ¶
Publish atomically installs snap as the current snapshot. base is the revision the caller believes is current (optimistic concurrency): a base that does not equal the live current revision is rejected as stale (a concurrent publish won), and NOTHING is published. The new revision must be strictly greater than the current one, and the snapshot's capability must match the store. A rejected publish leaves the current snapshot unchanged.
type SubjectKind ¶
type SubjectKind uint8
SubjectKind is the authenticated subject type.
const ( // SubjectUnset — zero value; rejected by input validation. SubjectUnset SubjectKind = iota // SubjectHuman — a human subject. SubjectHuman // SubjectWorkload — a non-human workload subject. SubjectWorkload )
func (SubjectKind) String ¶
func (s SubjectKind) String() string
String returns the subject-kind label.
type Tool ¶
type Tool struct {
Name string
ServerID string // MUST equal Server.ServerID
FingerprintHash string // hex of the catalog composite fingerprint (required)
Disposition Disposition
Drift DriftClass
Destination Destination // observed breadth
CredentialPower CredentialPower
Reversibility Reversibility
InputSchemaHash string
OutputSchemaHash string
DescriptionHash string
RiskSignals []string // bounded, opaque labels
}
Tool is the resolved Gateway tool (from PR-2 catalog). All potentially sensitive content is a one-way hash; risk signals are bounded enum-like labels.
type TraceEntry ¶
type TraceEntry struct {
Kind TraceKind
RuleID RuleID
ConditionID string // stable "field|op" of the decisive condition (or "")
Matched bool
Label string // fixed, developer-authored label (never hostile input)
}
TraceEntry is one bounded, sanitized step of the internal explain trace. It identifies fields and condition ids but never exposes raw bearer tokens, DPoP proofs, credential material, complete tool arguments, secrets, private cert material or unbounded tenant-controlled strings — only opaque ids, enum labels and stable condition ids ("field|op").
type TraceKind ¶
type TraceKind uint8
TraceKind is the kind of an explain-trace entry.
const ( // TraceHardOverride — a hard security override was evaluated. TraceHardOverride TraceKind = iota // TraceRuleConsidered — an ordinary rule was considered. TraceRuleConsidered // TraceWinner — the winning rule. TraceWinner // TraceDefaultDeny — the terminal default-deny. TraceDefaultDeny // TraceInputInvalid — the input failed structural validation. TraceInputInvalid )
type TrustClass ¶
type TrustClass uint8
TrustClass is a supplied trust/risk classification for an agent or client.
const ( // TrustUnknown — no classification supplied. TrustUnknown TrustClass = iota // TrustUntrusted — explicitly untrusted. TrustUntrusted // TrustLow — low trust. TrustLow // TrustHigh — high trust. TrustHigh )
func (TrustClass) String ¶
func (t TrustClass) String() string
String returns the trust-class label.