"""Unit tests for app/core/auth.py -- pure functions, no DB needed. Written after a real bug (watch_provider never registered as an Aurora ID entity type) shipped unnoticed because every test touching that path skips locally without Postgres -- this module's logic is exercised for real here rather than only through integration tests that might not run.""" from __future__ import annotations import uuid import pytest from app.core.auth import ( InvalidTokenError, burn_time_like_a_password_check, create_access_token, decode_access_token, hash_password, normalize_email, verify_password, ) def test_hash_password_round_trips(): hashed = hash_password("correct horse battery staple") assert verify_password("correct horse battery staple", hashed) is True def test_verify_password_rejects_wrong_password(): hashed = hash_password("correct horse battery staple") assert verify_password("wrong password", hashed) is False def test_hash_password_is_salted(): # Same input, different output each time -- otherwise two users with # the same password would have identical hashed_password rows, # trivially revealing the match to anyone with DB access. assert hash_password("same password") != hash_password("same password") def test_normalize_email_lowercases_and_strips(): assert normalize_email(" User@Example.COM ") == "user@example.com" def test_access_token_round_trips(): user_id = uuid.uuid4() token = create_access_token(user_id) assert decode_access_token(token) == user_id def test_decode_rejects_garbage_token(): with pytest.raises(InvalidTokenError): decode_access_token("not.a.valid.token") def test_decode_rejects_token_signed_with_a_different_key(monkeypatch): import jwt from app.core import auth as auth_module forged = jwt.encode({"sub": str(uuid.uuid4())}, "a-different-secret", algorithm="HS256") with pytest.raises(InvalidTokenError): auth_module.decode_access_token(forged) def test_decode_rejects_expired_token(): from datetime import UTC, datetime, timedelta import jwt from app.core import auth as auth_module from app.core.config import get_settings expired_payload = { "sub": str(uuid.uuid4()), "iat": datetime.now(UTC) - timedelta(hours=48), "exp": datetime.now(UTC) - timedelta(hours=24), } token = jwt.encode(expired_payload, get_settings().AURORA_SECRET_KEY, algorithm="HS256") with pytest.raises(InvalidTokenError): auth_module.decode_access_token(token) def test_decode_rejects_token_missing_subject(): import jwt from app.core import auth as auth_module from app.core.config import get_settings token = jwt.encode({"nope": "no sub claim"}, get_settings().AURORA_SECRET_KEY, algorithm="HS256") with pytest.raises(InvalidTokenError): auth_module.decode_access_token(token) def test_burn_time_like_a_password_check_does_not_raise(): burn_time_like_a_password_check()