Invalidate existing sessions on password change/reset (B-34)

Neither self-service password change nor the admin reset invalidated
already-issued JWTs — a 24h-lifetime token stayed valid regardless, so
a stolen token (or an attacker who already had the old password) kept
working past a password change meant to lock them out. The admin reset
exists precisely for the "account compromised" case and didn't evict
the attacker at all.

Add User.token_version (migration 943dbd74d983), embedded in every JWT
as a "tv" claim and checked against the DB on every request in
get_current_user/get_optional_user; a mismatch reads as session_expired.
Both change-password and the admin reset bump it. change-password hands
back a freshly minted token so the caller's own session keeps working
instead of being logged out by its own request; the admin reset does
not, since that session isn't the one making the call.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-27 12:02:23 +02:00
co-authored by Claude Sonnet 5
parent 16802cafb6
commit 739fc9fed2
12 changed files with 159 additions and 36 deletions
+4
View File
@@ -205,6 +205,10 @@ async def test_admin_resets_user_password(client):
assert refreshed.password_hash != old_hash
assert verify_password(new_password, refreshed.password_hash)
assert not verify_password("original-password", refreshed.password_hash)
# B-34: the reset must bump token_version so a session opened before
# the reset (e.g. an attacker who had the old password) is evicted
# immediately rather than staying valid until the JWT naturally expires.
assert refreshed.token_version == 1
async def test_admin_reset_password_requires_token(client):
+15 -2
View File
@@ -9,8 +9,21 @@ def test_password_hash_roundtrip():
def test_jwt_roundtrip(monkeypatch):
monkeypatch.setattr(security.settings, "jwt_secret", "test-secret")
token = security.create_access_token(user_id=42)
assert security.decode_access_token(token) == 42
token = security.create_access_token(user_id=42, token_version=3)
assert security.decode_access_token(token) == (42, 3)
def test_jwt_decode_defaults_token_version_for_tokens_issued_before_it_existed(monkeypatch):
"""B-34: a token minted before the "tv" claim existed has no such key at
all. It must still decode — as token_version 0, matching a freshly
migrated user's starting value — rather than raising or being treated as
permanently stale."""
import jwt as pyjwt
monkeypatch.setattr(security.settings, "jwt_secret", "test-secret")
payload = {"sub": "42"}
token = pyjwt.encode(payload, "test-secret", algorithm=security.settings.jwt_algorithm)
assert security.decode_access_token(token) == (42, 0)
def test_verify_password_returns_false_for_an_unparseable_hash():
+32 -1
View File
@@ -81,7 +81,8 @@ async def test_change_password_updates_login(client):
headers=headers,
json={"current_password": "original-password", "new_password": "brand-new-password"},
)
assert resp.status_code == 204
assert resp.status_code == 200
assert resp.json()["access_token"]
resp = await client.post("/auth/login", json={"username": "alice", "password": "original-password"})
assert resp.status_code == 401
@@ -90,6 +91,36 @@ async def test_change_password_updates_login(client):
assert resp.status_code == 200
async def test_change_password_invalidates_the_old_token_but_not_the_new_one(client):
"""B-34: neither self-service change-password nor the admin reset used to
invalidate already-issued JWTs, so a stolen token (or an attacker who
already had the old password) stayed logged in until the token's natural
24h expiry — even past a password change meant to lock them out."""
old_token = await _register(client)
old_headers = {"Authorization": f"Bearer {old_token}"}
resp = await client.post(
"/users/me/change-password",
headers=old_headers,
json={"current_password": "original-password", "new_password": "brand-new-password"},
)
assert resp.status_code == 200
new_token = resp.json()["access_token"]
assert new_token != old_token
# The old token (what an attacker holding the old password would still
# have) is now rejected...
resp = await client.get("/users/me", headers=old_headers)
assert resp.status_code == 401
assert resp.json()["detail"]["code"] == "session_expired"
# ...but the freshly issued one keeps this same session working, so the
# user who just changed their own password isn't logged out too.
new_headers = {"Authorization": f"Bearer {new_token}"}
resp = await client.get("/users/me", headers=new_headers)
assert resp.status_code == 200
async def test_change_password_rejects_too_short(client):
token = await _register(client)
headers = {"Authorization": f"Bearer {token}"}