Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(gateway): discriminate the tenant-resolution failures

Petr Bauch0d41506ef968
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index 239aa49da..0fdc56b88 100644
--- a/core/switch_core/db/tenant_lookup.py
+++ b/core/switch_core/db/tenant_lookup.py
@@ -139,10 +139,9 @@ class TenantLookupError(RuntimeError):
Only reachable for a key that is not unique by constraint — today only
`agents.oauth_client_id`, which has no unique index. Raised rather than
- resolved by picking one, for the same reason `get_sole_tenant_id` refuses
- to: a credential that resolves to two tenants is a provisioning fault, and
- guessing which one it meant is how a caller ends up authenticated into
- somebody else's data.
+ resolved by picking one: a credential that resolves to two tenants is a
+ provisioning fault, and guessing which one it meant is how a caller ends
+ up authenticated into somebody else's data.
"""
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 3fbe48032..546da4767 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -32,6 +32,15 @@ logger = logging.getLogger(__name__)
JWT_ALGORITHM = "HS256"
JWT_EXPIRY_HOURS = 24
+# The `error` discriminator on the three tenant-resolution failures a client
+# has to tell apart. A bare `{"detail": [...]}` is indistinguishable from
+# FastAPI's own validation failures, and the status code alone does not
+# separate "choose a workspace" from "the one you chose is gone" — both of
+# which the caller can fix without help, unlike the third.
+TENANT_SELECTION_REQUIRED = "tenant_selection_required"
+TENANT_SELECTION_INVALID = "tenant_selection_invalid"
+TENANT_MEMBERSHIP_UNRESOLVED = "tenant_membership_unresolved"
+
def hash_password(password: str) -> str:
result: bytes = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
@@ -166,29 +175,29 @@ async def is_tenant_member(
return tenant_id in await tenants_of_user(session_factory, user_id)
-async def list_tenant_memberships(
+async def _describe_memberships(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
user_id: str,
+ tenant_ids: list[str],
) -> list[TenantMembershipResponse]:
- """Every tenant `user_id` belongs to: id, slug, name, and their role in it.
-
- Backs `GET /tenants`, and the body of the 409 `_resolve_tenant_id` raises
- when there is no claim to bind and several memberships to choose from —
- the same question asked at a different moment
- (`docs/old/multi-tenancy-phase2-tenants.md`, §7).
-
- Never holds two connections at once. `tenants_of_user` is its own
- short session with nothing bound; each tenant after that is read on its
- own short `tenant_session`, opened and closed before the next one starts.
- A request reaching this has no other session open — `get_current_user` is
- exactly what this exists to run *before* — so nothing here needs the
- guarantee, but the shape is worth keeping anyway: looping bound sessions
- from inside a request that already holds one is the mistake this design
- explicitly rejects.
+ """Name and role for each of `tenant_ids`, as the caller holds them.
+
+ Takes the ids rather than looking them up so the one caller that already
+ has them — `_resolve_tenant_id`, which reads them to decide the case it is
+ in — does not ask the exemption a second question it already knows the
+ answer to.
+
+ Never holds two connections at once: each tenant is read on its own short
+ `tenant_session`, opened and closed before the next one starts. A request
+ reaching this has no other session open — `get_current_user` is exactly
+ what this exists to run *before* — so nothing here needs the guarantee,
+ but the shape is worth keeping anyway: looping bound sessions from inside
+ a request that already holds one is the mistake this design explicitly
+ rejects.
"""
memberships: list[TenantMembershipResponse] = []
- for tenant_id in await tenants_of_user(session_factory, user_id):
+ for tenant_id in tenant_ids:
async with tenant_session(session_factory, tenant_id) as session:
tenant = await session.get(Tenant, tenant_id)
role = await user_store.tenant_role(session, tenant_id, user_id)
@@ -212,6 +221,26 @@ async def list_tenant_memberships(
return memberships
+async def list_tenant_memberships(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ user_id: str,
+) -> list[TenantMembershipResponse]:
+ """Every tenant `user_id` belongs to: id, slug, name, and their role in it.
+
+ Backs `GET /tenants`. `_resolve_tenant_id` builds the same list for the
+ 409 it raises — the same question asked at a different moment
+ (`docs/old/multi-tenancy-phase2-tenants.md`, §7) — but goes straight to
+ `_describe_memberships` with ids it has already read.
+ """
+ return await _describe_memberships(
+ session_factory,
+ user_store,
+ user_id,
+ await tenants_of_user(session_factory, user_id),
+ )
+
+
async def _resolve_tenant_id(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
@@ -223,23 +252,33 @@ async def _resolve_tenant_id(
`docs/old/multi-tenancy-phase2-tenants.md`, §4:
1. A claim naming a tenant the caller belongs to → bind it.
- 2. A claim naming a tenant the caller does not belong to → 403. The cookie
- is not cleared here: it is `lax`, so a cross-site navigation can reach
- this path, and any page resetting someone's selection on a stale or
- forged claim would be a worse failure than answering 403 and leaving
- the session alone. Clearing belongs on a dedicated endpoint.
+ 2. A claim naming a tenant the caller does not belong to → 403
+ `tenant_selection_invalid`. The caller can fix this unaided — `GET
+ /tenants` and `POST /tenants/{id}/switch` both authenticate without
+ binding a tenant, and signing in again mints a null claim — so the
+ message says so rather than sending them to an administrator. It is
+ not a rare state either: removing a member puts everyone it touches
+ here on their next request.
+
+ The cookie is not cleared here: it is `lax`, so a cross-site
+ navigation can reach this path, and any page resetting someone's
+ selection on a stale or forged claim would be a worse failure than
+ answering 403 and leaving the session alone. Clearing belongs on a
+ dedicated endpoint.
3. No claim, exactly one membership → bind it. Every session issued before
this change, and every single-workspace account forever, lands here.
- 4. No claim, several memberships → the choose-one response, gated on
- `choice_enabled` because it is a breaking change for a client that has
- never had to handle it. Off, this falls through to the same 403 as
- case 5 — the exact behaviour every account had before this change,
- since two memberships did not exist for anyone to reach it.
- 5. No memberships → 403.
-
- `tenants_of_user` is read once and used for every case below it, rather
- than once per case, so this is one round trip to the exemption regardless
- of which case answers.
+ 4. No claim, several memberships → 409 `tenant_selection_required`
+ carrying the choices, gated on `choice_enabled` because it is a
+ breaking change for a client that has never had to handle it. Off,
+ this falls through to the same 403 as case 5 — the exact behaviour
+ every account had before this change, since two memberships did not
+ exist for anyone to reach it.
+ 5. No memberships → 403 `tenant_membership_unresolved`, the one of the
+ three the caller genuinely cannot resolve alone.
+
+ `tenants_of_user` is read once and used for every case below it, including
+ the 409's body, so this is one round trip to the exemption regardless of
+ which case answers.
"""
memberships = await tenants_of_user(session_factory, user_id)
@@ -251,20 +290,28 @@ async def _resolve_tenant_id(
)
raise HTTPException(
status_code=403,
- detail=(
- "This account is not a member of the selected tenant; "
- "ask an administrator to check its membership."
- ),
+ detail={
+ "error": TENANT_SELECTION_INVALID,
+ "message": (
+ "The workspace selected on this session is not one you "
+ "belong to. Choose another, or sign in again."
+ ),
+ },
)
if len(memberships) == 1:
return memberships[0]
if len(memberships) > 1 and choice_enabled:
- choices = await list_tenant_memberships(session_factory, user_store, user_id)
+ choices = await _describe_memberships(
+ session_factory, user_store, user_id, memberships
+ )
raise HTTPException(
status_code=409,
- detail=[choice.model_dump() for choice in choices],
+ detail={
+ "error": TENANT_SELECTION_REQUIRED,
+ "tenants": [choice.model_dump() for choice in choices],
+ },
)
logger.error(
@@ -274,10 +321,13 @@ async def _resolve_tenant_id(
)
raise HTTPException(
status_code=403,
- detail=(
- "This account is not a member of exactly one tenant; "
- "ask an administrator to check its membership."
- ),
+ detail={
+ "error": TENANT_MEMBERSHIP_UNRESOLVED,
+ "message": (
+ "This account is not a member of exactly one workspace; "
+ "ask an administrator to check its membership."
+ ),
+ },
)
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index e782fbea2..59e87a806 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -13,10 +13,16 @@ import switch_core.gateway.oidc_routes as oidc_routes
from switch_core.config import SwitchConfig
from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, TenantMember, User
from switch_core.db.stores.user_store import OidcIdentityRaceError, UserStore
-from switch_core.gateway.auth import hash_password
+from switch_core.gateway.auth import decode_jwt, hash_password
from switch_core.gateway.auth_routes import auth_config
+def _tenant_claim(set_cookie: str) -> str | None:
+ token = set_cookie.split("switch_auth=", 1)[1].split(";", 1)[0]
+ claim: str | None = decode_jwt(token, "secret").get("tenant_id")
+ return claim
+
+
def _config(**overrides: object) -> SwitchConfig:
base: dict[str, object] = dict(
db_host="h",
@@ -88,6 +94,12 @@ class TestOidcCallback:
assert response.status_code == 303
set_cookie = response.headers.get("set-cookie")
assert set_cookie is not None and "switch_auth=" in set_cookie
+ # Signing in selects no workspace. That null claim is the recovery
+ # path out of a selection that has gone stale — a removed member is
+ # 403'd on every request until something mints one without it — so
+ # a later change carrying the previous tenant forward here would
+ # strand them until their cookie expired (CHOO-2723).
+ assert _tenant_claim(set_cookie) is None
user = await UserStore().get_by_email(session, "[email protected]")
assert user is not None
diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.py
index d02693e5a..31895eb62 100644
--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -30,7 +30,11 @@ from dataclasses import dataclass
from fastapi import APIRouter
import switch_core.gateway as gateway_package
-from switch_core.gateway.auth import get_current_user, require_admin
+from switch_core.gateway.auth import (
+ get_authenticated_user_id,
+ get_current_user,
+ require_admin,
+)
from switch_core.gateway.dependencies import get_session, get_system_session
# The only routes that may open a session with no tenant bound. `get_session`
@@ -46,6 +50,17 @@ _ROUTES_WITH_NO_TENANT_BOUND = {
("POST", "/tenants/{tenant_id}/switch"),
}
+# The only routes that may authenticate a caller without resolving a tenant at
+# all. `get_authenticated_user_id` verifies the cookie and stops there, so it
+# is a reachable way past the membership check `get_current_user` performs —
+# every case of `_resolve_tenant_id`, including the two 403s. These two need
+# it because a caller with several memberships and no selection cannot reach
+# `get_current_user` by construction; nothing else has that excuse.
+_ROUTES_AUTHENTICATED_WITHOUT_RESOLVING_A_TENANT = {
+ ("GET", "/tenants"),
+ ("POST", "/tenants/{tenant_id}/switch"),
+}
+
@dataclass(frozen=True)
class _Route:
@@ -124,6 +139,29 @@ def test_the_routes_with_no_tenant_bound_are_exactly_these_three() -> None:
} == _ROUTES_WITH_NO_TENANT_BOUND
+def test_the_routes_skipping_tenant_resolution_are_exactly_these_two() -> None:
+ """`get_authenticated_user_id` is the newest way past the tenant check, and
+ the one with the least around it: no membership read, no scoped session,
+ nothing a policy would refuse. Pinned by the same reasoning
+ `test_tenant_exemption_allowlist` gives for the `SECURITY DEFINER`
+ lookups — what matters is that it is reachable, not that today's two
+ callers happen to be the right ones."""
+ assert {
+ route.key for route in ROUTES if get_authenticated_user_id in route.calls
+ } == _ROUTES_AUTHENTICATED_WITHOUT_RESOLVING_A_TENANT
+
+
+def test_no_route_both_resolves_a_tenant_and_skips_resolving_one() -> None:
+ """Taking both would mean the membership check runs and its answer is
+ ignored — the route would authorize against whichever dependency it
+ happened to read."""
+ assert not [
+ str(route)
+ for route in ROUTES
+ if get_authenticated_user_id in route.calls and get_current_user in route.calls
+ ]
+
+
def test_the_exempt_routes_do_not_also_take_the_tenant_scoped_session() -> None:
"""A route holding both would be authenticated-looking and unscoped at
once, which is the worst of the two."""
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index a792b02e6..6b3bfc05b 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -42,8 +42,9 @@ from types import SimpleNamespace
from typing import Annotated
import httpx
+import pytest
import pytest_asyncio
-from fastapi import Depends, FastAPI
+from fastapi import Depends, FastAPI, Response
from sqlalchemy import insert, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
@@ -51,8 +52,19 @@ from switch_core.db.base import Base
from switch_core.db.engine import create_session_factory
from switch_core.db.models import TENANT_ZERO_ID, Tenant, TenantMember, User
from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway import auth as gw_auth
from switch_core.gateway import dependencies as gw_deps
-from switch_core.gateway.auth import create_jwt, get_current_user
+from switch_core.gateway.auth import (
+ TENANT_MEMBERSHIP_UNRESOLVED,
+ TENANT_SELECTION_INVALID,
+ TENANT_SELECTION_REQUIRED,
+ create_jwt,
+ decode_jwt,
+ get_current_user,
+ hash_password,
+)
+from switch_core.gateway.auth_routes import login
+from switch_core.gateway.schemas import LoginRequest
from switch_core.gateway.tenants import router as tenants_router
_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
@@ -133,6 +145,23 @@ def _client(app: FastAPI, token: str) -> httpx.AsyncClient:
)
+def _login_config() -> SimpleNamespace:
+ # The three attributes `login` reads.
+ return SimpleNamespace(
+ gateway_password_login_enabled=True,
+ jwt_secret_key=_SECRET,
+ gateway_cookie_secure=False,
+ )
+
+
+def _tenant_claim(response: Response) -> str | None:
+ raw = response.headers.get("set-cookie")
+ assert raw is not None, "no session cookie was minted"
+ token = raw.split("switch_auth=", 1)[1].split(";", 1)[0]
+ claim: str | None = decode_jwt(token, _SECRET).get("tenant_id")
+ return claim
+
+
async def _make_user(
session_factory: async_sessionmaker[AsyncSession],
*,
@@ -176,6 +205,51 @@ async def _make_user_with_memberships(
return user.id
+class TestSigningInSelectsNoWorkspace:
+ """Both interactive mint sites pass a null tenant claim, and that is load
+ bearing rather than incidental.
+
+ It is the way out of a selection that has gone stale: a member removed
+ from the workspace their cookie names is 403'd
+ (`TENANT_SELECTION_INVALID`) on every request until something mints a
+ cookie without it. If either of these were later made to "helpfully"
+ carry the previous tenant forward, that person would be stranded until
+ their cookie expired — and the rest of the suite would stay green, since
+ only `/auth/refresh`'s claim is asserted anywhere else (CHOO-2723).
+ """
+
+ async def test_password_login_mints_no_tenant_claim(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ user = User(
+ name="signer",
+ role="user",
+ password_hash=hash_password("correct horse battery staple"),
+ )
+ session.add(user)
+ await session.flush()
+ session.add(
+ TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member")
+ )
+ await session.commit()
+
+ response = Response()
+ await login(
+ LoginRequest(
+ password="correct horse battery staple",
+ ),
+ response,
+ session,
+ UserStore(),
+ _login_config(),
+ )
+
+ assert _tenant_claim(response) is None
+
+
class TestAGatewayRequestBindsTheCallersTenant:
async def test_the_sessions_tenant_matches_the_users_membership(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -249,7 +323,12 @@ class TestAClaimSelectsAMembership:
response = await client.get("/whoami")
assert response.status_code == 403
- assert "tenant" in response.json()["detail"]
+ detail = response.json()["detail"]
+ assert detail["error"] == TENANT_SELECTION_INVALID
+ # A caller in this state fixes it themselves — `GET /tenants` and the
+ # switch route both still work — so the message must not send them to
+ # an administrator. Member removal makes this the common 403.
+ assert "administrator" not in detail["message"]
# The cookie is `lax`, so a cross-site navigation can reach this path;
# clearing someone's selection off the back of a stale or forged
# claim would be worse than just refusing (§4 of the design doc).
@@ -276,7 +355,7 @@ class TestNoClaimWithSeveralMemberships:
response = await client.get("/whoami")
assert response.status_code == 403
- assert "tenant" in response.json()["detail"]
+ assert response.json()["detail"]["error"] == TENANT_MEMBERSHIP_UNRESOLVED
async def test_flag_on_is_409_with_the_choices(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -290,8 +369,46 @@ class TestNoClaimWithSeveralMemberships:
response = await client.get("/whoami")
assert response.status_code == 409
- tenant_ids = {choice["id"] for choice in response.json()["detail"]}
- assert tenant_ids == {TENANT_ZERO_ID, TENANT_B}
+ detail = response.json()["detail"]
+ # Discriminated, because FastAPI's own validation failures are also
+ # `{"detail": [...]}` and 409 is a plausible status for some future
+ # conflict elsewhere in the API. A client branches on `error`, not on
+ # the shape of what it got.
+ assert detail["error"] == TENANT_SELECTION_REQUIRED
+ assert {choice["id"] for choice in detail["tenants"]} == {
+ TENANT_ZERO_ID,
+ TENANT_B,
+ }
+
+ async def test_the_choose_one_body_costs_no_second_lookup(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """`_resolve_tenant_id` reads the exemption once and reuses the answer
+ for the 409's body. It is the function every authenticated request
+ goes through, and the case that builds a body is the one where a
+ second `SECURITY DEFINER` round trip would be easiest not to notice."""
+ calls = 0
+ real = gw_auth.tenants_of_user
+
+ async def counting(*args: object, **kwargs: object) -> list[str]:
+ nonlocal calls
+ calls += 1
+ return await real(*args, **kwargs) # type: ignore[arg-type]
+
+ monkeypatch.setattr(gw_auth, "tenants_of_user", counting)
+
+ user_id = await _make_user_with_memberships(
+ session_factory, name="counted", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(_app(session_factory, choice_enabled=True), token) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 409
+ assert calls == 1
class TestAUserWithNoMembership:
@@ -316,8 +433,8 @@ class TestAUserWithNoMembership:
assert response.status_code == 403
detail = response.json()["detail"]
- assert "tenant" in detail
- assert user_id not in detail
+ assert detail["error"] == TENANT_MEMBERSHIP_UNRESOLVED
+ assert user_id not in detail["message"]
class TestConcurrentRequests: