-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost_middleware.go
More file actions
71 lines (61 loc) · 1.88 KB
/
Copy pathhost_middleware.go
File metadata and controls
71 lines (61 loc) · 1.88 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
package routeit
import (
"strconv"
"strings"
"github.com/sktylr/routeit/internal/cmp"
"github.com/sktylr/routeit/internal/util"
)
// Middleware that is always registered as the third (or fourth, if the server
// assigns request ID's to each incoming request) piece of middleware for the
// server, and rejects all incoming requests that do not match the server's
// expected Host header pattern. Per RFC-9112 Sec 7.2, the server MUST reject
// the request and return 400: Bad Request when it does not contain a Host
// header. We do the same when the Host header does not match any expected
// values.
func hostValidationMiddleware(allowed []string) Middleware {
if len(allowed) == 0 {
return func(c Chain, rw *ResponseWriter, req *Request) error {
return ErrBadRequest()
}
}
allowed = util.StripDuplicates(allowed)
hosts := make([]*cmp.ExactOrWildcard, 0, len(allowed))
for _, h := range allowed {
if strings.HasPrefix(h, ".") {
hosts = append(hosts, cmp.NewDynamicWildcardMatcher("", h[1:], validSubdomain))
hosts = append(hosts, cmp.NewExactMatcher(h[1:]))
} else {
hosts = append(hosts, cmp.NewExactMatcher(h))
}
}
return func(c Chain, rw *ResponseWriter, req *Request) error {
host, hasHost := req.Headers().First("Host")
if !hasHost {
return ErrBadRequest()
}
// Strip out the port as this is not relevant for Host validation.
lastIndex := strings.LastIndexByte(host, ':')
if lastIndex != -1 && lastIndex != len(host)-1 {
withoutPort := host[lastIndex+1:]
port, err := strconv.Atoi(withoutPort)
if err == nil && port < 65536 {
host = host[:lastIndex]
}
}
matches := false
for _, h := range hosts {
if h.Matches(host) {
matches = true
break
}
}
if !matches {
return ErrBadRequest()
}
req.host = host
return c.Proceed(rw, req)
}
}
func validSubdomain(seg string) bool {
return strings.Count(seg, ".") == 1
}