-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathservice.go
1047 lines (857 loc) · 28.8 KB
/
service.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kratos
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
hClient "github.com/ory/hydra-client-go/v2"
kClient "github.com/ory/kratos-client-go"
"github.com/canonical/identity-platform-login-ui/internal/logging"
httpHelpers "github.com/canonical/identity-platform-login-ui/internal/misc/http"
"github.com/canonical/identity-platform-login-ui/internal/monitoring"
"github.com/canonical/identity-platform-login-ui/internal/tracing"
)
const (
NotEnoughCharacters = 4000003
TooManyCharacters = 4000017
IncorrectCredentials = 4000006
InactiveAccount = 4000010
InvalidRecoveryCode = 4060006
RecoveryCodeSent = 1060003
InvalidProperty = 4000002
InvalidAuthCode = 4000008
MissingSecurityKeySetup = 4000015
BackupCodeAlreadyUsed = 4000012
InvalidBackupCode = 4000016
MissingBackupCodesSetup = 4000014
PasswordIdentifierSimilarity = 4000031
PasswordTooLong = 4000033
MinimumBackupCodesAmount = 3
)
type Service struct {
kratos KratosClientInterface
kratosAdmin KratosAdminClientInterface
hydra HydraClientInterface
authz AuthorizerInterface
oidcWebAuthnSequencingEnabled bool
tracer tracing.TracingInterface
monitor monitoring.MonitorInterface
logger logging.LoggerInterface
}
// We override the type from the kratos sdk, as it does not
// get marshalled correctly into json.
// For more info see: https://github.com/canonical/identity-platform-login-ui/pull/73/files#r1250460283
type ErrorBrowserLocationChangeRequired struct {
Error *kClient.GenericError `json:"error,omitempty"`
// Points to where to redirect the user to next.
RedirectBrowserTo *string `json:"redirect_browser_to,omitempty"`
}
func (e *ErrorBrowserLocationChangeRequired) GetRedirectTo() string {
if e.RedirectBrowserTo == nil {
return ""
}
return *e.RedirectBrowserTo
}
func (e *ErrorBrowserLocationChangeRequired) HasError() bool {
return e.Error != nil
}
func (e *BrowserLocationChangeRequired) HasError() bool {
return e.Error != nil
}
func (e *BrowserLocationChangeRequired) HasRedirectTo() bool {
return e.RedirectTo != nil
}
func (e *BrowserLocationChangeRequired) GetRedirectTo() string {
if e.RedirectTo == nil {
return ""
}
return *e.RedirectTo
}
type BrowserLocationChangeRequired struct {
Error *kClient.GenericError `json:"error,omitempty"`
// Points to where to redirect the user to next.
RedirectTo *string `json:"redirect_to,omitempty"`
}
type UiErrorMessages struct {
Ui kClient.UiContainer `json:"ui"`
}
type methodOnly struct {
Method string `json:"method"`
}
type LookupSecrets []struct {
Code string `json:"code"`
UsedAt time.Time `json:"used_at,omitempty"`
}
func (s *Service) CheckSession(ctx context.Context, cookies []*http.Cookie) (*kClient.Session, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.ToSession")
defer span.End()
session, resp, err := s.kratos.FrontendApi().
ToSession(ctx).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
if err != nil {
return nil, nil, err
}
return session, resp.Cookies(), nil
}
func (s *Service) AcceptLoginRequest(ctx context.Context, session *kClient.Session, lc string) (*hClient.OAuth2RedirectTo, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.AcceptLoginRequest")
defer span.End()
accept := hClient.NewAcceptOAuth2LoginRequest(session.Identity.Id)
accept.SetRemember(true)
accept.Amr = []string{}
for _, r := range session.AuthenticationMethods {
accept.Amr = append(accept.Amr, r.GetMethod())
}
accept.IdentityProviderSessionId = &session.Id
if session.ExpiresAt != nil {
expAt := time.Until(*session.ExpiresAt)
// Set the session to expire when the kratos session expires
accept.SetRememberFor(int64(expAt.Seconds()))
}
redirectTo, resp, err := s.hydra.OAuth2API().
AcceptOAuth2LoginRequest(ctx).
LoginChallenge(lc).
AcceptOAuth2LoginRequest(*accept).
Execute()
if err != nil {
return nil, nil, err
}
return redirectTo, resp.Cookies(), nil
}
func (s *Service) GetLoginRequest(ctx context.Context, loginChallenge string) (*hClient.OAuth2LoginRequest, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.GetLoginRequest")
defer span.End()
redirectTo, resp, err := s.hydra.OAuth2API().
GetOAuth2LoginRequest(ctx).
LoginChallenge(loginChallenge).
Execute()
if err != nil {
return nil, nil, err
}
return redirectTo, resp.Cookies(), nil
}
func (s *Service) MustReAuthenticate(ctx context.Context, hydraLoginChallenge string, session *kClient.Session, c FlowStateCookie) (bool, error) {
if session == nil {
// No session exists, user is not logged in
return true, nil
}
if hydraLoginChallenge == "" {
// It's not a hydra flow, let kratos handle it
return true, nil
}
// This is the first user login, they set up their authenticator app
// Or backup code was used for login, no need to re-auth
if validateHash(hydraLoginChallenge, c.LoginChallengeHash) && (c.TotpSetup || c.BackupCodeUsed || c.WebauthnSetup) {
return false, nil
}
hydraLoginRequest, _, err := s.GetLoginRequest(ctx, hydraLoginChallenge)
if err != nil {
return true, err
}
return !hydraLoginRequest.GetSkip(), nil
}
func (s *Service) CreateBrowserLoginFlow(
ctx context.Context, aal, returnTo, loginChallenge string, refresh bool, cookies []*http.Cookie,
) (*kClient.LoginFlow, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.CreateBrowserLoginFlow")
defer span.End()
request := s.kratos.FrontendApi().
CreateBrowserLoginFlow(ctx).
Aal(aal).
ReturnTo(returnTo).
Refresh(refresh).
Cookie(httpHelpers.CookiesToString(cookies))
if !s.oidcWebAuthnSequencingEnabled {
if loginChallenge != "" {
request = request.LoginChallenge(loginChallenge)
} else if loginChallenge == "" && returnTo == "" {
return nil, nil, fmt.Errorf("no return_to or login_challenge was provided")
}
}
flow, resp, err := request.Execute()
if err != nil {
return nil, nil, err
}
// Populate the flow with the hydra login req, so that the UI can retrieve this info
flow, err = s.hydrateKratosLoginFlow(ctx, flow)
if err != nil {
s.logger.Warnf("Failed to fetch the hydra oauth2 request: %v", err)
}
return flow, resp.Cookies(), nil
}
func (s *Service) CreateBrowserRecoveryFlow(ctx context.Context, returnTo string, cookies []*http.Cookie) (*kClient.RecoveryFlow, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.CreateBrowserRecoveryFlow")
defer span.End()
flow, resp, err := s.kratos.FrontendApi().
CreateBrowserRecoveryFlow(ctx).
ReturnTo(returnTo).
Execute()
if err != nil {
return nil, nil, err
}
return flow, resp.Cookies(), nil
}
func (s *Service) CreateBrowserSettingsFlow(ctx context.Context, returnTo string, cookies []*http.Cookie) (*kClient.SettingsFlow, *BrowserLocationChangeRequired, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.CreateBrowserSettingsFlow")
defer span.End()
request := s.kratos.FrontendApi().
CreateBrowserSettingsFlow(ctx).
Cookie(httpHelpers.CookiesToString(cookies))
if returnTo != "" {
request = request.ReturnTo(returnTo)
}
flow, resp, err := request.Execute()
// 403 means the user must be redirected to complete second factor auth
// in order to access settings
if err != nil && resp.StatusCode != http.StatusForbidden {
return nil, nil, err
}
if err == nil {
return flow, nil, nil
}
redirectResp := new(ErrorBrowserLocationChangeRequired)
err = unmarshalByteJson(resp.Body, redirectResp)
if err != nil {
s.logger.Errorf("Failed to unmarshal JSON: %s", err)
return nil, nil, err
}
returnToResp := &BrowserLocationChangeRequired{
RedirectTo: redirectResp.RedirectBrowserTo,
Error: redirectResp.Error,
}
return flow, returnToResp, nil
}
func (s *Service) GetLoginFlow(ctx context.Context, id string, cookies []*http.Cookie) (*kClient.LoginFlow, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.GetLoginFlow")
defer span.End()
flow, resp, err := s.kratos.FrontendApi().
GetLoginFlow(ctx).
Id(id).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
if err != nil {
return nil, nil, err
}
// Populate the flow with the hydra login req, so that the UI can retrieve this info
flow, err = s.hydrateKratosLoginFlow(ctx, flow)
if err != nil {
s.logger.Warnf("Failed to fetch the hydra oauth2 request: %v", err)
}
return flow, resp.Cookies(), nil
}
func (s *Service) GetRecoveryFlow(ctx context.Context, id string, cookies []*http.Cookie) (*kClient.RecoveryFlow, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.GetRecoveryFlow")
defer span.End()
flow, resp, err := s.kratos.FrontendApi().
GetRecoveryFlow(ctx).
Id(id).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
if err != nil {
return nil, nil, err
}
return flow, resp.Cookies(), nil
}
func (s *Service) GetSettingsFlow(ctx context.Context, id string, cookies []*http.Cookie) (*kClient.SettingsFlow, *BrowserLocationChangeRequired, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.GetSettingsFlow")
defer span.End()
flow, resp, err := s.kratos.FrontendApi().
GetSettingsFlow(ctx).
Id(id).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
// 403 means the user must be redirected to complete second factor auth
// in order to access settings
if err != nil && resp.StatusCode != http.StatusForbidden {
return nil, nil, err
}
if err == nil {
return flow, nil, nil
}
redirectResp := new(ErrorBrowserLocationChangeRequired)
err = unmarshalByteJson(resp.Body, redirectResp)
if err != nil {
s.logger.Errorf("Failed to unmarshal JSON: %s", err)
return nil, nil, err
}
returnToResp := &BrowserLocationChangeRequired{
RedirectTo: redirectResp.RedirectBrowserTo,
Error: redirectResp.Error,
}
return flow, returnToResp, nil
}
func (s *Service) UpdateRecoveryFlow(
ctx context.Context, flow string, body kClient.UpdateRecoveryFlowBody, cookies []*http.Cookie,
) (*BrowserLocationChangeRequired, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.UpdateRecoveryFlow")
defer span.End()
recovery, resp, err := s.kratos.FrontendApi().
UpdateRecoveryFlow(ctx).
Flow(flow).
UpdateRecoveryFlowBody(body).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
// if the flow responds with 400, it means a session already exists
if err != nil && resp.StatusCode == http.StatusBadRequest {
redirectResp := new(ErrorBrowserLocationChangeRequired)
err := unmarshalByteJson(resp.Body, redirectResp)
if err != nil {
s.logger.Errorf("Failed to unmarshal JSON: %s", err)
return nil, nil, err
}
returnToResp := &BrowserLocationChangeRequired{
RedirectTo: redirectResp.RedirectBrowserTo,
Error: redirectResp.Error,
}
return returnToResp, nil, nil
}
// If the recovery code was invalid, kratos returns a 200 response
// with a 4060006 error in the rendered ui messages.
// If the recovery code was valid, we expect to get a 422 response from kratos.
// That is because the user needs to be redirected to self-service settings page.
// The sdk forces us to make the request with an 'application/json' content-type, whereas Kratos
// expects the 'Content-Type' and 'Accept' to be 'application/x-www-form-urlencoded'.
// This is not a real error, as we still get the URL to which the user needs to be
// redirected to.
if err != nil && resp.StatusCode != http.StatusUnprocessableEntity {
err := s.getUiError(resp.Body)
return nil, nil, err
}
if resp.StatusCode == http.StatusOK {
uiMsg := recovery.GetUi()
for _, message := range uiMsg.GetMessages() {
if message.GetId() == InvalidRecoveryCode {
return nil, nil, fmt.Errorf("the recovery code is invalid or has already been used")
}
}
}
redirectResp := new(ErrorBrowserLocationChangeRequired)
err = unmarshalByteJson(resp.Body, redirectResp)
if err != nil {
s.logger.Errorf("Failed to unmarshal JSON: %s", err)
return nil, nil, err
}
returnToResp := BrowserLocationChangeRequired{RedirectTo: redirectResp.RedirectBrowserTo}
return &returnToResp, resp.Cookies(), nil
}
func (s *Service) UpdateLoginFlow(
ctx context.Context, flow string, body kClient.UpdateLoginFlowBody, cookies []*http.Cookie,
) (*BrowserLocationChangeRequired, *kClient.SuccessfulNativeLogin, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.UpdateLoginFlow")
defer span.End()
f, resp, err := s.kratos.FrontendApi().
UpdateLoginFlow(ctx).
Flow(flow).
UpdateLoginFlowBody(body).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
// We expect to get a 422 response from Kratos. The sdk forces us to
// make the request with an 'application/json' content-type, whereas Kratos
// expects the 'Content-Type' and 'Accept' to be 'application/x-www-form-urlencoded'.
// This is not a real error, as we still get the URL to which the user needs to be
// redirected to.
if err != nil && resp.StatusCode != http.StatusUnprocessableEntity {
err := s.getUiError(resp.Body)
return nil, nil, nil, err
}
redirectResp := new(ErrorBrowserLocationChangeRequired)
err = unmarshalByteJson(resp.Body, redirectResp)
if err != nil {
s.logger.Errorf("Failed to unmarshal JSON: %s", err)
return nil, nil, nil, err
}
c := resp.Cookies()
if body.UpdateLoginFlowWithOidcMethod != nil {
// If this is an oidc flow, we need to delete the session cookie
// A session cookie (probably) means that the user used 1fa, but went back from the 2nd factor screen
// If the session cookie is set, then Kratos will redirect the user to the default return to URL
// The only way to avoid this is by setting refresh=true, but the user has no kratos session.
// This is probably a bug on kratos side, as they check if a session exists to set refresh=false.
// But in oidc they only check if the session cookie exists, which is not sufficient as the user may not have
// enough aal
c = append(c, kratosSessionUnsetCookie())
}
if resp.StatusCode == http.StatusUnprocessableEntity {
// We trasform the kratos response to our own custom response here.
// The original kratos response contains an 'Error' field, which we remove
// because this is not a real error.
returnToResp := BrowserLocationChangeRequired{RedirectTo: redirectResp.RedirectBrowserTo}
return &returnToResp, nil, c, nil
}
// Workaround for marshalling error
// TODO: Evaluate if we can get rid of that when kratos sdk 1.3 is out
f.ContinueWith = nil
return nil, f, c, nil
}
func (s *Service) UpdateSettingsFlow(
ctx context.Context, flow string, body kClient.UpdateSettingsFlowBody, cookies []*http.Cookie,
) (*kClient.SettingsFlow, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.UpdateSettingsFlow")
defer span.End()
settingsFlow, resp, err := s.kratos.FrontendApi().
UpdateSettingsFlow(ctx).
Flow(flow).
UpdateSettingsFlowBody(body).
Cookie(httpHelpers.CookiesToString(cookies)).
Execute()
if err != nil && resp.StatusCode != http.StatusOK {
err := s.getUiError(resp.Body)
return nil, nil, err
}
// Workaround for marshalling error
// TODO: Evaluate if we can get rid of that when kratos sdk 1.3 is out
settingsFlow.ContinueWith = nil
return settingsFlow, resp.Cookies(), nil
}
func (s *Service) getUiError(responseBody io.ReadCloser) (err error) {
errorMessages := new(UiErrorMessages)
body, _ := io.ReadAll(responseBody)
json.Unmarshal([]byte(body), &errorMessages)
errorCodes := errorMessages.Ui.Messages
// if no message was found, search through nodes
if len(errorCodes) == 0 {
nodes := errorMessages.Ui.GetNodes()
for _, node := range nodes {
// look for the node where error appears
for _, message := range node.Messages {
if message.Type == "error" {
errorCodes = node.GetMessages()
}
}
}
}
if len(errorCodes) == 0 {
err = fmt.Errorf("error code not found")
s.logger.Errorf(err.Error())
return err
}
// TODO: Add unit tests for all handled error codes
switch errorCode := errorCodes[0].Id; errorCode {
case IncorrectCredentials:
err = fmt.Errorf("incorrect username or password")
case InactiveAccount:
err = fmt.Errorf("inactive account")
case InvalidProperty:
err = fmt.Errorf("invalid %s", errorCodes[0].Context["property"])
case NotEnoughCharacters:
err = fmt.Errorf("at least %v characters required", errorCodes[0].Context["min_length"])
case TooManyCharacters, PasswordTooLong:
err = fmt.Errorf("maximum %v characters allowed", errorCodes[0].Context["max_length"])
case InvalidAuthCode:
err = fmt.Errorf("invalid authentication code")
case MissingSecurityKeySetup:
err = fmt.Errorf("choose a different login method")
case BackupCodeAlreadyUsed:
err = fmt.Errorf("this backup code was already used")
case InvalidBackupCode:
err = fmt.Errorf("invalid backup code")
case MissingBackupCodesSetup:
err = fmt.Errorf("login with backup codes unavailable")
case PasswordIdentifierSimilarity:
err = fmt.Errorf("password can not be similar to the email")
default:
s.logger.Errorf("Unknown kratos error code: %v", errorCode)
err = fmt.Errorf("server error")
}
return err
}
func (s *Service) GetFlowError(ctx context.Context, id string) (*kClient.FlowError, []*http.Cookie, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.GetFlowError")
defer span.End()
flowError, resp, err := s.kratos.FrontendApi().GetFlowError(ctx).Id(id).Execute()
if err != nil {
return nil, nil, err
}
return flowError, resp.Cookies(), nil
}
func (s *Service) CheckAllowedProvider(ctx context.Context, loginFlow *kClient.LoginFlow, updateFlowBody *kClient.UpdateLoginFlowBody) (bool, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.CheckAllowedProvider")
defer span.End()
provider := s.getProviderName(updateFlowBody)
clientName := s.getClientName(loginFlow)
allowedProviders, err := s.authz.ListObjects(ctx, fmt.Sprintf("app:%s", clientName), "allowed_access", "provider")
if err != nil {
return false, err
}
// If the user has not configured providers for this app, we allow all providers
if len(allowedProviders) == 0 {
return true, nil
}
return s.contains(allowedProviders, fmt.Sprintf("%v", provider)), nil
}
func (s *Service) getProviderName(updateFlowBody *kClient.UpdateLoginFlowBody) string {
if updateFlowBody.GetActualInstance() == updateFlowBody.UpdateLoginFlowWithOidcMethod {
return updateFlowBody.UpdateLoginFlowWithOidcMethod.Provider
}
return ""
}
func (s *Service) getClientName(loginFlow *kClient.LoginFlow) string {
oauth2LoginRequest := loginFlow.Oauth2LoginRequest
if oauth2LoginRequest != nil {
return oauth2LoginRequest.Client.GetClientName()
}
// Handle Oathkeeper case
return ""
}
func (s *Service) FilterFlowProviderList(ctx context.Context, flow *kClient.LoginFlow) (*kClient.LoginFlow, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.FilterFlowProviderList")
defer span.End()
clientName := s.getClientName(flow)
allowedProviders, err := s.authz.ListObjects(ctx, fmt.Sprintf("app:%s", clientName), "allowed_access", "provider")
if err != nil {
return nil, err
}
// If the user has not configured providers for this app, we allow all providers
if len(allowedProviders) == 0 {
return flow, nil
}
// Filter UI nodes
var nodes []kClient.UiNode
for _, node := range flow.Ui.Nodes {
switch node.Group {
case "oidc":
if s.contains(allowedProviders, fmt.Sprintf("%v", node.Attributes.UiNodeInputAttributes.GetValue())) {
nodes = append(nodes, node)
}
}
}
flow.Ui.Nodes = nodes
return flow, nil
}
func (s *Service) ParseLoginFlowMethodBody(r *http.Request) (*kClient.UpdateLoginFlowBody, []*http.Cookie, error) {
// TODO: try to refactor when we bump kratos sdk to 1.x.x
var (
ret kClient.UpdateLoginFlowBody
cookies = r.Cookies()
)
methodOnly := new(methodOnly)
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
return nil, cookies, errors.New("unable to read body")
}
// replace the body that was consumed
r.Body = io.NopCloser(bytes.NewReader(b))
if err := json.Unmarshal(b, methodOnly); err != nil {
// return nil, cookies, err
methodOnly.Method = "webauthn"
}
switch methodOnly.Method {
case "password":
body := new(kClient.UpdateLoginFlowWithPasswordMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, cookies, err
}
ret = kClient.UpdateLoginFlowWithPasswordMethodAsUpdateLoginFlowBody(
body,
)
case "totp":
body := new(kClient.UpdateLoginFlowWithTotpMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, cookies, err
}
ret = kClient.UpdateLoginFlowWithTotpMethodAsUpdateLoginFlowBody(
body,
)
ret.UpdateLoginFlowWithTotpMethod.Method = "totp"
case "webauthn":
body := new(kClient.UpdateLoginFlowWithWebAuthnMethod)
var err error
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
// TODO: fix me. The UI should start sending that data in json format
err = r.ParseForm()
if err != nil {
return nil, cookies, err
}
csrf := r.Form.Get("csrf_token")
l := r.Form.Get("webauthn_login")
body.CsrfToken = &csrf
body.Identifier = r.Form.Get("identifier")
body.WebauthnLogin = &l
} else {
err = parseBody(r.Body, &body)
}
if err != nil {
return nil, cookies, err
}
ret = kClient.UpdateLoginFlowWithWebAuthnMethodAsUpdateLoginFlowBody(
body,
)
case "lookup_secret":
body := new(kClient.UpdateLoginFlowWithLookupSecretMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, cookies, err
}
ret = kClient.UpdateLoginFlowWithLookupSecretMethodAsUpdateLoginFlowBody(
body,
)
// method field is empty for oidc: https://github.com/ory/kratos/pull/3564
default:
body := new(kClient.UpdateLoginFlowWithOidcMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, cookies, err
}
ret = kClient.UpdateLoginFlowWithOidcMethodAsUpdateLoginFlowBody(
body,
)
}
if s.is1FAMethod(methodOnly.Method) {
for i, c := range cookies {
if c.Name == KRATOS_SESSION_COOKIE_NAME {
if i == len(cookies)-1 {
cookies = cookies[:i]
} else {
cookies[i] = cookies[len(cookies)-1]
cookies = cookies[:len(cookies)-1]
}
}
}
}
return &ret, cookies, nil
}
func (s *Service) ParseRecoveryFlowMethodBody(r *http.Request) (*kClient.UpdateRecoveryFlowBody, error) {
body := new(kClient.UpdateRecoveryFlowWithCodeMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, err
}
ret := kClient.UpdateRecoveryFlowWithCodeMethodAsUpdateRecoveryFlowBody(
body,
)
ret.UpdateRecoveryFlowWithCodeMethod.Method = "code"
return &ret, nil
}
func (s *Service) ParseSettingsFlowMethodBody(r *http.Request) (*kClient.UpdateSettingsFlowBody, error) {
methodOnly := new(methodOnly)
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
return nil, errors.New("unable to read body")
}
// replace the body that was consumed
r.Body = io.NopCloser(bytes.NewReader(b))
if err := json.Unmarshal(b, methodOnly); err != nil {
return nil, err
}
var ret kClient.UpdateSettingsFlowBody
switch methodOnly.Method {
case "password":
body := new(kClient.UpdateSettingsFlowWithPasswordMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, err
}
ret = kClient.UpdateSettingsFlowWithPasswordMethodAsUpdateSettingsFlowBody(
body,
)
case "totp":
body := new(kClient.UpdateSettingsFlowWithTotpMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, err
}
ret = kClient.UpdateSettingsFlowWithTotpMethodAsUpdateSettingsFlowBody(
body,
)
case "webauthn":
body := new(kClient.UpdateSettingsFlowWithWebAuthnMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, err
}
ret = kClient.UpdateSettingsFlowWithWebAuthnMethodAsUpdateSettingsFlowBody(
body,
)
case "lookup_secret":
body := new(kClient.UpdateSettingsFlowWithLookupMethod)
err := parseBody(r.Body, &body)
if err != nil {
return nil, err
}
ret = kClient.UpdateSettingsFlowWithLookupMethodAsUpdateSettingsFlowBody(
body,
)
}
return &ret, nil
}
func (s *Service) contains(str []string, e string) bool {
for _, a := range str {
if a == e {
return true
}
}
return false
}
func (s *Service) HasTOTPAvailable(ctx context.Context, id string) (bool, error) {
identity, _, err := s.kratosAdmin.IdentityApi().
GetIdentity(ctx, id).
IncludeCredential([]string{"totp"}).
Execute()
if err != nil {
return false, err
}
_, ok := identity.GetCredentials()["totp"]
return ok, nil
}
func (s *Service) HasWebAuthnAvailable(ctx context.Context, id string) (bool, error) {
ctx, span := s.tracer.Start(ctx, "kratos.Service.HasWebAuthnAvailable")
defer span.End()
identity, _, err := s.kratosAdmin.IdentityApi().
GetIdentity(ctx, id).
IncludeCredential([]string{"webauthn"}).
Execute()
if err != nil {
return false, err
}
var (
webauthnInfo kClient.IdentityCredentials
ok = false
)
if webauthnInfo, ok = identity.GetCredentials()["webauthn"]; !ok {
s.logger.Debugf("Identity %s has no credential entries", id)
return false, nil
}
credentialsSlice, ok := webauthnInfo.Config["credentials"].([]interface{})
if !ok {
// user has no webauthn keys
s.logger.Debugf("Identity %s has no webauthn credentials", id)
return false, nil
}
for _, credentialElem := range credentialsSlice {
credential, ok := credentialElem.(map[string]interface{})
if !ok {
continue
}
isPasswordless, ok := credential["is_passwordless"]
if ok && !isPasswordless.(bool) {
s.logger.Debugf("Identity %s has a 2fa webauthn key", id)
return true, nil
}
}
return false, nil
}
func (s *Service) HasNotEnoughLookupSecretsLeft(ctx context.Context, id string) (bool, error) {
identity, _, err := s.kratosAdmin.IdentityApi().
GetIdentity(ctx, id).
IncludeCredential([]string{"lookup_secret"}).
Execute()
if err != nil {
return false, err
}
lookupSecret, ok := identity.GetCredentials()["lookup_secret"]
if !ok {
s.logger.Debugf("User has no lookup secret credentials")
return false, nil
}
lookupCredentials, ok := lookupSecret.Config["recovery_codes"]
if !ok {
s.logger.Debugf("Recovery codes unavailable")
return false, nil
}
jsonbody, err := json.Marshal(lookupCredentials)
if err != nil {
s.logger.Errorf("Marshalling to json failed: %s", err)
return false, err
}
lookupSecrets := new(LookupSecrets)
if err := json.Unmarshal(jsonbody, &lookupSecrets); err != nil {
s.logger.Errorf("Unmarshalling failed: %s", err)
return false, err
}
unusedCodes := 0
for _, code := range *lookupSecrets {
if code.UsedAt.IsZero() {
unusedCodes += 1
}
}
if unusedCodes > MinimumBackupCodesAmount {
return false, nil
}
s.logger.Debugf("Only %d backup codes are left, redirect the user to generate a new set", unusedCodes)
return true, nil
}
func (s *Service) is1FAMethod(method string) bool {
switch method {
case "password", "oidc":
return true
case "webauthn":
return !s.oidcWebAuthnSequencingEnabled
default:
return false
}
}
// hydrateKratosLoginFlow hydrates the kratos login flow with information about the oauth2 flow
// that initiated it. This is usefull only if the login_challenge was not sent to kratos when
// creating the flow.
func (s *Service) hydrateKratosLoginFlow(ctx context.Context, flow *kClient.LoginFlow) (*kClient.LoginFlow, error) {
u, _ := url.Parse(flow.GetReturnTo())
loginChallenge := u.Query().Get("login_challenge")
// This is not a hydra request, nothing to do here
if loginChallenge == "" {
return flow, nil
}
// The flow already contains information about the oauth2 request
if flow.Oauth2LoginRequest != nil {
return flow, nil
}
b, err := flow.MarshalJSON()
if err != nil {
return nil, err
}
newFlow := new(kClient.LoginFlow)
err = newFlow.UnmarshalJSON(b)
if err != nil {
return nil, err
}
newFlow.Oauth2LoginChallenge = &loginChallenge
hydraLoginRequest, _, err := s.GetLoginRequest(ctx, loginChallenge)
if err != nil {
return newFlow, err