feat(sync): paginate Android sync with change tokens
This commit is contained in:
1 parent
0ff94f9b10
commit
97c237be80
76 files changed
+3401
-851
No files matched your search
@@ -21,6 +21,8 @@ type authContract struct {
|
||||
Hashes []struct {
|
||||
Name string `json:"name"`
|
||||
Hash string `json:"hash"`
|
||||
Password string `json:"password"`
|
||||
WrongPassword string `json:"wrongPassword"`
|
||||
Verifies map[string]bool `json:"verifies"`
|
||||
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
|
||||
} `json:"hashes"`
|
||||
@@ -36,6 +38,7 @@ type authContract struct {
|
||||
Unix int64 `json:"unix"`
|
||||
Code string `json:"code"`
|
||||
Secret *string `json:"secret"`
|
||||
MatchedStep *int64 `json:"matchedStep"`
|
||||
Valid bool `json:"valid"`
|
||||
} `json:"cases"`
|
||||
} `json:"totp"`
|
||||
@@ -71,21 +74,29 @@ func TestContractPasswordHashes(t *testing.T) {
|
||||
contract := loadContract(t)
|
||||
for _, entry := range contract.Password.Hashes {
|
||||
t.Run(entry.Name, func(t *testing.T) {
|
||||
if got := VerifyPassword(entry.Hash, contract.Password.Plaintext); got != entry.Verifies["go"] {
|
||||
password := entry.Password
|
||||
if password == "" {
|
||||
password = contract.Password.Plaintext
|
||||
}
|
||||
wrongPassword := entry.WrongPassword
|
||||
if wrongPassword == "" {
|
||||
wrongPassword = contract.Password.WrongPassword
|
||||
}
|
||||
if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] {
|
||||
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
|
||||
}
|
||||
if VerifyPassword(entry.Hash, contract.Password.WrongPassword) {
|
||||
if VerifyPassword(entry.Hash, wrongPassword) {
|
||||
t.Error("VerifyPassword accepted the wrong password")
|
||||
}
|
||||
if want, ok := entry.NeedsUpgrade["go"]; ok {
|
||||
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
|
||||
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
|
||||
}
|
||||
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, contract.Password.Plaintext)
|
||||
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password)
|
||||
if err != nil || !valid || (upgraded != "") != want {
|
||||
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
|
||||
}
|
||||
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) || !VerifyPassword(upgraded, contract.Password.Plaintext)) {
|
||||
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) {
|
||||
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
|
||||
}
|
||||
}
|
||||
@@ -109,9 +120,19 @@ func TestContractTOTP(t *testing.T) {
|
||||
if entry.Secret != nil {
|
||||
secret = *entry.Secret
|
||||
}
|
||||
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid {
|
||||
step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0))
|
||||
if got != entry.Valid {
|
||||
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
|
||||
}
|
||||
if got {
|
||||
want := entry.Unix / 30
|
||||
if entry.MatchedStep != nil {
|
||||
want = *entry.MatchedStep
|
||||
}
|
||||
if step != want {
|
||||
t.Errorf("VerifyTOTP matched step %d, want %d", step, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
// BcryptCost is kept in one place so all services use the same password
|
||||
@@ -17,9 +23,19 @@ const BcryptCost = 12
|
||||
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
|
||||
// are upgraded on login.
|
||||
const bcryptScheme = "bcrypt$"
|
||||
const bcryptSHA256Scheme = "bcrypt-sha256$"
|
||||
|
||||
const (
|
||||
maxPasswordBytes = 72
|
||||
legacyPBKDF2Iterations = 100000
|
||||
maxPBKDF2Iterations = 10000000
|
||||
)
|
||||
|
||||
// HashPassword returns a versioned password hash suitable for storage.
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len([]byte(password)) > maxPasswordBytes {
|
||||
return "", errors.New("password must be at most 72 bytes")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -27,20 +43,38 @@ func HashPassword(password string) (string, error) {
|
||||
return bcryptScheme + string(hash), nil
|
||||
}
|
||||
|
||||
// VerifyPassword checks a plaintext password against a stored hash. It accepts
|
||||
// hashes from HashPassword and unprefixed bcrypt hashes; any other format
|
||||
// fails closed.
|
||||
// VerifyPassword checks a plaintext password against bcrypt and legacy Node
|
||||
// PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword.
|
||||
func VerifyPassword(hash, password string) bool {
|
||||
if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok {
|
||||
digest := sha256.Sum256([]byte(password))
|
||||
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil
|
||||
}
|
||||
if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok {
|
||||
actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New)
|
||||
expectedBytes, err := hex.DecodeString(expected)
|
||||
return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1
|
||||
}
|
||||
bcryptHash, ok := bcryptHashOf(hash)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len([]byte(password)) > maxPasswordBytes {
|
||||
return false
|
||||
}
|
||||
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
|
||||
}
|
||||
|
||||
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
|
||||
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
|
||||
func PasswordHashNeedsUpgrade(hash string) bool {
|
||||
if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed {
|
||||
cost, err := bcrypt.Cost([]byte(bcryptHash))
|
||||
return err != nil || cost < BcryptCost
|
||||
}
|
||||
if _, _, _, ok := parsePBKDF2Hash(hash); ok {
|
||||
return true
|
||||
}
|
||||
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
|
||||
if !prefixed {
|
||||
return true
|
||||
@@ -61,6 +95,15 @@ func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded strin
|
||||
if !PasswordHashNeedsUpgrade(hash) {
|
||||
return true, "", nil
|
||||
}
|
||||
if len([]byte(password)) > maxPasswordBytes {
|
||||
digest := sha256.Sum256([]byte(password))
|
||||
var hashBytes []byte
|
||||
hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost)
|
||||
if err == nil {
|
||||
upgraded = bcryptSHA256Scheme + string(hashBytes)
|
||||
}
|
||||
return true, upgraded, err
|
||||
}
|
||||
upgraded, err = HashPassword(password)
|
||||
if err != nil {
|
||||
return true, "", err
|
||||
@@ -78,3 +121,32 @@ func bcryptHashOf(stored string) (string, bool) {
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func parsePBKDF2Hash(stored string) (iterations int, salt, expected string, ok bool) {
|
||||
if strings.HasPrefix(stored, "pbkdf2-sha256$") {
|
||||
parts := strings.Split(stored, "$")
|
||||
if len(parts) != 4 {
|
||||
return 0, "", "", false
|
||||
}
|
||||
parsedIterations, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return 0, "", "", false
|
||||
}
|
||||
iterations, salt, expected = parsedIterations, parts[2], parts[3]
|
||||
} else if strings.Count(stored, ":") == 1 {
|
||||
parts := strings.SplitN(stored, ":", 2)
|
||||
iterations, salt, expected = legacyPBKDF2Iterations, parts[0], parts[1]
|
||||
} else {
|
||||
return 0, "", "", false
|
||||
}
|
||||
if iterations < 1 || iterations > maxPBKDF2Iterations || len(salt) != 32 || len(expected) != 64 {
|
||||
return 0, "", "", false
|
||||
}
|
||||
if _, err := hex.DecodeString(salt); err != nil {
|
||||
return 0, "", "", false
|
||||
}
|
||||
if _, err := hex.DecodeString(expected); err != nil {
|
||||
return 0, "", "", false
|
||||
}
|
||||
return iterations, salt, expected, true
|
||||
}
|
||||
@@ -165,9 +165,9 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
@@ -183,6 +183,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||
)
|
||||
|
||||
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from
|
||||
@@ -223,7 +224,7 @@ var (
|
||||
// message rather than a generic "internal error" that would be
|
||||
// indistinguishable from any other server bug.
|
||||
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
|
||||
errSecretNotSet = errors.New("SECRET environment variable is not set.")
|
||||
errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength)
|
||||
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
|
||||
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
|
||||
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
|
||||
@@ -286,6 +287,10 @@ type Service struct {
|
||||
// real base URL.
|
||||
authGuard *authclient.Client
|
||||
configurationError error
|
||||
// reauthenticateEmailChanges is opt-in because older consumers historically
|
||||
// allowed email-only edits without the current password. Password changes
|
||||
// always require current credentials in UpdateMe.
|
||||
reauthenticateEmailChanges bool
|
||||
loginCacheMu sync.Mutex
|
||||
loginCacheValue bool
|
||||
loginCacheSet bool
|
||||
@@ -305,9 +310,10 @@ type Service struct {
|
||||
type ServiceOption func(*serviceOptions)
|
||||
|
||||
type serviceOptions struct {
|
||||
disabled bool
|
||||
requireSecret bool
|
||||
trustedProxies []*net.IPNet
|
||||
disabled bool
|
||||
requireSecret bool
|
||||
reauthenticateEmailChanges bool
|
||||
trustedProxies []*net.IPNet
|
||||
}
|
||||
|
||||
// Disabled explicitly builds a Service in auth-disabled mode (see the
|
||||
@@ -329,6 +335,14 @@ func RequireSecret() ServiceOption {
|
||||
return func(o *serviceOptions) { o.requireSecret = true }
|
||||
}
|
||||
|
||||
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
|
||||
// enabled, for email changes through UpdateMe. Password changes already
|
||||
// require the same proof. This is opt-in to preserve existing consumers that
|
||||
// have not adopted the matching profile-dialog flow.
|
||||
func ReauthenticateEmailChanges() ServiceOption {
|
||||
return func(o *serviceOptions) { o.reauthenticateEmailChanges = true }
|
||||
}
|
||||
|
||||
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
|
||||
// honoured when a login's client address is taken. Build the list from the
|
||||
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
|
||||
@@ -379,8 +393,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
|
||||
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
|
||||
}
|
||||
var configurationError error
|
||||
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
|
||||
configurationError = errSecretNotSet
|
||||
if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) {
|
||||
configurationError = errSecretNotUsable
|
||||
}
|
||||
return &Service{
|
||||
store: store,
|
||||
@@ -388,6 +402,7 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
|
||||
secureCookies: secureCookies,
|
||||
authGuard: client,
|
||||
configurationError: configurationError,
|
||||
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
|
||||
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
|
||||
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
|
||||
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
|
||||
@@ -694,9 +709,11 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var input struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
CurrentPassword string `json:"currentPassword"`
|
||||
TOTPToken string `json:"totpToken"`
|
||||
}
|
||||
if err := decodeProxyJSON(r, &input); err != nil {
|
||||
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
@@ -719,7 +736,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
writeProxyError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
managedInput.Password = input.Password
|
||||
}
|
||||
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
|
||||
if input.CurrentPassword == "" {
|
||||
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
|
||||
return
|
||||
}
|
||||
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
|
||||
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
|
||||
return
|
||||
}
|
||||
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
|
||||
if err != nil {
|
||||
writeAuthGuardError(w, err, "current credentials could not be verified")
|
||||
return
|
||||
}
|
||||
if token := temporarySessionToken(reauthenticated); token != "" {
|
||||
defer func() {
|
||||
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
|
||||
}()
|
||||
}
|
||||
if input.Password != "" {
|
||||
managedInput.Password = input.Password
|
||||
}
|
||||
}
|
||||
|
||||
token := s.sessionToken(r)
|
||||
@@ -736,6 +775,18 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
|
||||
}
|
||||
|
||||
func temporarySessionToken(session *authclient.SessionResult) string {
|
||||
if session == nil {
|
||||
return ""
|
||||
}
|
||||
for _, cookie := range session.Cookies {
|
||||
if cookie != nil && cookie.Name == authclient.DefaultCookieName {
|
||||
return cookie.Value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
|
||||
// comment's "Setup flow" section.
|
||||
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -856,7 +907,7 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
|
||||
// expose the same propagation endpoint without duplicating its JSON handling.
|
||||
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
|
||||
if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
|
||||
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -406,6 +406,12 @@ func TestTOTPInitiateAndStatus(t *testing.T) {
|
||||
|
||||
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||
guard := newFakeAuthGuard(t)
|
||||
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
|
||||
w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||
})
|
||||
guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true})
|
||||
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
|
||||
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||
service, _ := guard.service(t)
|
||||
@@ -418,7 +424,7 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||
service.UpdateMe(rec, req)
|
||||
return rec
|
||||
}
|
||||
manager := &ProxyUser{ID: 7, Role: "admin"}
|
||||
manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true}
|
||||
|
||||
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("no session user: status = %d, want 401", rec.Code)
|
||||
@@ -431,6 +437,8 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
|
||||
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
|
||||
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
|
||||
"missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`,
|
||||
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
|
||||
"not JSON": `nope`,
|
||||
} {
|
||||
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
|
||||
@@ -452,6 +460,29 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||
if _, sent := calls[0].Body["password"]; sent {
|
||||
t.Fatal("an update without a password sent one to AuthGuard")
|
||||
}
|
||||
|
||||
rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
loginCalls := guard.callsTo("POST /api/login")
|
||||
if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" {
|
||||
t.Fatalf("reauthentication request = %+v", loginCalls)
|
||||
}
|
||||
calls = guard.callsTo("PUT /api/admin/users/7")
|
||||
if len(calls) != 2 || calls[1].Body["password"] != "new-password" {
|
||||
t.Fatalf("password update request = %+v", calls)
|
||||
}
|
||||
if _, sent := calls[1].Body["currentPassword"]; sent {
|
||||
t.Fatal("current password was forwarded to the managed-user API")
|
||||
}
|
||||
if _, sent := calls[1].Body["totpToken"]; sent {
|
||||
t.Fatal("TOTP code was forwarded to the managed-user API")
|
||||
}
|
||||
logoutCalls := guard.callsTo("POST /api/logout")
|
||||
if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" {
|
||||
t.Fatalf("temporary login session was not removed: %+v", logoutCalls)
|
||||
}
|
||||
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
|
||||
t.Fatalf("response user = %v", user)
|
||||
}
|
||||
|
||||
@@ -87,6 +87,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_login_at TIMESTAMPTZ
|
||||
@@ -95,6 +96,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
-- last_login_at is nullable (NULL means "never logged in" - registration
|
||||
@@ -220,8 +222,9 @@ func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
// TOTPState is the private provisioning state for one account. Secret must
|
||||
// never be included in an API response.
|
||||
type TOTPState struct {
|
||||
Secret string
|
||||
Enabled bool
|
||||
Secret string
|
||||
Enabled bool
|
||||
LastUsedStep int64
|
||||
}
|
||||
|
||||
// GetTOTPState reads the stored TOTP provisioning state for an account.
|
||||
@@ -230,7 +233,7 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
|
||||
return TOTPState{}, err
|
||||
}
|
||||
var state TOTPState
|
||||
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled)
|
||||
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return TOTPState{}, nil
|
||||
}
|
||||
@@ -246,7 +249,7 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
|
||||
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set TOTP secret: %w", err)
|
||||
}
|
||||
@@ -262,16 +265,39 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableTOTP marks a previously provisioned secret as active.
|
||||
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error {
|
||||
// EnableTOTP marks a previously provisioned secret as active and records the
|
||||
// step used to confirm it, preventing that code from being reused at login.
|
||||
func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE auth_users
|
||||
SET totp_enabled = true, last_used_step = $1, updated_at = now()
|
||||
WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1
|
||||
`, step, userID, secret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("enable TOTP: %w", err)
|
||||
return false, fmt.Errorf("enable TOTP: %w", err)
|
||||
}
|
||||
return nil
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// ConsumeTOTPStep advances an account's accepted TOTP step only once. The
|
||||
// expected secret and enabled flag are part of the update so a concurrent
|
||||
// disable or re-enrollment cannot consume a code against stale state.
|
||||
func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE auth_users
|
||||
SET last_used_step = $1, updated_at = now()
|
||||
WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1
|
||||
`, step, userID, secret)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("consume TOTP step: %w", err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// DisableTOTP clears both the active and pending TOTP secret.
|
||||
@@ -279,7 +305,7 @@ func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
|
||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("disable TOTP: %w", err)
|
||||
}
|
||||
@@ -382,6 +408,22 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpgradePasswordHash replaces an old verifier only if it is still current,
|
||||
// so a concurrent password change cannot be overwritten by a login rehash.
|
||||
func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE auth_users SET password_hash = $1, updated_at = now()
|
||||
WHERE id = $2 AND password_hash = $3
|
||||
`, newHash, id, oldHash)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("upgrade password hash: %w", err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// ListUsers returns the non-secret account fields used by the shared user
|
||||
// management screen.
|
||||
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
|
||||
|
||||
@@ -230,8 +230,8 @@ func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
|
||||
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
|
||||
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
|
||||
}
|
||||
if err := store.EnableTOTP(ctx, owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
if enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled {
|
||||
t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err)
|
||||
}
|
||||
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
|
||||
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
|
||||
|
||||
@@ -52,19 +52,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string {
|
||||
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
|
||||
}
|
||||
|
||||
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
|
||||
func VerifyTOTP(secret, token string, now time.Time) bool {
|
||||
// VerifyTOTP checks a six-digit token with a one-period clock-skew window and
|
||||
// returns the matching time step. A caller must atomically record that step
|
||||
// before accepting the code so it cannot be used twice.
|
||||
func VerifyTOTP(secret, token string, now time.Time) (int64, bool) {
|
||||
secret = normalizeTOTPSecret(secret)
|
||||
token = normalizeTOTPToken(token)
|
||||
if secret == "" || len(token) != TOTPDigits {
|
||||
return false
|
||||
return -1, false
|
||||
}
|
||||
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
||||
if err != nil || len(key) == 0 {
|
||||
return false
|
||||
return -1, false
|
||||
}
|
||||
period := now.Unix() / int64(TOTPPeriod/time.Second)
|
||||
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
|
||||
// Prefer the current step if a six-digit collision occurs in the window.
|
||||
for _, offset := range [...]int64{0, -1, 1} {
|
||||
if period+offset < 0 {
|
||||
continue
|
||||
}
|
||||
@@ -80,10 +83,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool {
|
||||
uint32(digest[index+3])
|
||||
candidate := fmt.Sprintf("%06d", value%1000000)
|
||||
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
|
||||
return true
|
||||
return period + offset, true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return -1, false
|
||||
}
|
||||
|
||||
func normalizeTOTPSecret(value string) string {
|
||||
|
||||
@@ -18,8 +18,11 @@ func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
|
||||
{unix: 2000000000, code: "279037"},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) {
|
||||
step, valid := VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0))
|
||||
if !valid {
|
||||
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
|
||||
} else if want := testCase.unix / int64(TOTPPeriod/time.Second); step != want {
|
||||
t.Errorf("VerifyTOTP(%d, %q) matched step %d, want %d", testCase.unix, testCase.code, step, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user