-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscopie.go
336 lines (271 loc) · 8.31 KB
/
scopie.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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package scopie
import (
"errors"
"fmt"
"strings"
)
const (
BlockSeperator = byte('/')
ArraySeperator = byte('|')
VariablePrefix = byte('@')
Wildcard = byte('*')
AllowPermission = "allow"
DenyPermission = "deny"
)
const (
fmtAllowedInvalidChar = "scopie-100 in %s: invalid character '%s'"
fmtAllowedVarInArray = "scopie-101: variable '%s' found in array block"
fmtAllowedVarNotFound = "scopie-104: variable '%s' not found"
fmtValidateVarInArray = "scopie-101: variable '%s' found in array block"
fmtValidateInvalidChar = "scopie-100: invalid character '%s'"
)
var (
errSuperNotLast = errors.New("scopie-105: super wildcard not in the last block")
errSuperInArray = errors.New("scopie-103: super wildcard found in array block")
errWildcardInArray = errors.New("scopie-102: wildcard found in array block")
errScopesEmpty = errors.New("scopie-106 in scope: scopes was empty")
errScopeEmpty = errors.New("scopie-106 in scope: scope was empty")
errRuleEmpty = errors.New("scopie-106 in rule: rule was empty")
// validation specific
errValidateScopeRulesEmpty = errors.New("scopie-106: scope or rule was empty")
errValidateNoScopeRules = errors.New("scopie-106: scope or rule array was empty")
errValidateInconsistent = errors.New("scopie-107: inconsistent array of scopes and rules")
)
// IsAllowedFunc is a type wrapper for [IsAllowed] that can be used as
// a dependency.
type IsAllowedFunc func(map[string]string, string, string) (bool, error)
// ValidateScopeFunc is a type wrapper for [ValidateScopes] that can be
// used as a dependency.
type ValidateScopeFunc func(string) error
// IsAllowed returns whether or not the scopes are allowed with the given rules.
// [Is Allowed Spec] is the function specification.
//
// Scopes specifies one or more scopes our actor must match.
// When using more then one scope, they are treated as a series of OR conditions,
// and an actor will be allowed if they match any of the scopes.
//
// Rules specifies one or more rules our requesting scopes has to have
// to be allowed access.
// An optional dictionary or map of variable to values.
// Variable keys should not start with `@`
//
// isAllowed, err := IsAllowed(
// []string{"accounts/thor/edit",
// "allow/accounts/@username/*",
// map[string]string{"username": "thor"},
// )
// if err != nil {
// return fmt.Errorf("invalid scope or rule: %w", err)
// }
// if !isAllowed {
// return fmt.Errorf("unauthorized")
// }
//
// [Is Allowed Spec]: https://scopie.dev/specification/functions/#is-allowed
func IsAllowed(scopes, rules []string, vars map[string]string) (bool, error) {
if len(scopes) == 0 {
return false, errScopesEmpty
}
if len(rules) == 0 {
return false, nil
}
hasBeenAllowed := false
for _, actorRule := range rules {
if len(actorRule) == 0 {
return false, errRuleEmpty
}
actorRule := actorRule
isAllowBlock := strings.HasPrefix(actorRule, AllowPermission)
if isAllowBlock && hasBeenAllowed {
continue
}
for _, actionScope := range scopes {
if len(actionScope) == 0 {
return false, errScopeEmpty
}
actionScope := actionScope
match, err := compareRuleToScope(&actorRule, &actionScope, vars)
if err != nil {
return false, err
}
if match && isAllowBlock {
hasBeenAllowed = true
} else if match && !isAllowBlock {
return false, nil
}
}
}
return hasBeenAllowed, nil
}
// ValidateScopes checks whether or not the given scopes or rules are valid given the
// requirements outlined in the specification.
// [Validate Scopes Spec] is the function specification.
//
// err := ValidateScopes("allow/accounts/@username/*")
// if err != nil {
// return fmt.Errorf("scope is invalid: %w", err)
// }
//
// [Validate Scopes Spec]: https://scopie.dev/specification/functions/#validate-scopes
func ValidateScopes(scopeOrRules []string) error {
if len(scopeOrRules) == 0 {
return errValidateNoScopeRules
}
isRules := strings.HasPrefix(scopeOrRules[0], AllowPermission) ||
strings.HasPrefix(scopeOrRules[0], DenyPermission)
for _, scope := range scopeOrRules {
if scope == "" {
return errValidateScopeRulesEmpty
}
scopeIsRule := strings.HasPrefix(scope, AllowPermission) ||
strings.HasPrefix(scope, DenyPermission)
if isRules != scopeIsRule {
return errValidateInconsistent
}
inArray := false
for i := range scope {
if scope[i] == BlockSeperator {
inArray = false
continue
}
if scope[i] == ArraySeperator {
inArray = true
continue
}
if inArray {
if scope[i] == Wildcard && i < len(scope)-1 && scope[i+1] == Wildcard {
return errSuperInArray
}
if scope[i] == Wildcard {
return errWildcardInArray
}
if scope[i] == VariablePrefix {
end := endOfArrayElement(&scope, i)
return fmt.Errorf(fmtValidateVarInArray, scope[i+1:end])
}
}
if !isValidCharacter(scope[i]) {
return fmt.Errorf(fmtValidateInvalidChar, string(scope[i]))
}
if scope[i] == Wildcard && i < len(scope)-1 && scope[i+1] == Wildcard && i < len(scope)-2 {
return errSuperNotLast
}
}
}
return nil
}
func compareRuleToScope(
rule *string,
scope *string,
vars map[string]string,
) (bool, error) {
// Skip the allow and deny prefix for actors
ruleLeft, _, _ := endOfBlock(rule, 0, "rule")
ruleLeft += 1 // don't forget to skip the slash
scopeLeft := 0
for ruleLeft < len(*rule) || scopeLeft < len(*scope) {
// In case one is longer then the other
if (ruleLeft < len(*rule)) != (scopeLeft < len(*scope)) {
return false, nil
}
scopeSlider, _, err := endOfBlock(scope, scopeLeft, "scope")
if err != nil {
return false, err
}
ruleSlider, ruleArray, err := endOfBlock(rule, ruleLeft, "rule")
if err != nil {
return false, err
}
// Super wildcards are checked here as it skips the who rest of the checks.
if ruleSlider-ruleLeft == 2 && (*rule)[ruleLeft] == Wildcard && (*rule)[ruleLeft+1] == Wildcard {
if len(*rule) > ruleSlider {
return false, errSuperNotLast
}
return true, nil
} else {
match, err := compareBlock(rule, ruleLeft, ruleSlider, ruleArray, scope, scopeLeft, scopeSlider, vars)
if err != nil {
return false, err
}
if !match {
return false, nil
}
}
scopeLeft = scopeSlider + 1
ruleLeft = ruleSlider + 1
}
return true, nil
}
func compareBlock(
rule *string, ruleLeft, ruleSlider int, ruleArray bool,
scope *string, scopeLeft, scopeSlider int,
vars map[string]string,
) (bool, error) {
if (*rule)[ruleLeft] == VariablePrefix {
key := (*rule)[ruleLeft+1 : ruleSlider]
varValue, found := vars[key]
if !found {
return false, fmt.Errorf(fmtAllowedVarNotFound, key)
}
return varValue == (*scope)[scopeLeft:scopeSlider], nil
}
if ruleSlider-ruleLeft == 1 && (*rule)[ruleLeft] == Wildcard {
return true, nil
}
if ruleArray {
for ruleLeft < ruleSlider {
arrayRight := endOfArrayElement(rule, ruleLeft)
if (*rule)[ruleLeft] == VariablePrefix {
key := (*rule)[ruleLeft+1 : arrayRight]
return false, fmt.Errorf(fmtAllowedVarInArray, key)
}
if (*rule)[ruleLeft] == Wildcard {
if arrayRight-ruleLeft > 1 && (*rule)[ruleLeft+1] == Wildcard {
return false, errSuperInArray
}
return false, errWildcardInArray
}
if (*rule)[ruleLeft:arrayRight] == (*scope)[scopeLeft:scopeSlider] {
return true, nil
}
ruleLeft = arrayRight + 1
}
return false, nil
}
return (*rule)[ruleLeft:ruleSlider] == (*scope)[scopeLeft:scopeSlider], nil
}
func endOfBlock(value *string, start int, category string) (int, bool, error) {
isArray := false
for i := start; i < len(*value); i++ {
if (*value)[i] == ArraySeperator {
isArray = true
} else if (*value)[i] == BlockSeperator {
return i, isArray, nil
} else if !isValidCharacter((*value)[i]) {
invalidChar := string((*value)[i])
return 0, false, fmt.Errorf(fmtAllowedInvalidChar, category, invalidChar)
}
}
return len(*value), isArray, nil
}
func endOfArrayElement(value *string, start int) int {
for i := start + 1; i < len(*value); i++ {
if (*value)[i] == BlockSeperator ||
(*value)[i] == ArraySeperator {
return i
}
}
return len(*value)
}
func isValidCharacter(char byte) bool {
if char >= 'a' && char <= 'z' {
return true
}
if char >= 'A' && char <= 'Z' {
return true
}
if char >= '0' && char <= '9' {
return true
}
return char == '_' || char == '-' || char == VariablePrefix || char == Wildcard
}