diff --git a/packages/oauth/src/keycardai/oauth/__init__.py b/packages/oauth/src/keycardai/oauth/__init__.py index a0fc6d3..937a64d 100644 --- a/packages/oauth/src/keycardai/oauth/__init__.py +++ b/packages/oauth/src/keycardai/oauth/__init__.py @@ -32,6 +32,7 @@ """ from .client import AsyncClient, Client +from .client_auth import ClientAuthentication, ClientAuthenticator from .exceptions import ( PERMANENT_ERROR_CODES, AuthenticationError, @@ -119,6 +120,9 @@ "TokenTypeHint", "PKCECodeChallengeMethod", "WellKnownEndpoint", + # === Client Authentication === + "ClientAuthentication", + "ClientAuthenticator", # === HTTP Auth Strategies === "AuthStrategy", "BasicAuth", diff --git a/packages/oauth/src/keycardai/oauth/client_auth.py b/packages/oauth/src/keycardai/oauth/client_auth.py new file mode 100644 index 0000000..ec63242 --- /dev/null +++ b/packages/oauth/src/keycardai/oauth/client_auth.py @@ -0,0 +1,72 @@ +"""Client authentication, an optional capability of a credential. + +A credential that implements ClientAuthenticator returns the headers and +form fields that authenticate the client on one request. The capability is +separate from ApplicationCredential, so a credential implemented outside the +SDK does not need it. +""" + +from dataclasses import dataclass, field +from typing import Protocol, runtime_checkable + +from .exceptions import ConfigError + + +@dataclass(frozen=True) +class ClientAuthentication: + """Headers and form fields that authenticate the client on one request. + + Holds only client authentication. It never includes a grant parameter + such as ``grant_type`` or ``subject_token_type``. + + Both fields hold secrets, such as a Basic header or a client assertion, + so ``repr()`` leaves them out. + """ + + headers: dict[str, str] = field(default_factory=dict, repr=False) + form_fields: dict[str, str] = field(default_factory=dict, repr=False) + + +@runtime_checkable +class ClientAuthenticator(Protocol): + """A credential that can authenticate the client on any endpoint. + + A credential may also define ``check_client_authentication()``, which + raises ConfigError when the credential cannot authenticate the client. + require_client_authenticator calls it. + """ + + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + """Return the client authentication for one request. + + Call it once per request. An assertion-based credential signs or + fetches a new assertion on every call. + + Args: + issuer: The zone's issuer. A multi-zone credential selects its + zone by it and fails for an unknown zone. + endpoint: The URL the request goes to. An assertion-based + credential signs it as the assertion's ``aud``. + """ + ... + + +def require_client_authenticator(credential: object) -> ClientAuthenticator: + """Return ``credential`` as a ClientAuthenticator. + + Call it before sending any request. + + Raises: + ConfigError: The credential does not provide client authentication, + or its ``check_client_authentication()`` raised. + """ + if not isinstance(credential, ClientAuthenticator): + raise ConfigError( + f"{type(credential).__name__} does not provide client authentication" + ) + check = getattr(credential, "check_client_authentication", None) + if callable(check): + check() + return credential diff --git a/packages/oauth/src/keycardai/oauth/server/credentials.py b/packages/oauth/src/keycardai/oauth/server/credentials.py index a0628ad..b419ba0 100644 --- a/packages/oauth/src/keycardai/oauth/server/credentials.py +++ b/packages/oauth/src/keycardai/oauth/server/credentials.py @@ -29,9 +29,11 @@ AuthStrategy, BasicAuth, ClientConfig, + ConfigError, MultiZoneBasicAuth, NoneAuth, ) +from keycardai.oauth.client_auth import ClientAuthentication from keycardai.oauth.types.models import JsonWebKeySet, TokenExchangeRequest from keycardai.oauth.types.oauth import GrantType, TokenEndpointAuthMethod @@ -40,6 +42,7 @@ CredentialDiscoveryError, EKSWorkloadIdentityConfigurationError, EKSWorkloadIdentityRuntimeError, + WebIdentityConfigurationError, WorkloadIdentityConfigurationError, WorkloadIdentityRuntimeError, ) @@ -64,6 +67,10 @@ class ApplicationCredential(Protocol): Application credential providers are responsible for preparing token exchange requests with the appropriate authentication parameters based on the workload's credential type (none, private key JWT, cloud workload identity, etc.). + + Client authentication is a separate, optional capability: + keycardai.oauth.client_auth.ClientAuthenticator. ClientSecret, + WebIdentity, and WorkloadIdentity implement it. """ def get_http_client_auth(self) -> AuthStrategy: @@ -152,6 +159,23 @@ async def prepare_token_exchange_request( subject_token_type="urn:ietf:params:oauth:token-type:access_token", ) + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + """Return the Basic header for ``issuer``. No form fields. + + A multi-zone credential selects the zone by ``issuer``. + + Raises: + ConfigError: A multi-zone credential has no credentials for + ``issuer``. + """ + try: + headers = self.get_http_client_auth().apply_headers(issuer) + except KeyError as e: + raise ConfigError(f"ClientSecret has no credentials for {issuer}") from e + return ClientAuthentication(headers=dict(headers)) + class WebIdentity: """Private key JWT client assertion provider. @@ -163,8 +187,15 @@ class WebIdentity: Example: provider = WebIdentity( server_name="My Server", - storage_dir="./server_keys" + storage_dir="./server_keys", + client_id="registered-client-id", ) + + Args: + client_id: The registered OAuth client ID, signed as the assertion's + ``iss`` and ``sub``. Required for client authentication. Token + exchange uses the auth context's ``resource_client_id`` when + present, and this value otherwise. """ _DEFAULT_STORAGE_DIR = "./server_keys" @@ -179,8 +210,10 @@ def __init__( audience_config: str | dict[str, str] | None = None, # Backward-compatible alias mcp_server_name: str | None = None, + client_id: str | None = None, ): server_name = server_name or mcp_server_name + self.client_id = client_id if storage is not None: self._storage = storage @@ -237,7 +270,7 @@ def set_client_config( raise ValueError( "auth_info with 'resource_server_url' is required for WebIdentity" ) - config.client_id = auth_info["resource_client_id"] + config.client_id = self._signing_client_id(auth_info) config.auto_register_client = False config.client_jwks_url = self.identity_manager.get_client_jwks_url( resource_server_url @@ -266,15 +299,10 @@ async def prepare_token_exchange_request( resource: str, auth_info: Mapping[str, str | None] | None = None, ) -> TokenExchangeRequest: - resource_client_id = auth_info.get("resource_client_id") if auth_info else None - if resource_client_id is None: - raise ValueError( - "auth_info with 'resource_client_id' is required for WebIdentity" - ) - + client_id = self._signing_client_id(auth_info) audience = await _get_token_exchange_audience(client) client_assertion = self.identity_manager.create_client_assertion( - issuer=resource_client_id, + issuer=client_id, audience=audience, ) @@ -286,6 +314,63 @@ async def prepare_token_exchange_request( client_assertion=client_assertion, ) + def _signing_client_id(self, auth_info: Mapping[str, str | None] | None) -> str: + """Return the auth context's ``resource_client_id``, else the option. + + Raises: + WebIdentityConfigurationError: Neither is set. + """ + client_id = (auth_info.get("resource_client_id") if auth_info else None) or ( + self.client_id + ) + if not client_id: + raise WebIdentityConfigurationError( + "WebIdentity needs auth_info with 'resource_client_id' or the " + "client_id option" + ) + return client_id + + def check_client_authentication(self) -> None: + """Raise unless client authentication can sign an assertion. + + Raises: + WebIdentityConfigurationError: The ``client_id`` option is not + set. + """ + if not self.client_id: + raise WebIdentityConfigurationError( + "WebIdentity client authentication requires client_id" + ) + + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + """Return a newly signed client assertion for ``endpoint``. + + The assertion's ``iss`` and ``sub`` are the ``client_id`` option and + its ``aud`` is ``endpoint``. ``audience_config`` does not apply. A + Keycard zone rejects any other ``aud`` with ``invalid_client``. + + Raises: + WebIdentityConfigurationError: The ``client_id`` option is not + set, or ``endpoint`` is empty. No assertion is signed. + """ + self.check_client_authentication() + assert self.client_id is not None + if not endpoint: + raise WebIdentityConfigurationError( + "WebIdentity client authentication requires an endpoint" + ) + assertion = self.identity_manager.create_client_assertion( + issuer=self.client_id, audience=endpoint + ) + return ClientAuthentication( + form_fields={ + "client_assertion": assertion, + "client_assertion_type": GrantType.JWT_BEARER_CLIENT_ASSERTION.value, + } + ) + # Source identifiers carried on WorkloadIdentityConfigurationError and # WorkloadIdentityRuntimeError, for branching on which token source failed. @@ -597,6 +682,22 @@ async def prepare_token_exchange_request( client_id=self.client_id, ) + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + """Return the source's current token as the client assertion. + + The form fields are ``client_assertion``, ``client_assertion_type``, + and ``client_id`` when configured. No headers. + """ + form_fields = { + "client_assertion": await self._fetch_identity_token(), + "client_assertion_type": GrantType.JWT_BEARER_CLIENT_ASSERTION.value, + } + if self.client_id: + form_fields["client_id"] = self.client_id + return ClientAuthentication(form_fields=form_fields) + class EKSWorkloadIdentity(WorkloadIdentity): """EKS workload identity provider using mounted tokens. diff --git a/packages/oauth/src/keycardai/oauth/server/exceptions.py b/packages/oauth/src/keycardai/oauth/server/exceptions.py index edd18a0..a2dea5a 100644 --- a/packages/oauth/src/keycardai/oauth/server/exceptions.py +++ b/packages/oauth/src/keycardai/oauth/server/exceptions.py @@ -11,7 +11,7 @@ from typing import Any -from keycardai.oauth.exceptions import classify_discovery_failure +from keycardai.oauth.exceptions import ConfigError, classify_discovery_failure class OAuthServerError(Exception): @@ -674,6 +674,16 @@ def __init__( super().__init__(message, details=details) +class WebIdentityConfigurationError(ConfigError, ValueError): + """WebIdentity has no client ID to sign as the assertion's ``iss``. + + Raised when neither the auth context's ``resource_client_id`` nor the + ``client_id`` option is set, or when client authentication has no + endpoint to sign as ``aud``. It is also a ValueError, so + ``except ValueError`` catches it. + """ + + class CredentialDiscoveryError(OAuthServerError): """Raised when discover_credential cannot pick one credential from the environment. diff --git a/packages/oauth/tests/keycardai/oauth/server/test_client_authentication.py b/packages/oauth/tests/keycardai/oauth/server/test_client_authentication.py new file mode 100644 index 0000000..9725c74 --- /dev/null +++ b/packages/oauth/tests/keycardai/oauth/server/test_client_authentication.py @@ -0,0 +1,416 @@ +"""Client authentication on ClientSecret, WebIdentity, and WorkloadIdentity. + +Test ids name the credential spec and its unit test row +(specs/application-credentials/*.md in the Keycard SDK spec). +""" + +import base64 +import json +import re +import uuid +from unittest.mock import MagicMock + +import pytest +from joserfc import jwt as jose_jwt +from joserfc.jwk import KeySet + +from keycardai.oauth import ( + ClientAuthentication, + ClientConfig, + ConfigError, +) +from keycardai.oauth.client_auth import require_client_authenticator +from keycardai.oauth.server.credentials import ( + ClientSecret, + WebIdentity, + WorkloadIdentity, +) +from keycardai.oauth.server.exceptions import ( + WebIdentityConfigurationError, + WorkloadIdentityRuntimeError, +) + +ISSUER = "https://zone1.keycard.cloud" +DEVICE_ENDPOINT = "https://zone1.keycard.cloud/oauth/device_authorization" +TOKEN_ENDPOINT = "https://zone1.keycard.cloud/oauth/token" +JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" +NO_CLIENT_ID = "WebIdentity needs auth_info with 'resource_client_id' or the client_id option" + +pytestmark = pytest.mark.asyncio + + +def exactly(message: str) -> str: + return f"^{re.escape(message)}$" + + +def basic(client_id: str, secret: str) -> str: + """The Basic header for values that are already percent-encoded.""" + return "Basic " + base64.b64encode(f"{client_id}:{secret}".encode()).decode() + + +def web_identity(tmp_path, **kwargs) -> WebIdentity: + return WebIdentity(server_name="server", storage_dir=str(tmp_path), **kwargs) + + +def decode(assertion: str) -> tuple[dict, dict]: + header, payload, _ = assertion.split(".") + + def part(segment: str) -> dict: + return json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))) + + return part(header), part(payload) + + +# The capability + + +class ThirdPartyCredential: + """A credential implemented outside the SDK, with client authentication.""" + + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + return ClientAuthentication() + + +class ExchangeOnlyCredential: + """A credential implemented outside the SDK, without client authentication.""" + + async def prepare_token_exchange_request(self, client, subject_token, resource, auth_info=None): + raise AssertionError("not used") + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda tmp: ClientSecret(("cid", "secret")), id="ClientSecret"), + pytest.param(lambda tmp: web_identity(tmp, client_id="cid"), id="WebIdentity"), + pytest.param(lambda tmp: WorkloadIdentity(lambda: "token"), id="WorkloadIdentity"), + pytest.param(lambda tmp: ThirdPartyCredential(), id="third-party"), + ], +) +async def test_credentials_provide_client_authentication(tmp_path, make): + credential = make(tmp_path) + + assert require_client_authenticator(credential) is credential + + +@pytest.mark.parametrize( + ("make", "error_type", "message"), + [ + pytest.param( + lambda tmp: ExchangeOnlyCredential(), + ConfigError, + "ExchangeOnlyCredential does not provide client authentication", + id="no-client-authentication", + ), + pytest.param( + lambda tmp: web_identity(tmp), + WebIdentityConfigurationError, + "WebIdentity client authentication requires client_id", + id="web-identity-row-8-before-any-request", + ), + ], +) +async def test_require_client_authenticator_refuses(tmp_path, make, error_type, message): + with pytest.raises(error_type, match=exactly(message)) as exc: + require_client_authenticator(make(tmp_path)) + + assert isinstance(exc.value, ConfigError) + + +async def test_client_authentication_repr_leaves_out_secrets(): + auth = ClientAuthentication( + headers={"Authorization": basic("cid", "secret")}, + form_fields={"client_assertion": "signed.jwt.value"}, + ) + + assert repr(auth) == "ClientAuthentication()" + + +# ClientSecret + + +@pytest.mark.parametrize( + ("credentials", "expected"), + [ + pytest.param(("cid", "secret"), basic("cid", "secret"), id="row-7-single-zone"), + pytest.param( + { + ISSUER: ("zone1-id", "zone1-secret"), + "https://zone2.keycard.cloud": ("zone2-id", "zone2-secret"), + }, + basic("zone1-id", "zone1-secret"), + id="row-7-configured-zone", + ), + pytest.param( + ("ua:client", "a b+%41"), + basic("ua%3Aclient", "a%20b%2B%2541"), + id="row-8-encoding", + ), + ], +) +async def test_client_secret_basic_header(credentials, expected): + auth = await ClientSecret(credentials).client_authentication( + issuer=ISSUER, endpoint=DEVICE_ENDPOINT + ) + + assert auth == ClientAuthentication(headers={"Authorization": expected}) + + +async def test_client_secret_row_4_unknown_zone_fails_closed(): + credential = ClientSecret({"https://zone2.keycard.cloud": ("id", "secret")}) + + with pytest.raises(ConfigError, match=exactly(f"ClientSecret has no credentials for {ISSUER}")): + await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + + +# WebIdentity + + +@pytest.mark.parametrize( + ("endpoint", "audience_config"), + [ + pytest.param(DEVICE_ENDPOINT, None, id="row-7-device-endpoint"), + pytest.param(TOKEN_ENDPOINT, None, id="token-endpoint"), + # audience_config has no effect on any path today, so this row guards + # client authentication against a future use of it. + pytest.param(DEVICE_ENDPOINT, "https://other.example.com", id="row-9-string"), + pytest.param( + DEVICE_ENDPOINT, {ISSUER: "https://other.example.com"}, id="row-9-per-zone" + ), + ], +) +async def test_web_identity_assertion_for_the_endpoint(tmp_path, endpoint, audience_config): + credential = web_identity( + tmp_path, client_id="registered-client", audience_config=audience_config + ) + + auth = await credential.client_authentication(issuer=ISSUER, endpoint=endpoint) + + assert auth.headers == {} + assert set(auth.form_fields) == {"client_assertion", "client_assertion_type"} + assert auth.form_fields["client_assertion_type"] == JWT_BEARER + header, claims = decode(auth.form_fields["client_assertion"]) + assert header == {"alg": "RS256", "typ": "JWT", "kid": credential.identity_manager.key_id} + assert set(claims) == {"iss", "sub", "aud", "jti", "iat", "exp"} + assert (claims["iss"], claims["sub"], claims["aud"]) == ( + "registered-client", + "registered-client", + endpoint, + ) + assert claims["exp"] == claims["iat"] + 300 + uuid.UUID(claims["jti"]) + keys = KeySet.import_key_set(credential.identity_manager.get_public_jwks()) + assert jose_jwt.decode(auth.form_fields["client_assertion"], keys).claims == claims + + +async def test_web_identity_each_call_signs_a_new_assertion(tmp_path): + credential = web_identity(tmp_path, client_id="registered-client") + + first = await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + second = await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + + assert decode(first.form_fields["client_assertion"])[1]["jti"] != decode( + second.form_fields["client_assertion"] + )[1]["jti"] + + +@pytest.mark.parametrize( + ("client_id", "endpoint", "message"), + [ + pytest.param( + None, + DEVICE_ENDPOINT, + "WebIdentity client authentication requires client_id", + id="row-8-no-client_id", + ), + pytest.param( + "", + DEVICE_ENDPOINT, + "WebIdentity client authentication requires client_id", + id="row-8-empty-client_id", + ), + pytest.param( + "registered-client", + "", + "WebIdentity client authentication requires an endpoint", + id="empty-endpoint", + ), + ], +) +async def test_web_identity_client_authentication_misconfigured( + tmp_path, client_id, endpoint, message +): + credential = web_identity(tmp_path, client_id=client_id) + credential.identity_manager = MagicMock(wraps=credential.identity_manager) + + with pytest.raises(WebIdentityConfigurationError, match=exactly(message)): + await credential.client_authentication(issuer=ISSUER, endpoint=endpoint) + + credential.identity_manager.create_client_assertion.assert_not_called() + + +def exchange_client() -> MagicMock: + client = MagicMock(_initialized=True) + client._discovered_endpoints.token = TOKEN_ENDPOINT + return client + + +@pytest.mark.parametrize( + ("client_id", "auth_info", "expected_iss"), + [ + pytest.param( + "registered-client", + {"resource_client_id": "context-client"}, + "context-client", + id="row-10-auth-context-wins", + ), + pytest.param("registered-client", None, "registered-client", id="option"), + pytest.param( + "registered-client", + {"resource_client_id": ""}, + "registered-client", + id="empty-context-falls-back", + ), + pytest.param(None, {"resource_client_id": "context-client"}, "context-client", id="context"), + ], +) +async def test_web_identity_row_10_token_exchange_client_id( + tmp_path, client_id, auth_info, expected_iss +): + credential = web_identity(tmp_path, client_id=client_id) + + request = await credential.prepare_token_exchange_request( + client=exchange_client(), subject_token="st", resource="https://api", auth_info=auth_info + ) + + assert request.client_assertion is not None + _, claims = decode(request.client_assertion) + assert (claims["iss"], claims["sub"], claims["aud"]) == ( + expected_iss, + expected_iss, + TOKEN_ENDPOINT, + ) + + +@pytest.mark.parametrize( + ("client_id", "auth_info"), + [ + pytest.param(None, None, id="neither"), + pytest.param("", {"resource_client_id": ""}, id="both-empty"), + ], +) +async def test_web_identity_token_exchange_without_a_client_id(tmp_path, client_id, auth_info): + credential = web_identity(tmp_path, client_id=client_id) + + with pytest.raises(WebIdentityConfigurationError, match=exactly(NO_CLIENT_ID)) as exc: + await credential.prepare_token_exchange_request( + client=exchange_client(), subject_token="st", resource="https://api", auth_info=auth_info + ) + + assert isinstance(exc.value, ValueError) + assert isinstance(exc.value, ConfigError) + + +RESOURCE_SERVER = {"resource_server_url": "https://mcp.example.com"} + + +@pytest.mark.parametrize( + ("client_id", "auth_info", "expected"), + [ + pytest.param("registered-client", RESOURCE_SERVER, "registered-client", id="option"), + pytest.param( + "registered-client", + {**RESOURCE_SERVER, "resource_client_id": "context-client"}, + "context-client", + id="auth-context-wins", + ), + pytest.param( + None, + {**RESOURCE_SERVER, "resource_client_id": "context-client"}, + "context-client", + id="context", + ), + ], +) +async def test_web_identity_set_client_config_client_id(tmp_path, client_id, auth_info, expected): + credential = web_identity(tmp_path, client_id=client_id) + + config = credential.set_client_config(ClientConfig(), auth_info) + + assert config.client_id == expected + + +async def test_web_identity_set_client_config_without_a_client_id(tmp_path): + credential = web_identity(tmp_path) + + with pytest.raises(WebIdentityConfigurationError, match=exactly(NO_CLIENT_ID)): + credential.set_client_config(ClientConfig(), RESOURCE_SERVER) + + +# WorkloadIdentity + + +@pytest.mark.parametrize( + ("client_id", "expected"), + [ + pytest.param( + None, + {"client_assertion": "platform-token", "client_assertion_type": JWT_BEARER}, + id="row-4b-without-client_id", + ), + pytest.param( + "app-credential-id", + { + "client_assertion": "platform-token", + "client_assertion_type": JWT_BEARER, + "client_id": "app-credential-id", + }, + id="row-4b-with-client_id", + ), + ], +) +async def test_workload_identity_rows_4b_and_4c_form_fields(client_id, expected): + # "platform-token" is not a JWT. Row 4c: it goes out unchanged. + credential = WorkloadIdentity(lambda: "platform-token", client_id=client_id) + + auth = await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + + assert auth == ClientAuthentication(form_fields=expected) + + +async def test_workload_identity_calls_the_source_on_every_request(): + tokens = iter(["token-1", "token-2"]) + credential = WorkloadIdentity(lambda: next(tokens)) + + first = await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + second = await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + + assert [first.form_fields["client_assertion"], second.form_fields["client_assertion"]] == [ + "token-1", + "token-2", + ] + + +def failing_source(): + raise OSError("metadata server down") + + +@pytest.mark.parametrize( + ("source", "message", "cause_type"), + [ + pytest.param(failing_source, "Error fetching identity token", OSError, id="source-raises"), + pytest.param( + lambda: " ", "Identity token source returned an empty token", type(None), id="empty-token" + ), + ], +) +async def test_workload_identity_source_failure(source, message, cause_type): + credential = WorkloadIdentity(source) + + with pytest.raises(WorkloadIdentityRuntimeError, match=exactly(message)) as exc: + await credential.client_authentication(issuer=ISSUER, endpoint=TOKEN_ENDPOINT) + + assert exc.value.source == "custom" + assert type(exc.value.__cause__) is cause_type diff --git a/packages/oauth/tests/keycardai/oauth/server/test_credentials.py b/packages/oauth/tests/keycardai/oauth/server/test_credentials.py index 06ed522..2ac6f20 100644 --- a/packages/oauth/tests/keycardai/oauth/server/test_credentials.py +++ b/packages/oauth/tests/keycardai/oauth/server/test_credentials.py @@ -212,7 +212,7 @@ async def test_prepare_token_exchange_request_without_auth_info(self, mock_clien storage_dir=tmpdir ) - with pytest.raises(ValueError, match="auth_info with 'resource_client_id' is required"): + with pytest.raises(ValueError, match="auth_info with 'resource_client_id' or the client_id option"): await provider.prepare_token_exchange_request( client=mock_client, subject_token="test_access_token", @@ -328,7 +328,7 @@ async def test_prepare_token_exchange_request_with_none_resource_client_id_raise ): with tempfile.TemporaryDirectory() as tmpdir: provider = WebIdentity(mcp_server_name="Test Server", storage_dir=tmpdir) - with pytest.raises(ValueError, match="auth_info with 'resource_client_id' is required"): + with pytest.raises(ValueError, match="auth_info with 'resource_client_id' or the client_id option"): await provider.prepare_token_exchange_request( client=mock_client, subject_token="test_access_token",