-
-
Notifications
You must be signed in to change notification settings - Fork 363
/
request_handler.go
357 lines (310 loc) · 11.1 KB
/
request_handler.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
* Copyright © 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* 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.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/
package proxy
import (
"encoding/json"
"net/http"
"github.com/ory/herodot"
"github.com/ory/x/errorsx"
"github.com/ory/oathkeeper/driver/configuration"
"github.com/ory/oathkeeper/x"
"github.com/ory/oathkeeper/pipeline/authn"
"github.com/ory/oathkeeper/pipeline/authz"
pe "github.com/ory/oathkeeper/pipeline/errors"
"github.com/ory/oathkeeper/pipeline/mutate"
"github.com/pkg/errors"
"github.com/ory/oathkeeper/helper"
"github.com/ory/oathkeeper/rule"
)
type requestHandlerRegistry interface {
x.RegistryWriter
x.RegistryLogger
authn.Registry
authz.Registry
mutate.Registry
pe.Registry
}
type RequestHandler struct {
r requestHandlerRegistry
c configuration.Provider
}
type whenConfig struct {
When pe.Whens `json:"when"`
}
func NewRequestHandler(r requestHandlerRegistry, c configuration.Provider) *RequestHandler {
return &RequestHandler{r: r, c: c}
}
// matchesWhen
func (d *RequestHandler) matchesWhen(w http.ResponseWriter, r *http.Request, h pe.Handler, config json.RawMessage, handleErr error) error {
var when whenConfig
if err := d.c.ErrorHandlerConfig(h.GetID(), config, &when); err != nil {
d.r.Writer().WriteError(w, r, pe.NewErrErrorHandlerMisconfigured(h, err))
return err
}
if err := pe.MatchesWhen(when.When, r, handleErr); err != nil {
if errorsx.Cause(err) == pe.ErrHandlerNotResponsible {
return err
}
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(`Unable to execute error handler "%s". This is either a bug or a configuration issue and should be reported to the administrator. Returned error: "%s". Original error: "%s"`, h.GetID(), err, handleErr)))
return err
}
return nil
}
func (d *RequestHandler) HandleError(w http.ResponseWriter, r *http.Request, rl *rule.Rule, handleErr error) {
if rl == nil {
// Create a new, empty rule.
rl = new(rule.Rule)
}
var h pe.Handler
var config json.RawMessage
for _, re := range rl.Errors {
handler, err := d.r.PipelineErrorHandler(re.Handler)
if err != nil {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
"Unable to find error handler named: %s. This is a configuration issue and should be reported to the administrator.", re.Handler,
)))
return
}
if err := d.matchesWhen(w, r, handler, re.Config, handleErr); errorsx.Cause(err) == pe.ErrHandlerNotResponsible {
continue
} else if err != nil {
// error was handled already by d.matchesWhen
return
}
if h != nil {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
`Found more than one error handlers to be responsible for this request. This is a configuration error that needs to be resolved by the system administrator."`,
)))
return
}
h = handler
config = re.Config
}
if h == nil {
for _, name := range d.c.ErrorHandlerFallbackSpecificity() {
if !d.c.ErrorHandlerIsEnabled(name) {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
`Fallback error handler "%s" was requested but is disabled or unknown. This is a configuration issue and should be reported to the administrator.`, name,
)))
return
}
handler, err := d.r.PipelineErrorHandler(name)
if err != nil {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
`Unable to find fallback error handler named "%s". This is a configuration issue and should be reported to the administrator.`, name,
)))
return
}
if err := d.matchesWhen(w, r, handler, nil, handleErr); errorsx.Cause(err) == pe.ErrHandlerNotResponsible {
continue
} else if err != nil {
// error was handled already by d.matchesWhen
return
}
h = handler
break
}
}
if h == nil {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
"Unable to handle HTTP request because no matching error handling strategy was found. This is a bug and should be reported to: http://github.com/ory/oathkeeper",
)))
return
}
if err := h.Validate(config); err != nil {
d.r.Writer().WriteError(w, r, err)
return
}
if err := h.Handle(w, r, config, rl, handleErr); err != nil {
d.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrInternalServerError.WithReasonf(
`Unable to execute error handler "%s". This is either a bug or a configuration issue and should be reported to the administrator. Returned error: "%s". Original error: "%s"`, h.GetID(), err, handleErr,
)))
return
}
}
func (d *RequestHandler) HandleRequest(r *http.Request, rl *rule.Rule) (session *authn.AuthenticationSession, err error) {
var found bool
fields := map[string]interface{}{
"http_method": r.Method,
"http_url": r.URL.String(),
"http_host": r.Host,
"http_user_agent": r.UserAgent(),
"rule_id": rl.ID,
}
// initialize the session used during all the flow
session = d.InitializeAuthnSession(r, rl)
if len(rl.Authenticators) == 0 {
err = errors.New("No authentication handler was set in the rule")
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("reason_id", "authentication_handler_missing").
Warn("No authentication handler was set in the rule")
return nil, err
}
for _, a := range rl.Authenticators {
anh, err := d.r.PipelineAuthenticator(a.Handler)
if err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authentication_handler", a.Handler).
WithField("reason_id", "unknown_authentication_handler").
Warn("Unknown authentication handler requested")
return nil, err
}
if err := anh.Validate(a.Config); err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authentication_handler", a.Handler).
WithField("reason_id", "invalid_authentication_handler").
Warn("Unable to validate use of authentication handler")
return nil, err
}
err = anh.Authenticate(r, session, a.Config, rl)
if err != nil {
switch errors.Cause(err).Error() {
case authn.ErrAuthenticatorNotResponsible.Error():
// The authentication handler is not responsible for handling this request, skip to the next handler
break
// case ErrAuthenticatorBypassed.Error():
// The authentication handler says that no further authentication/authorization is required, and the request should
// be forwarded to its final destination.
// return nil
case helper.ErrUnauthorized.ErrorField:
d.r.Logger().Info(err)
return nil, err
default:
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authentication_handler", a.Handler).
WithField("reason_id", "authentication_handler_error").
Warn("The authentication handler encountered an error")
return nil, err
}
} else {
// The first authenticator that matches must return the session
found = true
fields["subject"] = session.Subject
break
}
}
if !found {
err := errors.WithStack(helper.ErrUnauthorized)
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("reason_id", "authentication_handler_no_match").
Warn("No authentication handler was responsible for handling the authentication request")
return nil, err
}
azh, err := d.r.PipelineAuthorizer(rl.Authorizer.Handler)
if err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authorization_handler", rl.Authorizer.Handler).
WithField("reason_id", "unknown_authorization_handler").
Warn("Unknown authentication handler requested")
return nil, err
}
if err := azh.Validate(rl.Authorizer.Config); err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authorization_handler", rl.Authorizer.Handler).
WithField("reason_id", "invalid_authorization_handler").
Warn("Unable to validate use of authorization handler")
return nil, err
}
if err := azh.Authorize(r, session, rl.Authorizer.Config, rl); err != nil {
d.r.Logger().
WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("authorization_handler", rl.Authorizer.Handler).
WithField("reason_id", "authorization_handler_error").
Warn("The authorization handler encountered an error")
return nil, err
}
if len(rl.Mutators) == 0 {
err = errors.New("No mutation handler was set in the rule")
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("reason_id", "mutation_handler_missing").
Warn("No mutation handler was set in the rule")
return nil, err
}
for _, m := range rl.Mutators {
sh, err := d.r.PipelineMutator(m.Handler)
if err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("access_url", r.URL.String()).
WithField("mutation_handler", m.Handler).
WithField("reason_id", "unknown_mutation_handler").
Warn("Unknown mutator requested")
return nil, err
}
if err := sh.Validate(m.Config); err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("mutation_handler", m.Handler).
WithField("reason_id", "invalid_mutation_handler").
Warn("Invalid mutator requested")
return nil, err
}
if err := sh.Mutate(r, session, m.Config, rl); err != nil {
d.r.Logger().WithError(err).
WithFields(fields).
WithField("granted", false).
WithField("mutation_handler", m.Handler).
WithField("reason_id", "mutation_handler_error").
Warn("The mutation handler encountered an error")
return nil, err
}
}
return session, nil
}
// InitializeAuthnSession reates an authentication session and initializes it with a Match context if possible
func (d *RequestHandler) InitializeAuthnSession(r *http.Request, rl *rule.Rule) *authn.AuthenticationSession {
session := &authn.AuthenticationSession{
Subject: "",
}
values, err := rl.ExtractRegexGroups(d.c.AccessRuleMatchingStrategy(), r.URL)
if err != nil {
d.r.Logger().WithError(err).
WithField("rule_id", rl.ID).
WithField("access_url", r.URL.String()).
WithField("reason_id", "capture_groups_error").
Warn("Unable to capture the groups for the MatchContext")
} else {
session.MatchContext = authn.MatchContext{
RegexpCaptureGroups: values,
URL: r.URL,
}
}
return session
}