From 1205a2506d6fd0caa98c224d1680d90aa82a7384 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Thu, 26 Nov 2026 02:55:32 -0500 Subject: [PATCH] Use shared JWT helpers in 2FA tests The new setup-endpoint tests minted tokens directly, which the one-door ratchet rejects. They now use headers_for. The race path for an already-confirmed user raises ConflictError instead of returning a hand-shaped error body, so the inventory count stays at 849. The setup route reads the optional regenerate flag through json_object. --- backend/app/api/two_factor.py | 12 ++++-------- backend/app/services/totp_service.py | 3 ++- backend/tests/test_totp_service.py | 21 +++++++++------------ 3 files changed, 15 insertions(+), 21 deletions(-) diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py index c5d15e86..d231275b 100644 --- a/backend/app/api/two_factor.py +++ b/backend/app/api/two_factor.py @@ -7,7 +7,7 @@ Provides endpoints for enabling, disabling, and managing 2FA. import logging import threading import time -from flask import Blueprint, jsonify, request +from flask import Blueprint, jsonify from flask_jwt_extended import jwt_required, get_jwt_identity from app import limiter from app.middleware.session_auth import issue_session_tokens @@ -80,15 +80,11 @@ def initiate_2fa_setup(): if user.totp_enabled: return jsonify({'error': '2FA is already enabled'}), 400 - data = request.get_json(silent=True) - regenerate = isinstance(data, dict) and data.get('regenerate') is True + data = json_object(optional=True) + regenerate = data.get('regenerate') is True setup = TwoFactorSetup(user) - try: - setup_data = setup.initiate_setup(regenerate=regenerate) - except ValueError: - # Confirmed between the check above and the row lock. - return jsonify({'error': '2FA is already enabled'}), 400 + setup_data = setup.initiate_setup(regenerate=regenerate) return jsonify({ 'message': '2FA setup initiated. Scan the QR code and enter a verification code.', diff --git a/backend/app/services/totp_service.py b/backend/app/services/totp_service.py index 2066447d..24a4f351 100644 --- a/backend/app/services/totp_service.py +++ b/backend/app/services/totp_service.py @@ -209,7 +209,8 @@ class TwoFactorSetup: db.session.refresh(self.user, with_for_update=True) if self.user.totp_enabled: - raise ValueError('2FA is already enabled') + from app.exceptions import ConflictError + raise ConflictError('2FA is already enabled') secret = self.user.totp_secret if regenerate or not secret: diff --git a/backend/tests/test_totp_service.py b/backend/tests/test_totp_service.py index de11f684..f44f2c85 100644 --- a/backend/tests/test_totp_service.py +++ b/backend/tests/test_totp_service.py @@ -9,6 +9,8 @@ from werkzeug.security import generate_password_hash from app import db from app.models import User from app.services.totp_service import TOTPService, TwoFactorSetup +from app.exceptions import ConflictError +from factories import headers_for @pytest.fixture @@ -211,25 +213,20 @@ def test_regenerate_mints_new_secret_only_while_unconfirmed(user): second = setup.initiate_setup(regenerate=True)['secret'] assert second != first and user.totp_secret == second setup.confirm_setup(TOTPService.get_current_code(second)) - with pytest.raises(ValueError): + with pytest.raises(ConflictError): setup.initiate_setup(regenerate=True) assert user.totp_secret == second -def _headers(user): - from flask_jwt_extended import create_access_token - return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'} - - def test_setup_endpoint_reuses_secret_until_regenerate(client, user): url = '/api/v1/auth/2fa/setup' - a = client.post(url, headers=_headers(user)).get_json() - b = client.post(url, headers=_headers(user)).get_json() + a = client.post(url, headers=headers_for(user)).get_json() + b = client.post(url, headers=headers_for(user)).get_json() assert a['secret'] == b['secret'] and a['uri'] == b['uri'] - assert client.get('/api/v1/auth/2fa/status', headers=_headers(user)).get_json()['enabled'] is False - c = client.post(url, json={'regenerate': True}, headers=_headers(user)).get_json() + assert client.get('/api/v1/auth/2fa/status', headers=headers_for(user)).get_json()['enabled'] is False + c = client.post(url, json={'regenerate': True}, headers=headers_for(user)).get_json() assert c['secret'] != a['secret'] - confirm = client.post(url + '/confirm', headers=_headers(user), + confirm = client.post(url + '/confirm', headers=headers_for(user), json={'code': TOTPService.get_current_code(c['secret'])}) assert confirm.status_code == 200 @@ -239,7 +236,7 @@ def test_setup_endpoint_rejects_confirmed_user_without_rotating(client, user): secret = user.totp_secret TwoFactorSetup(user).confirm_setup(TOTPService.get_current_code(secret)) for body in (None, {'regenerate': True}): - r = client.post('/api/v1/auth/2fa/setup', json=body, headers=_headers(user)) + r = client.post('/api/v1/auth/2fa/setup', json=body, headers=headers_for(user)) assert r.status_code == 400 db.session.refresh(user) assert user.totp_secret == secret and user.totp_enabled