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): enforce cloud app quotas on DSL imports (#44525)

林玮 (Jade Lin)01b54496b2e5
diff --git a/api/controllers/inner_api/app/dsl.py b/api/controllers/inner_api/app/dsl.py
index 4169a7320b4..53d816f6e0d 100644
--- a/api/controllers/inner_api/app/dsl.py
+++ b/api/controllers/inner_api/app/dsl.py
@@ -11,6 +11,7 @@ from uuid import UUID
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field, RootModel, ValidationError, field_validator
+from werkzeug.exceptions import Forbidden
from controllers.common.fields import SimpleMessageResponse
from controllers.common.schema import (
@@ -30,6 +31,7 @@ from libs.helper import dump_response
from services.entities.app_entities import AppExportOptions
from services.entities.dsl_entities import AppImportParams, Import, ImportMode, ImportStatus
from services.errors.app import AppDiscoveryNotFoundError, IsDraftWorkflowError, WorkflowNotFoundError
+from services.errors.base import NoPermissionError
class InnerAppDSLImportPayload(BaseModel):
@@ -82,6 +84,7 @@ class EnterpriseAppDSLImport(Resource):
@inner_api_ns.response(
HTTPStatus.BAD_REQUEST, "Import failed (business error)", inner_api_ns.models[Import.__name__]
)
+ @inner_api_ns.response(HTTPStatus.FORBIDDEN, "Import permission denied or app quota exceeded")
@inner_api_ns.response(
HTTPStatus.NOT_FOUND,
"Creator account not found or inactive",
@@ -90,18 +93,21 @@ class EnterpriseAppDSLImport(Resource):
def post(self, workspace_id: str):
"""Import a DSL into a workspace on behalf of a specified creator."""
args = validate_request(InnerAppDSLImportPayload)
- result = application_services().apps.imports.import_as_creator(
- workspace_id=workspace_id,
- creator_email=args.creator_email,
- params=AppImportParams(
- mode=ImportMode.YAML_CONTENT,
- yaml_content=args.yaml_content,
- name=args.name,
- description=args.description,
- ),
- request_id=get_request_id(),
- trace_id=get_trace_id(),
- )
+ try:
+ result = application_services().apps.imports.import_as_creator(
+ workspace_id=workspace_id,
+ creator_email=args.creator_email,
+ params=AppImportParams(
+ mode=ImportMode.YAML_CONTENT,
+ yaml_content=args.yaml_content,
+ name=args.name,
+ description=args.description,
+ ),
+ request_id=get_request_id(),
+ trace_id=get_trace_id(),
+ )
+ except NoPermissionError as error:
+ raise Forbidden(str(error)) from error
if result is None:
return dump_response(
SimpleMessageResponse, {"message": f"account '{args.creator_email}' not found or inactive"}
diff --git a/api/services/app/console_gateway.py b/api/services/app/console_gateway.py
index 47935a1c882..5a9730f6bc4 100644
--- a/api/services/app/console_gateway.py
+++ b/api/services/app/console_gateway.py
@@ -160,10 +160,6 @@ class ConsoleAppPermissions(AppPermissions):
class EnterpriseConsoleAppAccess(ConsoleAppAccess):
@override
def require_import(self, context: RequestContext, kind: Literal["url", "dsl", "agent"]) -> None:
- if kind == "dsl" and dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
- apps = FeatureService.get_features(context.active_workspace_id, exclude_vector_space=True).apps
- if 0 < apps.limit <= apps.size:
- raise NoPermissionError("The number of apps has reached the limit of your subscription.")
if not dify_config.RBAC_ENABLED:
return
permissions = (
diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.py
index 7beff301780..686afdd781f 100644
--- a/api/services/app_dsl_service.py
+++ b/api/services/app_dsl_service.py
@@ -39,6 +39,7 @@ from core.workflow.llm_environment_variable import (
from core.workflow.nodes.agent_v2.validators import WorkflowAgentNodeValidator
from core.workflow.nodes.knowledge_retrieval.entities import KnowledgeRetrievalNodeData
from core.workflow.nodes.trigger_schedule.trigger_schedule_node import TriggerScheduleNode
+from enums import DeploymentEdition
from events.app_event import app_model_config_was_updated, app_was_created
from extensions.ext_redis import redis_client
from factories import variable_factory
@@ -75,7 +76,7 @@ from services.entities.dsl_entities import (
make_app_dsl,
)
from services.entities.site_dsl import SiteDsl, apply_site_dsl
-from services.errors.app import DraftChangedError, WorkflowNotFoundError
+from services.errors.app import AppQuotaCheckError, DraftChangedError, WorkflowNotFoundError
from services.errors.base import NoPermissionError
from services.feature_service import FeatureService
from services.icon_configuration import (
@@ -157,6 +158,21 @@ class AppDslService:
self._session = session
self._warnings = []
+ @staticmethod
+ def _check_app_quota(account: Account) -> None:
+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
+ return
+ tenant_id = account.current_tenant_id
+ if tenant_id is None:
+ raise ValueError("Current tenant is not set")
+ try:
+ apps = FeatureService.get_features(tenant_id, exclude_vector_space=True).apps
+ except Exception as error:
+ # A failed lookup is a server failure, not an invalid DSL or exhausted quota.
+ raise AppQuotaCheckError("Unable to check the app quota.") from error
+ if 0 < apps.limit <= apps.size:
+ raise NoPermissionError("The number of apps has reached the limit of your subscription.")
+
def import_app(
self,
*,
@@ -175,7 +191,7 @@ class AppDslService:
preserve_agent_bindings: bool = False,
draft_hash: str | None = None,
) -> Import:
- """Import an App DSL after checking Site entitlements and staging archive resources.
+ """Import an App DSL after validating applicable entitlements and staging archive resources.
With ``draft_hash``, an overwrite saves only while the draft's ``draft_token`` still equals it and
raises DraftChangedError otherwise; a pending import keeps it for the confirm.
@@ -281,6 +297,9 @@ class AppDslService:
error=missing_app_section_error(original_top_level_keys),
)
+ if not app_id:
+ self._check_app_quota(account)
+
allow_premium_site_settings = True
if status != ImportStatus.PENDING and data.get("site") is not None:
# Resolve billing before archive uploads or database writes.
@@ -413,7 +432,7 @@ class AppDslService:
error=f"Invalid YAML format: {str(e)}",
)
- except (NoPermissionError, DraftChangedError):
+ except (NoPermissionError, DraftChangedError, AppQuotaCheckError):
raise
except Exception as e:
@@ -456,6 +475,9 @@ class AppDslService:
status=ImportStatus.FAILED,
error="Import information expired or does not exist",
)
+ if not pending_data.app_id:
+ # Workspace usage may have changed since the pending import was staged.
+ self._check_app_quota(account)
data = yaml.safe_load(pending_data.yaml_content)
self._warnings = list(pending_data.warnings)
@@ -508,7 +530,7 @@ class AppDslService:
warnings=self._warnings,
)
- except (NoPermissionError, DraftChangedError):
+ except (NoPermissionError, DraftChangedError, AppQuotaCheckError):
raise
except Exception as e:
diff --git a/api/services/errors/app.py b/api/services/errors/app.py
index cde92c2eb95..6e1bfa82130 100644
--- a/api/services/errors/app.py
+++ b/api/services/errors/app.py
@@ -6,6 +6,10 @@ class PermittedAppsUnavailableError(Exception):
pass
+class AppQuotaCheckError(Exception):
+ """The app quota could not be determined because its lookup failed."""
+
+
class MoreLikeThisDisabledError(Exception):
pass
diff --git a/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py b/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
index 03cb772e2ec..a400023d9a3 100644
--- a/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
+++ b/api/tests/unit_tests/controllers/console/app/test_roster_package_routes.py
@@ -196,12 +196,20 @@ def test_url_without_any_import_permission_does_not_download(
@pytest.mark.parametrize("is_yaml", [False, True])
def test_url_quota_is_enforced_after_content_detection(
- app: Flask, imports: Imports, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None], is_yaml: bool
+ app: Flask,
+ imports: Imports,
+ app_query_services: ControllerTestServices,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ is_yaml: bool,
) -> None:
config_overrides(DEPLOYMENT_EDITION="CLOUD")
+ transfers = app_query_services.apps.console._transfers
+ assert isinstance(transfers, AppTransferGateway)
+ monkeypatch.setattr(transfers, "import_dsl", AppTransferGateway.import_dsl.__get__(transfers))
features = FeatureModel(apps=LimitationModel(size=1, limit=1))
- monkeypatch.setattr("services.app.console_gateway.FeatureService.get_features", lambda *_a, **_k: features)
- _mock_download(monkeypatch, b"app: {}" if is_yaml else _roster_archive().getvalue())
+ monkeypatch.setattr("services.app_dsl_service.FeatureService.get_features", lambda *_a, **_k: features)
+ _mock_download(monkeypatch, b"app: {mode: workflow}" if is_yaml else _roster_archive().getvalue())
if is_yaml:
with pytest.raises(Forbidden, match="number of apps"):
_post(app, imports, json={"mode": "yaml-url", "yaml_url": "https://example.com/download"})
@@ -490,14 +498,22 @@ def test_package_url_rejects_ambiguous_sources(app: Flask, imports: Imports, ext
@pytest.mark.parametrize("quota", [False, True])
def test_ordinary_package_import_checks_permission_and_quota(
- app: Flask, imports: Imports, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None], quota: bool
+ app: Flask,
+ imports: Imports,
+ app_query_services: ControllerTestServices,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ quota: bool,
) -> None:
config_overrides(RBAC_ENABLED=not quota, DEPLOYMENT_EDITION="CLOUD" if quota else "COMMUNITY")
+ transfers = app_query_services.apps.console._transfers
+ assert isinstance(transfers, AppTransferGateway)
+ monkeypatch.setattr(transfers, "import_dsl", AppTransferGateway.import_dsl.__get__(transfers))
monkeypatch.setattr(
"services.app.console_gateway.rbac_service.RBACService.CheckAccess.check", lambda *_a, **_k: False
)
features = FeatureModel(apps=LimitationModel(size=1, limit=1))
- monkeypatch.setattr("services.app.console_gateway.FeatureService.get_features", lambda *_a, **_k: features)
+ monkeypatch.setattr("services.app_dsl_service.FeatureService.get_features", lambda *_a, **_k: features)
with AppPackageService().export(dsl="kind: app\napp: {mode: workflow}\n", name="Workflow") as package:
with pytest.raises(Forbidden):
_post(app, imports, data={"file": (package.archive, "workflow.ifpkg")})
diff --git a/api/tests/unit_tests/controllers/test_app_import_quota.py b/api/tests/unit_tests/controllers/test_app_import_quota.py
new file mode 100644
index 00000000000..d01fa8f3df4
--- /dev/null
+++ b/api/tests/unit_tests/controllers/test_app_import_quota.py
@@ -0,0 +1,134 @@
+"""Quota failures retain their HTTP semantics across both app import surfaces."""
+
+from collections.abc import Callable
+from inspect import unwrap
+from typing import Protocol, cast
+from uuid import uuid4
+
+import httpx
+import pytest
+from flask import Flask
+from flask_restx import Resource
+from sqlalchemy import select
+from sqlalchemy.orm import Session
+
+from constants.dsl_version import CURRENT_APP_DSL_VERSION
+from controllers.console.app import app_import as console
+from controllers.inner_api.app import dsl as inner
+from controllers.openapi import app_dsl as openapi
+from controllers.openapi._errors import OpenApiErrorFormatter
+from controllers.openapi._models import AppDslImportPayload
+from enums import DeploymentEdition
+from extensions.ext_redis import redis_client
+from libs.external_api import ExternalApi
+from machinery.context import RequestContext
+from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
+from models.model import App
+from services.app_dsl_service import AppDslService, PendingData
+from services.billing_service import BillingService, _BillingHTTPStatusError
+from services.entities.feature_entities import FeatureModel, LimitationModel
+from services.feature_service import FeatureService
+from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.controllers.conftest import ControllerTestServices
+
+
+class _EndpointView(Protocol):
+ __handler__: Callable[..., tuple[object, int]]
+
+
+ ("surface", "confirm"),
+ [("console", False), ("console", True), ("openapi", False), ("openapi", True), ("inner", False)],
+)
[email protected]("failure", ["timeout", "upstream_503", "invalid_response", "quota_exhausted"])
+def test_import_quota_failure_http_status(
+ app_query_services: ControllerTestServices,
+ sqlite_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ surface: str,
+ confirm: bool,
+ failure: str,
+) -> None:
+ apply_config_overrides(
+ monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, INNER_API=True, INNER_API_KEY="test-inner-api-key"
+ )
+ monkeypatch.setattr("controllers.console.wraps._is_setup_completed", lambda: True)
+ account = Account(name="Importer", email="[email protected]")
+ tenant = Tenant(name="Workspace")
+ account.id, tenant.id = str(uuid4()), str(uuid4())
+ sqlite_session.add_all(
+ [
+ account,
+ tenant,
+ TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=TenantAccountRole.OWNER),
+ ]
+ )
+ sqlite_session.commit()
+ context = RequestContext("request-1", None, account.id, tenant.id)
+ content = (
+ f"version: {CURRENT_APP_DSL_VERSION}\napp: {{name: Imported, mode: workflow}}\n"
+ "workflow: {graph: {nodes: [], edges: []}, features: {}}\n"
+ )
+ pending = PendingData(tenant_id=tenant.id, account_id=account.id, import_mode="yaml-content", yaml_content=content)
+ monkeypatch.setattr(redis_client, "get", lambda _: pending.model_dump_json())
+
+ def unexpected_side_effect(*_args: object, **_kwargs: object) -> None:
+ pytest.fail("A failed quota check must preserve pending data and avoid database writes")
+
+ monkeypatch.setattr(redis_client, "delete", unexpected_side_effect)
+ monkeypatch.setattr(AppDslService, "_create_or_update_app", unexpected_side_effect)
+ if failure == "quota_exhausted":
+ monkeypatch.setattr(
+ FeatureService,
+ "get_features",
+ lambda *_args, **_kwargs: FeatureModel(apps=LimitationModel(size=5, limit=5)),
+ )
+ else:
+
+ def failed_billing(*_args: object, **_kwargs: object) -> dict[str, str]:
+ if failure == "timeout":
+ raise httpx.ReadTimeout("Private billing timeout details")
+ if failure == "upstream_503":
+ raise _BillingHTTPStatusError("Private billing failure details", 503)
+ return {"subscription": "Private invalid billing response"}
+
+ monkeypatch.setattr(BillingService, "_send_request", failed_billing)
+
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ app.extensions["application_services"] = app_query_services
+ api = ExternalApi(app, error_body_formatter=OpenApiErrorFormatter() if surface == "openapi" else None)
+
+ class AdmittedImport(Resource):
+ def post(self) -> tuple[object, int]:
+ if surface == "inner":
+ return inner.EnterpriseAppDSLImport().post(workspace_id=tenant.id)
+ if surface == "console":
+ if confirm:
+ controller = console.AppImportConfirmApi()
+ return unwrap(controller.post)(controller, context, import_id="pending-1")
+ controller = console.AppImportApi()
+ return unwrap(controller.post)(controller, context)
+ if confirm:
+ controller = openapi.AppDslImportConfirmApi()
+ return cast(_EndpointView, controller.post).__handler__(
+ controller, context, workspace_id=tenant.id, import_id="pending-1"
+ )
+ controller = openapi.AppDslImportApi()
+ return cast(_EndpointView, controller.post).__handler__(
+ controller,
+ context,
+ workspace_id=tenant.id,
+ body=AppDslImportPayload(mode="yaml-content", yaml_content=content),
+ )
+
+ api.add_resource(AdmittedImport, "/imports")
+ response = app.test_client().post(
+ "/imports",
+ json={"mode": "yaml-content", "yaml_content": content, "creator_email": account.email},
+ headers={"X-Inner-Api-Key": "test-inner-api-key"},
+ )
+
+ assert response.status_code == (403 if failure == "quota_exhausted" else 500)
+ assert "Private" not in response.get_data(as_text=True)
+ assert sqlite_session.scalar(select(App.id).where(App.tenant_id == tenant.id)) is None
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 287ef0709d1..ddc2b3dedd7 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -1,5 +1,6 @@
from collections.abc import Callable
from dataclasses import dataclass, field
+from io import BytesIO
from types import SimpleNamespace
from typing import cast
from unittest.mock import Mock
@@ -14,13 +15,17 @@ from constants.dsl_version import CURRENT_APP_DSL_VERSION
from core.plugin.entities.plugin import PluginDependency, PluginDependencyType
from core.rbac import RBACPermission, RBACResourceScope
from core.workflow.llm_environment_variable import LLMEnvironmentVariable
+from enums import DeploymentEdition
from models import Account, App, AppMode
from models.enums import CustomizeTokenStrategy
from models.model import AppModelConfig, AppModelConfigDict, IconType, Site
from models.workflow import Workflow
from services.agent.dsl_entities import AgentPackage
+from services.agent.roster_package_entities import PackageIcon
from services.app_dsl_service import AppDslService, PendingData
+from services.app_package_service import PreparedAppPackage
from services.entities.dsl_entities import ImportStatus
+from services.entities.feature_entities import FeatureModel, LimitationModel
from services.entities.site_dsl import SiteDsl
from services.errors.app import DraftChangedError, WorkflowNotFoundError
from services.errors.base import NoPermissionError
@@ -95,6 +100,155 @@ def _workflow(
return make_workflow(workflow_id="workflow-1", graph=graph, environment_variables=environment_variables or [])
[email protected]("version", [CURRENT_APP_DSL_VERSION, "99.0.0"])
[email protected]("size", [5, 6])
+def test_import_rejects_cloud_app_quota_before_side_effects(
+ monkeypatch: pytest.MonkeyPatch, unbound_session: Session, version: str, size: int
+) -> None:
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+ feature_calls: list[tuple[str, bool]] = []
+
+ def features(tenant_id: str, *, exclude_vector_space: bool) -> FeatureModel:
+ feature_calls.append((tenant_id, exclude_vector_space))
+ return FeatureModel(apps=LimitationModel(size=size, limit=5))
+
+ def unexpected_side_effect(*_args: object, **_kwargs: object) -> None:
+ pytest.fail("Quota rejection must precede import side effects")
+
+ monkeypatch.setattr("services.app_dsl_service.FeatureService.get_features", features)
+ monkeypatch.setattr("services.app_dsl_service.redis_client.setex", unexpected_side_effect)
+ service = AppDslService(unbound_session)
+ monkeypatch.setattr(service, "_create_or_update_app", unexpected_side_effect)
+ package = PreparedAppPackage(
+ archive=BytesIO(),
+ members={},
+ dsl="",
+ agents={},
+ agent_resources={},
+ icons=[PackageIcon(id="i_000001", path="i_000001.png", size=0, sha256="0" * 64)],
+ )
+ monkeypatch.setattr(package, "materialize_icons", unexpected_side_effect)
+ monkeypatch.setattr(package, "materialize_agents", unexpected_side_effect)
+
+ with (
+ package,
+ pytest.raises(NoPermissionError, match="The number of apps has reached the limit of your subscription"),
+ ):
+ service.import_app(
+ account=_account(),
+ import_mode="yaml-content",
+ yaml_content=yaml.safe_dump({"version": version, "app": {"name": "Imported", "mode": "workflow"}}),
+ package=package,
+ )
+
+ assert feature_calls == [("tenant-1", True)]
+
+
[email protected]("confirmed", [False, True])
+ ("edition", "size", "limit", "overwrite"),
+ [
+ (DeploymentEdition.COMMUNITY, 5, 5, False),
+ (DeploymentEdition.ENTERPRISE, 5, 5, False),
+ (DeploymentEdition.CLOUD, 4, 5, False),
+ (DeploymentEdition.CLOUD, 5, 0, False),
+ (DeploymentEdition.CLOUD, 5, 5, True),
+ ],
+)
+def test_import_app_quota_allows_other_editions_available_capacity_and_overwrites(
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_session: Session,
+ confirmed: bool,
+ edition: DeploymentEdition,
+ size: int,
+ limit: int,
+ overwrite: bool,
+) -> None:
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=edition)
+ feature_calls: list[tuple[str, bool]] = []
+
+ def features(tenant_id: str, *, exclude_vector_space: bool) -> FeatureModel:
+ feature_calls.append((tenant_id, exclude_vector_space))
+ return FeatureModel(apps=LimitationModel(size=size, limit=limit))
+
+ monkeypatch.setattr("services.app_dsl_service.FeatureService.get_features", features)
+ monkeypatch.setattr(
+ "services.app_dsl_service.WorkflowDraftVariableService.delete_app_workflow_variables",
+ lambda *_args, **_kwargs: None,
+ )
+ service = AppDslService(sqlite_session)
+ app = _app(mode=AppMode.WORKFLOW)
+ imported: list[App] = []
+
+ def create_or_update(**_kwargs: object) -> App:
+ imported.append(app)
+ return app
+
+ monkeypatch.setattr(service, "_create_or_update_app", create_or_update)
+ monkeypatch.setattr(service, "_load_app_for_overwrite", lambda *_args: app)
+ pending = PendingData(
+ tenant_id="tenant-1",
+ account_id="account-1",
+ import_mode="yaml-content",
+ yaml_content=yaml.safe_dump(
+ {"version": CURRENT_APP_DSL_VERSION, "app": {"name": "Imported", "mode": "workflow"}}
+ ),
+ app_id=app.id if overwrite else None,
+ )
+
+ if confirmed:
+ monkeypatch.setattr("services.app_dsl_service.redis_client.get", lambda _: pending.model_dump_json())
+ result = service.confirm_import(import_id="pending", account=_account())
+ else:
+ result = service.import_app(
+ account=_account(),
+ import_mode=pending.import_mode,
+ yaml_content=pending.yaml_content,
+ app_id=pending.app_id,
+ )
+
+ assert result.status == ImportStatus.COMPLETED, result.error
+ assert imported == [app]
+ assert feature_calls == ([("tenant-1", True)] if edition == DeploymentEdition.CLOUD and not overwrite else [])
+
+
+def test_confirm_import_rechecks_cloud_app_quota_and_preserves_pending_on_rejection(
+ monkeypatch: pytest.MonkeyPatch, unbound_session: Session
+) -> None:
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+ features = FeatureModel(apps=LimitationModel(size=4, limit=5))
+ monkeypatch.setattr("services.app_dsl_service.FeatureService.get_features", lambda *_args, **_kwargs: features)
+ 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)
+ service = AppDslService(unbound_session)
+ imported: list[App] = []
+
+ def create_or_update(**_kwargs: object) -> App:
+ app = _app(mode=AppMode.WORKFLOW)
+ imported.append(app)
+ return app
+
+ monkeypatch.setattr(service, "_create_or_update_app", create_or_update)
+ pending = service.import_app(account=_account(), import_mode="yaml-content", yaml_content=_PENDING_WORKFLOW_DSL)
+ assert pending.status == ImportStatus.PENDING
+
+ features.apps.size = 5
+ with pytest.raises(NoPermissionError, match="The number of apps has reached the limit of your subscription"):
+ service.confirm_import(import_id=pending.id, account=_account())
+ assert not imported
+ assert f"app_import_info:{pending.id}" in pending_imports
+
+ features.apps.size = 4
+ assert service.confirm_import(import_id=pending.id, account=_account()).status == ImportStatus.COMPLETED
+ assert len(imported) == 1
+ assert f"app_import_info:{pending.id}" not in pending_imports
+
+
def test_extract_workflow_dependencies_includes_plugin_nodes(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
"services.app_dsl_service.ToolNodeData.model_validate",
@@ -383,7 +537,11 @@ def test_pending_import_is_scoped_to_its_owner(monkeypatch: pytest.MonkeyPatch,
assert redis_key not in pending_imports
-def test_pending_import_requires_current_tenant(monkeypatch: pytest.MonkeyPatch, unbound_session: Session) -> None:
[email protected]("edition", [DeploymentEdition.COMMUNITY, DeploymentEdition.CLOUD])
+def test_pending_import_requires_current_tenant(
+ monkeypatch: pytest.MonkeyPatch, unbound_session: Session, edition: DeploymentEdition
+) -> None:
+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=edition)
setex = Mock()
monkeypatch.setattr("services.app_dsl_service.redis_client.setex", setex)
account = _account()