From 689bb625c0a1ff68b597c922efb0e999f0c4f166 Mon Sep 17 00:00:00 2001 From: Alejandro Estringana Ruiz Date: Fri, 13 Nov 2026 11:05:09 +0100 Subject: [PATCH] Persist proxy flows off the event loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mitmproxy runs every hook on a single asyncio event loop and does not send the response back to the client until the hook returns. The proxy's response hook used to write the captured flow synchronously, so a slow open() + json.dump() froze the whole proxy. On the CI runner behind APPSEC-71652, a ~14 s disk stall in that hook made the PHP sidecar's trace POST time out, the trace of the blocked request was dropped, and the test failed with "No appsec event validate this condition". The bug is in the proxy, not in PHP — any tracer with a short-enough trace-POST timeout is exposed. Move deserialization and file writes to a single background worker thread (utils/proxy/_flow_writer.py). The response hook only queues the captured flow data, so the sidecar always gets its response on time. One worker preserves submission order, so file numbering is unchanged. The addon's done hook flushes the queue on shutdown, and a SIGTERM handler makes docker stop wait for that flush when the proxy runs as PID 1. Reproduction: injecting a 20 s stall and running APPSEC_API_SECURITY_RC on PHP apache-mod-7.4 reproduces the CI failure on the old code (zero flows served during the stall, blocked trace file absent) and passes with the fix (28 flows served during the stall, blocked trace written 11 ms after it starts). Regression tests in tests/test_the_test/test_proxy_writer.py. RULES APPLIED: .agents/rules/general-behavior.md --- tests/test_the_test/test_proxy_writer.py | 141 +++++++++++++++++++++++ utils/proxy/_flow_writer.py | 119 +++++++++++++++++++ utils/proxy/core.py | 61 +++++----- 3 files changed, 291 insertions(+), 30 deletions(-) create mode 100644 tests/test_the_test/test_proxy_writer.py create mode 100644 utils/proxy/_flow_writer.py diff --git a/tests/test_the_test/test_proxy_writer.py b/tests/test_the_test/test_proxy_writer.py new file mode 100644 index 00000000000..2167e153bfd --- /dev/null +++ b/tests/test_the_test/test_proxy_writer.py @@ -0,0 +1,141 @@ +"""The proxy must keep serving flows while the disk is slow (APPSEC-71652). + +mitmproxy only sends a response to the client once the response hook returns. When that hook wrote the flow +file synchronously, a ~14s I/O stall on a CI runner froze the whole proxy, the PHP sidecar's trace submission +timed out, and the trace never reached the test. +""" + +from collections.abc import Iterator +import json +from pathlib import Path +import threading +import time +from typing import Any + +from utils import pytest, scenarios +from utils.proxy import _flow_writer +from utils.proxy._flow_writer import FlowWriter + + +@pytest.fixture +def writer() -> Iterator[FlowWriter]: + result = FlowWriter() + try: + yield result + finally: + result.close() + + +def _data(folder: Path, name: str, path: str) -> dict[str, Any]: + return { + "log_filename": str(folder / name), + "path": path, + "query": "", + "request": {"headers": [("content-type", "application/json")], "length": 0}, + "response": {"status_code": 200, "headers": [("content-type", "application/json")], "length": 0}, + } + + +def _submit(writer: FlowWriter, folder: Path, name: str, path: str) -> None: + writer.submit( + "flow-id", + _data(folder, name, path), + "library", + json.dumps({"path": path}).encode(), + b'{"ok": true}', + str(folder / "files"), + response_killed=False, + ) + + +@scenarios.test_the_test +def test_submit_does_not_wait_for_the_disk(writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + disk_released = threading.Event() + original_deserialize = _flow_writer.deserialize + + def stalled_deserialize(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 + # stands for the slow disk: everything the writer thread does happens after this + disk_released.wait(timeout=30) + original_deserialize(*args, **kwargs) + + monkeypatch.setattr(_flow_writer, "deserialize", stalled_deserialize) + + start = time.monotonic() + _submit(writer, tmp_path, "00000__v0.4_traces.json", "/v0.4/traces") + _submit(writer, tmp_path, "00001__v0.7_config.json", "/v0.7/config") + elapsed = time.monotonic() - start + + # the response hook can return, so mitmproxy answers the tracer, while the flows are not on disk yet + assert elapsed < 1, f"submit blocked for {elapsed:.1f}s on a stalled disk" + assert not list(tmp_path.glob("*.json")) + + disk_released.set() + writer.close() # flushes the pending writes, as on proxy shutdown + + assert sorted(p.name for p in tmp_path.glob("*.json")) == ["00000__v0.4_traces.json", "00001__v0.7_config.json"] + + data = json.loads((tmp_path / "00001__v0.7_config.json").read_text()) + assert data["path"] == "/v0.7/config" + assert data["request"]["content"] == {"path": "/v0.7/config"} + assert data["response"]["content"] == {"ok": True} + + +@scenarios.test_the_test +def test_flows_are_written_in_submission_order( + writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + written: list[str] = [] + original_persist_flow = _flow_writer.persist_flow + + def recording_persist_flow(data: dict[str, Any], *args: Any, **kwargs: Any) -> None: # noqa: ANN401 + original_persist_flow(data, *args, **kwargs) + written.append(Path(data["log_filename"]).name) + + monkeypatch.setattr(_flow_writer, "persist_flow", recording_persist_flow) + + names = [f"{i:05d}__v0.4_traces.json" for i in range(50)] + for name in names: + _submit(writer, tmp_path, name, "/v0.4/traces") + writer.close() + + assert written == names + + +@scenarios.test_the_test +def test_killed_response_is_saved_as_none(writer: FlowWriter, tmp_path: Path) -> None: + writer.submit( + "flow-id", + _data(tmp_path, "00000__v0.4_traces.json", "/v0.4/traces"), + "library", + b'{"a": 1}', + b'{"b": 2}', + str(tmp_path / "files"), + response_killed=True, + ) + writer.close() + + data = json.loads((tmp_path / "00000__v0.4_traces.json").read_text()) + assert data["request"]["content"] == {"a": 1} + assert data["response"] is None + + +@scenarios.test_the_test +def test_failed_write_does_not_stop_the_writer( + writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + original_dump = json.dump + calls = {"count": 0} + + def flaky_dump(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 + calls["count"] += 1 + if calls["count"] == 1: + raise OSError("No space left on device") + original_dump(*args, **kwargs) + + monkeypatch.setattr(_flow_writer.json, "dump", flaky_dump) + + _submit(writer, tmp_path, "00000__v0.7_config.json", "/v0.7/config") + _submit(writer, tmp_path, "00001__v0.7_config.json", "/v0.7/config") + writer.close() + + assert json.loads((tmp_path / "00001__v0.7_config.json").read_text())["path"] == "/v0.7/config" diff --git a/utils/proxy/_flow_writer.py b/utils/proxy/_flow_writer.py new file mode 100644 index 00000000000..d58d3ad97a1 --- /dev/null +++ b/utils/proxy/_flow_writer.py @@ -0,0 +1,119 @@ +"""Persists the flows seen by the proxy, without blocking its event loop. + +mitmproxy runs every hook on a single event loop, and sends the response to the client only once the response +hook returns. When that hook wrote the flow file synchronously, a slow disk stalled the whole proxy: during a +~14s I/O stall on a CI runner no flow was served, the PHP sidecar's trace submission timed out, and the trace +was dropped (APPSEC-71652). + +This module does not depend on mitmproxy, so it can be tested from the runner. +""" + +from concurrent.futures import Future, ThreadPoolExecutor +import json +import os +from typing import Any + +from ._deserializer import deserialize, Interface +from .utils import logger + + +class ObjectDumpEncoder(json.JSONEncoder): + def default(self, o: Any) -> Any: # noqa: ANN401 + if isinstance(o, bytes): + return str(o) + return json.JSONEncoder.default(self, o) + + +def persist_flow( + data: dict[str, Any], + interface: Interface, + request_content: bytes | None, + response_content: bytes | None, + export_content_files_to: str, + *, + response_killed: bool, +) -> None: + """Deserialize the request and response content into data, and write it to data["log_filename"]""" + + deserialize( + data, + key="request", + content=request_content, + interface=interface, + export_content_files_to=export_content_files_to, + ) + + if response_killed: + data["response"] = None + else: + deserialize( + data, + key="response", + content=response_content, + interface=interface, + export_content_files_to=export_content_files_to, + ) + + with open(data["log_filename"], "w", encoding="utf-8", opener=lambda path, flags: os.open(path, flags, 0o777)) as f: + json.dump(data, f, indent=2, cls=ObjectDumpEncoder) + + +class FlowWriter: + """Runs persist_flow on a background thread. + + A single worker keeps the files written in the order their numbers were assigned. + """ + + def __init__(self) -> None: + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="proxy-writer") + + def submit( + self, + flow_id: str, + data: dict[str, Any], + interface: Interface, + request_content: bytes | None, + response_content: bytes | None, + export_content_files_to: str, + *, + response_killed: bool, + ) -> Future[None]: + """Queue the flow and return immediately. data must not be modified by the caller afterwards""" + return self._executor.submit( + self._persist_flow, + flow_id, + data, + interface, + request_content, + response_content, + export_content_files_to, + response_killed=response_killed, + ) + + def close(self) -> None: + """Wait for all queued flows to be written""" + self._executor.shutdown(wait=True) + + @staticmethod + def _persist_flow( + flow_id: str, + data: dict[str, Any], + interface: Interface, + request_content: bytes | None, + response_content: bytes | None, + export_content_files_to: str, + *, + response_killed: bool, + ) -> None: + # the executor would silently keep the exception in a future nobody reads: log it instead + try: + persist_flow( + data, + interface, + request_content, + response_content, + export_content_files_to, + response_killed=response_killed, + ) + except Exception: + logger.exception(f"Flow {flow_id}: failed to save {data.get('log_filename')}") diff --git a/utils/proxy/core.py b/utils/proxy/core.py index 353670e4756..916989c24a8 100644 --- a/utils/proxy/core.py +++ b/utils/proxy/core.py @@ -7,7 +7,8 @@ import json import logging import os -from typing import Any, cast +import signal +from typing import TYPE_CHECKING, cast from datetime import datetime, UTC import zstandard @@ -17,11 +18,14 @@ from mitmproxy.flow import Error as FlowError from mitmproxy.http import HTTPFlow, Request -from ._deserializer import deserialize, Interface +from ._flow_writer import FlowWriter from .ports import ProxyPorts from .mocked_response import MOCKED_TRACER_RESPONSES_PATH, MockedTracerResponse from .utils import logger +if TYPE_CHECKING: + from ._deserializer import Interface + # prevent permission issues on file created by the proxy when the host is linux os.umask(0) @@ -93,13 +97,6 @@ def get_decoded_content(message: http.Message) -> bytes | None: return message.content -class ObjectDumpEncoder(json.JSONEncoder): - def default(self, o: Any) -> Any: # noqa: ANN401 - if isinstance(o, bytes): - return str(o) - return json.JSONEncoder.default(self, o) - - class _RequestLogger: def __init__(self) -> None: handler = logging.StreamHandler() @@ -121,6 +118,13 @@ def __init__(self) -> None: self.internal_mocked_tracer_responses = MockedTracerResponse.many_from_file() """Tracer mocked responses valid for the entire session, controlled by scenarios""" + self._writer = FlowWriter() + """Persists flows off the event loop, so a slow disk does not stall the proxy (see _flow_writer.py)""" + + def done(self) -> None: + """Shutdown hook called by mitmproxy: flush the flows still waiting to be written""" + self._writer.close() + @staticmethod def get_error_response(message: bytes) -> http.Response: logger.error(message) @@ -273,29 +277,21 @@ def response(self, flow: HTTPFlow): }, } - deserialize( - data, - key="request", - content=request_content, - interface=interface, - export_content_files_to=export_content_files_to, - ) - - if flow.error and flow.error.msg == FlowError.KILLED_MESSAGE: - data["response"] = None - else: - deserialize( - data, - key="response", - content=response_content, - interface=interface, - export_content_files_to=export_content_files_to, - ) + response_killed = bool(flow.error and flow.error.msg == FlowError.KILLED_MESSAGE) + # Everything the file needs has been captured from the flow. Deserializing and writing (which may also + # export multipart files) happen on the writer thread, so the client gets its response right away + # even if the disk is slow. logger.info(f"Flow {flow.id}: Saving as {log_filename}") - - with open(log_filename, "w", encoding="utf-8", opener=lambda path, flags: os.open(path, flags, 0o777)) as f: - json.dump(data, f, indent=2, cls=ObjectDumpEncoder) + self._writer.submit( + flow.id, + data, + interface, + request_content, + response_content, + export_content_files_to, + response_killed=response_killed, + ) def _modify_response(self, flow: HTTPFlow): if self.request_is_from_tracer(flow.request): @@ -337,6 +333,11 @@ def start_proxy() -> None: proxy.addons.add(_RequestLogger()) async def _run() -> None: + # The proxy runs as PID 1, which ignores SIGTERM without a handler: `docker stop` would end with a + # SIGKILL, losing the flows still queued on the writer thread. Shut down gracefully instead, so that + # the addons' done hook runs and flushes them. + asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, proxy.shutdown) + await _start_udp_forwarder( listen_host=listen_host, listen_port=ProxyPorts.dogstatsd_weblog,