Coverage for app / dependency / workspace.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""The workspace a request is made in (``app/services/workspace.py``). 

2 

3fe-core names it on every request — ``?workspace=personal`` / 

4``organisation:<id>`` / ``project:<id>`` — because every page shows exactly 

5one workspace. Lists read it as a parameter of their own; this captures it 

6once per request (``capture_workspace``, a dependency of the whole ``/app`` 

7router) for the paths that create something, so what is made on a page 

8belongs to the workspace the page is showing (``owner_for``). 

9 

10A context variable rather than a parameter on each create path, of which 

11there are thirty-odd, several deep in a generative flow that builds rows 

12directly: the dependency runs in the request's own context, which a sync 

13endpoint's thread inherits. 

14""" 

15 

16from __future__ import annotations 

17 

18from contextvars import ContextVar 

19from typing import Any 

20 

21from fastapi import Query 

22from sqlalchemy.orm import Session 

23 

24_REQUESTED: ContextVar[str | None] = ContextVar("requested_workspace", default=None) 

25 

26 

27async def capture_workspace( 

28 workspace: str | None = Query(default=None, include_in_schema=False), 

29) -> None: 

30 _REQUESTED.set(workspace or None) 

31 

32 

33def requested_workspace() -> str | None: 

34 """The workspace key this request named, if any.""" 

35 return _REQUESTED.get() 

36 

37 

38def request_workspace(db: Session, user: Any): 

39 """The workspace this request was made in, resolved — the caller must 

40 belong to it — and Personal when it names none.""" 

41 from app.services import workspace as workspace_service 

42 

43 return workspace_service.resolve( 

44 db, requested_workspace() or workspace_service.PERSONAL, user 

45 ) 

46 

47 

48def owner_for(db: Session, user: Any, *, model: type) -> dict[str, Any]: 

49 """Owner columns for a ``model`` that ``user`` creates without naming an 

50 owner: the workspace the request was made in — checked that they belong 

51 to it and may create one there (``verify_owner_scope``) — or their 

52 personal workspace when the request names none.""" 

53 from app.dependency.resource_access import verify_owner_scope 

54 from app.services import workspace as workspace_service 

55 

56 key = requested_workspace() 

57 if not key: 

58 return { 

59 "owner_user_id": user.id, 

60 "owner_organisation_id": None, 

61 "owner_project_id": None, 

62 } 

63 owner = workspace_service.resolve(db, key, user).owner_columns() 

64 verify_owner_scope(owner, user, db, model=model) 

65 return owner