Skip to content
Draft
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
25 changes: 25 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,31 @@ GOTRUE_SECURITY_REFRESH_TOKEN_REUSE_INTERVAL="0"
GOTRUE_SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION="false"
GOTRUE_OPERATOR_TOKEN="unused-operator-token"

# Password hash compute policy. Limits which password hashing algorithms the server
# will verify and the maximum cost parameters they may use. If a user's stored
# hash is not permitted, sign-in (and password change) fails with the
# `password_reset_required` error code and the user must reset their password.
# Everything is permitted when unset; 0 means "no limit" for numeric options.
#
# Configured as a single JSON object in GOTRUE_PASSWORD_HASH_COMPUTE_POLICY with
# one optional object per algorithm. Once the variable is set it is an
# ALLOWLIST: an algorithm that is not mentioned is rejected (use "bcrypt":{}
# to allow it without limits, and note that "{}" rejects every hash). Each
# object accepts:
# disabled: true rejects every hash using the algorithm
# plus the maximum parameters for the algorithm:
# bcrypt: max_cost (default cost is 10)
# argon2: variants (list of argon2i and/or argon2id; all if omitted),
# max_memory_kib (m), max_time (t), max_threads (p)
# fbscrypt: max_memory_cost_log2 (n as a power of 2), max_rounds (r),
# max_threads (p)
# Unknown keys are ignored (so policies for newer versions still load); this
# also means a misspelled key silently has no effect.
#
# Example: bcrypt up to cost 10, Argon2id only (Argon2i is rejected),
# bounded Firebase scrypt:
# GOTRUE_PASSWORD_HASH_COMPUTE_POLICY='{"bcrypt":{"max_cost":10},"argon2":{"variants":["argon2id"],"max_memory_kib":65536,"max_time":4,"max_threads":4},"fbscrypt":{"max_memory_cost_log2":14,"max_rounds":8,"max_threads":1}}'

# Trusted rate limiting header - this should be set by a trusted upstream proxy
GOTRUE_RATE_LIMIT_HEADER="X-Forwarded-For"
GOTRUE_RATE_LIMIT_EMAIL_SENT="100"
Expand Down
2 changes: 1 addition & 1 deletion internal/api/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ func (ts *AdminTestSuite) TestAdminUserCreate() {

if _, ok := c.expected["password"]; ok {
expectedPassword := fmt.Sprintf("%v", c.expected["password"])
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, expectedPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID)
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, expectedPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID, nil)
require.NoError(ts.T(), err)
require.Equal(ts.T(), c.expected["isAuthenticated"], isAuthenticated)
}
Expand Down
5 changes: 5 additions & 0 deletions internal/api/apierrors/errorcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,9 @@ const (
ErrorCodeWebAuthnChallengeExpired ErrorCode = "webauthn_challenge_expired"
ErrorCodeWebAuthnVerificationFailed ErrorCode = "webauthn_verification_failed"
ErrorCodeWebAuthnCredentialExists ErrorCode = "webauthn_credential_exists" // #nosec G101 -- not a credential

// ErrorCodePasswordResetRequired is returned when the stored password hash
// is not permitted by the server's hash compute policy and the user must
// reset their password.
ErrorCodePasswordResetRequired ErrorCode = "password_reset_required"
)
2 changes: 1 addition & 1 deletion internal/api/otp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ func (ts *OtpTestSuite) TestSubsequentOtp() {
// users, so the invariant is that the attacker's password is gone, not that
// the user has no password at all.
func (ts *OtpTestSuite) requirePasswordRejected(user *models.User, password string) {
ok, _, err := user.Authenticate(context.Background(), ts.API.db, password, ts.Config.Security.DBEncryption.DecryptionKeys, false, "")
ok, _, err := user.Authenticate(context.Background(), ts.API.db, password, ts.Config.Security.DBEncryption.DecryptionKeys, false, "", nil)
require.NoError(ts.T(), err)
require.False(ts.T(), ok)
}
Expand Down
12 changes: 12 additions & 0 deletions internal/api/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@ package api

import (
"context"
"errors"
"fmt"
"strings"
"unicode/utf8"

"github.com/sirupsen/logrus"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/crypto"
)

// passwordHashError converts a crypto.ErrPasswordHashNotPermitted returned
// from User.Authenticate into an HTTP error that tells the client the user
// must reset their password. Other errors are returned unchanged.
func passwordHashError(err error) error {
if errors.Is(err, crypto.ErrPasswordHashNotPermitted) {
return apierrors.NewBadRequestError(apierrors.ErrorCodePasswordResetRequired, "Your password must be reset before you can sign in.").WithInternalError(err)
}
return err
}

// BCrypt hashed passwords have a 72 character limit
const MaxPasswordLength = 72

Expand Down
13 changes: 7 additions & 6 deletions internal/api/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/gofrs/uuid"

"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/crypto"
"github.com/supabase/auth/internal/hooks/v0hooks"
"github.com/supabase/auth/internal/metering"
Expand Down Expand Up @@ -129,9 +130,9 @@ func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWri
// for. The session is only created while the row still has this value.
verifiedHash := storedHash

isValidPassword, shouldReEncrypt, err := user.Authenticate(ctx, db, params.Password, config.Security.DBEncryption.DecryptionKeys, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID)
isValidPassword, shouldReEncrypt, err := user.Authenticate(ctx, db, params.Password, config.Security.DBEncryption.DecryptionKeys, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID, &config.Password.HashComputePolicy)
if err != nil {
return err
return passwordHashError(err)
}

var weakPasswordError *WeakPasswordError
Expand Down Expand Up @@ -166,9 +167,9 @@ func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWri
// a password change or another sign-in re-encrypting it.
// Check the password again so a password change made
// during this sign-in is not bypassed.
isValidPassword, verifiedHash, err = reverifyPassword(ctx, db, user.ID, params.Password, config.Security.DBEncryption.DecryptionKeys)
isValidPassword, verifiedHash, err = reverifyPassword(ctx, db, user.ID, params.Password, config.Security.DBEncryption.DecryptionKeys, &config.Password.HashComputePolicy)
if err != nil {
return err
return passwordHashError(err)
}
if !isValidPassword {
observability.GetLogEntry(r).Entry.Warn("Rejected sign-in because the password changed before re-encryption")
Expand Down Expand Up @@ -262,7 +263,7 @@ func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWri
// reverifyPassword checks password against the user's currently stored hash.
// It returns false if the user no longer exists or the password doesn't match.
// The returned hash is the stored value the check ran against.
func reverifyPassword(ctx context.Context, db *storage.Connection, userID uuid.UUID, password string, decryptionKeys map[string]string) (bool, string, error) {
func reverifyPassword(ctx context.Context, db *storage.Connection, userID uuid.UUID, password string, decryptionKeys map[string]string, hashPolicy *conf.PasswordHashPolicy) (bool, string, error) {
current, err := models.FindUserByID(db, userID)
if err != nil {
if models.IsNotFoundError(err) {
Expand All @@ -278,7 +279,7 @@ func reverifyPassword(ctx context.Context, db *storage.Connection, userID uuid.U
storedHash = *current.EncryptedPassword
}

isValid, _, err := current.Authenticate(ctx, db, password, decryptionKeys, false, "")
isValid, _, err := current.Authenticate(ctx, db, password, decryptionKeys, false, "", hashPolicy)
if err != nil {
return false, "", err
}
Expand Down
30 changes: 27 additions & 3 deletions internal/api/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,30 @@ func (ts *TokenTestSuite) TestTokenPasswordGrantSuccess() {
assert.Equal(ts.T(), http.StatusOK, w.Code)
}

func (ts *TokenTestSuite) TestTokenPasswordGrantHashNotPermitted() {
// the test user's bcrypt hash must be rejected when bcrypt is disabled
original := ts.Config.Password.HashComputePolicy
ts.Config.Password.HashComputePolicy = conf.PasswordHashPolicy{Bcrypt: &conf.BcryptHashPolicy{Disabled: true}}
defer func() { ts.Config.Password.HashComputePolicy = original }()

var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"email": "test@example.com",
"password": "password",
}))

req := httptest.NewRequest(http.MethodPost, "http://localhost/token?grant_type=password", &buffer)
req.Header.Set("Content-Type", "application/json")

w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusBadRequest, w.Code)

var body map[string]interface{}
require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&body))
require.Equal(ts.T(), string(apierrors.ErrorCodePasswordResetRequired), body["error_code"])
}

func (ts *TokenTestSuite) TestTokenRefreshTokenGrantSuccess() {
var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
Expand Down Expand Up @@ -970,7 +994,7 @@ func (ts *TokenTestSuite) TestReverifyPassword() {
require.NoError(ts.T(), u.SetPassword(ctx, "password", true, enc.EncryptionKeyID, enc.EncryptionKey))
require.NoError(ts.T(), db.UpdateOnly(u, "encrypted_password"))

ok, hash, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys)
ok, hash, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys, nil)
require.NoError(ts.T(), err)
require.True(ts.T(), ok)
require.Equal(ts.T(), *u.EncryptedPassword, hash, "should return the stored hash it checked against")
Expand All @@ -982,15 +1006,15 @@ func (ts *TokenTestSuite) TestReverifyPassword() {
require.NoError(ts.T(), u.SetPassword(ctx, "new-password", true, enc.EncryptionKeyID, enc.EncryptionKey))
require.NoError(ts.T(), u.UpdatePassword(db, nil))

ok, _, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys)
ok, _, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys, nil)
require.NoError(ts.T(), err)
require.False(ts.T(), ok)
})

ts.Run("rejects when the user no longer exists", func() {
require.NoError(ts.T(), db.Destroy(ts.User))

ok, hash, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys)
ok, hash, err := reverifyPassword(ctx, db, ts.User.ID, "password", enc.DecryptionKeys, nil)
require.NoError(ts.T(), err)
require.False(ts.T(), ok)
require.Empty(ts.T(), hash)
Expand Down
18 changes: 14 additions & 4 deletions internal/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package api

import (
"context"
"errors"
"net/http"
"time"

"github.com/gofrs/uuid"
"github.com/sirupsen/logrus"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/api/sms_provider"
"github.com/supabase/auth/internal/crypto"
"github.com/supabase/auth/internal/mailer"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
Expand Down Expand Up @@ -176,18 +178,26 @@ func (a *API) UserUpdate(w http.ResponseWriter, r *http.Request) error {
if params.CurrentPassword == nil || *params.CurrentPassword == "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeCurrentPasswordRequired, "Current password required when setting new password.")
}
isCurrentPasswordCorrect, _, err := user.Authenticate(ctx, db, *params.CurrentPassword, config.Security.DBEncryption.DecryptionKeys, false, "")
isCurrentPasswordCorrect, _, err := user.Authenticate(ctx, db, *params.CurrentPassword, config.Security.DBEncryption.DecryptionKeys, false, "", &config.Password.HashComputePolicy)
if err != nil {
return err
return passwordHashError(err)
}
if !isCurrentPasswordCorrect {
return apierrors.NewBadRequestError(apierrors.ErrorCodeCurrentPasswordMismatch, "Current password required when setting new password.")
}
}
}
auth, _, err := user.Authenticate(ctx, db, password, config.Security.DBEncryption.DecryptionKeys, false, "")
auth, _, err := user.Authenticate(ctx, db, password, config.Security.DBEncryption.DecryptionKeys, false, "", &config.Password.HashComputePolicy)
if session.IsRecovery() && errors.Is(err, crypto.ErrPasswordHashNotPermitted) {
// Password reset flow: the old hash can't be checked under
// the hash compute policy, so the new password can't be
// treated as the same one. This must not block the reset
// that replaces the hash. Outside of a recovery session the
// error is returned so the user is told to reset.
auth, err = false, nil
}
if err != nil {
return err
return passwordHashError(err)
}

isSamePassword = auth
Expand Down
8 changes: 4 additions & 4 deletions internal/api/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ func (ts *UserTestSuite) TestUserUpdatePassword() {
u, err = models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
require.NoError(ts.T(), err)

isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID)
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID, nil)
require.NoError(ts.T(), err)

require.Equal(ts.T(), c.expected.isAuthenticated, isAuthenticated)
Expand Down Expand Up @@ -488,7 +488,7 @@ func (ts *UserTestSuite) TestUserUpdatePasswordViaRecovery() {
u, err = models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
require.NoError(ts.T(), err)

isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID)
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID, nil)
require.NoError(ts.T(), err)

require.Equal(ts.T(), c.expected.isAuthenticated, isAuthenticated)
Expand Down Expand Up @@ -551,7 +551,7 @@ func (ts *UserTestSuite) TestUserUpdatePasswordNoReauthenticationRequired() {
u, err = models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
require.NoError(ts.T(), err)

isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID)
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, c.newPassword, ts.API.config.Security.DBEncryption.DecryptionKeys, ts.API.config.Security.DBEncryption.Encrypt, ts.API.config.Security.DBEncryption.EncryptionKeyID, nil)
require.NoError(ts.T(), err)

require.Equal(ts.T(), c.expected.isAuthenticated, isAuthenticated)
Expand Down Expand Up @@ -609,7 +609,7 @@ func (ts *UserTestSuite) TestUserUpdatePasswordReauthentication() {
u, err = models.FindUserByEmailAndAudience(ts.API.db, "test@example.com", ts.Config.JWT.Aud)
require.NoError(ts.T(), err)

isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, "newpass", ts.Config.Security.DBEncryption.DecryptionKeys, ts.Config.Security.DBEncryption.Encrypt, ts.Config.Security.DBEncryption.EncryptionKeyID)
isAuthenticated, _, err := u.Authenticate(context.Background(), ts.API.db, "newpass", ts.Config.Security.DBEncryption.DecryptionKeys, ts.Config.Security.DBEncryption.Encrypt, ts.Config.Security.DBEncryption.EncryptionKeyID, nil)
require.NoError(ts.T(), err)

require.True(ts.T(), isAuthenticated)
Expand Down
5 changes: 5 additions & 0 deletions internal/conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,11 @@ type PasswordConfiguration struct {
RequiredCharacters PasswordRequiredCharacters `json:"required_characters" split_words:"true"`

HIBP HIBPConfiguration `json:"hibp"`

// HashComputePolicy limits which password hashing algorithms (and their
// maximum cost parameters) the server will verify. A user whose stored
// hash violates the policy is told to reset their password.
HashComputePolicy PasswordHashPolicy `json:"hash_compute_policy" envconfig:"HASH_COMPUTE_POLICY"`
}

type AuditLogConfiguration struct {
Expand Down
79 changes: 79 additions & 0 deletions internal/conf/configuration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"testing"
"time"

"github.com/kelseyhightower/envconfig"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -1314,3 +1315,81 @@ func TestApplyDefaultsClampsOtpExp(t *testing.T) {
})
}
}

func TestPasswordHashPolicyEnv(t *testing.T) {
t.Setenv("GOTRUE_PASSWORD_HASH_COMPUTE_POLICY", `{
"bcrypt": { "max_cost": 10 },
"argon2": { "variants": ["argon2id"], "max_memory_kib": 65536, "max_time": 4, "max_threads": 4 },
"fbscrypt": { "max_memory_cost_log2": 14, "max_rounds": 8, "max_threads": 1 }
}`)

var cfg PasswordConfiguration
require.NoError(t, envconfig.Process("gotrue_password", &cfg))

require.Equal(t, PasswordHashPolicy{
Allowlist: true,
Bcrypt: &BcryptHashPolicy{MaxCost: 10},
Argon2: &Argon2HashPolicy{Variants: []string{"argon2id"}, MaxMemoryKiB: 65536, MaxTime: 4, MaxThreads: 4},
FirebaseScrypt: &FirebaseScryptHashPolicy{MaxMemoryCostLog2: 14, MaxRounds: 8, MaxThreads: 1},
}, cfg.HashComputePolicy)
}

func TestPasswordHashPolicyEnvAllowlist(t *testing.T) {
// unset: permissive
var cfg PasswordConfiguration
require.NoError(t, envconfig.Process("gotrue_password", &cfg))
require.False(t, cfg.HashComputePolicy.Allowlist)

// set to an empty object: an (empty) allowlist
t.Setenv("GOTRUE_PASSWORD_HASH_COMPUTE_POLICY", `{}`)
cfg = PasswordConfiguration{}
require.NoError(t, envconfig.Process("gotrue_password", &cfg))
require.True(t, cfg.HashComputePolicy.Allowlist)
require.Nil(t, cfg.HashComputePolicy.Bcrypt)

// mentioning an algorithm with {} allows it without limits
t.Setenv("GOTRUE_PASSWORD_HASH_COMPUTE_POLICY", `{"bcrypt": {}}`)
cfg = PasswordConfiguration{}
require.NoError(t, envconfig.Process("gotrue_password", &cfg))
require.True(t, cfg.HashComputePolicy.Allowlist)
require.Equal(t, &BcryptHashPolicy{}, cfg.HashComputePolicy.Bcrypt)
require.Nil(t, cfg.HashComputePolicy.Argon2)
}

func TestPasswordHashPolicyEnvIgnoresUnknownKeys(t *testing.T) {
t.Setenv("GOTRUE_PASSWORD_HASH_COMPUTE_POLICY", `{
"future_algorithm": { "max_cost": 1 },
"bcrypt": { "max_cost": 10, "future_key": true },
"argon2": { "variants": ["argon2id", "argon2d"], "max_time": 4, "future_key": [1, 2] },
"future_top_level": 1
}`)

var cfg PasswordConfiguration
require.NoError(t, envconfig.Process("gotrue_password", &cfg))

require.True(t, cfg.HashComputePolicy.Allowlist)
require.Equal(t, &BcryptHashPolicy{MaxCost: 10}, cfg.HashComputePolicy.Bcrypt)
require.Equal(t, &Argon2HashPolicy{Variants: []string{"argon2id", "argon2d"}, MaxTime: 4}, cfg.HashComputePolicy.Argon2)
require.Nil(t, cfg.HashComputePolicy.FirebaseScrypt)
}

func TestPasswordHashPolicyEnvInvalid(t *testing.T) {
cases := map[string]string{
"not json": `not json`,
"not an object": `["bcrypt"]`,
"algorithm not obj": `{"bcrypt": true}`,
"wrong type": `{"bcrypt": {"max_cost": "10"}}`,
"disabled not bool": `{"bcrypt": {"disabled": "yes"}}`,
"negative": `{"argon2": {"max_time": -1}}`,
"fractional": `{"argon2": {"max_time": 1.5}}`,
"bcrypt above max": `{"bcrypt": {"max_cost": 32}}`,
}

for name, value := range cases {
t.Run(name, func(t *testing.T) {
t.Setenv("GOTRUE_PASSWORD_HASH_COMPUTE_POLICY", value)
var cfg PasswordConfiguration
require.Error(t, envconfig.Process("gotrue_password", &cfg))
})
}
}
Loading
Loading