Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions apps/application/tests/test_workflow_file_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,19 @@ def test_own_chat_upload_is_allowed(self):
file = _file(FileSourceType.CHAT, CHAT, user_id=USER)
self.assertIs(self._get(file, _app_root()), file)

def test_another_users_upload_is_denied(self):
self.assertDenied(_file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER), _app_root())
def test_another_users_upload_to_root_chat_is_allowed(self):
# 工具等以其他身份上传到根对话的文件:与 OSS 下载一致,能访问该对话即可读取
file = _file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER)
self.assertIs(self._get(file, _app_root()), file)
self.assertIs(self._get(file, _sub_tool(_app_root(), TOOL_A)), file)

def test_another_users_upload_to_other_chat_is_denied(self):
self.assertDenied(_file(FileSourceType.CHAT, OTHER_CHAT, user_id=OTHER_USER), _app_root())

def test_chat_file_is_denied_outside_application_root(self):
file = _file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER)
self.assertDenied(file, root_context("SYSTEM_USER", USER, WorkflowType.TOOL, TOOL_A))
self.assertDenied(file, root_context("SYSTEM_USER", USER, WorkflowType.KNOWLEDGE, KNOWLEDGE))

@patch("application.workflow.file_access._is_knowledge_bound", return_value=False)
def test_unbound_knowledge_source_file_is_denied(self, _bound):
Expand Down
111 changes: 111 additions & 0 deletions apps/application/tests/test_workflow_reply_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from django.test import SimpleTestCase

from application.workflow.content_type import ContentType
from application.workflow.message.aggregator.aggregation_manager import AggregationManager
from application.workflow.message.struct.file_content import FileContent
from application.workflow.nodes.reply_node.handle.impl.file_reply import to_file_id_list
from application.workflow.nodes.reply_node.reply_node import ReplyNode, get_reply_handle
from application.workflow.status import Status
from common.exception.app_exception import AppUnauthorizedFailed

FILE_A = "019a0000-0000-7000-8000-0000000000a1"
FILE_B = "019a0000-0000-7000-8000-0000000000b1"
WORKFLOW_PARAMS = {"root_user_id": "019a0000-0000-7000-8000-0000000000aa"}


def _reply_node(node_params, reference_value=None):
node = ReplyNode.__new__(ReplyNode)
node.data = {}
node.context = {}
node.workflow_manage = MagicMock()
node.workflow_manage.get_reference_field.return_value = reference_value
node.workflow_manage.generate_prompt.side_effect = lambda prompt: prompt
node.get_parameters = lambda: node_params
node.get_workflow_parameters = lambda: WORKFLOW_PARAMS
node.get_node_id = lambda: "reply"
node.get_node_name = lambda: "Reply"
node.write_context = lambda key, value: node.context.__setitem__(key, value)
return node


def _stored_file(file_id):
return SimpleNamespace(id=file_id, file_name=f"{file_id[-2:]}.png", file_size=10)


class FileIdListTest(SimpleTestCase):
def test_accepts_file_objects_urls_and_ids_in_order_without_duplicates(self):
value = [{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"url": f"./oss/file/{FILE_B}"}, FILE_A]
self.assertEqual(to_file_id_list(value), [FILE_A, FILE_B])

def test_accepts_rendered_text(self):
self.assertEqual(to_file_id_list(str([{"file_id": FILE_A}])), [FILE_A])
self.assertEqual(to_file_id_list(f'["{FILE_A}", "{FILE_B}"]'), [FILE_A, FILE_B])
self.assertEqual(to_file_id_list(f"{FILE_A}, ./oss/file/{FILE_B}"), [FILE_A, FILE_B])

def test_empty_values(self):
self.assertEqual(to_file_id_list(None), [])
self.assertEqual(to_file_id_list(""), [])
self.assertEqual(to_file_id_list([{"name": "no-id"}]), [])


class ReplyFileTest(SimpleTestCase):
def test_unknown_content_type_falls_back_to_text(self):
self.assertTrue(get_reply_handle("UNKNOWN").support("TEXT"))

@patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file")
def test_file_reply_reads_metadata_from_authorized_files(self, get_authorized_file):
get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id)
node = _reply_node(
{"reply_type": "referencing", "fields": ["image", "image"], "content_type": "FILE", "is_result": True},
reference_value=[{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"file_id": FILE_B}],
)
node.execute()

self.assertEqual(
[call.args for call in get_authorized_file.call_args_list],
[(FILE_A, WORKFLOW_PARAMS), (FILE_B, WORKFLOW_PARAMS)],
)
expected = [
{"file_id": FILE_A, "name": "a1.png", "url": f"./oss/file/{FILE_A}", "size": 10},
{"file_id": FILE_B, "name": "b1.png", "url": f"./oss/file/{FILE_B}", "size": 10},
]
self.assertEqual(node.context["answer"], expected)
(message,) = [call.args[0] for call in node.workflow_manage.write.call_args_list]
self.assertIsInstance(message, FileContent)
self.assertEqual(message.to_dict()["file_list"], expected)

@patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file")
def test_file_reply_rejects_unauthorized_file(self, get_authorized_file):
get_authorized_file.side_effect = AppUnauthorizedFailed(403, "No permission to access")
node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": True})
with self.assertRaises(AppUnauthorizedFailed):
node.execute()
node.workflow_manage.write.assert_not_called()

@patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file")
def test_file_reply_hidden_when_not_result(self, get_authorized_file):
get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id)
node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": False})
node.execute()
self.assertEqual(len(node.context["answer"]), 1)
node.workflow_manage.write.assert_not_called()

def test_file_contents_aggregate_by_id(self):
manager = AggregationManager()
manager.aggregate(FileContent("1", [{"file_id": FILE_A, "name": "a.png"}], Status.RUNNING, None, None))
manager.aggregate(
FileContent(
"1",
[{"file_id": FILE_B, "name": "b.pdf"}, {"file_id": FILE_A, "name": "a2.png"}],
Status.SUCCESS,
None,
None,
)
)
(content,) = manager.get_contents()
self.assertEqual(content["type"], ContentType.FILE.value)
self.assertEqual(content["status"], Status.SUCCESS.value)
self.assertEqual([file["name"] for file in content["file_list"]], ["a2.png", "b.pdf"])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, the tests are clear and mostly well-isolated. I do not see syntax errors or obvious failing assertions, but there are several brittleness/coverage/security-adjacent concerns.

Potential issues

  1. String vs enum inconsistency

    get_reply_handle("UNKNOWN").support("TEXT")

    Elsewhere the code uses ContentType.FILE.value, implying ContentType is an enum. If support() expects a ContentType, passing "TEXT" may be incorrect or only work accidentally. Prefer:

    handler = get_reply_handle("UNKNOWN")
    self.assertTrue(handler.support(ContentType.TEXT.value))

    or use ContentType.TEXT consistently depending on the API contract.

  2. The test encourages overly permissive text parsing

    to_file_id_list(str([{"file_id": FILE_A}]))

    This requires support for Python repr-style input in addition to JSON and comma-separated IDs. If the implementation uses eval, that is a security problem. Even with ast.literal_eval, it broadens the accepted format unnecessarily.

    • Prefer one documented serialization format, e.g. JSON.
    • Add malformed-input tests.
    • Ensure no eval is used.
  3. Brittle extraction of the written message

    (message,) = [call.args[0] for call in node.workflow_manage.write.call_args_list]

    This implicitly assumes exactly one positional call. Use:

    node.workflow_manage.write.assert_called_once()
    message = node.workflow_manage.write.call_args.args[0]

    This gives clearer failure messages.

  4. Manual ReplyNode.__new__ construction is brittle

    node = ReplyNode.__new__(ReplyNode)
    node.data = {}
    ...

    This bypasses __init__ and will break if ReplyNode gains required attributes or initialization logic. Consider a small factory using mocks, or at least keep all required attributes in one place and assert they exist.

  5. get_authorized_file side effect is signature-sensitive

    get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id)

    If production code later calls it with keyword arguments or extra arguments, the test fails for an uninteresting reason. Prefer:

    def _get_file(*args, **kwargs):
        return _stored_file(args[0] if args else kwargs["file_id"])

    Alternatively keep the strict signature if that is intentionally part of the contract.

  6. Global mutable WORKFLOW_PARAMS

    WORKFLOW_PARAMS = {"root_user_id": ...}

    If production code mutates the dict, tests can leak state. Return a copy from get_workflow_parameters:

    node.get_workflow_parameters = lambda: dict(WORKFLOW_PARAMS)

    or use an immutable mapping.

  7. Incomplete failure-path assertions
    In test_file_reply_rejects_unauthorized_file, you assert that write was not called, but not that no partial context was written. If authorization fails after adding one file, you could leak partial state. Add:

    self.assertNotIn("answer", node.context)

    or assert the expected empty/unchanged state.

  8. Weak assertion in test_file_reply_hidden_when_not_result

    self.assertEqual(len(node.context["answer"]), 1)

    This does not verify content or hidden behavior. Assert the exact answer and that write was not called. Also consider testing an empty file list for is_result=False.

  9. Aggregation order assumption may be brittle

    self.assertEqual([file["name"] for file in content["file_list"]], ["a2.png", "b.pdf"])

    This assumes that replacing an existing file_id preserves its original position. If that is a required contract, keep it; otherwise assert on a set or document the ordering requirement.

  10. Missing edge cases
    Useful additions:

    • Unauthorized failure on the second file after the first succeeds, to verify no partial write/context.
    • Empty file list with is_result=True.
    • Duplicate IDs with different URLs/metadata.
    • URL that does not match the file_id.
    • Malformed rendered text input.
    • Missing root_user_id or invalid workflow params.

Minor optimization suggestions

  • Use a class-level @patch(...) on ReplyFileTest to avoid repeating the decorator.
  • In test_accepts_rendered_text, use subTest for each format so failures identify the exact format.
  • Consider moving test_file_contents_aggregate_by_id into a separate FileContentAggregationTest class since it does not test ReplyNode.
  • Replace assertTrue(get_reply_handle("UNKNOWN").support(...)) with an assertion on the handler type if the fallback behavior is the real intent.

No blocking issue is apparent, but I would prioritize the enum/string consistency, the overly broad text parsing test, and stronger failure-path assertions.

1 change: 1 addition & 0 deletions apps/application/workflow/content_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
class ContentType(Enum):
TEXT = "TEXT"
HTML = "HTML"
FILE = "FILE"
REASONING = "REASONING"
FAILURE = "FAILURE"
TOOL = "TOOL"
Expand Down
11 changes: 10 additions & 1 deletion apps/application/workflow/file_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,15 @@ def _in_root_resource(file, workflow_params):
and str(file.source_id) == str(resource_id)
and (file.meta or {}).get("chat_id") in (None, root_chat_id)
)
if file.source_type == FileSourceType.CHAT:
# 根对话的文件(含工具等以其他身份上传到该对话的文件):入口已校验根对话归属发起者,
# 与 OSS 下载「能访问该对话即可访问其文件」一致
root_chat_id = workflow_params.get("root_chat_id")
return (
resource_type == ResourceType.APPLICATION
and bool(root_chat_id)
and str(file.source_id) == str(root_chat_id)
)
if file.source_type == FileSourceType.TOOL:
return resource_type == ResourceType.TOOL and str(file.source_id) == str(resource_id)
knowledge_id = _get_file_knowledge_id(file)
Expand All @@ -129,7 +138,7 @@ def get_authorized_file(file_id, workflow_params):
"""
工作流节点读取文件的唯一入口。允许:
1. 发起者本人上传的文件,或本次运行(含嵌套子工作流)生成的文件
2. 根资源的文件(应用当前对话的文件、知识库文件、根应用/工具关联知识库的文件),
2. 根资源的文件(应用当前对话的文件,含他人身份上传到该对话的文件、知识库文件、根应用/工具关联知识库的文件),
但他人运行时生成的工具/应用文件除外
"""
workflow_params = workflow_params or {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
from typing import Dict, Type, Optional

from application.workflow.message.aggregator.content_aggregator import ContentAggregator
from application.workflow.message.aggregator.impl import FormAggregator, HtmlAggregator
from application.workflow.message.aggregator.impl import FileAggregator, FormAggregator, HtmlAggregator
from application.workflow.message.aggregator.impl.reasoning_aggregator import ReasoningAggregator
from application.workflow.message.aggregator.impl.text_aggregator import TextAggregator
from application.workflow.message.aggregator.impl.tool_aggregator import ToolAggregator
from application.workflow.message.struct.content import Content
from application.workflow.message.struct.file_content import FileContent
from application.workflow.message.struct.form_content import FormContent
from application.workflow.message.struct.html_content import HtmlContent
from application.workflow.message.struct.reasoning_content import ReasoningContent
Expand All @@ -33,6 +34,7 @@ class AggregatorFactory:
ToolContent: ToolAggregator(),
FormContent: FormAggregator(),
HtmlContent: HtmlAggregator(),
FileContent: FileAggregator(),
}

@classmethod
Expand Down
10 changes: 9 additions & 1 deletion apps/application/workflow/message/aggregator/impl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,13 @@
from application.workflow.message.aggregator.impl.tool_aggregator import ToolAggregator
from application.workflow.message.aggregator.impl.form_aggregator import FormAggregator
from application.workflow.message.aggregator.impl.html_aggregator import HtmlAggregator
from application.workflow.message.aggregator.impl.file_aggregator import FileAggregator

__all__ = ["TextAggregator", "ReasoningAggregator", "ToolAggregator", "FormAggregator", "HtmlAggregator"]
__all__ = [
"TextAggregator",
"ReasoningAggregator",
"ToolAggregator",
"FormAggregator",
"HtmlAggregator",
"FileAggregator",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# coding=utf-8
"""
@project: MaxKB
@file: file_aggregator.py
@date:2026/12/4
@desc: FileContent 聚合器
"""

from application.workflow.message.aggregator.content_aggregator import ContentAggregator
from application.workflow.message.struct.file_content import FileContent


def _file_key(file: dict):
return file.get("file_id") or file.get("url")


class FileAggregator(ContentAggregator[FileContent]):
"""
文件内容聚合器
按顺序追加文件,file_id(无则 url)相同的文件后到覆盖先到
"""

def aggregate(self, prev: FileContent, chunk: FileContent) -> FileContent:
if prev is None:
return chunk
file_list = list(prev.file_list)
key_to_index = {_file_key(file): index for index, file in enumerate(file_list) if _file_key(file)}
for file in chunk.file_list:
key = _file_key(file)
if key and key in key_to_index:
file_list[key_to_index[key]] = file
else:
if key:
key_to_index[key] = len(file_list)
file_list.append(file)
result = FileContent(prev.id, file_list, prev.status, prev.node_info, prev.position)
self.merge_base_fields(prev, chunk, result)
return result
41 changes: 41 additions & 0 deletions apps/application/workflow/message/struct/file_content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# coding=utf-8
"""
@project: MaxKB
@Author:虎虎
@file: file_content.py
@date:2026/12/4
@desc: 文件内容,前端按文件类型渲染(图片预览、音视频播放、其他文件下载)
"""

from typing import Dict, List, Optional

from application.workflow.content_type import ContentType
from application.workflow.message.struct.content import Content, NodeInfo, Position
from application.workflow.status import Status


class FileContent(Content):
"""
file_list 中每一项:
file_id: 文件 id
name: 文件名(前端据扩展名决定图标与渲染方式)
url: 访问地址
size: 文件大小(字节,可选)
"""

def __init__(
self,
_id,
file_list: Optional[List[Dict]],
status: Status,
node_info: NodeInfo,
position: Position,
**kwargs,
):
self.file_list = list(file_list or [])
super().__init__(_id, status, ContentType.FILE, node_info, position, **kwargs)

def to_dict(self):
result = super().to_dict()
result["file_list"] = self.file_list
return result
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# coding=utf-8
"""
@project: MaxKB
@Author:虎虎
@file: file_reply.py
@date:2026/12/4
@desc: 文件回复:按 file_id 鉴权后从文件表取文件名与大小,前端按扩展名渲染
"""

import ast
import json
import re
from typing import List

import uuid_utils.compat as uuid

from application.workflow.file_access import get_authorized_file
from application.workflow.message.struct.content import Content, NodeInfo, Position
from application.workflow.message.struct.file_content import FileContent
from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle
from application.workflow.status import Status

OSS_FILE_PREFIX = "/oss/file/"


def _parse_text(text: str):
"""回复文本可能是 JSON、Python 字面量(模板渲染列表/字典)或以逗号、空白分隔的 file_id / 文件地址"""
text = text.strip()
if not text:
return []
for parse in (json.loads, ast.literal_eval):
try:
parsed = parse(text)
except (ValueError, SyntaxError):
continue
if not isinstance(parsed, str):
return parsed
return [token for token in re.split(r"[\s,]+", text) if token]


def _token_to_file_id(token: str):
token = token.strip()
if OSS_FILE_PREFIX in token:
token = token.split(OSS_FILE_PREFIX, 1)[1].split("?", 1)[0].split("/", 1)[0]
return token or None


def to_file_id_list(value):
"""
把回复值归一化为 file_id 列表(保持顺序、去重)。
支持 file_id、./oss/file/{file_id} 地址、带 file_id/url 的文件对象,以及它们组成的列表或其文本形式。
"""
file_id_list = []

def collect(item):
if item is None:
return
if isinstance(item, (list, tuple)):
for child in item:
collect(child)
elif isinstance(item, dict):
if item.get("file_id"):
collect(str(item.get("file_id")))
elif isinstance(item.get("url"), str):
collect(item.get("url"))
elif isinstance(item, str):
file_id = _token_to_file_id(item)
if file_id and file_id not in file_id_list:
file_id_list.append(file_id)

collect(_parse_text(value) if isinstance(value, str) else value)
return file_id_list


class FileReply(ReplyBaseHandle):
def support(self, content_type: str) -> bool:
return content_type == "FILE"

def get_answer(self, node, value):
workflow_params = node.get_workflow_parameters()
file_list = []
for file_id in to_file_id_list(value):
# 与图片理解等节点一致:只允许发起者本人或根资源的文件,无权限直接拒绝
file = get_authorized_file(file_id, workflow_params)
file_list.append(
{
"file_id": str(file.id),
"name": file.file_name,
"url": f"./oss/file/{file.id}",
"size": file.file_size,
}
)
return file_list

def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]:
if not answer:
return []
return [FileContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)]
Loading
Loading