CI / lint (push) Canceled after 0s
CI / typecheck (push) Canceled after 0s
CI / unit-tests (push) Canceled after 0s
CI / integration-tests (push) Canceled after 0s
CI / container-build (push) Canceled after 0s
CI / dependency-audit (push) Canceled after 0s
The first authenticated-user concept in Aurora Core -- everything else in this codebase is public, read-only catalog data. Foundation for ratings and a watchlist (not yet built): POST /auth/register, POST /auth/login, GET /auth/me. Security specifics worth knowing: - Passwords hashed with argon2 (via argon2-cffi), never stored plain or logged. - Login returns an identical 401 for a nonexistent email and a wrong password on a real one, including matching response timing (burn_time_like_a_password_check) -- otherwise either the status code or the timing alone lets a client enumerate registered emails. - AURORA_SECRET_KEY now actually signs JWTs (previously defined but unused anywhere) -- .env.example's existing token_urlsafe(48) guidance already produces a long enough key, just flagged its new stakes. - Email matched case-insensitively via explicit normalization in the service layer, not relied on from Pydantic's EmailStr (which does not lowercase the local part). 12 new integration tests (register/login/me over real HTTP via the `client` fixture) plus 10 unit tests for the hashing/JWT logic itself, following the same-day lesson that only unit tests actually execute locally without Postgres -- the auth core is tested for real here rather than only through integration tests that might not run before a deploy. Co-Authored-By: Claude Sonnet 5 <[email protected]>
76 lines
2.5 KiB
Python
76 lines
2.5 KiB
Python
"""Password hashing and JWT access tokens for registered users.
|
|
|
|
Separate from app/core/security.py, which handles admin-API-key auth and
|
|
rate limiting -- unrelated concerns (a machine-to-machine secret vs. a
|
|
human user's own credentials).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import jwt
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import VerifyMismatchError
|
|
|
|
from app.core.config import get_settings
|
|
|
|
_hasher = PasswordHasher()
|
|
_JWT_ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_TTL = timedelta(hours=24)
|
|
|
|
|
|
class InvalidTokenError(Exception):
|
|
"""Raised for any access token that's missing, malformed, expired, or
|
|
signed with a different key -- callers treat all of these identically
|
|
(401), so this collapses PyJWT's several exception types into one."""
|
|
|
|
|
|
def normalize_email(email: str) -> str:
|
|
"""Emails are matched and stored case-insensitively (RFC 5321 technically
|
|
allows a case-sensitive local part, but no mainstream provider honors
|
|
that, and forcing lowercase avoids needing a functional unique index)."""
|
|
|
|
return email.strip().lower()
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return _hasher.hash(password)
|
|
|
|
|
|
def verify_password(password: str, hashed_password: str) -> bool:
|
|
try:
|
|
return _hasher.verify(hashed_password, password)
|
|
except VerifyMismatchError:
|
|
return False
|
|
|
|
|
|
# Computed once at import time, verified against on a login attempt whose
|
|
# email doesn't exist at all -- so rejecting a nonexistent account takes
|
|
# roughly the same time as rejecting a wrong password on a real one.
|
|
# Without this, a login endpoint's response time itself reveals which
|
|
# emails are registered, letting an attacker enumerate accounts without
|
|
# ever guessing a password.
|
|
_DUMMY_HASH = _hasher.hash("not-a-real-password-used-only-for-timing")
|
|
|
|
|
|
def burn_time_like_a_password_check() -> None:
|
|
verify_password("irrelevant", _DUMMY_HASH)
|
|
|
|
|
|
def create_access_token(user_id: uuid.UUID) -> str:
|
|
settings = get_settings()
|
|
now = datetime.now(UTC)
|
|
payload = {"sub": str(user_id), "iat": now, "exp": now + ACCESS_TOKEN_TTL}
|
|
return jwt.encode(payload, settings.AURORA_SECRET_KEY, algorithm=_JWT_ALGORITHM)
|
|
|
|
|
|
def decode_access_token(token: str) -> uuid.UUID:
|
|
settings = get_settings()
|
|
try:
|
|
payload = jwt.decode(token, settings.AURORA_SECRET_KEY, algorithms=[_JWT_ALGORITHM])
|
|
return uuid.UUID(payload["sub"])
|
|
except (jwt.InvalidTokenError, KeyError, ValueError) as exc:
|
|
raise InvalidTokenError(str(exc)) from exc
|