-
Notifications
You must be signed in to change notification settings - Fork 635
Expand file tree
/
Copy pathexternal.go
More file actions
858 lines (765 loc) · 29 KB
/
external.go
File metadata and controls
858 lines (765 loc) · 29 KB
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
package api
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/fatih/structs"
"github.com/gofrs/uuid"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/sirupsen/logrus"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/api/provider"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/metering"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/observability"
"github.com/supabase/auth/internal/storage"
"github.com/supabase/auth/internal/utilities"
"golang.org/x/oauth2"
)
// ExternalProviderClaims are the JWT claims sent as the state in the external oauth provider signup flow
type ExternalProviderClaims struct {
AuthMicroserviceClaims
Provider string `json:"provider"`
InviteToken string `json:"invite_token,omitempty"`
Referrer string `json:"referrer,omitempty"`
FlowStateID string `json:"flow_state_id"`
OAuthClientStateID string `json:"oauth_client_state_id,omitempty"`
LinkingTargetID string `json:"linking_target_id,omitempty"`
EmailOptional bool `json:"email_optional,omitempty"`
}
// ExternalProviderRedirect redirects the request to the oauth provider
func (a *API) ExternalProviderRedirect(w http.ResponseWriter, r *http.Request) error {
rurl, err := a.GetExternalProviderRedirectURL(w, r, nil)
if err != nil {
return err
}
http.Redirect(w, r, rurl, http.StatusFound)
return nil
}
// GetExternalProviderRedirectURL returns the URL to start the oauth flow with the corresponding oauth provider
func (a *API) GetExternalProviderRedirectURL(w http.ResponseWriter, r *http.Request, linkingTargetUser *models.User) (string, error) {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
query := r.URL.Query()
providerType := query.Get("provider")
scopes := query.Get("scopes")
codeChallenge := query.Get("code_challenge")
codeChallengeMethod := query.Get("code_challenge_method")
p, pConfig, err := a.Provider(ctx, providerType, scopes)
if err != nil {
return "", apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Unsupported provider: %+v", err).WithInternalError(err)
}
inviteToken := query.Get("invite_token")
if inviteToken != "" {
_, userErr := models.FindUserByConfirmationToken(db, inviteToken)
if userErr != nil {
if models.IsNotFoundError(userErr) {
return "", apierrors.NewNotFoundError(apierrors.ErrorCodeUserNotFound, "User identified by token not found")
}
return "", apierrors.NewInternalServerError("Database error finding user").WithInternalError(userErr)
}
}
redirectURL := utilities.GetReferrer(r, config)
log := observability.GetLogEntry(r).Entry
log.WithField("provider", providerType).Info("Redirecting to external provider")
if err := validatePKCEParams(codeChallengeMethod, codeChallenge); err != nil {
return "", err
}
authUrlParams := make([]oauth2.AuthCodeOption, 0)
query.Del("scopes")
query.Del("provider")
query.Del("code_challenge")
query.Del("code_challenge_method")
for key := range query {
if key == "workos_provider" {
// See https://workos.com/docs/reference/sso/authorize/get
authUrlParams = append(authUrlParams, oauth2.SetAuthURLParam("provider", query.Get(key)))
} else {
authUrlParams = append(authUrlParams, oauth2.SetAuthURLParam(key, query.Get(key)))
}
}
// Handle OAuthClientState for providers that require PKCE on their end
var oauthClientStateID *uuid.UUID
if oauthProvider, ok := p.(provider.OAuthProvider); ok && oauthProvider.RequiresPKCE() {
codeVerifier := oauth2.GenerateVerifier()
oauthClientState := models.NewOAuthClientState(providerType, &codeVerifier)
err := db.Create(oauthClientState)
if err != nil {
return "", err
}
oauthClientStateID = &oauthClientState.ID
authUrlParams = append(authUrlParams, oauth2.S256ChallengeOption(codeVerifier))
}
// Build flow state params with all context
flowParams := models.FlowStateParams{
ProviderType: providerType,
AuthenticationMethod: models.OAuth,
CodeChallenge: codeChallenge,
CodeChallengeMethod: codeChallengeMethod,
InviteToken: inviteToken,
Referrer: redirectURL,
OAuthClientStateID: oauthClientStateID,
EmailOptional: pConfig.EmailOptional,
}
if linkingTargetUser != nil {
// this means that the user is performing manual linking
flowParams.LinkingTargetID = &linkingTargetUser.ID
}
// Always create flow state for all flows (both PKCE and implicit)
// The flow state ID is used as the state parameter instead of JWT
flowState, err := models.NewFlowState(flowParams)
if err != nil {
return "", apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Invalid code_challenge_method").WithInternalError(err)
}
if err := db.Create(flowState); err != nil {
return "", apierrors.NewInternalServerError("Error creating flow state").WithInternalError(err)
}
// Use the flow state ID as the state parameter (UUID format)
authURL := p.AuthCodeURL(flowState.ID.String(), authUrlParams...)
return authURL, nil
}
// ExternalProviderCallback handles the callback endpoint in the external oauth provider flow
func (a *API) ExternalProviderCallback(w http.ResponseWriter, r *http.Request) error {
rurl := a.getExternalRedirectURL(r)
u, err := url.Parse(rurl)
if err != nil {
return err
}
redirectErrors(a.internalExternalProviderCallback, w, r, u)
return nil
}
func (a *API) handleOAuthCallback(r *http.Request) (*OAuthProviderData, error) {
ctx := r.Context()
providerType, _ := getExternalProviderType(ctx)
var oAuthResponseData *OAuthProviderData
var err error
switch providerType {
case "twitter":
// future OAuth1.0 providers will use this method
oAuthResponseData, err = a.oAuth1Callback(ctx, providerType)
default:
oAuthResponseData, err = a.oAuthCallback(ctx, r, providerType)
}
if err != nil {
return nil, err
}
return oAuthResponseData, nil
}
func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
var grantParams models.GrantParams
grantParams.FillGrantParams(r)
providerType, emailOptional := getExternalProviderType(ctx)
data, err := a.handleOAuthCallback(r)
if err != nil {
return err
}
userData := data.userData
if len(userData.Emails) == 0 && !emailOptional {
return apierrors.NewInternalServerError("Error getting user email from external provider")
}
userData.Metadata.EmailVerified = false
for _, email := range userData.Emails {
if email.Primary {
userData.Metadata.Email = email.Email
userData.Metadata.EmailVerified = email.Verified
break
} else {
userData.Metadata.Email = email.Email
userData.Metadata.EmailVerified = email.Verified
}
}
providerAccessToken := data.token
providerRefreshToken := data.refreshToken
// Get flow state from context (new UUID format) or load from FlowStateID (legacy JWT format)
flowState := getFlowState(ctx)
if flowState == nil {
// Backward compatibility: load from FlowStateID for legacy JWT state
// To be removed in subsequent release.
if flowStateID := getFlowStateID(ctx); flowStateID != "" {
flowState, err = models.FindFlowStateByID(db, flowStateID)
if models.IsNotFoundError(err) {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeFlowStateNotFound, "Flow state not found").WithInternalError(err)
} else if err != nil {
return apierrors.NewInternalServerError("Failed to find flow state").WithInternalError(err)
}
}
}
targetUser := getTargetUser(ctx)
inviteToken := getInviteToken(ctx)
if targetUser == nil && inviteToken == "" {
if err := a.triggerBeforeUserCreatedExternal(
r, db, userData, providerType); err != nil {
return err
}
}
var createdUser bool
var user *models.User
var token *AccessTokenResponse
err = db.Transaction(func(tx *storage.Connection) error {
var terr error
if targetUser != nil {
if user, terr = a.linkIdentityToUser(r, ctx, tx, userData, providerType); terr != nil {
return terr
}
} else if inviteToken != "" {
if user, terr = a.processInvite(r, tx, userData, inviteToken, providerType); terr != nil {
return terr
}
} else {
createdUser = true
if _, user, terr = a.createAccountFromExternalIdentity(tx, r, userData, providerType, emailOptional); terr != nil {
return terr
}
}
if flowState != nil && flowState.IsPKCE() {
// PKCE flow: update flow state with user ID and tokens
flowState.ProviderAccessToken = providerAccessToken
flowState.ProviderRefreshToken = providerRefreshToken
flowState.UserID = &(user.ID)
issueTime := time.Now()
flowState.AuthCodeIssuedAt = &issueTime
terr = tx.Update(flowState)
} else {
// Implicit flow: issue tokens directly
token, terr = a.issueRefreshToken(r, w.Header(), tx, user, models.OAuth, grantParams)
if terr == nil && flowState != nil {
terr = tx.Destroy(flowState)
}
}
if terr != nil {
return apierrors.NewOAuthError("server_error", terr.Error())
}
return nil
})
if err != nil {
return err
}
if createdUser {
if err := a.triggerAfterUserCreated(r, db, user); err != nil {
return err
}
}
// Record login for analytics - only when token is issued (not during pkce authorize)
if token != nil {
metering.RecordLogin(metering.LoginTypeOAuth, user.ID, &metering.LoginData{
Provider: providerType,
})
}
rurl := a.getExternalRedirectURL(r)
if flowState != nil && flowState.IsPKCE() {
// PKCE flow: redirect with auth code
rurl, err = a.prepPKCERedirectURL(rurl, *flowState.AuthCode)
if err != nil {
return err
}
} else if token != nil {
q := url.Values{}
q.Set("provider_token", providerAccessToken)
// Because not all providers give out a refresh token
// See corresponding OAuth2 spec: <https://www.rfc-editor.org/rfc/rfc6749.html#section-5.1>
if providerRefreshToken != "" {
q.Set("provider_refresh_token", providerRefreshToken)
}
rurl = token.AsRedirectURL(rurl, q)
}
http.Redirect(w, r, rurl, http.StatusFound)
return nil
}
func (a *API) createAccountFromExternalIdentity(tx *storage.Connection, r *http.Request, userData *provider.UserProvidedData, providerType string, emailOptional bool) (models.AccountLinkingDecision, *models.User, error) {
ctx := r.Context()
aud := a.requestAud(ctx, r)
config := a.config
var user *models.User
var identity *models.Identity
var identityData map[string]interface{}
if userData.Metadata != nil {
identityData = structs.Map(userData.Metadata)
}
decision, terr := models.DetermineAccountLinking(tx, config, userData.Emails, aud, providerType, userData.Metadata.Subject)
if terr != nil {
return 0, nil, terr
}
switch decision.Decision {
case models.LinkAccount:
user = decision.User
if identity, terr = a.createNewIdentity(tx, user, providerType, identityData); terr != nil {
return 0, nil, terr
}
if terr = user.UpdateUserMetaData(tx, identityData); terr != nil {
return 0, nil, terr
}
if terr = user.UpdateAppMetaDataProviders(tx); terr != nil {
return 0, nil, terr
}
case models.CreateAccount:
if config.DisableSignup {
return 0, nil, apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeSignupDisabled, "Signups not allowed for this instance")
}
params := &SignupParams{
Provider: providerType,
Email: decision.CandidateEmail.Email,
Aud: aud,
Data: identityData,
}
// This is a little bit of a hack. Let me explain: When
// is_sso_user == true, it allows there to be different user
// rows with the same email address. Initially it was added to
// support SSO accounts, but at this point renaming the column
// or adding a new one requires re-indexing the table which is
// expensive and introduces a potentially unnecessary API
// surface change. It therefore set to true for other linking
// domains, not just SSO ones. This enables different linking
// domains to co-exist, such as when using
// GOTRUE_EXPERIMENTAL_PROVIDERS_WITH_OWN_LINKING_DOMAIN="provider_a,provider_b".
isSSOUser := decision.LinkingDomain != "default"
// because params above sets no password, this method is not
// computationally hard so it can be used within a database
// transaction
user, terr = params.ToUserModel(isSSOUser)
if terr != nil {
return 0, nil, terr
}
if user, terr = a.signupNewUser(tx, user); terr != nil {
return 0, nil, terr
}
if identity, terr = a.createNewIdentity(tx, user, providerType, identityData); terr != nil {
return 0, nil, terr
}
user.Identities = append(user.Identities, *identity)
case models.AccountExists:
user = decision.User
identity = decision.Identities[0]
identity.IdentityData = identityData
if terr = tx.UpdateOnly(identity, "identity_data", "last_sign_in_at"); terr != nil {
return 0, nil, terr
}
if terr = user.UpdateUserMetaData(tx, identityData); terr != nil {
return 0, nil, terr
}
if terr = user.UpdateAppMetaDataProviders(tx); terr != nil {
return 0, nil, terr
}
case models.MultipleAccounts:
return 0, nil, apierrors.NewInternalServerError("Multiple accounts with the same email address in the same linking domain detected: %v", decision.LinkingDomain)
default:
return 0, nil, apierrors.NewInternalServerError("Unknown automatic linking decision: %v", decision.Decision)
}
if user.IsBanned() {
return 0, nil, apierrors.NewForbiddenError(apierrors.ErrorCodeUserBanned, "User is banned")
}
hasEmails := providerType != "web3" && !(emailOptional && decision.CandidateEmail.Email == "")
if hasEmails && !user.IsConfirmed() {
// The user may have other unconfirmed email + password
// combination, phone or oauth identities. These identities
// need to be removed when a new oauth identity is being added
// to prevent pre-account takeover attacks from happening.
if terr = user.RemoveUnconfirmedIdentities(tx, identity); terr != nil {
return 0, nil, apierrors.NewInternalServerError("Error updating user").WithInternalError(terr)
}
if decision.CandidateEmail.Verified || config.Mailer.Autoconfirm {
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.UserSignedUpAction, "", map[string]interface{}{
"provider": providerType,
}); terr != nil {
return 0, nil, terr
}
// fall through to auto-confirm and issue token
if terr = user.Confirm(tx); terr != nil {
return 0, nil, apierrors.NewInternalServerError("Error updating user").WithInternalError(terr)
}
} else {
emailConfirmationSent := false
if decision.CandidateEmail.Email != "" {
if terr = a.sendConfirmation(r, tx, user, models.ImplicitFlow); terr != nil {
return 0, nil, terr
}
emailConfirmationSent = true
}
if !config.Mailer.AllowUnverifiedEmailSignIns {
if emailConfirmationSent {
err := apierrors.NewUnprocessableEntityError(
apierrors.ErrorCodeProviderEmailNeedsVerification,
"Unverified email with %v. A confirmation email has been sent to your %v email",
providerType, providerType,
)
return 0, nil, storage.NewCommitWithError(err)
}
err := apierrors.NewUnprocessableEntityError(
apierrors.ErrorCodeProviderEmailNeedsVerification,
"Unverified email with %v. Verify the email with %v in order to sign in",
providerType, providerType)
return 0, nil, storage.NewCommitWithError(err)
}
}
} else {
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.LoginAction, "", map[string]interface{}{
"provider": providerType,
}); terr != nil {
return 0, nil, terr
}
}
return decision.Decision, user, nil
}
func (a *API) processInvite(r *http.Request, tx *storage.Connection, userData *provider.UserProvidedData, inviteToken, providerType string) (*models.User, error) {
config := a.config
user, err := models.FindUserByConfirmationToken(tx, inviteToken)
if err != nil {
if models.IsNotFoundError(err) {
return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeInviteNotFound, "Invite not found")
}
return nil, apierrors.NewInternalServerError("Database error finding user").WithInternalError(err)
}
var emailData *provider.Email
var emails []string
for i, e := range userData.Emails {
emails = append(emails, e.Email)
if user.GetEmail() == e.Email {
emailData = &userData.Emails[i]
break
}
}
if emailData == nil {
return nil, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Invited email does not match emails from external provider").WithInternalMessage("invited=%s external=%s", user.Email, strings.Join(emails, ", "))
}
var identityData map[string]interface{}
if userData.Metadata != nil {
identityData = structs.Map(userData.Metadata)
}
identity, err := a.createNewIdentity(tx, user, providerType, identityData)
if err != nil {
return nil, err
}
if err := user.UpdateAppMetaData(tx, map[string]interface{}{
"provider": providerType,
}); err != nil {
return nil, err
}
if err := user.UpdateAppMetaDataProviders(tx); err != nil {
return nil, err
}
if err := user.UpdateUserMetaData(tx, identityData); err != nil {
return nil, apierrors.NewInternalServerError("Database error updating user").WithInternalError(err)
}
if err := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.InviteAcceptedAction, "", map[string]interface{}{
"provider": providerType,
}); err != nil {
return nil, err
}
// an account with a previously unconfirmed email + password
// combination or phone may exist. so now that there is an
// OAuth identity bound to this user, and since they have not
// confirmed their email or phone, they are unaware that a
// potentially malicious door exists into their account; thus
// the password and phone needs to be removed.
if err := user.RemoveUnconfirmedIdentities(tx, identity); err != nil {
return nil, apierrors.NewInternalServerError("Error updating user").WithInternalError(err)
}
// confirm because they were able to respond to invite email
if err := user.Confirm(tx); err != nil {
return nil, err
}
return user, nil
}
func (a *API) loadExternalState(ctx context.Context, r *http.Request, db *storage.Connection) (context.Context, error) {
var state string
switch r.Method {
case http.MethodPost:
state = r.FormValue("state")
default:
state = r.URL.Query().Get("state")
}
if state == "" {
return ctx, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthCallback, "OAuth state parameter missing")
}
// Try to parse state as UUID first (new format)
if stateUUID, err := uuid.FromString(state); err == nil {
return a.loadExternalStateFromUUID(ctx, db, stateUUID)
}
// Fall back to JWT parsing for backward compatibility
return a.loadExternalStateFromJWT(ctx, db, state)
}
// loadExternalStateFromUUID loads OAuth state from a flow_state record (new UUID format)
func (a *API) loadExternalStateFromUUID(ctx context.Context, db *storage.Connection, stateID uuid.UUID) (context.Context, error) {
config := a.config
flowState, err := models.FindFlowStateByID(db, stateID.String())
if models.IsNotFoundError(err) {
return ctx, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth state not found or expired")
} else if err != nil {
return ctx, apierrors.NewInternalServerError("Error loading flow state").WithInternalError(err)
}
// Check expiration
if flowState.IsExpired(config.External.FlowStateExpiryDuration) {
return ctx, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth state has expired")
}
ctx = withExternalProviderType(ctx, flowState.ProviderType, flowState.EmailOptional)
if flowState.InviteToken != nil && *flowState.InviteToken != "" {
ctx = withInviteToken(ctx, *flowState.InviteToken)
}
if flowState.Referrer != nil && *flowState.Referrer != "" {
ctx = withExternalReferrer(ctx, *flowState.Referrer)
}
if flowState.OAuthClientStateID != nil {
ctx = withOAuthClientStateID(ctx, *flowState.OAuthClientStateID)
}
if flowState.LinkingTargetID != nil {
u, err := models.FindUserByID(db, *flowState.LinkingTargetID)
if err != nil {
if models.IsNotFoundError(err) {
return nil, apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeUserNotFound, "Linking target user not found")
}
return nil, apierrors.NewInternalServerError("Database error loading user").WithInternalError(err)
}
ctx = withTargetUser(ctx, u)
}
// Store the entire flow state in context for later use
ctx = withFlowState(ctx, flowState)
return withSignature(ctx, stateID.String()), nil
}
// loadExternalStateFromJWT loads OAuth state from a JWT (legacy format for backward compatibility)
func (a *API) loadExternalStateFromJWT(ctx context.Context, db *storage.Connection, state string) (context.Context, error) {
config := a.config
claims := ExternalProviderClaims{}
p := jwt.NewParser(jwt.WithValidMethods(config.JWT.ValidMethods))
_, err := p.ParseWithClaims(state, &claims, func(token *jwt.Token) (interface{}, error) {
if kid, ok := token.Header["kid"]; ok {
if kidStr, ok := kid.(string); ok {
key, err := conf.FindPublicKeyByKid(kidStr, &config.JWT)
if err != nil {
return nil, err
}
if key != nil {
return key, nil
}
// otherwise try to use fallback
}
}
if alg, ok := token.Header["alg"]; ok {
if alg == jwt.SigningMethodHS256.Name {
// preserve backward compatibility for cases where the kid is not set or potentially invalid but the key can be decoded with the secret
return []byte(config.JWT.Secret), nil
}
}
return nil, fmt.Errorf("unrecognized JWT kid %v for algorithm %v", token.Header["kid"], token.Header["alg"])
})
if err != nil {
return ctx, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth callback with invalid state").WithInternalError(err)
}
if claims.Provider == "" {
return ctx, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth callback with invalid state (missing provider)")
}
if claims.InviteToken != "" {
ctx = withInviteToken(ctx, claims.InviteToken)
}
if claims.Referrer != "" {
ctx = withExternalReferrer(ctx, claims.Referrer)
}
if claims.FlowStateID != "" {
ctx = withFlowStateID(ctx, claims.FlowStateID)
}
if claims.OAuthClientStateID != "" {
oauthClientStateID, err := uuid.FromString(claims.OAuthClientStateID)
if err != nil {
return nil, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth callback with invalid state (oauth_client_state_id must be UUID)")
}
ctx = withOAuthClientStateID(ctx, oauthClientStateID)
}
if claims.LinkingTargetID != "" {
linkingTargetUserID, err := uuid.FromString(claims.LinkingTargetID)
if err != nil {
return nil, apierrors.NewBadRequestError(apierrors.ErrorCodeBadOAuthState, "OAuth callback with invalid state (linking_target_id must be UUID)")
}
u, err := models.FindUserByID(db, linkingTargetUserID)
if err != nil {
if models.IsNotFoundError(err) {
return nil, apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeUserNotFound, "Linking target user not found")
}
return nil, apierrors.NewInternalServerError("Database error loading user").WithInternalError(err)
}
ctx = withTargetUser(ctx, u)
}
ctx = withExternalProviderType(ctx, claims.Provider, claims.EmailOptional)
return withSignature(ctx, state), nil
}
// Provider returns a Provider interface for the given name.
func (a *API) Provider(ctx context.Context, name string, scopes string) (provider.Provider, conf.OAuthProviderConfiguration, error) {
config := a.config
name = strings.ToLower(name)
var err error
var p provider.Provider
var pConfig conf.OAuthProviderConfiguration
switch name {
case "apple":
pConfig = config.External.Apple
p, err = provider.NewAppleProvider(ctx, pConfig)
case "azure":
pConfig = config.External.Azure
p, err = provider.NewAzureProvider(pConfig, scopes)
case "bitbucket":
pConfig = config.External.Bitbucket
p, err = provider.NewBitbucketProvider(pConfig)
case "discord":
pConfig = config.External.Discord
p, err = provider.NewDiscordProvider(pConfig, scopes)
case "facebook":
pConfig = config.External.Facebook
p, err = provider.NewFacebookProvider(pConfig, scopes)
case "figma":
pConfig = config.External.Figma
p, err = provider.NewFigmaProvider(pConfig, scopes)
case "fly":
pConfig = config.External.Fly
p, err = provider.NewFlyProvider(pConfig, scopes)
case "github":
pConfig = config.External.Github
p, err = provider.NewGithubProvider(pConfig, scopes)
case "gitlab":
pConfig = config.External.Gitlab
p, err = provider.NewGitlabProvider(pConfig, scopes)
case "google":
pConfig = config.External.Google
p, err = provider.NewGoogleProvider(ctx, pConfig, scopes)
case "kakao":
pConfig = config.External.Kakao
p, err = provider.NewKakaoProvider(pConfig, scopes)
case "keycloak":
pConfig = config.External.Keycloak
p, err = provider.NewKeycloakProvider(pConfig, scopes)
case "linkedin":
pConfig = config.External.Linkedin
p, err = provider.NewLinkedinProvider(pConfig, scopes)
case "linkedin_oidc":
pConfig = config.External.LinkedinOIDC
p, err = provider.NewLinkedinOIDCProvider(ctx, pConfig, scopes)
case "notion":
pConfig = config.External.Notion
p, err = provider.NewNotionProvider(pConfig)
case "snapchat":
pConfig = config.External.Snapchat
p, err = provider.NewSnapchatProvider(pConfig, scopes)
case "spotify":
pConfig = config.External.Spotify
p, err = provider.NewSpotifyProvider(pConfig, scopes)
case "slack":
pConfig = config.External.Slack
p, err = provider.NewSlackProvider(pConfig, scopes)
case "slack_oidc":
pConfig = config.External.SlackOIDC
p, err = provider.NewSlackOIDCProvider(pConfig, scopes)
case "twitch":
pConfig = config.External.Twitch
p, err = provider.NewTwitchProvider(pConfig, scopes)
case "twitter":
pConfig = config.External.Twitter
p, err = provider.NewTwitterProvider(pConfig, scopes)
case "x":
pConfig = config.External.X
p, err = provider.NewXProvider(pConfig, scopes)
case "vercel_marketplace":
pConfig = config.External.VercelMarketplace
p, err = provider.NewVercelMarketplaceProvider(ctx, pConfig, scopes)
case "workos":
pConfig = config.External.WorkOS
p, err = provider.NewWorkOSProvider(pConfig)
case "zoom":
pConfig = config.External.Zoom
p, err = provider.NewZoomProvider(pConfig)
default:
return nil, pConfig, fmt.Errorf("Provider %s could not be found", name)
}
return p, pConfig, err
}
func redirectErrors(handler apiHandler, w http.ResponseWriter, r *http.Request, u *url.URL) {
ctx := r.Context()
log := observability.GetLogEntry(r).Entry
errorID := utilities.GetRequestID(ctx)
err := handler(w, r)
if err != nil {
q := getErrorQueryString(err, errorID, log, u.Query())
u.RawQuery = q.Encode()
// TODO: deprecate returning error details in the query fragment
hq := url.Values{}
if q.Get("error") != "" {
hq.Set("error", q.Get("error"))
}
if q.Get("error_description") != "" {
hq.Set("error_description", q.Get("error_description"))
}
if q.Get("error_code") != "" {
hq.Set("error_code", q.Get("error_code"))
}
// Add Supabase Auth identifier to help clients distinguish Supabase Auth redirects
hq.Set("sb", "")
u.Fragment = hq.Encode()
http.Redirect(w, r, u.String(), http.StatusFound)
}
}
func getErrorQueryString(err error, errorID string, log logrus.FieldLogger, q url.Values) *url.Values {
switch e := err.(type) {
case *HTTPError:
if e.ErrorCode == apierrors.ErrorCodeSignupDisabled {
q.Set("error", "access_denied")
} else if e.ErrorCode == apierrors.ErrorCodeUserBanned {
q.Set("error", "access_denied")
} else if e.ErrorCode == apierrors.ErrorCodeProviderEmailNeedsVerification {
q.Set("error", "access_denied")
} else if str, ok := oauthErrorMap[e.HTTPStatus]; ok {
q.Set("error", str)
} else {
q.Set("error", "server_error")
}
if e.HTTPStatus >= http.StatusInternalServerError {
e.ErrorID = errorID
// this will get us the stack trace too
log.WithError(e.Cause()).Error(e.Error())
} else {
log.WithError(e.Cause()).Info(e.Error())
}
q.Set("error_description", e.Message)
q.Set("error_code", e.ErrorCode)
case *OAuthError:
q.Set("error", e.Err)
q.Set("error_description", e.Description)
log.WithError(e.Cause()).Info(e.Error())
case ErrorCause:
return getErrorQueryString(e.Cause(), errorID, log, q)
default:
error_type, error_description := "server_error", err.Error()
// Provide better error messages for certain user-triggered Postgres errors.
if pgErr := utilities.NewPostgresError(e); pgErr != nil {
error_description = pgErr.Message
if oauthErrorType, ok := oauthErrorMap[pgErr.HttpStatusCode]; ok {
error_type = oauthErrorType
}
}
q.Set("error", error_type)
q.Set("error_description", error_description)
}
return &q
}
func (a *API) getExternalRedirectURL(r *http.Request) string {
ctx := r.Context()
config := a.config
if config.External.RedirectURL != "" {
return config.External.RedirectURL
}
if er := getExternalReferrer(ctx); er != "" {
return er
}
return config.SiteURL
}
func (a *API) createNewIdentity(tx *storage.Connection, user *models.User, providerType string, identityData map[string]interface{}) (*models.Identity, error) {
identity, err := models.NewIdentity(user, providerType, identityData)
if err != nil {
return nil, err
}
if terr := tx.Create(identity); terr != nil {
return nil, apierrors.NewInternalServerError("Error creating identity").WithInternalError(terr)
}
return identity, nil
}