Repository navigation
Expand file tree
/
Copy pathpolicy_index.go
More file actions
222 lines (198 loc) · 6.14 KB
/
Copy pathpolicy_index.go
File metadata and controls
222 lines (198 loc) · 6.14 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package casbin
import (
"errors"
"fmt"
"sync"
"github.com/casbin/casbin/v3/model"
)
const (
wildcardPolicyBucket uint32 = ^uint32(0)
missingPolicyBucket uint32 = ^uint32(1)
)
// PolicyIndex partitions the policy rules of one policy type so that Enforce
// only evaluates the rules in the request's partition.
//
// RequestKey receives the request values, with an optional EnforceContext
// removed, and returns the partition key for the request. Returning false
// disables the index for that request, so every rule is evaluated.
//
// PolicyKey returns the partition key for one policy rule. The key "*" puts
// the rule in every partition.
//
// Enforce skips the matcher of a rule whose key differs from the request key.
// The caller must guarantee that such a rule can never match the request;
// otherwise the decision changes. This includes matchers that evaluate policy
// fields with eval(). Rules are still merged by the configured effector, so
// deny rules must be reachable through the request key or "*".
type PolicyIndex struct {
RequestKey func(rvals []interface{}) (string, bool)
PolicyKey func(rule []string) string
}
// SetPolicyIndex installs a policy partition for ptype. It replaces an
// existing index for the same policy type. The index is rebuilt automatically
// when the policy changes.
func (e *Enforcer) SetPolicyIndex(ptype string, index PolicyIndex) error {
return e.setPolicyIndex(ptype, "", index)
}
// setPolicyIndex limits the index to requests of rType; an empty rType means
// every request type.
func (e *Enforcer) setPolicyIndex(ptype string, rType string, index PolicyIndex) error {
if index.RequestKey == nil || index.PolicyKey == nil {
return errors.New("policy index functions cannot be nil")
}
if _, ok := e.model["p"][ptype]; !ok {
return fmt.Errorf("policy type %q does not exist", ptype)
}
e.policyIndexes.Store(ptype, &policyIndex{
rType: rType,
requestKey: index.RequestKey,
policyKey: index.PolicyKey,
})
return nil
}
// SetPolicyIndexByToken installs a policy partition that uses the string value
// of requestToken as the request key and the string value of policyToken as
// the rule key. It applies only to requests of the default request type "r";
// requests of other types evaluate every rule. Use SetPolicyIndex with
// a custom function when enforcing through an EnforceContext.
func (e *Enforcer) SetPolicyIndexByToken(ptype string, requestToken string, policyToken string) error {
rAssertion, ok := e.model["r"]["r"]
if !ok {
return errors.New("request type \"r\" does not exist")
}
requestIndex := -1
for i, token := range rAssertion.Tokens {
if token == requestToken {
requestIndex = i
break
}
}
if requestIndex == -1 {
return fmt.Errorf("request token %q does not exist", requestToken)
}
pAssertion, ok := e.model["p"][ptype]
if !ok {
return fmt.Errorf("policy type %q does not exist", ptype)
}
policyIndex := -1
for i, token := range pAssertion.Tokens {
if token == policyToken {
policyIndex = i
break
}
}
if policyIndex == -1 {
return fmt.Errorf("policy token %q does not exist", policyToken)
}
return e.setPolicyIndex(ptype, "r", PolicyIndex{
RequestKey: func(rvals []interface{}) (string, bool) {
if requestIndex >= len(rvals) {
return "", false
}
key, ok := rvals[requestIndex].(string)
return key, ok
},
PolicyKey: func(rule []string) string {
if policyIndex >= len(rule) {
return ""
}
return rule[policyIndex]
},
})
}
// RemovePolicyIndex removes the policy partition for ptype.
func (e *Enforcer) RemovePolicyIndex(ptype string) {
e.policyIndexes.Delete(ptype)
}
func (e *Enforcer) getPolicyIndex(ptype string, rType string) *policyIndex {
if value, ok := e.policyIndexes.Load(ptype); ok {
idx := value.(*policyIndex)
if idx.rType != "" && idx.rType != rType {
return nil
}
return idx
}
return nil
}
type policyIndex struct {
rType string
requestKey func(rvals []interface{}) (string, bool)
policyKey func(rule []string) string
mu sync.Mutex
built bool
version uint64
bucketIDs []uint32
names map[string]uint32
}
func (idx *policyIndex) ensureBuilt(ast *model.Assertion) []uint32 {
idx.mu.Lock()
defer idx.mu.Unlock()
if idx.built && idx.version == ast.PolicyVersion && len(idx.bucketIDs) == len(ast.Policy) {
return idx.bucketIDs
}
names := make(map[string]uint32)
bucketIDs := make([]uint32, len(ast.Policy))
var next uint32
for i, rule := range ast.Policy {
key := idx.policyKey(rule)
if key == "*" {
bucketIDs[i] = wildcardPolicyBucket
continue
}
id, ok := names[key]
if !ok {
id = next
names[key] = id
next++
}
bucketIDs[i] = id
}
idx.version = ast.PolicyVersion
idx.bucketIDs = bucketIDs
idx.names = names
idx.built = true
return bucketIDs
}
func (idx *policyIndex) reset() {
idx.mu.Lock()
idx.built = false
idx.bucketIDs = nil
idx.names = nil
idx.mu.Unlock()
}
func (idx *policyIndex) requestBucket(rvals []interface{}) (uint32, bool) {
key, ok := idx.requestKey(rvals)
if !ok {
return 0, false
}
idx.mu.Lock()
id, found := idx.names[key]
idx.mu.Unlock()
if !found {
return missingPolicyBucket, true
}
return id, true
}
func policyMatchesBucket(bucketIDs []uint32, policyIndex int, bucket uint32) bool {
if policyIndex < 0 || policyIndex >= len(bucketIDs) {
return true
}
id := bucketIDs[policyIndex]
return id == wildcardPolicyBucket || id == bucket
}