fix(log): redact the debug_requests record and write each body to a file in a per-run folder

This commit is contained in:
imSp4rky
2026-12-04 13:18:35 -07:00
parent 8e850d168e
commit 67dea28712
8 changed files with 304 additions and 212 deletions
+38 -9
View File
@@ -5,6 +5,7 @@ for the hardcoded-message TypeError footgun), and tool_run logging."""
from __future__ import annotations
import json
import threading
from pathlib import Path
import pytest
@@ -84,16 +85,11 @@ def test_log_event_emits_with_level_message_and_context(debug_log: Path):
assert e["context"] == {"count": 3}
def test_a_raw_entry_keeps_its_values_and_redacts_only_local_paths(debug_log: Path):
home = str(Path.home())
values = {"url": "https://h/x?access_token=T1", "password": "P1", "key": "K1", "file": f"{home}/a.txt"}
log_event("raw_event", raw=True, message=f"token=T1 {home}/m", context=values)
def test_an_entry_masks_secret_values_and_local_paths(debug_log: Path):
values = {"url": "https://h/x?access_token=T1", "password": "P1", "key": "K1", "file": f"{Path.home()}/a.txt"}
log_event("masked_event", message="token=T1", context=values)
entries = read_entries(debug_log)
raw, masked = find(entries, "raw_event"), find(entries, "masked_event")
assert raw["message"] == "token=T1 ~/m"
assert raw["context"] == {**values, "file": "~/a.txt"}
masked = find(read_entries(debug_log), "masked_event")
assert masked["message"] == "token=***"
assert masked["context"] == {"url": "redacted", "password": "[REDACTED]", "key": "[REDACTED]", "file": "~/a.txt"}
@@ -102,12 +98,45 @@ def test_a_value_too_deep_for_the_log_never_raises(debug_log: Path):
deep: list = []
for _ in range(5000):
deep = [deep]
log_event("deep_event", raw=True, context={"body": deep})
log_event("deep_event", context={"body": deep})
log_event("after_event")
assert find(read_entries(debug_log), "after_event")
def test_a_body_after_close_writes_no_file(debug_log: Path):
logger = get_debug_logger()
assert logger.write_body(logger.body_number(), ["GET", "h", "a"], ".txt", b"first") == "0001_GET_h_a.txt"
close_debug_logger()
assert logger.write_body(logger.body_number(), ["GET", "h", "b"], ".txt", b"late") is None
assert [p.name for p in debug_log.with_suffix("").iterdir()] == ["0001_GET_h_a.txt"]
def test_a_body_file_of_an_earlier_run_is_never_overwritten(debug_log: Path):
folder = debug_log.with_suffix("")
folder.mkdir()
(folder / "0001_GET_h_a.txt").write_bytes(b"earlier")
logger = get_debug_logger()
assert logger.write_body(logger.body_number(), ["GET", "h", "a"], ".txt", b"later") is None
assert (folder / "0001_GET_h_a.txt").read_bytes() == b"earlier"
def test_body_numbers_stay_unique_across_threads(debug_log: Path):
logger = get_debug_logger()
numbers: list[int] = []
threads = [
threading.Thread(target=lambda: numbers.extend(logger.body_number() for _ in range(200))) for _ in range(8)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert sorted(numbers) == list(range(1, 1601))
def test_log_event_noop_when_disabled():
close_debug_logger()
assert get_debug_logger() is None
+118 -95
View File
@@ -1,4 +1,4 @@
"""The debug_requests http_request entry in the JSONL debug log, for both HTTP session types."""
"""The debug_requests http_request entry in the JSONL debug log and the body files, for both HTTP session types."""
from __future__ import annotations
@@ -6,6 +6,7 @@ import copy
import importlib
import json
import logging
import re
import threading
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -43,7 +44,7 @@ class Server(ThreadingHTTPServer):
def __init__(self) -> None:
self.hits: list[str] = []
self.docs: dict[str, str] = {}
self.docs: dict[str, str | bytes] = {}
self.types: dict[str, str] = {}
self.lock = threading.Lock()
super().__init__(("127.0.0.1", 0), Handler)
@@ -80,7 +81,8 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
return
ranged = bool(self.headers.get("Range")) and not path.startswith("/plain")
body = self.server.docs[path].encode() if path in self.server.docs else BODY[:1] if ranged else BODY
body = self.server.docs.get(path, BODY[:1] if ranged else BODY)
body = body.encode() if isinstance(body, str) else body
if path.startswith("/chunked"):
self.send_response(200)
self.send_header("Content-Type", self.server.types.get(path, "text/plain"))
@@ -126,6 +128,10 @@ def records(path: Path) -> list[dict]:
return [e for e in lines if e.get("operation") == "http_request"]
def folder(path: Path) -> Path:
return path.with_suffix("")
def requests_session() -> rq.Session:
session = rq.Session()
adapter = HTTPAdapter(max_retries=Retry(total=2, backoff_factor=0, status_forcelist=[503]))
@@ -150,20 +156,23 @@ SESSIONS = [pytest.param(requests_session, id="requests"), pytest.param(rnet_ses
@pytest.mark.parametrize("make_session", SESSIONS)
def test_the_entry_keeps_host_path_and_query_as_received(server, debug_log, make_session):
make_session().get(f"{server.url}/api/{JWT}/items;hmac=a1b2?id=5&access_token=SECRET123")
def test_the_entry_masks_a_secret_query_value_and_names_the_body_file(server, debug_log, make_session):
server.types["/api/items"] = "text/plain"
make_session().get(f"{server.url}/api/items?id=5&access_token=SECRET123")
(entry,) = records(debug_log)
assert entry["request"] == {
"method": "GET",
"host": server.host,
"path": f"/api/{JWT}/items;hmac=a1b2",
"query": "id=5&access_token=SECRET123",
"path": "/api/items",
"query": "id=5&access_token=***",
"attempt": 1,
}
assert entry["response"] == {"status": 200, "size": len(BODY)}
name = f"0001_GET_{server.host.replace(':', '_')}_items.txt"
assert entry["response"] == {"status": 200, "size": len(BODY), "body_file": name}
assert entry["duration_ms"] >= 0
assert entry["failure"] is None
assert (folder(debug_log) / name).read_bytes() == BODY
@pytest.mark.parametrize("make_session", SESSIONS)
@@ -235,6 +244,7 @@ def test_a_debug_run_without_debug_requests_records_nothing(
assert server.hits.count("/api") == 1
assert records(debug_log) == []
assert not folder(debug_log).exists()
assert "session_start" in debug_log.read_text(encoding="utf-8")
@@ -283,97 +293,122 @@ def test_the_rnet_console_line_keeps_the_query(server, debug_log, caplog):
def body_of(
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str, **kw: Any
) -> dict:
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str | bytes, **kw: Any
) -> tuple[str, bytes] | None:
"""The response body file name and bytes of one GET, or None when it wrote none."""
server.docs[path] = doc
if kind:
server.types[path] = kind
make_session().get(f"{server.url}{path}", **kw)
(entry,) = records(debug_log)
return entry["response"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_json_body_is_stored_as_an_object_as_received(server, debug_log, make_session):
doc = json.dumps({"items": [{"lang": "xx-ZZ"}], "access_token": "T1", "key": "K1", "file": f"{Path.home()}/a"})
response = body_of(server, debug_log, make_session, "/api/json", "application/json; charset=utf-8", doc)
assert response["body"] == {"items": [{"lang": "xx-ZZ"}], "access_token": "T1", "key": "K1", "file": "~/a"}
assert str(Path.home()) not in debug_log.read_text(encoding="utf-8")
name = entry["response"].get("body_file")
return (name, (folder(debug_log) / name).read_bytes()) if name else None
@pytest.mark.parametrize(
("path", "kind", "doc"),
[
pytest.param("/a.txt", "text/plain", "error inside a 200", id="text"),
pytest.param("/bad-json", "application/json", "{not json", id="bad-json"),
pytest.param("/m.xml", "application/xml", "<a/>", id="xml"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_text_body_is_stored_as_a_string(server, debug_log, make_session, path, kind, doc):
assert body_of(server, debug_log, make_session, path, kind, doc)["body"] == doc
@pytest.mark.parametrize(
("path", "kind", "kw"),
[
pytest.param("/seg.bin", "application/octet-stream", {}, id="binary"),
pytest.param("/seg.m3u8", "video/mp2t", {}, id="media-type"),
pytest.param("/no-type", None, {}, id="no-type"),
pytest.param("/api/stream", "application/json", {"stream": True}, id="stream"),
pytest.param("/events", "text/event-stream", {}, id="event-stream"),
pytest.param("/v/manifest.mpd", "application/dash+xml", {}, id="mpd"),
pytest.param("/v/manifest.mpd", "text/xml", {}, id="mpd-suffix"),
pytest.param("/master", "application/vnd.apple.mpegurl", {}, id="m3u8"),
pytest.param("/v.m3u8", "text/plain", {}, id="m3u8-suffix"),
pytest.param("/a.ism/Manifest", "application/vnd.ms-sstr+xml", {}, id="ism"),
pytest.param("/a.ism/Manifest", "text/xml", {}, id="ism-suffix"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_no_body_for_binary_or_streamed_responses(server, debug_log, make_session, path, kind, kw):
assert "body" not in body_of(server, debug_log, make_session, path, kind, '{"a": 1}', **kw)
@pytest.mark.parametrize(
("kw", "expected"),
("path", "kind", "doc", "extension"),
[
pytest.param("/a.txt", "text/plain", "error inside a 200", ".txt", id="text"),
pytest.param(
{"json": {"q": "query Me", "variables": {"id": 1}}}, {"q": "query Me", "variables": {"id": 1}}, id="json"
"/api/json", "application/json; charset=utf-8", '{"access_token": "TOKEN_VALUE"}', ".json", id="json"
),
pytest.param({"data": {"a": "1", "b": "x y"}}, "a=1&b=x+y", id="form"),
pytest.param({"data": "<Envelope/>", "headers": {"Content-Type": "text/xml"}}, "<Envelope/>", id="xml"),
pytest.param("/jsonp", "application/x-javascript; charset=utf-8", 'callback({"sub":[]})', ".js", id="jsonp"),
pytest.param("/problem", "application/problem+json", '{"title": "x"}', ".json", id="json-suffix"),
pytest.param("/a.xml", "application/xml", "<a/>", ".xml", id="application-xml"),
pytest.param("/error.mpd", "application/json", '{"error": 1}', ".json", id="json-at-manifest-path"),
pytest.param("/v.m3u8", "text/plain", "#EXTM3U\n", ".m3u8", id="m3u8-path"),
pytest.param("/m.xml", "text/xml", "<a/>", ".xml", id="xml"),
pytest.param("/no-type", None, "plain words", ".bin", id="no-type"),
pytest.param("/latin", "text/plain", "caf\xe9".encode("latin-1"), ".txt", id="not-utf8"),
pytest.param("/licence", "application/octet-stream", b"\x08\x04\x12\xff\x00", ".bin", id="binary"),
pytest.param("/a.png", "image/png", b"\x89PNG\r\n\x1a\n\x00", ".png", id="image"),
pytest.param("/v/manifest.mpd", "application/dash+xml", "<MPD/>", ".mpd", id="mpd"),
pytest.param("/master", "application/vnd.apple.mpegurl", "#EXTM3U\n", ".m3u8", id="m3u8"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_text_request_body_is_recorded_as_sent(server, debug_log, make_session, kw, expected):
make_session().post(f"{server.url}/api/send", **kw)
def test_each_response_body_is_a_file_with_the_bytes_as_received(
server, debug_log, make_session, path, kind, doc, extension
):
name, data = body_of(server, debug_log, make_session, path, kind, doc)
assert records(debug_log)[-1]["request"]["body"] == expected
assert data == (doc if isinstance(doc, bytes) else doc.encode())
assert name.endswith(extension)
assert "body" not in records(debug_log)[0]["response"]
assert b"TOKEN_VALUE" not in debug_log.read_bytes()
@pytest.mark.parametrize(
"kw",
("path", "kind", "doc", "kw"),
[
pytest.param({"data": b"\x08\x04\x12", "headers": {"Content-Type": "application/octet-stream"}}, id="binary"),
pytest.param({"data": b"\x08\x04\x12"}, id="no-type"),
pytest.param({}, id="none"),
pytest.param("/api/stream", "application/json", '{"a": 1}', {"stream": True}, id="stream"),
pytest.param("/events", "text/event-stream", "data: 1\n\n", {}, id="event-stream"),
pytest.param("/empty", "application/json", "", {}, id="empty"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_no_request_body_for_a_binary_or_empty_request(server, debug_log, make_session, kw):
make_session().post(f"{server.url}/api/send", **kw)
def test_no_body_file_for_a_streamed_or_empty_response(server, debug_log, make_session, path, kind, doc, kw):
assert body_of(server, debug_log, make_session, path, kind, doc, **kw) is None
assert not folder(debug_log).exists()
assert "body" not in records(debug_log)[-1]["request"]
@pytest.mark.parametrize(
("kw", "extension"),
[
pytest.param({"data": {"username": "EXAMPLE", "password": "P4SSWORD"}}, ".bin", id="form"),
pytest.param({"json": {"username": "EXAMPLE", "password": "P4SSWORD"}}, ".json", id="json"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_request_body_is_a_file_and_never_in_the_log(server, debug_log, make_session, kw, extension):
server.types["/login"] = "application/json"
server.docs["/login"] = '{"ok": true}'
make_session().post(f"{server.url}/login", **kw)
(entry,) = records(debug_log)
stem = f"0001_POST_{server.host.replace(':', '_')}_login"
assert (entry["request"]["body_file"], entry["response"]["body_file"]) == (
f"{stem}_request{extension}",
f"{stem}.json",
)
assert b"P4SSWORD" in (folder(debug_log) / entry["request"]["body_file"]).read_bytes()
assert (folder(debug_log) / f"{stem}.json").read_bytes() == b'{"ok": true}'
assert "P4SSWORD" not in debug_log.read_text(encoding="utf-8")
assert "body" not in entry["request"] and "body" not in entry["response"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_server_process_records_no_request_body(server, debug_log, make_session, monkeypatch):
monkeypatch.setattr(http_session, "record_bodies", False)
make_session().post(f"{server.url}/api/send", json={"a": 1})
def test_a_bytes_request_body_is_kept_as_sent(server, debug_log, make_session):
session = make_session()
session.post(f"{server.url}/api/send", data=b"\x08\x04\x12")
session.post(f"{server.url}/api/send")
assert "body" not in records(debug_log)[-1]["request"]
with_body, without_body = records(debug_log)
assert (folder(debug_log) / with_body["request"]["body_file"]).read_bytes() == b"\x08\x04\x12"
assert "body_file" not in without_body["request"]
def test_a_bytes_content_type_never_fails_the_request(server, debug_log):
response = requests_session().post(
f"{server.url}/api/send", data="{}", headers={"Content-Type": b"application/json"}
)
assert response.status_code == 200
assert records(debug_log)[-1]["request"]["body_error"].startswith("TypeError")
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_hostile_path_stays_inside_the_folder(server, debug_log, tmp_path, make_session):
session = make_session()
for path in ("/../..%2f", f"/{'a' * 300}:b*c%7Cd%3C%3E%22%5C"):
session.get(f"{server.url}{path}")
files = [p for p in tmp_path.rglob("*") if p.is_file()]
names = [p.name for p in files if p != debug_log]
assert len(names) == 2
assert all(p == debug_log or p.parent == folder(debug_log) for p in files)
assert all(re.fullmatch(r"[A-Za-z0-9._-]{1,150}", name) for name in names)
assert sorted(e["response"]["body_file"] for e in records(debug_log)) == sorted(names)
@pytest.mark.parametrize("make_session", SESSIONS)
@@ -385,13 +420,6 @@ def test_the_size_comes_from_the_body_without_a_content_length(server, debug_log
assert records(debug_log)[-1]["response"]["size"] == len(server.docs["/chunked"])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_json_reply_at_a_manifest_path_keeps_its_body(server, debug_log, make_session):
assert body_of(server, debug_log, make_session, "/playback/manifest", "application/json", '{"a": 1}')["body"] == {
"a": 1
}
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session):
server.docs["/api/read"] = '{"a": 1}'
@@ -404,13 +432,13 @@ def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_se
assert b"".join(streamed.iter_content(3)) == b'{"a": 1}'
@pytest.mark.parametrize("kind", ["application/json", "text/plain"])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_body_over_the_limit_is_cut_and_marked(server, debug_log, monkeypatch, make_session, kind):
def test_a_body_over_the_limit_is_cut_and_marked(server, debug_log, monkeypatch, make_session):
monkeypatch.setattr(config, "debug_requests_body_limit", 5)
response = body_of(server, debug_log, make_session, "/api/long", kind, '{"xyzwvu": 1}')
_, data = body_of(server, debug_log, make_session, "/api/long", "application/json", '{"xyzwvu": 1}')
assert (response["body"], response["body_size"], response["body_cut"]) == ('{"xyz', 13, True)
response = records(debug_log)[0]["response"]
assert (data, response["body_size"], response["body_cut"]) == (b'{"xyz', 13, True)
def test_a_failed_body_read_is_recorded_and_raised_again(debug_log):
@@ -430,15 +458,6 @@ def test_a_failed_body_read_is_recorded_and_raised_again(debug_log):
assert entry["response"]["body_error"].startswith("ChunkedEncodingError")
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_body_too_deep_for_the_log_never_breaks_the_caller(server, debug_log, make_session):
deep = "[" * 5000 + "]" * 5000
server.docs["/api/deep"] = deep
server.types["/api/deep"] = "application/json"
assert make_session().get(f"{server.url}/api/deep").text == deep
@pytest.mark.parametrize(("value", "limit"), [(None, 0), ("5", 5), (-5, 0)])
def test_the_body_limit_is_a_byte_count(value, limit):
assert Config(debug_requests_body_limit=value).debug_requests_body_limit == limit
@@ -469,10 +488,13 @@ def worker_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_path, make_session, start):
start(monkeypatch, tmp_path)
response = body_of(server, debug_log, make_session, "/api/json", "application/json", '{"a": 1}')
make_session().post(f"{server.url}/api/json", json={"a": 1})
assert http_session.record_bodies is False
assert response == {"status": 200, "size": 8}
assert records(debug_log)[0]["response"] == {"status": 200, "size": len(BODY)}
assert "body_file" not in records(debug_log)[0]["request"]
assert not folder(debug_log).exists()
def test_serve_keeps_request_lines_out_of_the_dashboard_log(monkeypatch, tmp_path, caplog):
@@ -507,7 +529,7 @@ def test_hls_media_probes_are_not_recorded_but_the_playlist_is(server, debug_log
assert (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2)
assert paths(debug_log) == ["/v.m3u8"]
assert "body" not in records(debug_log)[0]["response"]
assert len(list(folder(debug_log).iterdir())) == 1
@pytest.mark.parametrize("make_session", SESSIONS)
@@ -543,6 +565,7 @@ def test_dash_init_reads_are_not_recorded_but_the_manifest_is(server, debug_log,
assert [server.hits.count(p) for p in ("/init.mp4", "/file.mp4", "/list.mp4")] == [1, 2, 1]
assert paths(debug_log) == ["/manifest.mpd"]
assert [p.suffix for p in folder(debug_log).iterdir()] == [".mpd"]
@pytest.mark.parametrize("make_session", SESSIONS)