authorization

package module
v0.0.0-...-2ce9d76 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 12 Imported by: 0

README

authorization

authorization is an application-oriented authorization engine for typed Go policies. It uses explicit ACL, RBAC, and ABAC models rather than a positional string meta-model or separate policy language.

The current implementation includes:

  • typed requests, decisions, reason codes, and policy identities;
  • deny-overrides, allow-overrides, first-applicable, and priority-order composition;
  • immutable revisioned snapshots with atomic optimistic replacement;
  • bounded batch evaluation and bounded explanation traces;
  • activation windows, fail-closed errors, and default deny;
  • typed, indexed ACL evaluation and resource-ID listing;
  • tenant-safe RBAC with bounded inheritance and assignment administration;
  • closed, typed ABAC conditions with deterministic cost and depth budgets;
  • policy diff, dry-run, and a strict versioned JSON persistence envelope;
  • bounded manifest compilation through an explicit model decoder registry;
  • strict versioned ACL, RBAC, and ABAC model documents for activation;
  • atomic PostgreSQL manifest persistence with optimistic revision checks and a reusable migrations migration;
  • monotonic Valkey invalidation with pub/sub wakeups and durable polling fallback;
  • direct source-of-truth synchronization independent of cache publication;
  • dependency-neutral authenticated-principal mapping;
  • fail-closed standard-library HTTP and native jsonrpc integration;
  • bounded log audit and telemetry metrics/trace adapters; and
  • explicit advisory cache manifest integration.

See the five-minute ACL quickstart and five-minute RBAC quickstart, plus the five-minute ABAC quickstart. Model decoders and the standard HTTP integration are deliberately interface-based so applications can add framework-specific adapters without changing policy semantics.

The complete guide map is in the documentation index. For a compiled multi-model application, see the tenant documents example.

Policy composition and portable format contracts are documented in policy composition and policy format compatibility. PostgreSQL setup and atomic update semantics are covered in PostgreSQL persistence. Cross-process invalidation is covered in Valkey invalidation.

Authentication mapping and transport behavior are documented in authentication integration, HTTP integration, and JSON-RPC integration. Audit, telemetry, and cache boundaries are covered in observability and cache integration. Reusable fixtures, assertions, decision snapshots, and integration conformance checks are documented in authorization testing. Default resource bounds, the benchmark matrix, reference measurements, and scaling guidance are documented in performance and limits.

Repository checks are available as ./scripts/check-format.sh and ./scripts/check-coverage.sh. Integration tests run when POSTGRES_URL or VALKEY_ADDRESS is configured and otherwise skip without contacting local services.

Security boundaries and operational assumptions are documented in the threat model. See SECURITY.md for private reporting guidance and CONTRIBUTING.md for local quality gates. The package is licensed under the MIT License.

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidCombiningAlgorithm indicates an unsupported combining algorithm.
	ErrInvalidCombiningAlgorithm = errors.New("invalid combining algorithm")
	// ErrInvalidOutcome indicates a decision with an unsupported outcome.
	ErrInvalidOutcome = errors.New("invalid decision outcome")
)
View Source
var (
	ErrRevisionConflict     = errors.New("authorization revision conflict")
	ErrRevisionNotMonotonic = errors.New("authorization revision is not monotonic")
)
View Source
var (
	ErrNilAuthorizer                = errors.New("authorization instrumented authorizer is nil")
	ErrNilInstrumenter              = errors.New("authorization instrumenter is nil")
	ErrInvalidInstrumentationConfig = errors.New("authorization instrumentation config is invalid")
)
View Source
var (
	ErrInvalidPolicy           = errors.New("invalid policy")
	ErrDuplicatePolicy         = errors.New("duplicate policy")
	ErrInvalidActivationWindow = errors.New("invalid policy activation window")
	ErrInvalidRevision         = errors.New("invalid policy revision")
)
View Source
var ErrBatchLimitExceeded = errors.New("authorization batch limit exceeded")
View Source
var ErrInvalidFloat = errors.New("attribute float must be finite")
View Source
var ErrInvalidRequest = errors.New("invalid authorization request")
View Source
var ErrNilSnapshot = errors.New("authorization snapshot is nil")
View Source
var ErrPolicyLimitExceeded = errors.New("authorization policy limit exceeded")
View Source
var ErrPolicyPanic = errors.New("authorization policy panicked")

Functions

This section is empty.

Types

type Action

type Action string

type AttributeName

type AttributeName string

type Attributes

type Attributes map[AttributeName]Value

type Authorizer

type Authorizer interface {
	Decide(context.Context, Request) (Decision, error)
}

type CombiningAlgorithm

type CombiningAlgorithm uint8

CombiningAlgorithm determines how multiple policy decisions are resolved.

const (
	DenyOverrides CombiningAlgorithm = iota
	AllowOverrides
	FirstApplicable
	PriorityOrder
)

func (CombiningAlgorithm) String

func (algorithm CombiningAlgorithm) String() string

String returns the stable name of a combining algorithm.

type Decision

type Decision struct {
	Outcome                   Outcome
	Reason                    ReasonCode
	MatchedPolicyIDs          []PolicyID
	MatchedPolicyIDsTruncated bool
	Revision                  Revision
	Trace                     []TraceEntry
	TraceTruncated            bool
}

Decision is the result of one or more policy evaluations.

func Combine

func Combine(algorithm CombiningAlgorithm, decisions []Decision) (Decision, error)

Combine resolves decisions with the selected combining algorithm.

type Engine

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

Engine evaluates every request against one coherent snapshot.

func NewEngine

func NewEngine(snapshot *Snapshot, options ...EngineOption) (*Engine, error)

NewEngine creates an engine from an immutable policy snapshot.

func (*Engine) Decide

func (engine *Engine) Decide(ctx context.Context, request Request) (Decision, error)

Decide evaluates one request and denies when no policy applies.

func (*Engine) DecideBatch

func (engine *Engine) DecideBatch(
	ctx context.Context,
	requests []Request,
) ([]Decision, error)

DecideBatch evaluates a bounded request set against exactly one snapshot.

func (*Engine) ReplaceSnapshot

func (engine *Engine) ReplaceSnapshot(next *Snapshot, expected Revision) error

ReplaceSnapshot atomically installs a newer snapshot when the caller's expected revision still matches the active view.

func (*Engine) Revision

func (engine *Engine) Revision() Revision

Revision returns the revision of the snapshot currently used for new decisions.

type EngineOption

type EngineOption func(*Engine)

func WithClock

func WithClock(clock func() time.Time) EngineOption

WithClock supplies the time used when a request omits Environment.Time.

func WithLimits

func WithLimits(limits Limits) EngineOption

WithLimits configures positive limits and leaves zero-valued fields at safe defaults.

type Environment

type Environment struct {
	Time       time.Time
	Attributes Attributes
}

Environment contains deterministic request-scoped evaluation inputs.

type Evaluator

type Evaluator interface {
	Evaluate(context.Context, Request) (Decision, error)
}

Evaluator is the bounded, I/O-free decision interface implemented by policy models such as ACL, RBAC, and ABAC.

type Event

type Event struct {
	Outcome                   Outcome
	Reason                    ReasonCode
	Revision                  Revision
	MatchedPolicyIDs          []PolicyID
	MatchedPolicyIDsTruncated bool
	TraceCount                int
	TraceTruncated            bool
	Duration                  time.Duration
	Failed                    bool
}

Event contains bounded decision metadata without subject, resource, tenant, attribute, or policy-document contents.

type InstrumentationConfig

type InstrumentationConfig struct {
	Clock        func() time.Time
	MaxPolicyIDs int
}

type Instrumented

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

func NewInstrumented

func NewInstrumented(
	authorizer Authorizer,
	instrumenter Instrumenter,
	config InstrumentationConfig,
) (*Instrumented, error)

func (*Instrumented) Decide

func (instrumented *Instrumented) Decide(
	ctx context.Context,
	request Request,
) (Decision, error)

type Instrumenter

type Instrumenter interface {
	Start(context.Context) (context.Context, func(Event))
}

type Limits

type Limits struct {
	MaxBatchSize        int
	MaxPolicies         int
	MaxTraceSize        int
	MaxMatchedPolicyIDs int
}

Limits bounds work and diagnostic cardinality for one engine.

type Outcome

type Outcome uint8

Outcome is the result of evaluating an authorization policy.

const (
	NotApplicable Outcome = iota
	Allow
	Deny
)

func (Outcome) String

func (outcome Outcome) String() string

type PolicyDefinition

type PolicyDefinition struct {
	ID          PolicyID
	Revision    Revision
	Priority    int
	ActiveFrom  time.Time
	ActiveUntil time.Time
	Metadata    map[string]string
	Evaluator   Evaluator
}

PolicyDefinition binds a stable policy identity to its evaluator.

type PolicyEvaluationError

type PolicyEvaluationError struct {
	PolicyID PolicyID
	Err      error
}

PolicyEvaluationError identifies a failed policy without exposing its internal error text. Unwrap retains programmatic error inspection.

func (*PolicyEvaluationError) Error

func (evaluationError *PolicyEvaluationError) Error() string

func (*PolicyEvaluationError) Unwrap

func (evaluationError *PolicyEvaluationError) Unwrap() error

type PolicyID

type PolicyID string

type PolicyInfo

type PolicyInfo struct {
	ID          PolicyID
	Revision    Revision
	Priority    int
	ActiveFrom  time.Time
	ActiveUntil time.Time
	Metadata    map[string]string
}

PolicyInfo is the safe, inspectable metadata for one snapshotted policy.

type ReasonCode

type ReasonCode string
const (
	ReasonDefaultDeny     ReasonCode = "default-deny"
	ReasonInvalidRequest  ReasonCode = "invalid-request"
	ReasonEvaluationError ReasonCode = "evaluation-error"
	ReasonContextCanceled ReasonCode = "context-canceled"
	ReasonPolicyInactive  ReasonCode = "policy-inactive"
	ReasonPolicyStale     ReasonCode = "policy-stale"
)

type Request

type Request struct {
	Subject     Subject
	Action      Action
	Resource    Resource
	Tenant      TenantID
	Environment Environment
	Attributes  Attributes
}

Request contains the stable, typed inputs shared by every policy model. An empty tenant denotes an explicitly global request scope.

func (Request) Validate

func (request Request) Validate() error

Validate rejects incomplete requests before any policy is evaluated.

type Resource

type Resource struct {
	Type       ResourceType
	ID         ResourceID
	Attributes Attributes
}

Resource identifies either a resource type or a concrete resource instance. An empty ID intentionally represents the entire resource type.

type ResourceID

type ResourceID string

type ResourceType

type ResourceType string

type Revision

type Revision uint64

type Snapshot

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

Snapshot is one coherent, immutable policy view used for a complete decision. Its policy contents are intentionally private.

func NewSnapshot

func NewSnapshot(
	revision Revision,
	algorithm CombiningAlgorithm,
	definitions ...PolicyDefinition,
) (*Snapshot, error)

NewSnapshot validates and creates a revisioned policy snapshot.

func (*Snapshot) Algorithm

func (snapshot *Snapshot) Algorithm() CombiningAlgorithm

Algorithm returns the snapshot's validated combining algorithm.

func (*Snapshot) Policies

func (snapshot *Snapshot) Policies() []PolicyInfo

Policies returns a defensive copy of inspectable policy metadata.

func (*Snapshot) Revision

func (snapshot *Snapshot) Revision() Revision

Revision returns the immutable snapshot revision.

type Subject

type Subject struct {
	Kind       SubjectKind
	ID         SubjectID
	Groups     []SubjectID
	Attributes Attributes
}

Subject identifies the principal making an authorization request.

type SubjectID

type SubjectID string

type SubjectKind

type SubjectKind string

SubjectKind identifies the application-defined kind of principal.

const (
	SubjectUser           SubjectKind = "user"
	SubjectServiceAccount SubjectKind = "service-account"
	SubjectAPIKey         SubjectKind = "api-key"
	SubjectGroup          SubjectKind = "group"
)

type TenantID

type TenantID string

type TraceEntry

type TraceEntry struct {
	PolicyID PolicyID
	Outcome  Outcome
	Reason   ReasonCode
}

TraceEntry records one policy result without request or attribute values.

type ValidationError

type ValidationError struct {
	Field string
}

ValidationError identifies an invalid public input without including its potentially sensitive value.

func (*ValidationError) Error

func (validationError *ValidationError) Error() string

func (*ValidationError) Unwrap

func (validationError *ValidationError) Unwrap() error

type Value

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

Value is an immutable typed attribute value. Its zero value represents an invalid or missing value and is distinct from explicit null.

func BoolValue

func BoolValue(value bool) Value

func FloatValue

func FloatValue(value float64) (Value, error)

func IPValue

func IPValue(value netip.Addr) Value

func IntValue

func IntValue(value int64) Value

func MustFloatValue

func MustFloatValue(value float64) Value

func NullValue

func NullValue() Value

func StringSetValue

func StringSetValue(values []string) Value

func StringValue

func StringValue(value string) Value

func TimeValue

func TimeValue(value time.Time) Value

func (Value) Bool

func (value Value) Bool() (bool, bool)

func (Value) CollectionLength

func (value Value) CollectionLength() (int, bool)

CollectionLength reports the cardinality of collection values.

func (Value) Compare

func (value Value) Compare(other Value) (int, bool)

Compare orders comparable values of the same kind without coercion.

func (Value) Equal

func (value Value) Equal(other Value) bool

Equal reports structural equality without type coercion.

func (Value) Float

func (value Value) Float() (float64, bool)

func (Value) IP

func (value Value) IP() (netip.Addr, bool)

func (Value) Int

func (value Value) Int() (int64, bool)

func (Value) Kind

func (value Value) Kind() ValueKind

func (Value) String

func (value Value) String() (string, bool)

func (Value) StringSet

func (value Value) StringSet() ([]string, bool)

func (Value) Time

func (value Value) Time() (time.Time, bool)

type ValueKind

type ValueKind uint8

ValueKind is the closed set of supported attribute representations.

const (
	ValueMissing ValueKind = iota
	ValueNull
	ValueString
	ValueBool
	ValueInt
	ValueFloat
	ValueTime
	ValueIP
	ValueStringSet
)

Directories

Path Synopsis
Package abac provides a bounded, closed expression model for typed attribute-based authorization.
Package abac provides a bounded, closed expression model for typed attribute-based authorization.
Package acl provides typed subject-to-resource access control lists.
Package acl provides typed subject-to-resource access control lists.
Package authcache provides explicit advisory cache adapters for portable policy manifests.
Package authcache provides explicit advisory cache adapters for portable policy manifests.
Package authhttp provides the canonical net/http authorization adapter.
Package authhttp provides the canonical net/http authorization adapter.
Package authlog emits bounded authorization audit events through log/slog.
Package authlog emits bounded authorization audit events through log/slog.
Package authn maps immutable authenticated principals into authorization subjects without making authentication depend on authorization.
Package authn maps immutable authenticated principals into authorization subjects without making authentication depend on authorization.
Package authorizationtest provides deterministic fixtures, assertions, and conformance checks for authorization integrations.
Package authorizationtest provides deterministic fixtures, assertions, and conformance checks for authorization integrations.
Package authotel records bounded authorization metrics and traces through standard OpenTelemetry providers, including providers owned by telemetry.
Package authotel records bounded authorization metrics and traces through standard OpenTelemetry providers, including providers owned by telemetry.
Package authrpc provides fail-closed jsonrpc authorization middleware.
Package authrpc provides fail-closed jsonrpc authorization middleware.
examples
tenant_documents command
Package main demonstrates composing tenant RBAC, resource ACL, and a trusted ownership attribute under deny-overrides semantics.
Package main demonstrates composing tenant RBAC, resource ACL, and a trusted ownership attribute under deny-overrides semantics.
Package httpauth provides fail-closed net/http authorization integration.
Package httpauth provides fail-closed net/http authorization integration.
Package policy provides snapshot inspection, diff, dry-run, and portable policy manifest contracts.
Package policy provides snapshot inspection, diff, dry-run, and portable policy manifest contracts.
Package postgres persists complete policy manifests atomically in PostgreSQL.
Package postgres persists complete policy manifests atomically in PostgreSQL.
Package rbac provides typed roles, permissions, assignments, and bounded role inheritance.
Package rbac provides typed roles, permissions, assignments, and bounded role inheritance.
Package valkey distributes monotonic policy revision invalidations through Valkey without relying on lossy pub/sub delivery for correctness.
Package valkey distributes monotonic policy revision invalidations through Valkey without relying on lossy pub/sub delivery for correctness.

Jump to

Keyboard shortcuts

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