host

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT, MIT Imports: 19 Imported by: ? 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

Index

Constants

View Source
const DefaultCredentialLease = 5 * time.Minute
View Source
const DefaultCredentialLifetime = time.Hour
View Source
const MaxAuditIdentifierBytes = 256

MaxAuditIdentifierBytes caps every untrusted identifier copied to telemetry.

Variables

This section is empty.

Functions

This section is empty.

Types

type Actor

type Actor struct{ Kind, ID string }

Actor identifies a host-verified audit subject, including plugins.

type AuditEvent

type AuditEvent struct {
	Timestamp                           time.Time
	TraceID, RequestID                  string
	Actor                               Actor
	InitiatingCaller                    *Actor
	Owner                               capability.RuntimeIdentity
	Capability, GrantID, PolicyRevision string
	Target, Server, Tool                string
	Effect                              capability.Effect
	Outcome                             capability.Code // Empty means success.
	Reason                              capability.FailureDetail
	EffectState                         capability.EffectState
	Duration                            time.Duration
}

AuditEvent carries only authorization metadata. There is intentionally no arguments, content, arbitrary details, error message or bearer token field. Actor/caller/target identifiers must be host-verified safe identifiers.

type AuditSink

type AuditSink interface {
	Record(context.Context, AuditEvent) error
}

AuditSink must return promptly and honor cancellation. The host chooses bounded buffering/retention; the library creates no unbounded telemetry queue.

type Auditor

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

Auditor isolates telemetry failure from enforcement decisions. The returned bool and failure count report sink failure separately, without exposing the sink's raw error. Presentations may read Failures after their sink recovers.

func NewAuditor

func NewAuditor(sink AuditSink) *Auditor

func (*Auditor) Denials

func (a *Auditor) Denials() map[DenialKey]uint64

Denials returns a copy of per-code/reason counts, independent of sink success.

func (*Auditor) Failures

func (a *Auditor) Failures() uint64

func (*Auditor) Record

func (a *Auditor) Record(ctx context.Context, event AuditEvent) (ok bool)

type Authority

type Authority struct {
	Background              bool
	Authenticated           bool
	Actor                   Subject
	InitiatingCaller        *Subject
	Owner                   capability.RuntimeIdentity
	Audience                string
	Grant                   capability.Grant
	PolicyRevision          string
	Policy                  capability.Scope
	CallerPolicy            *capability.Scope
	TransportScope          *capability.Scope
	LeaseContext            context.Context
	Active, TargetAvailable bool
	ProvisionalLogging      bool
}

Authority is resolved afresh from a trusted host transport/policy adapter. Actor and initiating caller MUST be authenticated by that adapter. Plugin calls require a connection-bound narrow scope, never a bearer credential. LeaseContext is cancelled by lifecycle, grant or binding withdrawal.

type AuthorityResolver

type AuthorityResolver interface {
	Resolve(context.Context, Call) (Authority, error)
}

AuthorityResolver authenticates the actual connection/client, validates its binding and returns a consistent immutable snapshot of current grant, tuple, policy and target state. It must be safe for concurrent calls. Request fields/headers cannot stand in for those host-verified facts. Resolve must honor ctx and return promptly; the library cannot stop an uncooperative host callback without leaving its work running.

type Budget

type Budget interface {
	Reserve(context.Context, Authority, Call) (release func(), err error)
}

Budget reserves cumulative/rate/concurrency budgets before effects. It must be atomic across calls, return a nonnil release function and not block without observing ctx. Reserve must roll back partial work if it panics before returning a release handle. Release must return promptly. Missing adapters fail closed even for byte-only limits.

type Call

type Call struct {
	Capability, GrantID, Operation, Target string
	Effect                                 capability.Effect
	Dimensions                             map[string]string
	Usage                                  map[string]int64
	TraceID, Server, Tool                  string
	RequestID                              capability.RequestID
}

Call contains host-normalized operation demands, never raw RPC arguments. Dimensions and Usage must cover every descriptor dimension/limit; adapters resolve canonical identifiers and actual effects rather than trusting hints.

type Clock

type Clock interface {
	Now() time.Time
	AfterFunc(time.Duration, func()) Timer
}

type Counters

type Counters struct{ Allowed, Denied, AuditFailures, CleanupFailures uint64 }

Counters remain available even when telemetry persistence/presentation fails. Enforcer must not be copied after use. Counts reflect helper admission/outcome events, not downstream application records or a host's complete registry.

type CredentialClaims

type CredentialClaims struct {
	Subject         Subject
	Owner           capability.RuntimeIdentity
	Audience        string
	GrantIDs        []string
	Scopes          map[string]capability.Scope
	CapabilityNames map[string]string
	GrantExpiresAt  map[string]time.Time
}

CredentialClaims are host-authenticated metadata, not a signed wire token. Scopes are keyed by grant ID; each ID must have an explicit scope. Issuers must first resolve scopes under reviewed grants and current caller policy.

type CredentialConfig

type CredentialConfig struct {
	HostInstance, Audience string
	MaxLease               time.Duration
	MaxLifetime            time.Duration
	Clock                  Clock
}

CredentialConfig pins one process epoch and audience. MaxLease is a ceiling; zero chooses five minutes. MaxLifetime bounds the entire renewal chain and defaults to one hour. Clock defaults to wall time without monotonic readings.

type CredentialLease

type CredentialLease struct {
	Claims    CredentialClaims
	ExpiresAt time.Time
	Context   context.Context
	LeaseID   string
}

CredentialLease is a copied authority snapshot with a cancellation context. Callers must reverify at dispatch and after waiting, before mutation. Holding this snapshot alone never protects against a later revocation race.

type CredentialStore

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

CredentialStore retains only token hashes and authority metadata. It must be owned by one live host process, closed on shutdown and never serialized.

func NewCredentialStore

func NewCredentialStore(cfg CredentialConfig) (*CredentialStore, error)

func (*CredentialStore) ActivateOwner

func (s *CredentialStore) ActivateOwner(tuple capability.RuntimeIdentity) error

ActivateOwner installs a host-issued incarnation and cancels all earlier leases for that owner. Repeating the current activation is idempotent; a fenced generation cannot be resurrected or a counter reset within an epoch.

func (*CredentialStore) Close

func (s *CredentialStore) Close()

func (*CredentialStore) Issue

Issue accepts claims from a trusted issuer after host authentication/approval. The library cannot authenticate a control channel or infer reviewed policy.

func (*CredentialStore) Renew

func (s *CredentialStore) Renew(token string, next CredentialClaims, lease time.Duration) (IssuedCredential, error)

Renew rotates the credential on an authenticated live owner/control channel. The adapter must verify that channel before invoking this method. Subject, tuple and audience are immutable; grants/scopes may only narrow. Old leases are cancelled immediately after the replacement is issued successfully.

func (*CredentialStore) Revoke

func (s *CredentialStore) Revoke(token string)

func (*CredentialStore) RevokeGrant

func (s *CredentialStore) RevokeGrant(owner capability.RuntimeIdentity, grantID string)

RevokeGrant withdraws credentials referencing a specific grant in one tuple.

func (*CredentialStore) RevokeLease

func (s *CredentialStore) RevokeLease(leaseID string)

RevokeLease withdraws the current token in a renewal chain by non-secret ID.

func (*CredentialStore) RevokeOwner

func (s *CredentialStore) RevokeOwner(tuple capability.RuntimeIdentity)

RevokeOwner fences exactly one incarnation; stale cleanup cannot revoke its replacement. Use this for lifecycle stop/disable/unload; client or grant withdrawal uses the selective revocation methods below.

func (*CredentialStore) RevokeSubject

func (s *CredentialStore) RevokeSubject(owner capability.RuntimeIdentity, subject Subject)

RevokeSubject withdraws one verified client without fencing the incarnation.

func (*CredentialStore) Verify

func (s *CredentialStore) Verify(token string, subject Subject, owner capability.RuntimeIdentity, audience string) (CredentialLease, error)

type DenialKey

type DenialKey struct {
	Code   capability.Code
	Reason capability.FailureDetail
}

DenialKey has a bounded vocabulary so malformed telemetry cannot allocate counters per arbitrary user-supplied string.

type Enforcer

type Enforcer struct {
	Catalog  *capability.Catalog
	Resolver AuthorityResolver
	Budget   Budget
	Audit    *Auditor
	Clock    Clock
	// contains filtered or unexported fields
}

func NewEnforcer

func NewEnforcer(cfg EnforcerConfig) (*Enforcer, error)

func (*Enforcer) Counters

func (e *Enforcer) Counters() Counters

func (*Enforcer) RequireCapability

func (e *Enforcer) RequireCapability(ctx context.Context, call Call) (permit *Permit, err error)

RequireCapability performs call-time checks and budget reservation before any application side effect. Use Run for automatic release and success/denial audit.

func (*Enforcer) Run

func (e *Enforcer) Run(ctx context.Context, call Call, fn func(context.Context, *Permit) error) (err error)

Run is the side-effect entry point for RPC/HTTP adapters. It always audits the decision/outcome and releases reservations, including panic/error paths. It preserves a definite successful commit despite a late cancellation; raw callback failures become safe internal errors with an unknown effect state.

type EnforcerConfig

type EnforcerConfig struct {
	HostInstance, Audience string
	Catalog                *capability.Catalog
	Resolver               AuthorityResolver
	Budget                 Budget
	Audit                  *Auditor
	Clock                  Clock
}

EnforcerConfig fixes the host epoch and audience independently of resolver output.

type GrantPlan

type GrantPlan struct {
	Runtime                                       capability.RuntimeIdentity
	Audience, IssuedAt, ExpiresAt, PolicyRevision string
	NewGrantID                                    func() string
}

GrantPlan supplies host-issued identity/time/revision metadata and fresh grant IDs. It does not allocate incarnations or authenticate the requesting plugin.

type IssuedCredential

type IssuedCredential struct {
	LeaseID   string
	ExpiresAt time.Time
	// contains filtered or unexported fields
}

IssuedCredential carries a non-secret lease handle and a one-shot closure. Copies share Reveal state. Encoding and logging redact the credential; nested private-field formatting can print the closure address but cannot print its captured secret. Reveal is the only supported access to the token.

func (IssuedCredential) Format

func (IssuedCredential) Format(state fmt.State, verb rune)

func (IssuedCredential) GoString

func (IssuedCredential) GoString() string

func (IssuedCredential) LogValue

func (IssuedCredential) LogValue() slog.Value

func (IssuedCredential) MarshalJSON

func (IssuedCredential) MarshalJSON() ([]byte, error)

func (IssuedCredential) MarshalText

func (IssuedCredential) MarshalText() ([]byte, error)

func (IssuedCredential) Reveal

func (c IssuedCredential) Reveal() (string, error)

func (IssuedCredential) String

func (IssuedCredential) String() string

type Permit

type Permit struct {
	Context context.Context
	// contains filtered or unexported fields
}

Permit owns a reserved call and observes request/authority/expiry cancellation. Recheck after waiting and under the host's commit/admission guard. Close must be called on every path; it attempts each cleanup callback once, isolates panic and reports cleanup failures separately. Close during Commit cancels work but retains its reservation until the callback actually returns.

func (*Permit) Close

func (p *Permit) Close()

func (*Permit) Commit

func (p *Permit) Commit(fn func(context.Context) error) (err error)

Commit consumes this permit once, rechecks current authority and releases on every path. Call it under the host's commit guard after any wait. A failed attempt cannot be retried through this permit.

func (*Permit) Recheck

func (p *Permit) Recheck() (err error)

type PlanNotice

type PlanNotice struct {
	Capability string
	GrantID    string
	Code       capability.Code
	Narrowed   bool
}

PlanNotice reports either a named refusal (Code set) or an admitted narrowing (Narrowed set with GrantID). Narrowing is never silently hidden.

func ResolveGrants

func ResolveGrants(ctx context.Context, catalog *capability.Catalog, resolver ScopeResolver, requests []Request, plan GrantPlan) (grants capability.GrantSet, notices []PlanNotice, err error)

ResolveGrants intersects requested, supported, approved and policy authority. Optional refusals produce named notices; any required refusal aborts the whole plan. No handler/credential/registration is installed. Hosts call it before spawn and activation, then serialize the shared Grant DTO into the sole Init.

type Request

type Request struct {
	Name          string
	SchemaVersion uint32
	Reason        string
	Optional      bool
	Scope         capability.Scope
}

Request is a host-normalized planning input; it is not an alternative Init wire DTO. Each request resolves independently, including repeated names with distinct operation/target pairs. The host supplies reviewed policy inputs.

type ScopeInputs

type ScopeInputs struct{ Supported, Approved, Policy capability.Scope }

type ScopeResolver

type ScopeResolver interface {
	Scopes(context.Context, Request) (ScopeInputs, error)
}

ScopeResolver must honor cancellation and return promptly. Host policy remains trusted; callback panic aborts planning rather than hiding as denial.

type Subject

type Subject struct {
	Kind SubjectKind
	ID   string
}

type SubjectKind

type SubjectKind string

SubjectKind excludes plugins: plugins use their authenticated stdio binding.

const (
	AgentClient    SubjectKind = "agent"
	SessionClient  SubjectKind = "session"
	MCPProxyClient SubjectKind = "mcp_proxy"
)
const (
	PluginActor SubjectKind = "plugin"
	UserActor   SubjectKind = "user"
)

type Timer

type Timer interface{ Stop() bool }

Timer and Clock permit deterministic expiry tests without changing wall time. AfterFunc must schedule asynchronously, never invoke inline, and must not invoke the callback before the requested duration. Stop must not wait for it.

Directories

Path Synopsis
Package hosttest runs behavioral capability conformance through a host's actual admission, dispatcher, lifecycle and non-plugin bridge adapters.
Package hosttest runs behavioral capability conformance through a host's actual admission, dispatcher, lifecycle and non-plugin bridge adapters.

Jump to

Keyboard shortcuts

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