Skip to content

Commit c1054c8

Browse files
Improve token validation in password reset flow
1 parent bba8d07 commit c1054c8

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

backend/app/utils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ def verify_password_reset_token(token: str) -> str | None:
118118
decoded_token = jwt.decode(
119119
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
120120
)
121-
return str(decoded_token["sub"])
121+
subject = decoded_token.get("sub")
122+
if not isinstance(subject, str) or not subject:
123+
return None
124+
return subject
122125
except InvalidTokenError:
123126
return None

backend/tests/api/routes/test_login.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
from unittest.mock import patch
22

33
from fastapi.testclient import TestClient
4+
import jwt
45
from pwdlib.hashers.bcrypt import BcryptHasher
56
from sqlmodel import Session
67

8+
from app.core import security
79
from app.core.config import settings
810
from app.core.security import get_password_hash, verify_password
911
from app.crud import create_user
@@ -126,6 +128,27 @@ def test_reset_password_invalid_token(
126128
assert response["detail"] == "Invalid token"
127129

128130

131+
def test_reset_password_token_without_subject_claim(
132+
client: TestClient, superuser_token_headers: dict[str, str]
133+
) -> None:
134+
token_without_sub = jwt.encode(
135+
{"nbf": 0, "exp": 4102444800},
136+
settings.SECRET_KEY,
137+
algorithm=security.ALGORITHM,
138+
)
139+
data = {"new_password": "changethis", "token": token_without_sub}
140+
r = client.post(
141+
f"{settings.API_V1_STR}/reset-password/",
142+
headers=superuser_token_headers,
143+
json=data,
144+
)
145+
response = r.json()
146+
147+
assert "detail" in response
148+
assert r.status_code == 400
149+
assert response["detail"] == "Invalid token"
150+
151+
129152
def test_login_with_bcrypt_password_upgrades_to_argon2(
130153
client: TestClient, db: Session
131154
) -> None:

0 commit comments

Comments
 (0)