8000 fix[auth]: clarify API key extraction semantics by aschlean · Pull Request #141 · golf-mcp/golf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,9 @@ configure_dev_auth(
)
```

### API Key Authentication
```python
# In auth.py
from golf.auth import configure_api_key

configure_api_key(
header_name="Authorization",
header_prefix="Bearer ",
required=True,
)
```
### API Key header extraction (deprecated)
`configure_api_key()` is not MCP authentication. It only extracts a
caller-provided header for `get_api_key()` so tools can forward that
credential to an upstream API, which validates it. Golf does not check
the key value. Use JWT, OAuth, or development tokens to authenticate
MCP clients. This helper will be removed in a future release.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Golf is a **framework** designed to streamline the creation of MCP server applic
Golf targets FastMCP 4.0.0 and the current MCP 2026-07-28 protocol.
FastMCP also negotiates legacy MCP clients through its compatibility mode.

With Golf v0.2.0, you get **enterprise-grade authentication** (JWT, OAuth Server, API key, development tokens), **built-in utilities** for LLM interactions, and **automatic telemetry** integration. Focus on implementing your agent's logic while Golf handles authentication, monitoring, and server infrastructure.
With Golf v0.2.0, you get **enterprise-grade authentication** (JWT, OAuth Server, development tokens), **built-in utilities** for LLM interactions, and **automatic telemetry** integration. Focus on implementing your agent's logic while Golf handles authentication, monitoring, and server infrastructure.

## Quick Start

Expand Down
21 changes: 20 additions & 1 deletion src/golf/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@
)

# Re-export for backward compatibility
from .api_key import configure_api_key, get_api_key_config, is_api_key_configured
from .api_key import (
ApiKeyMiddleware,
configure_api_key,
get_api_key_config,
is_api_key_configured,
reset_api_key_config,
)
from .helpers import (
CallerAuth,
extract_token_from_header,
Expand All @@ -51,6 +57,7 @@
"configure_dev_auth",
"configure_oauth_proxy",
"get_auth_config",
"reset_auth_config",
# Provider configurations
"AuthConfig",
"JWTAuthConfig",
Expand All @@ -73,9 +80,11 @@
"register_provider_factory",
"register_provider_plugin",
# API key functions (backward compatibility)
"ApiKeyMiddleware",
"configure_api_key",
"get_api_key_config",
"is_api_key_configured",
"reset_api_key_config",
# Helper functions
"CallerAuth",
"extract_token_from_header",
Expand Down Expand Up @@ -357,6 +366,16 @@ def is_auth_configured() -> bool:
return _auth_config is not None


def reset_auth_config() -> None:
"""Clear process-global FastMCP auth configuration.

The builder calls this before loading a project's auth.py so one project
cannot inherit another project's provider settings.
"""
global _auth_config
_auth_config = None


# Breaking change in Golf 0.2.x: Legacy auth system removed
# Users must migrate to modern auth configurations

Expand Down
125 changes: 103 additions & 22 deletions src/golf/auth/api_key.py
Original file line number Diff line number Diff line change
@@ -1,62 +1,80 @@
"""API Key authentication support for Golf MCP servers.
"""Deprecated caller API-key extraction for Golf MCP servers.

This module provides an explicitly non-MCP custom API-key mode. It is separate
from FastMCP JWT/OAuth resource-token authentication. Never configure it as a
way to expose or forward inbound MCP resource tokens to upstream services.
This module is not MCP authentication. It extracts a caller-provided header so
tools can forward that credential to an upstream API, which is responsible for
validating it. Golf does not compare the value against any expected secret.

Never configure this as a way to expose or forward inbound MCP resource tokens
to upstream services. Prefer FastMCP JWT/OAuth authentication instead.
"""

from __future__ import annotations

import warnings
from collections.abc import Awaitable, Callable, Mapping

from pydantic import BaseModel, Field
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response

_UNPROTECTED_PATHS = frozenset({"/metrics", "/health"})

_DEPRECATION_MESSAGE = (
"configure_api_key() is deprecated and is not MCP authentication. "
"It only extracts a caller-provided header for get_api_key() so tools can "
"forward that credential to an upstream API, which is responsible for "
"validating it. Golf does not verify API key values. Use configure_jwt_auth() "
"or configure_dev_auth() to authenticate MCP clients. This helper will be "
"removed in a future release."
)


class ApiKeyConfig(BaseModel):
"""Configuration for API key authentication."""
"""Configuration for deprecated caller API-key header extraction."""

header_name: str = Field("X-API-Key", description="Name of the header containing the API key")
header_prefix: str = Field(
"",
description="Optional prefix to strip from the header value (e.g., 'Bearer ')",
)
required: bool = Field(True, description="Whether API key is required for all requests")
required: bool = Field(True, description="Whether the header must be present on inbound requests")


# Global configuration storage
_api_key_config: ApiKeyConfig | None = None


def configure_api_key(header_name: str = "X-API-Key", header_prefix: str = "", required: bool = True) -> None:
"""Configure API key extraction from request headers.
"""Extract a caller-provided API key from request headers.

This function should be called in auth.py to set up API key handling.
Deprecated: this is not MCP-server authentication. The extracted value is
made available to tools via ``get_api_key()`` so they can call an upstream
API. That upstream service validates the key. Golf never checks the value.

Args:
header_name: Name of the header containing the API key (default: "X-API-Key")
header_prefix: Optional prefix to strip from the header value (e.g., "Bearer ")
required: Whether API key is required for all requests (default: True)
required: Whether the header must be present for all requests (default: True)

Example:
# In auth.py
# In auth.py — prefer JWT/OAuth instead of this helper
from golf.auth.api_key import configure_api_key

# Require API key for all requests
configure_api_key(
header_name="Authorization",
header_prefix="Bearer ",
required=True
)

# Or make this custom API key optional
configure_api_key(
header_name="Authorization",
header_prefix="Bearer ",
required=False
required=True,
)
"""
warnings.warn(_DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=2)

global _api_key_config
_api_key_config = ApiKeyConfig(header_name=header_name, header_prefix=header_prefix, required=required)


def get_api_key_config() -> ApiKeyConfig | None:
"""Get the current API key configuration.
"""Get the current API key extraction configuration.

Returns:
The API key configuration if set, None otherwise
Expand All @@ -65,9 +83,72 @@ def get_api_key_config() -> ApiKeyConfig | None:


def is_api_key_configured() -> bool:
"""Check if API key authentication is configured.
"""Check if deprecated API key header extraction is configured.

Returns:
True if API key authentication is configured, False otherwise
True if API key extraction is configured, False otherwise
"""
return _api_key_config is not None


def reset_api_key_config() -> None:
"""Clear process-global API key configuration.

The builder calls this before loading a project's auth.py so one project
cannot inherit another project's API-key settings.
"""
global _api_key_config
_api_key_config = None


def extract_api_key_from_headers(headers: Mapping[str, str], config: ApiKeyConfig) -> str | None:
"""Extract and normalize the API key from request headers."""
raw: str | None = None
for name, value in headers.items():
if name.lower() == config.header_name.lower():
raw = value
break

if raw is None:
return None

if config.header_prefix and raw.startswith(config.header_prefix):
raw = raw[len(config.header_prefix) :]

stripped = raw.strip()
return stripped or None


class ApiKeyMiddleware(BaseHTTPMiddleware):
"""Extract a caller-provided API key; do not treat the value as authenticated.

When ``required`` is True, a missing header is rejected so tools have a
credential to forward upstream. The value itself is not verified here.
"""

async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
if request.url.path in _UNPROTECTED_PATHS:
return await call_next(request)

config = get_api_key_config()
if config is None:
return await call_next(request)

provided = extract_api_key_from_headers(request.headers, config)
if provided:
request.state.api_key = provided
from golf.auth.helpers import set_api_key

set_api_key(provided)

if config.required and not provided:
return JSONResponse(
{
"error": "unauthorized",
"detail": f"Missing required {config.header_name} header",
},
status_code=401,
headers={"WWW-Authenticate": f'{config.header_name} realm="MCP Server"'},
)

return await call_next(request)
48 changes: 11 additions & 37 deletions src/golf/auth/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def extract_token_from_header(auth_header: str) -> str | None:
"""Extract a bearer value for custom API-key authentication only.
"""Extract a bearer value for custom API-key forwarding only.

Do not use this helper to forward an MCP resource token to another API.
MCP tokens are audience-bound credentials for this resource server.
Expand Down Expand Up @@ -42,11 +42,13 @@ def set_api_key(api_key: str | None) -> None:


def get_api_key() -> str | None:
"""Get a caller-provided key in explicit custom API-key mode.
"""Get a caller-provided key for forwarding to an upstream API.

This helper does not expose credentials verified by FastMCP JWT/OAuth
authentication. A custom API key may be used upstream only when that key
was explicitly issued for the upstream API.
This helper does not authenticate the MCP client and does not expose
credentials verified by FastMCP JWT/OAuth authentication. The returned
value is whatever the caller sent; the upstream API is responsible for
validating it. Use it only when that key was explicitly issued for the
upstream API.

Returns:
The API key if available, None otherwise
Expand All @@ -64,54 +66,26 @@ async def call_api():
headers = {"Authorization": f"Bearer {api_key}"}
...
"""
# Try to get directly from HTTP request if available (FastMCP pattern)
try:
# This follows the FastMCP pattern for accessing HTTP requests
from fastmcp.server.dependencies import get_http_request
from golf.auth.api_key import extract_api_key_from_headers, get_api_key_config

request = get_http_request()

if request and hasattr(request, "state") and hasattr(request.state, "api_key"):
api_key = request.state.api_key
return api_key

# Get the API key configuration
from golf.auth.api_key import get_api_key_config
return request.state.api_key

api_key_config = get_api_key_config()

if api_key_config and request:
# Extract API key from headers
header_name = api_key_config.header_name
header_prefix = api_key_config.header_prefix

# Case-insensitive header lookup
api_key = None
for k, v in request.headers.items():
if k.lower() == header_name.lower():
api_key = v
break

# Strip prefix if configured
if api_key and header_prefix and api_key.startswith(header_prefix):
api_key = api_key[len(header_prefix) :]

if api_key:
return api_key
return extract_api_key_from_headers(request.headers, api_key_config)
except (ImportError, RuntimeError):
# FastMCP not available or not in HTTP context
pass
except Exception:
pass

# Final fallback: environment variable (for development/testing)
import os

env_api_key = os.environ.get("API_KEY")
if env_api_key:
return env_api_key

return None
return os.environ.get("API_KEY")


@dataclass(frozen=True)
Expand Down
8 changes: 7 additions & 1 deletion src/golf/core/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -1544,6 +1544,12 @@ def build_project(
"""
# Load environment variables from .env for build operations
from dotenv import load_dotenv
from golf.auth import reset_auth_config
from golf.auth.api_key import reset_api_key_config

# Isolate this build from any process-global auth left by a previous project.
reset_auth_config()
reset_api_key_config()

project_env_file = project_path / ".env"
if project_env_file.exists():
Expand Down Expand Up @@ -1763,7 +1769,7 @@ def build_project(
# Legacy ProviderConfig removed in Golf 0.2.x - use modern auth configurations
# Legacy OAuth imports removed; use FastMCP 4.0.0 auth providers
from golf.auth.helpers import extract_token_from_header, get_api_key, set_api_key
from golf.auth.api_key import configure_api_key, get_api_key_config
from golf.auth.api_key import ApiKeyMiddleware, configure_api_key, get_api_key_config
from golf.auth.factory import create_auth_provider
from golf.auth.providers import RemoteAuthConfig, JWTAuthConfig, StaticTokenConfig, OAuthServerConfig
"""
Expand Down
Loading
Loading
0