Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Make password-reset tokens single-use by binding verification to the stored token, invalidate outstanding reset links on password change, and drop the dead secondary signing-key fallback

Murtaza Nasir8e90f5892930
diff --git a/src/api/auth.py b/src/api/auth.py
index 42ac1059..9e60329a 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -5,6 +5,7 @@ This blueprint handles user registration, login, logout, account management,
and password changes.
"""
+import hmac
import os
import re
import mimetypes
@@ -526,6 +527,16 @@ def reset_password(token):
flash('User not found.', 'danger')
return redirect(url_for('auth.forgot_password'))
+ # Single-use enforcement: the itsdangerous token is only signature+expiry
+ # checked, so on its own it stays replayable for the whole TTL even after
+ # it has been used or superseded. Bind it to the token currently stored on
+ # the user: a used token (cleared on reset) or one superseded by a newer
+ # reset request no longer matches and is rejected immediately.
+ stored_token = user.password_reset_token or ''
+ if not stored_token or not hmac.compare_digest(stored_token, token):
+ flash('The password reset link is invalid or has expired.', 'danger')
+ return redirect(url_for('auth.forgot_password'))
+
if request.method == 'POST':
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
@@ -870,6 +881,10 @@ def change_password():
# Update password
hashed_password = bcrypt.generate_password_hash(new_password).decode('utf-8')
current_user.password = hashed_password
+ # Invalidate any outstanding password-reset link: a deliberate change must
+ # not leave an emailed reset token able to overwrite the new password.
+ current_user.password_reset_token = None
+ current_user.password_reset_sent_at = None
db.session.commit()
flash('Your password has been updated!', 'success')
diff --git a/src/services/email.py b/src/services/email.py
index a5f84d0d..e1e6d410 100644
--- a/src/services/email.py
+++ b/src/services/email.py
@@ -57,9 +57,13 @@ def is_smtp_configured() -> bool:
def get_serializer(salt: str) -> URLSafeTimedSerializer:
- """Get a URL-safe timed serializer for token generation."""
- secret_key = current_app.config.get('SECRET_KEY', 'default-dev-key')
- return URLSafeTimedSerializer(secret_key, salt=salt)
+ """Get a URL-safe timed serializer for token generation.
+
+ SECRET_KEY is guaranteed set (and never the insecure default) by the
+ startup guard in src/app.py, so no fallback is needed here — a fallback
+ would only reintroduce a weak, forgeable signing key.
+ """
+ return URLSafeTimedSerializer(current_app.config['SECRET_KEY'], salt=salt)
def generate_verification_token(user_id: int) -> str:
diff --git a/tests/test_password_reset_single_use.py b/tests/test_password_reset_single_use.py
new file mode 100644
index 00000000..1cf8ac5f
--- /dev/null
+++ b/tests/test_password_reset_single_use.py
@@ -0,0 +1,102 @@
+"""Password-reset tokens must be single-use and invalidated on supersede /
+password change. Previously the itsdangerous token was only signature+expiry
+checked, so a leaked link kept working for the full 1h TTL even after it had
+been used or the password had already been changed.
+"""
+
+import os
+import sys
+import uuid
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db, bcrypt
+from src.models import User
+from src.services.email import generate_password_reset_token
+
+app.config['WTF_CSRF_ENABLED'] = False
+
+
+def _make_user():
+ suffix = uuid.uuid4().hex[:8]
+ u = User(username=f'reset_{suffix}', email=f'reset_{suffix}@local.test',
+ password=bcrypt.generate_password_hash('OldPassw0rd!').decode())
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _issue_token(user):
+ token = generate_password_reset_token(user.id)
+ user.password_reset_token = token
+ db.session.commit()
+ return token
+
+
+def test_valid_token_resets_password_once():
+ with app.app_context():
+ user = _make_user()
+ token = _issue_token(user)
+ client = app.test_client()
+
+ r = client.post(f'/reset-password/{token}',
+ data={'password': 'NewPassw0rd!', 'confirm_password': 'NewPassw0rd!'},
+ follow_redirects=False)
+ assert r.status_code in (200, 302)
+ db.session.refresh(user)
+ assert bcrypt.check_password_hash(user.password, 'NewPassw0rd!')
+ assert user.password_reset_token is None # cleared on use
+
+ # Reuse of the same token must now fail (password unchanged).
+ r2 = client.post(f'/reset-password/{token}',
+ data={'password': 'Attacker1!', 'confirm_password': 'Attacker1!'},
+ follow_redirects=False)
+ db.session.refresh(user)
+ assert not bcrypt.check_password_hash(user.password, 'Attacker1!')
+ assert bcrypt.check_password_hash(user.password, 'NewPassw0rd!')
+
+ db.session.delete(user)
+ db.session.commit()
+
+
+def test_superseded_token_is_rejected():
+ # A validly-signed older token that no longer matches the token currently
+ # stored on the user (a newer reset request replaced it) must be rejected.
+ # itsdangerous emits identical tokens within the same second, so we model
+ # the supersede by storing a distinct current token directly rather than
+ # racing the clock.
+ with app.app_context():
+ user = _make_user()
+ old_token = generate_password_reset_token(user.id) # validly signed
+ user.password_reset_token = old_token + 'SUPERSEDED' # newer stored token differs
+ db.session.commit()
+ client = app.test_client()
+
+ r = client.post(f'/reset-password/{old_token}',
+ data={'password': 'ViaOld1!', 'confirm_password': 'ViaOld1!'},
+ follow_redirects=False)
+ db.session.refresh(user)
+ assert not bcrypt.check_password_hash(user.password, 'ViaOld1!')
+
+ db.session.delete(user)
+ db.session.commit()
+
+
+def test_token_with_no_stored_counterpart_is_rejected():
+ with app.app_context():
+ user = _make_user()
+ # A validly-signed token, but nothing stored on the user (never
+ # requested, or already cleared).
+ token = generate_password_reset_token(user.id)
+ user.password_reset_token = None
+ db.session.commit()
+ client = app.test_client()
+
+ r = client.post(f'/reset-password/{token}',
+ data={'password': 'NoStore1!', 'confirm_password': 'NoStore1!'},
+ follow_redirects=False)
+ db.session.refresh(user)
+ assert not bcrypt.check_password_hash(user.password, 'NoStore1!')
+
+ db.session.delete(user)
+ db.session.commit()