Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): isolate trigger OAuth authorization flow (#44505)

非法操作11517691d296
diff --git a/api/.importlinter b/api/.importlinter
index 01d9b6a79c3..fa65cae4b57 100644
--- a/api/.importlinter
+++ b/api/.importlinter
@@ -1433,6 +1433,7 @@ name = Trigger OAuth client orchestration does not directly depend on persistenc
type = forbidden
source_modules =
services.trigger.oauth_client_service
+ services.trigger.oauth_service
forbidden_modules =
controllers
extensions
diff --git a/api/controllers/console/workspace/error.py b/api/controllers/console/workspace/error.py
index 33e0bc6263c..fd7e777ff11 100644
--- a/api/controllers/console/workspace/error.py
+++ b/api/controllers/console/workspace/error.py
@@ -3,6 +3,18 @@ from http import HTTPStatus
from libs.exception import BaseHTTPException
+class TriggerOAuthContextInvalidError(BaseHTTPException):
+ error_code = "trigger_oauth_context_invalid"
+ code = HTTPStatus.FORBIDDEN
+ description = "The trigger OAuth context is missing, expired or invalid."
+
+
+class TriggerOAuthProviderRequestError(BaseHTTPException):
+ error_code = "trigger_oauth_provider_error"
+ code = HTTPStatus.BAD_GATEWAY
+ description = "The trigger provider could not complete OAuth authorization."
+
+
class TriggerOAuthClientConfigInvalidError(BaseHTTPException):
error_code = "trigger_oauth_client_config_invalid"
code = HTTPStatus.INTERNAL_SERVER_ERROR
diff --git a/api/controllers/console/workspace/trigger_providers.py b/api/controllers/console/workspace/trigger_providers.py
index a2d4ded66d7..dd2dbaa5d9e 100644
--- a/api/controllers/console/workspace/trigger_providers.py
+++ b/api/controllers/console/workspace/trigger_providers.py
@@ -6,16 +6,22 @@ from flask import make_response, redirect, request
from flask_restx import Resource
from pydantic import BaseModel, RootModel, model_validator
from sqlalchemy.orm import sessionmaker
-from werkzeug.exceptions import BadRequest, Forbidden
+from werkzeug import Response
+from werkzeug.exceptions import BadRequest
from configs import dify_config
-from controllers.common.errors import NotFoundError
+from controllers.common.errors import ForbiddenError, NotFoundError
from controllers.common.fields import SimpleResultResponse
from controllers.common.rbac import RBACCheck, Workspace
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.flask_admission import console_account_admission
-from controllers.console.workspace.error import TriggerOAuthClientChangedError, TriggerOAuthClientConfigInvalidError
+from controllers.console.workspace.error import (
+ TriggerOAuthClientChangedError,
+ TriggerOAuthClientConfigInvalidError,
+ TriggerOAuthContextInvalidError,
+ TriggerOAuthProviderRequestError,
+)
from controllers.console.wraps import (
RBACPermission,
account_initialization_required,
@@ -29,7 +35,6 @@ from controllers.console.wraps import (
)
from core.entities.provider_entities import ProviderConfig
from core.plugin.entities.plugin_daemon import CredentialType
-from core.plugin.impl.oauth import OAuthHandler
from core.trigger.entities.api_entities import (
SubscriptionBuilderApiEntity,
TriggerProviderApiEntity,
@@ -47,9 +52,14 @@ from libs.login import login_required
from machinery.context import RequestContext
from models.account import Account
from models.provider_ids import TriggerProviderID
-from services.plugin.oauth_service import OAuthProxyService
from services.trigger.oauth_client_service import TriggerOAuthClientChangedError as TriggerOAuthClientChanged
from services.trigger.oauth_client_service import TriggerOAuthClientConfigError
+from services.trigger.oauth_service import (
+ TriggerOAuthCallbackRequest,
+ TriggerOAuthClientNotConfiguredError,
+ TriggerOAuthContextError,
+ TriggerOAuthProviderError,
+)
from services.trigger.trigger_provider_service import TriggerProviderService
from services.trigger.trigger_subscription_builder_service import TriggerSubscriptionBuilderService
from services.trigger.trigger_subscription_operator_service import TriggerSubscriptionOperatorService
@@ -564,168 +574,83 @@ class TriggerSubscriptionDeleteApi(Resource):
@console_ns.route("/workspaces/current/trigger-provider/<path:provider>/subscriptions/oauth/authorize")
class TriggerOAuthAuthorizeApi(Resource):
# response-contract:ignore cookie-bearing Flask response
+ @error_responses(NotFoundError, TriggerOAuthClientConfigInvalidError, TriggerOAuthProviderRequestError)
@console_ns.response(
- 200,
+ HTTPStatus.OK,
"Trigger OAuth authorization URL generated successfully",
console_ns.models[TriggerOAuthAuthorizeResponse.__name__],
)
- @setup_required
- @login_required
- @account_initialization_required
- @with_current_user
- @with_current_tenant_id
- def get(self, tenant_id: str, user: Account, provider: str):
- """Initiate OAuth authorization flow for a trigger provider"""
-
+ @console_account_admission()
+ def get(self, context: RequestContext, provider: str) -> Response:
+ """Initiate OAuth authorization flow for a trigger provider."""
try:
- provider_id = TriggerProviderID(provider)
- plugin_id = provider_id.plugin_id
- provider_name = provider_id.provider_name
- tenant_id = tenant_id
-
- # Get OAuth client configuration
- oauth_client_params = TriggerProviderService.get_oauth_client(
- tenant_id=tenant_id,
- provider_id=provider_id,
- )
-
- if oauth_client_params is None:
- raise NotFoundError("No OAuth client configuration found for this trigger provider")
-
- # Create subscription builder
- subscription_builder = TriggerSubscriptionBuilderService.create_trigger_subscription_builder(
- tenant_id=tenant_id,
- user_id=user.id,
- provider_id=provider_id,
- credential_type=CredentialType.OAUTH2,
+ result = application_services().workspaces.trigger_oauth.authorize(
+ tenant_id=context.active_workspace_id,
+ user_id=context.account_id,
+ provider_id=TriggerProviderID(provider),
+ redirect_uri=f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider}/trigger/callback",
)
-
- # Create OAuth handler and proxy context
- oauth_handler = OAuthHandler()
- context_id = OAuthProxyService.create_proxy_context(
- user_id=user.id,
- tenant_id=tenant_id,
- plugin_id=plugin_id,
- provider=provider_name,
- extra_data={
- "subscription_builder_id": subscription_builder.id,
- "plugin_unique_identifier": oauth_client_params.plugin_unique_identifier,
+ except TriggerOAuthClientNotConfiguredError as error:
+ raise NotFoundError(str(error)) from error
+ except TriggerOAuthClientConfigError as error:
+ raise TriggerOAuthClientConfigInvalidError(str(error)) from error
+ except TriggerOAuthProviderError as error:
+ raise TriggerOAuthProviderRequestError(str(error)) from error
+
+ response = make_response(
+ dump_response(
+ TriggerOAuthAuthorizeResponse,
+ {
+ "authorization_url": result.authorization_url,
+ "subscription_builder_id": result.subscription_builder.id,
+ "subscription_builder": result.subscription_builder,
},
)
-
- # Build redirect URI for callback
- redirect_uri = f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider}/trigger/callback"
-
- # Get authorization URL
- authorization_url_response = oauth_handler.get_authorization_url(
- tenant_id=tenant_id,
- user_id=user.id,
- plugin_id=plugin_id,
- provider=provider_name,
- redirect_uri=redirect_uri,
- system_credentials=dict(oauth_client_params.credentials),
- plugin_unique_identifier=oauth_client_params.plugin_unique_identifier,
- )
-
- response = make_response(
- TriggerOAuthAuthorizeResponse(
- authorization_url=authorization_url_response.authorization_url,
- subscription_builder_id=subscription_builder.id,
- subscription_builder=subscription_builder,
- ).model_dump(mode="json")
- )
- response.set_cookie(
- "context_id",
- context_id,
- httponly=True,
- samesite="Lax",
- max_age=OAuthProxyService.__MAX_AGE__,
- )
-
- return response
-
- except Exception as e:
- logger.exception("Error initiating OAuth flow", exc_info=e)
- raise
+ )
+ response.set_cookie(
+ "context_id",
+ result.context_id,
+ httponly=True,
+ samesite="Lax",
+ max_age=result.context_max_age,
+ )
+ return response
@console_ns.route("/oauth/plugin/<path:provider>/trigger/callback")
class TriggerOAuthCallbackApi(Resource):
# response-contract:ignore redirect response
- @console_ns.response(302, "Redirect to OAuth callback page")
+ @error_responses(
+ ForbiddenError,
+ TriggerOAuthContextInvalidError,
+ TriggerOAuthClientConfigInvalidError,
+ TriggerOAuthProviderRequestError,
+ )
+ @console_ns.response(HTTPStatus.FOUND, "Redirect to OAuth callback page")
@setup_required
- def get(self, provider: str):
- """Handle OAuth callback for trigger provider"""
- context_id = request.cookies.get("context_id")
- if not context_id:
- raise Forbidden("context_id not found")
-
- # Use and validate proxy context
- context = OAuthProxyService.use_proxy_context(context_id)
- if context is None:
- raise Forbidden("Invalid context_id")
-
- # Parse provider ID
- provider_id = TriggerProviderID(provider)
- plugin_id = provider_id.plugin_id
- provider_name = provider_id.provider_name
- user_id: str = context["user_id"]
- tenant_id: str = context["tenant_id"]
- subscription_builder_id: str = context["subscription_builder_id"]
-
- # Get OAuth client configuration
- oauth_client_params = TriggerProviderService.get_oauth_client(
- tenant_id=tenant_id,
- provider_id=provider_id,
- )
-
- if oauth_client_params is None:
- raise Forbidden("No OAuth client configuration found for this trigger provider")
-
+ def get(self, provider: str) -> Response:
+ """Complete the cookie-bound flow without requiring a Console login."""
try:
- OAuthProxyService.validate_plugin_context(
- context,
- plugin_id=plugin_id,
- provider=provider_name,
- plugin_unique_identifier=oauth_client_params.plugin_unique_identifier,
+ application_services().workspaces.trigger_oauth.callback(
+ provider=provider,
+ context_id=request.cookies.get("context_id"),
+ redirect_uri=f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider}/trigger/callback",
+ callback_loader=lambda: TriggerOAuthCallbackRequest(
+ method=request.method,
+ full_path=request.full_path,
+ headers=tuple(request.headers.items()),
+ body=request.get_data(as_text=False),
+ ),
)
- except ValueError as error:
- raise Forbidden(str(error)) from error
-
- # Get OAuth credentials from callback
- oauth_handler = OAuthHandler()
- redirect_uri = f"{dify_config.CONSOLE_API_URL}/console/api/oauth/plugin/{provider}/trigger/callback"
-
- credentials_response = oauth_handler.get_credentials(
- tenant_id=tenant_id,
- user_id=user_id,
- plugin_id=plugin_id,
- provider=provider_name,
- redirect_uri=redirect_uri,
- system_credentials=dict(oauth_client_params.credentials),
- plugin_unique_identifier=oauth_client_params.plugin_unique_identifier,
- request=request,
- )
-
- credentials = credentials_response.credentials
- expires_at = credentials_response.expires_at
-
- if not credentials:
- raise ValueError("Failed to get OAuth credentials from the provider.")
-
- # Update subscription builder
- TriggerSubscriptionBuilderService.update_trigger_subscription_builder(
- tenant_id=tenant_id,
- user_id=user_id,
- provider_id=provider_id,
- subscription_builder_id=subscription_builder_id,
- subscription_builder_updater=SubscriptionBuilderUpdater(
- credentials=credentials,
- credential_expires_at=expires_at,
- ),
- )
- # Redirect to OAuth callback page
- return redirect(f"{dify_config.CONSOLE_WEB_URL}/oauth-callback")
+ except TriggerOAuthContextError as error:
+ raise TriggerOAuthContextInvalidError(str(error)) from error
+ except TriggerOAuthClientNotConfiguredError as error:
+ raise ForbiddenError(str(error)) from error
+ except TriggerOAuthClientConfigError as error:
+ raise TriggerOAuthClientConfigInvalidError(str(error)) from error
+ except TriggerOAuthProviderError as error:
+ raise TriggerOAuthProviderRequestError(str(error)) from error
+ return redirect(f"{dify_config.CONSOLE_WEB_URL}/oauth-callback", code=HTTPStatus.FOUND)
@console_ns.route("/workspaces/current/trigger-provider/<path:provider>/oauth/client")
diff --git a/api/core/plugin/impl/oauth.py b/api/core/plugin/impl/oauth.py
index d27d9a221ac..b2f4302c75b 100644
--- a/api/core/plugin/impl/oauth.py
+++ b/api/core/plugin/impl/oauth.py
@@ -59,8 +59,35 @@ class OAuthHandler(BasePluginClient):
"""
try:
- # encode request to raw http request
- raw_request_bytes = self._convert_request_to_raw_data(request)
+ raw_request = self._convert_request_to_raw_data(request)
+ except Exception as error:
+ raise ValueError(f"Error getting credentials: {error}") from error
+
+ return self.get_credentials_from_raw_request(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ plugin_id=plugin_id,
+ provider=provider,
+ redirect_uri=redirect_uri,
+ system_credentials=system_credentials,
+ raw_request=raw_request,
+ plugin_unique_identifier=plugin_unique_identifier,
+ )
+
+ def get_credentials_from_raw_request(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ plugin_id: str,
+ provider: str,
+ redirect_uri: str,
+ system_credentials: Mapping[str, Any],
+ raw_request: bytes,
+ plugin_unique_identifier: str | None,
+ ) -> PluginOAuthCredentialsResponse:
+ """Exchange a detached callback without depending on Flask's request lifetime."""
+ try:
response = self._request_with_plugin_daemon_response_stream(
"POST",
f"plugin/{tenant_id}/dispatch/oauth/get_credentials",
@@ -72,7 +99,7 @@ class OAuthHandler(BasePluginClient):
"redirect_uri": redirect_uri,
"system_credentials": system_credentials,
# for json serialization
- "raw_http_request": binascii.hexlify(raw_request_bytes).decode(),
+ "raw_http_request": binascii.hexlify(raw_request).decode(),
},
},
headers=plugin_dispatch_headers(plugin_id, plugin_unique_identifier),
diff --git a/api/extensions/application_services/workspace.py b/api/extensions/application_services/workspace.py
index 33836e13082..96895b623c4 100644
--- a/api/extensions/application_services/workspace.py
+++ b/api/extensions/application_services/workspace.py
@@ -4,8 +4,7 @@ from dataclasses import dataclass
from sqlalchemy.orm import Session, sessionmaker
-from core.plugin.plugin_service import PluginService
-from core.trigger.trigger_manager import TriggerManager
+from core.plugin.impl.oauth import OAuthHandler
from extensions.ext_redis import RedisClientWrapper
from repositories.account.repository import SQLAlchemyAccountRepository
from repositories.app.console_repository import ConsoleAppRepository
@@ -16,6 +15,12 @@ from repositories.workspace.workspace_repository import WorkspaceRepository
from services.account.adapters import RedisInvitationTokenStore
from services.file_service import FileService
from services.trigger.oauth_client_service import TriggerOAuthClientService
+from services.trigger.oauth_gateway import (
+ OAuthProxyContextGateway,
+ PluginTriggerOAuthGateway,
+ TriggerOAuthBuilderGateway,
+)
+from services.trigger.oauth_service import TriggerOAuthService
from services.workspace.gateways import (
DeploymentWorkspaceCreationPolicy,
DeploymentWorkspaceFeatureGateway,
@@ -52,6 +57,7 @@ class WorkspaceServices:
identity: WorkspaceIdentityGateway
resource_cleanup: WorkspaceResourceCleanupService
trigger_oauth_clients: TriggerOAuthClientService
+ trigger_oauth: TriggerOAuthService
def build_workspace_membership_services(
@@ -88,6 +94,11 @@ def build_workspace_services(
registration: InvitedAccountRegistration,
invitation_tokens: RedisInvitationTokenStore,
) -> WorkspaceServices:
+ trigger_providers = PluginTriggerOAuthGateway(oauth=OAuthHandler())
+ trigger_oauth_clients = TriggerOAuthClientService(
+ clients=TriggerOAuthClientRepository(session_factory=database_client),
+ providers=trigger_providers,
+ )
return WorkspaceServices(
queries=WorkspaceQueryService(workspaces=workspaces, plans=DeploymentWorkspacePlanGateway()),
management=WorkspaceService(
@@ -120,9 +131,11 @@ def build_workspace_services(
datasets=SQLAlchemyDatasetRepository(session_factory=database_client),
agent_resources=WorkspaceResourceCleanupRepository(session_factory=database_client),
),
- trigger_oauth_clients=TriggerOAuthClientService(
- clients=TriggerOAuthClientRepository(session_factory=database_client),
- get_provider=TriggerManager.get_trigger_provider,
- is_plugin_verified=PluginService.is_plugin_verified,
+ trigger_oauth_clients=trigger_oauth_clients,
+ trigger_oauth=TriggerOAuthService(
+ clients=trigger_oauth_clients,
+ providers=trigger_providers,
+ contexts=OAuthProxyContextGateway(),
+ builders=TriggerOAuthBuilderGateway(),
),
)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 3633b8592e7..ef329f4fa2b 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -11395,7 +11395,7 @@ Initiate OAuth login process
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [GET] /oauth/plugin/{provider}/trigger/callback
-**Handle OAuth callback for trigger provider**
+**Complete the cookie-bound flow without requiring a Console login**
#### Parameters
@@ -11408,6 +11408,9 @@ Initiate OAuth login process
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 302 | Redirect to OAuth callback page | |
+| 403 | Forbidden | **application/json**: [ForbiddenError](#forbiddenerror)<br>[TriggerOauthContextInvalidError](#triggeroauthcontextinvaliderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 500 | Internal Server Error | **application/json**: [TriggerOauthClientConfigInvalidError](#triggeroauthclientconfiginvaliderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [TriggerOauthProviderError](#triggeroauthprovidererror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /oauth/provider
@@ -18633,6 +18636,8 @@ Import a Skill zip package from multipart form field `file`.
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Trigger OAuth authorization URL generated successfully | **application/json**: [TriggerOAuthAuthorizeResponse](#triggeroauthauthorizeresponse)<br> |
+| 500 | Internal Server Error | **application/json**: [TriggerOauthClientConfigInvalidError](#triggeroauthclientconfiginvaliderror)<br>[ErrorResponse](#errorresponse)<br> |
+| 502 | Bad Gateway | **application/json**: [TriggerOauthProviderError](#triggeroauthprovidererror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
### [POST] /workspaces/current/trigger-provider/{provider}/subscriptions/verify/{subscription_id}
@@ -36530,6 +36535,22 @@ The stored trigger OAuth client configuration is invalid.
| ---- | ---- | ----------- | -------- |
| TriggerOauthClientConfigInvalidError | | The stored trigger OAuth client configuration is invalid. | |
+#### TriggerOauthContextInvalidError
+
+The trigger OAuth context is missing, expired or invalid.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| TriggerOauthContextInvalidError | | The trigger OAuth context is missing, expired or invalid. | |
+
+#### TriggerOauthProviderError
+
+The trigger provider could not complete OAuth authorization.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| TriggerOauthProviderError | | The trigger provider could not complete OAuth authorization. | |
+
#### TriggerProviderApiEntity
| Name | Type | Description | Required |
diff --git a/api/repositories/trigger/oauth_client_repository.py b/api/repositories/trigger/oauth_client_repository.py
index 59a8021622d..fbacb9b47a1 100644
--- a/api/repositories/trigger/oauth_client_repository.py
+++ b/api/repositories/trigger/oauth_client_repository.py
@@ -51,14 +51,11 @@ class TriggerOAuthClientRepository(TriggerOAuthClientStore):
def get(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthClientSnapshot:
with self._session_factory() as session:
custom = self._find_custom(session=session, tenant_id=tenant_id, provider_id=provider_id)
- system_configured = (
- session.scalar(
- select(TriggerOAuthSystemClient.id).where(
- TriggerOAuthSystemClient.plugin_id == provider_id.plugin_id,
- TriggerOAuthSystemClient.provider == provider_id.provider_name,
- )
+ encrypted_system_oauth_params = session.scalar(
+ select(TriggerOAuthSystemClient.encrypted_oauth_params).where(
+ TriggerOAuthSystemClient.plugin_id == provider_id.plugin_id,
+ TriggerOAuthSystemClient.provider == provider_id.provider_name,
)
- is not None
)
return TriggerOAuthClientSnapshot(
custom=TriggerOAuthTenantClientRecord(
@@ -68,7 +65,7 @@ class TriggerOAuthClientRepository(TriggerOAuthClientStore):
)
if custom is not None
else None,
- system_configured=system_configured,
+ encrypted_system_oauth_params=encrypted_system_oauth_params,
)
@override
diff --git a/api/services/trigger/oauth_client_service.py b/api/services/trigger/oauth_client_service.py
index b6cb13ab207..e46cecba0f3 100644
--- a/api/services/trigger/oauth_client_service.py
+++ b/api/services/trigger/oauth_client_service.py
@@ -1,7 +1,7 @@
"""Trigger OAuth client configuration and credential masking."""
import json
-from collections.abc import Callable, Mapping
+from collections.abc import Mapping
from dataclasses import dataclass
from typing import Protocol
@@ -9,12 +9,13 @@ from constants import HIDDEN_VALUE, UNKNOWN_VALUE
from core.entities.provider_entities import ProviderConfig
from core.helper.provider_cache import NoOpProviderCredentialCache
from core.helper.provider_encryption import create_provider_encrypter
-from core.trigger.provider import PluginTriggerProviderController
+from core.tools.utils.system_encryption import EncryptionError, decrypt_system_params
from models.provider_ids import TriggerProviderID
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
class TriggerOAuthClientConfigError(Exception):
- """The stored tenant OAuth client configuration cannot be read."""
+ """The stored tenant or system OAuth client configuration cannot be read."""
class TriggerOAuthClientChangedError(Exception):
@@ -31,7 +32,26 @@ class TriggerOAuthTenantClientRecord:
@dataclass(frozen=True, slots=True)
class TriggerOAuthClientSnapshot:
custom: TriggerOAuthTenantClientRecord | None
- system_configured: bool
+ # None means no system client exists; an empty ciphertext is corrupt config.
+ encrypted_system_oauth_params: str | None
+
+ @property
+ def system_configured(self) -> bool:
+ return self.encrypted_system_oauth_params is not None
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerOAuthProviderMetadata:
+ schema: list[ProviderConfig]
+ plugin_unique_identifier: str
+
+
+class TriggerOAuthProviderMetadataGateway(Protocol):
+ """Read only the plugin metadata needed to configure and resolve OAuth clients."""
+
+ def get_metadata(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthProviderMetadata: ...
+
+ def is_verified(self, *, tenant_id: str, plugin_unique_identifier: str) -> bool: ...
@dataclass(frozen=True, slots=True)
@@ -76,19 +96,15 @@ class TriggerOAuthClientService:
self,
*,
clients: TriggerOAuthClientStore,
- # TODO: When migrating OAuth authorize/callback, consolidate these callbacks
- # into a shared provider gateway returning metadata instead of a controller.
- get_provider: Callable[[str, TriggerProviderID], PluginTriggerProviderController],
- is_plugin_verified: Callable[[str, str], bool],
+ providers: TriggerOAuthProviderMetadataGateway,
) -> None:
self._clients = clients
- self._get_provider = get_provider
- self._is_plugin_verified = is_plugin_verified
+ self._providers = providers
def get(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthClientConfiguration:
snapshot = self._clients.get(tenant_id=tenant_id, provider_id=provider_id)
- provider = self._get_provider(tenant_id, provider_id)
- schema = provider.get_oauth_client_schema()
+ provider = self._providers.get_metadata(tenant_id=tenant_id, provider_id=provider_id)
+ schema = provider.schema
params: Mapping[str, object] = {}
if snapshot.custom is not None:
encrypter, _ = create_provider_encrypter(
@@ -104,10 +120,46 @@ class TriggerOAuthClientService:
schema=schema,
params=params,
system_configured=snapshot.system_configured
- and self._is_plugin_verified(tenant_id, provider.plugin_unique_identifier),
+ and self._providers.is_verified(
+ tenant_id=tenant_id, plugin_unique_identifier=provider.plugin_unique_identifier
+ ),
custom_enabled=snapshot.custom is not None and snapshot.custom.enabled,
)
+ def resolve(self, *, tenant_id: str, provider_id: TriggerProviderID) -> PluginOAuthClientConfig | None:
+ """Return credentials bound to their plugin package, or None if no permitted client exists.
+
+ An enabled tenant client takes priority, including an empty configuration.
+ Otherwise only a verified plugin may use its system client.
+ """
+ snapshot = self._clients.get(tenant_id=tenant_id, provider_id=provider_id)
+ provider = self._providers.get_metadata(tenant_id=tenant_id, provider_id=provider_id)
+ if snapshot.custom is not None and snapshot.custom.enabled:
+ encrypter, _ = create_provider_encrypter(
+ tenant_id=tenant_id,
+ config=[field.to_basic_provider_config() for field in provider.schema],
+ cache=NoOpProviderCredentialCache(),
+ )
+ return PluginOAuthClientConfig(
+ plugin_unique_identifier=provider.plugin_unique_identifier,
+ credentials=encrypter.decrypt(self._parse_params(snapshot.custom, provider_id)),
+ )
+
+ encrypted_system_params = snapshot.encrypted_system_oauth_params
+ if encrypted_system_params is None or not self._providers.is_verified(
+ tenant_id=tenant_id, plugin_unique_identifier=provider.plugin_unique_identifier
+ ):
+ return None
+ try:
+ return PluginOAuthClientConfig(
+ plugin_unique_identifier=provider.plugin_unique_identifier,
+ credentials=decrypt_system_params(encrypted_system_params),
+ )
+ except (EncryptionError, ValueError) as error:
+ raise TriggerOAuthClientConfigError(
+ f"Stored system OAuth client configuration for trigger provider {provider_id} is invalid."
+ ) from error
+
def save(
self,
*,
@@ -125,12 +177,12 @@ class TriggerOAuthClientService:
return
snapshot = self._clients.get(tenant_id=tenant_id, provider_id=provider_id)
- provider = self._get_provider(tenant_id, provider_id)
+ provider = self._providers.get_metadata(tenant_id=tenant_id, provider_id=provider_id)
encrypted_params = "{}"
if client_params is not None:
encrypter, cache = create_provider_encrypter(
tenant_id=tenant_id,
- config=[field.to_basic_provider_config() for field in provider.get_oauth_client_schema()],
+ config=[field.to_basic_provider_config() for field in provider.schema],
cache=NoOpProviderCredentialCache(),
)
original_params = encrypter.decrypt(
diff --git a/api/services/trigger/oauth_gateway.py b/api/services/trigger/oauth_gateway.py
new file mode 100644
index 00000000000..62e9a90c90f
--- /dev/null
+++ b/api/services/trigger/oauth_gateway.py
@@ -0,0 +1,160 @@
+"""Plugin transport and compatibility boundaries for trigger OAuth."""
+
+from collections.abc import Mapping
+
+from pydantic import TypeAdapter
+
+from core.plugin.entities.plugin_daemon import CredentialType
+from core.plugin.impl.oauth import OAuthHandler
+from core.plugin.plugin_service import PluginService
+from core.trigger.entities.api_entities import SubscriptionBuilderApiEntity
+from core.trigger.entities.entities import SubscriptionBuilderUpdater
+from core.trigger.trigger_manager import TriggerManager
+from models.provider_ids import TriggerProviderID
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
+from services.plugin.oauth_service import OAuthProxyService
+from services.trigger.oauth_client_service import TriggerOAuthProviderMetadata
+from services.trigger.oauth_service import (
+ TriggerOAuthCallbackRequest,
+ TriggerOAuthContext,
+ TriggerOAuthContextError,
+ TriggerOAuthCredentials,
+ TriggerOAuthProviderError,
+)
+from services.trigger.trigger_subscription_builder_service import TriggerSubscriptionBuilderService
+
+_context_adapter = TypeAdapter(TriggerOAuthContext)
+
+
+class PluginTriggerOAuthGateway:
+ def __init__(self, *, oauth: OAuthHandler) -> None:
+ self._oauth = oauth
+
+ def get_metadata(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthProviderMetadata:
+ provider = TriggerManager.get_trigger_provider(tenant_id, provider_id)
+ return TriggerOAuthProviderMetadata(
+ schema=provider.get_oauth_client_schema(),
+ plugin_unique_identifier=provider.plugin_unique_identifier,
+ )
+
+ def is_verified(self, *, tenant_id: str, plugin_unique_identifier: str) -> bool:
+ return PluginService.is_plugin_verified(tenant_id, plugin_unique_identifier)
+
+ def authorization_url(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ ) -> str:
+ try:
+ result = self._oauth.get_authorization_url(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ plugin_id=provider_id.plugin_id,
+ provider=provider_id.provider_name,
+ redirect_uri=redirect_uri,
+ system_credentials=dict(client_config.credentials),
+ plugin_unique_identifier=client_config.plugin_unique_identifier,
+ )
+ except ValueError as error:
+ raise TriggerOAuthProviderError("Failed to get the trigger provider's OAuth authorization URL.") from error
+ return result.authorization_url
+
+ def exchange_credentials(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ callback: TriggerOAuthCallbackRequest,
+ ) -> TriggerOAuthCredentials:
+ # Preserve the legacy raw request, including trailing '?' and header order.
+ protocol = next(
+ (value for name, value in callback.headers if name.lower().replace("-", "_") == "http_version"), "HTTP/1.1"
+ )
+ raw_request = f"{callback.method} {callback.full_path} {protocol}\r\n".encode()
+ raw_request += b"".join(f"{name}: {value}\r\n".encode() for name, value in callback.headers)
+ raw_request += b"\r\n" + callback.body
+ try:
+ result = self._oauth.get_credentials_from_raw_request(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ plugin_id=provider_id.plugin_id,
+ provider=provider_id.provider_name,
+ redirect_uri=redirect_uri,
+ system_credentials=dict(client_config.credentials),
+ plugin_unique_identifier=client_config.plugin_unique_identifier,
+ raw_request=raw_request,
+ )
+ except ValueError as error:
+ raise TriggerOAuthProviderError("Failed to get OAuth credentials from the trigger provider.") from error
+ return TriggerOAuthCredentials(credentials=result.credentials, expires_at=result.expires_at)
+
+
+class OAuthProxyContextGateway:
+ """Retain the shared proxy format so in-flight callbacks survive deployment.
+
+ TODO: Migrate the shared proxy owner to atomic consumption for all plugin
+ OAuth callers; its existing GET/DELETE pair does not exclude concurrent replay.
+ """
+
+ max_age: int = OAuthProxyService.__MAX_AGE__
+
+ def create(self, context: TriggerOAuthContext) -> str:
+ return OAuthProxyService.create_proxy_context(
+ user_id=context.user_id,
+ tenant_id=context.tenant_id,
+ plugin_id=context.plugin_id,
+ provider=context.provider,
+ extra_data={
+ "subscription_builder_id": context.subscription_builder_id,
+ "plugin_unique_identifier": context.plugin_unique_identifier,
+ },
+ )
+
+ def consume(self, context_id: str) -> TriggerOAuthContext:
+ try:
+ context = OAuthProxyService.use_proxy_context(context_id)
+ return _context_adapter.validate_python(context)
+ except ValueError as error:
+ raise TriggerOAuthContextError("Invalid or expired context_id") from error
+
+
+class TriggerOAuthBuilderGateway:
+ """Keep builder locking, ownership and masking with its existing owner.
+
+ TODO: Inject the shared builder application service when the remaining
+ subscription builder endpoints are migrated.
+ """
+
+ def create(self, *, tenant_id: str, user_id: str, provider_id: TriggerProviderID) -> SubscriptionBuilderApiEntity:
+ return TriggerSubscriptionBuilderService.create_trigger_subscription_builder(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ provider_id=provider_id,
+ credential_type=CredentialType.OAUTH2,
+ )
+
+ def set_credentials(
+ self,
+ *,
+ context: TriggerOAuthContext,
+ provider_id: TriggerProviderID,
+ credentials: Mapping[str, object],
+ expires_at: int,
+ ) -> None:
+ TriggerSubscriptionBuilderService.update_trigger_subscription_builder(
+ tenant_id=context.tenant_id,
+ user_id=context.user_id,
+ provider_id=provider_id,
+ subscription_builder_id=context.subscription_builder_id,
+ subscription_builder_updater=SubscriptionBuilderUpdater(
+ credentials=credentials,
+ credential_expires_at=expires_at,
+ ),
+ )
diff --git a/api/services/trigger/oauth_service.py b/api/services/trigger/oauth_service.py
new file mode 100644
index 00000000000..852ea05568a
--- /dev/null
+++ b/api/services/trigger/oauth_service.py
@@ -0,0 +1,183 @@
+"""Orchestrate trigger authorization without carrying HTTP or ORM objects."""
+
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from typing import Protocol
+
+from core.trigger.entities.api_entities import SubscriptionBuilderApiEntity
+from models.provider_ids import TriggerProviderID
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
+from services.trigger.oauth_client_service import TriggerOAuthClientService
+
+
+class TriggerOAuthClientNotConfiguredError(Exception):
+ """Neither an enabled tenant client nor a trusted system client is available."""
+
+
+class TriggerOAuthContextError(Exception):
+ """The callback capability is missing, expired or no longer matches the provider package."""
+
+
+class TriggerOAuthProviderError(Exception):
+ """The provider could not authorize or exchange credentials."""
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerOAuthContext:
+ tenant_id: str
+ user_id: str
+ plugin_id: str
+ provider: str
+ subscription_builder_id: str
+ # None keeps callbacks created before package binding compatible.
+ plugin_unique_identifier: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerOAuthCallbackRequest:
+ method: str
+ full_path: str
+ headers: tuple[tuple[str, str], ...]
+ body: bytes
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerOAuthCredentials:
+ credentials: Mapping[str, object]
+ expires_at: int
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerOAuthAuthorization:
+ authorization_url: str
+ subscription_builder: SubscriptionBuilderApiEntity
+ context_id: str
+ context_max_age: int
+
+
+class TriggerOAuthProviderGateway(Protocol):
+ def authorization_url(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ ) -> str: ...
+
+ def exchange_credentials(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ callback: TriggerOAuthCallbackRequest,
+ ) -> TriggerOAuthCredentials: ...
+
+
+class TriggerOAuthContexts(Protocol):
+ @property
+ def max_age(self) -> int: ...
+
+ def create(self, context: TriggerOAuthContext) -> str: ...
+
+ def consume(self, context_id: str) -> TriggerOAuthContext: ...
+
+
+class TriggerOAuthBuilders(Protocol):
+ def create(
+ self, *, tenant_id: str, user_id: str, provider_id: TriggerProviderID
+ ) -> SubscriptionBuilderApiEntity: ...
+
+ def set_credentials(
+ self,
+ *,
+ context: TriggerOAuthContext,
+ provider_id: TriggerProviderID,
+ credentials: Mapping[str, object],
+ expires_at: int,
+ ) -> None: ...
+
+
+class TriggerOAuthService:
+ def __init__(
+ self,
+ *,
+ clients: TriggerOAuthClientService,
+ providers: TriggerOAuthProviderGateway,
+ contexts: TriggerOAuthContexts,
+ builders: TriggerOAuthBuilders,
+ ) -> None:
+ self._clients = clients
+ self._providers = providers
+ self._contexts = contexts
+ self._builders = builders
+
+ def authorize(
+ self, *, tenant_id: str, user_id: str, provider_id: TriggerProviderID, redirect_uri: str
+ ) -> TriggerOAuthAuthorization:
+ client_config = self._clients.resolve(tenant_id=tenant_id, provider_id=provider_id)
+ if client_config is None:
+ raise TriggerOAuthClientNotConfiguredError("No OAuth client configuration found for this trigger provider")
+ builder = self._builders.create(tenant_id=tenant_id, user_id=user_id, provider_id=provider_id)
+ context_id = self._contexts.create(
+ TriggerOAuthContext(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ plugin_id=provider_id.plugin_id,
+ provider=provider_id.provider_name,
+ subscription_builder_id=builder.id,
+ plugin_unique_identifier=client_config.plugin_unique_identifier,
+ )
+ )
+ authorization_url = self._providers.authorization_url(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ provider_id=provider_id,
+ redirect_uri=redirect_uri,
+ client_config=client_config,
+ )
+ return TriggerOAuthAuthorization(authorization_url, builder, context_id, self._contexts.max_age)
+
+ def callback(
+ self,
+ *,
+ provider: str,
+ context_id: str | None,
+ redirect_uri: str,
+ callback_loader: Callable[[], TriggerOAuthCallbackRequest],
+ ) -> None:
+ """Consume the cookie capability; None means the browser omitted the cookie."""
+ if not context_id:
+ raise TriggerOAuthContextError("context_id not found")
+ context = self._contexts.consume(context_id)
+ provider_id = TriggerProviderID(provider)
+ if context.plugin_id != provider_id.plugin_id or context.provider != provider_id.provider_name:
+ raise TriggerOAuthContextError("OAuth context does not belong to this trigger provider")
+ client_config = self._clients.resolve(tenant_id=context.tenant_id, provider_id=provider_id)
+ if client_config is None:
+ raise TriggerOAuthClientNotConfiguredError("No OAuth client configuration found for this trigger provider")
+ if (
+ context.plugin_unique_identifier is not None
+ and context.plugin_unique_identifier != client_config.plugin_unique_identifier
+ ):
+ raise TriggerOAuthContextError("Plugin changed during OAuth authorization; restart authorization")
+ result = self._providers.exchange_credentials(
+ tenant_id=context.tenant_id,
+ user_id=context.user_id,
+ provider_id=provider_id,
+ redirect_uri=redirect_uri,
+ client_config=client_config,
+ callback=callback_loader(),
+ )
+ if not result.credentials:
+ raise TriggerOAuthProviderError("Failed to get OAuth credentials from the provider.")
+ self._builders.set_credentials(
+ context=context,
+ provider_id=provider_id,
+ credentials=result.credentials,
+ expires_at=result.expires_at,
+ )
diff --git a/api/services/trigger/trigger_provider_service.py b/api/services/trigger/trigger_provider_service.py
index 1565c48e8c7..3741ffd37de 100644
--- a/api/services/trigger/trigger_provider_service.py
+++ b/api/services/trigger/trigger_provider_service.py
@@ -601,6 +601,9 @@ class TriggerProviderService:
:param tenant_id: Tenant ID
:param provider_id: Provider identifier
:return: OAuth client configuration or None
+
+ TODO: Remove this legacy resolver when subscription token refresh uses
+ the injected TriggerOAuthClientService already shared by the OAuth APIs.
"""
if provider_controller is None:
provider_controller = TriggerManager.get_trigger_provider(tenant_id=tenant_id, provider_id=provider_id)
diff --git a/api/tests/e2e_tests/containers/services/test_trigger_oauth_gateway.py b/api/tests/e2e_tests/containers/services/test_trigger_oauth_gateway.py
new file mode 100644
index 00000000000..93e4022e4bd
--- /dev/null
+++ b/api/tests/e2e_tests/containers/services/test_trigger_oauth_gateway.py
@@ -0,0 +1,237 @@
+"""Exercise callback compatibility and the real Redis subscription builder boundary."""
+
+import json
+from collections.abc import Iterator
+from dataclasses import asdict, dataclass, replace
+from threading import Lock
+from uuid import uuid4
+
+import pytest
+from flask import Flask
+
+import contexts
+from core.entities.provider_entities import ProviderConfig, ProviderConfigType
+from core.plugin.entities import OAuthSchema
+from core.plugin.entities.plugin_daemon import CredentialType
+from core.tools.entities.common_entities import I18nObject
+from core.trigger.entities.api_entities import SubscriptionBuilderApiEntity
+from core.trigger.entities.entities import (
+ EventParameter,
+ EventParameterType,
+ SubscriptionBuilder,
+ SubscriptionConstructor,
+ TriggerProviderEntity,
+ TriggerProviderIdentity,
+)
+from core.trigger.provider import PluginTriggerProviderController
+from extensions.ext_redis import redis_client
+from models.provider_ids import TriggerProviderID
+from services.plugin.oauth_service import OAuthProxyService
+from services.trigger.oauth_gateway import OAuthProxyContextGateway, TriggerOAuthBuilderGateway
+from services.trigger.oauth_service import TriggerOAuthContext, TriggerOAuthContextError
+from services.trigger.trigger_subscription_builder_service import TriggerSubscriptionBuilderService
+
+_PROVIDER_ID = TriggerProviderID("langgenius/github/github")
+_PLUGIN_IDENTIFIER = "langgenius/github:0.1.0@package-hash"
+
+
+def _context() -> TriggerOAuthContext:
+ return TriggerOAuthContext(
+ tenant_id=str(uuid4()),
+ user_id=str(uuid4()),
+ plugin_id="langgenius/github",
+ provider="github",
+ subscription_builder_id=str(uuid4()),
+ )
+
+
+def test_new_context_remains_readable_by_legacy_callback(flask_app_with_containers: Flask) -> None:
+ gateway = OAuthProxyContextGateway()
+ context = replace(_context(), plugin_unique_identifier=_PLUGIN_IDENTIFIER)
+ with flask_app_with_containers.app_context():
+ context_id = gateway.create(context)
+ key = f"{OAuthProxyService.__KEY_PREFIX__}{context_id}"
+ try:
+ assert 0 < redis_client.ttl(key) <= gateway.max_age == 300
+ assert OAuthProxyService.use_proxy_context(context_id) == asdict(context)
+ assert redis_client.exists(key) == 0
+ finally:
+ redis_client.delete(key)
+
+
+def test_new_context_preserves_package_binding_when_consumed(flask_app_with_containers: Flask) -> None:
+ gateway = OAuthProxyContextGateway()
+ context = replace(_context(), plugin_unique_identifier=_PLUGIN_IDENTIFIER)
+ with flask_app_with_containers.app_context():
+ context_id = gateway.create(context)
+ key = f"{OAuthProxyService.__KEY_PREFIX__}{context_id}"
+ try:
+ assert gateway.consume(context_id) == context
+ assert redis_client.exists(key) == 0
+ finally:
+ redis_client.delete(key)
+
+
+def test_existing_context_is_consumed_once_by_new_callback(flask_app_with_containers: Flask) -> None:
+ gateway = OAuthProxyContextGateway()
+ context = _context()
+ with flask_app_with_containers.app_context():
+ context_id = OAuthProxyService.create_proxy_context(
+ user_id=context.user_id,
+ tenant_id=context.tenant_id,
+ plugin_id=context.plugin_id,
+ provider=context.provider,
+ extra_data={"subscription_builder_id": context.subscription_builder_id},
+ )
+ key = f"{OAuthProxyService.__KEY_PREFIX__}{context_id}"
+ try:
+ assert gateway.consume(context_id) == context
+ assert redis_client.exists(key) == 0
+ with pytest.raises(TriggerOAuthContextError, match="Invalid or expired context_id"):
+ gateway.consume(context_id)
+ finally:
+ redis_client.delete(key)
+
+
+@dataclass(frozen=True)
+class _CreatedBuilder:
+ context: TriggerOAuthContext
+ response: SubscriptionBuilderApiEntity
+
+
+def _provider(tenant_id: str, provider_id: TriggerProviderID) -> PluginTriggerProviderController:
+ label = I18nObject(en_US="GitHub")
+ return PluginTriggerProviderController(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ plugin_id=provider_id.plugin_id,
+ plugin_unique_identifier=_PLUGIN_IDENTIFIER,
+ entity=TriggerProviderEntity(
+ identity=TriggerProviderIdentity(
+ author="langgenius", name=provider_id.provider_name, label=label, description=label
+ ),
+ subscription_schema=[ProviderConfig(name="repository", type=ProviderConfigType.TEXT_INPUT, default="dify")],
+ subscription_constructor=SubscriptionConstructor(
+ parameters=[EventParameter(name="event", type=EventParameterType.STRING, label=label, default="push")],
+ oauth_schema=OAuthSchema(
+ credentials_schema=[ProviderConfig(name="access_token", type=ProviderConfigType.SECRET_INPUT)]
+ ),
+ ),
+ ),
+ )
+
+
+def created_builder(flask_app_with_containers: Flask) -> Iterator[_CreatedBuilder]:
+ tenant_id, user_id = str(uuid4()), str(uuid4())
+ # Populate the normal request cache with real controllers. The gateway, builder
+ # service, ownership checks, updater and Redis lock/storage all execute normally.
+ previous_providers = contexts.plugin_trigger_providers.get({})
+ previous_lock = contexts.plugin_trigger_providers_lock.get(Lock())
+ contexts.plugin_trigger_providers.set(
+ {
+ str(provider_id): _provider(tenant_id, provider_id)
+ for provider_id in (_PROVIDER_ID, TriggerProviderID("langgenius/github/other"))
+ }
+ )
+ contexts.plugin_trigger_providers_lock.set(Lock())
+ try:
+ with flask_app_with_containers.app_context():
+ response = TriggerOAuthBuilderGateway().create(
+ tenant_id=tenant_id, user_id=user_id, provider_id=_PROVIDER_ID
+ )
+ context = TriggerOAuthContext(
+ tenant_id=tenant_id,
+ user_id=user_id,
+ plugin_id=_PROVIDER_ID.plugin_id,
+ provider=_PROVIDER_ID.provider_name,
+ subscription_builder_id=response.id,
+ plugin_unique_identifier=_PLUGIN_IDENTIFIER,
+ )
+ try:
+ yield _CreatedBuilder(context=context, response=response)
+ finally:
+ redis_client.delete(TriggerSubscriptionBuilderService.encode_cache_key(response.id))
+ finally:
+ contexts.plugin_trigger_providers.set(previous_providers)
+ contexts.plugin_trigger_providers_lock.set(previous_lock)
+
+
+def _read_builder(builder_id: str) -> SubscriptionBuilder:
+ cached = redis_client.get(TriggerSubscriptionBuilderService.encode_cache_key(builder_id))
+ assert cached is not None
+ return SubscriptionBuilder.model_validate_json(cached)
+
+
+def test_builder_gateway_creates_owned_oauth_builder(created_builder: _CreatedBuilder) -> None:
+ context, response = created_builder.context, created_builder.response
+ stored = _read_builder(response.id)
+
+ assert stored.id == stored.endpoint_id == context.subscription_builder_id
+ assert stored.tenant_id == context.tenant_id
+ assert stored.user_id == context.user_id
+ assert stored.provider_id == response.provider == str(_PROVIDER_ID)
+ assert stored.credential_type == response.credential_type == CredentialType.OAUTH2
+ assert stored.credentials == response.credentials == {}
+ assert stored.credential_expires_at == -1
+ assert stored.parameters == response.parameters == {"event": "push"}
+ assert stored.properties == response.properties == {"repository": "dify"}
+ assert 0 < redis_client.ttl(TriggerSubscriptionBuilderService.encode_cache_key(response.id)) <= 30 * 60
+
+
+def test_builder_gateway_updates_credentials_and_expiry_only(created_builder: _CreatedBuilder) -> None:
+ context = created_builder.context
+ before = _read_builder(context.subscription_builder_id)
+ credentials = {"access_token": "provider-access-token", "refresh_token": "provider-refresh-token"}
+
+ TriggerOAuthBuilderGateway().set_credentials(
+ context=context,
+ provider_id=_PROVIDER_ID,
+ credentials=credentials,
+ expires_at=123456,
+ )
+
+ assert _read_builder(context.subscription_builder_id) == before.model_copy(
+ update={"credentials": credentials, "credential_expires_at": 123456}
+ )
+
+
[email protected]("mismatch", ["tenant", "user", "provider", "builder_id"])
+def test_builder_gateway_rejects_mismatched_owner_without_updating(
+ created_builder: _CreatedBuilder, mismatch: str
+) -> None:
+ context = created_builder.context
+ before = _read_builder(context.subscription_builder_id)
+ provider_id = _PROVIDER_ID
+ if mismatch == "tenant":
+ context = replace(context, tenant_id=str(uuid4()))
+ elif mismatch == "user":
+ context = replace(context, user_id=str(uuid4()))
+ elif mismatch == "provider":
+ provider_id = TriggerProviderID("langgenius/github/other")
+ else:
+ context = replace(context, subscription_builder_id=str(uuid4()))
+
+ with pytest.raises(ValueError, match="not found"):
+ TriggerOAuthBuilderGateway().set_credentials(
+ context=context,
+ provider_id=provider_id,
+ credentials={"access_token": "must-not-be-stored"},
+ expires_at=123456,
+ )
+
+ assert _read_builder(before.id) == before
+
+
[email protected]("payload", ["not-json", "[]", json.dumps({"tenant_id": "workspace"})])
+def test_invalid_cached_context_raises_domain_error(flask_app_with_containers: Flask, payload: str) -> None:
+ context_id = str(uuid4())
+ key = f"{OAuthProxyService.__KEY_PREFIX__}{context_id}"
+ with flask_app_with_containers.app_context():
+ redis_client.setex(key, OAuthProxyContextGateway.max_age, payload)
+ try:
+ with pytest.raises(TriggerOAuthContextError, match="Invalid or expired context_id"):
+ OAuthProxyContextGateway().consume(context_id)
+ assert redis_client.exists(key) == 0
+ finally:
+ redis_client.delete(key)
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_client.py b/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_client.py
index 3ffa1ea6548..b86b2bb925d 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_client.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_client.py
@@ -16,7 +16,11 @@ from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
from werkzeug.test import TestResponse
from constants import HEADER_NAME_CSRF_TOKEN, HIDDEN_VALUE, UNKNOWN_VALUE
-from controllers.console.workspace.trigger_providers import TriggerOAuthClientManageApi
+from controllers.console.workspace.trigger_providers import (
+ TriggerOAuthAuthorizeApi,
+ TriggerOAuthCallbackApi,
+ TriggerOAuthClientManageApi,
+)
from controllers.console.wraps import _is_setup_completed
from core.entities.provider_entities import ProviderConfig, ProviderConfigType
from core.helper.encrypter import decrypt_token
@@ -40,7 +44,7 @@ from models.engine import db
from models.provider_ids import TriggerProviderID
from models.trigger import TriggerOAuthSystemClient, TriggerOAuthTenantClient
from repositories.trigger.oauth_client_repository import TriggerOAuthClientRepository
-from services.trigger.oauth_client_service import TriggerOAuthClientService
+from services.trigger.oauth_client_service import TriggerOAuthClientService, TriggerOAuthProviderMetadata
from tests.helpers.unit.config_override import config_overrides_context
_PROVIDER = "langgenius/github/github"
@@ -63,7 +67,7 @@ class _PluginMetadata:
# lookup so tests can interleave a real concurrent persistence operation.
before_provider: Callable[[], None] | None = None
- def get_provider(self, tenant_id: str, provider_id: TriggerProviderID) -> PluginTriggerProviderController:
+ def get_metadata(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthProviderMetadata:
assert all(not session.in_transaction() for session in self.sessions)
assert tenant_id == self.provider.tenant_id
assert str(provider_id) == str(self.provider.provider_id)
@@ -72,9 +76,11 @@ class _PluginMetadata:
self.before_provider = None
if before_provider is not None:
before_provider()
- return self.provider
+ return TriggerOAuthProviderMetadata(
+ schema=_SCHEMA, plugin_unique_identifier=self.provider.plugin_unique_identifier
+ )
- def is_verified(self, tenant_id: str, plugin_unique_identifier: str) -> bool:
+ def is_verified(self, *, tenant_id: str, plugin_unique_identifier: str) -> bool:
assert all(not session.in_transaction() for session in self.sessions)
assert tenant_id == self.provider.tenant_id
assert plugin_unique_identifier == self.provider.plugin_unique_identifier
@@ -140,6 +146,7 @@ def harness(sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session]
INIT_PASSWORD="",
SECRET_KEY="trigger-oauth-http-secret-at-least-32-bytes",
CONSOLE_API_URL="https://console.example.test",
+ CONSOLE_WEB_URL="https://console.example.test",
KEY_PROVIDER_TYPE="local",
STORAGE_TYPE="local",
STORAGE_LOCAL_PATH=storage_path,
@@ -197,8 +204,7 @@ def harness(sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session]
)
oauth_clients = TriggerOAuthClientService(
clients=TriggerOAuthClientRepository(session_factory=sqlite_session_factory),
- get_provider=metadata.get_provider,
- is_plugin_verified=metadata.is_verified,
+ providers=metadata,
)
services = replace(services, workspaces=replace(services.workspaces, trigger_oauth_clients=oauth_clients))
app.extensions["application_services"] = services
@@ -212,6 +218,11 @@ def harness(sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session]
api.add_resource(
TriggerOAuthClientManageApi, "/workspaces/current/trigger-provider/<path:provider>/oauth/client"
)
+ api.add_resource(
+ TriggerOAuthAuthorizeApi,
+ "/workspaces/current/trigger-provider/<path:provider>/subscriptions/oauth/authorize",
+ )
+ api.add_resource(TriggerOAuthCallbackApi, "/oauth/plugin/<path:provider>/trigger/callback")
app.register_blueprint(blueprint)
with app.app_context():
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_flow.py b/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_flow.py
new file mode 100644
index 00000000000..45373d9d13e
--- /dev/null
+++ b/api/tests/unit_tests/controllers/console/workspace/test_trigger_oauth_flow.py
@@ -0,0 +1,482 @@
+"""Real HTTP admission and persisted OAuth clients; plugin/cache/builder ports are local."""
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field, replace
+from http import HTTPStatus
+from http.cookies import SimpleCookie
+from uuid import uuid4
+
+import pytest
+from pydantic import TypeAdapter
+from werkzeug.test import TestResponse
+
+from core.plugin.entities.plugin_daemon import CredentialType
+from core.trigger.entities.api_entities import SubscriptionBuilderApiEntity
+from extensions.ext_application_services import application_services
+from models.account import TenantAccountRole
+from models.provider_ids import TriggerProviderID
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
+from services.trigger.oauth_service import (
+ TriggerOAuthCallbackRequest,
+ TriggerOAuthContext,
+ TriggerOAuthContextError,
+ TriggerOAuthCredentials,
+ TriggerOAuthProviderError,
+ TriggerOAuthService,
+)
+from tests.unit_tests.controllers.console.workspace import test_trigger_oauth_client
+from tests.unit_tests.controllers.console.workspace.test_trigger_oauth_client import _PROVIDER, _Harness
+
+harness = test_trigger_oauth_client.harness
+
+_AUTHORIZE = f"/console/api/workspaces/current/trigger-provider/{_PROVIDER}/subscriptions/oauth/authorize"
+_CALLBACK = f"/console/api/oauth/plugin/{_PROVIDER}/trigger/callback"
+_REDIRECT_URI = f"https://console.example.test{_CALLBACK}"
+
+
+@dataclass(frozen=True)
+class _PluginCall:
+ tenant_id: str
+ user_id: str
+ provider_id: str
+ redirect_uri: str
+ client_config: PluginOAuthClientConfig
+
+
+@dataclass
+class _PluginOAuth:
+ harness: _Harness
+ authorizations: list[_PluginCall] = field(default_factory=list)
+ exchanges: list[tuple[_PluginCall, TriggerOAuthCallbackRequest]] = field(default_factory=list)
+ credentials: Mapping[str, object] = field(default_factory=lambda: {"access_token": "provider-access-token"})
+ fail_authorization: bool = False
+ fail_exchange: bool = False
+
+ def authorization_url(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ ) -> str:
+ assert all(not session.in_transaction() for session in self.harness.metadata.sessions)
+ self.authorizations.append(_PluginCall(tenant_id, user_id, str(provider_id), redirect_uri, client_config))
+ if self.fail_authorization:
+ raise TriggerOAuthProviderError("The provider could not start authorization")
+ return "https://provider.example.test/oauth/authorize?client_id=test-client"
+
+ def exchange_credentials(
+ self,
+ *,
+ tenant_id: str,
+ user_id: str,
+ provider_id: TriggerProviderID,
+ redirect_uri: str,
+ client_config: PluginOAuthClientConfig,
+ callback: TriggerOAuthCallbackRequest,
+ ) -> TriggerOAuthCredentials:
+ assert all(not session.in_transaction() for session in self.harness.metadata.sessions)
+ self.exchanges.append(
+ (_PluginCall(tenant_id, user_id, str(provider_id), redirect_uri, client_config), callback)
+ )
+ if self.fail_exchange:
+ raise TriggerOAuthProviderError("The provider could not exchange credentials")
+ return TriggerOAuthCredentials(self.credentials, 1234567890)
+
+
+@dataclass
+class _Contexts:
+ """External one-use capability boundary; real Redis expiry is tested separately."""
+
+ max_age: int = 300
+ contexts: dict[str, TriggerOAuthContext] = field(default_factory=dict)
+
+ def create(self, context: TriggerOAuthContext) -> str:
+ context_id = str(uuid4())
+ self.contexts[context_id] = context
+ return context_id
+
+ def consume(self, context_id: str) -> TriggerOAuthContext:
+ try:
+ return self.contexts.pop(context_id)
+ except KeyError as exc:
+ raise TriggerOAuthContextError("Invalid or expired context_id") from exc
+
+
+@dataclass
+class _Builders:
+ created: list[tuple[str, str, str, SubscriptionBuilderApiEntity]] = field(default_factory=list)
+ credentials: list[tuple[TriggerOAuthContext, str, Mapping[str, object], int]] = field(default_factory=list)
+
+ def create(self, *, tenant_id: str, user_id: str, provider_id: TriggerProviderID) -> SubscriptionBuilderApiEntity:
+ builder = SubscriptionBuilderApiEntity(
+ id=str(uuid4()),
+ name="GitHub subscription",
+ provider=str(provider_id),
+ endpoint="subscription-endpoint",
+ parameters={},
+ properties={},
+ credentials={},
+ credential_type=CredentialType.OAUTH2,
+ )
+ self.created.append((tenant_id, user_id, str(provider_id), builder))
+ return builder
+
+ def set_credentials(
+ self,
+ *,
+ context: TriggerOAuthContext,
+ provider_id: TriggerProviderID,
+ credentials: Mapping[str, object],
+ expires_at: int,
+ ) -> None:
+ self.credentials.append((context, str(provider_id), credentials, expires_at))
+
+
+@dataclass(frozen=True)
+class _Flow:
+ harness: _Harness
+ plugin: _PluginOAuth
+ contexts: _Contexts
+ builders: _Builders
+
+ def configure(self) -> None:
+ response = self.harness.call(
+ "POST", payload={"client_params": {"client_id": "test-client", "client_secret": "real-secret"}}
+ )
+ assert response.status_code == HTTPStatus.OK
+
+ def authorize(self) -> TestResponse:
+ return self.harness.call("GET", url=_AUTHORIZE)
+
+ def grant_callback(self, *, provider_id: str = _PROVIDER) -> str:
+ provider = TriggerProviderID(provider_id)
+ context_id = self.contexts.create(
+ TriggerOAuthContext(
+ tenant_id=self.harness.tenant_id,
+ user_id=self.harness.account_id,
+ plugin_id=provider.plugin_id,
+ provider=provider.provider_name,
+ subscription_builder_id=str(uuid4()),
+ )
+ )
+ self.harness.client.set_cookie("context_id", context_id)
+ return context_id
+
+
+def flow(harness: _Harness) -> _Flow:
+ plugin = _PluginOAuth(harness)
+ contexts = _Contexts()
+ builders = _Builders()
+ with harness.app.app_context():
+ services = application_services()
+ oauth = TriggerOAuthService(
+ clients=services.workspaces.trigger_oauth_clients,
+ providers=plugin,
+ contexts=contexts,
+ builders=builders,
+ )
+ harness.app.extensions["application_services"] = replace(
+ services, workspaces=replace(services.workspaces, trigger_oauth=oauth)
+ )
+ return _Flow(harness, plugin, contexts, builders)
+
+
+def test_authorize_returns_url_builder_and_http_only_context_cookie(flow: _Flow) -> None:
+ flow.configure()
+
+ response = flow.authorize()
+
+ assert response.status_code == HTTPStatus.OK
+ assert response.content_type == "application/json"
+ builder = flow.builders.created[0][3]
+ assert response.get_json() == {
+ "authorization_url": "https://provider.example.test/oauth/authorize?client_id=test-client",
+ "subscription_builder_id": builder.id,
+ "subscription_builder": builder.model_dump(mode="json"),
+ }
+ cookie = SimpleCookie()
+ cookie.load(response.headers["Set-Cookie"])
+ context_cookie = cookie["context_id"]
+ assert context_cookie["httponly"]
+ assert context_cookie["samesite"] == "Lax"
+ assert context_cookie["max-age"] == "300"
+ assert context_cookie["path"] == "/"
+ context = flow.contexts.contexts[context_cookie.value]
+ identifier = flow.harness.metadata.provider.plugin_unique_identifier
+ assert context == TriggerOAuthContext(
+ flow.harness.tenant_id, flow.harness.account_id, "langgenius/github", "github", builder.id, identifier
+ )
+ assert flow.plugin.authorizations == [
+ _PluginCall(
+ flow.harness.tenant_id,
+ flow.harness.account_id,
+ _PROVIDER,
+ _REDIRECT_URI,
+ PluginOAuthClientConfig(identifier, {"client_id": "test-client", "client_secret": "real-secret"}),
+ )
+ ]
+ assert "real-secret" not in response.get_data(as_text=True)
+
+
+def test_callback_without_login_preserves_http_input_and_updates_only_context_builder(flow: _Flow) -> None:
+ flow.configure()
+ assert flow.authorize().status_code == HTTPStatus.OK
+ context = next(iter(flow.contexts.contexts.values()))
+ callback_path = f"{_CALLBACK}?code=a%2Bb&state=provider-state"
+
+ response = flow.harness.client.get(
+ callback_path,
+ headers={"X-Provider-Signature": "signature", "Content-Type": "application/octet-stream"},
+ data=b"provider-body",
+ )
+
+ assert response.status_code == HTTPStatus.FOUND
+ assert response.headers["Location"] == "https://console.example.test/oauth-callback"
+ assert response.content_type == "text/html; charset=utf-8"
+ assert len(flow.plugin.exchanges) == 1
+ call, callback = flow.plugin.exchanges[0]
+ assert call == flow.plugin.authorizations[0]
+ assert callback.method == "GET"
+ assert callback.full_path == callback_path
+ assert callback.body == b"provider-body"
+ assert dict(callback.headers)["X-Provider-Signature"] == "signature"
+ assert dict(callback.headers)["Content-Type"] == "application/octet-stream"
+ assert flow.builders.credentials == [(context, _PROVIDER, {"access_token": "provider-access-token"}, 1234567890)]
+ assert flow.contexts.contexts == {}
+
+ replay = flow.harness.client.get(callback_path)
+ assert replay.status_code == HTTPStatus.FORBIDDEN
+ assert replay.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert len(flow.plugin.exchanges) == 1
+ assert len(flow.builders.credentials) == 1
+
+
+def test_callback_rejects_package_replaced_after_authorization_before_exchange_or_update(flow: _Flow) -> None:
+ flow.configure()
+ assert flow.authorize().status_code == HTTPStatus.OK
+ context = next(iter(flow.contexts.contexts.values()))
+ original_identifier = flow.harness.metadata.provider.plugin_unique_identifier
+ assert context.plugin_unique_identifier == original_identifier
+ flow.harness.metadata.provider.plugin_unique_identifier = "langgenius/github:2.0.0@replacement"
+
+ response = flow.harness.client.get(f"{_CALLBACK}?code=provider-code")
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert response.get_json()["message"] == "Plugin changed during OAuth authorization; restart authorization"
+ assert flow.plugin.exchanges == []
+ assert flow.builders.credentials == []
+ assert flow.contexts.contexts == {}
+
+
[email protected]("identifier_state", ["missing", "none"])
+def test_legacy_context_without_package_uses_current_package_for_exchange(flow: _Flow, identifier_state: str) -> None:
+ flow.configure()
+ payload: dict[str, object] = {
+ "tenant_id": flow.harness.tenant_id,
+ "user_id": flow.harness.account_id,
+ "plugin_id": "langgenius/github",
+ "provider": "github",
+ "subscription_builder_id": str(uuid4()),
+ }
+ if identifier_state == "none":
+ payload["plugin_unique_identifier"] = None
+ context = TypeAdapter(TriggerOAuthContext).validate_python(payload)
+ assert context.plugin_unique_identifier is None
+ context_id = flow.contexts.create(context)
+ flow.harness.client.set_cookie("context_id", context_id)
+ current_identifier = "langgenius/github:2.0.0@replacement"
+ flow.harness.metadata.provider.plugin_unique_identifier = current_identifier
+
+ response = flow.harness.client.get(f"{_CALLBACK}?code=provider-code")
+
+ assert response.status_code == HTTPStatus.FOUND
+ assert len(flow.plugin.exchanges) == 1
+ call, _callback = flow.plugin.exchanges[0]
+ assert call.client_config == PluginOAuthClientConfig(
+ current_identifier, {"client_id": "test-client", "client_secret": "real-secret"}
+ )
+ assert flow.builders.credentials == [(context, _PROVIDER, {"access_token": "provider-access-token"}, 1234567890)]
+ assert flow.contexts.contexts == {}
+
+
[email protected]("role", list(TenantAccountRole))
+def test_authorize_keeps_access_for_each_workspace_role(flow: _Flow, role: TenantAccountRole) -> None:
+ flow.configure()
+ flow.harness.set_role(role)
+
+ assert flow.authorize().status_code == HTTPStatus.OK
+ assert len(flow.plugin.authorizations) == 1
+
+
+def test_authorize_still_requires_login(flow: _Flow) -> None:
+ flow.configure()
+
+ response = flow.harness.client.get(_AUTHORIZE)
+
+ assert response.status_code == HTTPStatus.UNAUTHORIZED
+ assert flow.plugin.authorizations == []
+ assert flow.builders.created == []
+
+
[email protected]("configured_disabled", [False, True])
+def test_authorize_without_enabled_client_returns_not_found(flow: _Flow, configured_disabled: bool) -> None:
+ if configured_disabled:
+ flow.harness.add_client(
+ tenant_id=flow.harness.tenant_id, encrypted_params='{"client_id":"disabled"}', enabled=False
+ )
+
+ response = flow.authorize()
+
+ assert response.status_code == HTTPStatus.NOT_FOUND
+ assert response.get_json()["code"] == "not_found"
+ assert "OAuth client" in response.get_json()["message"]
+ assert flow.builders.created == []
+ assert flow.contexts.contexts == {}
+ assert flow.plugin.authorizations == []
+
+
+def test_callback_configuration_removed_after_authorize_returns_forbidden(flow: _Flow) -> None:
+ flow.configure()
+ assert flow.authorize().status_code == HTTPStatus.OK
+ assert flow.harness.call("DELETE").status_code == HTTPStatus.OK
+
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "forbidden"
+ assert "OAuth client" in response.get_json()["message"]
+ assert flow.plugin.exchanges == []
+ assert flow.builders.credentials == []
+
+
[email protected]("context_state", ["missing_cookie", "unknown", "expired"])
+def test_missing_or_expired_context_fails_before_plugin_or_config_lookup(flow: _Flow, context_state: str) -> None:
+ if context_state == "unknown":
+ flow.harness.client.set_cookie("context_id", str(uuid4()))
+ elif context_state == "expired":
+ context_id = flow.grant_callback()
+ del flow.contexts.contexts[context_id]
+
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert flow.harness.metadata.provider_requests == 0
+ assert flow.plugin.exchanges == []
+ assert flow.builders.credentials == []
+
+
[email protected]("context_state", ["missing_cookie", "unknown", "expired"])
+def test_invalid_context_is_rejected_before_parsing_invalid_provider(flow: _Flow, context_state: str) -> None:
+ if context_state == "unknown":
+ flow.harness.client.set_cookie("context_id", str(uuid4()))
+ elif context_state == "expired":
+ context_id = flow.grant_callback()
+ del flow.contexts.contexts[context_id]
+
+ response = flow.harness.client.get("/console/api/oauth/plugin/INVALID!/trigger/callback")
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert flow.harness.metadata.provider_requests == 0
+ assert flow.plugin.exchanges == []
+
+
+def test_invalid_provider_after_valid_context_consumes_context(flow: _Flow) -> None:
+ context_id = flow.grant_callback()
+
+ response = flow.harness.client.get("/console/api/oauth/plugin/INVALID!/trigger/callback")
+
+ assert response.status_code == HTTPStatus.BAD_REQUEST
+ assert response.get_json()["code"] == "invalid_param"
+ assert context_id not in flow.contexts.contexts
+ assert flow.plugin.exchanges == []
+
+
[email protected]("context_state", ["missing_cookie", "unknown"])
+def test_invalid_context_is_rejected_before_reading_oversized_body(flow: _Flow, context_state: str) -> None:
+ flow.harness.app.config["MAX_CONTENT_LENGTH"] = 1
+ if context_state == "unknown":
+ flow.harness.client.set_cookie("context_id", str(uuid4()))
+
+ response = flow.harness.client.get(_CALLBACK, data=b"oversized")
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert flow.plugin.exchanges == []
+
+
+def test_valid_context_reads_callback_body_and_enforces_limit(flow: _Flow) -> None:
+ flow.configure()
+ flow.grant_callback()
+ flow.harness.app.config["MAX_CONTENT_LENGTH"] = 1
+
+ response = flow.harness.client.get(_CALLBACK, data=b"oversized")
+
+ assert response.status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE
+ assert flow.plugin.exchanges == []
+
+
[email protected]("provider", ["another/github/github", "langgenius/github/other"])
+def test_context_cannot_authorize_another_plugin_or_provider(flow: _Flow, provider: str) -> None:
+ flow.grant_callback(provider_id=provider)
+
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.FORBIDDEN
+ assert response.get_json()["code"] == "trigger_oauth_context_invalid"
+ assert flow.harness.metadata.provider_requests == 0
+ assert flow.contexts.contexts == {}
+ assert flow.plugin.exchanges == []
+ assert flow.builders.credentials == []
+
+
[email protected]("operation", ["authorize", "callback"])
+def test_plugin_failure_has_specific_bad_gateway_error(flow: _Flow, operation: str) -> None:
+ flow.configure()
+ if operation == "authorize":
+ flow.plugin.fail_authorization = True
+ response = flow.authorize()
+ else:
+ flow.grant_callback()
+ flow.plugin.fail_exchange = True
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.BAD_GATEWAY
+ assert response.get_json()["code"] == "trigger_oauth_provider_error"
+ assert flow.builders.credentials == []
+
+
+def test_empty_provider_credentials_do_not_complete_builder(flow: _Flow) -> None:
+ flow.configure()
+ flow.grant_callback()
+ flow.plugin.credentials = {}
+
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.BAD_GATEWAY
+ assert response.get_json()["code"] == "trigger_oauth_provider_error"
+ assert flow.builders.credentials == []
+
+
[email protected]("operation", ["authorize", "callback"])
+def test_corrupt_persisted_client_is_server_error_instead_of_invalid_request(flow: _Flow, operation: str) -> None:
+ flow.harness.add_client(tenant_id=flow.harness.tenant_id, encrypted_params="{broken-json")
+ if operation == "authorize":
+ response = flow.authorize()
+ else:
+ flow.grant_callback()
+ response = flow.harness.client.get(_CALLBACK)
+
+ assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
+ assert response.get_json()["code"] == "trigger_oauth_client_config_invalid"
+ assert _PROVIDER in response.get_json()["message"]
+ assert "{broken-json" not in response.get_data(as_text=True)
+ assert flow.plugin.authorizations == []
+ assert flow.plugin.exchanges == []
+ assert flow.builders.credentials == []
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_trigger_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_trigger_providers.py
index 98471033c51..32bf8fb747e 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_trigger_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_trigger_providers.py
@@ -11,12 +11,10 @@ import pytest
from flask import Flask
from pydantic import ValidationError
from sqlalchemy.engine import Engine
-from werkzeug.exceptions import BadRequest, Forbidden
+from werkzeug.exceptions import BadRequest
from controllers.common.errors import NotFoundError
from controllers.console.workspace.trigger_providers import (
- TriggerOAuthAuthorizeApi,
- TriggerOAuthCallbackApi,
TriggerProviderIconApi,
TriggerProviderInfoApi,
TriggerProviderListApi,
@@ -41,14 +39,10 @@ from core.trigger.entities.entities import RequestLog
from models.account import Account
from models.engine import db
from services.credentials.query import CredentialQuery
-from services.plugin.dispatch_identity import PluginOAuthClientConfig
"""Unit tests for controllers.console.workspace.trigger_providers endpoints."""
-_OAUTH_IDENTIFIER = f"langgenius/github:1.0.0@{'a' * 64}"
-
-
def mock_user() -> Account:
user = Account(name="User", email="user.com")
user.id = "u1"
@@ -395,189 +389,6 @@ class TestTriggerProviderApisCases:
"s1",
) == {"result": "success"}
- class TestTriggerOAuthApis:
- def test_oauth_callback_rejects_replaced_package_before_dispatch(
- self, app: Flask, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- context = {
- "user_id": "u1",
- "tenant_id": "t1",
- "subscription_builder_id": "b1",
- "plugin_id": "langgenius/github",
- "provider": "github",
- "plugin_unique_identifier": _OAUTH_IDENTIFIER,
- }
- config = PluginOAuthClientConfig(f"langgenius/github:2.0.0@{'b' * 64}", {"client_secret": "test-secret"})
- controller_module = import_module("controllers.console.workspace.trigger_providers")
- monkeypatch.setattr(
- controller_module.OAuthProxyService,
- "use_proxy_context",
- lambda _context_id: context,
- )
- monkeypatch.setattr(
- controller_module.TriggerProviderService,
- "get_oauth_client",
- lambda *_args, **_kwargs: config,
- )
-
- def unexpected_dispatch(*_args: object, **_kwargs: object) -> None:
- raise AssertionError("Changed packages must not receive OAuth credentials")
-
- monkeypatch.setattr(controller_module.OAuthHandler, "get_credentials", unexpected_dispatch)
- api = TriggerOAuthCallbackApi()
- with app.test_request_context("/", headers={"Cookie": "context_id=ctx"}):
- with pytest.raises(Forbidden, match="Plugin changed"):
- unwrap(api.get)(api, "github")
-
- def test_oauth_authorize_success(self, app: Flask) -> None:
- api = TriggerOAuthAuthorizeApi()
- method = unwrap(api.get)
-
- with (
- app.test_request_context("/"),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerProviderService.get_oauth_client",
- return_value=PluginOAuthClientConfig(_OAUTH_IDENTIFIER, {"a": 1}),
- ),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerSubscriptionBuilderService.create_trigger_subscription_builder",
- return_value=subscription_builder(),
- ),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthProxyService.create_proxy_context",
- return_value="ctx",
- ) as create_context,
- patch(
- "controllers.console.workspace.trigger_providers.OAuthHandler.get_authorization_url",
- return_value=MagicMock(authorization_url="url"),
- ) as authorize,
- ):
- resp = method(api, "t1", mock_user(), "github")
- assert resp.status_code == 200
- assert create_context.call_args.kwargs["extra_data"]["plugin_unique_identifier"] == _OAUTH_IDENTIFIER
- assert authorize.call_args.kwargs["plugin_unique_identifier"] == _OAUTH_IDENTIFIER
- assert authorize.call_args.kwargs["system_credentials"] == {"a": 1}
-
- def test_oauth_authorize_no_client(self, app: Flask) -> None:
- api = TriggerOAuthAuthorizeApi()
- method = unwrap(api.get)
-
- with (
- app.test_request_context("/"),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerProviderService.get_oauth_client",
- return_value=None,
- ),
- ):
- with pytest.raises(NotFoundError):
- method(api, "t1", mock_user(), "github")
-
- def test_oauth_callback_forbidden(self, app: Flask) -> None:
- api = TriggerOAuthCallbackApi()
- method = unwrap(api.get)
-
- with app.test_request_context("/"):
- with pytest.raises(Forbidden):
- method(api, "github")
-
- def test_oauth_callback_success(self, app: Flask) -> None:
- api = TriggerOAuthCallbackApi()
- method = unwrap(api.get)
-
- ctx = {
- "user_id": "u1",
- "tenant_id": "t1",
- "subscription_builder_id": "b1",
- "plugin_id": "langgenius/github",
- "provider": "github",
- "plugin_unique_identifier": _OAUTH_IDENTIFIER,
- }
-
- with (
- app.test_request_context("/", headers={"Cookie": "context_id=ctx"}),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthProxyService.use_proxy_context",
- return_value=ctx,
- ),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerProviderService.get_oauth_client",
- return_value=PluginOAuthClientConfig(_OAUTH_IDENTIFIER, {"a": 1}),
- ),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthHandler.get_credentials",
- return_value=MagicMock(credentials={"a": 1}, expires_at=1),
- ) as get_credentials,
- patch(
- "controllers.console.workspace.trigger_providers.TriggerSubscriptionBuilderService.update_trigger_subscription_builder"
- ) as mock_update_builder,
- ):
- resp = method(api, "github")
- assert resp.status_code == 302
- assert get_credentials.call_args.kwargs["plugin_unique_identifier"] == _OAUTH_IDENTIFIER
- assert get_credentials.call_args.kwargs["system_credentials"] == {"a": 1}
- mock_update_builder.assert_called_once_with(
- tenant_id="t1",
- user_id="u1",
- provider_id=ANY,
- subscription_builder_id="b1",
- subscription_builder_updater=ANY,
- )
-
- def test_oauth_callback_no_oauth_client(self, app: Flask) -> None:
- api = TriggerOAuthCallbackApi()
- method = unwrap(api.get)
-
- ctx = {
- "user_id": "u1",
- "tenant_id": "t1",
- "subscription_builder_id": "b1",
- }
-
- with (
- app.test_request_context("/", headers={"Cookie": "context_id=ctx"}),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthProxyService.use_proxy_context",
- return_value=ctx,
- ),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerProviderService.get_oauth_client",
- return_value=None,
- ),
- ):
- with pytest.raises(Forbidden):
- method(api, "github")
-
- def test_oauth_callback_empty_credentials(self, app: Flask) -> None:
- api = TriggerOAuthCallbackApi()
- method = unwrap(api.get)
-
- ctx = {
- "user_id": "u1",
- "tenant_id": "t1",
- "subscription_builder_id": "b1",
- "plugin_id": "langgenius/github",
- "provider": "github",
- "plugin_unique_identifier": _OAUTH_IDENTIFIER,
- }
-
- with (
- app.test_request_context("/", headers={"Cookie": "context_id=ctx"}),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthProxyService.use_proxy_context",
- return_value=ctx,
- ),
- patch(
- "controllers.console.workspace.trigger_providers.TriggerProviderService.get_oauth_client",
- return_value=PluginOAuthClientConfig(_OAUTH_IDENTIFIER, {"a": 1}),
- ),
- patch(
- "controllers.console.workspace.trigger_providers.OAuthHandler.get_credentials",
- return_value=MagicMock(credentials=None, expires_at=None),
- ),
- ):
- with pytest.raises(ValueError, match="Failed to get OAuth credentials from the provider\\."):
- method(api, "github")
-
class TestTriggerSubscriptionVerifyApi:
def test_verify_success(self, app: Flask) -> None:
api = TriggerSubscriptionVerifyApi()
diff --git a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py
index ad82f06dcc8..53dc3759603 100644
--- a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py
+++ b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py
@@ -15,8 +15,7 @@ from werkzeug.exceptions import UnprocessableEntity
from controllers.inner_api.workspace import workspace as controller
from controllers.inner_api.wraps import InnerApiUnauthorizedError
-from core.plugin.plugin_service import PluginService
-from core.trigger.trigger_manager import TriggerManager
+from core.plugin.impl.oauth import OAuthHandler
from extensions.application_services.workspace import WorkspaceServices
from libs.external_api import register_external_error_handlers
from repositories.trigger.oauth_client_repository import TriggerOAuthClientRepository
@@ -28,6 +27,12 @@ from services.errors.workspace import (
WorkspacesLimitExceededError,
)
from services.trigger.oauth_client_service import TriggerOAuthClientService
+from services.trigger.oauth_gateway import (
+ OAuthProxyContextGateway,
+ PluginTriggerOAuthGateway,
+ TriggerOAuthBuilderGateway,
+)
+from services.trigger.oauth_service import TriggerOAuthService
from services.workspace.contracts import CreatedWorkspace, WorkspaceMembership
from services.workspace.provisioning_service import WorkspaceProvisioningService
from services.workspace.service import WorkspaceQueryService, WorkspaceService
@@ -98,6 +103,10 @@ class TestWorkspaceCases:
@pytest.fixture
def provisioning(monkeypatch: pytest.MonkeyPatch, sqlite_session_factory: sessionmaker[Session]) -> Mock:
provisioning = create_autospec(WorkspaceProvisioningService, instance=True)
+ oauth_provider = PluginTriggerOAuthGateway(oauth=OAuthHandler())
+ oauth_clients = TriggerOAuthClientService(
+ clients=TriggerOAuthClientRepository(session_factory=sqlite_session_factory), providers=oauth_provider
+ )
services = WorkspaceServices(
queries=create_autospec(WorkspaceQueryService, instance=True),
management=create_autospec(WorkspaceService, instance=True),
@@ -108,10 +117,12 @@ class TestWorkspaceCases:
invitations=Mock(),
identity=Mock(),
resource_cleanup=Mock(),
- trigger_oauth_clients=TriggerOAuthClientService(
- clients=TriggerOAuthClientRepository(session_factory=sqlite_session_factory),
- get_provider=TriggerManager.get_trigger_provider,
- is_plugin_verified=PluginService.is_plugin_verified,
+ trigger_oauth_clients=oauth_clients,
+ trigger_oauth=TriggerOAuthService(
+ clients=oauth_clients,
+ providers=oauth_provider,
+ contexts=OAuthProxyContextGateway(),
+ builders=TriggerOAuthBuilderGateway(),
),
)
monkeypatch.setattr(controller, "application_services", lambda: Services(services))
diff --git a/api/tests/unit_tests/core/plugin/impl/test_oauth.py b/api/tests/unit_tests/core/plugin/impl/test_oauth.py
index 17a05bad0d2..3b5c2ffa637 100644
--- a/api/tests/unit_tests/core/plugin/impl/test_oauth.py
+++ b/api/tests/unit_tests/core/plugin/impl/test_oauth.py
@@ -6,6 +6,7 @@ import pytest
from pytest_mock import MockerFixture
from werkzeug import Request
from werkzeug.datastructures import Headers
+from werkzeug.exceptions import RequestEntityTooLarge
from werkzeug.test import EnvironBuilder
from core.plugin.impl.oauth import OAuthHandler
@@ -217,3 +218,21 @@ def test_oauth_convert_request_to_raw_data_with_json_body() -> None:
assert b'"code": "abc123"' in raw_request_bytes
assert b'"state": "xyz789"' in raw_request_bytes
assert b'"grant_type": "authorization_code"' in raw_request_bytes
+
+
+def test_get_credentials_preserves_error_wrapper_when_callback_body_exceeds_limit() -> None:
+ with Request.from_values(method="POST", data="over-limit") as request:
+ request.max_content_length = 1
+
+ with pytest.raises(ValueError, match="Error getting credentials: 413") as raised:
+ OAuthHandler().get_credentials(
+ tenant_id="tenant-id",
+ user_id="user-id",
+ plugin_id="langgenius/github",
+ provider="github",
+ redirect_uri="https://console.example.test/oauth/callback",
+ system_credentials={},
+ request=request,
+ )
+
+ assert isinstance(raised.value.__cause__, RequestEntityTooLarge)
diff --git a/api/tests/unit_tests/repositories/test_trigger_oauth_client_repository.py b/api/tests/unit_tests/repositories/test_trigger_oauth_client_repository.py
index 9ce1411c449..1395762549c 100644
--- a/api/tests/unit_tests/repositories/test_trigger_oauth_client_repository.py
+++ b/api/tests/unit_tests/repositories/test_trigger_oauth_client_repository.py
@@ -37,7 +37,7 @@ def _custom(*, tenant_id: str, plugin_id: str, provider: str) -> TriggerOAuthTen
def test_missing_clients_return_empty_snapshot(repository: TriggerOAuthClientRepository) -> None:
assert repository.get(
tenant_id=str(uuid4()), provider_id=TriggerProviderID("langgenius/github/github")
- ) == TriggerOAuthClientSnapshot(custom=None, system_configured=False)
+ ) == TriggerOAuthClientSnapshot(custom=None, encrypted_system_oauth_params=None)
def test_repository_returns_its_connection_after_every_operation(
@@ -81,7 +81,7 @@ def test_custom_lookup_uses_complete_owner_scope(
assert repository.get(
tenant_id=tenant_id, provider_id=TriggerProviderID("langgenius/github/github")
- ) == TriggerOAuthClientSnapshot(custom=None, system_configured=False)
+ ) == TriggerOAuthClientSnapshot(custom=None, encrypted_system_oauth_params=None)
@pytest.mark.parametrize("other_scope", ["plugin", "provider"])
@@ -133,7 +133,7 @@ def test_get_materializes_ciphertext_and_enabled_before_closing_session(
encrypted_oauth_params='{"client_secret": "original-ciphertext"}',
enabled=False,
),
- system_configured=True,
+ encrypted_system_oauth_params="system-ciphertext",
)
diff --git a/api/tests/unit_tests/services/trigger/test_oauth_client_service.py b/api/tests/unit_tests/services/trigger/test_oauth_client_service.py
new file mode 100644
index 00000000000..4ada717c9bf
--- /dev/null
+++ b/api/tests/unit_tests/services/trigger/test_oauth_client_service.py
@@ -0,0 +1,258 @@
+"""Resolve real stored OAuth credentials before entering provider operations."""
+
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from tempfile import TemporaryDirectory
+from uuid import uuid4
+
+import pytest
+from flask import Flask
+from sqlalchemy import Connection, Engine, event
+from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
+
+from core.entities.provider_entities import ProviderConfig, ProviderConfigType
+from core.tools.utils.system_encryption import encrypt_system_params
+from extensions.ext_key_provider import key_provider_manager
+from extensions.ext_storage import storage
+from models.account import Tenant
+from models.engine import db
+from models.provider_ids import TriggerProviderID
+from models.trigger import TriggerOAuthSystemClient, TriggerOAuthTenantClient
+from repositories.trigger.oauth_client_repository import TriggerOAuthClientRepository
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
+from services.trigger.oauth_client_service import (
+ TriggerOAuthClientConfigError,
+ TriggerOAuthClientService,
+ TriggerOAuthProviderMetadata,
+)
+from tests.helpers.unit.config_override import config_overrides_context
+
+_IDENTIFIER = "langgenius/github:1.0.0@test"
+_PROVIDER = TriggerProviderID("langgenius/github/github")
+_SCHEMA = [
+ ProviderConfig(name="client_id", type=ProviderConfigType.TEXT_INPUT),
+ ProviderConfig(name="client_secret", type=ProviderConfigType.SECRET_INPUT),
+]
+
+
+@dataclass
+class _PluginMetadata:
+ """Only metadata from the plugin daemon is supplied by this external boundary."""
+
+ tenant_id: str
+ sessions: list[Session] = field(default_factory=list)
+ verified: bool = True
+ verification_calls: int = 0
+
+ def assert_sessions_closed(self) -> None:
+ assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
+
+ def get_metadata(self, *, tenant_id: str, provider_id: TriggerProviderID) -> TriggerOAuthProviderMetadata:
+ self.assert_sessions_closed()
+ assert tenant_id == self.tenant_id
+ assert provider_id == _PROVIDER
+ return TriggerOAuthProviderMetadata(schema=_SCHEMA, plugin_unique_identifier=_IDENTIFIER)
+
+ def is_verified(self, *, tenant_id: str, plugin_unique_identifier: str) -> bool:
+ self.assert_sessions_closed()
+ assert tenant_id == self.tenant_id
+ assert plugin_unique_identifier == _IDENTIFIER
+ self.verification_calls += 1
+ return self.verified
+
+
+@dataclass(frozen=True)
+class _Harness:
+ service: TriggerOAuthClientService
+ session_factory: sessionmaker[Session]
+ metadata: _PluginMetadata
+
+ @property
+ def tenant_id(self) -> str:
+ return self.metadata.tenant_id
+
+ def add_system(self, *, encrypted_params: str) -> None:
+ with self.session_factory.begin() as session:
+ session.add(
+ TriggerOAuthSystemClient(
+ plugin_id=_PROVIDER.plugin_id,
+ provider=_PROVIDER.provider_name,
+ encrypted_oauth_params=encrypted_params,
+ )
+ )
+
+ def add_custom(self, *, encrypted_params: str, enabled: bool) -> None:
+ with self.session_factory.begin() as session:
+ session.add(
+ TriggerOAuthTenantClient(
+ tenant_id=self.tenant_id,
+ plugin_id=_PROVIDER.plugin_id,
+ provider=_PROVIDER.provider_name,
+ encrypted_oauth_params=encrypted_params,
+ enabled=enabled,
+ )
+ )
+
+ def resolve(self) -> PluginOAuthClientConfig | None:
+ result = self.service.resolve(tenant_id=self.tenant_id, provider_id=_PROVIDER)
+ self.metadata.assert_sessions_closed()
+ return result
+
+
+def harness(sqlite_engine: Engine, sqlite_session_factory: sessionmaker[Session]) -> Iterator[_Harness]:
+ previous_storage = storage.__dict__.copy()
+ previous_key_provider = key_provider_manager._provider
+ with (
+ TemporaryDirectory(prefix="trigger-oauth-resolution-keys-") as storage_path,
+ config_overrides_context(
+ KEY_PROVIDER_TYPE="local",
+ STORAGE_TYPE="local",
+ STORAGE_LOCAL_PATH=storage_path,
+ ),
+ ):
+ app = Flask(__name__)
+ app.config.update(TESTING=True, SQLALCHEMY_DATABASE_URI=str(sqlite_engine.url))
+ db.init_app(app)
+ storage.init_app(app)
+ key_provider_manager.init_app(app)
+ with sqlite_session_factory.begin() as session:
+ tenant = Tenant(name="OAuth workspace")
+ session.add(tenant)
+ session.flush()
+ tenant_id = tenant.id
+ metadata = _PluginMetadata(tenant_id)
+ service = TriggerOAuthClientService(
+ clients=TriggerOAuthClientRepository(session_factory=sqlite_session_factory), providers=metadata
+ )
+
+ def observe_repository_session(
+ session: Session, _transaction: SessionTransaction, _connection: Connection
+ ) -> None:
+ metadata.sessions.append(session)
+
+ def assert_repository_closed_for_key_lookup(
+ _session: Session, _transaction: SessionTransaction, _connection: Connection
+ ) -> None:
+ metadata.assert_sessions_closed()
+
+ event.listen(sqlite_session_factory.class_, "after_begin", observe_repository_session)
+ event.listen(db.session.session_factory.class_, "after_begin", assert_repository_closed_for_key_lookup)
+ try:
+ with app.app_context():
+ yield _Harness(service, sqlite_session_factory, metadata)
+ finally:
+ event.remove(sqlite_session_factory.class_, "after_begin", observe_repository_session)
+ event.remove(db.session.session_factory.class_, "after_begin", assert_repository_closed_for_key_lookup)
+ with app.app_context():
+ db.session.remove()
+ db.engine.dispose()
+ storage.__dict__.clear()
+ storage.__dict__.update(previous_storage)
+ key_provider_manager._provider = previous_key_provider
+
+
+def test_resolve_without_configuration_returns_none_without_verification(harness: _Harness) -> None:
+ assert harness.resolve() is None
+ assert harness.metadata.verification_calls == 0
+
+
+def test_enabled_custom_credentials_decrypt_with_real_rsa_and_take_priority(harness: _Harness) -> None:
+ with harness.session_factory.begin() as session:
+ tenant = session.get(Tenant, harness.tenant_id)
+ assert tenant is not None
+ tenant.encrypt_public_key = key_provider_manager.provider.generate_key_pair(tenant.id)
+ harness.add_system(encrypted_params=encrypt_system_params({"client_secret": "system-secret"}))
+ harness.metadata.verified = False
+ harness.service.save(
+ tenant_id=harness.tenant_id,
+ provider_id=_PROVIDER,
+ client_params={"client_id": "tenant-id", "client_secret": "tenant-secret"},
+ enabled=True,
+ )
+
+ assert harness.resolve() == PluginOAuthClientConfig(
+ _IDENTIFIER, {"client_id": "tenant-id", "client_secret": "tenant-secret"}
+ )
+ assert harness.metadata.verification_calls == 0
+
+
+def test_enabled_empty_custom_client_does_not_fall_back_to_system(harness: _Harness) -> None:
+ harness.add_custom(encrypted_params="{}", enabled=True)
+ harness.add_system(encrypted_params=encrypt_system_params({"client_id": "system-id"}))
+
+ assert harness.resolve() == PluginOAuthClientConfig(_IDENTIFIER, {})
+ assert harness.metadata.verification_calls == 0
+
+
[email protected]("custom_enabled", [None, False])
+def test_verified_system_credentials_are_used_without_enabled_custom_client(
+ harness: _Harness, custom_enabled: bool | None
+) -> None:
+ if custom_enabled is not None:
+ harness.add_custom(encrypted_params="invalid-but-disabled", enabled=custom_enabled)
+ harness.add_system(encrypted_params=encrypt_system_params({"client_id": "system-id", "client_secret": "secret"}))
+
+ assert harness.resolve() == PluginOAuthClientConfig(
+ _IDENTIFIER, {"client_id": "system-id", "client_secret": "secret"}
+ )
+ assert harness.metadata.verification_calls == 1
+
+
+def test_unverified_plugin_cannot_read_system_credentials(harness: _Harness) -> None:
+ harness.add_system(encrypted_params="invalid-system-ciphertext")
+ harness.metadata.verified = False
+
+ assert harness.resolve() is None
+ assert harness.metadata.verification_calls == 1
+
+
[email protected]("invalid_params", ['{"client_secret": "private-value"', '["private-value"]'])
+def test_invalid_enabled_custom_config_raises_domain_error_without_exposing_contents(
+ harness: _Harness, invalid_params: str
+) -> None:
+ harness.add_custom(encrypted_params=invalid_params, enabled=True)
+
+ with pytest.raises(TriggerOAuthClientConfigError) as raised:
+ harness.resolve()
+
+ assert str(_PROVIDER) in str(raised.value)
+ assert "private-value" not in str(raised.value)
+ harness.metadata.assert_sessions_closed()
+
+
[email protected]("invalid_params", ["", "invalid-system-ciphertext"])
+def test_invalid_system_config_raises_domain_error_without_exposing_ciphertext(
+ harness: _Harness, invalid_params: str
+) -> None:
+ harness.add_system(encrypted_params=invalid_params)
+
+ with pytest.raises(TriggerOAuthClientConfigError) as raised:
+ harness.resolve()
+
+ assert "system OAuth client" in str(raised.value)
+ assert "invalid-system-ciphertext" not in str(raised.value)
+ harness.metadata.assert_sessions_closed()
+
+
+def test_disabled_custom_without_system_client_returns_none(harness: _Harness) -> None:
+ harness.add_custom(encrypted_params="invalid-but-disabled", enabled=False)
+
+ assert harness.resolve() is None
+ assert harness.metadata.verification_calls == 0
+
+
[email protected]("other_scope", ["tenant", "plugin", "provider"])
+def test_resolution_does_not_read_custom_credentials_from_other_scope(harness: _Harness, other_scope: str) -> None:
+ with harness.session_factory.begin() as session:
+ session.add(
+ TriggerOAuthTenantClient(
+ tenant_id=str(uuid4()) if other_scope == "tenant" else harness.tenant_id,
+ plugin_id="langgenius/other" if other_scope == "plugin" else _PROVIDER.plugin_id,
+ provider="other" if other_scope == "provider" else _PROVIDER.provider_name,
+ encrypted_oauth_params='{"client_id": "other-scope"}',
+ enabled=True,
+ )
+ )
+
+ assert harness.resolve() is None
diff --git a/api/tests/unit_tests/services/trigger/test_oauth_gateway.py b/api/tests/unit_tests/services/trigger/test_oauth_gateway.py
new file mode 100644
index 00000000000..042de600f5f
--- /dev/null
+++ b/api/tests/unit_tests/services/trigger/test_oauth_gateway.py
@@ -0,0 +1,222 @@
+"""Exercise the trigger gateway and real OAuth transport against a local HTTP server."""
+
+import json
+from collections.abc import Iterator
+from contextlib import closing
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from threading import Thread
+from typing import override
+
+import pytest
+from werkzeug import Request
+from werkzeug.test import EnvironBuilder
+from yarl import URL
+
+from configs import dify_config
+from core.plugin.impl import base as plugin_transport
+from core.plugin.impl.oauth import OAuthHandler
+from models.provider_ids import TriggerProviderID
+from services.plugin.dispatch_identity import PluginOAuthClientConfig
+from services.trigger.oauth_gateway import PluginTriggerOAuthGateway
+from services.trigger.oauth_service import TriggerOAuthCallbackRequest, TriggerOAuthProviderError
+
+_PROVIDER = TriggerProviderID("langgenius/github/github")
+_REDIRECT_URI = "https://console.example/console/api/oauth/plugin/langgenius/github/github/trigger/callback"
+_CLIENT_PARAMS: dict[str, object] = {"client_id": "client-id", "client_secret": "client-secret"}
+_IDENTIFIER = "langgenius/github:1.0.0@test"
+_CLIENT_CONFIG = PluginOAuthClientConfig(_IDENTIFIER, _CLIENT_PARAMS)
+
+
+@dataclass(frozen=True)
+class _DaemonRequest:
+ path: str
+ headers: dict[str, str]
+ payload: dict[str, object]
+
+
+@dataclass
+class _Daemon:
+ gateway: PluginTriggerOAuthGateway
+ response: bytes = b""
+ requests: list[_DaemonRequest] = field(default_factory=list)
+
+ def respond(self, payload: dict[str, object]) -> None:
+ self.response = f"data: {json.dumps(payload)}\n\n".encode()
+
+
+def daemon() -> Iterator[_Daemon]:
+ daemon = _Daemon(gateway=PluginTriggerOAuthGateway(oauth=OAuthHandler()))
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self) -> None:
+ payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ daemon.requests.append(_DaemonRequest(self.path, dict(self.headers.items()), payload))
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Content-Length", str(len(daemon.response)))
+ self.end_headers()
+ self.wfile.write(daemon.response)
+
+ @override
+ def log_message(self, format: str, *args: object) -> None:
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
+ previous_url = plugin_transport.plugin_daemon_inner_api_baseurl
+ plugin_transport.plugin_daemon_inner_api_baseurl = URL(f"http://127.0.0.1:{server.server_port}")
+ thread.start()
+ try:
+ yield daemon
+ finally:
+ plugin_transport.plugin_daemon_inner_api_baseurl = previous_url
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def test_authorization_url_preserves_provider_and_client_configuration(daemon: _Daemon) -> None:
+ daemon.respond({"code": 0, "message": "", "data": {"authorization_url": "https://github.example/authorize"}})
+
+ result = daemon.gateway.authorization_url(
+ tenant_id="workspace",
+ user_id="account",
+ provider_id=_PROVIDER,
+ redirect_uri=_REDIRECT_URI,
+ client_config=_CLIENT_CONFIG,
+ )
+
+ assert result == "https://github.example/authorize"
+ assert len(daemon.requests) == 1
+ sent = daemon.requests[0]
+ assert sent.path == "/plugin/workspace/dispatch/oauth/get_authorization_url"
+ assert sent.headers["X-Plugin-ID"] == "langgenius/github"
+ assert sent.headers["X-Plugin-Unique-Identifier"] == _IDENTIFIER
+ assert sent.headers["X-Api-Key"] == dify_config.PLUGIN_DAEMON_KEY
+ assert sent.payload == {
+ "user_id": "account",
+ "data": {"provider": "github", "redirect_uri": _REDIRECT_URI, "system_credentials": _CLIENT_PARAMS},
+ }
+
+
+ ("query_string", "headers", "body"),
+ [
+ pytest.param("", {}, b"", id="trailing-query-marker"),
+ pytest.param("code=a%2Bb&state=first&state=second&empty=", {}, b"", id="raw-query"),
+ pytest.param("code=abc", {"HTTP_VERSION": "HTTP/2", "X-Custom": "value"}, b"", id="http-version"),
+ pytest.param("code=abc", {"Content-Type": "application/octet-stream"}, b"\x00\xffpayload", id="raw-body"),
+ ],
+)
+def test_exchange_preserves_legacy_raw_request_bytes(
+ daemon: _Daemon, query_string: str, headers: dict[str, str], body: bytes
+) -> None:
+ daemon.respond(
+ {"code": 0, "message": "", "data": {"credentials": {"access_token": "provider-token"}, "expires_at": 12345}}
+ )
+ with closing(
+ EnvironBuilder(method="GET", path="/callback", query_string=query_string, headers=headers.items(), data=body)
+ ) as builder:
+ request = Request(builder.get_environ())
+ expected_raw_request = OAuthHandler()._convert_request_to_raw_data(request)
+ callback = TriggerOAuthCallbackRequest(
+ method=request.method,
+ full_path=request.full_path,
+ headers=tuple(request.headers.items()),
+ body=request.get_data(),
+ )
+
+ result = daemon.gateway.exchange_credentials(
+ tenant_id="workspace",
+ user_id="account",
+ provider_id=_PROVIDER,
+ redirect_uri=_REDIRECT_URI,
+ client_config=_CLIENT_CONFIG,
+ callback=callback,
+ )
+
+ assert result.credentials == {"access_token": "provider-token"}
+ assert result.expires_at == 12345
+ assert len(daemon.requests) == 1
+ sent = daemon.requests[0]
+ assert sent.path == "/plugin/workspace/dispatch/oauth/get_credentials"
+ assert sent.headers["X-Plugin-ID"] == "langgenius/github"
+ assert sent.headers["X-Plugin-Unique-Identifier"] == _IDENTIFIER
+ assert sent.payload == {
+ "user_id": "account",
+ "data": {
+ "provider": "github",
+ "redirect_uri": _REDIRECT_URI,
+ "system_credentials": _CLIENT_PARAMS,
+ "raw_http_request": expected_raw_request.hex(),
+ },
+ }
+
+
[email protected]("identifier", [None, _IDENTIFIER], ids=["legacy-unpinned", "pinned-package"])
+def test_request_wrapper_preserves_optional_package_identifier(daemon: _Daemon, identifier: str | None) -> None:
+ daemon.respond(
+ {"code": 0, "message": "", "data": {"credentials": {"access_token": "provider-token"}, "expires_at": 12345}}
+ )
+ with closing(Request.from_values("/callback?code=abc")) as request:
+ handler = OAuthHandler()
+ raw_request = handler._convert_request_to_raw_data(request)
+ result = handler.get_credentials(
+ tenant_id="workspace",
+ user_id="account",
+ plugin_id=_PROVIDER.plugin_id,
+ provider=_PROVIDER.provider_name,
+ redirect_uri=_REDIRECT_URI,
+ system_credentials=_CLIENT_PARAMS,
+ request=request,
+ plugin_unique_identifier=identifier,
+ )
+
+ assert result.credentials == {"access_token": "provider-token"}
+ assert len(daemon.requests) == 1
+ sent = daemon.requests[0]
+ assert sent.headers.get("X-Plugin-Unique-Identifier") == identifier
+ assert sent.payload == {
+ "user_id": "account",
+ "data": {
+ "provider": "github",
+ "redirect_uri": _REDIRECT_URI,
+ "system_credentials": _CLIENT_PARAMS,
+ "raw_http_request": raw_request.hex(),
+ },
+ }
+
+
[email protected]("operation", ["authorization", "exchange"])
[email protected]("failure", ["rejected", "invalid-response", "empty-stream"])
+def test_provider_failures_become_domain_errors(daemon: _Daemon, operation: str, failure: str) -> None:
+ if failure == "rejected":
+ daemon.respond({"code": 42, "message": "OAuth provider rejected the request", "data": None})
+ elif failure == "invalid-response":
+ daemon.respond({"code": 0, "message": "", "data": {}})
+
+ if operation == "authorization":
+ with pytest.raises(TriggerOAuthProviderError) as caught:
+ daemon.gateway.authorization_url(
+ tenant_id="workspace",
+ user_id="account",
+ provider_id=_PROVIDER,
+ redirect_uri=_REDIRECT_URI,
+ client_config=_CLIENT_CONFIG,
+ )
+ else:
+ with pytest.raises(TriggerOAuthProviderError) as caught:
+ daemon.gateway.exchange_credentials(
+ tenant_id="workspace",
+ user_id="account",
+ provider_id=_PROVIDER,
+ redirect_uri=_REDIRECT_URI,
+ client_config=_CLIENT_CONFIG,
+ callback=TriggerOAuthCallbackRequest("GET", "/callback?code=abc", (), b""),
+ )
+
+ assert len(daemon.requests) == 1
+ assert isinstance(caught.value.__cause__, ValueError)
+ assert "client-secret" not in str(caught.value)
diff --git a/packages/contracts/generated/api/console/errors.gen.ts b/packages/contracts/generated/api/console/errors.gen.ts
index aa0e6a892ab..22c3caea276 100644
--- a/packages/contracts/generated/api/console/errors.gen.ts
+++ b/packages/contracts/generated/api/console/errors.gen.ts
@@ -58,6 +58,7 @@ export { get12Errors as 'GET /apps/{app_id}/agent/config/skills/{name}/files/dow
export { get12Errors as 'GET /knowledge-fs/spaces/{control_space_id}/documents/{document_id}/revisions/{revision}/chunks/{chunk_id}' } from './knowledge-fs/errors.gen.ts'
export { get12Errors as 'GET /rag/pipelines/{pipeline_id}/workflows/draft/environment-variables' } from './rag/errors.gen.ts'
export { get12Errors as 'GET /trial-apps/{app_id}/export' } from './trial-apps/errors.gen.ts'
+export { get131Errors as 'GET /workspaces/current/trigger-provider/{provider}/subscriptions/oauth/authorize' } from './workspaces/errors.gen.ts'
export { get13Errors as 'GET /agent/{agent_id}/config/skills/{name}/download' } from './agent/errors.gen.ts'
export { get13Errors as 'GET /apps/{app_id}/agent/config/skills/{name}/files/preview' } from './apps/errors.gen.ts'
export { get13Errors as 'GET /datasets/{dataset_id}/batch/{batch}/indexing-estimate' } from './datasets/errors.gen.ts'
diff --git a/packages/contracts/generated/api/console/workspaces/errors.gen.ts b/packages/contracts/generated/api/console/workspaces/errors.gen.ts
index b94e045d728..fd15779c0dd 100644
--- a/packages/contracts/generated/api/console/workspaces/errors.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/errors.gen.ts
@@ -274,6 +274,14 @@ const zTriggerOauthClientChangedError = /* @__PURE__ */ (() =>
}),
))()
+const zTriggerOauthProviderError = /* @__PURE__ */ (() =>
+ zErrorResponse.and(
+ z.object({
+ code: z.literal('trigger_oauth_provider_error'),
+ status: z.literal(502),
+ }),
+ ))()
+
const zFilenameNotExistsError = /* @__PURE__ */ (() =>
zErrorResponse.and(
z.object({
@@ -517,6 +525,11 @@ export const post84Errors = {
trigger_oauth_client_config_invalid: { status: 500, data: zTriggerOauthClientConfigInvalidError },
}
+export const get131Errors = {
+ trigger_oauth_client_config_invalid: { status: 500, data: zTriggerOauthClientConfigInvalidError },
+ trigger_oauth_provider_error: { status: 502, data: zTriggerOauthProviderError },
+}
+
export const post92Errors = {
file_too_large: { status: 413, data: zFileTooLargeError },
filename_not_exists_error: { status: 400, data: zFilenameNotExistsError },
diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
index ed1a7c36c15..ac3ae3e9925 100644
--- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts
@@ -40,6 +40,7 @@ import {
zTooManyFilesError,
zTriggerOauthClientChangedError,
zTriggerOauthClientConfigInvalidError,
+ zTriggerOauthProviderError,
zUnsupportedFileTypeError,
} from './zod.gen.ts'
import {
@@ -6035,6 +6036,13 @@ export const get131 = oc
}),
)
.output(zGetWorkspacesCurrentTriggerProviderByProviderSubscriptionsOauthAuthorizeResponse)
+ .errors({
+ trigger_oauth_client_config_invalid: {
+ status: 500,
+ data: zTriggerOauthClientConfigInvalidError,
+ },
+ trigger_oauth_provider_error: { status: 502, data: zTriggerOauthProviderError },
+ })
export const authorize = {
get: get131,
diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.ts
index a110b9a6b29..7f499a865dc 100644
--- a/packages/contracts/generated/api/console/workspaces/types.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts
@@ -1665,6 +1665,11 @@ export type TriggerOAuthAuthorizeResponse = {
subscription_builder_id: string
}
+export type TriggerOauthProviderError = ErrorResponse & {
+ code: 'trigger_oauth_provider_error'
+ status: 502
+}
+
export type TriggerSubscriptionVerifyPayload = {
credentials: {
[key: string]: unknown
@@ -10721,6 +10726,8 @@ export type GetWorkspacesCurrentTriggerProviderByProviderSubscriptionsOauthAutho
}
export type GetWorkspacesCurrentTriggerProviderByProviderSubscriptionsOauthAuthorizeErrors = {
+ 500: TriggerOauthClientConfigInvalidError | ErrorResponse
+ 502: TriggerOauthProviderError | ErrorResponse
default: ErrorResponse
}
diff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
index 83520111d69..f640dce667b 100644
--- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
@@ -1321,6 +1321,18 @@ export const zTriggerProviderErrorResponse = z.object({
error: z.string(),
})
+/**
+ * TriggerOauthProviderError
+ *
+ * The trigger provider could not complete OAuth authorization.
+ */
+export const zTriggerOauthProviderError = zErrorResponse.and(
+ z.object({
+ code: z.literal('trigger_oauth_provider_error'),
+ status: z.literal(502),
+ }),
+)
+
/**
* TriggerSubscriptionVerifyPayload
*/