|
| 1 | +import time |
| 2 | +from collections.abc import Awaitable, Callable |
| 3 | +from typing import Any |
| 4 | +from uuid import uuid4 |
| 5 | + |
| 6 | +import httpx |
| 7 | +import jwt |
| 8 | +from pydantic import BaseModel, Field |
| 9 | + |
| 10 | +from mcp.client.auth import OAuthClientProvider, OAuthFlowError, OAuthTokenError, TokenStorage |
| 11 | +from mcp.shared.auth import OAuthClientMetadata |
| 12 | + |
| 13 | + |
| 14 | +class JWTParameters(BaseModel): |
| 15 | + """JWT parameters.""" |
| 16 | + |
| 17 | + assertion: str | None = Field( |
| 18 | + default=None, |
| 19 | + description="JWT assertion for JWT authentication. " |
| 20 | + "Will be used instead of generating a new assertion if provided.", |
| 21 | + ) |
| 22 | + |
| 23 | + issuer: str | None = Field(default=None, description="Issuer for JWT assertions.") |
| 24 | + subject: str | None = Field(default=None, description="Subject identifier for JWT assertions.") |
| 25 | + audience: str | None = Field(default=None, description="Audience for JWT assertions.") |
| 26 | + claims: dict[str, Any] | None = Field(default=None, description="Additional claims for JWT assertions.") |
| 27 | + jwt_signing_algorithm: str | None = Field(default="RS256", description="Algorithm for signing JWT assertions.") |
| 28 | + jwt_signing_key: str | None = Field(default=None, description="Private key for JWT signing.") |
| 29 | + jwt_lifetime_seconds: int = Field(default=300, description="Lifetime of generated JWT in seconds.") |
| 30 | + |
| 31 | + def to_assertion(self, with_audience_fallback: str | None = None) -> str: |
| 32 | + if self.assertion is not None: |
| 33 | + # Prebuilt JWT (e.g. acquired out-of-band) |
| 34 | + assertion = self.assertion |
| 35 | + else: |
| 36 | + if not self.jwt_signing_key: |
| 37 | + raise OAuthFlowError("Missing signing key for JWT bearer grant") |
| 38 | + if not self.issuer: |
| 39 | + raise OAuthFlowError("Missing issuer for JWT bearer grant") |
| 40 | + if not self.subject: |
| 41 | + raise OAuthFlowError("Missing subject for JWT bearer grant") |
| 42 | + |
| 43 | + audience = self.audience if self.audience else with_audience_fallback |
| 44 | + if not audience: |
| 45 | + raise OAuthFlowError("Missing audience for JWT bearer grant") |
| 46 | + |
| 47 | + now = int(time.time()) |
| 48 | + claims: dict[str, Any] = { |
| 49 | + "iss": self.issuer, |
| 50 | + "sub": self.subject, |
| 51 | + "aud": audience, |
| 52 | + "exp": now + self.jwt_lifetime_seconds, |
| 53 | + "iat": now, |
| 54 | + "jti": str(uuid4()), |
| 55 | + } |
| 56 | + claims.update(self.claims or {}) |
| 57 | + |
| 58 | + assertion = jwt.encode( |
| 59 | + claims, |
| 60 | + self.jwt_signing_key, |
| 61 | + algorithm=self.jwt_signing_algorithm or "RS256", |
| 62 | + ) |
| 63 | + return assertion |
| 64 | + |
| 65 | + |
| 66 | +class RFC7523OAuthClientProvider(OAuthClientProvider): |
| 67 | + """OAuth client provider for RFC7532 clients.""" |
| 68 | + |
| 69 | + jwt_parameters: JWTParameters | None = None |
| 70 | + |
| 71 | + def __init__( |
| 72 | + self, |
| 73 | + server_url: str, |
| 74 | + client_metadata: OAuthClientMetadata, |
| 75 | + storage: TokenStorage, |
| 76 | + redirect_handler: Callable[[str], Awaitable[None]] | None = None, |
| 77 | + callback_handler: Callable[[], Awaitable[tuple[str, str | None]]] | None = None, |
| 78 | + timeout: float = 300.0, |
| 79 | + jwt_parameters: JWTParameters | None = None, |
| 80 | + ) -> None: |
| 81 | + super().__init__(server_url, client_metadata, storage, redirect_handler, callback_handler, timeout) |
| 82 | + self.jwt_parameters = jwt_parameters |
| 83 | + |
| 84 | + async def _exchange_token_authorization_code( |
| 85 | + self, auth_code: str, code_verifier: str, *, token_data: dict[str, Any] | None = None |
| 86 | + ) -> httpx.Request: |
| 87 | + """Build token exchange request for authorization_code flow.""" |
| 88 | + token_data = token_data or {} |
| 89 | + if self.context.client_metadata.token_endpoint_auth_method == "private_key_jwt": |
| 90 | + self._add_client_authentication_jwt(token_data=token_data) |
| 91 | + return await super()._exchange_token_authorization_code(auth_code, code_verifier, token_data=token_data) |
| 92 | + |
| 93 | + async def _perform_authorization(self) -> httpx.Request: |
| 94 | + """Perform the authorization flow.""" |
| 95 | + if "urn:ietf:params:oauth:grant-type:jwt-bearer" in self.context.client_metadata.grant_types: |
| 96 | + token_request = await self._exchange_token_jwt_bearer() |
| 97 | + return token_request |
| 98 | + else: |
| 99 | + return await super()._perform_authorization() |
| 100 | + |
| 101 | + def _add_client_authentication_jwt(self, *, token_data: dict[str, Any]): |
| 102 | + """Add JWT assertion for client authentication to token endpoint parameters.""" |
| 103 | + if not self.jwt_parameters: |
| 104 | + raise OAuthTokenError("Missing JWT parameters for private_key_jwt flow") |
| 105 | + if not self.context.oauth_metadata: |
| 106 | + raise OAuthTokenError("Missing OAuth metadata for private_key_jwt flow") |
| 107 | + |
| 108 | + # We need to set the audience to the issuer identifier of the authorization server |
| 109 | + # https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rfc7523bis-01#name-updates-to-rfc-7523 |
| 110 | + issuer = str(self.context.oauth_metadata.issuer) |
| 111 | + assertion = self.jwt_parameters.to_assertion(with_audience_fallback=issuer) |
| 112 | + |
| 113 | + # When using private_key_jwt, in a client_credentials flow, we use RFC 7523 Section 2.2 |
| 114 | + token_data["client_assertion"] = assertion |
| 115 | + token_data["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" |
| 116 | + # We need to set the audience to the resource server, the audience is difference from the one in claims |
| 117 | + # it represents the resource server that will validate the token |
| 118 | + token_data["audience"] = self.context.get_resource_url() |
| 119 | + |
| 120 | + async def _exchange_token_jwt_bearer(self) -> httpx.Request: |
| 121 | + """Build token exchange request for JWT bearer grant.""" |
| 122 | + if not self.context.client_info: |
| 123 | + raise OAuthFlowError("Missing client info") |
| 124 | + if not self.jwt_parameters: |
| 125 | + raise OAuthFlowError("Missing JWT parameters") |
| 126 | + if not self.context.oauth_metadata: |
| 127 | + raise OAuthTokenError("Missing OAuth metadata") |
| 128 | + |
| 129 | + # We need to set the audience to the issuer identifier of the authorization server |
| 130 | + # https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rfc7523bis-01#name-updates-to-rfc-7523 |
| 131 | + issuer = str(self.context.oauth_metadata.issuer) |
| 132 | + assertion = self.jwt_parameters.to_assertion(with_audience_fallback=issuer) |
| 133 | + |
| 134 | + token_data = { |
| 135 | + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", |
| 136 | + "assertion": assertion, |
| 137 | + } |
| 138 | + |
| 139 | + if self.context.should_include_resource_param(self.context.protocol_version): |
| 140 | + token_data["resource"] = self.context.get_resource_url() |
| 141 | + |
| 142 | + if self.context.client_metadata.scope: |
| 143 | + token_data["scope"] = self.context.client_metadata.scope |
| 144 | + |
| 145 | + token_url = self._get_token_endpoint() |
| 146 | + return httpx.Request( |
| 147 | + "POST", token_url, data=token_data, headers={"Content-Type": "application/x-www-form-urlencoded"} |
| 148 | + ) |
0 commit comments