Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix: tolerate adjacent TOTP windows (#441)

Albert Dolkunfe8c0bf2251d
diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py
index 21d1d664..d7e0d685 100644
--- a/backend/app/api/two_factor.py
+++ b/backend/app/api/two_factor.py
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.auth import current_active_user, get_jwt_strategy
from app.core.database import get_async_session
+from app.core.rate_limit import login_rate_limit
from app.core.redis import get_redis
from app.models.user import User
from app.schemas.two_factor import (
@@ -18,6 +19,11 @@ from app.schemas.two_factor import (
)
router = APIRouter()
+TOTP_VALID_WINDOW = 1
+
+
+def _verify_totp(secret: str, code: str) -> bool:
+ return pyotp.TOTP(secret).verify(code, valid_window=TOTP_VALID_WINDOW)
def _parse_temp_token_payload(raw: str | bytes) -> dict[str, object] | None:
@@ -58,8 +64,7 @@ async def enable_2fa(
if not user.totp_secret:
raise HTTPException(status_code=400, detail="Call /2fa/setup first")
- totp = pyotp.TOTP(user.totp_secret)
- if not totp.verify(body.code):
+ if not _verify_totp(user.totp_secret, body.code):
raise HTTPException(status_code=400, detail="Invalid 2FA code")
user.is_2fa_enabled = True
@@ -91,8 +96,7 @@ async def disable_2fa(
if not user.totp_secret:
raise HTTPException(status_code=400, detail="2FA is not set up")
- totp = pyotp.TOTP(user.totp_secret)
- if not totp.verify(body.code):
+ if not _verify_totp(user.totp_secret, body.code):
raise HTTPException(status_code=400, detail="Invalid 2FA code")
user.totp_secret = None
@@ -102,7 +106,7 @@ async def disable_2fa(
return {"detail": "2FA disabled"}
[email protected]("/2fa/verify")
[email protected]("/2fa/verify", dependencies=[Depends(login_rate_limit)])
async def verify_2fa(
body: TwoFactorVerifyRequest,
session: AsyncSession = Depends(get_async_session),
@@ -126,8 +130,7 @@ async def verify_2fa(
raise HTTPException(status_code=401, detail="Invalid token")
# Verify TOTP
- totp = pyotp.TOTP(user.totp_secret)
- if not totp.verify(body.code):
+ if not _verify_totp(user.totp_secret, body.code):
raise HTTPException(status_code=400, detail="Invalid 2FA code")
# Delete temp token
diff --git a/backend/tests/test_rate_limit.py b/backend/tests/test_rate_limit.py
index 1063fd8e..9a8bda13 100644
--- a/backend/tests/test_rate_limit.py
+++ b/backend/tests/test_rate_limit.py
@@ -66,3 +66,19 @@ async def test_login_rate_limit(client: AsyncClient, test_user):
)
assert response.status_code == 429
assert "Retry-After" in response.headers
+
+
+async def test_totp_verify_rate_limit(client: AsyncClient):
+ for i in range(5):
+ response = await client.post(
+ "/api/auth/2fa/verify",
+ json={"temp_token": "invalid", "code": "000000"},
+ )
+ assert response.status_code == 401, f"Request {i + 1} got {response.status_code}"
+
+ response = await client.post(
+ "/api/auth/2fa/verify",
+ json={"temp_token": "invalid", "code": "000000"},
+ )
+ assert response.status_code == 429
+ assert "Retry-After" in response.headers
diff --git a/backend/tests/test_two_factor.py b/backend/tests/test_two_factor.py
index 642f2e73..0dad6918 100644
--- a/backend/tests/test_two_factor.py
+++ b/backend/tests/test_two_factor.py
@@ -1,9 +1,12 @@
-from unittest.mock import AsyncMock, patch
+from datetime import datetime
+from unittest.mock import AsyncMock, MagicMock, patch
import pyotp
import pytest
from httpx import AsyncClient
+from app.api.two_factor import _verify_totp
+
def _make_redis_mock_with_store():
"""Create a Redis mock that actually stores and retrieves key-value pairs."""
@@ -24,11 +27,7 @@ def _make_redis_mock_with_store():
mock.delete = AsyncMock(side_effect=mock_delete)
# Pipeline for rate limiter (always allow)
- pipe_mock = AsyncMock()
- pipe_mock.zremrangebyscore = AsyncMock()
- pipe_mock.zcard = AsyncMock()
- pipe_mock.zadd = AsyncMock()
- pipe_mock.expire = AsyncMock()
+ pipe_mock = MagicMock()
pipe_mock.execute = AsyncMock(return_value=[0, 0, True, True])
mock.pipeline = lambda: pipe_mock
@@ -89,6 +88,23 @@ async def test_enable_2fa_invalid_code(client: AsyncClient, auth_headers: dict,
assert response.status_code == 400
+def test_verify_totp_allows_adjacent_time_windows():
+ secret = pyotp.random_base32()
+ fixed_time = datetime(2026, 7, 19, 12, 0)
+ totp = pyotp.TOTP(secret)
+ previous_code = totp.at(fixed_time, counter_offset=-1)
+ next_code = totp.at(fixed_time, counter_offset=1)
+
+ class FrozenDateTime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return cls(2026, 7, 19, 12, 0, tzinfo=tz)
+
+ with patch("pyotp.totp.datetime.datetime", FrozenDateTime):
+ assert _verify_totp(secret, previous_code)
+ assert _verify_totp(secret, next_code)
+
+
async def test_login_with_2fa(client: AsyncClient, test_user_with_2fa):
response = await client.post(
"/api/auth/login",
@@ -202,7 +218,7 @@ async def test_verify_2fa_with_valid_token(client: AsyncClient, test_user_with_2
mock_r = AsyncMock()
mock_r.get = AsyncMock(return_value=str(test_user_with_2fa.id))
mock_r.delete = AsyncMock()
- pipe = AsyncMock()
+ pipe = MagicMock()
pipe.execute = AsyncMock(return_value=[0, 0, True, True])
mock_r.pipeline = lambda: pipe