Skip to content

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

Refuse an expired key at controller enrollment and token exchange too

Petr Baucha9128e70737b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52d45e7a9..bea89e5fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,8 +97,10 @@ version of their own to them without also giving them a release of their own.
which warns that the key keeps working if it leaks. `POST /api-keys`
takes `expires_in_days` (1 to 365, or `"never"`; 90 when left out), the
key list shows each key's expiry or **No expiry**, and an expired key is
- refused with 401 wherever keys are accepted. Keys made before this release,
- agents' own keys and the deployment's bootstrap key do not expire.
+ refused with 401 by the agent API, the MCP server and agent registration.
+ Its owner can still reveal it under API keys, to see which key it was.
+ Keys made before this release, agents' own keys and the deployment's
+ bootstrap key do not expire.
- **Messages with files attached are checked by Switch Trust.** A message with
a file used to skip the check entirely, typed text included, both from a
person on a chat platform and from an agent sending files. Now the text is
diff --git a/core/switch_core/management/service.py b/core/switch_core/management/service.py
index 544915590..f9684d09d 100644
--- a/core/switch_core/management/service.py
+++ b/core/switch_core/management/service.py
@@ -300,7 +300,11 @@ class ManagementService:
"The enrollment code is invalid, already used, or expired.",
)
key = await self.api_keys.get_by_hash(session, tokens.hash_secret(code))
- if key is None or key.type != CONTROLLER_ENROLLMENT_KEY_TYPE:
+ if (
+ key is None
+ or key.type != CONTROLLER_ENROLLMENT_KEY_TYPE
+ or key.expired(self.now())
+ ):
raise invalid
consumed = await self.controllers.consume_enrollment_code(
session, tenant_id, key.id, self.now()
@@ -395,7 +399,7 @@ class ManagementService:
401, reason_codes.INVALID_CREDENTIAL, "The credential is not valid."
)
key = await self.api_keys.get_by_hash(session, tokens.hash_secret(credential))
- if key is None or key.type != CONTROLLER_KEY_TYPE:
+ if key is None or key.type != CONTROLLER_KEY_TYPE or key.expired(self.now()):
raise invalid
controller = await self.controllers.get_by_api_key(session, tenant_id, key.id)
if controller is None or controller.id != controller_id:
diff --git a/core/tests/switch_core/management/test_controller_routes.py b/core/tests/switch_core/management/test_controller_routes.py
index a20c0e55c..be219be1d 100644
--- a/core/tests/switch_core/management/test_controller_routes.py
+++ b/core/tests/switch_core/management/test_controller_routes.py
@@ -8,14 +8,15 @@ the operation lifecycle, and the bindings placement keeps in Core.
from __future__ import annotations
import hashlib
+from datetime import timedelta
import pytest
-from sqlalchemy import select
+from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
from switch_core.config import ControllerRelease
-from switch_core.db.models import AgentControllerEnrollmentCode
+from switch_core.db.models import AgentControllerEnrollmentCode, ApiKey
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.management.bindings import load_bindings
from switch_core.management.controller_routes import ASSIGNMENT_FORMAT
@@ -55,6 +56,18 @@ async def _code(harness: Harness, owner_cookies: dict[str, str]) -> str:
return str(body["code"])
+async def _expire_key(harness: Harness, secret: str) -> None:
+ """Give the key behind `secret` an expiry that has passed, as a key made
+ with one would have."""
+ async with harness.session_factory() as session:
+ await session.execute(
+ update(ApiKey)
+ .where(ApiKey.key_hash == hashlib.sha256(secret.encode()).hexdigest())
+ .values(expires_at=harness.clock.now - timedelta(seconds=1))
+ )
+ await session.commit()
+
+
class TestEnrollmentCodes:
async def test_a_code_names_the_server_to_enroll_against(
self, harness: Harness
@@ -177,6 +190,19 @@ class TestEnrollmentByCode:
assert response.status_code == 401
assert response.json()["error"]["code"] == "enrollment_code_invalid"
+ async def test_a_code_whose_key_has_expired_is_refused(
+ self, harness: Harness
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+ code = await _code(harness, cookies_for(owner))
+ await _expire_key(harness, code)
+ async with harness.client() as client:
+ response = await client.post(
+ "/v1/management/controllers/enroll", json=_enroll_body(code)
+ )
+ assert response.status_code == 401
+ assert response.json()["error"]["code"] == "enrollment_code_invalid"
+
async def test_an_unknown_code_is_refused(self, harness: Harness) -> None:
async with harness.client() as client:
response = await client.post(
@@ -221,6 +247,20 @@ class TestTokenExchange:
assert response.status_code == 401
assert response.json()["error"]["code"] == "invalid_credential"
+ async def test_a_credential_whose_key_has_expired_is_refused(
+ self, harness: Harness
+ ) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+ async with harness.client() as client:
+ controller = await enroll_console(harness, client, owner)
+ await _expire_key(harness, controller.credential)
+ response = await client.post(
+ f"/v1/management/controllers/{controller.controller_id}/token",
+ json={"credential": controller.credential},
+ )
+ assert response.status_code == 401
+ assert response.json()["error"]["code"] == "invalid_credential"
+
async def test_a_credential_for_another_controller_is_refused(
self, harness: Harness
) -> None: