diff --git a/backend/.test_durations b/backend/.test_durations index e011451c7e..54c688d9ba 100644 --- a/backend/.test_durations +++ b/backend/.test_durations @@ -13898,37 +13898,6 @@ "tests/test_image_download_limit.py::test_provider_limit_stops_stream_and_closes[9-opensandbox]": 0.0010075520003738347, "tests/test_image_download_limit.py::test_provider_limit_stops_stream_and_closes[9-tenki]": 0.0009922730000653246, "tests/test_image_download_limit.py::test_tool_rejects_21_mib_without_consuming_the_complete_stream": 0.007827877999943667, - "tests/test_image_result_idna_hosts.py::test_ddg_image_search_keeps_safe_thumbnail_when_idna_image_is_private": 0.0034168139998200786, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://10\\u30020\\u30020\\u30021/image-10.0.0.1]": 0.0010299340003712132, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://127\\u30020\\u30020\\u30021/image-127.0.0.1]": 0.001022770000190576, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://127\\uff0e0\\uff0e0\\uff0e1/image-127.0.0.1]": 0.0010231099997781712, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://127\\uff610\\uff610\\uff611/image-127.0.0.1]": 0.0010016209998866543, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://169\\u3002254\\u3002169\\u3002254/image-169.254.169.254]": 0.0010038839998287585, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://localhost\\u3002/image-localhost.]": 0.0009869030000118073, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[brave.tools-http://metadata\\u3002google\\u3002internal/image-metadata.google.internal]": 0.0010104670000146143, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://10\\u30020\\u30020\\u30021/image-10.0.0.1]": 0.0010000870001931617, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://127\\u30020\\u30020\\u30021/image-127.0.0.1]": 0.0010218479999366537, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://127\\uff0e0\\uff0e0\\uff0e1/image-127.0.0.1]": 0.0010058380000828038, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://127\\uff610\\uff610\\uff611/image-127.0.0.1]": 0.0010130119999303133, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://169\\u3002254\\u3002169\\u3002254/image-169.254.169.254]": 0.001038522000044395, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://localhost\\u3002/image-localhost.]": 0.0009890859998904489, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[serper.tools-http://metadata\\u3002google\\u3002internal/image-metadata.google.internal]": 0.000998975999891627, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://10\\u30020\\u30020\\u30021/image-10.0.0.1]": 0.0010380090000126074, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://127\\u30020\\u30020\\u30021/image-127.0.0.1]": 0.0011398290000670386, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://127\\uff0e0\\uff0e0\\uff0e1/image-127.0.0.1]": 0.001029813000059221, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://127\\uff610\\uff610\\uff611/image-127.0.0.1]": 0.001039871999864772, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://169\\u3002254\\u3002169\\u3002254/image-169.254.169.254]": 0.0010313050001968804, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://localhost\\u3002/image-localhost.]": 0.0010645700001532532, - "tests/test_image_result_idna_hosts.py::test_image_results_reject_idna_normalized_private_hosts[url_safety-http://metadata\\u3002google\\u3002internal/image-metadata.google.internal]": 0.0010322380001070997, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[brave.tools-https://\\u4f8b\\u3048.\\u30c6\\u30b9\\u30c8/full.jpg]": 0.0010448509999605449, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[brave.tools-https://images.example/full.jpg]": 0.0010380690000602044, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[brave.tools-https://images\\u3002example/full.jpg]": 0.0011684539999805565, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[serper.tools-https://\\u4f8b\\u3048.\\u30c6\\u30b9\\u30c8/full.jpg]": 0.001046002999828488, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[serper.tools-https://images.example/full.jpg]": 0.0010523949999878823, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[serper.tools-https://images\\u3002example/full.jpg]": 0.001067574999979115, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[url_safety-https://\\u4f8b\\u3048.\\u30c6\\u30b9\\u30c8/full.jpg]": 0.0010867999999391031, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[url_safety-https://images.example/full.jpg]": 0.0010527370002364478, - "tests/test_image_result_idna_hosts.py::test_public_idna_result_urls_keep_the_original_string_without_dns[url_safety-https://images\\u3002example/full.jpg]": 0.0010980819999986124, "tests/test_image_result_url_safety.py::test_image_providers_keep_public_results_without_dns[brave.tools-http://134744072/image]": 0.0010423470000660018, "tests/test_image_result_url_safety.py::test_image_providers_keep_public_results_without_dns[brave.tools-http://8.8.8.8/image]": 0.0010469349999766564, "tests/test_image_result_url_safety.py::test_image_providers_keep_public_results_without_dns[brave.tools-http://[2606:4700:4700::1111]/image]": 0.0011966980000579497, @@ -27799,11 +27768,6 @@ "tests/test_runtime_provider_close_cancellation.py::test_close_drain_helper_propagates_owner_failure[enter]": 0.00162332600029913, "tests/test_runtime_provider_close_cancellation.py::test_stream_bridge_context_drains_close_across_repeated_cancellation": 0.0017330939999737893, "tests/test_runtime_provider_close_cancellation.py::test_stream_bridge_redis_context_drains_close_across_repeated_cancellation": 0.0017282839990002685, - "tests/test_safety_finish_reason_graph_integration.py::test_content_filter_empty_no_tool_calls_is_backfilled_not_persisted_empty": 0.0076939139999012696, - "tests/test_safety_finish_reason_graph_integration.py::test_content_filter_with_tool_calls_does_not_invoke_tool_node": 0.006241778000003251, - "tests/test_safety_finish_reason_graph_integration.py::test_content_filter_without_tool_calls_preserves_text_and_marks_termination": 0.008195023000098445, - "tests/test_safety_finish_reason_graph_integration.py::test_normal_tool_call_round_trip_is_not_affected": 0.016179583000848652, - "tests/test_safety_finish_reason_graph_integration.py::test_safety_termination_event_reaches_astream_events[asyncio]": 0.007407775000046968, "tests/test_safety_finish_reason_middleware.py::TestAuditEvent::test_audit_event_never_carries_tool_arguments": 0.001480175999859057, "tests/test_safety_finish_reason_middleware.py::TestAuditEvent::test_journal_record_exception_warns_without_breaking_run": 0.00239404400008425, "tests/test_safety_finish_reason_middleware.py::TestAuditEvent::test_no_journal_in_runtime_context_is_silently_skipped": 0.0010710999999901105, @@ -34470,14 +34434,6 @@ "tests/test_stream_cleanup.py::test_repeated_cancellation_does_not_interrupt_stream_close": 0.001973006000298483, "tests/test_stream_cleanup.py::test_stream_originated_cancellation_is_reported_as_close_failure": 0.00151140799971472, "tests/test_stream_cleanup.py::test_synchronous_stream_close_cancellation_is_reported_as_failure": 0.0016123879995575408, - "tests/test_stream_get_action_rejected.py::test_get_with_action_is_rejected_before_owner_lookup": 0.03946596499963562, - "tests/test_stream_get_action_rejected.py::test_get_with_cancel_action_is_rejected[interrupt]": 0.041747839999516145, - "tests/test_stream_get_action_rejected.py::test_get_with_cancel_action_is_rejected[rollback]": 0.042567158000110794, - "tests/test_stream_get_action_rejected.py::test_get_with_invalid_action_has_one_validation_error": 0.04024516899971786, - "tests/test_stream_get_action_rejected.py::test_get_without_action_still_joins": 0.041925785999865184, - "tests/test_stream_get_action_rejected.py::test_post_with_cancel_action_still_cancels[interrupt]": 0.04350369600024351, - "tests/test_stream_get_action_rejected.py::test_post_with_cancel_action_still_cancels[rollback]": 0.040691194999908475, - "tests/test_stream_get_action_rejected.py::test_unsupported_method_preserves_post_allow_header": 0.041446843999892735, "tests/test_subagent_acceptance_followup.py::test_all_holds_encourages_reuse_with_evidence_boundary": 0.0007427239997923607, "tests/test_subagent_acceptance_followup.py::test_gap_summaries_bound_and_escape_both_kinds_even_after_many_failures": 0.0008661350002512336, "tests/test_subagent_acceptance_followup.py::test_guidance_uses_leaves_not_persisted_all_hold_aggregate": 0.000780966999627708, diff --git a/backend/tests/test_image_result_idna_hosts.py b/backend/tests/test_image_result_idna_hosts.py deleted file mode 100644 index 54b91f35bd..0000000000 --- a/backend/tests/test_image_result_idna_hosts.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Image result screening must classify the host clients use after IDNA.""" - -import importlib -import json -from unittest.mock import patch - -import httpx -import pytest - -from deerflow.community.image_search import tools - - -@pytest.fixture(params=["url_safety", "brave.tools", "serper.tools"]) -def screen(request): - module = importlib.import_module(f"deerflow.community.{request.param}") - return module.safe_public_result_url if request.param == "url_safety" else module._safe_public_url - - -@pytest.mark.parametrize( - ("url", "normalized_host"), - [ - ("http://127\u30020\u30020\u30021/image", "127.0.0.1"), - ("http://127\uff0e0\uff0e0\uff0e1/image", "127.0.0.1"), - ("http://127\uff610\uff610\uff611/image", "127.0.0.1"), - ("http://169\u3002254\u3002169\u3002254/image", "169.254.169.254"), - ("http://10\u30020\u30020\u30021/image", "10.0.0.1"), - ("http://localhost\u3002/image", "localhost."), - ("http://metadata\u3002google\u3002internal/image", "metadata.google.internal"), - ], -) -def test_image_results_reject_idna_normalized_private_hosts(screen, url, normalized_host): - # Parse with the real client, without connecting, to pin the normalization - # that makes these spellings equivalent to the blocked ASCII hosts. - assert httpx.URL(url).host == normalized_host - assert screen(url) == "" - - -@pytest.mark.parametrize("url", ["https://images\u3002example/full.jpg", "https://\u4f8b\u3048.\u30c6\u30b9\u30c8/full.jpg", "https://images.example/full.jpg"]) -def test_public_idna_result_urls_keep_the_original_string_without_dns(screen, url): - with patch("socket.getaddrinfo", side_effect=AssertionError("Result screening must not resolve DNS")): - assert screen(url) == url - - -@pytest.mark.asyncio -async def test_ddg_image_search_keeps_safe_thumbnail_when_idna_image_is_private(): - rows = [{"title": "reference", "image": "http://127\u30020\u30020\u30021/full.jpg", "thumbnail": "https://images.example/thumb.jpg"}] - with patch.object(tools, "_search_images", return_value=rows), patch.object(tools, "get_app_config") as config: - config.return_value.get_tool_config.return_value = None - result = json.loads(await tools.image_search_tool.ainvoke({"query": "reference"})) - - assert result["total_results"] == 1 - assert result["results"] == [{"title": "reference", "image_url": "", "thumbnail_url": "https://images.example/thumb.jpg", "source_url": ""}] diff --git a/backend/tests/test_safety_finish_reason_graph_integration.py b/backend/tests/test_safety_finish_reason_graph_integration.py deleted file mode 100644 index 7af41c822d..0000000000 --- a/backend/tests/test_safety_finish_reason_graph_integration.py +++ /dev/null @@ -1,310 +0,0 @@ -"""End-to-end graph integration test for SafetyFinishReasonMiddleware. - -Unit tests prove ``_apply`` does the right thing on a synthetic state. -This test does one level up: builds a real ``langchain.agents.create_agent`` -graph with the SafetyFinishReasonMiddleware in place, feeds it a fake model -that returns ``finish_reason='content_filter'`` + tool_calls, and asserts: - - 1. The tool node is **not** invoked (the dangerous truncated tool call - is suppressed). - 2. The final AIMessage in graph state has ``tool_calls == []``. - 3. The observability ``safety_termination`` record is attached. - 4. The user-facing explanation is appended to the message content. - -This is the closest we can get to the issue's failure mode without a live -Moonshot key, and it proves the middleware actually gates LangChain's -tool router — not just rewrites state in isolation. -""" - -from __future__ import annotations - -from typing import Any - -import pytest -from langchain.agents import create_agent -from langchain.agents.middleware import AgentMiddleware -from langchain.agents.middleware.types import ModelRequest, ModelResponse -from langchain_core.language_models import BaseChatModel -from langchain_core.messages import AIMessage, HumanMessage -from langchain_core.outputs import ChatGeneration, ChatResult -from langchain_core.tools import tool - -from deerflow.agents.middlewares.safety_finish_reason_middleware import SafetyFinishReasonMiddleware - -_TOOL_INVOCATIONS: list[dict[str, Any]] = [] - - -@tool -def write_file(path: str, content: str) -> str: - """Pretend to write *content* to *path*. Records the call for assertion.""" - _TOOL_INVOCATIONS.append({"path": path, "content": content}) - return f"wrote {len(content)} bytes to {path}" - - -class _ContentFilteredModel(BaseChatModel): - """Fake chat model that mimics OpenAI/Moonshot's content_filter response. - - First call returns finish_reason='content_filter' + a tool_call whose - arguments are visibly truncated. Second call (if reached) returns a - normal text completion so the agent can terminate cleanly. - """ - - call_count: int = 0 - - @property - def _llm_type(self) -> str: - return "fake-content-filtered" - - def bind_tools(self, tools, **kwargs): - # create_agent binds tools onto the model; we don't actually need - # to bind anything since responses are hard-coded, but the method - # must not raise. - return self - - def _generate(self, messages, stop=None, run_manager=None, **kwargs): - self.call_count += 1 - if self.call_count == 1: - message = AIMessage( - content="Here is the report:\n# Weekly Politics\n- Meeting time: 2026-05-12—", - tool_calls=[ - { - "id": "call_truncated_1", - "name": "write_file", - "args": { - "path": "/mnt/user-data/outputs/report.md", - "content": "# Weekly Politics\n- Meeting time: 2026-05-12—", - }, - } - ], - response_metadata={"finish_reason": "content_filter", "model_name": "fake-kimi"}, - ) - else: - message = AIMessage(content="ack", response_metadata={"finish_reason": "stop"}) - return ChatResult(generations=[ChatGeneration(message=message)]) - - async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs): - return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs) - - -class _InspectMiddleware(AgentMiddleware): - """Captures the messages list at every model entry so we can assert - no synthetic tool result was injected back into the conversation.""" - - def __init__(self) -> None: - super().__init__() - self.observed: list[list[Any]] = [] - - def wrap_model_call(self, request: ModelRequest, handler) -> ModelResponse: - self.observed.append(list(request.messages)) - return handler(request) - - -def test_content_filter_with_tool_calls_does_not_invoke_tool_node(): - _TOOL_INVOCATIONS.clear() - inspector = _InspectMiddleware() - - agent = create_agent( - model=_ContentFilteredModel(), - tools=[write_file], - # Inspector first so its after_model is registered; Safety last in - # the list so it executes first under LIFO (matches production wiring). - middleware=[inspector, SafetyFinishReasonMiddleware()], - ) - - result = agent.invoke({"messages": [HumanMessage(content="write me a report")]}) - - # Critical assertion: the dangerous truncated tool call must NOT have - # been executed. This is the entire point of the middleware. - assert _TOOL_INVOCATIONS == [], f"write_file was invoked despite content_filter: {_TOOL_INVOCATIONS}" - - # Final AIMessage has no tool calls left. - final_ai = next(m for m in reversed(result["messages"]) if isinstance(m, AIMessage)) - assert final_ai.tool_calls == [] - - # Observability stamp is present. - record = final_ai.additional_kwargs.get("safety_termination") - assert record is not None - assert record["detector"] == "openai_compatible_content_filter" - assert record["reason_field"] == "finish_reason" - assert record["reason_value"] == "content_filter" - assert record["suppressed_tool_call_count"] == 1 - assert record["suppressed_tool_call_names"] == ["write_file"] - - # User-facing explanation is appended. - assert "safety-related signal" in final_ai.content - # Original partial text preserved (we don't throw away what the user - # already saw in the stream — see middleware docstring). - assert "Weekly Politics" in final_ai.content - - # finish_reason on response_metadata is preserved (so SSE / converters - # downstream still see the real provider reason). - assert final_ai.response_metadata.get("finish_reason") == "content_filter" - - -@pytest.mark.anyio -async def test_safety_termination_event_reaches_astream_events(): - """Exercise the middleware's real async graph hook and callback context.""" - - _TOOL_INVOCATIONS.clear() - agent = create_agent( - model=_ContentFilteredModel(), - tools=[write_file], - middleware=[SafetyFinishReasonMiddleware()], - context_schema=dict, - ) - - events = [ - event - async for event in agent.astream_events( - {"messages": [HumanMessage(content="write me a report")]}, - version="v2", - context={"thread_id": "safety-stream-thread"}, - ) - if event["event"] == "on_custom_event" - ] - - assert len(events) == 1 - assert events[0]["name"] == "safety_termination" - assert events[0]["data"] == { - "type": "safety_termination", - "detector": "openai_compatible_content_filter", - "reason_field": "finish_reason", - "reason_value": "content_filter", - "suppressed_tool_call_count": 1, - "suppressed_tool_call_names": ["write_file"], - "thread_id": "safety-stream-thread", - } - assert _TOOL_INVOCATIONS == [] - - -def test_content_filter_without_tool_calls_preserves_text_and_marks_termination(): - """Keep the partial response visible while telling later hooks to stop.""" - _TOOL_INVOCATIONS.clear() - - class _NoToolModel(BaseChatModel): - @property - def _llm_type(self) -> str: - return "fake-no-tool" - - def bind_tools(self, tools, **kwargs): - return self - - def _generate(self, messages, stop=None, run_manager=None, **kwargs): - msg = AIMessage( - content="Partial answer truncated by safety filter", - response_metadata={"finish_reason": "content_filter"}, - ) - return ChatResult(generations=[ChatGeneration(message=msg)]) - - async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs): - return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs) - - agent = create_agent( - model=_NoToolModel(), - tools=[write_file], - middleware=[SafetyFinishReasonMiddleware()], - ) - result = agent.invoke({"messages": [HumanMessage(content="hi")]}) - final_ai = next(m for m in reversed(result["messages"]) if isinstance(m, AIMessage)) - - # Content untouched. - assert final_ai.content == "Partial answer truncated by safety filter" - assert final_ai.additional_kwargs["safety_termination"]["suppressed_tool_call_count"] == 0 - # tool node never ran (there were no tool calls in the first place). - assert _TOOL_INVOCATIONS == [] - - -def test_content_filter_empty_no_tool_calls_is_backfilled_not_persisted_empty(): - """#4393: a content_filter response with empty content and no tool calls - must not survive in graph state as an empty AIMessage — strict - OpenAI-compatible providers reject an empty assistant message on the next - request, poisoning the whole thread. The middleware backfills a - user-facing explanation so the persisted message is non-empty.""" - _TOOL_INVOCATIONS.clear() - - class _EmptyContentFilterModel(BaseChatModel): - """Mimics Kimi/Moonshot refusing a sensitive question: an empty - assistant message flagged finish_reason='content_filter'.""" - - @property - def _llm_type(self) -> str: - return "fake-empty-content-filter" - - def bind_tools(self, tools, **kwargs): - return self - - def _generate(self, messages, stop=None, run_manager=None, **kwargs): - msg = AIMessage(content="", response_metadata={"finish_reason": "content_filter"}) - return ChatResult(generations=[ChatGeneration(message=msg)]) - - async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs): - return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs) - - agent = create_agent( - model=_EmptyContentFilterModel(), - tools=[write_file], - middleware=[SafetyFinishReasonMiddleware()], - ) - result = agent.invoke({"messages": [HumanMessage(content="a sensitive question")]}) - final_ai = next(m for m in reversed(result["messages"]) if isinstance(m, AIMessage)) - - # The poison condition: the persisted assistant message must not be empty. - assert isinstance(final_ai.content, str) - assert final_ai.content.strip(), "empty assistant message would be rejected by strict providers on the next turn" - assert "safety-related signal" in final_ai.content - assert "returned no content" in final_ai.content - - # Observability stamp present with zero suppressed tool calls. - record = final_ai.additional_kwargs.get("safety_termination") - assert record is not None - assert record["suppressed_tool_call_count"] == 0 - - # Real provider reason preserved for downstream SSE / converters. - assert final_ai.response_metadata.get("finish_reason") == "content_filter" - assert _TOOL_INVOCATIONS == [] - - -def test_normal_tool_call_round_trip_is_not_affected(): - """Regression: a healthy finish_reason='tool_calls' response must still - execute the tool. The middleware must not over-fire.""" - _TOOL_INVOCATIONS.clear() - - class _HealthyToolModel(BaseChatModel): - call_count: int = 0 - - @property - def _llm_type(self) -> str: - return "fake-healthy" - - def bind_tools(self, tools, **kwargs): - return self - - def _generate(self, messages, stop=None, run_manager=None, **kwargs): - self.call_count += 1 - if self.call_count == 1: - msg = AIMessage( - content="", - tool_calls=[ - { - "id": "call_ok", - "name": "write_file", - "args": {"path": "/tmp/ok", "content": "complete content"}, - } - ], - response_metadata={"finish_reason": "tool_calls"}, - ) - else: - msg = AIMessage(content="done", response_metadata={"finish_reason": "stop"}) - return ChatResult(generations=[ChatGeneration(message=msg)]) - - async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs): - return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs) - - agent = create_agent( - model=_HealthyToolModel(), - tools=[write_file], - middleware=[SafetyFinishReasonMiddleware()], - ) - agent.invoke({"messages": [HumanMessage(content="write")]}) - - assert _TOOL_INVOCATIONS == [{"path": "/tmp/ok", "content": "complete content"}] diff --git a/backend/tests/test_stream_get_action_rejected.py b/backend/tests/test_stream_get_action_rejected.py deleted file mode 100644 index ac53d05121..0000000000 --- a/backend/tests/test_stream_get_action_rejected.py +++ /dev/null @@ -1,116 +0,0 @@ -"""GET on the join-stream route must not carry cancel actions. - -The existing-run stream path supports both GET and POST; POST's ``action`` -branch cancels the run. The CSRF middleware exempts GET, while a SameSite=Lax -session cookie still accompanies a cross-site top-level safe navigation. An -attacker-induced navigation to -``GET .../runs/{run_id}/stream?action=interrupt|rollback`` was therefore a -state-changing GET that bypassed the CSRF protection guarding the POST -variant. These tests pin that GET stays a read-only join and POST keeps -cancelling. -""" - -from __future__ import annotations - -import asyncio - -import pytest -from _router_auth_helpers import make_authed_test_app -from fastapi.testclient import TestClient - -from app.gateway.routers import thread_runs -from deerflow.runtime import RunManager, RunStatus -from deerflow.runtime.stream_bridge import MemoryStreamBridge - -THREAD_ID = "thread-get-action" - - -def _make_seeded_run_client(run_status: RunStatus = RunStatus.running) -> tuple[TestClient, RunManager, str]: - mgr = RunManager() - - async def _seed(): - record = await mgr.create(THREAD_ID) - await mgr.set_status(record.run_id, run_status) - return record.run_id - - run_id = asyncio.run(_seed()) - app = make_authed_test_app() - app.include_router(thread_runs.router) - app.state.run_manager = mgr - app.state.stream_bridge = MemoryStreamBridge() - return TestClient(app, raise_server_exceptions=False), mgr, run_id - - -def _get_run_status(mgr: RunManager, run_id: str) -> RunStatus: - async def _read_status() -> RunStatus: - record = await mgr.get(run_id) - assert record is not None - return record.status - - return asyncio.run(_read_status()) - - -@pytest.mark.parametrize("action", ("interrupt", "rollback")) -def test_get_with_cancel_action_is_rejected(action: str): - """GET + action=interrupt|rollback must answer 405, not cancel.""" - client, mgr, run_id = _make_seeded_run_client() - response = client.get(f"/api/threads/{THREAD_ID}/runs/{run_id}/stream?action={action}") - assert response.status_code == 405 - assert response.headers["allow"] == "POST" - assert "POST" in response.json()["detail"] - assert _get_run_status(mgr, run_id) == RunStatus.running - - -def test_get_with_invalid_action_has_one_validation_error(): - """The dependency must not duplicate the endpoint's query validation.""" - client, mgr, run_id = _make_seeded_run_client() - - response = client.get(f"/api/threads/{THREAD_ID}/runs/{run_id}/stream?action=invalid") - - assert response.status_code == 422 - assert len(response.json()["detail"]) == 1 - assert _get_run_status(mgr, run_id) == RunStatus.running - - -def test_unsupported_method_preserves_post_allow_header(): - """Splitting the handlers must not change Starlette's route precedence.""" - client, _, run_id = _make_seeded_run_client() - - response = client.put(f"/api/threads/{THREAD_ID}/runs/{run_id}/stream") - - assert response.status_code == 405 - assert response.headers["allow"] == "POST" - - -def test_get_with_action_is_rejected_before_owner_lookup(): - """The method gate must not reveal whether a thread metadata row exists.""" - app = make_authed_test_app(owner_check_passes=False) - app.include_router(thread_runs.router) - client = TestClient(app, raise_server_exceptions=False) - - response = client.get(f"/api/threads/{THREAD_ID}/runs/missing-run/stream?action=interrupt") - - assert response.status_code == 405 - assert response.headers["allow"] == "POST" - app.state.thread_store.check_access.assert_not_awaited() - - -def test_get_without_action_still_joins(): - """The method guard must not break the plain read-only GET join. The - seeded run is terminal so the SSE stream emits `end` and completes.""" - client, _, run_id = _make_seeded_run_client(run_status=RunStatus.success) - with client.stream("GET", f"/api/threads/{THREAD_ID}/runs/{run_id}/stream") as response: - assert response.status_code == 200 - events = [line for line in response.iter_lines() if line.startswith("event:")] - - assert events[-1].strip() == "event: end" - - -@pytest.mark.parametrize("action", ("interrupt", "rollback")) -def test_post_with_cancel_action_still_cancels(action: str): - """The documented POST cancel-then-stream flow is unchanged.""" - client, mgr, run_id = _make_seeded_run_client() - with client.stream("POST", f"/api/threads/{THREAD_ID}/runs/{run_id}/stream?action={action}") as response: - assert response.status_code == 200 - - assert _get_run_status(mgr, run_id) == RunStatus.interrupted