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:
+126
-2
@@ -10,13 +10,17 @@ Pattern (copy for each new entity):
|
||||
4. `<Entity>ServiceDep` — Annotated type alias
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
import aiosqlite
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.config import settings
|
||||
from app.entities.child import Child
|
||||
from app.entities.personal_data import PersonalData
|
||||
from app.entities.user import User
|
||||
from app.repositories.child_repository import ChildRepository
|
||||
from app.repositories.day_override_repository import DayOverrideRepository
|
||||
@@ -25,6 +29,7 @@ from app.repositories.parental_leave_repository import ParentalLeaveRepository
|
||||
from app.repositories.personal_data_repository import PersonalDataRepository
|
||||
from app.repositories.planned_leave_repository import PlannedLeaveRepository
|
||||
from app.repositories.tip_dismissal_repository import TipDismissalRepository
|
||||
from app.repositories.unit_of_work import UnitOfWork
|
||||
from app.repositories.user_repository import UserRepository
|
||||
from app.repositories.vacation_days_repository import VacationDaysRepository
|
||||
from app.repositories.workspace_repository import (
|
||||
@@ -38,6 +43,7 @@ from app.repositories_impl.sqlite.parental_leave_repository import SQLiteParenta
|
||||
from app.repositories_impl.sqlite.personal_data_repository import SQLitePersonalDataRepository
|
||||
from app.repositories_impl.sqlite.planned_leave_repository import SQLitePlannedLeaveRepository
|
||||
from app.repositories_impl.sqlite.tip_dismissal_repository import SQLiteTipDismissalRepository
|
||||
from app.repositories_impl.sqlite.unit_of_work import SQLiteUnitOfWork
|
||||
from app.repositories_impl.sqlite.user_repository import SQLiteUserRepository
|
||||
from app.repositories_impl.sqlite.vacation_days_repository import SQLiteVacationDaysRepository
|
||||
from app.repositories_impl.sqlite.workspace_repository import (
|
||||
@@ -74,6 +80,15 @@ def get_connection(request: Request) -> aiosqlite.Connection:
|
||||
ConnectionDep = Annotated[aiosqlite.Connection, Depends(get_connection)]
|
||||
|
||||
|
||||
def get_unit_of_work(conn: ConnectionDep) -> UnitOfWork:
|
||||
if settings.database_type == "sqlite":
|
||||
return SQLiteUnitOfWork(conn)
|
||||
raise ValueError(f"Unsupported database_type: {settings.database_type}")
|
||||
|
||||
|
||||
UnitOfWorkDep = Annotated[UnitOfWork, Depends(get_unit_of_work)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Repository factories
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -196,8 +211,9 @@ def get_auth_service(
|
||||
user_repo: UserRepositoryDep,
|
||||
pd_repo: PersonalDataRepositoryDep,
|
||||
ws_repo: WorkspaceRepositoryDep,
|
||||
uow: UnitOfWorkDep,
|
||||
) -> AuthService:
|
||||
return AuthService(user_repo, pd_repo, ws_repo)
|
||||
return AuthService(user_repo, pd_repo, ws_repo, uow=uow)
|
||||
|
||||
|
||||
AuthServiceDep = Annotated[AuthService, Depends(get_auth_service)]
|
||||
@@ -282,6 +298,7 @@ def get_workspace_service(
|
||||
planned_leave_repo: PlannedLeaveRepositoryDep,
|
||||
parental_leave_repo: ParentalLeaveRepositoryDep,
|
||||
vacation_days_repo: VacationDaysRepositoryDep,
|
||||
uow: UnitOfWorkDep,
|
||||
) -> WorkspaceService:
|
||||
return WorkspaceService(
|
||||
ws_repo,
|
||||
@@ -292,6 +309,7 @@ def get_workspace_service(
|
||||
planned_leave_repo,
|
||||
parental_leave_repo,
|
||||
vacation_days_repo,
|
||||
uow=uow,
|
||||
)
|
||||
|
||||
|
||||
@@ -349,9 +367,15 @@ def get_planning_service(
|
||||
parental_leave_repo: ParentalLeaveRepositoryDep,
|
||||
vacation_repo: VacationDaysRepositoryDep,
|
||||
planning_engine_service: PlanningEngineServiceDep,
|
||||
uow: UnitOfWorkDep,
|
||||
) -> PlanningService:
|
||||
return PlanningService(
|
||||
repo, analytics_service, parental_leave_repo, vacation_repo, planning_engine_service
|
||||
repo,
|
||||
analytics_service,
|
||||
parental_leave_repo,
|
||||
vacation_repo,
|
||||
planning_engine_service,
|
||||
uow=uow,
|
||||
)
|
||||
|
||||
|
||||
@@ -377,3 +401,103 @@ async def get_current_user(
|
||||
|
||||
|
||||
CurrentUserDep = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tenant scoping
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# Rule of thumb: identity-derived facts (which workspace the caller belongs
|
||||
# to) live here in the DI layer; entity-ownership checks that require loading
|
||||
# a row (e.g. a leave wish's own workspace_id) live in the service, mirroring
|
||||
# `WorkspaceService._get_member`. Routers stay thin: they hand the resolved
|
||||
# scope to the service and let a NotFoundError become a 404 — never a 403,
|
||||
# so a foreign id never confirms its own existence. See the T1 authz audit,
|
||||
# §3 "Scoping primitive — design for app/dependencies.py".
|
||||
|
||||
|
||||
async def get_current_personal_data(
|
||||
current_user: CurrentUserDep, pd_repo: PersonalDataRepositoryDep
|
||||
) -> PersonalData:
|
||||
"""The caller's own PersonalData row — the root of tenant scoping."""
|
||||
pd = await pd_repo.get_by_id(current_user.personal_data_uuid)
|
||||
if pd is None or pd.deleted_at is not None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "No parent profile for this account")
|
||||
return pd
|
||||
|
||||
|
||||
CurrentPersonalDataDep = Annotated[PersonalData, Depends(get_current_personal_data)]
|
||||
|
||||
|
||||
async def get_current_workspace_id(pd: CurrentPersonalDataDep) -> UUID:
|
||||
return pd.workspace_id
|
||||
|
||||
|
||||
CurrentWorkspaceIdDep = Annotated[UUID, Depends(get_current_workspace_id)]
|
||||
|
||||
|
||||
def _not_found(kind: str, id_: UUID) -> HTTPException:
|
||||
# 404, never 403: do not confirm that a foreign id exists.
|
||||
return HTTPException(status.HTTP_404_NOT_FOUND, f"{kind} {id_} not found")
|
||||
|
||||
|
||||
async def require_workspace_access(workspace_id: UUID, current: CurrentWorkspaceIdDep) -> UUID:
|
||||
"""Path-param guard for `/{workspace_id}/...` routes.
|
||||
|
||||
FastAPI binds the `workspace_id` path param by name, so a router only
|
||||
has to declare `workspace_id: WorkspaceIdDep` in place of `UUID` to get
|
||||
this check for free.
|
||||
"""
|
||||
if workspace_id != current:
|
||||
raise _not_found("Workspace", workspace_id)
|
||||
return workspace_id
|
||||
|
||||
|
||||
WorkspaceIdDep = Annotated[UUID, Depends(require_workspace_access)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkspaceScope:
|
||||
"""The caller's tenant, plus helpers for ids arriving in a body/query.
|
||||
|
||||
`check_workspace` is a cheap identity comparison (no DB read — the
|
||||
caller's own workspace_id is already known). `check_child`/`check_member`
|
||||
load the row because ownership can only be known after the load; both
|
||||
404 (never 403) on a missing OR foreign-workspace id, so a foreign id can
|
||||
never be distinguished from a nonexistent one.
|
||||
"""
|
||||
|
||||
workspace_id: UUID
|
||||
personal_data_uuid: UUID
|
||||
user_id: UUID
|
||||
_child_repo: ChildRepository
|
||||
_pd_repo: PersonalDataRepository
|
||||
|
||||
def check_workspace(self, workspace_id: UUID) -> UUID:
|
||||
if workspace_id != self.workspace_id:
|
||||
raise _not_found("Workspace", workspace_id)
|
||||
return workspace_id
|
||||
|
||||
async def check_child(self, child_id: UUID) -> Child:
|
||||
child = await self._child_repo.get_by_id(child_id)
|
||||
if child is None or child.workspace_id != self.workspace_id:
|
||||
raise _not_found("Child", child_id)
|
||||
return child
|
||||
|
||||
async def check_member(self, personal_data_uuid: UUID) -> PersonalData:
|
||||
pd = await self._pd_repo.get_by_id(personal_data_uuid)
|
||||
if pd is None or pd.deleted_at is not None or pd.workspace_id != self.workspace_id:
|
||||
raise _not_found("PersonalData", personal_data_uuid)
|
||||
return pd
|
||||
|
||||
|
||||
async def get_workspace_scope(
|
||||
current_user: CurrentUserDep,
|
||||
pd: CurrentPersonalDataDep,
|
||||
child_repo: ChildRepositoryDep,
|
||||
pd_repo: PersonalDataRepositoryDep,
|
||||
) -> WorkspaceScope:
|
||||
return WorkspaceScope(pd.workspace_id, pd.uuid, current_user.id, child_repo, pd_repo)
|
||||
|
||||
|
||||
WorkspaceScopeDep = Annotated[WorkspaceScope, Depends(get_workspace_scope)]
|
||||
|
||||
Reference in New Issue
Block a user