Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,8 @@ GOTRUE_EXPERIMENTAL_CREATE_EMAIL_IDENTITY_ON_PASSWORD_SET_ENABLED="false"
GOTRUE_EXPERIMENTAL_ENABLE_OTT_AS_SOURCE_OF_TRUTH="false"

GOTRUE_EXPERIMENTAL_ONE_TIME_TOKEN_EXPIRES_AT_WRITE_ENABLED="false"

# Refuses an external provider login with 422 email_exists, saving nothing, when
# the provider's unverified email already belongs to another user, instead of
# creating a separate user with no email.
GOTRUE_EXPERIMENTAL_REJECT_UNVERIFIED_EMAIL_IN_USE_ENABLED="false"
28 changes: 27 additions & 1 deletion internal/api/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
inviteToken := getInviteToken(ctx)
if targetUser == nil && inviteToken == "" {
if err := a.triggerBeforeUserCreatedExternal(
r, db, userData, providerType); err != nil {
r, db, userData, providerType, emailOptional); err != nil {
return err
}
}
Expand Down Expand Up @@ -299,6 +299,19 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
return nil
}

// rejectUnverifiedEmailInUse reports whether an external login should be
// refused with email_exists instead of creating a separate user with no email.
// It applies only when GOTRUE_EXPERIMENTAL_REJECT_UNVERIFIED_EMAIL_IN_USE_ENABLED
// is on and the provider's unverified email already belongs to another user.
func rejectUnverifiedEmailInUse(config *conf.GlobalConfiguration, decision models.AccountLinkingResult, emailOptional bool) bool {
return config.Experimental.RejectUnverifiedEmailInUseEnabled &&
decision.Decision == models.CreateAccount &&
decision.EmailTaken &&
decision.LinkingDomain == "default" &&
!emailOptional &&
!config.Mailer.AllowUnverifiedEmailSignIns
}

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)
Expand Down Expand Up @@ -341,6 +354,15 @@ func (a *API) createAccountFromExternalIdentity(tx *storage.Connection, r *http.
}

case models.CreateAccount:
if rejectUnverifiedEmailInUse(config, decision, emailOptional) {
// A plain error rolls back the transaction, so no emailless
// user is left behind.
return 0, nil, apierrors.NewUnprocessableEntityError(
apierrors.ErrorCodeEmailExists,
"Unverified email with %v already belongs to an existing account. Sign in to that account to link %v",
providerType, providerType)
}

if config.DisableSignup {
return 0, nil, apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeSignupDisabled, "Signups not allowed for this instance")
}
Expand Down Expand Up @@ -901,6 +923,10 @@ func getErrorQueryString(err error, errorID string, log logrus.FieldLogger, q ur
q.Set("error", "access_denied")
} else if e.ErrorCode == apierrors.ErrorCodeProviderEmailNeedsVerification {
q.Set("error", "access_denied")
} else if e.ErrorCode == apierrors.ErrorCodeEmailExists && e.HTTPStatus == http.StatusUnprocessableEntity {
// only the 422 from rejectUnverifiedEmailInUse; identity
// linking returns email_exists as a 400 (invalid_request)
q.Set("error", "access_denied")
} else if str, ok := oauthErrorMap[e.HTTPStatus]; ok {
q.Set("error", str)
} else {
Expand Down
151 changes: 151 additions & 0 deletions internal/api/external_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,157 @@ func (ts *ExternalTestSuite) TestAutomaticLinkIdentityWritesAuditLog() {
require.Len(ts.T(), logs, 1, "signing in with an existing identity must not emit another audit log")
}

// TestUnverifiedEmailInUseReturnsEmailExists signs in with GitHub reporting an
// unverified email that already belongs to a user, with the opt-in flag on. The
// login must be refused with email_exists, the before-user-created hook must
// not run, and nothing may be saved.
func (ts *ExternalTestSuite) TestUnverifiedEmailInUseReturnsEmailExists() {
ts.Config.Mailer.AllowUnverifiedEmailSignIns = false
ts.Config.Experimental.RejectUnverifiedEmailInUseEnabled = true
defer func() { ts.Config.Experimental.RejectUnverifiedEmailInUseEnabled = false }()

existingUser, err := ts.createUser("", "github@example.com", "", "", "")
ts.Require().NoError(err)
ts.Require().NoError(existingUser.Confirm(ts.API.db))

var hookCalls int
hookServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hookCalls++
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{}`)
}))
defer hookServer.Close()
ts.Config.Hook.BeforeUserCreated = conf.ExtensibilityPointConfiguration{Enabled: true, URI: hookServer.URL}
defer func() { ts.Config.Hook.BeforeUserCreated = conf.ExtensibilityPointConfiguration{} }()

tokenCount, userCount := 0, 0
code := "authcode"
emails := `[{"email":"github@example.com", "primary": true, "verified": false}]`
server := GitHubTestSignupSetup(ts, &tokenCount, &userCount, code, emails)
defer server.Close()

u := performAuthorization(ts, "github", code, "")

v, err := url.ParseQuery(u.RawQuery)
ts.Require().NoError(err)
ts.Require().Equal("access_denied", v.Get("error"))
ts.Require().Equal("email_exists", v.Get("error_code"))
ts.Require().Equal("Unverified email with github already belongs to an existing account. Sign in to that account to link github", v.Get("error_description"))

ts.Require().Equal(0, hookCalls, "before-user-created hook must be skipped")

_, err = models.FindIdentityByIdAndProvider(ts.API.db, "123", "github")
ts.Require().True(models.IsNotFoundError(err), "no github identity may be saved")

var users []models.User
ts.Require().NoError(ts.API.db.All(&users))
ts.Require().Len(users, 1, "no emailless user may be saved")
ts.Require().Equal(existingUser.ID, users[0].ID)
}

// TestUnverifiedEmailInUseFlagDisabled keeps today's behavior when the opt-in
// flag is off: the login is refused with provider_email_needs_verification and
// a separate emailless user is saved.
func (ts *ExternalTestSuite) TestUnverifiedEmailInUseFlagDisabled() {
ts.Config.Mailer.AllowUnverifiedEmailSignIns = false
ts.Config.Experimental.RejectUnverifiedEmailInUseEnabled = false

existingUser, err := ts.createUser("", "github@example.com", "", "", "")
ts.Require().NoError(err)
ts.Require().NoError(existingUser.Confirm(ts.API.db))

tokenCount, userCount := 0, 0
code := "authcode"
emails := `[{"email":"github@example.com", "primary": true, "verified": false}]`
server := GitHubTestSignupSetup(ts, &tokenCount, &userCount, code, emails)
defer server.Close()

u := performAuthorization(ts, "github", code, "")

v, err := url.ParseQuery(u.RawQuery)
ts.Require().NoError(err)
ts.Require().Equal("access_denied", v.Get("error"))
ts.Require().Equal("provider_email_needs_verification", v.Get("error_code"))

identity, err := models.FindIdentityByIdAndProvider(ts.API.db, "123", "github")
ts.Require().NoError(err)
ts.Require().NotEqual(existingUser.ID, identity.UserID)
}

// TestUnverifiedEmailInUseWithAllowUnverifiedSignIns keeps the existing behavior
// when unverified email sign-ins are allowed, even with the opt-in flag on: a
// separate emailless user is created and signed in.
func (ts *ExternalTestSuite) TestUnverifiedEmailInUseWithAllowUnverifiedSignIns() {
ts.Config.Mailer.AllowUnverifiedEmailSignIns = true
ts.Config.Experimental.RejectUnverifiedEmailInUseEnabled = true
defer func() {
ts.Config.Mailer.AllowUnverifiedEmailSignIns = false
ts.Config.Experimental.RejectUnverifiedEmailInUseEnabled = false
}()

existingUser, err := ts.createUser("", "github@example.com", "", "", "")
ts.Require().NoError(err)
ts.Require().NoError(existingUser.Confirm(ts.API.db))

tokenCount, userCount := 0, 0
code := "authcode"
emails := `[{"email":"github@example.com", "primary": true, "verified": false}]`
server := GitHubTestSignupSetup(ts, &tokenCount, &userCount, code, emails)
defer server.Close()

u := performAuthorization(ts, "github", code, "")

v, err := url.ParseQuery(u.Fragment)
ts.Require().NoError(err)
ts.Require().NotEmpty(v.Get("access_token"))

identity, err := models.FindIdentityByIdAndProvider(ts.API.db, "123", "github")
ts.Require().NoError(err)
ts.Require().NotEqual(existingUser.ID, identity.UserID)
}

func TestRejectUnverifiedEmailInUse(t *testing.T) {
taken := models.AccountLinkingResult{
Decision: models.CreateAccount,
LinkingDomain: "default",
EmailTaken: true,
}

cases := []struct {
desc string
decision func(models.AccountLinkingResult) models.AccountLinkingResult
flagDisabled bool
emailOptional bool
allowUnverified bool
expected bool
}{
{desc: "unverified email in use", expected: true},
{desc: "flag disabled", flagDisabled: true},
{desc: "email not taken", decision: func(d models.AccountLinkingResult) models.AccountLinkingResult { d.EmailTaken = false; return d }},
{desc: "non-default linking domain", decision: func(d models.AccountLinkingResult) models.AccountLinkingResult { d.LinkingDomain = "social"; return d }},
{desc: "sso linking domain", decision: func(d models.AccountLinkingResult) models.AccountLinkingResult { d.LinkingDomain = "sso:abc"; return d }},
{desc: "not a create decision", decision: func(d models.AccountLinkingResult) models.AccountLinkingResult {
d.Decision = models.AccountExists
return d
}},
{desc: "email optional", emailOptional: true},
{desc: "unverified sign-ins allowed", allowUnverified: true},
}

for _, c := range cases {
t.Run(c.desc, func(t *testing.T) {
config := &conf.GlobalConfiguration{}
config.Mailer.AllowUnverifiedEmailSignIns = c.allowUnverified
config.Experimental.RejectUnverifiedEmailInUseEnabled = !c.flagDisabled
decision := taken
if c.decision != nil {
decision = c.decision(decision)
}
require.Equal(t, c.expected, rejectUnverifiedEmailInUse(config, decision, c.emailOptional))
})
}
}

func (ts *ExternalTestSuite) createUser(providerId string, email string, name string, avatar string, confirmationToken string) (*models.User, error) {
// Cleanup existing user, if they already exist
if u, _ := models.FindUserByEmailAndAudience(ts.API.db, email, ts.Config.JWT.Aud); u != nil {
Expand Down
6 changes: 6 additions & 0 deletions internal/api/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func (a *API) triggerBeforeUserCreatedExternal(
db *storage.Connection,
userData *provider.UserProvidedData,
providerType string,
emailOptional bool,
) error {
if !a.hooksMgr.Enabled(v0hooks.BeforeUserCreated) {
return nil
Expand Down Expand Up @@ -91,6 +92,11 @@ func (a *API) triggerBeforeUserCreatedExternal(
if decision.Decision != models.CreateAccount {
return nil
}
if rejectUnverifiedEmailInUse(config, decision, emailOptional) {
// no user will be created: createAccountFromExternalIdentity
// refuses this login with email_exists
return nil
}
if config.DisableSignup {
return apierrors.NewUnprocessableEntityError(
apierrors.ErrorCodeSignupDisabled,
Expand Down
2 changes: 1 addition & 1 deletion internal/api/samlacs.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ func (a *API) handleSamlAcs(w http.ResponseWriter, r *http.Request) error {

providerType := "sso:" + ssoProvider.ID.String()
if err := a.triggerBeforeUserCreatedExternal(
r, db, &userProvidedData, providerType); err != nil {
r, db, &userProvidedData, providerType, false); err != nil {
return err
}

Expand Down
2 changes: 1 addition & 1 deletion internal/api/token_oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.R
grantParams.FillGrantParams(r)

if !params.LinkIdentity {
if err := a.triggerBeforeUserCreatedExternal(r, db, userData, providerType); err != nil {
if err := a.triggerBeforeUserCreatedExternal(r, db, userData, providerType, emailOptional); err != nil {
return err
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/api/web3.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func (a *API) web3GrantSolana(ctx context.Context, w http.ResponseWriter, r *htt
var grantParams models.GrantParams
grantParams.FillGrantParams(r)

if err := a.triggerBeforeUserCreatedExternal(r, db, &userData, providerType); err != nil {
if err := a.triggerBeforeUserCreatedExternal(r, db, &userData, providerType, true); err != nil {
return err
}

Expand Down Expand Up @@ -286,7 +286,7 @@ func (a *API) web3GrantEthereum(ctx context.Context, w http.ResponseWriter, r *h
var grantParams models.GrantParams
grantParams.FillGrantParams(r)

if err := a.triggerBeforeUserCreatedExternal(r, db, &userData, providerType); err != nil {
if err := a.triggerBeforeUserCreatedExternal(r, db, &userData, providerType, true); err != nil {
return err
}

Expand Down
8 changes: 8 additions & 0 deletions internal/conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,14 @@ type ExperimentalConfiguration struct {
// for custom OAuth providers.
// Env: GOTRUE_EXPERIMENTAL_CLIENT_ASSERTION_*
ClientAssertion ClientAssertionConfiguration `split_words:"true"`

// RejectUnverifiedEmailInUseEnabled refuses an external provider login with
// 422 email_exists, saving nothing, when the provider reports an unverified
// email that already belongs to another user. Without it, such a login
// creates a separate user with no email. The user is expected to sign in to
// the existing account and link the identity manually.
// Env: GOTRUE_EXPERIMENTAL_REJECT_UNVERIFIED_EMAIL_IN_USE_ENABLED=true
RejectUnverifiedEmailInUseEnabled bool `split_words:"true" default:"false"`
}

// ReloadingConfiguration holds the configuration values for runtime
Expand Down
9 changes: 8 additions & 1 deletion internal/models/linking.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ type AccountLinkingResult struct {
Identities []*Identity
LinkingDomain string
CandidateEmail provider.Email

// EmailTaken is set when the provider's email is unverified and already
// belongs to another user, so CandidateEmail.Email was cleared instead of
// linking to that user.
EmailTaken bool
}

// DetermineAccountLinking uses the provided data and database state to compute a decision on whether:
Expand Down Expand Up @@ -106,13 +111,15 @@ func DetermineAccountLinking(tx *storage.Connection, config *conf.GlobalConfigur
if terr != nil {
return AccountLinkingResult{}, terr
}
if user != nil {
emailTaken := user != nil
if emailTaken {
candidateEmail.Email = ""
}
return AccountLinkingResult{
Decision: CreateAccount,
LinkingDomain: candidateLinkingDomain,
CandidateEmail: candidateEmail,
EmailTaken: emailTaken,
}, nil
}

Expand Down
2 changes: 2 additions & 0 deletions internal/models/linking_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ func (ts *AccountLinkingTestSuite) TestLinkingScenarios() {
Verified: false,
Primary: true,
},
EmailTaken: true,
},
},
{
Expand Down Expand Up @@ -297,6 +298,7 @@ func (ts *AccountLinkingTestSuite) TestLinkingScenarios() {
require.Equal(ts.T(), c.decision.CandidateEmail.Email, decision.CandidateEmail.Email)
require.Equal(ts.T(), c.decision.CandidateEmail.Verified, decision.CandidateEmail.Verified)
require.Equal(ts.T(), c.decision.CandidateEmail.Primary, decision.CandidateEmail.Primary)
require.Equal(ts.T(), c.decision.EmailTaken, decision.EmailTaken)
})
}

Expand Down
Loading