forked from greenpau/go-authcrunch
/
authenticate.go
331 lines (294 loc) · 9.84 KB
/
authenticate.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
// Copyright 2022 Paul Greenberg greenpau@outlook.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package authz
import (
"context"
"github.com/andrewsonpradeep/go-authcrunch/pkg/authz/bypass"
"github.com/andrewsonpradeep/go-authcrunch/pkg/authz/handlers"
"github.com/andrewsonpradeep/go-authcrunch/pkg/errors"
"github.com/andrewsonpradeep/go-authcrunch/pkg/requests"
"github.com/andrewsonpradeep/go-authcrunch/pkg/user"
"github.com/andrewsonpradeep/go-authcrunch/pkg/util"
addrutil "github.com/andrewsonpradeep/go-authcrunch/pkg/util/addr"
"github.com/andrewsonpradeep/go-authcrunch/pkg/util/validate"
"go.uber.org/zap"
"net/http"
"net/url"
"strings"
)
var (
placeholders = []string{
"http.request.uri", "uri",
"url",
}
)
// Authenticate authorizes HTTP requests.
func (g *Gatekeeper) Authenticate(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
// Perform authorization bypass checks
if g.bypassEnabled && bypass.Match(r, g.config.BypassConfigs) {
ar.Response.Authorized = false
ar.Response.Bypassed = true
g.logger.Info(
"authorization bypassed",
zap.String("session_id", ar.SessionID),
zap.String("request_id", ar.ID),
zap.String("src_ip", addrutil.GetSourceAddress(r)),
zap.String("src_conn_ip", addrutil.GetSourceConnAddress(r)),
zap.String("url", addrutil.GetTargetURL(r)),
)
return nil
}
g.parseSessionID(r, ar)
usr, err := g.tokenValidator.Authorize(context.Background(), r, ar)
if err != nil {
ar.Response.Error = err
return g.handleUnauthorizedUser(w, r, ar)
}
return g.handleAuthorizedUser(w, r, ar, usr)
}
// handleAuthorizedUser handles authorized requests.
func (g *Gatekeeper) handleAuthorizedUser(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest, usr *user.User) error {
g.injectHeaders(r, usr)
g.stripAuthToken(r, usr)
ar.Response.Authorized = true
if usr.Cached {
ar.Response.User = usr.GetRequestIdentity()
return nil
}
ar.Response.User = usr.BuildRequestIdentity(g.config.UserIdentityField)
if err := g.tokenValidator.CacheUser(usr); err != nil {
g.logger.Error(
"token caching error",
zap.String("session_id", ar.SessionID),
zap.String("request_id", ar.ID),
zap.Error(err),
)
}
return nil
}
// parseSessionID extracts Session ID from HTTP request.
func (g *Gatekeeper) parseSessionID(r *http.Request, ar *requests.AuthorizationRequest) {
if cookie, err := r.Cookie("AUTHP_SESSION_ID"); err == nil {
v, err := url.Parse(cookie.Value)
if err == nil && v.String() != "" {
ar.SessionID = util.SanitizeSessionID(v.String())
}
}
}
// handleUnauthorizedUser handles failed authorization requests.
func (g *Gatekeeper) handleUnauthorizedUser(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
err := ar.Response.Error
g.logger.Debug(
"token validation error",
zap.String("session_id", ar.SessionID),
zap.String("request_id", ar.ID),
zap.Error(err),
)
switch {
case (err == errors.ErrAccessNotAllowed) || (err == errors.ErrAccessNotAllowedByPathACL):
return g.handleAuthorizeWithForbidden(w, r, ar)
case (err == errors.ErrBasicAuthFailed) || (err == errors.ErrAPIKeyAuthFailed):
return g.handleAuthorizeWithAuthFailed(w, r, ar)
case err == errors.ErrCryptoKeyStoreTokenData:
return g.handleAuthorizeWithBadRequest(w, r, ar)
}
g.expireAuthCookies(w, r)
if !g.config.AuthRedirectDisabled {
return g.handleAuthorizeWithRedirect(w, r, ar)
}
return err
}
// expireAuthCookies sends cookie delete in HTTP response.
func (g *Gatekeeper) expireAuthCookies(w http.ResponseWriter, r *http.Request) {
cookies := g.tokenValidator.GetAuthCookies()
if cookies == nil {
return
}
for _, cookie := range r.Cookies() {
if _, exists := cookies[cookie.Name]; !exists {
continue
}
w.Header().Add("Set-Cookie", cookie.Name+"=delete; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT")
}
return
}
// handleAuthorizeWithAuthFailed handles failed authorization requests based on
// basic authentication and API keys.
func (g *Gatekeeper) handleAuthorizeWithAuthFailed(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
g.expireAuthCookies(w, r)
w.WriteHeader(401)
w.Write([]byte(`401 Unauthorized`))
return ar.Response.Error
}
// handleAuthorizeWithBadRequest handles failed authorization requests where
// user data was insufficient to establish a user.
func (g *Gatekeeper) handleAuthorizeWithBadRequest(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
g.expireAuthCookies(w, r)
w.WriteHeader(400)
w.Write([]byte(`400 Bad Request`))
return ar.Response.Error
}
// handleAuthorizeWithForbidden handles forbidden responses.
func (g *Gatekeeper) handleAuthorizeWithForbidden(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
if g.config.ForbiddenURL == "" {
w.WriteHeader(403)
w.Write([]byte(`Forbidden`))
return ar.Response.Error
}
if strings.Contains(g.config.ForbiddenURL, "{") && strings.Contains(g.config.ForbiddenURL, "}") {
// Run through placeholder replacer.
redirectLocation := g.config.ForbiddenURL
for _, placeholder := range placeholders {
switch placeholder {
case "uri", "http.request.uri":
redirectLocation = strings.ReplaceAll(redirectLocation, "{"+placeholder+"}", r.URL.String())
case "url":
redirectLocation = strings.ReplaceAll(redirectLocation, "{"+placeholder+"}", util.GetCurrentURL(r))
}
}
w.Header().Set("Location", redirectLocation)
} else {
w.Header().Set("Location", g.config.ForbiddenURL)
}
w.WriteHeader(303)
w.Write([]byte(`Forbidden`))
return ar.Response.Error
}
func (g *Gatekeeper) handleAuthorizeWithRedirect(w http.ResponseWriter, r *http.Request, ar *requests.AuthorizationRequest) error {
if ar.Redirect.AuthURL == "" {
ar.Redirect.AuthURL = g.config.AuthURLPath
}
ar.Redirect.QueryDisabled = g.config.AuthRedirectQueryDisabled
ar.Redirect.QueryParameter = g.config.AuthRedirectQueryParameter
if g.config.AuthRedirectStatusCode > 0 {
ar.Redirect.StatusCode = g.config.AuthRedirectStatusCode
}
if len(g.config.LoginHintValidators) > 0 {
g.handleLoginHint(r, ar)
}
if g.config.AdditionalScopes {
g.handleAdditionalScopes(r, ar)
}
if g.config.RedirectWithJavascript {
g.logger.Debug(
"redirecting unauthorized user",
zap.String("session_id", ar.SessionID),
zap.String("request_id", ar.ID),
zap.String("method", "js"),
)
handlers.HandleJavascriptRedirect(w, r, ar)
} else {
g.logger.Debug(
"redirecting unauthorized user",
zap.String("session_id", ar.SessionID),
zap.String("request_id", ar.ID),
zap.String("method", "location"),
)
handlers.HandleLocationHeaderRedirect(w, r, ar)
}
return ar.Response.Error
}
func (g *Gatekeeper) stripAuthToken(r *http.Request, usr *user.User) {
if !g.config.StripTokenEnabled {
return
}
switch usr.TokenSource {
case "cookie":
if usr.TokenName == "" {
return
}
if _, exists := r.Header["Cookie"]; !exists {
return
}
for i, entry := range r.Header["Cookie"] {
var updatedEntry []string
var updateCookie bool
for _, cookie := range strings.Split(entry, ";") {
s := strings.TrimSpace(cookie)
if strings.HasPrefix(s, usr.TokenName+"=") {
// Skip the cookie matching the token name.
updateCookie = true
continue
}
if strings.Contains(s, usr.Token) {
// Skip the cookie with the value matching user token.
updateCookie = true
continue
}
updatedEntry = append(updatedEntry, cookie)
}
if !updateCookie {
continue
}
r.Header["Cookie"][i] = strings.Join(updatedEntry, ";")
}
}
}
func (g *Gatekeeper) injectHeaders(r *http.Request, usr *user.User) {
if g.config.PassClaimsWithHeaders {
// Inject default X-Token headers.
headers := usr.GetRequestHeaders()
if headers == nil {
headers = make(map[string]string)
if usr.Claims.Name != "" {
headers["X-Token-User-Name"] = usr.Claims.Name
}
if usr.Claims.Email != "" {
headers["X-Token-User-Email"] = usr.Claims.Email
}
if len(usr.Claims.Roles) > 0 {
headers["X-Token-User-Roles"] = strings.Join(usr.Claims.Roles, " ")
}
if usr.Claims.Subject != "" {
headers["X-Token-Subject"] = usr.Claims.Subject
}
usr.SetRequestHeaders(headers)
}
for k, v := range headers {
if g.injectedHeaders != nil {
if _, exists := g.injectedHeaders[k]; exists {
continue
}
}
r.Header.Set(k, v)
}
}
// Inject custom headers.
for _, entry := range g.config.HeaderInjectionConfigs {
if v := usr.GetClaimValueByField(entry.Field); v != "" {
r.Header.Set(entry.Header, v)
}
}
}
func (g *Gatekeeper) handleLoginHint(r *http.Request, ar *requests.AuthorizationRequest) {
if loginHint := r.URL.Query().Get("login_hint"); loginHint != "" {
if err := validate.LoginHint(loginHint, g.config.LoginHintValidators); err != nil {
g.logger.Warn(err.Error())
} else {
ar.Redirect.LoginHint = loginHint
}
}
}
func (g *Gatekeeper) handleAdditionalScopes(r *http.Request, ar *requests.AuthorizationRequest) {
if additionalScopes := r.URL.Query().Get("additional_scopes"); additionalScopes != "" {
if err := validate.AdditionalScopes(additionalScopes); err != nil {
g.logger.Warn("Provide a valid set of additional scopes in the query parameter (ex.: scope_A scopeB)",
zap.String("additional_scopes", additionalScopes),
zap.Error(err),
)
} else {
ar.Redirect.AdditionalScopes = additionalScopes
}
}
}