Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/late/mcp/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,17 @@ def is_allowed_origin(request: Request) -> bool:
# user id and, for an OAuth token, its granted scope. Kept so a grant served
# from cache still says whose token it is and what it may reach.
_IDENTITY_BY_TOKEN: OrderedDict[str, dict[str, str]] = OrderedDict()
# How long a confirmed answer stands before the next request asks upstream
# again. An API key is revoked by hand in the dashboard and an MCP session
# re-presents it for hours, so 10 minutes of reuse is the right trade. An
# OAuth access token can be revoked by the client (RFC 7009, /api/oauth/revoke)
# and the user expects that to land at once, so it is re-asked every minute:
# a revoked token keeps working here for at most this long.
_FRESH_TTL_SECONDS = 600.0
_OAUTH_FRESH_TTL_SECONDS = 60.0
# Prefix the Zernio authorization server gives every OAuth access token
# (Schedule-Posts-API app/api/oauth/token/route.ts generateToken("late_at_")).
_OAUTH_ACCESS_TOKEN_PREFIX = "late_at_"
_VERIFY_KEEPALIVE_SECONDS = 60.0
_IN_FLIGHT: dict[str, "asyncio.Task[Verification]"] = {}
# Only used when upstream could not answer. Blast radius is bounded to
Expand Down Expand Up @@ -138,6 +148,12 @@ def _classify(status_code: int) -> Verification:
return Verification.UNKNOWN


def _fresh_ttl(token: str) -> float:
if token.startswith(_OAUTH_ACCESS_TOKEN_PREFIX):
return _OAUTH_FRESH_TTL_SECONDS
return _FRESH_TTL_SECONDS


def token_cache_key(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()

Expand Down Expand Up @@ -263,7 +279,7 @@ async def verify_token(self, token: str) -> AccessToken | None:
now = time.monotonic()
verified_at = _VERIFIED_AT.get(token_key)

if verified_at is not None and now - verified_at < _FRESH_TTL_SECONDS:
if verified_at is not None and now - verified_at < _fresh_ttl(token):
_touch(token_key)
return self._grant(token, resolved_by="cache")

Expand Down
91 changes: 91 additions & 0 deletions tests/test_mcp_auth_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import httpx
import pytest
from starlette.authentication import AuthenticationError

from late.mcp import auth, server
from late.mcp.auth import ZernioTokenVerifier
Expand Down Expand Up @@ -207,3 +208,93 @@ async def test_an_api_key_grant_has_no_scope_claim():

assert granted is not None
assert "scope" not in granted.claims


class CountingUpstream:
def __init__(self, response: httpx.Response | Exception) -> None:
self.calls = 0
self.response = response

def __call__(self, _request: httpx.Request) -> httpx.Response:
self.calls += 1
if isinstance(self.response, Exception):
raise self.response
return self.response


def _verifier_counting(
response: httpx.Response | Exception,
) -> tuple[ZernioTokenVerifier, CountingUpstream]:
upstream = CountingUpstream(response)
client = httpx.AsyncClient(transport=httpx.MockTransport(upstream))
return ZernioTokenVerifier(client=client), upstream


def _verified_seconds_ago(token: str, seconds: float) -> None:
auth._VERIFIED_AT[auth.token_cache_key(token)] = time.monotonic() - seconds


async def test_an_oauth_token_verified_under_a_minute_ago_is_served_from_cache():
verifier, upstream = _verifier_counting(httpx.Response(200))
_verified_seconds_ago("late_at_live", 50)

granted = await verifier.verify_token("late_at_live")

assert granted is not None
assert granted.claims["resolved_by"] == "cache"
assert upstream.calls == 0


async def test_an_oauth_token_is_asked_about_again_after_a_minute():
verifier, upstream = _verifier_counting(httpx.Response(200))
_verified_seconds_ago("late_at_live", 61)

granted = await verifier.verify_token("late_at_live")

assert granted is not None
assert granted.claims["resolved_by"] == "upstream"
assert upstream.calls == 1


async def test_an_api_key_keeps_its_ten_minute_cache():
verifier, upstream = _verifier_counting(httpx.Response(200))
_verified_seconds_ago("sk_live", 61)

assert (await verifier.verify_token("sk_live")).claims["resolved_by"] == "cache"
assert upstream.calls == 0

_verified_seconds_ago("sk_live", 601)

assert (await verifier.verify_token("sk_live")).claims["resolved_by"] == "upstream"
assert upstream.calls == 1


async def test_a_revoked_oauth_token_is_refused_on_the_first_call_after_its_minute():
verifier, upstream = _verifier_counting(httpx.Response(401))
_verified_seconds_ago("late_at_revoked", 61)

assert await verifier.verify_token("late_at_revoked") is None
assert upstream.calls == 1
assert auth.token_cache_key("late_at_revoked") not in auth._VERIFIED_AT


@pytest.mark.parametrize(
"response", [httpx.ConnectTimeout("verify timed out"), httpx.Response(503)]
)
async def test_an_oauth_token_past_its_minute_keeps_the_outage_grace(response):
verifier, upstream = _verifier_counting(response)
_verified_seconds_ago("late_at_live", 1800)

granted = await verifier.verify_token("late_at_live")

assert granted is not None
assert granted.claims["resolved_by"] == "grace"
assert upstream.calls == 1


async def test_an_oauth_token_past_the_outage_grace_is_not_granted():
verifier, _ = _verifier_counting(httpx.Response(503))
_verified_seconds_ago("late_at_live", 3601)

with pytest.raises(AuthenticationError):
await verifier.verify_token("late_at_live")
Loading