|
| 1 | +"""Debug token verifier for testing and special cases. |
| 2 | +
|
| 3 | +This module provides a flexible token verifier that delegates validation |
| 4 | +to a custom callable. Useful for testing, development, or scenarios where |
| 5 | +standard verification isn't possible (like opaque tokens without introspection). |
| 6 | +
|
| 7 | +Example: |
| 8 | + ```python |
| 9 | + from fastmcp import FastMCP |
| 10 | + from fastmcp.server.auth.providers.debug import DebugTokenVerifier |
| 11 | +
|
| 12 | + # Accept all tokens (default - useful for testing) |
| 13 | + auth = DebugTokenVerifier() |
| 14 | +
|
| 15 | + # Custom sync validation logic |
| 16 | + auth = DebugTokenVerifier(validate=lambda token: token.startswith("valid-")) |
| 17 | +
|
| 18 | + # Custom async validation logic |
| 19 | + async def check_cache(token: str) -> bool: |
| 20 | + return await redis.exists(f"token:{token}") |
| 21 | +
|
| 22 | + auth = DebugTokenVerifier(validate=check_cache) |
| 23 | +
|
| 24 | + mcp = FastMCP("My Server", auth=auth) |
| 25 | + ``` |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import inspect |
| 31 | +from collections.abc import Awaitable, Callable |
| 32 | + |
| 33 | +from fastmcp.server.auth import TokenVerifier |
| 34 | +from fastmcp.server.auth.auth import AccessToken |
| 35 | +from fastmcp.utilities.logging import get_logger |
| 36 | + |
| 37 | +logger = get_logger(__name__) |
| 38 | + |
| 39 | + |
| 40 | +class DebugTokenVerifier(TokenVerifier): |
| 41 | + """Token verifier with custom validation logic. |
| 42 | +
|
| 43 | + This verifier delegates token validation to a user-provided callable. |
| 44 | + By default, it accepts all non-empty tokens (useful for testing). |
| 45 | +
|
| 46 | + Use cases: |
| 47 | + - Testing: Accept any token without real verification |
| 48 | + - Development: Custom validation logic for prototyping |
| 49 | + - Opaque tokens: When you have tokens with no introspection endpoint |
| 50 | +
|
| 51 | + WARNING: This bypasses standard security checks. Only use in controlled |
| 52 | + environments or when you understand the security implications. |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + validate: Callable[[str], bool] |
| 58 | + | Callable[[str], Awaitable[bool]] = lambda token: True, |
| 59 | + client_id: str = "debug-client", |
| 60 | + scopes: list[str] | None = None, |
| 61 | + required_scopes: list[str] | None = None, |
| 62 | + ): |
| 63 | + """Initialize the debug token verifier. |
| 64 | +
|
| 65 | + Args: |
| 66 | + validate: Callable that takes a token string and returns True if valid. |
| 67 | + Can be sync or async. Default accepts all tokens. |
| 68 | + client_id: Client ID to assign to validated tokens |
| 69 | + scopes: Scopes to assign to validated tokens |
| 70 | + required_scopes: Required scopes (inherited from TokenVerifier base class) |
| 71 | + """ |
| 72 | + super().__init__(required_scopes=required_scopes) |
| 73 | + self.validate = validate |
| 74 | + self.client_id = client_id |
| 75 | + self.scopes = scopes or [] |
| 76 | + |
| 77 | + async def verify_token(self, token: str) -> AccessToken | None: |
| 78 | + """Verify token using custom validation logic. |
| 79 | +
|
| 80 | + Args: |
| 81 | + token: The token string to validate |
| 82 | +
|
| 83 | + Returns: |
| 84 | + AccessToken if validation succeeds, None otherwise |
| 85 | + """ |
| 86 | + # Reject empty tokens |
| 87 | + if not token or not token.strip(): |
| 88 | + logger.debug("Rejecting empty token") |
| 89 | + return None |
| 90 | + |
| 91 | + try: |
| 92 | + # Call validation function and await if result is awaitable |
| 93 | + result = self.validate(token) |
| 94 | + if inspect.isawaitable(result): |
| 95 | + is_valid = await result |
| 96 | + else: |
| 97 | + is_valid = result |
| 98 | + |
| 99 | + if not is_valid: |
| 100 | + logger.debug("Token validation failed: callable returned False") |
| 101 | + return None |
| 102 | + |
| 103 | + # Return valid AccessToken |
| 104 | + return AccessToken( |
| 105 | + token=token, |
| 106 | + client_id=self.client_id, |
| 107 | + scopes=self.scopes, |
| 108 | + expires_at=None, # No expiration |
| 109 | + claims={"token": token}, # Store original token in claims |
| 110 | + ) |
| 111 | + |
| 112 | + except Exception as e: |
| 113 | + logger.debug("Token validation error: %s", e, exc_info=True) |
| 114 | + return None |
0 commit comments