Skip to content

Self-improving AI Employees for everyone

feat(credentials): enumerate the scopes holding a key for one provider

trohitg62eeef360bbb
diff --git a/server/core/credentials_database.py b/server/core/credentials_database.py
index 0d58297d..eaba77f7 100644
--- a/server/core/credentials_database.py
+++ b/server/core/credentials_database.py
@@ -335,6 +335,26 @@ class CredentialsDatabase:
result = await session.execute(select(EncryptedAPIKey.provider).where(EncryptedAPIKey.session_id == session_id))
return [row[0] for row in result.all()]
+ async def list_key_scopes(self, provider: str) -> List[str]:
+ """
+ List every session_id that has a key stored for one provider.
+
+ The inverse of :meth:`list_api_keys`, which walks the other axis of
+ the ``{session_id}_{provider}`` key. Used by plugins that hold
+ several accounts for the same provider and need to enumerate them.
+
+ Args:
+ provider: Provider name
+
+ Returns:
+ Sorted list of session identifiers
+ """
+ async with self.get_session() as session:
+ result = await session.execute(
+ select(EncryptedAPIKey.session_id).where(EncryptedAPIKey.provider == provider).distinct()
+ )
+ return sorted(row[0] for row in result.all())
+
async def get_api_key_models(self, provider: str, session_id: str = "default") -> List[str]:
"""
Get stored models for an API key.
diff --git a/server/services/auth.py b/server/services/auth.py
index a80ec288..5421b60c 100644
--- a/server/services/auth.py
+++ b/server/services/auth.py
@@ -215,6 +215,25 @@ class AuthService:
logger.error("Failed to get API key", provider=provider, error=str(e))
return None
+ async def list_key_scopes(self, provider: str) -> List[str]:
+ """List every session_id holding a key for one provider.
+
+ Reads the database directly rather than the cache: the cache is
+ populated lazily per lookup, so it only knows the scopes that
+ happen to have been read already.
+
+ Args:
+ provider: API provider name
+
+ Returns:
+ Sorted list of session identifiers, empty on failure
+ """
+ try:
+ return await self.credentials_db.list_key_scopes(provider)
+ except Exception as e:
+ logger.error("Failed to list key scopes", provider=provider, error=str(e))
+ return []
+
async def get_stored_models(self, provider: str, session_id: str = "default") -> List[str]:
"""Get stored models for provider.
diff --git a/server/tests/credentials/test_auth_service.py b/server/tests/credentials/test_auth_service.py
index 8ad7fa14..ed4fa732 100644
--- a/server/tests/credentials/test_auth_service.py
+++ b/server/tests/credentials/test_auth_service.py
@@ -56,6 +56,28 @@ class TestApiKeyOps:
assert await auth_service.get_api_key("openai", "default") == "sk-default"
assert await auth_service.get_api_key("openai", "other") == "sk-other"
+ async def test_list_key_scopes_enumerates_accounts(self, auth_service):
+ await auth_service.store_api_key("discord", "bot-a", models=[])
+ await auth_service.store_api_key("discord", "bot-b", models=[], session_id="discord:222")
+ await auth_service.store_api_key("openai", "sk-x", models=[])
+
+ assert await auth_service.list_key_scopes("discord") == ["default", "discord:222"]
+
+ async def test_list_key_scopes_reads_through_to_storage(self, auth_service):
+ """Must not answer from the lazily-populated key cache.
+
+ The cache only holds scopes that happen to have been read already, so
+ answering from it would hide accounts that exist but were never
+ fetched this process.
+ """
+ await auth_service.store_api_key("discord", "bot-b", models=[], session_id="discord:222")
+ auth_service._api_key_cache.clear()
+
+ assert await auth_service.list_key_scopes("discord") == ["discord:222"]
+
+ async def test_list_key_scopes_empty_for_unknown_provider(self, auth_service):
+ assert await auth_service.list_key_scopes("discord") == []
+
class TestMemoryCache:
async def test_get_after_store_uses_memory_cache(self, auth_service, monkeypatch):
diff --git a/server/tests/credentials/test_credentials_database.py b/server/tests/credentials/test_credentials_database.py
index 303e7c31..2d219569 100644
--- a/server/tests/credentials/test_credentials_database.py
+++ b/server/tests/credentials/test_credentials_database.py
@@ -69,6 +69,35 @@ class TestApiKeyCrud:
listed = await credentials_db.list_api_keys()
assert sorted(listed) == ["anthropic", "openai"]
+ async def test_list_key_scopes_returns_sessions_for_one_provider(self, credentials_db: CredentialsDatabase):
+ """The inverse axis of list_api_keys: sessions for a provider.
+
+ Plugins holding several accounts for the same provider scope them by
+ session_id, so enumerating the accounts means enumerating the scopes.
+ """
+ await credentials_db.save_api_key("discord", "bot-a")
+ await credentials_db.save_api_key("discord", "bot-b", session_id="discord:222")
+ await credentials_db.save_api_key("discord", "bot-c", session_id="discord:111")
+ # A different provider in one of the same scopes must not leak in.
+ await credentials_db.save_api_key("openai", "sk-x", session_id="discord:111")
+
+ assert await credentials_db.list_key_scopes("discord") == [
+ "default",
+ "discord:111",
+ "discord:222",
+ ]
+
+ async def test_list_key_scopes_is_empty_for_unknown_provider(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-x")
+ assert await credentials_db.list_key_scopes("discord") == []
+
+ async def test_list_key_scopes_drops_a_deleted_scope(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("discord", "bot-a")
+ await credentials_db.save_api_key("discord", "bot-b", session_id="discord:222")
+ await credentials_db.delete_api_key("discord", session_id="discord:222")
+
+ assert await credentials_db.list_key_scopes("discord") == ["default"]
+
async def test_get_api_key_info_does_not_decrypt(self, credentials_db: CredentialsDatabase):
await credentials_db.save_api_key("openai", "sk-secret", models=["gpt-4", "gpt-3.5"])
info = await credentials_db.get_api_key_info("openai")