-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
permissions.go
99 lines (85 loc) · 2.3 KB
/
permissions.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
// Package permissions provides functionalities to
// calculate, update and merge arrays of permission
// domain rules.
//
// Read this to get more information about how
// permission domains and rules are working:
// https://github.com/zekroTJA/shinpuru/wiki/Permissions-Guide
package permissions
import (
"fmt"
"strings"
)
const maxPermIndex = 999
// permissionMatchDNs tries to match the passed
// domainName on the passed perm.
//
// This also respects explicit domainNames
// prefixed with '!'.
//
// The resulting match index is returned. If the
// match index is < 0, this must be interpreted as
// no match.
func permissionMatchDNs(domainName, perm string) int {
if domainName == "" {
return -1
}
var needsExplicitAllow bool
// A domainName with the prefix '!' sets
// needsExplicitAllow to true.
// This means, the domainName must be
// explicitely allowed and can not be matched
// by wildcard.
if domainName[0] == '!' {
needsExplicitAllow = true
domainName = domainName[1:]
}
// If the domain name equals perm, return
// 999 match index.
if domainName == perm {
return maxPermIndex
}
// ...otherwise, if needsExplicitAllow is
// true and it is not an exact match,
// return negative match.
if needsExplicitAllow {
return -1
}
// Split domainName in areas seperated by '.'
dnAreas := strings.Split(domainName, ".")
assembled := ""
for i, dnArea := range dnAreas {
if assembled == "" {
// If assembled is empty, set assembled to
// current dnArea.
assembled = dnArea
} else {
// Otherwise, add current dnArea to assembled.
assembled = fmt.Sprintf("%s.%s", assembled, dnArea)
}
// If perm equals assembled area with trailing
// wildcard selector ".*", return current index
// as match index.
if perm == fmt.Sprintf("%s.*", assembled) {
return i
}
}
// Otherwise, return negative match index.
return -1
}
// permissionCheckDNs tries to match domainName on the
// passed perm and returns the match index and if
// it matched and perm is not prefixed with '-'.
func permissionCheckDNs(domainName, perm string) (int, bool) {
if perm == "" {
return -1, false
}
if perm[0] != '+' && perm[0] != '-' {
return -1, false
}
match := permissionMatchDNs(domainName, perm[1:])
if match < 0 {
return match, false
}
return match, !strings.HasPrefix(perm, "-")
}