decision

package
v0.5.15 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: AGPL-3.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 decision defines the small signed object boundary shared by local enforcers and managed or self-hosted authorization providers.

Index

Constants

View Source
const (
	ApprovalRequestDomain = "pilot-approval-request-v1"
	ApprovalGrantDomain   = "pilot-approval-grant-v1"
)
View Source
const (
	SchemaVersion  uint16 = 1
	IntentDomain          = "pilot-intent-v1"
	DecisionDomain        = "pilot-decision-v1"

	MaxClockSkew   = time.Minute
	MaxIntentTTL   = 5 * time.Minute
	MaxDecisionTTL = 5 * time.Minute
)
View Source
const (
	// DisclosureBindingVersion preserves the original V1 canonical bytes.
	// Callers that do not need retention metadata should continue to use it.
	DisclosureBindingVersion uint16 = 1
	// DisclosureBindingRetentionVersion adds a policy-selected retention class
	// without changing V1 Intent or disclosure hashes.
	DisclosureBindingRetentionVersion uint16 = 2
	DisclosureBindingDomain                  = "pilot-disclosure-binding-v1"
	DisclosureBindingRetentionDomain         = "pilot-disclosure-binding-v2"
)
View Source
const (
	EvaluatorAttestationVersion uint16 = 1
	EvaluatorAttestationDomain         = "pilot-evaluator-attestation-v1"
	MaxEvaluatorAttestationTTL         = 24 * time.Hour
)
View Source
const (
	FederationResultVersion uint16 = 1
	FederationResultDomain         = "pilot-federation-result-v1"
)
View Source
const (
	MandateDomain         = "pilot-mandate-v1"
	MaxMandateTTL         = 90 * 24 * time.Hour
	MaxMandateActions     = 64
	MaxMandateResources   = 64
	MaxMandateConstraints = 32
	MaxMandateApprovals   = 32
)
View Source
const (
	MandateBundleDomain = "pilot-mandate-bundle-v1"
	MaxMandateBundleTTL = 24 * time.Hour
	MaxBundleMandates   = 256
)
View Source
const (
	ReceiptDomain            = "pilot-receipt-v1"
	ReceiptDisclosureDomain  = "pilot-receipt-v2"
	ReceiptDisclosureVersion = uint16(2)
)
View Source
const (
	UsageExportFailureTransport           = "transport"
	UsageExportFailureRemoteRejected      = "remote_rejected"
	UsageExportFailureInvalidAcknowledged = "invalid_acknowledgement"
	UsageExportFailureAckPersistence      = "ack_persistence"
)
View Source
const (
	ApprovalTransactionDomain = "pilot-approval-transaction-v1"
	ApprovalVoteDomain        = "pilot-approval-vote-v1"
	ApprovalCertificateDomain = "pilot-approval-certificate-v1"
	MaxApprovalTransactionTTL = 7 * 24 * time.Hour
	MaxApprovalKeys           = 32
	MaxApprovalVotes          = 32
)
View Source
const ApprovalCancellationDomain = "pilot-approval-cancellation-v1"
View Source
const (
	// DefaultPresidioMaxBytes bounds the local buffering needed to call
	// Presidio's JSON API. Larger governed objects should be scanned by a
	// streaming local implementation rather than silently truncated.
	DefaultPresidioMaxBytes int64 = 1 << 20
)
View Source
const FederatedContentVersion uint16 = 1
View Source
const MaxReceiptJournalLineBytes = 1 << 20
View Source
const SemanticPolicyContextVersion uint16 = 1
View Source
const UsageKindSemanticEvaluation = "semantic_evaluation"

Variables

This section is empty.

Functions

func HashPayload

func HashPayload(payload []byte) string

HashPayload returns the opaque payload binding placed in Intent.PayloadHash.

func NewNonce

func NewNonce() (string, error)

NewNonce returns a 128-bit random lowercase-hex nonce.

func ReceiptID

func ReceiptID(decisionID, enforcementPoint string) (string, error)

func ReceiptRFC5424

func ReceiptRFC5424(receipt Receipt) (string, error)

ReceiptRFC5424 formats signed enforcement evidence as an RFC 5424 syslog event. It deliberately carries receipt metadata and signature only; raw application payloads are represented by the receipt's signed hashes.

func ReportModelUsage

func ReportModelUsage(ctx context.Context, usage ModelUsage) error

func VerifyApprovedDecision

func VerifyApprovedDecision(intent Intent, initial, final Decision, request ApprovalRequest, grant ApprovalGrant, decisionKey, approvalKey ed25519.PublicKey, now time.Time) error

VerifyApprovedDecision validates the complete local evidence package for a final allow/constrain issued after human approval.

func VerifyApprovedExecution

func VerifyApprovedExecution(intent Intent, transaction ApprovalTransaction, certificate ApprovalCertificate, votes []ApprovalVote, approvalKeys map[string]ed25519.PublicKey, decisionPublicKey ed25519.PublicKey, now time.Time) error

VerifyApprovedExecution binds a fresh workload-signed intent to a long-lived approval certificate. Callers must separately verify the intent signature and atomically consume the transaction before producing side effects.

Types

type ApprovalCancellation

type ApprovalCancellation struct {
	Version         uint16 `json:"version"`
	ID              string `json:"id"`
	TransactionHash string `json:"transaction_hash"`
	TenantID        string `json:"tenant_id"`
	Reason          string `json:"reason"`
	CancelledAt     int64  `json:"cancelled_at"`
	ProviderID      string `json:"provider_id"`
	KeyID           string `json:"key_id"`
	Signature       string `json:"signature"`
}

ApprovalCancellation is a decision-authority-signed terminal transition for an unconsumed approval transaction. It gives operators durable evidence that an approval was deliberately stopped rather than merely left to expire.

func NewApprovalCancellation

func NewApprovalCancellation(transaction ApprovalTransaction, reason string, cancelledAt time.Time, providerID, keyID string) (ApprovalCancellation, error)

func (ApprovalCancellation) Canonical

func (cancellation ApprovalCancellation) Canonical() ([]byte, error)

func (ApprovalCancellation) Hash

func (cancellation ApprovalCancellation) Hash() (string, error)

func (*ApprovalCancellation) Sign

func (cancellation *ApprovalCancellation) Sign(privateKey ed25519.PrivateKey) error

func (*ApprovalCancellation) SignWith

func (cancellation *ApprovalCancellation) SignWith(signer func([]byte) ([]byte, error)) error

func (ApprovalCancellation) Validate

func (cancellation ApprovalCancellation) Validate() error

func (ApprovalCancellation) VerifyFor

func (cancellation ApprovalCancellation) VerifyFor(transaction ApprovalTransaction, decisionPublicKey ed25519.PublicKey, now time.Time) error

type ApprovalCertificate

type ApprovalCertificate struct {
	Version            uint16       `json:"version"`
	ID                 string       `json:"id"`
	TransactionHash    string       `json:"transaction_hash"`
	TenantID           string       `json:"tenant_id"`
	AgentID            string       `json:"agent_id"`
	Outcome            Outcome      `json:"outcome"`
	Constraints        []Constraint `json:"constraints,omitempty"`
	PolicyRevision     uint64       `json:"policy_revision"`
	RevocationEpoch    uint64       `json:"revocation_epoch"`
	ApprovalVoteHashes []string     `json:"approval_vote_hashes"`
	FinalizedAt        int64        `json:"finalized_at"`
	ExpiresAt          int64        `json:"expires_at"`
	ProviderID         string       `json:"provider_id"`
	KeyID              string       `json:"key_id"`
	Signature          string       `json:"signature"`
}

ApprovalCertificate is the decision authority's signed threshold result. It repeats the transaction's exact authority and the sorted vote hashes so an enforcer can verify the workflow without trusting mutable server state.

func IssueApprovalCertificate

func IssueApprovalCertificate(transaction ApprovalTransaction, votes []ApprovalVote, approvalKeys map[string]ed25519.PublicKey, decisionPrivateKey ed25519.PrivateKey, finalizedAt time.Time, providerID, keyID string) (ApprovalCertificate, error)

func NewApprovalCertificate

func NewApprovalCertificate(transaction ApprovalTransaction, votes []ApprovalVote, approvalKeys map[string]ed25519.PublicKey, decisionPublicKey ed25519.PublicKey, finalizedAt time.Time, providerID, keyID string) (ApprovalCertificate, error)

func (ApprovalCertificate) Canonical

func (certificate ApprovalCertificate) Canonical() ([]byte, error)

func (ApprovalCertificate) Hash

func (certificate ApprovalCertificate) Hash() (string, error)

func (*ApprovalCertificate) Sign

func (certificate *ApprovalCertificate) Sign(privateKey ed25519.PrivateKey) error

func (*ApprovalCertificate) SignWith

func (certificate *ApprovalCertificate) SignWith(signer func([]byte) ([]byte, error)) error

func (ApprovalCertificate) Validate

func (certificate ApprovalCertificate) Validate() error

func (ApprovalCertificate) VerifyFor

func (certificate ApprovalCertificate) VerifyFor(transaction ApprovalTransaction, votes []ApprovalVote, approvalKeys map[string]ed25519.PublicKey, decisionPublicKey ed25519.PublicKey, now time.Time) error

type ApprovalGrant

type ApprovalGrant struct {
	Version     uint16       `json:"version"`
	ID          string       `json:"id"`
	RequestHash string       `json:"request_hash"`
	TenantID    string       `json:"tenant_id"`
	AgentID     string       `json:"agent_id"`
	ApproverID  string       `json:"approver_id"`
	Outcome     Outcome      `json:"outcome"`
	Constraints []Constraint `json:"constraints,omitempty"`
	IssuedAt    int64        `json:"issued_at"`
	ExpiresAt   int64        `json:"expires_at"`
	Nonce       string       `json:"nonce"`
	KeyID       string       `json:"key_id"`
	Signature   string       `json:"signature"`
}

ApprovalGrant is a purpose-limited approver signature over one exact ApprovalRequest. It can allow or add constraints; it cannot be reused for a different intent, decision, tenant, or agent.

func NewApprovalGrant

func NewApprovalGrant(request ApprovalRequest, approverID string, outcome Outcome, constraints []Constraint, issuedAt, expiresAt time.Time, nonce, keyID string) (ApprovalGrant, error)

func (ApprovalGrant) Canonical

func (grant ApprovalGrant) Canonical() ([]byte, error)

func (ApprovalGrant) EvidenceReason

func (grant ApprovalGrant) EvidenceReason() (string, error)

func (ApprovalGrant) Hash

func (grant ApprovalGrant) Hash() (string, error)

func (*ApprovalGrant) Sign

func (grant *ApprovalGrant) Sign(privateKey ed25519.PrivateKey) error

func (ApprovalGrant) Validate

func (grant ApprovalGrant) Validate() error

func (ApprovalGrant) VerifyFor

func (grant ApprovalGrant) VerifyFor(request ApprovalRequest, publicKey ed25519.PublicKey, now time.Time) error

type ApprovalRequest

type ApprovalRequest struct {
	Version         uint16 `json:"version"`
	ID              string `json:"id"`
	IntentHash      string `json:"intent_hash"`
	DecisionID      string `json:"decision_id"`
	DecisionHash    string `json:"decision_hash"`
	TenantID        string `json:"tenant_id"`
	AgentID         string `json:"agent_id"`
	PolicyRevision  uint64 `json:"policy_revision"`
	RevocationEpoch uint64 `json:"revocation_epoch"`
	RequestedAt     int64  `json:"requested_at"`
	ExpiresAt       int64  `json:"expires_at"`
}

ApprovalRequest is a deterministic view of one signed approval_required decision. It adds no authority by itself.

func NewApprovalRequest

func NewApprovalRequest(intent Intent, initial Decision) (ApprovalRequest, error)

func (ApprovalRequest) Canonical

func (request ApprovalRequest) Canonical() ([]byte, error)

func (ApprovalRequest) Hash

func (request ApprovalRequest) Hash() (string, error)

func (ApprovalRequest) Validate

func (request ApprovalRequest) Validate() error

func (ApprovalRequest) ValidateFor

func (request ApprovalRequest) ValidateFor(intent Intent, initial Decision) error

type ApprovalTransaction

type ApprovalTransaction struct {
	Version             uint16       `json:"version"`
	ID                  string       `json:"id"`
	InitialDecisionHash string       `json:"initial_decision_hash"`
	TenantID            string       `json:"tenant_id"`
	AgentID             string       `json:"agent_id"`
	Action              string       `json:"action"`
	Resource            string       `json:"resource"`
	PayloadHash         string       `json:"payload_hash"`
	Risk                RiskClass    `json:"risk"`
	Outcome             Outcome      `json:"outcome"`
	Constraints         []Constraint `json:"constraints,omitempty"`
	PolicyRevision      uint64       `json:"policy_revision"`
	RevocationEpoch     uint64       `json:"revocation_epoch"`
	ApproverKeyIDs      []string     `json:"approver_key_ids"`
	RequiredApprovals   uint16       `json:"required_approvals"`
	CreatedAt           int64        `json:"created_at"`
	ExpiresAt           int64        `json:"expires_at"`
	ProviderID          string       `json:"provider_id"`
	KeyID               string       `json:"key_id"`
	Signature           string       `json:"signature"`
}

ApprovalTransaction is a decision-authority-signed, long-lived proposal. Its exact action fields and proposed outcome are the maximum authority that a later threshold certificate can unlock.

func NewApprovalTransaction

func NewApprovalTransaction(intent Intent, initial Decision, outcome Outcome, constraints []Constraint, approverKeyIDs []string, required uint16, createdAt, expiresAt time.Time, providerID, keyID string) (ApprovalTransaction, error)

func (ApprovalTransaction) Canonical

func (transaction ApprovalTransaction) Canonical() ([]byte, error)

func (ApprovalTransaction) Hash

func (transaction ApprovalTransaction) Hash() (string, error)

func (ApprovalTransaction) MatchesIntent

func (transaction ApprovalTransaction) MatchesIntent(intent Intent) error

func (*ApprovalTransaction) Sign

func (transaction *ApprovalTransaction) Sign(privateKey ed25519.PrivateKey) error

func (*ApprovalTransaction) SignWith

func (transaction *ApprovalTransaction) SignWith(signer func([]byte) ([]byte, error)) error

func (ApprovalTransaction) Validate

func (transaction ApprovalTransaction) Validate() error

func (ApprovalTransaction) Verify

func (transaction ApprovalTransaction) Verify(publicKey ed25519.PublicKey, now time.Time) error

type ApprovalVote

type ApprovalVote struct {
	Version         uint16             `json:"version"`
	ID              string             `json:"id"`
	TransactionHash string             `json:"transaction_hash"`
	TenantID        string             `json:"tenant_id"`
	ApproverID      string             `json:"approver_id"`
	Choice          ApprovalVoteChoice `json:"choice"`
	IssuedAt        int64              `json:"issued_at"`
	ExpiresAt       int64              `json:"expires_at"`
	Nonce           string             `json:"nonce"`
	KeyID           string             `json:"key_id"`
	Signature       string             `json:"signature"`
}

ApprovalVote is one purpose-limited approval-key vote over an exact transaction. Distinct key IDs, not self-asserted display names, satisfy the threshold.

func NewApprovalVote

func NewApprovalVote(transaction ApprovalTransaction, approverID string, choice ApprovalVoteChoice, issuedAt, expiresAt time.Time, nonce, keyID string) (ApprovalVote, error)

func (ApprovalVote) Canonical

func (vote ApprovalVote) Canonical() ([]byte, error)

func (ApprovalVote) Hash

func (vote ApprovalVote) Hash() (string, error)

func (*ApprovalVote) Sign

func (vote *ApprovalVote) Sign(privateKey ed25519.PrivateKey) error

func (*ApprovalVote) SignWith

func (vote *ApprovalVote) SignWith(signer func([]byte) ([]byte, error)) error

func (ApprovalVote) Validate

func (vote ApprovalVote) Validate() error

func (ApprovalVote) VerifyFor

func (vote ApprovalVote) VerifyFor(transaction ApprovalTransaction, publicKey ed25519.PublicKey, now time.Time) error

type ApprovalVoteChoice

type ApprovalVoteChoice string
const (
	ApprovalVoteApprove ApprovalVoteChoice = "approve"
	ApprovalVoteReject  ApprovalVoteChoice = "reject"
)

type AuthorityCeiling

type AuthorityCeiling interface {
	Check(ctx context.Context, intent Intent, decision Decision) error
}

AuthorityCeiling checks the tenant's local mandate and deterministic policy. A provider decision is usable only when this local ceiling also permits it.

type Authorizer

type Authorizer interface {
	Authorize(context.Context, Intent) (Decision, error)
}

Authorizer is the complete provider hook. A deterministic local evaluator, managed policy service, or semantic/LLM evaluator implements the same one method. Provider transport and billing are deliberately outside this API.

type BatchEvaluationUsageStore

type BatchEvaluationUsageStore interface {
	DurableEvaluationUsageStore
	MarkEvaluationsExported(context.Context, []string) error
}

BatchEvaluationUsageStore atomically acknowledges a delivered cohort. It is optional so file-backed and third-party durable stores retain the original per-unit contract.

type Constraint

type Constraint struct {
	Key      string `json:"key"`
	Operator string `json:"operator"`
	Value    string `json:"value"`
}

Constraint narrows an allowed action. Enforcers must understand every returned operator; an unknown constraint is a denial, never an invitation to ignore it.

type Decision

type Decision struct {
	Version         uint16       `json:"version"`
	ID              string       `json:"id"`
	IntentHash      string       `json:"intent_hash"`
	TenantID        string       `json:"tenant_id"`
	AgentID         string       `json:"agent_id"`
	Outcome         Outcome      `json:"outcome"`
	Reasons         []string     `json:"reasons,omitempty"`
	Constraints     []Constraint `json:"constraints,omitempty"`
	PolicyRevision  uint64       `json:"policy_revision"`
	RevocationEpoch uint64       `json:"revocation_epoch"`
	ProviderID      string       `json:"provider_id"`
	IssuedAt        int64        `json:"issued_at"`
	ExpiresAt       int64        `json:"expires_at"`
	KeyID           string       `json:"key_id"`
	Signature       string       `json:"signature"`
}

Decision is an issuer-signed answer tied to one exact Intent hash, tenant, and agent. PolicyRevision and RevocationEpoch make stale-state behavior observable at the enforcement point.

func IssueApprovedDecision

func IssueApprovedDecision(intent Intent, initial Decision, request ApprovalRequest, grant ApprovalGrant, decisionPublicKey, approvalPublicKey ed25519.PublicKey, decisionPrivateKey ed25519.PrivateKey, providerID, decisionKeyID string, now time.Time) (Decision, error)

IssueApprovedDecision is the authority-side transition from an approval_required result plus a valid human grant to a final signed result.

func IssueApprovedDecisionWithSigner

func IssueApprovedDecisionWithSigner(intent Intent, initial Decision, request ApprovalRequest, grant ApprovalGrant, decisionPublicKey, approvalPublicKey ed25519.PublicKey, signer func([]byte) ([]byte, error), providerID, decisionKeyID string, now time.Time) (Decision, error)

IssueApprovedDecisionWithSigner is the remote-key-compatible variant of IssueApprovedDecision. signer signs the final canonical Decision with the same public key that verified the initial authority decision.

func (Decision) Canonical

func (d Decision) Canonical() ([]byte, error)

func (Decision) Hash

func (d Decision) Hash() (string, error)

func (*Decision) Sign

func (d *Decision) Sign(privateKey ed25519.PrivateKey) error

func (*Decision) SignWith

func (d *Decision) SignWith(signer func([]byte) ([]byte, error)) error

SignWith signs the canonical decision using a caller-supplied Ed25519 operation. It lets a hardware-backed or remote key keep private material outside the authority process while preserving the wire signature format.

func (Decision) Validate

func (d Decision) Validate() error

func (Decision) Verify

func (d Decision) Verify(publicKey ed25519.PublicKey, now time.Time) error

func (Decision) VerifyFor

func (d Decision) VerifyFor(intent Intent, publicKey ed25519.PublicKey, now time.Time) error

VerifyFor proves that d is a valid answer for this exact intent. This is the enforcement-point check; verifying the decision signature alone is not sufficient because a valid answer must not be replayed across actions, tenants, agents, or wider time windows.

type DisclosureAuthorizer

type DisclosureAuthorizer interface {
	AuthorizeDisclosure(context.Context, Intent, DisclosureBinding) (Decision, error)
}

DisclosureAuthorizer is an explicit extension point for evaluators that can inspect typed, hash-bound disclosure metadata. A caller must never fall back to Authorize when a DisclosureBinding is present: doing so would silently ignore labels or residency that a required profile expects to govern.

type DisclosureBinding

type DisclosureBinding struct {
	Version       uint16   `json:"version"`
	ContentHash   string   `json:"content_hash"`
	DeclaredBytes uint64   `json:"declared_bytes"`
	ContentType   string   `json:"content_type"`
	Labels        []string `json:"labels"`
	Recipient     string   `json:"recipient"`
	Purpose       string   `json:"purpose"`
	Residency     string   `json:"residency"`
	Filename      string   `json:"filename,omitempty"`
	TransferID    string   `json:"transfer_id,omitempty"`
	// RetentionClass is available only in V2. It is an opaque, tenant-defined
	// class (for example "finance-7y"), not an unsupported claim that the
	// receiver has already performed deletion or legal-hold operations.
	RetentionClass string `json:"retention_class,omitempty"`
}

DisclosureBinding is canonical privacy metadata for a governed disclosure. It deliberately carries hashes and declared characteristics, never the application body. V1 Intents bind it by placing Hash() in PayloadHash; this leaves historical Intent and Receipt canonicalization unchanged.

func (DisclosureBinding) Canonical

func (binding DisclosureBinding) Canonical() ([]byte, error)

func (DisclosureBinding) Hash

func (binding DisclosureBinding) Hash() (string, error)

func (DisclosureBinding) Validate

func (binding DisclosureBinding) Validate() error

func (DisclosureBinding) VerifyIntent

func (binding DisclosureBinding) VerifyIntent(intent Intent) error

VerifyIntent proves that the caller signed this exact disclosure binding into a legacy V1 Intent without changing that Intent's canonical bytes.

type DisclosureCeiling

type DisclosureCeiling interface {
	CheckDisclosure(ctx context.Context, intent Intent, result Decision, disclosure DisclosureBinding) error
}

DisclosureCeiling is the strict local policy extension used when an Intent binds a DisclosureBinding. A receiver must not accept typed metadata using a ceiling that can only inspect the legacy Intent fields, because that would silently drop label, content-type, recipient, purpose, or residency rules.

type DisclosureContentInspector

type DisclosureContentInspector interface {
	InspectDisclosureContent(ctx context.Context, intent Intent, disclosure *DisclosureBinding, contentType, filename string, content io.Reader) error
}

DisclosureContentInspector is a receiver-local DLP hook. It receives the exact bounded payload reader only after a governed transport has verified its Intent, Decision, and (when present) DisclosureBinding. Implementations must not treat a successful inspection as authority to expand a Decision; they can only reject the delivery. The central authority never invokes this interface, keeping ordinary peer payloads out of the decision plane.

type DurableEvaluationUsageStore

type DurableEvaluationUsageStore interface {
	EvaluationJournalStore
	PendingEvaluationRecords(context.Context, int) ([]EvaluationRecord, error)
	MarkEvaluationExported(context.Context, string) error
	PendingEvaluationCount(context.Context) (int, error)
}

DurableEvaluationUsageStore keeps delivery state beside shared evaluation records. It removes local acknowledgement files from multi-replica fleets; duplicate concurrent delivery remains safe through the required remote idempotency key.

type EnforcementResult

type EnforcementResult string
const (
	Enforced        EnforcementResult = "enforced"
	Denied          EnforcementResult = "denied"
	ApprovalPending EnforcementResult = "approval_pending"
	Failed          EnforcementResult = "failed"
)

type Enforcer

type Enforcer struct {
	Provider Authorizer
	Trust    TrustStore
	Ceiling  AuthorityCeiling
	Now      func() time.Time
}

Enforcer performs the complete provider-independent authorization sequence. It intentionally has no billing dependency.

func (*Enforcer) Authorize

func (e *Enforcer) Authorize(ctx context.Context, intent Intent) (Decision, error)

func (*Enforcer) AuthorizeDisclosure

func (e *Enforcer) AuthorizeDisclosure(ctx context.Context, intent Intent, disclosure DisclosureBinding) (Decision, error)

AuthorizeDisclosure requests and locally verifies a Decision for a disclosure-bound Intent. Both the provider and local ceiling must opt in to the explicit disclosure interfaces; falling back to legacy authorization is unsafe because it would ignore typed policy inputs.

func (*Enforcer) Verify

func (e *Enforcer) Verify(ctx context.Context, intent Intent, result Decision) error

Verify applies the local trust, freshness, state-floor, and deterministic ceiling checks to a signed decision obtained through a non-standard path, such as a completed long-running approval workflow. The caller remains responsible for obtaining the decision and for resource-side idempotency.

func (*Enforcer) VerifyDisclosure

func (e *Enforcer) VerifyDisclosure(ctx context.Context, intent Intent, result Decision, disclosure DisclosureBinding) error

VerifyDisclosure applies the normal signed decision checks and an explicit disclosure-aware local ceiling. It rejects a legacy ceiling rather than treating its non-disclosure check as evidence that a typed rule was applied.

type EvaluationFailureMode

type EvaluationFailureMode string

EvaluationFailureMode determines how a semantic evaluator outage is handled for one risk class. Inherit keeps the GuardedAuthorizer's legacy global FailClosed setting; explicit modes let tenants preserve availability for low-risk actions while failing closed for sensitive or irreversible work.

const (
	EvaluationFailureInherit EvaluationFailureMode = ""
	EvaluationFailureOpen    EvaluationFailureMode = "fail_open"
	EvaluationFailureClosed  EvaluationFailureMode = "fail_closed"
)

type EvaluationJournal

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

func OpenEvaluationJournal

func OpenEvaluationJournal(path string) (*EvaluationJournal, error)

func (*EvaluationJournal) EvaluationRecordForIntent

func (journal *EvaluationJournal) EvaluationRecordForIntent(ctx context.Context, tenantID, intentHash string) (EvaluationRecord, bool, error)

func (*EvaluationJournal) EvaluationRecords

func (journal *EvaluationJournal) EvaluationRecords(ctx context.Context, limit int) ([]EvaluationRecord, error)

EvaluationRecords returns records in chronological order. A zero limit returns the complete journal for backwards-compatible single-node usage; positive limits return the most recent bounded window.

func (*EvaluationJournal) RecordEvaluation

func (journal *EvaluationJournal) RecordEvaluation(ctx context.Context, record EvaluationRecord) error

func (*EvaluationJournal) Records

func (journal *EvaluationJournal) Records() []EvaluationRecord

type EvaluationJournalStore

type EvaluationJournalStore interface {
	EvaluationObserver
	EvaluationRecords(context.Context, int) ([]EvaluationRecord, error)
}

EvaluationJournalStore is the durable observation/read contract used by semantic enforcement, usage delivery, and the operator console. File-backed single-node deployments and shared PostgreSQL fleets implement the same interface.

type EvaluationLookupStore

type EvaluationLookupStore interface {
	EvaluationRecordForIntent(context.Context, string, string) (EvaluationRecord, bool, error)
}

EvaluationLookupStore is the indexed correlation contract used by an action trace. It remains optional so external append-only journals stay compatible.

type EvaluationMode

type EvaluationMode string
const (
	EvaluationShadow   EvaluationMode = "shadow"
	EvaluationDenyOnly EvaluationMode = "deny_only"
	EvaluationNarrow   EvaluationMode = "narrow"
)

type EvaluationObserver

type EvaluationObserver interface {
	RecordEvaluation(context.Context, EvaluationRecord) error
}

type EvaluationRecord

type EvaluationRecord struct {
	Version              uint16                `json:"version"`
	ID                   string                `json:"id"`
	IntentHash           string                `json:"intent_hash"`
	TenantID             string                `json:"tenant_id"`
	AgentID              string                `json:"agent_id"`
	Mode                 EvaluationMode        `json:"mode"`
	Identity             EvaluatorIdentity     `json:"identity"`
	BaseOutcome          Outcome               `json:"base_outcome"`
	SemanticOutcome      Outcome               `json:"semantic_outcome,omitempty"`
	AppliedOutcome       Outcome               `json:"applied_outcome"`
	Applied              bool                  `json:"applied"`
	StartedAt            int64                 `json:"started_at_unix_nano"`
	CompletedAt          int64                 `json:"completed_at_unix_nano"`
	TimeoutMillis        int64                 `json:"timeout_millis,omitempty"`
	FailureMode          EvaluationFailureMode `json:"failure_mode,omitempty"`
	SemanticContextHash  string                `json:"semantic_context_hash,omitempty"`
	MatchedClauseIDs     []string              `json:"matched_clause_ids,omitempty"`
	ApprovalPlanID       string                `json:"approval_plan_id,omitempty"`
	ApprovalPlanRevision uint64                `json:"approval_plan_revision,omitempty"`
	ErrorCode            string                `json:"error_code,omitempty"`
	ModelCalls           uint64                `json:"model_calls,omitempty"`
	InputTokens          uint64                `json:"input_tokens,omitempty"`
	OutputTokens         uint64                `json:"output_tokens,omitempty"`
}

func (EvaluationRecord) UsageEvent

func (record EvaluationRecord) UsageEvent() UsageEvent

func (EvaluationRecord) UsageUnitID

func (record EvaluationRecord) UsageUnitID() string

func (EvaluationRecord) Validate

func (record EvaluationRecord) Validate() error

type EvaluationRiskPolicy

type EvaluationRiskPolicy struct {
	Timeout     time.Duration
	FailureMode EvaluationFailureMode
}

EvaluationRiskPolicy overrides semantic timeout and/or outage behavior for a signed Intent risk class. A zero timeout inherits GuardedAuthorizer.Timeout.

type EvaluatorAttestation

type EvaluatorAttestation struct {
	Version      uint16 `json:"version"`
	Endpoint     string `json:"endpoint"`
	Residency    string `json:"residency"`
	AttestorID   string `json:"attestor_id"`
	EvidenceHash string `json:"evidence_hash"`
	IssuedAt     int64  `json:"issued_at"`
	ExpiresAt    int64  `json:"expires_at"`
	KeyID        string `json:"key_id"`
	Signature    string `json:"signature"`
}

EvaluatorAttestation is a short-lived, independently signed assertion that an evaluator endpoint is approved for one residency. EvidenceHash binds an external attestation record without embedding operator or payload data in the control request.

func (EvaluatorAttestation) Canonical

func (attestation EvaluatorAttestation) Canonical() ([]byte, error)

func (*EvaluatorAttestation) Sign

func (attestation *EvaluatorAttestation) Sign(privateKey ed25519.PrivateKey) error

func (EvaluatorAttestation) Validate

func (attestation EvaluatorAttestation) Validate() error

func (EvaluatorAttestation) VerifyForEndpoint

func (attestation EvaluatorAttestation) VerifyForEndpoint(endpoint, residency, attestorID, keyID string, publicKey ed25519.PublicKey, now time.Time) error

VerifyForEndpoint proves that a separately pinned attestor approved exactly this evaluator origin and residency at the current time.

type EvaluatorIdentity

type EvaluatorIdentity struct {
	EvaluatorID   string `json:"evaluator_id"`
	Model         string `json:"model"`
	ModelVersion  string `json:"model_version"`
	PromptVersion string `json:"prompt_version"`
}

type FederatedContent

type FederatedContent struct {
	Version    uint16            `json:"version"`
	Disclosure DisclosureBinding `json:"disclosure"`
	Body       []byte            `json:"body"`
}

FederatedContent is the exact exchange body submitted to Pilot's hosted federation boundary. Disclosure is signed into the Intent through Intent.PayloadHash; it in turn binds the body hash, byte length, media type, recipient, purpose, residency, filename, labels, and retention class.

Body is deliberately absent from Decisions, approval transactions, evaluation journals, and action receipts. The hosted exchange repository encrypts it separately for the tenant-scoped operator experience.

func NewFederatedContent

func NewFederatedContent(disclosure DisclosureBinding, body []byte) (FederatedContent, error)

func (FederatedContent) Clone

func (content FederatedContent) Clone() FederatedContent

func (FederatedContent) Validate

func (content FederatedContent) Validate() error

func (FederatedContent) VerifyIntent

func (content FederatedContent) VerifyIntent(intent Intent) error

type FederatedContentAuthorizer

type FederatedContentAuthorizer interface {
	AuthorizeFederatedContent(context.Context, Intent, FederatedContent) (Decision, error)
}

FederatedContentAuthorizer is implemented only by Pilot's hosted exchange evaluation path. It receives the exact body after the caller's signed Intent and hash-bound DisclosureBinding have been verified. Implementations may preserve or narrow authority; content can never be used to expand a signed deterministic result.

type FederationResult

type FederationResult struct {
	Version                uint16                 `json:"version"`
	ID                     string                 `json:"id"`
	ExchangeID             string                 `json:"exchange_id"`
	TenantID               string                 `json:"tenant_id"`
	AgentID                string                 `json:"agent_id"`
	IntentHash             string                 `json:"intent_hash"`
	DecisionID             string                 `json:"decision_id"`
	Status                 FederationResultStatus `json:"status"`
	ErrorCode              string                 `json:"error_code,omitempty"`
	ResponseDisclosureHash string                 `json:"response_disclosure_hash,omitempty"`
	ObservedAt             int64                  `json:"observed_at"`
	KeyID                  string                 `json:"key_id"`
	Signature              string                 `json:"signature"`
}

FederationResult is the enrolled node's signed post-hook assertion for one hosted exchange. IntentHash and DecisionID bind the exact authorization that preceded execution. ResponseDisclosureHash, when present, binds the complete response content carried beside this object without placing plaintext in logs, receipts, or command telemetry.

func NewFederationResult

func NewFederationResult(exchangeID string, intent Intent, result Decision, status FederationResultStatus, errorCode string, response *DisclosureBinding, observedAt time.Time, keyID string) (FederationResult, error)

func (FederationResult) Canonical

func (result FederationResult) Canonical() ([]byte, error)

func (*FederationResult) Sign

func (result *FederationResult) Sign(privateKey ed25519.PrivateKey) error

func (FederationResult) Validate

func (result FederationResult) Validate() error

func (FederationResult) Verify

func (result FederationResult) Verify(publicKey ed25519.PublicKey, now time.Time) error

type FederationResultStatus

type FederationResultStatus string
const (
	FederationResultSucceeded       FederationResultStatus = "succeeded"
	FederationResultFailed          FederationResultStatus = "failed"
	FederationResultSkipped         FederationResultStatus = "skipped"
	FederationResultDenied          FederationResultStatus = "denied"
	FederationResultApprovalPending FederationResultStatus = "approval_pending"
)

type GuardedAuthorizer

type GuardedAuthorizer struct {
	Base               Authorizer
	Semantic           Authorizer
	Mode               EvaluationMode
	Identity           EvaluatorIdentity
	Observer           EvaluationObserver
	Timeout            time.Duration
	FailClosed         bool
	RiskPolicies       map[RiskClass]EvaluationRiskPolicy
	ContextProvider    SemanticPolicyContextProvider
	RequireObservation bool
	Now                func() time.Time
}

func (*GuardedAuthorizer) Authorize

func (authorizer *GuardedAuthorizer) Authorize(ctx context.Context, intent Intent) (Decision, error)

Authorize evaluates deterministic policy first. Semantic output is never permitted to expand the base result; its strongest production mode can only deny, require approval, or add constraints.

func (*GuardedAuthorizer) AuthorizeDisclosure

func (authorizer *GuardedAuthorizer) AuthorizeDisclosure(ctx context.Context, intent Intent, disclosure DisclosureBinding) (Decision, error)

AuthorizeDisclosure preserves the same deterministic-first and non-expansion guarantees while passing only hash-bound typed metadata to evaluators that explicitly support it. A missing implementation is an error rather than a fallback to Authorize, because a required disclosure profile must not silently drop labels or residency information.

func (*GuardedAuthorizer) AuthorizeFederatedContent

func (authorizer *GuardedAuthorizer) AuthorizeFederatedContent(ctx context.Context, intent Intent, content FederatedContent) (Decision, error)

AuthorizeFederatedContent evaluates the exact exchange body through Pilot's hosted semantic provider. The deterministic base still receives only the signed intent and disclosure metadata, preserving the rule that semantic content analysis can narrow but never create authority.

type Intent

type Intent struct {
	Version  uint16 `json:"version"`
	ID       string `json:"id"`
	TenantID string `json:"tenant_id"`
	AgentID  string `json:"agent_id"`
	Action   string `json:"action"`
	Resource string `json:"resource"`
	// MandateID is optional for compatibility with the original v1 wire
	// profile. Enterprise mandate ceilings require it; when present it changes
	// the canonical signing domain so an unmandated Intent cannot be replayed
	// as a delegated one.
	MandateID   string    `json:"mandate_id,omitempty"`
	Audience    string    `json:"audience,omitempty"`
	Purpose     string    `json:"purpose,omitempty"`
	PayloadHash string    `json:"payload_hash"`
	Risk        RiskClass `json:"risk"`
	IssuedAt    int64     `json:"issued_at"`
	ExpiresAt   int64     `json:"expires_at"`
	Nonce       string    `json:"nonce"`
	KeyID       string    `json:"key_id"`
	Signature   string    `json:"signature"`
}

Intent is the privacy-preserving authorization request. PayloadHash binds the actual action body without requiring the authority plane to retain it.

func (Intent) Canonical

func (i Intent) Canonical() ([]byte, error)

func (Intent) Hash

func (i Intent) Hash() (string, error)

func (*Intent) Sign

func (i *Intent) Sign(privateKey ed25519.PrivateKey) error

func (*Intent) SignWith

func (i *Intent) SignWith(signer func([]byte) ([]byte, error)) error

func (Intent) Validate

func (i Intent) Validate() error

func (Intent) Verify

func (i Intent) Verify(publicKey ed25519.PublicKey, now time.Time) error

type Mandate

type Mandate struct {
	Version           uint16       `json:"version"`
	ID                string       `json:"id"`
	TenantID          string       `json:"tenant_id"`
	SubjectAgentID    string       `json:"subject_agent_id"`
	Actions           []string     `json:"actions"`
	ResourcePrefixes  []string     `json:"resource_prefixes"`
	Audience          string       `json:"audience"`
	Purpose           string       `json:"purpose"`
	Constraints       []Constraint `json:"constraints,omitempty"`
	RequiredApprovals uint16       `json:"required_approvals,omitempty"`
	RevocationEpoch   uint64       `json:"revocation_epoch"`
	IssuedAt          int64        `json:"issued_at"`
	ExpiresAt         int64        `json:"expires_at"`
	KeyID             string       `json:"key_id"`
	Signature         string       `json:"signature"`
}

Mandate is a tenant-issuer-signed delegation to one workload. It is a ceiling, not a provider decision: a matching policy Decision may only be used when it is equal to or narrower than this delegation.

Audience and Purpose are intentionally explicit. A caller cannot use a mandate issued for one counterparty or business purpose with another exact Intent, even where action and resource names happen to match.

func (Mandate) Canonical

func (mandate Mandate) Canonical() ([]byte, error)

func (Mandate) Check

func (mandate Mandate) Check(intent Intent, result Decision) error

Check ensures that result cannot exceed the signed delegation. Denials and approval-required results are always narrower than an executable result; execution after a threshold approval must be represented as a fresh Intent and Decision that still satisfies the mandate's constraints.

func (Mandate) Hash

func (mandate Mandate) Hash() (string, error)

Hash is the stable identifier of the mandate's signed content. It excludes only the transport encoding of Signature: the issuer key ID and every delegated field are part of Canonical and therefore the hash.

func (*Mandate) Sign

func (mandate *Mandate) Sign(privateKey ed25519.PrivateKey) error

func (Mandate) Validate

func (mandate Mandate) Validate() error

func (Mandate) Verify

func (mandate Mandate) Verify(publicKey ed25519.PublicKey, now time.Time) error

type MandateBundle

type MandateBundle struct {
	Version         uint16    `json:"version"`
	TenantID        string    `json:"tenant_id"`
	SubjectAgentID  string    `json:"subject_agent_id"`
	Revision        uint64    `json:"revision"`
	RevocationEpoch uint64    `json:"revocation_epoch"`
	Mandates        []Mandate `json:"mandates"`
	IssuedAt        int64     `json:"issued_at"`
	ExpiresAt       int64     `json:"expires_at"`
	KeyID           string    `json:"key_id"`
	Signature       string    `json:"signature"`
}

MandateBundle is the revisioned, signed distribution snapshot for one workload. A newer valid bundle replaces the whole prior set. Consequently, a mandate that is absent from a higher revision is revoked at the next local refresh, without relying on an unsafe mutable cache-delete signal.

The contained Mandates remain independently signed and verifiable. The bundle signature binds their canonical hashes, agent scope, revision, and revocation epoch so an authority endpoint cannot splice valid mandates from different snapshots or replay an older set after a newer one is installed.

func (MandateBundle) Canonical

func (bundle MandateBundle) Canonical() ([]byte, error)

func (MandateBundle) Hash

func (bundle MandateBundle) Hash() (string, error)

Hash identifies the exact revisioned delegation snapshot for idempotent publication and durable anti-rollback records.

func (*MandateBundle) Sign

func (bundle *MandateBundle) Sign(privateKey ed25519.PrivateKey) error

func (MandateBundle) Validate

func (bundle MandateBundle) Validate() error

func (MandateBundle) Verify

func (bundle MandateBundle) Verify(ctx context.Context, publicKey ed25519.PublicKey, mandateKey MandateKeyResolver, now time.Time) error

Verify verifies the snapshot issuer and every contained mandate at the same point in time. A caller must still compare Revision to its durable local floor before replacing an installed snapshot.

type MandateCeiling

type MandateCeiling struct {
	Store MandateStore
	Keys  MandateKeyResolver
	Next  AuthorityCeiling
	Now   func() time.Time
}

MandateCeiling composes mandate checks ahead of the deterministic policy ceiling. It cannot create authority: it requires a valid signed mandate, makes its restrictions part of the exact Intent, then delegates to Next.

func (MandateCeiling) Check

func (ceiling MandateCeiling) Check(ctx context.Context, intent Intent, result Decision) error

func (MandateCeiling) CheckDisclosure

func (ceiling MandateCeiling) CheckDisclosure(ctx context.Context, intent Intent, result Decision, disclosure DisclosureBinding) error

CheckDisclosure preserves the mandate's exact audience and purpose ceiling, then delegates typed disclosure conditions to the next local policy ceiling. It never falls back to Next.Check when a disclosure is present.

type MandateKeyResolver

type MandateKeyResolver interface {
	MandateKey(context.Context, string, string) (ed25519.PublicKey, error)
}

MandateKeyResolver resolves a current tenant-delegated mandate issuer key. Implementations normally also satisfy MandateStateResolver via the same root-pinned trust store.

type MandateStateResolver

type MandateStateResolver interface {
	MinimumState(context.Context, string) (policyRevision, revocationEpoch uint64, err error)
}

type MandateStore

type MandateStore interface {
	Mandate(context.Context, string, string) (Mandate, error)
}

MandateStore supplies locally retained signed mandates. A missing mandate is a denial; the store can immediately revoke one by deleting it before an updated tenant trust bundle propagates.

type ModelUsage

type ModelUsage struct {
	ModelCalls   uint64 `json:"model_calls,omitempty"`
	InputTokens  uint64 `json:"input_tokens,omitempty"`
	OutputTokens uint64 `json:"output_tokens,omitempty"`
}

ModelUsage is provider-reported usage for one hosted semantic evaluation. It is attached out-of-band to the semantic response and copied into the durable evaluation record; it never influences authorization authority.

func (ModelUsage) Validate

func (usage ModelUsage) Validate() error

type ModelUsageRecorder

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

ModelUsageRecorder is scoped to one authorization attempt. The HTTP semantic client reports the provider response into it, and the guarded authorizer snapshots it before persisting the evaluation.

func WithModelUsageRecorder

func WithModelUsageRecorder(ctx context.Context) (context.Context, *ModelUsageRecorder)

func (*ModelUsageRecorder) Snapshot

func (recorder *ModelUsageRecorder) Snapshot() ModelUsage

type Outcome

type Outcome string
const (
	Allow            Outcome = "allow"
	Deny             Outcome = "deny"
	Constrain        Outcome = "constrain"
	ApprovalRequired Outcome = "approval_required"
)

type PresidioInspector

type PresidioInspector struct {
	Endpoint       string
	HTTPClient     *http.Client
	Language       string
	Entities       []string
	ScoreThreshold float64
	MaxBytes       int64
}

PresidioInspector implements DisclosureContentInspector using a local Presidio Analyzer service. Endpoint is the base service URL; the inspector calls its /analyze endpoint. Run this service on the enforcement host or a private tenant network with transport authentication. It is deliberately an inspection-only hook: any detector result or service failure rejects the delivery, but a clean result never expands the signed Decision.

The adapter accepts only textual and structured-text content types. A required profile consequently fails closed for binary or image files unless the operator provides an appropriate local inspector for those formats.

func (PresidioInspector) InspectDisclosureContent

func (inspector PresidioInspector) InspectDisclosureContent(ctx context.Context, _ Intent, _ *DisclosureBinding, contentType, _ string, content io.Reader) error

InspectDisclosureContent rejects the content when Presidio reports any finding at or above the configured score threshold. Its errors contain no inspected content or detection spans.

func (PresidioInspector) Validate

func (inspector PresidioInspector) Validate() error

Validate checks the static inspector configuration before a transport starts. It intentionally does not make a network call; service availability remains a delivery-time fail-closed condition.

type Receipt

type Receipt struct {
	Version      uint16 `json:"version"`
	ID           string `json:"id"`
	DecisionID   string `json:"decision_id"`
	DecisionHash string `json:"decision_hash"`
	IntentHash   string `json:"intent_hash"`
	// DisclosureHash is required only by receipt V2. It is the hash of the
	// canonical DisclosureBinding, never application plaintext.
	DisclosureHash string `json:"disclosure_hash,omitempty"`
	TenantID       string `json:"tenant_id"`
	MandateID      string `json:"mandate_id,omitempty"`
	// AgentID identifies the local enforcement agent whose delegated receipt
	// key signed this record. The initiating actor remains bound by IntentHash.
	AgentID          string            `json:"agent_id"`
	Outcome          Outcome           `json:"outcome"`
	Result           EnforcementResult `json:"result"`
	EnforcementPoint string            `json:"enforcement_point"`
	ObservedAt       int64             `json:"observed_at"`
	KeyID            string            `json:"key_id"`
	Signature        string            `json:"signature"`
}

Receipt is the signed local evidence that an enforcement point acted on a decision. Its deterministic ID is also the idempotency key for usage metering, so retrying delivery cannot create another billable unit.

func NewDisclosureReceiptForEnforcer

func NewDisclosureReceiptForEnforcer(intent Intent, result Decision, disclosure DisclosureBinding, enforcementAgentID, enforcementPoint, keyID string, observedAt int64, enforced EnforcementResult) (Receipt, error)

NewDisclosureReceiptForEnforcer creates V2 enforcement evidence for a disclosure-bound action. V1 receipt canonical bytes and verification remain unchanged; V2 adds only the signed canonical disclosure hash.

func NewReceipt

func NewReceipt(intent Intent, result Decision, enforcementPoint, keyID string, observedAt int64, enforced EnforcementResult) (Receipt, error)

func NewReceiptForEnforcer

func NewReceiptForEnforcer(intent Intent, result Decision, enforcementAgentID, enforcementPoint, keyID string, observedAt int64, enforced EnforcementResult) (Receipt, error)

NewReceiptForEnforcer creates evidence for an enforcement point operated by enforcementAgentID. This differs from the Intent actor for receiver-side transport controls: a broker or inbox must sign with its own delegated receipt key, not with the sender's key. NewReceipt remains the convenient same-agent form used by wallets and local tools.

func (Receipt) Canonical

func (r Receipt) Canonical() ([]byte, error)

func (Receipt) Hash

func (r Receipt) Hash() (string, error)

func (*Receipt) Sign

func (r *Receipt) Sign(privateKey ed25519.PrivateKey) error

func (*Receipt) SignWith

func (r *Receipt) SignWith(signer func([]byte) ([]byte, error)) error

func (Receipt) UsageUnitID

func (r Receipt) UsageUnitID() string

func (Receipt) Validate

func (r Receipt) Validate() error

func (Receipt) Verify

func (r Receipt) Verify(publicKey ed25519.PublicKey) error

func (Receipt) VerifyFor

func (r Receipt) VerifyFor(intent Intent, result Decision, publicKey ed25519.PublicKey) error

func (Receipt) VerifyForDisclosure

func (r Receipt) VerifyForDisclosure(intent Intent, result Decision, disclosure DisclosureBinding, enforcementAgentID string, publicKey ed25519.PublicKey) error

VerifyForDisclosure proves that V2 evidence was signed for this exact disclosure binding in addition to the Intent and Decision it already binds.

func (Receipt) VerifyForEnforcer

func (r Receipt) VerifyForEnforcer(intent Intent, result Decision, enforcementAgentID string, publicKey ed25519.PublicKey) error

VerifyForEnforcer verifies evidence made by a particular enforcement agent. Callers resolve publicKey through the receipt-key delegation for that agent, while IntentHash and DecisionHash still bind the receipt to the original requesting actor and exact authority decision.

type ReceiptExporter

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

ReceiptExporter retries signed evidence until a collector echoes the exact receipt ID. Its locally fsynced acknowledgement makes retries idempotent across restarts; a collector outage leaves enforcement unaffected.

func NewReceiptExporter

func NewReceiptExporter(config ReceiptExporterConfig) (*ReceiptExporter, error)

func (*ReceiptExporter) ExportOnce

func (exporter *ReceiptExporter) ExportOnce(ctx context.Context) error

func (*ReceiptExporter) Pending

func (exporter *ReceiptExporter) Pending() int

func (*ReceiptExporter) Run

func (exporter *ReceiptExporter) Run(ctx context.Context) error

type ReceiptExporterConfig

type ReceiptExporterConfig struct {
	Journal     *ReceiptJournal
	Endpoint    string
	AckPath     string
	BearerToken string
	HTTPClient  *http.Client
	Interval    time.Duration
	BatchSize   int
}

ReceiptExporterConfig configures asynchronous delivery of already-signed enforcement evidence to a customer retention, SIEM, or billing collector. It is intentionally independent from Enforcer and cannot allow, deny, or delay an action.

type ReceiptJournal

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

ReceiptJournal is an append-only, fsync-before-return local evidence sink. Receipt IDs make retries idempotent; conflicting content for one ID fails.

func OpenReceiptJournal

func OpenReceiptJournal(path string) (*ReceiptJournal, error)

func (*ReceiptJournal) AppendReceipt

func (journal *ReceiptJournal) AppendReceipt(ctx context.Context, receipt Receipt) error

func (*ReceiptJournal) Receipts

func (journal *ReceiptJournal) Receipts() []Receipt

Receipts returns a stable snapshot in journal append order. Exporters use this read-only view outside authorization and enforcement paths; the journal itself remains the durable idempotency authority.

func (*ReceiptJournal) Refresh added in v0.5.13

func (journal *ReceiptJournal) Refresh() error

Refresh discovers complete records appended by another process after this journal was opened. Managed hooks and the long-running daemon deliberately use separate processes, so exporters must refresh before inspecting their in-memory snapshot. Existing records are not rescanned on every poll.

type RiskClass

type RiskClass string
const (
	RiskLow      RiskClass = "low"
	RiskMedium   RiskClass = "medium"
	RiskHigh     RiskClass = "high"
	RiskCritical RiskClass = "critical"
)

type SemanticContextAuthorizer

type SemanticContextAuthorizer interface {
	AuthorizeSemantic(context.Context, Intent, SemanticPolicyContext) (Decision, error)
}

type SemanticContextDisclosureAuthorizer

type SemanticContextDisclosureAuthorizer interface {
	AuthorizeSemanticDisclosure(context.Context, Intent, DisclosureBinding, SemanticPolicyContext) (Decision, error)
}

type SemanticContextFederatedContentAuthorizer

type SemanticContextFederatedContentAuthorizer interface {
	AuthorizeSemanticFederatedContent(context.Context, Intent, FederatedContent, SemanticPolicyContext) (Decision, error)
}

SemanticContextFederatedContentAuthorizer is the Pilot-hosted semantic extension. Workload callers cannot submit SemanticPolicyContext on the public authorization route; the authority supplies reviewed active clauses.

type SemanticPolicyClause

type SemanticPolicyClause struct {
	ID                   string                `json:"id"`
	StatementID          string                `json:"statement_id"`
	StatementRevision    uint64                `json:"statement_revision"`
	Instruction          string                `json:"instruction"`
	Actions              []string              `json:"actions"`
	OutcomeOnMatch       Outcome               `json:"outcome_on_match"`
	ApprovalPlanID       string                `json:"approval_plan_id,omitempty"`
	ApprovalPlanRevision uint64                `json:"approval_plan_revision,omitempty"`
	MetadataFields       []string              `json:"metadata_fields"`
	FailureMode          EvaluationFailureMode `json:"failure_mode"`
	ExpiresAt            int64                 `json:"expires_at,omitempty"`
}

SemanticPolicyClause is reviewed policy input for an optional semantic evaluator. It may only describe a narrowing result. The evaluator still runs below deterministic policy and cannot grant authority.

func (SemanticPolicyClause) Validate

func (clause SemanticPolicyClause) Validate() error

type SemanticPolicyContext

type SemanticPolicyContext struct {
	Version     uint16                 `json:"version"`
	TenantID    string                 `json:"tenant_id"`
	Clauses     []SemanticPolicyClause `json:"clauses"`
	ContextHash string                 `json:"context_hash"`
}

SemanticPolicyContext is generated by the authority from active reviewed statements. Workload callers cannot supply or replace it on the primary authorization endpoint.

func NewSemanticPolicyContext

func NewSemanticPolicyContext(tenantID string, clauses []SemanticPolicyClause) (SemanticPolicyContext, error)

func (SemanticPolicyContext) Hash

func (policy SemanticPolicyContext) Hash() (string, error)

func (SemanticPolicyContext) Validate

func (policy SemanticPolicyContext) Validate() error

func (SemanticPolicyContext) ValidateIntent

func (policy SemanticPolicyContext) ValidateIntent(intent Intent, now int64) error

type SemanticPolicyContextProvider

type SemanticPolicyContextProvider interface {
	SemanticPolicyContext(context.Context, Intent) (SemanticPolicyContext, bool, error)
}

type StaticMandateStore

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

StaticMandateStore holds a reviewed snapshot of signed mandates. It is deliberately immutable: configuration reloads replace the complete store, while every enforcement check still revalidates the mandate against current trust and revocation state through MandateCeiling.

func NewStaticMandateStore

func NewStaticMandateStore(ctx context.Context, tenantID string, mandates []Mandate, keys MandateKeyResolver, state MandateStateResolver, now time.Time) (*StaticMandateStore, error)

NewStaticMandateStore verifies a tenant-scoped mandate snapshot before it can be attached to an enforcement point. An empty snapshot is rejected so a configuration that claims to require delegation cannot silently become permissive.

func NewStaticMandateStoreFromBundle

func NewStaticMandateStoreFromBundle(ctx context.Context, bundle MandateBundle, keys MandateKeyResolver, state MandateStateResolver, now time.Time) (*StaticMandateStore, error)

NewStaticMandateStoreFromBundle verifies a complete signed distribution snapshot before exposing its mandates to an enforcement point. Empty bundles are valid and intentionally create an empty, fail-closed delegation set.

func (*StaticMandateStore) Mandate

func (store *StaticMandateStore) Mandate(_ context.Context, tenantID, mandateID string) (Mandate, error)

Mandate returns an independent copy so a caller cannot alter the retained signed delegation between checks.

type TransferQuotaConfig

type TransferQuotaConfig struct {
	Window     time.Duration
	MaxBytes   uint64
	MaxActions uint64
	MaxSenders int
	Now        func() time.Time
}

TransferQuotaConfig bounds admitted governed transfers for each signed sender identity within a fixed window. It is an enforcement-plane control: only a transport that has already verified an Intent may consume it.

A quota counts admitted attempts, including ones later rejected by a local content inspector or receipt recorder. This deliberately prevents a sender from using repeated failing deliveries to exhaust local inspection work without consuming its own governed-transfer budget.

type TransferQuotaLimiter

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

TransferQuotaLimiter is a bounded, concurrency-safe per-sender admission limiter. It is local state by design. A future shared/durable limiter must preserve these same no-reset-on-clock-rollback semantics.

func NewTransferQuotaLimiter

func NewTransferQuotaLimiter(config TransferQuotaConfig) (*TransferQuotaLimiter, error)

NewTransferQuotaLimiter validates and initializes a local quota limiter.

func (*TransferQuotaLimiter) Allow

func (limiter *TransferQuotaLimiter) Allow(sender string, bytes uint64) error

Allow reserves one admitted transfer for sender. An error means the caller must deny the delivery before any side effect. sender must be a verified signed agent identity, not a transport address or caller-supplied label.

type TrustStore

type TrustStore interface {
	IntentKey(ctx context.Context, tenantID, agentID, keyID string) (ed25519.PublicKey, error)
	DecisionKey(ctx context.Context, tenantID, keyID string) (ed25519.PublicKey, error)
	MinimumState(ctx context.Context, tenantID string) (policyRevision, revocationEpoch uint64, err error)
}

TrustStore resolves keys within an explicit tenant scope and supplies the minimum state an enforcement point is willing to accept.

type UsageEvent

type UsageEvent struct {
	Version         uint16            `json:"version"`
	UnitID          string            `json:"unit_id"`
	Kind            string            `json:"kind"`
	TenantID        string            `json:"tenant_id"`
	AgentID         string            `json:"agent_id"`
	Quantity        uint64            `json:"quantity"`
	OccurredAt      int64             `json:"occurred_at_unix_nano"`
	Evaluator       EvaluatorIdentity `json:"evaluator"`
	Mode            EvaluationMode    `json:"mode"`
	Applied         bool              `json:"applied"`
	BaseOutcome     Outcome           `json:"base_outcome"`
	SemanticOutcome Outcome           `json:"semantic_outcome,omitempty"`
	AppliedOutcome  Outcome           `json:"applied_outcome"`
	ModelCalls      uint64            `json:"model_calls,omitempty"`
	InputTokens     uint64            `json:"input_tokens,omitempty"`
	OutputTokens    uint64            `json:"output_tokens,omitempty"`
}

func (UsageEvent) Validate

func (event UsageEvent) Validate() error

type UsageExportStatus

type UsageExportStatus struct {
	Pending         int    `json:"pending"`
	LastAttemptAt   int64  `json:"last_attempt_at,omitempty"`
	LastSuccessAt   int64  `json:"last_success_at,omitempty"`
	LastFailureAt   int64  `json:"last_failure_at,omitempty"`
	LastFailureCode string `json:"last_failure_code,omitempty"`
}

UsageExportStatus is a bounded operational snapshot. It deliberately exposes no usage payload, endpoint, token, or raw network error: operators need to know whether export is keeping up without turning diagnostics into a second source of sensitive decision context.

func (UsageExportStatus) Validate

func (status UsageExportStatus) Validate() error

type UsageExporter

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

UsageExporter runs outside the authorization call path. It acknowledges a unit locally only after the remote endpoint returns the same unit ID; local ack failure causes a safe idempotent resend.

func NewUsageExporter

func NewUsageExporter(config UsageExporterConfig) (*UsageExporter, error)

func (*UsageExporter) ExportOnce

func (exporter *UsageExporter) ExportOnce(ctx context.Context) error

func (*UsageExporter) Pending

func (exporter *UsageExporter) Pending() int

func (*UsageExporter) Run

func (exporter *UsageExporter) Run(ctx context.Context) error

func (*UsageExporter) Status

func (exporter *UsageExporter) Status() UsageExportStatus

Status returns the current delivery backlog and generic health markers. It is safe to expose on a management read path and never affects evaluation or authorization.

type UsageExporterConfig

type UsageExporterConfig struct {
	Journal     EvaluationJournalStore
	Endpoint    string
	AckPath     string
	BearerToken string
	HTTPClient  *http.Client
	Interval    time.Duration
	BatchSize   int
}

Jump to

Keyboard shortcuts

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