/
http_secure_redirect.go
199 lines (171 loc) · 6 KB
/
http_secure_redirect.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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package x
import (
"net/http"
"net/url"
"strings"
"github.com/ory/kratos/text"
"github.com/golang/gddo/httputil"
"github.com/pkg/errors"
"github.com/ory/herodot"
"github.com/ory/x/stringsx"
"github.com/ory/x/urlx"
"github.com/samber/lo"
"github.com/ory/kratos/driver/config"
)
type secureRedirectOptions struct {
allowlist []url.URL
defaultReturnTo *url.URL
returnTo string
sourceURL string
}
type SecureRedirectOption func(*secureRedirectOptions)
// SecureRedirectAllowURLs allows the given URLs for redirects.
func SecureRedirectAllowURLs(urls []url.URL) SecureRedirectOption {
return func(o *secureRedirectOptions) {
o.allowlist = append(o.allowlist, urls...)
}
}
// SecureRedirectUseSourceURL uses the given source URL (checks the `?return_to` value)
// instead of r.URL.
func SecureRedirectUseSourceURL(source string) SecureRedirectOption {
return func(o *secureRedirectOptions) {
o.sourceURL = source
}
}
// SecureRedirectReturnTo uses the provided URL to redirect the user to it.
func SecureRedirectReturnTo(returnTo string) SecureRedirectOption {
return func(o *secureRedirectOptions) {
o.returnTo = returnTo
}
}
// SecureRedirectAllowSelfServiceURLs allows the caller to define `?return_to=` values
// which contain the server's URL and `/self-service` path prefix. Useful for redirecting
// to the login endpoint, for example.
func SecureRedirectAllowSelfServiceURLs(publicURL *url.URL) SecureRedirectOption {
return func(o *secureRedirectOptions) {
o.allowlist = append(o.allowlist, *urlx.AppendPaths(publicURL, "/self-service"))
}
}
// SecureRedirectOverrideDefaultReturnTo overrides the defaultReturnTo address specified
// as the second arg.
func SecureRedirectOverrideDefaultReturnTo(defaultReturnTo *url.URL) SecureRedirectOption {
return func(o *secureRedirectOptions) {
o.defaultReturnTo = defaultReturnTo
}
}
// SecureRedirectToIsAllowedHost validates if the redirect_to param is allowed for a given wildcard
func SecureRedirectToIsAllowedHost(returnTo *url.URL, allowed url.URL) bool {
if allowed.Host != "" && allowed.Host[:1] == "*" {
return strings.HasSuffix(strings.ToLower(returnTo.Host), strings.ToLower(allowed.Host)[1:])
}
return strings.EqualFold(allowed.Host, returnTo.Host)
}
// TakeOverReturnToParameter carries over the return_to parameter to a new URL
// If `from` does not contain the `return_to` query parameter, the first non-empty value from `fallback` is used instead.
func TakeOverReturnToParameter(from string, to string, fallback ...string) (string, error) {
fromURL, err := url.Parse(from)
if err != nil {
return "", err
}
returnTo := stringsx.Coalesce(append([]string{fromURL.Query().Get("return_to")}, fallback...)...)
// Empty return_to parameter, return early
if returnTo == "" {
return to, nil
}
toURL, err := url.Parse(to)
if err != nil {
return "", err
}
toQuery := toURL.Query()
toQuery.Set("return_to", returnTo)
toURL.RawQuery = toQuery.Encode()
return toURL.String(), nil
}
// SecureRedirectTo implements a HTTP redirector who mitigates open redirect vulnerabilities by
// working with allow lists.
func SecureRedirectTo(r *http.Request, defaultReturnTo *url.URL, opts ...SecureRedirectOption) (returnTo *url.URL, err error) {
o := &secureRedirectOptions{defaultReturnTo: defaultReturnTo}
for _, opt := range opts {
opt(o)
}
if len(o.allowlist) == 0 {
return o.defaultReturnTo, nil
}
source := RequestURL(r)
if o.sourceURL != "" {
source, err = url.ParseRequestURI(o.sourceURL)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithWrap(err).WithReasonf("Unable to parse the original request URL: %s", err))
}
}
rawReturnTo := stringsx.Coalesce(o.returnTo, source.Query().Get("return_to"))
if rawReturnTo == "" {
return o.defaultReturnTo, nil
}
returnTo, err = url.Parse(rawReturnTo)
if err != nil {
return nil, errors.WithStack(herodot.ErrBadRequest.WithWrap(err).WithReasonf("Unable to parse the return_to query parameter as an URL: %s", err))
}
returnTo.Host = stringsx.Coalesce(returnTo.Host, o.defaultReturnTo.Host)
returnTo.Scheme = stringsx.Coalesce(returnTo.Scheme, o.defaultReturnTo.Scheme)
for _, allowed := range o.allowlist {
if strings.EqualFold(allowed.Scheme, returnTo.Scheme) &&
SecureRedirectToIsAllowedHost(returnTo, allowed) &&
strings.HasPrefix(
stringsx.Coalesce(returnTo.Path, "/"),
stringsx.Coalesce(allowed.Path, "/")) {
return returnTo, nil
}
}
return nil, errors.WithStack(herodot.ErrBadRequest.
WithID(text.ErrIDRedirectURLNotAllowed).
WithReasonf("Requested return_to URL %q is not allowed.", returnTo).
WithDebugf("Allowed domains are: %v", strings.Join(lo.Map(o.allowlist, func(u url.URL, _ int) string {
return u.String()
}), ", ")))
}
func SecureContentNegotiationRedirection(
w http.ResponseWriter, r *http.Request, out interface{},
requestURL string, writer herodot.Writer, c *config.Config,
opts ...SecureRedirectOption,
) error {
switch httputil.NegotiateContentType(r, []string{
"text/html",
"application/json",
}, "text/html") {
case "application/json":
writer.Write(w, r, out)
case "text/html":
fallthrough
default:
ret, err := SecureRedirectTo(r, c.SelfServiceBrowserDefaultReturnTo(r.Context()),
append([]SecureRedirectOption{
SecureRedirectUseSourceURL(requestURL),
SecureRedirectAllowURLs(c.SelfServiceBrowserAllowedReturnToDomains(r.Context())),
SecureRedirectAllowSelfServiceURLs(c.SelfPublicURL(r.Context())),
}, opts...)...,
)
if err != nil {
return err
}
http.Redirect(w, r, ret.String(), http.StatusSeeOther)
}
return nil
}
func ContentNegotiationRedirection(
w http.ResponseWriter, r *http.Request, out interface{}, writer herodot.Writer, returnTo string,
) {
switch httputil.NegotiateContentType(r, []string{
"text/html",
"application/json",
}, "text/html") {
case "application/json":
writer.Write(w, r, out)
case "text/html":
fallthrough
default:
http.Redirect(w, r, returnTo, http.StatusSeeOther)
}
}