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(security): retire unauthenticated /collab bridge-admin API (CHOO-1251, H5) (#120)

Louis Amaudruzc05d0763a287
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index 33f6136bd..4d4f4cdbe 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -25,7 +25,6 @@ PUBLIC_PATH_PREFIXES: tuple[str, ...] = (
"/health",
"/.well-known",
"/oauth",
- "/collab",
"/gateway",
# Public switchdash:// deeplink HTTP redirect — followed by whoever clicks
# the "Open in SwitchDash" link in an external channel, so no bearer token.
diff --git a/core/switch_core/bridges/collaboration/api.py b/core/switch_core/bridges/collaboration/api.py
deleted file mode 100644
index 2aaa7609d..000000000
--- a/core/switch_core/bridges/collaboration/api.py
+++ /dev/null
@@ -1,144 +0,0 @@
-from __future__ import annotations
-
-from typing import Annotated, Any
-
-from fastapi import APIRouter, Depends, HTTPException
-from pydantic import BaseModel
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from switch_core.bridges.collaboration.dependencies import (
- get_bridge_store,
- get_collab_lifecycle,
- get_session,
-)
-from switch_core.bridges.collaboration.lifecycle_service import (
- CollaborationBridgeLifecycleService,
-)
-from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
-
-router = APIRouter()
-
-
-class OnboardBridgeRequest(BaseModel):
- bridge_type: str
- display_name: str
- connection_config: dict[str, Any]
- # Nominate this bridge as the one new rooms land on when none is named.
- # Set by the bundled-Mattermost setup so a standalone deployment bridges
- # rooms out of the box.
- set_as_default: bool = False
-
-
-class OnboardBridgeResponse(BaseModel):
- bridge_id: str
- status: str
- is_default: bool
-
-
-class BridgeInfo(BaseModel):
- bridge_id: str
- bridge_type: str
- display_name: str
- status: str
- is_default: bool
-
-
-async def onboard_bridge(
- req: OnboardBridgeRequest,
- collab_lifecycle: Annotated[
- CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
- ],
- session: Annotated[AsyncSession, Depends(get_session)],
- bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
-) -> OnboardBridgeResponse:
- try:
- bridge = await collab_lifecycle.register(
- bridge_type=req.bridge_type,
- display_name=req.display_name,
- connection_config=req.connection_config,
- )
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except RuntimeError as e:
- raise HTTPException(status_code=502, detail=str(e))
-
- is_default = bridge.is_default
- if req.set_as_default:
- await bridge_store.set_default(session, bridge.id)
- await session.commit()
- is_default = True
-
- return OnboardBridgeResponse(
- bridge_id=bridge.id, status=bridge.status, is_default=is_default
- )
-
-
-async def list_bridges(
- session: Annotated[AsyncSession, Depends(get_session)],
- bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
-) -> list[BridgeInfo]:
- bridges = await bridge_store.get_all(session)
- return [
- BridgeInfo(
- bridge_id=b.id,
- bridge_type=b.type,
- display_name=b.display_name,
- status=b.status,
- is_default=b.is_default,
- )
- for b in bridges
- ]
-
-
[email protected]("/{bridge_id}")
-async def get_bridge(
- bridge_id: str,
- session: Annotated[AsyncSession, Depends(get_session)],
- bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
-) -> BridgeInfo:
- bridge = await bridge_store.get(session, bridge_id)
- if bridge is None:
- raise HTTPException(status_code=404, detail="Bridge not found")
-
- return BridgeInfo(
- bridge_id=bridge.id,
- bridge_type=bridge.type,
- display_name=bridge.display_name,
- status=bridge.status,
- is_default=bridge.is_default,
- )
-
-
[email protected]("/{bridge_id}/default")
-async def set_default_bridge(
- bridge_id: str,
- session: Annotated[AsyncSession, Depends(get_session)],
- bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
-) -> BridgeInfo:
- """Nominate a bridge as the instance default, demoting the previous one."""
- try:
- bridge = await bridge_store.set_default(session, bridge_id)
- except ValueError as e:
- raise HTTPException(status_code=404, detail=str(e))
- await session.commit()
-
- return BridgeInfo(
- bridge_id=bridge.id,
- bridge_type=bridge.type,
- display_name=bridge.display_name,
- status=bridge.status,
- is_default=bridge.is_default,
- )
-
-
[email protected]("/{bridge_id}")
-async def remove_bridge(
- bridge_id: str,
- collab_lifecycle: Annotated[
- CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
- ],
-) -> dict[str, bool]:
- await collab_lifecycle.remove(bridge_id)
- return {"ok": True}
diff --git a/core/switch_core/bridges/collaboration/app.py b/core/switch_core/bridges/collaboration/app.py
deleted file mode 100644
index 38c89056b..000000000
--- a/core/switch_core/bridges/collaboration/app.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from __future__ import annotations
-
-from fastapi import FastAPI
-
-from switch_core.bridges.collaboration.api import router as bridges_router
-from switch_core.bridges.collaboration.dependencies import init_dependencies
-from switch_core.bridges.collaboration.lifecycle_service import (
- CollaborationBridgeLifecycleService,
-)
-from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
-
-
-def create_collaboration_bridge_app(
- *,
- bridge_store: CollaborationBridgeStore,
- collab_lifecycle: CollaborationBridgeLifecycleService,
- session_factory: object,
-) -> FastAPI:
- init_dependencies(
- bridge_store=bridge_store,
- collab_lifecycle=collab_lifecycle,
- session_factory=session_factory,
- )
-
- app = FastAPI(title="Switch Collaboration Bridge API")
- app.include_router(bridges_router, prefix="/bridges", tags=["bridges"])
-
- return app
diff --git a/core/switch_core/bridges/collaboration/dependencies.py b/core/switch_core/bridges/collaboration/dependencies.py
deleted file mode 100644
index a9cca026d..000000000
--- a/core/switch_core/bridges/collaboration/dependencies.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from __future__ import annotations
-
-from collections.abc import AsyncIterator
-from typing import Any
-
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from switch_core.bridges.collaboration.lifecycle_service import (
- CollaborationBridgeLifecycleService,
-)
-from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
-
-_state: dict[str, Any] = {}
-
-
-def init_dependencies(
- *,
- bridge_store: CollaborationBridgeStore,
- collab_lifecycle: CollaborationBridgeLifecycleService,
- session_factory: Any,
-) -> None:
- _state["bridge_store"] = bridge_store
- _state["collab_lifecycle"] = collab_lifecycle
- _state["session_factory"] = session_factory
-
-
-async def get_session() -> AsyncIterator[AsyncSession]:
- async with _state["session_factory"]() as session:
- yield session
-
-
-def get_bridge_store() -> CollaborationBridgeStore:
- return _state["bridge_store"] # type: ignore[no-any-return]
-
-
-def get_collab_lifecycle() -> CollaborationBridgeLifecycleService:
- return _state["collab_lifecycle"] # type: ignore[no-any-return]
diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.py
index 779e12ca2..145383efa 100644
--- a/core/switch_core/gateway/collaborations.py
+++ b/core/switch_core/gateway/collaborations.py
@@ -56,6 +56,8 @@ async def list_bridge_types(
@router.post("")
async def create_bridge(
req: BridgeCreateRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
collab_lifecycle: Annotated[
CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)
],
@@ -75,18 +77,52 @@ async def create_bridge(
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ is_default = bridge.is_default
+ if req.set_as_default:
+ await bridge_store.set_default(session, bridge.id)
+ await session.commit()
+ is_default = True
+
return BridgeDetail(
bridge_id=bridge.id,
bridge_type=bridge.type,
display_name=bridge.display_name,
status=bridge.status,
agent_greetings_enabled=bridge.agent_greetings_enabled,
- is_default=bridge.is_default,
+ is_default=is_default,
room_count=0,
created_at=str(bridge.created_at),
)
[email protected]("/{bridge_id}/default")
+async def set_default_bridge(
+ bridge_id: str,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ bridge_store: Annotated[CollaborationBridgeStore, Depends(get_bridge_store)],
+ room_store: Annotated[RoomStore, Depends(get_room_store)],
+ _user: Annotated[User, Depends(require_admin)],
+) -> BridgeDetail:
+ """Nominate a bridge as the instance default, demoting the previous one."""
+ try:
+ bridge = await bridge_store.set_default(session, bridge_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ await session.commit()
+
+ rooms = await room_store.get_by_bridge(session, bridge_id)
+ return BridgeDetail(
+ bridge_id=bridge.id,
+ bridge_type=bridge.type,
+ display_name=bridge.display_name,
+ status=bridge.status,
+ agent_greetings_enabled=bridge.agent_greetings_enabled,
+ is_default=bridge.is_default,
+ room_count=len(rooms),
+ created_at=str(bridge.created_at),
+ )
+
+
@router.get("")
async def list_bridges(
session: Annotated[AsyncSession, Depends(get_session)],
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 7e5fed3aa..130ac70c4 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -431,6 +431,10 @@ class BridgeCreateRequest(BaseModel):
bridge_type: str
display_name: str
connection_config: dict[str, object]
+ # Nominate this bridge as the one new rooms land on when none is named.
+ # Set by the headless standalone bootstrap so a fresh deployment bridges
+ # rooms out of the box.
+ set_as_default: bool = False
class ExternalUserSummary(BaseModel):
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 94cc26f5c..95f87daab 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -30,7 +30,6 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (
OpenCodeConnectionConfig,
OpenCodeConnector,
)
-from switch_core.bridges.collaboration.app import create_collaboration_bridge_app
from switch_core.bridges.collaboration.discord.adapter import (
DiscordAdapter,
DiscordConnectionConfig,
@@ -340,12 +339,6 @@ async def run() -> None:
config=config,
connections=connections,
)
- collab_bridge_app = create_collaboration_bridge_app(
- bridge_store=bridge_store,
- collab_lifecycle=collab_lifecycle,
- session_factory=session_factory,
- )
-
# ── Server-side connector lifecycle ─────────────────────────────────────
connector_lifecycle = ServerSideConnectorLifecycleService(
connector_store=connector_store,
@@ -389,12 +382,11 @@ async def run() -> None:
"discord", DiscordAdapter, DiscordConnectionConfig
)
- # Health check and collab bridge mounted on the agent bridge app
+ # Health check mounted on the agent bridge app
@agent_bridge_app.get("/health")
async def health_check() -> JSONResponse:
return JSONResponse({"status": "ok"})
- agent_bridge_app.mount("/collab", collab_bridge_app)
agent_bridge_app.mount("/gateway", gateway_app)
# ── Ensure system clients exist ─────────────────────────────────────────
diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
index 705066c53..32462a437 100644
--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_remove.py
@@ -92,7 +92,7 @@ async def test_remove_detaches_dependent_rooms(
) -> None:
"""Removing a bridge that still has dependent rooms must not FK-violate.
- Regression for the DELETE /collab/bridges 500: rooms.bridge_id references
+ Regression for the DELETE /gateway/collaborations 500: rooms.bridge_id references
collaboration_bridges.id with no ON DELETE rule, so deleting the bridge
while rooms point at it raised a raw FK error. remove() now detaches the
rooms (non-destructive) before deleting the bridge.
diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.py
new file mode 100644
index 000000000..37f6388fb
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py
@@ -0,0 +1,149 @@
+"""Security regression tests for retiring the unauthenticated /collab
+bridge-admin API (CHOO-1251, H5).
+
+The old `/collab` mount let anyone list/delete/register collaboration bridges
+with no credentials: it sat on the Bearer-auth bypass list and its handlers
+carried no authorization. The fix removes `/collab` entirely and routes all
+bridge administration through the already admin-gated
+`/gateway/collaborations`, adding the one capability the gateway lacked
+(nominating a default bridge).
+
+These tests lock in three properties:
+1. `/collab` is gone — not in the auth-bypass list, and its modules deleted.
+2. Every collaboration write route on the gateway requires an admin (the
+ route dependency is `require_admin`), and every route requires at least
+ authentication.
+3. The new set-default behaviour is correct against real Postgres.
+"""
+
+from __future__ import annotations
+
+import importlib
+import uuid
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.auth import PUBLIC_PATH_PREFIXES
+from switch_core.db.models import Client, CollaborationBridge, User
+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore
+from switch_core.db.stores.room_store import RoomStore
+from switch_core.gateway.auth import get_current_user, require_admin
+from switch_core.gateway.collaborations import router, set_default_bridge
+
+_BRIDGE_STORE = CollaborationBridgeStore()
+_ROOM_STORE = RoomStore()
+
+
+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
+
+
+# ── 1. /collab is retired ────────────────────────────────────────────────────
+
+
+def test_collab_not_on_auth_bypass_list() -> None:
+ assert "/collab" not in PUBLIC_PATH_PREFIXES
+
+
+def test_collab_api_module_is_gone() -> None:
+ # The unauthenticated bridge-admin app and its wiring were deleted; importing
+ # them must fail rather than silently resurrect a second admin surface.
+ for module in (
+ "switch_core.bridges.collaboration.api",
+ "switch_core.bridges.collaboration.app",
+ "switch_core.bridges.collaboration.dependencies",
+ ):
+ with pytest.raises(ModuleNotFoundError):
+ importlib.import_module(module)
+
+
+# ── 2. gateway collaboration routes are authorized ───────────────────────────
+
+
+def test_bridge_write_routes_require_admin() -> None:
+ """create + set-default (the state-changing admin actions) must be gated on
+ require_admin — a bridge is an unowned, workspace-wide integration holding
+ platform secrets."""
+ admin_gated = {
+ (frozenset(route.methods), route.path)
+ for route in router.routes
+ if require_admin in _dependency_calls(route.dependant)
+ }
+ assert (frozenset({"POST"}), "") in admin_gated # create
+ assert (frozenset({"POST"}), "/{bridge_id}/default") in admin_gated # set-default
+
+
+def test_every_collaboration_route_requires_authentication() -> None:
+ """No route may fall back to the old unauthenticated behaviour: each must
+ depend on get_current_user directly or via require_admin."""
+ for route in router.routes:
+ calls = _dependency_calls(route.dependant)
+ assert get_current_user in calls or require_admin in calls, (
+ f"{sorted(route.methods)} {route.path} is not authenticated"
+ )
+
+
+# ── 3. set-default behaviour ─────────────────────────────────────────────────
+
+
+async def _make_bridge(session: AsyncSession, *, is_default: bool = False) -> str:
+ client = Client(
+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:12]}:test",
+ display_name="bridge client",
+ type="bridge",
+ password="x",
+ )
+ session.add(client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="mattermost",
+ display_name="MM",
+ client_id=client.id,
+ status="active",
+ is_default=is_default,
+ )
+ session.add(bridge)
+ await session.flush()
+ return bridge.id
+
+
+def _admin() -> User:
+ return User(id="admin-1", name="admin", email="admin@test", role="admin")
+
+
+async def test_set_default_promotes_and_demotes(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ first = await _make_bridge(session, is_default=True)
+ second = await _make_bridge(session, is_default=False)
+ await session.commit()
+
+ async with session_factory() as session:
+ detail = await set_default_bridge(
+ second, session, _BRIDGE_STORE, _ROOM_STORE, _admin()
+ )
+ assert detail.bridge_id == second
+ assert detail.is_default is True
+
+ async with session_factory() as session:
+ assert (await _BRIDGE_STORE.get(session, second)).is_default is True
+ # The previous default was demoted — a single-default invariant holds.
+ assert (await _BRIDGE_STORE.get(session, first)).is_default is False
+
+
+async def test_set_default_unknown_bridge_is_404(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ async with session_factory() as session:
+ with pytest.raises(HTTPException) as exc:
+ await set_default_bridge(
+ "does-not-exist", session, _BRIDGE_STORE, _ROOM_STORE, _admin()
+ )
+ assert exc.value.status_code == 404
diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
index 7829a1830..5acd58de0 100644
--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -176,6 +176,8 @@ services:
MATTERMOST_TEAM_NAME: ${MATTERMOST_TEAM_NAME}
MATTERMOST_USER: ${MATTERMOST_USER}
MATTERMOST_USER_PASSWORD: ${MATTERMOST_USER_PASSWORD}
+ GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
+ GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
depends_on:
- mattermost
- switch
diff --git a/deploy/local/docker-compose.yml b/deploy/local/docker-compose.yml
index bd6e90021..7099d51b1 100644
--- a/deploy/local/docker-compose.yml
+++ b/deploy/local/docker-compose.yml
@@ -89,6 +89,8 @@ services:
MATTERMOST_TEAM_NAME: ${MATTERMOST_TEAM_NAME}
MATTERMOST_USER: ${MATTERMOST_USER}
MATTERMOST_USER_PASSWORD: ${MATTERMOST_USER_PASSWORD}
+ GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
+ GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
depends_on:
- mattermost
diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.yml
index d715a9f27..8b1291271 100644
--- a/deploy/local/standalone-docker-compose.yml
+++ b/deploy/local/standalone-docker-compose.yml
@@ -169,6 +169,8 @@ services:
MATTERMOST_TEAM_NAME: ${MATTERMOST_TEAM_NAME}
MATTERMOST_USER: ${MATTERMOST_USER}
MATTERMOST_USER_PASSWORD: ${MATTERMOST_USER_PASSWORD}
+ GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
+ GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
depends_on:
- mattermost
- switch
diff --git a/deploy/remote/helm/switch/samples/ingress.example.yaml b/deploy/remote/helm/switch/samples/ingress.example.yaml
index 937076645..da0652d45 100644
--- a/deploy/remote/helm/switch/samples/ingress.example.yaml
+++ b/deploy/remote/helm/switch/samples/ingress.example.yaml
@@ -10,8 +10,8 @@
# switch.example.com -> your hostname
# letsencrypt-prod -> your cert-manager ClusterIssuer (or drop TLS entirely)
#
-# Routing mirrors the managed Ingress: the agent/MCP surface and bridge webhooks
-# go to switch-core; everything else (the gateway SPA, which proxies /gateway to
+# Routing mirrors the managed Ingress: the agent/MCP surface goes to
+# switch-core; everything else (the gateway SPA, which proxies /gateway to
# switch-core) goes to the gateway.
apiVersion: networking.k8s.io/v1
kind: Ingress
@@ -46,9 +46,6 @@ spec:
- path: /.well-known
pathType: Prefix
backend: { service: { name: RELEASE-switch-core, port: { number: 8000 } } }
- - path: /collab
- pathType: Prefix
- backend: { service: { name: RELEASE-switch-core, port: { number: 8000 } } }
- path: /health
pathType: Prefix
backend: { service: { name: RELEASE-switch-core, port: { number: 8000 } } }
diff --git a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml b/deploy/remote/helm/switch/templates/common/generic-ingress.yaml
index 1706966a6..fdbf23d43 100644
--- a/deploy/remote/helm/switch/templates/common/generic-ingress.yaml
+++ b/deploy/remote/helm/switch/templates/common/generic-ingress.yaml
@@ -3,9 +3,9 @@
{{- $svcGateway := printf "%s-gateway" (include "switch.fullname" .) }}
# Generic Ingress for the Switch web surface (ingress.mode=managed).
#
-# One host, path-routed. The agent/MCP surface and bridge webhooks go straight
-# to switch-core; everything else (the gateway SPA, which itself proxies
-# /gateway to switch-core) goes to the gateway. Bring your own ingress
+# One host, path-routed. The agent/MCP surface goes straight to switch-core;
+# everything else (the gateway SPA, which itself proxies /gateway to
+# switch-core) goes to the gateway. Bring your own ingress
# controller: set ingress.className, ingress.host and, for HTTPS, ingress.tls.
#
# ingress.mode=existing renders nothing — see samples/ingress.example.yaml for
diff --git a/deploy/remote/helm/switch/templates/setup/job.yaml b/deploy/remote/helm/switch/templates/setup/job.yaml
index 39ad66928..892455d56 100644
--- a/deploy/remote/helm/switch/templates/setup/job.yaml
+++ b/deploy/remote/helm/switch/templates/setup/job.yaml
@@ -55,4 +55,14 @@ spec:
secretKeyRef:
name: {{ include "switch.secretName" . }}
key: MATTERMOST_USER_PASSWORD
+ - name: GATEWAY_ADMIN_EMAIL
+ valueFrom:
+ secretKeyRef:
+ name: {{ include "switch.secretName" . }}
+ key: GATEWAY_ADMIN_EMAIL
+ - name: GATEWAY_ADMIN_PASSWORD
+ valueFrom:
+ secretKeyRef:
+ name: {{ include "switch.secretName" . }}
+ key: GATEWAY_ADMIN_PASSWORD
{{- end }}
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 6ae1e461f..3c0e9bb33 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -39,14 +39,12 @@ ingress:
# above, or reference a pre-created TLS Secret.
secretName: ""
# Path prefixes on the primary host routed to switch-core instead of the
- # gateway: the Bearer-auth agent bridge + MCP, public OAuth/MCP discovery,
- # and the collaboration bridge webhooks.
+ # gateway: the Bearer-auth agent bridge + MCP, and public OAuth/MCP discovery.
agentApiPaths:
- /agents
- /mcp
- /oauth
- /.well-known
- - /collab
- /health
# ── Secrets ───────────────────────────────────────────────────────────────────
diff --git a/deploy/shared_resources/setup.py b/deploy/shared_resources/setup.py
index 71b029254..887554ee1 100644
--- a/deploy/shared_resources/setup.py
+++ b/deploy/shared_resources/setup.py
@@ -2,7 +2,8 @@
Runs as a short-lived init container in docker-compose. Waits for Switch and
Mattermost to be healthy, bootstraps the Mattermost admin/team, then registers
-the Mattermost bridge via the Switch collaboration API.
+the Mattermost bridge via the authorized Switch gateway API — logging in as the
+seeded gateway admin first, since bridge administration is an admin action.
"""
import os
@@ -12,6 +13,8 @@ import time
import httpx
SWITCH_URL = os.environ["SWITCH_URL"]
+GATEWAY_ADMIN_EMAIL = os.environ["GATEWAY_ADMIN_EMAIL"]
+GATEWAY_ADMIN_PASSWORD = os.environ["GATEWAY_ADMIN_PASSWORD"]
MATTERMOST_URL = os.environ["MATTERMOST_URL"]
MATTERMOST_URL_FOR_SWITCH = os.environ.get(
"MATTERMOST_URL_FOR_SWITCH", "http://localhost:8065"
@@ -162,11 +165,29 @@ def setup_mattermost() -> None:
def register_bridge() -> None:
- """Register Mattermost bridge with Switch via the collaboration API."""
+ """Register Mattermost bridge with Switch via the authorized gateway API.
+
+ Bridge administration is admin-gated, so we log in as the seeded gateway
+ admin (cookie-based JWT) and drive the same authorized endpoint the
+ dashboard uses — there is no unauthenticated bridge-admin surface.
+ """
client = httpx.Client(base_url=SWITCH_URL, timeout=10)
+ # Authenticate as the seeded gateway admin; the login sets the switch_auth
+ # cookie on the client, which every subsequent gateway call carries.
+ resp = client.post(
+ "/gateway/auth/login",
+ json={"email": GATEWAY_ADMIN_EMAIL, "password": GATEWAY_ADMIN_PASSWORD},
+ )
+ if not resp.is_success:
+ print(
+ "ERROR: Could not log in to the Switch gateway as "
+ f"{GATEWAY_ADMIN_EMAIL}: {resp.status_code} {resp.text}"
+ )
+ sys.exit(1)
+
# Check if bridge already registered
- resp = client.get("/collab/bridges")
+ resp = client.get("/gateway/collaborations")
if resp.is_success:
bridges = resp.json()
for bridge in bridges:
@@ -178,7 +199,7 @@ def register_bridge() -> None:
# rather than only new ones.
if not any(b.get("is_default") for b in bridges):
client.post(
- f"/collab/bridges/{bridge_id}/default"
+ f"/gateway/collaborations/{bridge_id}/default"
).raise_for_status()
print(f"Set Mattermost bridge as default: {bridge_id}")
client.close()
@@ -199,7 +220,7 @@ def register_bridge() -> None:
if MATTERMOST_PUBLIC_URL:
connection_config["public_url"] = MATTERMOST_PUBLIC_URL
resp = client.post(
- "/collab/bridges",
+ "/gateway/collaborations",
json={
"bridge_type": "mattermost",
"display_name": "Mattermost",
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 73a074aec..1a0d3da10 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -33,14 +33,13 @@ rooms, and to bridge them out to external platforms.
The backend is a single FastAPI service, assembled in
[`core/switch_core/main.py`](../core/switch_core/main.py). The Agent Bridge app is
-the root ASGI app; the MCP server, health check, collaboration bridge, and
-gateway are mounted onto it:
+the root ASGI app; the MCP server, health check, and gateway are mounted onto it:
- `POST/GET /agents/...` — Agent Bridge HTTP API
- `/mcp` — MCP server (agent tool surface)
- `/health` — health check
-- `/collab` — collaboration bridge admin API (bridge CRUD/onboarding)
-- `/gateway` — gateway management API (backs the operator dashboard)
+- `/gateway` — gateway management API (backs the operator dashboard); includes
+ the admin-gated collaboration-bridge admin API (`/gateway/collaborations`)
```mermaid
flowchart LR
@@ -180,8 +179,8 @@ sequenceDiagram
AC-->>AG: append AgentEvent (pushed down the agent's SSE stream)
```
-Inbound messages do **not** arrive through the `/collab` HTTP app (that app only
-does bridge CRUD). Each adapter owns its transport:
+Inbound messages do **not** arrive through the `/gateway/collaborations` admin
+API (that only does bridge CRUD). Each adapter owns its transport:
Slack (Socket Mode WebSocket), Mattermost (WebSocket), and Discord (Gateway
WebSocket) hold **authenticated outbound connections**; Teams is the exception —
it self-hosts an HTTP listener (default port 3978) for Bot Framework activities
@@ -275,13 +274,14 @@ Everything ingress-facing, and where to find it:
| Agent event stream | `/agents/{id}/events` (SSE) | Bearer | `bridges/agent/protocol/stream.py`, `protocol/connections.py` |
| MCP server | `/mcp` (HTTP, FastMCP) | Bearer | `bridges/agent/mcp/server.py` |
| Health | `/health` | public | `main.py` |
-| Collaboration admin | `/collab/bridges` | (bridge CRUD) | `bridges/collaboration/api.py` |
+| Collaboration admin | `/gateway/collaborations` | cookie JWT + admin | `gateway/collaborations.py` |
| Gateway API | `/gateway/*` | cookie JWT (`switch_auth`) | `gateway/app.py`, `gateway/auth.py` |
| Platform ingress | adapter transports (Slack/MM/Discord WebSocket; Teams HTTP :3978) | platform token / Teams JWT+HMAC | `bridges/collaboration/*/adapter.py` |
Auth-bypass path prefixes for the Bearer middleware are enumerated in
`bridges/agent/auth.py` (`PUBLIC_PATH_PREFIXES`): `/health`, `/.well-known`,
-`/collab`, `/gateway` (the gateway uses its own cookie-based auth).
+`/oauth`, `/gateway` (the gateway uses its own cookie-based auth), and
+`/deeplink`.
---