Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Skip hash-only API keys when re-encrypting stored secrets at boot (#689)

Abel Dantase5e343c52d83
diff --git a/core/switch_core/db/key_rotation.py b/core/switch_core/db/key_rotation.py
index c0904f908..49604d06a 100644
--- a/core/switch_core/db/key_rotation.py
+++ b/core/switch_core/db/key_rotation.py
@@ -59,6 +59,10 @@ async def reencrypt_stale_text(
Raises `UndecryptableError` for a value no key opens: that is a key
removed too early, and continuing would leave a credential nothing can
read while reporting the rotation done.
+
+ The empty string is skipped like NULL: a hash-only API key (a controller
+ credential, an enrollment code) stores `""` because the column is NOT NULL,
+ and there is nothing in it to open.
"""
stored = model.__table__.c[column]
# Rows are named by their primary key, which is not always a single `id`.
@@ -66,6 +70,7 @@ async def reencrypt_stale_text(
rows = await session.execute(
select(*keys, stored).where(
stored.is_not(None),
+ stored != "",
~stored.startswith(keyring.current_prefix(), autoescape=True),
)
)
diff --git a/core/tests/switch_core/db/test_key_rotation.py b/core/tests/switch_core/db/test_key_rotation.py
index c9a78ab11..f3639f716 100644
--- a/core/tests/switch_core/db/test_key_rotation.py
+++ b/core/tests/switch_core/db/test_key_rotation.py
@@ -161,3 +161,27 @@ async def test_a_value_no_key_opens_stops_the_boot(
monkeypatch.setattr(encrypted_json, "_keyring", too_early)
with pytest.raises(UndecryptableError):
await reencrypt_stored_secrets(rls_harness.restricted, too_early, [tenant_id])
+
+
+async def test_a_hash_only_key_is_left_alone(
+ rls_harness: RLSHarness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Controller credentials and enrollment codes keep only a hash, so their
+ `encrypted_key` is the empty string. Boot must not try to open it."""
+ monkeypatch.setattr(encrypted_json, "_keyring", _NEW)
+ tenant_id, user_id = await _tenant_with_user(rls_harness.owner)
+ async with tenant_session(rls_harness.restricted, tenant_id) as session:
+ key = ApiKey(
+ user_id=user_id,
+ key_hash=uuid.uuid4().hex,
+ encrypted_key="",
+ label="controller",
+ type="user",
+ )
+ session.add(key)
+ await session.commit()
+ key_id = key.id
+
+ await reencrypt_stored_secrets(rls_harness.restricted, _NEW, [tenant_id])
+
+ assert await _raw(rls_harness.owner, "api_keys", "encrypted_key", key_id) == ""