from __future__ import annotations import time import pytest from app.features.auth.errors import InvalidEmailError, InvalidTokenError, WeakPasswordError from app.features.auth.security import ( base64url_decode, base64url_encode, create_access_token, decode_access_token, generate_otp_code, hash_password, normalize_email, normalize_phone_number, validate_password_strength, verify_password, ) class TestEmailAndPhoneNormalization: def test_normalize_valid_email(self) -> None: assert normalize_email(" USER@Example.COM ") == "user@example.com" assert normalize_email("john.doe+test@domain.co.in") == "john.doe+test@domain.co.in" assert normalize_email("sanskar+sarak@gmail.com") == "sanskar+sarak@gmail.com" def test_normalize_invalid_email_raises(self) -> None: invalid_emails = [ "", "plainaddress", "@missingusername.com", "username@.com", "user name@domain.com", "user@domain", "sanskar@+gmail+.com", "sanskar@+gmail.com", "sanskar@gmail+.com", "user@domain..com", "user@-domain.com", "user@domain-.com", "user@domain.c", ] for email in invalid_emails: with pytest.raises(InvalidEmailError): normalize_email(email) def test_normalize_phone_number(self) -> None: assert normalize_phone_number(" +91 9876543210 ") == "+91 9876543210" assert normalize_phone_number(None) == "" assert normalize_phone_number("") == "" class TestPasswordValidationAndHashing: def test_password_strength_valid(self) -> None: # Must pass without raising validate_password_strength("ValidPassword123!") validate_password_strength("P@ssw0rd2026") validate_password_strength("Str0ng#Pass") def test_password_strength_too_short(self) -> None: with pytest.raises(WeakPasswordError, match="at least 8 characters"): validate_password_strength("Short1!") def test_password_strength_missing_uppercase(self) -> None: with pytest.raises(WeakPasswordError, match="uppercase"): validate_password_strength("lowercase123!") def test_password_strength_missing_digit(self) -> None: with pytest.raises(WeakPasswordError, match="number"): validate_password_strength("NoNumbersHere!") def test_password_strength_missing_special_character(self) -> None: with pytest.raises(WeakPasswordError, match="special character"): validate_password_strength("Password12345") def test_password_strength_space_instead_of_special_char_fails(self) -> None: with pytest.raises(WeakPasswordError, match="special character"): validate_password_strength("Password 12345") def test_password_strength_emoji_instead_of_special_char_fails(self) -> None: with pytest.raises(WeakPasswordError, match="special character"): validate_password_strength("Password😀12345") def test_hash_and_verify_password_lifecycle(self) -> None: raw_pw = "SuperSecure#2026" hashed = hash_password(raw_pw) assert hashed.startswith("$2b$") assert verify_password(raw_pw, hashed) is True assert verify_password("WrongPassword123!", hashed) is False def test_verify_password_with_invalid_hashes(self) -> None: assert verify_password("Password123!", None) is False assert verify_password("Password123!", "") is False assert verify_password("Password123!", "plain_text_not_a_bcrypt_hash") is False assert verify_password("Password123!", "$pbkdf2-sha256$29000$test") is False class TestOTPGeneration: def test_generate_otp_code(self) -> None: otp = generate_otp_code() assert len(otp) == 6 assert otp.isdigit() class TestJWTTokens: def test_create_and_decode_valid_token(self) -> None: payload = { "sub": "123e4567-e89b-12d3-a456-426614174000", "email": "doctor@acupedia.test", "roles": ["practitioner"], } token = create_access_token(payload) decoded = decode_access_token(token) assert decoded["sub"] == payload["sub"] assert decoded["email"] == payload["email"] assert decoded["roles"] == ["practitioner"] assert "exp" in decoded assert decoded["exp"] > int(time.time()) def test_decode_malformed_token_raises_invalid_token(self) -> None: with pytest.raises(InvalidTokenError): decode_access_token("this.isNotAValidToken") def test_decode_tampered_signature_raises_invalid_token(self) -> None: token = create_access_token({"sub": "valid-user", "role": "user"}) parts = token.split(".") # Valid base64url string that fails HMAC comparison tampered_sig = base64url_encode(b"wrong_hmac_signature_bytes_32_b") tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}" with pytest.raises(InvalidTokenError): decode_access_token(tampered_token) def test_decode_invalid_header_raises(self) -> None: import hashlib import hmac from app.features.auth.security import JWT_SECRET bad_header = base64url_encode(b'{"alg":"none","typ":"JWT"}') payload = base64url_encode(b'{"sub":"user1","exp":9999999999}') signing_input = f"{bad_header}.{payload}".encode("utf-8") valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest()) token = f"{bad_header}.{payload}.{valid_sig}" with pytest.raises(InvalidTokenError): decode_access_token(token) def test_decode_malformed_json_in_token_raises(self) -> None: header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}') bad_payload = base64url_encode(b'not valid json') token = f"{header}.{bad_payload}.c2lnbmF0dXJl" with pytest.raises(InvalidTokenError): decode_access_token(token) def test_decode_non_int_exp_raises(self) -> None: import hashlib import hmac from app.features.auth.security import JWT_SECRET header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}') payload = base64url_encode(b'{"sub":"user1","exp":"never"}') signing_input = f"{header}.{payload}".encode("utf-8") valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest()) token = f"{header}.{payload}.{valid_sig}" with pytest.raises(InvalidTokenError): decode_access_token(token) def test_decode_expired_token_raises_invalid_token(self, monkeypatch: pytest.MonkeyPatch) -> None: # Create token with TTL in the past monkeypatch.setattr("app.features.auth.security.JWT_TTL_SECONDS", -10) expired_token = create_access_token({"sub": "user-123"}) with pytest.raises(InvalidTokenError): decode_access_token(expired_token) def test_decode_missing_sub_raises_invalid_token(self) -> None: token = create_access_token({"role": "guest"}) # No 'sub' key with pytest.raises(InvalidTokenError): decode_access_token(token) def test_verify_password_catches_invalid_salt_format(self) -> None: # Format passes startswith $2b$ but is invalid for bcrypt.checkpw assert verify_password("pass", "$2b$invalid_format_hash") is False @pytest.mark.asyncio async def test_change_password_same_password_raises(self) -> None: from unittest.mock import AsyncMock, MagicMock from uuid import uuid4 from app.features.auth.service import AuthService from app.features.auth.schema import ChangePasswordRequest from app.features.auth.errors import SamePasswordError mock_session = AsyncMock() mock_repo = AsyncMock() user = MagicMock() user.id = uuid4() user.password_hash = hash_password("ValidPass123!") mock_repo.get_user_by_id = AsyncMock(return_value=user) token = create_access_token({"sub": str(user.id)}) service = AuthService( session=mock_session, repository=mock_repo, password_reset_email_sender=MagicMock(), ) req = ChangePasswordRequest(old_password="ValidPass123!", new_password="ValidPass123!") with pytest.raises(SamePasswordError, match="cannot be the same"): await service.change_password(access_token=token, request=req)