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(openapi): inject file upload service (#41606)

非法操作d8c3f7c5ee7a
diff --git a/api/controllers/openapi/files.py b/api/controllers/openapi/files.py
index 3b3f68fa36b..ab9e3455bb3 100644
--- a/api/controllers/openapi/files.py
+++ b/api/controllers/openapi/files.py
@@ -20,10 +20,9 @@ from controllers.openapi._contract import returns
from controllers.openapi._errors import FilenameNotExists
from controllers.openapi.auth.composition import auth_router
from controllers.openapi.auth.data import AuthData
-from extensions.ext_database import db
+from extensions.ext_application_services import application_services
from fields.file_fields import FileResponse
from libs.oauth_bearer import Scope
-from services.file_service import FileService
@openapi_ns.route("/apps/<string:app_id>/files")
@@ -33,16 +32,16 @@ class AppFileUploadApi(Resource):
@openapi_ns.doc(
responses={
201: "File uploaded successfully",
- 400: "Bad request — no file or filename missing",
+ 400: "Bad request — no file, multiple files, invalid filename, or blocked extension",
401: "Unauthorized — invalid or expired bearer token",
413: "File too large",
- 415: "Unsupported file type or blocked extension",
+ 415: "Unsupported file type",
}
)
@auth_router.guard(scope=Scope.APPS_RUN)
@returns(HTTPStatus.CREATED, FileResponse, description="File uploaded")
- def post(self, app_id: str, *, auth_data: AuthData):
- app_model, caller, _ = auth_data.require_app_context()
+ def post(self, app_id: str, *, auth_data: AuthData) -> FileResponse:
+ _app_model, caller, _caller_kind = auth_data.require_app_context()
if "file" not in request.files:
raise NoFileUploadedError()
if len(request.files) > 1:
@@ -55,19 +54,19 @@ class AppFileUploadApi(Resource):
raise FilenameNotExists()
try:
- upload_file = FileService(db.engine).upload_file(
+ upload_file = application_services().files.upload_file(
filename=file.filename,
content=file.stream.read(),
mimetype=file.mimetype,
user=caller,
)
- except ValueError as exc:
- raise BadRequest(str(exc))
except services.errors.file.FileTooLargeError as exc:
- raise FileTooLargeError(exc.description)
- except services.errors.file.UnsupportedFileTypeError:
- raise UnsupportedFileTypeError()
+ raise FileTooLargeError(exc.description) from exc
+ except services.errors.file.UnsupportedFileTypeError as exc:
+ raise UnsupportedFileTypeError() from exc
except services.errors.file.BlockedFileExtensionError as exc:
- raise BlockedFileExtensionError(exc.description)
+ raise BlockedFileExtensionError(exc.description) from exc
+ except ValueError as exc:
+ raise BadRequest(str(exc)) from exc
return FileResponse.model_validate(upload_file, from_attributes=True)
diff --git a/api/openapi/markdown/openapi-openapi.md b/api/openapi/markdown/openapi-openapi.md
index 5d2c1850c73..a793cbcd2b9 100644
--- a/api/openapi/markdown/openapi-openapi.md
+++ b/api/openapi/markdown/openapi-openapi.md
@@ -154,10 +154,10 @@ Upload a file to use as an input variable when running the app
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | File uploaded successfully | **application/json**: [FileResponse](#fileresponse)<br> |
-| 400 | Bad request — no file or filename missing | |
+| 400 | Bad request — no file, multiple files, invalid filename, or blocked extension | |
| 401 | Unauthorized — invalid or expired bearer token | |
| 413 | File too large | |
-| 415 | Unsupported file type or blocked extension | |
+| 415 | Unsupported file type | |
| default | Error | **application/json**: [ErrorBody](#errorbody)<br> |
### [GET] /apps/{app_id}/human-input-forms/{form_token}
diff --git a/api/tests/unit_tests/controllers/openapi/test_files.py b/api/tests/unit_tests/controllers/openapi/test_files.py
new file mode 100644
index 00000000000..2ced95bfea4
--- /dev/null
+++ b/api/tests/unit_tests/controllers/openapi/test_files.py
@@ -0,0 +1,156 @@
+from inspect import unwrap
+from io import BytesIO
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from flask import Flask
+from werkzeug.exceptions import BadRequest
+
+from controllers.common.errors import (
+ BlockedFileExtensionError,
+ FileTooLargeError,
+ UnsupportedFileTypeError,
+)
+from controllers.openapi.auth.data import AuthData, CallerKind
+from controllers.openapi.files import AppFileUploadApi
+from libs.exception import BaseHTTPException
+from libs.oauth_bearer import Scope, TokenType
+from models import Account
+from services.errors.file import BlockedFileExtensionError as ServiceBlockedFileExtensionError
+from services.errors.file import FileTooLargeError as ServiceFileTooLargeError
+from services.errors.file import UnsupportedFileTypeError as ServiceUnsupportedFileTypeError
+
+
+def _auth_data(caller: Account) -> AuthData:
+ return AuthData.model_construct(
+ token_type=TokenType.OAUTH_ACCOUNT,
+ token_hash="test-token",
+ scopes=frozenset({Scope.APPS_RUN}),
+ app=object(),
+ caller=caller,
+ caller_kind=CallerKind.ACCOUNT,
+ )
+
+
+def _caller() -> Account:
+ caller = Account(name="Uploader", email="[email protected]")
+ caller.id = "account-1"
+ return caller
+
+
+def _upload_result() -> SimpleNamespace:
+ return SimpleNamespace(
+ id="00000000-0000-0000-0000-000000000001",
+ name="note.txt",
+ size=5,
+ extension="txt",
+ mime_type="text/plain",
+ )
+
+
+def _file_service(monkeypatch: pytest.MonkeyPatch) -> Mock:
+ from controllers.openapi import files as module
+
+ service = Mock()
+ monkeypatch.setattr(module, "application_services", lambda: SimpleNamespace(files=service))
+ return service
+
+
+def test_upload_uses_injected_file_service(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
+ service = _file_service(monkeypatch)
+ service.upload_file.return_value = _upload_result()
+ caller = _caller()
+
+ with app.test_request_context(
+ "/openapi/v1/apps/app-1/files",
+ method="POST",
+ data={"file": (BytesIO(b"hello"), "note.txt", "text/plain")},
+ content_type="multipart/form-data",
+ ):
+ result = unwrap(AppFileUploadApi.post)(
+ AppFileUploadApi(),
+ app_id="app-1",
+ auth_data=_auth_data(caller),
+ )
+
+ assert result.id == "00000000-0000-0000-0000-000000000001"
+ service.upload_file.assert_called_once_with(
+ filename="note.txt",
+ content=b"hello",
+ mimetype="text/plain",
+ user=caller,
+ )
+
+
+ ("service_error", "controller_error", "status", "error_code", "message"),
+ [
+ (ServiceFileTooLargeError("too large"), FileTooLargeError, 413, "file_too_large", "too large"),
+ (
+ ServiceUnsupportedFileTypeError(),
+ UnsupportedFileTypeError,
+ 415,
+ "unsupported_file_type",
+ "File type not allowed.",
+ ),
+ (
+ ServiceBlockedFileExtensionError("blocked extension"),
+ BlockedFileExtensionError,
+ 400,
+ "file_extension_blocked",
+ "blocked extension",
+ ),
+ ],
+)
+def test_upload_preserves_specific_file_errors(
+ app: Flask,
+ monkeypatch: pytest.MonkeyPatch,
+ service_error: ValueError,
+ controller_error: type[BaseHTTPException],
+ status: int,
+ error_code: str,
+ message: str,
+) -> None:
+ service = _file_service(monkeypatch)
+ service.upload_file.side_effect = service_error
+
+ with app.test_request_context(
+ "/openapi/v1/apps/app-1/files",
+ method="POST",
+ data={"file": (BytesIO(b"hello"), "note.txt", "text/plain")},
+ content_type="multipart/form-data",
+ ):
+ with pytest.raises(controller_error) as error_info:
+ unwrap(AppFileUploadApi.post)(
+ AppFileUploadApi(),
+ app_id="app-1",
+ auth_data=_auth_data(_caller()),
+ )
+
+ assert error_info.value.code == status
+ assert error_info.value.error_code == error_code
+ assert error_info.value.data == {"code": error_code, "message": message, "status": status}
+ assert error_info.value.__cause__ is service_error
+
+
+def test_upload_maps_other_value_errors_to_bad_request(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
+ service = _file_service(monkeypatch)
+ service_error = ValueError("Filename contains invalid characters")
+ service.upload_file.side_effect = service_error
+
+ with app.test_request_context(
+ "/openapi/v1/apps/app-1/files",
+ method="POST",
+ data={"file": (BytesIO(b"hello"), "../note.txt", "text/plain")},
+ content_type="multipart/form-data",
+ ):
+ with pytest.raises(BadRequest) as error_info:
+ unwrap(AppFileUploadApi.post)(
+ AppFileUploadApi(),
+ app_id="app-1",
+ auth_data=_auth_data(_caller()),
+ )
+
+ assert error_info.value.description == str(service_error)
+ assert error_info.value.__cause__ is service_error