access

package
v0.24.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EventAccessAuthorized is emitted when an authorization check succeeds.
	// Payload: *AccessAuthorizedEventPayload
	EventAccessAuthorized = "access:authorized"

	// EventAccessDenied is emitted when an authorization check is denied.
	// Payload: *AccessDeniedEventPayload
	EventAccessDenied = "access:denied"

	// EventRoleCreated is emitted when a new role is registered in AccessControl.
	// Payload: *RoleCreatedEventPayload
	EventRoleCreated = "access:role:created"

	// EventRoleDeleted is emitted when a role is removed from AccessControl.
	// Payload: *RoleDeletedEventPayload
	EventRoleDeleted = "access:role:deleted"
)

Event topics dispatched by the Access Control plugin over the shared EventBus.

View Source
const (
	// ErrPrefixUnknownResource is the error prefix when a requested resource is not recognized under ConnectorAND.
	// Matches: "You are not allowed to access resource: <resource>"
	ErrPrefixUnknownResource = "You are not allowed to access resource: "

	// ErrPrefixUnauthorized is the error prefix when a requested action on a known resource is not allowed under ConnectorAND.
	// Matches: "unauthorized to access resource \"<resource>\""
	ErrPrefixUnauthorized = "unauthorized to access resource "

	// ErrMsgNotAuthorized is the generic error message when no resources or actions match under ConnectorOR or empty request.
	ErrMsgNotAuthorized = "Not authorized"

	// ErrMsgInvalidRequest is the error message for malformed access control requests.
	ErrMsgInvalidRequest = "Invalid access control request"
)

Standard error messages matching Better Auth TypeScript specifications.

View Source
const (
	// ContextKeyAccessControl is the key used to store and retrieve the AccessControl instance from plugin.Context.
	ContextKeyAccessControl = "access:control"

	// ContextKeySubjectRoles is the context key used by context helpers to pass subject roles.
	ContextKeySubjectRoles = "access:subject:roles"

	// Extra metadata keys for audit events.
	ExtraKeyResource = "resource"
	ExtraKeyActions  = "actions"
	ExtraKeyRoles    = "roles"
	ExtraKeySubject  = "subject"
	ExtraKeyReason   = "reason"
)

Shared plugin context and extra metadata keys.

View Source
const (
	// WildcardAll matches any resource or action when wildcards are enabled.
	WildcardAll = "*"
)

Wildcard constants for granting blanket permissions.

Variables

View Source
var (
	// ErrAccessDenied is returned by guards when authorization fails.
	ErrAccessDenied = errors.New("access denied: insufficient permissions")

	// ErrNoSubjectRoles is returned when no roles could be resolved for the subject.
	ErrNoSubjectRoles = errors.New("access denied: no roles associated with subject")
)

Functions

func ContextRoleResolver

func ContextRoleResolver(ctx context.Context) ([]string, error)

ContextRoleResolver is a built-in resolver that retrieves roles stored in the context via WithSubjectRoles.

func RequirePermission

func RequirePermission(ac *AccessControl, resolver SubjectPermissionResolver, resource string, actions ...string) func(ctx context.Context) error

RequirePermission returns a guard function that validates whether the subject has the specified actions on a resource.

func RequirePermissionHTTP added in v0.20.0

func RequirePermissionHTTP(ac *AccessControl, resolver SubjectPermissionResolver, resource string, actions ...string) func(next http.Handler) http.Handler

RequirePermissionHTTP returns a net/http middleware handler that validates whether the resolved subject has permission for a resource and actions.

func RequireRequest

func RequireRequest(ac *AccessControl, resolver SubjectPermissionResolver, req AuthorizeRequest, connector ...Connector) func(ctx context.Context) error

RequireRequest returns a guard function that validates an AuthorizeRequest for the resolved subject.

func SubjectRolesFromContext

func SubjectRolesFromContext(ctx context.Context) ([]string, bool)

SubjectRolesFromContext extracts attached subject roles from a context.

func WithSubjectRoles

func WithSubjectRoles(ctx context.Context, roles ...string) context.Context

WithSubjectRoles attaches a list of subject role identifiers to a context.

Types

type AccessAuthorizedEventPayload

type AccessAuthorizedEventPayload struct {
	// Roles contains the role identifiers evaluated.
	Roles []string

	// Request is the authorization request that was evaluated.
	Request AuthorizeRequest

	// Extra provides optional contextual metadata.
	Extra map[string]any
}

AccessAuthorizedEventPayload contains context about a successful authorization evaluation.

type AccessControl

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

AccessControl is the central coordinator managing master statements schemas, registered roles, and multi-role evaluations.

func CreateAccessControl

func CreateAccessControl(masterStatements Statements, opts ...Option) *AccessControl

CreateAccessControl creates and initializes an AccessControl instance with master statements and options.

func (*AccessControl) AuthorizeRoleString

func (ac *AccessControl) AuthorizeRoleString(roleString string, request AuthorizeRequest, connector ...Connector) AuthorizeResult

AuthorizeRoleString evaluates a comma-separated role string (e.g. "admin,billing_manager") against an AuthorizeRequest.

func (*AccessControl) AuthorizeRoles

func (ac *AccessControl) AuthorizeRoles(roleNames []string, request AuthorizeRequest, connector ...Connector) AuthorizeResult

AuthorizeRoles evaluates an AuthorizeRequest against multiple role names assigned to a subject. Statements from all matched roles are combined with union semantics before evaluation.

func (*AccessControl) DeleteRole

func (ac *AccessControl) DeleteRole(name string) bool

DeleteRole removes a registered role from AccessControl. Returns true if the role existed and was removed.

func (*AccessControl) GetAllRoles

func (ac *AccessControl) GetAllRoles() map[string]*Role

GetAllRoles returns a snapshot copy of all registered roles.

func (*AccessControl) GetRole

func (ac *AccessControl) GetRole(name string) (*Role, bool)

GetRole retrieves a registered role by its name.

func (*AccessControl) MasterStatements

func (ac *AccessControl) MasterStatements() Statements

MasterStatements returns an isolated copy of the schema master statements.

func (*AccessControl) MergeRoles

func (ac *AccessControl) MergeRoles(roleNames ...string) (*Role, error)

MergeRoles combines multiple registered roles into a single consolidated Role instance.

func (*AccessControl) MustNewRole

func (ac *AccessControl) MustNewRole(name string, roleStatements Statements) *Role

MustNewRole creates a new role and panics if an error occurs.

func (*AccessControl) NewAnonymousRole

func (ac *AccessControl) NewAnonymousRole(roleStatements Statements) (*Role, error)

NewAnonymousRole creates an unregistered Role instance with the given statements.

func (*AccessControl) NewRole

func (ac *AccessControl) NewRole(name string, roleStatements Statements) (*Role, error)

NewRole creates and registers a new Role under the given name after validating against master statements (if strict).

type AccessDeniedEventPayload

type AccessDeniedEventPayload struct {
	// Roles contains the role identifiers evaluated.
	Roles []string

	// Request is the authorization request that failed.
	Request AuthorizeRequest

	// Reason describes why authorization was denied.
	Reason string

	// Extra provides optional contextual metadata.
	Extra map[string]any
}

AccessDeniedEventPayload contains context about a failed authorization evaluation.

type ActionRequest

type ActionRequest struct {
	Actions   []string  `json:"actions"`
	Connector Connector `json:"connector,omitempty"`
}

ActionRequest defines the set of requested actions for a specific resource, along with a local evaluation connector (AND or OR).

func Actions

func Actions(actions ...string) ActionRequest

Actions creates an ActionRequest configured with ConnectorAND.

func ActionsOR

func ActionsOR(actions ...string) ActionRequest

ActionsOR creates an ActionRequest configured with ConnectorOR.

type AuthorizeRequest

type AuthorizeRequest map[string]ActionRequest

AuthorizeRequest defines a map of resource names to their respective action requests.

func Req

func Req(resource string, actions ...string) AuthorizeRequest

Req creates a single-resource AuthorizeRequest with ConnectorAND. Example: access.Req("project", "create", "read")

func ReqOR

func ReqOR(resource string, actions ...string) AuthorizeRequest

ReqOR creates a single-resource AuthorizeRequest with ConnectorOR. Example: access.ReqOR("project", "create", "read")

type AuthorizeRequestBuilder

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

AuthorizeRequestBuilder provides a fluent builder pattern for constructing AuthorizeRequest.

func NewAuthorizeRequest

func NewAuthorizeRequest() *AuthorizeRequestBuilder

NewAuthorizeRequest initializes a new fluent AuthorizeRequestBuilder.

func (*AuthorizeRequestBuilder) Build

Build returns the underlying AuthorizeRequest.

func (*AuthorizeRequestBuilder) Require

func (b *AuthorizeRequestBuilder) Require(resource string, actions ...string) *AuthorizeRequestBuilder

Require adds a resource check with ConnectorAND.

func (*AuthorizeRequestBuilder) RequireOR

func (b *AuthorizeRequestBuilder) RequireOR(resource string, actions ...string) *AuthorizeRequestBuilder

RequireOR adds a resource check with ConnectorOR.

type AuthorizeResult

type AuthorizeResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

AuthorizeResult encapsulates the outcome of an authorization evaluation.

func AuthorizeSubject

func AuthorizeSubject(ctx context.Context, ac *AccessControl, resolver SubjectPermissionResolver, req AuthorizeRequest, connector ...Connector) AuthorizeResult

AuthorizeSubject evaluates an AuthorizeRequest for a subject resolved from context.

func (AuthorizeResult) Err

func (r AuthorizeResult) Err() error

Err converts the AuthorizeResult into a standard Go error if Success is false, or returns nil if successful.

type Config

type Config struct {
	// MasterStatements defines the complete schema of valid resources and permitted actions.
	MasterStatements Statements

	// InitialRoles defines pre-configured roles to register upon instantiation.
	InitialRoles map[string]Statements

	// AllowWildcards determines if the '*' wildcard is recognized for blanket resource/action grants.
	AllowWildcards bool

	// StrictResources enforces that any registered role's statements must strictly exist in MasterStatements.
	StrictResources bool
}

Config defines the configuration options for the AccessControl instance and plugin.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration options.

type Connector

type Connector string

Connector defines the logical boolean evaluation strategy between multiple permissions or resources.

const (
	// ConnectorAND requires that all specified conditions/actions must be satisfied.
	ConnectorAND Connector = "AND"

	// ConnectorOR requires that at least one specified condition/action must be satisfied.
	ConnectorOR Connector = "OR"
)

type Evaluator

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

Evaluator executes access control evaluation algorithms against Statements.

func NewEvaluator

func NewEvaluator(allowWildcards bool) *Evaluator

NewEvaluator creates a new Evaluator instance with the specified wildcard configuration.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(statements Statements, request AuthorizeRequest, globalConnector Connector) AuthorizeResult

Evaluate evaluates an AuthorizeRequest against Statements using the given global Connector. It complies with 100% Better Auth TypeScript parity and short-circuit evaluation.

type Option

type Option func(*Config)

Option represents a functional option for configuring AccessControl.

func WithAllowWildcards

func WithAllowWildcards(allow bool) Option

WithAllowWildcards enables or disables wildcard ('*') handling for resources and actions.

func WithInitialRoles

func WithInitialRoles(roles map[string]Statements) Option

WithInitialRoles registers a set of initial roles during initialization.

func WithMasterStatements

func WithMasterStatements(stmts Statements) Option

WithMasterStatements sets the master statements schema.

func WithStrictResources

func WithStrictResources(strict bool) Option

WithStrictResources enforces that roles cannot grant resources/actions not listed in MasterStatements.

type Plugin

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

Plugin implements the plugin.Plugin interface for Granular Access Control and RBAC/ABAC in go-modular-auth.

func New

func New(masterStatements Statements, opts ...Option) *Plugin

New creates a new Access Control plugin configured with master statements and options.

func NewFromAccessControl

func NewFromAccessControl(ac *AccessControl) *Plugin

NewFromAccessControl creates a Plugin from an existing AccessControl instance.

func (*Plugin) AccessControl

func (p *Plugin) AccessControl() *AccessControl

AccessControl returns the underlying AccessControl manager instance.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique identifier for the Access Control plugin.

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin within the shared modular auth context and registers the AccessControl instance.

func (*Plugin) PublishAuthorized

func (p *Plugin) PublishAuthorized(roles []string, req AuthorizeRequest, extra map[string]any)

PublishAuthorized emits an EventAccessAuthorized event on the shared EventBus if initialized.

func (*Plugin) PublishDenied

func (p *Plugin) PublishDenied(roles []string, req AuthorizeRequest, reason string, extra map[string]any)

PublishDenied emits an EventAccessDenied event on the shared EventBus if initialized.

func (*Plugin) PublishRoleCreated

func (p *Plugin) PublishRoleCreated(role *Role)

PublishRoleCreated emits an EventRoleCreated event on the shared EventBus if initialized.

func (*Plugin) PublishRoleDeleted

func (p *Plugin) PublishRoleDeleted(roleName string)

PublishRoleDeleted emits an EventRoleDeleted event on the shared EventBus if initialized.

func (*Plugin) RequirePermission added in v0.20.0

func (p *Plugin) RequirePermission(resource string, actions ...string) func(next http.Handler) http.Handler

RequirePermission returns a net/http middleware handler that validates whether the resolved subject has permission for a resource and actions.

type Role

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

Role represents a named or anonymous role definition paired with its granted permission statements.

func NewRole

func NewRole(name string, statements Statements, allowWildcards bool) *Role

NewRole instantiates a new Role with the given identifier and statements.

func (*Role) Authorize

func (r *Role) Authorize(request AuthorizeRequest, connector ...Connector) AuthorizeResult

Authorize evaluates an AuthorizeRequest against the role's statements using an optional global Connector (default: AND).

func (*Role) Clone

func (r *Role) Clone(newName ...string) *Role

Clone creates an exact deep copy of the Role, optionally assigning a new name.

func (*Role) Extend

func (r *Role) Extend(newName string, additionalStatements Statements) *Role

Extend derives a new Role combining the existing statements with additional statements without mutating the parent role.

func (*Role) HasPermission

func (r *Role) HasPermission(resource string, action string) bool

HasPermission is a high-performance convenience helper to check a single resource and action permission.

func (*Role) MarshalJSON

func (r *Role) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Role into JSON format for database persistence and caching.

func (*Role) Name

func (r *Role) Name() string

Name returns the role's identifier name.

func (*Role) Statements

func (r *Role) Statements() Statements

Statements returns an isolated deep copy of the role's permission statements.

func (*Role) UnmarshalJSON

func (r *Role) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes a Role from JSON format.

type RoleCreatedEventPayload

type RoleCreatedEventPayload struct {
	// Role is the newly created Role instance.
	Role *Role
}

RoleCreatedEventPayload contains the details of a newly registered role.

type RoleDeletedEventPayload

type RoleDeletedEventPayload struct {
	// RoleName is the identifier of the removed role.
	RoleName string
}

RoleDeletedEventPayload contains the name of the deleted role.

type Statements

type Statements map[string][]string

Statements defines a map of resource names to allowed action strings. Example: Statements{"project": {"create", "read", "update", "delete"}, "user": {"read"}}

func CloneStatements

func CloneStatements(s Statements) Statements

CloneStatements creates an isolated deep copy of a Statements map.

func MergeStatements

func MergeStatements(dst, src Statements) Statements

MergeStatements merges source statements into destination statements without duplicating actions.

type SubjectPermissionResolver

type SubjectPermissionResolver func(ctx context.Context) ([]string, error)

SubjectPermissionResolver extracts the assigned roles for a subject from a context.

Jump to

Keyboard shortcuts

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