/
role.go
82 lines (71 loc) · 1.85 KB
/
role.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
package roles
import (
"fmt"
"strings"
"unicode"
)
// Role is a deprecated type.
type Role string
const defaultRole = Role("*")
func (r Role) IsDefault() bool {
return r == defaultRole
}
func (r Role) Assign() func(interface{}) {
return func(v interface{}) {
type roler interface {
WithRole(string)
}
if ri, ok := v.(roler); ok {
ri.WithRole(string(r))
}
}
}
func (r Role) Proto() *string {
s := string(r)
return &s
}
// IsStrictSubroleOf returns true if left is a strict subrole of right.
func IsStrictSubroleOf(left, right string) bool {
return len(left) > len(right) && left[len(right)] == '/' && strings.HasPrefix(left, right)
}
var illegalComponents = map[string]struct{}{
".": struct{}{},
"..": struct{}{},
"*": struct{}{},
}
func Parse(s string) (string, error) {
if s == string(defaultRole) {
return s, nil
}
if strings.HasPrefix(s, "/") {
return "", fmt.Errorf("role %q cannot start with a slash", s)
}
if strings.HasSuffix(s, "/") {
return "", fmt.Errorf("role %q cannot end with a slash", s)
}
// validate each component in the role path
for _, part := range strings.Split(s, "/") {
if part == "" {
return "", fmt.Errorf("role %q cannot contain two adjacent slashes", s)
}
if bad, found := illegalComponents[part]; found {
return "", fmt.Errorf("role %q cannot contain %q as a component", s, bad)
}
if strings.HasPrefix(part, "-") {
return "", fmt.Errorf("role component %q is invalid because it begins with a dash", part)
}
if strings.IndexFunc(part, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) > -1 {
return "", fmt.Errorf("role component %q is invalid because it contains backspace or whitespace", part)
}
}
return s, nil
}
func Validate(roles ...string) error {
for i := range roles {
_, err := Parse(roles[i])
if err != nil {
return err
}
}
return nil
}