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>
45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
from app.auth import security
|
|
|
|
|
|
def test_password_hash_roundtrip():
|
|
hashed = security.hash_password("s3cret!")
|
|
assert security.verify_password("s3cret!", hashed)
|
|
assert not security.verify_password("wrong", hashed)
|
|
|
|
|
|
def test_jwt_roundtrip(monkeypatch):
|
|
monkeypatch.setattr(security.settings, "jwt_secret", "test-secret")
|
|
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():
|
|
"""B-13: only VerifyMismatchError was caught, so a corrupted stored hash raised
|
|
InvalidHashError and became an unhandled 500 on the login endpoint instead of a
|
|
plain "wrong credentials" 401."""
|
|
from app.auth.security import verify_password
|
|
|
|
assert verify_password("whatever", "not-an-argon2-hash") is False
|
|
assert verify_password("whatever", "") is False
|
|
|
|
|
|
def test_verify_password_still_rejects_a_wrong_password():
|
|
from app.auth.security import hash_password, verify_password
|
|
|
|
stored = hash_password("correct-horse-battery")
|
|
assert verify_password("correct-horse-battery", stored) is True
|
|
assert verify_password("wrong", stored) is False
|