Answer rate-limited requests with 429 and Retry-After, not 401 invalid_token #126

Closed
opened 2026-11-02 02:09:33 +00:00 by piers · 2 comments
Owner

Problem

FileTokenVerifier.verify_token returns None when the per-token bucket is empty, so FastMCP answers 401 invalid_token for a rate-limited request. A valid client cannot tell "wrong token" from "slow down": People Mind's mailmind Source classified it as mailmind-auth and gave up on every pass (dev/people-mind-mcp#35; 20 mail_changes pages in 0.58 s against the defaults rate_per_second = 5.0, rate_burst = 20). The API log also prints Auth error returned: invalid_token (status=401) for what is a throttle, which misleads an operator reading it.

Fix

Answer a rate-limited request with 429 Too Many Requests and a Retry-After header (whole seconds until one bucket token refills, minimum 1), and keep 401 for an unknown token. The verifier's contract cannot express 429, so the limiter moves out of verify_token into an ASGI middleware that runs after authentication and keys the bucket on the authenticated token's client_id as today. Log the throttle as rate-limited scope=<client_id> at INFO, counts and codes only.

Acceptance

  • A test with a limiter of burst 2 shows the third request answers 429 with Retry-After, the first two answer 200, and a request with an unknown token still answers 401.
  • tests/test_auth.py keeps the token-bucket unit tests; nothing about scopes changes.
  • No tool, scope, or config change; rate_per_second and rate_burst keep their names and defaults.

Primary files

  • src/mail_mind_mcp/auth.py
  • src/mail_mind_mcp/server.py (build_app)
  • tests/test_auth.py

Blocked by

None.

## Problem `FileTokenVerifier.verify_token` returns `None` when the per-token bucket is empty, so FastMCP answers `401 invalid_token` for a rate-limited request. A valid client cannot tell "wrong token" from "slow down": People Mind's mailmind Source classified it as `mailmind-auth` and gave up on every pass (dev/people-mind-mcp#35; 20 `mail_changes` pages in 0.58 s against the defaults `rate_per_second = 5.0`, `rate_burst = 20`). The API log also prints `Auth error returned: invalid_token (status=401)` for what is a throttle, which misleads an operator reading it. ## Fix Answer a rate-limited request with `429 Too Many Requests` and a `Retry-After` header (whole seconds until one bucket token refills, minimum 1), and keep 401 for an unknown token. The verifier's contract cannot express 429, so the limiter moves out of `verify_token` into an ASGI middleware that runs after authentication and keys the bucket on the authenticated token's `client_id` as today. Log the throttle as `rate-limited scope=<client_id>` at INFO, counts and codes only. ## Acceptance - A test with a limiter of burst 2 shows the third request answers 429 with `Retry-After`, the first two answer 200, and a request with an unknown token still answers 401. - `tests/test_auth.py` keeps the token-bucket unit tests; nothing about scopes changes. - No tool, scope, or config change; `rate_per_second` and `rate_burst` keep their names and defaults. ## Primary files - `src/mail_mind_mcp/auth.py` - `src/mail_mind_mcp/server.py` (`build_app`) - `tests/test_auth.py` ## Blocked by None.
Collaborator

⏸ SVD architect gate: dev/mail-mind-mcp#126 answer-rate-limited-requests-with-429-and-retry-after-not-40

Status: CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity standard · dispatch effort medium

Run: 20261102T023307Z-390c63f8

Held because: CLEAN but 3 open risk(s) (2 verification · 1 decision) — HOLD-ALL parks everything. The risks, verbatim:

Open risks:

  1. The HTTP-level test's request shape was derived from reading the SDK, not executed, because the Half-A sandbox denied the repo's .venv Python. The shape is a raw initialize POST with Accept 'application/json, text/event-stream', expected to answer 200 under stateless_http=True. Check: in the dispatch worktree run uv run python3 -m pytest -q tests/test_auth.py -k rate_limited and see statuses [200, 200, 429] plus a 401 for the unknown token. If initialize does not answer 200, use a request the served fixture already proves and record it in deviations. [verification]
  2. SECURITY.md is not in the issue's three named files. The spec adds a one-row update to its 'Rate limit' row so the security model states 429 + Retry-After. Question: keep the doc row in this PR, or drop it to stay strictly inside the issue's file list? (tests/test_evidence.py is not optional: it calls the changed constructor.) [decision]
  3. Post-deploy end-to-end check: on a People Mind mailmind pass that exceeds the burst, the mail-mind API log shows 'rate-limited scope=<client_id>' at INFO, and no 'Auth error returned: invalid_token (status=401)' line for that token. Client-side retry is dev/people-mind-mcp#35 and is not sequenced behind this. [verification]

Change: 1. Add RateLimiter.take(key, *, now=None) -> int | None in auth.py. It returns None when it consumes a token. Otherwise it returns max(1, ceil((1 - tokens) / rate)). Reimplement allow as take(...) is None.
2. Drop the limiter parameter and the allow check from FileTokenVerifier (auth.py:96-110).
3. Add a pure-ASGI RateLimitMiddleware(app, limiter) in auth.py, mirroring AuthContextMiddleware (mcp/server/auth/middleware/auth_context.py:24-48). When scope['user'] is an AuthenticatedUser, it keys the bucket on user.access_token.client_id. On a throttle it logs INFO 'rate-limited scope=%s' with extra seconds, and answers PlainTextResponse('rate limited', 429, Retry-After=str(wait)). Unauthenticated requests pass through, so RequireAuthMiddleware still answers 401.
4. In build_app (server.py:1105-1115), build FileTokenVerifier(tokens) and pass middleware=[host_check, Middleware(RateLimitMiddleware, limiter=limiter)]. FastMCP 3.4.11 appends user middleware after its AuthenticationMiddleware (fastmcp/server/http.py:650,699-700), so scope['user'] is set when the middleware runs.
5. Update the SECURITY.md:10 row.
6. Rewrite the throttling assertions in test_auth.py::test_verifier and test_evidence.py::test_the_evidence_token_has_its_own_bucket. Add a uvicorn-served burst-2 HTTP test (200, 200, 429 with Retry-After, unknown token 401), mirroring tests/test_server.py:55-89.

Files: src/mail_mind_mcp/auth.py · src/mail_mind_mcp/server.py · tests/test_auth.py · tests/test_evidence.py · SECURITY.md

Decision: accept the 3 open risk(s) above and dispatch this spec (svd:go), or park (svd:skip) / re-spec (svd:respec)?

Your call (when this issue is held at the gate via svd:hold):

  • add label svd:go — approve; Half-B dispatch accepts exactly this spec (open risks accepted)
  • add label svd:fire beside svd:go — approve AND authorise the Half-B fire from the phone; never on its own
  • add label svd:skip — park it; dispatch refuses it and the issue stays for a human
  • add label svd:respec — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context

Spec: /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-answer-rate-limited-requests-with-429-and-retry-after-not-40.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-answer-rate-limited-requests-with-429-and-retry-after-not-40.md

### ⏸ SVD architect gate: dev/mail-mind-mcp#126 answer-rate-limited-requests-with-429-and-retry-after-not-40 **Status:** CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity `standard` · dispatch effort `medium` **Run:** `20261102T023307Z-390c63f8` **Held because:** CLEAN but 3 open risk(s) (2 verification · 1 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. The HTTP-level test's request shape was derived from reading the SDK, not executed, because the Half-A sandbox denied the repo's .venv Python. The shape is a raw `initialize` POST with Accept 'application/json, text/event-stream', expected to answer 200 under stateless_http=True. Check: in the dispatch worktree run `uv run python3 -m pytest -q tests/test_auth.py -k rate_limited` and see statuses [200, 200, 429] plus a 401 for the unknown token. If initialize does not answer 200, use a request the served fixture already proves and record it in deviations. [verification] 2. SECURITY.md is not in the issue's three named files. The spec adds a one-row update to its 'Rate limit' row so the security model states 429 + Retry-After. Question: keep the doc row in this PR, or drop it to stay strictly inside the issue's file list? (tests/test_evidence.py is not optional: it calls the changed constructor.) [decision] 3. Post-deploy end-to-end check: on a People Mind mailmind pass that exceeds the burst, the mail-mind API log shows 'rate-limited scope=<client_id>' at INFO, and no 'Auth error returned: invalid_token (status=401)' line for that token. Client-side retry is dev/people-mind-mcp#35 and is not sequenced behind this. [verification] **Change:** 1. Add RateLimiter.take(key, *, now=None) -> int | None in auth.py. It returns None when it consumes a token. Otherwise it returns max(1, ceil((1 - tokens) / rate)). Reimplement allow as `take(...) is None`. 2. Drop the limiter parameter and the allow check from FileTokenVerifier (auth.py:96-110). 3. Add a pure-ASGI RateLimitMiddleware(app, limiter) in auth.py, mirroring AuthContextMiddleware (mcp/server/auth/middleware/auth_context.py:24-48). When scope['user'] is an AuthenticatedUser, it keys the bucket on user.access_token.client_id. On a throttle it logs INFO 'rate-limited scope=%s' with extra seconds, and answers PlainTextResponse('rate limited', 429, Retry-After=str(wait)). Unauthenticated requests pass through, so RequireAuthMiddleware still answers 401. 4. In build_app (server.py:1105-1115), build FileTokenVerifier(tokens) and pass middleware=[host_check, Middleware(RateLimitMiddleware, limiter=limiter)]. FastMCP 3.4.11 appends user middleware after its AuthenticationMiddleware (fastmcp/server/http.py:650,699-700), so scope['user'] is set when the middleware runs. 5. Update the SECURITY.md:10 row. 6. Rewrite the throttling assertions in test_auth.py::test_verifier and test_evidence.py::test_the_evidence_token_has_its_own_bucket. Add a uvicorn-served burst-2 HTTP test (200, 200, 429 with Retry-After, unknown token 401), mirroring tests/test_server.py:55-89. **Files:** `src/mail_mind_mcp/auth.py` · `src/mail_mind_mcp/server.py` · `tests/test_auth.py` · `tests/test_evidence.py` · `SECURITY.md` **Decision:** accept the 3 open risk(s) above and dispatch this spec (`svd:go`), or park (`svd:skip`) / re-spec (`svd:respec`)? **Your call** (when this issue is held at the gate via `svd:hold`): - add label `svd:go` — approve; Half-B dispatch accepts exactly this spec (open risks accepted) - add label `svd:fire` **beside** `svd:go` — approve AND authorise the Half-B fire from the phone; never on its own - add label `svd:skip` — park it; dispatch refuses it and the issue stays for a human - add label `svd:respec` — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context <sub>Spec: `/Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-answer-rate-limited-requests-with-429-and-retry-after-not-40.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-answer-rate-limited-requests-with-429-and-retry-after-not-40.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/mail-mind-mcp#126 answer-rate-limited-requests-with-429-and-retry-after-not-40 completed integration verify.

  • PR: #127
  • Branch: feat/svd-dev-mail-mind-mcp-126-answer-rate-limited-requests-w-ed8b59de
  • Commit: 0302441ef5
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Check forgejo commit statuses: absent
  • Checks: Remote checks: none reported (Forgejo statuses empty, no CI). Local: 799 passed, 8 skipped; lint, format and mypy clean.
  • Warning: No remote CI exists for this repo; integration truth rests on local runs.
  • Warning: Post-deploy check (open risk 3): confirm 'rate-limited scope=...' INFO lines and no invalid_token 401 for a throttled token.
  • Warning: no CI for forgejo commit statuses: Commit statuses for the PR head are empty and the repo has no CI workflow directory (spec: no .forgejo/.github); no tracking pointer exists. — reported as absent, not blocking (gh#633)
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261102T031327Z-ed8b59de --confirm-merge)
spec-verify-dispatch Half B for dev/mail-mind-mcp#126 answer-rate-limited-requests-with-429-and-retry-after-not-40 completed integration verify. - PR: https://git.groupthink.asia/dev/mail-mind-mcp/pulls/127 - Branch: feat/svd-dev-mail-mind-mcp-126-answer-rate-limited-requests-w-ed8b59de - Commit: 0302441ef503d5a19cb91e6ca55e2c6eb5700e24 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Check forgejo commit statuses: absent - Checks: Remote checks: none reported (Forgejo statuses empty, no CI). Local: 799 passed, 8 skipped; lint, format and mypy clean. - Warning: No remote CI exists for this repo; integration truth rests on local runs. - Warning: Post-deploy check (open risk 3): confirm 'rate-limited scope=...' INFO lines and no invalid_token 401 for a throttled token. - Warning: no CI for forgejo commit statuses: Commit statuses for the PR head are empty and the repo has no CI workflow directory (spec: no .forgejo/.github); no tracking pointer exists. — reported as absent, not blocking (gh#633) - Decision: review the PR and merge? (`codex-svd ship --run-id 20261102T031327Z-ed8b59de --confirm-merge`)
svc-svd-writer 2026-11-02 03:22:56 +00:00
  • closed this issue
  • removed the
    svd:go
    label
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
dev/mail-mind-mcp#126
No description provided.