🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: constant-time login check, hashed reset tokens with one-hour life (AUTH-06, AUTH-08)
Omega (QA)6e3a1de6f4d0
diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex 969afab..5bd74a5 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -6,6 +6,7 @@ import uuidimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText+import hashlibimport osimport pytzimport psycopg2@@ -31,6 +32,23 @@ except ImportError:auth_bp = Blueprint('auth_bp', __name__)+# AUTH-06: a valid bcrypt hash of a random value nobody knows, checked+# when the login name matches no account or the account has no local+# password hash (OIDC-only). Running the check unconditionally keeps+# login timing from revealing whether an account exists, and a NULL+# hash returns the same 401 as a wrong password instead of a 500.+_DUMMY_PASSWORD_HASH = '$2b$12$LItrc0bk3Uh0XRSXHNV2aO43hjnIhIrWoz9LLb2k514.lybEznWj6'+++def _hash_reset_token(token):+ """One-way hash of a password reset token for storage (AUTH-08).++ Only the hash is stored, so the database value alone can never+ complete a reset. The emailed link still carries the raw token.+ """+ return hashlib.sha256(token.encode('utf-8')).hexdigest()++@auth_bp.route('/register', methods=['POST'])def register():conn = None@@ -179,7 +197,11 @@ def login():cur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))user = cur.fetchone()- if not user or not bcrypt.check_password_hash(user[3], password):+ password_hash = user[3] if user and user[3] else _DUMMY_PASSWORD_HASH+ # Run the check unconditionally: branching on `user` first+ # would short-circuit it and restore the timing split.+ password_ok = bcrypt.check_password_hash(password_hash, password)+ if not user or not password_ok:return jsonify({'message': 'Invalid username or password!'}), 401if not user[4]: # is_active@@ -359,17 +381,19 @@ def request_password_reset():user_id = user[0]- # Generate reset token+ # Generate reset token. Only its hash is stored (AUTH-08), so+ # the database value alone can never complete a reset; the+ # emailed link carries the raw token. Tokens live one hour.reset_token = str(uuid.uuid4())- expires_at = datetime.now(UTC) + timedelta(hours=24)-+ expires_at = datetime.now(UTC) + timedelta(hours=1)+# Delete any existing tokens for this usercur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))-- # Insert new token++ # Insert new token (hash only)cur.execute('INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',- (user_id, reset_token, expires_at)+ (user_id, _hash_reset_token(reset_token), expires_at))conn.commit()@@ -670,8 +694,8 @@ def reset_password():conn = db_handler.get_db_connection()with conn.cursor() as cur:- # Check if token exists and is valid- cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))+ # Check if token exists and is valid (stored as a hash, AUTH-08)+ cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (_hash_reset_token(token),))token_info = cur.fetchone()if not token_info:@@ -696,7 +720,7 @@ def reset_password():cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))# Delete the used token- cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))+ cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (_hash_reset_token(token),))conn.commit()@@ -800,7 +824,7 @@ def send_password_reset_email(recipient_email, reset_link):<p>Please click the link below to reset your password:</p><p><a href="{reset_link}">Reset Password</a></p><p>If you did not request this password reset, please ignore this email.</p>- <p>This link will expire in 24 hours.</p>+ <p>This link will expire in 1 hour.</p><p>Thanks,<br>The {app_name} Team</p></body></html>diff --git a/tests/test_auth_enumeration_reset.py b/tests/test_auth_enumeration_reset.pynew file mode 100644index 0000000..94c06ff--- /dev/null+++ b/tests/test_auth_enumeration_reset.py@@ -0,0 +1,125 @@+"""Account enumeration hardening (AUTH-06) and reset token storage (AUTH-08).++AUTH-06: login always runs the bcrypt check, so an unknown user and a+known user with a wrong password take the same time, and an OIDC-only+account with no local password hash gets the same 401 as a wrong+password instead of a 500.++AUTH-08: reset tokens are stored as SHA-256 hashes, so the database+value alone can never complete a reset, and tokens live one hour.+"""+import re+import time+import uuid+from datetime import datetime, timedelta, UTC++from backend.auth_routes import _hash_reset_token+++def test_unknown_user_login_is_slow_401(client):+ started = time.monotonic()+ r = client.post("/api/auth/login", json={+ "username": "nobody-at-all", "password": "Whatever123!"})+ elapsed = time.monotonic() - started+ assert r.status_code == 401+ assert r.get_json()["message"] == "Invalid username or password!"+ # The bcrypt check must have run: the pre-fix skip answered in ~3 ms.+ assert elapsed > 0.05+++def test_oidc_only_user_login_is_401_not_500(client, db_connection):+ username = f"oidconly_{uuid.uuid4().hex[:8]}"+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO users (username, email, password_hash, oidc_sub, "+ "oidc_issuer, is_active) VALUES (%s, %s, NULL, %s, %s, TRUE)",+ (username, f"{username}@test.local", "sub-123", "https://idp.test"),+ )+ r = client.post("/api/auth/login", json={+ "username": username, "password": "Whatever123!"})+ assert r.status_code == 401+ assert r.get_json()["message"] == "Invalid username or password!"+++def test_known_user_wrong_password_still_401(client, user_factory):+ user = user_factory()+ r = client.post("/api/auth/login", json={+ "username": user["username"], "password": "WrongPass123!"})+ assert r.status_code == 401+ assert r.get_json()["message"] == "Invalid username or password!"+++def _request_reset(client, db_connection, email):+ r = client.post("/api/auth/password/reset-request", json={"email": email})+ assert r.status_code == 200+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT token, expires_at, created_at FROM password_reset_tokens "+ "WHERE user_id = (SELECT id FROM users WHERE email = %s)",+ (email,),+ )+ return cur.fetchone()+++def test_reset_token_stored_as_hash_with_one_hour_life(+ client, user_factory, db_connection):+ user = user_factory()+ email = f"{user['username']}@test.local"+ token, expires_at, created_at = _request_reset(client, db_connection, email)+ # A SHA-256 hex digest, not the raw uuid4 token from the email link.+ assert re.fullmatch(r"[0-9a-f]{64}", token), token+ lifetime = (expires_at - created_at).total_seconds()+ assert 3500 < lifetime <= 3610, lifetime+++def test_reset_completes_with_raw_token_not_with_stored_hash(+ client, user_factory, db_connection):+ user = user_factory()+ email = f"{user['username']}@test.local"+ raw_token = str(uuid.uuid4())+ with db_connection, db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE email = %s", (email,))+ user_id = cur.fetchone()[0]+ cur.execute(+ "INSERT INTO password_reset_tokens (user_id, token, expires_at) "+ "VALUES (%s, %s, %s)",+ (user_id, _hash_reset_token(raw_token),+ datetime.now(UTC) + timedelta(hours=1)),+ )++ # The stored hash value alone must not complete a reset.+ stored_hash = _hash_reset_token(raw_token)+ r = client.post("/api/auth/password/reset", json={+ "token": stored_hash, "password": "NewPass123!"})+ assert r.status_code == 400++ # The raw token from the email link completes the reset.+ r = client.post("/api/auth/password/reset", json={+ "token": raw_token, "password": "NewPass123!"})+ assert r.status_code == 200++ # The new password works, and the token is single-use.+ r = client.post("/api/auth/login", json={+ "username": user["username"], "password": "NewPass123!"})+ assert r.status_code == 200+ r = client.post("/api/auth/password/reset", json={+ "token": raw_token, "password": "Another123!"})+ assert r.status_code == 400+++def test_expired_reset_token_rejected(client, user_factory, db_connection):+ user = user_factory()+ email = f"{user['username']}@test.local"+ raw_token = str(uuid.uuid4())+ with db_connection, db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE email = %s", (email,))+ user_id = cur.fetchone()[0]+ cur.execute(+ "INSERT INTO password_reset_tokens (user_id, token, expires_at) "+ "VALUES (%s, %s, %s)",+ (user_id, _hash_reset_token(raw_token),+ datetime.now(UTC) - timedelta(minutes=1)),+ )+ r = client.post("/api/auth/password/reset", json={+ "token": raw_token, "password": "NewPass123!"})+ assert r.status_code == 400