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(agent): scope the deployment-wide registration token to a non-admin owner (CHOO-2624)

Wojciech Wojtyniak93504c1fc9cf
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index b85f29503..a05bb1f17 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -90,6 +90,10 @@ from switch_core.bridges.agent.protocol.connections import (
)
from switch_core.bridges.agent.protocol.service import AgentExistsError, ProtocolService
from switch_core.bridges.agent.protocol.stream import event_stream
+from switch_core.bridges.agent.registration_bootstrap import (
+ REGISTRATION_KEY_TYPES,
+ resolve_registration_owner_id,
+)
from switch_core.db.models import Agent, Task
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.feature_flag_store import FeatureFlagStore
@@ -130,17 +134,24 @@ async def _resolve_registration_user_id(
authorization: Annotated[str, Header()],
session: Annotated[AsyncSession, Depends(get_session)],
api_key_store: Annotated[ApiKeyStore, Depends(get_api_key_store)],
+ protocol: Annotated[ProtocolService, Depends(get_protocol)],
) -> str:
"""Validate the registration token in the Authorization header and
- return the owning user_id."""
+ return the user_id new agents should be owned by.
+
+ A personal ``"registration"`` key resolves to the user who minted it. The
+ deployment-wide ``"bootstrap"`` key (see ``registration_bootstrap.py``)
+ resolves to a dedicated, non-admin account instead of the admin who
+ seeded it, so holding it never confers admin authority.
+ """
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid authorization header")
token = authorization[7:]
token_hash = hashlib.sha256(token.encode()).hexdigest()
key = await api_key_store.get_by_hash(session, token_hash)
- if key is None or key.type != "registration":
+ if key is None or key.type not in REGISTRATION_KEY_TYPES:
raise HTTPException(status_code=401, detail="Invalid registration token")
- return key.user_id
+ return await resolve_registration_owner_id(session, protocol.user_store, key)
# Registration endpoints
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index 712ef320b..ca0df669d 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -11,6 +11,7 @@ from starlette.responses import Response
from starlette.types import ASGIApp, Receive, Scope, Send
from switch_core.bridges.agent.api_key_cache import ApiKeyCache
+from switch_core.bridges.agent.registration_bootstrap import REGISTRATION_KEY_TYPES
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
@@ -71,8 +72,9 @@ class BearerAuthMiddleware:
Used by agent-bridge HTTP endpoints and MCP.
2. OIDC token — validated against the configured issuer, mapped to an
agent via the ``oauth_client_id`` field on Agent.
- 3. Registration token — an ApiKey row of type ``"registration"`` that
- has no associated agent. Used by the registration endpoint
+ 3. Registration token — an ApiKey row of type ``"registration"`` or
+ ``"bootstrap"`` (see ``registration_bootstrap.py``) that has no
+ associated agent. Used by the registration endpoint
(``POST /agents``). Sets ``scope["api_key"]`` so downstream
handlers can validate it again.
@@ -137,7 +139,7 @@ class BearerAuthMiddleware:
# Registration token: pass through (handler validates again). MCP rejects.
if (
api_key is not None
- and api_key.type == "registration"
+ and api_key.type in REGISTRATION_KEY_TYPES
and not path.startswith("/mcp")
):
scope["api_key"] = api_key
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index d9a15bb0d..e181b5b37 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -51,6 +51,10 @@ from switch_core.bridges.agent.protocol.types import (
ToolCallReport,
ToolSpec,
)
+from switch_core.bridges.agent.registration_bootstrap import (
+ REGISTRATION_KEY_TYPES,
+ resolve_registration_owner_id,
+)
from switch_core.bridges.resource.service import ResourceService
from switch_core.crypto import encrypt_token
from switch_core.db.models import (
@@ -435,14 +439,18 @@ class ProtocolService:
) -> RegistrationResult:
"""Resolve a registration token to its owner, then register the agent.
- Raises PermissionError if the token does not match a stored ApiKey.
+ Raises PermissionError if the token does not match a stored ApiKey of
+ a registration type (see ``registration_bootstrap.REGISTRATION_KEY_TYPES``).
Raises AgentExistsError if the name is taken and ``overwrite`` is False.
"""
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:
- raise PermissionError("Invalid registration token")
+ if key is None or key.type not in REGISTRATION_KEY_TYPES:
+ raise PermissionError("Invalid registration token")
+ owner_id = await resolve_registration_owner_id(
+ session, self.user_store, key
+ )
return await self.register_agent(
name=name,
@@ -453,7 +461,7 @@ class ProtocolService:
tools=tools,
models=models,
metadata=metadata,
- owner_id=key.user_id,
+ owner_id=owner_id,
overwrite=overwrite,
addressable_by_agent_ids=addressable_by_agent_ids,
owner_only=owner_only,
diff --git a/core/switch_core/bridges/agent/registration_bootstrap.py b/core/switch_core/bridges/agent/registration_bootstrap.py
new file mode 100644
index 000000000..27283d73b
--- /dev/null
+++ b/core/switch_core/bridges/agent/registration_bootstrap.py
@@ -0,0 +1,72 @@
+"""The deployment-wide agent-registration bootstrap credential.
+
+``AGENT_REGISTRATION_TOKEN`` is seeded once at startup as an ``ApiKey`` of
+type ``"bootstrap"`` (see ``main.py``) so a fresh deployment has *some* way to
+register its first agents before any user has logged into the gateway to mint
+a personal one (``gateway/api_keys.py``, type ``"registration"``).
+
+A ``"registration"`` key is minted by, and owned by, a single user: agents it
+registers are attributed to that user directly. A ``"bootstrap"`` key has no
+such owner in mind — it is handed to whoever needs to bring an agent up
+against a fresh deployment — so agents registered through it are attributed
+to a dedicated, non-admin account (see :data:`BOOTSTRAP_OWNER_EMAIL`) instead
+of the seeded admin. Otherwise every holder of that one shared secret would
+register agents that inherit the admin's authority over every room and
+resource in the deployment, not just their own.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from switch_core.db.models import ApiKey, User
+from switch_core.db.stores.user_store import UserStore
+
+BOOTSTRAP_KEY_TYPE = "bootstrap"
+
+# Every ApiKey type that may stand in for a registration token at the
+# `POST /agents` family of endpoints. Anything else (in practice, an agent's
+# own `"agent"`-type key) must not be replayed to register more agents.
+REGISTRATION_KEY_TYPES = ("registration", BOOTSTRAP_KEY_TYPE)
+
+# Synthetic account, never logged into (no password), that owns every agent
+# registered through the deployment-wide bootstrap key. Kept distinct from
+# the admin user specifically so that key confers no admin authority.
+BOOTSTRAP_OWNER_EMAIL = "[email protected]"
+BOOTSTRAP_OWNER_NAME = "Agent Bootstrap"
+
+BOOTSTRAP_KEY_LABEL = "Deployment bootstrap (from AGENT_REGISTRATION_TOKEN)"
+
+# Label of the key this replaces, from before agent-registration bootstrap
+# had its own owner and its own ApiKey type. Startup seeding uses this to
+# find and migrate an existing deployment's old admin-owned key in place
+# rather than leaving it live alongside a new one.
+LEGACY_BOOTSTRAP_KEY_LABEL = "Default (from AGENT_REGISTRATION_TOKEN)"
+
+
+async def ensure_bootstrap_owner(session: AsyncSession, user_store: UserStore) -> User:
+ """Idempotently create the account bootstrap-registered agents are owned by."""
+ owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)
+ if owner is not None:
+ return owner
+ owner = User(name=BOOTSTRAP_OWNER_NAME, email=BOOTSTRAP_OWNER_EMAIL, role="user")
+ await user_store.create(session, owner)
+ return owner
+
+
+async def resolve_registration_owner_id(
+ session: AsyncSession, user_store: UserStore, key: ApiKey
+) -> str:
+ """The user new agents should be owned by, given the key used to register them.
+
+ ``key`` must already be validated as one of ``REGISTRATION_KEY_TYPES``.
+ """
+ if key.type != BOOTSTRAP_KEY_TYPE:
+ return key.user_id
+ owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)
+ if owner is None:
+ raise RuntimeError(
+ f"Agent-registration bootstrap owner ({BOOTSTRAP_OWNER_EMAIL}) is "
+ "missing; restart the server to reseed it."
+ )
+ return owner.id
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index a677214d5..7f091ce1e 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -22,6 +22,12 @@ from switch_core.bridges.agent.protocol.connections import (
)
from switch_core.bridges.agent.protocol.event_buffer import EventBuffer
from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_KEY_LABEL,
+ BOOTSTRAP_KEY_TYPE,
+ LEGACY_BOOTSTRAP_KEY_LABEL,
+ ensure_bootstrap_owner,
+)
from switch_core.bridges.agent.server_connectors.lifecycle import (
ServerSideConnectorLifecycleService,
)
@@ -208,9 +214,9 @@ async def run() -> None:
message_store = MessageStore()
media_store = MediaStore()
- # ── Seed admin user + registration key ──────────────────────────────────
+ # ── Seed admin user + agent-registration bootstrap key ──────────────────
await _seed_admin_user(session_factory, user_store, config)
- await _seed_admin_registration_key(
+ await _seed_agent_registration_bootstrap_key(
session_factory, user_store, api_key_store, config
)
@@ -487,41 +493,110 @@ async def _seed_admin_user(
logger.info("Seeded admin user: %s", config.gateway_admin_email)
-async def _seed_admin_registration_key(
+# Marker recorded on the admin user's metadata once the agent-registration
+# bootstrap key has been seeded. Independent of the ApiKey row itself so that
+# an operator who deletes the key (revoking it from the gateway's API Keys
+# page) gets a permanent revocation: the next restart sees the flag, finds no
+# bootstrap-type key, and does not silently recreate one from the still-set
+# AGENT_REGISTRATION_TOKEN. Rotating the env var, by contrast, always takes
+# effect immediately: an existing bootstrap key's hash is kept in sync with
+# whatever the config currently holds.
+_BOOTSTRAP_SEEDED_FLAG = "agent_bootstrap_key_seeded"
+
+
+async def _seed_agent_registration_bootstrap_key(
session_factory: object,
user_store: UserStore,
api_key_store: ApiKeyStore,
config: SwitchConfig,
) -> None:
+ """Seed the deployment-wide agent-registration bootstrap key.
+
+ Unlike a personal registration key (minted by, and owned by, a single
+ gateway user), this key is handed out to bring up the first agents
+ against a fresh deployment before anyone has logged in. Agents it
+ registers are attributed to a dedicated, non-admin account (see
+ ``registration_bootstrap.py``), not to the admin user this key's ApiKey
+ row is filed under — the row lives on the admin so it is listed and
+ revocable from the admin's own API Keys page, but holding the token
+ itself confers no admin authority.
+ """
async with session_factory() as session: # type: ignore[operator]
admin = await user_store.get_by_email(session, config.gateway_admin_email)
if admin is None:
- logger.error(
- "Cannot seed registration key: admin user %s not found",
- config.gateway_admin_email,
+ raise RuntimeError(
+ "Cannot seed agent-registration bootstrap key: admin user "
+ f"{config.gateway_admin_email} not found"
)
- return
+ await ensure_bootstrap_owner(session, user_store)
token_hash = hashlib.sha256(
config.agent_registration_token.encode()
).hexdigest()
- existing = await api_key_store.get_by_hash(session, token_hash)
- if existing is not None:
- logger.info("Admin registration key already seeded")
- return
+ encrypted_key = encrypt_token(
+ config.agent_registration_token, config.jwt_secret_key
+ )
- key = ApiKey(
- user_id=admin.id,
- key_hash=token_hash,
- encrypted_key=encrypt_token(
- config.agent_registration_token, config.jwt_secret_key
+ admin_keys = await api_key_store.get_by_user(session, admin.id)
+ legacy_key = next(
+ (
+ k
+ for k in admin_keys
+ if k.type == "registration" and k.label == LEGACY_BOOTSTRAP_KEY_LABEL
),
- label="Default (from AGENT_REGISTRATION_TOKEN)",
- type="registration",
+ None,
)
- await api_key_store.create(session, key)
+ bootstrap_key = next(
+ (k for k in admin_keys if k.type == BOOTSTRAP_KEY_TYPE), None
+ )
+ already_seeded = bool((admin.metadata_ or {}).get(_BOOTSTRAP_SEEDED_FLAG))
+
+ if legacy_key is not None and bootstrap_key is None:
+ legacy_key.type = BOOTSTRAP_KEY_TYPE
+ legacy_key.label = BOOTSTRAP_KEY_LABEL
+ legacy_key.key_hash = token_hash
+ legacy_key.encrypted_key = encrypted_key
+ bootstrap_key = legacy_key
+ already_seeded = True
+ logger.info(
+ "Migrated the legacy admin-owned registration key to a "
+ "scoped agent-registration bootstrap key"
+ )
+
+ if bootstrap_key is not None:
+ if bootstrap_key.key_hash != token_hash:
+ bootstrap_key.key_hash = token_hash
+ bootstrap_key.encrypted_key = encrypted_key
+ logger.info(
+ "Rotated the agent-registration bootstrap key from "
+ "AGENT_REGISTRATION_TOKEN"
+ )
+ elif already_seeded:
+ logger.warning(
+ "Agent-registration bootstrap key was revoked; not "
+ "reseeding it from AGENT_REGISTRATION_TOKEN. Mint per-user "
+ "registration keys from the gateway's API Keys page instead."
+ )
+ else:
+ key = ApiKey(
+ user_id=admin.id,
+ key_hash=token_hash,
+ encrypted_key=encrypted_key,
+ label=BOOTSTRAP_KEY_LABEL,
+ type=BOOTSTRAP_KEY_TYPE,
+ )
+ await api_key_store.create(session, key)
+ logger.info(
+ "Seeded the agent-registration bootstrap key from "
+ "AGENT_REGISTRATION_TOKEN"
+ )
+
+ if not already_seeded:
+ meta = dict(admin.metadata_ or {})
+ meta[_BOOTSTRAP_SEEDED_FLAG] = True
+ admin.metadata_ = meta
+
await session.commit()
- logger.info("Seeded admin registration key from AGENT_REGISTRATION_TOKEN")
async def _shutdown(
diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.py
index 4442fd186..a777f41c4 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -75,6 +75,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.task_store import TaskStore
from switch_core.db.stores.user_store import UserStore
+from switch_core.main import _seed_agent_registration_bootstrap_key
from switch_core.messages.notify import MessageListener
from switch_core.provisioning import Provisioning
from switch_core.provisioning.postgres import PostgresProvisioning
@@ -248,6 +249,24 @@ class Harness:
self._registered.append(result.agent_id)
return result
+ async def register_agent_via_registration_token(
+ self, name: str, token: str
+ ) -> RegistrationResult:
+ """Register the way a standalone agent does: with a bearer token
+ presented to `POST /agents`, resolved here directly against the
+ protocol service rather than over real HTTP."""
+ result = await self.protocol.register_agent_with_token(
+ registration_token=token,
+ name=name,
+ description=f"integration test agent {name}",
+ connector_type="test",
+ integration_profile=_PROFILE,
+ overwrite=True,
+ owner_only=False,
+ )
+ self._registered.append(result.agent_id)
+ return result
+
async def start_clients(self, timeout: float = 20.0) -> None:
"""Start every registered agent's client and await readiness.
@@ -375,6 +394,13 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:
await session.commit()
owner_id = owner.id
+ # Seeds the same deployment-wide bootstrap key `main.py` would on a real
+ # boot, so a test can register through REGISTRATION_TOKEN exactly as a
+ # standalone agent does, without duplicating that seeding logic here.
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, session_env.user_store, session_env.api_key_store, config
+ )
+
# Per-test in-memory wiring: a fresh EventBuffer / client registry so queued
# events and client registrations never leak across tests.
event_buffer = EventBuffer()
diff --git a/core/tests/integration/test_registration_bootstrap_scope.py b/core/tests/integration/test_registration_bootstrap_scope.py
new file mode 100644
index 000000000..ca2107187
--- /dev/null
+++ b/core/tests/integration/test_registration_bootstrap_scope.py
@@ -0,0 +1,65 @@
+"""The deployment-wide AGENT_REGISTRATION_TOKEN must not grant admin authority.
+
+Before this fix, any holder of that one shared secret registered agents owned
+by the seeded admin user. Since room/resource authorization treats "owned by
+an admin" as "acts with admin authority" (`ProtocolService._resolve_acting_identity`),
+that made the token a privilege-escalation vector: a colleague given the
+deployment secret to bring up their own agent got an agent that could bypass
+`read_visibility`/`write_visibility` on every room and resource in the
+deployment, not just their own.
+
+This test registers an agent the same way a standalone agent does — presenting
+REGISTRATION_TOKEN to `register_agent_with_token` — and proves the resulting
+agent is owned by a dedicated, non-admin account instead.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.integration.conftest import REGISTRATION_TOKEN, Harness, SessionEnv
+
+pytestmark = [pytest.mark.integration, pytest.mark.asyncio(loop_scope="session")]
+
+
+async def test_bootstrap_token_registration_does_not_own_as_admin(
+ harness: Harness, session_env: SessionEnv
+) -> None:
+ result = await harness.register_agent_via_registration_token(
+ "colleague-agent", REGISTRATION_TOKEN
+ )
+
+ async with session_env.session_factory() as session: # type: ignore[operator]
+ agent = await harness.protocol.agent_store.get(session, result.agent_id)
+ assert agent is not None
+ assert agent.owner_id is not None
+ assert agent.owner_id != harness.owner_id, (
+ "agent registered through the deployment-wide bootstrap token "
+ "must not be owned by the admin user"
+ )
+
+ owner = await session_env.user_store.get(session, agent.owner_id)
+ assert owner is not None
+ assert owner.role != "admin", (
+ "agent registered through the deployment-wide bootstrap token "
+ "must not inherit admin authority"
+ )
+
+
+async def test_bootstrap_token_registration_is_repeatable_and_stable(
+ harness: Harness, session_env: SessionEnv
+) -> None:
+ """Two different colleagues sharing the same bootstrap token land on the
+ same non-admin owner, rather than each minting a new one."""
+ first = await harness.register_agent_via_registration_token(
+ "colleague-one", REGISTRATION_TOKEN
+ )
+ second = await harness.register_agent_via_registration_token(
+ "colleague-two", REGISTRATION_TOKEN
+ )
+
+ async with session_env.session_factory() as session: # type: ignore[operator]
+ agent_one = await harness.protocol.agent_store.get(session, first.agent_id)
+ agent_two = await harness.protocol.agent_store.get(session, second.agent_id)
+ assert agent_one is not None and agent_two is not None
+ assert agent_one.owner_id == agent_two.owner_id
diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
index 4425b156f..9715ccbd2 100644
--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -20,6 +20,7 @@ from switch_core.bridges.agent.protocol.types import (
from switch_core.db.models import Client, User
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
+from switch_core.db.stores.user_store import UserStore
PROFILE = IntegrationProfile(
connection_model="session_passive",
@@ -69,6 +70,7 @@ def make_service(
svc.session_factory = session_factory # type: ignore[attr-defined]
svc.agent_store = AgentStore() # type: ignore[attr-defined]
svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
+ svc.user_store = UserStore() # type: ignore[attr-defined]
svc.api_key_cache = ApiKeyCache(ttl_seconds=5.0, max_entries=8) # type: ignore[attr-defined]
svc.client_lifecycle = FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = NoBridges() # type: ignore[attr-defined]
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.py b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.py
new file mode 100644
index 000000000..fd27e40ea
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_with_token_bootstrap.py
@@ -0,0 +1,135 @@
+"""`register_agent_with_token` must not let a shared secret act as admin.
+
+Before this fix, the deployment-wide AGENT_REGISTRATION_TOKEN was seeded as a
+`"registration"`-type key owned by the admin user, so every agent registered
+through it inherited the admin's authority (`_resolve_acting_identity` reads
+the owner's `role` straight off the `User` row). A `"bootstrap"`-type key now
+resolves to a dedicated, non-admin owner instead — this proves it, and that
+a non-registration key (an agent's own) can no longer be replayed as one.
+"""
+
+from __future__ import annotations
+
+import hashlib
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_KEY_TYPE,
+ ensure_bootstrap_owner,
+)
+from switch_core.db.models import ApiKey, User
+from switch_core.db.stores.user_store import UserStore
+from tests.switch_core.bridges.agent.protocol.registration_harness import (
+ PROFILE,
+ make_service,
+)
+
+
+async def _make_admin(session_factory: async_sessionmaker[AsyncSession]) -> str:
+ async with session_factory() as session:
+ admin = User(name="Admin", email="admin@test", role="admin")
+ session.add(admin)
+ await session.commit()
+ return admin.id
+
+
+async def _make_key(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ user_id: str,
+ token: str,
+ key_type: str,
+) -> None:
+ async with session_factory() as session:
+ session.add(
+ ApiKey(
+ user_id=user_id,
+ key_hash=hashlib.sha256(token.encode()).hexdigest(),
+ encrypted_key="irrelevant",
+ label="test key",
+ type=key_type,
+ )
+ )
+ await session.commit()
+
+
+class TestBootstrapTokenRegistration:
+ async def test_bootstrap_token_owns_the_agent_as_the_bootstrap_account(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ admin_id = await _make_admin(session_factory)
+ async with session_factory() as session:
+ bootstrap_owner = await ensure_bootstrap_owner(session, UserStore())
+ await session.commit()
+ await _make_key(
+ session_factory,
+ user_id=admin_id,
+ token="shared-secret",
+ key_type=BOOTSTRAP_KEY_TYPE,
+ )
+
+ result = await svc.register_agent_with_token(
+ registration_token="shared-secret",
+ name="colleague-agent",
+ description="d",
+ connector_type="test",
+ integration_profile=PROFILE,
+ owner_only=False,
+ )
+
+ async with session_factory() as session:
+ agent = await svc.agent_store.get(session, result.agent_id)
+ assert agent is not None
+ assert agent.owner_id == bootstrap_owner.id
+ assert agent.owner_id != admin_id
+
+ async def test_a_plain_registration_key_still_owns_as_itself(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ async with session_factory() as session:
+ owner = User(name="owner", email="owner2@test", role="user")
+ session.add(owner)
+ await session.commit()
+ owner_id = owner.id
+ await _make_key(
+ session_factory, user_id=owner_id, token="personal", key_type="registration"
+ )
+
+ result = await svc.register_agent_with_token(
+ registration_token="personal",
+ name="personal-agent",
+ description="d",
+ connector_type="test",
+ integration_profile=PROFILE,
+ owner_only=False,
+ )
+
+ async with session_factory() as session:
+ agent = await svc.agent_store.get(session, result.agent_id)
+ assert agent is not None
+ assert agent.owner_id == owner_id
+
+ async def test_an_agent_key_cannot_be_replayed_as_a_registration_token(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ svc = make_service(session_factory)
+ admin_id = await _make_admin(session_factory)
+ await _make_key(
+ session_factory,
+ user_id=admin_id,
+ token="leaked-agent-key",
+ key_type="agent",
+ )
+
+ with pytest.raises(PermissionError):
+ await svc.register_agent_with_token(
+ registration_token="leaked-agent-key",
+ name="should-not-exist",
+ description="d",
+ connector_type="test",
+ integration_profile=PROFILE,
+ )
diff --git a/core/tests/switch_core/bridges/agent/test_bearer_auth_registration_pass_through.py b/core/tests/switch_core/bridges/agent/test_bearer_auth_registration_pass_through.py
new file mode 100644
index 000000000..e0793e7ad
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_bearer_auth_registration_pass_through.py
@@ -0,0 +1,112 @@
+"""BearerAuthMiddleware's registration-token pass-through gate.
+
+Both `"registration"` (personal, self-serve) and `"bootstrap"` (the
+deployment-wide AGENT_REGISTRATION_TOKEN) keys must reach the registration
+handlers on ordinary paths, and neither may reach `/mcp` — a registration
+token opens no MCP session, bootstrap included.
+"""
+
+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 ApiKey, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+async def _seed_key(
+ session_factory: async_sessionmaker[AsyncSession], token: str, key_type: str
+) -> None:
+ async with session_factory() as session:
+ user = User(name="u", email="u@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ session.add(
+ ApiKey(
+ user_id=user.id,
+ key_hash=_hash(token),
+ encrypted_key="enc",
+ label="k",
+ type=key_type,
+ )
+ )
+ await session.commit()
+
+
+def _middleware(session_factory: Any) -> tuple[BearerAuthMiddleware, dict]:
+ called: dict[str, Any] = {}
+
+ async def _app(scope: Any, receive: Any, send: Any) -> None:
+ called["scope"] = scope
+
+ 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, called
+
+
+async def _dispatch(mw: BearerAuthMiddleware, path: str, 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": path,
+ "headers": [(b"authorization", f"Bearer {token}".encode())],
+ }
+ await mw(scope, receive, send)
+ return sent
+
+
+class TestRegistrationPassThrough:
+ async def test_a_bootstrap_key_reaches_a_registration_path(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_key(session_factory, "tok", "bootstrap")
+ mw, called = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "/agents", "tok")
+
+ assert sent == []
+ assert called["scope"]["api_key"].type == "bootstrap"
+
+ async def test_a_bootstrap_key_is_rejected_on_mcp(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_key(session_factory, "tok", "bootstrap")
+ mw, called = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "/mcp", "tok")
+
+ assert "scope" not in called
+ assert sent[0]["status"] == 401
+
+ async def test_a_registration_key_reaches_a_registration_path(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_key(session_factory, "tok", "registration")
+ mw, called = _middleware(session_factory)
+
+ sent = await _dispatch(mw, "/agents", "tok")
+
+ assert sent == []
+ assert called["scope"]["api_key"].type == "registration"
diff --git a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
new file mode 100644
index 000000000..fdc2958c2
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_KEY_TYPE,
+ BOOTSTRAP_OWNER_EMAIL,
+ ensure_bootstrap_owner,
+ resolve_registration_owner_id,
+)
+from switch_core.db.models import ApiKey, User
+from switch_core.db.stores.user_store import UserStore
+
+
+async def _make_user(
+ session_factory: async_sessionmaker[AsyncSession], *, role: str
+) -> str:
+ async with session_factory() as session:
+ user = User(name=role, email=f"{role}@test", role=role, password_hash="x")
+ session.add(user)
+ await session.commit()
+ return user.id
+
+
+class TestEnsureBootstrapOwner:
+ async def test_creates_a_non_admin_user_once(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store = UserStore()
+ async with session_factory() as session:
+ owner = await ensure_bootstrap_owner(session, user_store)
+ await session.commit()
+ assert owner.email == BOOTSTRAP_OWNER_EMAIL
+ assert owner.role != "admin"
+
+ async with session_factory() as session:
+ again = await ensure_bootstrap_owner(session, user_store)
+ await session.commit()
+ assert again.id == owner.id
+
+
+class TestResolveRegistrationOwnerId:
+ async def test_registration_key_resolves_to_its_own_user(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store = UserStore()
+ user_id = await _make_user(session_factory, role="user")
+ key = ApiKey(
+ user_id=user_id,
+ key_hash="h",
+ encrypted_key="e",
+ label="mine",
+ type="registration",
+ )
+ async with session_factory() as session:
+ owner_id = await resolve_registration_owner_id(session, user_store, key)
+ assert owner_id == user_id
+
+ async def test_bootstrap_key_resolves_to_the_bootstrap_owner_not_its_user_id(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store = UserStore()
+ admin_id = await _make_user(session_factory, role="admin")
+ async with session_factory() as session:
+ bootstrap_owner = await ensure_bootstrap_owner(session, user_store)
+ await session.commit()
+
+ key = ApiKey(
+ user_id=admin_id,
+ key_hash="h",
+ encrypted_key="e",
+ label="deployment bootstrap",
+ type=BOOTSTRAP_KEY_TYPE,
+ )
+ async with session_factory() as session:
+ owner_id = await resolve_registration_owner_id(session, user_store, key)
+
+ assert owner_id == bootstrap_owner.id
+ assert owner_id != admin_id
+
+ async def test_bootstrap_key_without_a_seeded_owner_fails_loud(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store = UserStore()
+ admin_id = await _make_user(session_factory, role="admin")
+ key = ApiKey(
+ user_id=admin_id,
+ key_hash="h",
+ encrypted_key="e",
+ label="deployment bootstrap",
+ type=BOOTSTRAP_KEY_TYPE,
+ )
+ async with session_factory() as session:
+ with pytest.raises(RuntimeError):
+ await resolve_registration_owner_id(session, user_store, key)
diff --git a/core/tests/switch_core/test_main.py b/core/tests/switch_core/test_main.py
new file mode 100644
index 000000000..d5f7c1aca
--- /dev/null
+++ b/core/tests/switch_core/test_main.py
@@ -0,0 +1,189 @@
+"""Seeding the deployment-wide agent-registration bootstrap key.
+
+See `bridges/agent/test_registration_bootstrap.py` for what the key resolves
+to; this covers the seeding lifecycle itself: fresh install, in-place
+rotation, and that a deliberate revocation (deleting the key from the
+gateway's API Keys page) survives a restart instead of being silently
+recreated.
+"""
+
+from __future__ import annotations
+
+import hashlib
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_KEY_LABEL,
+ BOOTSTRAP_KEY_TYPE,
+ LEGACY_BOOTSTRAP_KEY_LABEL,
+)
+from switch_core.config import SwitchConfig
+from switch_core.db.models import ApiKey, User
+from switch_core.db.stores.api_key_store import ApiKeyStore
+from switch_core.db.stores.user_store import UserStore
+from switch_core.main import (
+ _BOOTSTRAP_SEEDED_FLAG,
+ _seed_agent_registration_bootstrap_key,
+)
+
+ADMIN_EMAIL = "[email protected]"
+
+
+def _config(token: str) -> SwitchConfig:
+ return SwitchConfig(
+ db_host="unused",
+ db_port="5432",
+ db_user="unused",
+ db_password="unused",
+ db_name="unused",
+ matrix_server_name="test",
+ agent_registration_token=token,
+ jwt_secret_key="test-jwt-secret",
+ gateway_admin_email=ADMIN_EMAIL,
+ gateway_admin_password="unused",
+ )
+
+
+async def _make_admin(session_factory: async_sessionmaker[AsyncSession]) -> str:
+ async with session_factory() as session:
+ admin = User(name="Admin", email=ADMIN_EMAIL, role="admin")
+ session.add(admin)
+ await session.commit()
+ return admin.id
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+class TestSeedAgentRegistrationBootstrapKey:
+ async def test_fresh_install_seeds_one_bootstrap_key_owned_by_admin(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+ config = _config("dev-test-token")
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ admin = await user_store.get(session, admin_id)
+
+ bootstrap_keys = [k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]
+ assert len(bootstrap_keys) == 1
+ assert bootstrap_keys[0].key_hash == _hash("dev-test-token")
+ assert bootstrap_keys[0].label == BOOTSTRAP_KEY_LABEL
+ assert admin is not None
+ assert (admin.metadata_ or {}).get(_BOOTSTRAP_SEEDED_FLAG) is True
+
+ async def test_rerunning_with_the_same_token_is_a_no_op(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+ config = _config("dev-test-token")
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ assert len([k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]) == 1
+
+ async def test_migrates_a_legacy_admin_owned_registration_key_in_place(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+ config = _config("dev-test-token")
+
+ async with session_factory() as session:
+ legacy = ApiKey(
+ user_id=admin_id,
+ key_hash=_hash("dev-test-token"),
+ encrypted_key="irrelevant",
+ label=LEGACY_BOOTSTRAP_KEY_LABEL,
+ type="registration",
+ )
+ session.add(legacy)
+ await session.commit()
+ legacy_id = legacy.id
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ bootstrap_keys = [k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]
+ assert len(bootstrap_keys) == 1
+ assert bootstrap_keys[0].id == legacy_id
+ assert bootstrap_keys[0].label == BOOTSTRAP_KEY_LABEL
+ assert not any(k.type == "registration" for k in keys)
+
+ async def test_rotating_the_token_updates_the_existing_key_in_place(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, _config("old-token")
+ )
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, _config("new-token")
+ )
+
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ bootstrap_keys = [k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]
+ assert len(bootstrap_keys) == 1
+ assert bootstrap_keys[0].key_hash == _hash("new-token")
+
+ async def test_revoking_the_key_survives_a_restart_with_the_same_token(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Deleting the seeded key (as an operator would from the gateway's
+ API Keys page) must be a durable revocation: restarting the server
+ with the same, unchanged AGENT_REGISTRATION_TOKEN must not bring it
+ back — the old failure this guards against is exactly that."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+ config = _config("dev-test-token")
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ (bootstrap_key,) = [k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]
+ await api_key_store.delete(session, bootstrap_key.id)
+ await session.commit()
+
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
+
+ async with session_factory() as session:
+ keys = await api_key_store.get_by_user(session, admin_id)
+ assert not any(k.type == BOOTSTRAP_KEY_TYPE for k in keys)
+
+ async def test_missing_admin_user_fails_loud(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ config = _config("dev-test-token")
+
+ with pytest.raises(RuntimeError):
+ await _seed_agent_registration_bootstrap_key(
+ session_factory, user_store, api_key_store, config
+ )
diff --git a/docs/old/ARCHITECTURE.md b/docs/old/ARCHITECTURE.md
index 3ef6ae348..8da165b3f 100644
--- a/docs/old/ARCHITECTURE.md
+++ b/docs/old/ARCHITECTURE.md
@@ -124,7 +124,12 @@ The relational schema is defined in
presentation only and falls back to `name`. An agent inherits exactly its
owner's permissions. **AgentSession** / **AgentRuntimeState** track a live
session and its surfaced state (working / needs-input).
-- **ApiKey** — a hashed credential, of type `"agent"` or `"registration"`.
+- **ApiKey** — a hashed credential, of type `"agent"`, `"registration"`
+ (minted by, and owned by, a single user), or `"bootstrap"` (the
+ deployment-wide key seeded from `AGENT_REGISTRATION_TOKEN`; agents it
+ registers are owned by a dedicated non-admin account rather than the admin
+ it is filed under — see
+ [`bridges/agent/registration_bootstrap.py`](../core/switch_core/bridges/agent/registration_bootstrap.py)).
- **Client** / **ClientRoom** — the Matrix client backing each participant and
its room memberships.
- **Room** — a Matrix room plus Switch metadata (channel type, bridge link,
@@ -156,7 +161,8 @@ The relational schema is defined in
### 4.1 Agent registration & connection
1. An agent calls `POST /agents` with a **registration token** (an `ApiKey` of
- type `"registration"`) and receives its own `{id, api_key}`
+ type `"registration"` or `"bootstrap"`) and receives its own `{id,
+ api_key}`
([`bridges/agent/api/handlers.py`](../core/switch_core/bridges/agent/api/handlers.py)).
Known-agent types (e.g. `claude-code`) register via `POST /agents/register-known`.
2. All later calls present the agent API key as a `Bearer` token. The
diff --git a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
index 0cc4c26a1..8d5bc07c2 100644
--- a/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
+++ b/gateway/src/pages/registration-keys/RegistrationKeysPage.tsx
@@ -67,7 +67,10 @@ export default function RegistrationKeysPage() {
}, []);
const registrationKeys = useMemo(
- () => keys?.filter((k) => k.type === "registration") ?? [],
+ // Everything that isn't an agent's own key is a way to register more
+ // agents — a personal "registration" key or the deployment-wide
+ // "bootstrap" key seeded from AGENT_REGISTRATION_TOKEN.
+ () => keys?.filter((k) => k.type !== "agent") ?? [],
[keys],
);