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(agent): make bootstrap-key seeding resilient to admin changes and reserve the bootstrap owner's identity
Wojciech Wojtyniakc533e00f5acc
diff --git a/core/switch_core/bridges/agent/registration_bootstrap.py b/core/switch_core/bridges/agent/registration_bootstrap.pyindex 27283d73b..50babe65e 100644--- a/core/switch_core/bridges/agent/registration_bootstrap.py+++ b/core/switch_core/bridges/agent/registration_bootstrap.py@@ -13,6 +13,13 @@ to a dedicated, non-admin account (see :data:`BOOTSTRAP_OWNER_EMAIL`) insteadof the seeded admin. Otherwise every holder of that one shared secret wouldregister agents that inherit the admin's authority over every room andresource in the deployment, not just their own.++That guarantee only holds if the account at :data:`BOOTSTRAP_OWNER_EMAIL` is+never an admin. Nothing in this codebase reserves that address — a gateway+admin can `POST /users` with it and an admin role, and an OIDC identity+provider can assert it as someone's login email — so both entry points here+verify the resolved account's role and refuse rather than silently adopting+an admin."""from __future__ import annotations@@ -38,16 +45,42 @@ 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.+# had its own owner and its own ApiKey type. Startup seeding uses this,+# together with a hash match against the configured token, 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)"+# Persisted on the bootstrap owner's own metadata (never on the admin's): the+# admin a deployment resolves to is a mutable config value (`GATEWAY_ADMIN_EMAIL`),+# so a marker filed there stops meaning what it says the moment that value+# changes. The bootstrap owner's email is a fixed constant, so this survives+# an admin-email change intact. It records the hash of the token last seeded+# rather than a bare boolean so a revoked key stays revoked only for the+# value it was revoked at: rotating AGENT_REGISTRATION_TOKEN to a new value+# re-establishes bootstrap registration without touching the database by+# hand, while restarting with the same, already-revoked value does not.+BOOTSTRAP_LAST_SEEDED_HASH_META_KEY = "agent_bootstrap_key_last_hash"+++def _raise_if_admin(owner: User) -> None:+ if owner.role == "admin":+ raise RuntimeError(+ f"{BOOTSTRAP_OWNER_EMAIL} is reserved for agent-registration "+ "bootstrap and must never be an admin, but the account at that "+ "address currently has the admin role. Demote or remove it "+ "before agent-registration bootstrap can run."+ )+async def ensure_bootstrap_owner(session: AsyncSession, user_store: UserStore) -> User:- """Idempotently create the account bootstrap-registered agents are owned by."""+ """Idempotently create the account bootstrap-registered agents are owned by.++ Raises if an account already exists at that address with the admin role.+ """owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)if owner is not None:+ _raise_if_admin(owner)return ownerowner = User(name=BOOTSTRAP_OWNER_NAME, email=BOOTSTRAP_OWNER_EMAIL, role="user")await user_store.create(session, owner)@@ -60,6 +93,9 @@ async def resolve_registration_owner_id("""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``.+ Raises if a bootstrap key resolves to an account that has since been+ promoted to admin — ``ensure_bootstrap_owner`` only runs at startup, so+ this is the check that catches a later promotion."""if key.type != BOOTSTRAP_KEY_TYPE:return key.user_id@@ -69,4 +105,5 @@ async def resolve_registration_owner_id(f"Agent-registration bootstrap owner ({BOOTSTRAP_OWNER_EMAIL}) is ""missing; restart the server to reseed it.")+ _raise_if_admin(owner)return owner.iddiff --git a/core/switch_core/db/stores/api_key_store.py b/core/switch_core/db/stores/api_key_store.pyindex c24357bac..649ad9c21 100644--- a/core/switch_core/db/stores/api_key_store.py+++ b/core/switch_core/db/stores/api_key_store.py@@ -50,6 +50,16 @@ class ApiKeyStore:)return list(result.scalars().all())+ async def get_by_type(self, session: AsyncSession, key_type: str) -> list[ApiKey]:+ """Every key of a given type, regardless of which user owns it.++ Used where a type is meant to be a deployment-wide singleton (the+ agent-registration bootstrap key) and existence must not depend on+ which user currently holds it.+ """+ result = await session.execute(select(ApiKey).where(ApiKey.type == key_type))+ return list(result.scalars().all())+async def delete(self, session: AsyncSession, key_id: str) -> None:key = await session.get(ApiKey, key_id)if key:diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 777fecd54..e06e89618 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -25,6 +25,7 @@ from switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.registration_bootstrap import (BOOTSTRAP_KEY_LABEL,BOOTSTRAP_KEY_TYPE,+ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY,LEGACY_BOOTSTRAP_KEY_LABEL,ensure_bootstrap_owner,)@@ -217,7 +218,7 @@ async def run() -> None:# ── Seed admin user + agent-registration bootstrap key ──────────────────await _seed_admin_user(session_factory, user_store, config)await _seed_agent_registration_bootstrap_key(- session_factory, user_store, api_key_store, config+ session_factory, user_store, api_key_store, agent_store, config)# ── Event queue + request trackers ───────────────────────────────────────@@ -493,21 +494,11 @@ async def _seed_admin_user(logger.info("Seeded admin user: %s", config.gateway_admin_email)-# 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,+ agent_store: AgentStore,config: SwitchConfig,) -> None:"""Seed the deployment-wide agent-registration bootstrap key.@@ -520,6 +511,14 @@ async def _seed_agent_registration_bootstrap_key(row is filed under — the row lives on the admin so it is listed andrevocable from the admin's own API Keys page, but holding the tokenitself confers no admin authority.++ Existence and rotation are resolved by the key's own hash and type+ globally, never by which user the configured admin email currently+ resolves to: an admin row is looked up here only to own a freshly+ created key, and can be swapped out (``GATEWAY_ADMIN_EMAIL`` changed to a+ different account) without this re-inserting a duplicate of a key that+ already exists under the old one, which would collide on the unique+ ``key_hash`` and fail the whole boot."""async with session_factory() as session: # type: ignore[operator]admin = await user_store.get_by_email(session, config.gateway_admin_email)@@ -528,7 +527,22 @@ async def _seed_agent_registration_bootstrap_key("Cannot seed agent-registration bootstrap key: admin user "f"{config.gateway_admin_email} not found")- await ensure_bootstrap_owner(session, user_store)+ bootstrap_owner = await ensure_bootstrap_owner(session, user_store)++ admin_owned_agents = [+ a for a in await agent_store.get_all(session) if a.owner_id == admin.id+ ]+ if admin_owned_agents:+ logger.warning(+ "%d agent(s) are owned by the admin user (%s) and carry "+ "admin-equivalent authority over every room and resource in "+ "this deployment, not just their own: %s. If any were "+ "registered through AGENT_REGISTRATION_TOKEN, reassign or "+ "re-register them under a non-admin owner.",+ len(admin_owned_agents),+ config.gateway_admin_email,+ ", ".join(a.name for a in admin_owned_agents),+ )token_hash = hashlib.sha256(config.agent_registration_token.encode()@@ -537,38 +551,27 @@ async def _seed_agent_registration_bootstrap_key(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- ),- None,- )- bootstrap_key = next(- (k for k in admin_keys if k.type == BOOTSTRAP_KEY_TYPE), None+ bootstrap_keys = await api_key_store.get_by_type(session, BOOTSTRAP_KEY_TYPE)+ bootstrap_key = bootstrap_keys[0] if bootstrap_keys else None++ if bootstrap_key is None:+ legacy_candidate = await api_key_store.get_by_hash(session, token_hash)+ if (+ legacy_candidate is not None+ and legacy_candidate.type == "registration"+ and legacy_candidate.label == LEGACY_BOOTSTRAP_KEY_LABEL+ ):+ legacy_candidate.type = BOOTSTRAP_KEY_TYPE+ legacy_candidate.label = BOOTSTRAP_KEY_LABEL+ bootstrap_key = legacy_candidate+ logger.info(+ "Migrated the legacy admin-owned registration key to a "+ "scoped agent-registration bootstrap key"+ )++ last_seeded_hash = (bootstrap_owner.metadata_ or {}).get(+ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY)- # Whether the flag is *already durably recorded* — read-only, used to- # decide whether a missing key means "revoked" vs. "never seeded".- # Deliberately not reused as a "did something get provisioned this- # call" flag: that conflated the migration branch (which provisions a- # key without having recorded the flag yet) with a true revocation,- # so the flag write below was skipped on the exact call that migrates- # a legacy key, leaving a revocation made shortly after unable to- # stick past the next restart.- flag_already_set = 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- 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:@@ -578,11 +581,13 @@ async def _seed_agent_registration_bootstrap_key("Rotated the agent-registration bootstrap key from ""AGENT_REGISTRATION_TOKEN")- elif flag_already_set:+ elif last_seeded_hash == token_hash: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."+ "reseeding it from AGENT_REGISTRATION_TOKEN. Rotate the "+ "token to a new value to re-enable deployment-wide bootstrap "+ "registration, or mint per-user registration keys from the "+ "gateway's API Keys page instead.")else:bootstrap_key = ApiKey(@@ -598,10 +603,10 @@ async def _seed_agent_registration_bootstrap_key("AGENT_REGISTRATION_TOKEN")- if bootstrap_key is not None and not flag_already_set:- meta = dict(admin.metadata_ or {})- meta[_BOOTSTRAP_SEEDED_FLAG] = True- admin.metadata_ = meta+ if bootstrap_key is not None and last_seeded_hash != token_hash:+ meta = dict(bootstrap_owner.metadata_ or {})+ meta[BOOTSTRAP_LAST_SEEDED_HASH_META_KEY] = token_hash+ bootstrap_owner.metadata_ = metaawait session.commit()diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex a777f41c4..9b985cecc 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -398,7 +398,11 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:# 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+ session_factory,+ session_env.user_store,+ session_env.api_key_store,+ session_env.agent_store,+ config,)# Per-test in-memory wiring: a fresh EventBuffer / client registry so queueddiff --git a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.pyindex fdc2958c2..d663dd993 100644--- a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py+++ b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py@@ -39,6 +39,24 @@ class TestEnsureBootstrapOwner:await session.commit()assert again.id == owner.id+ async def test_refuses_an_existing_account_with_the_admin_role(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Nothing reserves this address: a gateway admin can `POST /users`+ with it and an admin role, or an OIDC provider can hand it to any+ identity that asserts it. Adopting that account would silently+ restore the exact escalation this module exists to close."""+ user_store = UserStore()+ async with session_factory() as session:+ session.add(+ User(name="squatter", email=BOOTSTRAP_OWNER_EMAIL, role="admin")+ )+ await session.commit()++ async with session_factory() as session:+ with pytest.raises(RuntimeError, match="admin"):+ await ensure_bootstrap_owner(session, user_store)+class TestResolveRegistrationOwnerId:async def test_registration_key_resolves_to_its_own_user(@@ -94,3 +112,33 @@ class TestResolveRegistrationOwnerId:async with session_factory() as session:with pytest.raises(RuntimeError):await resolve_registration_owner_id(session, user_store, key)++ async def test_bootstrap_owner_promoted_to_admin_after_startup_fails_loud(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`ensure_bootstrap_owner` only runs once at startup, so a later+ promotion of the bootstrap owner to admin (e.g. by a gateway admin+ editing the account, or an OIDC identity being linked to it after+ #397) must still be caught here, at registration time."""+ 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()++ async with session_factory() as session:+ promoted = await session.get(User, bootstrap_owner.id)+ assert promoted is not None+ promoted.role = "admin"+ 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:+ with pytest.raises(RuntimeError, match="admin"):+ 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.pyindex 84cb23225..b445c3714 100644--- a/core/tests/switch_core/test_main.py+++ b/core/tests/switch_core/test_main.py@@ -2,9 +2,9 @@See `bridges/agent/test_registration_bootstrap.py` for what the key resolvesto; 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.+rotation, legacy migration, and that a deliberate revocation (deleting the+key from the gateway's API Keys page) survives a restart instead of being+silently recreated — including when the admin email changes underneath it."""from __future__ import annotations@@ -17,21 +17,20 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.registration_bootstrap import (BOOTSTRAP_KEY_LABEL,BOOTSTRAP_KEY_TYPE,+ BOOTSTRAP_OWNER_EMAIL,LEGACY_BOOTSTRAP_KEY_LABEL,)from switch_core.config import SwitchConfig-from switch_core.db.models import ApiKey, User+from switch_core.db.models import Agent, ApiKey, Client, User+from switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.main import (- _BOOTSTRAP_SEEDED_FLAG,- _seed_agent_registration_bootstrap_key,-)+from switch_core.main import _seed_agent_registration_bootstrap_keyADMIN_EMAIL = "[email protected]"-def _config(token: str) -> SwitchConfig:+def _config(token: str, *, admin_email: str = ADMIN_EMAIL) -> SwitchConfig:return SwitchConfig(db_host="unused",db_port="5432",@@ -41,17 +40,65 @@ def _config(token: str) -> SwitchConfig:matrix_server_name="test",agent_registration_token=token,jwt_secret_key="test-jwt-secret",- gateway_admin_email=ADMIN_EMAIL,+ gateway_admin_email=admin_email,gateway_admin_password="unused",)+async def _make_user(+ session_factory: async_sessionmaker[AsyncSession], *, email: str, role: str+) -> str:+ async with session_factory() as session:+ user = User(name=role, email=email, role=role)+ session.add(user)+ await session.commit()+ return user.id++async def _make_admin(session_factory: async_sessionmaker[AsyncSession]) -> str:+ return await _make_user(session_factory, email=ADMIN_EMAIL, role="admin")+++async def _make_agent_owned_by(+ session_factory: async_sessionmaker[AsyncSession], *, owner_id: str, name: str+) -> None:async with session_factory() as session:- admin = User(name="Admin", email=ADMIN_EMAIL, role="admin")- session.add(admin)+ client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ session.add(client)+ await session.flush()+ key = ApiKey(+ user_id=owner_id,+ key_hash=_hash(f"agent-key-{name}"),+ encrypted_key="irrelevant",+ label=name,+ type="agent",+ )+ session.add(key)+ await session.flush()+ session.add(+ Agent(+ name=name,+ description="d",+ agent_type="session_addressable",+ connector_type="claude_code",+ integration_profile={},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=owner_id,+ )+ )await session.commit()- return admin.id+++async def _seed(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ api_key_store: ApiKeyStore,+ config: SwitchConfig,+) -> None:+ await _seed_agent_registration_bootstrap_key(+ session_factory, user_store, api_key_store, AgentStore(), config+ )def _hash(token: str) -> str:@@ -66,20 +113,15 @@ class TestSeedAgentRegistrationBootstrapKey: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(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) == 1assert 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 Trueasync def test_rerunning_with_the_same_token_is_a_no_op(self, session_factory: async_sessionmaker[AsyncSession]@@ -88,12 +130,8 @@ class TestSeedAgentRegistrationBootstrapKey: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- )+ await _seed(session_factory, user_store, api_key_store, config)+ await _seed(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)@@ -118,9 +156,7 @@ class TestSeedAgentRegistrationBootstrapKey:await session.commit()legacy_id = legacy.id- await _seed_agent_registration_bootstrap_key(- session_factory, user_store, api_key_store, config- )+ await _seed(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)@@ -130,13 +166,43 @@ class TestSeedAgentRegistrationBootstrapKey:assert bootstrap_keys[0].label == BOOTSTRAP_KEY_LABELassert not any(k.type == "registration" for k in keys)+ async def test_a_personal_key_sharing_the_legacy_label_but_not_the_hash_is_untouched(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A label is free text an admin could reuse by coincidence; only a+ matching hash proves a row really is the historical bootstrap key."""+ 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:+ personal = ApiKey(+ user_id=admin_id,+ key_hash=_hash("some-unrelated-personal-secret"),+ encrypted_key="irrelevant",+ label=LEGACY_BOOTSTRAP_KEY_LABEL,+ type="registration",+ )+ session.add(personal)+ await session.commit()+ personal_id = personal.id++ await _seed(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)+ by_id = {k.id: k for k in keys}+ assert by_id[personal_id].type == "registration"+ assert by_id[personal_id].key_hash == _hash("some-unrelated-personal-secret")+ assert len([k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]) == 1+async def test_revoking_a_migrated_legacy_key_survives_a_restart(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- """The durable-seeded flag must be recorded on the very call that- migrates a legacy key, not only on a later, unrelated call — an- operator can revoke (delete) the freshly migrated key immediately,- with no intervening restart to have backfilled the flag."""+ """The durable marker must be recorded on the very call that migrates+ a legacy key, not only on a later, unrelated call — an operator can+ revoke (delete) the freshly migrated key immediately, with no+ intervening restart to have backfilled it."""user_store, api_key_store = UserStore(), ApiKeyStore()admin_id = await _make_admin(session_factory)config = _config("dev-test-token")@@ -152,9 +218,7 @@ class TestSeedAgentRegistrationBootstrapKey:session.add(legacy)await session.commit()- await _seed_agent_registration_bootstrap_key(- session_factory, user_store, api_key_store, config- )+ await _seed(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)@@ -162,9 +226,7 @@ class TestSeedAgentRegistrationBootstrapKey: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- )+ await _seed(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)@@ -176,12 +238,8 @@ class TestSeedAgentRegistrationBootstrapKey: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")- )+ await _seed(session_factory, user_store, api_key_store, _config("old-token"))+ await _seed(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)@@ -200,23 +258,49 @@ class TestSeedAgentRegistrationBootstrapKey: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(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- )+ await _seed(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_rotating_to_a_new_value_after_revocation_re_enables_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A revoked key stays revoked only for the value it was revoked at.+ An operator with no database access can re-enable deployment-wide+ bootstrap registration by rotating to a new secret."""+ user_store, api_key_store = UserStore(), ApiKeyStore()+ admin_id = await _make_admin(session_factory)++ await _seed(session_factory, user_store, api_key_store, _config("old-token"))+ 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()++ # Same value: stays revoked.+ await _seed(session_factory, user_store, api_key_store, _config("old-token"))+ 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)++ # New value: re-enabled.+ await _seed(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_missing_admin_user_fails_loud(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -224,6 +308,89 @@ class TestSeedAgentRegistrationBootstrapKey:config = _config("dev-test-token")with pytest.raises(RuntimeError):- await _seed_agent_registration_bootstrap_key(- session_factory, user_store, api_key_store, config+ await _seed(session_factory, user_store, api_key_store, config)++ async def test_bootstrap_owner_promoted_to_admin_blocks_seeding(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Adversarial: something (a gateway admin via POST /users, or an+ OIDC identity provider on an upgrading deployment) has already+ claimed the bootstrap owner's reserved address with the admin role.+ Seeding must refuse rather than adopt it — that account would confer+ admin authority on every agent registered through the shared token,+ exactly the escalation this fix closes."""+ user_store, api_key_store = UserStore(), ApiKeyStore()+ await _make_admin(session_factory)+ await _make_user(session_factory, email=BOOTSTRAP_OWNER_EMAIL, role="admin")+ config = _config("dev-test-token")++ with pytest.raises(RuntimeError, match="admin"):+ await _seed(session_factory, user_store, api_key_store, config)++ async def test_admin_owned_agents_are_logged_as_a_warning(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ user_store, api_key_store = UserStore(), ApiKeyStore()+ admin_id = await _make_admin(session_factory)+ await _make_agent_owned_by(+ session_factory, owner_id=admin_id, name="admin-owned-agent"+ )+ config = _config("dev-test-token")++ with caplog.at_level("WARNING", logger="switch_core.main"):+ await _seed(session_factory, user_store, api_key_store, config)++ warnings = [r.message for r in caplog.records if r.levelname == "WARNING"]+ assert any("admin-owned-agent" in w for w in warnings)++ async def test_changing_the_admin_email_does_not_crash_or_duplicate_the_key(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The seed check must not be scoped to whichever user the currently+ configured admin email resolves to: an admin-email change must not+ cause a duplicate insert of a key that already exists (and collides+ on the unique key_hash) under the previous admin."""+ user_store, api_key_store = UserStore(), ApiKeyStore()+ await _make_admin(session_factory)+ config = _config("dev-test-token")+ await _seed(session_factory, user_store, api_key_store, config)++ new_admin_email = "[email protected]"+ await _make_user(session_factory, email=new_admin_email, role="admin")+ new_config = _config("dev-test-token", admin_email=new_admin_email)++ # Must not raise (would previously fail the unique constraint on+ # api_keys.key_hash by trying to insert a second row for the same+ # token under the new admin).+ await _seed(session_factory, user_store, api_key_store, new_config)++ async with session_factory() as session:+ all_keys_by_hash = await api_key_store.get_by_hash(+ session, _hash("dev-test-token"))+ assert all_keys_by_hash is not None++ async def test_changing_the_admin_email_after_revocation_does_not_resurrect_it(+ 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(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()++ new_admin_email = "[email protected]"+ await _make_user(session_factory, email=new_admin_email, role="admin")+ new_config = _config("dev-test-token", admin_email=new_admin_email)+ await _seed(session_factory, user_store, api_key_store, new_config)++ async with session_factory() as session:+ found = await api_key_store.get_by_hash(session, _hash("dev-test-token"))+ assert found is None