-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolicy.go
More file actions
96 lines (87 loc) · 1.93 KB
/
policy.go
File metadata and controls
96 lines (87 loc) · 1.93 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
package sts
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
const (
allowedVersion = "STSv1"
)
const (
Policy_ENFORCE Mode = iota
Policy_TESTING
Policy_NONE
)
type (
// Mode can be Policy_ENFORCE, Policy_TESTING, or Policy_NONE.
Mode int32
// Policy represents a parsed policy.
Policy struct {
Mode Mode
MXs []string
Expires time.Time
Id string
}
)
var (
// Mockable for testing.
clock = time.Now
validHostname = regexp.MustCompile(`^([*]\.)?([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`)
)
// ParsePolicy returns a Policy from a raw string, or error.
func ParsePolicy(raw string) (Policy, error) {
p := Policy{}
// Split by lines.
lines := strings.Split(raw, "\n")
for _, l := range lines {
l = strings.TrimSpace(l)
if l == "" {
continue
}
kv := strings.SplitN(l, ":", 2)
if len(kv) < 2 {
return p, fmt.Errorf("invalid syntax, line %s", l)
}
key, val := strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
switch key {
case "version":
if val != allowedVersion {
return p, fmt.Errorf("invalid version: %s", val)
}
case "mode":
switch val {
case "enforce":
p.Mode = Policy_ENFORCE
case "testing":
p.Mode = Policy_TESTING
case "none":
p.Mode = Policy_NONE
default:
return p, fmt.Errorf("invalid mode: %s", val)
}
case "max_age":
v, err := strconv.ParseInt(val, 10, 32)
if err != nil {
return p, fmt.Errorf("invalid max_age: %v", err)
}
if v == 0 {
return p, fmt.Errorf("policy was revoked (max_age=0)")
}
p.Expires = clock().Add(time.Duration(v) * time.Second)
case "mx":
if !validHostname.MatchString(val) {
return p, fmt.Errorf("invalid mx: %s", val)
}
if p.MXs == nil {
p.MXs = []string{val}
} else {
p.MXs = append(p.MXs, val)
}
default:
return p, fmt.Errorf("unrecognized key: %s", key)
}
}
return p, nil
}