From 2a8e2e9e0cb7fa011ad8dea22bfc6c0cf3510652 Mon Sep 17 00:00:00 2001 From: Stojan Dimitrovski Date: Fri, 20 Nov 2026 17:00:39 +0100 Subject: [PATCH 1/2] feat(auth): add password hash compute policy Add GOTRUE_PASSWORD_HASH_COMPUTE_POLICY, a JSON object validated against a JSON schema, that limits which password hashing algorithms the server will verify and the maximum cost parameters they may use (bcrypt cost, Argon2 memory/time/threads and variants, Firebase scrypt n/r/p). Once set it is an allowlist: an algorithm that is not mentioned is rejected. Unknown keys are ignored so policies written for newer versions still load. A stored hash outside the policy is rejected before any hashing is done and the request fails with the new password_reset_required error code (HTTP 400). Password sign-in and the password checks in PUT /user apply the policy. In a recovery session the same-password check skips a blocked hash so the reset can replace it. Also log a warning, with the user ID and hash parameters (never salts, hashes or keys), whenever a password is compared against a non-default hash. Co-Authored-By: Claude Sonnet 5.5 --- example.env | 25 ++++ internal/api/admin_test.go | 2 +- internal/api/apierrors/errorcode.go | 5 + internal/api/otp_test.go | 2 +- internal/api/password.go | 12 ++ internal/api/token.go | 13 ++- internal/api/token_test.go | 30 ++++- internal/api/user.go | 18 ++- internal/api/user_test.go | 8 +- internal/conf/configuration.go | 5 + internal/conf/configuration_test.go | 79 +++++++++++++ internal/conf/password_hash.go | 146 ++++++++++++++++++++++++ internal/crypto/password_params.go | 60 ++++++++++ internal/crypto/password_params_test.go | 38 ++++++ internal/crypto/password_policy.go | 115 +++++++++++++++++++ internal/crypto/password_policy_test.go | 71 ++++++++++++ internal/models/user.go | 16 ++- internal/models/user_test.go | 6 +- 18 files changed, 628 insertions(+), 23 deletions(-) create mode 100644 internal/conf/password_hash.go create mode 100644 internal/crypto/password_params.go create mode 100644 internal/crypto/password_params_test.go create mode 100644 internal/crypto/password_policy.go create mode 100644 internal/crypto/password_policy_test.go diff --git a/example.env b/example.env index 4406d616d9..f37700d0c4 100644 --- a/example.env +++ b/example.env @@ -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" diff --git a/internal/api/admin_test.go b/internal/api/admin_test.go index e29abc8bc5..936bb96896 100644 --- a/internal/api/admin_test.go +++ b/internal/api/admin_test.go @@ -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) } diff --git a/internal/api/apierrors/errorcode.go b/internal/api/apierrors/errorcode.go index 7c41718d01..66ecc05317 100644 --- a/internal/api/apierrors/errorcode.go +++ b/internal/api/apierrors/errorcode.go @@ -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" ) diff --git a/internal/api/otp_test.go b/internal/api/otp_test.go index adf5030749..841d862b70 100644 --- a/internal/api/otp_test.go +++ b/internal/api/otp_test.go @@ -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) } diff --git a/internal/api/password.go b/internal/api/password.go index 8939915932..0db5e67f13 100644 --- a/internal/api/password.go +++ b/internal/api/password.go @@ -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 diff --git a/internal/api/token.go b/internal/api/token.go index 2ce8ddc4c1..be9e020499 100644 --- a/internal/api/token.go +++ b/internal/api/token.go @@ -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" @@ -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 @@ -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") @@ -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) { @@ -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 } diff --git a/internal/api/token_test.go b/internal/api/token_test.go index aac47fdbfe..0f6c290497 100644 --- a/internal/api/token_test.go +++ b/internal/api/token_test.go @@ -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{}{ @@ -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") @@ -982,7 +1006,7 @@ 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) }) @@ -990,7 +1014,7 @@ func (ts *TokenTestSuite) TestReverifyPassword() { 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) diff --git a/internal/api/user.go b/internal/api/user.go index f96b174ef7..7e26d967ae 100644 --- a/internal/api/user.go +++ b/internal/api/user.go @@ -2,6 +2,7 @@ package api import ( "context" + "errors" "net/http" "time" @@ -9,6 +10,7 @@ import ( "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" @@ -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 diff --git a/internal/api/user_test.go b/internal/api/user_test.go index 352b7fcc1d..314a8c65e8 100644 --- a/internal/api/user_test.go +++ b/internal/api/user_test.go @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/internal/conf/configuration.go b/internal/conf/configuration.go index a61329e2e5..70c01b6a4e 100644 --- a/internal/conf/configuration.go +++ b/internal/conf/configuration.go @@ -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 { diff --git a/internal/conf/configuration_test.go b/internal/conf/configuration_test.go index 9b79e5cad0..767460b465 100644 --- a/internal/conf/configuration_test.go +++ b/internal/conf/configuration_test.go @@ -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" @@ -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)) + }) + } +} diff --git a/internal/conf/password_hash.go b/internal/conf/password_hash.go new file mode 100644 index 0000000000..49670c3331 --- /dev/null +++ b/internal/conf/password_hash.go @@ -0,0 +1,146 @@ +package conf + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/xeipuuv/gojsonschema" +) + +// PasswordHashPolicy limits which password hashing algorithms may be verified +// by the server and the maximum cost parameters they may use. It protects the +// server from spending excessive CPU or memory on verifying imported hashes. +// +// The zero value (variable not set) permits every supported algorithm and +// applies no limits beyond the hard limits built into the hash parsers. +// +// When the policy is loaded from the environment (see Decode) it becomes an +// allowlist: only algorithms that appear in it are permitted, and an algorithm +// that is not mentioned is rejected. Use an empty object, e.g. "bcrypt": {}, +// to permit an algorithm without limits. +type PasswordHashPolicy struct { + // Allowlist rejects algorithms whose entry below is nil. It is set by + // Decode whenever a policy value is provided. + Allowlist bool `json:"-"` + + Bcrypt *BcryptHashPolicy `json:"bcrypt"` + Argon2 *Argon2HashPolicy `json:"argon2"` + FirebaseScrypt *FirebaseScryptHashPolicy `json:"fbscrypt"` +} + +// BcryptHashPolicy limits bcrypt hashes. +type BcryptHashPolicy struct { + // Disabled rejects every bcrypt hash. + Disabled bool `json:"disabled"` + // MaxCost is the maximum bcrypt cost. 0 means no limit. + MaxCost int `json:"max_cost"` +} + +// Argon2 variant names, as used in Argon2HashPolicy.Variants. +const ( + Argon2VariantI = "argon2i" + Argon2VariantID = "argon2id" +) + +// Argon2HashPolicy limits Argon2 hashes. +type Argon2HashPolicy struct { + // Disabled rejects every Argon2 hash. + Disabled bool `json:"disabled"` + // Variants lists the permitted variants: argon2i and/or argon2id. When + // omitted, all variants are permitted. + Variants []string `json:"variants"` + // MaxMemoryKiB is the maximum memory (m) in KiB. 0 means no limit. + MaxMemoryKiB uint64 `json:"max_memory_kib"` + // MaxTime is the maximum number of passes (t). 0 means no limit. + MaxTime uint64 `json:"max_time"` + // MaxThreads is the maximum parallelism (p). 0 means no limit. + MaxThreads uint64 `json:"max_threads"` +} + +// FirebaseScryptHashPolicy limits Firebase scrypt hashes. +type FirebaseScryptHashPolicy struct { + // Disabled rejects every Firebase scrypt hash. + Disabled bool `json:"disabled"` + // MaxMemoryCostLog2 is the maximum mem_cost (the "n" parameter, as a + // power of 2). 0 means no limit. + MaxMemoryCostLog2 uint64 `json:"max_memory_cost_log2"` + // MaxRounds is the maximum number of rounds (r). 0 means no limit. + MaxRounds uint64 `json:"max_rounds"` + // MaxThreads is the maximum parallelism (p). 0 means no limit. + MaxThreads uint64 `json:"max_threads"` +} + +// passwordHashPolicySchema is the JSON schema every +// GOTRUE_PASSWORD_HASH_COMPUTE_POLICY value must satisfy before it is decoded. +const passwordHashPolicySchema = `{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "bcrypt": { + "type": "object", + "properties": { + "disabled": { "type": "boolean" }, + "max_cost": { "type": "integer", "minimum": 0, "maximum": 31 } + } + }, + "argon2": { + "type": "object", + "properties": { + "disabled": { "type": "boolean" }, + "variants": { + "type": "array", + "uniqueItems": true, + "minItems": 1, + "items": { "type": "string" } + }, + "max_memory_kib": { "type": "integer", "minimum": 0 }, + "max_time": { "type": "integer", "minimum": 0 }, + "max_threads": { "type": "integer", "minimum": 0, "maximum": 255 } + } + }, + "fbscrypt": { + "type": "object", + "properties": { + "disabled": { "type": "boolean" }, + "max_memory_cost_log2": { "type": "integer", "minimum": 0, "maximum": 63 }, + "max_rounds": { "type": "integer", "minimum": 0 }, + "max_threads": { "type": "integer", "minimum": 0, "maximum": 255 } + } + } + } +}` + +var passwordHashPolicySchemaLoader = gojsonschema.NewStringLoader(passwordHashPolicySchema) + +// Decode implements envconfig.Decoder so the whole policy can be provided as a +// single JSON object in one environment variable, e.g. +// GOTRUE_PASSWORD_HASH_COMPUTE_POLICY='{"bcrypt":{"max_cost":10},"argon2":{"variants":["argon2id"]}}'. +// The value is validated against a JSON schema first; wrong types and +// out-of-range values are rejected. Unknown keys are deliberately accepted and +// ignored so that policies written for newer versions still load. +func (p *PasswordHashPolicy) Decode(value string) error { + if strings.TrimSpace(value) == "" { + return nil + } + + result, err := gojsonschema.Validate(passwordHashPolicySchemaLoader, gojsonschema.NewStringLoader(value)) + if err != nil { + return fmt.Errorf("conf: invalid password hash compute policy JSON: %w", err) + } + if !result.Valid() { + msgs := make([]string, 0, len(result.Errors())) + for _, e := range result.Errors() { + msgs = append(msgs, e.String()) + } + return fmt.Errorf("conf: password hash compute policy does not match schema: %s", strings.Join(msgs, "; ")) + } + + var parsed PasswordHashPolicy + if err := json.Unmarshal([]byte(value), &parsed); err != nil { + return fmt.Errorf("conf: invalid password hash compute policy JSON: %w", err) + } + parsed.Allowlist = true + *p = parsed + return nil +} diff --git a/internal/crypto/password_params.go b/internal/crypto/password_params.go new file mode 100644 index 0000000000..065acb62d9 --- /dev/null +++ b/internal/crypto/password_params.go @@ -0,0 +1,60 @@ +package crypto + +import ( + "strings" + + "golang.org/x/crypto/bcrypt" +) + +// NonDefaultHashParameters reports whether the hash was produced with +// anything other than the server's default for newly generated hashes (bcrypt +// at bcrypt.DefaultCost). If it was, it returns the algorithm and its cost +// parameters, suitable for logging. Salts, hashes, keys and other secret +// material are never included. +// +// Hashes that cannot be parsed are reported as not-default with only the +// algorithm family, so that they still show up in logs. +func NonDefaultHashParameters(hash string) (map[string]any, bool) { + switch { + case strings.HasPrefix(hash, Argon2Prefix): + input, err := ParseArgon2Hash(hash) + if err != nil { + return map[string]any{"alg": "argon2", "parse_error": true}, true + } + return map[string]any{ + "alg": input.alg, + "version": input.v, + "m": input.memory, + "t": input.time, + "p": input.threads, + "hash_len": len(input.rawHash), + }, true + + case strings.HasPrefix(hash, FirebaseScryptPrefix): + input, err := ParseFirebaseScryptHash(hash) + if err != nil { + return map[string]any{"alg": "fbscrypt", "parse_error": true}, true + } + var memoryCost uint64 + for m := input.memory; m > 1; m >>= 1 { + memoryCost++ + } + return map[string]any{ + "alg": "fbscrypt", + "version": input.v, + "n_log2": memoryCost, + "r": input.rounds, + "p": input.threads, + "hash_len": len(input.rawHash), + }, true + } + + cost, err := bcrypt.Cost([]byte(hash)) + if err != nil { + return map[string]any{"alg": "unknown", "parse_error": true}, true + } + if cost == bcrypt.DefaultCost { + return nil, false + } + return map[string]any{"alg": "bcrypt", "cost": cost}, true +} diff --git a/internal/crypto/password_params_test.go b/internal/crypto/password_params_test.go new file mode 100644 index 0000000000..cbcbef484f --- /dev/null +++ b/internal/crypto/password_params_test.go @@ -0,0 +1,38 @@ +package crypto + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNonDefaultHashParameters(t *testing.T) { + params, ok := NonDefaultHashParameters("$2y$10$va66S4MxFrH6G6L7BzYl0.QgcYgvSr/F92gc.3botlz7bG4p/g/1i") + require.False(t, ok) + require.Nil(t, params) + + params, ok = NonDefaultHashParameters("$2y$11$4lH57PU7bGATpRcx93vIoObH3qDmft/pytbOzDG9/1WsyNmN5u4di") + require.True(t, ok) + require.Equal(t, map[string]any{"alg": "bcrypt", "cost": 11}, params) + + params, ok = NonDefaultHashParameters("$argon2id$v=19$m=32,t=3,p=2$SFVpOWJ0eXhjRzVkdGN1RQ$RXnb8rh7LaDcn07xsssqqulZYXOM/EUCEFMVcAcyYVk") + require.True(t, ok) + require.Equal(t, "argon2id", params["alg"]) + require.EqualValues(t, 32, params["m"]) + require.EqualValues(t, 3, params["t"]) + require.EqualValues(t, 2, params["p"]) + require.NotContains(t, params, "salt") + + params, ok = NonDefaultHashParameters("$fbscrypt$v=1,n=14,r=8,p=1,ss=Bw==,sk=ou9tdYTGyYm8kuR6Dt0Bp0kDuAYoXrK16mbZO4yGwAn3oLspjnN0/c41v8xZnO1n14J3MjKj1b2g6AUCAlFwMw==$C0sHCg9ek77hsg==$zKVTMvnWVw5BBOZNUdnsalx4c4c7y/w7IS5p6Ut2+CfEFFlz37J9huyQfov4iizN8dbjvEJlM5tQaJP84+hfTw==") + require.True(t, ok) + require.Equal(t, "fbscrypt", params["alg"]) + require.EqualValues(t, 14, params["n_log2"]) + require.EqualValues(t, 8, params["r"]) + require.EqualValues(t, 1, params["p"]) + require.NotContains(t, params, "sk") + require.NotContains(t, params, "ss") + + params, ok = NonDefaultHashParameters("garbage") + require.True(t, ok) + require.Equal(t, true, params["parse_error"]) +} diff --git a/internal/crypto/password_policy.go b/internal/crypto/password_policy.go new file mode 100644 index 0000000000..028340b02b --- /dev/null +++ b/internal/crypto/password_policy.go @@ -0,0 +1,115 @@ +package crypto + +import ( + "errors" + "fmt" + "slices" + "strings" + + "github.com/supabase/auth/internal/conf" + "golang.org/x/crypto/bcrypt" +) + +// ErrPasswordHashNotPermitted is returned when a stored password hash uses an +// algorithm, or algorithm parameters, that the server configuration does not +// permit. The user must reset their password to continue. +var ErrPasswordHashNotPermitted = errors.New("crypto: password hash is not permitted by server configuration") + +func exceeds(limit, value uint64) bool { + return limit > 0 && value > limit +} + +// CheckPasswordHashPolicy returns ErrPasswordHashNotPermitted (wrapped with the reason) if the +// hash violates the policy. It only parses the hash and never performs the +// expensive hashing, so it is safe to call before CompareHashAndPassword. +// Hashes that cannot be parsed are not rejected here; verifying them fails on +// its own. A nil policy permits everything. +func CheckPasswordHashPolicy(hash string, p *conf.PasswordHashPolicy) error { + if p == nil { + return nil + } + + notPermitted := func(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrPasswordHashNotPermitted, fmt.Sprintf(format, args...)) + } + + switch { + case strings.HasPrefix(hash, Argon2Prefix): + input, err := ParseArgon2Hash(hash) + if err != nil { + return nil + } + limits := p.Argon2 + if limits == nil { + if p.Allowlist { + return notPermitted("algorithm argon2 is not allowed") + } + return nil + } + if limits.Disabled { + return notPermitted("algorithm argon2 is disabled") + } + if len(limits.Variants) > 0 && !slices.Contains(limits.Variants, input.alg) { + return notPermitted("argon2 variant %s is not allowed", input.alg) + } + if exceeds(limits.MaxMemoryKiB, input.memory) { + return notPermitted("%s m=%d exceeds %d", input.alg, input.memory, limits.MaxMemoryKiB) + } + if exceeds(limits.MaxTime, input.time) { + return notPermitted("%s t=%d exceeds %d", input.alg, input.time, limits.MaxTime) + } + if exceeds(limits.MaxThreads, input.threads) { + return notPermitted("%s p=%d exceeds %d", input.alg, input.threads, limits.MaxThreads) + } + + case strings.HasPrefix(hash, FirebaseScryptPrefix): + input, err := ParseFirebaseScryptHash(hash) + if err != nil { + return nil + } + limits := p.FirebaseScrypt + if limits == nil { + if p.Allowlist { + return notPermitted("algorithm fbscrypt is not allowed") + } + return nil + } + if limits.Disabled { + return notPermitted("algorithm fbscrypt is disabled") + } + // memory is stored as 1< 1; m >>= 1 { + memoryCost++ + } + if exceeds(limits.MaxMemoryCostLog2, memoryCost) { + return notPermitted("fbscrypt n=%d exceeds %d", memoryCost, limits.MaxMemoryCostLog2) + } + if exceeds(limits.MaxRounds, input.rounds) { + return notPermitted("fbscrypt r=%d exceeds %d", input.rounds, limits.MaxRounds) + } + if exceeds(limits.MaxThreads, input.threads) { + return notPermitted("fbscrypt p=%d exceeds %d", input.threads, limits.MaxThreads) + } + + default: + cost, err := bcrypt.Cost([]byte(hash)) + if err != nil { + return nil + } + if p.Bcrypt == nil { + if p.Allowlist { + return notPermitted("algorithm bcrypt is not allowed") + } + return nil + } + if p.Bcrypt.Disabled { + return notPermitted("algorithm bcrypt is disabled") + } + if p.Bcrypt.MaxCost > 0 && cost > p.Bcrypt.MaxCost { + return notPermitted("bcrypt cost=%d exceeds %d", cost, p.Bcrypt.MaxCost) + } + } + + return nil +} diff --git a/internal/crypto/password_policy_test.go b/internal/crypto/password_policy_test.go new file mode 100644 index 0000000000..574d8e192f --- /dev/null +++ b/internal/crypto/password_policy_test.go @@ -0,0 +1,71 @@ +package crypto + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/supabase/auth/internal/conf" +) + +func TestCheckPasswordHashPolicy(t *testing.T) { + const ( + bcrypt10 = "$2y$10$va66S4MxFrH6G6L7BzYl0.QgcYgvSr/F92gc.3botlz7bG4p/g/1i" + argon2i = "$argon2i$v=19$m=16,t=2,p=1$bGJRWThNOHJJTVBSdHl2dQ$NfEnUOuUpb7F2fQkgFUG4g" + argon2id = "$argon2id$v=19$m=32,t=3,p=2$SFVpOWJ0eXhjRzVkdGN1RQ$RXnb8rh7LaDcn07xsssqqulZYXOM/EUCEFMVcAcyYVk" + fbscrypt = "$fbscrypt$v=1,n=14,r=8,p=1,ss=Bw==,sk=ou9tdYTGyYm8kuR6Dt0Bp0kDuAYoXrK16mbZO4yGwAn3oLspjnN0/c41v8xZnO1n14J3MjKj1b2g6AUCAlFwMw==$C0sHCg9ek77hsg==$zKVTMvnWVw5BBOZNUdnsalx4c4c7y/w7IS5p6Ut2+CfEFFlz37J9huyQfov4iizN8dbjvEJlM5tQaJP84+hfTw==" + ) + + tests := []struct { + name string + hash string + policy *conf.PasswordHashPolicy + allowed bool + }{ + {"nil policy", bcrypt10, nil, true}, + {"zero policy", argon2id, &conf.PasswordHashPolicy{}, true}, + {"garbage hash is not rejected here", "garbage", &conf.PasswordHashPolicy{Bcrypt: &conf.BcryptHashPolicy{Disabled: true}}, true}, + + {"allowlist: bcrypt not mentioned", bcrypt10, &conf.PasswordHashPolicy{Allowlist: true, Argon2: &conf.Argon2HashPolicy{}}, false}, + {"allowlist: argon2 not mentioned", argon2id, &conf.PasswordHashPolicy{Allowlist: true, Bcrypt: &conf.BcryptHashPolicy{}}, false}, + {"allowlist: argon2 mentioned allows all variants", argon2i, &conf.PasswordHashPolicy{Allowlist: true, Argon2: &conf.Argon2HashPolicy{}}, true}, + {"allowlist: fbscrypt not mentioned", fbscrypt, &conf.PasswordHashPolicy{Allowlist: true, Bcrypt: &conf.BcryptHashPolicy{}}, false}, + {"allowlist: fbscrypt mentioned", fbscrypt, &conf.PasswordHashPolicy{Allowlist: true, FirebaseScrypt: &conf.FirebaseScryptHashPolicy{}}, true}, + {"allowlist: empty allows nothing", bcrypt10, &conf.PasswordHashPolicy{Allowlist: true}, false}, + {"allowlist: mentioned but disabled", bcrypt10, &conf.PasswordHashPolicy{Allowlist: true, Bcrypt: &conf.BcryptHashPolicy{Disabled: true}}, false}, + {"allowlist: mentioned but over limit", bcrypt10, &conf.PasswordHashPolicy{Allowlist: true, Bcrypt: &conf.BcryptHashPolicy{MaxCost: 9}}, false}, + {"no allowlist: unmentioned allowed", bcrypt10, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{}}, true}, + + {"bcrypt disabled", bcrypt10, &conf.PasswordHashPolicy{Bcrypt: &conf.BcryptHashPolicy{Disabled: true}}, false}, + {"bcrypt unaffected by others disabled", bcrypt10, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Disabled: true}}, true}, + {"bcrypt at max cost", bcrypt10, &conf.PasswordHashPolicy{Bcrypt: &conf.BcryptHashPolicy{MaxCost: 10}}, true}, + {"bcrypt above max cost", bcrypt10, &conf.PasswordHashPolicy{Bcrypt: &conf.BcryptHashPolicy{MaxCost: 9}}, false}, + + {"argon2 disabled (argon2i)", argon2i, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Disabled: true}}, false}, + {"argon2 disabled (argon2id)", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Disabled: true}}, false}, + {"argon2 variants: argon2id only rejects argon2i", argon2i, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Variants: []string{"argon2id"}}}, false}, + {"argon2 variants: argon2id only allows argon2id", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Variants: []string{"argon2id"}}}, true}, + {"argon2 variants: both", argon2i, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{Variants: []string{"argon2i", "argon2id"}}}, true}, + {"argon2 variants omitted allows all", argon2i, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxMemoryKiB: 16}}, true}, + {"argon2 within limits", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxMemoryKiB: 32, MaxTime: 3, MaxThreads: 2}}, true}, + {"argon2 memory too high", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxMemoryKiB: 31}}, false}, + {"argon2 time too high", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxTime: 2}}, false}, + {"argon2 threads too high", argon2id, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxThreads: 1}}, false}, + {"argon2 limits apply to argon2i too", argon2i, &conf.PasswordHashPolicy{Argon2: &conf.Argon2HashPolicy{MaxMemoryKiB: 8}}, false}, + + {"fbscrypt disabled", fbscrypt, &conf.PasswordHashPolicy{FirebaseScrypt: &conf.FirebaseScryptHashPolicy{Disabled: true}}, false}, + {"fbscrypt within limits", fbscrypt, &conf.PasswordHashPolicy{FirebaseScrypt: &conf.FirebaseScryptHashPolicy{MaxMemoryCostLog2: 14, MaxRounds: 8, MaxThreads: 1}}, true}, + {"fbscrypt memory too high", fbscrypt, &conf.PasswordHashPolicy{FirebaseScrypt: &conf.FirebaseScryptHashPolicy{MaxMemoryCostLog2: 13}}, false}, + {"fbscrypt rounds too high", fbscrypt, &conf.PasswordHashPolicy{FirebaseScrypt: &conf.FirebaseScryptHashPolicy{MaxRounds: 7}}, false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := CheckPasswordHashPolicy(tc.hash, tc.policy) + if tc.allowed { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, ErrPasswordHashNotPermitted) + } + }) + } +} diff --git a/internal/models/user.go b/internal/models/user.go index 661c206670..e5969045ed 100644 --- a/internal/models/user.go +++ b/internal/models/user.go @@ -15,8 +15,10 @@ import ( "github.com/gobuffalo/pop/v6" "github.com/gofrs/uuid" "github.com/pkg/errors" + "github.com/sirupsen/logrus" "github.com/supabase/auth/internal/conf" "github.com/supabase/auth/internal/crypto" + "github.com/supabase/auth/internal/observability" "github.com/supabase/auth/internal/storage" "golang.org/x/crypto/bcrypt" ) @@ -526,7 +528,7 @@ func (u *User) UpdatePassword(tx *storage.Connection, sessionID *uuid.UUID) erro } // Authenticate a user from a password -func (u *User) Authenticate(ctx context.Context, tx *storage.Connection, password string, decryptionKeys map[string]string, encrypt bool, encryptionKeyID string) (bool, bool, error) { +func (u *User) Authenticate(ctx context.Context, tx *storage.Connection, password string, decryptionKeys map[string]string, encrypt bool, encryptionKeyID string, hashPolicy *conf.PasswordHashPolicy) (bool, bool, error) { if u.EncryptedPassword == nil { return false, false, nil } @@ -547,6 +549,18 @@ func (u *User) Authenticate(ctx context.Context, tx *storage.Connection, passwor hash = string(h) } + // reject disallowed hashes before doing any expensive hashing work + if err := crypto.CheckPasswordHashPolicy(hash, hashPolicy); err != nil { + return false, false, err + } + + if params, nonDefault := crypto.NonDefaultHashParameters(hash); nonDefault { + observability.GetLogEntryFromContext(ctx).Entry.WithFields(logrus.Fields{ + "user_id": u.ID.String(), + "password_hash_params": params, + }).Warn("comparing password against a non-default password hash") + } + compareErr := crypto.CompareHashAndPassword(ctx, hash, password) if !strings.HasPrefix(hash, crypto.Argon2Prefix) && !strings.HasPrefix(hash, crypto.FirebaseScryptPrefix) { diff --git a/internal/models/user_test.go b/internal/models/user_test.go index 57136c9a17..b1b667b6c6 100644 --- a/internal/models/user_test.go +++ b/internal/models/user_test.go @@ -907,7 +907,7 @@ func (ts *UserTestSuite) TestAuthenticate() { require.NoError(ts.T(), ts.db.Create(u)) require.NotNil(ts.T(), u) - isAuthenticated, _, err := u.Authenticate(context.Background(), ts.db, "test", nil, false, "") + isAuthenticated, _, err := u.Authenticate(context.Background(), ts.db, "test", nil, false, "", nil) require.NoError(ts.T(), err) require.True(ts.T(), isAuthenticated) @@ -933,7 +933,7 @@ func (ts *UserTestSuite) TestReEncryptPassword() { // login re-encrypts the password the same way the password grant does login := func(u *User, password string) bool { storedHash := *u.EncryptedPassword - ok, shouldReEncrypt, err := u.Authenticate(ctx, ts.db, password, enc.DecryptionKeys, true, enc.EncryptionKeyID) + ok, shouldReEncrypt, err := u.Authenticate(ctx, ts.db, password, enc.DecryptionKeys, true, enc.EncryptionKeyID, nil) require.NoError(ts.T(), err) require.True(ts.T(), ok) require.True(ts.T(), shouldReEncrypt) @@ -944,7 +944,7 @@ func (ts *UserTestSuite) TestReEncryptPassword() { } authenticates := func(id uuid.UUID, password string) bool { - ok, _, err := loadUser(id).Authenticate(ctx, ts.db, password, enc.DecryptionKeys, false, "") + ok, _, err := loadUser(id).Authenticate(ctx, ts.db, password, enc.DecryptionKeys, false, "", nil) require.NoError(ts.T(), err) return ok } From b4b11bfd951f679f22f9515ed70f3448f65f6b44 Mon Sep 17 00:00:00 2001 From: Stojan Dimitrovski Date: Fri, 20 Nov 2026 18:18:39 +0100 Subject: [PATCH 2/2] fix(auth): rename hash policy schema constant to satisfy gosec G101 Co-Authored-By: Claude Sonnet 5.5 --- internal/conf/password_hash.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/conf/password_hash.go b/internal/conf/password_hash.go index 49670c3331..50e7dbfd76 100644 --- a/internal/conf/password_hash.go +++ b/internal/conf/password_hash.go @@ -71,9 +71,9 @@ type FirebaseScryptHashPolicy struct { MaxThreads uint64 `json:"max_threads"` } -// passwordHashPolicySchema is the JSON schema every +// hashComputePolicySchema is the JSON schema every // GOTRUE_PASSWORD_HASH_COMPUTE_POLICY value must satisfy before it is decoded. -const passwordHashPolicySchema = `{ +const hashComputePolicySchema = `{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { @@ -111,7 +111,7 @@ const passwordHashPolicySchema = `{ } }` -var passwordHashPolicySchemaLoader = gojsonschema.NewStringLoader(passwordHashPolicySchema) +var hashComputePolicySchemaLoader = gojsonschema.NewStringLoader(hashComputePolicySchema) // Decode implements envconfig.Decoder so the whole policy can be provided as a // single JSON object in one environment variable, e.g. @@ -124,7 +124,7 @@ func (p *PasswordHashPolicy) Decode(value string) error { return nil } - result, err := gojsonschema.Validate(passwordHashPolicySchemaLoader, gojsonschema.NewStringLoader(value)) + result, err := gojsonschema.Validate(hashComputePolicySchemaLoader, gojsonschema.NewStringLoader(value)) if err != nil { return fmt.Errorf("conf: invalid password hash compute policy JSON: %w", err) }