|
| 1 | +"""Test OAuth token expiry handling with absolute timestamps.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from datetime import datetime, timedelta, timezone |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import pytest |
| 8 | +from mcp.shared.auth import OAuthToken |
| 9 | + |
| 10 | +from fastmcp.client.auth.oauth import FileTokenStorage |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.asyncio |
| 14 | +async def test_token_storage_with_expiry(tmp_path: Path): |
| 15 | + """Test that tokens are stored with absolute expiry time and loaded correctly.""" |
| 16 | + storage = FileTokenStorage("http://test.example.com", cache_dir=tmp_path) |
| 17 | + |
| 18 | + # Create a token with 3600 seconds expiry |
| 19 | + token = OAuthToken( |
| 20 | + access_token="test_token", |
| 21 | + token_type="Bearer", |
| 22 | + expires_in=3600, |
| 23 | + refresh_token="refresh_token", |
| 24 | + ) |
| 25 | + |
| 26 | + # Save the token |
| 27 | + await storage.set_tokens(token) |
| 28 | + |
| 29 | + # Check that the file contains the dataclass format |
| 30 | + token_file = storage._get_file_path("tokens") |
| 31 | + data = json.loads(token_file.read_text()) |
| 32 | + |
| 33 | + assert "token_payload" in data |
| 34 | + assert "expires_at" in data |
| 35 | + assert data["expires_at"] is not None |
| 36 | + # expires_at should be approximately now + 3600 seconds |
| 37 | + expires_at = datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00")) |
| 38 | + expected = datetime.now(timezone.utc) + timedelta(seconds=3600) |
| 39 | + assert abs((expires_at - expected).total_seconds()) < 2 |
| 40 | + |
| 41 | + # Load the token back |
| 42 | + loaded_token = await storage.get_tokens() |
| 43 | + assert loaded_token is not None |
| 44 | + assert loaded_token.access_token == "test_token" |
| 45 | + # expires_in should be recalculated to be approximately 3600 (minus loading time) |
| 46 | + assert loaded_token.expires_in is not None |
| 47 | + assert 3595 <= loaded_token.expires_in <= 3600 |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.asyncio |
| 51 | +async def test_expired_token_returns_none(tmp_path: Path): |
| 52 | + """Test that expired tokens return None when loaded.""" |
| 53 | + storage = FileTokenStorage("http://test.example.com", cache_dir=tmp_path) |
| 54 | + |
| 55 | + # Manually create an already-expired token file |
| 56 | + token_file = storage._get_file_path("tokens") |
| 57 | + past_expiry = datetime.now(timezone.utc) - timedelta( |
| 58 | + seconds=10 |
| 59 | + ) # Expired 10 seconds ago |
| 60 | + |
| 61 | + expired_token = { |
| 62 | + "token_payload": { |
| 63 | + "access_token": "test_token", |
| 64 | + "token_type": "Bearer", |
| 65 | + "expires_in": 3600, |
| 66 | + "refresh_token": "refresh_token", |
| 67 | + }, |
| 68 | + "expires_at": past_expiry.isoformat(), |
| 69 | + } |
| 70 | + token_file.write_text(json.dumps(expired_token, indent=2, default=str)) |
| 71 | + |
| 72 | + # Load the token - should return None since it's expired |
| 73 | + loaded_token = await storage.get_tokens() |
| 74 | + assert loaded_token is None |
| 75 | + |
| 76 | + |
| 77 | +@pytest.mark.asyncio |
| 78 | +async def test_token_without_expiry(tmp_path: Path): |
| 79 | + """Test that tokens without expires_in are handled correctly.""" |
| 80 | + storage = FileTokenStorage("http://test.example.com", cache_dir=tmp_path) |
| 81 | + |
| 82 | + # Create a token without expires_in (perpetual token) |
| 83 | + token = OAuthToken( |
| 84 | + access_token="test_token", |
| 85 | + token_type="Bearer", |
| 86 | + expires_in=None, |
| 87 | + refresh_token="refresh_token", |
| 88 | + ) |
| 89 | + |
| 90 | + # Save the token |
| 91 | + await storage.set_tokens(token) |
| 92 | + |
| 93 | + # Check that expires_at is None in the file |
| 94 | + token_file = storage._get_file_path("tokens") |
| 95 | + data = json.loads(token_file.read_text()) |
| 96 | + assert data["expires_at"] is None |
| 97 | + |
| 98 | + # Load the token back - should work since no expiry |
| 99 | + loaded_token = await storage.get_tokens() |
| 100 | + assert loaded_token is not None |
| 101 | + assert loaded_token.access_token == "test_token" |
| 102 | + assert loaded_token.expires_in is None |
| 103 | + |
| 104 | + |
| 105 | +@pytest.mark.asyncio |
| 106 | +async def test_invalid_format_returns_none(tmp_path: Path): |
| 107 | + """Test that invalid token format returns None.""" |
| 108 | + storage = FileTokenStorage("http://test.example.com", cache_dir=tmp_path) |
| 109 | + |
| 110 | + # Manually write an invalid format token file (missing required fields) |
| 111 | + token_file = storage._get_file_path("tokens") |
| 112 | + invalid_token = { |
| 113 | + "access_token": "invalid_token", |
| 114 | + "token_type": "Bearer", |
| 115 | + "expires_in": 3600, |
| 116 | + "refresh_token": "refresh_token", |
| 117 | + } |
| 118 | + token_file.write_text(json.dumps(invalid_token, indent=2)) |
| 119 | + |
| 120 | + # Try to load - should return None |
| 121 | + loaded_token = await storage.get_tokens() |
| 122 | + assert loaded_token is None |
| 123 | + |
| 124 | + |
| 125 | +@pytest.mark.asyncio |
| 126 | +async def test_token_expiry_recalculated_on_load(tmp_path: Path): |
| 127 | + """Test that expires_in is correctly recalculated when loading tokens.""" |
| 128 | + storage = FileTokenStorage("http://test.example.com", cache_dir=tmp_path) |
| 129 | + |
| 130 | + # Manually create a token file with a specific expires_at |
| 131 | + token_file = storage._get_file_path("tokens") |
| 132 | + future_expiry = datetime.now(timezone.utc) + timedelta( |
| 133 | + seconds=1800 |
| 134 | + ) # 30 minutes from now |
| 135 | + |
| 136 | + stored_token = { |
| 137 | + "token_payload": { |
| 138 | + "access_token": "test_token", |
| 139 | + "token_type": "Bearer", |
| 140 | + "expires_in": 3600, # Original value (will be recalculated) |
| 141 | + "refresh_token": "refresh_token", |
| 142 | + }, |
| 143 | + "expires_at": future_expiry.isoformat(), |
| 144 | + } |
| 145 | + token_file.write_text(json.dumps(stored_token, indent=2, default=str)) |
| 146 | + |
| 147 | + # Load the token |
| 148 | + loaded_token = await storage.get_tokens() |
| 149 | + assert loaded_token is not None |
| 150 | + # expires_in should be recalculated to approximately 1800 seconds |
| 151 | + assert loaded_token.expires_in is not None |
| 152 | + assert 1795 <= loaded_token.expires_in <= 1800 |
0 commit comments