Skip to content

Commit a7e97d6

Browse files
staaldraadhfclaude
authored
feat: clear existing password on recover (#2887)
## What kind of change does this PR introduce? Bug fix ## What is the current behavior? A password set on an unconfirmed account would remain valid if the account was verified through a linked signup (magic link etc) ## What is the new behavior? a password set on an unconfirmed account is now wiped when the email’s owner proves ownership through a magic link, email OTP or password recovery Co-authored-by: Stojan Dimitrovski <sdimitrovski@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 6311d50 commit a7e97d6

7 files changed

Lines changed: 185 additions & 0 deletions

File tree

‎internal/api/magic_link.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,22 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
8181
if user != nil {
8282
isNewUser = !user.IsConfirmed()
8383
}
84+
if user != nil && isNewUser && user.HasPassword() {
85+
// The unconfirmed user's password may have been set by someone who
86+
// doesn't own the email. Remove it so it can't be used once the
87+
// email owner confirms the account through this magic link.
88+
err = db.Transaction(func(tx *storage.Connection) error {
89+
if terr := user.ClearUnconfirmedPassword(tx); terr != nil {
90+
return terr
91+
}
92+
return models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.UserModifiedAction, "", map[string]interface{}{
93+
"reason": models.UnconfirmedPasswordClearedReason,
94+
})
95+
})
96+
if err != nil {
97+
return apierrors.NewInternalServerError("Database error updating user").WithInternalError(err)
98+
}
99+
}
84100
if isNewUser {
85101
// User either doesn't exist or hasn't completed the signup process.
86102
// Sign them up with temporary password.

‎internal/api/otp_test.go‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@ package api
33
import (
44
"bytes"
55
"encoding/json"
6+
"fmt"
67
"net/http"
78
"net/http/httptest"
89
"testing"
10+
"time"
911

1012
"github.com/stretchr/testify/assert"
1113
"github.com/stretchr/testify/require"
1214
"github.com/stretchr/testify/suite"
1315
"github.com/supabase/auth/internal/api/apierrors"
1416
"github.com/supabase/auth/internal/conf"
17+
mail "github.com/supabase/auth/internal/mailer"
1518
"github.com/supabase/auth/internal/models"
1619
)
1720

@@ -310,3 +313,121 @@ func (ts *OtpTestSuite) TestSubsequentOtp() {
310313
require.Empty(ts.T(), user.RecoverySentAt)
311314
require.Empty(ts.T(), user.EmailConfirmedAt)
312315
}
316+
317+
func (ts *OtpTestSuite) TestOtpClearsUnconfirmedPassword() {
318+
ts.Config.SMTP.MaxFrequency = 0
319+
ts.Config.Mailer.Autoconfirm = false
320+
defer func() { ts.Config.Mailer.Autoconfirm = false }()
321+
322+
userEmail := "victim@example.com"
323+
attackerPassword := "attacker-password-123"
324+
325+
// attacker signs up with the victim's email and leaves it unconfirmed
326+
var buffer bytes.Buffer
327+
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
328+
"email": userEmail,
329+
"password": attackerPassword,
330+
}))
331+
req := httptest.NewRequest(http.MethodPost, "/signup", &buffer)
332+
req.Header.Set("Content-Type", "application/json")
333+
w := httptest.NewRecorder()
334+
ts.API.handler.ServeHTTP(w, req)
335+
require.Equal(ts.T(), http.StatusOK, w.Code)
336+
337+
user, err := models.FindUserByEmailAndAudience(ts.API.db, userEmail, ts.Config.JWT.Aud)
338+
require.NoError(ts.T(), err)
339+
require.False(ts.T(), user.IsConfirmed())
340+
require.True(ts.T(), user.HasPassword())
341+
342+
// email owner requests a magic link
343+
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
344+
"email": userEmail,
345+
}))
346+
req = httptest.NewRequest(http.MethodPost, "/otp", &buffer)
347+
req.Header.Set("Content-Type", "application/json")
348+
w = httptest.NewRecorder()
349+
ts.API.handler.ServeHTTP(w, req)
350+
require.Equal(ts.T(), http.StatusOK, w.Code)
351+
352+
user, err = models.FindUserByEmailAndAudience(ts.API.db, userEmail, ts.Config.JWT.Aud)
353+
require.NoError(ts.T(), err)
354+
require.False(ts.T(), user.HasPassword())
355+
require.NotEmpty(ts.T(), user.ConfirmationToken)
356+
357+
// email owner confirms through the link
358+
reqURL := fmt.Sprintf("http://localhost/verify?type=%s&token=%s", mail.SignupVerification, user.ConfirmationToken)
359+
req = httptest.NewRequest(http.MethodGet, reqURL, nil)
360+
w = httptest.NewRecorder()
361+
ts.API.handler.ServeHTTP(w, req)
362+
require.Equal(ts.T(), http.StatusSeeOther, w.Code)
363+
364+
user, err = models.FindUserByEmailAndAudience(ts.API.db, userEmail, ts.Config.JWT.Aud)
365+
require.NoError(ts.T(), err)
366+
require.True(ts.T(), user.IsConfirmed())
367+
require.False(ts.T(), user.HasPassword())
368+
369+
// attacker can no longer sign in with their password
370+
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
371+
"email": userEmail,
372+
"password": attackerPassword,
373+
}))
374+
req = httptest.NewRequest(http.MethodPost, "/token?grant_type=password", &buffer)
375+
req.Header.Set("Content-Type", "application/json")
376+
w = httptest.NewRecorder()
377+
ts.API.handler.ServeHTTP(w, req)
378+
require.Equal(ts.T(), http.StatusBadRequest, w.Code)
379+
}
380+
381+
func (ts *OtpTestSuite) TestOtpClearsUnconfirmedPasswordWithAutoconfirm() {
382+
ts.Config.SMTP.MaxFrequency = 0
383+
ts.Config.Mailer.Autoconfirm = true
384+
defer func() { ts.Config.Mailer.Autoconfirm = false }()
385+
386+
userEmail := "victim@example.com"
387+
388+
// unconfirmed user created before autoconfirm was enabled
389+
u, err := models.NewUser("", userEmail, "attacker-password-123", ts.Config.JWT.Aud, nil)
390+
require.NoError(ts.T(), err)
391+
require.NoError(ts.T(), ts.API.db.Create(u))
392+
require.True(ts.T(), u.HasPassword())
393+
394+
var buffer bytes.Buffer
395+
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
396+
"email": userEmail,
397+
}))
398+
req := httptest.NewRequest(http.MethodPost, "/otp", &buffer)
399+
req.Header.Set("Content-Type", "application/json")
400+
w := httptest.NewRecorder()
401+
ts.API.handler.ServeHTTP(w, req)
402+
require.Equal(ts.T(), http.StatusOK, w.Code)
403+
404+
user, err := models.FindUserByEmailAndAudience(ts.API.db, userEmail, ts.Config.JWT.Aud)
405+
require.NoError(ts.T(), err)
406+
require.True(ts.T(), user.IsConfirmed())
407+
require.False(ts.T(), user.HasPassword())
408+
}
409+
410+
func (ts *OtpTestSuite) TestOtpKeepsConfirmedPassword() {
411+
ts.Config.SMTP.MaxFrequency = 0
412+
413+
userEmail := "confirmed@example.com"
414+
u, err := models.NewUser("", userEmail, "password-123", ts.Config.JWT.Aud, nil)
415+
require.NoError(ts.T(), err)
416+
now := time.Now()
417+
u.EmailConfirmedAt = &now
418+
require.NoError(ts.T(), ts.API.db.Create(u))
419+
420+
var buffer bytes.Buffer
421+
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
422+
"email": userEmail,
423+
}))
424+
req := httptest.NewRequest(http.MethodPost, "/otp", &buffer)
425+
req.Header.Set("Content-Type", "application/json")
426+
w := httptest.NewRecorder()
427+
ts.API.handler.ServeHTTP(w, req)
428+
require.Equal(ts.T(), http.StatusOK, w.Code)
429+
430+
user, err := models.FindUserByEmailAndAudience(ts.API.db, userEmail, ts.Config.JWT.Aud)
431+
require.NoError(ts.T(), err)
432+
require.True(ts.T(), user.HasPassword())
433+
}

‎internal/api/verify.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,13 @@ func (a *API) recoverVerify(r *http.Request, conn *storage.Connection, user *mod
382382
return terr
383383
}
384384

385+
// a password set before the email was confirmed may belong to
386+
// someone who doesn't own the email, so it must not survive
387+
// confirmation
388+
if terr = user.ClearUnconfirmedPassword(tx); terr != nil {
389+
return terr
390+
}
391+
385392
if terr = user.Confirm(tx); terr != nil {
386393
return terr
387394
}

‎internal/api/verify_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ func (ts *VerifyTestSuite) TestVerifyPasswordRecovery() {
136136
u, err = models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
137137
require.NoError(ts.T(), err)
138138
assert.True(ts.T(), u.IsConfirmed())
139+
// the password was set before the email was confirmed, so it
140+
// must not survive confirmation through recovery
141+
assert.False(ts.T(), u.HasPassword())
139142

140143
if c.isPKCE {
141144
rURL, _ := w.Result().Location()

‎internal/models/audit_log_entry.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ import (
2020
type AuditAction string
2121
type auditLogType string
2222

23+
// AuditLogReason is a machine-readable explanation recorded in an audit log
24+
// entry's "reason" trait, giving more context for why an action occurred.
25+
type AuditLogReason string
26+
27+
const (
28+
UnconfirmedPasswordClearedReason AuditLogReason = "unconfirmed_password_cleared"
29+
)
30+
2331
const (
2432
LoginAction AuditAction = "login"
2533
LogoutAction AuditAction = "logout"

‎internal/models/user.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,16 @@ func (u *User) SetPassword(ctx context.Context, password string, encrypt bool, e
431431
return nil
432432
}
433433

434+
// ClearUnconfirmedPassword removes a password that was set before the user's
435+
// email was confirmed, since whoever set it may not own the email address.
436+
func (u *User) ClearUnconfirmedPassword(tx *storage.Connection) error {
437+
if u.IsConfirmed() || !u.HasPassword() {
438+
return nil
439+
}
440+
u.EncryptedPassword = nil
441+
return tx.UpdateOnly(u, "encrypted_password")
442+
}
443+
434444
// UpdatePassword updates the user's password. Use SetPassword outside of a transaction first!
435445
func (u *User) UpdatePassword(tx *storage.Connection, sessionID *uuid.UUID) error {
436446
// These need to be reset because password change may mean the user no longer trusts the actions performed by the previous password.

‎internal/models/user_test.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,26 @@ func (ts *UserTestSuite) createUserWithEmail(email string) *User {
378378
return user
379379
}
380380

381+
func (ts *UserTestSuite) TestClearUnconfirmedPassword() {
382+
unconfirmed := ts.createUserWithEmail("unconfirmed@example.com")
383+
require.True(ts.T(), unconfirmed.HasPassword())
384+
require.NoError(ts.T(), unconfirmed.ClearUnconfirmedPassword(ts.db))
385+
require.False(ts.T(), unconfirmed.HasPassword())
386+
387+
reloaded, err := FindUserByID(ts.db, unconfirmed.ID)
388+
require.NoError(ts.T(), err)
389+
require.False(ts.T(), reloaded.HasPassword())
390+
391+
confirmed := ts.createUserWithEmail("confirmed@example.com")
392+
require.NoError(ts.T(), confirmed.Confirm(ts.db))
393+
require.NoError(ts.T(), confirmed.ClearUnconfirmedPassword(ts.db))
394+
require.True(ts.T(), confirmed.HasPassword())
395+
396+
reloaded, err = FindUserByID(ts.db, confirmed.ID)
397+
require.NoError(ts.T(), err)
398+
require.True(ts.T(), reloaded.HasPassword())
399+
}
400+
381401
func (ts *UserTestSuite) TestRemoveUnconfirmedIdentities() {
382402
user, err := NewUser("+29382983298", "someone@example.com", "abcdefgh", "authenticated", nil)
383403
require.NoError(ts.T(), err)

0 commit comments

Comments
 (0)