Files
F-r-ldraledigplannerare/backend/tests/unit/test_services/test_auth_service.py
T
jacobh2 02db5430eb Harden the API and the data layer after a security and performance audit
Security
- Every route now requires a login and refuses ids outside the caller's
  workspace with 404: plan, leave-wishes, day-overrides and vacation-days
  were fully anonymous; every other router trusted client-supplied
  workspace/child/parent ids. Scraper sessions are bound to their owner.
- Invitations can no longer be created for a foreign workspace, and a
  redeemer who is already a member (or a full workspace) is refused.
- Production refuses the default JWT secret; API docs are hidden in
  production; a failed migration aborts startup instead of serving.
- Login and register no longer reveal whether an email exists; inactive
  accounts are rejected; /auth/refresh is rate limited.
- The FK scraper writes debug artefacts only when explicitly enabled,
  logs no scraped values or page text, clears the BankID QR as soon as it
  is scanned and purges finished sessions after five minutes.
- Real FK page captures are removed from the tree (history rewrite
  follows); the parser tests use a synthetic fixture.

Performance and correctness
- Plan apply/sync run inside one locked transaction with batched writes
  instead of one commit per row, so a failure mid-batch leaves nothing
  half-applied and concurrent syncs no longer corrupt each other.
- SQLite runs in WAL mode with a busy timeout; 14 indexes cover the
  filters that were full scans; argon2 hashing runs off the event loop;
  responses are gzipped.
- Frontend: a 401 now refreshes the token once and retries, so sessions
  no longer die silently after 15 minutes; every data hook discards
  stale responses; logout clears state even when the server call fails.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CsXCCcDfmV4Sps4ZQSvNEY
2026-09-18 07:54:21 +02:00

107 lines
4.9 KiB
Python

"""Tests for AuthService: register, login, token round-trip."""
import pytest
from app.repositories_impl.sqlite.user_repository import SQLiteUserRepository
from app.services.auth_service import AuthService
from app.utils.errors import AuthError, ConflictError, UnauthorizedError
class TestAuthServiceRegisterLogin:
async def test_register_creates_user_and_personal_data(self, auth_service: AuthService) -> None:
user, pd = await auth_service.register("alice@example.com", "securepassword", "Alice")
assert user.email == "alice@example.com"
assert pd.name == "Alice"
assert user.personal_data_uuid == pd.uuid
async def test_register_duplicate_email_raises_conflict(
self, auth_service: AuthService
) -> None:
await auth_service.register("bob@example.com", "password123", "Bob")
with pytest.raises(ConflictError):
await auth_service.register("bob@example.com", "otherpass", "Bob2")
async def test_login_success(self, auth_service: AuthService) -> None:
await auth_service.register("carol@example.com", "mypassword", "Carol")
user = await auth_service.login("carol@example.com", "mypassword")
assert user.email == "carol@example.com"
async def test_login_wrong_password_raises(self, auth_service: AuthService) -> None:
await auth_service.register("dave@example.com", "correctpass", "Dave")
with pytest.raises(AuthError):
await auth_service.login("dave@example.com", "wrongpass")
async def test_login_unknown_email_raises(self, auth_service: AuthService) -> None:
with pytest.raises(AuthError):
await auth_service.login("nobody@example.com", "anything")
async def test_register_conflict_message_is_generic(self, auth_service: AuthService) -> None:
await auth_service.register("henry@example.com", "password123", "Henry")
with pytest.raises(ConflictError) as exc_info:
await auth_service.register("henry@example.com", "otherpass", "Henry2")
assert "henry@example.com" not in str(exc_info.value)
assert str(exc_info.value) == "Email already registered"
async def test_login_wrong_password_and_unknown_email_share_message(
self, auth_service: AuthService
) -> None:
await auth_service.register("ivy@example.com", "correctpass", "Ivy")
with pytest.raises(AuthError) as wrong_password:
await auth_service.login("ivy@example.com", "wrongpass")
with pytest.raises(AuthError) as unknown_email:
await auth_service.login("nobody2@example.com", "anything")
assert str(wrong_password.value) == str(unknown_email.value)
async def test_login_inactive_account_raises_unauthorized(
self,
auth_service: AuthService,
user_repo: SQLiteUserRepository,
) -> None:
user, _ = await auth_service.register("jack@example.com", "password123", "Jack")
user.is_active = False
await user_repo.update(user.id, user)
with pytest.raises(UnauthorizedError):
await auth_service.login("jack@example.com", "password123")
class TestAuthServiceTokens:
async def test_access_token_round_trip(self, auth_service: AuthService) -> None:
user, _ = await auth_service.register("eve@example.com", "pass1234", "Eve")
token = auth_service.create_access_token(user.id)
decoded_user = await auth_service.get_user_from_token(token)
assert decoded_user.id == user.id
async def test_refresh_token_issues_new_access_token(self, auth_service: AuthService) -> None:
user, _ = await auth_service.register("frank@example.com", "pass5678", "Frank")
refresh = auth_service.create_refresh_token(user.id)
access = await auth_service.refresh_access_token(refresh)
decoded = await auth_service.get_user_from_token(access)
assert decoded.id == user.id
async def test_using_refresh_as_access_raises_unauthorized(
self, auth_service: AuthService
) -> None:
user, _ = await auth_service.register("grace@example.com", "pass9012", "Grace")
refresh = auth_service.create_refresh_token(user.id)
with pytest.raises(UnauthorizedError):
await auth_service.get_user_from_token(refresh)
async def test_invalid_token_raises_unauthorized(self, auth_service: AuthService) -> None:
with pytest.raises(UnauthorizedError):
await auth_service.get_user_from_token("not.a.valid.jwt")
async def test_token_for_inactive_user_raises_unauthorized(
self,
auth_service: AuthService,
user_repo: SQLiteUserRepository,
) -> None:
user, _ = await auth_service.register("heidi@example.com", "pass3456", "Heidi")
token = auth_service.create_access_token(user.id)
user.is_active = False
await user_repo.update(user.id, user)
with pytest.raises(UnauthorizedError):
await auth_service.get_user_from_token(token)