/
strategy_recovery.go
489 lines (411 loc) · 16.4 KB
/
strategy_recovery.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package code
import (
"net/http"
"net/url"
"time"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
"github.com/ory/herodot"
"github.com/ory/x/decoderx"
"github.com/ory/x/otelx"
"github.com/ory/x/sqlxx"
"github.com/ory/x/urlx"
"github.com/ory/kratos/identity"
"github.com/ory/kratos/schema"
"github.com/ory/kratos/selfservice/flow"
"github.com/ory/kratos/selfservice/flow/recovery"
"github.com/ory/kratos/session"
"github.com/ory/kratos/text"
"github.com/ory/kratos/ui/container"
"github.com/ory/kratos/ui/node"
"github.com/ory/kratos/x"
)
func (s *Strategy) RecoveryStrategyID() string {
return string(recovery.RecoveryStrategyCode)
}
func (s *Strategy) PopulateRecoveryMethod(r *http.Request, f *recovery.Flow) error {
f.UI.SetCSRF(s.deps.GenerateCSRFToken(r))
f.UI.GetNodes().Upsert(
node.NewInputField("email", nil, node.CodeGroup, node.InputAttributeTypeEmail, node.WithRequiredInputAttribute).
WithMetaLabel(text.NewInfoNodeInputEmail()),
)
f.UI.
GetNodes().
Append(node.NewInputField("method", s.RecoveryStrategyID(), node.CodeGroup, node.InputAttributeTypeSubmit).
WithMetaLabel(text.NewInfoNodeLabelSubmit()))
return nil
}
// Update Recovery Flow with Code Method
//
// swagger:model updateRecoveryFlowWithCodeMethod
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type updateRecoveryFlowWithCodeMethod struct {
// The email address of the account to recover
//
// If the email belongs to a valid account, a recovery email will be sent.
//
// If you want to notify the email address if the account does not exist, see
// the [notify_unknown_recipients flag](https://www.ory.sh/docs/kratos/self-service/flows/account-recovery-password-reset#attempted-recovery-notifications)
//
// If a code was already sent, including this field in the payload will invalidate the sent code and re-send a new code.
//
// format: email
// required: false
Email string `json:"email" form:"email"`
// Code from the recovery email
//
// If you want to submit a code, use this field, but make sure to _not_ include the email field, as well.
//
// required: false
Code string `json:"code" form:"code"`
// Sending the anti-csrf token is only required for browser login flows.
CSRFToken string `form:"csrf_token" json:"csrf_token"`
// Method is the method that should be used for this recovery flow
//
// Allowed values are `link` and `code`.
//
// required: true
Method recovery.RecoveryMethod `json:"method"`
}
func (s Strategy) isCodeFlow(f *recovery.Flow) bool {
value, err := f.Active.Value()
if err != nil {
return false
}
return value == s.NodeGroup().String()
}
func (s *Strategy) Recover(w http.ResponseWriter, r *http.Request, f *recovery.Flow) (err error) {
ctx, span := s.deps.Tracer(r.Context()).Tracer().Start(r.Context(), "selfservice.strategy.code.strategy.Recover")
span.SetAttributes(attribute.String("selfservice_flows_recovery_use", s.deps.Config().SelfServiceFlowRecoveryUse(ctx)))
defer otelx.End(span, &err)
if !s.isCodeFlow(f) {
return errors.WithStack(flow.ErrStrategyNotResponsible)
}
body, err := s.decodeRecovery(r)
if err != nil {
return s.HandleRecoveryError(w, r, nil, body, err)
}
if f.DangerousSkipCSRFCheck {
s.deps.Logger().
WithRequest(r).
Debugf("A recovery flow with `DangerousSkipCSRFCheck` set has been submitted, skipping anti-CSRF measures.")
} else if err := flow.EnsureCSRF(s.deps, r, f.Type, s.deps.Config().DisableAPIFlowEnforcement(ctx), s.deps.GenerateCSRFToken, body.CSRFToken); err != nil {
// If a CSRF violation occurs the flow is most likely FUBAR, as the user either lost the CSRF token, or an attack occured.
// In this case, we just issue a new flow and "abandon" the old flow.
return s.retryRecoveryFlow(w, r, flow.TypeBrowser, RetryWithError(err))
}
sID := s.RecoveryStrategyID()
f.UI.ResetMessages()
// If the email is present in the submission body, the user needs a new code via resend
if f.State != flow.StateChooseMethod && len(body.Email) == 0 {
if err := flow.MethodEnabledAndAllowed(ctx, flow.RecoveryFlow, sID, sID, s.deps); err != nil {
return s.HandleRecoveryError(w, r, nil, body, err)
}
return s.recoveryUseCode(w, r, body, f)
}
if _, err := s.deps.SessionManager().FetchFromRequest(ctx, r); err == nil {
// User is already logged in
if x.IsJSONRequest(r) {
session.RespondWithJSONErrorOnAuthenticated(s.deps.Writer(), recovery.ErrAlreadyLoggedIn)(w, r, nil)
} else {
session.RedirectOnAuthenticated(s.deps)(w, r, nil)
}
return errors.WithStack(flow.ErrCompletedByStrategy)
}
if err := flow.MethodEnabledAndAllowed(ctx, flow.RecoveryFlow, sID, body.Method, s.deps); err != nil {
return s.HandleRecoveryError(w, r, nil, body, err)
}
recoveryFlow, err := s.deps.RecoveryFlowPersister().GetRecoveryFlow(ctx, x.ParseUUID(body.Flow))
if err != nil {
return s.HandleRecoveryError(w, r, recoveryFlow, body, err)
}
if err := recoveryFlow.Valid(); err != nil {
return s.HandleRecoveryError(w, r, recoveryFlow, body, err)
}
switch recoveryFlow.State {
case flow.StateChooseMethod:
fallthrough
case flow.StateEmailSent:
return s.recoveryHandleFormSubmission(w, r, recoveryFlow, body)
case flow.StatePassedChallenge:
// was already handled, do not allow retry
return s.retryRecoveryFlow(w, r, recoveryFlow.Type, RetryWithMessage(text.NewErrorValidationRecoveryRetrySuccess()))
default:
return s.retryRecoveryFlow(w, r, recoveryFlow.Type, RetryWithMessage(text.NewErrorValidationRecoveryStateFailure()))
}
}
func (s *Strategy) recoveryIssueSession(w http.ResponseWriter, r *http.Request, f *recovery.Flow, id *identity.Identity) error {
ctx := r.Context()
f.UI.Messages.Clear()
f.State = flow.StatePassedChallenge
f.RecoveredIdentityID = uuid.NullUUID{
UUID: id.ID,
Valid: true,
}
if f.Type == flow.TypeBrowser {
f.SetCSRFToken(s.deps.CSRFHandler().RegenerateToken(w, r))
}
if err := s.deps.RecoveryFlowPersister().UpdateRecoveryFlow(ctx, f); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
sess, err := session.NewActiveSession(r, id, s.deps.Config(), time.Now().UTC(),
identity.CredentialsTypeRecoveryCode, identity.AuthenticatorAssuranceLevel1)
if err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
if err := s.deps.RecoveryExecutor().PostRecoveryHook(w, r, f, sess); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
switch f.Type {
case flow.TypeBrowser:
if err := s.deps.SessionManager().UpsertAndIssueCookie(ctx, w, r, sess); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
case flow.TypeAPI:
if err := s.deps.SessionPersister().UpsertSession(r.Context(), sess); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
f.ContinueWith = append(f.ContinueWith, flow.NewContinueWithSetToken(sess.Token))
}
sf, err := s.deps.SettingsHandler().NewFlow(w, r, sess.Identity, f.Type)
if err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
returnToURL := s.deps.Config().SelfServiceFlowRecoveryReturnTo(r.Context(), nil)
returnTo := ""
if returnToURL != nil {
returnTo = returnToURL.String()
}
sf.RequestURL, err = x.TakeOverReturnToParameter(f.RequestURL, sf.RequestURL, returnTo)
if err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
config := s.deps.Config()
sf.UI.Messages.Set(text.NewRecoverySuccessful(time.Now().Add(config.SelfServiceFlowSettingsPrivilegedSessionMaxAge(ctx))))
if err := s.deps.SettingsFlowPersister().UpdateSettingsFlow(r.Context(), sf); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
if s.deps.Config().UseContinueWithTransitions(ctx) {
switch {
case f.Type.IsAPI():
fallthrough
case x.IsJSONRequest(r):
f.ContinueWith = append(f.ContinueWith, flow.NewContinueWithSettingsUI(sf))
s.deps.Writer().Write(w, r, f)
default:
http.Redirect(w, r, sf.AppendTo(s.deps.Config().SelfServiceFlowSettingsUI(r.Context())).String(), http.StatusSeeOther)
}
} else {
if x.IsJSONRequest(r) {
s.deps.Writer().WriteError(w, r, flow.NewBrowserLocationChangeRequiredError(sf.AppendTo(s.deps.Config().SelfServiceFlowSettingsUI(r.Context())).String()))
} else {
http.Redirect(w, r, sf.AppendTo(s.deps.Config().SelfServiceFlowSettingsUI(r.Context())).String(), http.StatusSeeOther)
}
}
return errors.WithStack(flow.ErrCompletedByStrategy)
}
func (s *Strategy) recoveryUseCode(w http.ResponseWriter, r *http.Request, body *recoverySubmitPayload, f *recovery.Flow) error {
ctx := r.Context()
code, err := s.deps.RecoveryCodePersister().UseRecoveryCode(ctx, f.ID, body.Code)
if errors.Is(err, ErrCodeNotFound) {
f.UI.Messages.Clear()
f.UI.Messages.Add(text.NewErrorValidationRecoveryCodeInvalidOrAlreadyUsed())
if err := s.deps.RecoveryFlowPersister().UpdateRecoveryFlow(ctx, f); err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
if f.Type == flow.TypeBrowser && !x.IsJSONRequest(r) {
http.Redirect(w, r, f.AppendTo(s.deps.Config().SelfServiceFlowRecoveryUI(r.Context())).String(), http.StatusSeeOther)
} else {
s.deps.Writer().Write(w, r, f)
}
return errors.WithStack(flow.ErrCompletedByStrategy)
} else if err != nil {
return s.retryRecoveryFlow(w, r, f.Type, RetryWithError(err))
}
recovered, err := s.deps.IdentityPool().GetIdentity(ctx, code.IdentityID, identity.ExpandDefault)
if err != nil {
return s.HandleRecoveryError(w, r, f, nil, err)
}
// mark address as verified only for a self-service flow
if code.CodeType == RecoveryCodeTypeSelfService {
if err := s.markRecoveryAddressVerified(w, r, f, recovered, code.RecoveryAddress); err != nil {
return s.HandleRecoveryError(w, r, f, body, err)
}
}
return s.recoveryIssueSession(w, r, f, recovered)
}
type retry struct {
err error
message *text.Message
}
type RetryOption func(*retry)
func RetryWithError(err error) RetryOption {
return func(r *retry) {
r.err = err
}
}
func RetryWithMessage(msg *text.Message) RetryOption {
return func(r *retry) {
r.message = msg
}
}
func (s *Strategy) retryRecoveryFlow(w http.ResponseWriter, r *http.Request, ft flow.Type, opts ...RetryOption) error {
retryOptions := retry{}
for _, o := range opts {
o(&retryOptions)
}
logger := s.deps.Logger().WithRequest(r).WithError(retryOptions.err)
if retryOptions.message != nil {
logger = logger.WithField("message", retryOptions.message)
}
logger.Debug("A recovery flow is being retried because a validation error occurred.")
ctx := r.Context()
config := s.deps.Config()
f, err := recovery.NewFlow(config, config.SelfServiceFlowRecoveryRequestLifespan(ctx), s.deps.CSRFHandler().RegenerateToken(w, r), r, s, ft)
if err != nil {
return err
}
if retryOptions.message != nil {
f.UI.Messages.Add(retryOptions.message)
}
if retryOptions.err != nil {
if expired := new(flow.ExpiredError); errors.As(retryOptions.err, &expired) {
f.UI.Messages.Add(text.NewErrorValidationRecoveryFlowExpired(expired.ExpiredAt))
} else if err := f.UI.ParseError(node.CodeGroup, retryOptions.err); err != nil {
return err
}
}
if err := s.deps.RecoveryFlowPersister().CreateRecoveryFlow(ctx, f); err != nil {
return err
}
if s.deps.Config().UseContinueWithTransitions(ctx) {
switch {
case x.IsJSONRequest(r):
rErr := new(herodot.DefaultError)
if !errors.As(retryOptions.err, &rErr) {
rErr = rErr.WithError(retryOptions.err.Error())
}
s.deps.Writer().WriteError(w, r, flow.ErrorWithContinueWith(rErr, flow.NewContinueWithRecoveryUI(f)))
default:
http.Redirect(w, r, f.AppendTo(config.SelfServiceFlowRecoveryUI(ctx)).String(), http.StatusSeeOther)
}
} else {
if x.IsJSONRequest(r) {
http.Redirect(w, r, urlx.CopyWithQuery(urlx.AppendPaths(config.SelfPublicURL(ctx),
recovery.RouteGetFlow), url.Values{"id": {f.ID.String()}}).String(), http.StatusSeeOther)
} else {
http.Redirect(w, r, f.AppendTo(config.SelfServiceFlowRecoveryUI(ctx)).String(), http.StatusSeeOther)
}
}
return errors.WithStack(flow.ErrCompletedByStrategy)
}
// recoveryHandleFormSubmission handles the submission of an Email for recovery
func (s *Strategy) recoveryHandleFormSubmission(w http.ResponseWriter, r *http.Request, f *recovery.Flow, body *recoverySubmitPayload) error {
if len(body.Email) == 0 {
return s.HandleRecoveryError(w, r, f, body, schema.NewRequiredError("#/email", "email"))
}
ctx := r.Context()
config := s.deps.Config()
if err := flow.EnsureCSRF(s.deps, r, f.Type, config.DisableAPIFlowEnforcement(ctx), s.deps.GenerateCSRFToken, body.CSRFToken); err != nil {
return s.HandleRecoveryError(w, r, f, body, err)
}
if err := s.deps.RecoveryCodePersister().DeleteRecoveryCodesOfFlow(ctx, f.ID); err != nil {
return s.HandleRecoveryError(w, r, f, body, err)
}
if err := s.deps.CodeSender().SendRecoveryCode(ctx, f, identity.VerifiableAddressTypeEmail, body.Email); err != nil {
if !errors.Is(err, ErrUnknownAddress) {
return s.HandleRecoveryError(w, r, f, body, err)
}
// Continue execution
}
// re-initialize the UI with a "clean" new state
f.UI = &container.Container{
Method: "POST",
Action: flow.AppendFlowTo(urlx.AppendPaths(s.deps.Config().SelfPublicURL(r.Context()), recovery.RouteSubmitFlow), f.ID).String(),
}
f.UI.SetCSRF(s.deps.GenerateCSRFToken(r))
f.Active = sqlxx.NullString(s.NodeGroup())
f.State = flow.StateEmailSent
f.UI.Messages.Set(text.NewRecoveryEmailWithCodeSent())
f.UI.Nodes.Append(node.NewInputField("code", nil, node.CodeGroup, node.InputAttributeTypeText, node.WithInputAttributes(func(a *node.InputAttributes) {
a.Required = true
a.Pattern = "[0-9]+"
})).
WithMetaLabel(text.NewInfoNodeLabelRecoveryCode()),
)
f.UI.Nodes.Append(node.NewInputField("method", s.NodeGroup(), node.CodeGroup, node.InputAttributeTypeHidden))
f.UI.
GetNodes().
Append(node.NewInputField("method", s.RecoveryStrategyID(), node.CodeGroup, node.InputAttributeTypeSubmit).
WithMetaLabel(text.NewInfoNodeLabelSubmit()))
f.UI.Nodes.Append(node.NewInputField("email", body.Email, node.CodeGroup, node.InputAttributeTypeSubmit).
WithMetaLabel(text.NewInfoNodeResendOTP()),
)
if err := s.deps.RecoveryFlowPersister().UpdateRecoveryFlow(r.Context(), f); err != nil {
return s.HandleRecoveryError(w, r, f, body, err)
}
return nil
}
func (s *Strategy) markRecoveryAddressVerified(w http.ResponseWriter, r *http.Request, f *recovery.Flow, id *identity.Identity, recoveryAddress *identity.RecoveryAddress) error {
var address *identity.VerifiableAddress
for idx := range id.VerifiableAddresses {
va := id.VerifiableAddresses[idx]
if va.Value == recoveryAddress.Value {
address = &va
break
}
}
if address != nil && !address.Verified { // can it be that the address is nil?
address.Verified = true
verifiedAt := sqlxx.NullTime(time.Now().UTC())
address.VerifiedAt = &verifiedAt
address.Status = identity.VerifiableAddressStatusCompleted
if err := s.deps.PrivilegedIdentityPool().UpdateVerifiableAddress(r.Context(), address); err != nil {
return s.HandleRecoveryError(w, r, f, nil, err)
}
}
return nil
}
func (s *Strategy) HandleRecoveryError(w http.ResponseWriter, r *http.Request, flow *recovery.Flow, body *recoverySubmitPayload, err error) error {
if flow != nil {
email := ""
if body != nil {
email = body.Email
}
flow.UI.SetCSRF(s.deps.GenerateCSRFToken(r))
flow.UI.GetNodes().Upsert(
node.NewInputField("email", email, node.CodeGroup, node.InputAttributeTypeEmail, node.WithRequiredInputAttribute).
WithMetaLabel(text.NewInfoNodeInputEmail()),
)
}
return err
}
type recoverySubmitPayload struct {
Method string `json:"method" form:"method"`
Code string `json:"code" form:"code"`
CSRFToken string `json:"csrf_token" form:"csrf_token"`
Flow string `json:"flow" form:"flow"`
Email string `json:"email" form:"email"`
}
func (s *Strategy) decodeRecovery(r *http.Request) (*recoverySubmitPayload, error) {
var body recoverySubmitPayload
compiler, err := decoderx.HTTPRawJSONSchemaCompiler(recoveryMethodSchema)
if err != nil {
return nil, errors.WithStack(err)
}
if err := s.dx.Decode(r, &body, compiler,
decoderx.HTTPDecoderUseQueryAndBody(),
decoderx.HTTPKeepRequestBody(true),
decoderx.HTTPDecoderAllowedMethods("POST"),
decoderx.HTTPDecoderSetValidatePayloads(true),
decoderx.HTTPDecoderJSONFollowsFormFormat(),
); err != nil {
return nil, errors.WithStack(err)
}
return &body, nil
}