88197060de
Re-checked every item of the audit's own outcome section against the tree.
Most held, but five items marked fixed had residual gaps — one of them a
live IDOR — and the deferred list was untouched.
Security:
- Analytics IDOR: /api/analytics/{ws}/overview and /projection took
child_id as an unchecked query param, and get_overview called
get_days_left_at_age_4 without workspace_id, so the ownership guard
never ran. Any member could read another workspace's child projection.
Fixed at both layers.
- Scraper: session ids no longer logged at INFO; a persist-callback
failure's raw exception text and the FK maintenance banner's scraped
text no longer reach the poll client.
- Email is now case-normalised at the API boundary, with migration 009
lowercasing existing rows (aborts naming colliding rows rather than
failing opaquely on the UNIQUE constraint).
Frontend correctness:
- usePlanProposal/usePlanSync gained the stale-response guard the other
hooks already had.
- PlanSyncProvider no longer fires POST /plan/sync before auth resolves
off a blindly-read localStorage workspaceId.
- Busy flags are cleared unconditionally across all 16 useLatestRequest
consumers. setBusy(true) was unconditional while the clear was guarded
by isCurrent, so a superseded call stranded its flag forever — under
StrictMode this hung every in-app navigation behind the PageSkeleton.
isCurrent decides which response's data wins, never whether a call
releases the flag it raised.
Performance:
- Calendar no longer blanks on a mutation, and a multi-day save issues N
writes plus one background refetch instead of 2N requests.
- take_pl_on_red_days moved onto GET /auth/context, dropping a redundant
GET /workspace/:id from every cold load.
CI and repo hygiene: least-privilege permissions block, actions pinned to
commit SHAs, npm ci, uv sync --locked, failure-only artifact upload,
dependabot; dead frontend/out.js removed; CSP added to the nginx template
(repeated into the location blocks that set their own add_header, since
nginx does not merge them across levels).
Left deferred by decision: refresh-token revocation, the phase-2 contract
change, M4, M5, L2, and H12's cross-route cache. Details and the smaller
follow-ups browser verification turned up are in the audit report.
Backend 901 passed, coverage 92%. Frontend 1322 tests, coverage
98.17/94.79/92.14/98.17.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PngVF38MLpdkgXcByKfdW6
151 lines
5.3 KiB
Python
151 lines
5.3 KiB
Python
"""HTTP routes for auth: register, login, logout, me, refresh."""
|
|
|
|
from fastapi import APIRouter, Cookie, HTTPException, Response, status
|
|
from pydantic import BaseModel
|
|
from starlette.requests import Request
|
|
|
|
from app.config import settings
|
|
from app.dependencies import (
|
|
AuthServiceDep,
|
|
ChildRepositoryDep,
|
|
CurrentUserDep,
|
|
PersonalDataRepositoryDep,
|
|
WorkspaceRepositoryDep,
|
|
)
|
|
from app.rate_limit import limiter
|
|
from app.models.auth import LoginRequest, RegisterRequest, TokenResponse, UserMeResponse
|
|
from app.utils.errors import AuthError, ConflictError, InvitationError, UnauthorizedError
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
_REFRESH_COOKIE = "refresh_token"
|
|
_ACCESS_EXPIRES_IN = settings.jwt_access_token_expire_minutes * 60
|
|
|
|
|
|
@router.post("/register", response_model=TokenResponse, status_code=status.HTTP_201_CREATED)
|
|
@limiter.limit("10/minute")
|
|
async def register(
|
|
request: Request, payload: RegisterRequest, response: Response, service: AuthServiceDep
|
|
) -> TokenResponse:
|
|
try:
|
|
user, _pd = await service.register(
|
|
email=str(payload.email),
|
|
password=payload.password,
|
|
display_name=payload.display_name,
|
|
invite_token=payload.invite_token,
|
|
)
|
|
except ConflictError as exc:
|
|
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
|
|
except InvitationError as exc:
|
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
|
|
|
access = service.create_access_token(user.id)
|
|
refresh = service.create_refresh_token(user.id)
|
|
_set_refresh_cookie(response, refresh)
|
|
return TokenResponse(access_token=access, expires_in=_ACCESS_EXPIRES_IN)
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse)
|
|
@limiter.limit("10/minute")
|
|
async def login(
|
|
request: Request, payload: LoginRequest, response: Response, service: AuthServiceDep
|
|
) -> TokenResponse:
|
|
try:
|
|
user = await service.login(str(payload.email), payload.password)
|
|
except AuthError as exc:
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, str(exc)) from exc
|
|
|
|
access = service.create_access_token(user.id)
|
|
refresh = service.create_refresh_token(user.id)
|
|
_set_refresh_cookie(response, refresh)
|
|
return TokenResponse(access_token=access, expires_in=_ACCESS_EXPIRES_IN)
|
|
|
|
|
|
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def logout(response: Response) -> None:
|
|
response.delete_cookie(_REFRESH_COOKIE)
|
|
|
|
|
|
@router.post("/refresh", response_model=TokenResponse)
|
|
@limiter.limit("30/minute")
|
|
async def refresh(
|
|
request: Request,
|
|
response: Response,
|
|
service: AuthServiceDep,
|
|
refresh_token: str | None = Cookie(default=None, alias=_REFRESH_COOKIE),
|
|
) -> TokenResponse:
|
|
if not refresh_token:
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "No refresh token")
|
|
try:
|
|
access = await service.refresh_access_token(refresh_token)
|
|
except UnauthorizedError as exc:
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, str(exc)) from exc
|
|
return TokenResponse(access_token=access, expires_in=_ACCESS_EXPIRES_IN)
|
|
|
|
|
|
@router.get("/me", response_model=UserMeResponse)
|
|
async def me(current_user: CurrentUserDep) -> UserMeResponse:
|
|
# PersonalData is fetched separately when workspace context is needed.
|
|
# Here we return just the user-level data.
|
|
return UserMeResponse(
|
|
id=str(current_user.id),
|
|
email=current_user.email,
|
|
display_name="", # enriched by the frontend via workspace API
|
|
workspace_id=None, # client fetches via /api/workspace after login
|
|
)
|
|
|
|
|
|
class _ChildContext(BaseModel):
|
|
id: str
|
|
name: str
|
|
birth_date: str
|
|
|
|
|
|
class _UserContext(BaseModel):
|
|
personal_data_uuid: str
|
|
workspace_id: str
|
|
parent_name: str
|
|
children: list[_ChildContext]
|
|
# Mirrors `WorkspaceResponse.take_pl_on_red_days` — included here so the
|
|
# frontend's cold-load `refreshContext()` can build its `workspace`
|
|
# state from this response alone, without a follow-up `GET
|
|
# /workspace/:id` (see AGENTS.md H12 step 1).
|
|
take_pl_on_red_days: bool
|
|
|
|
|
|
@router.get("/context", response_model=_UserContext)
|
|
async def get_context(
|
|
current_user: CurrentUserDep,
|
|
pd_repo: PersonalDataRepositoryDep,
|
|
child_repo: ChildRepositoryDep,
|
|
ws_repo: WorkspaceRepositoryDep,
|
|
) -> _UserContext:
|
|
"""Return workspace + children for the current user. Used by the dev harness."""
|
|
pd = await pd_repo.get_by_id(current_user.personal_data_uuid)
|
|
if pd is None:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "No parent profile found")
|
|
children = await child_repo.list_by_workspace(pd.workspace_id)
|
|
workspace = await ws_repo.get_by_id(pd.workspace_id)
|
|
if workspace is None:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "No workspace found")
|
|
return _UserContext(
|
|
personal_data_uuid=str(pd.uuid),
|
|
workspace_id=str(pd.workspace_id),
|
|
parent_name=pd.name,
|
|
children=[
|
|
_ChildContext(id=str(c.id), name=c.name, birth_date=str(c.birth_date)) for c in children
|
|
],
|
|
take_pl_on_red_days=workspace.take_pl_on_red_days,
|
|
)
|
|
|
|
|
|
def _set_refresh_cookie(response: Response, token: str) -> None:
|
|
response.set_cookie(
|
|
key=_REFRESH_COOKIE,
|
|
value=token,
|
|
httponly=True,
|
|
secure=True,
|
|
samesite="lax",
|
|
max_age=settings.jwt_refresh_token_expire_days * 86400,
|
|
)
|