Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Enforce administrator roles on sensitive organization APIs (#8047)
Aaron Perez7104034af30a
diff --git a/docs/cloud/account-settings/organization-settings.mdx b/docs/cloud/account-settings/organization-settings.mdxindex f216b9477..8668a0d34 100644--- a/docs/cloud/account-settings/organization-settings.mdx+++ b/docs/cloud/account-settings/organization-settings.mdx@@ -26,18 +26,18 @@ Plans that support multiple users (Pro and Enterprise) show a **Members** sectio### Inviting members-Click **Invite Member**, enter their email address, and send the invitation. They'll receive an email with a link to join your organization. Once they accept, they appear in the members list with full access to agents, runs, credentials, and API keys.+Click **Invite Member**, enter their email address, and send the invitation. They'll receive an email with a link to join your organization. Once they accept, they can use the organization's shared agents and runs according to their assigned role.### Removing membersClick the **remove icon** next to a member's name to revoke their access. They lose access to all organization resources immediately.<Warning>-When removing a team member, also review your [API keys](/cloud/account-settings/api-keys); they may have copied keys that remain active.+When removing a team member, also review your [API keys](/cloud/account-settings/api-keys). Organization API keys have administrator-level access and remain active until they are rotated.</Warning><Note>-Role-based access control (restricting what individual members can do) is available on **Enterprise** plans. On other plans, all members have full access to the organization's resources.+Role-based access control is available on **Enterprise** plans. Organization administrators can manage organization settings, credentials and secrets, API keys, and billing. Non-admin members cannot call those sensitive organization APIs.</Note><CardGroup cols={2}>diff --git a/skyvern/cli/core/mcp_http_auth.py b/skyvern/cli/core/mcp_http_auth.pyindex 0866ac3ab..239689ef9 100644--- a/skyvern/cli/core/mcp_http_auth.py+++ b/skyvern/cli/core/mcp_http_auth.py@@ -26,7 +26,12 @@ from skyvern.forge import appfrom skyvern.forge.sdk.core.aiohttp_helper import aiohttp_requestfrom skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenType-from skyvern.forge.sdk.services.org_auth_service import resolve_org_from_api_key+from skyvern.forge.sdk.services.org_auth_service import (+ extract_clerk_org_id,+ extract_clerk_org_role,+ require_org_admin_role,+ resolve_org_from_api_key,+)from .api_key_hash import hash_api_key_for_cachefrom .client import reset_api_key_override, set_api_key_override@@ -264,22 +269,10 @@ def _get_oauth_org_auth_methods(db: object) -> tuple[_OrgEntitiesGetter | None,def _extract_explicit_oauth_org_id(payload: dict[str, object]) -> str:- """Return the Clerk org id from supported org-scoped JWT claim shapes.-- Our Clerk template uses `org_id`; Clerk's org-scoped session JWTs can also- expose the active organization as compact claim `o.id`.- """- org_id_claim = payload.get("org_id")- if isinstance(org_id_claim, str) and org_id_claim:- return org_id_claim-- compact_org_claim = payload.get("o")- if isinstance(compact_org_claim, dict):- compact_org_id = compact_org_claim.get("id")- if isinstance(compact_org_id, str) and compact_org_id:- return compact_org_id-- raise MissingOrgContextError()+ org_id = extract_clerk_org_id(payload)+ if not org_id:+ raise MissingOrgContextError()+ return org_idasync def _resolve_oauth_subject_to_org(@@ -301,6 +294,7 @@ async def _resolve_oauth_subject_to_org(raise HTTPException(status_code=401, detail="Bearer token missing subject claim")clerk_org_id = _extract_explicit_oauth_org_id(payload)+ require_org_admin_role(extract_clerk_org_role(payload))org_entities = await get_entities(clerk_org_id, "organization")if not org_entities:diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 746852eca..7d85562c7 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -5252,7 +5252,7 @@ async def generate_task()async def update_organization(org_update: OrganizationUpdate,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> Organization:# Validate the per-org artifact URL expiry against the same bounds the# signing helper clamps to. Reject out-of-range values at the API edge so@@ -5379,7 +5379,7 @@ async def get_current_organization()async def get_api_keys(organization_id: str,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> GetOrganizationAPIKeysResponse:if organization_id != current_org.organization_id:raise HTTPException(status_code=403, detail="You do not have permission to access this organization")diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex ef73b0c29..022c3d508 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -446,7 +446,7 @@ async def fetch_credential_item_background(item_id: str) -> None:)async def send_totp_code(data: TOTPCodeCreate,- curr_org: Organization = Depends(org_auth_service.get_current_org),+ curr_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> TOTPCode:totp_identifier = normalize_identifier_if_email(data.totp_identifier)redacted_totp_identifier = redact_otp_identifier_for_log(data.totp_identifier)@@ -568,7 +568,7 @@ async def send_totp_code(include_in_schema=False,)async def get_totp_codes(- curr_org: Organization = Depends(org_auth_service.get_current_org),+ curr_org: Organization = Depends(org_auth_service.get_current_admin_org),totp_identifier: str | None = Query(None,description="Filter by TOTP identifier such as an email or phone number.",@@ -692,7 +692,7 @@ async def create_credential(],openapi_extra={"x-fern-sdk-parameter-name": "data"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialResponse:if isinstance(data.credential, NonEmptyPasswordCredential):await _normalize_authenticator_totp_for_organization_or_raise(@@ -858,7 +858,7 @@ async def rename_credential(...,description="The credential fields to update",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialResponse:credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -943,7 +943,7 @@ async def test_login(...,description="The login credentials and URL to test",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),x_user_agent: Annotated[str | None, Header()] = None,) -> TestLoginResponse:"""Test a login with inline credentials without requiring a saved credential."""@@ -1155,7 +1155,7 @@ async def test_credential(...,description="Test configuration including the login URL",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),x_user_agent: Annotated[str | None, Header()] = None,) -> TestCredentialResponse:organization_id = current_org.organization_id@@ -1386,7 +1386,7 @@ async def get_test_credential_status(description="The workflow run ID from the test initiation",examples=["wr_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> TestCredentialStatusResponse:organization_id = current_org.organization_id@@ -1497,7 +1497,7 @@ async def cancel_credential_test(description="The workflow run ID to cancel",examples=["wr_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CancelTestResponse:organization_id = current_org.organization_id@@ -1898,7 +1898,7 @@ async def update_credential(],openapi_extra={"x-fern-sdk-parameter-name": "data"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialResponse:existing_credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -2057,7 +2057,7 @@ async def delete_credential(examples=["cred_1234567890"],openapi_extra={"x-fern-sdk-parameter-name": "credential_id"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> None:credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -2205,7 +2205,7 @@ async def get_credential_totp_code(description="The unique identifier of the credential",examples=["cred_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialTotpCodeResponse:response.headers["Cache-Control"] = "no-store"response.headers["Pragma"] = "no-cache"@@ -2310,7 +2310,7 @@ async def get_credential(examples=["cred_1234567890"],openapi_extra={"x-fern-sdk-parameter-name": "credential_id"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialResponse:"""Return non-sensitive metadata for a single credential.@@ -2354,7 +2354,7 @@ async def get_credential(include_in_schema=False,)async def get_credentials(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),page: int = Query(1,ge=1,@@ -2434,7 +2434,7 @@ def _to_credential_folder_response(folder: CredentialFolderModel, credential_cou@base_router.post("/credential_folders/", response_model=CredentialFolder, include_in_schema=False)async def create_credential_folder(data: CredentialFolderCreate = Body(..., description="The credential folder to create"),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.create_credential_folder(organization_id=current_org.organization_id,@@ -2460,7 +2460,7 @@ async def create_credential_folder(@base_router.get("/credential_folders/{folder_id}/", response_model=CredentialFolder, include_in_schema=False)async def get_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.get_credential_folder(folder_id=folder_id,@@ -2493,7 +2493,7 @@ async def get_credential_folders(page: int = Query(1, ge=1, description="Page number"),page_size: int = Query(100, ge=1, le=500, description="Number of folders per page"),search: str | None = Query(None, description="Search folders by title or description"),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> list[CredentialFolder]:folders = await app.DATABASE.credential_folders.get_credential_folders(organization_id=current_org.organization_id,@@ -2531,7 +2531,7 @@ async def get_credential_folders(async def update_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),data: CredentialFolderUpdate = Body(...),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.update_credential_folder(folder_id=folder_id,@@ -2564,7 +2564,7 @@ async def update_credential_folder(@base_router.delete("/credential_folders/{folder_id}/", include_in_schema=False)async def delete_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> dict:success = await app.DATABASE.credential_folders.soft_delete_credential_folder(folder_id=folder_id,@@ -2594,7 +2594,7 @@ async def delete_credential_folder(async def update_credential_folder_assignment(credential_id: str = Path(..., description="The ID of the credential.", examples=["cred_1234567890"]),data: UpdateCredentialFolderRequest = Body(...),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CredentialResponse:try:credential = await app.DATABASE.credential_folders.set_credential_folder(@@ -2624,7 +2624,7 @@ async def update_credential_folder_assignment(include_in_schema=False,)async def get_onepassword_token(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CreateOnePasswordTokenResponse:"""Get the current OnePassword service account token for the organization.@@ -2670,7 +2670,7 @@ async def get_onepassword_token(include_in_schema=False,)async def list_onepassword_items(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> OnePasswordItemsResponse:org_auth_token = await app.DATABASE.organizations.get_valid_org_auth_token(current_org.organization_id,@@ -2805,7 +2805,7 @@ async def list_onepassword_items(include_in_schema=False,)async def list_bitwarden_items(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> BitwardenItemsResponse:org_auth_token = await app.DATABASE.organizations.get_valid_org_auth_token(current_org.organization_id,@@ -2850,7 +2850,7 @@ async def list_bitwarden_items()async def update_onepassword_token(data: CreateOnePasswordTokenRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CreateOnePasswordTokenResponse:"""Create or update a OnePassword service account token for the current organization.@@ -2907,7 +2907,7 @@ async def update_onepassword_token()async def clear_org_auth_credential(credential_provider: str = Path(..., description="The organization auth credential provider to clear."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> ClearOrganizationAuthTokenResponse:"""Clear the current organization auth credential for the organization.@@ -2961,7 +2961,7 @@ def _to_safe_bitwarden_response(auth_token: BitwardenOrganizationAuthToken) -> Binclude_in_schema=False,)async def get_bitwarden_credential(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> BitwardenCredentialResponse:"""Get the current Bitwarden credential for the organization.@@ -3008,7 +3008,7 @@ async def get_bitwarden_credential()async def update_bitwarden_credential(request: CreateBitwardenCredentialRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> BitwardenCredentialResponse:"""Create or update a Bitwarden credential for the current organization.@@ -3060,7 +3060,7 @@ async def update_bitwarden_credential(include_in_schema=False,)async def get_azure_client_secret_credential(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> AzureClientSecretCredentialResponse:"""Get the current Azure Client Secret Credential for the organization.@@ -3107,7 +3107,7 @@ async def get_azure_client_secret_credential()async def update_azure_client_secret_credential(request: CreateAzureClientSecretCredentialRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> AzureClientSecretCredentialResponse:"""Create or update an Azure Client Secret Credential for the current organization.@@ -3163,7 +3163,7 @@ async def update_azure_client_secret_credential(include_in_schema=False,)async def get_custom_credential_service_config(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CustomCredentialServiceConfigResponse:"""Get the current custom credential service configuration for the organization.@@ -3210,7 +3210,7 @@ async def get_custom_credential_service_config()async def update_custom_credential_service_config(request: CreateCustomCredentialServiceConfigRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CustomCredentialServiceConfigResponse:"""Create or update a custom credential service configuration for the current organization.@@ -3268,7 +3268,7 @@ async def update_custom_credential_service_config()async def test_custom_credential_service_connection(request: CreateCustomCredentialServiceConfigRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> TestConnectionResponse:"""Test connectivity to the custom credential service API.diff --git a/skyvern/forge/sdk/routes/custom_llms.py b/skyvern/forge/sdk/routes/custom_llms.pyindex 8d5788dcf..5aef60474 100644--- a/skyvern/forge/sdk/routes/custom_llms.py+++ b/skyvern/forge/sdk/routes/custom_llms.py@@ -71,7 +71,7 @@ async def _get_custom_llm(include_in_schema=False,)async def list_custom_llms(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CustomLLMListResponse:tokens = await app.DATABASE.organizations.get_valid_org_auth_tokens(organization_id=current_org.organization_id,@@ -108,7 +108,7 @@ async def list_custom_llms()async def create_custom_llm(request: CustomLLMCreateRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CustomLLMResponse:await _validate_custom_llm_api_base(request.config)token = await app.DATABASE.organizations.create_org_auth_token(@@ -137,7 +137,7 @@ async def create_custom_llm(async def update_custom_llm(request: CustomLLMUpdateRequest,custom_llm_id: str = Path(..., description="The custom LLM id."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> CustomLLMResponse:try:existing_custom_llm = await _get_custom_llm(current_org.organization_id, custom_llm_id)@@ -172,7 +172,7 @@ async def update_custom_llm()async def delete_custom_llm(custom_llm_id: str = Path(..., description="The custom LLM id."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_admin_org),) -> ClearOrganizationAuthTokenResponse:try:await app.DATABASE.organizations.invalidate_org_auth_token(diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.pyindex 4d663c61f..378b59416 100644--- a/skyvern/forge/sdk/routes/google_oauth.py+++ b/skyvern/forge/sdk/routes/google_oauth.py@@ -128,7 +128,7 @@ def _require_scopes_from_token(token_data: dict) -> list[str]:@google_oauth_router.post("/oauth/authorize")async def google_oauth_authorize(request: CreateGoogleOAuthAuthorizeRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> GoogleOAuthAuthorizeResponse:"""Kick off the Google OAuth 2.0 authorization flow."""@@ -163,7 +163,7 @@ async def google_oauth_authorize(@google_oauth_router.post("/oauth/callback")async def google_oauth_callback(request: CreateGoogleOAuthCallbackRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> GoogleOAuthCredentialResponse:"""Handle the Google OAuth 2.0 authorization callback."""@@ -277,7 +277,7 @@ async def google_oauth_callback(@google_oauth_router.get("/oauth/config")async def get_google_oauth_client_config(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> GoogleOAuthClientConfigResponse:"""Return the effective Google OAuth client configuration without the client secret."""_require_organization_client_config_enabled()@@ -291,7 +291,7 @@ async def get_google_oauth_client_config(@google_oauth_router.put("/oauth/config")async def update_google_oauth_client_config(request: UpdateGoogleOAuthClientConfigRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> GoogleOAuthClientConfigResponse:"""Store an organization-level Google OAuth client configuration."""_require_organization_client_config_enabled()@@ -328,7 +328,7 @@ async def update_google_oauth_client_config(@google_oauth_router.delete("/oauth/config")async def delete_google_oauth_client_config(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> dict[str, bool]:"""Clear the organization-level Google OAuth client config and fall back to environment config."""_require_organization_client_config_enabled()@@ -341,7 +341,7 @@ async def delete_google_oauth_client_config(@google_oauth_router.get("/oauth/credentials")async def list_google_oauth_credentials(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],include_email: bool = False,) -> GoogleOAuthCredentialListResponse:"""Fetch a list of Google OAuth credentials associated with an organization."""@@ -366,7 +366,7 @@ async def list_google_oauth_credentials(async def rename_google_oauth_credential(credential_id: str,request: UpdateGoogleOAuthCredentialRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> GoogleOAuthCredentialResponse:"""Renames an existing Google OAuth credential for the specified organization"""updated = await google_oauth_service.rename_credential(@@ -384,7 +384,7 @@ async def rename_google_oauth_credential()async def delete_google_oauth_credential(credential_id: str,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> dict[str, bool]:"""Deletes a specific Google OAuth credential associated with an organization"""revoked = await google_oauth_service.revoke_credential(diff --git a/skyvern/forge/sdk/routes/microsoft_oauth.py b/skyvern/forge/sdk/routes/microsoft_oauth.pyindex accd05311..b9c08ca12 100644--- a/skyvern/forge/sdk/routes/microsoft_oauth.py+++ b/skyvern/forge/sdk/routes/microsoft_oauth.py@@ -108,7 +108,7 @@ def _require_scopes_from_token(token_data: dict) -> list[str]:@microsoft_oauth_router.post("/oauth/authorize")async def microsoft_oauth_authorize(request: CreateMicrosoftOAuthAuthorizeRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> MicrosoftOAuthAuthorizeResponse:try:@@ -137,7 +137,7 @@ async def microsoft_oauth_authorize(@microsoft_oauth_router.post("/oauth/callback")async def microsoft_oauth_callback(request: CreateMicrosoftOAuthCallbackRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> MicrosoftOAuthCredentialResponse:context = await microsoft_oauth_service.load_pending_consent_context(@@ -251,7 +251,7 @@ async def microsoft_oauth_callback(@microsoft_oauth_router.get("/oauth/credentials")async def list_microsoft_oauth_credentials(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],include_email: bool = False,) -> MicrosoftOAuthCredentialListResponse:credentials = await microsoft_oauth_service.get_credentials_for_org(@@ -275,7 +275,7 @@ async def list_microsoft_oauth_credentials(async def rename_microsoft_oauth_credential(credential_id: str,request: UpdateMicrosoftOAuthCredentialRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> MicrosoftOAuthCredentialResponse:updated = await microsoft_oauth_service.rename_credential(organization_id=current_org.organization_id,@@ -293,7 +293,7 @@ async def rename_microsoft_oauth_credential()async def delete_microsoft_oauth_credential(credential_id: str,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_admin_org)],) -> None:revoked = await microsoft_oauth_service.revoke_credential(organization_id=current_org.organization_id,diff --git a/skyvern/forge/sdk/schemas/organizations.py b/skyvern/forge/sdk/schemas/organizations.pyindex d0a69139d..a0aa1e0fe 100644--- a/skyvern/forge/sdk/schemas/organizations.py+++ b/skyvern/forge/sdk/schemas/organizations.py@@ -1,15 +1,22 @@from datetime import datetime+from enum import StrEnumfrom pydantic import BaseModel, ConfigDict, EmailStr, Fieldfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+class OrganizationRole(StrEnum):+ admin = "org:admin"+ member = "org:member"++class Organization(BaseModel):model_config = ConfigDict(from_attributes=True)organization_id: strorganization_name: str+ role: OrganizationRole | None = Field(default=None, exclude=True)webhook_callback_url: str | None = Nonemax_steps_per_run: int | None = Nonemax_steps_per_workflow_run: int | None = Nonediff --git a/skyvern/forge/sdk/services/org_auth_service.py b/skyvern/forge/sdk/services/org_auth_service.pyindex 97d2d3235..5af46871e 100644--- a/skyvern/forge/sdk/services/org_auth_service.py+++ b/skyvern/forge/sdk/services/org_auth_service.py@@ -1,7 +1,7 @@import asyncioimport timefrom dataclasses import dataclass-from typing import Annotated, Sequence+from typing import Annotated, Any, Mapping, Sequenceimport jwtimport structlog@@ -17,7 +17,12 @@ from skyvern.forge import appfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.models import TokenPayload-from skyvern.forge.sdk.schemas.organizations import Organization, OrganizationAuthToken, OrganizationAuthTokenType+from skyvern.forge.sdk.schemas.organizations import (+ Organization,+ OrganizationAuthToken,+ OrganizationAuthTokenType,+ OrganizationRole,+)from skyvern.forge.sdk.workflow.models.tags import CallerTypeLOG = structlog.get_logger()@@ -34,6 +39,7 @@ _SAFE_JWT_ERROR_REASONS = {"Signature verification failed","Invalid header string: must be a json object",}+ADMIN_ROLE_REQUIRED_DETAIL = "Organization administrator role required"@dataclass@@ -176,6 +182,78 @@ async def get_current_org()+def extract_clerk_org_id(payload: Mapping[str, Any]) -> str | None:+ """Return the Clerk org id from either supported org-scoped JWT claim shape.++ Our Clerk template uses `org_id`; Clerk's org-scoped session JWTs can also+ expose the active organization as compact claim `o.id`. Callers that miss the+ compact shape treat an org session as a personal account and skip role checks.+ """+ org_id_claim = payload.get("org_id")+ if isinstance(org_id_claim, str) and org_id_claim:+ return org_id_claim++ compact_org_claim = payload.get("o")+ if isinstance(compact_org_claim, dict):+ compact_org_id = compact_org_claim.get("id")+ if isinstance(compact_org_id, str) and compact_org_id:+ return compact_org_id++ return None+++def extract_clerk_org_role(payload: Mapping[str, Any]) -> str | None:+ """Return the org role claim, normalizing the compact `o.rol` form to `org:<role>`."""+ role = payload.get("org_role")+ if isinstance(role, str):+ return role++ compact_org_claim = payload.get("o")+ if isinstance(compact_org_claim, dict):+ compact_role = compact_org_claim.get("rol")+ if isinstance(compact_role, str):+ return f"org:{compact_role.removeprefix('org:')}"++ return None+++def require_org_admin_role(role: OrganizationRole | str | None) -> None:+ if role != OrganizationRole.admin:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=ADMIN_ROLE_REQUIRED_DETAIL,+ )+++def require_org_admin(organization: Organization) -> Organization:+ require_org_admin_role(organization.role)+ return organization+++async def get_current_admin_org(+ x_api_key: Annotated[+ str | None,+ Header(+ description="Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ ),+ ] = None,+ authorization: Annotated[str | None, Header(include_in_schema=False)] = None,+) -> Organization:+ """Authorize an administrator, preferring a member session while retaining API-key service authority."""+ if authorization:+ organization = require_org_admin(await authenticate_helper(authorization))+ apply_request_org_context(organization)+ return organization+ if x_api_key:+ organization = await get_current_org_cached(x_api_key, app.DATABASE)+ apply_request_org_context(organization)+ return organization+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Invalid credentials",+ )++def apply_request_org_context(organization: Organization) -> None:"""Populate skyvern_context + OTEL span with the resolved organization.diff --git a/tests/unit/test_credential_test_trigger_type.py b/tests/unit/test_credential_test_trigger_type.pyindex d09edc46a..270420595 100644--- a/tests/unit/test_credential_test_trigger_type.py+++ b/tests/unit/test_credential_test_trigger_type.py@@ -242,7 +242,7 @@ def test_test_credential_endpoint_wires_user_agent_header(app = FastAPI()app.add_api_route("/credentials/{credential_id}/test", credentials.test_credential, methods=["POST"])- app.dependency_overrides[org_auth_service.get_current_org] = _auth_override+ app.dependency_overrides[org_auth_service.get_current_admin_org] = _auth_overrideresp = TestClient(app).post("/credentials/cred_test/test",@@ -280,7 +280,7 @@ def test_test_login_endpoint_wires_user_agent_header(app = FastAPI()app.add_api_route("/credentials/test-login", credentials.test_login, methods=["POST"])- app.dependency_overrides[org_auth_service.get_current_org] = _auth_override+ app.dependency_overrides[org_auth_service.get_current_admin_org] = _auth_overrideresp = TestClient(app).post("/credentials/test-login",diff --git a/tests/unit/test_mcp_http_auth.py b/tests/unit/test_mcp_http_auth.pyindex fd2f9ee49..eae8dc0ea 100644--- a/tests/unit/test_mcp_http_auth.py+++ b/tests/unit/test_mcp_http_auth.py@@ -905,6 +905,7 @@ async def test_validate_mcp_oauth_token_passes_clock_skew_leeway_to_pyjwt("resource": "https://api.skyvern.com/mcp/","sub": "user_123","org_id": "clerk_org_jwt",+ "org_role": "org:admin",}fake_db = SimpleNamespace(@@ -1081,7 +1082,7 @@ async def test_resolve_oauth_subject_to_org_uses_explicit_org_id() -> None:)resolution = await mcp_http_auth._resolve_oauth_subject_to_org(- {"sub": "user_123", "org_id": "clerk_org_123"},+ {"sub": "user_123", "org_id": "clerk_org_123", "org_role": "org:admin"},fake_db,)@@ -1120,7 +1121,7 @@ async def test_resolve_oauth_subject_to_org_uses_organizations_repository_shape()resolution = await mcp_http_auth._resolve_oauth_subject_to_org(- {"sub": "user_123", "org_id": "clerk_org_cloud"},+ {"sub": "user_123", "org_id": "clerk_org_cloud", "org_role": "org:admin"},fake_db,)@@ -1140,7 +1141,7 @@ async def test_resolve_oauth_subject_to_org_uses_compact_clerk_org_claim() -> No)resolution = await mcp_http_auth._resolve_oauth_subject_to_org(- {"sub": "user_123", "o": {"id": "clerk_org_compact"}},+ {"sub": "user_123", "o": {"id": "clerk_org_compact", "rol": "admin"}},fake_db,)