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 ¶
- Constants
- Variables
- func Configure(modules []platform.Module, opts ...Option) error
- func IsPublic(app *platform.App, method string) bool
- func RolesFrom(ctx context.Context) ([]string, bool)
- func WithRoles(ctx context.Context, roles ...string) context.Context
- type Config
- type Enforcer
- func (e *Enforcer) Allowed(roles []string, method string) bool
- func (e *Enforcer) Casbin() *casbin.SyncedEnforcer
- func (e *Enforcer) Check(ctx context.Context, method string) error
- func (e *Enforcer) Public(method string) bool
- func (e *Enforcer) Reload() error
- func (e *Enforcer) Rules() []Rule
- func (e *Enforcer) Unmatched(methods []string) []Rule
- type Module
- type Option
- func WithAdapter(a persist.Adapter) Option
- func WithFunction(name string, fn func(args ...any) (any, error)) Option
- func WithModel(text string) Option
- func WithPolicy(text string) Option
- func WithPublic(fn func(method string) []any) Option
- func WithReloadEvery(d time.Duration) Option
- func WithRequest(fn RequestFunc) Option
- type RequestFunc
- type Rule
Examples ¶
Constants ¶
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.
const Public = "*"
Public is the role that makes a method public: no authentication is needed.
Variables ¶
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
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 ¶
IsPublic reports whether a method needs no authentication, for the project's authentication interceptor.
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.
type Enforcer ¶
type Enforcer struct {
// contains filtered or unexported fields
}
Enforcer answers access questions. It is safe for concurrent use, a Reload included.
func NewEnforcer ¶
NewEnforcer builds an enforcer of taply's model from a policy text.
func NewEnforcerWith ¶ added in v0.11.0
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 ¶
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
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 ¶
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
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 ¶
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.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module implements platform.Module.
type Option ¶
type Option func(*Module)
Option configures the module.
func WithAdapter ¶ added in v0.11.0
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
WithFunction adds a function the matcher of the model may call, as casbin's AddFunction does.
func WithModel ¶ added in v0.11.0
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 ¶
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
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
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
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 ¶
Rule is one line of the policy.
func ParsePolicy ¶
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.