mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 20:55:16 +09:00
Reuse the pending 2FA setup secret
initiate_setup minted and committed a new secret on every call, so a
second Enable click, a double-click or reopening the setup window threw
away the secret the user had just scanned and the authenticator's code
never verified.
Reuse the unconfirmed secret unless none exists or the caller sends
{"regenerate": true}. The user row is locked for the call so concurrent
/auth/2fa/setup requests cannot both invent a secret. Confirmed users
still get 400 and are never rotated. TOTP parameters are unchanged.
Tests cover reuse, confirm with the reused secret, regenerate, the 400
for confirmed users, and the QR being built from the otpauth URI.
This commit is contained in:
1 parent
1e733d0bf8
commit
9bb3672551
3 files changed
+99
-9
No files matched your search
@@ -7,7 +7,7 @@ Provides endpoints for enabling, disabling, and managing 2FA.
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from flask import Blueprint, jsonify
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
from app import limiter
|
||||
from app.middleware.session_auth import issue_session_tokens
|
||||
@@ -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,15 @@ 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
|
||||
|
||||
setup = TwoFactorSetup(user)
|
||||
setup_data = setup.initiate_setup()
|
||||
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
|
||||
|
||||
return jsonify({
|
||||
'message': '2FA setup initiated. Scan the QR code and enter a verification code.',
|
||||
|
||||
@@ -191,20 +191,31 @@ 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:
|
||||
raise ValueError('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
|
||||
|
||||
@@ -172,3 +172,74 @@ 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(ValueError):
|
||||
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()
|
||||
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 c['secret'] != a['secret']
|
||||
confirm = client.post(url + '/confirm', headers=_headers(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(user))
|
||||
assert r.status_code == 400
|
||||
db.session.refresh(user)
|
||||
assert user.totp_secret == secret and user.totp_enabled
|
||||
Reference in new issue
Block a user