Help us shape the future of Go! Take the 2026 Go Developer Survey

authorization

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package authorization owns the validity of cached caller permissions.

Index

Constants

View Source
const (
	// AnonymousSubject identifies host-selected anonymous policy, never a bearer hash.
	AnonymousSubject = "local:anonymous"
	// SessionSubjectPrefix separates signed identity sessions from bearer hashes.
	SessionSubjectPrefix = "session:"
	// OperatorSubject identifies verified machine-local operator policy.
	OperatorSubject = "local:operator"
)

Variables

View Source
var (
	// ErrDenied reports an explicitly inactive key or account.
	ErrDenied = errors.New("authorization denied")
	// ErrUnavailable reports an authority or clock that cannot establish permission.
	ErrUnavailable = errors.New("authorization authority unavailable")
	// ErrWithdrawn reports a fence change after a load or receipt.
	ErrWithdrawn = errors.New("authorization changed during use")
	// ErrExpired reports the end of the verified permission interval.
	ErrExpired = errors.New("authorization validity expired")
	// ErrEvidence reports incomplete or incompatible authority evidence.
	ErrEvidence = errors.New("authorization evidence is invalid")
)
View Source
var ErrCapacity = errors.New("authorization working set capacity reached")

ErrCapacity reports a bounded working set or cold-load limit.

Functions

This section is empty.

Types

type AccountReader

type AccountReader interface {
	GetByID(context.Context, string) (account.Record, error)
}

AccountReader reads the account policy that a key names.

type AuthoritySet

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

AuthoritySet requires independent evidence from each configured policy owner. Configuration owns this set. A candidate cannot omit an authority requirement.

func NewAuthoritySet

func NewAuthoritySet(fences ...*Fence) (*AuthoritySet, error)

NewAuthoritySet binds at most eight distinct authority epochs without reads.

func (*AuthoritySet) Observe

func (s *AuthoritySet) Observe(evidence Evidence) error

Observe records a verified requirement for one authority only. An epoch change closes that authority until explicit recovery replaces its fence.

type AuthorityStatus

type AuthorityStatus struct {
	Authority  string    `json:"authority"`
	Epoch      string    `json:"epoch"`
	Sequence   uint64    `json:"sequence"`
	CheckedAt  time.Time `json:"checked_at"`
	VerifiedAt time.Time `json:"verified_at"`
	Attempts   uint64    `json:"attempts"`
	Failure    string    `json:"failure"`
	Recovery   string    `json:"recovery"`
}

AuthorityStatus reports this replica's observation, not fleet-wide enforcement. Errors use fixed codes. Storage errors and connection details never enter status.

type Bundle

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

Bundle holds immutable caller records and their permission receipt.

func (*Bundle) Account

func (b *Bundle) Account() account.Record

Account returns caller-owned account policy without exposing cached collections.

func (*Bundle) BudgetPolicy

func (b *Bundle) BudgetPolicy() *limits.BudgetPolicy

BudgetPolicy returns immutable consumption policy from this accepted bundle. The request's permission reader must check the bundle receipt before use.

func (*Bundle) Key

func (b *Bundle) Key() apikey.Record

Key returns caller-owned key policy without exposing cached collections.

func (*Bundle) Permit

func (b *Bundle) Permit() Permit

Permit returns the immutable validity handle for retries and cache delivery.

func (*Bundle) Team

func (b *Bundle) Team() *identity.TeamRecord

Team returns a caller-owned team record. Absence means the key has no team.

type Cache

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

Cache owns a bounded active-caller working set. NewCache does not read storage.

func NewCache

func NewCache(source Source, authorities *AuthoritySet, limits CacheLimits, clock Clock, elapsed ElapsedClock) (*Cache, error)

NewCache requires explicit limits and a clock-health provider.

func (*Cache) CheckDeadline

func (c *Cache) CheckDeadline(deadline time.Time) error

CheckDeadline verifies an external expiry against the configured clock margin. It does not renew a policy receipt or read storage.

func (*Cache) Close

func (c *Cache) Close()

Close cancels owned loads, revokes outstanding receipts, and waits for workers.

func (*Cache) Ready

func (c *Cache) Ready() bool

Ready checks shared admission prerequisites without loading caller policy. It neither reads storage nor creates or renews permission receipts.

func (*Cache) Resolve

func (c *Cache) Resolve(ctx context.Context, identity Identity) (*Bundle, error)

Resolve returns a valid memory bundle or joins one bounded cold load. A caller's cancellation does not cancel work that other callers share.

func (*Cache) Status

func (c *Cache) Status() Status

Status reads bounded memory without renewing receipts or querying authorities.

type CacheLimits

type CacheLimits struct {
	Entries            int
	Bytes              int
	BundleBytes        int
	ConcurrentLoads    int
	TenantLoads        int
	LoadTimeout        time.Duration
	PermissionLifetime time.Duration
	ClockUncertainty   time.Duration
}

CacheLimits bounds resident records and concurrent cold loads. Bytes measures encoded policy bytes, not total Go heap consumption.

type Candidate

type Candidate struct {
	Principal *identity.UserRecord
	Key       apikey.Record
	Account   account.Record
	Team      *identity.TeamRecord
	Evidence  []Evidence
}

Candidate contains one coherent source read with explicit dependency revisions. A nil team confirms absence only when the key has no team dependency.

type Clock

type Clock func() (time.Time, bool)

Clock supplies current time and the deployment's clock-health decision. It must support concurrent calls without blocking or storage reads.

type ElapsedClock

type ElapsedClock func() (time.Duration, bool)

ElapsedClock reads a process-local counter that includes system sleep. It must support concurrent calls without file or network reads.

type Evidence

type Evidence struct {
	Authority  string
	Epoch      string
	Sequence   uint64
	VerifiedAt time.Time
	ValidUntil time.Time
}

Evidence records a verified authority receipt, not a cache access time. The repository adapter must prove its epoch and sequence before publication.

type Fence

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

Fence prevents publication across local mutations and missed-update recovery. One deployment authority owns one fence. It holds no caller records.

func NewFence

func NewFence(authority, epoch string) *Fence

NewFence creates an authority fence before any callers load state.

func (*Fence) BeginMutation

func (f *Fence) BeginMutation() func()

BeginMutation revokes existing receipts before a repository mutation starts. Call the returned function after either success or failure. It is idempotent. A failed mutation still requires fresh evidence before admission resumes.

func (*Fence) Require

func (f *Fence) Require(sequence uint64) error

Require records a verified withdrawal before replacement data can activate. The caller must authenticate the sequence within this fence's authority epoch.

func (*Fence) Start

func (f *Fence) Start() (Ticket, error)

Start refuses loads during a local mutation or recovery operation.

func (*Fence) Withdraw

func (f *Fence) Withdraw()

Withdraw closes an authority until explicit recovery constructs a new fence.

type GrantReader

type GrantReader interface {
	ResolveAccount(context.Context, string, string) (string, error)
}

GrantReader resolves an account through direct and membership grants.

type Identity

type Identity struct {
	Tenant  string
	Subject string
}

Identity scopes one authenticated caller lookup. Tenant must come from trusted routing. An unresolved bearer lookup uses an empty tenant until its source verifies ownership.

type KeyReader

type KeyReader interface {
	GetByHash(context.Context, string) (apikey.Record, error)
}

KeyReader resolves the durable key policy by its authentication hash.

type LocalKeys

type LocalKeys struct {
	Keys      KeyReader
	Anonymous apikey.APIKey
}

LocalKeys resolves host policy without storing synthetic credentials. Only authentication middleware can select these non-hash subjects.

func (LocalKeys) GetByHash

func (s LocalKeys) GetByHash(ctx context.Context, hash string) (apikey.Record, error)

GetByHash delegates bearer hashes and supplies the host's fixed local identities.

type Monitor

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

Monitor checks durable revisions independently of requests and notifications. It never extends an existing permission receipt.

func NewMonitor

func NewMonitor(owners []WatchedAuthority, authorities *AuthoritySet, interval, timeout time.Duration) (*Monitor, error)

NewMonitor validates its fixed authority set without reading storage or starting work.

func (*Monitor) Close

func (m *Monitor) Close(ctx context.Context) error

Close cancels and joins workers. Callers can retry after a timeout.

func (*Monitor) Start

func (m *Monitor) Start(parent context.Context)

Start starts one bounded worker per authority. Repeated calls start no extra work.

func (*Monitor) Status

func (m *Monitor) Status() []AuthorityStatus

Status copies observation data without storage reads or evidence renewal.

type Permit

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

Permit requires every authority receipt to remain valid. Its private receipts cannot change after publication.

func (Permit) Check

func (p Permit) Check(now time.Time, healthy bool) error

Check rechecks every owner before admission, retries, and cached response delivery.

func (Permit) Deadline

func (p Permit) Deadline() time.Time

Deadline returns the earliest authority deadline.

func (Permit) Evidence

func (p Permit) Evidence() []Evidence

Evidence returns caller-owned authority receipts without extending validity.

type PolicyStatus

type PolicyStatus struct {
	Authority string `json:"authority"`
	Sequence  uint64 `json:"sequence"`
	State     string `json:"state"`
	Recovery  string `json:"recovery"`
}

PolicyStatus identifies a prerequisite without exposing caller or storage data.

type Receipt

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

Receipt permits memory reads only during its original verified interval. Copies share the same fence and cannot escape a withdrawal.

func (Receipt) Check

func (r Receipt) Check(now time.Time, clockHealthy bool) error

Check rechecks permission before admission, retries, and cached response delivery. The caller must supply current clock health on every check.

func (Receipt) Deadline

func (r Receipt) Deadline() time.Time

Deadline returns the effective expiry after the clock allowance.

func (Receipt) Evidence

func (r Receipt) Evidence() Evidence

Evidence returns the original receipt without extending its validity.

type RepositorySource

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

RepositorySource checks independent revision markers around one policy read. The constructor starts without I/O. Startup initializes markers and creates fences.

func NewRepositorySource

func NewRepositorySource(s RepositorySources, authorities *AuthoritySet, clock Clock, lifetime time.Duration) (*RepositorySource, error)

NewRepositorySource requires exactly the configured KV and SQL authorities.

func (*RepositorySource) Load

func (s *RepositorySource) Load(ctx context.Context, caller Identity) (Candidate, error)

Load refuses records that span a policy change. The caller can retry the whole load. Observed requirements revoke old permits even when replacement records cannot load.

type RepositorySources

type RepositorySources struct {
	// PrepareBudget runs only during bounded source loads. It may establish
	// accounting history and change a revision, requiring a complete reread.
	PrepareBudget             func(context.Context, *limits.BudgetPolicy) error
	Users                     UserReader
	Grants                    GrantReader
	Keys                      KeyReader
	Accounts                  AccountReader
	Teams                     TeamReader
	KV, SQL                   RevisionReader
	KVAuthority, SQLAuthority string
}

RepositorySources binds policy records to their authoritative revision owners.

type RevisionReader

type RevisionReader interface {
	Read(context.Context) (revision.Stamp, error)
}

RevisionReader reads the current marker from the authoritative store. Replicas and caches without a linearizable read contract cannot supply it.

type Source

type Source interface {
	Load(context.Context, Identity) (Candidate, error)
}

Source loads coherent durable records. Errors never represent confirmed absence. The source must honor cancellation and verify the evidence's authority and sequence.

type Status

type Status struct {
	Ready              bool              `json:"ready"`
	PermissionLifetime time.Duration     `json:"permission_lifetime_ns"`
	ValidBundles       int               `json:"valid_bundles"`
	InvalidBundles     int               `json:"invalid_bundles"`
	LatestDeadline     time.Time         `json:"latest_deadline,omitempty"`
	Authorities        []PolicyStatus    `json:"authorities"`
	Observations       []AuthorityStatus `json:"observations"`
	Recovery           string            `json:"recovery"`
}

Status describes this replica's policy observations, not fleet enforcement. Counts describe cached bundles at observation time, not all deployed callers.

type TeamReader

type TeamReader interface {
	GetByID(context.Context, string) (identity.TeamRecord, error)
}

TeamReader reads a required team and its budget policy.

type Ticket

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

Ticket identifies the local authority state before a durable load starts.

func (Ticket) Accept

func (t Ticket) Accept(evidence Evidence, now time.Time, maxLifetime, uncertainty time.Duration, clockHealthy bool) (Receipt, error)

Accept bounds authority evidence by the configured permission lifetime. Clock uncertainty shortens validity. Unknown clock health refuses acceptance.

type UserReader

type UserReader interface {
	GetBySubject(context.Context, string) (identity.UserRecord, error)
}

UserReader resolves a verified external subject to its durable principal.

type WatchedAuthority

type WatchedAuthority struct {
	Authority string
	Reader    RevisionReader
}

WatchedAuthority binds one durable revision source to its configured owner. The reader must honor context cancellation.

Directories

Path Synopsis
Package revision owns durable authorization change markers.
Package revision owns durable authorization change markers.

Jump to

Keyboard shortcuts

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