rbac

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package rbac is a platform module: role based access to the gRPC methods of the API, in the model and policy format of taply by default, or in any casbin model.

The module decides what a role may call; who the caller is stays with the project. The project's authentication interceptor puts the roles into the context with WithRoles, and asks Public to skip authentication for public methods.

Without options beyond WithPolicy the module is taply's: the model is Model, the policy is the embedded rbac/policy.csv checked by ParsePolicy. WithModel, WithAdapter, WithFunction, WithRequest and WithPublic take it to any casbin model — role inheritance, domains, matchers of the project's own — and a policy in any casbin adapter, reloaded without a restart. Casbin gives the enforcer itself for the rest.

Index

Examples

Constants

View Source
const Model = `` /* 222-byte string literal not displayed */

Model is taply's casbin model: a role may call a method matching a keyMatch2 pattern, such as /shop.v1.OrdersService/* for a whole service.

View Source
const Public = "*"

Public is the role that makes a method public: no authentication is needed.

Variables

View Source
var ErrUnauthenticated = errors.New("rbac: authentication required")

ErrUnauthenticated is what a RequestFunc returns for a caller who has not authenticated: the call is answered Unauthenticated.

Functions

func Configure added in v0.11.0

func Configure(modules []platform.Module, opts ...Option) error

Configure applies options to the rbac module among the modules, for a project whose wiring is generated: call it in main, between platformModules and platform.Run.

func IsPublic

func IsPublic(app *platform.App, method string) bool

IsPublic reports whether a method needs no authentication, for the project's authentication interceptor.

func RolesFrom

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

RolesFrom returns the roles of the caller and whether the caller is authenticated.

func WithRoles

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

WithRoles returns a context carrying the roles of the authenticated caller. The project's authentication interceptor calls it.

Types

type Config

type Config struct{}

Config holds module settings. The module has no environment variables: access rules are code, reviewed and deployed with the service.

func Load

func Load(*confx.Loader) Config

Load reads the module settings from environment variables.

type Enforcer

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

Enforcer answers access questions. It is safe for concurrent use, a Reload included.

func From

func From(app *platform.App) *Enforcer

From returns the enforcer from the container.

func NewEnforcer

func NewEnforcer(policy string) (*Enforcer, error)

NewEnforcer builds an enforcer of taply's model from a policy text.

func NewEnforcerWith added in v0.11.0

func NewEnforcerWith(opts ...Option) (*Enforcer, error)

NewEnforcerWith builds an enforcer from the options of the module, for a check outside the module: a command, a test, a handler of a non-gRPC route.

func (*Enforcer) Allowed

func (e *Enforcer) Allowed(roles []string, method string) bool

Allowed reports whether any of the roles may call the method: whether {role, method, "*"} is allowed for any of them. With WithRequest the requests are the project's; Check asks what the module asks.

func (*Enforcer) Casbin added in v0.11.0

func (e *Enforcer) Casbin() *casbin.SyncedEnforcer

Casbin returns the casbin enforcer, for what the module does not wrap: role links, domains, policy changes through the casbin API, a watcher. Changes to the policy it makes are seen by the module at once; with a policy text they live until a restart. In taply's model the adapter it holds checks the format on every load. A change made through it while a Reload runs may be lost to the reloaded policy: with an adapter, write to the store and reload.

func (*Enforcer) Check added in v0.11.0

func (e *Enforcer) Check(ctx context.Context, method string) error

Check answers whether the caller in the context may call the method, as the module's interceptor does: nil, or the gRPC status the caller gets.

func (*Enforcer) Public

func (e *Enforcer) Public(method string) bool

Public reports whether a method needs no authentication: whether the public request is allowed — {"*", method, "*"} unless WithPublic gives another one. A model whose request is not sub, obj, act has no public methods without WithPublic.

func (*Enforcer) Reload added in v0.11.0

func (e *Enforcer) Reload() error

Reload reads the policy from the adapter again and swaps it in whole: calls being checked see the old policy or the new one, never a mix. A policy that fails to load — or, in taply's model, breaks its format — leaves the old one in place and returns the error. A policy text is fixed and Reload does nothing.

func (*Enforcer) Rules

func (e *Enforcer) Rules() []Rule

Rules returns the policy: the rules of p, with the line of the policy text when there is one. For a model of the project's own a rule takes its fields from sub, obj and act of the policy definition, the ones it lacks stay empty; Casbin gives the rest, role links and domains included.

func (*Enforcer) Unmatched

func (e *Enforcer) Unmatched(methods []string) []Rule

Unmatched returns the rules whose method pattern matches none of the given methods: a renamed method or a typo leaves such a rule granting nothing. For a model of the project's own only rules whose obj is a method pattern, starting with /, are looked at.

type Module

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

Module implements platform.Module.

func New

func New(_ Config, opts ...Option) *Module

New creates the module.

func (*Module) Init

func (m *Module) Init(_ context.Context, app *platform.App) error

Init reads the policy and puts the access check in front of every call.

func (*Module) Name

func (m *Module) Name() string

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

Start reloads the policy on the period of WithReloadEvery, and warns about rules that grant nothing because no registered method matches them.

type Option

type Option func(*Module)

Option configures the module.

func WithAdapter added in v0.11.0

func WithAdapter(a persist.Adapter) Option

WithAdapter takes the policy from a casbin adapter — a database, a file, a service — instead of the text of WithPolicy. Reload, or WithReloadEvery, reads it again without a restart. In taply's model every load is checked as ParsePolicy checks a text.

func WithFunction added in v0.11.0

func WithFunction(name string, fn func(args ...any) (any, error)) Option

WithFunction adds a function the matcher of the model may call, as casbin's AddFunction does.

func WithModel added in v0.11.0

func WithModel(text string) Option

WithModel replaces taply's model with a casbin model of the project's own: role inheritance (g), domains, matchers and effects of its own. The policy must follow it.

func WithPolicy

func WithPolicy(text string) Option

WithPolicy gives the module the policy of the project. The generated wiring passes the embedded rbac/policy.csv. In taply's model it is checked by ParsePolicy; in a model of the project's own it is casbin's CSV — p, g and the other types the model defines — and casbin checks it, with the line of a broken rule. WithAdapter replaces it.

func WithPublic added in v0.11.0

func WithPublic(fn func(method string) []any) Option

WithPublic gives the request that, when allowed, makes a method public, in the order of the model's request_definition. The default is {"*", method, "*"} for a request of sub, obj, act; a model with another request has no public methods without it.

func WithReloadEvery added in v0.11.0

func WithReloadEvery(d time.Duration) Option

WithReloadEvery reloads the policy of the adapter on a period, from the start of the module until the service stops. A failed reload keeps the policy in force, is logged and counted in rbac_policy_reloads_total{result="error"}.

func WithRequest added in v0.11.0

func WithRequest(fn RequestFunc) Option

WithRequest replaces how a call becomes the requests to enforce; see RequestFunc. It is needed for a model whose request is not sub, obj, act — a domain, a tenant, an attribute of the caller.

Example
package main

import (
	"context"
	"fmt"

	"google.golang.org/grpc/status"

	"github.com/aidarbn/platform-go/kit/modules/rbac"
)

// Domains: a user has a role in a tenant; the tenant comes from the call.
const domainModel = `[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act

[role_definition]
g = _, _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = (g(r.sub, p.sub, r.dom) || p.sub == "*") && (p.dom == "*" || r.dom == p.dom) && keyMatch2(r.obj, p.obj) && (p.act == "*" || r.act == p.act)
`

const domainPolicy = `p, *, *, /grpc.health.v1.Health/*, *
p, admin, *, /shop.v1.Orders/*, *
p, clerk, *, /shop.v1.Orders/Get, *
g, alice, admin, shop-1
g, alice, clerk, shop-2
`

type tenantKey struct{}

func main() {
	// The tenant comes from the call; the user's roles in it decide.
	e, err := rbac.NewEnforcerWith(
		rbac.WithModel(domainModel),
		rbac.WithPolicy(domainPolicy),
		rbac.WithRequest(func(ctx context.Context, method string) ([][]any, error) {
			users, ok := rbac.RolesFrom(ctx)
			if !ok {
				return nil, rbac.ErrUnauthenticated
			}
			tenant, _ := ctx.Value(tenantKey{}).(string)
			var reqs [][]any
			for _, u := range users {
				reqs = append(reqs, []any{u, tenant, method, "*"})
			}
			return reqs, nil
		}),
		rbac.WithPublic(func(method string) []any { return []any{"", "", method, "*"} }),
	)
	if err != nil {
		panic(err)
	}
	ctx := context.WithValue(rbac.WithRoles(context.Background(), "alice"), tenantKey{}, "shop-2")
	fmt.Println(status.Code(e.Check(ctx, "/shop.v1.Orders/Delete")))
}
Output:
PermissionDenied

type RequestFunc added in v0.11.0

type RequestFunc func(ctx context.Context, method string) ([][]any, error)

RequestFunc turns a call into the requests to enforce: each one is the arguments of casbin's Enforce, in the order of the model's request_definition, and the call is allowed when any of them is. The default is one request per role from the context, {role, method, "*"}.

It returns ErrUnauthenticated for a caller who has not authenticated (Unauthenticated), no requests for an authenticated caller who may do nothing (PermissionDenied), and any other error to refuse the call: an error with a gRPC status is returned to the client as it is, any other one answers Internal and is logged.

type Rule

type Rule struct {
	Role   string
	Method string // keyMatch2 pattern
	Action string
	Line   int
}

Rule is one line of the policy.

func ParsePolicy

func ParsePolicy(text string) ([]Rule, error)

ParsePolicy reads a policy in taply's CSV format: "p, role, method, action" per line, # comments and empty lines allowed. Every broken line is reported.

Jump to

Keyboard shortcuts

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