π The fast, Pythonic way to build MCP servers and clients.
fix(oauth-proxy): answer a repeated consent approval with the same redirect (#5775)
James Maidment60cba2394334
diff --git a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/consent.py b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/consent.pyindex d201cd38c..a63090ea9 100644--- a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/consent.py+++ b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/consent.py@@ -22,6 +22,7 @@ from starlette.responses import HTMLResponse, RedirectResponsefrom fastmcp.server.auth.oauth_proxy.models import (ConsentCSRFToken,+ OAuthTransaction,ProxyDCRClient,_hash_token,)@@ -126,6 +127,21 @@ class ConsentMixin:return self._upstream_client_secret.get_secret_value().encode()return self._jwt_signing_key+ def _consent_token_for(self: OAuthProxy, csrf_token: str) -> str:+ """Consent binding token for an approval made with `csrf_token`.++ Derived rather than random so that every submit of the same form yields+ the same binding. A double-clicked Approve sends two submits that can+ overlap in any order, and the browser keeps whichever binding cookie it+ applies last; with a fresh token per submit, that cookie could disagree+ with the one the transaction stored, and the callback would reject the+ flow. Keyed with the cookie signing key, so only the server can compute+ it, even from a known CSRF token.+ """+ key = self._cookie_signing_key()+ message = f"consent-binding:{csrf_token}".encode()+ return hmac.new(key, message, hashlib.sha256).hexdigest()+def _sign_cookie(self: OAuthProxy, payload: str) -> str:"""Sign a cookie payload with HMAC-SHA256.@@ -579,6 +595,64 @@ class ConsentMixin:self._expire_cookie(response, name)return response+ async def _approve_consent(+ self: OAuthProxy,+ request: Request,+ txn_id: str,+ txn_model: OAuthTransaction,+ csrf_token: str,+ *,+ legacy_csrf: bool,+ ) -> RedirectResponse:+ """Record this browser's approval of a transaction and redirect upstream.++ Repeating an approval with the same form is answered exactly as the+ approval was, since the consent token is derived from the CSRF token.+ """+ txn = txn_model.model_dump()+ consent_token = self._consent_token_for(csrf_token)+ # A page rendered before the CSRF store kept its token on the+ # transaction. Retire it there along with the approval, so a repeat+ # of this submit is recognised as a repeat rather than a new approval.+ retire_legacy = legacy_csrf and txn_model.csrf_token is not None+ if txn_model.consent_token != consent_token or retire_legacy:+ txn_model.consent_token = consent_token+ if retire_legacy:+ txn_model.csrf_token = None+ txn_model.csrf_expires_at = None+ await self._transaction_store.put(key=txn_id, value=txn_model, ttl=15 * 60)++ upstream_url = self._build_upstream_authorize_url(txn_id, txn)+ response = RedirectResponse(url=upstream_url, status_code=302)++ # Only persist the approval for future silent consent in "remember"+ # mode; in the default "always" mode the cookie would never be read.+ if self._require_authorization_consent == "remember":+ client_key = self._make_client_key(+ txn["client_id"], txn["client_redirect_uri"]+ )+ approved = list(self._decode_list_cookie(request, "MCP_APPROVED_CLIENTS"))+ if client_key in approved:+ approved.remove(client_key)+ approved.append(client_key)+ approved = approved[-_MAX_REMEMBERED_CLIENTS:]+ self._set_list_cookie(+ response,+ "MCP_APPROVED_CLIENTS",+ self._encode_list_cookie(approved),+ max_age=365 * 24 * 3600,+ )++ # Retire this transaction's consent state, both halves of it: the+ # stored token so it cannot be replayed, and the cookies that+ # carried it. Other pending flows are left alone.+ await self._consent_csrf_store.delete(key=_hash_token(csrf_token))+ self._clear_consent_state_for_transaction(+ request, response, txn_id, include_legacy=legacy_csrf+ )+ self._set_consent_binding_cookie(response, txn_id, consent_token)+ return response+async def _submit_consent(self: OAuthProxy, request: Request) -> RedirectResponse | HTMLResponse:@@ -627,7 +701,48 @@ class ConsentMixin:)legacy_csrf = csrf_valid+ state_entry = self._read_consent_state_cookies(request).get(+ self._cookie_name(_consent_state_base_name(csrf_token))+ )+ holds_state_cookie = state_entry is not None and hmac.compare_digest(+ state_entry[0], txn_id+ )+ holds_legacy_cookie = bool(csrf_token) and csrf_token in (+ self._decode_list_cookie(request, _CONSENT_STATE_COOKIE_BASE)+ )+if not csrf_valid:+ # Approving retires the token, so a double-clicked Approve sends a+ # second submit the token no longer covers, and the browser shows+ # the response to that one rather than following the first one's+ # redirect. If this token made the approval, and this browser proves+ # it holds the form, with the state cookie the approval clears or+ # the binding cookie it sets (whichever it holds depends on whether+ # the first response arrived first), answer the repeat the way the+ # approval was answered.+ consent_token = txn_model.consent_token+ if (+ action == "approve"+ and csrf_token+ and consent_token is not None+ and hmac.compare_digest(+ consent_token, self._consent_token_for(csrf_token)+ )+ and (+ holds_state_cookie+ or holds_legacy_cookie+ or self._verify_consent_binding_cookie(+ request, txn_id, consent_token+ )+ )+ ):+ return await self._approve_consent(+ request,+ txn_id,+ txn_model,+ csrf_token,+ legacy_csrf=holds_legacy_cookie,+ )return create_secure_html_response("<h1>Error</h1><p>Invalid or expired consent token</p>", status_code=400)@@ -636,15 +751,7 @@ class ConsentMixin:# Without this, an attacker who knows their own tx_id/csrf_token can# CSRF the victim's browser into approving consent, bypassing the# consent binding cookie protection.- if legacy_csrf:- cookie_ok = csrf_token in self._decode_list_cookie(- request, _CONSENT_STATE_COOKIE_BASE- )- else:- entry = self._read_consent_state_cookies(request).get(- self._cookie_name(_consent_state_base_name(csrf_token))- )- cookie_ok = entry is not None and hmac.compare_digest(entry[0], txn_id)+ cookie_ok = holds_legacy_cookie if legacy_csrf else holds_state_cookieif not cookie_ok:logger.warning("CSRF double-submit check failed for transaction %s "@@ -662,41 +769,11 @@ class ConsentMixin:remember_mode = self._require_authorization_consent == "remember"if action == "approve":- consent_token = secrets.token_urlsafe(32)- txn_model.consent_token = consent_token- await self._transaction_store.put(key=txn_id, value=txn_model, ttl=15 * 60)-- upstream_url = self._build_upstream_authorize_url(txn_id, txn)- response = RedirectResponse(url=upstream_url, status_code=302)-- # Only persist the approval for future silent consent in "remember"- # mode; in the default "always" mode the cookie would never be read.- if remember_mode:- approved = list(- self._decode_list_cookie(request, "MCP_APPROVED_CLIENTS")- )- if client_key in approved:- approved.remove(client_key)- approved.append(client_key)- approved = approved[-_MAX_REMEMBERED_CLIENTS:]- self._set_list_cookie(- response,- "MCP_APPROVED_CLIENTS",- self._encode_list_cookie(approved),- max_age=365 * 24 * 3600,- )-- # Retire this transaction's consent state, both halves of it: the- # stored token so it cannot be replayed, and the cookies that- # carried it. Other pending flows are left alone.- await self._consent_csrf_store.delete(key=_hash_token(csrf_token))- self._clear_consent_state_for_transaction(- request, response, txn_id, include_legacy=legacy_csrf+ return await self._approve_consent(+ request, txn_id, txn_model, csrf_token, legacy_csrf=legacy_csrf)- self._set_consent_binding_cookie(response, txn_id, consent_token)- return response- elif action == "deny":+ if action == "deny":if not self._validate_client_redirect_uri(txn["client_redirect_uri"]):logger.warning("Blocked consent denial redirect to disallowed URI for transaction %s",diff --git a/tests/server/auth/test_oauth_consent_flow.py b/tests/server/auth/test_oauth_consent_flow.pyindex 51e57d90e..9e11af3f1 100644--- a/tests/server/auth/test_oauth_consent_flow.py+++ b/tests/server/auth/test_oauth_consent_flow.py@@ -16,6 +16,7 @@ import asyncioimport reimport secretsimport time+from collections.abc import Mappingfrom urllib.parse import parse_qs, urlparseimport httpx@@ -25,6 +26,7 @@ from mcp.server.auth.provider import AuthorizationParamsfrom mcp.shared.auth import OAuthClientInformationFullfrom pydantic import AnyUrlfrom starlette.applications import Starlette+from starlette.requests import Requestfrom starlette.testclient import TestClientfrom fastmcp.server.auth.auth import AccessToken, TokenVerifier@@ -712,6 +714,303 @@ class TestConcurrentConsentRenders:assert response.status_code == 302+async def _assert_responses_bind_to_transaction(+ proxy: OAuthProxy, txn_id: str, *set_cookies: Mapping[str, str]+) -> None:+ """Each response's binding cookie matches the token the callback checks."""+ txn = await proxy._transaction_store.get(key=txn_id)+ assert txn is not None+ assert txn.consent_token+ for response_cookies in set_cookies:+ cookies = "; ".join(f"{k}={v}" for k, v in response_cookies.items())+ request = Request({"type": "http", "headers": [(b"cookie", cookies.encode())]})+ assert proxy._verify_consent_binding_cookie(request, txn_id, txn.consent_token)+++class TestRepeatedConsentSubmit:+ """Submitting the consent form again after approving it."""++ async def test_resubmitted_approval_redirects_to_upstream_again(+ self, oauth_proxy_with_storage+ ):+ """A double-click on Approve must not end the flow on an error page.++ Approving retires the CSRF token, so a second submit of the same form+ used to fail with "Invalid or expired consent token". A browser shows+ the response to the last submit, so the user lands on that error even+ though the first submit was accepted and the flow is still valid.+ """+ txn_id, _ = await _start_flow(+ oauth_proxy_with_storage,+ "double-submit-client",+ "http://localhost:9090/callback",+ )++ app = Starlette(routes=oauth_proxy_with_storage.get_routes())+ with TestClient(app, base_url="https://myserver.com") as browser:+ csrf = _extract_csrf(browser.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}++ first = browser.post("/consent", data=form, follow_redirects=False)+ second = browser.post("/consent", data=form, follow_redirects=False)++ assert first.status_code == 302+ assert second.status_code == 302+ assert second.headers["location"] == first.headers["location"]++ async def test_repeat_sent_before_the_first_response_arrives(+ self, oauth_proxy_with_storage+ ):+ """A fast double-click: the repeat leaves before the first response lands.++ It carries the browser's cookies as they were before the approval, so no+ binding cookie yet, but still the consent-state cookie the approval would+ have cleared. Whichever response the browser ends up applying, its binding+ must match the consent token the callback will check.+ """+ proxy = oauth_proxy_with_storage+ txn_id, _ = await _start_flow(+ proxy, "double-submit-fast", "http://localhost:9090/callback"+ )++ app = Starlette(routes=proxy.get_routes())+ with TestClient(app, base_url="https://myserver.com") as browser:+ csrf = _extract_csrf(browser.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ cookies_before_approval = dict(browser.cookies)+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}++ first = browser.post("/consent", data=form, follow_redirects=False)++ with TestClient(+ app, base_url="https://myserver.com", cookies=cookies_before_approval+ ) as same_browser_earlier:+ second = same_browser_earlier.post(+ "/consent", data=form, follow_redirects=False+ )++ assert first.status_code == 302+ assert second.status_code == 302+ assert second.headers["location"] == first.headers["location"]++ await _assert_responses_bind_to_transaction(+ proxy, txn_id, first.cookies, second.cookies+ )++ async def test_overlapping_approvals_bind_to_the_same_token(+ self, oauth_proxy_with_storage+ ):+ """Two submits that both read the CSRF token before either retires it.++ Neither is a repeat as far as the handler can tell, since the token is+ valid for both. Whichever stores its approval last and whichever+ response the browser applies last, the binding must still match.+ """+ proxy = oauth_proxy_with_storage+ txn_id, _ = await _start_flow(+ proxy, "double-submit-overlap", "http://localhost:9090/callback"+ )++ app = Starlette(routes=proxy.get_routes())+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="https://myserver.com",+ ) as browser:+ csrf = _extract_csrf((await browser.get(f"/consent?txn_id={txn_id}")).text)+ assert csrf+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}++ gate = _RenderGate(2)+ original_get = proxy._consent_csrf_store.get++ async def gated_get(*args, **kwargs):+ result = await original_get(*args, **kwargs)+ await gate.wait()+ return result++ proxy._consent_csrf_store.get = gated_get+ first, second = await asyncio.gather(+ browser.post("/consent", data=form),+ browser.post("/consent", data=form),+ )++ assert first.status_code == 302+ assert second.status_code == 302+ assert second.headers["location"] == first.headers["location"]+ await _assert_responses_bind_to_transaction(+ proxy, txn_id, first.cookies, second.cookies+ )++ @pytest.mark.parametrize("repeat_before_first_response", [True, False])+ async def test_repeat_of_a_page_rendered_before_the_csrf_store(+ self, oauth_proxy_with_storage, repeat_before_first_response+ ):+ """A form rendered by an older version keeps its token on the transaction.++ That token stays valid after approval unless the approval retires it,+ and a repeat that still finds it valid would be treated as a fresh+ approval. The repeat must bind to the same token either way.+ """+ proxy = oauth_proxy_with_storage+ txn_id, _ = await _start_flow(+ proxy, "double-submit-legacy", "http://localhost:9090/callback"+ )+ csrf = "token-rendered-before-upgrade"+ txn_model = await proxy._transaction_store.get(key=txn_id)+ assert txn_model is not None+ txn_model.csrf_token = csrf+ txn_model.csrf_expires_at = time.time() + 15 * 60+ await proxy._transaction_store.put(key=txn_id, value=txn_model, ttl=15 * 60)++ app = Starlette(routes=proxy.get_routes())+ legacy_cookie = {+ proxy._cookie_name(_CONSENT_STATE_COOKIE_BASE): proxy._encode_list_cookie(+ [csrf]+ )+ }+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}+ with TestClient(+ app, base_url="https://myserver.com", cookies=legacy_cookie+ ) as browser:+ first = browser.post("/consent", data=form, follow_redirects=False)+ # Before the first response, the repeat carries the cookies the+ # browser had when it rendered the form.+ repeater = (+ TestClient(app, base_url="https://myserver.com", cookies=legacy_cookie)+ if repeat_before_first_response+ else browser+ )+ second = repeater.post("/consent", data=form, follow_redirects=False)++ assert first.status_code == 302+ assert second.status_code == 302+ assert second.headers["location"] == first.headers["location"]+ await _assert_responses_bind_to_transaction(+ proxy, txn_id, first.cookies, second.cookies+ )++ async def test_repeat_remembers_the_client_like_the_approval(+ self, oauth_proxy_https_remember+ ):+ """In "remember" mode the repeat sets the remembered-client cookie too.++ If the browser follows the repeat's response rather than the approval's,+ the approval's cookie is never applied, and only the repeat can carry it.+ """+ proxy = oauth_proxy_https_remember+ txn_id, _ = await _start_flow(+ proxy, "double-submit-remember", "http://localhost:9090/callback"+ )++ app = Starlette(routes=proxy.get_routes())+ with TestClient(app, base_url="https://myserver.example") as browser:+ csrf = _extract_csrf(browser.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ cookies_before_approval = dict(browser.cookies)+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}+ browser.post("/consent", data=form, follow_redirects=False)++ with TestClient(+ app, base_url="https://myserver.example", cookies=cookies_before_approval+ ) as same_browser_earlier:+ repeat = same_browser_earlier.post(+ "/consent", data=form, follow_redirects=False+ )++ assert repeat.status_code == 302+ assert "__Host-MCP_APPROVED_CLIENTS" in repeat.cookies++ async def test_spent_token_does_not_approve_an_unapproved_transaction(+ self, oauth_proxy_with_storage+ ):+ """The state cookie alone is not enough: the transaction must be approved.++ A token spent on a denial leaves its state cookie in a browser that sends+ the request before the denial response arrives, but nothing was approved,+ so there is nothing to repeat.+ """+ txn_id, _ = await _start_flow(+ oauth_proxy_with_storage,+ "double-submit-denied-then-approved",+ "http://localhost:9090/callback",+ )++ app = Starlette(routes=oauth_proxy_with_storage.get_routes())+ with TestClient(app, base_url="https://myserver.com") as browser:+ csrf = _extract_csrf(browser.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ cookies_before_denial = dict(browser.cookies)+ denied = browser.post(+ "/consent",+ data={"action": "deny", "txn_id": txn_id, "csrf_token": csrf},+ follow_redirects=False,+ )++ with TestClient(+ app, base_url="https://myserver.com", cookies=cookies_before_denial+ ) as same_browser_earlier:+ approved = same_browser_earlier.post(+ "/consent",+ data={"action": "approve", "txn_id": txn_id, "csrf_token": csrf},+ follow_redirects=False,+ )++ assert denied.status_code == 302+ assert approved.status_code == 400++ async def test_resubmitted_token_rejected_without_this_browsers_approval(+ self, oauth_proxy_with_storage+ ):+ """Only the browser that approved can repeat the approval.++ The redirect is re-issued on the strength of the consent binding cookie+ the approval set, not the spent token, so another browser holding that+ token still gets nothing.+ """+ txn_id, _ = await _start_flow(+ oauth_proxy_with_storage,+ "double-submit-other-browser",+ "http://localhost:9090/callback",+ )++ app = Starlette(routes=oauth_proxy_with_storage.get_routes())+ with TestClient(app, base_url="https://myserver.com") as approver:+ csrf = _extract_csrf(approver.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ form = {"action": "approve", "txn_id": txn_id, "csrf_token": csrf}+ assert (+ approver.post("/consent", data=form, follow_redirects=False).status_code+ == 302+ )++ with TestClient(app, base_url="https://myserver.com") as other:+ other.get(f"/consent?txn_id={txn_id}")+ response = other.post("/consent", data=form, follow_redirects=False)+ assert response.status_code == 400+ assert "Invalid or expired consent token" in response.text++ async def test_resubmitted_denial_is_still_rejected(self, oauth_proxy_with_storage):+ """A denial is not repeated: nothing was approved for this browser."""+ txn_id, _ = await _start_flow(+ oauth_proxy_with_storage,+ "double-submit-deny",+ "http://localhost:9090/callback",+ )++ app = Starlette(routes=oauth_proxy_with_storage.get_routes())+ with TestClient(app, base_url="https://myserver.com") as browser:+ csrf = _extract_csrf(browser.get(f"/consent?txn_id={txn_id}").text)+ assert csrf+ form = {"action": "deny", "txn_id": txn_id, "csrf_token": csrf}++ first = browser.post("/consent", data=form, follow_redirects=False)+ second = browser.post("/consent", data=form, follow_redirects=False)++ assert first.status_code == 302+ assert second.status_code == 400++class TestConsentStateCookieScope:"""Consent state is per transaction and bounded."""