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): backfill the bootstrap marker, revoke retired-key hashes, and retire instead of delete

Wojciech Wojtyniak46b10cf31a0e
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 19cd9dae9..6069d9511 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -154,7 +154,10 @@ async def _resolve_registration_user_id(
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
+ logger.error("Agent-registration bootstrap owner resolution failed: %s", exc)
+ raise HTTPException(
+ status_code=503, detail="Agent registration is temporarily unavailable"
+ ) from exc
# Registration endpoints
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index e181b5b37..f59876df7 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -440,7 +440,10 @@ class ProtocolService:
"""Resolve a registration token to its owner, then register the agent.
Raises PermissionError if the token does not match a stored ApiKey of
- a registration type (see ``registration_bootstrap.REGISTRATION_KEY_TYPES``).
+ a registration type (see ``registration_bootstrap.REGISTRATION_KEY_TYPES``),
+ or if the bootstrap owner cannot be resolved (misconfigured deployment
+ — the detail is logged, not raised, to match the HTTP registration
+ path's handling of the same failure).
Raises AgentExistsError if the name is taken and ``overwrite`` is False.
"""
token_hash = hashlib.sha256(registration_token.encode()).hexdigest()
@@ -448,9 +451,17 @@ class ProtocolService:
key = await self.api_key_store.get_by_hash(session, token_hash)
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
- )
+ try:
+ owner_id = await resolve_registration_owner_id(
+ session, self.user_store, key
+ )
+ except RuntimeError as exc:
+ logger.error(
+ "Agent-registration bootstrap owner resolution failed: %s", exc
+ )
+ raise PermissionError(
+ "Agent registration is temporarily unavailable"
+ ) from exc
return await self.register_agent(
name=name,
diff --git a/core/switch_core/bridges/agent/registration_bootstrap.py b/core/switch_core/bridges/agent/registration_bootstrap.py
index 2135ce81d..4d3170b4f 100644
--- a/core/switch_core/bridges/agent/registration_bootstrap.py
+++ b/core/switch_core/bridges/agent/registration_bootstrap.py
@@ -22,8 +22,8 @@ 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.
+it is provably genuine, and refuse an admin role on top of that as a second,
+independent check.
"""
from __future__ import annotations
@@ -37,20 +37,37 @@ 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.
+# own `"agent"`-type key, or a `RETIRED_KEY_TYPE` row) must not be replayed
+# to register more agents.
REGISTRATION_KEY_TYPES = ("registration", BOOTSTRAP_KEY_TYPE)
+# Assigned to a stale legacy-labeled key at startup instead of deleting it:
+# not in REGISTRATION_KEY_TYPES, so it stops authenticating exactly as
+# deletion would, but the row (and its label, rewritten to say so) stays on
+# the gateway's API Keys page for a human to notice and remove — a deleted
+# row leaves nothing but a startup log line, and the two cases this can be
+# (a stale rotated-out bootstrap key, or an unrelated personal key that
+# happened to share the auto-generated label) are not distinguishable at
+# seed time, so the evidence needs to survive for a human to tell afterward.
+RETIRED_KEY_TYPE = "retired"
+
# 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"
-# 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.
+# Stamped into the bootstrap owner's metadata by this module's own creation
+# path. 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 — *unless* it already carries
+# BOOTSTRAP_LAST_SEEDED_HASH_META_KEY (below): that key is written only by
+# this module's own seeding step, so its presence on an unmarked row proves
+# the row predates the marker (created by an earlier version of this
+# feature) rather than being squatted — a squatter cannot have written a
+# value only this code ever writes. Backfilled onto such a row rather than
+# refused, so upgrading past the commit that introduced the marker does not
+# brick a database this already ran against.
BOOTSTRAP_OWNER_MARKER_META_KEY = "agent_bootstrap_owner"
BOOTSTRAP_KEY_LABEL = "Deployment bootstrap (from AGENT_REGISTRATION_TOKEN)"
@@ -81,8 +98,15 @@ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY = "agent_bootstrap_key_last_hash"
BOOTSTRAP_REVOKED_HASHES_META_KEY = "agent_bootstrap_revoked_hashes"
+def _is_genuine(owner: User) -> bool:
+ meta = owner.metadata_ or {}
+ if meta.get(BOOTSTRAP_OWNER_MARKER_META_KEY):
+ return True
+ return BOOTSTRAP_LAST_SEEDED_HASH_META_KEY in meta
+
+
def _raise_unless_genuine(owner: User) -> None:
- if not (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY):
+ if not _is_genuine(owner):
raise RuntimeError(
f"An account already exists at {BOOTSTRAP_OWNER_EMAIL} but was "
"not created by agent-registration bootstrap seeding, so it "
@@ -93,23 +117,29 @@ def _raise_unless_genuine(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. 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."
+ f"{BOOTSTRAP_OWNER_EMAIL} must never be an admin, but the "
+ "account at that 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 that this function
- did not itself create, or that has since been given the admin role.
+ Raises if an account already exists at that address that cannot be
+ proven genuine (see ``_is_genuine``), or that has since been given the
+ admin role. A genuine row created before the marker existed is backfilled
+ with one here rather than refused.
"""
owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)
if owner is not None:
_raise_unless_genuine(owner)
+ if not (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY):
+ meta = dict(owner.metadata_ or {})
+ meta[BOOTSTRAP_OWNER_MARKER_META_KEY] = True
+ owner.metadata_ = meta
return owner
owner = User(
name=BOOTSTRAP_OWNER_NAME,
@@ -127,8 +157,8 @@ 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 this module did not
- provision, or one that has since been given the admin role —
+ Raises if a bootstrap key resolves to an account that cannot be proven
+ genuine, 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.
"""
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index d96fc6a8a..2eb819d32 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -28,6 +28,7 @@ from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_LAST_SEEDED_HASH_META_KEY,
BOOTSTRAP_REVOKED_HASHES_META_KEY,
LEGACY_BOOTSTRAP_KEY_LABEL,
+ RETIRED_KEY_TYPE,
ensure_bootstrap_owner,
)
from switch_core.bridges.agent.server_connectors.lifecycle import (
@@ -560,52 +561,19 @@ async def _seed_agent_registration_bootstrap_key(
)
bootstrap_key = bootstrap_keys[0] if bootstrap_keys else None
- # 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 []
+ raw_revoked_hashes = (bootstrap_owner.metadata_ or {}).get(
+ BOOTSTRAP_REVOKED_HASHES_META_KEY
)
+ if raw_revoked_hashes is not None and not isinstance(raw_revoked_hashes, list):
+ raise RuntimeError(
+ f"{BOOTSTRAP_REVOKED_HASHES_META_KEY} on the agent-registration "
+ "bootstrap owner is not a list; refusing to guess which "
+ "hashes are revoked. This needs a direct database fix."
+ )
+ revoked_hashes: list[str] = list(raw_revoked_hashes or [])
meta_dirty = False
if (
@@ -624,6 +592,64 @@ async def _seed_agent_registration_bootstrap_key(
"if AGENT_REGISTRATION_TOKEN is later set back to it."
)
+ if bootstrap_key is None:
+ # 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. Scoped to "no bootstrap key yet":
+ # once one exists, any startup that still finds a legacy-labeled
+ # row here already retired it on an earlier pass.
+ 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 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
+ # Retired, not deleted: every consumer already refuses
+ # RETIRED_KEY_TYPE (it is not in REGISTRATION_KEY_TYPES), so
+ # this stops it authenticating exactly as deletion would —
+ # but the row stays on the API Keys page (filtered on type,
+ # not existence) with a label that says why, so an operator
+ # can tell a stale bootstrap key apart from a personal key
+ # that coincidentally shared the label, and delete it
+ # themselves once they have. Its hash is also permanently
+ # revoked: restoring an old .env or values file must not
+ # bring it back to life via the rotation path below.
+ stale.type = RETIRED_KEY_TYPE
+ stale.label = f"{stale.label} (retired: stale, no longer authenticates)"
+ if stale.key_hash not in revoked_hashes:
+ revoked_hashes.append(stale.key_hash)
+ meta_dirty = True
+ logger.warning(
+ "Retired 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. It is now visible "
+ "on the API Keys page for a human to review and delete.",
+ stale.id,
+ LEGACY_BOOTSTRAP_KEY_LABEL,
+ )
+
if bootstrap_key is not None:
if bootstrap_key.key_hash != token_hash:
if token_hash in revoked_hashes:
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 95cdd4e75..801a68fff 100644
--- a/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
+++ b/core/tests/switch_core/bridges/agent/test_registration_bootstrap.py
@@ -5,6 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_KEY_TYPE,
+ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY,
BOOTSTRAP_OWNER_EMAIL,
BOOTSTRAP_OWNER_MARKER_META_KEY,
ensure_bootstrap_owner,
@@ -58,22 +59,64 @@ class TestEnsureBootstrapOwner:
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(
+ async def test_backfills_the_marker_onto_a_row_created_before_it_existed(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """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."""
+ """Upgrade path: a bootstrap owner created by an earlier commit of
+ this same feature, before the marker existed, has no marker but does
+ carry the last-seeded-hash key — a value only this module's own
+ seeding step ever writes, so a squatter cannot have it. Must be
+ healed in place, not refused, or upgrading past the commit that
+ introduced the marker bricks every database that already ran this."""
user_store = UserStore()
async with session_factory() as session:
session.add(
- User(name="squatter", email=BOOTSTRAP_OWNER_EMAIL, role="admin")
+ User(
+ name=BOOTSTRAP_OWNER_EMAIL,
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="user",
+ metadata_={BOOTSTRAP_LAST_SEEDED_HASH_META_KEY: "some-hash"},
+ )
)
await session.commit()
async with session_factory() as session:
- with pytest.raises(RuntimeError, match="admin"):
+ owner = await ensure_bootstrap_owner(session, user_store)
+ await session.commit()
+
+ assert (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY) is True
+ assert (owner.metadata_ or {}).get(BOOTSTRAP_LAST_SEEDED_HASH_META_KEY) == (
+ "some-hash"
+ )
+
+ async with session_factory() as session:
+ persisted = await session.get(User, owner.id)
+ assert persisted is not None
+ assert (persisted.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY) is True
+
+ async def test_refuses_a_marked_account_promoted_to_the_admin_role(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """The role check as its own, independently-exercised guard: an
+ otherwise-genuine account (it carries the marker) that has been
+ given the admin role — e.g. a gateway admin editing it directly —
+ must still be refused. Deliberately marked so this hits the role
+ check specifically rather than the (already separately tested)
+ missing-marker check."""
+ user_store = UserStore()
+ async with session_factory() as session:
+ session.add(
+ User(
+ name="promoted",
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="admin",
+ metadata_={BOOTSTRAP_OWNER_MARKER_META_KEY: True},
+ )
+ )
+ await session.commit()
+
+ async with session_factory() as session:
+ with pytest.raises(RuntimeError, match="must never be an admin"):
await ensure_bootstrap_owner(session, user_store)
diff --git a/core/tests/switch_core/test_main.py b/core/tests/switch_core/test_main.py
index 268e2812b..771f32e5b 100644
--- a/core/tests/switch_core/test_main.py
+++ b/core/tests/switch_core/test_main.py
@@ -17,8 +17,13 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_KEY_LABEL,
BOOTSTRAP_KEY_TYPE,
+ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY,
BOOTSTRAP_OWNER_EMAIL,
+ BOOTSTRAP_OWNER_MARKER_META_KEY,
+ BOOTSTRAP_OWNER_NAME,
+ BOOTSTRAP_REVOKED_HASHES_META_KEY,
LEGACY_BOOTSTRAP_KEY_LABEL,
+ RETIRED_KEY_TYPE,
)
from switch_core.config import SwitchConfig
from switch_core.db.models import Agent, ApiKey, Client, User
@@ -46,10 +51,14 @@ def _config(token: str, *, admin_email: str = ADMIN_EMAIL) -> SwitchConfig:
async def _make_user(
- session_factory: async_sessionmaker[AsyncSession], *, email: str, role: str
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ email: str,
+ role: str,
+ metadata: dict | None = None,
) -> str:
async with session_factory() as session:
- user = User(name=role, email=email, role=role)
+ user = User(name=role, email=email, role=role, metadata_=metadata)
session.add(user)
await session.commit()
return user.id
@@ -175,7 +184,11 @@ class TestSeedAgentRegistrationBootstrapKey:
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."""
+ exists after this run and later runs never look for it again.
+
+ Retired, not deleted: the row must stop authenticating but stay
+ visible (and its old value permanently revoked, so restoring an old
+ .env or values file can't bring it back either)."""
user_store, api_key_store = UserStore(), ApiKeyStore()
admin_id = await _make_admin(session_factory)
@@ -189,19 +202,29 @@ class TestSeedAgentRegistrationBootstrapKey:
)
session.add(legacy)
await session.commit()
+ legacy_id = legacy.id
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)
+ by_id = {k.id: k for k in keys}
+ 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")
+ # Still visible, no longer live: retired, not gone.
+ assert legacy_id in by_id
+ assert by_id[legacy_id].type == RETIRED_KEY_TYPE
+ assert by_id[legacy_id].type not in ("registration", BOOTSTRAP_KEY_TYPE)
+
+ # Restoring the old .env (or a stale values file) must not resurrect
+ # it: its hash is permanently revoked, not just retyped away.
+ 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_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,
@@ -214,9 +237,10 @@ class TestSeedAgentRegistrationBootstrapKey:
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."""
+ can no longer register anything, but stays visible on the API Keys
+ page instead of vanishing) and name it loudly in a warning, so the
+ rare coincidental case is at least visible and recoverable 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")
@@ -238,7 +262,10 @@ class TestSeedAgentRegistrationBootstrapKey:
async with session_factory() as session:
keys = await api_key_store.get_by_user(session, admin_id)
- assert not any(k.id == stale_id for k in keys)
+ by_id = {k.id: k for k in keys}
+ assert stale_id in by_id, "the retired row must still be visible"
+ assert by_id[stale_id].type == RETIRED_KEY_TYPE
+ assert "retired" in by_id[stale_id].label.lower()
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)
@@ -390,22 +417,76 @@ class TestSeedAgentRegistrationBootstrapKey:
with pytest.raises(RuntimeError):
await _seed(session_factory, user_store, api_key_store, config)
- async def test_bootstrap_owner_promoted_to_admin_blocks_seeding(
+ async def test_malformed_revoked_hashes_fails_loud(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A hand-edited, non-list value must not be silently coerced (`list("a
+ string")` iterates its characters) into "nothing is revoked"."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ await _make_admin(session_factory)
+ async with session_factory() as session:
+ session.add(
+ User(
+ name=BOOTSTRAP_OWNER_NAME,
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="user",
+ metadata_={
+ BOOTSTRAP_OWNER_MARKER_META_KEY: True,
+ BOOTSTRAP_REVOKED_HASHES_META_KEY: "not-a-list",
+ },
+ )
+ )
+ await session.commit()
+ config = _config("dev-test-token")
+
+ with pytest.raises(RuntimeError, match="not a list"):
+ await _seed(session_factory, user_store, api_key_store, config)
+
+ async def test_promoted_bootstrap_owner_blocks_seeding(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- """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."""
+ """The role check exercised on its own: an otherwise-genuine account
+ (carries the marker) that was given the admin role directly — e.g. a
+ gateway admin editing it — must still block seeding. Marked so this
+ hits the role check rather than the separately-tested missing-marker
+ one."""
user_store, api_key_store = UserStore(), ApiKeyStore()
await _make_admin(session_factory)
- await _make_user(session_factory, email=BOOTSTRAP_OWNER_EMAIL, role="admin")
+ await _make_user(
+ session_factory,
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="admin",
+ metadata={BOOTSTRAP_OWNER_MARKER_META_KEY: True},
+ )
config = _config("dev-test-token")
- with pytest.raises(RuntimeError, match="admin"):
+ with pytest.raises(RuntimeError, match="must never be an admin"):
await _seed(session_factory, user_store, api_key_store, config)
+ async def test_upgrading_past_the_marker_commit_does_not_brick_seeding(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A bootstrap owner created by an earlier commit of this same
+ feature (before the marker existed) has no marker but does carry the
+ last-seeded-hash key, which only this module's own seeding ever
+ writes. Seeding must heal it in place rather than refuse to start."""
+ user_store, api_key_store = UserStore(), ApiKeyStore()
+ await _make_admin(session_factory)
+ await _make_user(
+ session_factory,
+ email=BOOTSTRAP_OWNER_EMAIL,
+ role="user",
+ metadata={BOOTSTRAP_LAST_SEEDED_HASH_META_KEY: "old-hash"},
+ )
+ config = _config("dev-test-token")
+
+ await _seed(session_factory, user_store, api_key_store, config)
+
+ async with session_factory() as session:
+ owner = await user_store.get_by_email(session, BOOTSTRAP_OWNER_EMAIL)
+ assert owner is not None
+ assert (owner.metadata_ or {}).get(BOOTSTRAP_OWNER_MARKER_META_KEY) is True
+
async def test_role_user_squatter_at_bootstrap_address_blocks_seeding(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None: