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
2 changes: 1 addition & 1 deletion internal/api/mfa.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
55 changes: 55 additions & 0 deletions internal/api/mfa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion internal/api/reauthenticate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
88 changes: 88 additions & 0 deletions internal/api/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down