Skip to content

Automate browser based workflows with AI

Make MCP sign-ins use member-bound API keys (#8947)

Aaron Perez45dc4a07d7ad
diff --git a/skyvern/cli/core/mcp_http_auth.py b/skyvern/cli/core/mcp_http_auth.py
index 6a46863b1..c6b0812bd 100644
--- a/skyvern/cli/core/mcp_http_auth.py
+++ b/skyvern/cli/core/mcp_http_auth.py
@@ -91,6 +91,7 @@ class _OAuthResolution:
api_key: str
validation: MCPAPIKeyValidation
+ api_key_token_id: str | None = None
class MissingOrgContextError(HTTPException):
@@ -100,6 +101,13 @@ class MissingOrgContextError(HTTPException):
super().__init__(status_code=401, detail=_OAUTH_MISSING_ORG_CONTEXT_MSG)
+class MCPOrgRoleRequiredError(HTTPException):
+ """Raised when an organization session has no supported MCP sign-in role."""
+
+ def __init__(self) -> None:
+ super().__init__(status_code=403, detail="MCP sign-in requires an organization Admin or Member role.")
+
+
def _canonical_mcp_url(base_url: str | None = None) -> str:
"""Return the canonical MCP resource URI with no trailing slash.
@@ -334,6 +342,12 @@ async def _resolve_oauth_subject_to_org(
raise HTTPException(status_code=401, detail="No organization found for this user")
org_id = org_entities[0].organization_id
+ member_api_key = await app.AGENT_FUNCTION.resolve_mcp_oauth_member_api_key(org_id, payload)
+ if member_api_key is not None:
+ api_key_token_id, api_key = member_api_key
+ validation = MCPAPIKeyValidation(organization_id=org_id, token_type=OrganizationAuthTokenType.api)
+ return _OAuthResolution(api_key=api_key, validation=validation, api_key_token_id=api_key_token_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
@@ -348,7 +362,7 @@ async def _resolve_oauth_subject_to_org(
)
validation = MCPAPIKeyValidation(organization_id=org_id, token_type=OrganizationAuthTokenType.api)
- return _OAuthResolution(api_key=api_token.token, validation=validation)
+ return _OAuthResolution(api_key=api_token.token, validation=validation, api_key_token_id=api_token.id)
def _resolve_api_key_cache_ttl_seconds() -> float:
@@ -583,7 +597,7 @@ async def validate_mcp_oauth_token(bearer_token: str) -> _OAuthResolution:
resolution = await _resolve_oauth_subject_to_org(payload, db)
except HTTPException as exc:
- if exc.status_code in {401, 403}:
+ if exc.status_code in {401, 403} and not isinstance(exc, MCPOrgRoleRequiredError):
_cache_negative_oauth(key)
raise
@@ -778,6 +792,13 @@ class MCPAPIKeyMiddleware:
api_key=resolution.api_key,
)
return
+ except MCPOrgRoleRequiredError as e:
+ response = JSONResponse(
+ {"error": {"code": "FORBIDDEN", "message": e.detail}},
+ status_code=403,
+ )
+ await response(scope, receive, send)
+ return
except HTTPException as e:
if e.status_code == 503:
oauth_service_error = e
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index ba1b6be1d..73c9b2344 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -1760,6 +1760,17 @@ class AgentFunction:
"""
return None
+ async def resolve_mcp_oauth_member_api_key(
+ self, organization_id: str, payload: dict[str, Any]
+ ) -> tuple[str, str] | None:
+ return None
+
+ async def resolve_member_api_key_user_id(self, organization_id: str, token_id: str) -> str | None:
+ return None
+
+ async def resolve_api_key_profile(self, organization_id: str, token_id: str) -> tuple[str, str | None, bool] | None:
+ return "full_org", None, True
+
async def resolve_org_api_key(self, organization_id: str) -> str | None:
"""Return an org-scoped API key; returns None in the base implementation."""
return None
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index 43630f057..7d5c22b2a 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -158,7 +158,12 @@ def set_request_principal(
identity = _request_identity.get()
if identity is None:
return
- if identity.principal is None:
+ # The bound member key takes precedence over any bearer principal observed earlier in this request.
+ if principal.auth_kind == "member_api_key":
+ identity.principal = principal
+ identity.principal_resolution_key = resolution_key
+ identity.bearer_identity_status = bearer_identity_status
+ elif identity.principal is None:
identity.principal = principal
identity.principal_resolution_key = resolution_key
identity.bearer_identity_status = bearer_identity_status
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 48c2270fd..39ca5c8b5 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -154,7 +154,11 @@ from skyvern.forge.sdk.schemas.tasks import (
)
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunTimeline
from skyvern.forge.sdk.services import org_auth_service
-from skyvern.forge.sdk.services.request_principal import get_request_principal
+from skyvern.forge.sdk.services.request_principal import (
+ RequestPrincipal,
+ get_request_principal,
+ reject_non_admin_api_key_secret_access,
+)
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.workflow.browser_profile_key import build_workflow_browser_session_storage_key_from_digest
from skyvern.forge.sdk.workflow.exceptions import (
@@ -6465,7 +6469,9 @@ async def get_current_organization(
async def get_api_keys(
organization_id: str,
current_org: Organization = Depends(org_auth_service.get_current_org_with_api_token),
+ principal: RequestPrincipal | None = Depends(get_request_principal),
) -> GetOrganizationAPIKeysResponse:
+ reject_non_admin_api_key_secret_access(principal)
if organization_id != current_org.organization_id:
raise HTTPException(status_code=403, detail="You do not have permission to access this organization")
api_keys = []
diff --git a/skyvern/forge/sdk/services/org_auth_service.py b/skyvern/forge/sdk/services/org_auth_service.py
index 9d6cc074c..72a6910f8 100644
--- a/skyvern/forge/sdk/services/org_auth_service.py
+++ b/skyvern/forge/sdk/services/org_auth_service.py
@@ -21,7 +21,11 @@ from skyvern.forge.sdk.core.organization_age_cache import remember_organization_
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.models import TokenPayload
from skyvern.forge.sdk.schemas.organizations import Organization, OrganizationAuthToken, OrganizationAuthTokenType
-from skyvern.forge.sdk.services.request_principal import resolve_request_principal, synthetic_user_id
+from skyvern.forge.sdk.services.request_principal import (
+ resolve_api_key_profile_identity,
+ resolve_request_principal,
+ synthetic_user_id,
+)
from skyvern.forge.sdk.workflow.models.tags import CallerType
LOG = structlog.get_logger()
@@ -52,6 +56,8 @@ class ApiKeyValidationResult:
class _CachedOrganizationAuth:
organization: Organization
token_id: str
+ access_mode: str = "full_org"
+ bound_user_id: str | None = None
def _normalize_api_key_with_flags(raw_api_key: str) -> tuple[str, dict[str, bool]]:
@@ -287,12 +293,19 @@ async def _get_current_org_for_token_types(
fern_language=fern_language,
)
apply_request_org_context(validation.organization)
+ api_key_profile = (
+ await resolve_api_key_profile_identity(validation.organization.organization_id, validation.token.id)
+ if validation.token.token_type == OrganizationAuthTokenType.api
+ else None
+ )
await resolve_request_principal(
validation.organization.organization_id,
api_key_type=_api_key_type(_decode_token_before_cache(x_api_key)),
api_key_token_id=(
validation.token.id if validation.token.token_type == OrganizationAuthTokenType.api else None
),
+ api_key_profile=api_key_profile,
+ api_key_profile_resolved=api_key_profile is not None,
bearer_token=_extract_bearer_token(authorization),
)
return validation.organization
@@ -746,7 +759,15 @@ async def _get_current_org_cached(
user_agent=user_agent,
fern_language=fern_language,
)
- cached_auth = _CachedOrganizationAuth(validation.organization, validation.token.id)
+ api_key_profile = await resolve_api_key_profile_identity(
+ validation.organization.organization_id, validation.token.id
+ )
+ cached_auth = _CachedOrganizationAuth(
+ validation.organization,
+ validation.token.id,
+ api_key_profile[0],
+ api_key_profile[1],
+ )
if invalidation_generation == _current_org_cache_invalidation_generation:
_current_org_cache[cache_key] = cached_auth
@@ -789,6 +810,13 @@ async def get_current_org_cached(
user_agent=user_agent,
fern_language=fern_language,
)
+ api_key_profile = (cached_auth.access_mode, cached_auth.bound_user_id, True)
+ if cached_auth.access_mode == "member":
+ current_profile = await resolve_api_key_profile_identity(
+ cached_auth.organization.organization_id, cached_auth.token_id
+ )
+ if current_profile != api_key_profile:
+ raise HTTPException(status_code=401, detail="Invalid credentials")
organization = cached_auth.organization
token_id = cached_auth.token_id
apply_request_org_context(organization)
@@ -796,6 +824,8 @@ async def get_current_org_cached(
organization.organization_id,
api_key_type=_api_key_type(payload),
api_key_token_id=token_id,
+ api_key_profile=api_key_profile if not _claims_ui_session(payload) else None,
+ api_key_profile_resolved=not _claims_ui_session(payload),
bearer_token=_extract_bearer_token(authorization),
)
return organization
diff --git a/skyvern/forge/sdk/services/request_principal.py b/skyvern/forge/sdk/services/request_principal.py
index 8356c90bd..0da6741e3 100644
--- a/skyvern/forge/sdk/services/request_principal.py
+++ b/skyvern/forge/sdk/services/request_principal.py
@@ -23,6 +23,7 @@ class AuthKind(StrEnum):
bearer = "bearer"
# The key authorized the request; a valid bearer for the same organization supplied the user.
api_key_and_bearer = "api_key_and_bearer"
+ member_api_key = "member_api_key"
ui_session_and_bearer = "ui_session_and_bearer"
@@ -84,6 +85,29 @@ def get_request_principal() -> RequestPrincipal | None:
return resolved[1] if resolved else None
+def reject_non_admin_api_key_secret_access(principal: RequestPrincipal | None) -> None:
+ if not isinstance(principal, RequestPrincipal):
+ return
+ if principal.auth_kind == AuthKind.member_api_key:
+ raise HTTPException(status_code=403, detail="Organization API-key secrets require an Admin session")
+
+
+async def resolve_api_key_profile_identity(organization_id: str, token_id: str) -> tuple[str, str | None, bool]:
+ try:
+ profile = await app.AGENT_FUNCTION.resolve_api_key_profile(organization_id, token_id)
+ except Exception:
+ LOG.warning("Failed to resolve API key profile", exc_info=True)
+ raise HTTPException(status_code=401, detail="Invalid credentials") from None
+ if (
+ profile is None
+ or not profile[2]
+ or profile[0] not in {"full_org", "member"}
+ or (profile[0] == "member" and not profile[1])
+ ):
+ raise HTTPException(status_code=401, detail="Invalid credentials")
+ return profile
+
+
async def _resolve_bearer_identity(bearer_token: str, organization_id: str) -> BearerIdentityResolution:
try:
resolution = await asyncio.wait_for(
@@ -112,15 +136,43 @@ def _auth_kind(api_key_type: OrganizationAuthTokenType | None, has_user: bool) -
return AuthKind.api_key_and_bearer if has_user else AuthKind.api_key
+def _build_request_principal(
+ organization_id: str,
+ api_key_type: OrganizationAuthTokenType | None,
+ api_key_token_id: str | None,
+ identity: BearerIdentity | None,
+ member_user_id: str | None,
+) -> RequestPrincipal:
+ member_key = member_user_id is not None
+ return RequestPrincipal(
+ organization_id=organization_id,
+ auth_kind=AuthKind.member_api_key if member_key else _auth_kind(api_key_type, identity is not None),
+ api_key_token_id=api_key_token_id,
+ user_id=member_user_id or (identity.user_id if identity else None),
+ org_role="org:member" if member_user_id is not None else (identity.org_role if identity else None),
+ org_role_claim=identity.org_role_claim if identity else None,
+ token_has_organization_claim=(
+ True if member_key else (identity.token_has_organization_claim if identity else None)
+ ),
+ )
+
+
async def resolve_request_principal(
organization_id: str,
*,
api_key_type: OrganizationAuthTokenType | None = None,
api_key_token_id: str | None = None,
+ api_key_profile: tuple[str, str | None, bool] | None = None,
+ api_key_profile_resolved: bool = False,
bearer_token: str | None = None,
) -> RequestPrincipal:
principal = await _resolve_request_principal(
- organization_id, api_key_type=api_key_type, api_key_token_id=api_key_token_id, bearer_token=bearer_token
+ organization_id,
+ api_key_type=api_key_type,
+ api_key_token_id=api_key_token_id,
+ api_key_profile=api_key_profile,
+ api_key_profile_resolved=api_key_profile_resolved,
+ bearer_token=bearer_token,
)
await app.AGENT_FUNCTION.enforce_request_role(principal, pending_route_action.get(), _bearer_identity_status())
return principal
@@ -139,9 +191,20 @@ async def _resolve_request_principal(
*,
api_key_type: OrganizationAuthTokenType | None = None,
api_key_token_id: str | None = None,
+ api_key_profile: tuple[str, str | None, bool] | None = None,
+ api_key_profile_resolved: bool = False,
bearer_token: str | None = None,
) -> RequestPrincipal:
- """Record the caller's identity after auth without changing the request outcome."""
+ """Resolve the caller's identity and fail closed when an API-key profile is invalid."""
+ member_user_id: str | None = None
+ if api_key_type == OrganizationAuthTokenType.api and api_key_token_id:
+ if not api_key_profile_resolved:
+ api_key_profile = await resolve_api_key_profile_identity(organization_id, api_key_token_id)
+ elif api_key_profile is None:
+ raise HTTPException(status_code=401, detail="Invalid credentials")
+ if api_key_profile[0] == "member":
+ member_user_id = api_key_profile[1]
+
bearer_hash = hashlib.sha256(bearer_token.encode()).digest() if bearer_token else None
resolution_key = (
organization_id,
@@ -153,7 +216,7 @@ async def _resolve_request_principal(
request_state = get_request_principal_state()
if request_state is not None:
async with request_state.principal_resolution_lock:
- if request_state.principal is not None:
+ if request_state.principal is not None and member_user_id is None:
set_request_principal(
request_state.principal,
identity_key,
@@ -163,18 +226,15 @@ async def _resolve_request_principal(
identity_result = (
await _resolve_bearer_identity(bearer_token, organization_id)
- if bearer_token
+ if bearer_token and member_user_id is None
else BearerIdentityResolution(None, BearerIdentityStatus.no_bearer)
)
- identity = identity_result.identity
- principal = RequestPrincipal(
- organization_id=organization_id,
- auth_kind=_auth_kind(api_key_type, identity is not None),
- api_key_token_id=api_key_token_id,
- user_id=identity.user_id if identity else None,
- org_role=identity.org_role if identity else None,
- org_role_claim=identity.org_role_claim if identity else None,
- token_has_organization_claim=identity.token_has_organization_claim if identity else None,
+ principal = _build_request_principal(
+ organization_id,
+ api_key_type,
+ api_key_token_id,
+ identity_result.identity,
+ member_user_id,
)
set_request_principal(principal, identity_key, identity_result.status.value)
return principal
@@ -185,18 +245,15 @@ async def _resolve_request_principal(
identity_result = (
await _resolve_bearer_identity(bearer_token, organization_id)
- if bearer_token
+ if bearer_token and member_user_id is None
else BearerIdentityResolution(None, BearerIdentityStatus.no_bearer)
)
- identity = identity_result.identity
- principal = RequestPrincipal(
- organization_id=organization_id,
- auth_kind=_auth_kind(api_key_type, identity is not None),
- api_key_token_id=api_key_token_id,
- user_id=identity.user_id if identity else None,
- org_role=identity.org_role if identity else None,
- org_role_claim=identity.org_role_claim if identity else None,
- token_has_organization_claim=identity.token_has_organization_claim if identity else None,
+ principal = _build_request_principal(
+ organization_id,
+ api_key_type,
+ api_key_token_id,
+ identity_result.identity,
+ member_user_id,
)
_request_principal.set((resolution_key, principal, identity_result.status))
return principal
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index b78ef77b6..cb14944cf 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -110,6 +110,8 @@ def create_forge_stub_app() -> ForgeApp:
fake_app_module.AGENT_FUNCTION.allow_copilot_inline_code_execution = MagicMock(return_value=False)
fake_app_module.AGENT_FUNCTION.is_backup_queue_organization = base_agent_function.is_backup_queue_organization
fake_app_module.AGENT_FUNCTION.resolve_mcp_oauth_org_lookups = MagicMock(return_value=None)
+ fake_app_module.AGENT_FUNCTION.resolve_mcp_oauth_member_api_key = AsyncMock(return_value=None)
+ fake_app_module.AGENT_FUNCTION.resolve_api_key_profile = AsyncMock(return_value=("full_org", None, True))
fake_app_module.AGENT_FUNCTION.get_mcp_request_organization_id = MagicMock(return_value=None)
fake_app_module.AGENT_FUNCTION.schedule_workflow_run_group_advance = MagicMock(return_value=None)
# Sync method returning a key or None — _LazyNamespace would auto-mock it as a truthy
diff --git a/tests/unit/test_mcp_http_auth.py b/tests/unit/test_mcp_http_auth.py
index 1d21e4d28..9967b39dc 100644
--- a/tests/unit/test_mcp_http_auth.py
+++ b/tests/unit/test_mcp_http_auth.py
@@ -938,6 +938,7 @@ async def test_validate_mcp_oauth_token_negative_caches_401_errors(monkeypatch:
SimpleNamespace(
AGENT_FUNCTION=SimpleNamespace(
get_mcp_oauth_jwt_key=AsyncMock(return_value="jwk"),
+ resolve_mcp_oauth_member_api_key=AsyncMock(return_value=None),
)
),
)
@@ -1004,7 +1005,7 @@ async def test_validate_mcp_oauth_token_passes_clock_skew_leeway_to_pyjwt(
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")),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(id="oat_jwt", token="sk_live_from_jwt")),
)
monkeypatch.setattr(jwt, "PyJWK", _fake_jwk)
monkeypatch.setattr(jwt, "decode", _fake_decode)
@@ -1018,6 +1019,7 @@ async def test_validate_mcp_oauth_token_passes_clock_skew_leeway_to_pyjwt(
SimpleNamespace(
AGENT_FUNCTION=SimpleNamespace(
get_mcp_oauth_jwt_key=AsyncMock(return_value="jwk"),
+ resolve_mcp_oauth_member_api_key=AsyncMock(return_value=None),
)
),
)
@@ -1025,11 +1027,60 @@ async def test_validate_mcp_oauth_token_passes_clock_skew_leeway_to_pyjwt(
resolution = await mcp_http_auth.validate_mcp_oauth_token(_jwtish_token())
assert resolution.api_key == "sk_live_from_jwt"
+ assert resolution.api_key_token_id == "oat_jwt"
assert captured["kwargs"]["leeway"] == mcp_http_auth._TOKEN_CLOCK_SKEW_SECONDS
assert captured["kwargs"]["options"] == {"verify_aud": False}
fake_db.get_organization_entities.assert_awaited_once_with("clerk_org_jwt", "organization")
+async def test_validate_mcp_oauth_token_returns_role_403_without_negative_caching(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jwt
+
+ def _fake_decode(*_args: object, **_kwargs: object) -> dict[str, object]:
+ return {
+ "iss": "https://clerk.example.com",
+ "aud": ["https://api.skyvern.com/mcp/"],
+ "resource": "https://api.skyvern.com/mcp/",
+ "sub": "user_123",
+ "org_id": "clerk_org_jwt",
+ }
+
+ resolve_member_key = AsyncMock(side_effect=mcp_http_auth.MCPOrgRoleRequiredError)
+ fake_db = SimpleNamespace(
+ get_organization_entities=AsyncMock(return_value=[SimpleNamespace(organization_id="org_jwt")]),
+ get_valid_org_auth_token=AsyncMock(),
+ )
+ monkeypatch.setattr(jwt, "PyJWK", lambda key: key)
+ 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"),
+ resolve_mcp_oauth_member_api_key=resolve_member_key,
+ )
+ ),
+ )
+
+ for _ in range(2):
+ with pytest.raises(mcp_http_auth.MCPOrgRoleRequiredError) as exc_info:
+ await mcp_http_auth.validate_mcp_oauth_token(_jwtish_token())
+ assert exc_info.value.status_code == 403
+ assert "Admin or Member" in exc_info.value.detail
+
+ assert resolve_member_key.await_count == 2
+ fake_db.get_valid_org_auth_token.assert_not_awaited()
+ assert mcp_http_auth._oauth_cache_key(_jwtish_token()) not in mcp_http_auth._api_key_validation_cache
+
+
@pytest.mark.asyncio
async def test_mcp_http_auth_accepts_opaque_bearer_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
@@ -1084,6 +1135,25 @@ async def test_mcp_http_auth_falls_back_to_api_key_after_invalid_oauth_token(
}
+async def test_mcp_http_auth_returns_403_for_unsupported_org_role_without_api_key_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ role_error = mcp_http_auth.MCPOrgRoleRequiredError()
+ validate_api_key = AsyncMock(side_effect=HTTPException(status_code=401, detail="Invalid API key"))
+ monkeypatch.setattr(mcp_http_auth, "validate_mcp_oauth_token", AsyncMock(side_effect=role_error))
+ monkeypatch.setattr(mcp_http_auth, "validate_mcp_api_key", validate_api_key)
+ app = _build_test_app()
+
+ response = await _request(app, "POST", "/mcp", headers={"authorization": "Bearer a.b.c"}, json={})
+
+ assert response.status_code == 403
+ assert response.json() == {
+ "error": {"code": "FORBIDDEN", "message": role_error.detail},
+ }
+ validate_api_key.assert_not_awaited()
+
+
@pytest.mark.parametrize(
("headers", "oauth_error"),
[
@@ -1213,7 +1283,7 @@ async def test_resolve_oauth_subject_to_org_logs_missing_db_methods(monkeypatch:
async def test_resolve_oauth_subject_to_org_uses_explicit_org_id() -> None:
fake_db = SimpleNamespace(
get_organization_entities=AsyncMock(return_value=[SimpleNamespace(organization_id="skyvern_org_123")]),
- get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="sk_live_org_123")),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(id="oat_org_123", token="sk_live_org_123")),
)
resolution = await mcp_http_auth._resolve_oauth_subject_to_org(
@@ -1223,6 +1293,7 @@ async def test_resolve_oauth_subject_to_org_uses_explicit_org_id() -> None:
assert resolution.api_key == "sk_live_org_123"
assert resolution.validation.organization_id == "skyvern_org_123"
+ assert resolution.api_key_token_id == "oat_org_123"
fake_db.get_organization_entities.assert_awaited_once_with("clerk_org_123", "organization")
fake_db.get_valid_org_auth_token.assert_awaited_once_with(
"skyvern_org_123", mcp_http_auth.OrganizationAuthTokenType.api
@@ -1239,7 +1310,7 @@ async def test_resolve_oauth_subject_to_org_uses_organizations_repository_shape(
# exercises the same delegation contract without importing cloud modules.
organizations_repo = SimpleNamespace(
get_organization_entities=AsyncMock(return_value=[SimpleNamespace(organization_id="skyvern_cloud_org")]),
- get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="sk_live_cloud_org")),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(id="oat_cloud_org", token="sk_live_cloud_org")),
)
fake_db = SimpleNamespace(organizations=organizations_repo)
@@ -1262,6 +1333,7 @@ async def test_resolve_oauth_subject_to_org_uses_organizations_repository_shape(
assert resolution.api_key == "sk_live_cloud_org"
assert resolution.validation.organization_id == "skyvern_cloud_org"
+ assert resolution.api_key_token_id == "oat_cloud_org"
organizations_repo.get_organization_entities.assert_awaited_once_with("clerk_org_cloud", "organization")
organizations_repo.get_valid_org_auth_token.assert_awaited_once_with(
"skyvern_cloud_org", mcp_http_auth.OrganizationAuthTokenType.api
@@ -1272,7 +1344,7 @@ async def test_resolve_oauth_subject_to_org_uses_organizations_repository_shape(
async def test_resolve_oauth_subject_to_org_uses_compact_clerk_org_claim() -> None:
fake_db = SimpleNamespace(
get_organization_entities=AsyncMock(return_value=[SimpleNamespace(organization_id="skyvern_org_compact")]),
- get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="sk_live_compact")),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(id="oat_compact", token="sk_live_compact")),
)
resolution = await mcp_http_auth._resolve_oauth_subject_to_org(
@@ -1282,6 +1354,7 @@ async def test_resolve_oauth_subject_to_org_uses_compact_clerk_org_claim() -> No
assert resolution.api_key == "sk_live_compact"
assert resolution.validation.organization_id == "skyvern_org_compact"
+ assert resolution.api_key_token_id == "oat_compact"
fake_db.get_organization_entities.assert_awaited_once_with("clerk_org_compact", "organization")
diff --git a/tests/unit/test_org_auth_service.py b/tests/unit/test_org_auth_service.py
index 6464c2004..affcba051 100644
--- a/tests/unit/test_org_auth_service.py
+++ b/tests/unit/test_org_auth_service.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime, timedelta
from time import time as current_time
from types import SimpleNamespace
from typing import Annotated
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
import httpx
import jwt
@@ -316,7 +316,10 @@ async def test_get_current_org_cached_preserves_token_id_on_cache_miss_and_hit(m
api_key = create_access_token("org-a", expires_delta=timedelta(hours=1))
organizations = _RotatingAuthOrganizations({api_key: True})
db = _AuthDatabase(organizations)
- monkeypatch.setattr(org_auth_service.app, "AGENT_FUNCTION", AgentFunction())
+ agent_function = AgentFunction()
+ profile_lookup = AsyncMock(return_value=("full_org", None, True))
+ monkeypatch.setattr(agent_function, "resolve_api_key_profile", profile_lookup)
+ monkeypatch.setattr(org_auth_service.app, "AGENT_FUNCTION", agent_function)
request_principal._request_principal.set(None)
await org_auth_service.get_current_org_cached(api_key, db)
@@ -331,6 +334,7 @@ async def test_get_current_org_cached_preserves_token_id_on_cache_miss_and_hit(m
assert principal_on_hit is not None
assert principal_on_hit.api_key_token_id == "oat_test"
assert organizations.validate_calls == 1
+ profile_lookup.assert_awaited_once_with("org-a", "oat_test")
@pytest.mark.asyncio
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index 306f05092..440c55a37 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -463,6 +463,7 @@ async def test_runtime_end_run_phase_follows_the_runs_hold_on_the_browser(
context.close = hang_after_close_call
monkeypatch.setattr(real_browser_state_module, "BROWSER_CLOSE_TIMEOUT", 0)
+ monkeypatch.setattr(real_browser_state_module, "BROWSER_CONTEXT_CLOSE_TIMEOUT", 0)
await manager.cleanup_for_workflow_run(owner, [], close_browser_on_completion=True)
await asyncio.gather(*list(state._detached_teardown_tasks), return_exceptions=True)
else:
diff --git a/tests/unit/workflow/test_block_browser_state_recovery.py b/tests/unit/workflow/test_block_browser_state_recovery.py
index 145ff7202..29df1065d 100644
--- a/tests/unit/workflow/test_block_browser_state_recovery.py
+++ b/tests/unit/workflow/test_block_browser_state_recovery.py
@@ -1819,6 +1819,7 @@ async def test_browser_runtime_event_failed_close_keeps_later_loss_unexpected(
state = RealBrowserState(pw=MagicMock(), browser_context=context, browser_cleanup=cleanup)
if failure == "timeout":
monkeypatch.setattr(real_browser_state_module, "BROWSER_CLOSE_TIMEOUT", 0)
+ monkeypatch.setattr(real_browser_state_module, "BROWSER_CONTEXT_CLOSE_TIMEOUT", 0)
with capture_logs() as logs:
if operation == "recreate":
assert await state.close_current_open_page() is False
@@ -2048,6 +2049,7 @@ async def test_browser_runtime_event_failed_close_intent_is_not_proof_of_context
state = RealBrowserState(pw=MagicMock(), browser_context=context)
if failure == "timeout":
monkeypatch.setattr(real_browser_state_module, "BROWSER_CLOSE_TIMEOUT", 0)
+ monkeypatch.setattr(real_browser_state_module, "BROWSER_CONTEXT_CLOSE_TIMEOUT", 0)
with capture_logs() as logs:
if operation == "recreate":
assert await state.close_current_open_page() is False
@@ -2868,7 +2870,7 @@ async def test_lifecycle_v4_close_intent_follows_owned_teardown(
context.close = close_context
if detach == "timeout":
- monkeypatch.setattr(real_browser_state_module, "BROWSER_CLOSE_TIMEOUT", 0)
+ monkeypatch.setattr(real_browser_state_module, "BROWSER_CONTEXT_CLOSE_TIMEOUT", 0)
with capture_logs() as logs:
if detach == "caller_cancel":
closing = asyncio.create_task(state.close(release_driver=False))