-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.go
More file actions
67 lines (58 loc) · 1.37 KB
/
security.go
File metadata and controls
67 lines (58 loc) · 1.37 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
package main
import (
"net"
"net/http"
"net/url"
"strings"
)
var allowedWebSocketOrigins []string
func isAllowedWebSocketOrigin(r *http.Request) bool {
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
// Non-browser clients may omit Origin.
return true
}
if originAllowedByConfig(origin) {
return true
}
u, err := url.Parse(origin)
if err != nil || u.Hostname() == "" {
return false
}
return strings.EqualFold(u.Hostname(), hostOnly(r.Host))
}
func setAllowedWebSocketOriginsFromCSV(raw string) {
allowedWebSocketOrigins = allowedWebSocketOrigins[:0]
if strings.TrimSpace(raw) == "" {
allowedWebSocketOrigins = append(allowedWebSocketOrigins, "*")
return
}
for _, item := range strings.Split(raw, ",") {
item = strings.TrimSpace(item)
if item == "" {
continue
}
allowedWebSocketOrigins = append(allowedWebSocketOrigins, item)
}
}
func originAllowedByConfig(origin string) bool {
for _, item := range allowedWebSocketOrigins {
if item == "*" {
return true
}
if strings.EqualFold(item, origin) {
return true
}
}
return false
}
func hostOnly(hostport string) string {
hostport = strings.TrimSpace(hostport)
if hostport == "" {
return ""
}
if host, _, err := net.SplitHostPort(hostport); err == nil {
return strings.Trim(strings.ToLower(host), "[]")
}
return strings.Trim(strings.ToLower(hostport), "[]")
}