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(db): bind the request's tenant onto every session (CHOO-2623)

Wojciech Wojtyniak8cfc97c1b58a
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index cc898f792..a81cf72be 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -16,6 +16,7 @@ from switch_core.db.models import Agent, ApiKey
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
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__)
@@ -82,6 +83,17 @@ class BearerAuthMiddleware:
Public paths (see ``PUBLIC_PATH_PREFIXES``) bypass authentication
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.
"""
def __init__(
@@ -134,11 +146,18 @@ class BearerAuthMiddleware:
if agent is not None:
scope["agent"] = agent
scope["agent_id"] = agent.id
- token = bind_log_context(agent_id=agent.id)
+ # api_key.tenant_id is the source of truth (docs/old/
+ # multi-tenancy-phase1-db.md, "Setting the tenant"); the OIDC
+ # path resolves straight to an Agent with no ApiKey row, so it
+ # falls back to the agent's own tenant.
+ tenant_id = api_key.tenant_id if api_key is not None else agent.tenant_id
+ log_token = bind_log_context(agent_id=agent.id, tenant_id=tenant_id)
+ tenant_token = bind_tenant_id(tenant_id)
try:
await self.app(scope, receive, send)
finally:
- unbind_log_context(token)
+ unbind_tenant_id(tenant_token)
+ unbind_log_context(log_token)
return
# Registration token: pass through (handler validates again). MCP rejects.
@@ -172,6 +191,8 @@ class BearerAuthMiddleware:
if cached is not None:
return cached
+ # A system session: no tenant is bound yet, because this lookup is
+ # what determines one.
async with self._session_factory() as session:
found = await self._api_key_store.get_with_agent_by_hash(
session, token_hash
@@ -200,6 +221,8 @@ class BearerAuthMiddleware:
logger.warning("OIDC token has no azp or client_id claim")
return None
+ # A system session, same reason as _resolve_api_key: this is what
+ # decides which agent (and so which tenant) is asking.
async with self._session_factory() as session:
return await self._agent_store.get_by_oauth_client_id(session, client_id)
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 899b49d1b..299b524f3 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -91,13 +91,11 @@ class SwitchConfig(BaseSettings):
service_name: str = "switch-core"
environment: str | None = None
- # The tenant every log line is attributed to. Switch is single-tenant: one
- # deployment serves one organisation, so the tenant is a deployment-wide
- # constant and there is nothing per-request to read it from. Setting it per
- # deployment now means the logs of two deployments can be told apart in one
- # pipeline today, and that when the tenant model lands the only change is
- # where the value comes from — the field is already on every line, and on
- # every log call written between now and then.
+ # The tenant a log line is attributed to when nothing bound a real one.
+ # An authenticated request binds the caller's actual tenant
+ # (`gateway/auth.py`, `bridges/agent/auth.py`); this is only what a
+ # background task, a startup script, or anything else with no request
+ # in flight falls back to.
tenant_id: str = "default"
server_host: str = "0.0.0.0"
diff --git a/core/switch_core/db/engine.py b/core/switch_core/db/engine.py
index 8a51edcbd..8936a50c2 100644
--- a/core/switch_core/db/engine.py
+++ b/core/switch_core/db/engine.py
@@ -12,6 +12,7 @@ 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
logger = logging.getLogger(__name__)
@@ -161,4 +162,9 @@ 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/models.py b/core/switch_core/db/models.py
index 848fe0646..d9a56257b 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -28,6 +28,7 @@ from switch_core.db.notify_ddl import (
CREATE_NOTIFY_TRIGGER,
DROP_NOTIFY_TRIGGER,
)
+from switch_core.tenant_context import current_tenant_id
def _uuid() -> str:
@@ -87,14 +88,24 @@ class TenantMember(Base):
TENANT_ZERO_ID = "00000000-0000-0000-0000-000000000000"
+def _tenant_id_default() -> str:
+ """The tenant a new scoped row lands in when nothing tells it otherwise.
+
+ Prefers the tenant bound to the current request/session context; falls
+ back to tenant zero only when nothing is bound. The fallback is still
+ load-bearing: the ~206 background call sites that open a session from the
+ factory directly (`docs/old/multi-tenancy-phase1-db.md`, "Setting the
+ tenant") bind no tenant at all today, and removing this fallback before
+ they are converted — and before the row-level-security policies land to
+ make an unscoped write fail loudly instead — would break every one of
+ them. Remove it once both have shipped.
+ """
+ return current_tenant_id() or TENANT_ZERO_ID
+
+
class TenantScoped:
"""Mixin carrying the tenant column shared by every per-tenant table.
- The Python-side default returns tenant zero — the only tenant that exists
- today — so an ordinary ORM insert needs no change to land in the right
- place. A later PR replaces this default with a value read from the
- request/session context; nothing here reads from a contextvar yet.
-
The foreign key is named explicitly (`fk_<table>_tenant`) rather than left
for the dialect to default, because `declared_attr` gives each subclass
its own column and an unnamed constraint would default to
@@ -113,7 +124,7 @@ class TenantScoped:
name=f"fk_{cls.__tablename__}_tenant", # type: ignore[attr-defined]
),
nullable=False,
- default=TENANT_ZERO_ID,
+ default=_tenant_id_default,
)
diff --git a/core/switch_core/db/stores/tenant_member_store.py b/core/switch_core/db/stores/tenant_member_store.py
new file mode 100644
index 000000000..cf4837875
--- /dev/null
+++ b/core/switch_core/db/stores/tenant_member_store.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import TenantMember
+
+
+class TenantMembershipError(Exception):
+ """A user has zero, or more than one, tenant memberships.
+
+ 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".
+ """
+
+
+class TenantMemberStore:
+ async def create(
+ self, session: AsyncSession, *, tenant_id: str, user_id: str, role: str
+ ) -> None:
+ session.add(TenantMember(tenant_id=tenant_id, user_id=user_id, role=role))
+ await session.flush()
+
+ async def get_sole_tenant_id(self, session: AsyncSession, user_id: str) -> str:
+ """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`).
+ """
+ result = await session.execute(
+ select(TenantMember.tenant_id).where(TenantMember.user_id == user_id)
+ )
+ tenant_ids = result.scalars().all()
+ if len(tenant_ids) != 1:
+ raise TenantMembershipError(
+ f"user {user_id} has {len(tenant_ids)} tenant memberships; "
+ "expected exactly 1"
+ )
+ return tenant_ids[0]
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index 1ea987d91..d97611154 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -6,7 +6,8 @@ from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import OidcIdentity, User
+from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, TenantMember, User
+from switch_core.tenant_context import current_tenant_id
logger = logging.getLogger(__name__)
@@ -43,8 +44,31 @@ class OidcIdentityRaceError(Exception):
class UserStore:
async def create(self, session: AsyncSession, user: User) -> None:
+ """Create the user, and the membership that lets them ever sign in.
+
+ Tenant resolution (`gateway/auth.py`) raises rather than guessing when
+ 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.
+ """
session.add(user)
await session.flush()
+ session.add(
+ TenantMember(
+ tenant_id=current_tenant_id() or TENANT_ZERO_ID,
+ user_id=user.id,
+ role="owner" if user.role == "admin" else "member",
+ )
+ )
+ await session.flush()
async def get(self, session: AsyncSession, user_id: str) -> User | None:
return await session.get(User, user_id)
diff --git a/core/switch_core/db/tenant_session.py b/core/switch_core/db/tenant_session.py
new file mode 100644
index 000000000..a8a8a855b
--- /dev/null
+++ b/core/switch_core/db/tenant_session.py
@@ -0,0 +1,65 @@
+"""Stamps the bound tenant onto every session's transaction, on begin.
+
+This is an SQLAlchemy `after_begin` event hook rather than a call each call
+site makes for itself, because a call site is something a future call site
+can forget — and the failure mode of forgetting is not "no tenant", it is
+"the previous request's tenant". Connections are pooled: a session that never
+issues `set_config` simply keeps whatever the connection it borrowed was left
+holding, because nothing ever resets it. Two of the four prior-art bugs this
+design exists to prevent were exactly that — a session-scoped setting on a
+pooled connection outliving the request that set it and leaking into the
+next one to borrow that connection. An event hook fires on every session this
+process opens, unconditionally, so there is no call site to remember and
+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.
+
+When no tenant is bound (see `switch_core.tenant_context`), the hook does
+nothing rather than substituting one — a system session (auth resolution,
+Alembic, startup seeding) has no tenant, and the database does not yet reject
+that (that lands with `require_tenant_id()` and the row-level-security
+policies, in a later change). Until then, a query issued with no tenant set
+simply runs unscoped, same as before this hook existed.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import event, text
+from sqlalchemy.engine import Connection
+from sqlalchemy.orm import Session, SessionTransaction
+
+from switch_core.tenant_context import current_tenant_id
+
+_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.
+ """
+ global _registered
+ if _registered:
+ return
+ event.listens_for(Session, "after_begin")(_set_tenant_on_begin)
+ _registered = True
+
+
+def _set_tenant_on_begin(
+ session: Session, transaction: SessionTransaction, connection: Connection
+) -> None:
+ tenant_id = current_tenant_id()
+ if tenant_id is None:
+ return
+ connection.execute(
+ text("SELECT set_config('app.tenant_id', :tenant_id, true)"),
+ {"tenant_id": tenant_id},
+ )
diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.py
index ab24b4e3c..fb0e3fa96 100644
--- a/core/switch_core/gateway/app.py
+++ b/core/switch_core/gateway/app.py
@@ -21,6 +21,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_group_store import RoomGroupStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.server_connector_store import ServerConnectorStore
+from switch_core.db.stores.tenant_member_store import TenantMemberStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.agents import router as agents_router
from switch_core.gateway.api_keys import router as api_keys_router
@@ -56,6 +57,7 @@ def create_gateway_app(
user_store: UserStore,
external_user_store: ExternalUserStore,
api_key_store: ApiKeyStore,
+ tenant_member_store: TenantMemberStore,
resource_service: ResourceService,
protocol: ProtocolService,
config: SwitchConfig,
@@ -75,6 +77,7 @@ def create_gateway_app(
user_store=user_store,
external_user_store=external_user_store,
api_key_store=api_key_store,
+ tenant_member_store=tenant_member_store,
resource_service=resource_service,
protocol=protocol,
config=config,
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 24c567982..9a8565e59 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import datetime
+from collections.abc import AsyncIterator
from typing import Annotated
import bcrypt
@@ -12,9 +13,16 @@ 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.user_store import UserStore
-from switch_core.gateway.dependencies import get_config, get_session, get_user_store
-from switch_core.logging_context import bind_log_context
+from switch_core.gateway.dependencies import (
+ get_config,
+ get_system_session,
+ 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
JWT_ALGORITHM = "HS256"
JWT_EXPIRY_HOURS = 24
@@ -80,10 +88,26 @@ def decode_jwt(token: str, secret_key: str) -> dict:
async def get_current_user(
request: Request,
- session: Annotated[AsyncSession, Depends(get_session)],
+ session: Annotated[AsyncSession, Depends(get_system_session)],
user_store: Annotated[UserStore, Depends(get_user_store)],
+ tenant_member_store: Annotated[TenantMemberStore, Depends(get_tenant_member_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
-) -> User:
+) -> 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.
+ """
token = request.cookies.get("switch_auth")
if token is None:
raise HTTPException(status_code=401, detail="Not authenticated")
@@ -91,10 +115,15 @@ async def get_current_user(
user = await user_store.get(session, payload["sub"])
if user is None:
raise HTTPException(status_code=401, detail="User not found")
- # Unbound by RequestContextMiddleware when the request ends: its reset
- # restores the context to what it was before the request, discarding this.
- bind_log_context(user_id=user.id)
- return user
+ tenant_id = await tenant_member_store.get_sole_tenant_id(session, user.id)
+
+ log_token = bind_log_context(user_id=user.id, tenant_id=tenant_id)
+ tenant_token = bind_tenant_id(tenant_id)
+ try:
+ yield user
+ finally:
+ unbind_tenant_id(tenant_token)
+ unbind_log_context(log_token)
async def require_admin(
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index 5858cdab3..b0fffa3a7 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -23,6 +23,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStore
from switch_core.db.stores.room_group_store import RoomGroupStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.server_connector_store import ServerConnectorStore
+from switch_core.db.stores.tenant_member_store import TenantMemberStore
from switch_core.db.stores.user_store import UserStore
from switch_core.room_service import RoomService
from switch_core.rooms_yaml import RoomYamlService
@@ -46,6 +47,7 @@ def init_dependencies(
user_store: UserStore,
external_user_store: ExternalUserStore,
api_key_store: ApiKeyStore,
+ tenant_member_store: TenantMemberStore,
resource_service: ResourceService,
protocol: ProtocolService,
config: SwitchConfig,
@@ -64,12 +66,44 @@ def init_dependencies(
_state["user_store"] = user_store
_state["external_user_store"] = external_user_store
_state["api_key_store"] = api_key_store
+ _state["tenant_member_store"] = tenant_member_store
_state["resource_service"] = resource_service
_state["protocol"] = protocol
_state["config"] = config
async def get_session() -> AsyncIterator[AsyncSession]:
+ """The tenant-scoped session for an authenticated endpoint handler.
+
+ 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
+ `get_system_session`.
+ """
+ async with _state["session_factory"]() as session:
+ yield session
+
+
+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.
+ """
async with _state["session_factory"]() as session:
yield session
@@ -136,6 +170,10 @@ def get_api_key_store() -> ApiKeyStore:
return _state["api_key_store"] # type: ignore[no-any-return]
+def get_tenant_member_store() -> TenantMemberStore:
+ return _state["tenant_member_store"] # type: ignore[no-any-return]
+
+
def get_connector_lifecycle() -> ServerSideConnectorLifecycleService:
return _state["connector_lifecycle"] # type: ignore[no-any-return]
diff --git a/core/switch_core/logging_context.py b/core/switch_core/logging_context.py
index d13f701e1..5c5597024 100644
--- a/core/switch_core/logging_context.py
+++ b/core/switch_core/logging_context.py
@@ -7,9 +7,11 @@ record and the formatters in :mod:`switch_core.logging_config` render it.
``tenant_id`` is the point of the exercise: multi-tenancy needs "is this one
customer or everyone?" to be answerable from the logs alone, and that is far
-cheaper to build before tenants exist than after. Until the tenant model lands
-nothing binds it per request, and the filter stamps the deployment's configured
-tenant instead — see ``SwitchConfig.tenant_id``.
+cheaper to build before tenants exist than after. It was built before tenants
+existed, and now that they do, ``gateway/auth.py`` and ``bridges/agent/auth.py``
+bind the real one for every authenticated request. Outside a request — a
+background task, a startup script, anything that never binds one — the filter
+falls back to the deployment's configured tenant; see ``SwitchConfig.tenant_id``.
"""
from __future__ import annotations
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 8325ae9a3..89c749215 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -94,6 +94,7 @@ from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.db.stores.server_connector_store import ServerConnectorStore
from switch_core.db.stores.task_store import TaskStore
+from switch_core.db.stores.tenant_member_store import TenantMemberStore
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.app import create_gateway_app
from switch_core.gateway.auth import hash_password
@@ -204,6 +205,7 @@ async def run(config: SwitchConfig) -> None:
bridge_message_map_store = BridgeMessageMapStore()
user_store = UserStore()
api_key_store = ApiKeyStore()
+ tenant_member_store = TenantMemberStore()
reference_store = ReferenceStore()
reference_type_store = ReferenceTypeStore()
document_store = DocumentStore()
@@ -382,6 +384,7 @@ async def run(config: SwitchConfig) -> None:
user_store=user_store,
external_user_store=external_user_store,
api_key_store=api_key_store,
+ tenant_member_store=tenant_member_store,
resource_service=resource_service,
protocol=protocol,
config=config,
diff --git a/core/switch_core/tenant_context.py b/core/switch_core/tenant_context.py
new file mode 100644
index 000000000..fd9f63aab
--- /dev/null
+++ b/core/switch_core/tenant_context.py
@@ -0,0 +1,58 @@
+"""The current request's tenant, held in a context variable.
+
+Shaped like :mod:`switch_core.logging_context`: a module-level `ContextVar`,
+a bind that returns a token, and an unbind that resets it — the house pattern
+for anything that needs to travel with a request/task without being threaded
+through every function signature along the way.
+
+This module only holds the value and the plumbing to bind/read/unbind it. It
+does not decide *how* a tenant is resolved (that is `gateway/auth.py` for the
+JWT cookie and `bridges/agent/auth.py` for the bearer token) and it does not
+decide what happens when nothing is bound — callers do, deliberately:
+
+- `db/tenant_session.py`'s `after_begin` hook treats "nothing bound" as
+ "do nothing" — a system session (auth resolution, startup seeding, Alembic)
+ has no tenant and must not be given one it invented.
+- `db/models.py`'s `TenantScoped` default treats "nothing bound" as tenant
+ zero, because the background call sites that still write through it have
+ not been converted to bind one yet.
+
+Neither of those fallbacks lives here. A `current_tenant_id()` that quietly
+substituted a default would make both of those call sites indistinguishable
+from a real bind, which is exactly the ambiguity the fail-closed design (see
+`docs/old/multi-tenancy-phase1-db.md`) depends on not existing.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar, Token
+
+_current_tenant_id: ContextVar[str | None] = ContextVar(
+ "switch_tenant_id", default=None
+)
+
+
+def current_tenant_id() -> str | None:
+ """The tenant bound to the current context, or `None` if none is."""
+ return _current_tenant_id.get()
+
+
+def bind_tenant_id(tenant_id: str) -> Token[str | None]:
+ """Bind `tenant_id` for the current context, returning a token to unbind with."""
+ return _current_tenant_id.set(tenant_id)
+
+
+def unbind_tenant_id(token: Token[str | None]) -> None:
+ _current_tenant_id.reset(token)
+
+
+@contextmanager
+def tenant_scope(tenant_id: str) -> Iterator[None]:
+ """Bind `tenant_id` for the duration of the block."""
+ token = bind_tenant_id(tenant_id)
+ try:
+ yield
+ finally:
+ unbind_tenant_id(token)
diff --git a/core/tests/conftest.py b/core/tests/conftest.py
index d759fbf0d..46d832e55 100644
--- a/core/tests/conftest.py
+++ b/core/tests/conftest.py
@@ -17,6 +17,7 @@ from testcontainers.postgres import PostgresContainer
# create_all provisions the full schema (rooms, room_groups, FKs, …).
import switch_core.db.models # noqa: F401
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
@@ -59,7 +60,11 @@ async def session_factory(
await conn.run_sync(Base.metadata.create_all)
await _seed_tenant_zero(conn)
try:
- yield async_sessionmaker(bind=engine, expire_on_commit=False)
+ # 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.
+ yield create_session_factory(engine)
finally:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_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
new file mode 100644
index 000000000..f23b6f603
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_bearer_auth_tenant_binding.py
@@ -0,0 +1,142 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from typing import Any
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
+from switch_core.bridges.agent.auth import BearerAuthMiddleware
+from switch_core.db.models import Agent, ApiKey, Client, Tenant, User
+from switch_core.db.stores.agent_store import AgentStore
+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"
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+async def _seed_agent(
+ session_factory: async_sessionmaker[AsyncSession], token: str, tenant_id: str
+) -> None:
+ async with session_factory() as session:
+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))
+ await session.flush()
+
+ user = User(name="owner", email="[email protected]", role="user")
+ session.add(user)
+ await session.flush()
+
+ client = Client(
+ tenant_id=tenant_id,
+ matrix_user_id="@bearer-agent:test",
+ display_name="bearer-agent",
+ type="agent",
+ )
+ session.add(client)
+ await session.flush()
+
+ api_key = ApiKey(
+ tenant_id=tenant_id,
+ user_id=user.id,
+ key_hash=_hash(token),
+ encrypted_key="enc",
+ label="k",
+ type="agent",
+ )
+ session.add(api_key)
+ await session.flush()
+
+ agent = Agent(
+ tenant_id=tenant_id,
+ name="bearer-agent",
+ description="desc",
+ agent_type="always_on",
+ connector_type="claude_code",
+ integration_profile={"connection_model": "always_on"},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ owner_id=user.id,
+ )
+ session.add(agent)
+ await session.commit()
+
+
+def _middleware(session_factory: Any) -> tuple[BearerAuthMiddleware, dict]:
+ captured: dict[str, Any] = {}
+
+ async def _app(scope: Any, receive: Any, send: Any) -> None:
+ # Read while the middleware's `self.app(...)` call is still on the
+ # 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")
+
+ mw = BearerAuthMiddleware(
+ _app,
+ agent_store=AgentStore(),
+ api_key_store=ApiKeyStore(),
+ api_key_cache=ApiKeyCache(ttl_seconds=5, max_entries=8),
+ session_factory=session_factory,
+ )
+ return mw, captured
+
+
+async def _dispatch(mw: BearerAuthMiddleware, token: str) -> list[dict]:
+ async def receive() -> dict:
+ return {"type": "http.request"}
+
+ sent: list[dict] = []
+
+ async def send(message: dict) -> None:
+ sent.append(message)
+
+ scope = {
+ "type": "http",
+ "path": "/agents/whatever",
+ "headers": [(b"authorization", f"Bearer {token}".encode())],
+ }
+ await mw(scope, receive, send)
+ return sent
+
+
+class TestBearerAuthBindsTheApiKeysTenant:
+ async def test_the_agents_api_key_tenant_is_bound_during_the_call(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "tok", TENANT_A)
+ mw, captured = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "tok")
+
+ assert sent == [] # never rejected — the inner app ran
+ assert captured["agent_id"] is not None
+ assert captured["tenant_id"] == TENANT_A
+
+ async def test_the_tenant_is_not_bound_before_or_after_the_call(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "tok", TENANT_A)
+ mw, _ = _middleware(session_factory)
+
+ assert current_tenant_id() is None
+ await _dispatch(mw, "tok")
+ assert current_tenant_id() is None
+
+ async def test_an_unknown_token_binds_nothing(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ mw, captured = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "not-a-real-token")
+
+ 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
new file mode 100644
index 000000000..70708ee5c
--- /dev/null
+++ b/core/tests/switch_core/db/test_tenant_session_hook.py
@@ -0,0 +1,102 @@
+"""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.
+
+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()`.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import pytest_asyncio
+from sqlalchemy import 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.tenant_context import tenant_scope
+
+TENANT_A = "tenant-hook-a"
+
+
+@pytest_asyncio.fixture
+async def single_connection_session_factory(
+ postgres_url: str,
+) -> AsyncIterator[async_sessionmaker[AsyncSession]]:
+ engine = create_async_engine(postgres_url, pool_size=1, max_overflow=0)
+ 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.
+ yield create_session_factory(engine)
+ finally:
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.drop_all)
+ await engine.dispose()
+
+
+async def _current_setting(session: AsyncSession) -> str | None:
+ result = await session.execute(
+ text("SELECT current_setting('app.tenant_id', true)")
+ )
+ value = result.scalar_one()
+ return value or None
+
+
+async def _pid_and_setting(session: AsyncSession) -> tuple[int, str | None]:
+ result = await session.execute(
+ text("SELECT pg_backend_pid(), current_setting('app.tenant_id', true)")
+ )
+ pid, value = result.one()
+ return pid, (value or None)
+
+
+class TestTenantSetOnBeginAndReleasedOnCommit:
+ async def test_tenant_is_visible_inside_the_transaction(
+ 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.commit()
+
+ async def test_tenant_is_released_once_the_transaction_commits(
+ self, single_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with single_connection_session_factory() as session:
+ with tenant_scope(TENANT_A):
+ await _current_setting(session) # begins the transaction
+ await session.commit()
+
+ # Same session, same connection, a new transaction — and by now
+ # the context that set it has been unbound (the `with` above
+ # exited before the commit).
+ assert await _current_setting(session) is None
+
+
+class TestNoLeakAcrossAPooledConnection:
+ async def test_a_reused_connection_does_not_inherit_the_previous_tenant(
+ self, single_connection_session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ 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()
+
+ # A second session, opened after the first is closed, with no tenant
+ # bound at all — e.g. a system session doing auth resolution, or a
+ # background job that has not been converted to bind one yet. With a
+ # pool of exactly one connection this must be the same physical
+ # connection the first session used.
+ async with single_connection_session_factory() as session:
+ 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
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 685527d3a..eac1ca2a5 100644
--- a/core/tests/switch_core/gateway/test_reference_types_routes.py
+++ b/core/tests/switch_core/gateway/test_reference_types_routes.py
@@ -25,6 +25,8 @@ from switch_core.gateway.dependencies import (
get_config,
get_resource_service,
get_session,
+ get_system_session,
+ get_tenant_member_store,
get_user_store,
)
from switch_core.gateway.references import (
@@ -135,6 +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
+ app.dependency_overrides[get_tenant_member_store] = lambda: None
app.dependency_overrides[get_user_store] = lambda: None
app.dependency_overrides[get_config] = lambda: None
app.dependency_overrides[get_resource_service] = lambda: None
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
new file mode 100644
index 000000000..5ee0bd7d1
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -0,0 +1,165 @@
+"""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
+parameter.
+
+`TestGetSoleTenantId` covers `TenantMemberStore.get_sole_tenant_id` raising
+rather than picking a tenant when a user's memberships aren't exactly one.
+`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.
+
+Uses `httpx.AsyncClient` over `ASGITransport` rather than
+`fastapi.testclient.TestClient`: the sync `TestClient` runs the app in a
+separate thread with its own event loop, and the `session_factory` fixture's
+connections belong to this test's loop — crossing that boundary is a real bug
+class of its own (asyncpg futures tied to the wrong loop), not something to
+paper over here.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Annotated
+
+import httpx
+import pytest
+from fastapi import Depends, FastAPI
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import TENANT_ZERO_ID, Tenant, TenantMember, User
+from switch_core.db.stores.tenant_member_store import (
+ TenantMembershipError,
+ 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, get_current_user
+
+_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
+TENANT_B = "tenant-resolution-b"
+
+
+class TestGetSoleTenantId:
+ async def test_raises_when_the_user_has_no_membership(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TenantMemberStore()
+ async with session_factory() as session:
+ user = User(name="orphan", email="[email protected]", role="user")
+ session.add(user)
+ await session.flush()
+
+ with pytest.raises(TenantMembershipError):
+ await store.get_sole_tenant_id(session, user.id)
+
+ async def test_raises_when_the_user_has_more_than_one_membership(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TenantMemberStore()
+ 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.flush()
+
+ with pytest.raises(TenantMembershipError):
+ await store.get_sole_tenant_id(session, user.id)
+
+ async def test_returns_the_one_tenant_a_user_belongs_to(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = TenantMemberStore()
+ 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.flush()
+
+ assert await store.get_sole_tenant_id(session, user.id) == TENANT_ZERO_ID
+
+
+def _app(session_factory: async_sessionmaker[AsyncSession]) -> 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`)."""
+
+ async def _session_dep():
+ async with session_factory() as session:
+ 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_user_store] = lambda: UserStore()
+ app.dependency_overrides[gw_deps.get_tenant_member_store] = lambda: (
+ TenantMemberStore()
+ )
+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
+ jwt_secret_key=_SECRET
+ )
+
+ @app.get("/whoami")
+ async def whoami(
+ user: Annotated[User, Depends(get_current_user)],
+ session: Annotated[AsyncSession, Depends(gw_deps.get_session)],
+ ) -> 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}
+
+ return app
+
+
+class TestAGatewayRequestBindsTheCallersTenant:
+ async def test_the_sessions_tenant_matches_the_users_membership(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store = UserStore()
+ async with session_factory() as session:
+ user = User(name="Ada", email="[email protected]", role="user")
+ # UserStore.create also inserts the tenant_members row — see its
+ # docstring — landing this user in tenant zero, since no request
+ # context is bound while seeding it here.
+ await user_store.create(session, user)
+ await session.commit()
+ 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:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["user_id"] == user_id
+ assert body["db_tenant_id"] == TENANT_ZERO_ID
+
+ async def test_a_request_with_no_cookie_is_rejected(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ transport = httpx.ASGITransport(app=_app(session_factory))
+ async with httpx.AsyncClient(
+ transport=transport, base_url="http://test"
+ ) as client:
+ response = await client.get("/whoami")
+
+ assert response.status_code == 401
diff --git a/core/tests/switch_core/test_tenant_context.py b/core/tests/switch_core/test_tenant_context.py
new file mode 100644
index 000000000..f4f3bd67a
--- /dev/null
+++ b/core/tests/switch_core/test_tenant_context.py
@@ -0,0 +1,51 @@
+"""switch_core.tenant_context: the contextvar itself, independent of anything
+that reads or writes it for a real request."""
+
+from __future__ import annotations
+
+from switch_core.tenant_context import (
+ bind_tenant_id,
+ current_tenant_id,
+ tenant_scope,
+ unbind_tenant_id,
+)
+
+
+class TestBindAndUnbind:
+ def test_nothing_bound_reads_as_none(self) -> None:
+ assert current_tenant_id() is None
+
+ def test_bind_is_visible_until_unbound(self) -> None:
+ token = bind_tenant_id("tenant-a")
+ try:
+ assert current_tenant_id() == "tenant-a"
+ finally:
+ unbind_tenant_id(token)
+ assert current_tenant_id() is None
+
+ def test_unbinding_restores_the_enclosing_value_not_none(self) -> None:
+ outer = bind_tenant_id("outer")
+ try:
+ inner = bind_tenant_id("inner")
+ try:
+ assert current_tenant_id() == "inner"
+ finally:
+ unbind_tenant_id(inner)
+ assert current_tenant_id() == "outer"
+ finally:
+ unbind_tenant_id(outer)
+
+
+class TestTenantScope:
+ def test_binds_for_the_block_and_releases_after(self) -> None:
+ with tenant_scope("tenant-a"):
+ assert current_tenant_id() == "tenant-a"
+ assert current_tenant_id() is None
+
+ def test_releases_even_if_the_block_raises(self) -> None:
+ try:
+ with tenant_scope("tenant-a"):
+ raise ValueError("boom")
+ except ValueError:
+ pass
+ assert current_tenant_id() is None