/
rbac.go
55 lines (46 loc) · 1.3 KB
/
rbac.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package rego
import (
"context"
_ "embed"
"errors"
"fmt"
"github.com/kanthorlabs/common/gatekeeper/entities"
"github.com/open-policy-agent/opa/rego"
)
//go:embed rbac.rego
var rbac string
var (
ErrRBAC = errors.New("GATEKEEPER.REGO.RBAC.ERROR")
ErrRBACNotAllow = errors.New("GATEKEEPER.REGO.RBAC.NOT_ALLOW.ERROR")
)
// RBAC is a factory function that returns a function that evaluates the given permission and privileges based on RBAC rules.
func RBAC(ctx context.Context, definitions map[string][]entities.Permission) (Evaluate, error) {
store, err := Memory(definitions)
if err != nil {
return nil, fmt.Errorf("%s: %w", ErrRBAC.Error(), err)
}
query, err := rego.
New(
rego.Query("data.kanthorlabs.gatekeeper.allow"),
rego.Module("rbac.rego", rbac),
rego.Store(store),
).
PrepareForEval(ctx)
if err != nil {
return nil, fmt.Errorf("%s: %w", ErrRBAC.Error(), err)
}
return func(ectx context.Context, permission *entities.Permission, privileges []entities.Privilege) error {
input := map[string]any{
"permission": permission,
"privileges": privileges,
}
results, err := query.Eval(ectx, rego.EvalInput(input))
if err != nil {
return fmt.Errorf("%s: %w", ErrRBAC.Error(), err)
}
if !results.Allowed() {
return ErrRBACNotAllow
}
return nil
}, nil
}