-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathroute.go
337 lines (299 loc) · 8.52 KB
/
route.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
337
package j8a
import (
"errors"
"fmt"
"github.com/asaskevich/govalidator"
urlverifier "github.com/davidmytton/url-verifier"
"golang.org/x/net/idna"
"net/http"
"net/url"
"regexp"
"strings"
"time"
)
// Aboutj8a special Resource alias for internal endpoint
const about string = "about"
type WeightedSlugs []string
type RoutePath WeightedSlugs
type DNSNameComponents WeightedSlugs
func NewRoutePath(r Route) RoutePath {
rps := strings.Split(r.Path, slashS)
return RoutePath(WeightedSlugs(rps).trimEmptySlug())
}
func NewDNSNameComponents(r Route) DNSNameComponents {
rhs := strings.Split(r.PunyHost, dot)
for i, j := 0, len(rhs)-1; i < j; i, j = i+1, j-1 {
rhs[i], rhs[j] = rhs[j], rhs[i]
}
return DNSNameComponents(WeightedSlugs(rhs).trimEmptySlug())
}
func (w WeightedSlugs) trimEmptySlug() WeightedSlugs {
if len(w[0]) == 0 && len(w) > 1 {
w = w[1:]
}
return w
}
func (w WeightedSlugs) trimNextSlug() (WeightedSlugs, error) {
if len(w) > 1 {
w = w[1:]
return w, nil
} else {
return nil, errors.New("no more slugs")
}
}
func (w WeightedSlugs) Less(w2 WeightedSlugs) bool {
less := false
if len(w[0]) > len(w2[0]) {
less = true
} else if len(w[0]) == len(w2[0]) {
wn, e := w.trimNextSlug()
w2n, e2 := w2.trimNextSlug()
if e == nil && e2 == nil {
less = wn.Less(w2n)
} else if e2 != nil {
/////aaarrggghhh this fixes an issue because we share sorting slug paths and DNS name segments with the same alg
if w[0] == STAR {
less = false
} else {
less = true
}
}
}
return less
}
type Routes []Route
func (s Routes) Len() int {
return len(s)
}
func (s Routes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Routes) Less(i, j int) bool {
if s[i].PunyHost == s[j].PunyHost {
return s.PathIsLess(i, j)
} else {
return s.HostIsLess(i, j)
}
}
func (s Routes) HostIsLess(i int, j int) bool {
return WeightedSlugs(NewDNSNameComponents(s[i])).Less(WeightedSlugs(NewDNSNameComponents(s[j])))
}
func (s Routes) PathIsLess(i int, j int) bool {
pis := NewRoutePath(s[i])
pjs := NewRoutePath(s[j])
less := false
if (s[i].PathType == exact && s[j].PathType == exact) || (s[i].PathType == prefixS && s[j].PathType == prefixS) {
less = WeightedSlugs(pis).Less(WeightedSlugs(pjs))
} else {
less = s[i].PathType == exact
}
return less
}
// Route maps a Path to an upstream resource
type Route struct {
Host string //idna host pattern
PunyHost string //punycode host pattern
CompiledPunyHost *regexp.Regexp // as regex
Path string
PathType string // exact | prefix
CompiledPathRegex *regexp.Regexp
Transform string
Resource string
Policy string
Jwt string
}
const wildcard = "*"
func (route *Route) validHostPattern() (bool, error) {
//first check the name is a valid idna name.
p := idna.New(
idna.ValidateLabels(true),
//this has to be off it disallows * for registration
//idna.ValidateForRegistration(),
idna.StrictDomainName(true))
_, err := p.ToUnicode(route.Host)
if err != nil {
return false, err
} else {
a, err := p.ToASCII(route.Host)
if err != nil {
return false, err
}
for i, j := range strings.Split(a, ".") {
if len(j) == 0 {
return false, errors.New("dns name segments cannot be empty string")
}
if j == wildcard && i != 0 {
return false, errors.New("wildcard can only be at far left of domain name")
}
if strings.Contains(j, wildcard) && len(j) > 1 {
return false, errors.New("wildcard can only be used for entire subdomains, not regex style")
}
}
//now perform DNS name validation on ascii format.
v2 := govalidator.IsDNSName(a)
if v2 {
return true, nil
} else {
//this validator does not pass wildcard names so we have to
if strings.HasPrefix(a, wildcard) {
return true, nil
} else {
return false, errors.New("not a valid DNS name after idna normalisation " + a)
}
}
}
}
func (route *Route) compileHostPattern() error {
if b, e := route.validHostPattern(); b {
al, e1 := idna.ToASCII(route.Host)
if e1 == nil {
route.PunyHost = al
re, _ := regexp.Compile(startS + al)
route.CompiledPunyHost = re
}
return e1
} else {
return e
}
}
func (route *Route) validPath() (bool, error) {
const fakeHost = "http://127.0.0.1"
defaultError := errors.New(fmt.Sprintf("route %v not a valid URL path", route.Path))
_, err := url.ParseRequestURI(fakeHost + route.Path)
if err != nil {
return false, defaultError
}
_, err = url.Parse(fakeHost + route.Path)
if err != nil {
return false, defaultError
}
_, err = urlverifier.NewVerifier().Verify(fakeHost + route.Path)
if err != nil {
return false, defaultError
}
if len(route.Path) == 0 {
return false, defaultError
}
if strings.Contains(route.Path, " ") {
return false, errors.New(fmt.Sprintf("route %v not a valid URL path, may not contain space character", route.Path))
}
if strings.Index(route.Path, "/") != 0 {
return false, errors.New(fmt.Sprintf("route %v not a valid URL path, does not start with '/'", route.Path))
}
if e := route.compilePath(); e != nil {
return false, e
}
return true, nil
}
const startS = "^"
const dollarS = "$"
const exact = "exact"
func (route *Route) compilePath() error {
compileMe := route.Path
if string(compileMe[0]) != startS {
compileMe = startS + compileMe
}
if strings.EqualFold(exact, route.PathType) {
compileMe = compileMe + dollarS
}
var err error
route.CompiledPathRegex, err = regexp.Compile(compileMe)
return err
}
const slashS = "/"
func (route Route) match(request *http.Request) bool {
if len(route.PunyHost) > 0 {
return route.matchHostHeader(request) &&
route.matchURIPath(request)
} else {
return route.matchURIPath(request)
}
}
func (route Route) matchHostHeader(request *http.Request) bool {
//safety measure in case we got a unicode host header
al, _ := idna.ToASCII(request.Host)
return route.CompiledPunyHost.MatchString(al) &&
len(strings.Split(route.PunyHost, ".")) == len(strings.Split(request.Host, "."))
}
func (route Route) matchURIPath(request *http.Request) bool {
match := route.CompiledPathRegex.MatchString(request.URL.Path)
if !match &&
route.PathType == prefixS &&
len(request.URL.Path) > 0 &&
string(request.URL.Path[len(request.URL.Path)-1]) != slashS {
match = route.CompiledPathRegex.MatchString(request.URL.Path + slashS)
}
return match
}
// Deprecated
func (route Route) matchURI_Naive(request *http.Request) bool {
return route.CompiledPathRegex.MatchString(request.URL.Path)
}
const upstreamResourceMapped = "upstream resource mapped"
const policyMsg = "policy"
const upResource = "upResource"
const routeMsg = "route"
const labelMsg = "label"
const defaultMsg = "default"
const routeMapped = "route mapped"
const routeNotMapped = "route not mapped"
const emptyString = ""
// maps a route to a URL. Returns the URL, the name of the mapped policy and whether mapping was successful
func (route Route) mapURL(proxy *Proxy) (*URL, string, bool) {
var policy Policy
var policyLabel string
if len(route.Policy) > 0 {
policy = Runner.Policies[route.Policy]
policyLabel = policy.resolveLabel()
}
resource := Runner.Resources[route.Resource]
if resource == nil {
return nil, emptyString, false
}
//if a policy exists, we match resources with a label. TODO: this should be an interface
if len(route.Policy) > 0 {
for _, resourceMapping := range resource {
for _, resourceLabel := range resourceMapping.Labels {
if policyLabel == resourceLabel {
infoOrTraceEv(proxy).Str(routeMsg, route.Path).
Str(upResource, resourceMapping.URL.String()).
Str(labelMsg, resourceLabel).
Str(policyMsg, route.Policy).
Str(XRequestID, proxy.XRequestID).
Int64(dwnElpsdMicros, time.Since(proxy.Dwn.startDate).Microseconds()).
Msg(upstreamResourceMapped)
return &resourceMapping.URL, policyLabel, true
}
}
}
} else {
infoOrTraceEv(proxy).
Str(routeMsg, route.Path).
Str(policyMsg, defaultMsg).
Str(XRequestID, proxy.XRequestID).
Str(upResource, resource[0].URL.String()).
Msg(routeMapped)
return &resource[0].URL, defaultMsg, true
}
infoOrTraceEv(proxy).
Str(routeMsg, route.Path).
Str(XRequestID, proxy.XRequestID).
Msg(routeNotMapped)
return nil, emptyString, false
}
func (route Route) hasJwt() bool {
return len(route.Jwt) > 0
}
type RoutePathTypes []string
func NewRoutePathTypes() RoutePathTypes {
return RoutePathTypes([]string{"exact", "prefix"})
}
func (r RoutePathTypes) isValid(t string) bool {
m := false
for _, rp := range r {
if strings.EqualFold(t, rp) {
m = true
}
}
return m
}