|
1 | 1 | """Tests for OAuth 2.0 shared code.""" |
2 | 2 |
|
3 | | -from mcp.shared.auth import OAuthMetadata |
| 3 | +import pytest |
| 4 | + |
| 5 | +from mcp.shared.auth import InvalidScopeError, OAuthClientMetadata, OAuthMetadata |
4 | 6 |
|
5 | 7 |
|
6 | 8 | def test_oauth(): |
@@ -58,3 +60,39 @@ def test_oauth_with_jarm(): |
58 | 60 | "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"], |
59 | 61 | } |
60 | 62 | ) |
| 63 | + |
| 64 | + |
| 65 | +class TestValidateScope: |
| 66 | + """Tests for OAuthClientMetadata.validate_scope.""" |
| 67 | + |
| 68 | + def _make_client(self, scope: str | None = None) -> OAuthClientMetadata: |
| 69 | + return OAuthClientMetadata.model_validate({"redirect_uris": ["https://example.com/callback"], "scope": scope}) |
| 70 | + |
| 71 | + def test_none_requested_scope_returns_none(self): |
| 72 | + client = self._make_client(scope="read write") |
| 73 | + assert client.validate_scope(None) is None |
| 74 | + |
| 75 | + def test_none_registered_scope_allows_any_requested_scope(self): |
| 76 | + client = self._make_client(scope=None) |
| 77 | + result = client.validate_scope("read write admin") |
| 78 | + assert result == ["read", "write", "admin"] |
| 79 | + |
| 80 | + def test_registered_scope_allows_matching_requested_scope(self): |
| 81 | + client = self._make_client(scope="read write") |
| 82 | + result = client.validate_scope("read") |
| 83 | + assert result == ["read"] |
| 84 | + |
| 85 | + def test_registered_scope_allows_all_matching_scopes(self): |
| 86 | + client = self._make_client(scope="read write") |
| 87 | + result = client.validate_scope("read write") |
| 88 | + assert result == ["read", "write"] |
| 89 | + |
| 90 | + def test_registered_scope_rejects_unregistered_scope(self): |
| 91 | + client = self._make_client(scope="read write") |
| 92 | + with pytest.raises(InvalidScopeError, match="Client was not registered with scope admin"): |
| 93 | + client.validate_scope("read admin") |
| 94 | + |
| 95 | + def test_empty_registered_scope_rejects_any_requested_scope(self): |
| 96 | + client = self._make_client(scope="") |
| 97 | + with pytest.raises(InvalidScopeError): |
| 98 | + client.validate_scope("read") |
0 commit comments