mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 23:15:07 +00:00
fix(log): redact the debug_requests record and write each body to a file in a per-run folder
This commit is contained in:
@@ -675,7 +675,7 @@ A few configuration toggles help when a title will not decrypt:
|
|||||||
|------------|---------|--------|
|
|------------|---------|--------|
|
||||||
| `debug` | `false` | Global debug output. |
|
| `debug` | `false` | Global debug output. |
|
||||||
| `debug_keys` | `false` | Log decryption keys. |
|
| `debug_keys` | `false` | Log decryption keys. |
|
||||||
| `debug_requests` | `false` | Log HTTP requests to the console with `-d`, and each request with its response body to the [JSON debug log](troubleshooting.md#debug-requests). The log then holds tokens and content keys as received. |
|
| `debug_requests` | `false` | Log HTTP requests to the console with `-d`, each request to the [JSON debug log](troubleshooting.md#debug-requests), and the request and response bodies as files in a folder beside it. The folder holds tokens and content keys as sent and received. |
|
||||||
|
|
||||||
```yaml title="unshackle.yaml"
|
```yaml title="unshackle.yaml"
|
||||||
debug_keys: true
|
debug_keys: true
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ There are two independent ways to enable debug logging, and they do slightly dif
|
|||||||
|
|
||||||
## The structured JSON debug log
|
## The structured JSON debug log
|
||||||
|
|
||||||
Beyond the console output, unshackle writes a structured log in [JSON Lines](https://jsonlines.org/) format: one complete JSON object per line. You can filter, examine, and analyse this file with standard tooling (`jq`, `grep`, a text editor). It is safe to attach to a bug report, because unshackle redacts it, unless `debug_requests` is on (see [Debugging HTTP traffic](#debug-requests)).
|
Beyond the console output, unshackle writes a structured log in [JSON Lines](https://jsonlines.org/) format: one complete JSON object per line. You can filter, examine, and analyse this file with standard tooling (`jq`, `grep`, a text editor). It is safe to attach to a bug report, because unshackle redacts it.
|
||||||
|
|
||||||
### Where it is written
|
### Where it is written
|
||||||
|
|
||||||
@@ -134,13 +134,13 @@ With `debug_keys: true`, the debug log stops masking content key fields. You can
|
|||||||
!!! warning "Keys are sensitive, turn this back off"
|
!!! warning "Keys are sensitive, turn this back off"
|
||||||
`debug_keys` writes real content keys into the log file in cleartext. Only enable it while you diagnose a content key problem. Never share a log written with it on, and set it back to `false` when you are done. Note that `debug_keys` only affects the **JSON debug log file**. It does not change what the console prints.
|
`debug_keys` writes real content keys into the log file in cleartext. Only enable it while you diagnose a content key problem. Never share a log written with it on, and set it back to `false` when you are done. Note that `debug_keys` only affects the **JSON debug log file**. It does not change what the console prints.
|
||||||
|
|
||||||
Fields that are *always* redacted regardless of `debug_keys` (anything whose name contains `password`, `token`, `secret`, `auth`, or `cookie`) stay masked, so credentials never leak even in a keys-on log. The `http_request` entries of [`debug_requests`](#debug-requests) are the exception.
|
Fields that are *always* redacted regardless of `debug_keys` (anything whose name contains `password`, `token`, `secret`, `auth`, or `cookie`) stay masked, so credentials never leak even in a keys-on log.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Debugging HTTP traffic with `debug_requests` { #debug-requests }
|
## Debugging HTTP traffic with `debug_requests` { #debug-requests }
|
||||||
|
|
||||||
`debug_requests` does two things: it keeps the HTTP library logs in the console, and it writes a record of each HTTP request to the JSON debug log.
|
`debug_requests` does two things. It keeps the HTTP library logs in the console, and it writes a record of each HTTP request to the JSON debug log, with the request and response bodies as files in a separate folder.
|
||||||
|
|
||||||
### HTTP library logs in the console
|
### HTTP library logs in the console
|
||||||
|
|
||||||
@@ -163,42 +163,59 @@ With `debug_requests: true`, unshackle leaves those libraries at `DEBUG` level w
|
|||||||
|
|
||||||
### Request records in the JSON debug log
|
### Request records in the JSON debug log
|
||||||
|
|
||||||
`debug_requests` is the one switch that writes request records to the [JSON debug log](#the-structured-json-debug-log). With `debug_requests: true` and the JSON debug log on (`-d` or `debug: true`), unshackle writes one `http_request` entry for each HTTP attempt. With `debug_requests: false`, the default, a `-d` run writes no `http_request` entry. A request that unshackle retries gives one entry for each attempt. A redirect gives one entry for each hop.
|
`debug_requests` is the one switch that writes request records. With `debug_requests: true` and the JSON debug log on (`-d` or `debug: true`), unshackle writes one `http_request` entry to the [JSON debug log](#the-structured-json-debug-log) for each HTTP attempt, and the bodies to files in a separate [body folder](#the-body-folder). With `debug_requests: false`, the default, a `-d` run writes no `http_request` entry and no body folder. A request that unshackle retries gives one entry for each attempt. A redirect gives one entry for each hop.
|
||||||
|
|
||||||
|
An `http_request` entry has no body, only the name of its body file, and unshackle redacts it like each other entry of the JSON debug log (see [What gets redacted](#what-gets-redacted)). A secret query value such as `access_token=SECRET` becomes `access_token=***`. The host and the path stay readable.
|
||||||
|
|
||||||
| Field | Content |
|
| Field | Content |
|
||||||
|-------|---------|
|
|-------|---------|
|
||||||
| `request.method` | The HTTP method. |
|
| `request.method` | The HTTP method. |
|
||||||
| `request.host` | The host name and port, with no scheme and no user name or password. |
|
| `request.host` | The host name and port, with no scheme and no user name or password. |
|
||||||
| `request.path` | The URL path, as sent. |
|
| `request.path` | The URL path. |
|
||||||
| `request.query` | The query string, as sent. |
|
| `request.query` | The query string, with the secret values masked. |
|
||||||
| `request.attempt` | The attempt number, from 1. |
|
| `request.attempt` | The attempt number, from 1. |
|
||||||
| `request.body` | The body of a JSON, form, XML or `text/*` request, as sent. A JSON body is an object. A binary body is not recorded. |
|
| `request.body_file` | The name of the file in the body folder that holds the request body. |
|
||||||
| `response.status` | The HTTP status, or `null` when no response came back. |
|
| `response.status` | The HTTP status, or `null` when no response came back. |
|
||||||
| `response.size` | The `Content-Length` of the response. When the server sent none, the length of the recorded body, else `null`. |
|
| `response.size` | The `Content-Length` of the response. When the server sent none, the length of the body that unshackle read, else `null`. |
|
||||||
| `response.body` | The text response body, as received. A JSON body is a JSON object, so `jq` can query it. Other text is a string. |
|
| `response.body_file` | The name of the file in the body folder that holds the response body. |
|
||||||
| `response.body_size` | The full size of the decoded body in bytes, when unshackle cut it to `debug_requests_body_limit`. `response.size` is the size on the wire, which can be compressed. |
|
| `response.body_error` | The failure, when unshackle could not read the body. `request.body_error` is the same for a request body. |
|
||||||
| `response.body_error` | The failure, when unshackle could not read the body. |
|
| `body_size`, `body_cut` | In `request` or `response`: the full size of the body in bytes and `true`, when unshackle cut its file to `debug_requests_body_limit`. |
|
||||||
| `response.body_cut` | `true` when unshackle cut the body. A cut JSON body is a string. |
|
|
||||||
| `duration_ms` | The time from the start of the attempt to the response headers. |
|
| `duration_ms` | The time from the start of the attempt to the response headers. |
|
||||||
| `failure` | The failure, without the URL, for an attempt that raised. |
|
| `failure` | The failure, without the URL, for an attempt that raised. |
|
||||||
|
|
||||||
unshackle records the body of a JSON, XML or `text/*` response. It records no body for a manifest (MPD, M3U8 or ISM, by its content type, or by the suffix of the request path when the response is not JSON), a binary content type, an event stream, a request sent with `stream=True`, or a server process. A request body is recorded by the same rule, by the request `Content-Type`; a form body counts as text. The entries contain no headers. Core writes no entry for the media requests that it makes. These are the segment and range-probe requests of a track download, and the init segment, index and probe reads before it. A range read that service code makes still writes an entry. Playlist and manifest fetches write an entry.
|
The redaction finds a secret query value by the name of its parameter. An id or a token inside the URL path stays in the entry, and so does the value of a query parameter with a name that the redaction does not know.
|
||||||
|
|
||||||
|
Core writes no entry for the media requests that it makes. These are the segment and range-probe requests of a track download, and the init segment, index and probe reads before it. A range read that service code makes still writes an entry. Playlist and manifest fetches write an entry.
|
||||||
|
|
||||||
```console
|
```console
|
||||||
jq 'select(.operation == "http_request") | [.request.method, .request.host, .request.path, .response.status]' \
|
jq 'select(.operation == "http_request") | [.request.method, .request.host, .request.path, .response.status]' \
|
||||||
unshackle_debug_EXAMPLE_20260703-142530.jsonl
|
unshackle_debug_EXAMPLE_20260703-142530.jsonl
|
||||||
jq 'select(.operation == "http_request" and .request.path == "/v1/titles") | .response.body' \
|
|
||||||
unshackle_debug_EXAMPLE_20260703-142530.jsonl
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The record covers the HTTP sessions that unshackle builds: the session from the service's `get_session()`, the import and `--remote` sessions, and the sessions of core helpers. A separate `requests.Session` that service code makes itself writes no entry.
|
The record covers the HTTP sessions that unshackle builds: the session from the service's `get_session()`, the import and `--remote` sessions, and the sessions of core helpers. A separate `requests.Session` that service code makes itself writes no entry.
|
||||||
|
|
||||||
On a `serve` server, the entries for the requests of a service stay on the server, with no body. A download job whose `dl` run has the JSON debug log on writes them to that log. A remote session writes none, because `serve` opens no JSON debug log for it. unshackle never sends them to a remote client: not in the remote session log, the remote session channel, an API reply or an error. A remote client with its own `debug_requests: true` records its own requests to the server, with the response bodies, in its own JSON debug log.
|
|
||||||
|
|
||||||
On an HTTP session of the `requests` library, `urllib3` retries inside one send. The attempts before the last then have no `duration_ms` and no `response.size`. A request that fails after all its retries gives one entry for the last failure, with `request.attempt` set to `null`.
|
On an HTTP session of the `requests` library, `urllib3` retries inside one send. The attempts before the last then have no `duration_ms` and no `response.size`. A request that fails after all its retries gives one entry for the last failure, with `request.attempt` set to `null`.
|
||||||
|
|
||||||
!!! danger "A request record holds secrets"
|
### The body folder
|
||||||
unshackle writes the `http_request` entries as received. It masks only the local folder prefixes (`redact_paths`). With `debug_requests` on, the JSONL file holds tokens, passwords, cookies, content keys and account data, in the path, the query and the body. `debug_keys` does not apply to these entries. Keep the file on your computer. Never attach it to a report.
|
|
||||||
|
unshackle writes each body that it records to its own file, in a folder beside the JSON debug log. The folder has the name of the log without `.jsonl`, for example `unshackle_debug_EXAMPLE_20260703-142530/`. unshackle makes the folder at the first body, so a run that records no body has no folder. A file holds the bytes as sent or as received, with no change.
|
||||||
|
|
||||||
|
The name of a file has these parts, in this order:
|
||||||
|
|
||||||
|
1. A sequence number of four digits, in the order that unshackle records the requests.
|
||||||
|
2. The HTTP method.
|
||||||
|
3. The host, and the last segment of the URL path without its extension.
|
||||||
|
4. `request` for a request body. The response body of the same request has the same number.
|
||||||
|
5. An extension from the content type: `.json`, `.xml`, `.js`, `.txt`, `.html`, `.png`. A manifest with an `.mpd` or `.m3u8` path, or a DASH or HLS content type, keeps `.mpd` or `.m3u8`. An unknown type has `.bin`.
|
||||||
|
|
||||||
|
For example, `0003_POST_api.example.com_login_request.json` and `0003_POST_api.example.com_login.json`. unshackle keeps only letters, digits, `.`, `_` and `-` from the host and the path, and it limits their length, so each name is valid on Windows and each file stays in the folder.
|
||||||
|
|
||||||
|
unshackle writes a file for each recorded response, whatever its type: JSON, JSONP, XML, HTML, a manifest, or binary data such as a licence reply or an image. It writes no file for a response with no body, an event stream, a request sent with `stream=True`, or a server process. A request body gets a file when it is JSON, a form, text or bytes. A multipart, file or iterator body gets no file. Neither the log nor the folder contains headers.
|
||||||
|
|
||||||
|
On a `serve` server, the entries for the requests of a service stay on the server, and the server writes no body folder. A download job whose `dl` run has the JSON debug log on writes the entries to that log. A remote session writes none, because `serve` opens no JSON debug log for it. unshackle never sends them to a remote client: not in the remote session log, the remote session channel, an API reply or an error. A remote client with its own `debug_requests: true` records its own requests to the server in its own JSON debug log, and their bodies in its own body folder.
|
||||||
|
|
||||||
|
!!! danger "The body folder holds secrets"
|
||||||
|
unshackle writes the body files as sent and received, with no redaction. They hold the passwords, tokens, cookies, content keys and account data of each request and reply. `debug_keys` does not apply to them. Keep the body folder on your computer. Never attach it to a report.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -210,15 +227,13 @@ unshackle redacts logged strings so that debug output is safe to share. It appli
|
|||||||
- **URLs**: unshackle collapses every `http(s)` URL to `redacted`. It keeps only the file extension, so a manifest still shows as `redacted.mpd` and a segment as `redacted.m4s`. This hides the CDN, manifest, segment, and licence-server locations, but keeps the *type* of resource.
|
- **URLs**: unshackle collapses every `http(s)` URL to `redacted`. It keeps only the file extension, so a manifest still shows as `redacted.mpd` and a segment as `redacted.m4s`. This hides the CDN, manifest, segment, and licence-server locations, but keeps the *type* of resource.
|
||||||
- **Local paths**: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.
|
- **Local paths**: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.
|
||||||
|
|
||||||
The [`http_request` entries](#debug-requests) of `debug_requests` get only the local path pass. Their secrets, URLs and bodies stay as received.
|
|
||||||
|
|
||||||
The `redact_paths` config key controls path redaction, and it is **on by default**:
|
The `redact_paths` config key controls path redaction, and it is **on by default**:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
redact_paths: true # default - mask local base directories in logged paths
|
redact_paths: true # default - mask local base directories in logged paths
|
||||||
```
|
```
|
||||||
|
|
||||||
Set `redact_paths: false` if you debug a path problem locally and want to see full, unmasked paths in the console and logs. unshackle always applies secret and URL redaction in the JSON debug log, except in the `http_request` entries, and this toggle does not change that.
|
Set `redact_paths: false` if you debug a path problem locally and want to see full, unmasked paths in the console and logs. unshackle always applies secret and URL redaction in the JSON debug log, and this toggle does not change that.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -366,7 +381,7 @@ The debug log is tuned for **developers troubleshooting pipeline flow** (maximum
|
|||||||
```
|
```
|
||||||
|
|
||||||
!!! warning "No request bodies and no raw dumps"
|
!!! warning "No request bodies and no raw dumps"
|
||||||
A `log_event` entry never holds a request body or a raw dump: no full `Tracks` object, no MPD/manifest body and no response payload. Only `debug_requests` records request and response bodies, in its `http_request` entries. Log only **counts, ids, sizes, and `safe_display_url(url)`**. This keeps the log low-noise and prevents leaking title or manifest data into the file *before* redaction even runs. Redaction is a backstop, not a licence to dump raw objects.
|
A `log_event` entry never holds a request body or a raw dump: no full `Tracks` object, no MPD/manifest body and no response payload. Only `debug_requests` records request and response bodies, and only as files in its separate body folder. Log only **counts, ids, sizes, and `safe_display_url(url)`**. This keeps the log low-noise and prevents leaking title or manifest data into the file *before* redaction even runs. Redaction is a backstop, not a licence to dump raw objects.
|
||||||
|
|
||||||
!!! note "Operation names: `<area>_<event>`, no registry"
|
!!! note "Operation names: `<area>_<event>`, no registry"
|
||||||
Operation names are plain lowercase strings that follow an `<area>_<event>` convention: `manifest_dash_parse`, `drm_decrypt`, `vault_get_key`, `tool_run`. We write them inline at each call site on purpose. There is **no central registry or enum**. Do not look for one, and do not make one. The absence is a deliberate design choice, not an omission.
|
Operation names are plain lowercase strings that follow an `<area>_<event>` convention: `manifest_dash_parse`, `drm_decrypt`, `vault_get_key`, `tool_run`. We write them inline at each call site on purpose. There is **no central registry or enum**. Do not look for one, and do not make one. The absence is a deliberate design choice, not an omission.
|
||||||
|
|||||||
@@ -165,8 +165,8 @@ calls.
|
|||||||
| `redact_paths` | bool | `true` | Mask install-root / venv / home prefixes in logged paths (`<unshackle>`, `<venv>`, `~`). Set `false` to show full paths. |
|
| `redact_paths` | bool | `true` | Mask install-root / venv / home prefixes in logged paths (`<unshackle>`, `<venv>`, `~`). Set `false` to show full paths. |
|
||||||
| `debug` | bool | `false` | Global debug mode. |
|
| `debug` | bool | `false` | Global debug mode. |
|
||||||
| `debug_keys` | bool | `false` | Log decryption keys. |
|
| `debug_keys` | bool | `false` | Log decryption keys. |
|
||||||
| `debug_requests` | bool | `false` | The one switch that writes an `http_request` entry for each HTTP attempt to the JSON debug log, with the text response body as received; `-d` and `debug` alone write none. With `-d` it also keeps the HTTP library logs in the console. See [Debugging HTTP traffic](../../guide/troubleshooting.md#debug-requests). |
|
| `debug_requests` | bool | `false` | The one switch that writes an `http_request` entry for each HTTP attempt to the JSON debug log, and the request and response bodies as files in a folder beside it; `-d` and `debug` alone write neither. With `-d` it also keeps the HTTP library logs in the console. See [Debugging HTTP traffic](../../guide/troubleshooting.md#debug-requests). |
|
||||||
| `debug_requests_body_limit` | int | `0` | The maximum number of bytes of a response body in an `http_request` entry. `0` or unset records the full body. unshackle cuts a longer body and records its full size. |
|
| `debug_requests_body_limit` | int | `0` | The maximum number of bytes of a body file of `debug_requests`. `0` or unset records the full body. unshackle cuts a longer body and records its full size. |
|
||||||
| `set_terminal_bg` | bool | `false` | Append the theme's background colour to output styling. |
|
| `set_terminal_bg` | bool | `false` | Append the theme's background colour to output styling. |
|
||||||
|
|
||||||
!!! note "Effect of `set_terminal_bg`"
|
!!! note "Effect of `set_terminal_bg`"
|
||||||
@@ -183,12 +183,11 @@ calls.
|
|||||||
`debug_keys` affects **only** content-encryption keys (the `content_key`/`key` fields).
|
`debug_keys` affects **only** content-encryption keys (the `content_key`/`key` fields).
|
||||||
Passwords, tokens, cookies, and session tokens are **always** redacted regardless of this
|
Passwords, tokens, cookies, and session tokens are **always** redacted regardless of this
|
||||||
setting, and KIDs, content key counts, and other metadata are always logged either way.
|
setting, and KIDs, content key counts, and other metadata are always logged either way.
|
||||||
The `http_request` entries of `debug_requests` are the exception.
|
|
||||||
|
|
||||||
!!! danger "`debug_requests` writes secrets"
|
!!! danger "The body folder of `debug_requests` holds secrets"
|
||||||
With `debug_requests` on, the JSONL file holds tokens, passwords, cookies, content keys and account data
|
With `debug_requests` on, unshackle writes the request and response bodies as sent and received to files in a
|
||||||
as the servers sent them. unshackle masks only the local folder prefixes in these entries. Keep the file on
|
folder beside the JSONL file (`unshackle_debug_*/`), with no redaction. They hold passwords, tokens, cookies,
|
||||||
your computer. Never attach it to a report.
|
content keys and account data. Keep the folder on your computer. Never attach it to a report.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ for the hardcoded-message TypeError footgun), and tool_run logging."""
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import threading
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -84,16 +85,11 @@ def test_log_event_emits_with_level_message_and_context(debug_log: Path):
|
|||||||
assert e["context"] == {"count": 3}
|
assert e["context"] == {"count": 3}
|
||||||
|
|
||||||
|
|
||||||
def test_a_raw_entry_keeps_its_values_and_redacts_only_local_paths(debug_log: Path):
|
def test_an_entry_masks_secret_values_and_local_paths(debug_log: Path):
|
||||||
home = str(Path.home())
|
values = {"url": "https://h/x?access_token=T1", "password": "P1", "key": "K1", "file": f"{Path.home()}/a.txt"}
|
||||||
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)
|
|
||||||
log_event("masked_event", message="token=T1", context=values)
|
log_event("masked_event", message="token=T1", context=values)
|
||||||
|
|
||||||
entries = read_entries(debug_log)
|
masked = find(read_entries(debug_log), "masked_event")
|
||||||
raw, masked = find(entries, "raw_event"), find(entries, "masked_event")
|
|
||||||
assert raw["message"] == "token=T1 ~/m"
|
|
||||||
assert raw["context"] == {**values, "file": "~/a.txt"}
|
|
||||||
assert masked["message"] == "token=***"
|
assert masked["message"] == "token=***"
|
||||||
assert masked["context"] == {"url": "redacted", "password": "[REDACTED]", "key": "[REDACTED]", "file": "~/a.txt"}
|
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 = []
|
deep: list = []
|
||||||
for _ in range(5000):
|
for _ in range(5000):
|
||||||
deep = [deep]
|
deep = [deep]
|
||||||
log_event("deep_event", raw=True, context={"body": deep})
|
log_event("deep_event", context={"body": deep})
|
||||||
log_event("after_event")
|
log_event("after_event")
|
||||||
|
|
||||||
assert find(read_entries(debug_log), "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():
|
def test_log_event_noop_when_disabled():
|
||||||
close_debug_logger()
|
close_debug_logger()
|
||||||
assert get_debug_logger() is None
|
assert get_debug_logger() is None
|
||||||
|
|||||||
@@ -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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -6,6 +6,7 @@ import copy
|
|||||||
import importlib
|
import importlib
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
import threading
|
import threading
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
@@ -43,7 +44,7 @@ class Server(ThreadingHTTPServer):
|
|||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.hits: list[str] = []
|
self.hits: list[str] = []
|
||||||
self.docs: dict[str, str] = {}
|
self.docs: dict[str, str | bytes] = {}
|
||||||
self.types: dict[str, str] = {}
|
self.types: dict[str, str] = {}
|
||||||
self.lock = threading.Lock()
|
self.lock = threading.Lock()
|
||||||
super().__init__(("127.0.0.1", 0), Handler)
|
super().__init__(("127.0.0.1", 0), Handler)
|
||||||
@@ -80,7 +81,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.end_headers()
|
self.end_headers()
|
||||||
return
|
return
|
||||||
ranged = bool(self.headers.get("Range")) and not path.startswith("/plain")
|
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"):
|
if path.startswith("/chunked"):
|
||||||
self.send_response(200)
|
self.send_response(200)
|
||||||
self.send_header("Content-Type", self.server.types.get(path, "text/plain"))
|
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"]
|
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:
|
def requests_session() -> rq.Session:
|
||||||
session = rq.Session()
|
session = rq.Session()
|
||||||
adapter = HTTPAdapter(max_retries=Retry(total=2, backoff_factor=0, status_forcelist=[503]))
|
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)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_the_entry_keeps_host_path_and_query_as_received(server, debug_log, make_session):
|
def test_the_entry_masks_a_secret_query_value_and_names_the_body_file(server, debug_log, make_session):
|
||||||
make_session().get(f"{server.url}/api/{JWT}/items;hmac=a1b2?id=5&access_token=SECRET123")
|
server.types["/api/items"] = "text/plain"
|
||||||
|
make_session().get(f"{server.url}/api/items?id=5&access_token=SECRET123")
|
||||||
|
|
||||||
(entry,) = records(debug_log)
|
(entry,) = records(debug_log)
|
||||||
assert entry["request"] == {
|
assert entry["request"] == {
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"host": server.host,
|
"host": server.host,
|
||||||
"path": f"/api/{JWT}/items;hmac=a1b2",
|
"path": "/api/items",
|
||||||
"query": "id=5&access_token=SECRET123",
|
"query": "id=5&access_token=***",
|
||||||
"attempt": 1,
|
"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["duration_ms"] >= 0
|
||||||
assert entry["failure"] is None
|
assert entry["failure"] is None
|
||||||
|
assert (folder(debug_log) / name).read_bytes() == BODY
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
@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 server.hits.count("/api") == 1
|
||||||
assert records(debug_log) == []
|
assert records(debug_log) == []
|
||||||
|
assert not folder(debug_log).exists()
|
||||||
assert "session_start" in debug_log.read_text(encoding="utf-8")
|
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(
|
def body_of(
|
||||||
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str, **kw: Any
|
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str | bytes, **kw: Any
|
||||||
) -> dict:
|
) -> tuple[str, bytes] | None:
|
||||||
|
"""The response body file name and bytes of one GET, or None when it wrote none."""
|
||||||
server.docs[path] = doc
|
server.docs[path] = doc
|
||||||
if kind:
|
if kind:
|
||||||
server.types[path] = kind
|
server.types[path] = kind
|
||||||
make_session().get(f"{server.url}{path}", **kw)
|
make_session().get(f"{server.url}{path}", **kw)
|
||||||
(entry,) = records(debug_log)
|
(entry,) = records(debug_log)
|
||||||
return entry["response"]
|
name = entry["response"].get("body_file")
|
||||||
|
return (name, (folder(debug_log) / name).read_bytes()) if name else None
|
||||||
|
|
||||||
@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")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("path", "kind", "doc"),
|
("path", "kind", "doc", "extension"),
|
||||||
[
|
|
||||||
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"),
|
|
||||||
[
|
[
|
||||||
|
pytest.param("/a.txt", "text/plain", "error inside a 200", ".txt", id="text"),
|
||||||
pytest.param(
|
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("/jsonp", "application/x-javascript; charset=utf-8", 'callback({"sub":[]})', ".js", id="jsonp"),
|
||||||
pytest.param({"data": "<Envelope/>", "headers": {"Content-Type": "text/xml"}}, "<Envelope/>", id="xml"),
|
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)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_a_text_request_body_is_recorded_as_sent(server, debug_log, make_session, kw, expected):
|
def test_each_response_body_is_a_file_with_the_bytes_as_received(
|
||||||
make_session().post(f"{server.url}/api/send", **kw)
|
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(
|
@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("/api/stream", "application/json", '{"a": 1}', {"stream": True}, id="stream"),
|
||||||
pytest.param({"data": b"\x08\x04\x12"}, id="no-type"),
|
pytest.param("/events", "text/event-stream", "data: 1\n\n", {}, id="event-stream"),
|
||||||
pytest.param({}, id="none"),
|
pytest.param("/empty", "application/json", "", {}, id="empty"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_no_request_body_for_a_binary_or_empty_request(server, debug_log, make_session, kw):
|
def test_no_body_file_for_a_streamed_or_empty_response(server, debug_log, make_session, path, kind, doc, kw):
|
||||||
make_session().post(f"{server.url}/api/send", **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)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_a_server_process_records_no_request_body(server, debug_log, make_session, monkeypatch):
|
def test_a_bytes_request_body_is_kept_as_sent(server, debug_log, make_session):
|
||||||
monkeypatch.setattr(http_session, "record_bodies", False)
|
session = make_session()
|
||||||
make_session().post(f"{server.url}/api/send", json={"a": 1})
|
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)
|
@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"])
|
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)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session):
|
def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session):
|
||||||
server.docs["/api/read"] = '{"a": 1}'
|
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}'
|
assert b"".join(streamed.iter_content(3)) == b'{"a": 1}'
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("kind", ["application/json", "text/plain"])
|
|
||||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
@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)
|
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):
|
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")
|
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)])
|
@pytest.mark.parametrize(("value", "limit"), [(None, 0), ("5", 5), (-5, 0)])
|
||||||
def test_the_body_limit_is_a_byte_count(value, limit):
|
def test_the_body_limit_is_a_byte_count(value, limit):
|
||||||
assert Config(debug_requests_body_limit=value).debug_requests_body_limit == 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)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_path, make_session, start):
|
def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_path, make_session, start):
|
||||||
start(monkeypatch, tmp_path)
|
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 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):
|
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 (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2)
|
||||||
assert paths(debug_log) == ["/v.m3u8"]
|
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)
|
@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 [server.hits.count(p) for p in ("/init.mp4", "/file.mp4", "/list.mp4")] == [1, 2, 1]
|
||||||
assert paths(debug_log) == ["/manifest.mpd"]
|
assert paths(debug_log) == ["/manifest.mpd"]
|
||||||
|
assert [p.suffix for p in folder(debug_log).iterdir()] == [".mpd"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||||
|
|||||||
@@ -487,8 +487,9 @@ def test_server_request_records_never_reach_the_remote_client(
|
|||||||
entries = [e for e in records if e.get("operation") == "http_request"]
|
entries = [e for e in records if e.get("operation") == "http_request"]
|
||||||
assert {"/v1/init", "/v1/init-rnet", "/v1/titles", "/v1/titles-rnet"} <= {e["request"]["path"] for e in entries}
|
assert {"/v1/init", "/v1/init-rnet", "/v1/titles", "/v1/titles-rnet"} <= {e["request"]["path"] for e in entries}
|
||||||
server_host = server.url.split("://")[1].rstrip("/")
|
server_host = server.url.split("://")[1].rstrip("/")
|
||||||
|
assert all("body" not in e["response"] for e in entries)
|
||||||
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
|
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
|
||||||
assert own and all(isinstance(e["response"]["body"], dict) for e in own)
|
assert own and all((tmp_path / "server" / e["response"]["body_file"]).is_file() for e in own)
|
||||||
|
|
||||||
|
|
||||||
def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
|||||||
+61
-62
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import contextlib
|
|
||||||
import http
|
import http
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
|
import mimetypes
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -16,6 +16,7 @@ from copy import copy
|
|||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from email.utils import parsedate_to_datetime
|
from email.utils import parsedate_to_datetime
|
||||||
from http.cookiejar import Cookie, CookieJar
|
from http.cookiejar import Cookie, CookieJar
|
||||||
|
from pathlib import PurePosixPath
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
|
from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
|
||||||
|
|
||||||
@@ -594,44 +595,40 @@ def failure_reason(exc: BaseException) -> str:
|
|||||||
return f"{type(inner).__name__} ({texts[-1]})" if texts else type(inner).__name__
|
return f"{type(inner).__name__} ({texts[-1]})" if texts else type(inner).__name__
|
||||||
|
|
||||||
|
|
||||||
TEXT_TYPES = ("json", "xml", "text/")
|
MANIFEST_SUFFIXES = (".mpd", ".m3u8")
|
||||||
MANIFEST_TYPES = ("dash+xml", "mpegurl", "vnd.ms-sstr")
|
BODY_EXTENSIONS = {"dash+xml": ".mpd", "mpegurl": ".m3u8", "json": ".json", "javascript": ".js", "xml": ".xml"}
|
||||||
MANIFEST_SUFFIXES = (".mpd", ".m3u8", ".m3u", "/manifest")
|
|
||||||
FORM_TYPE = "x-www-form-urlencoded"
|
|
||||||
|
|
||||||
record_bodies = True
|
record_bodies = True
|
||||||
"""False in a server process (``serve`` and its download job worker): its http_request entries carry no body."""
|
"""False in a server process (``serve`` and its download job worker): it writes no body file."""
|
||||||
|
|
||||||
|
|
||||||
def text_fields(data: bytes, content_type: str) -> dict[str, Any]:
|
def body_extension(content_type: str, path: str) -> str:
|
||||||
"""A text body as entry fields: JSON parsed, other text as a string, cut to the body limit."""
|
"""The file extension of a body from its content type: a manifest keeps .mpd or .m3u8, an unknown type is .bin."""
|
||||||
limit = config.debug_requests_body_limit
|
kind = content_type.partition(";")[0].strip().lower()
|
||||||
if limit and len(data) > limit:
|
suffix = PurePosixPath(path).suffix.lower()
|
||||||
return {"body": data[:limit].decode("utf-8", errors="replace"), "body_size": len(data), "body_cut": True}
|
if suffix in MANIFEST_SUFFIXES and "json" not in kind:
|
||||||
if "json" in content_type:
|
return suffix
|
||||||
with contextlib.suppress(ValueError):
|
for marker, extension in BODY_EXTENSIONS.items():
|
||||||
return {"body": json.loads(data)}
|
if marker in kind:
|
||||||
return {"body": data.decode("utf-8", errors="replace")}
|
return extension
|
||||||
|
return mimetypes.MimeTypes().guess_extension(kind) or ".bin"
|
||||||
|
|
||||||
|
|
||||||
def request_body(content_type: str, data: Any) -> dict[str, Any]:
|
def sent_body(content_type: str, data: Any) -> bytes:
|
||||||
"""The body fields of a sent request: a JSON, form, XML or text body as sent. A binary body has none."""
|
"""The bytes of a sent request body: a string as UTF-8, bytes as they are. A multipart, file or iterator body has none."""
|
||||||
content_type = content_type.lower()
|
|
||||||
if isinstance(data, str):
|
if isinstance(data, str):
|
||||||
data = data.encode("utf-8")
|
return data.encode("utf-8")
|
||||||
if not data or not isinstance(data, bytes):
|
if isinstance(data, bytes) and "multipart/" not in content_type.lower():
|
||||||
return {}
|
return data
|
||||||
if FORM_TYPE not in content_type and not any(t in content_type for t in TEXT_TYPES):
|
return b""
|
||||||
return {}
|
|
||||||
return text_fields(data, content_type)
|
|
||||||
|
|
||||||
|
|
||||||
def rnet_sent(kwargs: dict[str, Any], headers: Any) -> tuple[str, Any] | None:
|
def rnet_sent(kwargs: dict[str, Any], headers: Any) -> tuple[str, Any] | None:
|
||||||
"""The content type and body of an rnet request, for its http_request entry."""
|
"""The content type and body of an rnet request, for its request body file."""
|
||||||
if kwargs.get("json") is not None:
|
if kwargs.get("json") is not None:
|
||||||
return "application/json", json.dumps(kwargs["json"])
|
return "application/json", json.dumps(kwargs["json"])
|
||||||
if kwargs.get("form") is not None:
|
if kwargs.get("form") is not None:
|
||||||
return FORM_TYPE, urlencode(kwargs["form"])
|
return "application/x-www-form-urlencoded", urlencode(kwargs["form"])
|
||||||
if kwargs.get("body") is None:
|
if kwargs.get("body") is None:
|
||||||
return None
|
return None
|
||||||
merged = {k.lower(): v for k, v in dict(headers).items()}
|
merged = {k.lower(): v for k, v in dict(headers).items()}
|
||||||
@@ -639,24 +636,6 @@ def rnet_sent(kwargs: dict[str, Any], headers: Any) -> tuple[str, Any] | None:
|
|||||||
return merged.get("content-type", ""), kwargs["body"]
|
return merged.get("content-type", ""), kwargs["body"]
|
||||||
|
|
||||||
|
|
||||||
def response_body(response: Any, path: str) -> dict[str, Any]:
|
|
||||||
"""The body fields of a response for its http_request entry.
|
|
||||||
|
|
||||||
Only a text content-type has its body read. A manifest has none: a manifest content-type, or a manifest
|
|
||||||
path suffix on a response that is not JSON.
|
|
||||||
"""
|
|
||||||
content_type = (response.headers.get("content-type") or "").lower()
|
|
||||||
manifest = any(t in content_type for t in MANIFEST_TYPES) or (
|
|
||||||
"json" not in content_type and path.lower().endswith(MANIFEST_SUFFIXES)
|
|
||||||
)
|
|
||||||
if manifest or "event-stream" in content_type or not any(t in content_type for t in TEXT_TYPES):
|
|
||||||
return {}
|
|
||||||
data: bytes = response.content
|
|
||||||
if not data:
|
|
||||||
return {}
|
|
||||||
return text_fields(data, content_type)
|
|
||||||
|
|
||||||
|
|
||||||
def record_request(
|
def record_request(
|
||||||
method: str,
|
method: str,
|
||||||
url: str,
|
url: str,
|
||||||
@@ -669,48 +648,68 @@ def record_request(
|
|||||||
body: bool = False,
|
body: bool = False,
|
||||||
sent: tuple[str, Any] | None = None,
|
sent: tuple[str, Any] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Write one ``http_request`` debug-log entry for an HTTP attempt, with its values as received.
|
"""Write one ``http_request`` debug-log entry for an HTTP attempt, through the debug-log sanitisation.
|
||||||
|
|
||||||
With ``body`` set, a text response body goes in the entry too, and ``sent`` (content type, body) adds a
|
``sent`` (content type, body) and, with ``body`` set, the response body each go to a body file as they are,
|
||||||
text request body, except in a server process. A body read that fails writes ``body_error``, and the entry
|
except in a server process; the entry names the files. A body read that fails writes ``body_error``, and the
|
||||||
then raises a requests read error again, because a second read of a cut chunked body returns what arrived
|
entry then raises a requests read error again, because a second read of a cut chunked body returns what arrived
|
||||||
without an error. The duration stops at the response headers.
|
without an error. The duration stops at the response headers.
|
||||||
"""
|
"""
|
||||||
debug_logger = get_debug_logger()
|
debug_logger = get_debug_logger()
|
||||||
if not debug_logger or not debug_logger.enabled:
|
if not debug_logger or not debug_logger.enabled:
|
||||||
return
|
return
|
||||||
parts = urlsplit(url)
|
parts = urlsplit(url)
|
||||||
|
host = parts.netloc.rpartition("@")[2]
|
||||||
|
number = 0
|
||||||
|
|
||||||
|
def save(data: bytes, content_type: str, *marker: str) -> dict[str, Any]:
|
||||||
|
nonlocal number
|
||||||
|
number = number or debug_logger.body_number()
|
||||||
|
limit = config.debug_requests_body_limit
|
||||||
|
cut = bool(limit) and len(data) > limit
|
||||||
|
name_parts = [method, host, PurePosixPath(parts.path).stem, *marker]
|
||||||
|
name = debug_logger.write_body(
|
||||||
|
number, name_parts, body_extension(content_type, parts.path), data[:limit] if cut else data
|
||||||
|
)
|
||||||
|
if name is None:
|
||||||
|
return {}
|
||||||
|
return {"body_file": name, **({"body_size": len(data), "body_cut": True} if cut else {})}
|
||||||
|
|
||||||
|
sent_fields: dict[str, Any] = {}
|
||||||
|
if sent is not None and record_bodies:
|
||||||
|
try:
|
||||||
|
if data := sent_body(*sent):
|
||||||
|
sent_fields = save(data, sent[0], "request")
|
||||||
|
except Exception as e:
|
||||||
|
sent_fields = {"body_error": failure_reason(e)}
|
||||||
size: Any = None
|
size: Any = None
|
||||||
received: dict[str, Any] = {}
|
received: dict[str, Any] = {}
|
||||||
read_error: RequestException | None = None
|
read_error: RequestException | None = None
|
||||||
request_fields: dict[str, Any] = {}
|
|
||||||
if sent is not None and record_bodies:
|
|
||||||
try:
|
|
||||||
request_fields = request_body(*sent)
|
|
||||||
except Exception as e:
|
|
||||||
request_fields = {"body_error": failure_reason(e)}
|
|
||||||
if response is not None:
|
if response is not None:
|
||||||
status = response.status_code
|
status = response.status_code
|
||||||
|
content_type = response.headers.get("content-type") or ""
|
||||||
size = response.headers.get("content-length")
|
size = response.headers.get("content-length")
|
||||||
if body and record_bodies:
|
if body and record_bodies and "event-stream" not in content_type.lower():
|
||||||
try:
|
try:
|
||||||
received = response_body(response, parts.path)
|
data = response.content
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
data = b""
|
||||||
received = {"body_error": failure_reason(e)}
|
received = {"body_error": failure_reason(e)}
|
||||||
if isinstance(e, RequestException):
|
if isinstance(e, RequestException):
|
||||||
read_error = e
|
read_error = e
|
||||||
if not str(size).isdigit() and "body" in received:
|
if data:
|
||||||
size = len(response.content)
|
received = save(data, content_type)
|
||||||
|
if not str(size).isdigit():
|
||||||
|
size = len(data)
|
||||||
log_event(
|
log_event(
|
||||||
"http_request",
|
"http_request",
|
||||||
raw=True,
|
|
||||||
request={
|
request={
|
||||||
"method": method,
|
"method": method,
|
||||||
"host": parts.netloc.rpartition("@")[2],
|
"host": host,
|
||||||
"path": parts.path or "/",
|
"path": parts.path or "/",
|
||||||
"query": parts.query or None,
|
"query": parts.query or None,
|
||||||
"attempt": attempt,
|
"attempt": attempt,
|
||||||
**request_fields,
|
**sent_fields,
|
||||||
},
|
},
|
||||||
response={"status": status, "size": int(size) if str(size).isdigit() else None, **received},
|
response={"status": status, "size": int(size) if str(size).isdigit() else None, **received},
|
||||||
duration_ms=None if duration is None else round(duration * 1000, 1),
|
duration_ms=None if duration is None else round(duration * 1000, 1),
|
||||||
@@ -1089,7 +1088,7 @@ class RnetSession:
|
|||||||
) -> RnetResponse:
|
) -> RnetResponse:
|
||||||
"""Send one HTTP attempt. With debug_requests on, log it, and when ``record`` is set write its debug-log entry.
|
"""Send one HTTP attempt. With debug_requests on, log it, and when ``record`` is set write its debug-log entry.
|
||||||
|
|
||||||
``body`` puts the response body in the entry, and ``sent`` the request body.
|
``body`` writes the response body to a body file, and ``sent`` the request body.
|
||||||
"""
|
"""
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
try:
|
try:
|
||||||
|
|||||||
+40
-14
@@ -35,7 +35,7 @@ from unidecode import unidecode
|
|||||||
|
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
|
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
|
||||||
from unshackle.core.utils.redact import redact_all, redact_path
|
from unshackle.core.utils.redact import redact_all
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Utility functions for the unshackle media archival tool.
|
Utility functions for the unshackle media archival tool.
|
||||||
@@ -1090,6 +1090,8 @@ class DebugLogger:
|
|||||||
self.log_path = log_path
|
self.log_path = log_path
|
||||||
self.session_id = str(uuid4())[:8]
|
self.session_id = str(uuid4())[:8]
|
||||||
self.file_handle = None
|
self.file_handle = None
|
||||||
|
self.body_count = 0
|
||||||
|
self.body_lock = threading.Lock()
|
||||||
self.log_keys = log_keys
|
self.log_keys = log_keys
|
||||||
|
|
||||||
if self.enabled and self.log_path is not None:
|
if self.enabled and self.log_path is not None:
|
||||||
@@ -1129,7 +1131,6 @@ class DebugLogger:
|
|||||||
response: dict[str, Any] | None = None,
|
response: dict[str, Any] | None = None,
|
||||||
duration_ms: float | None = None,
|
duration_ms: float | None = None,
|
||||||
success: bool | None = None,
|
success: bool | None = None,
|
||||||
raw: bool = False,
|
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -1146,7 +1147,6 @@ class DebugLogger:
|
|||||||
response: Response details (status, headers, body)
|
response: Response details (status, headers, body)
|
||||||
duration_ms: Operation duration in milliseconds
|
duration_ms: Operation duration in milliseconds
|
||||||
success: Whether the operation succeeded
|
success: Whether the operation succeeded
|
||||||
raw: True to write the values as received, with only the local folder prefixes redacted
|
|
||||||
**kwargs: Additional fields to include in the log entry
|
**kwargs: Additional fields to include in the log entry
|
||||||
"""
|
"""
|
||||||
if not self.enabled or not self.file_handle:
|
if not self.enabled or not self.file_handle:
|
||||||
@@ -1162,15 +1162,15 @@ class DebugLogger:
|
|||||||
if operation:
|
if operation:
|
||||||
entry["operation"] = operation
|
entry["operation"] = operation
|
||||||
if message:
|
if message:
|
||||||
entry["message"] = self.sanitize_data(message, raw)
|
entry["message"] = self.sanitize_data(message)
|
||||||
if service:
|
if service:
|
||||||
entry["service"] = service
|
entry["service"] = service
|
||||||
if context:
|
if context:
|
||||||
entry["context"] = self.sanitize_data(context, raw)
|
entry["context"] = self.sanitize_data(context)
|
||||||
if request:
|
if request:
|
||||||
entry["request"] = self.sanitize_data(request, raw)
|
entry["request"] = self.sanitize_data(request)
|
||||||
if response:
|
if response:
|
||||||
entry["response"] = self.sanitize_data(response, raw)
|
entry["response"] = self.sanitize_data(response)
|
||||||
if duration_ms is not None:
|
if duration_ms is not None:
|
||||||
entry["duration_ms"] = duration_ms
|
entry["duration_ms"] = duration_ms
|
||||||
if success is not None:
|
if success is not None:
|
||||||
@@ -1187,30 +1187,30 @@ class DebugLogger:
|
|||||||
|
|
||||||
for key, value in kwargs.items():
|
for key, value in kwargs.items():
|
||||||
if key not in entry:
|
if key not in entry:
|
||||||
entry[key] = self.sanitize_data(value, raw)
|
entry[key] = self.sanitize_data(value)
|
||||||
|
|
||||||
self.file_handle.write(json.dumps(entry, default=str) + "\n")
|
self.file_handle.write(json.dumps(entry, default=str) + "\n")
|
||||||
self.file_handle.flush()
|
self.file_handle.flush()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Failed to write debug log: {e}", file=sys.stderr)
|
print(f"Failed to write debug log: {e}", file=sys.stderr)
|
||||||
|
|
||||||
def sanitize_data(self, data: Any, raw: bool = False) -> Any:
|
def sanitize_data(self, data: Any) -> Any:
|
||||||
"""
|
"""
|
||||||
Sanitise data for JSON serialization.
|
Sanitise data for JSON serialization.
|
||||||
Handles complex objects and removes sensitive information. ``raw`` redacts only the local folder prefixes.
|
Handles complex objects and removes sensitive information.
|
||||||
"""
|
"""
|
||||||
if data is None:
|
if data is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if isinstance(data, str):
|
if isinstance(data, str):
|
||||||
# mask secrets, collapse content/CDN URLs, and strip local path prefixes
|
# mask secrets, collapse content/CDN URLs, and strip local path prefixes
|
||||||
return redact_path(data) if raw else redact_all(data)
|
return redact_all(data)
|
||||||
|
|
||||||
if isinstance(data, (int, float, bool)):
|
if isinstance(data, (int, float, bool)):
|
||||||
return data
|
return data
|
||||||
|
|
||||||
if isinstance(data, (list, tuple)):
|
if isinstance(data, (list, tuple)):
|
||||||
return [self.sanitize_data(item, raw) for item in data]
|
return [self.sanitize_data(item) for item in data]
|
||||||
|
|
||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
sanitized = {}
|
sanitized = {}
|
||||||
@@ -1228,12 +1228,12 @@ class DebugLogger:
|
|||||||
and not any(safe in key_lower for safe in ["_count", "_id", "_type", "kid", "keys_", "key_found"])
|
and not any(safe in key_lower for safe in ["_count", "_id", "_type", "kid", "keys_", "key_found"])
|
||||||
)
|
)
|
||||||
|
|
||||||
should_redact = not raw and (is_always_sensitive or (is_key_field and not self.log_keys))
|
should_redact = is_always_sensitive or (is_key_field and not self.log_keys)
|
||||||
|
|
||||||
if should_redact:
|
if should_redact:
|
||||||
sanitized[key] = "[REDACTED]"
|
sanitized[key] = "[REDACTED]"
|
||||||
else:
|
else:
|
||||||
sanitized[key] = self.sanitize_data(value, raw)
|
sanitized[key] = self.sanitize_data(value)
|
||||||
return sanitized
|
return sanitized
|
||||||
|
|
||||||
if isinstance(data, bytes):
|
if isinstance(data, bytes):
|
||||||
@@ -1315,6 +1315,32 @@ class DebugLogger:
|
|||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def body_number(self) -> int:
|
||||||
|
"""The next body file number of the run; download threads record at the same time."""
|
||||||
|
with self.body_lock:
|
||||||
|
self.body_count += 1
|
||||||
|
return self.body_count
|
||||||
|
|
||||||
|
def write_body(self, number: int, name_parts: list[str], extension: str, data: bytes) -> str | None:
|
||||||
|
"""Write one body file in the folder of the run, named after the log; the first body makes the folder.
|
||||||
|
|
||||||
|
The name parts come from a URL, so each keeps only safe characters and a capped length, and the name has no
|
||||||
|
path separator. Gives the file name, or None when the log is closed or the write fails.
|
||||||
|
"""
|
||||||
|
if not self.file_handle or self.log_path is None:
|
||||||
|
return None
|
||||||
|
safe = [re.sub(r"[^A-Za-z0-9._-]", "_", part[:40]) for part in name_parts if part]
|
||||||
|
name = "_".join([f"{number:04d}", *safe]) + extension
|
||||||
|
folder = self.log_path.with_suffix("")
|
||||||
|
try:
|
||||||
|
folder.mkdir(exist_ok=True)
|
||||||
|
with open(folder / name, "xb") as file:
|
||||||
|
file.write(data)
|
||||||
|
except OSError as e:
|
||||||
|
print(f"Failed to write debug body file {name}: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
return name
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
"""Close the log file and clean up resources."""
|
"""Close the log file and clean up resources."""
|
||||||
if self.file_handle:
|
if self.file_handle:
|
||||||
|
|||||||
Reference in New Issue
Block a user