π The fast, Pythonic way to build MCP servers and clients.
Accept WorkOS tokens when required_scopes is set (#5881)
Asem ahmedbffe26eac416
diff --git a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.pyindex b6bd7d6f1..5ba0a9243 100644--- a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py+++ b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py@@ -2390,6 +2390,23 @@ class OAuthProxy(OAuthProvider, ConsentMixin):"expires_at": int(upstream_token_set.expires_at),})+ # A verifier without its own required_scopes (e.g. one that+ # checks an opaque token via userinfo, or an id_token) cannot+ # enforce the provider's required_scopes. Check them here+ # against the patched upstream scopes, so the requirement+ # holds even when an outer layer (e.g. MultiAuth with+ # required_scopes=[]) does not enforce it.+ missing_scopes = (+ set()+ if self._token_validator.required_scopes+ else set(self.required_scopes or []) - set(validated.scopes)+ )+ if missing_scopes:+ logger.debug(+ "Upstream token is missing required scopes: %s",+ sorted(missing_scopes),+ )+ return None# Propagate upstream claims from the verified FastMCP JWT into the# final AccessToken object. This allows subclasses to access customdiff --git a/fastmcp_slim/fastmcp/server/auth/providers/workos.py b/fastmcp_slim/fastmcp/server/auth/providers/workos.pyindex 9f9fef66b..95ca4f266 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/workos.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/workos.py@@ -253,15 +253,20 @@ class WorkOSProvider(OAuthProxy):authkit_domain_final = authkit_domain_str.rstrip("/")scopes_final = (parse_scopes(required_scopes) if required_scopes is not None else []- )+ ) or []valid_scopes_final = (parse_scopes(valid_scopes) if valid_scopes is not None else None)- # Create WorkOS token verifier+ # Do not pass provider-level required_scopes into the verifier here.+ # WorkOS's userinfo endpoint validates opaque access tokens and+ # returns identity claims, but granted scopes are carried reliably in+ # the upstream token response. OAuthProxy stores those scopes, enforces+ # provider.required_scopes against FastMCP-issued tokens, and+ # _uses_alternate_verification() patches the stored upstream scopes+ # onto the returned AccessToken.token_verifier = WorkOSTokenVerifier(authkit_domain=authkit_domain_final,- required_scopes=scopes_final,timeout_seconds=timeout_seconds,http_client=http_client,)@@ -298,6 +303,18 @@ class WorkOSProvider(OAuthProxy):authkit_domain_final,)+ self.required_scopes = scopes_final+ self.update_default_scopes(valid_scopes_final or scopes_final)++ def _uses_alternate_verification(self) -> bool:+ """Patch returned token scopes from the upstream token response.++ WorkOS access tokens are opaque. The userinfo endpoint validates the+ token and returns identity claims, but scope information is carried by+ the token response stored in OAuthProxy's upstream token set.+ """+ return True+class AuthKitProvider(RemoteAuthProvider):"""AuthKit metadata provider for DCR (Dynamic Client Registration).diff --git a/tests/server/auth/providers/test_workos.py b/tests/server/auth/providers/test_workos.pyindex 56f5c740f..9bc645691 100644--- a/tests/server/auth/providers/test_workos.py+++ b/tests/server/auth/providers/test_workos.py@@ -1,5 +1,6 @@"""Tests for WorkOS OAuth provider."""+import timefrom urllib.parse import urlparseimport pytest@@ -9,6 +10,8 @@ from starlette.testclient import TestClientfrom fastmcp import Client, FastMCPfrom fastmcp.client.transports import StreamableHttpTransport+from fastmcp.server.auth import MultiAuth+from fastmcp.server.auth.oauth_proxy.models import JTIMapping, UpstreamTokenSetfrom fastmcp.server.auth.providers.jwt import JWTVerifierfrom fastmcp.server.auth.providers.workos import (AuthKitProvider,@@ -405,3 +408,163 @@ class TestWorkOSTokenVerifierScopes:assert result is not Noneassert result.scopes == ["openid", "profile", "read:secrets"]+++_USERINFO_URL = "https://test.authkit.app/oauth2/userinfo"++# The userinfo response documented by WorkOS carries identity claims only: it+# never reports the scopes the token was granted.+_USERINFO = {+ "sub": "user_123",+ "name": "Leroy Jenkins",+ "given_name": "Leroy",+ "family_name": "Jenkins",+ "email": "[email protected]",+ "email_verified": True,+}++_REQUIRED_SCOPES = ["openid", "profile", "email"]+++class TestWorkOSProviderRequiredScopes:+ """`required_scopes` must hold for tokens whose userinfo has no scope field."""++ @pytest.fixture+ def provider(self, memory_storage: MemoryStore) -> WorkOSProvider:+ provider = WorkOSProvider(+ client_id="test_client",+ client_secret="test_secret",+ authkit_domain="https://test.authkit.app",+ base_url="https://myserver.com",+ required_scopes=_REQUIRED_SCOPES,+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ )+ provider.set_mcp_path("/mcp")+ return provider++ async def _issue_access_token(self, provider: WorkOSProvider, *, scope: str) -> str:+ """Issue a FastMCP token backed by an upstream grant of `scope`."""+ await provider._upstream_token_store.put(+ key="upstream-token-id",+ value=UpstreamTokenSet(+ upstream_token_id="upstream-token-id",+ access_token="upstream-access-token",+ refresh_token=None,+ refresh_token_expires_at=None,+ expires_at=time.time() + 3600,+ token_type="Bearer",+ scope=scope,+ client_id="test_client",+ created_at=time.time(),+ ),+ ttl=3600,+ )+ await provider._jti_mapping_store.put(+ key="access-jti",+ value=JTIMapping(+ jti="access-jti",+ upstream_token_id="upstream-token-id",+ created_at=time.time(),+ ),+ ttl=3600,+ )+ return provider.jwt_issuer.issue_access_token(+ client_id="test_client",+ scopes=scope.split(),+ jti="access-jti",+ expires_in=3600,+ )++ def test_required_scopes_are_enforced_by_the_provider(+ self, provider: WorkOSProvider+ ):+ assert provider.required_scopes == _REQUIRED_SCOPES+ assert provider._token_validator.required_scopes == []+ assert provider._uses_alternate_verification() is True++ def test_required_scopes_default_to_empty(self, memory_storage: MemoryStore):+ provider = WorkOSProvider(+ client_id="test_client",+ client_secret="test_secret",+ authkit_domain="https://test.authkit.app",+ base_url="https://myserver.com",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ )++ assert provider.required_scopes == []+ assert provider._token_validator.required_scopes == []++ def test_advertised_scopes_follow_required_scopes(self, provider: WorkOSProvider):+ reg_options = provider.client_registration_options+ assert reg_options is not None+ assert reg_options.valid_scopes == _REQUIRED_SCOPES+ assert reg_options.default_scopes == _REQUIRED_SCOPES++ async def test_load_access_token_uses_upstream_granted_scopes(+ self, provider: WorkOSProvider, httpx_mock: HTTPXMock+ ):+ httpx_mock.add_response(url=_USERINFO_URL, json=_USERINFO)+ token = await self._issue_access_token(provider, scope="openid profile email")++ result = await provider.load_access_token(token)++ assert result is not None+ assert result.scopes == ["openid", "profile", "email"]++ async def test_load_access_token_rejects_under_scoped_grant(+ self, provider: WorkOSProvider, httpx_mock: HTTPXMock+ ):+ httpx_mock.add_response(url=_USERINFO_URL, json=_USERINFO)+ token = await self._issue_access_token(provider, scope="openid profile")++ assert await provider.load_access_token(token) is None++ async def test_multi_auth_empty_override_keeps_provider_scopes(+ self, provider: WorkOSProvider, httpx_mock: HTTPXMock+ ):+ httpx_mock.add_response(url=_USERINFO_URL, json=_USERINFO)+ auth = MultiAuth(server=provider, required_scopes=[])+ token = await self._issue_access_token(provider, scope="openid profile")++ assert await auth.verify_token(token) is None++ @pytest.mark.parametrize(+ ("granted_scope", "expected_status"),+ [+ ("openid profile email", 200),+ ("openid profile", 401),+ ],+ )+ async def test_http_app_enforces_required_scopes_on_granted_scopes(+ self,+ provider: WorkOSProvider,+ httpx_mock: HTTPXMock,+ granted_scope: str,+ expected_status: int,+ ):+ httpx_mock.add_response(url=_USERINFO_URL, json=_USERINFO)+ app = FastMCP("test", auth=provider).http_app(path="/mcp")+ token = await self._issue_access_token(provider, scope=granted_scope)++ with TestClient(app) as client:+ response = client.post(+ "/mcp",+ headers={+ "Authorization": f"Bearer {token}",+ "Accept": "application/json, text/event-stream",+ },+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "1.0"},+ },+ },+ )++ assert response.status_code == expected_status