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): resolve the caller's tenant without a second session (CHOO-2623)

Wojciech Wojtyniak3efc430a69dc
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index a81cf72be..2bf9cb5f8 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -84,16 +84,20 @@ class BearerAuthMiddleware:
entirely. The MCP path also requires an agent — registration tokens
are not enough to open an MCP session.
- This is where an authenticated request's tenant gets bound (see
- ``switch_core.tenant_context``), not a FastAPI dependency: this class runs
- as ASGI middleware, ahead of routing and dependency injection entirely,
- so there is no ordering question about whether a downstream ``get_session``
- might query before the tenant is known — it cannot, since it does not run
- until after ``self.app(...)`` is called below. The lookups that resolve
- the credential itself (``_resolve_api_key``, ``_try_oidc``) run on their
- own session, opened directly from ``session_factory`` rather than through
- that downstream seam, because they are what determines the tenant and so
- must run before one is bound.
+ This is where a request's tenant gets bound (see
+ ``switch_core.tenant_context``), for all three credentials — registration
+ tokens included, since the request one of those carries is the request
+ that *creates* the rows every later request is authenticated against.
+
+ A middleware rather than a FastAPI dependency: this class runs ahead of
+ routing and dependency injection entirely, so there is no ordering
+ question about whether a downstream ``get_session`` might query before the
+ tenant is known — it cannot, since it does not run until after
+ ``self.app(...)`` is called below. The lookups that resolve the credential
+ itself (``_resolve_api_key``, ``_try_oidc``) run on their own session,
+ opened directly from ``session_factory`` rather than through that
+ downstream seam, because they are what determines the tenant and so must
+ run before one is bound.
"""
def __init__(
@@ -167,7 +171,20 @@ class BearerAuthMiddleware:
and not path.startswith("/mcp")
):
scope["api_key"] = api_key
- await self.app(scope, receive, send)
+ # The endpoints this reaches *insert* the `api_keys` and `agents`
+ # rows a later request will be authenticated against, and the
+ # branch above then treats `api_keys.tenant_id` as the source of
+ # truth. Registering with no tenant bound would land those rows in
+ # tenant zero by fallback and make that wrong answer permanent and
+ # self-confirming — so bind the token's own tenant here, exactly
+ # as an agent key does.
+ log_token = bind_log_context(tenant_id=api_key.tenant_id)
+ tenant_token = bind_tenant_id(api_key.tenant_id)
+ try:
+ await self.app(scope, receive, send)
+ finally:
+ unbind_tenant_id(tenant_token)
+ unbind_log_context(log_token)
return
response = Response("Invalid credentials", status_code=401)
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index a0c481c26..04b6ea931 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -90,6 +90,7 @@ from switch_core.events import (
ToolCallReport as MatrixToolCallReport,
)
from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE
+from switch_core.tenant_context import tenant_scope
from switch_core.transport import (
TransportError,
)
@@ -461,12 +462,23 @@ class ProtocolService:
exception, to match the HTTP registration path's handling of the
same failure).
Raises AgentExistsError if the name is taken and ``overwrite`` is False.
+
+ The token also decides the *tenant* the new agent and its API key land
+ in, and that is bound here rather than left to the caller. The HTTP
+ registration endpoint has ``BearerAuthMiddleware`` in front of it doing
+ the same thing; this path has nothing in front of it at all — a
+ server-side connector registers its agents from a startup task
+ (``server_connectors/core.py``), where no request and so no tenant
+ exists. Without this the rows would fall back to tenant zero, and
+ because bearer authentication then reads ``api_keys.tenant_id`` back as
+ the source of truth, that guess would confirm itself forever.
"""
token_hash = hashlib.sha256(registration_token.encode()).hexdigest()
async with self.session_factory() as session:
key = await self.api_key_store.get_by_hash(session, token_hash)
if key is None or key.type not in REGISTRATION_KEY_TYPES:
raise PermissionError("Invalid registration token")
+ tenant_id = key.tenant_id
try:
owner_id = await resolve_registration_owner_id(
session, self.user_store, key
@@ -479,20 +491,21 @@ class ProtocolService:
"Agent registration is temporarily unavailable"
) from exc
- return await self.register_agent(
- name=name,
- description=description,
- display_name=display_name,
- connector_type=connector_type,
- integration_profile=integration_profile,
- tools=tools,
- models=models,
- metadata=metadata,
- owner_id=owner_id,
- overwrite=overwrite,
- addressable_by_agent_ids=addressable_by_agent_ids,
- owner_only=owner_only,
- )
+ with tenant_scope(tenant_id):
+ return await self.register_agent(
+ name=name,
+ description=description,
+ display_name=display_name,
+ connector_type=connector_type,
+ integration_profile=integration_profile,
+ tools=tools,
+ models=models,
+ metadata=metadata,
+ owner_id=owner_id,
+ overwrite=overwrite,
+ addressable_by_agent_ids=addressable_by_agent_ids,
+ owner_only=owner_only,
+ )
async def _create_agent(
self,
diff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.py
index c19946116..9124e17c2 100644
--- a/core/switch_core/bridges/agent/server_connectors/core.py
+++ b/core/switch_core/bridges/agent/server_connectors/core.py
@@ -133,6 +133,10 @@ class ConnectorCore:
# ── internal ─────────────────────────────────────────────────────────
async def _register_agent(self, agent: DiscoveredAgent) -> None:
+ # Runs from `start()`, i.e. a startup task with no request and so no
+ # tenant bound. `register_agent_with_token` binds the registration
+ # token's own tenant for the write, which is why nothing is bound
+ # here — see its docstring.
try:
result = await self._protocol.register_agent_with_token(
registration_token=self._registration_token,
diff --git a/core/switch_core/db/engine.py b/core/switch_core/db/engine.py
index 8936a50c2..83a88b371 100644
--- a/core/switch_core/db/engine.py
+++ b/core/switch_core/db/engine.py
@@ -12,7 +12,12 @@ from sqlalchemy.ext.asyncio import (
from sqlalchemy.pool import NullPool
from switch_core.config import SwitchConfig
-from switch_core.db.tenant_session import register_tenant_session_hook
+
+# Imported for its side effect: it registers the `after_begin` hook that stamps
+# the bound tenant onto every session's transaction. Here rather than at a
+# factory call site, so a process that builds an `async_sessionmaker` by hand
+# is covered too — it still needs an engine, and an engine comes from here.
+from switch_core.db import tenant_session # noqa: F401
logger = logging.getLogger(__name__)
@@ -162,9 +167,4 @@ def create_unpooled_engine(config: SwitchConfig) -> AsyncEngine:
def create_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
- # The one place an async_sessionmaker is built, so it is the one seam
- # where registering the tenant-scoping hook (db/tenant_session.py) makes
- # every session it produces covered, rather than relying on every caller
- # of this function to remember to ask for that separately.
- register_tenant_session_hook()
return async_sessionmaker(bind=engine, expire_on_commit=False)
diff --git a/core/switch_core/db/stores/tenant_member_store.py b/core/switch_core/db/stores/tenant_member_store.py
index cf4837875..0945ab862 100644
--- a/core/switch_core/db/stores/tenant_member_store.py
+++ b/core/switch_core/db/stores/tenant_member_store.py
@@ -14,6 +14,10 @@ class TenantMembershipError(Exception):
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".
+
+ Raised, not returned, but not left to reach the client either: the gateway
+ turns it into a 403 naming no user id (`gateway/auth.py`), so a broken
+ account gets an answer an operator can act on instead of a bare 500.
"""
@@ -28,8 +32,9 @@ class TenantMemberStore:
"""The one tenant this user belongs to, raising if that isn't true.
Must run on a session with no tenant bound yet — this *is* how the
- tenant gets found, so it cannot presuppose one (see `get_system_session`
- in `gateway/dependencies.py`).
+ tenant gets found, so it cannot presuppose one. `gateway/auth.py`
+ opens a short-lived session for exactly this and closes it before the
+ request's own session is touched.
"""
result = await session.execute(
select(TenantMember.tenant_id).where(TenantMember.user_id == user_id)
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index d97611154..a35a4a427 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -50,17 +50,35 @@ class UserStore:
a user has no membership, so every path that creates a user — this
one, reached by the admin "create user" endpoint, JIT OIDC
provisioning, and startup admin seeding — must leave exactly one
- `tenant_members` row behind, or that user's first login raises.
-
- Joins the tenant bound to the caller's context, so an admin creating
- a user joins them to their own tenant; falls back to tenant zero for
- the callers with no tenant bound (JIT OIDC provisioning at login, and
- startup/bootstrap seeding) — the only tenant Phase 1 has anyway. The
- role mirrors the migration's own mapping for pre-existing users:
- `owner` for the global admin role, `member` otherwise.
+ `tenant_members` row behind, or that user's first login cannot be
+ placed in a tenant at all.
"""
session.add(user)
await session.flush()
+ await self._ensure_membership(session, user)
+
+ async def _ensure_membership(self, session: AsyncSession, user: User) -> None:
+ """Give `user` a membership if they have none; leave any they have.
+
+ Called from every path that can produce a user who would otherwise
+ have zero: creation, and linking an identity to an account that
+ predates memberships existing. Idempotent because the link path runs
+ against accounts that usually already have one, and adding a second
+ would be worse than adding none — resolution refuses to pick between
+ two.
+
+ Joins the tenant bound to the caller's context, so an admin creating a
+ user joins them to their own tenant; falls back to tenant zero for the
+ callers with no tenant bound (startup and bootstrap seeding) — the
+ only tenant Phase 1 has anyway. The role mirrors the migration's own
+ mapping for pre-existing users: `owner` for the global admin role,
+ `member` otherwise.
+ """
+ existing = await session.execute(
+ select(TenantMember.tenant_id).where(TenantMember.user_id == user.id)
+ )
+ if existing.first() is not None:
+ return
session.add(
TenantMember(
tenant_id=current_tenant_id() or TENANT_ZERO_ID,
@@ -73,6 +91,17 @@ class UserStore:
async def get(self, session: AsyncSession, user_id: str) -> User | None:
return await session.get(User, user_id)
+ async def exists(self, session: AsyncSession, user_id: str) -> bool:
+ """Whether this id names a real account, without loading the row.
+
+ Tenant resolution needs the answer on a session it closes immediately
+ (`gateway/auth.py`), and a `User` loaded there would be attached to a
+ session nobody can commit — the exact shape of bug this replaced. It
+ needs no attribute of the row, only that there is one.
+ """
+ result = await session.execute(select(User.id).where(User.id == user_id))
+ return result.first() is not None
+
async def get_by_email(self, session: AsyncSession, email: str) -> User | None:
"""Case-insensitive: an IdP and a person typing a password don't
reliably agree on the casing of the same mailbox, and accounts must
@@ -237,6 +266,10 @@ class UserStore:
logger.warning(
"Linking OIDC identity (iss=%r, sub=%r) to user %s", iss, sub, user.id
)
+ # Linking reaches accounts this store did not create, including any
+ # that predate memberships. Nothing else repairs an account with none,
+ # and the symptom would be that the person can never sign in again.
+ await self._ensure_membership(session, user)
async def get_all(self, session: AsyncSession) -> list[User]:
result = await session.execute(select(User))
diff --git a/core/switch_core/db/tenant_session.py b/core/switch_core/db/tenant_session.py
index a8a8a855b..87deb3201 100644
--- a/core/switch_core/db/tenant_session.py
+++ b/core/switch_core/db/tenant_session.py
@@ -14,12 +14,23 @@ nothing to leak: `is_local=true` scopes the setting to the transaction, and it
is released the moment that transaction ends, whether by commit or rollback.
Registered once, globally, on `sqlalchemy.orm.Session` — the class every
-`AsyncSession` this codebase creates is built on — via
-`register_tenant_session_hook()`, called from
-`switch_core.db.engine.create_session_factory`. That is the one place an
-`async_sessionmaker` is built, so calling it there is the single seam that
-makes it "impossible to open a session that skips setting the tenant" rather
-than a convention to remember at each one.
+`AsyncSession` this codebase creates is built on — as a side effect of
+importing this module, not of calling a factory. Importing is the weakest
+precondition available: a process that builds its own `async_sessionmaker`
+rather than calling `switch_core.db.engine.create_session_factory` still gets
+the hook, because `db/engine.py` imports this module and an engine is the one
+thing every session needs.
+
+The boundary that gives, stated exactly: **no ORM session in this process can
+skip setting the tenant.** Not "no statement can reach the database without
+one" — two paths never become a `Session` at all, both deliberately:
+
+- the delivery listener (`messages/notify.py`) reaches past SQLAlchemy to the
+ raw asyncpg connection to issue `LISTEN`, so nothing it does passes through
+ this hook. It reads no scoped table, which is what makes that acceptable
+ rather than a gap.
+- Alembic (`migrations/env.py`) runs a migration on a bare `Connection`, and
+ is cross-tenant by definition.
When no tenant is bound (see `switch_core.tenant_context`), the hook does
nothing rather than substituting one — a system session (auth resolution,
@@ -43,8 +54,10 @@ _registered = False
def register_tenant_session_hook() -> None:
"""Attach the `after_begin` hook, once per process.
- Idempotent so callers don't have to track whether some earlier
- `create_session_factory` call already registered it.
+ Called at the bottom of this module, so importing it is enough. Idempotent
+ so that an explicit call — a test asserting the registration, say — cannot
+ end up with the hook attached twice and the `set_config` issued twice per
+ transaction.
"""
global _registered
if _registered:
@@ -63,3 +76,6 @@ def _set_tenant_on_begin(
text("SELECT set_config('app.tenant_id', :tenant_id, true)"),
{"tenant_id": tenant_id},
)
+
+
+register_tenant_session_hook()
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 9a8565e59..6a026846a 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -1,29 +1,36 @@
from __future__ import annotations
import datetime
+import logging
from collections.abc import AsyncIterator
from typing import Annotated
import bcrypt
import jwt
from fastapi import Depends, HTTPException, Request, Response
-from sqlalchemy.ext.asyncio import AsyncSession
+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.stores.room_store import RoomStore
-from switch_core.db.stores.tenant_member_store import TenantMemberStore
+from switch_core.db.stores.tenant_member_store import (
+ TenantMembershipError,
+ TenantMemberStore,
+)
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.dependencies import (
get_config,
- get_system_session,
+ get_session,
+ get_session_factory,
get_tenant_member_store,
get_user_store,
)
from switch_core.logging_context import bind_log_context, unbind_log_context
from switch_core.tenant_context import bind_tenant_id, unbind_tenant_id
+logger = logging.getLogger(__name__)
+
JWT_ALGORITHM = "HS256"
JWT_EXPIRY_HOURS = 24
@@ -86,40 +93,84 @@ def decode_jwt(token: str, secret_key: str) -> dict:
raise HTTPException(status_code=401, detail="Invalid token")
+async def _resolve_tenant_id(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ tenant_member_store: TenantMemberStore,
+ user_id: str,
+) -> str:
+ """Which tenant the JWT's subject belongs to, before one is bound.
+
+ Runs on its own session, opened and closed here, because the lookup is
+ what *determines* the tenant and so cannot run on a session that is
+ supposed to already carry it. Short-lived on purpose: held as a yield
+ dependency instead, it 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.
+ """
+ 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 tenant_member_store.get_sole_tenant_id(system_session, 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)
+ raise HTTPException(
+ status_code=403,
+ detail=(
+ "This account is not a member of exactly one tenant; "
+ "ask an administrator to check its membership."
+ ),
+ ) from exc
+
+
async def get_current_user(
request: Request,
- session: Annotated[AsyncSession, Depends(get_system_session)],
+ session: Annotated[AsyncSession, Depends(get_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
user_store: Annotated[UserStore, Depends(get_user_store)],
tenant_member_store: Annotated[TenantMemberStore, Depends(get_tenant_member_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> AsyncIterator[User]:
- """Authenticate the caller and bind their tenant for the rest of the request.
-
- Runs on `get_system_session`, not `get_session`: resolving who is asking
- — decoding the cookie, loading the user, finding their membership — has
- to happen before a tenant is known, so it cannot run on the session an
- endpoint later scopes by one. Every gateway endpoint that uses
- `get_session` also depends on this (directly, or via `require_admin`), so
- by the time an endpoint issues its first query the tenant this function
- binds is already in place — see `get_session`'s docstring for why
- declaration order doesn't matter here.
-
- Phase 1 has exactly one tenant, so `get_sole_tenant_id` returning more
- or fewer than one membership is a bug, not a 401 — it is allowed to raise
- past this function rather than being turned into a guess.
+ """Authenticate the caller, bind their tenant, and load them on the
+ request's own session.
+
+ The order is the whole design. Resolving the tenant needs only the user id
+ the JWT already carries, so it happens first, on a separate short-lived
+ session (`_resolve_tenant_id`) that is closed before this one is touched.
+ Only then is the tenant bound and the `User` read — from `get_session`,
+ 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.
"""
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)
- user = await user_store.get(session, payload["sub"])
- if user is None:
- raise HTTPException(status_code=401, detail="User not found")
- tenant_id = await tenant_member_store.get_sole_tenant_id(session, user.id)
+ user_id = payload["sub"]
+
+ tenant_id = await _resolve_tenant_id(
+ session_factory, user_store, tenant_member_store, user_id
+ )
- log_token = bind_log_context(user_id=user.id, tenant_id=tenant_id)
+ log_token = bind_log_context(user_id=user_id, tenant_id=tenant_id)
tenant_token = bind_tenant_id(tenant_id)
try:
+ user = await user_store.get(session, user_id)
+ if user is None:
+ # Deleted between the two reads; rare, and still not a 500.
+ raise HTTPException(status_code=401, detail="User not found")
yield user
finally:
unbind_tenant_id(tenant_token)
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 80529940c..397e906f4 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -23,6 +23,7 @@ from switch_core.gateway.dependencies import (
get_config,
get_external_user_store,
get_session,
+ get_system_session,
get_user_store,
)
from switch_core.gateway.schemas import (
@@ -84,10 +85,14 @@ async def get_version(
async def login(
req: LoginRequest,
response: Response,
- session: Annotated[AsyncSession, Depends(get_session)],
+ session: Annotated[AsyncSession, Depends(get_system_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
) -> SessionUserResponse:
+ # `get_system_session`, not `get_session`: there is no caller to take a
+ # tenant from until this route decides there is one. It only ever reads
+ # `users`, which is global (a person is one account across tenants), so
+ # there is nothing here a tenant would scope even once policies land.
if not config.gateway_password_login_enabled:
raise HTTPException(status_code=403, detail="Password login is disabled")
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index b0fffa3a7..2123d0611 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -77,16 +77,24 @@ async def get_session() -> AsyncIterator[AsyncSession]:
Opening it does no I/O: the transaction — and with it the `after_begin`
hook that stamps `app.tenant_id` (`db/tenant_session.py`) — only begins on
- the first query the caller issues. By the time an endpoint body runs its
- first query, `get_current_user` (or `require_admin`) has already resolved
- and bound the tenant, because FastAPI resolves every dependency an
- endpoint declares before calling the endpoint itself, regardless of the
- order its parameters are listed in. A dependency that queries the
- database *during its own resolution*, before the tenant is known, would
- break that — none does; auth resolution runs on `get_system_session`
- instead, a separate session, precisely so it never becomes this one.
-
- Pre-auth lookups (deciding who is asking) must not use this — see
+ the first query someone issues on it. `get_current_user` takes *this*
+ session (not one of its own) and binds the caller's tenant before its
+ first query on it, so the transaction is stamped from the moment it opens,
+ and the `User` an endpoint receives belongs to the session that endpoint
+ commits.
+
+ Resolution order is load-bearing, so do not read the paragraph above as
+ "order doesn't matter". FastAPI resolves an endpoint's dependencies in
+ declaration order, and a sibling dependency declared *before*
+ `get_current_user` that queries this session during its own resolution
+ would open the transaction with no tenant bound and keep it that way for
+ the rest of the request. None does today — every other dependency is a
+ plain accessor — and
+ `tests/switch_core/gateway/test_session_requires_authentication.py` keeps
+ the weaker, checkable half of that true: every route reaching this
+ dependency also reaches `get_current_user`.
+
+ A request with no authenticated caller must not use this — see
`get_system_session`.
"""
async with _state["session_factory"]() as session:
@@ -94,15 +102,20 @@ async def get_session() -> AsyncIterator[AsyncSession]:
async def get_system_session() -> AsyncIterator[AsyncSession]:
- """A session opened before any tenant is known.
-
- Used only by the lookups that resolve *who* is asking and *which tenant*
- they belong to (`gateway/auth.py`'s `get_current_user`) — never by an
- endpoint. Named separately from `get_session` so a system lookup reads as
- a deliberate, reviewable exception rather than an accidentally-unscoped
- session; nothing about opening it differs from `get_session` today, since
- row-level security is not enforced yet, but the two must stay
- interchangeable in behaviour only, never in name.
+ """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, since row-level security is not enforced yet; 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
+ `oidc_routes.py`).
"""
async with _state["session_factory"]() as session:
yield session
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 9cbde51c5..5c45ef4e3 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -9,13 +9,19 @@ from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import RedirectResponse
from switch_core.config import SwitchConfig
+from switch_core.db.models import TENANT_ZERO_ID
from switch_core.db.stores.user_store import (
OidcIdentityConflictError,
OidcIdentityRaceError,
UserStore,
)
from switch_core.gateway.auth import set_session_cookie
-from switch_core.gateway.dependencies import get_config, get_session, get_user_store
+from switch_core.gateway.dependencies import (
+ get_config,
+ get_system_session,
+ get_user_store,
+)
+from switch_core.tenant_context import tenant_scope
logger = logging.getLogger(__name__)
@@ -73,9 +79,12 @@ async def oidc_login(
async def oidc_callback(
request: Request,
config: Annotated[SwitchConfig, Depends(get_config)],
- session: Annotated[AsyncSession, Depends(get_session)],
+ session: Annotated[AsyncSession, Depends(get_system_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
) -> RedirectResponse:
+ # `get_system_session`: nobody is signed in yet, so there is no principal
+ # to take a tenant from — the tenant this route writes into is chosen
+ # below, deliberately.
if not config.gateway_oidc_enabled:
raise HTTPException(status_code=404, detail="OIDC login is not configured")
client = _client()
@@ -125,25 +134,38 @@ async def oidc_callback(
iss = claims.get("iss") or config.gateway_oidc_issuer_url
if not iss:
raise HTTPException(status_code=401, detail="OIDC token missing issuer")
- try:
- user = await user_store.get_or_create_oidc_user(
- session, iss=iss, email=email, name=name, sub=sub, email_verified=verified
- )
- except OidcIdentityConflictError as exc:
- logger.warning("OIDC identity conflict: %s", exc)
- raise HTTPException(status_code=409, detail=str(exc)) from exc
- except OidcIdentityRaceError as exc:
- # Transient contention, not a rejected security decision (see the
- # exception's docstring) — 503 so an operator's dashboards can tell
- # this apart from the 409s above rather than lumping a retry storm in
- # with attack signal.
- logger.warning("OIDC identity resolution raced: %s", exc)
- raise HTTPException(
- status_code=503,
- detail="Login is temporarily contended, please try again",
- headers={"Retry-After": "1"},
- ) from exc
- await session.commit()
+ # A first sign-in provisions the account just in time, and that account
+ # needs a tenant: a user with no membership can never sign in again (see
+ # `gateway/auth.py`). Exactly one tenant exists, and this names it rather
+ # than letting `TenantScoped`'s fallback pick it by accident — the two
+ # produce the same row today, but only one of them is a decision. Sign-up
+ # creating a tenant of its own is a later phase, and this is the line it
+ # changes.
+ with tenant_scope(TENANT_ZERO_ID):
+ try:
+ user = await user_store.get_or_create_oidc_user(
+ session,
+ iss=iss,
+ email=email,
+ name=name,
+ sub=sub,
+ email_verified=verified,
+ )
+ except OidcIdentityConflictError as exc:
+ logger.warning("OIDC identity conflict: %s", exc)
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except OidcIdentityRaceError as exc:
+ # Transient contention, not a rejected security decision (see the
+ # exception's docstring) — 503 so an operator's dashboards can tell
+ # this apart from the 409s above rather than lumping a retry storm
+ # in with attack signal.
+ logger.warning("OIDC identity resolution raced: %s", exc)
+ raise HTTPException(
+ status_code=503,
+ detail="Login is temporarily contended, please try again",
+ headers={"Retry-After": "1"},
+ ) from exc
+ await session.commit()
# Verify-at-login only: we don't persist the IdP tokens. Land the browser
# back on the SPA with our own session cookie set.
diff --git a/core/tests/conftest.py b/core/tests/conftest.py
index 46d832e55..9f6f8b34b 100644
--- a/core/tests/conftest.py
+++ b/core/tests/conftest.py
@@ -60,10 +60,9 @@ async def session_factory(
await conn.run_sync(Base.metadata.create_all)
await _seed_tenant_zero(conn)
try:
- # Goes through the same factory constructor production wiring uses
- # (not a bare `async_sessionmaker(...)`) so the tenant-scoping
- # `after_begin` hook (db/tenant_session.py) is registered here too —
- # this fixture backs most of the store test suite.
+ # Goes through the same factory constructor production wiring uses,
+ # so this fixture — which backs most of the store test suite — differs
+ # from production in as little as possible.
yield create_session_factory(engine)
finally:
async with engine.begin() as conn:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
index ebb2c1a7b..5e673d170 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_addressing_policy.py
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.addressing import parse_policy
from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.db.models import TENANT_ZERO_ID
from tests.switch_core.bridges.agent.protocol.registration_harness import (
PROFILE,
make_owner,
@@ -192,6 +193,10 @@ class TestRegisterWithTokenPassesThrough:
def _stub_key(owner_id: str): # type: ignore[no-untyped-def]
async def _get_by_key(_session: AsyncSession, _token: str) -> object:
- return SimpleNamespace(user_id=owner_id, type="registration")
+ # Carries a `tenant_id` because registration binds the token's tenant
+ # for the write it delegates to — see `register_agent_with_token`.
+ return SimpleNamespace(
+ user_id=owner_id, type="registration", tenant_id=TENANT_ZERO_ID
+ )
return _get_by_key
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py
new file mode 100644
index 000000000..b004bcc73
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_tenant.py
@@ -0,0 +1,133 @@
+"""`register_agent_with_token` puts the new agent in the *token's* tenant.
+
+This is the registration path with nothing in front of it: a server-side
+connector registers its discovered agents from a startup task
+(`server_connectors/core.py`), where there is no request and so no bound
+tenant. The HTTP path has `BearerAuthMiddleware` binding one; this one has to
+bind it itself, from the same source of truth — `api_keys.tenant_id`.
+
+Getting it wrong is not a transient mistake. The rows written here are what a
+later bearer request is authenticated against, and that request reads
+`api_keys.tenant_id` back to decide the tenant — so an agent registered into
+tenant zero by fallback stays there, and keeps confirming itself.
+"""
+
+from __future__ import annotations
+
+import hashlib
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import TENANT_ZERO_ID, Agent, ApiKey, Client, Tenant, User
+from switch_core.tenant_context import current_tenant_id
+from tests.switch_core.bridges.agent.protocol.registration_harness import (
+ PROFILE,
+ make_service,
+)
+
+TENANT_B = "register-token-tenant-b"
+
+
+async def _seed_token(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ token: str,
+ tenant_id: str,
+) -> None:
+ async with session_factory() as session:
+ if tenant_id != TENANT_ZERO_ID:
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ await session.flush()
+ user = User(name="minter", email=f"minter-{tenant_id}@test", role="user")
+ session.add(user)
+ await session.flush()
+ session.add(
+ ApiKey(
+ tenant_id=tenant_id,
+ user_id=user.id,
+ key_hash=hashlib.sha256(token.encode()).hexdigest(),
+ encrypted_key="irrelevant",
+ label="registration",
+ type="registration",
+ )
+ )
+ await session.commit()
+
+
+class TestRegistrationTokenDecidesTheTenant:
+ async def test_the_agent_and_its_credentials_land_in_the_tokens_tenant(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)
+ svc = make_service(session_factory)
+
+ result = await svc.register_agent_with_token(
+ registration_token="reg-tok",
+ name="connector-agent",
+ description="discovered by a connector",
+ connector_type="server-side:test",
+ integration_profile=PROFILE,
+ owner_only=False,
+ )
+
+ async with session_factory() as session:
+ agent = await session.get(Agent, result.agent_id)
+ assert agent is not None
+ assert agent.tenant_id == TENANT_B
+
+ key = await session.get(ApiKey, agent.api_key_id)
+ assert key is not None
+ assert key.tenant_id == TENANT_B
+
+ client = await session.get(Client, agent.client_id)
+ assert client is not None
+ assert client.tenant_id == TENANT_B
+
+ async def test_nothing_stays_bound_after_registration_returns(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)
+ svc = make_service(session_factory)
+
+ assert current_tenant_id() is None
+ await svc.register_agent_with_token(
+ registration_token="reg-tok",
+ name="another-agent",
+ description="d",
+ connector_type="server-side:test",
+ integration_profile=PROFILE,
+ owner_only=False,
+ )
+ assert current_tenant_id() is None
+
+ async def test_no_row_falls_back_to_tenant_zero(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The failure mode this exists to prevent, stated as an assertion:
+ the `TenantScoped` default silently produces tenant zero, so a
+ registration that bound nothing would leave rows there and look fine.
+ """
+ await _seed_token(session_factory, token="reg-tok", tenant_id=TENANT_B)
+ svc = make_service(session_factory)
+
+ await svc.register_agent_with_token(
+ registration_token="reg-tok",
+ name="zero-check-agent",
+ description="d",
+ connector_type="server-side:test",
+ integration_profile=PROFILE,
+ owner_only=False,
+ )
+
+ async with session_factory() as session:
+ stray_agents = await session.execute(
+ select(Agent.name).where(Agent.tenant_id == TENANT_ZERO_ID)
+ )
+ stray_keys = await session.execute(
+ select(ApiKey.label).where(
+ ApiKey.tenant_id == TENANT_ZERO_ID, ApiKey.type == "agent"
+ )
+ )
+ assert stray_agents.scalars().all() == []
+ assert stray_keys.scalars().all() == []
diff --git a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
index f23b6f603..dcef7b913 100644
--- a/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
+++ b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
@@ -1,6 +1,13 @@
"""BearerAuthMiddleware binds the tenant of the resolved credential (CHOO-2623):
-`api_keys.tenant_id` for an agent key, before the wrapped app ever runs — and
-unbinds it once that call returns, so it cannot outlive the request.
+`api_keys.tenant_id`, before the wrapped app ever runs — and unbinds it once
+that call returns, so it cannot outlive the request.
+
+That holds for a registration token as well as an agent key, and it matters
+more there: the endpoints a registration token reaches *insert* the `api_keys`
+and `agents` rows that later requests are authenticated against, and this
+middleware then reads `api_keys.tenant_id` back as the source of truth. A
+registration that bound nothing would put those rows in tenant zero by
+fallback and make that guess permanent.
"""
from __future__ import annotations
@@ -18,6 +25,7 @@ from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.tenant_context import current_tenant_id
TENANT_A = "bearer-auth-tenant-a"
+TENANT_B = "bearer-auth-tenant-b"
def _hash(token: str) -> str:
@@ -70,6 +78,36 @@ async def _seed_agent(
await session.commit()
+async def _seed_registration_key(
+ session_factory: async_sessionmaker[AsyncSession],
+ token: str,
+ tenant_id: str,
+ key_type: str = "registration",
+) -> None:
+ """A registration token: an ApiKey row with no Agent behind it."""
+ async with session_factory() as session:
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ await session.flush()
+
+ user = User(
+ name="minter", email=f"minter-{tenant_id}@example.invalid", role="user"
+ )
+ session.add(user)
+ await session.flush()
+
+ session.add(
+ ApiKey(
+ tenant_id=tenant_id,
+ user_id=user.id,
+ key_hash=_hash(token),
+ encrypted_key="enc",
+ label="registration",
+ type=key_type,
+ )
+ )
+ await session.commit()
+
+
def _middleware(session_factory: Any) -> tuple[BearerAuthMiddleware, dict]:
captured: dict[str, Any] = {}
@@ -78,6 +116,7 @@ def _middleware(session_factory: Any) -> tuple[BearerAuthMiddleware, dict]:
# stack — the only place the bound tenant is supposed to be visible.
captured["tenant_id"] = current_tenant_id()
captured["agent_id"] = scope.get("agent_id")
+ captured["api_key_tenant_id"] = getattr(scope.get("api_key"), "tenant_id", None)
mw = BearerAuthMiddleware(
_app,
@@ -89,7 +128,9 @@ def _middleware(session_factory: Any) -> tuple[BearerAuthMiddleware, dict]:
return mw, captured
-async def _dispatch(mw: BearerAuthMiddleware, token: str) -> list[dict]:
+async def _dispatch(
+ mw: BearerAuthMiddleware, token: str, path: str = "/agents/whatever"
+) -> list[dict]:
async def receive() -> dict:
return {"type": "http.request"}
@@ -100,7 +141,7 @@ async def _dispatch(mw: BearerAuthMiddleware, token: str) -> list[dict]:
scope = {
"type": "http",
- "path": "/agents/whatever",
+ "path": path,
"headers": [(b"authorization", f"Bearer {token}".encode())],
}
await mw(scope, receive, send)
@@ -140,3 +181,54 @@ class TestBearerAuthBindsTheApiKeysTenant:
assert sent[0]["status"] == 401
assert captured == {}
assert current_tenant_id() is None
+
+
+class TestBearerAuthBindsARegistrationTokensTenant:
+ async def test_the_registration_branch_binds_the_keys_tenant(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_registration_key(session_factory, "reg-tok", TENANT_B)
+ mw, captured = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "reg-tok")
+
+ assert sent == [] # passed through to the registration handler
+ assert captured["agent_id"] is None # no agent behind a registration key
+ assert captured["api_key_tenant_id"] == TENANT_B
+ assert captured["tenant_id"] == TENANT_B
+
+ async def test_the_bootstrap_branch_binds_the_keys_tenant(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The deployment-wide token takes the same branch and must behave the
+ # same: it is the credential a fresh deployment registers with.
+ await _seed_registration_key(
+ session_factory, "boot-tok", TENANT_B, key_type="bootstrap"
+ )
+ mw, captured = _middleware(session_factory)
+
+ await _dispatch(mw, "boot-tok")
+
+ assert captured["tenant_id"] == TENANT_B
+
+ async def test_the_tenant_is_unbound_once_the_call_returns(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_registration_key(session_factory, "reg-tok", TENANT_B)
+ mw, _ = _middleware(session_factory)
+
+ assert current_tenant_id() is None
+ await _dispatch(mw, "reg-tok")
+ assert current_tenant_id() is None
+
+ async def test_mcp_still_refuses_a_registration_token_and_binds_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_registration_key(session_factory, "reg-tok", TENANT_B)
+ mw, captured = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "reg-tok", path="/mcp/messages")
+
+ assert sent[0]["status"] == 401
+ assert captured == {}
+ assert current_tenant_id() is None
diff --git a/core/tests/switch_core/db/test_tenant_session_hook.py b/core/tests/switch_core/db/test_tenant_session_hook.py
index 70708ee5c..191a766ba 100644
--- a/core/tests/switch_core/db/test_tenant_session_hook.py
+++ b/core/tests/switch_core/db/test_tenant_session_hook.py
@@ -1,28 +1,34 @@
"""The `after_begin` hook (`db/tenant_session.py`): it stamps `app.tenant_id`
-on a transaction while the bound context says so, releases it at commit, and
-— the exact prior-art bug this design exists to prevent — must not let a
-tenant leak from one session into the next session that reuses the same
-pooled connection.
+on a transaction while the bound context says so, releases it when that
+transaction ends however it ends, and — the exact prior-art bug this design
+exists to prevent — must not let a tenant leak from one session into the next
+session that reuses the same pooled connection.
Uses its own single-connection engine (`pool_size=1, max_overflow=0`) rather
than the shared `session_factory` fixture, so "the next session reuses the
same physical connection" is guaranteed rather than incidental — verified
-directly below via `pg_backend_pid()`.
+directly below via `pg_backend_pid()`. Tenant A followed by *tenant B* on that
+one connection is the case that distinguishes "released" from merely
+"overwritten"; tenant A followed by nothing cannot tell them apart.
"""
from __future__ import annotations
from collections.abc import AsyncIterator
+import pytest
import pytest_asyncio
-from sqlalchemy import text
+from sqlalchemy import event, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.orm import Session
+from switch_core.db import tenant_session
from switch_core.db.base import Base
from switch_core.db.engine import create_session_factory
from switch_core.tenant_context import tenant_scope
TENANT_A = "tenant-hook-a"
+TENANT_B = "tenant-hook-b"
@pytest_asyncio.fixture
@@ -33,8 +39,9 @@ async def single_connection_session_factory(
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
try:
- # Goes through the production factory constructor so the
- # after_begin hook is registered, same as the shared fixture.
+ # Goes through the production factory constructor, same as the shared
+ # fixture. The hook itself is registered on import, not by this call —
+ # `TestTheHookIsRegisteredByImportAlone` is what pins that.
yield create_session_factory(engine)
finally:
async with engine.begin() as conn:
@@ -58,6 +65,66 @@ async def _pid_and_setting(session: AsyncSession) -> tuple[int, str | None]:
return pid, (value or None)
+class TestTheHookIsRegisteredByImportAlone:
+ """Registration must not depend on anyone calling anything.
+
+ Attached as a side effect of `create_session_factory` instead, a process
+ that builds its own `async_sessionmaker` would silently get no tenant on
+ any session — the hook would fail open, and nothing would say so.
+ """
+
+ def test_importing_the_module_attaches_the_listener(self) -> None:
+ assert event.contains(
+ Session, "after_begin", tenant_session._set_tenant_on_begin
+ )
+
+ async def test_a_hand_built_sessionmaker_is_covered_too(
+ self, postgres_url: str
+ ) -> None:
+ engine = create_async_engine(postgres_url)
+ try:
+ # Deliberately not create_session_factory.
+ factory = async_sessionmaker(bind=engine, expire_on_commit=False)
+ async with factory() as session:
+ with tenant_scope(TENANT_A):
+ assert await _current_setting(session) == TENANT_A
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+ async def test_registering_twice_does_not_stamp_twice(
+ self, postgres_url: str
+ ) -> None:
+ """The idempotence guard, asserted on what it is for rather than on a
+ flag: a second listener would issue `set_config` twice per
+ transaction, on every transaction the process ever opens."""
+ engine = create_async_engine(postgres_url)
+ statements: list[str] = []
+
+ @event.listens_for(engine.sync_engine, "before_cursor_execute")
+ def _record(
+ conn: object,
+ cursor: object,
+ statement: str,
+ parameters: object,
+ context: object,
+ executemany: bool,
+ ) -> None:
+ statements.append(statement)
+
+ try:
+ tenant_session.register_tenant_session_hook()
+ factory = async_sessionmaker(bind=engine, expire_on_commit=False)
+ async with factory() as session:
+ with tenant_scope(TENANT_A):
+ await _current_setting(session)
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+ assert sum("set_config" in statement for statement in statements) == 1
+
+
class TestTenantSetOnBeginAndReleasedOnCommit:
async def test_tenant_is_visible_inside_the_transaction(
self, single_connection_session_factory: async_sessionmaker[AsyncSession]
@@ -81,6 +148,42 @@ class TestTenantSetOnBeginAndReleasedOnCommit:
assert await _current_setting(session) is None
+class TestTenantIsReleasedWhenATransactionRollsBack:
+ """`is_local=true` releases the setting at the end of the transaction
+ whichever way it ends. A rollback path that kept it would leave the value
+ on a connection heading straight back to the pool."""
+
+ async def test_an_explicit_rollback_releases_it(
+ self, single_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with single_connection_session_factory() as session:
+ with tenant_scope(TENANT_A):
+ assert await _current_setting(session) == TENANT_A
+ await session.rollback()
+
+ # A new transaction on the same connection, nothing bound.
+ assert await _current_setting(session) is None
+
+ async def test_an_exception_out_of_the_session_releases_it(
+ self, single_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ pids: list[int] = []
+
+ with pytest.raises(RuntimeError, match="boom"):
+ async with single_connection_session_factory() as session:
+ with tenant_scope(TENANT_A):
+ pid, setting = await _pid_and_setting(session)
+ pids.append(pid)
+ assert setting == TENANT_A
+ raise RuntimeError("boom")
+
+ # The session closed by rolling back, and handed the connection back.
+ async with single_connection_session_factory() as session:
+ pid, setting = await _pid_and_setting(session)
+ assert pid == pids[0], "the pool did not actually reuse the connection"
+ assert setting is None
+
+
class TestNoLeakAcrossAPooledConnection:
async def test_a_reused_connection_does_not_inherit_the_previous_tenant(
self, single_connection_session_factory: async_sessionmaker[AsyncSession]
@@ -100,3 +203,33 @@ class TestNoLeakAcrossAPooledConnection:
pid_b, setting_b = await _pid_and_setting(session)
assert pid_b == pid_a, "the pool did not actually reuse the connection"
assert setting_b is None
+
+ async def test_a_reused_connection_carries_the_second_tenant_not_the_first(
+ self, single_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The case the test above cannot see.
+
+ "A, then nothing" passes whether the hook releases the old value or
+ merely overwrites it, because there is no new value to overwrite it
+ with. "A, then B" fails if release is broken *and* B's `set_config`
+ ever fails to run — and, more usefully, pins that B is what the
+ connection reports rather than A lingering underneath it.
+ """
+ async with single_connection_session_factory() as session:
+ with tenant_scope(TENANT_A):
+ pid_a, setting_a = await _pid_and_setting(session)
+ assert setting_a == TENANT_A
+ await session.commit()
+
+ async with single_connection_session_factory() as session:
+ with tenant_scope(TENANT_B):
+ pid_b, setting_b = await _pid_and_setting(session)
+ assert pid_b == pid_a, "the pool did not actually reuse the connection"
+ assert setting_b == TENANT_B
+ await session.commit()
+
+ # And once neither is bound, the connection reports neither.
+ async with single_connection_session_factory() as session:
+ pid_c, setting_c = await _pid_and_setting(session)
+ assert pid_c == pid_a
+ assert setting_c is None
diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.py
index 07b883d7d..56e13d9f7 100644
--- a/core/tests/switch_core/gateway/test_change_password.py
+++ b/core/tests/switch_core/gateway/test_change_password.py
@@ -1,100 +1,207 @@
-"""Tests for self-service password change (PUT /auth/me/password).
-
-Exercises the route coroutine directly — same approach as test_auth_refresh.py.
-A lightweight async session stub replaces the real DB session so the test runs
-without PostgreSQL.
+"""Self-service password change (PUT /auth/me/password), end to end.
+
+Deliberately not a stubbed session. The endpoint mutates the `User` object
+`get_current_user` handed it and commits the session `get_session` handed it,
+so it is only correct if those are the *same* session — and a fake session
+records a commit no matter which. This drives real HTTP against real Postgres
+and then proves the change survived by signing in again with the new password,
+which is the only assertion that cannot pass on a write that was never issued.
+
+Uses `httpx.AsyncClient` over `ASGITransport` rather than
+`fastapi.testclient.TestClient` for the same reason as
+`test_tenant_resolution.py`: the sync client runs the app on its own event
+loop, and the `session_factory` fixture's connections belong to this one.
"""
from __future__ import annotations
+from types import SimpleNamespace
+
+import httpx
import pytest
-from fastapi import HTTPException
+from fastapi import FastAPI
from pydantic import ValidationError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import User
-from switch_core.gateway.auth import hash_password, verify_password
-from switch_core.gateway.auth_routes import change_password
+from switch_core.db.stores.tenant_member_store import TenantMemberStore
+from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway import dependencies as gw_deps
+from switch_core.gateway.auth import create_jwt, hash_password, verify_password
+from switch_core.gateway.auth_routes import router
from switch_core.gateway.schemas import ChangePasswordRequest
+_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
+_OLD_PASSWORD = "old-password-1"
+_NEW_PASSWORD = "new-password-1"
-class _FakeSession:
- """Stub that records whether commit was called."""
-
- def __init__(self) -> None:
- self.committed = False
-
- async def commit(self) -> None:
- self.committed = True
-
+_USER_STORE = UserStore()
-def _user(password: str = "old-password-1") -> User:
- return User(
- id="u-1",
- name="Ada",
- role="user",
- password_hash=hash_password(password),
- )
-
-
-async def test_happy_path_changes_password() -> None:
- user = _user()
- session = _FakeSession()
- req = ChangePasswordRequest(
- current_password="old-password-1", new_password="new-password-1"
- )
- result = await change_password(req, session, user) # type: ignore[arg-type]
+def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
+ """The real auth router, with only the process-global wiring replaced.
- assert result == {"ok": True}
- assert session.committed
- assert verify_password("new-password-1", user.password_hash)
- assert not verify_password("old-password-1", user.password_hash)
+ `get_session` is overridden with one that opens a session per request, the
+ way the real one does — not with a per-call session — so FastAPI's
+ dependency cache hands the endpoint and `get_current_user` the same object,
+ which is the property under test.
+ """
+ async def _session_dep():
+ async with session_factory() as session:
+ yield session
-async def test_wrong_current_password_returns_403() -> None:
- user = _user()
- session = _FakeSession()
- req = ChangePasswordRequest(
- current_password="wrong-password", new_password="new-password-1"
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[gw_deps.get_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep
+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory
+ app.dependency_overrides[gw_deps.get_user_store] = lambda: _USER_STORE
+ app.dependency_overrides[gw_deps.get_tenant_member_store] = lambda: (
+ TenantMemberStore()
)
-
- with pytest.raises(HTTPException) as exc_info:
- await change_password(req, session, user) # type: ignore[arg-type]
-
- assert exc_info.value.status_code == 403
- assert not session.committed
-
-
-async def test_short_new_password_rejected_by_schema() -> None:
- with pytest.raises(ValidationError) as exc_info:
- ChangePasswordRequest(current_password="old-password-1", new_password="short")
-
- errors = exc_info.value.errors()
- assert any(e["type"] == "string_too_short" for e in errors)
-
-
-async def test_empty_new_password_rejected_by_schema() -> None:
- with pytest.raises(ValidationError):
- ChangePasswordRequest(current_password="old-password-1", new_password="")
-
-
-async def test_oidc_user_without_password_hash_returns_403() -> None:
- """OIDC-provisioned users have password_hash=None — changing password must fail cleanly."""
- user = User(
- id="u-2",
- name="Oidc User",
- role="user",
- password_hash=None,
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ jwt_secret_key=_SECRET,
+ gateway_cookie_secure=False,
+ gateway_password_login_enabled=True,
)
- session = _FakeSession()
- req = ChangePasswordRequest(
- current_password="anything", new_password="new-password-1"
+ return app
+
+
+async def _seed_user(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ email: str,
+ password: str | None,
+) -> str:
+ async with session_factory() as session:
+ user = User(
+ name="Ada",
+ email=email,
+ role="user",
+ password_hash=None if password is None else hash_password(password),
+ )
+ # Also inserts the tenant_members row tenant resolution needs.
+ await _USER_STORE.create(session, user)
+ await session.commit()
+ return user.id
+
+
+async def _stored_hash(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str
+) -> str | None:
+ """Read back through a session that shares nothing with the request's."""
+ async with session_factory() as session:
+ user = await _USER_STORE.get(session, user_id)
+ assert user is not None
+ return user.password_hash
+
+
+def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:
+ token = create_jwt(user_id, email, "user", _SECRET)
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://test",
+ cookies={"switch_auth": token},
)
- with pytest.raises(HTTPException) as exc_info:
- await change_password(req, session, user) # type: ignore[arg-type]
- assert exc_info.value.status_code == 403
- assert not session.committed
+class TestPasswordChangeIsPersisted:
+ async def test_the_new_password_can_be_logged_in_with(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=_OLD_PASSWORD)
+ app = _app(session_factory)
+
+ async with _client(app, user_id, email) as client:
+ changed = await client.put(
+ "/auth/me/password",
+ json={
+ "current_password": _OLD_PASSWORD,
+ "new_password": _NEW_PASSWORD,
+ },
+ )
+ assert changed.status_code == 200, changed.text
+ assert changed.json() == {"ok": True}
+
+ # The assertion the old stubbed test could not make: a fresh client,
+ # a fresh session, and the credential actually working.
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as anonymous:
+ logged_in = await anonymous.post(
+ "/auth/login", json={"email": email, "password": _NEW_PASSWORD}
+ )
+ refused = await anonymous.post(
+ "/auth/login", json={"email": email, "password": _OLD_PASSWORD}
+ )
+ assert logged_in.status_code == 200, logged_in.text
+ assert logged_in.json()["id"] == user_id
+ assert refused.status_code == 401
+
+ async def test_the_row_in_the_database_carries_the_new_hash(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=_OLD_PASSWORD)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.put(
+ "/auth/me/password",
+ json={
+ "current_password": _OLD_PASSWORD,
+ "new_password": _NEW_PASSWORD,
+ },
+ )
+ assert response.status_code == 200, response.text
+
+ stored = await _stored_hash(session_factory, user_id)
+ assert verify_password(_NEW_PASSWORD, stored)
+ assert not verify_password(_OLD_PASSWORD, stored)
+
+
+class TestPasswordChangeIsRefused:
+ async def test_a_wrong_current_password_is_403_and_writes_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=_OLD_PASSWORD)
+ before = await _stored_hash(session_factory, user_id)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.put(
+ "/auth/me/password",
+ json={"current_password": "wrong-password", "new_password": "x" * 12},
+ )
+
+ assert response.status_code == 403
+ assert await _stored_hash(session_factory, user_id) == before
+
+ async def test_an_oidc_user_with_no_password_hash_is_403(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email=email, password=None)
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.put(
+ "/auth/me/password",
+ json={"current_password": "anything", "new_password": _NEW_PASSWORD},
+ )
+
+ assert response.status_code == 403
+ assert await _stored_hash(session_factory, user_id) is None
+
+
+class TestSchemaValidation:
+ """No database needed: the length floor is the schema's, not the route's."""
+
+ def test_short_new_password_rejected(self) -> None:
+ with pytest.raises(ValidationError) as exc_info:
+ ChangePasswordRequest(current_password=_OLD_PASSWORD, new_password="short")
+ assert any(e["type"] == "string_too_short" for e in exc_info.value.errors())
+
+ def test_empty_new_password_rejected(self) -> None:
+ with pytest.raises(ValidationError):
+ ChangePasswordRequest(current_password=_OLD_PASSWORD, new_password="")
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index 869c68f31..2f6c54090 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -4,11 +4,12 @@ from types import SimpleNamespace
import pytest
from fastapi import HTTPException
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
import switch_core.gateway.oidc_routes as oidc_routes
from switch_core.config import SwitchConfig
-from switch_core.db.models import OidcIdentity, User
+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_routes import auth_config
@@ -412,6 +413,130 @@ class TestOidcCallback:
assert exc.value.status_code == 401
+class TestTheCallbackPlacesTheUserInATenant:
+ """Sign-in provisions accounts, and an account with no membership can
+ never sign in again (`gateway/auth.py` refuses to guess one). The callback
+ binds tenant zero explicitly rather than letting `TenantScoped`'s fallback
+ supply it — the same row today, but a decision rather than an accident,
+ and the line a later sign-up phase changes.
+ """
+
+ async def _memberships(
+ self, session: AsyncSession, user_id: str
+ ) -> list[TenantMember]:
+ result = await session.execute(
+ select(TenantMember).where(TenantMember.user_id == user_id)
+ )
+ return list(result.scalars().all())
+
+ async def test_just_in_time_provisioning_creates_exactly_one_membership(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|jit",
+ "name": "Jit",
+ }
+ }
+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
+
+ async with session_factory() as session:
+ await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ user = await UserStore().get_by_email(session, "[email protected]")
+ assert user is not None
+ memberships = await self._memberships(session, user.id)
+
+ assert [m.tenant_id for m in memberships] == [TENANT_ZERO_ID]
+ assert memberships[0].role == "member"
+
+ async def test_linking_to_an_account_with_no_membership_repairs_it(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # An account that predates memberships: inserted directly, so it has
+ # none. Linking is the only thing that reaches it, so if linking does
+ # not give it one, nothing ever will.
+ async with session_factory() as session:
+ existing = User(
+ name="Legacy",
+ role="user",
+ password_hash=hash_password("pw"),
+ )
+ session.add(existing)
+ await session.commit()
+ user_id = existing.id
+
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|legacy",
+ "name": "Legacy",
+ }
+ }
+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
+
+ async with session_factory() as session:
+ await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ memberships = await self._memberships(session, user_id)
+
+ assert [m.tenant_id for m in memberships] == [TENANT_ZERO_ID]
+
+ async def test_linking_to_an_account_that_has_one_does_not_add_a_second(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # Two memberships is as broken as none: resolution refuses to pick.
+ async with session_factory() as session:
+ existing = User(
+ name="Member",
+ role="user",
+ password_hash=hash_password("pw"),
+ )
+ await UserStore().create(session, existing)
+ await session.commit()
+ user_id = existing.id
+
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|member",
+ "name": "Member",
+ }
+ }
+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
+
+ async with session_factory() as session:
+ await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ memberships = await self._memberships(session, user_id)
+
+ assert [m.tenant_id for m in memberships] == [TENANT_ZERO_ID]
+
+
class TestAuthConfigEndpoint:
async def test_reports_enabled_oidc_and_label(self) -> None:
config = _config(gateway_oidc_provider_label="Okta")
diff --git a/core/tests/switch_core/gateway/test_reference_types_routes.py b/core/tests/switch_core/gateway/test_reference_types_routes.py
index eac1ca2a5..b3cb7359a 100644
--- a/core/tests/switch_core/gateway/test_reference_types_routes.py
+++ b/core/tests/switch_core/gateway/test_reference_types_routes.py
@@ -25,7 +25,7 @@ from switch_core.gateway.dependencies import (
get_config,
get_resource_service,
get_session,
- get_system_session,
+ get_session_factory,
get_tenant_member_store,
get_user_store,
)
@@ -137,11 +137,12 @@ def _app() -> FastAPI:
app = FastAPI()
app.include_router(router)
app.dependency_overrides[get_session] = _stub_session
- # get_current_user resolves on its own system session, not get_session —
- # see gateway/dependencies.py — so the anonymous-client test below reaches
- # it too and needs it (and the membership store it also depends on)
- # stubbed the same way.
- app.dependency_overrides[get_system_session] = _stub_session
+ # get_current_user resolves the caller's tenant on a short-lived session it
+ # opens from the factory itself (see gateway/auth.py), so the
+ # anonymous-client test below reaches that dependency too and needs it —
+ # and the membership store — stubbed. Neither is ever called: a request
+ # with no cookie is refused before either is touched.
+ app.dependency_overrides[get_session_factory] = lambda: None
app.dependency_overrides[get_tenant_member_store] = lambda: None
app.dependency_overrides[get_user_store] = lambda: None
app.dependency_overrides[get_config] = lambda: 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
new file mode 100644
index 000000000..fe1035b1a
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py
@@ -0,0 +1,128 @@
+"""Every gateway route that opens the request session is authenticated.
+
+`get_session` is the tenant-scoped session (`gateway/dependencies.py`): the
+tenant is stamped on its transaction by the `after_begin` hook, and what binds
+that tenant is `get_current_user`. A route that takes the session without
+taking the user therefore runs its whole transaction unscoped — today that
+merely reads and writes unscoped, and once the row-level-security policies land
+it fails outright. Either way it is not a thing to discover one route at a
+time.
+
+FastAPI also resolves an endpoint's dependencies in *declaration order*, so
+"authenticated" is necessary but not sufficient: a sibling dependency declared
+before `get_current_user` that queried the session during its own resolution
+would still open the transaction untenanted. Nothing does — every other
+dependency is a plain accessor — but that is not mechanically checkable the way
+this is, so it is written down in `get_session`'s docstring and this test holds
+the checkable half.
+
+Generalised from `test_collaborations_authz.py`'s per-router check, and derived
+from the package rather than a hand-written list, so a new gateway router
+module is covered the day it appears.
+"""
+
+from __future__ import annotations
+
+import importlib
+import pkgutil
+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.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 = {
+ ("POST", "/auth/login"),
+ ("GET", "/auth/oidc/callback"),
+}
+
+
+@dataclass(frozen=True)
+class _Route:
+ module: str
+ method: str
+ path: str
+ calls: tuple[object, ...]
+
+ def __str__(self) -> str:
+ return f"{self.module}: {self.method} {self.path}"
+
+ @property
+ def key(self) -> tuple[str, str]:
+ return (self.method, self.path)
+
+
+def _dependency_calls(dependant: object) -> list[object]:
+ """All dependency callables reachable from a route, recursively."""
+ calls = [dependant.call] # type: ignore[attr-defined]
+ for sub in dependant.dependencies: # type: ignore[attr-defined]
+ calls.extend(_dependency_calls(sub))
+ return calls
+
+
+def _gateway_routes() -> list[_Route]:
+ """Every route on every `router` in the `switch_core.gateway` package."""
+ routes: list[_Route] = []
+ for info in pkgutil.iter_modules(gateway_package.__path__):
+ module = importlib.import_module(f"{gateway_package.__name__}.{info.name}")
+ router = getattr(module, "router", None)
+ if not isinstance(router, APIRouter):
+ continue
+ for route in router.routes:
+ dependant = getattr(route, "dependant", None)
+ if dependant is None:
+ continue
+ calls = tuple(_dependency_calls(dependant))
+ for method in sorted(getattr(route, "methods", ()) or ()):
+ routes.append(_Route(info.name, method, route.path, calls))
+ return routes
+
+
+ROUTES = _gateway_routes()
+
+
+def test_the_discovery_finds_the_gateway_routers() -> None:
+ """Guard the guard: a broken import or a renamed attribute would make
+ every assertion below pass over an empty set."""
+ assert {"auth_routes", "rooms", "agents", "collaborations"} <= {
+ route.module for route in ROUTES
+ }
+ assert len([r for r in ROUTES if get_session in r.calls]) > 50
+
+
+def test_every_route_taking_the_session_also_authenticates() -> None:
+ unauthenticated = sorted(
+ str(route)
+ for route in ROUTES
+ if get_session in route.calls
+ and route.key not in _UNAUTHENTICATED_ROUTES
+ and get_current_user not in route.calls
+ and require_admin not in route.calls
+ )
+ assert not unauthenticated, (
+ "these routes open the tenant-scoped session without an authenticated "
+ f"caller to take a tenant from: {unauthenticated}"
+ )
+
+
+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."""
+ assert {
+ route.key for route in ROUTES if get_system_session in route.calls
+ } == _UNAUTHENTICATED_ROUTES
+
+
+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."""
+ assert not [
+ str(route)
+ for route in ROUTES
+ if get_session in route.calls and route.key in _UNAUTHENTICATED_ROUTES
+ ]
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index 5ee0bd7d1..304c663d2 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -8,7 +8,9 @@ rather than picking a tenant when a user's memberships aren't exactly one.
`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.
+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.
Uses `httpx.AsyncClient` over `ASGITransport` rather than
`fastapi.testclient.TestClient`: the sync `TestClient` runs the app in a
@@ -20,15 +22,20 @@ paper over here.
from __future__ import annotations
+import asyncio
+from collections.abc import AsyncIterator
from types import SimpleNamespace
from typing import Annotated
import httpx
import pytest
+import pytest_asyncio
from fastapi import Depends, FastAPI
-from sqlalchemy import text
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from sqlalchemy import insert, text
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+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.tenant_member_store import (
TenantMembershipError,
@@ -104,8 +111,8 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
yield session
app = FastAPI()
- app.dependency_overrides[gw_deps.get_system_session] = _session_dep
app.dependency_overrides[gw_deps.get_session] = _session_dep
+ 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_tenant_member_store] = lambda: (
TenantMemberStore()
@@ -118,15 +125,54 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
async def whoami(
user: Annotated[User, Depends(get_current_user)],
session: Annotated[AsyncSession, Depends(gw_deps.get_session)],
+ hold: float = 0.0,
) -> dict:
- row = await session.execute(
- text("SELECT current_setting('app.tenant_id', true)")
- )
- return {"user_id": user.id, "db_tenant_id": row.scalar_one() or None}
+ first = await _session_tenant(session)
+ # `hold` lets a caller keep this request inside its transaction while
+ # another one runs, so the second read below happens with both in
+ # flight rather than one after the other.
+ await asyncio.sleep(hold)
+ return {
+ "user_id": user.id,
+ "db_tenant_id": first,
+ "db_tenant_id_after": await _session_tenant(session),
+ }
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
+
+
+def _client(app: FastAPI, token: str) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://test",
+ cookies={"switch_auth": token},
+ )
+
+
+async def _make_user(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ name: str,
+ tenant_id: str,
+) -> str:
+ """A user with exactly one membership, in `tenant_id`."""
+ async with session_factory() as session:
+ 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()
+ 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]
@@ -142,10 +188,7 @@ class TestAGatewayRequestBindsTheCallersTenant:
user_id = user.id
token = create_jwt(user_id, "[email protected]", "user", _SECRET)
- transport = httpx.ASGITransport(app=_app(session_factory))
- async with httpx.AsyncClient(
- transport=transport, base_url="http://test", cookies={"switch_auth": token}
- ) as client:
+ async with _client(_app(session_factory), token) as client:
response = await client.get("/whoami")
assert response.status_code == 200
@@ -163,3 +206,116 @@ class TestAGatewayRequestBindsTheCallersTenant:
response = await client.get("/whoami")
assert response.status_code == 401
+
+
+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."""
+
+ async def test_the_response_is_403_and_names_no_user_id(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Inserted directly, not through UserStore.create, precisely because
+ # that would give them the membership this test needs them to lack.
+ 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
+
+ token = create_jwt(user_id, "[email protected]", "user", _SECRET)
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 403
+ detail = response.json()["detail"]
+ assert "tenant" in detail
+ assert user_id not in detail
+
+
+class TestConcurrentRequests:
+ async def test_two_requests_in_different_tenants_do_not_see_each_other(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ zero_user = await _make_user(
+ session_factory, name="inzero", tenant_id=TENANT_ZERO_ID
+ )
+ b_user = await _make_user(session_factory, name="inb", tenant_id=TENANT_B)
+ app = _app(session_factory)
+
+ async def _call(user_id: str, name: str) -> dict:
+ token = create_jwt(user_id, f"{name}@example.invalid", "user", _SECRET)
+ async with _client(app, token) as client:
+ response = await client.get("/whoami", params={"hold": 0.2})
+ assert response.status_code == 200, response.text
+ return response.json()
+
+ # Both are inside their own transaction for the whole `hold`, so the
+ # second read in each happens while the other request is live. A
+ # tenant that leaked — through the contextvar or through a shared
+ # connection — would show up there.
+ in_zero, in_b = await asyncio.gather(
+ _call(zero_user, "inzero"), _call(b_user, "inb")
+ )
+
+ assert in_zero["db_tenant_id"] == TENANT_ZERO_ID
+ assert in_zero["db_tenant_id_after"] == TENANT_ZERO_ID
+ assert in_b["db_tenant_id"] == TENANT_B
+ assert in_b["db_tenant_id_after"] == TENANT_B
+
+
+@pytest_asyncio.fixture
+async def one_connection_session_factory(
+ postgres_url: str,
+) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
+ """A pool of exactly one connection, and a short timeout for waiting on it.
+
+ Makes "how many connections does a request hold at once?" an assertion
+ rather than an inspection: a request needing two deadlocks against itself
+ and fails on the timeout instead of quietly halving pool capacity in
+ production.
+ """
+ engine = create_async_engine(
+ postgres_url, pool_size=1, max_overflow=0, pool_timeout=5
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await conn.execute(
+ insert(Tenant.__table__).values(
+ id=TENANT_ZERO_ID, slug="default", name="Default"
+ )
+ )
+ try:
+ yield create_session_factory(engine)
+ finally:
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.drop_all)
+ await engine.dispose()
+
+
+class TestARequestHoldsOneConnection:
+ """Tenant resolution's session is opened and closed inside
+ `get_current_user`, before the request's own session is touched, so an
+ authenticated request never holds two pooled connections at once.
+
+ Held as a yield dependency instead — the shape this replaced — the
+ resolution session would keep its connection, idle in a transaction
+ nothing ever ends, for the whole request. On a pool of one that is a
+ deadlock; on a real pool it is half the capacity and every request one
+ `idle_in_transaction_session_timeout` away from failing.
+ """
+
+ async def test_an_authenticated_request_completes_on_a_pool_of_one(
+ self, one_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ 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)
+
+ 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