policy

package
v2.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 4 Imported by: 2 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 policy decides authorization: may this subject perform this action on this resource?

Engines deny by default. RBAC maps roles to permissions on resource types; Func adapts your own rules (ownership, tenancy, attributes); AnyOf and AllOf compose engines and fail closed on errors.

Index

Examples

Constants

View Source
const Wildcard = "*"

Wildcard matches any action or resource type in a Permission.

Variables

View Source
var ErrInvalidPolicy = errors.New("policy: invalid configuration")

ErrInvalidPolicy is returned by NewRBAC for malformed configuration.

Functions

This section is empty.

Types

type Action

type Action string

Action represents an operation being attempted on a resource.

type Decision

type Decision struct {
	Effect Effect
	Reason string // human-readable explanation; never shown to end users verbatim
}

Decision represents the outcome of an authorization check.

This structure is intentionally simple so it can be:

  • logged
  • audited
  • returned in debug / dry-run modes

func Allow

func Allow(reason string) *Decision

Allow returns an allow decision.

func Deny

func Deny(reason string) *Decision

Deny returns a deny decision.

func (*Decision) Allowed

func (d *Decision) Allowed() bool

Allowed reports whether d is an allow decision. A nil decision is a deny.

type Effect

type Effect string

Effect represents the result of a policy evaluation.

const (
	// EffectAllow indicates the action is permitted.
	EffectAllow Effect = "allow"

	// EffectDeny indicates the action is denied.
	EffectDeny Effect = "deny"
)

type Engine

type Engine interface {
	Evaluate(
		ctx context.Context,
		subject SubjectContext,
		action Action,
		resource Resource,
	) (*Decision, error)
}

Engine defines the contract for authorization decision making.

An Engine evaluates whether a subject can perform an action on a given resource under the current context.

The engine:

  • is invoked AFTER authentication
  • does NOT authenticate users
  • does NOT issue tokens

Implementations must be deterministic and deny by default: anything not explicitly allowed is denied. Returning an error also results in a deny.

var DenyAll Engine = Func(func(context.Context, SubjectContext, Action, Resource) (*Decision, error) {
	return Deny("deny all"), nil
})

DenyAll denies everything. Useful as a placeholder and in tests.

func AllOf

func AllOf(engines ...Engine) Engine

AllOf allows only if every engine allows. The first deny or error wins.

func AnyOf

func AnyOf(engines ...Engine) Engine

AnyOf allows if at least one engine allows. Engines are evaluated in order; an error from any engine evaluated before an allow fails closed.

Example

Editors may write any book; everyone else only the books they own.

package main

import (
	"context"
	"fmt"

	"github.com/kararnab/iam/v2/policy"
)

func main() {
	rbac, _ := policy.NewRBAC(map[string][]policy.Permission{
		"editor": {policy.P("write", "book")},
	})
	owner := policy.Func(func(_ context.Context, s policy.SubjectContext, _ policy.Action, r policy.Resource) (*policy.Decision, error) {
		if r.Attrs["owner_id"] == s.SubjectID {
			return policy.Allow("owner"), nil
		}
		return policy.Deny("not the owner"), nil
	})
	engine := policy.AnyOf(rbac, owner)

	book := policy.Resource{Type: "book", ID: "42", Attrs: map[string]string{"owner_id": "ana"}}
	for _, who := range []string{"ana", "bob"} {
		d, _ := engine.Evaluate(context.Background(), policy.SubjectContext{SubjectID: who}, "write", book)
		fmt.Println(who, d.Allowed())
	}
}
Output:
ana true
bob false

type Func

type Func func(ctx context.Context, subject SubjectContext, action Action, resource Resource) (*Decision, error)

Func adapts a function to Engine. It is the usual way to add ownership or attribute checks, combined with RBAC through AnyOf or AllOf.

func (Func) Evaluate

func (f Func) Evaluate(ctx context.Context, s SubjectContext, a Action, r Resource) (*Decision, error)

Evaluate implements Engine.

type Permission

type Permission struct {
	Action       Action
	ResourceType string
}

Permission grants an action on a resource type. Either may be Wildcard.

func P

func P(action Action, resourceType string) Permission

P is shorthand for a Permission.

func (Permission) String

func (p Permission) String() string

type RBAC

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

RBAC maps roles to permissions on resource types. It denies anything no role grants. It does not look at resource IDs or attributes; combine it with a Func through AnyOf/AllOf for ownership rules.

func NewRBAC

func NewRBAC(roles map[string][]Permission) (*RBAC, error)

NewRBAC validates and copies the role table.

policy.NewRBAC(map[string][]policy.Permission{
    "admin":  {policy.P("*", "*")},
    "editor": {policy.P("read", "book"), policy.P("write", "book")},
    "reader": {policy.P("read", "book")},
})
Example
package main

import (
	"context"
	"fmt"

	"github.com/kararnab/iam/v2/policy"
)

func main() {
	rbac, _ := policy.NewRBAC(map[string][]policy.Permission{
		"admin":  {policy.P(policy.Wildcard, policy.Wildcard)},
		"editor": {policy.P("read", "book"), policy.P("write", "book")},
		"reader": {policy.P("read", "book")},
	})

	reader := policy.SubjectContext{SubjectID: "u1", Roles: []string{"reader"}}
	for _, action := range []policy.Action{"read", "write"} {
		d, _ := rbac.Evaluate(context.Background(), reader, action, policy.Resource{Type: "book"})
		fmt.Printf("%s: %s (%s)\n", action, d.Effect, d.Reason)
	}
}
Output:
read: allow (role "reader" grants read on book)
write: deny (no role grants write on book)

func (*RBAC) Evaluate

func (r *RBAC) Evaluate(_ context.Context, s SubjectContext, a Action, res Resource) (*Decision, error)

Evaluate implements Engine.

func (*RBAC) Grants

func (r *RBAC) Grants(role string, a Action, resourceType string) bool

Grants reports whether role grants action on resourceType, for building UIs (for example to hide buttons). Authorization must still go through Evaluate.

type Resource

type Resource struct {
	Type  string            // e.g. "book", "order", "invoice"
	ID    string            // optional resource identifier
	Attrs map[string]string // resource-specific attributes (owner_id, ...)
}

Resource represents the target of an authorization decision.

IAM does NOT interpret resource semantics. It simply passes context to the policy engine.

type SubjectContext

type SubjectContext struct {
	SubjectID string
	Roles     []string
	Attrs     map[string]string
}

SubjectContext represents the identity context used for policy evaluation.

This is derived from IAM Subject + token claims.

Jump to

Keyboard shortcuts

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