abac

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package abac provides Attribute-Based Access Control (ABAC) policy evaluation.

Policies are predicates (Condition functions) paired with an Allow or Deny effect. The Evaluator applies policies in descending priority order; the first matching policy wins. When no policy matches, the default effect (Deny) is used — this is "deny-by-default" and is the secure default.

Quick start:

store := abac.NewMemoryStore()
store.AddPolicy(abac.Policy{
    ID:       "owner-can-edit",
    Effect:   abac.Allow,
    Priority: 10,
    Condition: abac.And(abac.OwnerIsSubject(), abac.ActionIs("read", "update")),
})

ev := abac.New(store)
decision := ev.Evaluate(abac.Request{
    Subject:  abac.Attributes{"id": "alice"},
    Resource: abac.Attributes{"owner": "alice"},
    Action:   "read",
})

Index

Constants

This section is empty.

Variables

View Source
var ErrPolicyNotFound = errors.New("abac: policy not found")

ErrPolicyNotFound is returned when a requested policy does not exist.

Functions

func Require

func Require(
	ev *Evaluator,
	action string,
	resourceFn func(*http.Request) Attributes,
	subjectFn func(*http.Request) Attributes,
) func(http.Handler) http.Handler

Require returns HTTP middleware that enforces an ABAC policy.

Parameters:

  • ev: the Evaluator to use.
  • action: the operation being performed (e.g. "read").
  • resourceFn: builds the resource Attributes from the request; may be nil.
  • subjectFn: builds the subject Attributes from the request.

The Environment attributes are populated automatically with the remote address, HTTP method, and URL path.

Usage:

mux.Handle("/docs/",
    authmw.JWT(svc)(
        abac.Require(ev, "read",
            func(r *http.Request) abac.Attributes { return loadDoc(r) },
            abac.SubjectFromClaims,
        )(handler),
    ),
)

Types

type Attributes

type Attributes map[string]any

Attributes is a generic map of named values attached to a subject, resource, or environment.

func SubjectFromClaims

func SubjectFromClaims(r *http.Request) Attributes

SubjectFromClaims is a pre-built subject function that maps JWT claims stored in the request context into an Attributes map. It sets "id" to the subject claim and merges all custom claims.

Pass this as the subjectFn argument to Require when using JWT auth.

type Condition

type Condition func(req Request) bool

Condition is a predicate over a Request. It returns true when the policy applies.

func ActionIs

func ActionIs(actions ...string) Condition

ActionIs returns a Condition that matches when Request.Action equals one of the given values.

func And

func And(conditions ...Condition) Condition

And returns a Condition that is true only when all provided conditions are true.

func EnvAttrEquals

func EnvAttrEquals(key string, value any) Condition

EnvAttrEquals returns a Condition that is true when environment[key] == value.

func Not

func Not(condition Condition) Condition

Not negates a condition.

func Or

func Or(conditions ...Condition) Condition

Or returns a Condition that is true when at least one provided condition is true.

func OwnerIsSubject

func OwnerIsSubject() Condition

OwnerIsSubject returns a Condition that is true when resource["owner"] == subject["id"].

func ResourceAttrEquals

func ResourceAttrEquals(key string, value any) Condition

ResourceAttrEquals returns a Condition that is true when resource[key] == value.

func SubjectAttrEquals

func SubjectAttrEquals(key string, value any) Condition

SubjectAttrEquals returns a Condition that is true when subject[key] == value.

func SubjectHasRole

func SubjectHasRole(role string) Condition

SubjectHasRole returns a Condition that checks for a role value in subject["roles"]. It accepts both a []string and a plain string value for subject["roles"].

type Decision

type Decision struct {
	// Allowed is true when access is permitted.
	Allowed bool
	// MatchedPolicy is the ID of the first policy that matched, or empty if none did.
	MatchedPolicy string
}

Decision is the outcome of evaluating a request against the policy store.

type Effect

type Effect int

Effect is the outcome of a policy match.

const (
	// Allow grants the request.
	Allow Effect = iota
	// Deny explicitly rejects the request (takes precedence over Allow at equal priority).
	Deny
)

type Evaluator

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

Evaluator evaluates access requests against a PolicyStore.

func New

func New(store PolicyStore, opts ...EvaluatorOption) *Evaluator

New creates an Evaluator backed by the given PolicyStore. The default behaviour is to deny requests that match no policy.

func (*Evaluator) Allow

func (ev *Evaluator) Allow(req Request) bool

Allow is a convenience wrapper that returns true when the request is permitted.

func (*Evaluator) Evaluate

func (ev *Evaluator) Evaluate(req Request) Decision

Evaluate runs req against all policies and returns a Decision. Policies are evaluated in descending priority order. The first matching policy determines the outcome. If no policy matches, the configured default effect is applied.

type EvaluatorOption

type EvaluatorOption func(*Evaluator)

EvaluatorOption configures an Evaluator.

func WithDefaultAllow

func WithDefaultAllow() EvaluatorOption

WithDefaultAllow changes the default decision to Allow when no policy matches. Use with caution — deny-by-default is the safer choice for most applications.

type MemoryStore

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

MemoryStore is a thread-safe in-memory PolicyStore.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an initialised MemoryStore.

func (*MemoryStore) AddPolicy

func (s *MemoryStore) AddPolicy(policy Policy) error

func (*MemoryStore) Policies

func (s *MemoryStore) Policies() ([]Policy, error)

func (*MemoryStore) RemovePolicy

func (s *MemoryStore) RemovePolicy(id string) error

type Policy

type Policy struct {
	// ID uniquely identifies the policy and appears in Decision.MatchedPolicy.
	ID string
	// Effect is applied when Condition returns true.
	Effect Effect
	// Condition determines whether this policy applies to a given request.
	// A nil Condition matches every request.
	Condition Condition
	// Priority controls evaluation order; higher values are evaluated first.
	Priority int
}

Policy defines a rule that maps a predicate (Condition) to an Effect.

type PolicyStore

type PolicyStore interface {
	// AddPolicy stores a policy. If a policy with the same ID already exists
	// it is overwritten.
	AddPolicy(policy Policy) error
	// RemovePolicy removes the policy with the given ID.
	RemovePolicy(id string) error
	// Policies returns all stored policies ordered by descending Priority.
	Policies() ([]Policy, error)
}

PolicyStore persists and retrieves access policies.

type Request

type Request struct {
	// Subject is the entity requesting access (e.g. the authenticated user).
	Subject Attributes
	// Resource is the object being accessed (e.g. a document or API endpoint).
	Resource Attributes
	// Action is the operation being performed (e.g. "read", "delete").
	Action string
	// Environment holds contextual attributes (e.g. IP address, time of day).
	Environment Attributes
}

Request is the input to a policy evaluation.

Jump to

Keyboard shortcuts

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