chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,121 @@
from __future__ import annotations
import uuid
from collections.abc import Callable, Sequence
from unittest.mock import patch
import pytest
from faker import Faker
from flask import Flask
from sqlalchemy.orm import Session
from constants.oauth_bearer import TokenType
from controllers.openapi.auth.context import Context
from controllers.openapi.auth.loaders import PathParam, load_app
from controllers.openapi.auth.requirements import Requirement, ResolveCaller
from controllers.openapi.auth.subjects import subject_from_auth
from libs.oauth_bearer import AuthContext
from models import Account, Tenant
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
from tests.e2e_tests.containers.helpers import generate_valid_password
_CLIENT_ID = "integration-cli"
@pytest.fixture
def app(flask_app_with_containers: Flask) -> Flask:
return flask_app_with_containers
@pytest.fixture
def make_account(db_session_with_containers: Session) -> Callable[..., Account]:
"""Factory that registers a real Account and gives it an owner workspace.
System feature gates are stubbed (registration / workspace creation
allowed) exactly like the AppDslService integration tests, so this stays a
pure account+tenant setup helper.
"""
# Depend on db_session_with_containers so the app context / DB session is
# active for the composed account and workspace services below.
assert db_session_with_containers is not None
def _make(*, with_owner_tenant: bool = True) -> Account:
fake = Faker()
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
mock_feature_service.is_registration_allowed.return_value = True
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
if with_owner_tenant:
account_fixtures.create_owner_workspace(
account, name=fake.company(), session=db_session_with_containers
)
return account
return _make
def add_tenant_for_account(
account: Account, *, session: Session, role: str = "normal", name: str = "Second WS"
) -> Tenant:
"""Create an additional tenant and join ``account`` to it (real service calls)."""
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
mock_feature_service.is_workspace_creation_allowed.return_value = True
tenant = account_fixtures.create_workspace(name=name, session=session)
account_fixtures.join_workspace(tenant, account, session, role=role)
return tenant
def _account_auth(
account: Account,
*,
token_id: uuid.UUID | None = None,
client_id: str = _CLIENT_ID,
) -> AuthContext:
"""The ``AuthContext`` a live ``dfoa_`` token for ``account`` would carry."""
return AuthContext(
subject_email=account.email,
subject_issuer=None,
account_id=uuid.UUID(str(account.id)),
client_id=client_id,
token_id=token_id or uuid.uuid4(),
token_type=TokenType.OAUTH_ACCOUNT,
expires_at=None,
)
def context_for(
account: Account,
*,
session: Session,
view_args: dict[str, str] | None = None,
token_id: uuid.UUID | None = None,
requirements: Sequence[Requirement] = (),
) -> Context:
"""Build the ``Context`` a handler is given after the pipeline ran.
The subject comes from a real ``AuthContext`` through ``subject_from_auth``,
so the helper walks the same resolution path the router does. ``view_args``
is the route's path params — the app and the workspace are loaded from it,
so a route carrying ``<app_id>`` needs ``{"app_id": ...}`` here.
``token_id`` only matters to the ``/account/sessions*`` family, which reads
it back off the subject.
Pass the route's context-loading requirements, such as
``CheckWorkspaceMember``, to bind the caller to its requested workspace.
They run alongside the pipeline's fixed ``ResolveCaller`` in rank order;
the caller is freshly loaded and does not inherit ``account.current_tenant``.
App routes also load their app, as ``CheckAppApiEnabled`` does before the
handler runs. Authorization itself is covered by the auth-layer tests.
"""
ctx = Context(subject_from_auth(_account_auth(account, token_id=token_id)), session, view_args or {})
if PathParam.APP_ID in ctx.view_args:
load_app(ctx)
for requirement in sorted((*requirements, ResolveCaller()), key=lambda item: item.rank):
requirement.run(ctx.subject, ctx, session)
return ctx
@@ -0,0 +1,54 @@
from __future__ import annotations
from collections.abc import Callable
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi.account import AccountApi
from models import Account
from models.account import TenantAccountRole
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
class TestAccountInfo:
def test_returns_account_and_owner_workspace(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
api = AccountApi()
with app.test_request_context("/openapi/v1/account"):
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
assert result.subject_type == "account"
assert result.subject_email == account.email
assert result.account is not None
assert result.account.id == account.id
assert result.account.email == account.email
workspaces = {w.id: w for w in result.workspaces}
assert set(workspaces) == {owner_tenant.id}
assert workspaces[owner_tenant.id].role == TenantAccountRole.OWNER.value
# No membership is flagged `current` yet, so the default falls back to
# the only workspace the account belongs to.
assert result.default_workspace_id == owner_tenant.id
def test_lists_all_joined_workspaces(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
api = AccountApi()
with app.test_request_context("/openapi/v1/account"):
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
assert {w.id for w in result.workspaces} == {owner_tenant.id, second.id}
roles = {w.id: w.role for w in result.workspaces}
assert roles[owner_tenant.id] == TenantAccountRole.OWNER.value
assert roles[second.id] == "normal"
@@ -0,0 +1,153 @@
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from constants.oauth_bearer import TokenType
from controllers.openapi._models import SessionListQuery
from controllers.openapi.account import (
AccountSessionByIdApi,
AccountSessionsApi,
AccountSessionsSelfApi,
)
from models import Account
from models.oauth import OAuthAccessToken
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
@dataclass(frozen=True, slots=True)
class _MintResult:
token_id: UUID
def _mint_account_token(
db_session: Session,
account: Account,
*,
client_id: str = "integration-cli",
device_label: str = "Test Device",
) -> _MintResult:
"""Mint a real, persisted ``dfoa_`` access token for ``account``."""
record = OAuthAccessToken(
subject_email=account.email,
subject_issuer="dify:account",
account_id=str(account.id),
client_id=client_id,
device_label=device_label,
prefix=TokenType.OAUTH_ACCOUNT.prefix,
token_hash=f"integration-{uuid4().hex}",
expires_at=datetime.now(UTC) + timedelta(days=14),
)
db_session.add(record)
db_session.commit()
return _MintResult(token_id=UUID(str(record.id)))
class TestSessionList:
def test_lists_active_session(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account, device_label="Laptop")
api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
result = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
query=SessionListQuery(),
)
assert result.total == 1
row = result.data[0]
assert row.id == str(mint.token_id)
assert row.prefix == TokenType.OAUTH_ACCOUNT.prefix
assert row.device_label == "Laptop"
def test_excludes_other_accounts_sessions(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""Sessions are subject-scoped: another account's token must not appear."""
account = make_account()
other = make_account()
mine = _mint_account_token(db_session_with_containers, account)
_mint_account_token(db_session_with_containers, other)
api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
result = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, token_id=mine.token_id),
query=SessionListQuery(),
)
assert {row.id for row in result.data} == {str(mine.token_id)}
class TestSessionRevoke:
def test_revoke_self_removes_from_active_list(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account)
revoke_api = AccountSessionsSelfApi()
with app.test_request_context("/openapi/v1/account/sessions/self", method="DELETE"):
result = revoke_api.delete.__handler__(
revoke_api, context_for(account, session=db_session_with_containers, token_id=mint.token_id)
)
assert result.status == "revoked"
# Revocation persisted: the real list path no longer returns it.
list_api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
listing = list_api.get.__handler__(
list_api,
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
query=SessionListQuery(),
)
assert listing.total == 0
def test_revoke_by_id_for_own_session(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account)
session_id = str(mint.token_id)
api = AccountSessionByIdApi()
ctx = context_for(
account,
session=db_session_with_containers,
view_args={"session_id": session_id},
token_id=mint.token_id,
)
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
result = api.delete.__handler__(api, ctx, session_id)
assert result.status == "revoked"
def test_revoke_foreign_session_is_404(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A token id owned by another subject must be indistinguishable from a
missing one (404), so token ids can't be probed across subjects. The
access service makes that call; the handler only maps it to 404."""
owner = make_account()
outsider = make_account()
foreign = _mint_account_token(db_session_with_containers, owner)
session_id = str(foreign.token_id)
ctx = context_for(outsider, session=db_session_with_containers, view_args={"session_id": session_id})
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
api = AccountSessionByIdApi()
with pytest.raises(NotFound):
api.delete.__handler__(api, ctx, session_id)
@@ -0,0 +1,287 @@
from __future__ import annotations
import json
from collections.abc import Callable, Generator
from typing import Protocol, cast
from unittest.mock import patch
from uuid import uuid4
import pytest
import yaml
from faker import Faker
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi._errors import DraftNotFound
from controllers.openapi._models import AppDslExportQuery, AppDslExportResponse, AppDslImportPayload
from controllers.openapi.app_dsl import (
AppDslCheckDependenciesApi,
AppDslExportApi,
AppDslImportApi,
AppDslImportConfirmApi,
)
from machinery.context import AppRequestContext, RequestContext
from models import Account, App
from models.model import AppMode, AppModelConfig
from services.app_dsl_service import CURRENT_DSL_VERSION
from services.app_service import AppService, CreateAppParams
from services.entities.dsl_entities import CheckDependenciesResult, Import, ImportStatus
from services.errors.app import WorkflowNotFoundError
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
from tests.e2e_tests.containers.helpers import generate_valid_password
class _Endpoint[T](Protocol):
__handler__: Callable[..., T]
def _workflow_yaml(*, version: str = CURRENT_DSL_VERSION, name: str = "My App") -> str:
return yaml.safe_dump(
{
"version": version,
"kind": "app",
"app": {"name": name, "mode": "workflow"},
"workflow": {"graph": {"nodes": []}, "features": {}},
},
allow_unicode=True,
)
@pytest.fixture
def external_deps() -> Generator[dict[str, object]]:
"""Stub the heavy collaborators an import/export touches (model runtime,
workflow sync, dependency analysis, enterprise hooks) while leaving the DSL
service and DB writes real."""
with (
patch("services.app_dsl_service.WorkflowService") as mock_workflow_service,
patch("services.app_dsl_service.DependenciesAnalysisService") as mock_dependencies_service,
patch("services.app_dsl_service.app_was_created") as mock_app_was_created,
patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,
patch("services.app_service.SystemFeatureService") as mock_feature_service,
patch("services.app_service.EnterpriseService") as mock_enterprise_service,
):
mock_workflow_service.get_draft_workflow.return_value = None
mock_workflow_service.get_published_workflow_by_id.return_value = None
mock_workflow_service.return_value.get_draft_workflow.return_value = None
mock_workflow_service.return_value.sync_draft_workflow.return_value = None
mock_dependencies_service.generate_latest_dependencies.return_value = [] # type: ignore[assignment]
mock_dependencies_service.get_leaked_dependencies.return_value = [] # type: ignore[assignment]
mock_dependencies_service.generate_dependencies.return_value = [] # type: ignore[assignment]
mock_app_was_created.send.return_value = None
mock_model_instance = mock_model_manager.return_value
mock_model_instance.get_default_model_instance.return_value = None
mock_model_instance.get_default_provider_model_name.return_value = ("openai", "gpt-3.5-turbo")
mock_feature_service.is_webapp_auth_enabled.return_value = False
mock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = None
mock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None
yield {"workflow_service": mock_workflow_service}
def _app_and_account(db_session: Session, *, mode: str = "chat") -> tuple[App, Account]:
fake = Faker()
with patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service:
mock_account_feature_service.is_registration_allowed.return_value = True
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session)
tenant = account.current_tenant
assert tenant is not None
app_args = CreateAppParams(
name=fake.company(),
description=fake.text(max_nb_chars=100),
mode=mode, # type: ignore[arg-type]
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
api_rph=100,
api_rpm=10,
)
app_model = AppService().create_app(tenant.id, app_args, account, session=db_session)
return app_model, account
class TestDslImport:
def test_invalid_dsl_maps_to_400_and_persists_nothing(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content="[]") # not a mapping
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 400
assert result.status == ImportStatus.FAILED
# A failed import must not leave an app behind.
assert db_session_with_containers.query(App).filter(App.tenant_id == tenant.id).count() == 0
def test_major_version_mismatch_maps_to_202_pending(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(version="99.0.0"))
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 202
assert result.status == ImportStatus.PENDING
assert result.id # a pending import id the caller can confirm with
def test_valid_dsl_maps_to_200_completed(
self,
app: Flask,
db_session_with_containers: Session,
make_account: Callable[..., Account],
external_deps: dict[str, object],
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(name="Imported"))
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 200
assert result.status in (ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS)
assert result.app_id is not None
class TestDslImportConfirm:
def test_unknown_pending_import_maps_to_400(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""An expired/unknown import id has no Redis pending data → FAILED → 400."""
account = make_account()
tenant = account.current_tenant
assert tenant is not None
import_id = str(uuid4())
api = AppDslImportConfirmApi()
with app.test_request_context(
f"/openapi/v1/workspaces/{tenant.id}/apps/imports/{import_id}:confirm", method="POST"
):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
import_id,
)
assert code == 400
assert result.status == ImportStatus.FAILED
class TestDslExport:
def test_export_returns_dsl_yaml(
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
) -> None:
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
model_config = AppModelConfig(
app_id=app_model.id,
provider="openai",
model_id="gpt-3.5-turbo",
model=json.dumps({"provider": "openai", "name": "gpt-3.5-turbo", "mode": "chat", "completion_params": {}}),
pre_prompt="You are a helpful assistant.",
prompt_type="simple", # type: ignore[arg-type]
created_by=account.id,
updated_by=account.id,
)
model_config.id = str(uuid4())
app_model.app_model_config_id = model_config.id
db_session_with_containers.add(model_config)
db_session_with_containers.commit()
api = AppDslExportApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):
response, code = cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDslExportQuery(),
)
assert code == 200
assert isinstance(response, AppDslExportResponse)
parsed = yaml.safe_load(response.data)
assert parsed["kind"] == "app"
assert parsed["app"]["name"] == app_model.name
def test_export_workflow_app_without_draft_maps_to_404(
self, app: Flask, db_session_with_containers: Session
) -> None:
"""A workflow app with no draft workflow can't be exported → the service
raises WorkflowNotFoundError, which the controller maps to 404 draft_not_found."""
app_model = App(
id=str(uuid4()),
tenant_id=str(uuid4()),
name="Workflow without draft",
mode=AppMode.WORKFLOW,
enable_api=True,
enable_site=False,
)
db_session_with_containers.add(app_model)
db_session_with_containers.commit()
api = AppDslExportApi()
with (
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"),
pytest.raises(DraftNotFound) as exc_info,
):
cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDslExportQuery(),
)
assert isinstance(exc_info.value.__cause__, WorkflowNotFoundError)
class TestDslCheckDependencies:
def test_check_dependencies_returns_result(
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
) -> None:
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
api = AppDslCheckDependenciesApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dependencies:check"):
result, code = cast(_Endpoint[tuple[CheckDependenciesResult, int]], api.get).__handler__(
api,
RequestContext("test-request", None, account.id, app_model.tenant_id),
app_model.id,
)
assert code == 200
assert result.leaked_dependencies == []
@@ -0,0 +1,55 @@
from __future__ import annotations
from collections.abc import Callable
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi._errors import RunNotFound
from controllers.openapi.app_run import AppRunStopApi
from models import Account, App
from services.app_service import AppService, CreateAppParams
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
def _create_app(db_session: Session, account: Account, *, name: str = "Runner") -> App:
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
db_session.commit()
return app_model
class TestAppRunStop:
def test_run_stop_rejects_an_unknown_run(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
app_model = _create_app(db_session_with_containers, account)
run_id = str(uuid4())
api = AppRunStopApi()
with (
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/runs/{run_id}:stop", method="POST"),
pytest.raises(RunNotFound),
):
api.post.__handler__( # pyrefly: ignore[missing-attribute]
api,
context_for(
account,
session=db_session_with_containers,
view_args={"app_id": app_model.id, "run_id": run_id},
),
app_model.id,
run_id,
)
@@ -0,0 +1,161 @@
from __future__ import annotations
from collections.abc import Callable
from typing import Protocol, cast
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from controllers.openapi._models import AppDescribeQuery, AppDescribeResponse, AppListQuery, AppListResponse
from controllers.openapi.apps import AppDescribeApi, AppListApi
from machinery.context import AppRequestContext, RequestContext
from models import Account, App
from services.app_service import AppService, CreateAppParams
class _Endpoint[T](Protocol):
__handler__: Callable[..., T]
def _create_app(
db_session: Session,
account: Account,
*,
name: str,
enable_api: bool = True,
) -> App:
"""Create a workflow app in the account's owner tenant.
Workflow mode is used because its template seeds no ``model_config``, so
``AppService.create_app`` never reaches ``ModelManager`` — keeping the
fixture free of model-runtime patching.
"""
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
# The openapi surface gate keys off ``enable_api``; flip it explicitly so
# the test states the visibility precondition rather than relying on the
# template default.
app_model.enable_api = enable_api
db_session.add(app_model)
db_session.commit()
return app_model
class TestAppList:
def test_lists_only_api_enabled_apps_in_workspace(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
visible = _create_app(db_session_with_containers, account, name="Visible", enable_api=True)
_create_app(db_session_with_containers, account, name="Hidden", enable_api=False)
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, account.id, tenant.id),
query=AppListQuery(workspace_id=str(tenant.id)),
)
# The api-disabled app is gated out, so it counts neither in `data`
# nor in `total` (the gate is pushed into the query for stable paging).
assert result.total == 1
assert [row.id for row in result.data] == [visible.id]
assert result.has_more is False
def test_uuid_name_filter_returns_matching_app(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
target = _create_app(db_session_with_containers, account, name="Target", enable_api=True)
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}&name={target.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, account.id, tenant.id),
query=AppListQuery(workspace_id=str(tenant.id), name=str(target.id)),
)
assert result.total == 1
assert result.data[0].id == target.id
assert result.data[0].workspace_id == str(tenant.id)
def test_uuid_name_filter_for_foreign_app_returns_empty(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A UUID that resolves to an app in another workspace must not leak
across tenants — the list returns empty rather than the foreign app."""
owner = make_account()
outsider = make_account()
foreign_app = _create_app(db_session_with_containers, owner, name="Foreign", enable_api=True)
outsider_tenant = outsider.current_tenant
assert outsider_tenant is not None
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={outsider_tenant.id}&name={foreign_app.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, outsider.id, outsider_tenant.id),
query=AppListQuery(workspace_id=str(outsider_tenant.id), name=str(foreign_app.id)),
)
assert result.total == 0
assert result.data == []
class TestAppDescribe:
def test_describe_info_returns_metadata(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
app_model = _create_app(db_session_with_containers, account, name="Describe Me", enable_api=True)
api = AppDescribeApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}?fields=info"):
result = cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDescribeQuery(fields="info"),
)
assert result.info is not None
assert result.info.id == app_model.id
assert result.info.name == "Describe Me"
assert result.info.service_api_enabled is True
# Only the requested block is materialized.
assert result.parameters is None
assert result.input_schema is None
def test_describe_unknown_app_is_404(self, app: Flask, make_account: Callable[..., Account]) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
missing_id = str(uuid4())
api = AppDescribeApi()
with app.test_request_context(f"/openapi/v1/apps/{missing_id}"):
with pytest.raises(NotFound):
cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
api,
AppRequestContext(tenant_id=tenant.id, app_id=missing_id),
missing_id,
query=AppDescribeQuery(),
)
@@ -0,0 +1,68 @@
from __future__ import annotations
from collections.abc import Callable
from io import BytesIO
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.datastructures import FileStorage
from controllers.openapi._models import FileUploadPayload
from controllers.openapi.auth.requirements import CheckWorkspaceMember
from controllers.openapi.files import AppFileUploadApi
from models import Account, App
from services.app_service import AppService, CreateAppParams
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
def _create_app(db_session: Session, account: Account, *, name: str = "Uploader") -> App:
"""Create a workflow app (no model_config → no ModelManager) for the upload context."""
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
db_session.commit()
return app_model
class TestAppFileUpload:
def test_upload_persists_and_returns_metadata(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
app_model = _create_app(db_session_with_containers, account)
content = b"hello integration world"
api = AppFileUploadApi()
body = FileUploadPayload(
file=FileStorage(stream=BytesIO(content), filename="note.txt", content_type="text/plain")
)
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/files", method="POST"):
result = vars(api.post)["__handler__"](
api,
context_for(
account,
session=db_session_with_containers,
view_args={"app_id": app_model.id},
requirements=(CheckWorkspaceMember(),),
),
app_model.id,
body=body,
)
assert result.id
assert result.name == "note.txt"
assert result.size == len(content)
assert result.extension == "txt"
assert result.mime_type == "text/plain"
# Persisted under the caller's tenant.
assert result.tenant_id == str(tenant.id)
@@ -0,0 +1,95 @@
from __future__ import annotations
from collections.abc import Callable
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from controllers.openapi._models import WorkspaceListQuery
from controllers.openapi.workspaces import WorkspaceByIdApi, WorkspacesApi
from models import Account
from models.account import TenantAccountRole
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
class TestWorkspacesList:
def test_lists_only_members_workspaces_with_role(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
api = WorkspacesApi()
with app.test_request_context("/openapi/v1/workspaces"):
result = api.get.__handler__(
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
)
ids = {w.id for w in result.data}
assert ids == {owner_tenant.id}
only = result.data[0]
assert only.role == TenantAccountRole.OWNER.value
assert only.status == "normal"
def test_lists_all_joined_workspaces(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
api = WorkspacesApi()
with app.test_request_context("/openapi/v1/workspaces"):
result = api.get.__handler__(
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
)
assert {w.id for w in result.data} == {owner_tenant.id, second.id}
class TestWorkspaceDetail:
def test_member_can_read_detail(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = WorkspaceByIdApi()
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}"):
detail = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, view_args={"workspace_id": tenant.id}),
tenant.id,
)
assert detail.id == tenant.id
assert detail.role == TenantAccountRole.OWNER.value
assert detail.created_at is not None
def test_non_member_detail_is_404_not_403(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A workspace the caller doesn't belong to must be indistinguishable
from a missing one (404), so IDs can't be probed across tenants."""
owner = make_account()
outsider = make_account()
someone_elses_ws = owner.current_tenant
assert someone_elses_ws is not None
api = WorkspaceByIdApi()
with app.test_request_context(f"/openapi/v1/workspaces/{someone_elses_ws.id}"):
with pytest.raises(NotFound):
api.get.__handler__(
api,
context_for(
outsider,
session=db_session_with_containers,
view_args={"workspace_id": someone_elses_ws.id},
),
someone_elses_ws.id,
)