/
originmatcher.go
108 lines (94 loc) · 2.3 KB
/
originmatcher.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
package originmatcher
import (
"errors"
"fmt"
"strings"
)
var errTryNextParser = errors.New("try next parser")
type matcher interface {
MatchOrigin(s string) bool
String() string
}
type T struct {
matchers []matcher
}
// String returns the original string that was parsed into t.
func (t *T) String() string {
specs := []string{}
for _, matcher := range t.matchers {
specs = append(specs, matcher.String())
}
return strings.Join(specs, ",")
}
// MatchOrigin tells whether s is an allowed origin.
// s typically should be the value of HTTP header "Origin".
// MatchOrigin is lenient that extra userinfo, path , query or fragment in s are ignored silently.
func (t *T) MatchOrigin(s string) bool {
for _, o := range t.matchers {
if o.MatchOrigin(s) {
return true
}
}
return false
}
func parseSingle(s string) (m matcher, err error) {
m, err = parseWildcard(s)
if err == nil {
return m, nil
}
if !errors.Is(err, errTryNextParser) {
return nil, err
}
// We try hierarchical first so that
// input like "localhost:3000" would not be
// misunderstood as scheme=localhost; opaque=3000
m, err = parseHierarchical(s)
if err == nil {
return m, nil
}
if !errors.Is(err, errTryNextParser) {
return nil, err
}
m, err = parseOpaque(s)
return
}
// Parse parses s into T, where s is comma-separated origin specs.
func Parse(s string) (*T, error) {
// strings.Split("", ",") == [""]
// which results in invalid spec
if s == "" {
return &T{
matchers: []matcher{},
}, nil
}
return New(strings.Split(s, ","))
}
// New creates a T from a slice of origin spec.
// An origin spec consist of a mandatory host, with optionally scheme and port.
// As a special case, "*" matches any origin.
// An origin spec is lenient that extra userinfo, path, query or fragment are ignored silently.
func New(specs []string) (*T, error) {
t := &T{
matchers: []matcher{},
}
for _, spec := range specs {
o, err := parseSingle(spec)
if err != nil {
return nil, err
}
t.matchers = append(t.matchers, o)
}
return t, nil
}
// CheckValidSpecStrict checks if spec is valid and does not contain extra information.
func CheckValidSpecStrict(spec string) (err error) {
o, err := parseSingle(spec)
if err != nil {
return
}
if o.String() != spec {
err = fmt.Errorf("%v is not strict", spec)
return
}
return
}