/
policy-enforcer.go
59 lines (49 loc) · 1.42 KB
/
policy-enforcer.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
56
57
58
59
package policyenforcer
import "context"
// matcherFunc defines how to match request policy with the stored policy
type matcherFunc func(r, p Policy) bool
// defaultMatcher function will be used when no custom
// matcher function in provided to the policy enforcer
func defaultMatcher(r, p Policy) bool {
if r.sub == p.sub && r.rtype == p.rtype && (r.act == p.act || p.act == "*") && (r.rid == p.rid || p.rid == "*") {
return true
}
return false
}
type PolicyEnforcer interface {
Enforce(ctx context.Context, s string, matcher matcherFunc) bool
GetResourceIDs(ctx context.Context, sub, rtype, act string) []string
}
func NewPolicyEnforcer(ps PolicyStorage) (PolicyEnforcer, error) {
if ps == nil {
return nil, ErrNilPolicyStorage
}
return &policyEnforcer{storage: ps}, nil
}
type policyEnforcer struct {
storage PolicyStorage
}
func (pe *policyEnforcer) Enforce(ctx context.Context, s string, matcher matcherFunc) bool {
r, err := getPolicyFromString(s)
if err != nil {
return false
}
if matcher == nil {
matcher = defaultMatcher
}
for _, p := range pe.storage.GetPolicyForSub(ctx, r.sub) {
if matcher(r, p) {
return true
}
}
return false
}
func (pe *policyEnforcer) GetResourceIDs(ctx context.Context, sub, rtype, act string) (rids []string) {
fPolicies := pe.storage.GetPolicyForSub(ctx, sub)
for _, fp := range fPolicies {
if rtype == fp.rtype && act == fp.act {
rids = append(rids, fp.rid)
}
}
return
}