|
| 1 | +"""Tests for the mcpserver Context class.""" |
| 2 | + |
| 3 | +import time |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from mcp.server.auth.middleware.auth_context import auth_context_var |
| 8 | +from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser |
| 9 | +from mcp.server.auth.provider import AccessToken |
| 10 | +from mcp.server.mcpserver import Context |
| 11 | + |
| 12 | + |
| 13 | +@pytest.fixture |
| 14 | +def access_token_with_subject() -> AccessToken: |
| 15 | + return AccessToken( |
| 16 | + token="tok", |
| 17 | + client_id="client", |
| 18 | + scopes=["read"], |
| 19 | + expires_at=int(time.time()) + 3600, |
| 20 | + subject="user-123", |
| 21 | + ) |
| 22 | + |
| 23 | + |
| 24 | +@pytest.fixture |
| 25 | +def access_token_no_subject() -> AccessToken: |
| 26 | + return AccessToken( |
| 27 | + token="tok", |
| 28 | + client_id="client", |
| 29 | + scopes=["read"], |
| 30 | + expires_at=int(time.time()) + 3600, |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +class TestContextSubject: |
| 35 | + """Tests for Context.subject property.""" |
| 36 | + |
| 37 | + def test_subject_returns_none_when_unauthenticated(self): |
| 38 | + """subject is None when no access token is in context.""" |
| 39 | + ctx = Context() |
| 40 | + assert ctx.subject is None |
| 41 | + |
| 42 | + def test_subject_returns_none_when_token_has_no_subject(self, access_token_no_subject: AccessToken): |
| 43 | + """subject is None when the access token has no subject set.""" |
| 44 | + user = AuthenticatedUser(access_token_no_subject) |
| 45 | + token = auth_context_var.set(user) |
| 46 | + try: |
| 47 | + ctx = Context() |
| 48 | + assert ctx.subject is None |
| 49 | + finally: |
| 50 | + auth_context_var.reset(token) |
| 51 | + |
| 52 | + def test_subject_returns_value_from_access_token(self, access_token_with_subject: AccessToken): |
| 53 | + """subject returns the JWT sub claim from the current access token.""" |
| 54 | + user = AuthenticatedUser(access_token_with_subject) |
| 55 | + token = auth_context_var.set(user) |
| 56 | + try: |
| 57 | + ctx = Context() |
| 58 | + assert ctx.subject == "user-123" |
| 59 | + finally: |
| 60 | + auth_context_var.reset(token) |
| 61 | + |
| 62 | + def test_subject_updates_with_context_var(self): |
| 63 | + """subject reflects the current value of the auth context variable.""" |
| 64 | + ctx = Context() |
| 65 | + assert ctx.subject is None |
| 66 | + |
| 67 | + token_a = AccessToken(token="a", client_id="c", scopes=[], subject="alice") |
| 68 | + cv_token = auth_context_var.set(AuthenticatedUser(token_a)) |
| 69 | + try: |
| 70 | + assert ctx.subject == "alice" |
| 71 | + finally: |
| 72 | + auth_context_var.reset(cv_token) |
| 73 | + |
| 74 | + # After reset, subject should be None again |
| 75 | + assert ctx.subject is None |
0 commit comments