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.

fix(api): inherit web app access mode when converting apps (#44857)

XiaoBa24e4037144d8
diff --git a/api/services/app/console_gateway.py b/api/services/app/console_gateway.py
index 869e75c5a87..570d3b3be8b 100644
--- a/api/services/app/console_gateway.py
+++ b/api/services/app/console_gateway.py
@@ -201,12 +201,7 @@ class EnterpriseConsoleAppAccess(ConsoleAppAccess):
def inherit_access(self, source_app_id: str, app_id: str) -> None:
if not SystemFeatureService.is_webapp_auth_enabled():
return
- try:
- access_mode = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(source_app_id).access_mode
- except Exception:
- # Old apps without settings default to public, matching the access fallback.
- access_mode = "public"
- EnterpriseService.WebAppAuth.update_app_access_mode(app_id, access_mode)
+ EnterpriseService.WebAppAuth.inherit_app_access_mode(source_app_id, app_id)
def __init__(self, *, members: MemberService) -> None:
self._members = members
diff --git a/api/services/enterprise/enterprise_service.py b/api/services/enterprise/enterprise_service.py
index c3217dcf93b..c86cc8c79f3 100644
--- a/api/services/enterprise/enterprise_service.py
+++ b/api/services/enterprise/enterprise_service.py
@@ -308,6 +308,16 @@ class EnterpriseService:
return ret
+ @classmethod
+ def inherit_app_access_mode(cls, source_app_id: str, target_app_id: str) -> None:
+ """Inherit a source app's mode, preserving the copy path's legacy public fallback."""
+ try:
+ access_mode = cls.get_app_access_mode_by_id(source_app_id).access_mode
+ except Exception:
+ # Preserve the existing copy behavior, including read failures for old apps without settings.
+ access_mode = "public"
+ cls.update_app_access_mode(target_app_id, access_mode)
+
@classmethod
def update_app_access_mode(cls, app_id: str, access_mode: str):
if not app_id:
diff --git a/api/services/workflow_service.py b/api/services/workflow_service.py
index ed64d903130..1ee77552ec5 100644
--- a/api/services/workflow_service.py
+++ b/api/services/workflow_service.py
@@ -6,7 +6,7 @@ from collections.abc import Callable, Generator, Mapping, Sequence
from dataclasses import dataclass
from typing import Any, cast
-from sqlalchemy import exists, select
+from sqlalchemy import exists, inspect, select
from sqlalchemy.orm import Session, sessionmaker
from configs import dify_config
@@ -95,6 +95,7 @@ from models.workflow import Workflow, WorkflowNodeExecutionModel, WorkflowNodeEx
from repositories.factory import DifyAPIRepositoryFactory
from services.agent.retirement_service import WorkflowAgentRetirementService
from services.billing_service import BillingService
+from services.enterprise.enterprise_service import EnterpriseService
from services.errors.app import (
IsDraftWorkflowError,
TriggerNodeLimitExceededError,
@@ -1866,6 +1867,7 @@ class WorkflowService:
if app_model.mode not in {AppMode.CHAT, AppMode.COMPLETION}:
raise ValueError(f"Current App mode: {app_model.mode} is not supported convert to workflow.")
+ source_app_id = app_model.id
# convert to workflow
new_app: App = workflow_converter.convert_to_workflow(
app_model=app_model,
@@ -1877,6 +1879,13 @@ class WorkflowService:
session=session,
)
+ if SystemFeatureService.is_webapp_auth_enabled():
+ # The converter committed and expired the App. Read its identity without
+ # opening another database transaction before calling Enterprise.
+ identity = inspect(new_app).identity
+ assert identity is not None
+ EnterpriseService.WebAppAuth.inherit_app_access_mode(source_app_id, str(identity[0]))
+
return new_app
def validate_graph_structure(self, graph: Mapping[str, Any]):
diff --git a/api/tests/unit_tests/services/app/test_console_gateway.py b/api/tests/unit_tests/services/app/test_console_gateway.py
index a49df5e453f..947d2488d39 100644
--- a/api/tests/unit_tests/services/app/test_console_gateway.py
+++ b/api/tests/unit_tests/services/app/test_console_gateway.py
@@ -942,3 +942,38 @@ def test_console_package_export_forwards_roster_options(
monkeypatch.setattr(AppPackageService, "export_app", export_app)
app_services.console.export(context, app_id, AppExportOptions(format="ifpkg", preserve_agent_bindings=True))
assert captured["preserve_agent_bindings"] is True
+
+
[email protected]("outcome", ["disabled", "write_error", "false_result"])
+def test_inherit_access_preserves_copy_contract(
+ monkeypatch: pytest.MonkeyPatch, rbac_domain: RBACDomain, outcome: str
+) -> None:
+ from services.enterprise.enterprise_service import EnterpriseRequest
+ from services.errors.enterprise import EnterpriseServiceError
+
+ monkeypatch.setattr(SystemFeatureService, "is_webapp_auth_enabled", lambda: outcome != "disabled")
+ calls: list[str] = []
+ error = EnterpriseServiceError("write failed")
+
+ def request(method: str, endpoint: str, **kwargs: object) -> dict[str, object]:
+ calls.append(method)
+ if method == "GET":
+ assert endpoint == "/webapp/access-mode/id"
+ assert kwargs["params"] == {"appId": "source"}
+ return {"accessMode": "private_all"}
+ assert method == "POST"
+ assert endpoint == "/webapp/access-mode"
+ assert kwargs["json"] == {"appId": "target", "accessMode": "private_all"}
+ if outcome == "write_error":
+ raise error
+ return {"result": False}
+
+ monkeypatch.setattr(EnterpriseRequest, "send_request", request)
+ gateway = EnterpriseConsoleAppAccess(members=rbac_domain.rbac.members)
+ if outcome == "write_error":
+ with pytest.raises(EnterpriseServiceError) as raised:
+ gateway.inherit_access("source", "target")
+ assert raised.value is error
+ else:
+ assert gateway.inherit_access("source", "target") is None
+ assert calls == ([] if outcome == "disabled" else ["GET", "POST"])
diff --git a/api/tests/unit_tests/services/enterprise/test_enterprise_service.py b/api/tests/unit_tests/services/enterprise/test_enterprise_service.py
index 5d2a4c8fd94..1494c16530e 100644
--- a/api/tests/unit_tests/services/enterprise/test_enterprise_service.py
+++ b/api/tests/unit_tests/services/enterprise/test_enterprise_service.py
@@ -561,3 +561,49 @@ class TestIssueMCPToken:
req.send_request.return_value = {"token": "t", "expires_at": True}
with pytest.raises(MCPTokenError, match="non-numeric expires_at"):
self._call()
+
+
+class TestWebAppAccessModeInheritance:
+ @pytest.mark.parametrize("mode", ["public", "private", "private_all", "sso_verified"])
+ @pytest.mark.parametrize("write_result", [True, False])
+ def test_inherits_source_mode(self, mode: str, write_result: bool) -> None:
+ from unittest.mock import call
+
+ with patch(f"{MODULE}.EnterpriseRequest.send_request") as request:
+ request.side_effect = [{"accessMode": mode}, {"result": write_result}]
+ assert EnterpriseService.WebAppAuth.inherit_app_access_mode("source", "target") is None
+ assert request.call_args_list == [
+ call("GET", "/webapp/access-mode/id", params={"appId": "source"}),
+ call("POST", "/webapp/access-mode", json={"appId": "target", "accessMode": mode}),
+ ]
+
+ @pytest.mark.parametrize("response", [{}, {"accessMode": None}])
+ def test_invalid_read_falls_back_to_public(self, response: dict[str, object]) -> None:
+ with patch(f"{MODULE}.EnterpriseRequest.send_request") as request:
+ request.side_effect = [response, {"result": True}]
+ EnterpriseService.WebAppAuth.inherit_app_access_mode("source", "target")
+ request.assert_called_with("POST", "/webapp/access-mode", json={"appId": "target", "accessMode": "public"})
+
+ def test_read_timeout_falls_back_to_public(self) -> None:
+ import httpx
+
+ with patch(f"{MODULE}.EnterpriseRequest.send_request") as request:
+ request.side_effect = [httpx.ReadTimeout("unavailable"), {"result": True}]
+ EnterpriseService.WebAppAuth.inherit_app_access_mode("source", "target")
+ request.assert_called_with("POST", "/webapp/access-mode", json={"appId": "target", "accessMode": "public"})
+
+ def test_unknown_mode_is_not_replaced_with_public(self) -> None:
+ with patch(f"{MODULE}.EnterpriseRequest.send_request") as request:
+ request.return_value = {"accessMode": "unknown"}
+ with pytest.raises(ValueError, match="access_mode must be one of"):
+ EnterpriseService.WebAppAuth.inherit_app_access_mode("source", "target")
+ assert request.call_count == 1
+
+ def test_write_error_propagates(self) -> None:
+ error = EnterpriseServiceError("write failed")
+ with patch(f"{MODULE}.EnterpriseRequest.send_request") as request:
+ request.side_effect = [{"accessMode": "private"}, error]
+ with pytest.raises(EnterpriseServiceError) as raised:
+ EnterpriseService.WebAppAuth.inherit_app_access_mode("source", "target")
+ assert raised.value is error
+ assert request.call_count == 2
diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.py
index a8050e5f731..18b048bcd8d 100644
--- a/api/tests/unit_tests/services/test_workflow_service.py
+++ b/api/tests/unit_tests/services/test_workflow_service.py
@@ -4370,3 +4370,134 @@ class TestWorkflowAgentPreviewIdentityCases:
prefill.assert_not_called()
with sessions() as session:
assert session.scalar(select(func.count()).select_from(WorkflowNodeExecutionModel)) == 0
+
+
[email protected]("source_mode", [AppMode.CHAT, AppMode.COMPLETION])
+ ("access_mode", "outcome"),
+ [
+ ("public", "success"),
+ ("private", "success"),
+ ("private_all", "success"),
+ ("sso_verified", "success"),
+ ("private", "read_timeout"),
+ ("private", "write_error"),
+ ("private", "false_result"),
+ ("private", "disabled"),
+ ("private", "conversion_error"),
+ ],
+)
+def test_convert_to_workflow_inherits_webapp_access(
+ sqlite_session_factory: sessionmaker[Session],
+ monkeypatch: pytest.MonkeyPatch,
+ source_mode: AppMode,
+ access_mode: str,
+ outcome: str,
+) -> None:
+ import httpx
+ from blinker import Signal
+
+ from events.event_handlers.create_installed_app_when_app_created import handle as create_installation
+ from events.event_handlers.create_site_record_when_app_created import handle as create_site
+ from models.model import AppModelConfig, InstalledApp, Site
+ from services.enterprise.enterprise_service import EnterpriseRequest
+ from services.errors.enterprise import EnterpriseServiceError
+ from services.workflow import workflow_converter as converter_module
+
+ apply_config_overrides(
+ monkeypatch,
+ DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY if outcome == "disabled" else DeploymentEdition.ENTERPRISE,
+ )
+ created_signal = Signal()
+ created_signal.connect(create_site)
+ created_signal.connect(create_installation)
+ monkeypatch.setattr(converter_module, "app_was_created", created_signal)
+ source_id = str(uuid4())
+ calls: list[str] = []
+ written: dict[str, str] = {}
+ write_error = EnterpriseServiceError("write failed")
+
+ def build_graph(
+ _converter: converter_module.WorkflowConverter,
+ *,
+ app_model: App,
+ app_model_config: AppModelConfig,
+ account_id: str,
+ session: Session,
+ ) -> Workflow:
+ assert app_model_config.app_id == app_model.id
+ if outcome == "conversion_error":
+ raise ValueError("conversion failed")
+ workflow = Workflow(
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ type=WorkflowType.CHAT if source_mode == AppMode.CHAT else WorkflowType.WORKFLOW,
+ version=Workflow.VERSION_DRAFT,
+ graph='{"nodes": [], "edges": []}',
+ _features="{}",
+ created_by=account_id,
+ _environment_variables=[],
+ _conversation_variables=[],
+ )
+ session.add(workflow)
+ session.commit()
+ return workflow
+
+ monkeypatch.setattr(converter_module.WorkflowConverter, "convert_app_model_config_to_workflow", build_graph)
+ with sqlite_session_factory(expire_on_commit=True) as session:
+ account = make_account(account_id=str(uuid4()), interface_language="en-US")
+ source = make_app(app_id=source_id, mode=source_mode, tenant_id=str(uuid4()))
+ config = AppModelConfig(app_id=source_id)
+ source.app_model_config_id = config.id
+ session.add_all([account, source, config])
+ session.commit()
+
+ def request(method: str, endpoint: str, **kwargs: Any) -> dict[str, Any]:
+ assert not session.in_transaction(), "Enterprise I/O must run after conversion commits"
+ calls.append(method)
+ if method == "GET":
+ assert endpoint == "/webapp/access-mode/id"
+ assert kwargs["params"] == {"appId": source_id}
+ if outcome == "read_timeout":
+ raise httpx.ReadTimeout("source unavailable")
+ return {"accessMode": access_mode}
+ assert method == "POST"
+ assert endpoint == "/webapp/access-mode"
+ target_id = kwargs["json"]["appId"]
+ assert target_id != source_id
+ assert kwargs["json"]["accessMode"] == ("public" if outcome == "read_timeout" else access_mode)
+ if outcome == "write_error":
+ raise write_error
+ written[target_id] = kwargs["json"]["accessMode"]
+ return {"result": outcome != "false_result"}
+
+ monkeypatch.setattr(EnterpriseRequest, "send_request", request)
+ service = WorkflowService(session_maker=sqlite_session_factory)
+ if outcome == "conversion_error":
+ with pytest.raises(ValueError, match="conversion failed"):
+ service.convert_to_workflow(source, account, {"name": "Converted"}, session=session)
+ assert calls == []
+ return
+ if outcome == "write_error":
+ with pytest.raises(EnterpriseServiceError) as raised:
+ service.convert_to_workflow(source, account, {"name": "Converted"}, session=session)
+ assert raised.value is write_error
+ assert calls == ["GET", "POST"]
+ else:
+ target = service.convert_to_workflow(source, account, {"name": "Converted"}, session=session)
+ assert target.id != source_id
+ assert target.mode == (AppMode.ADVANCED_CHAT if source_mode == AppMode.CHAT else AppMode.WORKFLOW)
+ assert target.workflow_id is None
+ assert calls == ([] if outcome == "disabled" else ["GET", "POST"])
+ if outcome != "disabled":
+ assert written == {target.id: "public" if outcome == "read_timeout" else access_mode}
+
+ with sqlite_session_factory() as verification:
+ target = verification.scalar(select(App).where(App.name == "Converted"))
+ assert target is not None
+ assert verification.get(App, source_id) is not None
+ workflow = verification.scalar(select(Workflow).where(Workflow.app_id == target.id))
+ assert workflow is not None
+ assert workflow.version == Workflow.VERSION_DRAFT
+ assert verification.scalar(select(Site).where(Site.app_id == target.id)) is not None
+ assert verification.scalar(select(InstalledApp).where(InstalledApp.app_id == target.id)) is not None