From 89c970758fcb5f953d8afb592229dab9ef0ad047 Mon Sep 17 00:00:00 2001 From: Team Gaya Date: Tue, 20 Oct 2026 00:17:43 +0530 Subject: [PATCH 1/3] fix: make in-memory user email lookups case-insensitive PostgresUserRepository stores emails lowercase and matches them with LOWER(email) = LOWER($1), but InMemoryUserRepository - the default for local development and the test suite - keyed users by the exact email string. In the default setup, signing up as "Alice@Example.com" and then logging in as "alice@example.com" returned 401, and the same address could register twice with different casing. Store the email lowercase on save and lowercase the lookup key in get_by_email so both backends behave the same, and document the case-insensitive contract on UserRepository.get_by_email. --- repositories/interfaces.py | 2 +- repositories/memory.py | 26 ++++++-- tests/test_auth_email_case.py | 111 ++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 7 deletions(-) create mode 100644 tests/test_auth_email_case.py diff --git a/repositories/interfaces.py b/repositories/interfaces.py index d3608bd..a61a8be 100644 --- a/repositories/interfaces.py +++ b/repositories/interfaces.py @@ -526,7 +526,7 @@ async def save(self, record: UserRecord) -> UserRecord: @abstractmethod async def get_by_email(self, email: str) -> Optional[UserRecord]: - """Fetch user by email. Returns None if not found.""" + """Fetch user by email, case-insensitively. Returns None if not found.""" @abstractmethod async def get_by_id(self, user_id: str) -> Optional[UserRecord]: diff --git a/repositories/memory.py b/repositories/memory.py index d39e1c7..1097ced 100644 --- a/repositories/memory.py +++ b/repositories/memory.py @@ -408,29 +408,43 @@ class InMemoryUserRepository(UserRepository): """Dict-backed `UserRepository`. TEMPORARY - see module docstring. Stores user accounts in memory with basic email/id lookups. + + Emails are stored lowercase and looked up case-insensitively, matching + `PostgresUserRepository`. Without this, local/test runs (which default + to this stub) would let "Alice@example.com" and "alice@example.com" + register as two accounts and reject a login whose casing differs from + signup - behaviour that silently changes once DATABASE_URL is set. """ def __init__(self) -> None: self._users: Dict[str, UserRecord] = {} - self._email_index: Dict[str, str] = {} # email -> user_id + self._email_index: Dict[str, str] = {} # lowercased email -> user_id self._lock = asyncio.Lock() async def save(self, record: UserRecord) -> UserRecord: - """Insert or update by user_id. Idempotent, preserves created_at.""" + """Insert or update by user_id. Idempotent, preserves created_at. + + Stores email in lowercase for case-insensitive lookups. + """ async with self._lock: existing = self._users.get(record.user_id) created_at = existing.created_at if existing else record.created_at + email = record.email.lower() stored = record.model_copy( - update={"created_at": created_at, "updated_at": datetime.now(timezone.utc)} + update={ + "email": email, + "created_at": created_at, + "updated_at": datetime.now(timezone.utc), + } ) self._users[record.user_id] = stored - self._email_index[record.email] = record.user_id + self._email_index[email] = record.user_id return stored async def get_by_email(self, email: str) -> Optional[UserRecord]: - """Fetch user by email. Returns None if not found.""" + """Fetch user by email. Case-insensitive. Returns None if not found.""" async with self._lock: - user_id = self._email_index.get(email) + user_id = self._email_index.get(email.lower()) return self._users.get(user_id) if user_id else None async def get_by_id(self, user_id: str) -> Optional[UserRecord]: diff --git a/tests/test_auth_email_case.py b/tests/test_auth_email_case.py new file mode 100644 index 0000000..3e304c0 --- /dev/null +++ b/tests/test_auth_email_case.py @@ -0,0 +1,111 @@ +""" +Email case-insensitivity for user accounts. + +`PostgresUserRepository` stores emails lowercase and looks them up with +`LOWER(email) = LOWER($1)`, so "Alice@example.com" and "alice@example.com" +are the same account. `InMemoryUserRepository` - the default for local +development and the test suite - must behave the same way, otherwise +signup/login semantics silently change depending on whether DATABASE_URL +is set. +""" +import pytest +from fastapi.testclient import TestClient + +from api.app import create_app +from core.config import AppSettings +from core.errors import ConflictError +from repositories.interfaces import UserRecord +from repositories.memory import InMemoryUserRepository +from services.auth_service import AuthService + + +def _user(user_id="user_1", email="Alice@Example.com"): + return UserRecord( + user_id=user_id, + email=email, + password_hash="hash", + user_type="candidate", + ) + + +class TestInMemoryUserRepositoryEmailCase: + @pytest.mark.asyncio + async def test_save_stores_email_lowercase(self): + repo = InMemoryUserRepository() + stored = await repo.save(_user()) + assert stored.email == "alice@example.com" + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "lookup", ["alice@example.com", "ALICE@EXAMPLE.COM", "Alice@Example.com"] + ) + async def test_get_by_email_is_case_insensitive(self, lookup): + repo = InMemoryUserRepository() + await repo.save(_user()) + found = await repo.get_by_email(lookup) + assert found is not None + assert found.user_id == "user_1" + + @pytest.mark.asyncio + async def test_get_by_email_unknown_still_returns_none(self): + repo = InMemoryUserRepository() + await repo.save(_user()) + assert await repo.get_by_email("bob@example.com") is None + + +class TestAuthServiceEmailCase: + @pytest.fixture + def service(self): + return AuthService(user_repository=InMemoryUserRepository(), settings=AppSettings()) + + @pytest.mark.asyncio + async def test_login_accepts_different_casing_from_signup(self, service): + signed_up, _, _ = await service.signup( + email="Alice@Example.com", password="password123", user_type="candidate" + ) + logged_in, _, _ = await service.login(email="alice@example.com", password="password123") + assert logged_in.user_id == signed_up.user_id + + @pytest.mark.asyncio + async def test_signup_rejects_same_email_with_different_casing(self, service): + await service.signup( + email="alice@example.com", password="password123", user_type="candidate" + ) + with pytest.raises(ConflictError): + await service.signup( + email="ALICE@example.com", password="password123", user_type="recruiter" + ) + + +class TestAuthRoutesEmailCase: + @pytest.fixture + def client(self): + with TestClient(create_app()) as c: + yield c + + def test_signup_then_login_with_different_casing(self, client): + signup = client.post( + "/auth/signup", + json={"email": "Alice@Example.com", "password": "password123", "user_type": "candidate"}, + ) + assert signup.status_code == 200, signup.text + assert signup.json()["user"]["email"] == "alice@example.com" + + login = client.post( + "/auth/login", json={"email": "alice@example.com", "password": "password123"} + ) + assert login.status_code == 200, login.text + assert login.json()["user"]["user_id"] == signup.json()["user"]["user_id"] + + def test_duplicate_signup_with_different_casing_conflicts(self, client): + first = client.post( + "/auth/signup", + json={"email": "alice@example.com", "password": "password123", "user_type": "candidate"}, + ) + assert first.status_code == 200, first.text + + second = client.post( + "/auth/signup", + json={"email": "ALICE@example.com", "password": "password123", "user_type": "candidate"}, + ) + assert second.status_code == 409, second.text From 583addb4746a667bc38f0d01a82ba8c75868d9c7 Mon Sep 17 00:00:00 2001 From: Team Gaya Date: Tue, 20 Oct 2026 00:27:33 +0530 Subject: [PATCH 2/3] fix: drop stale email index entry when a user's email changes Saving an existing user_id with a new email left the old address in _email_index, so get_by_email still resolved it. Remove the previous entry when it points to this user, matching the Postgres behaviour. --- repositories/memory.py | 5 +++++ tests/test_auth_email_case.py | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/repositories/memory.py b/repositories/memory.py index 1097ced..05b9aba 100644 --- a/repositories/memory.py +++ b/repositories/memory.py @@ -438,6 +438,11 @@ async def save(self, record: UserRecord) -> UserRecord: } ) self._users[record.user_id] = stored + # Drop the old index entry on an email change, so the previous + # address stops resolving to this user (as it would in Postgres). + if existing is not None and existing.email != email: + if self._email_index.get(existing.email) == record.user_id: + del self._email_index[existing.email] self._email_index[email] = record.user_id return stored diff --git a/tests/test_auth_email_case.py b/tests/test_auth_email_case.py index 3e304c0..7efd73a 100644 --- a/tests/test_auth_email_case.py +++ b/tests/test_auth_email_case.py @@ -46,6 +46,16 @@ async def test_get_by_email_is_case_insensitive(self, lookup): assert found is not None assert found.user_id == "user_1" + @pytest.mark.asyncio + async def test_changing_email_stops_old_email_resolving(self): + repo = InMemoryUserRepository() + await repo.save(_user()) + await repo.save(_user(email="Alice.New@Example.com")) + assert await repo.get_by_email("alice@example.com") is None + found = await repo.get_by_email("alice.new@example.com") + assert found is not None + assert found.user_id == "user_1" + @pytest.mark.asyncio async def test_get_by_email_unknown_still_returns_none(self): repo = InMemoryUserRepository() From e7a8208a9c1cbdec0a6d3454bd6369c71358f8ee Mon Sep 17 00:00:00 2001 From: Siddhartha Kushwaha Date: Wed, 28 Oct 2026 09:43:18 +0530 Subject: [PATCH 3/3] fix: resolve merge damage in InMemoryUserRepository (lowercase emails + deep-copy isolation) --- repositories/memory.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/repositories/memory.py b/repositories/memory.py index b3f773f..1946c8b 100644 --- a/repositories/memory.py +++ b/repositories/memory.py @@ -453,11 +453,12 @@ async def save(self, record: UserRecord) -> UserRecord: created_at = existing.created_at if existing else record.created_at email = record.email.lower() stored = record.model_copy( + deep=True, update={ "email": email, "created_at": created_at, "updated_at": datetime.now(timezone.utc), - } + }, ) self._users[record.user_id] = stored # Drop the old index entry on an email change, so the previous @@ -466,20 +467,12 @@ async def save(self, record: UserRecord) -> UserRecord: if self._email_index.get(existing.email) == record.user_id: del self._email_index[existing.email] self._email_index[email] = record.user_id - return stored - deep=True, - update={"created_at": created_at, "updated_at": datetime.now(timezone.utc)}, - ) - self._users[record.user_id] = stored - self._email_index[record.email] = record.user_id return stored.model_copy(deep=True) async def get_by_email(self, email: str) -> Optional[UserRecord]: """Fetch user by email. Case-insensitive. Returns None if not found.""" async with self._lock: user_id = self._email_index.get(email.lower()) - return self._users.get(user_id) if user_id else None - user_id = self._email_index.get(email) stored = self._users.get(user_id) if user_id else None return stored.model_copy(deep=True) if stored is not None else None