Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(auth): bind the request tenant through tenant_scope, not a raw token (CHOO-2623)
Wojciech Wojtyniak6a587b08ede0
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.pyindex 2bf9cb5f8..a4bb3841b 100644--- a/core/switch_core/bridges/agent/auth.py+++ b/core/switch_core/bridges/agent/auth.py@@ -16,7 +16,7 @@ from switch_core.db.models import Agent, ApiKeyfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.logging_context import bind_log_context, unbind_log_context-from switch_core.tenant_context import bind_tenant_id, unbind_tenant_id+from switch_core.tenant_context import tenant_scopelogger = logging.getLogger(__name__)@@ -155,13 +155,12 @@ class BearerAuthMiddleware:# 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_tenant_id(tenant_token)- unbind_log_context(log_token)+ with tenant_scope(tenant_id):+ log_token = bind_log_context(agent_id=agent.id, tenant_id=tenant_id)+ try:+ await self.app(scope, receive, send)+ finally:+ unbind_log_context(log_token)return# Registration token: pass through (handler validates again). MCP rejects.@@ -178,13 +177,12 @@ class BearerAuthMiddleware:# 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)+ with tenant_scope(api_key.tenant_id):+ log_token = bind_log_context(tenant_id=api_key.tenant_id)+ try:+ await self.app(scope, receive, send)+ finally:+ unbind_log_context(log_token)returnresponse = Response("Invalid credentials", status_code=401)diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 6a026846a..5f0794f20 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -27,7 +27,7 @@ from switch_core.gateway.dependencies import (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+from switch_core.tenant_context import tenant_scopelogger = logging.getLogger(__name__)@@ -164,17 +164,16 @@ async def get_current_user(session_factory, user_store, tenant_member_store, user_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)- unbind_log_context(log_token)+ with tenant_scope(tenant_id):+ log_token = bind_log_context(user_id=user_id, 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_log_context(log_token)async def require_admin(diff --git a/core/tests/switch_core/test_tenant_context.py b/core/tests/switch_core/test_tenant_context.pyindex eb9b5c5b1..216681c36 100644--- a/core/tests/switch_core/test_tenant_context.py+++ b/core/tests/switch_core/test_tenant_context.py@@ -8,6 +8,9 @@ import contextvarsfrom collections.abc import Coroutine, Generatorfrom typing import Any+import pytest++from switch_core.logging_context import bind_log_context, unbind_log_contextfrom switch_core.tenant_context import (bind_tenant_id,clear_tenant_id,@@ -158,3 +161,37 @@ class TestFinalisationInAnotherContext:"finalising a dropped coroutine leaked its tenant into the ""collector's context")++ @pytest.mark.xfail(+ strict=True,+ reason=(+ "tenant_scope alone does not cover this shape yet. "+ "gateway/auth.py and bridges/agent/auth.py bind a log context "+ "with the raw bind_log_context/unbind_log_context pair inside "+ "the tenant scope; unbind_log_context has the same unguarded "+ "Token.reset and raises first on finalisation, turning the "+ "GeneratorExit into a ValueError before tenant_scope's own "+ "guard ever sees one — so it resets its own token from the "+ "wrong context too, and the crash this ticket set out to close "+ "still reaches both call sites. Closing it needs "+ "logging_context.unbind_log_context to get the same guard "+ "tenant_context._held gives bind_tenant_id/unbind_tenant_id, "+ "tracked separately. Delete this test (or flip the assertion) "+ "once that lands."+ ),+ )+ def test_the_request_auth_shape_survives_too(self) -> None:+ """The shape `gateway/auth.py` and `bridges/agent/auth.py` bind: a+ tenant scope wrapping a log context, torn down together when the+ request that opened them is dropped rather than resumed."""++ async def body() -> None:+ with tenant_scope("the-request-s-tenant"):+ log_token = bind_log_context(tenant_id="the-request-s-tenant")+ try:+ await _Suspend()+ finally:+ unbind_log_context(log_token)++ self._drive_then_finalise_elsewhere(body())+ assert current_tenant_id() is None