rbac

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2024 License: Apache-2.0 Imports: 9 Imported by: 9

README

RBAC module for Go

Build Status Go Report Card GoDoc Coverage Status

RBAC (Role-Based Access Control) is a powerful module for Go that simplifies access control in your applications. It allows you to manage roles and permissions, making it easier to control who can perform specific actions within your system.

Features

  • Role Definitions: Create roles with associated permissions to represent different user roles or access levels.
  • Permission Checks: Easily check if a user or entity has the required permissions to perform actions.
  • Customizable Checks: Implement custom permission checks using callback functions to adapt the module to your specific needs.
  • Integration: Seamlessly integrate RBAC into your Go applications to enhance security and access control.

Installation

You can install the RBAC module using Go's package manager:

go get github.com/demdxx/rbac

Usage

Here's a simple example of how to use RBAC in your Go application:

import (
    "context"
    "fmt"
    "your/package/model" // Import your application's model
    "github.com/demdxx/rbac"
)

// Create a new RBAC manager of roles and permissions in your application
pm := rbac.NewManager(nil)

// Define a callback function for custom permission checks
callback := func(ctx context.Context, resource any, perm back.Permission) bool {
    // Implement your custom permission logic here
    return perm.Ext().(*model.RoleContext).DebugMode || strings.HasSuffix(resource.Name(), `.all`)
}

// Register your application's model objects
pm.RegisterObject(&model.User{}, callback)

// Register new permissions for the user object as
// [user.view.owner, user.veiw.account, user.view.all, user.edit.owner, user.edit.account, user.edit.all]
pm.RegisterNewOwningPermissions((*model.User)(nil), []string{`view`, `edit`})

// Create an admin role with permissions and the custom check callback
pm.RegisterRole(ctx, rbac.NewRole(`admin`, rbac.WithPermissins(
    rbac.NewSimplePermission(`access`),
    rbac.NewResourcePermission(`register`, &model.User{}, rbac.WithCustomCheck(callback, &roleContext)),
    `user.*.all`,
)))

// Check if a user has access and view permissions
if adminRole.CheckPermissions(ctx, userObject, `access`) {
    if !adminRole.CheckPermissions(ctx, userObject, `view.*`) {
        return ErrNoViewPermissions
    }
    fmt.Println("Access granted")
}

For detailed usage and further documentation, please refer to the GoDoc documentation.

License

This RBAC module is distributed under the Apache 2.0 License. For more information, please see the LICENSE file.

Contributing

Contributions are welcome! If you encounter issues or have suggestions for improvement, please open an issue or submit a pull request on the GitHub repository.

Documentation

Overview

Package rbac provides role-based access control (RBAC) system

Index

Constants

View Source
const (
	OwnOwner   = `owner`   // The owner of the object (creator or user assigned as owner)
	OwnAccount = `account` // The account owner
	OwnAll     = `all`     // The system owner (can control all objects) *not recommended
)

Variables

View Source
var (
	// ErrInvalidOption for this type
	ErrInvalidOption = errors.New(`invalid option`)

	// ErrInvalidOptionParam if param is not valid
	ErrInvalidOptionParam = errors.New(`invalid option param`)
)
View Source
var (
	// ErrInvalidCheckParams in case of empty permission check params
	ErrInvalidCheckParams = errors.New(`invalid check params`)

	// ErrInvalidResouceType if parameter is Nil
	ErrInvalidResouceType = errors.New(`invalid resource type`)
)
View Source
var (
	ErrEmptyPermissionName   = errors.New(`empty permission name`)
	ErrInvalidPermissionName = errors.New(`invalid permission name`)
	ErrInvalidPattern        = errors.New(`invalid pattern`)
)
View Source
var ErrResourceTypeRequired = errors.New(`resource type required`)

Functions

func GetResName

func GetResName(resource any) string

GetResName returns resource name

func GetResType

func GetResType(resource any) (res reflect.Type)

GetResType returns resource type

func Included added in v0.1.8

func Included(base Role, testRole Role) bool

Included returns true if testRole is included in the base role or equal

func MatchName added in v0.1.5

func MatchName(pattern, name string) (ok bool, err error)

MatchName permission pattern Example: `*` or `**` matches any string `test.*` matches `test.it`, `test.it.owner`, `test.it.admin `test.*.owner` matches `test.it.owner`, `test.object.owner` `test.*.*` matches `test.it.owner`, `test.object.owner` `test.*.?wner` matches `test.it.owner`, `test.object.owner `test.*.{owner|admin}` matches `test.it.owner`, `test.object.admin` `test.%r{[a-z]+}` matches `test.it.owner`, `test.object.admin` (regexp) `test.**` matches `test.it.owner`, `test.object.admin` (** must be at the end)

func WithoutCustomCheck

func WithoutCustomCheck(obj any) error

WithoutCustomCheck remove custom check

Types

type Manager

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

Manager of the roles and permissions

The manager is the main object of the system which contains all roles and permissions and provides methods to check permissions and roles for the object.

Default manager implements implies that all permissions will be defined in the code.

Default manager implements chain permission name type

Object permission name: `objectType.permissionName.owner|account|all`
where objectType is the object type name, permissionName is the permission name
and owner|account|all is the owner type

func NewManager

func NewManager(roleAccessor RoleAccessors) *Manager

NewManager creates new manager

func NewManagerWithLoader

func NewManagerWithLoader(roleLoader RoleLoader, lifetimeCache time.Duration) *Manager

NewManagerWithLoader creates new manager with role loader

func (*Manager) ObjectByName added in v0.1.3

func (mng *Manager) ObjectByName(name string) any

ObjectByName returns object by name

func (*Manager) ObjectPermissions

func (mng *Manager) ObjectPermissions(obj any, patterns ...string) []Permission

ObjectPermissions returns all or selected permissions for the object like .RBACResourceName() + `.` + pattern

func (*Manager) Permission

func (mng *Manager) Permission(name string) Permission

AddRole to the manager

func (*Manager) Permissions

func (mng *Manager) Permissions(patterns ...string) []Permission

Permissions returns all or selected permissions

func (*Manager) RegisterNewOwningPermissions

func (mng *Manager) RegisterNewOwningPermissions(resType any, names []string, options ...Option) error

RegisterNewOwningPermissions modifies permissions for owning with extension of the name > name.owner, name.account and name.all

func (*Manager) RegisterNewPermission

func (mng *Manager) RegisterNewPermission(resType any, name string, options ...Option) error

RegisterNewPermission in the system

func (*Manager) RegisterNewPermissions

func (mng *Manager) RegisterNewPermissions(resType any, names []string, options ...Option) error

RegisterNewPermissions multiple related to the resource type

func (*Manager) RegisterObject

func (mng *Manager) RegisterObject(objType, checkCallbac any) *Manager

RegisterObject for processing

func (*Manager) RegisterPermission

func (mng *Manager) RegisterPermission(perms ...Permission) *Manager

RegisterPermission in the system

func (*Manager) RegisterRole

func (mng *Manager) RegisterRole(ctx context.Context, roles ...Role) *Manager

Roles returns all or selected roles

func (*Manager) Role

func (mng *Manager) Role(ctx context.Context, name string) Role

AddRole to the manager

func (*Manager) Roles added in v0.1.1

func (mng *Manager) Roles(ctx context.Context, names ...string) []Role

Role returns role by name

func (*Manager) RolesByFilter added in v0.1.2

func (mng *Manager) RolesByFilter(ctx context.Context, filter RoleFilter) []Role

RolesByFilter returns roles by filter

type Option

type Option func(obj any) error

Option apply function to object

func WithChildRoles

func WithChildRoles(roles ...Role) Option

WithChildRoles of the role

func WithCustomCheck

func WithCustomCheck(f any, data ...any) Option

WithCustomCheck function and additional data if need to use in checker Example:

callback := func(ctx context.Context, resource any, names ...string) bool {
  return ExtData(ctx).(*model.RoleContext).DebugMode
}
perm := NewResourcePermission(`view`, &model.User{}, WithCustomCheck(callback, &roleContext))

func WithDescription added in v0.1.8

func WithDescription(description string) Option

WithDescription of the role or permission

func WithExtData

func WithExtData(data any) Option

WithExtData for the role or permission

func WithPermissions

func WithPermissions(permissions ...any) Option

WithPermissions apply subpermission

type Permission

type Permission interface {
	Name() string

	// Description of the permission
	Description() string

	// CheckPermissions to accept to resource
	CheckPermissions(ctx context.Context, resource any, patterns ...string) bool

	// CheckedPermission returns child permission for resource which has been checked as allowed
	CheckedPermissions(ctx context.Context, resource any, patterns ...string) Permission

	// ChildPermissions list returns list of child permissions
	ChildPermissions() []Permission

	// Permission returns permission by name
	Permission(name string) Permission

	// Permissions returns list of permissions by pattern
	Permissions(patterns ...string) []Permission

	// HasPermission returns true if permission has child permission
	HasPermission(patterns ...string) bool

	// MatchPermissionPattern returns true if permission matches any of the patterns
	MatchPermissionPattern(patterns ...string) bool

	// Ext returns additional user data
	Ext() any
}

Permission object checker

type ResourcePermission

type ResourcePermission struct {
	SimplePermission
	// contains filtered or unexported fields
}

ResourcePermission implementation for some specific object type

func MustNewResourcePermission

func MustNewResourcePermission(name string, resType any, options ...Option) *ResourcePermission

MustNewResourcePermission with name and resource type

func NewResourcePermission

func NewResourcePermission(name string, resType any, options ...Option) (*ResourcePermission, error)

NewResourcePermission object with custom checker and base type

func (*ResourcePermission) CheckPermissions

func (perm *ResourcePermission) CheckPermissions(ctx context.Context, resource any, patterns ...string) bool

CheckPermissions to accept to resource

func (*ResourcePermission) CheckType

func (perm *ResourcePermission) CheckType(resource any) bool

CheckType of resource and target type

func (*ResourcePermission) CheckedPermissions

func (perm *ResourcePermission) CheckedPermissions(ctx context.Context, resource any, patterns ...string) Permission

CheckedPermission returns child permission for resource which has been checked as allowed

func (*ResourcePermission) ChildPermissions

func (perm *ResourcePermission) ChildPermissions() []Permission

ChildPermissions returns list of child permissions

func (*ResourcePermission) Ext

func (perm *ResourcePermission) Ext() any

Ext returns additional user data

func (*ResourcePermission) HasPermission

func (perm *ResourcePermission) HasPermission(patterns ...string) bool

HasPermission returns true if permission has permission

func (*ResourcePermission) MatchPermissionPattern

func (perm *ResourcePermission) MatchPermissionPattern(patterns ...string) bool

MatchPermissionPattern returns true if permission matches any of the patterns

func (*ResourcePermission) Name

func (perm *ResourcePermission) Name() string

Name returns permission name

func (*ResourcePermission) Permission

func (perm *ResourcePermission) Permission(name string) Permission

Permission returns permission by name

func (*ResourcePermission) Permissions

func (perm *ResourcePermission) Permissions(patterns ...string) []Permission

Permissions returns list of permissions by pattern

func (*ResourcePermission) ResourceName

func (perm *ResourcePermission) ResourceName() string

ResourceName returns resource name

func (*ResourcePermission) ResourceType

func (perm *ResourcePermission) ResourceType() reflect.Type

ResourceType returns resource type

type Role

type Role interface {
	Permission

	// ChildRoles returns list of child roles
	ChildRoles() []Role

	// Role returns role by name
	Role(name string) Role

	// HasRole returns true if role has role
	HasRole(name string) bool
}

Role base interface

func MustNewRole

func MustNewRole(name string, options ...Option) Role

MustNewRole or produce panic

func NewDummyPermission

func NewDummyPermission(name string, allow bool) Role

NewDummyPermission permission with predefined check

func NewRole

func NewRole(name string, options ...Option) (Role, error)

NewRole interface implementation

type RoleAccessors

type RoleAccessors interface {
	Role(ctx context.Context, name string) Role
	Roles(ctx context.Context, names ...string) []Role
	RolesByFilter(ctx context.Context, filter RoleFilter) []Role
}

RoleAccessors interface for accessing roles

type RoleFilter added in v0.1.2

type RoleFilter func(ctx context.Context, role Role) bool

RoleLoader function for filling roles by custom rules

type RoleLoader

type RoleLoader interface {
	ListRoles(ctx context.Context) []Role
}

RoleLoader interface for loading roles from the storage or other source

type SimplePermission

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

SimplePermission implementation with simple functionality

func MustNewSimplePermission

func MustNewSimplePermission(name string, options ...Option) *SimplePermission

MustNewSimplePermission with name and resource type

func NewSimplePermission

func NewSimplePermission(name string, options ...Option) (*SimplePermission, error)

NewSimplePermission object with custom checker

func (*SimplePermission) CheckPermissions

func (perm *SimplePermission) CheckPermissions(ctx context.Context, resource any, patterns ...string) bool

CheckPermissions to accept to resource

func (*SimplePermission) CheckedPermissions

func (perm *SimplePermission) CheckedPermissions(ctx context.Context, resource any, patterns ...string) Permission

CheckedPermission returns child permission for resource which has been checked as allowed

func (*SimplePermission) ChildPermissions

func (perm *SimplePermission) ChildPermissions() []Permission

ChildPermissions returns list of child permissions

func (*SimplePermission) Description added in v0.1.8

func (perm *SimplePermission) Description() string

Description of the permission

func (*SimplePermission) Ext

func (perm *SimplePermission) Ext() any

Ext returns additional user data

func (*SimplePermission) HasPermission

func (perm *SimplePermission) HasPermission(patterns ...string) bool

HasPermission returns true if permission has permission

func (*SimplePermission) MatchPermissionPattern

func (perm *SimplePermission) MatchPermissionPattern(patterns ...string) bool

MatchPermissionPattern returns true if permission matches any of the patterns

func (*SimplePermission) Name

func (perm *SimplePermission) Name() string

Name of the permission

func (*SimplePermission) Permission

func (perm *SimplePermission) Permission(name string) Permission

Permission returns permission by name

func (*SimplePermission) Permissions

func (perm *SimplePermission) Permissions(patterns ...string) []Permission

Permissions returns list of permissions by pattern

Jump to

Keyboard shortcuts

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