π The fast, Pythonic way to build MCP servers and clients.
feat(auth): Add KeystoneTokenVerifier (#6264)
Bramc33f3dea02c5
diff --git a/docs/docs.json b/docs/docs.jsonindex 250f70525..7524658e5 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -302,6 +302,7 @@"integrations/google","integrations/huggingface","integrations/keycloak",+ "integrations/keystone","integrations/oci","integrations/permit","integrations/propelauth",diff --git a/docs/integrations/keystone.mdx b/docs/integrations/keystone.mdxnew file mode 100644index 000000000..5f076ed0d--- /dev/null+++ b/docs/integrations/keystone.mdx@@ -0,0 +1,141 @@+---+title: OpenStack Keystone π€ FastMCP+sidebarTitle: Keystone+description: Secure your FastMCP server with OpenStack Keystone tokens+icon: shield-check+---++import { VersionBadge } from "/snippets/version-badge.mdx"++<VersionBadge version="4.2.0" />++If your users already authenticate to an OpenStack cloud, your FastMCP server can accept the tokens they already have. `KeystoneTokenVerifier` validates each incoming token with Keystone, then exposes the caller's user, project, and roles to your tools.++Keystone tokens are opaque and Keystone has no RFC 7662 introspection endpoint, so the [generic introspection verifier](/servers/auth/token-verification#token-introspection-protocol) won't work. This verifier uses Keystone's own equivalent, the Identity v3 [token validation API](https://docs.openstack.org/api-ref/identity/v3/#validate-and-show-information-for-token), through a [keystoneauth1](https://docs.openstack.org/keystoneauth/latest/) session.++This is token verification only. FastMCP doesn't issue tokens or run a login flow, so clients must obtain a Keystone token themselves, and OAuth-based MCP clients can't sign in interactively.++## Configuration++### Prerequisites++Install the `keystone` extra:++```bash+pip install "fastmcp[keystone]"+```++You also need:++1. Your Keystone URL, such as `https://keystone.example.com:5000/v3`. The `/v3` suffix is optional.+2. A service account that's allowed to validate other users' tokens. Keystone's default policy grants this to the `service` role, so a user with that role on your `service` project is the usual choice. A username and password must come with `project_name`, because an unscoped token has no service catalog and can't validate tokens.++### FastMCP Configuration++Authenticate the verifier with the service account, then pass it to your server:++```python server.py+import os++from fastmcp import FastMCP+from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier+from fastmcp.server.dependencies import get_access_token++auth = KeystoneTokenVerifier(+ auth_url=os.environ["KEYSTONE_AUTH_URL"],+ username="mcp-service",+ password=os.environ["KEYSTONE_SERVICE_PASSWORD"],+ project_name="service",+ allowed_project_ids=[os.environ["KEYSTONE_PROJECT_ID"]],+)++mcp = FastMCP("Keystone Example Server", auth=auth)+++def whoami() -> dict:+ """Show the authenticated Keystone identity."""+ token = get_access_token()+ return {+ "user_id": token.client_id,+ "project": token.claims["project_name"],+ "roles": token.scopes,+ }+```++To authenticate with an application credential instead of a password, replace `username`, `password`, and `project_name` with `application_credential_id` and `application_credential_secret`. Each verifier uses exactly one of these two credential types.++<Warning>+**Set `allowed_project_ids` on shared clouds.** Keystone authenticates every user in the cloud, so without this restriction any valid token is accepted, whichever project it belongs to. Role checks don't close this gap, because users commonly hold the `member` role in their own project. When the option is set, domain-scoped, system-scoped, and unscoped tokens are rejected too.+</Warning>++### Reaching Keystone++The verifier finds the validation endpoint through the service catalog. It uses the `public` interface by default. Servers running inside the cloud may need `interface="internal"` and `region_name`. For a private certificate authority, set `verify` to the path of your CA bundle.++## Testing++Run your server, then get a token from the OpenStack CLI:++```bash+fastmcp run server.py --transport http --port 8000+openstack token issue -f value -c id+```++Clients send the token as a standard bearer token, not in the `X-Auth-Token` header that OpenStack APIs use:++```python client.py+import asyncio+import os++from fastmcp import Client+++async def main():+ token = os.environ["OS_TOKEN"]+ async with Client("http://localhost:8000/mcp", auth=token) as client:+ print(await client.call_tool("whoami"))+++asyncio.run(main())+```++## Authorization++Each token's Keystone role names become its FastMCP scopes, so you can use [`require_scopes`](/servers/authorization) to protect individual components. To require a role for the whole server, pass it to the verifier as `required_scopes`.++```python+from fastmcp.server.auth import require_scopes++[email protected](auth=require_scopes("admin"))+def delete_everything() -> str:+ return "done"+```++Tools can read these values from `get_access_token().claims`:++| Claim | Description |+| ----- | ----------- |+| `sub` | Keystone user ID, also available as `client_id` |+| `username`, `user_domain_id`, `user_domain_name` | User name and domain |+| `project_id`, `project_name`, `project_domain_id`, `project_domain_name` | Project, for project-scoped tokens |+| `domain_id`, `domain_name` | Domain, for domain-scoped tokens |+| `system_scoped` | Whether the token is system-scoped |+| `roles` | Keystone role names |+| `application_credential_id` | Application credential that produced the token, if any |+| `audit_id` | Keystone audit ID |++## Application Credential Access Rules++Tokens from application credentials with [access rules](https://docs.openstack.org/keystone/latest/user/application_credentials.html#access-rules) are always rejected. Those rules list the OpenStack services and API paths a token may reach, and an MCP server isn't one of them. Application credentials without access rules work normally.++## Caching++Every request is validated with Keystone by default, so a revoked token stops working immediately. Busy servers can set `cache_ttl_seconds` to reduce that load, and a revoked token then keeps working until its cache entry expires. Only successful validations are cached, and entries never outlive the token.++## Troubleshooting++When Keystone can't validate a token, for example during an outage or because of bad service credentials, the verifier fails closed. Callers receive a `401` that looks the same as an invalid token, and the server logs a warning with the cause.++If every token is rejected, look for these warnings. HTTP `401` means Keystone refused the service credentials, and HTTP `403` means the service account lacks permission to validate tokens.diff --git a/docs/servers/authorization.mdx b/docs/servers/authorization.mdxindex 5d598ff90..5e4b8ca99 100644--- a/docs/servers/authorization.mdx+++ b/docs/servers/authorization.mdx@@ -90,6 +90,7 @@ Keeping the claim path at the call site means any provider works, including ones| Provider | Extractor || --- | --- || Keycloak | `lambda c: c["realm_access"]["roles"]` |+| OpenStack Keystone | `lambda c: c["roles"]` || Microsoft Entra | `lambda c: c["roles"]` || AWS Cognito | `lambda c: c["cognito:groups"]` || Auth0 | `lambda c: c["permissions"]` |diff --git a/fastmcp_slim/fastmcp/server/auth/providers/keystone.py b/fastmcp_slim/fastmcp/server/auth/providers/keystone.pynew file mode 100644index 000000000..4cd4991cf--- /dev/null+++ b/fastmcp_slim/fastmcp/server/auth/providers/keystone.py@@ -0,0 +1,310 @@+"""OpenStack Keystone token verification for FastMCP.++Keystone issues opaque Fernet tokens and has no RFC 7662 introspection+endpoint. Its equivalent is the Identity v3 token validation API+(`GET /v3/auth/tokens`), which this verifier calls through an authenticated+keystoneauth1 session. The service account needs permission to validate other+users' tokens, which Keystone's default policy grants to the `service` role.++Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier++ verifier = KeystoneTokenVerifier(+ auth_url="https://keystone.example.com:5000/v3",+ username="mcp-service",+ password="service-password",+ project_name="service",+ allowed_project_ids=["f3a1c6b2d4e54c60a7c9e8b1d2f30456"],+ )++ mcp = FastMCP("My Protected Server", auth=verifier)+ ```+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any++import anyio.to_thread+from pydantic import AnyHttpUrl, SecretStr++from fastmcp.server.auth import AccessToken, TokenVerifier+from fastmcp.utilities.auth import parse_scopes+from fastmcp.utilities.logging import get_logger+from fastmcp.utilities.token_cache import TokenCache++try:+ from keystoneauth1 import access, adapter, session+ from keystoneauth1.identity import v3+except ImportError as e:+ raise ImportError(+ "KeystoneTokenVerifier requires the `keystone` extra. "+ "Install with: pip install 'fastmcp[keystone]'"+ ) from e++logger = get_logger(__name__)+++def _secret_value(secret: str | SecretStr) -> str:+ return secret.get_secret_value() if isinstance(secret, SecretStr) else secret+++class KeystoneTokenVerifier(TokenVerifier):+ """Verify OpenStack Keystone tokens with the Identity v3 validation API.++ Clients send their Keystone token as a standard `Authorization: Bearer`+ header. The token's Keystone role names become its FastMCP scopes, so+ `required_scopes` and `require_scopes` operate on roles.++ Authenticate the verifier with either a service user (`username`,+ `password`, and `project_name`) or an application credential+ (`application_credential_id` and `application_credential_secret`).++ Keystone authenticates every user in a cloud, so a valid token alone only+ proves that its holder has an account there. On a shared cloud, set+ `allowed_project_ids` to limit access to specific projects.++ Tokens from application credentials with access rules are rejected. Those+ rules name the OpenStack service and API paths a token may reach, and an+ MCP server is not one of the services they can describe.++ Caching is disabled by default so that revoked tokens stop working+ immediately. Set `cache_ttl_seconds` to reduce load on Keystone.+ """++ def __init__(+ self,+ *,+ auth_url: str,+ username: str | None = None,+ password: str | SecretStr | None = None,+ user_domain_name: str = "Default",+ project_name: str | None = None,+ project_domain_name: str = "Default",+ application_credential_id: str | None = None,+ application_credential_secret: str | SecretStr | None = None,+ interface: str = "public",+ region_name: str | None = None,+ verify: bool | str = True,+ timeout_seconds: int = 10,+ required_scopes: list[str] | None = None,+ allowed_project_ids: list[str] | None = None,+ base_url: AnyHttpUrl | str | None = None,+ cache_ttl_seconds: int | None = None,+ max_cache_size: int | None = None,+ ):+ """Initialize the Keystone token verifier.++ Args:+ auth_url: Keystone URL, with or without the `/v3` suffix.+ username: Service user that validates tokens.+ password: Password for the service user.+ user_domain_name: Domain of the service user.+ project_name: Project to scope the service user's token to. Required+ with `username` and `password`.+ project_domain_name: Domain of `project_name`.+ application_credential_id: Application credential to authenticate+ with instead of a service user.+ application_credential_secret: Secret for the application credential.+ interface: Service catalog interface used to reach Keystone's+ validation endpoint: `public`, `internal`, or `admin`.+ region_name: Service catalog region of the identity endpoint.+ verify: Whether to verify TLS certificates, or a path to a CA bundle.+ timeout_seconds: Timeout for each request to Keystone.+ required_scopes: Keystone role names that every token must hold.+ allowed_project_ids: Project IDs a token must be scoped to. None+ accepts any token that Keystone considers valid. When set,+ domain-scoped, system-scoped, and unscoped tokens are rejected.+ base_url: Base URL for the TokenVerifier protocol.+ cache_ttl_seconds: How long to cache successful validations. None+ disables caching so that revocation takes effect immediately.+ max_cache_size: Maximum number of cached tokens. Default: 10000.+ """+ super().__init__(+ base_url=base_url,+ required_scopes=(+ parse_scopes(required_scopes) if required_scopes is not None else None+ ),+ )++ has_user = username is not None or password is not None+ has_app_cred = (+ application_credential_id is not None+ or application_credential_secret is not None+ )+ if has_user == has_app_cred:+ raise ValueError(+ "Provide either username and password or "+ "application_credential_id and application_credential_secret."+ )++ base_auth_url = auth_url.rstrip("/").removesuffix("/v3")+ identity_url = f"{base_auth_url}/v3"++ auth: v3.Auth+ if has_app_cred:+ if (+ application_credential_id is None+ or application_credential_secret is None+ ):+ raise ValueError(+ "application_credential_id and application_credential_secret "+ "must be provided together."+ )+ auth = v3.ApplicationCredential(+ auth_url=identity_url,+ application_credential_id=application_credential_id,+ application_credential_secret=_secret_value(+ application_credential_secret+ ),+ )+ else:+ if username is None or password is None:+ raise ValueError("username and password must be provided together.")+ # An unscoped token has no service catalog to find Keystone's+ # endpoint in and no roles to pass the token validation policy.+ if project_name is None:+ raise ValueError(+ "project_name is required with username and password, because "+ "an unscoped service token cannot validate tokens."+ )+ auth = v3.Password(+ auth_url=identity_url,+ username=username,+ password=_secret_value(password),+ user_domain_name=user_domain_name,+ project_name=project_name,+ project_domain_name=project_domain_name,+ )++ self._identity = adapter.Adapter(+ session.Session(auth=auth, verify=verify, timeout=timeout_seconds),+ service_type="identity",+ interface=interface,+ region_name=region_name,+ version="3.0",+ )+ self.allowed_project_ids = (+ None if allowed_project_ids is None else set(allowed_project_ids)+ )+ self._cache = TokenCache(+ ttl_seconds=cache_ttl_seconds,+ max_size=max_cache_size,+ )++ def _fetch_token_data(self, token: str) -> dict[str, Any] | None:+ """Ask Keystone to validate a token, returning its data if valid."""+ response = self._identity.get(+ "/auth/tokens?nocatalog",+ headers={"X-Subject-Token": token},+ raise_exc=False,+ log=False,+ )+ if response.status_code == 200:+ return response.json()+ if response.status_code == 404:+ logger.debug("Keystone does not recognize this token")+ return None+ # Anything else is about this verifier rather than the caller's token:+ # 401 and 403 mean Keystone refused the service credentials or their+ # permission to validate tokens. Without this warning, every caller+ # would simply see 401 and the cause would be invisible.+ logger.warning(+ "Keystone token validation failed: HTTP %d", response.status_code+ )+ return None++ async def verify_token(self, token: str) -> AccessToken | None:+ """Verify a token against Keystone's token validation API.++ Args:+ token: The Keystone token to validate.++ Returns:+ AccessToken if Keystone accepts the token and it satisfies this+ verifier's restrictions, otherwise None.+ """+ if not token or not token.strip():+ return None++ is_cached, cached_result = self._cache.get(token)+ if is_cached:+ return cached_result++ try:+ # keystoneauth1 is synchronous and may need to fetch a service+ # token, discover endpoints, and validate, all over blocking HTTP.+ data = await anyio.to_thread.run_sync(self._fetch_token_data, token)+ if data is None:+ return None+ result = self._build_access_token(token, data)+ except Exception as e:+ # Fail closed on outages, bad service credentials, and malformed+ # responses. Log above debug because operators need to see these.+ logger.warning("Keystone token verification error: %s", e)+ return None++ if result is not None:+ self._cache.set(token, result)+ return result++ def _build_access_token(+ self, token: str, data: dict[str, Any]+ ) -> AccessToken | None:+ """Apply this verifier's restrictions and build an AccessToken."""+ auth_ref = access.create(body=data, auth_token=token)++ expires = auth_ref.expires+ if expires is None or expires <= datetime.now(UTC):+ logger.debug("Keystone token has expired")+ return None++ application_credential = data["token"].get("application_credential") or {}+ if application_credential.get("access_rules") is not None:+ logger.debug("Rejecting Keystone token restricted by access rules")+ return None++ project_id = auth_ref.project_id+ if (+ self.allowed_project_ids is not None+ and project_id not in self.allowed_project_ids+ ):+ logger.debug("Keystone token is not scoped to an allowed project")+ return None++ roles = auth_ref.role_names or []+ if self.required_scopes and not set(self.required_scopes).issubset(roles):+ logger.debug("Keystone token is missing required roles")+ return None++ user_id = auth_ref.user_id+ if not user_id:+ logger.debug("Keystone token has no user ID")+ return None++ return AccessToken(+ token=token,+ client_id=user_id,+ scopes=roles,+ expires_at=int(expires.timestamp()),+ subject=user_id,+ claims={+ "sub": user_id,+ "username": auth_ref.username,+ "user_domain_id": auth_ref.user_domain_id,+ "user_domain_name": auth_ref.user_domain_name,+ "project_id": project_id,+ "project_name": auth_ref.project_name,+ "project_domain_id": auth_ref.project_domain_id,+ "project_domain_name": auth_ref.project_domain_name,+ "domain_id": auth_ref.domain_id,+ "domain_name": auth_ref.domain_name,+ "system_scoped": auth_ref.system_scoped,+ "roles": roles,+ "application_credential_id": application_credential.get("id"),+ "audit_id": auth_ref.audit_id,+ },+ )diff --git a/fastmcp_slim/pyproject.toml b/fastmcp_slim/pyproject.tomlindex ff2d94c2d..973a44a3c 100644--- a/fastmcp_slim/pyproject.toml+++ b/fastmcp_slim/pyproject.toml@@ -78,6 +78,7 @@ client = []code-mode = ["pydantic-monty>=1.1,<2"]jev = ["typesafe-sdk>=0.5.7"]+keystone = ["keystoneauth1>=5.0.0"]gemini = ["certifi>=2026.10.19", "google-genai>=1.18.0", "jsonref>=1.1.0"]mcp = ["exceptiongroup>=1.2.2",diff --git a/pyproject.toml b/pyproject.tomlindex b00f61469..650d93511 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -58,6 +58,7 @@ apps = ["fastmcp-slim[apps]=={{ version }}"]azure = ["fastmcp-slim[azure]=={{ version }}"]code-mode = ["fastmcp-slim[code-mode]=={{ version }}"]jev = ["fastmcp-slim[jev]=={{ version }}"]+keystone = ["fastmcp-slim[keystone]=={{ version }}"]gemini = ["fastmcp-slim[gemini]=={{ version }}"]openai = ["fastmcp-slim[openai]=={{ version }}"]tasks = ["fastmcp-tasks=={{ version }}"]@@ -85,7 +86,7 @@ exclude-newer-package = { authlib = false, certifi = false, fastmcp = false, fas[dependency-groups]dev = ["dirty-equals>=0.9.0",- "fastmcp[anthropic,apps,azure,code-mode,gemini,jev,openai,tasks]",+ "fastmcp[anthropic,apps,azure,code-mode,gemini,jev,keystone,openai,tasks]","fastapi>=0.115.12","fastmcp-remote","opentelemetry-sdk>=1.20.0",diff --git a/tests/server/auth/providers/test_keystone.py b/tests/server/auth/providers/test_keystone.pynew file mode 100644index 000000000..6be3ae427--- /dev/null+++ b/tests/server/auth/providers/test_keystone.py@@ -0,0 +1,493 @@+"""Tests for KeystoneTokenVerifier against a local fake of the Identity v3 API."""++from __future__ import annotations++import json+import logging+import threading+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any++import httpx2+import pytest++pytest.importorskip("keystoneauth1")++from pydantic import SecretStr++from fastmcp import Client, FastMCP+from fastmcp.client.auth.bearer import BearerAuth+from fastmcp.client.transports import StreamableHttpTransport+from fastmcp.server.auth.providers.keystone import KeystoneTokenVerifier+from fastmcp.server.dependencies import get_access_token+from fastmcp.utilities.tests import run_server_async++SERVICE_TOKEN = "service-token"+PROJECT_ID = "project-1"+++def _timestamp(delta: timedelta) -> str:+ moment = datetime.now(UTC) + delta+ return moment.strftime("%Y-%m-%dT%H:%M:%S.000000Z")+++def user_token_body(**overrides: Any) -> dict[str, Any]:+ token: dict[str, Any] = {+ "methods": ["password"],+ "audit_ids": ["audit-1"],+ "expires_at": _timestamp(timedelta(hours=1)),+ "issued_at": _timestamp(timedelta(minutes=-1)),+ "user": {+ "id": "user-1",+ "name": "alice",+ "domain": {"id": "default", "name": "Default"},+ },+ "project": {+ "id": PROJECT_ID,+ "name": "demo",+ "domain": {"id": "default", "name": "Default"},+ },+ "roles": [{"id": "r1", "name": "member"}, {"id": "r2", "name": "reader"}],+ }+ token.update(overrides)+ return {"token": {key: value for key, value in token.items() if value is not None}}+++class FakeKeystone:+ """The parts of Keystone that keystoneauth1 touches to validate a token."""++ def __init__(self) -> None:+ self.tokens: dict[str, dict[str, Any]] = {}+ self.auth_requests: list[dict[str, Any]] = []+ self.validation_requests: list[dict[str, str]] = []+ self.validation_paths: list[str] = []+ self.validation_status: int | None = None+ self.url = ""+++def _handler_for(keystone: FakeKeystone) -> type[BaseHTTPRequestHandler]:+ class Handler(BaseHTTPRequestHandler):+ def log_message(self, format: str, *args: Any) -> None:+ pass++ def _send(+ self,+ status: int,+ body: dict[str, Any],+ headers: dict[str, str] | None = None,+ ) -> None:+ payload = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ for name, value in (headers or {}).items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(payload)++ def do_POST(self) -> None:+ length = int(self.headers["Content-Length"])+ request = json.loads(self.rfile.read(length))+ keystone.auth_requests.append(request)+ auth = request["auth"]+ if (+ "scope" not in auth+ and "application_credential" not in (auth["identity"]["methods"])+ ):+ # Real Keystone gives unscoped tokens no project or catalog.+ body = user_token_body(project=None, roles=None)+ self._send(201, body, {"X-Subject-Token": SERVICE_TOKEN})+ return+ body = user_token_body(+ catalog=[+ {+ "type": "identity",+ "name": "keystone",+ "id": "identity",+ "endpoints": [+ {+ "id": "public",+ "interface": "public",+ "region": "RegionOne",+ "region_id": "RegionOne",+ "url": f"{keystone.url}/v3",+ }+ ],+ }+ ]+ )+ self._send(201, body, {"X-Subject-Token": SERVICE_TOKEN})++ def do_GET(self) -> None:+ if self.path.split("?")[0].rstrip("/") == "/v3":+ self._send(+ 200,+ {+ "version": {+ "id": "v3.14",+ "status": "stable",+ "links": [+ {"rel": "self", "href": f"{keystone.url}/v3/"},+ ],+ }+ },+ )+ return++ keystone.validation_requests.append(dict(self.headers))+ keystone.validation_paths.append(self.path)+ if keystone.validation_status is not None:+ self._send(keystone.validation_status, {"error": {}})+ elif self.headers.get("X-Auth-Token") != SERVICE_TOKEN:+ self._send(401, {"error": {}})+ elif (token := self.headers["X-Subject-Token"]) in keystone.tokens:+ self._send(200, keystone.tokens[token])+ else:+ self._send(404, {"error": {}})++ return Handler+++def keystone() -> Iterator[FakeKeystone]:+ fake = FakeKeystone()+ server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(fake))+ fake.url = f"http://127.0.0.1:{server.server_port}"+ thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)+ thread.start()+ yield fake+ server.shutdown()+ server.server_close()+ thread.join()+++def make_verifier(keystone: FakeKeystone, **kwargs: Any) -> KeystoneTokenVerifier:+ return KeystoneTokenVerifier(+ auth_url=f"{keystone.url}/v3",+ username="mcp-service",+ password="secret",+ project_name="service",+ **kwargs,+ )+++class TestConfiguration:+ def test_requires_credentials(self):+ with pytest.raises(ValueError, match="either username and password"):+ KeystoneTokenVerifier(auth_url="http://keystone/v3")++ def test_rejects_both_credential_types(self):+ with pytest.raises(ValueError, match="either username and password"):+ KeystoneTokenVerifier(+ auth_url="http://keystone/v3",+ username="user",+ password="secret",+ application_credential_id="id",+ application_credential_secret="secret",+ )++ def test_rejects_username_without_password(self):+ with pytest.raises(ValueError, match="provided together"):+ KeystoneTokenVerifier(auth_url="http://keystone/v3", username="user")++ def test_rejects_unscoped_service_user(self):+ with pytest.raises(ValueError, match="project_name is required"):+ KeystoneTokenVerifier(+ auth_url="http://keystone/v3",+ username="user",+ password="secret",+ )++ def test_rejects_application_credential_without_secret(self):+ with pytest.raises(ValueError, match="provided together"):+ KeystoneTokenVerifier(+ auth_url="http://keystone/v3",+ application_credential_id="id",+ )+++class TestVerifyToken:+ async def test_valid_token(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()++ result = await make_verifier(keystone).verify_token("user-token")++ assert result is not None+ assert result.token == "user-token"+ assert result.client_id == "user-1"+ assert result.subject == "user-1"+ assert result.scopes == ["member", "reader"]+ assert result.expires_at is not None+ assert result.claims["project_id"] == PROJECT_ID+ assert result.claims["project_name"] == "demo"+ assert result.claims["username"] == "alice"+ assert result.claims["roles"] == ["member", "reader"]++ async def test_validation_call_shape(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()++ await make_verifier(keystone).verify_token("user-token")++ assert keystone.validation_paths == ["/v3/auth/tokens?nocatalog"]+ headers = keystone.validation_requests[0]+ assert headers["X-Auth-Token"] == SERVICE_TOKEN+ assert headers["X-Subject-Token"] == "user-token"++ @pytest.mark.parametrize("suffix", ["", "/", "/v3/"])+ async def test_auth_url_forms(self, keystone: FakeKeystone, suffix: str):+ keystone.tokens["user-token"] = user_token_body()+ verifier = KeystoneTokenVerifier(+ auth_url=f"{keystone.url}{suffix}",+ username="mcp-service",+ password="secret",+ project_name="service",+ )++ assert await verifier.verify_token("user-token") is not None++ async def test_service_user_auth_request(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()+ verifier = KeystoneTokenVerifier(+ auth_url=keystone.url,+ username="mcp-service",+ password=SecretStr("secret"),+ user_domain_name="services",+ project_name="service",+ project_domain_name="ops",+ )++ await verifier.verify_token("user-token")++ auth = keystone.auth_requests[0]["auth"]+ assert auth["identity"]["password"]["user"] == {+ "name": "mcp-service",+ "password": "secret",+ "domain": {"name": "services"},+ }+ assert auth["scope"]["project"] == {+ "name": "service",+ "domain": {"name": "ops"},+ }++ async def test_application_credential_auth_request(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()+ verifier = KeystoneTokenVerifier(+ auth_url=keystone.url,+ application_credential_id="cred-id",+ application_credential_secret=SecretStr("cred-secret"),+ )++ assert await verifier.verify_token("user-token") is not None++ identity = keystone.auth_requests[0]["auth"]["identity"]+ assert identity["methods"] == ["application_credential"]+ assert identity["application_credential"] == {+ "id": "cred-id",+ "secret": "cred-secret",+ }++ async def test_service_token_reused_between_validations(+ self, keystone: FakeKeystone+ ):+ keystone.tokens["user-token"] = user_token_body()+ verifier = make_verifier(keystone)++ await verifier.verify_token("user-token")+ await verifier.verify_token("user-token")++ assert len(keystone.auth_requests) == 1+ assert len(keystone.validation_requests) == 2+++class TestRejection:+ async def test_unknown_token(self, keystone: FakeKeystone):+ assert await make_verifier(keystone).verify_token("unknown") is None++ @pytest.mark.parametrize("token", ["", " "])+ async def test_empty_token_never_reaches_keystone(+ self, keystone: FakeKeystone, token: str+ ):+ assert await make_verifier(keystone).verify_token(token) is None+ assert keystone.auth_requests == []++ async def test_expired_token(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body(+ expires_at=_timestamp(timedelta(minutes=-1))+ )++ assert await make_verifier(keystone).verify_token("user-token") is None++ @pytest.mark.parametrize("status", [401, 403, 500, 503])+ async def test_keystone_refusal_fails_closed(+ self, keystone: FakeKeystone, status: int+ ):+ keystone.tokens["user-token"] = user_token_body()+ keystone.validation_status = status++ assert await make_verifier(keystone).verify_token("user-token") is None++ @pytest.mark.parametrize("status", [401, 403, 500])+ async def test_service_side_failures_are_logged_as_warnings(+ self,+ keystone: FakeKeystone,+ status: int,+ caplog: pytest.LogCaptureFixture,+ ):+ keystone.validation_status = status++ with caplog.at_level(logging.WARNING, logger="fastmcp"):+ await make_verifier(keystone).verify_token("user-token")++ assert f"HTTP {status}" in caplog.text++ async def test_unknown_token_is_not_logged_as_a_warning(+ self, keystone: FakeKeystone, caplog: pytest.LogCaptureFixture+ ):+ with caplog.at_level(logging.WARNING, logger="fastmcp"):+ await make_verifier(keystone).verify_token("unknown")++ assert "Keystone" not in caplog.text++ async def test_unreachable_keystone_fails_closed(self):+ verifier = KeystoneTokenVerifier(+ auth_url="http://127.0.0.1:1/v3",+ username="mcp-service",+ password="secret",+ project_name="service",+ timeout_seconds=1,+ )++ assert await verifier.verify_token("user-token") is None++ async def test_malformed_response_fails_closed(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = {"token": {"user": {"id": "user-1"}}}++ assert await make_verifier(keystone).verify_token("user-token") is None++ @pytest.mark.parametrize(+ "rules",+ [[], [{"service": "compute", "method": "GET", "path": "/v2.1/servers"}]],+ )+ async def test_access_rule_restricted_token(+ self, keystone: FakeKeystone, rules: list[dict[str, str]]+ ):+ keystone.tokens["user-token"] = user_token_body(+ application_credential={+ "id": "cred-1",+ "name": "restricted",+ "restricted": True,+ "access_rules": rules,+ }+ )++ assert await make_verifier(keystone).verify_token("user-token") is None++ async def test_unrestricted_application_credential_token(+ self, keystone: FakeKeystone+ ):+ keystone.tokens["user-token"] = user_token_body(+ application_credential={+ "id": "cred-1",+ "name": "plain",+ "restricted": True,+ }+ )++ result = await make_verifier(keystone).verify_token("user-token")++ assert result is not None+ assert result.claims["application_credential_id"] == "cred-1"+++class TestRestrictions:+ async def test_required_scopes_match_roles(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()++ allowed = make_verifier(keystone, required_scopes=["member"])+ denied = make_verifier(keystone, required_scopes=["admin"])++ assert await allowed.verify_token("user-token") is not None+ assert await denied.verify_token("user-token") is None++ async def test_allowed_project(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()++ allowed = make_verifier(keystone, allowed_project_ids=[PROJECT_ID])+ denied = make_verifier(keystone, allowed_project_ids=["another-project"])++ assert await allowed.verify_token("user-token") is not None+ assert await denied.verify_token("user-token") is None++ async def test_project_allowlist_rejects_unscoped_token(+ self, keystone: FakeKeystone+ ):+ keystone.tokens["user-token"] = user_token_body(project=None, roles=None)++ open_verifier = make_verifier(keystone)+ strict_verifier = make_verifier(keystone, allowed_project_ids=[PROJECT_ID])++ unscoped = await open_verifier.verify_token("user-token")+ assert unscoped is not None+ assert unscoped.scopes == []+ assert await strict_verifier.verify_token("user-token") is None+++class TestCaching:+ async def test_disabled_by_default_so_revocation_is_immediate(+ self, keystone: FakeKeystone+ ):+ keystone.tokens["user-token"] = user_token_body()+ verifier = make_verifier(keystone)++ assert await verifier.verify_token("user-token") is not None++ del keystone.tokens["user-token"]++ assert await verifier.verify_token("user-token") is None++ async def test_enabled_cache_skips_keystone(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()+ verifier = make_verifier(keystone, cache_ttl_seconds=60)++ first = await verifier.verify_token("user-token")+ second = await verifier.verify_token("user-token")++ assert first is not None and first == second+ assert len(keystone.validation_requests) == 1++ async def test_rejections_are_not_cached(self, keystone: FakeKeystone):+ verifier = make_verifier(keystone, cache_ttl_seconds=60)++ assert await verifier.verify_token("user-token") is None++ keystone.tokens["user-token"] = user_token_body()++ assert await verifier.verify_token("user-token") is not None+++class TestEndToEnd:+ async def test_bearer_token_over_http(self, keystone: FakeKeystone):+ keystone.tokens["user-token"] = user_token_body()+ mcp = FastMCP("keystone", auth=make_verifier(keystone))++ @mcp.tool+ def whoami() -> dict[str, Any]:+ token = get_access_token()+ assert token is not None+ return {"user": token.client_id, "project": token.claims["project_id"]}++ async with run_server_async(mcp, transport="http") as url:+ transport = StreamableHttpTransport(url, auth=BearerAuth("user-token"))+ async with Client(transport) as client:+ result = await client.call_tool("whoami")+ assert result.data == {"user": "user-1", "project": PROJECT_ID}++ async with httpx2.AsyncClient() as http:+ response = await http.post(+ url,+ headers={"Authorization": "Bearer bad"},+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},+ )+ assert response.status_code == 401diff --git a/uv.lock b/uv.lockindex 5cab794ae..8a2bb4fb0 100644--- a/uv.lock+++ b/uv.lock@@ -822,6 +822,9 @@ gemini = [jev = [{ name = "fastmcp-slim", extra = ["jev"] },]+keystone = [+ { name = "fastmcp-slim", extra = ["keystone"] },+]openai = [{ name = "fastmcp-slim", extra = ["openai"] },]@@ -833,7 +836,7 @@ tasks = [dev = [{ name = "dirty-equals" },{ name = "fastapi" },- { name = "fastmcp", extra = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"] },+ { name = "fastmcp", extra = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"] },{ name = "fastmcp-remote" },{ name = "inline-snapshot", extra = ["dirty-equals"] },{ name = "ipython" },@@ -868,16 +871,17 @@ requires-dist = [{ name = "fastmcp-slim", extras = ["code-mode"], marker = "extra == 'code-mode'", editable = "fastmcp_slim" },{ name = "fastmcp-slim", extras = ["gemini"], marker = "extra == 'gemini'", editable = "fastmcp_slim" },{ name = "fastmcp-slim", extras = ["jev"], marker = "extra == 'jev'", editable = "fastmcp_slim" },+ { name = "fastmcp-slim", extras = ["keystone"], marker = "extra == 'keystone'", editable = "fastmcp_slim" },{ name = "fastmcp-slim", extras = ["openai"], marker = "extra == 'openai'", editable = "fastmcp_slim" },{ name = "fastmcp-tasks", marker = "extra == 'tasks'", editable = "fastmcp_tasks" },]-provides-extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"]+provides-extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"][package.metadata.requires-dev]dev = [{ name = "dirty-equals", specifier = ">=0.9.0" },{ name = "fastapi", specifier = ">=0.115.12" },- { name = "fastmcp", extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "openai", "tasks"], editable = "." },+ { name = "fastmcp", extras = ["anthropic", "apps", "azure", "code-mode", "gemini", "jev", "keystone", "openai", "tasks"], editable = "." },{ name = "fastmcp-remote", editable = "fastmcp_remote" },{ name = "inline-snapshot", extras = ["dirty-equals"], specifier = ">=0.27.2" },{ name = "ipython", specifier = ">=8.12.3" },@@ -960,6 +964,9 @@ gemini = [jev = [{ name = "typesafe-sdk" },]+keystone = [+ { name = "keystoneauth1" },+]mcp = [{ name = "exceptiongroup" },{ name = "httpx2" },@@ -1025,6 +1032,7 @@ requires-dist = [{ name = "jsonref", marker = "extra == 'server'", specifier = ">=1.1.0" },{ name = "jsonschema", marker = "extra == 'server'", specifier = ">=4.20.0" },{ name = "jsonschema-path", marker = "extra == 'server'", specifier = ">=0.3.4" },+ { name = "keystoneauth1", marker = "extra == 'keystone'", specifier = ">=5.0.0" },{ name = "mcp", marker = "extra == 'client'", specifier = ">=2.3.0,<3.0.0" },{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=2.3.0,<3.0.0" },{ name = "mcp", marker = "extra == 'server'", specifier = ">=2.3.0,<3.0.0" },@@ -1058,7 +1066,7 @@ requires-dist = [{ name = "watchfiles", marker = "extra == 'server'", specifier = ">=1.0.0" },{ name = "websockets", marker = "extra == 'server'", specifier = ">=15.0.1" },]-provides-extras = ["anthropic", "apps", "azure", "client", "code-mode", "gemini", "jev", "mcp", "openai", "server"]+provides-extras = ["anthropic", "apps", "azure", "client", "code-mode", "gemini", "jev", "keystone", "mcp", "openai", "server"][[package]]name = "fastmcp-tasks"@@ -1349,6 +1357,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" },]+[[package]]+name = "iso8601"+version = "2.1.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/b9/f3/ef59cee614d5e0accf6fd0cbba025b93b272e626ca89fb70a3e9187c5d15/iso8601-2.1.0.tar.gz", hash = "sha256:6b1d3829ee8921c4301998c909f7829fa9ed3cbdac0d3b16af2d743aed1ba8df", size = 6522, upload-time = "2023-10-03T00:25:39.317Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/6c/0c/f37b6a241f0759b7653ffa7213889d89ad49a2b76eb2ddf3b57b2738c347/iso8601-2.1.0-py3-none-any.whl", hash = "sha256:aac4145c4dcb66ad8b648a02830f5e2ff6c24af20f4f482689be402db2429242", size = 7545, upload-time = "2023-10-03T00:25:32.304Z" },+]+[[package]]name = "jedi"version = "0.20.0"@@ -1510,6 +1527,22 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" },]+[[package]]+name = "keystoneauth1"+version = "5.18.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "iso8601" },+ { name = "os-service-types" },+ { name = "requests" },+ { name = "stevedore" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/04/af/268e14554c6bd4a2614872fb2b8431e466ce01415a9783b260ce7fb7ae5c/keystoneauth1-5.18.1.tar.gz", hash = "sha256:8970f9d103f335c39151366d70c001d1bb99b00d73845f03d47825e8dc35ff78", size = 319181, upload-time = "2026-10-12T09:04:48.166Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/78/24/38ccf4476c81435c834d4791804099f305b91087fad171ac17d18fc84ca9/keystoneauth1-5.18.1-py3-none-any.whl", hash = "sha256:2440f1f29e4aaaaf771893e8da7c098ca27548210dc13e964b53fd2aaaedd6b0", size = 367402, upload-time = "2026-10-12T09:04:46.753Z" },+]+[[package]]name = "loq"version = "0.1.0"@@ -1804,6 +1837,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" },]+[[package]]+name = "os-service-types"+version = "1.9.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "pbr" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/86/ae/fe7ac23155ae0b4b9779e06e9c5bb4070f2315dc4ca886a88fa3230d344b/os_service_types-1.9.0.tar.gz", hash = "sha256:1f2e5fb71d1f6f4ff31d8992674f2368465bc2f25cd94018015c3ddbfc5c617f", size = 28087, upload-time = "2026-08-04T13:07:43.171Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e3/79/f8ae99ae9bb54cd63e7ab89251b2a4ff4ff07f02847403948b6a6f50f816/os_service_types-1.9.0-py3-none-any.whl", hash = "sha256:f268545c896434177bf55c43f7d5129e65210d5d456df3f00a1c9832a71c3a4b", size = 25282, upload-time = "2026-08-04T13:07:42.258Z" },+]+[[package]]name = "packaging"version = "26.2"@@ -1840,6 +1886,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" },]+[[package]]+name = "pbr"+version = "7.1.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "setuptools" },+]+sdist = { url = "https://files.pythonhosted.org/packages/6b/8d/ce438c28c7958e33184e8ac851ea2225b47a41e5e9e708fa3bddba631135/pbr-7.1.3.tar.gz", hash = "sha256:9a4a85b84e906337708009af0b5f5cdabeeb72d4dc213c9e97974da54fd9acc5", size = 140100, upload-time = "2026-10-07T10:38:15.526Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/bb/a2/79a926b7ab54b247c3419bfa00cfbeb78ad495d21c6d787c978c6261623d/pbr-7.1.3-py2.py3-none-any.whl", hash = "sha256:6583e878a1d97cb135fdc509811f31b9235905cde8d4dacd3dbadf9efc45d745", size = 136717, upload-time = "2026-10-07T10:38:14.069Z" },+]+[[package]]name = "pdbpp"version = "0.12.1"@@ -2957,6 +3015,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/57/c9/e69b1ff4c8b69093ef08b8919ab767af0569666865b39c30a8795d88d3c6/ruff-0.15.22-py3-none-win_arm64.whl", hash = "sha256:e1168075b72158510839f250027659cdd78476f40507dd517892304c41318661", size = 11298172, upload-time = "2026-07-16T15:14:10.51Z" },]+[[package]]+name = "setuptools"+version = "84.2.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" },+]+[[package]]name = "shellingham"version = "1.5.4"@@ -3015,6 +3082,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },]+[[package]]+name = "stevedore"+version = "5.9.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/db/a1/3b8ed9c1fc3aa6eebb57732d924ddaa0500ecc3b638d0454816320994383/stevedore-5.9.1.tar.gz", hash = "sha256:e97a2667923efda926e8713fde6a73616df68210a3cbc6f02b48967b676fd8bf", size = 518111, upload-time = "2026-08-20T15:25:14.754Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c5/97/bba6e7ec2f5498b9dcb7b1b6400086b80ae5a8ebaff4b25e8c8add75f439/stevedore-5.9.1-py3-none-any.whl", hash = "sha256:5c8ff3a9f336cc1a06ac0f597bc79d11a2f950bfd32e290ca56b5a301fafafbf", size = 54931, upload-time = "2026-08-20T15:25:13.602Z" },+]+[[package]]name = "tenacity"version = "9.1.4"