/
hook.go
378 lines (327 loc) · 11.7 KB
/
hook.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package login
import (
"context"
"fmt"
"net/http"
"time"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/hydra"
"github.com/ory/kratos/identity"
"github.com/ory/kratos/schema"
"github.com/ory/kratos/selfservice/flow"
"github.com/ory/kratos/selfservice/sessiontokenexchange"
"github.com/ory/kratos/session"
"github.com/ory/kratos/ui/container"
"github.com/ory/kratos/ui/node"
"github.com/ory/kratos/x"
"github.com/ory/kratos/x/events"
"github.com/ory/x/otelx"
)
type (
PreHookExecutor interface {
ExecuteLoginPreHook(w http.ResponseWriter, r *http.Request, a *Flow) error
}
PostHookExecutor interface {
ExecuteLoginPostHook(w http.ResponseWriter, r *http.Request, g node.UiNodeGroup, a *Flow, s *session.Session) error
}
HooksProvider interface {
PreLoginHooks(ctx context.Context) []PreHookExecutor
PostLoginHooks(ctx context.Context, credentialsType identity.CredentialsType) []PostHookExecutor
}
)
type (
executorDependencies interface {
config.Provider
hydra.Provider
identity.PrivilegedPoolProvider
session.ManagementProvider
session.PersistenceProvider
x.CSRFTokenGeneratorProvider
x.WriterProvider
x.LoggingProvider
x.TracingProvider
sessiontokenexchange.PersistenceProvider
FlowPersistenceProvider
HooksProvider
StrategyProvider
}
HookExecutor struct {
d executorDependencies
}
HookExecutorProvider interface {
LoginHookExecutor() *HookExecutor
}
)
func PostHookExecutorNames(e []PostHookExecutor) []string {
names := make([]string, len(e))
for k, ee := range e {
names[k] = fmt.Sprintf("%T", ee)
}
return names
}
func NewHookExecutor(d executorDependencies) *HookExecutor {
return &HookExecutor{d: d}
}
func (e *HookExecutor) requiresAAL2(r *http.Request, s *session.Session, a *Flow) (bool, error) {
err := e.d.SessionManager().DoesSessionSatisfy(r, s, e.d.Config().SessionWhoAmIAAL(r.Context()))
if aalErr := new(session.ErrAALNotSatisfied); errors.As(err, &aalErr) {
if aalErr.PassReturnToAndLoginChallengeParameters(a.RequestURL) != nil {
_ = aalErr.WithDetail("pass_request_params_error", "failed to pass request parameters to aalErr.RedirectTo")
}
return true, aalErr
} else if err != nil {
return true, errors.WithStack(err)
}
return false, nil
}
func (e *HookExecutor) handleLoginError(_ http.ResponseWriter, r *http.Request, g node.UiNodeGroup, f *Flow, i *identity.Identity, flowError error) error {
if f != nil {
if i != nil {
cont, err := container.NewFromStruct("", g, i.Traits, "traits")
if err != nil {
e.d.Logger().WithError(err).Warn("could not update flow UI")
return err
}
for _, n := range cont.Nodes {
// we only set the value and not the whole field because we want to keep types from the initial form generation
f.UI.Nodes.SetValueAttribute(n.ID(), n.Attributes.GetValue())
}
}
if f.Type == flow.TypeBrowser {
f.UI.SetCSRF(e.d.GenerateCSRFToken(r))
}
}
return flowError
}
func (e *HookExecutor) PostLoginHook(
w http.ResponseWriter,
r *http.Request,
g node.UiNodeGroup,
a *Flow,
i *identity.Identity,
s *session.Session,
provider string,
) (err error) {
ctx := r.Context()
ctx, span := e.d.Tracer(ctx).Tracer().Start(ctx, "HookExecutor.PostLoginHook")
r = r.WithContext(ctx)
defer otelx.End(span, &err)
if err := e.maybeLinkCredentials(r.Context(), s, i, a); err != nil {
return err
}
if err := s.Activate(r, i, e.d.Config(), time.Now().UTC()); err != nil {
return err
}
c := e.d.Config()
// Verify the redirect URL before we do any other processing.
returnTo, err := x.SecureRedirectTo(r,
c.SelfServiceBrowserDefaultReturnTo(r.Context()),
x.SecureRedirectReturnTo(a.ReturnTo),
x.SecureRedirectUseSourceURL(a.RequestURL),
x.SecureRedirectAllowURLs(c.SelfServiceBrowserAllowedReturnToDomains(r.Context())),
x.SecureRedirectAllowSelfServiceURLs(c.SelfPublicURL(r.Context())),
x.SecureRedirectOverrideDefaultReturnTo(c.SelfServiceFlowLoginReturnTo(r.Context(), a.Active.String())),
)
if err != nil {
return err
}
span.SetAttributes(otelx.StringAttrs(map[string]string{
"return_to": returnTo.String(),
"flow_type": string(flow.TypeBrowser),
"redirect_reason": "login successful",
})...)
classified := s
s = s.Declassified()
e.d.Logger().
WithRequest(r).
WithField("identity_id", i.ID).
WithField("flow_method", a.Active).
Debug("Running ExecuteLoginPostHook.")
for k, executor := range e.d.PostLoginHooks(r.Context(), a.Active) {
if err := executor.ExecuteLoginPostHook(w, r, g, a, s); err != nil {
if errors.Is(err, ErrHookAbortFlow) {
e.d.Logger().
WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookExecutorNames(e.d.PostLoginHooks(r.Context(), a.Active))).
WithField("identity_id", i.ID).
WithField("flow_method", a.Active).
Debug("A ExecuteLoginPostHook hook aborted early.")
span.SetAttributes(attribute.String("redirect_reason", "aborted by hook"), attribute.String("executor", fmt.Sprintf("%T", executor)))
return nil
}
return e.handleLoginError(w, r, g, a, i, err)
}
e.d.Logger().
WithRequest(r).
WithField("executor", fmt.Sprintf("%T", executor)).
WithField("executor_position", k).
WithField("executors", PostHookExecutorNames(e.d.PostLoginHooks(r.Context(), a.Active))).
WithField("identity_id", i.ID).
WithField("flow_method", a.Active).
Debug("ExecuteLoginPostHook completed successfully.")
}
if a.Type == flow.TypeAPI {
span.SetAttributes(attribute.String("flow_type", string(flow.TypeAPI)))
if err := e.d.SessionPersister().UpsertSession(r.Context(), s); err != nil {
return errors.WithStack(err)
}
e.d.Audit().
WithRequest(r).
WithField("session_id", s.ID).
WithField("identity_id", i.ID).
Info("Identity authenticated successfully and was issued an Ory Kratos Session Token.")
span.AddEvent(events.NewLoginSucceeded(r.Context(), &events.LoginSucceededOpts{
SessionID: s.ID,
IdentityID: i.ID,
FlowType: string(a.Type),
RequestedAAL: string(a.RequestedAAL),
IsRefresh: a.Refresh,
Method: a.Active.String(),
SSOProvider: provider,
}))
if a.IDToken != "" {
// We don't want to redirect with the code, if the flow was submitted with an ID token.
// This is the case for Sign in with native Apple SDK or Google SDK.
} else if handled, err := e.d.SessionManager().MaybeRedirectAPICodeFlow(w, r, a, s.ID, g); err != nil {
return errors.WithStack(err)
} else if handled {
return nil
}
response := &APIFlowResponse{Session: s, Token: s.Token}
if required, _ := e.requiresAAL2(r, classified, a); required {
// If AAL is not satisfied, we omit the identity to preserve the user's privacy in case of a phishing attack.
response.Session.Identity = nil
}
e.d.Writer().Write(w, r, response)
return nil
}
if err := e.d.SessionManager().UpsertAndIssueCookie(r.Context(), w, r, s); err != nil {
return errors.WithStack(err)
}
e.d.Audit().
WithRequest(r).
WithField("identity_id", i.ID).
WithField("session_id", s.ID).
Info("Identity authenticated successfully and was issued an Ory Kratos Session Cookie.")
trace.SpanFromContext(r.Context()).AddEvent(events.NewLoginSucceeded(r.Context(), &events.LoginSucceededOpts{
SessionID: s.ID,
IdentityID: i.ID, FlowType: string(a.Type), RequestedAAL: string(a.RequestedAAL), IsRefresh: a.Refresh, Method: a.Active.String(),
SSOProvider: provider,
}))
if x.IsJSONRequest(r) {
span.SetAttributes(attribute.String("flow_type", "spa"))
// Browser flows rely on cookies. Adding tokens in the mix will confuse consumers.
s.Token = ""
// If we detect that whoami would require a higher AAL, we redirect!
if _, err := e.requiresAAL2(r, s, a); err != nil {
if aalErr := new(session.ErrAALNotSatisfied); errors.As(err, &aalErr) {
span.SetAttributes(attribute.String("return_to", aalErr.RedirectTo), attribute.String("redirect_reason", "requires aal2"))
e.d.Writer().WriteError(w, r, flow.NewBrowserLocationChangeRequiredError(aalErr.RedirectTo))
return nil
}
return err
}
// If Kratos is used as a Hydra login provider, we need to redirect back to Hydra by returning a 422 status
// with the post login challenge URL as the body.
if a.OAuth2LoginChallenge != "" {
postChallengeURL, err := e.d.Hydra().AcceptLoginRequest(r.Context(),
hydra.AcceptLoginRequestParams{
LoginChallenge: string(a.OAuth2LoginChallenge),
IdentityID: i.ID.String(),
SessionID: s.ID.String(),
AuthenticationMethods: s.AMR,
})
if err != nil {
return err
}
span.SetAttributes(attribute.String("return_to", postChallengeURL), attribute.String("redirect_reason", "oauth2 login challenge"))
e.d.Writer().WriteError(w, r, flow.NewBrowserLocationChangeRequiredError(postChallengeURL))
return nil
}
response := &APIFlowResponse{Session: s}
e.d.Writer().Write(w, r, response)
return nil
}
// If we detect that whoami would require a higher AAL, we redirect!
if _, err := e.requiresAAL2(r, s, a); err != nil {
if aalErr := new(session.ErrAALNotSatisfied); errors.As(err, &aalErr) {
http.Redirect(w, r, aalErr.RedirectTo, http.StatusSeeOther)
return nil
}
return errors.WithStack(err)
}
finalReturnTo := returnTo.String()
if a.OAuth2LoginChallenge != "" {
rt, err := e.d.Hydra().AcceptLoginRequest(r.Context(),
hydra.AcceptLoginRequestParams{
LoginChallenge: string(a.OAuth2LoginChallenge),
IdentityID: i.ID.String(),
SessionID: s.ID.String(),
AuthenticationMethods: s.AMR,
})
if err != nil {
return err
}
finalReturnTo = rt
span.SetAttributes(attribute.String("return_to", rt), attribute.String("redirect_reason", "oauth2 login challenge"))
}
x.ContentNegotiationRedirection(w, r, s, e.d.Writer(), finalReturnTo)
return nil
}
func (e *HookExecutor) PreLoginHook(w http.ResponseWriter, r *http.Request, a *Flow) error {
for _, executor := range e.d.PreLoginHooks(r.Context()) {
if err := executor.ExecuteLoginPreHook(w, r, a); err != nil {
return err
}
}
return nil
}
// maybeLinkCredentials links the identity with the credentials of the inner context of the login flow.
func (e *HookExecutor) maybeLinkCredentials(ctx context.Context, sess *session.Session, ident *identity.Identity, loginFlow *Flow) error {
lc, err := flow.DuplicateCredentials(loginFlow)
if err != nil {
return err
} else if lc == nil {
return nil
}
if err := e.checkDuplicateCredentialsIdentifierMatch(ctx, ident.ID, lc.DuplicateIdentifier); err != nil {
return err
}
strategy, err := e.d.AllLoginStrategies().Strategy(lc.CredentialsType)
if err != nil {
return err
}
linkableStrategy, ok := strategy.(LinkableStrategy)
if !ok {
// This should never happen because we check for this in the registration flow.
return errors.Errorf("strategy is not linkable: %T", linkableStrategy)
}
if err := linkableStrategy.Link(ctx, ident, lc.CredentialsConfig); err != nil {
return err
}
method := strategy.CompletedAuthenticationMethod(ctx, sess.AMR)
sess.CompletedLoginForMethod(method)
return nil
}
func (e *HookExecutor) checkDuplicateCredentialsIdentifierMatch(ctx context.Context, identityID uuid.UUID, match string) error {
i, err := e.d.PrivilegedIdentityPool().GetIdentityConfidential(ctx, identityID)
if err != nil {
return err
}
for _, credentials := range i.Credentials {
for _, identifier := range credentials.Identifiers {
if identifier == match {
return nil
}
}
}
return schema.NewLinkedCredentialsDoNotMatch()
}