Documentation
¶
Index ¶
- Constants
- Variables
- func ContextRoleResolver(ctx context.Context) ([]string, error)
- func RequirePermission(ac *AccessControl, resolver SubjectPermissionResolver, resource string, ...) func(ctx context.Context) error
- func RequireRequest(ac *AccessControl, resolver SubjectPermissionResolver, req AuthorizeRequest, ...) func(ctx context.Context) error
- func SubjectRolesFromContext(ctx context.Context) ([]string, bool)
- func WithSubjectRoles(ctx context.Context, roles ...string) context.Context
- type AccessAuthorizedEventPayload
- type AccessControl
- func (ac *AccessControl) AuthorizeRoleString(roleString string, request AuthorizeRequest, connector ...Connector) AuthorizeResult
- func (ac *AccessControl) AuthorizeRoles(roleNames []string, request AuthorizeRequest, connector ...Connector) AuthorizeResult
- func (ac *AccessControl) DeleteRole(name string) bool
- func (ac *AccessControl) GetAllRoles() map[string]*Role
- func (ac *AccessControl) GetRole(name string) (*Role, bool)
- func (ac *AccessControl) MasterStatements() Statements
- func (ac *AccessControl) MergeRoles(roleNames ...string) (*Role, error)
- func (ac *AccessControl) MustNewRole(name string, roleStatements Statements) *Role
- func (ac *AccessControl) NewAnonymousRole(roleStatements Statements) (*Role, error)
- func (ac *AccessControl) NewRole(name string, roleStatements Statements) (*Role, error)
- type AccessDeniedEventPayload
- type ActionRequest
- type AuthorizeRequest
- type AuthorizeRequestBuilder
- type AuthorizeResult
- type Config
- type Connector
- type Evaluator
- type Option
- type Plugin
- func (p *Plugin) AccessControl() *AccessControl
- func (p *Plugin) ID() string
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) PublishAuthorized(roles []string, req AuthorizeRequest, extra map[string]any)
- func (p *Plugin) PublishDenied(roles []string, req AuthorizeRequest, reason string, extra map[string]any)
- func (p *Plugin) PublishRoleCreated(role *Role)
- func (p *Plugin) PublishRoleDeleted(roleName string)
- type Role
- func (r *Role) Authorize(request AuthorizeRequest, connector ...Connector) AuthorizeResult
- func (r *Role) Clone(newName ...string) *Role
- func (r *Role) Extend(newName string, additionalStatements Statements) *Role
- func (r *Role) HasPermission(resource string, action string) bool
- func (r *Role) MarshalJSON() ([]byte, error)
- func (r *Role) Name() string
- func (r *Role) Statements() Statements
- func (r *Role) UnmarshalJSON(data []byte) error
- type RoleCreatedEventPayload
- type RoleDeletedEventPayload
- type Statements
- type SubjectPermissionResolver
Constants ¶
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.
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: " // 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.
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.
const (
// WildcardAll matches any resource or action when wildcards are enabled.
WildcardAll = "*"
)
Wildcard constants for granting blanket permissions.
Variables ¶
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 ¶
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 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 ¶
SubjectRolesFromContext extracts attached subject roles from 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 ¶
func (b *AuthorizeRequestBuilder) Build() AuthorizeRequest
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 ¶
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.
type Evaluator ¶
type Evaluator struct {
// contains filtered or unexported fields
}
Evaluator executes access control evaluation algorithms against Statements.
func NewEvaluator ¶
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 ¶
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 ¶
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) Init ¶
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 ¶
PublishRoleCreated emits an EventRoleCreated event on the shared EventBus if initialized.
func (*Plugin) PublishRoleDeleted ¶
PublishRoleDeleted emits an EventRoleDeleted event on the shared EventBus if initialized.
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) 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 ¶
HasPermission is a high-performance convenience helper to check a single resource and action permission.
func (*Role) MarshalJSON ¶
MarshalJSON serializes the Role into JSON format for database persistence and caching.
func (*Role) Statements ¶
func (r *Role) Statements() Statements
Statements returns an isolated deep copy of the role's permission statements.
func (*Role) UnmarshalJSON ¶
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 ¶
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.