-
Notifications
You must be signed in to change notification settings - Fork 569
/
cors.go
75 lines (68 loc) · 2.12 KB
/
cors.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
package httpmw
import (
"net/http"
"net/url"
"regexp"
"github.com/go-chi/cors"
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
)
const (
// Server headers.
AccessControlAllowOriginHeader = "Access-Control-Allow-Origin"
AccessControlAllowCredentialsHeader = "Access-Control-Allow-Credentials"
AccessControlAllowMethodsHeader = "Access-Control-Allow-Methods"
AccessControlAllowHeadersHeader = "Access-Control-Allow-Headers"
VaryHeader = "Vary"
// Client headers.
OriginHeader = "Origin"
AccessControlRequestMethodsHeader = "Access-Control-Request-Methods"
AccessControlRequestHeadersHeader = "Access-Control-Request-Headers"
)
//nolint:revive
func Cors(allowAll bool, origins ...string) func(next http.Handler) http.Handler {
if len(origins) == 0 {
// The default behavior is '*', so putting the empty string defaults to
// the secure behavior of blocking CORs requests.
origins = []string{""}
}
if allowAll {
origins = []string{"*"}
}
return cors.Handler(cors.Options{
AllowedOrigins: origins,
// We only need GET for latency requests
AllowedMethods: []string{http.MethodOptions, http.MethodGet},
AllowedHeaders: []string{"Accept", "Content-Type", "X-LATENCY-CHECK", "X-CSRF-TOKEN"},
// Do not send any cookies
AllowCredentials: false,
})
}
func WorkspaceAppCors(regex *regexp.Regexp, app appurl.ApplicationURL) func(next http.Handler) http.Handler {
return cors.Handler(cors.Options{
AllowOriginFunc: func(r *http.Request, rawOrigin string) bool {
origin, err := url.Parse(rawOrigin)
if rawOrigin == "" || origin.Host == "" || err != nil {
return false
}
subdomain, ok := appurl.ExecuteHostnamePattern(regex, origin.Host)
if !ok {
return false
}
originApp, err := appurl.ParseSubdomainAppURL(subdomain)
if err != nil {
return false
}
return ok && originApp.Username == app.Username
},
AllowedMethods: []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
})
}