From 6773e10e8dbc5c292f751e912bcb0311cfa60ec5 Mon Sep 17 00:00:00 2001 From: rgallegocode Date: Wed, 18 Nov 2026 18:45:16 +0100 Subject: [PATCH] fix: honor SMS hook and test OTPs with Twilio Verify in reauth and MFA --- internal/api/mfa.go | 2 +- internal/api/mfa_test.go | 55 +++++++++++++++++++++ internal/api/reauthenticate.go | 6 ++- internal/api/user_test.go | 88 ++++++++++++++++++++++++++++++++++ 4 files changed, 149 insertions(+), 2 deletions(-) diff --git a/internal/api/mfa.go b/internal/api/mfa.go index 6082009f8d..82f841183c 100644 --- a/internal/api/mfa.go +++ b/internal/api/mfa.go @@ -783,7 +783,7 @@ func (a *API) verifyPhoneFactor(w http.ResponseWriter, r *http.Request, params * var valid bool var otpCode string var shouldReEncrypt bool - if config.Sms.IsTwilioVerifyProvider() { + if !config.Hook.SendSMS.Enabled && config.Sms.IsTwilioVerifyProvider() { smsProvider, err := sms_provider.GetSmsProvider(*config) if err != nil { return apierrors.NewInternalServerError("Failed to get SMS provider").WithInternalError(err) diff --git a/internal/api/mfa_test.go b/internal/api/mfa_test.go index 1113b788c6..a1cef5fce4 100644 --- a/internal/api/mfa_test.go +++ b/internal/api/mfa_test.go @@ -25,6 +25,7 @@ import ( "github.com/pquerna/otp/totp" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "gopkg.in/h2non/gock.v1" ) type MFATestSuite struct { @@ -654,6 +655,60 @@ func (ts *MFATestSuite) TestMFAVerifyFactor() { } } +func (ts *MFATestSuite) TestMFAVerifyPhoneFactorSendSMSHookTwilioVerify() { + previousProvider := ts.Config.Sms.Provider + previousTwilioVerify := ts.Config.Sms.TwilioVerify + previousMock := sms_provider.MockProvider + defer func() { + ts.Config.Sms.Provider = previousProvider + ts.Config.Sms.TwilioVerify = previousTwilioVerify + sms_provider.MockProvider = previousMock + ts.Config.Hook.SendSMS.Enabled = false + gock.OffAll() + }() + + ts.Config.Hook.SendSMS.Enabled = true + ts.Config.Sms.Provider = "twilio_verify" + ts.Config.Sms.TwilioVerify = conf.TwilioVerifyProviderConfiguration{ + AccountSid: "AC-test", + AuthToken: "test-token", + MessageServiceSid: "VA-test", + } + sms_provider.MockProvider = nil + + // The challenge was sent through the Send SMS hook, so Twilio Verify must not be asked to check it. + gock.New("https://verify.twilio.com/v2/Services/VA-test/VerificationCheck"). + Post(""). + Reply(http.StatusOK). + JSON(map[string]interface{}{"status": "pending", "valid": false}) + + r, err := models.GrantAuthenticatedUser(ts.API.db, ts.TestUser, models.GrantParams{}) + require.NoError(ts.T(), err) + token := ts.generateAAL1Token(ts.TestUser, r.SessionId) + + f := models.NewPhoneFactor(ts.TestUser, "+15555550101", "phone-factor") + require.NoError(ts.T(), ts.API.db.Create(f), "Error creating new SMS factor") + + var buffer bytes.Buffer + req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/factors/%s/verify", f.ID), &buffer) + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + + code := "123456" + c, err := f.CreatePhoneChallenge(utilities.GetIPAddress(req), code, ts.Config.Security.DBEncryption.Encrypt, ts.Config.Security.DBEncryption.EncryptionKeyID, ts.Config.Security.DBEncryption.EncryptionKey) + require.NoError(ts.T(), err) + require.NoError(ts.T(), ts.API.db.Create(c), "Error saving new test challenge") + + require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{ + "challenge_id": c.ID, + "code": code, + })) + + w := httptest.NewRecorder() + ts.API.handler.ServeHTTP(w, req) + require.Equal(ts.T(), http.StatusOK, w.Code, w.Body.String()) + require.True(ts.T(), gock.IsPending(), "Twilio Verify should not have been called") +} + func (ts *MFATestSuite) TestUnenrollVerifiedFactor() { cases := []struct { desc string diff --git a/internal/api/reauthenticate.go b/internal/api/reauthenticate.go index 687b559cdc..c6dda7a6f0 100644 --- a/internal/api/reauthenticate.go +++ b/internal/api/reauthenticate.go @@ -2,6 +2,7 @@ package api import ( "net/http" + "time" "github.com/supabase/auth/internal/api/apierrors" "github.com/supabase/auth/internal/api/sms_provider" @@ -76,7 +77,10 @@ func (a *API) verifyReauthentication(nonce string, tx *storage.Connection, confi tokenHash := crypto.GenerateTokenHash(user.GetEmail(), nonce) isValid = isOtpValid(tokenHash, user.ReauthenticationToken, user.ReauthenticationSentAt, config.Mailer.OtpExp) } else if user.GetPhone() != "" { - if config.Sms.IsTwilioVerifyProvider() { + // sendPhoneConfirmation stores the OTP locally when it goes through the + // Send SMS hook or is a test OTP, so Twilio Verify never saw it. + _, isTestOTP := config.Sms.GetTestOTP(user.GetPhone(), time.Now()) + if !config.Hook.SendSMS.Enabled && !isTestOTP && config.Sms.IsTwilioVerifyProvider() { smsProvider, _ := sms_provider.GetSmsProvider(*config) if err := smsProvider.(*sms_provider.TwilioVerifyProvider).VerifyOTP(string(user.Phone), nonce); err != nil { return apierrors.NewForbiddenError(apierrors.ErrorCodeOTPExpired, "Token has expired or is invalid").WithInternalError(err) diff --git a/internal/api/user_test.go b/internal/api/user_test.go index 352b7fcc1d..47ceefe539 100644 --- a/internal/api/user_test.go +++ b/internal/api/user_test.go @@ -13,11 +13,13 @@ import ( "github.com/gofrs/uuid" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/supabase/auth/internal/api/sms_provider" "github.com/supabase/auth/internal/conf" "github.com/supabase/auth/internal/crypto" "github.com/supabase/auth/internal/mailer" "github.com/supabase/auth/internal/mailer/mockclient" "github.com/supabase/auth/internal/models" + "gopkg.in/h2non/gock.v1" ) type UserTestSuite struct { @@ -617,6 +619,92 @@ func (ts *UserTestSuite) TestUserUpdatePasswordReauthentication() { require.Nil(ts.T(), u.ReauthenticationSentAt) } +func (ts *UserTestSuite) TestUserUpdatePasswordReauthenticationPhoneTwilioVerify() { + ts.Config.Security.UpdatePasswordRequireReauthentication = true + ts.Config.Security.UpdatePasswordRequireCurrentPassword = false + + previousProvider := ts.Config.Sms.Provider + previousTwilioVerify := ts.Config.Sms.TwilioVerify + previousMock := sms_provider.MockProvider + defer func() { + ts.Config.Sms.Provider = previousProvider + ts.Config.Sms.TwilioVerify = previousTwilioVerify + sms_provider.MockProvider = previousMock + ts.Config.Hook.SendSMS.Enabled = false + ts.Config.Sms.TestOTP = nil + }() + + ts.Config.Sms.Provider = "twilio_verify" + ts.Config.Sms.TwilioVerify = conf.TwilioVerifyProviderConfiguration{ + AccountSid: "AC-test", + AuthToken: "test-token", + MessageServiceSid: "VA-test", + } + sms_provider.MockProvider = nil + + phone := "15555550100" + cases := []struct { + desc string + hookEnabled bool + testOTP map[string]string + }{ + { + desc: "OTP sent through the Send SMS hook", + hookEnabled: true, + }, + { + desc: "Test OTP", + testOTP: map[string]string{phone: "123456"}, + }, + } + + for _, c := range cases { + ts.Run(c.desc, func() { + defer gock.OffAll() + ts.Config.Hook.SendSMS.Enabled = c.hookEnabled + ts.Config.Sms.TestOTP = c.testOTP + + // Twilio Verify never issued this OTP, so it must not be asked to check it. + gock.New("https://verify.twilio.com/v2/Services/VA-test/VerificationCheck"). + Post(""). + Reply(http.StatusOK). + JSON(map[string]interface{}{"status": "pending", "valid": false}) + + u, err := models.NewUser(phone, "", "password", ts.Config.JWT.Aud, nil) + require.NoError(ts.T(), err) + now := time.Now() + u.PhoneConfirmedAt = &now + u.ReauthenticationToken = crypto.GenerateTokenHash(phone, "123456") + u.ReauthenticationSentAt = &now + require.NoError(ts.T(), ts.API.db.Create(u)) + defer func() { require.NoError(ts.T(), ts.API.db.Destroy(u)) }() + + r, err := models.GrantAuthenticatedUser(ts.API.db, u, models.GrantParams{}) + require.NoError(ts.T(), err) + require.NoError(ts.T(), ts.API.db.RawQuery( + "update "+models.Session{}.TableName()+" set created_at = ? where id = ?", + time.Now().Add(-24*time.Hour), + *r.SessionId).Exec(), + ) + + var buffer bytes.Buffer + require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{ + "password": "newpassword123", + "nonce": "123456", + })) + + req := httptest.NewRequest(http.MethodPut, "http://localhost/user", &buffer) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ts.generateToken(u, r.SessionId))) + + w := httptest.NewRecorder() + ts.API.handler.ServeHTTP(w, req) + require.Equal(ts.T(), http.StatusOK, w.Code, w.Body.String()) + require.True(ts.T(), gock.IsPending(), "Twilio Verify should not have been called") + }) + } +} + func (ts *UserTestSuite) TestUserUpdatePasswordLogoutOtherSessions() { ts.Config.Security.UpdatePasswordRequireReauthentication = false ts.Config.Security.UpdatePasswordRequireCurrentPassword = false