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
This commit is contained in:
@@ -5,8 +5,9 @@ Covers workspace creation/update, with a focus on the `planning_mode` field
|
||||
renaming/removing a placeholder partner (`rename_member` / `remove_member`).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from datetime import date, datetime
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -21,10 +22,33 @@ from app.repositories_impl.sqlite.planned_leave_repository import SQLitePlannedL
|
||||
from app.repositories_impl.sqlite.user_repository import SQLiteUserRepository
|
||||
from app.repositories_impl.sqlite.vacation_days_repository import SQLiteVacationDaysRepository
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
from app.utils.errors import NotFoundError, ValidationError
|
||||
from app.utils.errors import InvitationError, NotFoundError, ValidationError
|
||||
from tests.conftest import SeededIds
|
||||
|
||||
|
||||
def _hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
async def _make_inviter(user_repo: SQLiteUserRepository, personal_data_uuid: UUID) -> UUID:
|
||||
"""`workspace_invitation.invited_by_user_id` FKs to a real `user` row,
|
||||
which itself FKs to a real `personal_data` row — a bare `uuid4()` fails
|
||||
both constraints, so tests that create an invitation attribute it to a
|
||||
user backed by an already-seeded `PersonalData` row (`user.personal_
|
||||
data_uuid` is UNIQUE, so this only works once per `personal_data_uuid`
|
||||
per test)."""
|
||||
user = await user_repo.create(
|
||||
User(
|
||||
id=uuid4(),
|
||||
personal_data_uuid=personal_data_uuid,
|
||||
email=f"inviter-{uuid4()}@example.com",
|
||||
hashed_password="not-a-real-hash",
|
||||
created_at=datetime.now(),
|
||||
)
|
||||
)
|
||||
return user.id
|
||||
|
||||
|
||||
class TestWorkspacePlanningMode:
|
||||
"""Test planning_mode defaults and validation."""
|
||||
|
||||
@@ -328,3 +352,80 @@ class TestRemoveMember:
|
||||
await workspace_service.remove_member(
|
||||
seeded_ids.workspace_id, placeholder.uuid, seeded_ids.personal_data_uuid
|
||||
)
|
||||
|
||||
|
||||
class TestInvitationScoping:
|
||||
"""F2 (T1 authz audit): self-invitation used to grant full membership of
|
||||
any workspace whose id was known, and `revoke_invitation` was unscoped.
|
||||
"""
|
||||
|
||||
async def test_revoke_invitation_from_a_different_workspace_raises_not_found(
|
||||
self,
|
||||
workspace_service: WorkspaceService,
|
||||
seeded_ids: SeededIds,
|
||||
user_repo: SQLiteUserRepository,
|
||||
) -> None:
|
||||
"""An invitation belonging to workspace B must not be revocable by
|
||||
naming workspace A — closes F6/part of F2 (`revoke_invitation`
|
||||
gained a `workspace_id` argument)."""
|
||||
other_ws = await workspace_service.create_workspace("Other WS")
|
||||
token = await workspace_service.invite_partner(
|
||||
other_ws.id, await _make_inviter(user_repo, seeded_ids.personal_data_uuid)
|
||||
)
|
||||
inv = await workspace_service._inv.get_by_token_hash(_hash(token))
|
||||
assert inv is not None
|
||||
|
||||
# `seeded_ids.workspace_id` is NOT where the invitation lives.
|
||||
with pytest.raises(NotFoundError):
|
||||
await workspace_service.revoke_invitation(inv.id, seeded_ids.workspace_id)
|
||||
|
||||
async def test_revoke_invitation_from_its_own_workspace_succeeds(
|
||||
self,
|
||||
workspace_service: WorkspaceService,
|
||||
seeded_ids: SeededIds,
|
||||
user_repo: SQLiteUserRepository,
|
||||
) -> None:
|
||||
token = await workspace_service.invite_partner(
|
||||
seeded_ids.workspace_id, await _make_inviter(user_repo, seeded_ids.personal_data_uuid)
|
||||
)
|
||||
inv = await workspace_service._inv.get_by_token_hash(_hash(token))
|
||||
assert inv is not None
|
||||
await workspace_service.revoke_invitation(inv.id, seeded_ids.workspace_id)
|
||||
|
||||
refreshed = await workspace_service._inv.get_by_id(inv.id)
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == "revoked"
|
||||
|
||||
async def test_redeem_refuses_when_already_a_member_of_the_target_workspace(
|
||||
self,
|
||||
workspace_service: WorkspaceService,
|
||||
seeded_ids: SeededIds,
|
||||
user_repo: SQLiteUserRepository,
|
||||
) -> None:
|
||||
"""The exploit from F2: a caller who is ALREADY a member of a
|
||||
workspace could invite themselves and "redeem" their own invite,
|
||||
confirming nothing new but exercising a codepath that must still be
|
||||
closed for a caller re-redeeming while already a member."""
|
||||
token = await workspace_service.invite_partner(
|
||||
seeded_ids.workspace_id, await _make_inviter(user_repo, seeded_ids.personal_data_uuid)
|
||||
)
|
||||
with pytest.raises(InvitationError, match="already belong"):
|
||||
await workspace_service.redeem_invitation(token, seeded_ids.personal_data_uuid)
|
||||
|
||||
async def test_redeem_refuses_when_workspace_already_has_two_members(
|
||||
self,
|
||||
workspace_service: WorkspaceService,
|
||||
seeded_ids: SeededIds,
|
||||
user_repo: SQLiteUserRepository,
|
||||
) -> None:
|
||||
# Fill the target workspace to its 2-member cap first.
|
||||
await workspace_service.add_placeholder_parent(seeded_ids.workspace_id, "Partner")
|
||||
|
||||
other_ws = await workspace_service.create_workspace("Other WS")
|
||||
other_pd = await workspace_service.add_placeholder_parent(other_ws.id, "Redeemer")
|
||||
|
||||
token = await workspace_service.invite_partner(
|
||||
seeded_ids.workspace_id, await _make_inviter(user_repo, seeded_ids.personal_data_uuid)
|
||||
)
|
||||
with pytest.raises(InvitationError, match="maximum number of members"):
|
||||
await workspace_service.redeem_invitation(token, other_pd.uuid)
|
||||
|
||||
Reference in New Issue
Block a user