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(api): dep-inject the last three GET query models with @model_validate (#42318)

Eddy ZHANGf66773b63ce0
diff --git a/api/controllers/console/auth/activate.py b/api/controllers/console/auth/activate.py
index 69ed1899f2e..685342d5a67 100644
--- a/api/controllers/console/auth/activate.py
+++ b/api/controllers/console/auth/activate.py
@@ -7,6 +7,7 @@ from controllers.common.schema import query_params_from_model, register_schema_m
from controllers.console import console_ns
from controllers.console.auth.error import InvitationAccountMismatchError as InvitationAccountMismatchHTTPError
from controllers.console.error import AccountInFreezeError, AlreadyActivateError, EmailDomainSuspendedError
+from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from libs.helper import EmailStr, dump_response, timezone
from libs.login import current_account_with_tenant
@@ -88,8 +89,8 @@ class ActivateCheckApi(Resource):
"Success",
console_ns.models[ActivationCheckResponse.__name__],
)
- def get(self):
- args = ActivateCheckQuery.model_validate(request.args.to_dict(flat=True))
+ @model_validate(ActivateCheckQuery)
+ def get(self, args: ActivateCheckQuery):
result = application_services().account_activation.check(
InvitationLookup(
workspace_id=args.workspace_id,
diff --git a/api/controllers/files/upload_file_delivery.py b/api/controllers/files/upload_file_delivery.py
index 044e2c1a8fa..e1424d383d7 100644
--- a/api/controllers/files/upload_file_delivery.py
+++ b/api/controllers/files/upload_file_delivery.py
@@ -2,7 +2,7 @@ import os
from urllib.parse import quote
from uuid import UUID
-from flask import Response, request
+from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field
from werkzeug.exceptions import NotFound
@@ -10,6 +10,7 @@ from werkzeug.exceptions import NotFound
from controllers.common.errors import UnsupportedFileTypeError
from controllers.common.file_response import enforce_download_for_html
from controllers.common.schema import query_params_from_model, register_schema_models
+from controllers.console.wraps import model_validate
from controllers.files import files_ns
from extensions.ext_application_services import application_services
from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError
@@ -74,13 +75,13 @@ class ImagePreviewApi(Resource):
@files_ns.doc(
responses={
200: "Image preview returned successfully",
- 400: "Missing or invalid query parameters",
404: "File not found or signature is invalid",
415: "Unsupported file type",
+ 422: "Missing or invalid query parameters",
}
)
- def get(self, file_id: UUID) -> Response:
- args = FileSignatureQuery.model_validate(request.args.to_dict(flat=True))
+ @model_validate(FileSignatureQuery)
+ def get(self, args: FileSignatureQuery, file_id: UUID) -> Response:
try:
delivery = application_services().upload_file_delivery.get_signed_image_preview(
file_id=str(file_id),
@@ -109,13 +110,12 @@ class FilePreviewApi(Resource):
@files_ns.doc(
responses={
200: "File stream returned successfully",
- 400: "Missing or invalid query parameters",
404: "File not found or signature is invalid",
+ 422: "Missing or invalid query parameters",
}
)
- def get(self, file_id: UUID) -> Response:
- args = FilePreviewQuery.model_validate(request.args.to_dict(flat=True))
-
+ @model_validate(FilePreviewQuery)
+ def get(self, args: FilePreviewQuery, file_id: UUID) -> Response:
try:
delivery = application_services().upload_file_delivery.get_signed_file_preview(
file_id=str(file_id),
diff --git a/api/tests/unit_tests/controllers/console/auth/test_account_activation.py b/api/tests/unit_tests/controllers/console/auth/test_account_activation.py
index 6f5ba50e56a..f3ca84a309f 100644
--- a/api/tests/unit_tests/controllers/console/auth/test_account_activation.py
+++ b/api/tests/unit_tests/controllers/console/auth/test_account_activation.py
@@ -6,6 +6,7 @@ from unittest.mock import Mock, patch
import pytest
from flask import Flask
+from werkzeug.exceptions import UnprocessableEntity
from controllers.console.auth.activate import ActivateApi, ActivateCheckApi
from controllers.console.auth.error import InvitationAccountMismatchError as InvitationAccountMismatchHTTPError
@@ -74,7 +75,7 @@ class TestActivateCheckApi:
return_value=_services(activation_service),
),
):
- response = unwrap(ActivateCheckApi.get)(ActivateCheckApi())
+ response = ActivateCheckApi().get()
assert response == {
"is_valid": True,
@@ -104,10 +105,24 @@ class TestActivateCheckApi:
return_value=_services(activation_service),
),
):
- response = unwrap(ActivateCheckApi.get)(ActivateCheckApi())
+ response = ActivateCheckApi().get()
assert response == {"is_valid": False}
+ def test_rejects_request_without_token(self, app: Flask, activation_service: Mock) -> None:
+ """`token` is required, so a tokenless query must not reach the application service."""
+ with (
+ app.test_request_context("/activate/check?workspace_id=workspace-123"),
+ patch(
+ "controllers.console.auth.activate.application_services",
+ return_value=_services(activation_service),
+ ),
+ pytest.raises(UnprocessableEntity),
+ ):
+ ActivateCheckApi().get()
+
+ activation_service.check.assert_not_called()
+
class TestActivateApi:
def test_passes_parsed_command_to_application_service(
diff --git a/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py b/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py
index b390c526ac4..fcb05f3f564 100644
--- a/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py
+++ b/api/tests/unit_tests/controllers/files/test_upload_file_delivery.py
@@ -1,9 +1,9 @@
-import types
from inspect import unwrap
from unittest.mock import patch
import pytest
-from werkzeug.exceptions import NotFound
+from flask import Flask
+from werkzeug.exceptions import NotFound, UnprocessableEntity
import controllers.files.upload_file_delivery as module
from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError
@@ -34,18 +34,17 @@ def _delivery(
)
-def _fake_request(args: dict[str, object]):
- return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda **_kwargs: args))
+_SIGNED_QUERY = "/?timestamp=123&nonce=abc&sign=sig"
class TestImagePreviewApi:
@patch.object(module, "application_services")
- def test_success(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"})
+ def test_success(self, mock_application_services, app: Flask):
service = mock_application_services.return_value.upload_file_delivery
service.get_signed_image_preview.return_value = _delivery(mime_type="image/png", extension="png")
- response = unwrap(module.ImagePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.ImagePreviewApi().get("file-id")
assert response.mimetype == "image/png"
service.get_signed_image_preview.assert_called_once_with(
@@ -56,31 +55,39 @@ class TestImagePreviewApi:
)
@patch.object(module, "application_services")
- def test_not_found(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"})
+ def test_not_found(self, mock_application_services, app: Flask):
service = mock_application_services.return_value.upload_file_delivery
service.get_signed_image_preview.side_effect = UploadFileDeliveryNotFoundError(
"File not found or signature is invalid"
)
- with pytest.raises(NotFound, match="File not found or signature is invalid"):
- unwrap(module.ImagePreviewApi().get)("file-id")
+ with (
+ app.test_request_context(_SIGNED_QUERY),
+ pytest.raises(NotFound, match="File not found or signature is invalid"),
+ ):
+ module.ImagePreviewApi().get("file-id")
@patch.object(module, "application_services")
- def test_unsupported_file_type(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig"})
+ def test_unsupported_file_type(self, mock_application_services, app: Flask):
service = mock_application_services.return_value.upload_file_delivery
service.get_signed_image_preview.side_effect = UnsupportedFileTypeServiceError()
- with pytest.raises(module.UnsupportedFileTypeError):
- unwrap(module.ImagePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY), pytest.raises(module.UnsupportedFileTypeError):
+ module.ImagePreviewApi().get("file-id")
+
+ @patch.object(module, "application_services")
+ def test_missing_signature_params_are_rejected(self, mock_application_services, app: Flask):
+ """An incomplete signature must fail validation before the service is reached."""
+ with app.test_request_context("/?timestamp=123"), pytest.raises(UnprocessableEntity):
+ module.ImagePreviewApi().get("file-id")
+
+ mock_application_services.return_value.upload_file_delivery.get_signed_image_preview.assert_not_called()
class TestFilePreviewApi:
@patch.object(module, "enforce_download_for_html")
@patch.object(module, "application_services")
- def test_inline_preview_uses_file_metadata(self, mock_application_services, mock_enforce):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_inline_preview_uses_file_metadata(self, mock_application_services, mock_enforce, app: Flask):
service = mock_application_services.return_value.upload_file_delivery
service.get_signed_file_preview.return_value = _delivery(
mime_type="application/pdf",
@@ -89,7 +96,8 @@ class TestFilePreviewApi:
extension="pdf",
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.FilePreviewApi().get("file-id")
assert response.mimetype == "application/pdf"
assert response.headers["Content-Type"] == "application/pdf"
@@ -103,25 +111,25 @@ class TestFilePreviewApi:
)
@patch.object(module, "application_services")
- def test_audio_preview_supports_ranges(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_audio_preview_supports_ranges(self, mock_application_services, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery(
mime_type="audio/mpeg",
extension="mp3",
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.FilePreviewApi().get("file-id")
assert response.headers["Accept-Ranges"] == "bytes"
@patch.object(module, "application_services")
- def test_zero_size_omits_content_length(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_zero_size_omits_content_length(self, mock_application_services, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery(
size=0
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.FilePreviewApi().get("file-id")
assert "Content-Length" not in response.headers
@@ -135,8 +143,7 @@ class TestFilePreviewApi:
ids=("mime-type", "filename", "extension"),
)
@patch.object(module, "application_services")
- def test_svg_preview_forces_download(self, mock_application_services, mime_type, name, extension):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_svg_preview_forces_download(self, mock_application_services, mime_type, name, extension, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery(
mime_type=mime_type,
size=11,
@@ -144,15 +151,15 @@ class TestFilePreviewApi:
extension=extension,
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.FilePreviewApi().get("file-id")
assert response.headers["Content-Disposition"].startswith("attachment")
assert response.headers["Content-Type"] == "application/octet-stream"
assert response.headers["X-Content-Type-Options"] == "nosniff"
@patch.object(module, "application_services")
- def test_html_preview_still_forces_download(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_html_preview_still_forces_download(self, mock_application_services, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery(
mime_type="text/html",
size=25,
@@ -160,35 +167,46 @@ class TestFilePreviewApi:
extension="html",
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(_SIGNED_QUERY):
+ response = module.FilePreviewApi().get("file-id")
assert response.headers["Content-Disposition"].startswith("attachment")
assert response.headers["Content-Type"] == "application/octet-stream"
assert response.headers["X-Content-Type-Options"] == "nosniff"
@patch.object(module, "application_services")
- def test_as_attachment_encodes_filename(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": True})
+ def test_as_attachment_encodes_filename(self, mock_application_services, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.return_value = _delivery(
mime_type="application/pdf",
name="报告.pdf",
extension="pdf",
)
- response = unwrap(module.FilePreviewApi().get)("file-id")
+ with app.test_request_context(f"{_SIGNED_QUERY}&as_attachment=true"):
+ response = module.FilePreviewApi().get("file-id")
assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.pdf"
assert response.headers["Content-Type"] == "application/octet-stream"
@patch.object(module, "application_services")
- def test_not_found(self, mock_application_services):
- module.request = _fake_request({"timestamp": "123", "nonce": "abc", "sign": "sig", "as_attachment": False})
+ def test_not_found(self, mock_application_services, app: Flask):
mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.side_effect = (
UploadFileDeliveryNotFoundError("File not found or signature is invalid")
)
- with pytest.raises(NotFound, match="File not found or signature is invalid"):
- unwrap(module.FilePreviewApi().get)("file-id")
+ with (
+ app.test_request_context(_SIGNED_QUERY),
+ pytest.raises(NotFound, match="File not found or signature is invalid"),
+ ):
+ module.FilePreviewApi().get("file-id")
+
+ @patch.object(module, "application_services")
+ def test_missing_signature_params_are_rejected(self, mock_application_services, app: Flask):
+ """An incomplete signature must fail validation before the service is reached."""
+ with app.test_request_context("/?nonce=abc"), pytest.raises(UnprocessableEntity):
+ module.FilePreviewApi().get("file-id")
+
+ mock_application_services.return_value.upload_file_delivery.get_signed_file_preview.assert_not_called()
class TestWorkspaceWebappLogoApi: