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): keep web app access mode when importing DSL over an existing app (#44700)

Ryuta KOBAYASHI89cdc0c7a9c7
diff --git a/api/services/app/console_service.py b/api/services/app/console_service.py
index c100f9aa6f9..c01462daf0f 100644
--- a/api/services/app/console_service.py
+++ b/api/services/app/console_service.py
@@ -283,22 +283,34 @@ class ConsoleAppService:
self._access.require_import(context, "dsl")
result = self._transfers.import_dsl(context, params, package=package)
self._set_import_permissions(context, result, created=result.app_created)
- if result.app_id:
- self._access.initialize_import_access(result.app_id)
+ self._initialize_import_access(result, created=result.app_created)
return result
def confirm_import(self, context: RequestContext, import_id: str) -> Import:
result, created = self._transfers.confirm_import(context, import_id)
self._set_import_permissions(context, result, created=created)
+ self._initialize_import_access(result, created=created)
return result
def _set_import_permissions(self, context: RequestContext, result: Import, *, created: bool) -> None:
+ if app_id := self._created_app_id(result, created=created):
+ result.permission_keys = self._access.imported_permissions(context, app_id)
+
+ def _initialize_import_access(self, result: Import, *, created: bool) -> None:
+ # Only newly created apps get the default access mode; overwrites keep the target app's setting.
+ if app_id := self._created_app_id(result, created=created):
+ self._access.initialize_import_access(app_id)
+
+ @staticmethod
+ def _created_app_id(result: Import, *, created: bool) -> str | None:
+ """The app id when the import completed by creating a new app; None for overwrites and unfinished imports."""
if (
created
and result.app_id
and result.status in {ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS}
):
- result.permission_keys = self._access.imported_permissions(context, result.app_id)
+ return result.app_id
+ return None
def get_reference(self, context: RequestContext, app_id: str) -> AppReference:
"""Admit an existing console app without retaining its database session."""
diff --git a/api/tests/unit_tests/controllers/console/app/test_app_import.py b/api/tests/unit_tests/controllers/console/app/test_app_import.py
index 2531648168d..e6759518c1f 100644
--- a/api/tests/unit_tests/controllers/console/app/test_app_import.py
+++ b/api/tests/unit_tests/controllers/console/app/test_app_import.py
@@ -180,7 +180,8 @@ class TestAppImportApiCases:
completed = status in {ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS}
assert permissions == ([app_id] if completed and not overwrite else [])
assert response["permission_keys"] == (["app.acl.view_layout"] if permissions else [])
- assert access_updates == ([] if confirm else [(app_id, "private")])
+ # Overwrites keep the existing web app access mode; only completed creations get the private default.
+ assert access_updates == ([(app_id, "private")] if completed and not overwrite else [])
assert status_code == (
400 if status == ImportStatus.FAILED else 202 if status == ImportStatus.PENDING and not confirm else 200
)
@@ -315,6 +316,7 @@ class Imports:
packages: list[PreparedAppPackage] = field(default_factory=list)
agent_calls: list[AgentImportCall] = field(default_factory=list)
status: ImportStatus = ImportStatus.COMPLETED
+ app_created: bool = False
warnings: list[DslImportWarning] = field(default_factory=list)
def dsl(
@@ -326,7 +328,7 @@ class Imports:
assert isinstance(package, PreparedAppPackage)
assert not package.archive.closed
self.packages.append(package)
- return Import(id="import-1", status=self.status, app_id="app-1")
+ return Import(id="import-1", status=self.status, app_id="app-1", app_created=self.app_created)
def agent(self, *, source: BinaryIO, tenant_id: str, account: Account) -> RosterAgentPackageImportResult:
self.agent_calls.append(AgentImportCall(tenant_id, account, source.read()))
@@ -589,6 +591,37 @@ class TestRosterPackageRoutesCases:
)
assert imports.agent_calls == []
+ @staticmethod
+ @pytest.mark.parametrize("from_url", [False, True])
+ @pytest.mark.parametrize("overwrite", [False, True])
+ def test_ordinary_package_import_keeps_access_mode_on_overwrite(
+ app: Flask, imports: Imports, monkeypatch: pytest.MonkeyPatch, overwrite: bool, from_url: bool
+ ) -> None:
+ imports.app_created = not overwrite
+ access_updates: list[tuple[str, str]] = []
+ monkeypatch.setattr("services.app.console_gateway.SystemFeatureService.is_webapp_auth_enabled", lambda: True)
+ monkeypatch.setattr(
+ EnterpriseService.WebAppAuth,
+ "update_app_access_mode",
+ lambda app_id, access_mode: access_updates.append((app_id, access_mode)),
+ )
+ app_id = "app-1" if overwrite else None
+ with AppPackageService().export(dsl="kind: app\napp:\n mode: workflow\n", name="Workflow") as package:
+ if from_url:
+ _mock_download(monkeypatch, package.archive.read())
+ _data, code = _post(
+ app,
+ imports,
+ json={"mode": "yaml-url", "yaml_url": "https://example.com/workflow.ifpkg", "app_id": app_id},
+ )
+ else:
+ form: dict[str, object] = {"file": (package.archive, "workflow.ifpkg")}
+ if app_id:
+ form["app_id"] = app_id
+ _data, code = _post(app, imports, data=form)
+ assert code == 200
+ assert access_updates == ([] if overwrite else [("app-1", "private")])
+
@staticmethod
def test_export_query_rejects_conflicting_version_selectors() -> None:
with pytest.raises(ValidationError, match="version_id and workflow_id cannot be used together"):
diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py
index 673f36e01c9..ddb9459b5ea 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -4,6 +4,7 @@ from io import BytesIO
from types import SimpleNamespace
from typing import cast
from unittest.mock import Mock
+from uuid import uuid4
import pytest
import yaml
@@ -1482,3 +1483,34 @@ def test_pending_import_does_not_report_creation_or_cache_marker(
assert result.status == ImportStatus.PENDING
assert not result.app_created
assert "app_created" not in cache.call_args.args[2]
+
+
[email protected]("overwrite", [False, True])
+def test_confirmed_import_reports_creation_only_for_new_apps(
+ unbound_session: Session, monkeypatch: pytest.MonkeyPatch, overwrite: bool
+) -> None:
+ pending_imports: dict[str, str] = {}
+ monkeypatch.setattr(
+ "services.app_dsl_service.redis_client.setex",
+ lambda key, _expiry, value: pending_imports.__setitem__(key, value),
+ )
+ monkeypatch.setattr("services.app_dsl_service.redis_client.get", pending_imports.get)
+ monkeypatch.setattr("services.app_dsl_service.redis_client.delete", pending_imports.pop)
+ existing = _app(mode=AppMode.WORKFLOW)
+ service = AppDslService(unbound_session)
+ monkeypatch.setattr(service, "_load_app_for_overwrite", lambda _account, _app_id: existing)
+ monkeypatch.setattr(service, "_validate_workflow_overwrite", lambda _app, _data: None)
+ monkeypatch.setattr(service, "_create_or_update_app", lambda *, app, **_kwargs: app or _app(app_id=str(uuid4())))
+ pending = service.import_app(
+ account=_account(),
+ import_mode="yaml-content",
+ yaml_content=_PENDING_WORKFLOW_DSL,
+ app_id=existing.id if overwrite else None,
+ )
+ assert pending.status == ImportStatus.PENDING
+
+ result = service.confirm_import(import_id=pending.id, account=_account())
+
+ assert result.status == ImportStatus.COMPLETED
+ assert result.app_created is not overwrite
+ assert (result.app_id == existing.id) is overwrite