Skip to content

Automate browser based workflows with AI

Add proxy OAuth endpoints for remote MCP authentication (#5558)

Marc Kelechava49b8145f7db2
diff --git a/skyvern/cli/core/mcp_http_auth.py b/skyvern/cli/core/mcp_http_auth.py
index 85c28dfc5..f60e125b2 100644
--- a/skyvern/cli/core/mcp_http_auth.py
+++ b/skyvern/cli/core/mcp_http_auth.py
@@ -1,11 +1,15 @@
from __future__ import annotations
import asyncio
+import base64
+import hashlib
+import json
import os
import time
from collections import OrderedDict
from dataclasses import dataclass
from threading import RLock
+from urllib.parse import urlsplit, urlunsplit
import structlog
from fastapi import HTTPException
@@ -14,6 +18,8 @@ from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from skyvern.config import settings
+from skyvern.forge import app
+from skyvern.forge.sdk.core.aiohttp_helper import aiohttp_request
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.services.org_auth_service import resolve_org_from_api_key
@@ -23,16 +29,28 @@ from .client import reset_api_key_override, set_api_key_override
LOG = structlog.get_logger(__name__)
API_KEY_HEADER = "x-api-key"
+AUTHORIZATION_HEADER = "authorization"
+BEARER_PREFIX = "Bearer "
HEALTH_PATHS = {"/health", "/healthz"}
_MCP_ALLOWED_TOKEN_TYPES = (OrganizationAuthTokenType.api,)
_auth_db: AgentDB | None = None
_auth_db_lock = RLock()
_api_key_cache_lock = RLock()
-_api_key_validation_cache: OrderedDict[str, tuple[MCPAPIKeyValidation | None, float]] = OrderedDict()
+# Cache entries are namespace-separated by key prefix:
+# `cache_key(...)` stores MCPAPIKeyValidation, `_oauth_cache_key(...)` stores
+# _OAuthResolution. Keep those prefixes distinct if this cache evolves.
+_api_key_validation_cache: OrderedDict[str, tuple[MCPAPIKeyValidation | _OAuthResolution | None, float]] = OrderedDict()
+_OAUTH_CACHE_TTL_SECONDS = 30.0
_NEGATIVE_CACHE_TTL_SECONDS = 5.0
_VALIDATION_RETRY_EXHAUSTED_MESSAGE = "API key validation temporarily unavailable"
_MAX_VALIDATION_RETRIES = 2
_RETRY_DELAY_SECONDS = 0.25
+_OAUTH_UNAVAILABLE_MSG = "OAuth authentication requires cloud deployment"
+_OAUTH_SERVICE_UNAVAILABLE_MSG = "Authentication service temporarily unavailable"
+_DEFAULT_REMOTE_BASE_URL = "https://api.skyvern.com"
+_MCP_REALM = "mcp"
+_RESOURCE_CLAIM_KEYS = ("resource",)
+_TOKEN_CLOCK_SKEW_SECONDS = 60.0
@dataclass(frozen=True)
@@ -41,6 +59,176 @@ class MCPAPIKeyValidation:
token_type: OrganizationAuthTokenType
+@dataclass(frozen=True)
+class _OAuthResolution:
+ """Resolved OAuth token: the org's internal API key + validation metadata."""
+
+ api_key: str
+ validation: MCPAPIKeyValidation
+
+
+def _canonical_mcp_url(base_url: str | None = None) -> str:
+ candidate = (base_url or settings.SKYVERN_BASE_URL or _DEFAULT_REMOTE_BASE_URL).strip()
+ if not candidate:
+ candidate = _DEFAULT_REMOTE_BASE_URL
+ parts = urlsplit(candidate)
+ path = (parts.path or "").rstrip("/")
+ if path.endswith("/mcp"):
+ canonical_path = f"{path}/"
+ else:
+ canonical_path = f"{path}/mcp/" if path else "/mcp/"
+ return urlunsplit((parts.scheme, parts.netloc, canonical_path, "", ""))
+
+
+def _canonical_resource_metadata_url(base_url: str | None = None) -> str:
+ mcp_url = _canonical_mcp_url(base_url)
+ parts = urlsplit(mcp_url)
+ suffix = parts.path.rstrip("/").lstrip("/")
+ metadata_path = f"/.well-known/oauth-protected-resource/{suffix}"
+ return urlunsplit((parts.scheme, parts.netloc, metadata_path, "", ""))
+
+
+def _oauth_challenge_header(base_url: str | None = None) -> str:
+ return f'Bearer realm="{_MCP_REALM}", resource_metadata="{_canonical_resource_metadata_url(base_url)}"'
+
+
+def _apply_oauth_exposed_headers(headers: dict[str, str]) -> dict[str, str]:
+ headers["Access-Control-Expose-Headers"] = "WWW-Authenticate"
+ return headers
+
+
+def _looks_like_jwt(token: str) -> bool:
+ parts = token.split(".")
+ if len(parts) != 3 or not all(parts):
+ return False
+
+ header_segment = parts[0]
+ padded_header = header_segment + "=" * (-len(header_segment) % 4)
+ try:
+ header_bytes = base64.urlsafe_b64decode(padded_header)
+ header = json.loads(header_bytes)
+ except Exception:
+ return False
+
+ if not isinstance(header, dict):
+ return False
+
+ alg = header.get("alg")
+ if not isinstance(alg, str) or not alg:
+ return False
+
+ token_type = header.get("typ")
+ if token_type is None:
+ return True
+ if not isinstance(token_type, str):
+ return False
+ return token_type.lower() in {"jwt", "at+jwt"}
+
+
+def _normalize_issuer(value: str) -> str:
+ return value.rstrip("/")
+
+
+def _get_oauth_issuer_url() -> str:
+ issuer = _normalize_issuer(app.AGENT_FUNCTION.get_mcp_oauth_issuer_url() or "")
+ if not issuer:
+ raise HTTPException(status_code=401, detail=_OAUTH_UNAVAILABLE_MSG)
+ return issuer
+
+
+def _validate_token_issuer(payload: dict[str, object], expected_issuer: str) -> None:
+ issuer = payload.get("iss")
+ if not isinstance(issuer, str) or _normalize_issuer(issuer) != _normalize_issuer(expected_issuer):
+ raise HTTPException(status_code=401, detail="Token issuer is not valid for this MCP resource")
+
+
+def _validate_token_audience(payload: dict[str, object], expected_resource: str) -> None:
+ audience = payload.get("aud")
+ if isinstance(audience, str):
+ audiences = [audience]
+ elif isinstance(audience, list):
+ audiences = [item for item in audience if isinstance(item, str)]
+ else:
+ audiences = []
+
+ if expected_resource not in audiences:
+ raise HTTPException(status_code=401, detail="Token audience is not valid for this MCP resource")
+
+
+def _validate_token_resource_claims(payload: dict[str, object], expected_resource: str) -> None:
+ for key in _RESOURCE_CLAIM_KEYS:
+ claim_value = payload.get(key)
+ if claim_value is None:
+ continue
+ if claim_value != expected_resource:
+ raise HTTPException(status_code=401, detail="Token resource is not valid for this MCP resource")
+
+
+def _validate_oauth_token_contract(payload: dict[str, object], expected_resource: str, expected_issuer: str) -> None:
+ _validate_token_issuer(payload, expected_issuer)
+ _validate_token_audience(payload, expected_resource)
+ _validate_token_resource_claims(payload, expected_resource)
+
+
+async def _fetch_oauth_userinfo(bearer_token: str, issuer_url: str) -> dict[str, object]:
+ status, _headers, response_body = await aiohttp_request(
+ "GET",
+ f"{issuer_url}/oauth/userinfo",
+ headers={"Authorization": f"Bearer {bearer_token}"},
+ )
+ if status in {401, 403}:
+ raise HTTPException(status_code=401, detail="Invalid Bearer token")
+ if status != 200:
+ raise HTTPException(status_code=503, detail=_OAUTH_SERVICE_UNAVAILABLE_MSG)
+ if not isinstance(response_body, dict):
+ raise HTTPException(status_code=503, detail=_OAUTH_SERVICE_UNAVAILABLE_MSG)
+ if not isinstance(response_body.get("sub"), str):
+ raise HTTPException(status_code=401, detail="Bearer token missing subject claim")
+ return response_body
+
+
+async def _resolve_oauth_subject_to_org(
+ payload: dict[str, object],
+ db: object,
+) -> _OAuthResolution:
+ get_entities = getattr(db, "get_organization_entities", None)
+ get_auth_token = getattr(db, "get_valid_org_auth_token", None)
+ if not callable(get_entities) or not callable(get_auth_token):
+ LOG.debug(
+ "MCP OAuth DB object is missing required auth methods",
+ db_class=type(db).__name__,
+ has_get_organization_entities=callable(get_entities),
+ has_get_valid_org_auth_token=callable(get_auth_token),
+ )
+ raise HTTPException(status_code=401, detail=_OAUTH_UNAVAILABLE_MSG)
+
+ entity_id = payload.get("sub")
+ if not isinstance(entity_id, str) or not entity_id:
+ raise HTTPException(status_code=401, detail="Bearer token missing subject claim")
+
+ entity_type = "user"
+ org_id_claim = payload.get("org_id")
+ if isinstance(org_id_claim, str) and org_id_claim:
+ entity_type = "organization"
+ entity_id = org_id_claim
+
+ org_entities = await get_entities(entity_id, entity_type)
+ if not org_entities:
+ LOG.info("MCP OAuth: no org mapping for entity", entity_id=entity_id, entity_type=entity_type)
+ raise HTTPException(status_code=401, detail="No organization found for this user")
+
+ org_id = org_entities[0].organization_id
+ api_token = await get_auth_token(org_id, OrganizationAuthTokenType.api)
+ if not api_token:
+ from skyvern.forge.sdk.services import org_auth_token_service # noqa: PLC0415
+
+ api_token = await org_auth_token_service.create_org_api_token(org_id)
+ LOG.info("MCP OAuth: auto-created API key for org", organization_id=org_id)
+
+ validation = MCPAPIKeyValidation(organization_id=org_id, token_type=OrganizationAuthTokenType.api)
+ return _OAuthResolution(api_key=api_token.token, validation=validation)
+
+
def _resolve_api_key_cache_ttl_seconds() -> float:
raw = os.environ.get("SKYVERN_MCP_API_KEY_CACHE_TTL_SECONDS", "30")
try:
@@ -61,22 +249,16 @@ _API_KEY_CACHE_TTL_SECONDS = _resolve_api_key_cache_ttl_seconds()
_API_KEY_CACHE_MAX_SIZE = _resolve_api_key_cache_max_size()
-def _get_auth_db() -> AgentDB:
+def get_auth_db() -> AgentDB:
global _auth_db
# Guard singleton init in case HTTP transport is served with threaded workers.
with _auth_db_lock:
if _auth_db is None:
- # Prefer CloudAgentDB when available (cloud deploys) because the base
- # AgentDB.validate_org_auth_token does not handle encrypted tokens,
- # causing all API key validation to fail when ENABLE_ENCRYPTION is on.
- try:
- from cloud.db.cloud_agent_db import CloudAgentDB # noqa: PLC0415
-
- _auth_db = CloudAgentDB(settings.DATABASE_STRING, debug_enabled=settings.DEBUG_MODE)
- LOG.info("MCP auth DB initialized", db_class="CloudAgentDB")
- except ImportError:
- _auth_db = AgentDB(settings.DATABASE_STRING, debug_enabled=settings.DEBUG_MODE)
- LOG.info("MCP auth DB initialized", db_class="AgentDB")
+ _auth_db = app.AGENT_FUNCTION.build_mcp_auth_db(
+ settings.DATABASE_STRING,
+ debug_enabled=settings.DEBUG_MODE,
+ )
+ LOG.info("MCP auth DB initialized", db_class=type(_auth_db).__name__)
return _auth_db
@@ -114,7 +296,11 @@ async def validate_mcp_api_key(api_key: str) -> MCPAPIKeyValidation:
_api_key_validation_cache.move_to_end(key)
if cached_validation is None:
raise HTTPException(status_code=401, detail="Invalid API key")
- return cached_validation
+ if isinstance(cached_validation, MCPAPIKeyValidation):
+ return cached_validation
+ # The shared cache also stores OAuth resolutions under a different
+ # key namespace; treat any unexpected value here as a cache miss.
+ _api_key_validation_cache.pop(key, None)
_api_key_validation_cache.pop(key, None)
# Cache miss — do the DB lookup with simple retry on transient errors.
@@ -125,7 +311,7 @@ async def validate_mcp_api_key(api_key: str) -> MCPAPIKeyValidation:
try:
validation = await resolve_org_from_api_key(
api_key,
- _get_auth_db(),
+ get_auth_db(),
token_types=_MCP_ALLOWED_TOKEN_TYPES,
)
caller_validation = MCPAPIKeyValidation(
@@ -157,8 +343,125 @@ async def validate_mcp_api_key(api_key: str) -> MCPAPIKeyValidation:
raise HTTPException(status_code=503, detail=_VALIDATION_RETRY_EXHAUSTED_MESSAGE)
-def _unauthorized_response(message: str) -> JSONResponse:
- return JSONResponse({"error": {"code": "UNAUTHORIZED", "message": message}}, status_code=401)
+def _oauth_cache_key(bearer_token: str) -> str:
+ return "oauth:" + hashlib.sha256(bearer_token.encode()).hexdigest()
+
+
+async def validate_mcp_oauth_token(bearer_token: str) -> _OAuthResolution:
+ """Validate a Clerk-issued Bearer token and resolve the caller's org API key.
+
+ Flow:
+ 1. Check cache (keyed on hashed bearer token, 30s TTL).
+ 2. Decode the JWT locally using Clerk's public JWKS (RS256).
+ 3. Extract user identity (``sub`` claim) and map to an organization via
+ the same entity-lookup used by ``cloud/cloud_app.py:authentication_function``.
+ 4. Fetch (or auto-create) the org's internal API key.
+ 5. Cache and return.
+
+ Raises:
+ HTTPException(401) for invalid/expired tokens or missing org mapping.
+ HTTPException(503) if Clerk JWKS fetch fails (network error).
+ """
+ key = _oauth_cache_key(bearer_token)
+ expected_resource = _canonical_mcp_url()
+ expected_issuer = _get_oauth_issuer_url()
+
+ # 1. Cache hit?
+ with _api_key_cache_lock:
+ cached = _api_key_validation_cache.get(key)
+ if cached is not None:
+ cached_value, expires_at = cached
+ if expires_at > time.monotonic():
+ _api_key_validation_cache.move_to_end(key)
+ if cached_value is None:
+ raise HTTPException(status_code=401, detail="Invalid Bearer token")
+ # cached_value is an _OAuthResolution for oauth cache entries
+ if isinstance(cached_value, _OAuthResolution):
+ return cached_value
+ _api_key_validation_cache.pop(key, None)
+
+ db = get_auth_db()
+ try:
+ if _looks_like_jwt(bearer_token):
+ try:
+ import jwt as pyjwt # noqa: PLC0415
+ from jwt import PyJWK # noqa: PLC0415
+ from jwt.exceptions import InvalidKeyError, PyJWTError # noqa: PLC0415
+ except ImportError as exc:
+ # ``pyjwt`` missing is a server-side misconfiguration, not a
+ # credential problem — surface 503 so the client retries rather
+ # than invalidating otherwise-good tokens.
+ LOG.error("pyjwt is not installed; MCP OAuth Bearer validation is unavailable")
+ raise HTTPException(status_code=503, detail=_OAUTH_UNAVAILABLE_MSG) from exc
+
+ try:
+ jwt_key = await app.AGENT_FUNCTION.get_mcp_oauth_jwt_key()
+ except Exception as exc:
+ LOG.warning("Failed to fetch OAuth JWKS for MCP Bearer validation", exc_info=True)
+ raise HTTPException(status_code=503, detail=_OAUTH_SERVICE_UNAVAILABLE_MSG) from exc
+ if not jwt_key:
+ raise HTTPException(status_code=401, detail=_OAUTH_UNAVAILABLE_MSG)
+
+ try:
+ signing_key = PyJWK(jwt_key)
+ payload = pyjwt.decode(
+ bearer_token,
+ signing_key,
+ algorithms=["RS256"],
+ leeway=_TOKEN_CLOCK_SKEW_SECONDS,
+ )
+ except (InvalidKeyError, PyJWTError):
+ LOG.info("MCP OAuth Bearer token failed JWT verification")
+ raise HTTPException(status_code=401, detail="Invalid Bearer token")
+
+ _validate_oauth_token_contract(
+ payload,
+ expected_resource=expected_resource,
+ expected_issuer=expected_issuer,
+ )
+ else:
+ # Opaque (non-JWT) Bearer tokens cannot be audience-validated via
+ # ``/oauth/userinfo`` — that endpoint returns a user profile, not
+ # OAuth claims, so we have no way to confirm the token was issued
+ # for THIS MCP resource rather than another client under the same
+ # Clerk tenant. Reject instead of authenticating blindly. Callers
+ # holding a Clerk session should mint a JWT via a template (the
+ # flow used by ``McpAuthPage``) and retry.
+ LOG.info("Rejecting non-JWT Bearer token for MCP OAuth: audience cannot be validated")
+ raise HTTPException(status_code=401, detail="Opaque Bearer tokens are not supported")
+
+ resolution = await _resolve_oauth_subject_to_org(payload, db)
+ except HTTPException as exc:
+ if exc.status_code in {401, 403}:
+ _cache_negative_oauth(key)
+ raise
+
+ with _api_key_cache_lock:
+ _api_key_validation_cache[key] = (resolution, time.monotonic() + _OAUTH_CACHE_TTL_SECONDS)
+ _api_key_validation_cache.move_to_end(key)
+ while len(_api_key_validation_cache) > _API_KEY_CACHE_MAX_SIZE:
+ _api_key_validation_cache.popitem(last=False)
+ return resolution
+
+
+def _cache_negative_oauth(key: str) -> None:
+ with _api_key_cache_lock:
+ _api_key_validation_cache[key] = (None, time.monotonic() + _NEGATIVE_CACHE_TTL_SECONDS)
+ _api_key_validation_cache.move_to_end(key)
+ while len(_api_key_validation_cache) > _API_KEY_CACHE_MAX_SIZE:
+ _api_key_validation_cache.popitem(last=False)
+
+
+def _unauthorized_response(message: str, *, include_oauth_challenge: bool = True) -> JSONResponse:
+ headers: dict[str, str] = {}
+ if include_oauth_challenge:
+ headers["WWW-Authenticate"] = _oauth_challenge_header()
+ _apply_oauth_exposed_headers(headers)
+ return JSONResponse(
+ {"error": {"code": "UNAUTHORIZED", "message": message}},
+ status_code=401,
+ headers=headers,
+ )
def _internal_error_response() -> JSONResponse:
@@ -172,11 +475,12 @@ def _service_unavailable_response(message: str) -> JSONResponse:
return JSONResponse(
{"error": {"code": "SERVICE_UNAVAILABLE", "message": message}},
status_code=503,
+ headers={"Retry-After": "30"},
)
class MCPAPIKeyMiddleware:
- """Require x-api-key for MCP HTTP transport and scope requests to that key."""
+ """Require x-api-key or Authorization: Bearer for MCP HTTP transport."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
@@ -196,19 +500,103 @@ class MCPAPIKeyMiddleware:
await self.app(scope, receive, send)
return
+ # Try Authorization: Bearer first, then fall back to x-api-key.
+ auth_header = request.headers.get(AUTHORIZATION_HEADER, "")
+ if auth_header.startswith(BEARER_PREFIX):
+ bearer_token = auth_header[len(BEARER_PREFIX) :]
+ if not bearer_token:
+ response = _unauthorized_response("Empty Bearer token")
+ await response(scope, receive, send)
+ return
+ await self._handle_bearer(scope, receive, send, bearer_token)
+ return
+
api_key = request.headers.get(API_KEY_HEADER)
if not api_key:
- response = _unauthorized_response("Missing x-api-key header")
+ response = _unauthorized_response("Missing x-api-key or Authorization: Bearer header")
+ await response(scope, receive, send)
+ return
+
+ await self._handle_api_key(scope, receive, send, api_key)
+
+ async def _handle_bearer(self, scope: Scope, receive: Receive, send: Send, bearer_token: str) -> None:
+ """Validate Bearer token, resolve org API key, and forward the request.
+
+ Tries Clerk OAuth token validation first, then falls back to treating
+ the Bearer value as a raw API key (for tokens issued by the proxy
+ /oauth/token endpoint). Both auth failures (401/403) and Clerk service
+ outages (503) fall through to the API-key fallback so a raw API key in
+ the Bearer slot still authenticates when Clerk is degraded. If the
+ API-key fallback also fails, the original 503 is preferred over 401
+ because the OAuth path was the authoritative validator.
+ """
+ oauth_service_error: HTTPException | None = None
+
+ try:
+ resolution = await validate_mcp_oauth_token(bearer_token)
+ scope.setdefault("state", {})
+ scope["state"]["organization_id"] = resolution.validation.organization_id
+ token = set_api_key_override(resolution.api_key)
+ try:
+ await self.app(scope, receive, send)
+ finally:
+ reset_api_key_override(token)
+ return
+ except HTTPException as e:
+ if e.status_code == 503:
+ oauth_service_error = e
+ elif e.status_code not in {401, 403}:
+ LOG.warning("Unexpected HTTPException during MCP OAuth Bearer validation", status_code=e.status_code)
+ response = _internal_error_response()
+ await response(scope, receive, send)
+ return
+ except Exception:
+ LOG.exception("Unexpected MCP OAuth Bearer validation failure")
+ response = _internal_error_response()
+ await response(scope, receive, send)
+ return
+
+ # Fall back: treat Bearer value as a raw API key
+ try:
+ validation = await validate_mcp_api_key(bearer_token)
+ scope.setdefault("state", {})
+ scope["state"]["organization_id"] = validation.organization_id
+ except HTTPException as e:
+ if e.status_code in {401, 403}:
+ if oauth_service_error is not None:
+ response = _service_unavailable_response(
+ oauth_service_error.detail or _OAUTH_SERVICE_UNAVAILABLE_MSG
+ )
+ else:
+ response = _unauthorized_response(e.detail or "Invalid Bearer token")
+ elif e.status_code == 503:
+ response = _service_unavailable_response(e.detail or _VALIDATION_RETRY_EXHAUSTED_MESSAGE)
+ else:
+ LOG.warning("Unexpected HTTPException during MCP Bearer validation", status_code=e.status_code)
+ response = _internal_error_response()
await response(scope, receive, send)
return
+ except Exception:
+ LOG.exception("Unexpected MCP Bearer validation failure")
+ response = _internal_error_response()
+ await response(scope, receive, send)
+ return
+
+ token = set_api_key_override(bearer_token)
+ try:
+ await self.app(scope, receive, send)
+ finally:
+ reset_api_key_override(token)
+ async def _handle_api_key(self, scope: Scope, receive: Receive, send: Send, api_key: str) -> None:
+ """Validate x-api-key header and forward the request (original flow)."""
try:
validation = await validate_mcp_api_key(api_key)
scope.setdefault("state", {})
scope["state"]["organization_id"] = validation.organization_id
except HTTPException as e:
if e.status_code in {401, 403}:
- response = _unauthorized_response("Invalid API key")
+ response = _unauthorized_response("Invalid API key", include_oauth_challenge=False)
elif e.status_code == 503:
response = _service_unavailable_response(e.detail or _VALIDATION_RETRY_EXHAUSTED_MESSAGE)
else:
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index bd622b915..9018f3cfb 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -16,6 +16,7 @@ from skyvern.forge.async_operations import AsyncOperation
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
@@ -438,6 +439,31 @@ class AgentFunction:
Cloud overrides this to True and provides the Temporal-backed implementations below.
"""
+ def get_mcp_oauth_issuer_url(self) -> str | None:
+ """Return the cloud OAuth issuer URL when the build provides one.
+
+ OSS builds do not ship a remote OAuth issuer, so the base implementation
+ returns None and callers should treat OAuth validation as unavailable.
+ """
+ return None
+
+ async def get_mcp_oauth_jwt_key(self) -> Any | None:
+ """Return the current signing key/JWK for MCP OAuth token validation.
+
+ Cloud builds override this to provide the identity-provider signing key.
+ OSS builds return None.
+ """
+ return None
+
+ def build_mcp_auth_db(self, database_string: str, *, debug_enabled: bool) -> Any:
+ """Return the DB instance used by MCP auth middleware.
+
+ OSS builds use the base ``AgentDB``. Cloud overrides this to provide
+ the encryption-aware ``CloudAgentDB`` implementation without importing
+ cloud modules from the OSS-synced ``skyvern/`` tree.
+ """
+ return AgentDB(database_string, debug_enabled=debug_enabled)
+
async def validate_step_execution(
self,
task: Task,
diff --git a/tests/unit/test_mcp_http_auth.py b/tests/unit/test_mcp_http_auth.py
index d7c60d03e..a677d341b 100644
--- a/tests/unit/test_mcp_http_auth.py
+++ b/tests/unit/test_mcp_http_auth.py
@@ -1,8 +1,10 @@
from __future__ import annotations
import asyncio
+import base64
+import json
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import httpx
import pytest
@@ -16,6 +18,8 @@ from starlette.routing import Route
from skyvern.cli.core import client as client_mod
from skyvern.cli.core import mcp_http_auth
+_TEST_BASE_URL = "http://testserver"
+
@pytest.fixture(autouse=True)
def _reset_auth_context() -> None:
@@ -57,29 +61,74 @@ def _build_resolved_validation(
def _build_test_app() -> Starlette:
return Starlette(
- routes=[Route("/mcp", endpoint=_echo_request_context, methods=["POST"])],
+ routes=[Route("/mcp", endpoint=_echo_request_context, methods=["GET", "HEAD", "POST"])],
middleware=[Middleware(mcp_http_auth.MCPAPIKeyMiddleware)],
)
+def _jwtish_token(
+ *,
+ header: dict[str, object] | None = None,
+ payload: dict[str, object] | None = None,
+) -> str:
+ def _encode(segment: dict[str, object]) -> str:
+ return base64.urlsafe_b64encode(json.dumps(segment, separators=(",", ":")).encode()).rstrip(b"=").decode()
+
+ encoded_header = _encode(header or {"alg": "RS256", "typ": "JWT"})
+ encoded_payload = _encode(payload or {"sub": "user_123"})
+ return f"{encoded_header}.{encoded_payload}.signature"
+
+
+async def _request(
+ app: Starlette,
+ method: str,
+ path: str,
+ **kwargs: object,
+) -> httpx.Response:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=_TEST_BASE_URL) as client:
+ return await client.request(method, path, **kwargs)
+
+
+def _stub_auth_db(monkeypatch: pytest.MonkeyPatch, db: object) -> None:
+ monkeypatch.setattr(mcp_http_auth, "get_auth_db", lambda: db)
+
+
+def _expected_oauth_challenge(monkeypatch: pytest.MonkeyPatch) -> str:
+ monkeypatch.setattr(mcp_http_auth.settings, "SKYVERN_BASE_URL", "https://api.skyvern.com")
+ return mcp_http_auth._oauth_challenge_header()
+
+
@pytest.mark.asyncio
-async def test_mcp_http_auth_rejects_missing_api_key() -> None:
+async def test_mcp_http_auth_rejects_missing_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
app = _build_test_app()
+ expected_challenge = _expected_oauth_challenge(monkeypatch)
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", json={})
+ response = await _request(app, "POST", "/mcp", json={})
assert response.status_code == 401
assert response.json()["error"]["code"] == "UNAUTHORIZED"
assert "x-api-key" in response.json()["error"]["message"]
+ assert response.headers["www-authenticate"] == expected_challenge
+ assert response.headers["access-control-expose-headers"] == "WWW-Authenticate"
+
+
+async def test_mcp_http_auth_head_request_exposes_oauth_challenge(monkeypatch: pytest.MonkeyPatch) -> None:
+ app = _build_test_app()
+ expected_challenge = _expected_oauth_challenge(monkeypatch)
+
+ response = await _request(app, "HEAD", "/mcp")
+
+ assert response.status_code == 401
+ assert response.headers["www-authenticate"] == expected_challenge
+ assert response.headers["access-control-expose-headers"] == "WWW-Authenticate"
@pytest.mark.asyncio
async def test_mcp_http_auth_allows_health_checks_without_api_key() -> None:
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.get("/healthz")
+ response = await _request(app, "GET", "/healthz")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
@@ -94,12 +143,12 @@ async def test_mcp_http_auth_rejects_invalid_api_key(monkeypatch: pytest.MonkeyP
)
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", headers={"x-api-key": "bad-key"}, json={})
+ response = await _request(app, "POST", "/mcp", headers={"x-api-key": "bad-key"}, json={})
assert response.status_code == 401
assert response.json()["error"]["code"] == "UNAUTHORIZED"
assert response.json()["error"]["message"] == "Invalid API key"
+ assert "www-authenticate" not in response.headers
@pytest.mark.asyncio
@@ -111,8 +160,7 @@ async def test_mcp_http_auth_returns_500_on_non_auth_http_exception(monkeypatch:
)
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
+ response = await _request(app, "POST", "/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
assert response.status_code == 500
assert response.json()["error"]["code"] == "INTERNAL_ERROR"
@@ -127,8 +175,7 @@ async def test_mcp_http_auth_returns_503_on_transient_validation_exhaustion(monk
)
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
+ response = await _request(app, "POST", "/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
assert response.status_code == 503
assert response.json()["error"]["code"] == "SERVICE_UNAVAILABLE"
@@ -144,8 +191,7 @@ async def test_mcp_http_auth_returns_500_on_unexpected_validation_error(monkeypa
)
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
+ response = await _request(app, "POST", "/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
assert response.status_code == 500
assert response.json()["error"]["code"] == "INTERNAL_ERROR"
@@ -160,8 +206,7 @@ async def test_mcp_http_auth_sets_request_scoped_api_key(monkeypatch: pytest.Mon
)
app = _build_test_app()
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
- response = await client.post("/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
+ response = await _request(app, "POST", "/mcp", headers={"x-api-key": "sk_live_abc"}, json={})
assert response.status_code == 200
assert response.json() == {
@@ -181,7 +226,7 @@ async def test_validate_mcp_api_key_uses_ttl_cache(monkeypatch: pytest.MonkeyPat
return _build_resolved_validation("org_cached")
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
first = await mcp_http_auth.validate_mcp_api_key("sk_test_cache")
second = await mcp_http_auth.validate_mcp_api_key("sk_test_cache")
@@ -201,7 +246,7 @@ async def test_validate_mcp_api_key_cache_expires(monkeypatch: pytest.MonkeyPatc
return _build_resolved_validation(f"org_{calls}")
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
first = await mcp_http_auth.validate_mcp_api_key("sk_test_cache_expire")
cache_key = mcp_http_auth.cache_key("sk_test_cache_expire")
@@ -223,7 +268,7 @@ async def test_validate_mcp_api_key_negative_caches_auth_failures(monkeypatch: p
raise HTTPException(status_code=401, detail="Invalid credentials")
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
with pytest.raises(HTTPException, match="Invalid credentials"):
await mcp_http_auth.validate_mcp_api_key("sk_test_auth_failure")
@@ -248,7 +293,7 @@ async def test_validate_mcp_api_key_retries_transient_failure_without_negative_c
return _build_resolved_validation("org_recovered")
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
recovered_org = await mcp_http_auth.validate_mcp_api_key("sk_test_transient")
@@ -259,6 +304,446 @@ async def test_validate_mcp_api_key_retries_transient_failure_without_negative_c
assert calls == 2
+def test_profile_to_mcp_url_normalizes_base_variants() -> None:
+ assert mcp_http_auth._canonical_mcp_url("https://api.skyvern.com") == "https://api.skyvern.com/mcp/"
+ assert mcp_http_auth._canonical_mcp_url("https://api.skyvern.com/") == "https://api.skyvern.com/mcp/"
+ assert mcp_http_auth._canonical_mcp_url("https://api.skyvern.com/mcp") == "https://api.skyvern.com/mcp/"
+ assert mcp_http_auth._canonical_mcp_url("https://api.skyvern.com/mcp/") == "https://api.skyvern.com/mcp/"
+
+
+def test_resource_metadata_url_normalizes_base_variants() -> None:
+ assert (
+ mcp_http_auth._canonical_resource_metadata_url("https://api.skyvern.com")
+ == "https://api.skyvern.com/.well-known/oauth-protected-resource/mcp"
+ )
+ assert (
+ mcp_http_auth._canonical_resource_metadata_url("https://api.skyvern.com/mcp/")
+ == "https://api.skyvern.com/.well-known/oauth-protected-resource/mcp"
+ )
+
+
+def test_validate_token_audience_rejects_wrong_resource() -> None:
+ with pytest.raises(HTTPException, match="Token audience is not valid for this MCP resource"):
+ mcp_http_auth._validate_token_audience(
+ {"aud": ["https://some-other-resource.example.com/mcp/"]},
+ "https://api.skyvern.com/mcp/",
+ )
+
+
+def test_validate_token_audience_accepts_matching_url() -> None:
+ mcp_http_auth._validate_token_audience(
+ {"aud": ["https://api.skyvern.com/mcp/"]},
+ "https://api.skyvern.com/mcp/",
+ )
+
+
+def test_looks_like_jwt_rejects_dotted_opaque_token() -> None:
+ assert mcp_http_auth._looks_like_jwt("opaque.with.dots") is False
+
+
+def test_looks_like_jwt_accepts_jwt_header() -> None:
+ assert mcp_http_auth._looks_like_jwt(_jwtish_token()) is True
+
+
+def test_validate_oauth_token_contract_rejects_invalid_issuer() -> None:
+ with pytest.raises(HTTPException, match="Token issuer is not valid for this MCP resource"):
+ mcp_http_auth._validate_oauth_token_contract(
+ {
+ "iss": "https://wrong-issuer.example.com",
+ "aud": ["https://api.skyvern.com/mcp/"],
+ },
+ expected_resource="https://api.skyvern.com/mcp/",
+ expected_issuer="https://clerk.example.com",
+ )
+
+
+def test_validate_oauth_token_contract_rejects_mismatched_resource_claim() -> None:
+ with pytest.raises(HTTPException, match="Token resource is not valid for this MCP resource"):
+ mcp_http_auth._validate_oauth_token_contract(
+ {
+ "iss": "https://clerk.example.com",
+ "aud": ["https://api.skyvern.com/mcp/"],
+ "resource": "https://api.skyvern.com/other/",
+ },
+ expected_resource="https://api.skyvern.com/mcp/",
+ expected_issuer="https://clerk.example.com",
+ )
+
+
+def test_validate_oauth_token_contract_accepts_valid_jwt_claims() -> None:
+ mcp_http_auth._validate_oauth_token_contract(
+ {
+ "iss": "https://clerk.example.com/",
+ "aud": ["https://api.skyvern.com/mcp/"],
+ "resource": "https://api.skyvern.com/mcp/",
+ },
+ expected_resource="https://api.skyvern.com/mcp/",
+ expected_issuer="https://clerk.example.com",
+ )
+
+
+async def test_fetch_oauth_userinfo_returns_payload(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "aiohttp_request",
+ AsyncMock(return_value=(200, {}, {"sub": "user_123", "email": "[email protected]"})),
+ )
+
+ payload = await mcp_http_auth._fetch_oauth_userinfo("opaque-token", "https://clerk.example.com")
+
+ assert payload == {"sub": "user_123", "email": "[email protected]"}
+ mcp_http_auth.aiohttp_request.assert_awaited_once_with(
+ "GET",
+ "https://clerk.example.com/oauth/userinfo",
+ headers={"Authorization": "Bearer opaque-token"},
+ )
+
+
+async def test_validate_mcp_oauth_token_rejects_opaque_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Opaque (non-JWT) bearer tokens cannot be audience-validated; we reject with 401."""
+ fetch_userinfo = AsyncMock(return_value={"sub": "user_123"})
+ monkeypatch.setattr(mcp_http_auth, "_fetch_oauth_userinfo", fetch_userinfo)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "_get_oauth_issuer_url",
+ lambda: "https://clerk.example.com",
+ )
+ monkeypatch.setattr(mcp_http_auth.settings, "SKYVERN_BASE_URL", "https://api.skyvern.com")
+
+ with pytest.raises(HTTPException) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token("opaque-token")
+
+ assert exc_info.value.status_code == 401
+ assert "Opaque Bearer tokens" in exc_info.value.detail
+ # The reject path must never call userinfo — we decide purely on shape.
+ fetch_userinfo.assert_not_awaited()
+
+
+async def test_validate_mcp_oauth_token_rejects_dotted_opaque_tokens(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A token with dots but not a valid JWT header is still opaque and must be rejected."""
+ fetch_userinfo = AsyncMock(return_value={"sub": "user_123"})
+ monkeypatch.setattr(mcp_http_auth, "_fetch_oauth_userinfo", fetch_userinfo)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "_get_oauth_issuer_url",
+ lambda: "https://clerk.example.com",
+ )
+ monkeypatch.setattr(mcp_http_auth.settings, "SKYVERN_BASE_URL", "https://api.skyvern.com")
+
+ with pytest.raises(HTTPException) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token("opaque.with.dots")
+
+ assert exc_info.value.status_code == 401
+ fetch_userinfo.assert_not_awaited()
+
+
+async def test_validate_mcp_oauth_token_does_not_negative_cache_503_errors(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A 503 from Clerk JWKS fetch must not be cached — the next call should retry."""
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "_get_oauth_issuer_url",
+ lambda: "https://clerk.example.com",
+ )
+ _stub_auth_db(monkeypatch, object())
+ monkeypatch.setattr(mcp_http_auth, "_looks_like_jwt", lambda _token: True)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "app",
+ SimpleNamespace(
+ AGENT_FUNCTION=SimpleNamespace(
+ get_mcp_oauth_jwt_key=AsyncMock(side_effect=RuntimeError("clerk down")),
+ )
+ ),
+ )
+
+ jwt_token = _jwtish_token()
+ with pytest.raises(HTTPException) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token(jwt_token)
+
+ assert exc_info.value.status_code == 503
+ assert mcp_http_auth._oauth_cache_key(jwt_token) not in mcp_http_auth._api_key_validation_cache
+
+
+async def test_validate_mcp_oauth_token_negative_caches_401_errors(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An invalid-signature 401 should be negative-cached so repeated bad tokens are cheap."""
+ import jwt
+ from jwt.exceptions import InvalidSignatureError
+
+ def _fake_decode(*_args: object, **_kwargs: object) -> dict[str, object]:
+ raise InvalidSignatureError("bad signature")
+
+ monkeypatch.setattr(jwt, "PyJWK", lambda key: key)
+ monkeypatch.setattr(jwt, "decode", _fake_decode)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "_get_oauth_issuer_url",
+ lambda: "https://clerk.example.com",
+ )
+ _stub_auth_db(monkeypatch, object())
+ monkeypatch.setattr(mcp_http_auth, "_looks_like_jwt", lambda _token: True)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "app",
+ SimpleNamespace(
+ AGENT_FUNCTION=SimpleNamespace(
+ get_mcp_oauth_jwt_key=AsyncMock(return_value="jwk"),
+ )
+ ),
+ )
+
+ jwt_token = _jwtish_token()
+ with pytest.raises(HTTPException) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token(jwt_token)
+
+ assert exc_info.value.status_code == 401
+ assert mcp_http_auth._oauth_cache_key(jwt_token) in mcp_http_auth._api_key_validation_cache
+
+
+async def test_validate_mcp_oauth_token_returns_401_when_cloud_jwk_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "_get_oauth_issuer_url",
+ lambda: "https://clerk.example.com",
+ )
+ _stub_auth_db(monkeypatch, object())
+ monkeypatch.setattr(mcp_http_auth, "_looks_like_jwt", lambda _token: True)
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "app",
+ SimpleNamespace(
+ AGENT_FUNCTION=SimpleNamespace(
+ get_mcp_oauth_jwt_key=AsyncMock(return_value=None),
+ )
+ ),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token("header.payload.signature")
+
+ assert exc_info.value.status_code == 401
+ assert exc_info.value.detail == "OAuth authentication requires cloud deployment"
+
+
+async def test_validate_mcp_oauth_token_passes_clock_skew_leeway_to_pyjwt(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jwt
+
+ captured: dict[str, object] = {}
+
+ def _fake_jwk(key: object) -> object:
+ captured["jwk_key"] = key
+ return key
+
+ def _fake_decode(token: str, signing_key: object, **kwargs: object) -> dict[str, object]:
+ captured["token"] = token
+ captured["signing_key"] = signing_key
+ captured["kwargs"] = kwargs
+ return {
+ "iss": "https://clerk.example.com",
+ "aud": ["https://api.skyvern.com/mcp/"],
+ "resource": "https://api.skyvern.com/mcp/",
+ "sub": "user_123",
+ }
+
+ fake_db = SimpleNamespace(
+ get_organization_entities=AsyncMock(return_value=[SimpleNamespace(organization_id="org_jwt")]),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="sk_live_from_jwt")),
+ )
+ monkeypatch.setattr(jwt, "PyJWK", _fake_jwk)
+ monkeypatch.setattr(jwt, "decode", _fake_decode)
+ _stub_auth_db(monkeypatch, fake_db)
+ monkeypatch.setattr(mcp_http_auth, "_looks_like_jwt", lambda _token: True)
+ monkeypatch.setattr(mcp_http_auth, "_get_oauth_issuer_url", lambda: "https://clerk.example.com")
+ monkeypatch.setattr(mcp_http_auth.settings, "SKYVERN_BASE_URL", "https://api.skyvern.com")
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "app",
+ SimpleNamespace(
+ AGENT_FUNCTION=SimpleNamespace(
+ get_mcp_oauth_jwt_key=AsyncMock(return_value="jwk"),
+ )
+ ),
+ )
+
+ resolution = await mcp_http_auth.validate_mcp_oauth_token(_jwtish_token())
+
+ assert resolution.api_key == "sk_live_from_jwt"
+ assert captured["kwargs"]["leeway"] == mcp_http_auth._TOKEN_CLOCK_SKEW_SECONDS
+ assert "options" not in captured["kwargs"]
+
+
+async def test_mcp_http_auth_accepts_opaque_bearer_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_oauth_token",
+ AsyncMock(
+ return_value=mcp_http_auth._OAuthResolution(
+ api_key="sk_live_opaque",
+ validation=_build_validation("org_opaque"),
+ )
+ ),
+ )
+ app = _build_test_app()
+
+ response = await _request(app, "POST", "/mcp", headers={"authorization": "Bearer opaque-token"}, json={})
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "api_key": "sk_live_opaque",
+ "organization_id": "org_opaque",
+ }
+
+
+async def test_mcp_http_auth_falls_back_to_api_key_after_invalid_oauth_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_oauth_token",
+ AsyncMock(side_effect=HTTPException(status_code=401, detail="Invalid Bearer token")),
+ )
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_api_key",
+ AsyncMock(return_value=_build_validation("org_from_api_key")),
+ )
+ app = _build_test_app()
+
+ response = await _request(
+ app,
+ "POST",
+ "/mcp",
+ headers={"authorization": "Bearer sk_live_proxy_token"},
+ json={},
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "api_key": "sk_live_proxy_token",
+ "organization_id": "org_from_api_key",
+ }
+
+
+async def test_mcp_http_auth_returns_503_when_clerk_is_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_oauth_token",
+ AsyncMock(side_effect=HTTPException(status_code=503, detail="Authentication service temporarily unavailable")),
+ )
+ # API-key fallback also rejects the token; we must still surface 503 because
+ # the OAuth path was the authoritative validator for a JWT-shaped token.
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_api_key",
+ AsyncMock(side_effect=HTTPException(status_code=401, detail="Invalid API key")),
+ )
+ app = _build_test_app()
+
+ response = await _request(app, "POST", "/mcp", headers={"authorization": "Bearer a.b.c"}, json={})
+
+ assert response.status_code == 503
+ assert response.json()["error"]["code"] == "SERVICE_UNAVAILABLE"
+ assert response.json()["error"]["message"] == "Authentication service temporarily unavailable"
+
+
+async def test_mcp_http_auth_falls_back_to_api_key_after_oauth_service_outage(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A raw API key in the Bearer slot must still authenticate when Clerk is degraded."""
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_oauth_token",
+ AsyncMock(side_effect=HTTPException(status_code=503, detail="Authentication service temporarily unavailable")),
+ )
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_api_key",
+ AsyncMock(return_value=_build_validation("org_recovered")),
+ )
+ app = _build_test_app()
+
+ response = await _request(
+ app,
+ "POST",
+ "/mcp",
+ headers={"authorization": "Bearer sk_live_proxy_token"},
+ json={},
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "api_key": "sk_live_proxy_token",
+ "organization_id": "org_recovered",
+ }
+
+
+async def test_mcp_http_auth_returns_500_when_oauth_validation_crashes(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "validate_mcp_oauth_token",
+ AsyncMock(side_effect=RuntimeError("boom")),
+ )
+ validate_mcp_api_key = AsyncMock(return_value=_build_validation("org_should_not_run"))
+ monkeypatch.setattr(mcp_http_auth, "validate_mcp_api_key", validate_mcp_api_key)
+ app = _build_test_app()
+
+ response = await _request(app, "POST", "/mcp", headers={"authorization": "Bearer a.b.c"}, json={})
+
+ assert response.status_code == 500
+ assert response.json()["error"]["code"] == "INTERNAL_ERROR"
+ validate_mcp_api_key.assert_not_awaited()
+
+
+async def test_resolve_oauth_subject_to_org_logs_missing_db_methods(monkeypatch: pytest.MonkeyPatch) -> None:
+ debug_log = Mock()
+ monkeypatch.setattr(mcp_http_auth.LOG, "debug", debug_log)
+
+ with pytest.raises(HTTPException, match="OAuth authentication requires cloud deployment"):
+ await mcp_http_auth._resolve_oauth_subject_to_org({"sub": "user_123"}, object())
+
+ debug_log.assert_called_once()
+
+
+def test_get_auth_db_uses_agent_function_builder(monkeypatch: pytest.MonkeyPatch) -> None:
+ built_db = object()
+ builder = Mock(return_value=built_db)
+
+ monkeypatch.setattr(
+ mcp_http_auth,
+ "app",
+ SimpleNamespace(
+ AGENT_FUNCTION=SimpleNamespace(build_mcp_auth_db=builder),
+ ),
+ )
+ monkeypatch.setattr(mcp_http_auth, "_auth_db", None)
+
+ db = mcp_http_auth.get_auth_db()
+
+ assert db is built_db
+ builder.assert_called_once_with(
+ mcp_http_auth.settings.DATABASE_STRING,
+ debug_enabled=mcp_http_auth.settings.DEBUG_MODE,
+ )
+
+
@pytest.mark.asyncio
async def test_validate_mcp_api_key_concurrent_callers_all_succeed(
monkeypatch: pytest.MonkeyPatch,
@@ -273,7 +758,7 @@ async def test_validate_mcp_api_key_concurrent_callers_all_succeed(
return _build_resolved_validation("org_concurrent")
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
results = await asyncio.gather(*[mcp_http_auth.validate_mcp_api_key("test-key-concurrent") for _ in range(5)])
assert all(r.organization_id == "org_concurrent" for r in results)
@@ -293,7 +778,7 @@ async def test_validate_mcp_api_key_returns_503_after_retry_exhaustion(monkeypat
monkeypatch.setattr(mcp_http_auth, "_MAX_VALIDATION_RETRIES", 2)
monkeypatch.setattr(mcp_http_auth, "resolve_org_from_api_key", _resolve)
- monkeypatch.setattr(mcp_http_auth, "_get_auth_db", lambda: object())
+ _stub_auth_db(monkeypatch, object())
with pytest.raises(HTTPException, match="temporarily unavailable") as exc_info:
await mcp_http_auth.validate_mcp_api_key("sk_test_transient_exhausted")