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 installed app admission for saved messages and parameters (#41872)

非法操作75ba8d1dc49b
diff --git a/api/.importlinter b/api/.importlinter
index 6d693295d6a..9a4eaaf0994 100644
--- a/api/.importlinter
+++ b/api/.importlinter
@@ -199,6 +199,20 @@ forbidden_modules =
sqlalchemy
werkzeug
+[importlinter:contract:installed-app-access-boundary]
+name = Installed app access application service is framework and persistence neutral
+type = forbidden
+source_modules =
+ services.installed_app_access_service
+forbidden_modules =
+ controllers
+ extensions
+ flask
+ models
+ repositories
+ sqlalchemy
+ werkzeug
+
[importlinter:contract:account-application-boundary]
name = Account application services and contracts are framework and persistence neutral
type = forbidden
diff --git a/api/controllers/console/explore/installed_app_admission.py b/api/controllers/console/explore/installed_app_admission.py
new file mode 100644
index 00000000000..f0f70193045
--- /dev/null
+++ b/api/controllers/console/explore/installed_app_admission.py
@@ -0,0 +1,45 @@
+"""Installed-app admission for handlers using a pure installation reference."""
+
+from collections.abc import Callable
+from functools import wraps
+from typing import Concatenate
+
+from werkzeug.exceptions import NotFound
+
+from controllers.console.explore.error import AppAccessDeniedError
+from controllers.web.error import WebAppAccessServiceUnavailableError
+from extensions.ext_application_services import application_services
+from machinery.context import RequestContext
+from services.installed_app_access_service import (
+ InstalledAppAccessDeniedError,
+ InstalledAppNotFoundError,
+ InstalledAppRef,
+)
+from services.webapp_access_query_service import WebAppAccessUnavailableError
+
+
+def get_installed_app[T, **P, R](
+ view: Callable[Concatenate[T, RequestContext, InstalledAppRef, P], R],
+) -> Callable[Concatenate[T, RequestContext, P], R]:
+ """Resolve the route's installation after Console account admission."""
+
+ @wraps(view)
+ def decorated(self: T, request_context: RequestContext, /, *args: P.args, **kwargs: P.kwargs) -> R:
+ installed_app_id = kwargs.pop("installed_app_id", None)
+ if installed_app_id is None:
+ raise ValueError("installed_app_id is required")
+ try:
+ installed_app = application_services().installed_app_access.get_access(
+ installed_app_id=str(installed_app_id),
+ tenant_id=request_context.active_workspace_id,
+ account_id=request_context.account_id,
+ )
+ except InstalledAppNotFoundError:
+ raise NotFound("Installed app not found") from None
+ except InstalledAppAccessDeniedError:
+ raise AppAccessDeniedError() from None
+ except WebAppAccessUnavailableError:
+ raise WebAppAccessServiceUnavailableError() from None
+ return view(self, request_context, installed_app, *args, **kwargs)
+
+ return decorated
diff --git a/api/controllers/console/explore/parameter.py b/api/controllers/console/explore/parameter.py
index bbd0bf54f7a..5b1e5e00917 100644
--- a/api/controllers/console/explore/parameter.py
+++ b/api/controllers/console/explore/parameter.py
@@ -1,16 +1,19 @@
from typing import Any
+from flask_restx import Resource
from pydantic import BaseModel, Field
from controllers.common.fields import Parameters
from controllers.common.schema import register_response_schema_models
from controllers.console import console_ns
from controllers.console.app.error import AppUnavailableError
-from controllers.console.explore.wraps import InstalledAppResource
+from controllers.console.explore.installed_app_admission import get_installed_app
+from controllers.console.flask_admission import console_account_admission
from extensions.ext_application_services import application_services
from libs.helper import dump_response
-from models.model import InstalledApp
+from machinery.context import RequestContext
from services.app_definition_query_service import AppDefinitionUnavailableError
+from services.installed_app_access_service import InstalledAppRef
class ExploreAppMetaResponse(BaseModel):
@@ -26,11 +29,13 @@ register_response_schema_models(console_ns, Parameters, ExploreAppMetaResponse)
@console_ns.route("/installed-apps/<uuid:installed_app_id>/parameters", endpoint="installed_app_parameters")
-class AppParameterApi(InstalledAppResource):
+class AppParameterApi(Resource):
"""Resource for app variables."""
@console_ns.response(200, "Success", console_ns.models[Parameters.__name__])
- def get(self, installed_app: InstalledApp):
+ @console_account_admission()
+ @get_installed_app
+ def get(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
"""Retrieve app parameters."""
try:
parameters = application_services().app_definitions.get_parameters(installed_app.app_id)
@@ -41,9 +46,11 @@ class AppParameterApi(InstalledAppResource):
@console_ns.route("/installed-apps/<uuid:installed_app_id>/meta", endpoint="installed_app_meta")
-class ExploreAppMetaApi(InstalledAppResource):
+class ExploreAppMetaApi(Resource):
@console_ns.response(200, "Success", console_ns.models[ExploreAppMetaResponse.__name__])
- def get(self, installed_app: InstalledApp):
+ @console_account_admission()
+ @get_installed_app
+ def get(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
"""Get app meta"""
try:
tool_icons = application_services().app_definitions.get_tool_icons(installed_app.app_id)
diff --git a/api/controllers/console/explore/saved_message.py b/api/controllers/console/explore/saved_message.py
index 07b40a20e80..fe6ab013a02 100644
--- a/api/controllers/console/explore/saved_message.py
+++ b/api/controllers/console/explore/saved_message.py
@@ -1,5 +1,6 @@
from uuid import UUID
+from flask_restx import Resource
from werkzeug.exceptions import NotFound
from controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery
@@ -7,22 +8,24 @@ from controllers.common.schema import query_params_from_model, register_response
from controllers.console import console_ns
from controllers.console.app.error import AppUnavailableError
from controllers.console.explore.error import NotCompletionAppError
-from controllers.console.explore.wraps import InstalledAppResource
-from controllers.console.wraps import model_validate, with_current_user_id
+from controllers.console.explore.installed_app_admission import get_installed_app
+from controllers.console.flask_admission import console_account_admission
+from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.conversation_fields import ResultResponse
from fields.message_fields import SavedMessageInfiniteScrollPagination
from libs.helper import dump_response
-from models.model import InstalledApp
+from machinery.context import RequestContext
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.errors.message import MessageNotExistsError
+from services.installed_app_access_service import InstalledAppRef
from services.saved_message_service import SavedMessageActor
register_schema_models(console_ns, SavedMessageListQuery, SavedMessageCreatePayload)
register_response_schema_models(console_ns, ResultResponse, SavedMessageInfiniteScrollPagination)
-def _require_completion_app(installed_app: InstalledApp) -> str:
+def _require_completion_app(installed_app: InstalledAppRef) -> str:
app_id = installed_app.app_id
try:
mode = application_services().app_definitions.get_mode(app_id)
@@ -35,21 +38,22 @@ def _require_completion_app(installed_app: InstalledApp) -> str:
@console_ns.route("/installed-apps/<uuid:installed_app_id>/saved-messages", endpoint="installed_app_saved_messages")
-class SavedMessageListApi(InstalledAppResource):
+class SavedMessageListApi(Resource):
@console_ns.doc(params=query_params_from_model(SavedMessageListQuery))
@console_ns.response(200, "Success", console_ns.models[SavedMessageInfiniteScrollPagination.__name__])
- @with_current_user_id
+ @console_account_admission()
+ @get_installed_app
@model_validate(SavedMessageListQuery)
def get(
self,
req_data: SavedMessageListQuery,
- current_user_id: str,
- installed_app: InstalledApp,
+ request_context: RequestContext,
+ installed_app: InstalledAppRef,
) -> dict[str, object]:
app_id = _require_completion_app(installed_app)
pagination = application_services().saved_messages.pagination_by_last_id(
app_id=app_id,
- actor=SavedMessageActor.account(current_user_id),
+ actor=SavedMessageActor.account(request_context.account_id),
last_id=str(req_data.last_id) if req_data.last_id else None,
limit=req_data.limit,
)
@@ -57,20 +61,21 @@ class SavedMessageListApi(InstalledAppResource):
@console_ns.expect(console_ns.models[SavedMessageCreatePayload.__name__])
@console_ns.response(200, "Success", console_ns.models[ResultResponse.__name__])
- @with_current_user_id
+ @console_account_admission()
+ @get_installed_app
@model_validate(SavedMessageCreatePayload)
def post(
self,
req_data: SavedMessageCreatePayload,
- current_user_id: str,
- installed_app: InstalledApp,
+ request_context: RequestContext,
+ installed_app: InstalledAppRef,
) -> dict[str, object]:
app_id = _require_completion_app(installed_app)
try:
application_services().saved_messages.save(
app_id=app_id,
- actor=SavedMessageActor.account(current_user_id),
+ actor=SavedMessageActor.account(request_context.account_id),
message_id=str(req_data.message_id),
)
except MessageNotExistsError:
@@ -82,19 +87,20 @@ class SavedMessageListApi(InstalledAppResource):
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/saved-messages/<uuid:message_id>", endpoint="installed_app_saved_message"
)
-class SavedMessageApi(InstalledAppResource):
+class SavedMessageApi(Resource):
@console_ns.response(204, "Saved message deleted successfully")
- @with_current_user_id
+ @console_account_admission()
+ @get_installed_app
def delete(
self,
- current_user_id: str,
- installed_app: InstalledApp,
+ request_context: RequestContext,
+ installed_app: InstalledAppRef,
message_id: UUID,
) -> tuple[str, int]:
app_id = _require_completion_app(installed_app)
application_services().saved_messages.delete(
app_id=app_id,
- actor=SavedMessageActor.account(current_user_id),
+ actor=SavedMessageActor.account(request_context.account_id),
message_id=str(message_id),
)
diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py
index 095e8b3c761..168ad732d0c 100644
--- a/api/extensions/ext_application_services.py
+++ b/api/extensions/ext_application_services.py
@@ -53,6 +53,7 @@ from repositories.factory import DifyAPIRepositoryFactory
from repositories.file_grant_repository import FileGrantRepository
from repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepository
from repositories.installation_state_repository import InstallationStateRepository
+from repositories.installed_app_access_repository import SQLAlchemyInstalledAppAccessRepository
from repositories.message_file_preview_repository import MessageFilePreviewQueryRepository
from repositories.oauth_access_token_repository import SQLAlchemyOAuthAccessTokenRepository
from repositories.oauth_server_repository import RedisOAuthServerTokenRepository, SQLAlchemyOAuthServerRepository
@@ -175,6 +176,7 @@ from services.file_service import FileService
from services.human_input_file_upload_service import HumanInputFileUploadService
from services.init_validation_service import InitValidationService
from services.inner_mail_service import InnerMailService
+from services.installed_app_access_service import InstalledAppAccessService
from services.message_file_preview_service import MessageFilePreviewService
from services.message_suggested_questions_adapters import MessageSuggestedQuestionsRuntime
from services.message_suggested_questions_service import MessageSuggestedQuestions
@@ -308,6 +310,7 @@ class ApplicationServices:
upload_file_delivery: UploadFileDeliveryService
oauth_server: OAuthServerService
init_validation: InitValidationService
+ installed_app_access: InstalledAppAccessService
notifications: NotificationService
step_by_step_tour: StepByStepTourService
partner_tenant_bindings: PartnerTenantBindingService
@@ -460,6 +463,12 @@ def build_application_services(
installation_state = InstallationStateRepository(session_factory=database_client)
data_source_api_key_auth_bindings = SQLAlchemyDataSourceApiKeyAuthBindingRepository(session_factory=database_client)
app_definition_repository = AppDefinitionQueryRepository(session_factory=database_client)
+ webapp_access = WebAppAccessQueryService(
+ access=WebAppAccessQueryRepository(session_factory=database_client),
+ webapp_auth_enabled=SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition),
+ access_mode_for_app=_get_enterprise_webapp_access_mode,
+ is_user_allowed_for_app=_is_user_allowed_to_access_webapp,
+ )
app_preview_repository = AppPreviewQueryRepository(session_factory=database_client)
feature_gateway = FeatureServiceGateway()
accounts = SQLAlchemyAccountRepository(session_factory=database_client)
@@ -691,11 +700,10 @@ def build_application_services(
commands=AppScopedEndUserService(end_users=app_scoped_end_user_repository),
queries=AppScopedEndUserQueryService(end_users=app_scoped_end_user_repository),
),
- webapp_access=WebAppAccessQueryService(
- access=WebAppAccessQueryRepository(session_factory=database_client),
- webapp_auth_enabled=SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition),
- access_mode_for_app=_get_enterprise_webapp_access_mode,
- is_user_allowed_for_app=_is_user_allowed_to_access_webapp,
+ webapp_access=webapp_access,
+ installed_app_access=InstalledAppAccessService(
+ installed_apps=SQLAlchemyInstalledAppAccessRepository(session_factory=database_client),
+ is_user_allowed=webapp_access.is_user_allowed,
),
web_app_runtime=WebAppRuntimeQueryService(
runtime=app_definition_repository,
diff --git a/api/repositories/installed_app_access_repository.py b/api/repositories/installed_app_access_repository.py
new file mode 100644
index 00000000000..61dd6a65453
--- /dev/null
+++ b/api/repositories/installed_app_access_repository.py
@@ -0,0 +1,35 @@
+"""Resolve workspace installations before external access checks."""
+
+from typing import override
+
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+
+from models.model import App, InstalledApp
+from services.installed_app_access_service import InstalledAppAccessStore, InstalledAppRef
+
+
+class SQLAlchemyInstalledAppAccessRepository(InstalledAppAccessStore):
+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:
+ self._session_factory = session_factory
+
+ @override
+ def resolve(self, *, installed_app_id: str, tenant_id: str) -> InstalledAppRef | None:
+ with self._session_factory() as session:
+ installed_app = session.scalar(
+ select(InstalledApp)
+ .where(InstalledApp.id == installed_app_id, InstalledApp.tenant_id == tenant_id)
+ .limit(1)
+ )
+ if installed_app is None:
+ return None
+
+ # An installed public app can belong to another workspace. Admission
+ # preserves the existence check; publication policy belongs to its callers.
+ app_id = session.scalar(select(App.id).where(App.id == installed_app.app_id).limit(1))
+ if app_id is None:
+ session.delete(installed_app)
+ session.commit()
+ return None
+
+ return InstalledAppRef(id=installed_app.id, app_id=app_id, tenant_id=installed_app.tenant_id)
diff --git a/api/services/installed_app_access_service.py b/api/services/installed_app_access_service.py
new file mode 100644
index 00000000000..19c43d8e6c7
--- /dev/null
+++ b/api/services/installed_app_access_service.py
@@ -0,0 +1,46 @@
+"""Application admission for an app installed in a workspace."""
+
+from dataclasses import dataclass
+from typing import Protocol
+
+
+@dataclass(frozen=True, slots=True)
+class InstalledAppRef:
+ id: str
+ app_id: str
+ tenant_id: str
+
+
+class InstalledAppAccessStore(Protocol):
+ def resolve(self, *, installed_app_id: str, tenant_id: str) -> InstalledAppRef | None: ...
+
+
+class WebAppUserAccessCheck(Protocol):
+ def __call__(self, *, user_id: str, app_id: str) -> bool: ...
+
+
+class InstalledAppNotFoundError(LookupError):
+ """The workspace installation or its target app no longer exists."""
+
+
+class InstalledAppAccessDeniedError(PermissionError):
+ """The current account cannot access the installed app."""
+
+
+class InstalledAppAccessService:
+ def __init__(
+ self,
+ *,
+ installed_apps: InstalledAppAccessStore,
+ is_user_allowed: WebAppUserAccessCheck,
+ ) -> None:
+ self._installed_apps = installed_apps
+ self._is_user_allowed = is_user_allowed
+
+ def get_access(self, *, installed_app_id: str, tenant_id: str, account_id: str) -> InstalledAppRef:
+ installed_app = self._installed_apps.resolve(installed_app_id=installed_app_id, tenant_id=tenant_id)
+ if installed_app is None:
+ raise InstalledAppNotFoundError("Installed app not found")
+ if not self._is_user_allowed(user_id=account_id, app_id=installed_app.app_id):
+ raise InstalledAppAccessDeniedError("Access to installed app denied")
+ return installed_app
diff --git a/api/tests/unit_tests/controllers/console/explore/test_installed_app_admission.py b/api/tests/unit_tests/controllers/console/explore/test_installed_app_admission.py
new file mode 100644
index 00000000000..333c06a40f0
--- /dev/null
+++ b/api/tests/unit_tests/controllers/console/explore/test_installed_app_admission.py
@@ -0,0 +1,497 @@
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from operator import itemgetter
+from uuid import UUID, uuid4
+
+import pytest
+from flask import Flask, Request
+from flask_restx import Resource
+from sqlalchemy import Connection, event, inspect
+from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
+from werkzeug.exceptions import Unauthorized
+from werkzeug.test import TestResponse
+
+import controllers.console.explore.installed_app_admission as admission_module
+import controllers.console.explore.parameter as parameter_module
+import controllers.console.explore.saved_message as saved_message_module
+import controllers.console.flask_admission as console_admission
+import controllers.console.wraps as console_wraps
+import libs.login as login_module
+from controllers.console.explore.installed_app_admission import get_installed_app
+from controllers.console.flask_admission import console_account_admission
+from enums import DeploymentEdition
+from extensions.ext_login import DifyLoginManager, unauthorized_handler
+from libs.external_api import ExternalApi
+from machinery.context import RequestContext
+from models import Account, App, AppMode, InstalledApp, Tenant
+from models.account import AccountStatus
+from repositories.installed_app_access_repository import SQLAlchemyInstalledAppAccessRepository
+from services.installed_app_access_service import InstalledAppAccessService, InstalledAppRef
+from services.saved_message_service import SavedMessageActor, SavedMessagePage, SavedMessageRecord, SavedMessageService
+from services.webapp_access_query_service import WebAppAccessUnavailableError
+
+
+@dataclass
+class _AdmissionState:
+ setup_completed: bool = True
+ allowed: bool = True
+ permission_error: Exception | None = None
+ events: list[str] = field(default_factory=list)
+ permission_calls: list[tuple[str, str]] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class _ApplicationServices:
+ installed_app_access: InstalledAppAccessService
+
+
+@dataclass(frozen=True)
+class _Harness:
+ app: Flask
+ api: ExternalApi
+ account: Account
+ installed_app: InstalledApp
+ target_app: App
+ state: _AdmissionState
+
+ def url(self, *, installed_app_id: str | None = None) -> str:
+ return f"/reference/{installed_app_id or self.installed_app.id}/11111111-1111-4111-8111-111111111111"
+
+
+def harness(
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ sqlite_session_factory: sessionmaker[Session],
+) -> _Harness:
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, INIT_PASSWORD="", LOGIN_DISABLED=False)
+ state = _AdmissionState()
+ account = Account(name="Viewer", email="[email protected]")
+ viewer_tenant = Tenant(name="Viewer workspace")
+ account._current_tenant = viewer_tenant
+ target_app = App(
+ tenant_id=str(uuid4()),
+ name="Shared app",
+ mode=AppMode.COMPLETION,
+ enable_site=True,
+ enable_api=True,
+ )
+ target_app.id = str(uuid4())
+ installed_app = InstalledApp(
+ tenant_id=viewer_tenant.id,
+ app_id=target_app.id,
+ app_owner_tenant_id=target_app.tenant_id,
+ position=0,
+ is_pinned=False,
+ last_used_at=None,
+ )
+ with sqlite_session_factory() as session:
+ session.add_all([target_app, installed_app])
+ session.commit()
+
+ # Each real repository session must release its connection before enterprise
+ # access is consulted.
+ repository_sessions: list[Session] = []
+
+ repository_factory = sessionmaker(
+ bind=sqlite_session_factory.kw["bind"],
+ expire_on_commit=False,
+ )
+
+ @event.listens_for(repository_factory, "after_begin")
+ def track_repository_session(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
+ repository_sessions.append(session)
+
+ def permission_check(*, user_id: str, app_id: str) -> bool:
+ state.events.append("permission")
+ state.permission_calls.append((user_id, app_id))
+ assert repository_sessions
+ assert all(not session.in_transaction() and not session.identity_map for session in repository_sessions)
+ if state.permission_error is not None:
+ raise state.permission_error
+ return state.allowed
+
+ services = _ApplicationServices(
+ installed_app_access=InstalledAppAccessService(
+ installed_apps=SQLAlchemyInstalledAppAccessRepository(session_factory=repository_factory),
+ is_user_allowed=permission_check,
+ )
+ )
+
+ def setup_completed() -> bool:
+ state.events.append("setup")
+ return state.setup_completed
+
+ def check_csrf(_request: Request, user_id: str) -> None:
+ assert user_id == account.id
+ state.events.append("csrf")
+
+ monkeypatch.setattr(admission_module, "application_services", lambda: services)
+ monkeypatch.setattr(login_module, "current_user", account)
+ monkeypatch.setattr(login_module, "check_csrf_token", check_csrf)
+ monkeypatch.setattr(console_wraps, "_is_setup_completed", setup_completed)
+ monkeypatch.setattr(console_admission, "get_request_id", lambda: "request-1")
+ monkeypatch.setattr(console_admission, "get_trace_id", lambda: None)
+
+ app = Flask(__name__)
+ app.config.update(TESTING=True, RESTX_ERROR_404_HELP=False)
+ login_manager = DifyLoginManager()
+ login_manager.init_app(app)
+ login_manager.unauthorized_handler(unauthorized_handler)
+ api = ExternalApi(app)
+
+ class ReferenceApi(Resource):
+ @console_account_admission()
+ @get_installed_app
+ def get(
+ self,
+ request_context: RequestContext,
+ reference: InstalledAppRef,
+ message_id: UUID,
+ ) -> tuple[dict[str, object], int, dict[str, str]]:
+ state.events.append("handler")
+ assert isinstance(reference, InstalledAppRef)
+ assert inspect(reference, raiseerr=False) is None
+ return (
+ {
+ "id": reference.id,
+ "app_id": reference.app_id,
+ "tenant_id": reference.tenant_id,
+ "account_id": request_context.account_id,
+ "workspace_id": request_context.active_workspace_id,
+ "request_id": request_context.request_id,
+ "trace_id": request_context.trace_id,
+ "message_id": str(message_id),
+ },
+ 202,
+ {"X-Installed-App": "accepted"},
+ )
+
+ api.add_resource(ReferenceApi, "/reference/<uuid:installed_app_id>/<uuid:message_id>")
+ return _Harness(app, api, account, installed_app, target_app, state)
+
+
+def _assert_json_response(response: TestResponse, *, status: int, body: dict[str, object]) -> None:
+ assert response.status_code == status
+ assert response.get_json() == body
+ assert response.headers["Content-Type"] == "application/json"
+ assert int(response.headers["Content-Length"]) == len(response.data)
+
+
+def test_admission_injects_detached_reference_and_preserves_other_route_arguments(harness: _Harness) -> None:
+ response = harness.app.test_client().get(harness.url(), headers={"X-Trace-Id": "trace-1"})
+
+ _assert_json_response(
+ response,
+ status=202,
+ body={
+ "id": harness.installed_app.id,
+ "app_id": harness.target_app.id,
+ "tenant_id": harness.installed_app.tenant_id,
+ "account_id": harness.account.id,
+ "workspace_id": harness.installed_app.tenant_id,
+ "request_id": "request-1",
+ "trace_id": "trace-1",
+ "message_id": "11111111-1111-4111-8111-111111111111",
+ },
+ )
+ assert response.headers["X-Installed-App"] == "accepted"
+ assert harness.installed_app.tenant_id != harness.target_app.tenant_id
+ assert harness.state.permission_calls == [(harness.account.id, harness.target_app.id)]
+ assert harness.state.events == ["setup", "csrf", "permission", "handler"]
+
+
[email protected]("missing", ["installation", "tenant", "target_app"])
+def test_missing_or_foreign_installation_returns_404_before_permission(
+ harness: _Harness,
+ sqlite_session_factory: sessionmaker[Session],
+ missing: str,
+) -> None:
+ installed_app_id = harness.installed_app.id
+ if missing == "installation":
+ installed_app_id = str(uuid4())
+ elif missing == "tenant":
+ harness.account._current_tenant = Tenant(name="Other workspace")
+ else:
+ with sqlite_session_factory() as session:
+ target_app = session.get(App, harness.target_app.id)
+ assert target_app is not None
+ session.delete(target_app)
+ session.commit()
+
+ response = harness.app.test_client().get(harness.url(installed_app_id=installed_app_id))
+
+ _assert_json_response(
+ response,
+ status=404,
+ body={"code": "not_found", "message": "Installed app not found", "status": 404},
+ )
+ assert harness.state.permission_calls == []
+ assert harness.state.events == ["setup", "csrf"]
+ with sqlite_session_factory() as session:
+ remaining = session.get(InstalledApp, harness.installed_app.id)
+ assert (remaining is None) == (missing == "target_app")
+
+
+def test_access_denied_preserves_error_body_and_never_calls_handler(harness: _Harness) -> None:
+ harness.state.allowed = False
+
+ response = harness.app.test_client().get(harness.url())
+
+ _assert_json_response(
+ response,
+ status=403,
+ body={"code": "access_denied", "message": "App access denied.", "status": 403},
+ )
+ assert harness.state.events == ["setup", "csrf", "permission"]
+
+
+ ("phase", "status", "body", "events"),
+ [
+ (
+ "setup",
+ 401,
+ {
+ "code": "not_setup",
+ "message": "Dify has not been initialized and installed yet. "
+ "Please proceed with the initialization and installation process first.",
+ "status": 401,
+ },
+ ["setup"],
+ ),
+ ("login", 401, {"code": "unauthorized", "message": "Unauthorized."}, ["setup"]),
+ (
+ "initialization",
+ 400,
+ {
+ "code": "account_not_initialized",
+ "message": "The account has not been initialized yet. "
+ "Please proceed with the initialization process first.",
+ "status": 400,
+ },
+ ["setup", "csrf"],
+ ),
+ ],
+)
+def test_account_admission_precedes_installed_app_lookup(
+ harness: _Harness,
+ monkeypatch: pytest.MonkeyPatch,
+ phase: str,
+ status: int,
+ body: dict[str, object],
+ events: list[str],
+) -> None:
+ harness.account.status = AccountStatus.UNINITIALIZED
+ if phase in {"setup", "login"}:
+ monkeypatch.setattr(login_module, "current_user", None)
+ if phase == "setup":
+ harness.state.setup_completed = False
+
+ response = harness.app.test_client().get(harness.url(installed_app_id=str(uuid4())))
+
+ _assert_json_response(response, status=status, body=body)
+ assert harness.state.events == events
+ assert harness.state.permission_calls == []
+ if phase == "setup":
+ assert response.headers["WWW-Authenticate"] == 'Bearer realm="api"'
+
+
+def test_permission_dependency_unavailable_returns_503_without_calling_handler(harness: _Harness) -> None:
+ harness.state.permission_error = WebAppAccessUnavailableError()
+
+ response = harness.app.test_client().get(harness.url())
+
+ _assert_json_response(
+ response,
+ status=503,
+ body={
+ "code": "web_app_access_unavailable",
+ "message": "Web app access service is unavailable.",
+ "status": 503,
+ },
+ )
+ assert harness.state.events == ["setup", "csrf", "permission"]
+ assert harness.state.permission_calls == [(harness.account.id, harness.target_app.id)]
+
+
+def test_permission_dependency_http_error_is_not_replaced_by_access_denied(harness: _Harness) -> None:
+ error = Unauthorized("Enterprise session expired.")
+ harness.state.permission_error = error
+
+ response = harness.app.test_client().get(harness.url())
+
+ _assert_json_response(
+ response,
+ status=401,
+ body={"code": "unauthorized", "message": "Enterprise session expired.", "status": 401},
+ )
+ assert response.headers["WWW-Authenticate"] == 'Bearer realm="api"'
+ assert harness.state.events == ["setup", "csrf", "permission"]
+
+
+def test_csrf_rejection_precedes_account_initialization_and_installation_lookup(
+ harness: _Harness,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def reject_csrf(_request: Request, _user_id: str) -> None:
+ harness.state.events.append("csrf")
+ raise Unauthorized("CSRF token is missing.")
+
+ harness.account.status = AccountStatus.UNINITIALIZED
+ monkeypatch.setattr(login_module, "check_csrf_token", reject_csrf)
+
+ response = harness.app.test_client().get(harness.url(installed_app_id=str(uuid4())))
+
+ _assert_json_response(
+ response,
+ status=401,
+ body={"code": "unauthorized", "message": "CSRF token is missing.", "status": 401},
+ )
+ assert response.headers["WWW-Authenticate"] == 'Bearer realm="api"'
+ assert harness.state.events == ["setup", "csrf"]
+ assert harness.state.permission_calls == []
+
+
+@dataclass
+class _SavedMessageStore:
+ messages: set[tuple[str, SavedMessageActor, str]] = field(default_factory=set)
+
+ def pagination_by_last_id(
+ self, *, app_id: str, actor: SavedMessageActor, last_id: str | None, limit: int
+ ) -> SavedMessagePage:
+ assert last_id is None
+ return SavedMessagePage(
+ limit=limit,
+ has_more=False,
+ data=tuple(
+ SavedMessageRecord(
+ id=message_id,
+ inputs={"count": 0},
+ query="question",
+ answer="answer",
+ message_files=[],
+ user_feedback=None,
+ created_at=None,
+ )
+ for owner_app, owner_actor, message_id in sorted(self.messages, key=itemgetter(2))
+ if (owner_app, owner_actor) == (app_id, actor)
+ ),
+ )
+
+ def save(self, *, app_id: str, actor: SavedMessageActor, message_id: str) -> None:
+ self.messages.add((app_id, actor, message_id))
+
+ def delete(self, *, app_id: str, actor: SavedMessageActor, message_id: str) -> None:
+ self.messages.discard((app_id, actor, message_id))
+
+
+@dataclass(frozen=True)
+class _AppDefinitions:
+ app_id: str
+ parameters: dict[str, object]
+
+ def get_mode(self, app_id: str) -> str:
+ assert app_id == self.app_id
+ return "completion"
+
+ def get_parameters(self, app_id: str) -> dict[str, object]:
+ assert app_id == self.app_id
+ return self.parameters
+
+ def get_tool_icons(self, app_id: str) -> dict[str, str]:
+ assert app_id == self.app_id
+ return {"search": "/tools/search/icon"}
+
+
+@dataclass(frozen=True)
+class _HandlerServices:
+ saved_messages: SavedMessageService
+ app_definitions: _AppDefinitions
+
+
+def test_migrated_saved_message_and_parameter_handlers_dispatch_through_full_admission(
+ harness: _Harness,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ parameters: dict[str, object] = {
+ "opening_statement": "Welcome",
+ "suggested_questions": [],
+ "user_input_form": [],
+ "system_parameters": {
+ "image_file_size_limit": 10,
+ "video_file_size_limit": 100,
+ "audio_file_size_limit": 50,
+ "file_size_limit": 15,
+ "workflow_file_upload_limit": 10,
+ },
+ }
+ parameters.update(
+ {
+ feature: {"enabled": False}
+ for feature in (
+ "suggested_questions_after_answer",
+ "speech_to_text",
+ "text_to_speech",
+ "retriever_resource",
+ "annotation_reply",
+ "more_like_this",
+ "sensitive_word_avoidance",
+ "file_upload",
+ )
+ }
+ )
+ store = _SavedMessageStore()
+ handler_services = _HandlerServices(
+ saved_messages=SavedMessageService(saved_messages=store),
+ app_definitions=_AppDefinitions(app_id=harness.target_app.id, parameters=parameters),
+ )
+ monkeypatch.setattr(saved_message_module, "application_services", lambda: handler_services)
+ monkeypatch.setattr(parameter_module, "application_services", lambda: handler_services)
+ harness.api.add_resource(saved_message_module.SavedMessageListApi, "/saved/<uuid:installed_app_id>")
+ harness.api.add_resource(saved_message_module.SavedMessageApi, "/saved/<uuid:installed_app_id>/<uuid:message_id>")
+ harness.api.add_resource(parameter_module.AppParameterApi, "/parameters/<uuid:installed_app_id>")
+ harness.api.add_resource(parameter_module.ExploreAppMetaApi, "/meta/<uuid:installed_app_id>")
+ client = harness.app.test_client()
+ message_id = str(uuid4())
+ saved_url = f"/saved/{harness.installed_app.id}"
+
+ created = client.post(saved_url, json={"message_id": message_id})
+ _assert_json_response(created, status=200, body={"result": "success"})
+ assert store.messages == {(harness.target_app.id, SavedMessageActor.account(harness.account.id), message_id)}
+ listed = client.get(saved_url, query_string={"limit": 7})
+ _assert_json_response(
+ listed,
+ status=200,
+ body={
+ "limit": 7,
+ "has_more": False,
+ "data": [
+ {
+ "id": message_id,
+ "inputs": {"count": 0},
+ "query": "question",
+ "answer": "answer",
+ "message_files": [],
+ "feedback": None,
+ "created_at": None,
+ }
+ ],
+ },
+ )
+ deleted = client.delete(f"{saved_url}/{message_id}")
+ assert deleted.status_code == 204
+ assert deleted.data == b""
+ assert deleted.headers["Content-Type"] == "application/json"
+ assert store.messages == set()
+ _assert_json_response(
+ client.get(f"/parameters/{harness.installed_app.id}"),
+ status=200,
+ body=parameters,
+ )
+ _assert_json_response(
+ client.get(f"/meta/{harness.installed_app.id}"),
+ status=200,
+ body={"tool_icons": {"search": "/tools/search/icon"}},
+ )
+ assert harness.state.permission_calls == [(harness.account.id, harness.target_app.id)] * 5
diff --git a/api/tests/unit_tests/controllers/console/explore/test_parameter.py b/api/tests/unit_tests/controllers/console/explore/test_parameter.py
index a41a3805cc5..24eaf51e185 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_parameter.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_parameter.py
@@ -6,19 +6,17 @@ import pytest
import controllers.console.explore.parameter as module
from controllers.console.app.error import AppUnavailableError
-from models.model import InstalledApp
+from machinery.context import RequestContext
from services.app_definition_query_service import AppDefinitionQueryService, AppDefinitionUnavailableError
+from services.installed_app_access_service import InstalledAppRef
+_REQUEST_CONTEXT = RequestContext(
+ request_id="test-request", trace_id=None, account_id="account-1", active_workspace_id="viewer-tenant"
+)
-def _installed_app() -> InstalledApp:
- return InstalledApp(
- tenant_id="viewer-tenant",
- app_id="app-1",
- app_owner_tenant_id="owner-tenant",
- position=0,
- is_pinned=False,
- last_used_at=None,
- )
+
+def _installed_app() -> InstalledAppRef:
+ return InstalledAppRef(id="installed-1", tenant_id="viewer-tenant", app_id="app-1")
def _application_services() -> tuple[SimpleNamespace, MagicMock]:
@@ -36,7 +34,7 @@ class TestAppParameterApi:
patch.object(module, "application_services", return_value=services),
patch.object(module, "dump_response", return_value={"ok": True}) as dump_response,
):
- result = unwrap(module.AppParameterApi.get)(module.AppParameterApi(), installed_app)
+ result = unwrap(module.AppParameterApi.get)(module.AppParameterApi(), _REQUEST_CONTEXT, installed_app)
assert result == {"ok": True}
app_definitions.get_parameters.assert_called_once_with("app-1")
@@ -50,7 +48,7 @@ class TestAppParameterApi:
patch.object(module, "application_services", return_value=services),
pytest.raises(AppUnavailableError),
):
- unwrap(module.AppParameterApi.get)(module.AppParameterApi(), _installed_app())
+ unwrap(module.AppParameterApi.get)(module.AppParameterApi(), _REQUEST_CONTEXT, _installed_app())
class TestExploreAppMetaApi:
@@ -60,7 +58,7 @@ class TestExploreAppMetaApi:
installed_app = _installed_app()
with patch.object(module, "application_services", return_value=services):
- result = unwrap(module.ExploreAppMetaApi.get)(module.ExploreAppMetaApi(), installed_app)
+ result = unwrap(module.ExploreAppMetaApi.get)(module.ExploreAppMetaApi(), _REQUEST_CONTEXT, installed_app)
assert result == {"tool_icons": {"search": "/icon"}}
app_definitions.get_tool_icons.assert_called_once_with("app-1")
@@ -73,7 +71,7 @@ class TestExploreAppMetaApi:
patch.object(module, "application_services", return_value=services),
pytest.raises(AppUnavailableError) as raised,
):
- unwrap(module.ExploreAppMetaApi.get)(module.ExploreAppMetaApi(), _installed_app())
+ unwrap(module.ExploreAppMetaApi.get)(module.ExploreAppMetaApi(), _REQUEST_CONTEXT, _installed_app())
assert raised.value.data == {
"code": "app_unavailable",
diff --git a/api/tests/unit_tests/controllers/console/explore/test_saved_message.py b/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
index 6b5e91c49ab..62fc3c99fab 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_saved_message.py
@@ -12,10 +12,11 @@ from werkzeug.exceptions import NotFound
import controllers.console.explore.saved_message as module
from controllers.console.app.error import AppUnavailableError
from controllers.console.explore.error import NotCompletionAppError
-from controllers.console.explore.wraps import InstalledAppResource
from graphon.file import File, FileTransferMethod, FileType
-from models.model import InstalledApp
+from libs.external_api import ExternalApi
+from machinery.context import RequestContext
from services.errors.message import LastMessageNotExistsError, MessageNotExistsError
+from services.installed_app_access_service import InstalledAppRef
from services.saved_message_service import (
SavedMessageActor,
SavedMessageFeedback,
@@ -23,6 +24,7 @@ from services.saved_message_service import (
SavedMessagePage,
SavedMessageRecord,
)
+from tests.unit_tests.model_factories import make_account, make_tenant
_INPUT_FILE_URL = "https://example.com/input.pdf"
_CREATED_AT = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
@@ -33,17 +35,20 @@ _WORKSPACE_ID = "22222222-2222-4222-8222-222222222222"
@dataclass(frozen=True)
class _ApplicationServiceMocks:
app_definitions: MagicMock
+ installed_app_access: MagicMock
saved_messages: MagicMock
-def _installed_app() -> InstalledApp:
- return InstalledApp(
+_REQUEST_CONTEXT = RequestContext(
+ request_id="test-request", trace_id=None, account_id=_ACCOUNT_ID, active_workspace_id=_WORKSPACE_ID
+)
+
+
+def _installed_app() -> InstalledAppRef:
+ return InstalledAppRef(
+ id="99999999-9999-4999-8999-999999999999",
tenant_id=_WORKSPACE_ID,
app_id="33333333-3333-4333-8333-333333333333",
- app_owner_tenant_id="44444444-4444-4444-8444-444444444444",
- position=0,
- is_pinned=False,
- last_used_at=None,
)
@@ -125,9 +130,11 @@ def _expected_record() -> dict[str, object]:
def services() -> Generator[_ApplicationServiceMocks]:
service_mocks = _ApplicationServiceMocks(
app_definitions=MagicMock(),
+ installed_app_access=MagicMock(),
saved_messages=MagicMock(),
)
service_mocks.app_definitions.get_mode.return_value = "completion"
+ service_mocks.installed_app_access.get_access.return_value = _installed_app()
with patch.object(
module,
"application_services",
@@ -136,11 +143,6 @@ def services() -> Generator[_ApplicationServiceMocks]:
yield service_mocks
-def test_saved_message_resources_use_installed_app_admission() -> None:
- assert issubclass(module.SavedMessageListApi, InstalledAppResource)
- assert issubclass(module.SavedMessageApi, InstalledAppResource)
-
-
class TestSavedMessageListApi:
def test_get_success(self, app: Flask, services: _ApplicationServiceMocks) -> None:
installed_app = _installed_app()
@@ -157,7 +159,7 @@ class TestSavedMessageListApi:
result = unwrap(module.SavedMessageListApi().get)(
module.SavedMessageListApi(),
module.SavedMessageListQuery.model_validate({}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
installed_app,
)
@@ -183,7 +185,7 @@ class TestSavedMessageListApi:
result = unwrap(module.SavedMessageListApi().get)(
module.SavedMessageListApi(),
module.SavedMessageListQuery.model_validate({"last_id": last_id, "limit": "50"}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
installed_app,
)
@@ -199,18 +201,25 @@ class TestSavedMessageListApi:
@pytest.mark.parametrize("query_string", [{"limit": "0"}, {"limit": "101"}, {"last_id": "invalid-uuid"}])
def test_get_rejects_invalid_query(self, services: _ApplicationServiceMocks, query_string: dict[str, str]) -> None:
http_app = Flask(__name__)
+ http_app.config["TESTING"] = True
+ ExternalApi(http_app).add_resource(module.SavedMessageListApi, "/saved-messages/<uuid:installed_app_id>")
+ account = make_account(account_id=_ACCOUNT_ID, tenant=make_tenant(tenant_id=_WORKSPACE_ID))
+ installed_app = _installed_app()
- @http_app.get("/saved-messages")
- def get_saved_messages() -> dict[str, object]:
- return module.SavedMessageListApi().get(_installed_app())
-
- with patch(
- "controllers.console.wraps.current_account_with_tenant",
- return_value=(MagicMock(id=_ACCOUNT_ID), _WORKSPACE_ID),
+ with (
+ patch("libs.login.current_user", account),
+ patch("libs.login.check_csrf_token"),
+ patch("controllers.console.wraps._is_setup_completed", return_value=True),
+ patch("controllers.console.explore.installed_app_admission.application_services", return_value=services),
):
- response = http_app.test_client().get("/saved-messages", query_string=query_string)
+ response = http_app.test_client().get(f"/saved-messages/{installed_app.id}", query_string=query_string)
assert response.status_code == 422
+ services.installed_app_access.get_access.assert_called_once_with(
+ installed_app_id=installed_app.id,
+ tenant_id=_WORKSPACE_ID,
+ account_id=_ACCOUNT_ID,
+ )
services.app_definitions.get_mode.assert_not_called()
services.saved_messages.pagination_by_last_id.assert_not_called()
@@ -227,7 +236,7 @@ class TestSavedMessageListApi:
unwrap(module.SavedMessageListApi().get)(
module.SavedMessageListApi(),
module.SavedMessageListQuery.model_validate({"last_id": last_id}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
installed_app,
)
@@ -240,7 +249,7 @@ class TestSavedMessageListApi:
unwrap(module.SavedMessageListApi().get)(
module.SavedMessageListApi(),
module.SavedMessageListQuery.model_validate({}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
_installed_app(),
)
@@ -251,7 +260,7 @@ class TestSavedMessageListApi:
unwrap(module.SavedMessageListApi().get)(
module.SavedMessageListApi(),
module.SavedMessageListQuery.model_validate({}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
_installed_app(),
)
@@ -262,7 +271,7 @@ class TestSavedMessageListApi:
result = unwrap(module.SavedMessageListApi().post)(
module.SavedMessageListApi(),
module.SavedMessageCreatePayload.model_validate({"message_id": message_id}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
installed_app,
)
@@ -280,7 +289,7 @@ class TestSavedMessageListApi:
unwrap(module.SavedMessageListApi().post)(
module.SavedMessageListApi(),
module.SavedMessageCreatePayload.model_validate({"message_id": str(uuid4())}),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
_installed_app(),
)
@@ -292,7 +301,7 @@ class TestSavedMessageApi:
result = unwrap(module.SavedMessageApi().delete)(
module.SavedMessageApi(),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
installed_app,
message_id,
)
@@ -310,7 +319,7 @@ class TestSavedMessageApi:
with pytest.raises(NotCompletionAppError):
unwrap(module.SavedMessageApi().delete)(
module.SavedMessageApi(),
- _ACCOUNT_ID,
+ _REQUEST_CONTEXT,
_installed_app(),
uuid4(),
)
diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py
index 52dc3184035..03c57bf0d29 100644
--- a/api/tests/unit_tests/extensions/test_ext_application_services.py
+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py
@@ -21,7 +21,7 @@ from extensions.ext_redis import RedisClientWrapper
from machinery.context import RequestContext
from models.account import Account
from models.enums import CustomizeTokenStrategy
-from models.model import AccountTrialAppRecord, App, AppModelConfig, DifySetup, Site, TrialApp
+from models.model import AccountTrialAppRecord, App, AppMode, AppModelConfig, DifySetup, InstalledApp, Site, TrialApp
from repositories.account_activation_repository import SQLAlchemyAccountActivationRepository
from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository
from repositories.account_oauth_repository import (
@@ -83,6 +83,7 @@ from services.errors.enterprise import EnterpriseAPIError, EnterpriseAPINotFound
from services.file_service import FileService
from services.human_input_file_upload_service import HumanInputFileUploadService
from services.init_validation_service import InvalidInitializationPasswordError
+from services.installed_app_access_service import InstalledAppAccessDeniedError, InstalledAppRef
from services.message_file_preview_service import MessageFilePreviewService
from services.partner_tenant_binding_service import PartnerTenantBindingService
from services.plugin_file_upload_gateway import ToolFilePluginUploadGateway
@@ -714,6 +715,120 @@ def test_build_application_services_wires_trial_app_usage(
assert record.count == 1
+def installed_app_ref(sqlite_session_factory: sessionmaker[Session]) -> InstalledAppRef:
+ with sqlite_session_factory.begin() as session:
+ app = App(
+ tenant_id=str(uuid4()),
+ name="Installed app",
+ mode=AppMode.COMPLETION,
+ enable_site=True,
+ enable_api=True,
+ )
+ session.add(app)
+ session.flush()
+ installed_app = InstalledApp(
+ tenant_id=str(uuid4()),
+ app_id=app.id,
+ app_owner_tenant_id=app.tenant_id,
+ is_pinned=False,
+ )
+ session.add(installed_app)
+ session.flush()
+ result = InstalledAppRef(id=installed_app.id, app_id=app.id, tenant_id=installed_app.tenant_id)
+ return result
+
+
+ ("deployment_edition", "permission_result"),
+ [
+ pytest.param(DeploymentEdition.COMMUNITY, False, id="community-skips-permission"),
+ pytest.param(DeploymentEdition.CLOUD, False, id="cloud-skips-permission"),
+ pytest.param(DeploymentEdition.ENTERPRISE, True, id="enterprise-allowed"),
+ pytest.param(DeploymentEdition.ENTERPRISE, False, id="enterprise-denied"),
+ ],
+)
+def test_build_application_services_wires_installed_app_admission(
+ sqlite_session_factory: sessionmaker[Session],
+ installed_app_ref: InstalledAppRef,
+ deployment_edition: DeploymentEdition,
+ permission_result: bool,
+) -> None:
+ account_id = str(uuid4())
+ with patch(
+ "services.enterprise.enterprise_service.EnterpriseRequest.send_request",
+ return_value={"result": permission_result},
+ ) as enterprise_request:
+ services = ext_application_services.build_application_services(
+ database_client=sqlite_session_factory,
+ deployment_edition=deployment_edition,
+ initialization_password="",
+ redis=MagicMock(spec=RedisClientWrapper),
+ )
+ if deployment_edition == DeploymentEdition.ENTERPRISE and not permission_result:
+ with pytest.raises(InstalledAppAccessDeniedError):
+ services.installed_app_access.get_access(
+ installed_app_id=installed_app_ref.id,
+ tenant_id=installed_app_ref.tenant_id,
+ account_id=account_id,
+ )
+ else:
+ assert (
+ services.installed_app_access.get_access(
+ installed_app_id=installed_app_ref.id,
+ tenant_id=installed_app_ref.tenant_id,
+ account_id=account_id,
+ )
+ == installed_app_ref
+ )
+
+ if deployment_edition == DeploymentEdition.ENTERPRISE:
+ enterprise_request.assert_called_once_with(
+ "GET", "/webapp/permission", params={"userId": account_id, "appId": installed_app_ref.app_id}
+ )
+ else:
+ enterprise_request.assert_not_called()
+
+
+ "enterprise_error",
+ [
+ pytest.param(EnterpriseAPINotFoundError(), id="not-found"),
+ pytest.param(EnterpriseAPIError("permission unavailable"), id="api-error"),
+ pytest.param(httpx.ConnectError("connection failed"), id="transport"),
+ pytest.param(json.JSONDecodeError("invalid", "", 0), id="invalid-json"),
+ pytest.param(UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid"), id="invalid-encoding"),
+ ],
+)
+def test_installed_app_admission_normalizes_known_enterprise_errors(
+ sqlite_session_factory: sessionmaker[Session],
+ installed_app_ref: InstalledAppRef,
+ enterprise_error: Exception,
+) -> None:
+ account_id = str(uuid4())
+ with patch(
+ "services.enterprise.enterprise_service.EnterpriseRequest.send_request",
+ side_effect=enterprise_error,
+ ) as enterprise_request:
+ services = ext_application_services.build_application_services(
+ database_client=sqlite_session_factory,
+ deployment_edition=DeploymentEdition.ENTERPRISE,
+ initialization_password="",
+ redis=MagicMock(spec=RedisClientWrapper),
+ )
+ with pytest.raises(WebAppAccessUnavailableError) as raised:
+ services.installed_app_access.get_access(
+ installed_app_id=installed_app_ref.id,
+ tenant_id=installed_app_ref.tenant_id,
+ account_id=account_id,
+ )
+
+ assert raised.value.__cause__ is enterprise_error
+ enterprise_request.assert_called_once_with(
+ "GET", "/webapp/permission", params={"userId": account_id, "appId": installed_app_ref.app_id}
+ )
+
+
def test_trial_generation_uses_configured_access_runtime_and_usage(
sqlite_session_factory: sessionmaker[Session],
) -> None:
diff --git a/api/tests/unit_tests/repositories/test_installed_app_access_repository.py b/api/tests/unit_tests/repositories/test_installed_app_access_repository.py
new file mode 100644
index 00000000000..a1ecd1b8ba8
--- /dev/null
+++ b/api/tests/unit_tests/repositories/test_installed_app_access_repository.py
@@ -0,0 +1,103 @@
+from uuid import uuid4
+
+import pytest
+from sqlalchemy import inspect
+from sqlalchemy.orm import Session, sessionmaker
+
+from models.model import App, AppMode, InstalledApp
+from repositories.installed_app_access_repository import SQLAlchemyInstalledAppAccessRepository
+from services.installed_app_access_service import InstalledAppRef
+
+_VIEWER_TENANT_ID = "11111111-1111-4111-8111-111111111111"
+_OWNER_TENANT_ID = "22222222-2222-4222-8222-222222222222"
+
+
+def _installation(*, app_id: str) -> InstalledApp:
+ return InstalledApp(
+ app_id=app_id,
+ tenant_id=_VIEWER_TENANT_ID,
+ app_owner_tenant_id=_OWNER_TENANT_ID,
+ position=0,
+ is_pinned=False,
+ last_used_at=None,
+ )
+
+
+def test_resolve_returns_pure_reference_to_cross_workspace_app(
+ sqlite_session_factory: sessionmaker[Session],
+) -> None:
+ with sqlite_session_factory.begin() as session:
+ # Admission must not add public, published, or app-mode constraints.
+ app = App(
+ tenant_id=_OWNER_TENANT_ID,
+ name="Installed app",
+ mode=AppMode.AGENT,
+ is_public=False,
+ enable_site=True,
+ enable_api=True,
+ )
+ session.add(app)
+ session.flush()
+ installed_app = _installation(app_id=app.id)
+ session.add(installed_app)
+ session.flush()
+ installed_app_id = installed_app.id
+ app_id = app.id
+
+ repository = SQLAlchemyInstalledAppAccessRepository(session_factory=sqlite_session_factory)
+ result = repository.resolve(installed_app_id=installed_app_id, tenant_id=_VIEWER_TENANT_ID)
+
+ assert result == InstalledAppRef(id=installed_app_id, app_id=app_id, tenant_id=_VIEWER_TENANT_ID)
+ assert inspect(result, raiseerr=False) is None
+ with sqlite_session_factory() as session:
+ assert session.get(InstalledApp, installed_app_id) is not None
+
+
+def test_missing_installation_returns_none(sqlite_session_factory: sessionmaker[Session]) -> None:
+ repository = SQLAlchemyInstalledAppAccessRepository(session_factory=sqlite_session_factory)
+
+ assert repository.resolve(installed_app_id=str(uuid4()), tenant_id=_VIEWER_TENANT_ID) is None
+
+
[email protected]("orphaned", [False, True])
+def test_other_workspace_cannot_resolve_or_clean_up_installation(
+ sqlite_session_factory: sessionmaker[Session],
+ orphaned: bool,
+) -> None:
+ with sqlite_session_factory.begin() as session:
+ app_id = str(uuid4())
+ if not orphaned:
+ app = App(
+ id=app_id,
+ tenant_id=_OWNER_TENANT_ID,
+ name="Installed app",
+ mode=AppMode.COMPLETION,
+ enable_site=True,
+ enable_api=True,
+ )
+ session.add(app)
+ installed_app = _installation(app_id=app_id)
+ session.add(installed_app)
+ session.flush()
+ installed_app_id = installed_app.id
+
+ repository = SQLAlchemyInstalledAppAccessRepository(session_factory=sqlite_session_factory)
+
+ assert repository.resolve(installed_app_id=installed_app_id, tenant_id=_OWNER_TENANT_ID) is None
+ with sqlite_session_factory() as session:
+ assert session.get(InstalledApp, installed_app_id) is not None
+
+
+def test_orphan_cleanup_is_committed_and_idempotent(sqlite_session_factory: sessionmaker[Session]) -> None:
+ with sqlite_session_factory.begin() as session:
+ installed_app = _installation(app_id=str(uuid4()))
+ session.add(installed_app)
+ session.flush()
+ installed_app_id = installed_app.id
+
+ repository = SQLAlchemyInstalledAppAccessRepository(session_factory=sqlite_session_factory)
+
+ assert repository.resolve(installed_app_id=installed_app_id, tenant_id=_VIEWER_TENANT_ID) is None
+ with sqlite_session_factory() as session:
+ assert session.get(InstalledApp, installed_app_id) is None
+ assert repository.resolve(installed_app_id=installed_app_id, tenant_id=_VIEWER_TENANT_ID) is None
diff --git a/api/tests/unit_tests/services/test_installed_app_access_service.py b/api/tests/unit_tests/services/test_installed_app_access_service.py
new file mode 100644
index 00000000000..f547a212abc
--- /dev/null
+++ b/api/tests/unit_tests/services/test_installed_app_access_service.py
@@ -0,0 +1,89 @@
+import pytest
+
+from services.installed_app_access_service import (
+ InstalledAppAccessDeniedError,
+ InstalledAppAccessService,
+ InstalledAppNotFoundError,
+ InstalledAppRef,
+)
+
+_REF = InstalledAppRef(id="installation-1", app_id="app-1", tenant_id="workspace-1")
+
+
+class _Store:
+ def __init__(
+ self,
+ *,
+ result: InstalledAppRef | None,
+ events: list[tuple[str, ...]],
+ error: Exception | None = None,
+ ) -> None:
+ self._result = result
+ self._events = events
+ self._error = error
+
+ def resolve(self, *, installed_app_id: str, tenant_id: str) -> InstalledAppRef | None:
+ self._events.append(("resolve", installed_app_id, tenant_id))
+ if self._error is not None:
+ raise self._error
+ return self._result
+
+
[email protected]("allowed", [True, False])
+def test_access_resolves_workspace_installation_before_checking_target_app(allowed: bool) -> None:
+ events: list[tuple[str, ...]] = []
+
+ def is_user_allowed(*, user_id: str, app_id: str) -> bool:
+ events.append(("authorize", user_id, app_id))
+ return allowed
+
+ service = InstalledAppAccessService(
+ installed_apps=_Store(result=_REF, events=events),
+ is_user_allowed=is_user_allowed,
+ )
+
+ if allowed:
+ assert service.get_access(installed_app_id=_REF.id, tenant_id=_REF.tenant_id, account_id="account-1") is _REF
+ else:
+ with pytest.raises(InstalledAppAccessDeniedError):
+ service.get_access(installed_app_id=_REF.id, tenant_id=_REF.tenant_id, account_id="account-1")
+
+ assert events == [("resolve", _REF.id, _REF.tenant_id), ("authorize", "account-1", _REF.app_id)]
+
+
+def test_missing_installation_does_not_check_permission() -> None:
+ events: list[tuple[str, ...]] = []
+
+ def unexpected_permission_check(*, user_id: str, app_id: str) -> bool:
+ pytest.fail(f"Missing installation reached the permission provider: {user_id=}, {app_id=}")
+
+ service = InstalledAppAccessService(
+ installed_apps=_Store(result=None, events=events),
+ is_user_allowed=unexpected_permission_check,
+ )
+
+ with pytest.raises(InstalledAppNotFoundError, match="^Installed app not found$"):
+ service.get_access(installed_app_id="missing", tenant_id=_REF.tenant_id, account_id="account-1")
+
+ assert events == [("resolve", "missing", _REF.tenant_id)]
+
+
[email protected]("failure_source", ["store", "permission"])
+def test_dependency_errors_propagate_unchanged(failure_source: str) -> None:
+ events: list[tuple[str, ...]] = []
+ failure = RuntimeError("dependency unavailable")
+
+ def is_user_allowed(*, user_id: str, app_id: str) -> bool:
+ events.append(("authorize", user_id, app_id))
+ raise failure
+
+ service = InstalledAppAccessService(
+ installed_apps=_Store(result=_REF, events=events, error=failure if failure_source == "store" else None),
+ is_user_allowed=is_user_allowed,
+ )
+
+ with pytest.raises(RuntimeError) as raised:
+ service.get_access(installed_app_id=_REF.id, tenant_id=_REF.tenant_id, account_id="account-1")
+
+ assert raised.value is failure
+ assert len(events) == (1 if failure_source == "store" else 2)