Spaces:
Sleeping
Sleeping
Jeremiah Lowin commited on
Commit ·
b310c16
1
Parent(s): 0fcdf08
Support configuring bearer auth from env vars
Browse filesFiles changed (7)
38 unmodified lines3940414243444538 unmodified linesif isinstance(service_documentation_url, str):service_documentation_url = AnyHttpUrl(service_documentation_url)self.settings = AuthSettings(issuer_url=issuer_url,service_documentation_url=service_documentation_url,client_registration_options=client_registration_options,38 unmodified lines3940414243444538 unmodified linesif isinstance(service_documentation_url, str):service_documentation_url = AnyHttpUrl(service_documentation_url)self.auth_settings = AuthSettings(issuer_url=issuer_url,service_documentation_url=service_documentation_url,client_registration_options=client_registration_options,
12345678910111213141516171819202122232425139 unmodified lines1651661671681691701712 unmodified lines174175176177178179180181182183184185186187188189190191192193194195196197198"""Simple JWT Bearer Token validation for hosted MCP servers.Uses RS256 (asymmetric) where your control plane signs with a private keyand hosted MCP servers validate with the corresponding public key.Example usage:# Static public keyprovider = BearerAuthProvider(public_key='''-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...-----END PUBLIC KEY-----''',issuer="https://auth.yourservice.com")# Or JWKS URI (recommended for production - allows key rotation)provider = Bear(jwks_uri="https://auth.yourservice.com/.well-known/jwks.json",issuer="https://auth.yourservice.com")"""import timefrom dataclasses import dataclassfrom typing import Any, TypedDict139 unmodified linespayload,key=self.private_key.get_secret_value(),)return token_bytes.decode("utf-8")2 unmodified linesSimple JWT Bearer Token validator for hosted MCP servers.Uses RS256 asymmetric encryption. Supports either static public keyor JWKS URI for key rotation."""def __init__(self,issuer: str | None = None,public_key: str | None = None,jwks_uri: str | None = None,audience: str | None = None,required_scopes: list[str] | None = None,):"""Initialize the provider.Args:issuer: Expected issuer claim (your control plane)public_key: RSA public key in PEM format (for static key)jwks_uri: URI to fetch keys from (for key rotation)audience: Expected audience claim (optional)required_scopes: List of required scopes for access"""if not (public_key or jwks_uri):raise ValueError("Either public_key or jwks_uri must be provided")123139 unmodified lines1431441451461471482 unmodified lines151152153154155156157158159160161162163164165166167168169170171172173174175176177178import timefrom dataclasses import dataclassfrom typing import Any, TypedDict139 unmodified linespayload,key=self.private_key.get_secret_value(),)return token_bytes.decode("utf-8")2 unmodified linesSimple JWT Bearer Token validator for hosted MCP servers.Uses RS256 asymmetric encryption. Supports either static public keyor JWKS URI for key rotation.Note that this provider DOES NOT permit client registration or revocation, or any OAuth flows.It is intended to be used with a control plane that manages clients and tokens."""def __init__(self,public_key: str | None = None,jwks_uri: str | None = None,issuer: str | None = None,audience: str | None = None,required_scopes: list[str] | None = None,):"""Initialize the provider. Either public_key or jwks_uri must be provided.Args:public_key: RSA public key in PEM format (for static key)jwks_uri: URI to fetch keys from (for key rotation)issuer: Expected issuer claim (optional)audience: Expected audience claim (optional)required_scopes: List of required scopes for access (optional)"""if not (public_key or jwks_uri):raise ValueError("Either public_key or jwks_uri must be provided")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from enum import Enum
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastmcp.server.auth.providers.bearer import BearerAuthProvider
class NotSet(Enum): sentinel = 0
NOTSET = NotSet.sentinel
class EnvBearerAuthProviderSettings(BaseSettings): """Settings for the BearerAuthProvider."""
model_config = SettingsConfigDict( env_prefix="FASTMCP_AUTH_BEARER_", env_file=".env", extra="ignore", )
public_key: str | None = None jwks_uri: str | None = None issuer: str | None = None audience: str | None = None required_scopes: list[str] | None = None
class EnvBearerAuthProvider(BearerAuthProvider): """ A BearerAuthProvider that loads settings from environment variables. """
def __init__( self, public_key: str | None | NotSet = NOTSET, jwks_uri: str | None | NotSet = NOTSET, issuer: str | None | NotSet = NOTSET, audience: str | None | NotSet = NOTSET, required_scopes: list[str] | None | NotSet = NOTSET, ): kwargs = { "public_key": public_key, "jwks_uri": jwks_uri, "issuer": issuer, "audience": audience, "required_scopes": required_scopes, } settings = EnvBearerAuthProviderSettings( **{k: v for k, v in kwargs.items() if v is not NOTSET} ) super().__init__(**settings.model_dump())90 unmodified lines91929394959697989910010110210310410590 unmodified linesMiddleware(AuthContextMiddleware),]required_scopes = auth.settings.required_scopes or []auth_routes.extend(create_auth_routes(provider=auth,issuer_url=auth.settings.issuer_url,service_documentation_url=auth.settings.service_documentation_url,client_registration_options=auth.settings.client_registration_options,revocation_options=auth.settings.revocation_options,))90 unmodified lines91929394959697989910010110210310410590 unmodified linesMiddleware(AuthContextMiddleware),]required_scopes = auth.auth_settings.required_scopes or []auth_routes.extend(create_auth_routes(provider=auth,issuer_url=auth.auth_settings.issuer_url,service_documentation_url=auth.auth_settings.service_documentation_url,client_registration_options=auth.auth_settings.client_registration_options,revocation_options=auth.auth_settings.revocation_options,))
47 unmodified lines484950515253132 unmodified lines18618718818919019147 unmodified linesfrom fastmcp.resources import Resource, ResourceManagerfrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.auth.auth import OAuthProviderfrom fastmcp.server.http import (StarletteWithLifespan,create_sse_app,132 unmodified lineslifespan=_lifespan_wrapper(self, lifespan),)self.auth = authif tools:47 unmodified lines48495051525354132 unmodified lines18718818919019119219319447 unmodified linesfrom fastmcp.resources import Resource, ResourceManagerfrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.auth.auth import OAuthProviderfrom fastmcp.server.auth.providers.bearer_env import EnvBearerAuthProviderfrom fastmcp.server.http import (StarletteWithLifespan,create_sse_app,132 unmodified lineslifespan=_lifespan_wrapper(self, lifespan),)if auth is None and self.settings.auth_provider == "bearer_env":auth = EnvBearerAuthProvider()self.auth = authif tools:
4 unmodified lines567891011164 unmodified lines1761771781791804 unmodified linesfrom typing import Annotated, Literalfrom pydantic import Field, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom typing_extensions import SelfLOG_LEVEL = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]164 unmodified linesFalse # If True, uses true stateless mode (new transport per request))settings = Settings()4 unmodified lines567891011121314164 unmodified lines1791801811821831841851864 unmodified linesfrom typing import Annotated, Literalfrom pydantic import Field, model_validatorfrom pydantic_settings import (BaseSettings,SettingsConfigDict,)from typing_extensions import SelfLOG_LEVEL = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]164 unmodified linesFalse # If True, uses true stateless mode (new transport per request))# Auth settingsauth_provider: Literal["bearer_env"] | None = Nonesettings = Settings()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import pytestfrom pydantic import AnyHttpUrl, ValidationError
from fastmcp import FastMCPfrom fastmcp.server.auth.providers.bearer import BearerAuthProviderfrom fastmcp.server.auth.providers.bearer_env import EnvBearerAuthProvider
def test_load_bearer_env_from_env_var(monkeypatch): mcp = FastMCP() assert mcp.auth is None
monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
mcp_with_auth = FastMCP() assert isinstance(mcp_with_auth.auth, EnvBearerAuthProvider)
def test_load_bearer_env_from_env_var_requires_public_key_or_jwks_uri(monkeypatch): mcp = FastMCP() assert mcp.auth is None
monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env")
with pytest.raises( ValueError, match="Either public_key or jwks_uri must be provided" ): FastMCP()
def test_configure_bearer_env_from_env_var(monkeypatch): monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key") monkeypatch.setenv("FASTMCP_AUTH_BEARER_ISSUER", "http://test-issuer") monkeypatch.setenv("FASTMCP_AUTH_BEARER_AUDIENCE", "test-audience") monkeypatch.setenv( "FASTMCP_AUTH_BEARER_REQUIRED_SCOPES", '["test-scope1", "test-scope2"]' )
mcp = FastMCP() assert isinstance(mcp.auth, EnvBearerAuthProvider) assert mcp.auth.public_key == "test-public-key" assert mcp.auth.issuer == "http://test-issuer" assert mcp.auth.auth_settings.issuer_url == AnyHttpUrl("http://test-issuer") assert mcp.auth.audience == "test-audience" assert mcp.auth.auth_settings.required_scopes == ["test-scope1", "test-scope2"]
def test_list_of_scopes_must_be_a_list(monkeypatch): monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_REQUIRED_SCOPES", "test-scope1")
with pytest.raises(ValidationError, match="Input should be a valid list"): FastMCP()
def test_configure_bearer_env_jwks_uri_from_env_var(monkeypatch): monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_JWKS_URI", "test-jwks-uri")
mcp = FastMCP() assert isinstance(mcp.auth, EnvBearerAuthProvider) assert mcp.auth.jwks_uri == "test-jwks-uri"
def test_configure_bearer_env_public_key_and_jwks_uri_error(monkeypatch): monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key") monkeypatch.setenv("FASTMCP_AUTH_BEARER_JWKS_URI", "test-jwks-uri")
with pytest.raises(ValueError, match="Provide either public_key or jwks_uri"): FastMCP()
def test_provided_auth_takes_precedence_over_env_vars(monkeypatch): monkeypatch.setenv("FASTMCP_SERVER_AUTH_PROVIDER", "bearer_env") monkeypatch.setenv("FASTMCP_AUTH_BEARER_PUBLIC_KEY", "test-public-key")
mcp = FastMCP(auth=BearerAuthProvider(public_key="test-public-key-2")) assert isinstance(mcp.auth, BearerAuthProvider) assert not isinstance(mcp.auth, EnvBearerAuthProvider) assert mcp.auth.public_key == "test-public-key-2"src/fastmcp/server/auth/auth.py+1-1
src/fastmcp/server/auth/providers/bearer.py+7-27
src/fastmcp/server/auth/providers/bearer_env.pyAdded+54
src/fastmcp/server/http.py+5-5
src/fastmcp/server/server.py+3
src/fastmcp/settings.py+7-1
tests/auth/providers/test_bearer_env.pyAdded+83