|
1 | 1 | import urllib.parse |
| 2 | +from collections.abc import AsyncGenerator |
2 | 3 |
|
| 4 | +import httpx |
3 | 5 | import jwt |
4 | 6 | import pytest |
| 7 | +from inline_snapshot import snapshot |
5 | 8 | from pydantic import AnyHttpUrl, AnyUrl |
6 | 9 |
|
| 10 | +from mcp.client.auth import OAuthClientProvider, OAuthFlowError |
7 | 11 | from mcp.client.auth.extensions.client_credentials import ( |
8 | 12 | ClientCredentialsOAuthProvider, |
9 | 13 | JWTParameters, |
@@ -429,3 +433,207 @@ async def test_returns_static_token(self): |
429 | 433 |
|
430 | 434 | assert result1 == token |
431 | 435 | assert result2 == token |
| 436 | + |
| 437 | + |
| 438 | +_SERVER_URL = "https://api.example.com/v1/mcp" |
| 439 | +_CONFIGURED_ISSUER = "https://auth.example.com" |
| 440 | + |
| 441 | + |
| 442 | +def _metadata_for(issuer: str) -> dict[str, str]: |
| 443 | + return {"issuer": issuer, "authorization_endpoint": f"{issuer}/authorize", "token_endpoint": f"{issuer}/token"} |
| 444 | + |
| 445 | + |
| 446 | +def _provider_with_issuer(kind: str, storage: MockTokenStorage, audiences: list[str]) -> OAuthClientProvider: |
| 447 | + """A ClientCredentials ("secret") or PrivateKeyJWT ("jwt") provider configured for _CONFIGURED_ISSUER; |
| 448 | + `audiences` records every audience an assertion is minted for.""" |
| 449 | + if kind == "secret": |
| 450 | + return ClientCredentialsOAuthProvider( |
| 451 | + server_url=_SERVER_URL, storage=storage, client_id="cid", client_secret="csecret", issuer=_CONFIGURED_ISSUER |
| 452 | + ) |
| 453 | + |
| 454 | + async def assertion_provider(audience: str) -> str: |
| 455 | + audiences.append(audience) |
| 456 | + return "signed-assertion" |
| 457 | + |
| 458 | + return PrivateKeyJWTOAuthProvider( |
| 459 | + server_url=_SERVER_URL, |
| 460 | + storage=storage, |
| 461 | + client_id="cid", |
| 462 | + assertion_provider=assertion_provider, |
| 463 | + issuer=_CONFIGURED_ISSUER, |
| 464 | + ) |
| 465 | + |
| 466 | + |
| 467 | +async def _answer_discovery( |
| 468 | + flow: AsyncGenerator[httpx.Request, httpx.Response], |
| 469 | + *, |
| 470 | + authorization_server: str | list[str] | None, |
| 471 | + metadata: dict[str, str] | None, |
| 472 | +) -> httpx.Request: |
| 473 | + """Answer the provider's first request with a 401 and its discovery requests as described; |
| 474 | + return the request it builds once discovery is over. |
| 475 | +
|
| 476 | + `authorization_server` is what protected-resource metadata advertises (None: no PRM is |
| 477 | + served); `metadata` is the authorization server metadata document (None: every well-known |
| 478 | + 404s). |
| 479 | + """ |
| 480 | + request = await flow.__anext__() |
| 481 | + request = await flow.asend(httpx.Response(401, request=request)) |
| 482 | + while "/.well-known/oauth-protected-resource" in str(request.url): |
| 483 | + if authorization_server is None: |
| 484 | + response = httpx.Response(404, request=request) |
| 485 | + else: |
| 486 | + advertised = authorization_server if isinstance(authorization_server, list) else [authorization_server] |
| 487 | + prm = {"resource": _SERVER_URL, "authorization_servers": advertised} |
| 488 | + response = httpx.Response(200, json=prm, request=request) |
| 489 | + request = await flow.asend(response) |
| 490 | + while "/.well-known/" in str(request.url): |
| 491 | + if metadata is None: |
| 492 | + response = httpx.Response(404, request=request) |
| 493 | + else: |
| 494 | + response = httpx.Response(200, json=metadata, request=request) |
| 495 | + request = await flow.asend(response) |
| 496 | + return request |
| 497 | + |
| 498 | + |
| 499 | +@pytest.mark.anyio |
| 500 | +@pytest.mark.parametrize( |
| 501 | + "served_issuer", [_CONFIGURED_ISSUER, f"{_CONFIGURED_ISSUER}/"], ids=["as-configured", "root-slash"] |
| 502 | +) |
| 503 | +@pytest.mark.parametrize("kind", ["secret", "jwt"]) |
| 504 | +async def test_provider_with_configured_issuer_exchanges_at_that_issuer( |
| 505 | + mock_storage: MockTokenStorage, kind: str, served_issuer: str |
| 506 | +): |
| 507 | + """SDK-defined: with `issuer=` set and metadata discovered for that issuer (a root issuer served with |
| 508 | + its trailing slash is the same server), the token request goes to its token endpoint (positive |
| 509 | + control for the refusals below).""" |
| 510 | + audiences: list[str] = [] |
| 511 | + provider = _provider_with_issuer(kind, mock_storage, audiences) |
| 512 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 513 | + metadata = {**_metadata_for(_CONFIGURED_ISSUER), "issuer": served_issuer} |
| 514 | + |
| 515 | + token_request = await _answer_discovery(flow, authorization_server=served_issuer, metadata=metadata) |
| 516 | + |
| 517 | + assert (token_request.method, str(token_request.url)) == ("POST", "https://auth.example.com/token") |
| 518 | + # The SDK's URL type renders a root issuer with its trailing slash, which is the audience used. |
| 519 | + assert audiences == ([] if kind == "secret" else ["https://auth.example.com/"]) |
| 520 | + await flow.aclose() |
| 521 | + |
| 522 | + |
| 523 | +@pytest.mark.anyio |
| 524 | +@pytest.mark.parametrize("kind", ["secret", "jwt"]) |
| 525 | +async def test_provider_picks_its_configured_issuer_among_several_advertised_servers( |
| 526 | + mock_storage: MockTokenStorage, kind: str |
| 527 | +): |
| 528 | + """SDK-defined: when the resource lists several authorization servers, the one matching `issuer=` is |
| 529 | + discovered and used even if it is not listed first.""" |
| 530 | + provider = _provider_with_issuer(kind, mock_storage, []) |
| 531 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 532 | + |
| 533 | + token_request = await _answer_discovery( |
| 534 | + flow, |
| 535 | + authorization_server=["https://other-as.example.com", _CONFIGURED_ISSUER], |
| 536 | + metadata=_metadata_for(_CONFIGURED_ISSUER), |
| 537 | + ) |
| 538 | + |
| 539 | + assert provider.context.auth_server_url == f"{_CONFIGURED_ISSUER}/" |
| 540 | + assert str(token_request.url) == "https://auth.example.com/token" |
| 541 | + await flow.aclose() |
| 542 | + |
| 543 | + |
| 544 | +def test_an_issuer_that_is_not_an_http_url_is_rejected_at_construction(mock_storage: MockTokenStorage) -> None: |
| 545 | + """SDK-defined: `issuer=` is the authorization server's issuer URL; anything else is a configuration |
| 546 | + error on both machine-to-machine providers.""" |
| 547 | + with pytest.raises(ValueError) as cc_error: |
| 548 | + ClientCredentialsOAuthProvider( |
| 549 | + server_url=_SERVER_URL, storage=mock_storage, client_id="cid", client_secret="s", issuer="auth.example.com" |
| 550 | + ) |
| 551 | + with pytest.raises(ValueError) as jwt_error: |
| 552 | + PrivateKeyJWTOAuthProvider( |
| 553 | + server_url=_SERVER_URL, |
| 554 | + storage=mock_storage, |
| 555 | + client_id="cid", |
| 556 | + assertion_provider=static_assertion_provider("jwt"), |
| 557 | + issuer="auth.example.com", |
| 558 | + ) |
| 559 | + assert ( |
| 560 | + str(cc_error.value) |
| 561 | + == str(jwt_error.value) |
| 562 | + == snapshot("issuer must be the authorization server's http(s) issuer URL, got 'auth.example.com'") |
| 563 | + ) |
| 564 | + |
| 565 | + |
| 566 | +@pytest.mark.anyio |
| 567 | +@pytest.mark.parametrize("kind", ["secret", "jwt"]) |
| 568 | +async def test_provider_refuses_metadata_for_a_different_issuer(mock_storage: MockTokenStorage, kind: str): |
| 569 | + """SDK-defined: when discovery ends at an authorization server other than the configured `issuer`, |
| 570 | + no token request is built and no assertion is minted.""" |
| 571 | + audiences: list[str] = [] |
| 572 | + provider = _provider_with_issuer(kind, mock_storage, audiences) |
| 573 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 574 | + |
| 575 | + with pytest.raises(OAuthFlowError) as exc_info: |
| 576 | + await _answer_discovery( |
| 577 | + flow, |
| 578 | + authorization_server="https://other-as.example.com", |
| 579 | + metadata=_metadata_for("https://other-as.example.com"), |
| 580 | + ) |
| 581 | + |
| 582 | + assert str(exc_info.value) == snapshot( |
| 583 | + "Authorization server metadata issuer mismatch: https://other-as.example.com/ != https://auth.example.com" |
| 584 | + ) |
| 585 | + assert audiences == [] |
| 586 | + |
| 587 | + |
| 588 | +@pytest.mark.anyio |
| 589 | +@pytest.mark.parametrize("kind", ["secret", "jwt"]) |
| 590 | +async def test_provider_refuses_to_exchange_without_metadata_when_issuer_configured( |
| 591 | + mock_storage: MockTokenStorage, kind: str |
| 592 | +): |
| 593 | + """SDK-defined: with `issuer=` set, the 2025-03-26 default `/token` on the resource origin is not |
| 594 | + used when no authorization server metadata could be discovered.""" |
| 595 | + audiences: list[str] = [] |
| 596 | + provider = _provider_with_issuer(kind, mock_storage, audiences) |
| 597 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 598 | + |
| 599 | + with pytest.raises(OAuthFlowError) as exc_info: |
| 600 | + await _answer_discovery(flow, authorization_server=None, metadata=None) |
| 601 | + |
| 602 | + assert str(exc_info.value) == snapshot( |
| 603 | + "No authorization server metadata discovered for configured issuer https://auth.example.com" |
| 604 | + ) |
| 605 | + assert audiences == [] |
| 606 | + |
| 607 | + |
| 608 | +@pytest.mark.anyio |
| 609 | +@pytest.mark.parametrize("kind", ["secret", "jwt"]) |
| 610 | +async def test_a_refused_authorization_server_is_forgotten_so_the_next_request_rediscovers( |
| 611 | + mock_storage: MockTokenStorage, kind: str |
| 612 | +): |
| 613 | + """SDK-defined: when the exchange is refused because discovery ended somewhere other than the |
| 614 | + configured issuer, the refused metadata and any token held are dropped; the next request goes out |
| 615 | + unauthenticated and discovery starts again, rather than a refresh being built from what was refused.""" |
| 616 | + provider = _provider_with_issuer(kind, mock_storage, []) |
| 617 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 618 | + token_request = await _answer_discovery( |
| 619 | + flow, authorization_server=_CONFIGURED_ISSUER, metadata=_metadata_for(_CONFIGURED_ISSUER) |
| 620 | + ) |
| 621 | + token = {"access_token": "first", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "rt"} |
| 622 | + retried = await flow.asend(httpx.Response(200, json=token, request=token_request)) |
| 623 | + with pytest.raises(StopAsyncIteration): |
| 624 | + await flow.asend(httpx.Response(200, request=retried)) |
| 625 | + |
| 626 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 627 | + with pytest.raises(OAuthFlowError): |
| 628 | + await _answer_discovery( |
| 629 | + flow, |
| 630 | + authorization_server="https://other-as.example.com", |
| 631 | + metadata=_metadata_for("https://other-as.example.com"), |
| 632 | + ) |
| 633 | + assert provider.context.oauth_metadata is None |
| 634 | + assert provider.context.current_tokens is None |
| 635 | + |
| 636 | + flow = provider.async_auth_flow(httpx.Request("POST", _SERVER_URL)) |
| 637 | + request = await flow.__anext__() |
| 638 | + assert (str(request.url), request.headers.get("Authorization")) == (_SERVER_URL, None) |
| 639 | + await flow.aclose() |
0 commit comments