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): close a live-key orphan on rotated-before-upgrade legacy keys and other bootstrap-seeding gaps

Wojciech Wojtyniakacbd2bd593a8
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index a05bb1f17..19cd9dae9 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -151,7 +151,10 @@ async def _resolve_registration_user_id(
key = await api_key_store.get_by_hash(session, token_hash)
if key is None or key.type not in REGISTRATION_KEY_TYPES:
raise HTTPException(status_code=401, detail="Invalid registration token")
- return await resolve_registration_owner_id(session, protocol.user_store, key)
+ try:
+ return await resolve_registration_owner_id(session, protocol.user_store, key)
+ except RuntimeError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
# Registration endpoints
diff --git a/core/switch_core/bridges/agent/registration_bootstrap.py b/core/switch_core/bridges/agent/registration_bootstrap.py
index 50babe65e..2135ce81d 100644
--- a/core/switch_core/bridges/agent/registration_bootstrap.py
+++ b/core/switch_core/bridges/agent/registration_bootstrap.py
@@ -15,11 +15,15 @@ register agents that inherit the admin's authority over every room and
resource 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.
+the one this module itself provisioned. Nothing in this codebase reserves
+that address, and an admin role is not the only way to end up controlling
+it: a gateway admin can `POST /users` with that email and an admin role, but
+an OIDC identity provider can also claim it outright by asserting it as a
+login email — JIT provisioning always creates a `role="user"` account, so an
+account's mere existence there proves nothing about who put it there. Both
+entry points here refuse to adopt an existing account at that address unless
+it carries the marker only this module's own creation path sets, and refuse
+an admin role on top of that as a second, independent check.
"""
from __future__ import annotations
@@ -42,6 +46,13 @@ REGISTRATION_KEY_TYPES = ("registration", BOOTSTRAP_KEY_TYPE)
BOOTSTRAP_OWNER_EMAIL = "[email protected]"
BOOTSTRAP_OWNER_NAME = "Agent Bootstrap"
+# Stamped into the bootstrap owner's metadata only at the moment this module
+# creates it. An account found at BOOTSTRAP_OWNER_EMAIL without this marker
+# was put there by something else — a gateway admin, an OIDC login claiming
+# the address before this ever ran — and must not be adopted regardless of
+# its role.
+BOOTSTRAP_OWNER_MARKER_META_KEY = "agent_bootstrap_owner"
+
BOOTSTRAP_KEY_LABEL = "Deployment bootstrap (from AGENT_REGISTRATION_TOKEN)"
# Label of the key this replaces, from before agent-registration bootstrap
@@ -51,38 +62,61 @@ BOOTSTRAP_KEY_LABEL = "Deployment bootstrap (from AGENT_REGISTRATION_TOKEN)"
# 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.
+# Both 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 these survive an admin-email change intact.
+#
+# `..._LAST_HASH...` is the hash of the bootstrap key as of the last seed
+# call, used only to notice that a key present last time is now gone (i.e. it
+# was just revoked) so its hash can be recorded below.
+#
+# `..._REVOKED_HASHES...` is every hash ever revoked this way. A hash on this
+# list is refused forever, even if the currently active key or the
+# configured token later returns to it — recording only the single
+# most-recently-revoked value would let one rotation forward and one back
+# silently reinstate a value the operator deliberately killed.
BOOTSTRAP_LAST_SEEDED_HASH_META_KEY = "agent_bootstrap_key_last_hash"
+BOOTSTRAP_REVOKED_HASHES_META_KEY = "agent_bootstrap_revoked_hashes"
-def _raise_if_admin(owner: User) -> None:
+def _raise_unless_genuine(owner: User) -> None:
+ if not (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY):
+ raise RuntimeError(
+ f"An account already exists at {BOOTSTRAP_OWNER_EMAIL} but was "
+ "not created by agent-registration bootstrap seeding, so it "
+ "cannot be trusted to carry no admin authority now or later. "
+ "There is no gateway endpoint that removes or renames a user: "
+ "this needs a direct edit to the users table before "
+ "agent-registration bootstrap can run."
+ )
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."
+ "address currently has the admin role. There is no gateway "
+ "endpoint that changes a user's role: this needs a direct edit "
+ "to the users table 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.
- Raises if an account already exists at that address with the admin role.
+ Raises if an account already exists at that address that this function
+ did not itself create, or that has since been given the admin role.
"""
owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)
if owner is not None:
- _raise_if_admin(owner)
+ _raise_unless_genuine(owner)
return owner
- owner = User(name=BOOTSTRAP_OWNER_NAME, email=BOOTSTRAP_OWNER_EMAIL, role="user")
+ owner = User(
+ name=BOOTSTRAP_OWNER_NAME,
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="user",
+ metadata_={BOOTSTRAP_OWNER_MARKER_META_KEY: True},
+ )
await user_store.create(session, owner)
return owner
@@ -93,9 +127,10 @@ 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.
+ Raises if a bootstrap key resolves to an account this module did not
+ provision, or one that has since been given the admin role —
+ ``ensure_bootstrap_owner`` only runs at startup, so this is the check
+ that catches either happening afterward.
"""
if key.type != BOOTSTRAP_KEY_TYPE:
return key.user_id
@@ -105,5 +140,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)
+ _raise_unless_genuine(owner)
return owner.id
diff --git a/core/switch_core/db/stores/api_key_store.py b/core/switch_core/db/stores/api_key_store.py
index 649ad9c21..8f59d7849 100644
--- a/core/switch_core/db/stores/api_key_store.py
+++ b/core/switch_core/db/stores/api_key_store.py
@@ -60,6 +60,17 @@ class ApiKeyStore:
result = await session.execute(select(ApiKey).where(ApiKey.type == key_type))
return list(result.scalars().all())
+ async def get_by_label(self, session: AsyncSession, label: str) -> list[ApiKey]:
+ """Every key carrying a given label, regardless of type or owner.
+
+ Labels are free text, so this is a discovery aid, not an identity
+ lookup — a caller matching against a known auto-generated label
+ (never one a user is expected to type) still has to check the type
+ and, ideally, the hash, before treating a match as authoritative.
+ """
+ result = await session.execute(select(ApiKey).where(ApiKey.label == label))
+ 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.py
index e06e89618..d96fc6a8a 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -26,6 +26,7 @@ from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_KEY_LABEL,
BOOTSTRAP_KEY_TYPE,
BOOTSTRAP_LAST_SEEDED_HASH_META_KEY,
+ BOOTSTRAP_REVOKED_HASHES_META_KEY,
LEGACY_BOOTSTRAP_KEY_LABEL,
ensure_bootstrap_owner,
)
@@ -552,40 +553,98 @@ async def _seed_agent_registration_bootstrap_key(
)
bootstrap_keys = await api_key_store.get_by_type(session, BOOTSTRAP_KEY_TYPE)
+ if len(bootstrap_keys) > 1:
+ raise RuntimeError(
+ f"Found {len(bootstrap_keys)} agent-registration bootstrap "
+ "keys; expected at most one. This needs a direct database fix."
+ )
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"
- )
+ # Every row carrying the legacy label, not just one matching the
+ # current token: an admin who rotated AGENT_REGISTRATION_TOKEN at or
+ # before this upgrade leaves the old row's hash stale, so a hash-only
+ # lookup for the current token would miss it — and a `type:
+ # "registration"` row at that label is otherwise indistinguishable
+ # from a live credential that still authenticates as the admin.
+ legacy_rows = [
+ row
+ for row in await api_key_store.get_by_label(
+ session, LEGACY_BOOTSTRAP_KEY_LABEL
+ )
+ if row.type == "registration"
+ ]
+ matching_legacy = next(
+ (row for row in legacy_rows if row.key_hash == token_hash), None
+ )
+ if bootstrap_key is None and matching_legacy is not None:
+ matching_legacy.type = BOOTSTRAP_KEY_TYPE
+ matching_legacy.label = BOOTSTRAP_KEY_LABEL
+ matching_legacy.encrypted_key = encrypted_key
+ bootstrap_key = matching_legacy
+ logger.info(
+ "Migrated the legacy admin-owned registration key to a "
+ "scoped agent-registration bootstrap key"
+ )
+ for stale in legacy_rows:
+ if stale is matching_legacy:
+ continue
+ logger.warning(
+ "Removing a stale admin-owned registration key (id %s, "
+ "label %r): its value no longer matches "
+ "AGENT_REGISTRATION_TOKEN, so it predates a token rotation "
+ "and would otherwise keep registering agents with admin "
+ "authority indefinitely.",
+ stale.id,
+ LEGACY_BOOTSTRAP_KEY_LABEL,
+ )
+ await api_key_store.delete(session, stale.id)
last_seeded_hash = (bootstrap_owner.metadata_ or {}).get(
BOOTSTRAP_LAST_SEEDED_HASH_META_KEY
)
+ revoked_hashes: list[str] = list(
+ (bootstrap_owner.metadata_ or {}).get(BOOTSTRAP_REVOKED_HASHES_META_KEY)
+ or []
+ )
+ meta_dirty = False
+
+ if (
+ bootstrap_key is None
+ and last_seeded_hash is not None
+ and last_seeded_hash not in revoked_hashes
+ ):
+ # A key was active as of the last seed call and is gone now: it
+ # was deleted (revoked) since then. Remember its value forever,
+ # not just until the next rotation — see the constant's docstring.
+ revoked_hashes.append(last_seeded_hash)
+ meta_dirty = True
+ logger.warning(
+ "Agent-registration bootstrap key was deleted since the "
+ "last restart; its value is now permanently refused, even "
+ "if AGENT_REGISTRATION_TOKEN is later set back to it."
+ )
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 last_seeded_hash == token_hash:
+ if token_hash in revoked_hashes:
+ logger.warning(
+ "AGENT_REGISTRATION_TOKEN matches a previously "
+ "revoked agent-registration bootstrap key; refusing "
+ "to rotate onto it. Set a new, never-used value to "
+ "change the active key."
+ )
+ else:
+ 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 token_hash in revoked_hashes:
logger.warning(
"Agent-registration bootstrap key was revoked; not "
- "reseeding it from AGENT_REGISTRATION_TOKEN. Rotate the "
- "token to a new value to re-enable deployment-wide bootstrap "
+ "reseeding it from AGENT_REGISTRATION_TOKEN. Set a new, "
+ "never-used value to re-enable deployment-wide bootstrap "
"registration, or mint per-user registration keys from the "
"gateway's API Keys page instead."
)
@@ -603,9 +662,14 @@ async def _seed_agent_registration_bootstrap_key(
"AGENT_REGISTRATION_TOKEN"
)
- if bootstrap_key is not None and last_seeded_hash != token_hash:
+ new_last_seeded_hash = bootstrap_key.key_hash if bootstrap_key else None
+ if new_last_seeded_hash != last_seeded_hash:
+ meta_dirty = True
+
+ if meta_dirty:
meta = dict(bootstrap_owner.metadata_ or {})
- meta[BOOTSTRAP_LAST_SEEDED_HASH_META_KEY] = token_hash
+ meta[BOOTSTRAP_LAST_SEEDED_HASH_META_KEY] = new_last_seeded_hash
+ meta[BOOTSTRAP_REVOKED_HASHES_META_KEY] = revoked_hashes
bootstrap_owner.metadata_ = meta
await session.commit()
diff --git a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
index d663dd993..95cdd4e75 100644
--- a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
+++ b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
@@ -6,6 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_KEY_TYPE,
BOOTSTRAP_OWNER_EMAIL,
+ BOOTSTRAP_OWNER_MARKER_META_KEY,
ensure_bootstrap_owner,
resolve_registration_owner_id,
)
@@ -24,7 +25,7 @@ async def _make_user(
class TestEnsureBootstrapOwner:
- async def test_creates_a_non_admin_user_once(
+ async def test_creates_a_marked_non_admin_user_once(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
user_store = UserStore()
@@ -33,19 +34,37 @@ class TestEnsureBootstrapOwner:
await session.commit()
assert owner.email == BOOTSTRAP_OWNER_EMAIL
assert owner.role != "admin"
+ assert (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY) is True
async with session_factory() as session:
again = await ensure_bootstrap_owner(session, user_store)
await session.commit()
assert again.id == owner.id
+ async def test_refuses_a_role_user_account_squatting_the_address(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The realistic squatter: an identity claimed this address — via
+ OIDC JIT provisioning, or any other path — before bootstrap seeding
+ ever ran. JIT provisioning always creates `role="user"`, so a role
+ check alone would silently adopt it; only the creation marker this
+ module stamps distinguishes a genuine bootstrap owner from one."""
+ user_store = UserStore()
+ async with session_factory() as session:
+ session.add(User(name="squatter", email=BOOTSTRAP_OWNER_EMAIL, role="user"))
+ await session.commit()
+
+ async with session_factory() as session:
+ with pytest.raises(RuntimeError, match="not created by"):
+ await ensure_bootstrap_owner(session, user_store)
+
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."""
+ """A gateway admin can `POST /users` with this exact email and an
+ admin role. Adopting that account would silently restore the exact
+ escalation this module exists to close — caught here as a second,
+ independent check even though the missing marker already refuses it."""
user_store = UserStore()
async with session_factory() as session:
session.add(
@@ -142,3 +161,26 @@ class TestResolveRegistrationOwnerId:
async with session_factory() as session:
with pytest.raises(RuntimeError, match="admin"):
await resolve_registration_owner_id(session, user_store, key)
+
+ async def test_role_user_squatter_at_the_bootstrap_address_fails_loud(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Registration-time counterpart of the squatter case above: even
+ without ever having run `ensure_bootstrap_owner`, a bootstrap-type
+ key must not resolve to an unmarked account at that address."""
+ user_store = UserStore()
+ admin_id = await _make_user(session_factory, role="admin")
+ async with session_factory() as session:
+ session.add(User(name="squatter", email=BOOTSTRAP_OWNER_EMAIL, role="user"))
+ 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="not created by"):
+ 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
index b445c3714..268e2812b 100644
--- a/core/tests/switch_core/test_main.py
+++ b/core/tests/switch_core/test_main.py
@@ -166,35 +166,82 @@ class TestSeedAgentRegistrationBootstrapKey:
assert bootstrap_keys[0].label == BOOTSTRAP_KEY_LABEL
assert 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(
+ async def test_a_legacy_key_rotated_before_the_upgrade_is_retired_not_left_live(
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."""
+ """An operator who rotates AGENT_REGISTRATION_TOKEN at or before the
+ upgrade (ordinary practice) leaves the legacy row's hash stale, so a
+ hash-only lookup for the *current* token would never find it to
+ migrate. Left alone, that row keeps authenticating as
+ `type="registration"`, owned by the admin — exactly the escalation
+ this PR exists to close, and permanently, since a bootstrap key
+ exists after this run and later runs never look for it again."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+
+ async with session_factory() as session:
+ legacy = ApiKey(
+ user_id=admin_id,
+ key_hash=_hash("old-token"),
+ encrypted_key="irrelevant",
+ label=LEGACY_BOOTSTRAP_KEY_LABEL,
+ type="registration",
+ )
+ session.add(legacy)
+ await session.commit()
+
+ 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")
+ # The stale row must not still be live as a registration credential
+ # under the old value.
+ assert not any(
+ k.type == "registration" and k.key_hash == _hash("old-token") for k in keys
+ )
+
+ async def test_a_hash_mismatched_legacy_labeled_key_is_retired_and_warned_about(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ caplog: pytest.LogCaptureFixture,
+ ) -> None:
+ """The label alone cannot tell a stale, rotated-out bootstrap key
+ (finding 1: dangerous — admin-owned, still registers agents with
+ admin authority) apart from a personal key an admin happened to
+ label identically (finding 5's contrived scenario). Nothing in the
+ schema distinguishes them once the hash no longer matches, so this
+ favours closing the real, silent escalation: retire the row (so it
+ can no longer register anything) and name it loudly in a warning, so
+ the rare coincidental case is at least visible and cheap to recover
+ from (recreate a personal key) rather than a permanent, silent hole."""
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(
+ stale = ApiKey(
user_id=admin_id,
- key_hash=_hash("some-unrelated-personal-secret"),
+ key_hash=_hash("some-other-value"),
encrypted_key="irrelevant",
label=LEGACY_BOOTSTRAP_KEY_LABEL,
type="registration",
)
- session.add(personal)
+ session.add(stale)
await session.commit()
- personal_id = personal.id
+ stale_id = stale.id
- await _seed(session_factory, user_store, api_key_store, config)
+ with caplog.at_level("WARNING", logger="switch_core.main"):
+ 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 not any(k.id == stale_id for k in keys)
assert len([k for k in keys if k.type == BOOTSTRAP_KEY_TYPE]) == 1
+ warnings = [r.message for r in caplog.records if r.levelname == "WARNING"]
+ assert any(stale_id in w for w in warnings)
async def test_revoking_a_migrated_legacy_key_survives_a_restart(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -301,6 +348,39 @@ class TestSeedAgentRegistrationBootstrapKey:
assert len(bootstrap_keys) == 1
assert bootstrap_keys[0].key_hash == _hash("new-token")
+ async def test_rotating_back_to_a_revoked_value_does_not_reinstate_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Revoke X, rotate to Y and restart, rotate back to X and restart:
+ the deployment must keep serving Y (or nothing), never X again — a
+ revoked value is refused forever, not just until the next rotation."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ admin_id = await _make_admin(session_factory)
+
+ await _seed(session_factory, user_store, api_key_store, _config("x-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()
+
+ # Rotate forward to Y: re-enabled at the new value.
+ await _seed(session_factory, user_store, api_key_store, _config("y-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("y-token")
+
+ # Rotate back to X: must not reinstate the revoked value. Y stays active.
+ await _seed(session_factory, user_store, api_key_store, _config("x-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("y-token")
+ assert not any(k.key_hash == _hash("x-token") for k in keys)
+
async def test_missing_admin_user_fails_loud(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
@@ -313,9 +393,8 @@ class TestSeedAgentRegistrationBootstrapKey:
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.
+ """Adversarial: a gateway admin has already claimed the bootstrap
+ owner's reserved address with the admin role via `POST /users`.
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."""
@@ -327,6 +406,22 @@ class TestSeedAgentRegistrationBootstrapKey:
with pytest.raises(RuntimeError, match="admin"):
await _seed(session_factory, user_store, api_key_store, config)
+ async def test_role_user_squatter_at_bootstrap_address_blocks_seeding(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The realistic squatter: an identity claimed the bootstrap owner's
+ address (e.g. an OIDC login, which always provisions `role="user"`)
+ before agent-registration bootstrap ever ran. A role check alone
+ would silently adopt this account; only the creation marker this
+ module stamps on its own account catches it."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ await _make_admin(session_factory)
+ await _make_user(session_factory, email=BOOTSTRAP_OWNER_EMAIL, role="user")
+ config = _config("dev-test-token")
+
+ with pytest.raises(RuntimeError, match="not created by"):
+ 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],
@@ -367,10 +462,11 @@ class TestSeedAgentRegistrationBootstrapKey:
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")
+ bootstrap_keys = await api_key_store.get_by_type(
+ session, BOOTSTRAP_KEY_TYPE
)
- assert all_keys_by_hash is not None
+ assert len(bootstrap_keys) == 1
+ assert bootstrap_keys[0].key_hash == _hash("dev-test-token")
async def test_changing_the_admin_email_after_revocation_does_not_resurrect_it(
self, session_factory: async_sessionmaker[AsyncSession]