gabriel / musehub public
test_mcp_rate_limits.py python
130 lines 4.6 KB
Raw
sha256:d7af2b937831db3288db5589530c6c2f8e90f0c2c4efbbeb5dd0577076168b29 fix(mcp): SSE event ids + Last-Event-ID replay (#290); per-… Opus 5.5 minor ⚠ breaking 1 day ago
1 """POST /mcp holds each caller to its own rate limit (musehub#325).
2
3 * anonymous callers: ``settings.mcp_rate_limit_anonymous`` per client IP;
4 * signed humans: ``settings.mcp_rate_limit_human`` per MSign handle;
5 * signed agents: ``settings.mcp_rate_limit_agent`` per MSign handle;
6 * over the limit: ``429`` with ``Retry-After`` and a JSON-RPC error whose ``data.error_code`` is ``rate_limited``.
7
8 In-process, database-free: the real ``/mcp`` router on a bare FastAPI app, the caller identity stubbed.
9 """
10
11 from __future__ import annotations
12
13 from collections.abc import Iterator
14
15 import pytest
16 from fastapi import FastAPI
17 from fastapi.testclient import TestClient
18
19 from musehub.auth.request_signing import MSignContext
20
21 pytestmark = pytest.mark.no_db
22
23 PING = {"jsonrpc": "2.0", "id": 1, "method": "ping"}
24
25
26 def _limit(text: str) -> int:
27 return int(text.split("/", 1)[0])
28
29
30 class _Caller:
31 """The identity ``optional_signed_request`` resolves to; switch it between requests."""
32
33 ctx: MSignContext | None = None
34
35 def __call__(self) -> MSignContext | None:
36 return self.ctx
37
38
39 def _signed(handle: str, *, agent: bool) -> MSignContext:
40 return MSignContext(handle=handle, identity_id=f"id-{handle}", is_agent=agent, is_admin=False)
41
42
43 @pytest.fixture()
44 def caller() -> _Caller:
45 return _Caller()
46
47
48 @pytest.fixture()
49 def client(caller: _Caller) -> Iterator[TestClient]:
50 from musehub.api.routes import mcp as route
51 from musehub.auth.request_signing import optional_signed_request
52 from musehub.rate_limits import limiter
53
54 app = FastAPI()
55 app.state.limiter = limiter
56 app.include_router(route.router)
57 app.dependency_overrides[optional_signed_request] = caller
58 limiter.reset()
59 with TestClient(app) as c:
60 yield c
61 limiter.reset()
62
63
64 def _first_429(client: TestClient, upto: int) -> int | None:
65 for i in range(1, upto + 1):
66 if client.post("/mcp", json=PING).status_code == 429:
67 return i
68 return None
69
70
71 def test_an_anonymous_caller_gets_the_anonymous_limit(client: TestClient) -> None:
72 from musehub.config import settings
73
74 limit = _limit(settings.mcp_rate_limit_anonymous)
75 assert _first_429(client, limit + 5) == limit + 1
76
77
78 def test_the_429_carries_retry_after_and_a_jsonrpc_error_code(client: TestClient) -> None:
79 from musehub.config import settings
80
81 for _ in range(_limit(settings.mcp_rate_limit_anonymous)):
82 assert client.post("/mcp", json=PING).status_code == 200
83 r = client.post("/mcp", json=PING)
84 assert r.status_code == 429
85 assert 1 <= int(r.headers["Retry-After"]) <= 61
86 body = r.json()
87 assert body["jsonrpc"] == "2.0" and body["id"] is None
88 assert body["error"]["code"] == -32000
89 data = body["error"]["data"]
90 assert data["error_code"] == "rate_limited" and data["retry_after"] == int(r.headers["Retry-After"])
91 assert "anonymous" in data["error_message"] and "MSign" in data["hint"]
92
93
94 def test_a_signed_human_gets_the_human_limit_per_handle(client: TestClient, caller: _Caller) -> None:
95 from musehub.config import settings
96
97 limit = _limit(settings.mcp_rate_limit_human)
98 assert limit > _limit(settings.mcp_rate_limit_anonymous)
99 caller.ctx = _signed("human-a", agent=False)
100 assert _first_429(client, limit + 5) == limit + 1
101 caller.ctx = _signed("human-b", agent=False) # same IP, another handle: its own budget
102 assert client.post("/mcp", json=PING).status_code == 200
103 caller.ctx = None # the anonymous per-IP budget is separate from the signed callers' buckets
104 assert client.post("/mcp", json=PING).status_code == 200
105
106
107 def test_a_signed_agent_gets_the_agent_limit_per_handle(
108 client: TestClient, caller: _Caller, monkeypatch: pytest.MonkeyPatch
109 ) -> None:
110 from musehub.api.routes import mcp as route
111 from musehub.config import settings
112
113 assert route._CALLER_LIMITS["agent"] == settings.mcp_rate_limit_agent
114 assert _limit(settings.mcp_rate_limit_agent) > _limit(settings.mcp_rate_limit_human)
115 monkeypatch.setitem(route._CALLER_LIMITS, "agent", "70/minute") # above the human limit, below the per-IP ceiling
116 caller.ctx = _signed("agent-a", agent=True)
117 assert _first_429(client, 75) == 71
118 caller.ctx = _signed("agent-b", agent=True)
119 assert client.post("/mcp", json=PING).status_code == 200
120
121
122 def test_the_per_caller_limits_are_read_from_settings() -> None:
123 from musehub.api.routes import mcp as route
124 from musehub.config import settings
125
126 assert route._CALLER_LIMITS == {
127 "anonymous": settings.mcp_rate_limit_anonymous,
128 "human": settings.mcp_rate_limit_human,
129 "agent": settings.mcp_rate_limit_agent,
130 }
File History 1 commit
sha256:d7af2b937831db3288db5589530c6c2f8e90f0c2c4efbbeb5dd0577076168b29 fix(mcp): SSE event ids + Last-Event-ID replay (#290); per-… Opus 5.5 minor ⚠ 1 day ago