Skip to content

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

Verify a controller's access token once, not on every request (CHOO-3667)

Abel Dantasfb6bb62ba405
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b9791612..48a31492c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -224,6 +224,9 @@ version of their own to them without also giving them a release of their own.
group whose subgroup would move up next to a namesake is refused too, and
the dashboard now shows why. Names can no longer contain `/` or be blank.
Existing duplicates are left as they are and can be reached by id.
+- **A controller's access token is verified once.** Each process keeps the
+ tokens that verified until they expire, where every request verified its
+ token again; revocation is still checked on every request.
#### Fixed
- **On Slack, the 👀 and the activity card no longer arrive after the agent's
diff --git a/core/switch_core/management/auth.py b/core/switch_core/management/auth.py
index bf960e5ec..7dcfe6add 100644
--- a/core/switch_core/management/auth.py
+++ b/core/switch_core/management/auth.py
@@ -53,7 +53,7 @@ class ManagementAuthenticator:
) -> None:
self._session_factory = session_factory
self._controllers = controllers
- self._token_secret = token_secret
+ self._verified = tokens.VerifiedTokens(secret=token_secret)
self._presence = presence
self._auth_cache = auth_cache
@@ -76,7 +76,7 @@ class ManagementAuthenticator:
async def authenticate(self, token: str) -> ControllerPrincipal:
try:
- claims = tokens.verify_access_token(token, secret=self._token_secret)
+ claims = self._verified.verify(token)
except tokens.AccessTokenExpired as exc:
raise ControllerAuthError(
reason_codes.TOKEN_EXPIRED,
diff --git a/core/switch_core/management/tokens.py b/core/switch_core/management/tokens.py
index d47c72deb..52c76f98e 100644
--- a/core/switch_core/management/tokens.py
+++ b/core/switch_core/management/tokens.py
@@ -17,6 +17,8 @@ from __future__ import annotations
import hashlib
import secrets
+import time
+from collections import OrderedDict
from dataclasses import dataclass
from datetime import datetime, timedelta
@@ -97,6 +99,45 @@ def verify_access_token(token: str, *, secret: str) -> AccessTokenClaims:
AccessTokenInvalid: anything else — not a controller access token, a
bad signature, the wrong audience, or a missing claim.
"""
+ return _verify(token, secret=secret)[0]
+
+
+class VerifiedTokens:
+ """`verify_access_token`, remembering the tokens that verified until
+ each expires.
+
+ A controller sends the same token with every request for an hour, and
+ verifying it each time cost more than the rest of authenticating it:
+ PyJWT checks every character of the token in Python. Only a token that
+ verified is kept, by its sha256 like a stored secret, so a token that was
+ altered or forged never matches one; its expiry is checked on every use,
+ and an expired one is verified again, which refuses it as expired.
+ Revocation is not this class's to check: the caller reads the controller.
+ """
+
+ def __init__(self, *, secret: str, max_entries: int = 4096) -> None:
+ self._secret = secret
+ self._max_entries = max_entries
+ self._verified: OrderedDict[str, tuple[int, AccessTokenClaims]] = OrderedDict()
+
+ def verify(self, token: str) -> AccessTokenClaims:
+ digest = hash_secret(token)
+ kept = self._verified.get(digest)
+ if kept is not None:
+ expires_at, claims = kept
+ if time.time() < expires_at:
+ self._verified.move_to_end(digest)
+ return claims
+ del self._verified[digest]
+ claims, expires_at = _verify(token, secret=self._secret)
+ self._verified[digest] = (expires_at, claims)
+ while len(self._verified) > self._max_entries:
+ self._verified.popitem(last=False)
+ return claims
+
+
+def _verify(token: str, *, secret: str) -> tuple[AccessTokenClaims, int]:
+ """The claims of a token that verified, and its `exp`."""
if not token.startswith(ACCESS_TOKEN_PREFIX):
raise AccessTokenInvalid("not a controller access token")
try:
@@ -114,6 +155,11 @@ def verify_access_token(token: str, *, secret: str) -> AccessTokenClaims:
values = (claims.get("cid"), claims.get("tid"), claims.get("oid"))
if not all(isinstance(value, str) and value for value in values):
raise AccessTokenInvalid("access token claims are malformed")
- return AccessTokenClaims(
- controller_id=claims["cid"], tenant_id=claims["tid"], owner_id=claims["oid"]
+ return (
+ AccessTokenClaims(
+ controller_id=claims["cid"],
+ tenant_id=claims["tid"],
+ owner_id=claims["oid"],
+ ),
+ int(claims["exp"]),
)
diff --git a/core/tests/switch_core/management/test_verified_tokens.py b/core/tests/switch_core/management/test_verified_tokens.py
new file mode 100644
index 000000000..b5f5421c6
--- /dev/null
+++ b/core/tests/switch_core/management/test_verified_tokens.py
@@ -0,0 +1,102 @@
+"""`VerifiedTokens`: a controller access token is verified once, and its
+expiry is still checked on every use."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.management import tokens
+
+SECRET = "s" * 48
+
+
+def _token(controller_id: str = "c1") -> str:
+ token, _ = tokens.mint_access_token(
+ secret=SECRET,
+ controller_id=controller_id,
+ tenant_id="t1",
+ owner_id="o1",
+ now=datetime.now(UTC),
+ )
+ return token
+
+
+def decodes(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """The tokens PyJWT was asked to decode."""
+ seen: list[str] = []
+ decode = tokens.jwt.decode
+
+ def counted(token: str, *args: Any, **kwargs: Any) -> Any:
+ seen.append(token)
+ return decode(token, *args, **kwargs)
+
+ monkeypatch.setattr(tokens.jwt, "decode", counted)
+ return seen
+
+
+def test_a_token_is_decoded_once(decodes: list[str]) -> None:
+ verified = tokens.VerifiedTokens(secret=SECRET)
+ token = _token()
+
+ first = verified.verify(token)
+ again = verified.verify(token)
+
+ assert first == again == tokens.AccessTokenClaims("c1", "t1", "o1")
+ assert len(decodes) == 1
+
+
+def test_a_kept_token_is_refused_once_it_expires(
+ decodes: list[str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ verified = tokens.VerifiedTokens(secret=SECRET)
+ token = _token()
+ verified.verify(token)
+
+ later = tokens.time.time() + tokens.ACCESS_TOKEN_LIFETIME.total_seconds() + 1
+ monkeypatch.setattr(tokens, "time", SimpleNamespace(time=lambda: later))
+ monkeypatch.setattr(
+ tokens.jwt.api_jwt, "datetime", _Frozen(datetime.fromtimestamp(later, UTC))
+ )
+
+ with pytest.raises(tokens.AccessTokenExpired):
+ verified.verify(token)
+
+
+def test_an_altered_token_is_not_taken_for_a_kept_one() -> None:
+ verified = tokens.VerifiedTokens(secret=SECRET)
+ token = _token()
+ verified.verify(token)
+
+ with pytest.raises(tokens.AccessTokenInvalid):
+ verified.verify(token[:-2] + ("AA" if not token.endswith("AA") else "BB"))
+
+
+def test_it_keeps_no_more_than_its_bound(decodes: list[str]) -> None:
+ verified = tokens.VerifiedTokens(secret=SECRET, max_entries=2)
+ first, second, third = _token("c1"), _token("c2"), _token("c3")
+ for token in (first, second, third):
+ verified.verify(token)
+
+ verified.verify(third)
+ verified.verify(first)
+
+ assert len(decodes) == 4
+
+
+class _Frozen:
+ """PyJWT's view of `datetime`, with `now` fixed: it checks `exp` against
+ its own clock, not the one this module keeps."""
+
+ def __init__(self, now: datetime) -> None:
+ self._now = now
+
+ def now(self, tz: Any = None) -> datetime:
+ return self._now
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(datetime, name)