Skip to content

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

feat(gateway): let a session select its tenant among several memberships (CHOO-2723)

Wojciech Wojtyniak05ad9503c632
diff --git a/.env.example b/.env.example
index 06f5deafc..ed7a9c2f4 100644
--- a/.env.example
+++ b/.env.example
@@ -104,6 +104,14 @@ JWT_SECRET_KEY=
GATEWAY_ADMIN_PASSWORD=
+# Off by default: a person who belongs to more than one tenant and has not
+# selected one on their session gets a 403, same as a single-tenant deployment
+# does today, rather than a 409 listing the tenants to choose from. That 409 is
+# a breaking change for any client that has never had to handle it — turn this
+# on only once the client authenticating against this deployment does. See
+# docs/old/multi-tenancy-phase2-tenants.md, §4.
+# GATEWAY_TENANT_CHOICE_ENABLED=false
+
# ── Frontend ─────────────────────────────────────────────────────────────────
FRONTEND_BASE_URL=http://localhost:5173
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 59b05d80d..7ea62112d 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -131,6 +131,15 @@ class SwitchConfig(BaseSettings):
# this true so the JWT session cookie is never sent over an insecure channel.
gateway_cookie_secure: bool = False
+ # Off by default: a person who belongs to more than one tenant and has not
+ # selected one on their session gets the same 403 a single-tenant
+ # deployment already returns today, rather than a 409 listing the tenants
+ # to choose from. The 409 is a breaking change for a client that has never
+ # had to handle it — set true only once the client that will authenticate
+ # against this deployment knows what to do with it. See
+ # docs/old/multi-tenancy-phase2-tenants.md, §4.
+ gateway_tenant_choice_enabled: bool = False
+
# ── Logging ──────────────────────────────────────────────────────────────
# "text" for a terminal, "json" for a log pipeline that parses fields.
log_format: str = "text"
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index f97229980..376ca1e27 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -39,6 +39,7 @@ from switch_core.gateway.room_groups import router as room_groups_router
from switch_core.gateway.room_links import router as room_links_router
from switch_core.gateway.rooms import router as rooms_router
from switch_core.gateway.templates import router as templates_router
+from switch_core.gateway.tenants import router as tenants_router
from switch_core.room_service import RoomService
@@ -101,6 +102,7 @@ def create_gateway_app(
app.include_router(auth_router, tags=["auth"])
app.include_router(oidc_router, tags=["auth"])
+ app.include_router(tenants_router, tags=["tenants"])
app.include_router(rooms_router, prefix="/rooms", tags=["rooms"])
app.include_router(room_groups_router, prefix="/room-groups", tags=["room-groups"])
app.include_router(agents_router, prefix="/agents", tags=["agents"])
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 2b9e7ccea..3fbe48032 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -12,7 +12,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.authz import Action, Principal, require
from switch_core.config import SwitchConfig
-from switch_core.db.models import Room, User
+from switch_core.db.models import Room, Tenant, User
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.user_store import UserStore
from switch_core.db.tenant_lookup import tenants_of_user
@@ -22,6 +23,7 @@ from switch_core.gateway.dependencies import (
get_session_factory,
get_user_store,
)
+from switch_core.gateway.schemas import TenantMembershipResponse
from switch_core.logging_context import log_context
from switch_core.tenant_context import tenant_scope
@@ -45,11 +47,22 @@ def verify_password(password: str, password_hash: str | None) -> bool:
return result
-def create_jwt(user_id: str, email: str, role: str, secret_key: str) -> str:
+def create_jwt(
+ user_id: str, email: str, role: str, secret_key: str, tenant_id: str | None
+) -> str:
+ """Sign a session JWT. `tenant_id` is the caller's selected tenant, or
+ `None` for a session that has not selected one yet (a fresh login, or a
+ multi-membership account that has never called `/tenants/{id}/switch`).
+
+ The claim only ever *selects*: `_resolve_tenant_id` re-checks it against a
+ live membership row on every request, so a forged or stale value buys
+ nothing (`docs/old/multi-tenancy-phase2-tenants.md`, §3).
+ """
payload = {
"sub": user_id,
"email": email,
"role": role,
+ "tenant_id": tenant_id,
"exp": datetime.datetime.now(datetime.UTC)
+ datetime.timedelta(hours=JWT_EXPIRY_HOURS),
"iat": datetime.datetime.now(datetime.UTC),
@@ -58,17 +71,25 @@ def create_jwt(user_id: str, email: str, role: str, secret_key: str) -> str:
def set_session_cookie(
- response: Response, user: User, secret_key: str, secure: bool
+ response: Response,
+ user: User,
+ secret_key: str,
+ secure: bool,
+ tenant_id: str | None,
) -> None:
"""Mint the switch_auth session cookie for an authenticated user.
- Shared by password login and the OIDC callback so the session contract
- stays identical regardless of how the user proved their identity.
+ Shared by password login, the OIDC callback, `/auth/refresh` and
+ `/tenants/{id}/switch` so the session contract stays identical regardless
+ of how the user proved their identity or picked their tenant. Every one of
+ those four must pass `tenant_id` explicitly — `/auth/refresh` is the path
+ most likely to get this wrong, because it re-mints from the still-valid
+ `User` alone otherwise, silently dropping whatever tenant was selected.
`secure` gates the Secure flag: True on HTTPS deployments so the JWT is
never sent over plain HTTP, False for local dev served over http://.
"""
- token = create_jwt(user.id, user.email, user.role, secret_key)
+ token = create_jwt(user.id, user.email, user.role, secret_key, tenant_id)
response.set_cookie(
key="switch_auth",
value=token,
@@ -89,110 +110,175 @@ def decode_jwt(token: str, secret_key: str) -> dict:
raise HTTPException(status_code=401, detail="Invalid token")
-class TenantMembershipError(Exception):
- """A user has zero, or more than one, tenant memberships.
+async def _authenticate(
+ request: Request,
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ config: SwitchConfig,
+) -> dict:
+ """Decode the switch_auth cookie and confirm its subject still exists.
+
+ Nothing here binds a tenant — both reads are on `users`, which carries no
+ tenant column and so no policy, so a session with nothing bound is the
+ honest way to read it. Shared by `get_current_user` (which goes on to bind
+ one) and `get_authenticated_user_id` (which deliberately does not).
+ """
+ token = request.cookies.get("switch_auth")
+ if token is None:
+ raise HTTPException(status_code=401, detail="Not authenticated")
+ payload = decode_jwt(token, config.jwt_secret_key)
+ async with session_factory() as system_session:
+ if not await user_store.exists(system_session, payload["sub"]):
+ raise HTTPException(status_code=401, detail="User not found")
+ return payload
+
- Phase 1 has exactly one tenant, so exactly one membership row is the only
- correct state: zero means the user was never enrolled (a bug in whatever
- created the account), and more than one is Phase 2's tenant-switching
- shape arriving early. Either way this must not be resolved by picking
- one — see `docs/old/multi-tenancy-phase1-db.md`, "Setting the tenant".
+async def get_authenticated_user_id(
+ request: Request,
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> str:
+ """The caller's user id, authenticated but with no tenant bound.
- Raised, not returned, but not left to reach the client either:
- `get_current_user` below turns it into a 403 naming no user id, so a
- broken account gets an answer an operator can act on instead of a bare
- 500.
+ For the one route that must answer before a tenant can be chosen:
+ `GET /tenants` and `POST /tenants/{id}/switch` (`gateway/tenants.py`). A
+ caller with several memberships and no selection cannot reach
+ `get_current_user` at all — that is the whole point of the 409 it raises —
+ so listing and switching have to authenticate independently of it.
"""
+ payload = await _authenticate(request, session_factory, user_store, config)
+ return payload["sub"] # type: ignore[no-any-return]
-async def sole_tenant_id(
- session_factory: async_sessionmaker[AsyncSession], user_id: str
-) -> str:
- """The one tenant this user belongs to, raising if that isn't true.
-
- Here rather than on a store, and that placement is the point. This is the
- only caller there has ever been, and it is an authentication step: the
- JWT names a person, and a person is global (`users` carries no tenant),
- so something has to turn "who" into "which tenant" before a scoped session
- can exist at all.
-
- It goes through `tenants_of_user`, one of the seven `SECURITY DEFINER`
- lookups that make up the whole exemption from row-level security
- (`db/tenant_lookup.py`), which opens a session of its own with nothing
- bound and answers with tenant ids and nothing else. `tenant_members` is a
- scoped table, so a session cannot read the row that would tell it what to
- be scoped to; a plain `select` here worked only because every environment
- once connected as the tables' owner, and under the restricted runtime role
- it is one of the reads the policy refuses.
-
- That is also why this is a function and not an injected dependency. It
- reaches the exemption with an arbitrary user id, and as a store on the
- dependency graph any endpoint could declare it and do the same. The
- exemption's audit surface is the list of modules that import a lookup
- (`tests/switch_core/db/test_tenant_exemption_allowlist.py`), and a
- reachable-from-anywhere wrapper made that list say less than it looked
- like it said.
-
- Refusing rather than picking, on both sides of "exactly one": zero
- memberships is an account that was never enrolled, and two is a decision
- about which tenant's data the caller is about to see. Neither is a thing
- to guess at. Membership is written by exactly one function,
- `UserStore.ensure_membership`, which is idempotent and derives the role
- from the user — so "every account has exactly one" holds by construction
- rather than by every writer remembering, and a second, unguarded way to
- write one is how an account ends up with two.
+async def is_tenant_member(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str, tenant_id: str
+) -> bool:
+ """Whether `user_id` has a membership in `tenant_id`.
+
+ Backs `POST /tenants/{id}/switch`: the claim it goes on to mint never
+ authorises by itself (`_resolve_tenant_id` re-checks it on every request
+ regardless), but switching still must not let someone select a tenant
+ they do not belong to.
"""
- tenant_ids = await tenants_of_user(session_factory, user_id)
- if len(tenant_ids) != 1:
- raise TenantMembershipError(
- f"user {user_id} has {len(tenant_ids)} tenant memberships; expected exactly 1"
+ return tenant_id in await tenants_of_user(session_factory, user_id)
+
+
+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`, 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.
+ """
+ memberships: list[TenantMembershipResponse] = []
+ for tenant_id in await tenants_of_user(session_factory, user_id):
+ 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)
+ if tenant is None or role is None:
+ # tenants_of_user just said this tenant has a membership row for
+ # this user; either read failing to confirm it a moment later is
+ # a genuine race (removed between the two calls), not a bug to
+ # paper over by including a tenant we can no longer describe.
+ logger.warning(
+ "tenants_of_user named tenant %s for user %s, but it or the "
+ "membership row was gone by the time it was read",
+ tenant_id,
+ user_id,
+ )
+ continue
+ memberships.append(
+ TenantMembershipResponse(
+ id=tenant.id, slug=tenant.slug, name=tenant.name, role=role
+ )
)
- return tenant_ids[0]
+ return memberships
async def _resolve_tenant_id(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
user_id: str,
+ tenant_claim: str | None,
+ choice_enabled: bool,
) -> str:
- """Which tenant the JWT's subject belongs to, before one is bound.
-
- Two reads, and they are unbound for different reasons. `users` carries no
- tenant at all — a person is not a tenant member — so the existence check
- is an ordinary read on a session with nothing bound. The membership read
- is not: `tenant_members` is scoped, and this is the lookup that decides
- what to scope to, so it goes through the `SECURITY DEFINER` exemption
- (`db/tenant_lookup.py`) rather than through a session the policy would
- refuse.
-
- Both are short-lived on purpose. Held as a yield dependency instead, they
- would keep a second pooled connection — idle in transaction, since the
- lookup autobegins one nothing ever ends — for the whole request, halving
- effective pool capacity.
-
- Nothing loaded here escapes: the caller re-reads the `User` from the
- request's own session, so the object an endpoint mutates belongs to the
- session that endpoint commits.
+ """Which tenant a request binds, in the order set out in
+ `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.
+ 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.
"""
- async with session_factory() as system_session:
- if not await user_store.exists(system_session, user_id):
- raise HTTPException(status_code=401, detail="User not found")
- try:
- return await sole_tenant_id(session_factory, user_id)
- except TenantMembershipError as exc:
- # Phase 1 has exactly one tenant, so anything but one membership is a
- # provisioning bug, not a credential problem — but the caller still
- # deserves a legible answer instead of an opaque 500. The detail names
- # no user id: it is rendered to whoever is holding the cookie, not to
- # the operator, who gets the id from the log.
- logger.error("Cannot resolve a tenant for user %s: %s", user_id, exc)
+ memberships = await tenants_of_user(session_factory, user_id)
+
+ if tenant_claim is not None:
+ if tenant_claim in memberships:
+ return tenant_claim
+ logger.warning(
+ "Tenant claim %s for user %s names no membership", tenant_claim, user_id
+ )
raise HTTPException(
status_code=403,
detail=(
- "This account is not a member of exactly one tenant; "
+ "This account is not a member of the selected tenant; "
"ask an administrator to check its membership."
),
- ) from exc
+ )
+
+ 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)
+ raise HTTPException(
+ status_code=409,
+ detail=[choice.model_dump() for choice in choices],
+ )
+
+ logger.error(
+ "Cannot resolve a tenant for user %s: %d memberships and no selection",
+ user_id,
+ len(memberships),
+ )
+ raise HTTPException(
+ status_code=403,
+ detail=(
+ "This account is not a member of exactly one tenant; "
+ "ask an administrator to check its membership."
+ ),
+ )
async def get_current_user(
@@ -214,14 +300,23 @@ async def get_current_user(
the same session FastAPI hands the endpoint, so an endpoint that mutates
this object and commits that session persists the change. Loading it from
anywhere else silently discards writes.
+
+ The resolved tenant is stamped on `request.state` so `/auth/refresh` can
+ re-mint the cookie carrying it forward — the one mint that has no other
+ way to learn which tenant this session had selected.
"""
- token = request.cookies.get("switch_auth")
- if token is None:
- raise HTTPException(status_code=401, detail="Not authenticated")
- payload = decode_jwt(token, config.jwt_secret_key)
+ payload = await _authenticate(request, session_factory, user_store, config)
user_id = payload["sub"]
-
- tenant_id = await _resolve_tenant_id(session_factory, user_store, user_id)
+ tenant_claim = payload.get("tenant_id")
+
+ tenant_id = await _resolve_tenant_id(
+ session_factory,
+ user_store,
+ user_id,
+ tenant_claim,
+ config.gateway_tenant_choice_enabled,
+ )
+ request.state.tenant_id = tenant_id
with tenant_scope(tenant_id), log_context(user_id=user_id, tenant_id=tenant_id):
user = await user_store.get(session, user_id)
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 397e906f4..8050d2b42 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
from typing import Annotated
-from fastapi import APIRouter, Depends, HTTPException, Response
+from fastapi import APIRouter, Depends, HTTPException, Request, Response
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.config import SwitchConfig
@@ -101,13 +101,14 @@ async def login(
raise HTTPException(status_code=401, detail="Invalid email or password")
set_session_cookie(
- response, user, config.jwt_secret_key, config.gateway_cookie_secure
+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, None
)
return _session_response(user)
@router.post("/auth/refresh")
async def refresh(
+ request: Request,
response: Response,
user: Annotated[User, Depends(get_current_user)],
config: Annotated[SwitchConfig, Depends(get_config)],
@@ -118,8 +119,16 @@ async def refresh(
# rather than replaying either login flow). get_current_user rejects a
# missing/expired/invalid cookie with 401, so an expired session cannot renew
# itself; the client falls back to interactive sign-in in that case.
+ #
+ # `request.state.tenant_id` is what get_current_user just resolved this
+ # request to — carrying it forward is the whole point: re-minting from
+ # `user` alone would drop whatever tenant this session had selected.
set_session_cookie(
- response, user, config.jwt_secret_key, config.gateway_cookie_secure
+ response,
+ user,
+ config.jwt_secret_key,
+ config.gateway_cookie_secure,
+ request.state.tenant_id,
)
return _session_response(user)
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index 708ee6543..8a07e7e62 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -102,17 +102,20 @@ async def get_session() -> AsyncIterator[AsyncSession]:
async def get_system_session() -> AsyncIterator[AsyncSession]:
- """The session for a request that has no authenticated caller yet.
-
- Password login and the OIDC callback are the whole list: both run before
- anyone is signed in, so neither can bind a tenant from a principal the way
- `get_current_user` does. Named separately from `get_session` so that
- reads as a deliberate, reviewable exception rather than an
- accidentally-unscoped session, and so the guard test above can hold for
- `get_session` without exemptions. Nothing about opening it differs from
- `get_session` today — it is the same session and the same hook, simply
- with nothing bound around it — so the two must stay interchangeable in
- behaviour only, never in name.
+ """The session for a request with no tenant bound yet.
+
+ Password login and the OIDC callback are the original two: both run
+ before anyone is signed in, so neither can bind a tenant from a principal
+ the way `get_current_user` does. `POST /tenants/{id}/switch`
+ (`gateway/tenants.py`) is a third, for a different reason — the caller is
+ authenticated (`get_authenticated_user_id`) but has, by construction, not
+ yet selected the tenant this session opens for. Named separately from
+ `get_session` so that reads as a deliberate, reviewable exception rather
+ than an accidentally-unscoped session, and so the guard test above can
+ hold for `get_session` without exemptions. Nothing about opening it
+ differs from `get_session` today — it is the same session and the same
+ hook, simply with nothing bound around it — so the two must stay
+ interchangeable in behaviour only, never in name.
"No tenant bound" is not the same as "writes land nowhere in particular":
the OIDC callback provisions a user and picks its tenant explicitly (see
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 338ac2811..106482b38 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -208,6 +208,6 @@ async def oidc_callback(
# back on the SPA with our own session cookie set.
response = RedirectResponse(url=config.frontend_base_url or "/", status_code=303)
set_session_cookie(
- response, user, config.jwt_secret_key, config.gateway_cookie_secure
+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, None
)
return response
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index c5c973da8..cd0d40794 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -658,6 +658,21 @@ class ChangePasswordRequest(BaseModel):
new_password: str = Field(min_length=8)
+class TenantMembershipResponse(BaseModel):
+ """One tenant the caller belongs to, and their role in it.
+
+ The body of `GET /tenants`, and — as a list — the body of the 409
+ `_resolve_tenant_id` raises when there is no tenant claim to bind and
+ several memberships to choose from: the same question asked at a
+ different moment (`docs/old/multi-tenancy-phase2-tenants.md`, §4 and §7).
+ """
+
+ id: str
+ slug: str
+ name: str
+ role: str
+
+
class AuthConfigResponse(BaseModel):
# Read unauthenticated by the login page to decide which login methods to
# show. `oidc_provider_label` is the button text (e.g. "Okta").
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
new file mode 100644
index 000000000..00d7d49c2
--- /dev/null
+++ b/core/switch_core/gateway/tenants.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException, Response
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.config import SwitchConfig
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.auth import (
+ get_authenticated_user_id,
+ is_tenant_member,
+ list_tenant_memberships,
+ set_session_cookie,
+)
+from switch_core.gateway.auth_routes import _session_response
+from switch_core.gateway.dependencies import (
+ get_config,
+ get_session_factory,
+ get_system_session,
+ get_user_store,
+)
+from switch_core.gateway.schemas import SessionUserResponse, TenantMembershipResponse
+
+router = APIRouter()
+
+
[email protected]("/tenants")
+async def list_tenants(
+ user_id: Annotated[str, Depends(get_authenticated_user_id)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+) -> list[TenantMembershipResponse]:
+ """The caller's own tenants: id, slug, name, and their role in each.
+
+ Authenticated with `get_authenticated_user_id`, not `get_current_user`:
+ the caller may belong to several tenants and have none selected on their
+ session, which is exactly the state `get_current_user` cannot resolve
+ without this list existing first (`docs/old/multi-tenancy-phase2-tenants.md`,
+ §7). This route never holds a bound request session open while it reads
+ the others — see `list_tenant_memberships`.
+ """
+ return await list_tenant_memberships(session_factory, user_store, user_id)
+
+
[email protected]("/tenants/{tenant_id}/switch")
+async def switch_tenant(
+ tenant_id: str,
+ response: Response,
+ user_id: Annotated[str, Depends(get_authenticated_user_id)],
+ session: Annotated[AsyncSession, Depends(get_system_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> SessionUserResponse:
+ """Select `tenant_id` for this session: verify membership, then re-mint
+ the cookie carrying it as the tenant claim.
+
+ The membership check is what keeps the claim from being a way in on its
+ own: `_resolve_tenant_id` re-reads `tenant_members` on every request
+ regardless of what the cookie says, so a forged or stale claim already
+ buys nothing — but this route is the one place a *caller* picks the
+ value that goes into it, and it must not let them pick a tenant they do
+ not belong to.
+ """
+ if not await is_tenant_member(session_factory, user_id, tenant_id):
+ raise HTTPException(status_code=403, detail="Not a member of this tenant")
+
+ user = await user_store.get(session, user_id)
+ if user is None:
+ raise HTTPException(status_code=401, detail="User not found")
+
+ set_session_cookie(
+ response, user, config.jwt_secret_key, config.gateway_cookie_secure, tenant_id
+ )
+ return _session_response(user)
diff --git a/core/tests/switch_core/gateway/test_auth_refresh.py b/core/tests/switch_core/gateway/test_auth_refresh.py
index 606c7ddd4..7aa49f282 100644
--- a/core/tests/switch_core/gateway/test_auth_refresh.py
+++ b/core/tests/switch_core/gateway/test_auth_refresh.py
@@ -27,6 +27,13 @@ def _config(*, cookie_secure: bool = False) -> SimpleNamespace:
return SimpleNamespace(jwt_secret_key=_SECRET, gateway_cookie_secure=cookie_secure)
+def _request(*, tenant_id: str | None) -> SimpleNamespace:
+ # refresh() only reads request.state.tenant_id — the tenant
+ # get_current_user just resolved this request to, which it must carry
+ # forward into the re-minted cookie (CHOO-2723).
+ return SimpleNamespace(state=SimpleNamespace(tenant_id=tenant_id))
+
+
def _extract_cookie(response: Response) -> str:
raw = response.headers.get("set-cookie")
assert raw is not None, "refresh did not set a cookie"
@@ -40,7 +47,7 @@ async def test_refresh_remints_cookie_for_current_user() -> None:
user = User(id="u-1", name="Ada", email="[email protected]", role="user")
response = Response()
- result = await refresh(response, user, _config())
+ result = await refresh(_request(tenant_id="tenant-0"), response, user, _config())
token = _extract_cookie(response)
payload = decode_jwt(token, _SECRET)
@@ -54,15 +61,32 @@ async def test_refresh_remints_cookie_for_current_user() -> None:
assert result.email == "[email protected]"
+async def test_refresh_carries_the_selected_tenant_forward() -> None:
+ """The trap the design calls out by name: re-minting from `user` alone
+ would silently drop whichever tenant this session had selected."""
+ user = User(id="u-3", name="Cy", email="[email protected]", role="user")
+ response = Response()
+
+ await refresh(_request(tenant_id="tenant-b"), response, user, _config())
+
+ token = _extract_cookie(response)
+ payload = decode_jwt(token, _SECRET)
+ assert payload["tenant_id"] == "tenant-b"
+
+
async def test_refresh_cookie_is_httponly_and_respects_secure_flag() -> None:
user = User(id="u-2", name="Bo", email="[email protected]", role="admin")
insecure = Response()
- await refresh(insecure, user, _config(cookie_secure=False))
+ await refresh(
+ _request(tenant_id="tenant-0"), insecure, user, _config(cookie_secure=False)
+ )
header = insecure.headers.get("set-cookie") or ""
assert "httponly" in header.lower()
assert "secure" not in header.lower()
secure = Response()
- await refresh(secure, user, _config(cookie_secure=True))
+ await refresh(
+ _request(tenant_id="tenant-0"), secure, user, _config(cookie_secure=True)
+ )
assert "secure" in (secure.headers.get("set-cookie") or "").lower()
diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.py
index b4c928c17..20382418d 100644
--- a/core/tests/switch_core/gateway/test_change_password.py
+++ b/core/tests/switch_core/gateway/test_change_password.py
@@ -60,6 +60,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
jwt_secret_key=_SECRET,
gateway_cookie_secure=False,
gateway_password_login_enabled=True,
+ gateway_tenant_choice_enabled=False,
)
return app
@@ -94,7 +95,7 @@ async def _stored_hash(
def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:
- token = create_jwt(user_id, email, "user", _SECRET)
+ token = create_jwt(user_id, email, "user", _SECRET, None)
return httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://test",
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 fe1035b1a..d02693e5a 100644
--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -33,12 +33,17 @@ import switch_core.gateway as gateway_package
from switch_core.gateway.auth import get_current_user, require_admin
from switch_core.gateway.dependencies import get_session, get_system_session
-# The only routes that may open a session without an authenticated caller,
-# because there is not one yet: both are how a caller becomes authenticated.
-# They take `get_system_session` instead, which says so in the signature.
-_UNAUTHENTICATED_ROUTES = {
+# The only routes that may open a session with no tenant bound. `get_session`
+# is unavailable to them because there is no `get_current_user` to bind one:
+# for login and the OIDC callback there is no caller yet at all; for switching
+# tenants the caller is authenticated (`get_authenticated_user_id`) but has,
+# by construction, not yet selected the tenant this session opens for — see
+# `get_system_session`'s docstring. All three take `get_system_session`
+# instead, which says so in the signature.
+_ROUTES_WITH_NO_TENANT_BOUND = {
("POST", "/auth/login"),
("GET", "/auth/oidc/callback"),
+ ("POST", "/tenants/{tenant_id}/switch"),
}
@@ -100,7 +105,7 @@ def test_every_route_taking_the_session_also_authenticates() -> None:
str(route)
for route in ROUTES
if get_session in route.calls
- and route.key not in _UNAUTHENTICATED_ROUTES
+ and route.key not in _ROUTES_WITH_NO_TENANT_BOUND
and get_current_user not in route.calls
and require_admin not in route.calls
)
@@ -110,12 +115,13 @@ def test_every_route_taking_the_session_also_authenticates() -> None:
)
-def test_the_unauthenticated_routes_are_exactly_the_two_that_sign_you_in() -> None:
- """The exemption above is not a list to grow: `get_system_session` exists
- so that adding a third is a visible act, not a signature nobody reads."""
+def test_the_routes_with_no_tenant_bound_are_exactly_these_three() -> None:
+ """The exemption above is not a list to grow casually: `get_system_session`
+ exists so that adding a fourth is a visible act, not a signature nobody
+ reads."""
assert {
route.key for route in ROUTES if get_system_session in route.calls
- } == _UNAUTHENTICATED_ROUTES
+ } == _ROUTES_WITH_NO_TENANT_BOUND
def test_the_exempt_routes_do_not_also_take_the_tenant_scoped_session() -> None:
@@ -124,5 +130,5 @@ def test_the_exempt_routes_do_not_also_take_the_tenant_scoped_session() -> None:
assert not [
str(route)
for route in ROUTES
- if get_session in route.calls and route.key in _UNAUTHENTICATED_ROUTES
+ if get_session in route.calls and route.key in _ROUTES_WITH_NO_TENANT_BOUND
]
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index b99fc4b2e..a792b02e6 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -1,20 +1,30 @@
-"""Tenant resolution for the gateway (CHOO-2623): a request binds the tenant
-of the *user*, from their membership row — never a guess, never a request
+"""Tenant resolution for the gateway (CHOO-2623, CHOO-2723): a request binds a
+tenant of the *user*, from a membership row — never a guess, never a request
parameter.
-`TestSoleTenantId` covers `gateway.auth.sole_tenant_id` raising rather than
-picking a tenant when a user's memberships aren't exactly one. It takes a
-session factory rather than a session: `tenant_members` is a scoped table, so
-no session can read the row that says what it should be scoped to, and it
-reads through `tenants_of_user` (`db/tenant_lookup.py`) instead, on a session
-of its own with nothing bound.
-`TestAGatewayRequestBindsTheCallersTenant` drives a real HTTP request through
-`get_current_user` end to end — cookie in, `app.tenant_id` on the database
-session out — the same way `test_reference_types_routes.py` builds a
-route-scoped app rather than the process-global `init_dependencies`, so nothing
-here leaks into another test. `TestConcurrentRequests` runs two of those at
-once, in different tenants, because the whole design rests on one request's
-tenant being invisible to another.
+`_resolve_tenant_id` (`gateway/auth.py`) implements the five cases from
+`docs/old/multi-tenancy-phase2-tenants.md`, §4, in order: a tenant claim with a
+matching membership binds it; a claim naming no membership is refused; no
+claim with exactly one membership binds it; no claim with several is a 409
+listing them when `GATEWAY_TENANT_CHOICE_ENABLED` is set, otherwise the same
+403 every multi-membership account got before this phase; no memberships at
+all is a 403. `TestAGatewayRequestBindsTheCallersTenant` and the classes below
+drive real HTTP requests through `get_current_user` end to end — cookie in,
+`app.tenant_id` on the database session out — the same way
+`test_reference_types_routes.py` builds a route-scoped app rather than the
+process-global `init_dependencies`, so nothing here leaks into another test.
+`TestConcurrentRequests` runs two of those at once, in different tenants,
+because the whole design rests on one request's tenant being invisible to
+another.
+
+`TestListTenantsEndpoint` and `TestSwitchTenantEndpoint` cover
+`gateway/tenants.py`'s two routes (§5, §7): listing a caller's own tenants
+without binding one, and re-minting the cookie once they pick one.
+`TestTenantListingHoldsOneConnectionAtATime` is the one pinned in the design
+by name — §7 rejects looping bound sessions from inside a request that
+already holds a connection open, and this proves `list_tenant_memberships`
+does not do that, on the same pool-of-one shape as
+`TestARequestHoldsOneConnection` below.
Uses `httpx.AsyncClient` over `ASGITransport` rather than
`fastapi.testclient.TestClient`: the sync `TestClient` runs the app in a
@@ -32,7 +42,6 @@ from types import SimpleNamespace
from typing import Annotated
import httpx
-import pytest
import pytest_asyncio
from fastapi import Depends, FastAPI
from sqlalchemy import insert, text
@@ -43,70 +52,17 @@ 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 dependencies as gw_deps
-from switch_core.gateway.auth import (
- TenantMembershipError,
- create_jwt,
- get_current_user,
- sole_tenant_id,
-)
+from switch_core.gateway.auth import create_jwt, get_current_user
+from switch_core.gateway.tenants import router as tenants_router
_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
TENANT_B = "tenant-resolution-b"
+NOT_A_MEMBER_TENANT = "tenant-resolution-not-a-member"
-class TestSoleTenantId:
- async def test_raises_when_the_user_has_no_membership(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- async with session_factory() as session:
- user = User(name="orphan", email="[email protected]", role="user")
- session.add(user)
- await session.commit()
- user_id = user.id
-
- with pytest.raises(TenantMembershipError):
- await sole_tenant_id(session_factory, user_id)
-
- async def test_raises_when_the_user_has_more_than_one_membership(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- async with session_factory() as session:
- user = User(name="dual", email="[email protected]", role="user")
- session.add(user)
- await session.flush()
- session.add(Tenant(id=TENANT_B, slug=TENANT_B, name=TENANT_B))
- await session.flush()
- session.add_all(
- [
- TenantMember(
- tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member"
- ),
- TenantMember(tenant_id=TENANT_B, user_id=user.id, role="member"),
- ]
- )
- await session.commit()
- user_id = user.id
-
- with pytest.raises(TenantMembershipError):
- await sole_tenant_id(session_factory, user_id)
-
- async def test_returns_the_one_tenant_a_user_belongs_to(
- self, session_factory: async_sessionmaker[AsyncSession]
- ) -> None:
- async with session_factory() as session:
- user = User(name="single", email="[email protected]", role="user")
- session.add(user)
- await session.flush()
- session.add(
- TenantMember(tenant_id=TENANT_ZERO_ID, user_id=user.id, role="member")
- )
- await session.commit()
- user_id = user.id
-
- assert await sole_tenant_id(session_factory, user_id) == TENANT_ZERO_ID
-
-
-def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+def _app(
+ session_factory: async_sessionmaker[AsyncSession], *, choice_enabled: bool = False
+) -> FastAPI:
"""A route-scoped app: real `get_current_user`, everything it depends on
stubbed to the shared test database rather than through
`init_dependencies` (see `test_reference_types_routes.py`'s `_app`)."""
@@ -120,7 +76,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
- jwt_secret_key=_SECRET
+ jwt_secret_key=_SECRET, gateway_tenant_choice_enabled=choice_enabled
)
@app.get("/whoami")
@@ -143,6 +99,27 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
return app
+def _tenants_app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ """A route-scoped app for `gateway/tenants.py`'s routes, with the same
+ stubbing approach as `_app` above."""
+
+ async def _session_dep():
+ async with session_factory() as session:
+ yield session
+
+ app = FastAPI()
+ app.include_router(tenants_router)
+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ jwt_secret_key=_SECRET,
+ gateway_cookie_secure=False,
+ gateway_tenant_choice_enabled=False,
+ )
+ return app
+
+
async def _session_tenant(session: AsyncSession) -> str | None:
row = await session.execute(text("SELECT current_setting('app.tenant_id', true)"))
return row.scalar_one() or None
@@ -175,6 +152,30 @@ async def _make_user(
return user.id
+async def _make_user_with_memberships(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ name: str,
+ tenant_ids: list[str],
+) -> str:
+ """A user with one membership in each of `tenant_ids`, creating whichever
+ of them isn't tenant zero."""
+ async with session_factory() as session:
+ for tenant_id in tenant_ids:
+ if tenant_id != TENANT_ZERO_ID:
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ await session.flush()
+ user = User(name=name, email=f"{name}@example.invalid", role="user")
+ session.add(user)
+ await session.flush()
+ for tenant_id in tenant_ids:
+ session.add(
+ TenantMember(tenant_id=tenant_id, user_id=user.id, role="member")
+ )
+ await session.commit()
+ return user.id
+
+
class TestAGatewayRequestBindsTheCallersTenant:
async def test_the_sessions_tenant_matches_the_users_membership(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -189,7 +190,7 @@ class TestAGatewayRequestBindsTheCallersTenant:
await session.commit()
user_id = user.id
- token = create_jwt(user_id, "[email protected]", "user", _SECRET)
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
async with _client(_app(session_factory), token) as client:
response = await client.get("/whoami")
@@ -210,10 +211,93 @@ class TestAGatewayRequestBindsTheCallersTenant:
assert response.status_code == 401
+class TestAClaimSelectsAMembership:
+ """Case 1 and case 2 of `_resolve_tenant_id`: a tenant claim binds if it
+ names a membership, and is refused otherwise — the claim never widens
+ what the caller may see beyond what a live membership row already grants
+ (CHOO-2723)."""
+
+ async def test_a_claim_binds_even_with_several_memberships(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The exact case blanket 403 used to refuse outright: two
+ memberships, resolved by the claim rather than guessed at."""
+ user_id = await _make_user_with_memberships(
+ session_factory, name="claimant", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
+ )
+ token = create_jwt(
+ user_id, "[email protected]", "user", _SECRET, TENANT_B
+ )
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 200, response.text
+ assert response.json()["db_tenant_id"] == TENANT_B
+
+ async def test_a_claim_naming_no_membership_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user(
+ session_factory, name="mismatched", tenant_id=TENANT_ZERO_ID
+ )
+ token = create_jwt(
+ user_id, "[email protected]", "user", _SECRET, NOT_A_MEMBER_TENANT
+ )
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 403
+ assert "tenant" in response.json()["detail"]
+ # 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).
+ assert "set-cookie" not in response.headers
+
+
+class TestNoClaimWithSeveralMemberships:
+ """Case 4: behind `GATEWAY_TENANT_CHOICE_ENABLED`. Off, a multi-membership
+ account with no selection gets exactly the 403 every account got before
+ this phase — nobody who could sign in before is broken by it shipping. On,
+ it gets the list to choose from instead of a guess."""
+
+ async def test_flag_off_is_the_same_403_as_before(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ session_factory, name="undecided", 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=False), token
+ ) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 403
+ assert "tenant" in response.json()["detail"]
+
+ async def test_flag_on_is_409_with_the_choices(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ session_factory, name="chooser", 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
+ tenant_ids = {choice["id"] for choice in response.json()["detail"]}
+ assert tenant_ids == {TENANT_ZERO_ID, TENANT_B}
+
+
class TestAUserWithNoMembership:
"""The failure has no current cause — every creation path leaves a
membership — but it must be legible if one ever appears, rather than the
- opaque 500 an uncaught `TenantMembershipError` produces."""
+ opaque 500 an uncaught error would produce."""
async def test_the_response_is_403_and_names_no_user_id(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -226,7 +310,7 @@ class TestAUserWithNoMembership:
await session.commit()
user_id = user.id
- token = create_jwt(user_id, "[email protected]", "user", _SECRET)
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
async with _client(_app(session_factory), token) as client:
response = await client.get("/whoami")
@@ -247,7 +331,9 @@ class TestConcurrentRequests:
app = _app(session_factory)
async def _call(user_id: str, name: str) -> dict:
- token = create_jwt(user_id, f"{name}@example.invalid", "user", _SECRET)
+ token = create_jwt(
+ user_id, f"{name}@example.invalid", "user", _SECRET, None
+ )
async with _client(app, token) as client:
response = await client.get("/whoami", params={"hold": 0.2})
assert response.status_code == 200, response.text
@@ -267,6 +353,74 @@ class TestConcurrentRequests:
assert in_b["db_tenant_id_after"] == TENANT_B
+class TestListTenantsEndpoint:
+ async def test_lists_every_tenant_the_caller_belongs_to(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ session_factory, name="lister", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(_tenants_app(session_factory), token) as client:
+ response = await client.get("/tenants")
+
+ assert response.status_code == 200, response.text
+ by_id = {row["id"]: row for row in response.json()}
+ assert set(by_id) == {TENANT_ZERO_ID, TENANT_B}
+ assert by_id[TENANT_ZERO_ID]["role"] == "member"
+ assert by_id[TENANT_B]["slug"] == TENANT_B
+
+ async def test_a_caller_with_no_selection_can_still_list(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The whole point of authenticating this route independently of
+ `get_current_user`: a multi-membership caller with no claim cannot
+ pass `get_current_user` at all, but must still be able to reach this
+ list in order to pick one."""
+ user_id = await _make_user_with_memberships(
+ session_factory, name="undecided2", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(_tenants_app(session_factory), token) as client:
+ response = await client.get("/tenants")
+
+ assert response.status_code == 200
+ assert {row["id"] for row in response.json()} == {TENANT_ZERO_ID, TENANT_B}
+
+
+class TestSwitchTenantEndpoint:
+ async def test_switching_reminds_the_cookie_with_the_new_claim(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ session_factory, name="switcher", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(_tenants_app(session_factory), token) as client:
+ response = await client.post(f"/tenants/{TENANT_B}/switch")
+
+ assert response.status_code == 200, response.text
+ assert response.json()["id"] == user_id
+ set_cookie = response.headers.get("set-cookie")
+ assert set_cookie is not None and "switch_auth=" in set_cookie
+
+ async def test_switching_to_a_tenant_you_do_not_belong_to_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user(
+ session_factory, name="notmember", tenant_id=TENANT_ZERO_ID
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(_tenants_app(session_factory), token) as client:
+ response = await client.post(f"/tenants/{TENANT_B}/switch")
+
+ assert response.status_code == 403
+
+
@pytest_asyncio.fixture
async def one_connection_session_factory(
postgres_url: str,
@@ -314,10 +468,43 @@ class TestARequestHoldsOneConnection:
user_id = await _make_user(
one_connection_session_factory, name="solo", tenant_id=TENANT_ZERO_ID
)
- token = create_jwt(user_id, "[email protected]", "user", _SECRET)
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
async with _client(_app(one_connection_session_factory), token) as client:
response = await client.get("/whoami")
assert response.status_code == 200, response.text
assert response.json()["db_tenant_id"] == TENANT_ZERO_ID
+
+
+class TestTenantListingHoldsOneConnectionAtATime:
+ """§7, pinned the same way as `TestARequestHoldsOneConnection` above: a
+ caller with several tenants to list must never need two pooled
+ connections open at once to see them.
+
+ This is the test the design calls out as most likely to be written so it
+ cannot fail: a fixture that merely *builds* a pool of one proves nothing
+ by itself unless the work under test would actually need two connections
+ at the same moment to satisfy it. Two memberships are the minimum that
+ makes that possible — `list_tenant_memberships` reading them one tenant
+ at a time, sequentially, is exactly what keeps this passing on a pool of
+ one rather than timing out.
+ """
+
+ async def test_listing_two_tenants_completes_on_a_pool_of_one(
+ self, one_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_id = await _make_user_with_memberships(
+ one_connection_session_factory,
+ name="poolsolo",
+ tenant_ids=[TENANT_ZERO_ID, TENANT_B],
+ )
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET, None)
+
+ async with _client(
+ _tenants_app(one_connection_session_factory), token
+ ) as client:
+ response = await client.get("/tenants")
+
+ assert response.status_code == 200, response.text
+ assert {row["id"] for row in response.json()} == {TENANT_ZERO_ID, TENANT_B}
diff --git a/core/tests/switch_core/test_seed_admin_membership.py b/core/tests/switch_core/test_seed_admin_membership.py
index 5bcbff295..1803acc82 100644
--- a/core/tests/switch_core/test_seed_admin_membership.py
+++ b/core/tests/switch_core/test_seed_admin_membership.py
@@ -36,11 +36,8 @@ import switch_core
from switch_core.config import SwitchConfig
from switch_core.db.models import TENANT_ZERO_ID, TenantMember, User
from switch_core.db.stores.user_store import UserStore
-from switch_core.gateway.auth import (
- TenantMembershipError,
- hash_password,
- sole_tenant_id,
-)
+from switch_core.db.tenant_lookup import tenants_of_user
+from switch_core.gateway.auth import hash_password
from switch_core.main import _seed_admin_user
from switch_core.tenant_context import tenant_scope
@@ -182,8 +179,7 @@ class TestWhatBeingStrandedCosts:
await session.commit()
await _strand_the_admin(session_factory, user_id)
- with pytest.raises(TenantMembershipError):
- await sole_tenant_id(session_factory, user_id)
+ assert await tenants_of_user(session_factory, user_id) == []
async def test_creating_a_user_still_writes_one(
self, session_factory: async_sessionmaker[AsyncSession]