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(files): dep-inject query params with @model_validate (#42314)

Syrinx.40f859450a1d
diff --git a/api/controllers/files/tool_files.py b/api/controllers/files/tool_files.py
index ce20480bbd6..aa90cdba2c3 100644
--- a/api/controllers/files/tool_files.py
+++ b/api/controllers/files/tool_files.py
@@ -1,13 +1,14 @@
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 Forbidden, NotFound
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.tool_file_download_service import (
@@ -44,8 +45,8 @@ class ToolFileApi(Resource):
404: "File not found",
}
)
- def get(self, file_id: UUID, extension: str) -> Response:
- args = ToolFileQuery.model_validate(request.args.to_dict(flat=True))
+ @model_validate(ToolFileQuery)
+ def get(self, args: ToolFileQuery, file_id: UUID, extension: str) -> Response:
try:
download = application_services().tool_file_downloads.get_signed_file(
file_id=str(file_id),
diff --git a/api/tests/unit_tests/controllers/files/test_tool_files.py b/api/tests/unit_tests/controllers/files/test_tool_files.py
index 3a7544dcbcf..0f18ef09925 100644
--- a/api/tests/unit_tests/controllers/files/test_tool_files.py
+++ b/api/tests/unit_tests/controllers/files/test_tool_files.py
@@ -1,10 +1,10 @@
-import types
from collections.abc import Iterator
from inspect import unwrap
from unittest.mock import MagicMock, patch
import pytest
-from werkzeug.exceptions import Forbidden, NotFound
+from flask import Flask, Response
+from werkzeug.exceptions import Forbidden, NotFound, UnprocessableEntity
import controllers.files.tool_files as module
from services.tool_file_download_service import (
@@ -14,12 +14,13 @@ from services.tool_file_download_service import (
)
-def _fake_request(args: dict[str, object]) -> types.SimpleNamespace:
- return types.SimpleNamespace(args=types.SimpleNamespace(to_dict=lambda **_kwargs: args))
+def _query(*, sign: str = "sig", as_attachment: bool = False) -> module.ToolFileQuery:
+ return module.ToolFileQuery(timestamp="123", nonce="abc", sign=sign, as_attachment=as_attachment)
-def _set_request(monkeypatch: pytest.MonkeyPatch, args: dict[str, object]) -> None:
- monkeypatch.setattr(module, "request", _fake_request(args))
+def _get(query: module.ToolFileQuery, file_id: str, extension: str) -> Response:
+ api = module.ToolFileApi()
+ return unwrap(api.get)(api, query, file_id, extension)
def _download(
@@ -39,25 +40,12 @@ def _download(
class TestToolFileApi:
@patch.object(module, "application_services")
- def test_success_stream(
- self,
- mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
- ) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": False,
- },
- )
+ def test_success_stream(self, mock_application_services: MagicMock) -> None:
stream = iter([b"data"])
service = mock_application_services.return_value.tool_file_downloads
service.get_signed_file.return_value = _download(content=stream, size=100)
- response = unwrap(module.ToolFileApi().get)("file-id", "txt")
+ response = _get(_query(), "file-id", "txt")
assert response.response is stream
assert response.mimetype == "text/plain"
@@ -71,47 +59,21 @@ class TestToolFileApi:
)
@patch.object(module, "application_services")
- def test_zero_size_omits_content_length(
- self,
- mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
- ) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": False,
- },
- )
+ def test_zero_size_omits_content_length(self, mock_application_services: MagicMock) -> None:
mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download(size=0)
- response = unwrap(module.ToolFileApi().get)("file-id", "txt")
+ response = _get(_query(), "file-id", "txt")
assert "Content-Length" not in response.headers
@patch.object(module, "application_services")
- def test_as_attachment_preserves_mime_type(
- self,
- mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
- ) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": True,
- },
- )
+ def test_as_attachment_preserves_mime_type(self, mock_application_services: MagicMock) -> None:
mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download(
mime_type="application/pdf",
filename="报告.pdf",
)
- response = unwrap(module.ToolFileApi().get)("file-id", "pdf")
+ response = _get(_query(as_attachment=True), "file-id", "pdf")
assert response.headers["Content-Disposition"] == "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.pdf"
assert response.headers["Content-Type"] == "application/pdf"
@@ -128,95 +90,58 @@ class TestToolFileApi:
def test_html_forces_download(
self,
mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
mime_type: str,
filename: str,
route_extension: str,
) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": False,
- },
- )
mock_application_services.return_value.tool_file_downloads.get_signed_file.return_value = _download(
mime_type=mime_type,
filename=filename,
)
- response = unwrap(module.ToolFileApi().get)("file-id", route_extension)
+ response = _get(_query(), "file-id", route_extension)
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_invalid_signature(
- self,
- mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
- ) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "bad-sig",
- "as_attachment": False,
- },
- )
+ def test_invalid_signature(self, mock_application_services: MagicMock) -> None:
mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = (
ToolFileDownloadAccessDeniedError()
)
with pytest.raises(Forbidden, match=r"Invalid request\."):
- unwrap(module.ToolFileApi().get)("file-id", "txt")
+ _get(_query(sign="bad-sig"), "file-id", "txt")
@patch.object(module, "application_services")
- def test_file_not_found(
- self,
- mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
- ) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": False,
- },
- )
+ def test_file_not_found(self, mock_application_services: MagicMock) -> None:
mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = (
ToolFileDownloadNotFoundError()
)
with pytest.raises(NotFound, match="file is not found"):
- unwrap(module.ToolFileApi().get)("file-id", "txt")
+ _get(_query(), "file-id", "txt")
@pytest.mark.parametrize("service_error", [RuntimeError("database unavailable"), OSError("storage unavailable")])
@patch.object(module, "application_services")
def test_unexpected_error_is_not_converted(
self,
mock_application_services: MagicMock,
- monkeypatch: pytest.MonkeyPatch,
service_error: Exception,
) -> None:
- _set_request(
- monkeypatch,
- {
- "timestamp": "123",
- "nonce": "abc",
- "sign": "sig",
- "as_attachment": False,
- },
- )
mock_application_services.return_value.tool_file_downloads.get_signed_file.side_effect = service_error
with pytest.raises(type(service_error)) as error_info:
- unwrap(module.ToolFileApi().get)("file-id", "txt")
+ _get(_query(), "file-id", "txt")
assert error_info.value is service_error
+
+ def test_missing_signature_is_rejected_before_the_service_call(self, app: Flask) -> None:
+ """`timestamp`, `nonce` and `sign` are required, so this covers the decorator's rejection path."""
+ with patch.object(module, "application_services") as application_services:
+ with app.test_request_context("/files/tools/file-id.txt"):
+ with pytest.raises(UnprocessableEntity):
+ module.ToolFileApi().get("file-id", "txt")
+
+ application_services.assert_not_called()