Open-source personal finance manager. Self-hosted, privacy-first.
fix: gate the write routes that were reachable read-only (#613)
Tássio Noronha0133385c9476
diff --git a/backend/app/agents/api/chat.py b/backend/app/agents/api/chat.pyindex a15e2ee2..91f2dbc4 100644--- a/backend/app/agents/api/chat.py+++ b/backend/app/agents/api/chat.py@@ -20,7 +20,7 @@ from app.agents.runtime.executor import AgentExecutor, ExecutorEventfrom app.agents.schemas.conversation import SendMessageRequestfrom app.agents.services import agent_service, conversation_servicefrom app.core.database import get_async_session-from app.core.workspace_context import WorkspaceContext, current_workspace+from app.core.workspace_context import WorkspaceContext, current_writable_workspacerouter = APIRouter(prefix="/api/agents", tags=["agents"])@@ -34,7 +34,18 @@ def _format_event(event: ExecutorEvent) -> bytes:async def chat(agent_id: uuid.UUID,body: SendMessageRequest,- ctx: WorkspaceContext = Depends(current_workspace),+ # Write-gated for what the agent can do on the caller's behalf, not for+ # the conversation row it persists. The tool set reachable from here+ # includes `propose_create_transaction` and its siblings, which write —+ # so a read-only member chatting could create financial data the HTTP+ # API would have refused them.+ #+ # This deliberately also blocks a viewer from *asking* questions, which+ # is a real use case (a read-only accountant reading the books). The way+ # to restore it is to make the tools role-aware so a viewer's session+ # only exposes the reading ones — not to drop this gate, which would+ # bring the write path back with it.+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)diff --git a/backend/app/agents/api/mcp_tokens.py b/backend/app/agents/api/mcp_tokens.pyindex d0ebf79d..20b91b51 100644--- a/backend/app/agents/api/mcp_tokens.py+++ b/backend/app/agents/api/mcp_tokens.py@@ -21,13 +21,22 @@ from fastapi import APIRouter, Depends, statusfrom app.agents.config import get_agent_settingsfrom app.agents.mcp.auth import mint_token-from app.core.workspace_context import WorkspaceContext, current_workspace+from app.core.workspace_context import WorkspaceContext, current_writable_workspacerouter = APIRouter(prefix="/api/agents/mcp-tokens", tags=["agents"])@router.post("", status_code=status.HTTP_201_CREATED)-async def create_mcp_token(ctx: WorkspaceContext = Depends(current_workspace)):+async def create_mcp_token(ctx: WorkspaceContext = Depends(current_writable_workspace)):+ """Mint a long-lived MCP token for an external client.++ Write-gated because of what the token can do, not because minting+ writes a row. It carries (user, workspace) to the MCP server, whose+ tool set includes `propose_create_transaction`, `propose_create_budget`+ and friends — all of which persist. Handing a read-only member a+ credential that writes would route around the gate the HTTP API+ enforces.+ """s = get_agent_settings()ttl_seconds = max(s.mcp_external_ttl_days, 1) * 86400token = mint_token(diff --git a/backend/app/api/connections.py b/backend/app/api/connections.pyindex 1b9e0b9e..7afe9906 100644--- a/backend/app/api/connections.py+++ b/backend/app/api/connections.py@@ -204,10 +204,15 @@ async def sync_connection(@router.post("/{connection_id}/reconnect-token", response_model=ReconnectTokenResponse)async def get_reconnect_token(connection_id: uuid.UUID,- ctx: WorkspaceContext = Depends(current_workspace),+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- """Get a connect token for reconnecting an errored/expired connection."""+ """Get a connect token for reconnecting an errored/expired connection.++ Write-gated: the token this hands out re-links a bank connection, which+ is the same capability `get_reauth_url` above grants and gates. A+ read-only member has no business minting one.+ """connection = await connection_service.get_connection(session, connection_id, ctx.workspace.id)if not connection:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connection not found")diff --git a/backend/app/api/import_transactions.py b/backend/app/api/import_transactions.pyindex 3dbd51a7..c575a56c 100644--- a/backend/app/api/import_transactions.py+++ b/backend/app/api/import_transactions.py@@ -27,6 +27,14 @@ async def preview_import(inflow_column: Optional[str] = Form(None),outflow_column: Optional[str] = Form(None),column_mapping: Optional[str] = Form(None),+ # Read-gated on purpose, and the exception is deliberate rather than an+ # oversight. This is a POST because it takes a file upload, not because+ # it changes anything: it parses the upload and returns what *would* be+ # imported. The only workspace data it touches is+ # `enrich_with_category_suggestions`, which SELECTs rules and categories+ # to label the preview. Nothing is persisted, so a read-only member+ # previewing a file is doing exactly what their role allows. The write+ # gate belongs on `POST /import` below, which is where the rows land.ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 3dbb4bde..335c1f29 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -276,6 +276,54 @@ async def admin_auth_headers(admin_auth_token: str) -> dict:return {"Authorization": f"Bearer {admin_auth_token}"}+@pytest_asyncio.fixture+async def viewer_auth_headers(+ session: AsyncSession, client: AsyncClient, test_workspace: Workspace+) -> dict:+ """A second user who is a `viewer` member of the test workspace.++ Read-only by role. Exists so the write gate can be exercised over HTTP:+ the enforcement is a dependency wrapper, so asserting it at the service+ layer alone leaves the wiring between route and role untested — which is+ exactly the gap that let an audit conclude the gate was missing when it+ was not.+ """+ import bcrypt as _bcrypt++ user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=_bcrypt.hashpw(b"viewerpass123", _bcrypt.gensalt()).decode(),+ is_active=True,+ is_superuser=False,+ is_verified=True,+ )+ session.add(user)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(),+ workspace_id=test_workspace.id,+ user_id=user.id,+ role="viewer",+ )+ )+ await session.commit()++ response = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "viewerpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert response.status_code == 200, f"Viewer login failed: {response.text}"+ return {+ "Authorization": f"Bearer {response.json()['access_token']}",+ # Explicit, because the viewer's *default* workspace resolution would+ # otherwise decide which workspace this request lands in.+ "X-Workspace-Id": str(test_workspace.id),+ }++@pytest_asyncio.fixtureasync def test_categories(session: AsyncSession, test_user: User) -> list[Category]:"""Create test categories."""diff --git a/backend/tests/test_write_permission_coverage.py b/backend/tests/test_write_permission_coverage.pynew file mode 100644index 00000000..b5d73d9b--- /dev/null+++ b/backend/tests/test_write_permission_coverage.py@@ -0,0 +1,173 @@+"""Every mutating route declares an explicit permission decision.++This is the test the codebase was missing, and the reason it was missing is+the reason it is worth having: the write gate is a **dependency wrapper**,+so `require_write` appears in one file and grepping the routes for it+returns nothing. An audit did exactly that and reported that none of the+111 write routes were gated, when 85 of them were. The claim propagated+into three documents before someone re-read the code by hand.++So this walks the dependency graph the way the framework does, and answers+the question mechanically instead of leaving it to memory.++**It asserts the property, not the mechanism.** The rule is "a mutating+route reaches some recognised permission decision", with the recognised set+in `WRITE_GATES` below. Permissions may later become per-action, per-module+or per-view; when a narrower guard exists, it is added to that set and this+test keeps holding. Phrasing it as "must depend on+`current_writable_workspace`" would make the test an obstacle to the very+change it should survive.+"""+import pytest+from fastapi.routing import APIRoute++from app.main import app++MUTATING = {"POST", "PATCH", "PUT", "DELETE"}++#: Dependencies that constitute a workspace write decision. Add to this set+#: when a narrower gate is introduced — never loosen the assertion instead.+WRITE_GATES = {"current_writable_workspace"}++#: Mutating routes that are legitimately not workspace-write-gated, each with+#: the reason. This is not a list of exceptions to tolerate; it is the+#: inventory of everything that will need re-deciding when permissions get+#: finer, which is why the reason is stored next to the path.+ALLOWLIST: dict[tuple[str, str], str] = {+ # Not workspace-scoped: the actor is the user, on their own account.+ ("PATCH", "/me"): "the requester's own user record",+ ("POST", "/2fa/setup"): "the requester's own second factor",+ ("POST", "/2fa/enable"): "the requester's own second factor",+ ("POST", "/2fa/disable"): "the requester's own second factor",+ ("POST", "/2fa/verify"): "unauthenticated step of the requester's own login",+ ("POST", "/passkeys/register/options"): "the requester's own credentials",+ ("POST", "/passkeys/register/verify"): "the requester's own credentials",+ ("DELETE", "/passkeys/{passkey_id}"): "the requester's own credentials",+ ("POST", "/passkeys/authenticate/options"): "unauthenticated: this is how you log in",+ ("POST", "/passkeys/authenticate/verify"): "unauthenticated: this is how you log in",+ ("POST", "/passkeys/2fa/options"): "unauthenticated step of login",+ ("POST", "/passkeys/2fa/verify"): "unauthenticated step of login",+ ("POST", "/login"): "unauthenticated by definition",+ ("POST", "/logout"): "unauthenticated by definition",+ ("POST", "/register"): "unauthenticated by definition",+ ("POST", "/forgot-password"): "unauthenticated by definition",+ ("POST", "/reset-password"): "unauthenticated by definition",+ ("PATCH", "/{id}"): "fastapi-users' own user router, superuser-gated",+ ("DELETE", "/{id}"): "fastapi-users' own user router, superuser-gated",+ ("POST", "/api/setup/create-admin"): "first-run bootstrap, refuses once a user exists",+ # Instance administration: gated by `current_superuser`, not by workspace.+ ("POST", "/api/admin/users"): "superuser-gated instance administration",+ ("PATCH", "/api/admin/users/{user_id}"): "superuser-gated instance administration",+ ("DELETE", "/api/admin/users/{user_id}"): "superuser-gated instance administration",+ ("PATCH", "/api/admin/settings/{key}"): "superuser-gated instance administration",+ # Workspace administration: uses its own, stricter owner floor via+ # `require_membership(min_role="owner")` inside the handler. Converting+ # these to the write gate would *widen* access, since editors can write.+ ("POST", "/api/workspaces"): "creates the workspace there is no membership in yet",+ ("PATCH", "/api/workspaces/{workspace_id}"): "owner floor inside the handler",+ ("POST", "/api/workspaces/{workspace_id}/archive"): "owner floor inside the handler",+ ("POST", "/api/workspaces/{workspace_id}/members"): "owner floor inside the handler",+ ("PATCH", "/api/workspaces/{workspace_id}/members/{member_user_id}"): "owner floor inside the handler",+ ("DELETE", "/api/workspaces/{workspace_id}/members/{member_user_id}"): "owner floor inside the handler",+ # Deliberate: a POST that persists nothing. See the comment on the route.+ ("POST", "/api/transactions/import/preview"): "parses an upload and returns a preview; writes nothing",+ # The agents surface, mounted only when AGENTS_ENABLED is on (the test+ # suite turns it on so these are always covered). An LLM connection is+ # the requester's own credential — scoped by `user.id`, never by+ # workspace — so it belongs to the same family as passkeys rather than+ # to workspace data.+ ("POST", "/api/agents/connections"): "the requester's own LLM credentials",+ ("PATCH", "/api/agents/connections/{conn_id}"): "the requester's own LLM credentials",+ ("DELETE", "/api/agents/connections/{conn_id}"): "the requester's own LLM credentials",+ ("POST", "/api/agents/connections/{conn_id}/test"): "probes the requester's own credential",+ # Global, not workspace data: FX rates are shared by the whole instance.+ # Any authenticated user may refresh them, and nothing per-workspace is+ # touched. Flagged here so a future rate limit or admin floor is a+ # decision rather than an oversight.+ ("POST", "/api/fx-rates/refresh"): "refreshes instance-wide FX rates, no workspace data",+}+++def _api_routes(routes):+ """Descend through FastAPI's lazily-included routers.++ Routers are wrapped in `_IncludedRouter` rather than being flattened into+ `app.routes`, so a naive pass over `app.routes` finds four routes and+ concludes there is nothing to check.+ """+ for route in routes:+ if isinstance(route, APIRoute):+ yield route+ included = getattr(route, "original_router", None)+ if included is not None:+ yield from _api_routes(included.routes)+++def _dependency_names(route: APIRoute) -> set[str]:+ seen: set[int] = set()+ stack = [route.dependant]+ names: set[str] = set()+ while stack:+ dependant = stack.pop()+ if id(dependant) in seen:+ continue+ seen.add(id(dependant))+ if dependant.call is not None:+ names.add(getattr(dependant.call, "__name__", str(dependant.call)))+ stack.extend(dependant.dependencies)+ return names+++def _mutating_routes():+ for route in _api_routes(app.routes):+ for method in sorted(getattr(route, "methods", set()) & MUTATING):+ yield method, route.path, route+++ALL_MUTATING = sorted({(m, p) for m, p, _ in _mutating_routes()})+++def test_the_walk_actually_finds_the_routes():+ """Guards the guard. If route discovery silently returns nothing — a+ FastAPI internal renamed, say — every assertion below would pass on an+ empty set and this file would be decoration."""+ assert len(ALL_MUTATING) > 100, f"only found {len(ALL_MUTATING)} mutating routes"+++ "method,path", ALL_MUTATING, ids=[f"{m} {p}" for m, p in ALL_MUTATING]+)+def test_a_mutating_route_declares_a_permission_decision(method, path):+ if (method, path) in ALLOWLIST:+ pytest.skip(f"allowlisted: {ALLOWLIST[(method, path)]}")++ route = next(r for m, p, r in _mutating_routes() if (m, p) == (method, path))+ names = _dependency_names(route)+ assert names & WRITE_GATES, (+ f"{method} {path} mutates but reaches no write gate.\n"+ f"Add `ctx: WorkspaceContext = Depends(current_writable_workspace)`, "+ f"or add it to ALLOWLIST in this file with the reason it is exempt."+ )+++def test_the_allowlist_has_no_stale_entries():+ """An allowlisted route that no longer exists — renamed, deleted, or since+ gated — is a stale exemption that would silently cover a future route+ reusing the path."""+ stale = sorted(set(ALLOWLIST) - set(ALL_MUTATING))+ assert stale == [], f"allowlist entries matching no route: {stale}"+++def test_nothing_allowlisted_is_already_gated():+ """The opposite drift: a route that gained the gate but kept its+ exemption. Harmless at runtime, misleading to read."""+ redundant = [+ (m, p) for (m, p) in ALLOWLIST+ if any(+ _dependency_names(r) & WRITE_GATES+ for mm, pp, r in _mutating_routes() if (mm, pp) == (m, p)+ )+ ]+ assert redundant == [], (+ f"these are gated and no longer need an allowlist entry: {redundant}"+ )diff --git a/backend/tests/test_write_permission_gate.py b/backend/tests/test_write_permission_gate.pynew file mode 100644index 00000000..0ed34135--- /dev/null+++ b/backend/tests/test_write_permission_gate.py@@ -0,0 +1,101 @@+"""A read-only member cannot write, proved over HTTP.++These assert **behaviour, not plumbing**. "A viewer cannot create a+transaction" stays true if the gate is later expressed per action, per+module or per view; "this route depends on `current_writable_workspace`"+would have to be rewritten by that change, and costs the same to write.++Why they did not exist before: the gate ships as a dependency wrapper+(`current_writable_workspace` → `ctx.require_write()`), so the string+`require_write` appears in exactly one file. An audit that grepped for it+concluded no route was gated, when 85 of them were. Service-level tests of+`require_membership` existed, but nothing exercised the wiring between a+route, the requester's role, and the 403 — which is the part that was+doubted.+"""+import uuid++import pytest+from httpx import AsyncClient++#: One representative mutation per resource family. Not exhaustive on+#: purpose: the meta-test in `test_write_permission_coverage.py` is what+#: guarantees breadth, and duplicating it here would be the same assertion+#: written a hundred times.+MUTATIONS = [+ ("transaction", "POST", "/api/transactions", {+ "account_id": None, "date": "2026-08-01", "description": "Should not exist",+ "amount": 10, "type": "expense",+ }),+ ("account", "POST", "/api/accounts", {+ "name": "Should not exist", "type": "checking", "currency": "BRL",+ }),+ ("category", "POST", "/api/categories", {"name": "Should not exist", "type": "expense"}),+ ("budget", "POST", "/api/budgets", {+ "category_id": None, "amount": 100, "period": "monthly",+ "start_date": "2026-08-01",+ }),+]+++ "family,method,path,payload", MUTATIONS, ids=[m[0] for m in MUTATIONS]+)+async def test_a_viewer_is_refused_on_a_mutation(+ client: AsyncClient, viewer_auth_headers, test_account, test_categories,+ family, method, path, payload,+):+ body = dict(payload)+ if body.get("account_id", "absent") is None:+ body["account_id"] = str(test_account.id)+ if body.get("category_id", "absent") is None:+ body["category_id"] = str(test_categories[0].id)++ resp = await client.request(method, path, headers=viewer_auth_headers, json=body)+ assert resp.status_code == 403, (+ f"a viewer got {resp.status_code} creating a {family}: {resp.text}"+ )+++async def test_the_refusal_says_why(client: AsyncClient, viewer_auth_headers):+ """A 403 with no reason sends the user to support. The role is the reason."""+ resp = await client.post(+ "/api/categories", headers=viewer_auth_headers,+ json={"name": "Should not exist", "type": "expense"},+ )+ assert resp.status_code == 403+ assert "read-only" in resp.json()["detail"].lower()+++async def test_a_viewer_can_still_read(client: AsyncClient, viewer_auth_headers):+ """The gate must refuse writes without turning into a lockout — otherwise+ a 403 on everything would pass the tests above for the wrong reason."""+ for path in ("/api/transactions", "/api/accounts", "/api/categories", "/api/budgets"):+ resp = await client.get(path, headers=viewer_auth_headers)+ assert resp.status_code == 200, f"a viewer could not read {path}: {resp.text}"+++async def test_the_write_gate_is_about_role_not_identity(+ client: AsyncClient, viewer_auth_headers, auth_headers+):+ """The same request the viewer was refused succeeds for the owner, so the+ 403 is the role talking and not something wrong with the payload."""+ body = {"name": f"Owner may write {uuid.uuid4().hex[:6]}", "type": "expense"}+ refused = await client.post("/api/categories", headers=viewer_auth_headers, json=body)+ allowed = await client.post("/api/categories", headers=auth_headers, json=body)+ assert refused.status_code == 403+ assert allowed.status_code == 201, allowed.text+++async def test_previewing_an_import_is_not_a_write(+ client: AsyncClient, viewer_auth_headers+):+ """The one deliberate exception, pinned so a later tightening is a+ decision rather than an accident: previewing parses an upload and+ persists nothing, so a read-only member may do it."""+ resp = await client.post(+ "/api/transactions/import/preview",+ headers=viewer_auth_headers,+ files={"file": ("t.csv", b"date,description,amount\n2026-08-01,Coffee,-5\n", "text/csv")},+ )+ assert resp.status_code != 403, "previewing was gated as a write"diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex de133a79..a306877d 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -104,7 +104,18 @@ export function AppLayout() {const [updateDialogOpen, setUpdateDialogOpen] = useState(false)useCommandPaletteHotkey(setPaletteOpen)const { agentsEnabled } = useFeatureFlags()- const { hasModule, isLoading: workspaceLoading } = useWorkspace()+ const { hasModule, isLoading: workspaceLoading, canWrite } = useWorkspace()+ // The chat is offered only to members who can write. Sending a message+ // reaches a tool set that persists — `propose_create_transaction` and its+ // siblings — so the backend refuses it for a read-only role. Showing the+ // panel anyway would put a raw `403: {"detail":"Read-only role"}` in front+ // of the user, which is what happened before this guard.+ //+ // This costs a viewer the ability to *ask* questions, which is a real use+ // case. Restoring it means making the agent's tools role-aware so a+ // read-only session only exposes the reading ones; then this becomes+ // `agentsEnabled` again.+ const chatAvailable = agentsEnabled && canWrite// ⌘J / Ctrl+J toggles the global slide-over chat from anywhere.// Distinct from ⌘K (command palette) so users can have both open.@@ -115,7 +126,7 @@ export function AppLayout() {setThemeBasedOnSystem(light, dark, resolvedTheme)}).catch(() => {})- if (!agentsEnabled) return+ if (!chatAvailable) returnconst handler = (e: KeyboardEvent) => {const isMod = e.metaKey || e.ctrlKeyif (isMod && (e.key === 'j' || e.key === 'J')) {@@ -125,7 +136,7 @@ export function AppLayout() {}document.addEventListener('keydown', handler)return () => document.removeEventListener('keydown', handler)- }, [agentsEnabled, resolvedTheme])+ }, [chatAvailable, resolvedTheme])// The "Agents" management page used to live in the sidebar, but it's// a configuration surface (KB upload, providers, default selection),// not a daily destination. Moved to the user menu (Change password,@@ -232,7 +243,7 @@ export function AppLayout() {{/* AI chat — opens the global slide-over (also reachable via⌘J). Sits next to the theme toggle so the icon is alwayswithin thumb reach on mobile too. */}- {agentsEnabled && (+ {chatAvailable && (<buttononClick={() => setChatOpen(true)}className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1"@@ -311,7 +322,7 @@ export function AppLayout() {{/* AI chat — same trigger as the mobile bar, ⌘J alsoworks. Lives in the sidebar header so the entry pointis visible even on first load (no floating button). */}- {agentsEnabled && (+ {chatAvailable && (<buttononClick={() => setChatOpen(true)}className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"@@ -551,7 +562,7 @@ export function AppLayout() {{/* Slide-over global chat — opened from the sidebar pill or via⌘J. The previous floating bottom-right button was removedsince the entry point now lives in the sidebar next to ⌘K. */}- {agentsEnabled && <GlobalChatPanel open={chatOpen} onOpenChange={setChatOpen} />}+ {chatAvailable && <GlobalChatPanel open={chatOpen} onOpenChange={setChatOpen} />}<UpdateAvailableDialogopen={updateDialogOpen}onClose={() => setUpdateDialogOpen(false)}