Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ server = [
"pydantic-settings>=2.0.0,<3.0.0",
"requests>=2.32.0,<3.0.0",
"PyJWT>=2.12.0,<3.0.0",
"passlib[bcrypt]>=1.7.4,<2.0.0",
"bcrypt==3.1.7",
"bcrypt==5.0.0",
"uvicorn>=0.11.1,<1.0.0",
"asyncpg>=0.25.0,<1.0.0",
"alembic>=1.8.1,<2.0.0",
Expand All @@ -49,7 +48,6 @@ quality = [
"types-requests>=2.33.0.20260513",
"types-python-dateutil>=2.8.0,<3.0.0",
"sqlalchemy-stubs>=0.4,<0.5",
"types-passlib>=1.7.0",
]
test = [
"pytest==9.0.3",
Expand Down
20 changes: 15 additions & 5 deletions src/app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@
from datetime import timedelta
from typing import Any, Dict, Optional

import bcrypt
import jwt
from passlib.context import CryptContext

from app.core.config import settings
from app.core.time import utcnow

__all__ = ["create_access_token", "hash_password", "verify_password"]

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def create_access_token(content: Dict[str, Any], expires_minutes: Optional[int] = None) -> str:
"""Encode content dict using security algorithm, setting expiration."""
Expand All @@ -24,9 +22,21 @@ def create_access_token(content: Dict[str, Any], expires_minutes: Optional[int]
return jwt.encode({**content, "exp": expire}, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)


def _encode_password(password: str) -> bytes:
# bcrypt only hashes the first 72 bytes of the password. passlib's
# CryptContext used to silently truncate; mirror that here so hashes
# generated under the previous implementation keep verifying.
return password.encode("utf-8")[:72]


def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
try:
return bcrypt.checkpw(_encode_password(plain_password), hashed_password.encode("utf-8"))
except ValueError:
# Malformed stored hash — match the previous CryptContext.verify
# behaviour which returned False rather than raising.
return False


def hash_password(password: str) -> str:
return pwd_context.hash(password)
return bcrypt.hashpw(_encode_password(password), bcrypt.gensalt()).decode("utf-8")
17 changes: 17 additions & 0 deletions src/tests/test_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ def test_verify_password():
assert not verify_password("another_try", hash_pwd1)


def test_password_longer_than_72_bytes_is_truncated():
# bcrypt only hashes the first 72 bytes. The previous passlib
# implementation silently truncated, so we keep the same contract to
# stay backward-compatible with hashes already in the DB.
base = "a" * 72
hashed = hash_password(base)
assert verify_password(base + "extra_ignored_bytes", hashed)
assert not verify_password("a" * 71 + "b", hashed)


def test_verify_password_returns_false_on_malformed_hash():
# bcrypt.checkpw raises ValueError on malformed hashes; passlib used
# to swallow it and return False. We preserve that behaviour so a
# corrupt DB row produces 401, not 500.
assert not verify_password("anything", "not-a-bcrypt-hash")


@pytest.mark.parametrize(
("content", "expires_minutes", "expected_delta"),
[
Expand Down
Loading
Loading