diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py index 5597ea2e..d231275b 100644 --- a/backend/app/api/two_factor.py +++ b/backend/app/api/two_factor.py @@ -67,7 +67,8 @@ def get_2fa_status(): @jwt_required() def initiate_2fa_setup(): """ - Initiate 2FA setup. Generates a new secret and returns QR code. + Initiate 2FA setup. Reuses the pending unconfirmed secret (or generates + one); JSON {"regenerate": true} forces a fresh secret. User must verify with a code to complete setup. """ current_user_id = get_jwt_identity() @@ -79,8 +80,11 @@ def initiate_2fa_setup(): if user.totp_enabled: return jsonify({'error': '2FA is already enabled'}), 400 + data = json_object(optional=True) + regenerate = data.get('regenerate') is True + setup = TwoFactorSetup(user) - setup_data = setup.initiate_setup() + 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 28f9afbf..24a4f351 100644 --- a/backend/app/services/totp_service.py +++ b/backend/app/services/totp_service.py @@ -191,20 +191,32 @@ class TwoFactorSetup: def __init__(self, user): self.user = user - def initiate_setup(self): + def initiate_setup(self, regenerate=False): """ - Start 2FA setup by generating a new secret. + Start 2FA setup, reusing the pending unconfirmed secret if there is one. + + A new secret is minted only when none is pending or ``regenerate`` is + set, so repeated Enable clicks keep the secret the user already scanned. + A confirmed secret is never rotated here. Returns: dict: Setup data including secret and QR code """ from app import db - # Generate new secret (don't enable yet) - secret = TOTPService.generate_secret() - self.user.totp_secret = secret + # Serialize on the user row so concurrent /setup calls see one secret. + # (No-op on SQLite, where writes are already serialized.) + db.session.refresh(self.user, with_for_update=True) - # Don't enable until verified + if self.user.totp_enabled: + from app.exceptions import ConflictError + raise ConflictError('2FA is already enabled') + + secret = self.user.totp_secret + if regenerate or not secret: + secret = TOTPService.generate_secret() + self.user.totp_secret = secret + # Don't enable until verified; commit also releases the row lock. db.session.commit() # Generate QR code diff --git a/backend/tests/test_totp_service.py b/backend/tests/test_totp_service.py index ee248b04..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 @@ -172,3 +174,69 @@ def test_regenerate_backup_codes_replaces_old_set(user): assert ok and len(new) == 10 assert not old_hashes & set(user.get_backup_codes()) assert setup.regenerate_backup_codes('abc') == (False, 'Invalid verification code') + + +def test_qr_code_is_built_from_the_provisioning_uri(secret, monkeypatch): + from app.services import totp_service + if not totp_service.HAS_QRCODE: + pytest.skip('qrcode not installed') + added = [] + real = totp_service.qrcode.QRCode + + class Spy(real): + def add_data(self, data, *a, **kw): + added.append(data) + return super().add_data(data, *a, **kw) + + monkeypatch.setattr(totp_service.qrcode, 'QRCode', Spy) + TOTPService.generate_qr_code_base64(secret, 'me@example.com') + assert added == [TOTPService.get_provisioning_uri(secret, 'me@example.com')] + parsed = urlparse(added[0]) + assert parsed.scheme == 'otpauth' and parsed.netloc == 'totp' + assert parse_qs(parsed.query) == {'secret': [secret], 'issuer': ['ServerKit']} + + +def test_second_initiate_reuses_pending_secret_and_confirm_works(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup() + second = TwoFactorSetup(user).initiate_setup() + assert second['secret'] == first['secret'] == user.totp_secret + assert second['uri'] == first['uri'] and second['issuer'] == 'ServerKit' + assert not user.totp_enabled + ok, _ = setup.confirm_setup(TOTPService.get_current_code(first['secret'])) + assert ok and user.totp_enabled + + +def test_regenerate_mints_new_secret_only_while_unconfirmed(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup()['secret'] + 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(ConflictError): + setup.initiate_setup(regenerate=True) + assert user.totp_secret == second + + +def test_setup_endpoint_reuses_secret_until_regenerate(client, user): + url = '/api/v1/auth/2fa/setup' + 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_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_for(user), + json={'code': TOTPService.get_current_code(c['secret'])}) + assert confirm.status_code == 200 + + +def test_setup_endpoint_rejects_confirmed_user_without_rotating(client, user): + TwoFactorSetup(user).initiate_setup() + 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_for(user)) + assert r.status_code == 400 + db.session.refresh(user) + assert user.totp_secret == secret and user.totp_enabled diff --git a/frontend/src/components/Modal.jsx b/frontend/src/components/Modal.jsx index 28516053..c962bb7a 100644 --- a/frontend/src/components/Modal.jsx +++ b/frontend/src/components/Modal.jsx @@ -1,5 +1,6 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'; import { cn } from '@/lib/utils'; +import { dismissGuards } from '@/components/ui/dismissGuards'; // Generic modal built on the Radix Dialog primitive. SCSS owns all geometry // (styles/components/_ui.scss → .sk-modal*). `size` picks a max-width on @@ -12,6 +13,9 @@ import { cn } from '@/lib/utils'; // to the bottom of the scrolling body, and a nested .modal-body adds no extra // padding or scroller. Two-column .form-row stacks in narrow modals. // +// closeOnDismiss={false}: overlay click and Escape no longer close the modal +// (for flows that would lose in-progress state); explicit buttons still do. +// // Form mode: pass `onSubmit` and the body AND footer // are wrapped in one