-
Notifications
You must be signed in to change notification settings - Fork 654
Expand file tree
/
Copy pathlinking.go
More file actions
215 lines (189 loc) · 7.38 KB
/
linking.go
File metadata and controls
215 lines (189 loc) · 7.38 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
package models
import (
"slices"
"strings"
"github.com/supabase/auth/internal/api/provider"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/storage"
)
// GetAccountLinkingDomain returns a string that describes the account linking
// domain. An account linking domain describes a set of Identity entities that
// _should_ generally fall under the same User entity. It's just a runtime
// string, and is not typically persisted in the database. This value can vary
// across time.
func GetAccountLinkingDomain(provider string, ownLinkingDomains []string, dangerousSSOAutoLinking bool) string {
if strings.HasPrefix(provider, "sso:") {
if dangerousSSOAutoLinking {
// When dangerous SSO auto-linking is enabled, treat SSO providers
// like OAuth providers - they join the default linking domain and
// will be linked to existing accounts based on email matching.
return "default"
}
// Default behavior: SSO providers get their own isolated linking domain,
// meaning they will always create new user accounts.
return provider
}
if slices.Contains(ownLinkingDomains, provider) {
// Providers explicitly configured to have their own linking domain
return provider
}
// otherwise, the linking domain is the default linking domain that
// links all accounts
return "default"
}
type AccountLinkingDecision = int
const (
AccountExists AccountLinkingDecision = iota
CreateAccount
LinkAccount
MultipleAccounts
)
type AccountLinkingResult struct {
Decision AccountLinkingDecision
User *User
Identities []*Identity
LinkingDomain string
CandidateEmail provider.Email
}
// DetermineAccountLinking uses the provided data and database state to compute a decision on whether:
// - A new User should be created (CreateAccount)
// - A new Identity should be created (LinkAccount) with a UserID pointing to an existing user account
// - Nothing should be done (AccountExists)
// - It's not possible to decide due to data inconsistency (MultipleAccounts) and the caller should decide
//
// Errors signal failure in processing only, like database access errors.
func DetermineAccountLinking(tx *storage.Connection, config *conf.GlobalConfiguration, emails []provider.Email, aud, providerName, sub string) (AccountLinkingResult, error) {
var verifiedEmails []string
var candidateEmail provider.Email
for _, email := range emails {
if email.Verified || config.Mailer.Autoconfirm {
verifiedEmails = append(verifiedEmails, strings.ToLower(email.Email))
}
if email.Primary {
candidateEmail = email
candidateEmail.Email = strings.ToLower(email.Email)
}
}
// this is the linking domain for the new identity
candidateLinkingDomain := GetAccountLinkingDomain(providerName, config.Experimental.ProvidersWithOwnLinkingDomain, config.Security.DangerousSSOAutoLinking)
if identity, terr := FindIdentityByIdAndProvider(tx, sub, providerName); terr == nil {
// account exists
var user *User
if user, terr = FindUserByID(tx, identity.UserID); terr != nil {
return AccountLinkingResult{}, terr
}
// we overwrite the email with the existing user's email since the user
// could have an empty email
candidateEmail.Email = user.GetEmail()
return AccountLinkingResult{
Decision: AccountExists,
User: user,
Identities: []*Identity{identity},
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
} else if !IsNotFoundError(terr) {
return AccountLinkingResult{}, terr
}
// the identity does not exist, so we need to check if we should create a new account
// or link to an existing one
if len(verifiedEmails) == 0 {
// if there are no verified emails, we always decide to create a new account
user, terr := IsDuplicatedEmail(tx, candidateEmail.Email, aud, nil, config.Experimental.ProvidersWithOwnLinkingDomain, config.Security.DangerousSSOAutoLinking)
if terr != nil {
return AccountLinkingResult{}, terr
}
if user != nil {
candidateEmail.Email = ""
}
return AccountLinkingResult{
Decision: CreateAccount,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
}
var similarIdentities []*Identity
var similarUsers []*User
// look for similar identities and users based on email
if terr := tx.Q().Eager().Where("email = any (?)", verifiedEmails).All(&similarIdentities); terr != nil {
return AccountLinkingResult{}, terr
}
if candidateLinkingDomain == "default" {
// there can be multiple user accounts with the same email when is_sso_user is true
// so we just do not consider those similar user accounts
if terr := tx.Q().Eager().Where("email = any (?) and is_sso_user = false", verifiedEmails).All(&similarUsers); terr != nil {
return AccountLinkingResult{}, terr
}
}
// Need to check if the new identity should be assigned to an
// existing user or to create a new user, according to the automatic
// linking rules
var linkingIdentities []*Identity
// now let's see if there are any existing and similar identities in
// the same linking domain
for _, identity := range similarIdentities {
if GetAccountLinkingDomain(identity.Provider, config.Experimental.ProvidersWithOwnLinkingDomain, config.Security.DangerousSSOAutoLinking) == candidateLinkingDomain {
linkingIdentities = append(linkingIdentities, identity)
}
}
if len(linkingIdentities) == 0 {
if len(similarUsers) == 1 {
// no similarIdentities but a user with the same email exists
// so we link this new identity to the user
// TODO: Backfill the missing identity for the user
return AccountLinkingResult{
Decision: LinkAccount,
User: similarUsers[0],
Identities: linkingIdentities,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
} else if len(similarUsers) > 1 {
// this shouldn't happen since there is a partial unique index on (email and is_sso_user = false)
return AccountLinkingResult{
Decision: MultipleAccounts,
Identities: linkingIdentities,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
} else {
// there are no identities in the linking domain, we have to
// create a new identity and new user
return AccountLinkingResult{
Decision: CreateAccount,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
}
}
// there is at least one identity in the linking domain let's do a
// sanity check to see if all of the identities in the domain share the
// same user ID
linkingUserId := linkingIdentities[0].UserID
for _, identity := range linkingIdentities {
if identity.UserID != linkingUserId {
// ok this linking domain has more than one user account
// caller should decide what to do
return AccountLinkingResult{
Decision: MultipleAccounts,
Identities: linkingIdentities,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
}
}
// there's only one user ID in this linking domain, we can go on and
// create a new identity and link it to the existing account
var user *User
var terr error
if user, terr = FindUserByID(tx, linkingUserId); terr != nil {
return AccountLinkingResult{}, terr
}
return AccountLinkingResult{
Decision: LinkAccount,
User: user,
Identities: linkingIdentities,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
}, nil
}