fix: invalidate jwt token on password reset (#4248)
What changed, and why it matters
This commit fixes a security bug in LNbits where changing or resetting a user's password did not automatically log out active sessions. Before the fix, someone who stole or shared a login session could keep using it even after the password was changed, because the system only checked two-factor authentication revisions, not password changes. The patch now bumps a hidden 'session revision' whenever the password changes, so all existing tokens and browser cookies are rejected and the user must log in again.
Deploy this patch promptly. After upgrading, advise users to change their password if they suspect an active session may have been compromised, as the fix only invalidates sessions created after the patch is live. Review whether any other credential or security-setting changes (e.g., email/SSO linking) also need to bump the session revision.
Security signals we found
Session invalidation on credential change
Atomic update of password hash and MFA revision
Removal of bypass path that skipped revision check when 2FA was disabled
Regression tests for both password update and password reset operations
Evidence from the diff
The patch introduces update_account_credentials() and update_account_password() in lnbits/core/services/two_factor.py. When a password is updated via /api/v1/auth/password or /api/v1/auth/reset, the code now increments the per-account two_factor config revision and clears outstanding MFA challenges in a single atomic update. The existing check_two_factor_session() already rejects tokens whose mfa_revision does not match the current config revision, so the new revision invalidates previously issued JWT access tokens and cookie sessions. A regression test confirms that old tokens return HTTP 401 after both password-change and password-reset flows, while other users’ sessions remain valid.
Changed components
lnbits/core/crud/users.pylnbits/core/services/two_factor.pylnbits/core/views/auth_api.pytests/api/test_two_factor.pyInspect captured patch +145 / −9
diff --git a/lnbits/core/crud/users.py b/lnbits/core/crud/users.py
index 9f9cb1d..edafaa0 100644
--- a/lnbits/core/crud/users.py
+++ b/lnbits/core/crud/users.py
@@ -52,6 +52,30 @@ async def update_account(account: Account, conn: Connection | None = None) -> Ac
return account
+async def update_account_credentials(
+ account: Account,
+ config: TwoFactorConfig,
+ conn: Connection | None = None,
+) -> None:
+ """Save the password and session revision in a single atomic update."""
+ account.updated_at = datetime.now(timezone.utc)
+ await (conn or db).execute(
+ f"""
+ UPDATE accounts SET username = :username, password_hash = :password_hash,
+ updated_at = {db.timestamp_placeholder("updated_at")},
+ two_factor = :two_factor
+ WHERE id = :id
+ """, # noqa: S608
+ {
+ "id": account.id,
+ "username": account.username,
+ "password_hash": account.password_hash,
+ "updated_at": account.updated_at.timestamp(),
+ "two_factor": config.json(),
+ },
+ )
+
+
async def delete_account(user_id: str, conn: Connection | None = None) -> None:
await (conn or db).execute(
"DELETE from accounts WHERE id = :user",
diff --git a/lnbits/core/services/two_factor.py b/lnbits/core/services/two_factor.py
index d2d0e9e..80df1cc 100644
--- a/lnbits/core/services/two_factor.py
+++ b/lnbits/core/services/two_factor.py
@@ -21,8 +21,9 @@ from lnbits.core.crud.settings import (
from lnbits.core.crud.users import (
get_two_factor_config,
save_two_factor_config,
+ update_account_credentials,
)
-from lnbits.core.models.users import AccessTokenPayload, TwoFactorConfig
+from lnbits.core.models.users import AccessTokenPayload, Account, TwoFactorConfig
from lnbits.db import Connection
from lnbits.settings import UpdateSettings, settings
@@ -262,6 +263,14 @@ async def session_payload(
)
+async def update_account_password(account: Account) -> None:
+ async with _two_factor_lock(account.id):
+ config = await get_two_factor_config(account.id)
+ config.revision = secrets.token_hex(16)
+ config.challenges.clear()
+ await update_account_credentials(account, config)
+
+
async def sync_two_factor_policy() -> str:
"""Invalidate old MFA claims when policy changes, including via environment."""
fingerprint = json.dumps(
@@ -330,10 +339,6 @@ async def check_two_factor_session(
raise HTTPException(
HTTPStatus.FORBIDDEN, "Impersonation cannot change account security."
)
- if not settings.lnbits_two_factor_enabled and not (
- payload and payload.mfa_revision
- ):
- return
config = await get_two_factor_config(actor or user_id, conn)
if payload and config.revision != payload.mfa_revision:
raise two_factor_error("Account security changed. Please log in again.")
diff --git a/lnbits/core/views/auth_api.py b/lnbits/core/views/auth_api.py
index 12e6c29..da8bb60 100644
--- a/lnbits/core/views/auth_api.py
+++ b/lnbits/core/views/auth_api.py
@@ -30,7 +30,11 @@ from lnbits.core.models.users import (
UpdateAccessControlList,
)
from lnbits.core.services import create_user_account
-from lnbits.core.services.two_factor import issue_challenge, session_payload
+from lnbits.core.services.two_factor import (
+ issue_challenge,
+ session_payload,
+ update_account_password,
+)
from lnbits.core.services.users import (
check_register_activation_settings,
update_user_account,
@@ -535,7 +539,7 @@ async def update_password(
account.username = data.username
account.hash_password(data.password)
- await update_account(account)
+ await update_account_password(account)
_user = await get_user_from_account(account)
if not _user:
raise HTTPException(HTTPStatus.NOT_FOUND, "User not found.")
@@ -578,7 +582,7 @@ async def reset_password(data: ResetUserPassword) -> JSONResponse:
raise HTTPException(HTTPStatus.NOT_FOUND, "User not found.")
account.hash_password(data.password)
- await update_account(account)
+ await update_account_password(account)
return await _login_response(account)
diff --git a/tests/api/test_payment_status_api.py b/tests/api/test_payment_status_api.py
index a1f70b7..c6bca98 100644
--- a/tests/api/test_payment_status_api.py
+++ b/tests/api/test_payment_status_api.py
@@ -397,6 +397,8 @@ async def test_change_status_service_fee_is_credited_once(
@pytest.fixture(autouse=True)
def notification_tasks(mocker):
tasks = []
+ # Background admin alerts must not enter the captured payment task list.
+ mocker.patch("lnbits.core.services.notifications.send_notification_in_background")
mocker.patch(
"lnbits.core.services.notifications.create_task", side_effect=tasks.append
)
diff --git a/tests/api/test_two_factor.py b/tests/api/test_two_factor.py
index d3b1a20..1ebbc66 100644
--- a/tests/api/test_two_factor.py
+++ b/tests/api/test_two_factor.py
@@ -28,8 +28,9 @@ from lnbits.core.services.two_factor import (
from lnbits.core.services.users import create_user_account
from lnbits.core.views.auth_api import _handle_sso_login
from lnbits.core.views.user_api import api_users_reset_password
-from lnbits.helpers import create_access_token
+from lnbits.helpers import create_access_token, sha256s
from lnbits.settings import AuthMethods
+from lnbits.utils.cache import cache
from lnbits.utils.nostr import sign_event
pytestmark = pytest.mark.anyio
@@ -184,6 +185,106 @@ async def test_two_factor_user_id_and_cached_session_cannot_bypass(
assert response.json()["two_factor_required"]
+@pytest.mark.parametrize("operation", ["password", "reset"])
+@pytest.mark.parametrize("enrolled", [False, True])
+@pytest.mark.parametrize("cache_minutes", [0, 5])
+async def test_password_update_revokes_sessions(
+ http_client, factor_account, settings, operation, enrolled, cache_minutes
+):
+ settings.auth_authentication_cache_minutes = cache_minutes
+ settings.lnbits_two_factor_enabled = enrolled
+ if enrolled:
+ _, session = await enroll(http_client, factor_account)
+ else:
+ session = (await login(http_client, factor_account)).json()
+ old_token = session["access_token"]
+
+ other_account = Account(
+ id=uuid4().hex,
+ username="other_" + uuid4().hex[:8],
+ password_hash=factor_account.password_hash,
+ )
+ await create_user_account(other_account)
+ other_login = await login(http_client, other_account)
+ assert other_login.status_code == 200
+ other_headers = {"Authorization": f"Bearer {other_login.json()['access_token']}"}
+ http_client.cookies.clear()
+ headers = {"Authorization": f"Bearer {old_token}"}
+ for path in ("/api/v1/wallets", "/api/v1/wallet/paginated"):
+ assert (await http_client.get(path, headers=headers)).status_code == 200
+ if cache_minutes:
+ assert cache.get(f"auth:access_token:{sha256s(old_token)}")
+
+ challenge = await issue_challenge(factor_account.id)
+ before = await get_two_factor_config(factor_account.id)
+ if operation == "password":
+ response = await http_client.put(
+ "/api/v1/auth/password",
+ headers=headers,
+ json={
+ "user_id": factor_account.id,
+ "username": factor_account.username,
+ "password_old": "secret1234",
+ "password": "newsecret1234",
+ "password_repeat": "newsecret1234",
+ },
+ )
+ else:
+ reset_key = await api_users_reset_password(factor_account.id)
+ response = await http_client.put(
+ "/api/v1/auth/reset",
+ json={
+ "reset_key": reset_key,
+ "password": "newsecret1234",
+ "password_repeat": "newsecret1234",
+ },
+ )
+ assert response.status_code == 200, response.text
+ if operation == "reset" and not enrolled:
+ assert (await http_client.get("/api/v1/wallets")).status_code == 200
+
+ after = await get_two_factor_config(factor_account.id)
+ assert after.revision and after.revision != before.revision
+ assert challenge.jti not in after.challenges
+ assert not before.challenges.keys() & after.challenges.keys()
+ assert (
+ after.copy(
+ update={"revision": before.revision, "challenges": before.challenges}
+ )
+ == before
+ )
+
+ http_client.cookies.clear()
+ for path in ("/api/v1/wallets", "/api/v1/wallet/paginated"):
+ assert (await http_client.get(path, headers=headers)).status_code == 401
+ http_client.cookies.set("cookie_access_token", old_token)
+ assert (await http_client.get(path)).status_code == 401
+ http_client.cookies.clear()
+ challenge_headers = {
+ "Authorization": f"Bearer {create_access_token(challenge.dict())}"
+ }
+ assert (
+ await http_client.get("/api/v1/auth/2fa/status", headers=challenge_headers)
+ ).status_code == 401
+ assert (
+ await http_client.get("/api/v1/wallets", headers=other_headers)
+ ).status_code == 200
+
+ response = await http_client.post(
+ "/api/v1/auth",
+ json={"username": factor_account.username, "password": "newsecret1234"},
+ )
+ assert response.status_code == 200
+ if enrolled:
+ assert response.json()["two_factor_required"]
+ response = await http_client.post(
+ "/api/v1/auth/2fa/verify", json={"code": session["recovery_codes"][0]}
+ )
+ assert response.status_code == 200, response.text
+ assert (await http_client.get("/api/v1/wallets")).status_code == 200
+ assert (await http_client.get("/api/v1/wallet/paginated")).status_code == 200
+
+
async def test_two_factor_mandatory_enrollment_only(
http_client, factor_account, settings
):
Why this scored 60/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.