Documentation
¶
Overview ¶
Package rbac provides a lightweight RBAC (Role-Based Access Control) wrapper around [Casbin](https://github.com/casbin/casbin/v2) with pluggable policy storage adapters.
It offers:
- a unified Enforcer manager with cached enforcement;
- policy CRUD (add/remove/clear/list rules);
- role management (assign/revoke roles, check inheritance);
- a framework-agnostic Checker for embedding in any HTTP framework;
- an optional Gin middleware (in subpackage gin).
Quick start (in-memory) ¶
mgr, err := rbac.NewMemory()
if err != nil { ... }
defer mgr.Close()
// Grant role "admin" access to GET /api/users.
mgr.AddPolicy("admin", "/api/users", "GET")
// Check.
ok, _ := mgr.Enforce("admin", "/api/users", "GET") // true
ok, _ = mgr.Enforce("viewer", "/api/users", "GET") // false
With GORM adapter ¶
mgr, err := rbac.New(rbac.WithGormAdapter(db))
Index ¶
- Variables
- func NormalizePath(path, prefix string) string
- type CheckContext
- type Checker
- type CheckerOption
- type Manager
- func (m *Manager) AddPolicies(rules [][]string) (bool, error)
- func (m *Manager) AddPolicy(sub, obj, act string) (bool, error)
- func (m *Manager) AssignRole(user, role string) (bool, error)
- func (m *Manager) ClearPolicies(sub string) error
- func (m *Manager) Close()
- func (m *Manager) DeleteRole(role string) error
- func (m *Manager) Enforce(sub, obj, act string) (bool, error)
- func (m *Manager) Enforcer() *casbin.SyncedCachedEnforcer
- func (m *Manager) HasPolicy(sub, obj, act string) (bool, error)
- func (m *Manager) HasRole(user, role string) (bool, error)
- func (m *Manager) ListPolicies() [][]string
- func (m *Manager) ListPoliciesForSubject(sub string) [][]string
- func (m *Manager) RemovePolicies(rules [][]string) (bool, error)
- func (m *Manager) RemovePolicy(sub, obj, act string) (bool, error)
- func (m *Manager) RevokeRole(user, role string) (bool, error)
- func (m *Manager) RolesForUser(user string) ([]string, error)
- func (m *Manager) SetPolicies(sub string, rules [][2]string) error
- func (m *Manager) UsersForRole(role string) ([]string, error)
- type Option
- type SimpleCheckContext
Constants ¶
This section is empty.
Variables ¶
var ( // ErrEmptySubject is returned when a subject (role/user) is empty. ErrEmptySubject = fmt.Errorf("rbac: subject must not be empty") // ErrEmptyObject is returned when an object (path/resource) is empty. ErrEmptyObject = fmt.Errorf("rbac: object must not be empty") // ErrEmptyAction is returned when an action (HTTP method) is empty. ErrEmptyAction = fmt.Errorf("rbac: action must not be empty") // ErrPolicyNotFound is returned when a requested policy does not exist. ErrPolicyNotFound = fmt.Errorf("rbac: policy not found") )
Functions ¶
func NormalizePath ¶
NormalizePath removes a prefix from a path and trims trailing slashes. This is useful for stripping framework route prefixes before enforcement.
Types ¶
type CheckContext ¶
type CheckContext interface {
// Subject returns the authenticated subject (user ID, role, etc.).
Subject() string
// Object returns the resource being accessed (e.g. URL path).
Object() string
// Action returns the action being performed (e.g. HTTP method).
Action() string
}
CheckContext is the context passed to Checker functions. It is framework-agnostic — adapters convert framework-specific request objects into this interface.
type Checker ¶
type Checker struct {
// contains filtered or unexported fields
}
Checker is a framework-agnostic permission checker. It extracts the subject, object, and action from a request context and delegates to the Manager for enforcement.
func NewChecker ¶
func NewChecker(mgr *Manager, opts ...CheckerOption) *Checker
NewChecker creates a permission checker.
type CheckerOption ¶
type CheckerOption func(*Checker)
CheckerOption configures a Checker.
func WithActionFunc ¶
func WithActionFunc(f func(ctx CheckContext) string) CheckerOption
WithActionFunc sets the function that extracts the action from a context.
func WithObjectFunc ¶
func WithObjectFunc(f func(ctx CheckContext) string) CheckerOption
WithObjectFunc sets the function that extracts the object from a context.
func WithSubjectFunc ¶
func WithSubjectFunc(f func(ctx CheckContext) string) CheckerOption
WithSubjectFunc sets the function that extracts the subject from a context.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager wraps a Casbin enforcer with convenience methods for policy and role management. The zero value is NOT ready to use; call New or NewMemory.
func New ¶
New creates a new RBAC manager. At least one adapter option must be provided (or use NewMemory for an in-memory enforcer).
func NewMemory ¶
NewMemory creates a manager with an in-memory enforcer (no persistence). This is useful for testing and simple applications.
func (*Manager) AddPolicies ¶
AddPolicies adds multiple policy rules atomically.
func (*Manager) AddPolicy ¶
AddPolicy adds a single policy rule (sub, obj, act). Returns (true, nil) if the policy was added (false if it already existed).
func (*Manager) AssignRole ¶
AssignRole assigns a role (or user) to a parent role (role inheritance). e.g. AssignRole("alice", "admin") means alice inherits admin's permissions.
func (*Manager) ClearPolicies ¶
ClearPolicies removes all policies for a given subject (role/user).
func (*Manager) DeleteRole ¶
DeleteRole deletes a role and all its assignments.
func (*Manager) Enforce ¶
Enforce checks whether a subject can perform an action on an object. Returns (true, nil) if access is allowed.
func (*Manager) Enforcer ¶
func (m *Manager) Enforcer() *casbin.SyncedCachedEnforcer
Enforcer returns the underlying Casbin enforcer for advanced operations.
func (*Manager) ListPolicies ¶
ListPolicies returns all policy rules.
func (*Manager) ListPoliciesForSubject ¶
ListPoliciesForSubject returns all policy rules for a given subject.
func (*Manager) RemovePolicies ¶
RemovePolicies removes multiple policy rules atomically.
func (*Manager) RemovePolicy ¶
RemovePolicy removes a single policy rule. Returns (true, nil) if the policy was removed.
func (*Manager) RevokeRole ¶
RevokeRole removes a role assignment.
func (*Manager) RolesForUser ¶
RolesForUser returns all roles assigned to a user (direct and inherited).
func (*Manager) SetPolicies ¶
SetPolicies replaces all policies for a subject with the given rules. This is useful for updating a role's permissions atomically.
type Option ¶
Option configures a Manager.
func WithEnforcer ¶
func WithEnforcer(e *casbin.SyncedCachedEnforcer) Option
WithEnforcer uses a pre-configured Casbin enforcer.
func WithGormAdapter ¶
WithGormAdapter uses a GORM-backed policy adapter for persistence.
func WithModelText ¶
WithModelText uses a custom Casbin model text instead of the default. Must be combined with an adapter option.
type SimpleCheckContext ¶
SimpleCheckContext is a basic implementation of CheckContext.
func (SimpleCheckContext) Action ¶
func (s SimpleCheckContext) Action() string
Action returns the action.
func (SimpleCheckContext) Object ¶
func (s SimpleCheckContext) Object() string
Object returns the object.
func (SimpleCheckContext) Subject ¶
func (s SimpleCheckContext) Subject() string
Subject returns the subject.