diff --git a/README.md b/README.md index 45c45d7..c76a818 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,35 @@ uv run pytest tests/ -v uv run pytest tests/ --cov=http_api_tool --cov-report=html ``` +### Fuzz Harnesses + +Two [Atheris](https://github.com/google/atheris) harnesses in `tests/fuzz/` +check the redaction helpers in `src/http_api_tool/sanitize.py`: + +- `fuzz_url_redaction.py`: `sanitize_url_for_logging` and `parse_url` + drop the credentials from a URL and keep its host, port and path. + Separately, it checks that `extract_url_credentials` returns the + planted username and password; that result holds the secrets, so the + harness never shows it. +- `fuzz_header_body_redaction.py`: `sanitize_headers_for_logging` redacts + every secret header and never raises, and + `sanitize_request_body_for_logging` withholds a body holding a sensitive + word and truncates the rest. + +Both write each redacted value on a strict UTF-8 stream, as the CLI logs +it, so text that stream cannot carry fails the run. + +An organisation job runs them daily, and `uv run pytest` replays their +seeds without Atheris. To fuzz one by hand on Linux x86_64: + +```bash +uv sync --frozen +uv run --with atheris python tests/fuzz/fuzz_url_redaction.py -max_total_time=60 +``` + +Run without arguments, a harness fuzzes from its built-in seeds; given a +file, it runs that input once. + ### Integration Testing The project includes a comprehensive integration test suite: diff --git a/src/http_api_tool/sanitize.py b/src/http_api_tool/sanitize.py index d621cda..38e2f81 100644 --- a/src/http_api_tool/sanitize.py +++ b/src/http_api_tool/sanitize.py @@ -7,11 +7,16 @@ Every function here returns a value that is safe to display. Credential extraction lives in ``extract_url_credentials``, whose result must never reach a logging call. + +``os.environ`` turns undecodable bytes into lone surrogates, which a +strict UTF-8 stream refuses to write, so a displayed value shows U+FFFD +in their place. """ import json +import re from typing import Any -from urllib.parse import urlparse, urlunparse +from urllib.parse import ParseResult, urlparse, urlunparse SENSITIVE_HEADERS = frozenset( { @@ -39,6 +44,29 @@ "credential", ) +_LONE_SURROGATE = re.compile("[\ud800-\udfff]") + + +def _displayable(text: str) -> str: + """Replace each lone surrogate in *text* with U+FFFD.""" + return _LONE_SURROGATE.sub("\ufffd", text) + + +def _netloc_without_credentials(parsed: ParseResult) -> str: + """Rebuild the host and port of *parsed*, leaving out any credentials.""" + hostname = parsed.hostname or "" + # urlparse leaves a bracket in the host name only when it did not + # delimit an IP literal there; no rebuilt URL would parse. + if "[" in hostname or "]" in hostname: + raise ValueError("Invalid host in URL") + # urlparse strips the brackets that delimit an IPv6 literal, so a + # round trip through urlunparse must put them back. + if ":" in hostname: + hostname = f"[{hostname}]" + if parsed.port is not None: + hostname += f":{parsed.port}" + return hostname + def sanitize_url_for_logging(url: str) -> str: """Remove credentials from a URL so it is safe to display.""" @@ -48,11 +76,9 @@ def sanitize_url_for_logging(url: str) -> str: try: parsed = urlparse(url) if not (parsed.username or parsed.password): - return url - sanitized_netloc = parsed.hostname or "" - if parsed.port: - sanitized_netloc += f":{parsed.port}" - return urlunparse(parsed._replace(netloc=sanitized_netloc)) + return _displayable(url) + netloc = _netloc_without_credentials(parsed) + return _displayable(urlunparse(parsed._replace(netloc=netloc))) except ValueError: return "[URL parsing failed - credentials may be present]" @@ -64,12 +90,16 @@ def sanitize_headers_for_logging(headers_json: str) -> str: try: headers: dict[str, str] = json.loads(headers_json) + # The key goes on the wire as written, and a lenient server may + # trim the whitespace around it, so match it without that. sanitized = { - key: "*** (redacted)" if key.lower() in SENSITIVE_HEADERS else value + key: "*** (redacted)" if key.strip().lower() in SENSITIVE_HEADERS else value for key, value in headers.items() } return json.dumps(sanitized) - except (json.JSONDecodeError, TypeError, AttributeError): + # ValueError covers JSONDecodeError and the integer digit limit; + # RecursionError covers nesting deeper than the decoder allows. + except (ValueError, RecursionError, TypeError, AttributeError): return "*** (invalid JSON - potentially sensitive)" @@ -83,8 +113,8 @@ def sanitize_request_body_for_logging(body: str, max_length: int = 100) -> str: return "*** (request body contains potentially sensitive data)" if len(body) > max_length: - return body[:max_length] + "... (truncated)" - return body + return _displayable(body[:max_length]) + "... (truncated)" + return _displayable(body) def parse_url(url: str) -> dict[str, Any]: @@ -93,6 +123,11 @@ def parse_url(url: str) -> dict[str, Any]: The ``clean_url`` entry and every other value returned here are safe to log. Use ``extract_url_credentials`` when the credentials themselves are needed. + + Raises: + ValueError: The standard library cannot parse the URL or its + port, for example a port outside 0-65535, or the host name + holds a bracket that does not delimit an IP literal. """ parsed = urlparse(url) @@ -100,24 +135,17 @@ def parse_url(url: str) -> dict[str, Any]: if port is None: port = 443 if parsed.scheme == "https" else 80 - hostname = parsed.hostname or "" - # urlparse strips the brackets that delimit an IPv6 literal, so a - # round trip through urlunparse must put them back. - if ":" in hostname: - hostname = f"[{hostname}]" - sanitized_netloc = hostname - if parsed.port is not None: - sanitized_netloc += f":{parsed.port}" - clean_url = urlunparse(parsed._replace(netloc=sanitized_netloc)) + clean_url = urlunparse(parsed._replace(netloc=_netloc_without_credentials(parsed))) + host = parsed.hostname return { "protocol": parsed.scheme, - "host": parsed.hostname, + "host": None if host is None else _displayable(host), "port": port, - "path": parsed.path or "/", - "query": parsed.query, - "fragment": parsed.fragment, - "clean_url": clean_url, + "path": _displayable(parsed.path or "/"), + "query": _displayable(parsed.query), + "fragment": _displayable(parsed.fragment), + "clean_url": _displayable(clean_url), } diff --git a/tests/fuzz/fuzz_header_body_redaction.py b/tests/fuzz/fuzz_header_body_redaction.py new file mode 100644 index 0000000..62814f7 --- /dev/null +++ b/tests/fuzz/fuzz_header_body_redaction.py @@ -0,0 +1,406 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""Fuzz harness for the header and body redaction in ``http_api_tool.sanitize``. + +The contract under test, in the module's own words: + +- The module: "Every function here returns a value that is safe to + display." +- ``sanitize_headers_for_logging``: "Redact the values of headers that + commonly carry secrets." Input it cannot show as a JSON object comes + back as ``*** (invalid JSON - potentially sensitive)``. +- ``sanitize_request_body_for_logging``: "Truncate a request body, or + withhold it when it looks sensitive." + +A header is matched by its name with the HTTP whitespace (space and tab) +around it removed, since ``curl_client._build_headers`` sends the key as +written and a lenient server may trim it. + +Safe to display means the CLI can write the value on a strict UTF-8 +stream. ``os.environ`` turns undecodable bytes into lone surrogates, +which such a stream refuses, so a shown body carries U+FFFD in their +place and is otherwise the value the contract names. + +The first input byte picks a layout, by its value modulo three: raw +header JSON, header JSON planted with known secret headers and with +integers and nesting at the decoder's limits, or a request body with an +optional planted secret word. Text is decoded as ``os.environ`` decodes +an ``INPUT_*`` variable. + +Run by hand from the repository root, after ``uv sync --frozen``:: + + uv run --with atheris python tests/fuzz/fuzz_header_body_redaction.py \\ + -max_total_time=60 +""" + +import io +import json +import os +import sys +import tempfile +from collections.abc import Callable +from pathlib import Path +from typing import Any, TypeVar + +_SRC = str(Path(__file__).resolve().parents[2] / "src") +if _SRC not in sys.path: + sys.path.insert(0, _SRC) + +import typer # noqa: E402 + +from http_api_tool.sanitize import ( # noqa: E402 + SENSITIVE_BODY_PATTERNS, + SENSITIVE_HEADERS, + sanitize_headers_for_logging, + sanitize_request_body_for_logging, +) + +HEADER_PLACEHOLDER = "*** (invalid JSON - potentially sensitive)" +REDACTED = "*** (redacted)" +BODY_PLACEHOLDER = "*** (request body contains potentially sensitive data)" +TRUNCATION_SUFFIX = "... (truncated)" +MAX_BODY_LENGTH = 300 + +# Planted independently of the module's own lists, so dropping one of +# these from them fails the harness. +KNOWN_SECRET_HEADERS = ( + "authorization", + "cookie", + "x-api-key", + "x-auth-token", + "set-cookie", + "x-access-token", + "api-key", + "x-csrf-token", + "auth", + "bearer", + "access-token", + "x-session-token", +) +KNOWN_SECRET_WORDS = ("password", "secret", "token", "key", "auth", "credential") +_PADDING = ("", " ", "\t", " \t ") +_LITERALS = ("true", "false", "null", "0", "1", "-0.5", "1e400", "NaN", "{}", "[]") +_HTTP_WHITESPACE = " \t" +# Digits and brackets the generator may emit for one input, so a short +# input cannot ask for gigabytes; well past the decoder's limits. +GENERATED_BUDGET = 4_000_000 +# On Python 3.11 the JSON decoder and encoder count their nesting against +# the interpreter's recursion limit, so the oracle, a few calls deeper +# than the code under test, would run out of room first at the decoder's +# limit. It decodes with this much more room than the code under test +# has, and asks what is too deep to show with this much less. From 3.12 +# that nesting has a budget of its own, which Python calls leave alone. +ORACLE_ROOM = 50 + +_T = TypeVar("_T") + + +class ContractBreach(AssertionError): + """An input made the code under test break its documented contract.""" + + +class OracleExhausted(Exception): + """The oracle ran out of room decoding an input, despite its extra room.""" + + +def _require(condition: bool, message: str, value: str) -> None: + if not condition: + raise ContractBreach(f"{message}: {value[:200]!r}") + + +def decode_input(raw: bytes) -> str: + """Decode bytes the way ``os.environ`` decodes them on POSIX.""" + return raw.decode("utf-8", "surrogateescape") + + +def displayable(text: str) -> str: + """Return *text* with each lone surrogate shown as U+FFFD.""" + return "".join("\ufffd" if "\ud800" <= char <= "\udfff" else char for char in text) + + +class _Pairs(list[tuple[str, Any]]): + """A JSON object kept as its key/value pairs, in order.""" + + +def _with_room(extra: int, call: Callable[[Any], _T], arg: Any) -> _T: + """Return ``call(arg)`` with the recursion limit moved by *extra*.""" + limit = sys.getrecursionlimit() + sys.setrecursionlimit(limit + extra) + try: + return call(arg) + finally: + sys.setrecursionlimit(limit) + + +def _object_or_none(text: str) -> dict[str, Any] | None: + """Decode *text* as production does; None unless it is a JSON object. + + Raises: + OracleExhausted: *text* nests deeper than the oracle can decode + with more room than the code under test has. + """ + try: + loaded = _with_room(ORACLE_ROOM, json.loads, text) + except RecursionError: + raise OracleExhausted from None + except ValueError: + return None + return loaded if isinstance(loaded, dict) else None + + +def _too_deep_to_show(text: str, value: dict[str, Any]) -> bool: + """Tell whether the code under test may run out of room on *text*. + + It decodes *text* and encodes the result. With less room than it + has, the oracle does the same with *value*, decoded from *text*. + """ + try: + _ = _with_room(-ORACLE_ROOM, json.loads, text) + _ = _with_room(-ORACLE_ROOM, json.dumps, value) + except RecursionError: + return True + return False + + +def _is_secret_name(name: str) -> bool: + # The module may add names; it may not drop one of ours. + return name in KNOWN_SECRET_HEADERS or name in SENSITIVE_HEADERS + + +def _has_secret_word(lowered: str) -> bool: + # The module may add words; it may not drop one of ours. + return any(word in lowered for word in KNOWN_SECRET_WORDS) or any( + pattern in lowered for pattern in SENSITIVE_BODY_PATTERNS + ) + + +def _same_json(left: Any, right: Any) -> bool: + # Serialised text tells true from 1 and compares NaN equal to NaN. + return _with_room(ORACLE_ROOM, json.dumps, left) == _with_room( + ORACLE_ROOM, json.dumps, right + ) + + +def _object_pairs(text: str) -> Any: + return json.loads(text, object_pairs_hook=_Pairs) + + +def check_sanitized_headers(text: str, result: str) -> None: + """Check one ``sanitize_headers_for_logging`` result against its contract.""" + if not text: + _require(result == text, "empty headers changed", text) + return + try: + source = _object_or_none(text) + except OracleExhausted: + # The code under test has no more room than the oracle had. + _require(result == HEADER_PLACEHOLDER, "too deep to decode, yet shown", text) + return + if source is None: + _require(result == HEADER_PLACEHOLDER, "no placeholder for non-object", text) + return + if result == HEADER_PLACEHOLDER: + _require(_too_deep_to_show(text, source), "placeholder for a JSON object", text) + return + try: + pairs = _with_room(ORACLE_ROOM, _object_pairs, result) + shown = _with_room(ORACLE_ROOM, json.loads, result) + except ValueError: + raise ContractBreach(f"result is not JSON: {text[:200]!r}") from None + _require(isinstance(pairs, _Pairs), "result is not a JSON object", text) + _require( + [key for key, _ in pairs] == list(source), "result keys differ from input", text + ) + for key, value in source.items(): + if _is_secret_name(key.strip(_HTTP_WHITESPACE).lower()): + _require(shown[key] == REDACTED, f"header {key!r} not redacted", text) + elif _is_secret_name(key.strip().lower()): + _require( + shown[key] == REDACTED or _same_json(shown[key], value), + f"header {key!r} changed", + text, + ) + else: + _require(_same_json(shown[key], value), f"header {key!r} changed", text) + + +def check_planted_headers(text: str, secret_keys: list[str], result: str) -> None: + """Check that every planted secret header is redacted.""" + if not secret_keys or result == HEADER_PLACEHOLDER: + return + shown = _with_room(ORACLE_ROOM, json.loads, result) + for key in secret_keys: + _require(shown.get(key) == REDACTED, f"planted {key!r} not redacted", text) + + +def _planted_key(field: bytes) -> tuple[str, bool]: + """Return a header name built from *field*, and whether it is a secret.""" + if not field or not field[0] & 1: + return decode_input(field[1:]), False + selector = (field[0] >> 1) & 7 | (field[0] >> 4) & 8 + name = KNOWN_SECRET_HEADERS[selector % len(KNOWN_SECRET_HEADERS)] + mask = int.from_bytes(field[1:], "little") + name = "".join( + char.upper() if mask >> index & 1 else char for index, char in enumerate(name) + ) + padding = _PADDING[(field[0] >> 4) & 3] + return (padding + name if field[0] & 0x40 else name + padding), True + + +def _planted_value(field: bytes, budget: int) -> str: + """Return JSON text for a value built from *field*. + + Digits and brackets stay within *budget* characters. + """ + kind = field[0] % 4 if field else 0 + rest = field[1:] + if kind == 1: + digits = int.from_bytes(rest[:2].ljust(2, b"\x00"), "big") + 1 + return "7" * max(1, min(digits, budget)) + if kind == 2: + # Little-endian, so a depth below 65,536, where the decoder's + # limit lies, needs no NUL byte, which would end the field. + depth = int.from_bytes(rest[:3], "little") % 1_000_001 + depth = min(depth, budget // 2) + return "[" * depth + "]" * depth + if kind == 3: + return _LITERALS[rest[0] % len(_LITERALS)] if rest else "null" + return json.dumps(decode_input(rest)) + + +def plant_headers(payload: bytes) -> tuple[str, list[str]]: + """Build header JSON from *payload*; return it and its secret keys. + + The payload holds alternating key and value fields, separated by NUL + bytes. The digits and brackets of all values together stay within + ``GENERATED_BUDGET`` characters. + """ + fields = payload.split(b"\x00") + members = [] + secret_keys = [] + budget = GENERATED_BUDGET + for index in range(0, len(fields), 2): + key, secret = _planted_key(fields[index]) + field = fields[index + 1] if index + 1 < len(fields) else b"" + value = _planted_value(field, budget) + if field and field[0] % 4 in (1, 2): + budget = max(0, budget - len(value)) + members.append(f"{json.dumps(key)}: {value}") + if secret: + secret_keys.append(key) + return "{" + ", ".join(members) + "}", secret_keys + + +def check_sanitized_body(body: str, max_length: int, result: str) -> None: + """Check one ``sanitize_request_body_for_logging`` result.""" + if not body: + _require(result == body, "empty body changed", body) + return + if _has_secret_word(body.lower()): + _require(result == BODY_PLACEHOLDER, "sensitive body shown", body) + return + expected = displayable(body) + if len(body) > max_length: + expected = displayable(body[:max_length]) + TRUNCATION_SUFFIX + _require(result == expected, "body not shown as truncated input", body) + + +def plant_body(flags: int, position: int, body: str) -> tuple[str, bool]: + """Insert a known secret word into *body* when *flags* asks for one.""" + if not flags & 1: + return body, False + word = KNOWN_SECRET_WORDS[(flags >> 1) % len(KNOWN_SECRET_WORDS)] + if flags & 0x80: + word = word.upper() + at = position % (len(body) + 1) + return body[:at] + word + body[at:], True + + +def emit(label: str, shown: str) -> None: + """Write *shown* as the CLI does, on a strict UTF-8 stream.""" + stream = io.TextIOWrapper(io.BytesIO(), encoding="utf-8", errors="strict") + typer.echo(f" {label}: {shown}", file=stream) + stream.flush() + + +def check_one_input(data: bytes) -> None: + """Run one fuzz input through the header or body redaction contract.""" + mode = data[0] % 3 if data else 0 + if mode == 2: + header = data[1:5].ljust(4, b"\x00") + max_length = int.from_bytes(header[2:4], "big") % (MAX_BODY_LENGTH + 1) + body, planted = plant_body(header[0], header[1], decode_input(data[5:])) + result = sanitize_request_body_for_logging(body, max_length) + check_sanitized_body(body, max_length, result) + _require(not planted or result == BODY_PLACEHOLDER, "planted word shown", body) + emit("Request Body", result) + return + secret_keys: list[str] = [] + if mode == 1: + text, secret_keys = plant_headers(data[1:]) + else: + text = decode_input(data[1:]) + result = sanitize_headers_for_logging(text) + check_sanitized_headers(text, result) + check_planted_headers(text, secret_keys, result) + emit("Custom Headers", result) + + +_LONG_TEXT = b"lorem ipsum dolor sit amet " * 12 + +SEEDS: dict[str, bytes] = { + "empty": b"", + "headers": b'\x00{"Authorization": "Bearer t", "X-Custom": "v"}', + "headers-case": b'\x00{"x-API-key": "k", "Cookie": "c=1", "Accept": "*/*"}', + "headers-trailing-space": b'\x00{"X-Api-Key ": "s"}', + "headers-tab": b'\x00{"\\tAuthorization": "s"}', + "headers-duplicate": b'\x00{"Auth": "a", "x": 1, "AUTH": "b", "Auth": "c"}', + "headers-types": b'\x00{"a": true, "b": 1, "c": null, "d": [1, {"e": NaN}]}', + "headers-not-object": b"\x00[1, 2]", + "headers-invalid": b'\x00{"a": ', + "headers-surrogate": b'\x00{"a": "\\udc80", "\xff": "x"}', + "headers-big-int": b'\x00{"a": ' + b"1" * 4301 + b"}", + "planted-secrets": b"\x01\x01\x00\x00tok\x00\x13\xff\x00\x00\x00\x51\x00\x00v", + "planted-big-int": b"\x01\x05\x00\x01\x10\xcd\x00tok\x00x", + "planted-deep": b"\x01\x05\x00\x02\x40\x0d\x03\x00tok\x00x", + "planted-literals": b"\x01x\x00\x03\x06\x00y\x00\x03\x07", + "planted-late-names": ( + b"\x01\x81\x00\x04s\x00\x93\x00\x04s\x00\xe5\x00\x04s\x00\x87\x00\x04s" + ), + "planted-many-deep": b"\x01" + b"\x00\x02\x40\x42\x0f\x00" * 600, + # A secret header nested near the decoder's limit on 3.11, on 3.12 + # and 3.13, and on 3.14. + "planted-deep-auth-992": b"\x01\x01\x00\x02\xe0\x03", + "planted-deep-auth-9996": b"\x01\x01\x00\x02\x0c\x27", + "planted-deep-auth-116121": b"\x01\x01\x00\x02\x99\xc5\x01", + "body": b"\x02\x00\x00\x00\x64" + _LONG_TEXT, + "body-short": b"\x02\x00\x00\x00\x64hello", + "body-secret": b'\x02\x00\x00\x00\x64{"password": "x"}', + "body-kelvin": b"\x02\x00\x00\x00\x64api \xe2\x84\xaaey", + "body-planted": b"\x02\x83\x10\x01\x2c" + _LONG_TEXT, + "body-surrogate": b"\x02\x00\x00\x00\x03ab\xffcd", + "body-surrogate-whole": b"\x02\x00\x00\x00\x64ab\xffcd\xed\xa0\x80", +} + + +def _write_seeds(directory: str) -> str: + for name, data in SEEDS.items(): + Path(directory, name).write_bytes(data) + return directory + + +def main() -> None: + """Fuzz from the given corpus directories, or replay the given files.""" + import atheris # pyright: ignore[reportMissingModuleSource] + + argv = list(sys.argv) + if not any(os.path.isfile(arg) for arg in argv[1:]): + argv.append(_write_seeds(tempfile.mkdtemp(prefix="fuzz-header-seeds-"))) + atheris.instrument_all() # pyright: ignore[reportAttributeAccessIssue] + atheris.Setup(argv, check_one_input) + atheris.Fuzz() + + +if __name__ == "__main__": + main() diff --git a/tests/fuzz/fuzz_url_redaction.py b/tests/fuzz/fuzz_url_redaction.py new file mode 100644 index 0000000..abfc4e3 --- /dev/null +++ b/tests/fuzz/fuzz_url_redaction.py @@ -0,0 +1,374 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""Fuzz harness for the URL credential redaction in ``http_api_tool.sanitize``. + +The contract under test, in the module's own words: + +- The module: "Every function here returns a value that is safe to + display." +- ``sanitize_url_for_logging``: "Remove credentials from a URL so it is + safe to display." On ``ValueError`` it returns + ``[URL parsing failed - credentials may be present]``. +- ``parse_url``: "The ``clean_url`` entry and every other value returned + here are safe to log." It raises ``ValueError`` when "the standard + library cannot parse the URL or its port, ... or the host name holds a + bracket that does not delimit an IP literal." +- ``extract_url_credentials``: "Return the ``(username, password)`` + embedded in a URL." + +Safe to display means the CLI can write the value on a strict UTF-8 +stream. ``os.environ`` turns undecodable bytes into lone surrogates, +which such a stream refuses, so a shown value carries U+FFFD in their +place and is otherwise the value the contract names. + +The first input byte picks a layout. An even byte passes the rest of the +input, decoded as ``os.environ`` decodes an ``INPUT_URL`` variable, as +the URL. An odd byte also serves as the flags of ``plant_url``, which +plants known credentials, host, port and path in a URL built here, so +the expected results follow from the construction. + +Run by hand from the repository root, after ``uv sync --frozen``:: + + uv run --with atheris python tests/fuzz/fuzz_url_redaction.py \\ + -max_total_time=60 +""" + +import io +import os +import sys +import tempfile +from pathlib import Path +from typing import Any, NamedTuple +from urllib.parse import ParseResult, urlparse + +_SRC = str(Path(__file__).resolve().parents[2] / "src") +if _SRC not in sys.path: + sys.path.insert(0, _SRC) + +import typer # noqa: E402 + +from http_api_tool.sanitize import ( # noqa: E402 + extract_url_credentials, + parse_url, + sanitize_url_for_logging, +) + +URL_PLACEHOLDER = "[URL parsing failed - credentials may be present]" + +# Characters a planted user name or password may hold. The characters +# that end or split an authority (":/?#@") and IPv6 brackets are left +# out so the planted values are known exactly. +_USERINFO_CHARS = "".join( + chr(code) for code in range(0x20, 0x7F) if chr(code) not in ":/?#@[]" +) +_HOST_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.-" +# urlparse splits ";" parameters, "?" queries and "#" fragments out of +# the path, and urlunparse drops an empty one, so the planted path +# holds none of them. +_PATH_CHARS = "".join(chr(code) for code in range(0x21, 0x7F) if chr(code) not in "?#;") + + +class ContractBreach(AssertionError): + """An input made the code under test break its documented contract.""" + + +def _require(condition: bool, message: str, url: str) -> None: + if not condition: + raise ContractBreach(f"{message}: {url!r}") + + +def decode_input(raw: bytes) -> str: + """Decode bytes the way ``os.environ`` decodes them on POSIX.""" + return raw.decode("utf-8", "surrogateescape") + + +def displayable(text: str) -> str: + """Return *text* with each lone surrogate shown as U+FFFD.""" + return "".join("\ufffd" if "\ud800" <= char <= "\udfff" else char for char in text) + + +def _parse_fails(url: str) -> bool: + """Return True when *url* has no host and port that can be shown. + + That is when the standard library rejects the URL or its port, or + leaves a bracket in the host name: it does that only for a bracket + that does not delimit an IP literal, and no URL built from such a + host parses. + """ + try: + parsed = urlparse(url) + _ = parsed.port + except ValueError: + return True + host = parsed.hostname or "" + return "[" in host or "]" in host + + +def _port_or_error(parsed: ParseResult) -> int | str | None: + try: + return parsed.port + except ValueError: + return "unparsable port" + + +def _without_authority(parsed: ParseResult) -> tuple[str, ...]: + return (parsed.scheme, parsed.path, parsed.params, parsed.query, parsed.fragment) + + +def _require_same_target(url: str, source: ParseResult, shown: str, what: str) -> None: + """Require *shown* to name the target of *source* with no userinfo.""" + try: + cleaned = urlparse(shown) + except ValueError: + raise ContractBreach(f"{what} does not parse: {url!r}") from None + _require("@" not in cleaned.netloc, f"{what} keeps a userinfo part", url) + _require(cleaned.hostname == source.hostname, f"{what} changes the host", url) + _require( + _port_or_error(cleaned) == _port_or_error(source), + f"{what} changes the port", + url, + ) + _require( + _without_authority(cleaned) == _without_authority(source), + f"{what} changes the scheme, path, query or fragment", + url, + ) + + +def check_sanitized_url(url: str, result: str) -> None: + """Check one ``sanitize_url_for_logging`` result against its contract.""" + if result == URL_PLACEHOLDER and url != URL_PLACEHOLDER: + _require( + _parse_fails(url), "placeholder for a URL the standard library parses", url + ) + return + try: + source = urlparse(url) + has_credentials = bool(source.username or source.password) + except ValueError: + raise ContractBreach(f"no placeholder for an unparsable URL: {url!r}") from None + if not has_credentials: + _require(result == displayable(url), "URL without credentials changed", url) + return + _require( + not _parse_fails(url), "no placeholder for a URL whose port fails to parse", url + ) + _require_same_target(url, urlparse(displayable(url)), result, "sanitized URL") + + +def check_parse_url(url: str, parts: dict[str, Any]) -> None: + """Check one ``parse_url`` result against its contract.""" + _require(not _parse_fails(url), "parse_url accepted an unparsable URL", url) + source = urlparse(url) + default_port = 443 if source.scheme == "https" else 80 + expected_port = default_port if source.port is None else source.port + _require( + type(parts["port"]) is int and parts["port"] == expected_port, + "parse_url reports the wrong port", + url, + ) + shown = urlparse(displayable(url)) + _require(parts["host"] == shown.hostname, "parse_url reports the wrong host", url) + expected = { + "protocol": shown.scheme, + "path": shown.path or "/", + "query": shown.query, + "fragment": shown.fragment, + } + _require( + _typed({key: parts[key] for key in expected}) == _typed(expected), + "parse_url reports the wrong scheme, path, query or fragment", + url, + ) + _require_same_target(url, shown, parts["clean_url"], "parse_url clean_url") + + +def check_parse_url_refusal(url: str) -> None: + """Check that ``parse_url`` raised ValueError only for an unparsable URL.""" + _require(_parse_fails(url), "parse_url raised for a URL that parses", url) + + +class PlantedUrl(NamedTuple): + """A URL built from known parts, with the results the contract implies.""" + + url: str + sanitized: str + parts: dict[str, Any] + credentials: tuple[str | None, str] + + +def _pick(raw: bytes, alphabet: str) -> str: + """Map each byte into *alphabet*, keeping bytes that are already in it.""" + return "".join( + chr(byte) if chr(byte) in alphabet else alphabet[byte % len(alphabet)] + for byte in raw + ) + + +def _planted_host(kind: int, raw: bytes) -> tuple[str, str]: + """Return a host as urlparse reports it and as the URL spells it.""" + if kind == 1: + host = ".".join(str(byte) for byte in raw[:4].ljust(4, b"\x00")) + return host, host + if kind in (2, 3): + padded = raw[:16].ljust(16, b"\x00") + groups = [ + f"{int.from_bytes(padded[i : i + 2], 'big'):x}" for i in range(0, 16, 2) + ] + host = ":".join(groups) if kind == 2 else f"{groups[0]}::{groups[1]}" + return host, f"[{host}]" + host = _pick(raw, _HOST_CHARS) or "h" + return host, host + + +def plant_url(flags: int, payload: bytes) -> PlantedUrl: + """Build a URL from *flags* and *payload*, with the results they dictate. + + The flag bits choose the credential form (1-2), the host kind (3-4), + the port form (5-6) and the scheme (7). The payload holds the user + name, password, host, port and path, separated by NUL bytes. + """ + fields = (payload.split(b"\x00") + [b""] * 5)[:5] + scheme = "https" if flags & 0x80 else "http" + user = _pick(fields[0], _USERINFO_CHARS) + password = _pick(fields[1], _USERINFO_CHARS + ":") + host, host_text = _planted_host((flags >> 3) & 3, fields[2]) + port_number = int.from_bytes(fields[3][:2].ljust(2, b"\x00"), "big") + port_form = (flags >> 5) & 3 + port: int | None = None if port_form in (0, 2) else port_number + port_text = {0: "", 1: f":{port_number}", 2: ":", 3: f":00{port_number}"} + path = "/" + _pick(fields[4], _PATH_CHARS) if fields[4] else "" + + userinfo, credentials = { + 0: ("", (None, "")), + 1: (f"{user}@", (user, "")), + 2: (f"{user}:{password}@", (user, password)), + 3: (f":{password}@", ("", password)), + }[(flags >> 1) & 3] + url = f"{scheme}://{userinfo}{host_text}{port_text[port_form]}{path}" + clean = f"{scheme}://{host_text}{'' if port is None else f':{port}'}{path}" + default_port = 443 if scheme == "https" else 80 + return PlantedUrl( + url=url, + sanitized=clean if any(credentials) else url, + parts={ + "protocol": scheme, + "host": host, + "port": default_port if port is None else port, + "path": path or "/", + "query": "", + "fragment": "", + "clean_url": clean, + }, + credentials=credentials, + ) + + +def _typed(value: dict[str, Any]) -> dict[str, tuple[type, Any]]: + # Python's True == 1, so compare types as well as values. + return {key: (type(item), item) for key, item in value.items()} + + +def check_planted_url( + planted: PlantedUrl, + sanitized: str, + parts: dict[str, Any], + credentials: tuple[str | None, str], +) -> None: + """Check the results for a planted URL against the planted parts.""" + url = planted.url + _require(sanitized == planted.sanitized, "sanitized URL differs from planted", url) + _require( + _typed(parts) == _typed(planted.parts), "parse_url differs from planted", url + ) + _require(credentials == planted.credentials, "credentials differ from planted", url) + + +def emit(*shown: str) -> None: + """Write *shown* as the CLI does, on a strict UTF-8 stream.""" + stream = io.TextIOWrapper(io.BytesIO(), encoding="utf-8", errors="strict") + for text in shown: + typer.echo(f" URL: {text}", file=stream) + stream.flush() + + +def _check_raw_url(url: str) -> None: + sanitized = sanitize_url_for_logging(url) + check_sanitized_url(url, sanitized) + shown = [sanitized] + try: + parts = parse_url(url) + except ValueError: + check_parse_url_refusal(url) + else: + check_parse_url(url, parts) + # The verifier logs every part, and the job summary its target. + shown.extend(str(value) for value in parts.values()) + emit(*shown) + + +def check_one_input(data: bytes) -> None: + """Run one fuzz input through the URL redaction contract.""" + if not data or data[0] % 2 == 0: + _check_raw_url(decode_input(data[1:])) + return + planted = plant_url(data[0], data[1:]) + check_planted_url( + planted, + sanitize_url_for_logging(planted.url), + parse_url(planted.url), + extract_url_credentials(planted.url), + ) + _check_raw_url(planted.url) + + +SEEDS: dict[str, bytes] = { + "plain": b"\x00https://example.com/api/v1?q=1#top", + "credentials": b"\x00http://user:secret@example.com:8080/path", + "user-only": b"\x00https://token@example.com/", + "empty-userinfo": b"\x00http://:@example.com/", + "at-in-password": b"\x00http://user:p%40ss@a@example.com/x", + "ipv6-credentials": b"\x00http://u:p@[::1]:8080/x", + "ipv6-zone": b"\x00http://u:p@[fe80::1%25eth0]/x", + "port-zero": b"\x00http://u:p@example.com:0/x", + "port-out-of-range": b"\x00http://example.com:99999/", + "port-out-of-range-credentials": b"\x00http://u:p@example.com:99999/", + "bad-bracket": b"\x00http://u:p@[::1/x", + "ipvfuture": b"\x00bp://]:p@[ve8.\x00\x00[?/", + "stray-bracket": b"\x00bj://]h[ \xff.@v8.]", + "no-scheme": b"\x00//u:p@example.com/x", + "tab-in-userinfo": b"\x00http://u\t:p@example.com/", + "undecodable": b"\x00http://u:p@example.com/\xff\xfe", + "undecodable-no-credentials": b"\x00http://example.com/p\xff?q\xfe#f\xfd", + "undecodable-host": b"\x00http://u:p@ex\xffample.com/", + "non-ascii-host": b"\x00http://u:p@ex\xc3\xa4mple.com/", + "planted-credentials": b"\x25alice\x00s3cr3t:x\x00host\x00\x1f\x90\x00api", + "planted-ipv6": b"\x35bob\x00pw\x00\x20\x01\x0d\xb8\x00\x01\xbb\x00v", + "planted-ipv6-compressed": b"\x9dbob\x00pw\x00\xfe\x80\x01\x01\x00\x00v", + "planted-port-zero": b"\x25u\x00p\x00h\x00\x00/x", + "planted-empty-port": b"\x45u\x00p\x00h\x00\x00x", + "planted-padded-port": b"\xe3u\x00\x00h\x00\x01\xbb\x00", +} + + +def _write_seeds(directory: str) -> str: + for name, data in SEEDS.items(): + Path(directory, name).write_bytes(data) + return directory + + +def main() -> None: + """Fuzz from the given corpus directories, or replay the given files.""" + import atheris # pyright: ignore[reportMissingModuleSource] + + argv = list(sys.argv) + if not any(os.path.isfile(arg) for arg in argv[1:]): + argv.append(_write_seeds(tempfile.mkdtemp(prefix="fuzz-url-seeds-"))) + atheris.instrument_all() # pyright: ignore[reportAttributeAccessIssue] + atheris.Setup(argv, check_one_input) + atheris.Fuzz() + + +if __name__ == "__main__": + main() diff --git a/tests/test_http_api_tool.py b/tests/test_http_api_tool.py index e9ccefc..a0ef4b5 100644 --- a/tests/test_http_api_tool.py +++ b/tests/test_http_api_tool.py @@ -28,15 +28,22 @@ - Exclude integration tests: pytest tests/ -m "not integration" """ +import importlib.util +import io import json import os +import subprocess import tempfile +from collections.abc import Callable +from pathlib import Path +from types import ModuleType from typing import Any from unittest.mock import Mock, patch import pycurl import pytest +from http_api_tool.cli import _log_action_parameters from http_api_tool.curl_client import ( check_regex_match, create_curl_handle, @@ -44,7 +51,13 @@ perform_request, ) from http_api_tool.reporting import ActionReporter -from http_api_tool.sanitize import extract_url_credentials, parse_url +from http_api_tool.sanitize import ( + extract_url_credentials, + parse_url, + sanitize_headers_for_logging, + sanitize_request_body_for_logging, + sanitize_url_for_logging, +) from http_api_tool.validation import validate_inputs from http_api_tool.verifier import HTTPAPITester @@ -982,5 +995,397 @@ def capture(result: dict[str, Any], *_args: Any) -> None: # using a local go-httpbin service to avoid external dependencies in unit tests. +FUZZ_DIR = Path(__file__).resolve().parent / "fuzz" + + +def load_harness(name: str) -> ModuleType: + """Import a fuzz harness by path; tests/fuzz is not a package.""" + spec = importlib.util.spec_from_file_location(name, FUZZ_DIR / f"{name}.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +URL_HARNESS = load_harness("fuzz_url_redaction") +HEADER_BODY_HARNESS = load_harness("fuzz_header_body_redaction") +HARNESSES = (URL_HARNESS, HEADER_BODY_HARNESS) + + +def seed_cases() -> list[Any]: + """Return one pytest case per harness seed.""" + cases = [] + for harness in HARNESSES: + for name, data in harness.SEEDS.items(): + cases.append(pytest.param(harness, data, id=f"{harness.__name__}:{name}")) + return cases + + +def deep_auth(depth: int) -> str: + """Return header JSON whose Authorization value nests *depth* arrays.""" + return '{"Authorization": ' + "[" * depth + "]" * depth + "}" + + +def deepest_depth(holds: Callable[[int], object]) -> int: + """Return the largest depth below a million at which *holds* is true.""" + low, high = 0, 1_000_000 + while low < high: + middle = (low + high + 1) // 2 + if holds(middle): + low = middle + else: + high = middle - 1 + return low + + +@pytest.mark.unit +class TestFuzzHarnesses: + """Replay the fuzz seeds and prove each oracle rejects a wrong result.""" + + @pytest.mark.parametrize( # type: ignore[untyped-decorator] + ("harness", "data"), seed_cases() + ) + def test_seed_holds(self, harness: ModuleType, data: bytes) -> None: + """Test that every seed meets the contract its harness checks.""" + harness.check_one_input(data) + + def test_harness_discovery_text_only_in_harnesses(self) -> None: + """Test that only the harnesses carry the discovery text.""" + needle = "import " + "atheris" + try: + listed = subprocess.run( + ["git", "ls-files", "-z", "--", "*.py"], + cwd=FUZZ_DIR.parents[1], + capture_output=True, + check=True, + ) + except (OSError, subprocess.CalledProcessError): + pytest.skip("not a git checkout") + else: + root = FUZZ_DIR.parents[1] + tracked = set(listed.stdout.decode().split("\0")) + carriers = { + path + for path in tracked + if path and needle in (root / path).read_text(encoding="utf-8") + } + harness_paths = { + f"tests/fuzz/{harness.__name__}.py" for harness in HARNESSES + } + assert carriers == harness_paths & tracked + + def test_url_oracle_rejects_wrong_sanitized_urls(self) -> None: + """Test that check_sanitized_url rejects each kind of wrong result.""" + check = URL_HARNESS.check_sanitized_url + breach = URL_HARNESS.ContractBreach + placeholder = URL_HARNESS.URL_PLACEHOLDER + wrong = [ + ("http://u:p@h/x", "http://u:p@h/x"), + ("http://u:p@h/x", "http://:@h/x"), + ("http://u:p@h:8080/x", "http://h/x"), + ("http://u:p@[::1]:8080/x", "http://::1:8080/x"), + ("http://u:p@h/x?q=1", "http://h/x"), + ("http://h/x", "http://h/y"), + ("http://h/x", placeholder), + ("http://u:p@h:99999/x", "http://h/x"), + ("http://u:p@[::1/x", "http://h/x"), + ("http://h/\udcff", "http://h/\udcff"), + ("http://h/\udcff", "http://h/"), + ("http://u:p@h/\udcff", "http://h/\udcff"), + ] + for url, result in wrong: + with pytest.raises(breach): + check(url, result) + check("http://u:p@h:0/x", "http://h:0/x") + check("http://u:p@h/\udcff", "http://h/\ufffd") + + def test_url_oracle_rejects_wrong_parse_url_results(self) -> None: + """Test that check_parse_url and its refusal check reject wrong results.""" + breach = URL_HARNESS.ContractBreach + url = "http://u:p@h:1/x" + good = parse_url(url) + for key, value in [ + ("port", True), + ("port", 80), + ("host", "u"), + ("protocol", "https"), + ("path", "/y"), + ("query", "q"), + ("fragment", "f"), + ("clean_url", url), + ("clean_url", "http://h/x"), + ]: + with pytest.raises(breach): + URL_HARNESS.check_parse_url(url, {**good, key: value}) + with pytest.raises(breach): + URL_HARNESS.check_parse_url("http://h:99999/", good) + with pytest.raises(breach): + URL_HARNESS.check_parse_url_refusal("http://h/") + URL_HARNESS.check_parse_url(url, good) + url = "http://u:p@h/x;p?q=1#f" + good = parse_url(url) + for key, value in [ + ("path", "/x;p"), + ("path", "/"), + ("query", ""), + ("query", None), + ("fragment", ""), + ]: + with pytest.raises(breach): + URL_HARNESS.check_parse_url(url, {**good, key: value}) + URL_HARNESS.check_parse_url(url, good) + url = "http://u:p@h\udcff/p\udcff?q\udcff#f\udcff" + good = { + "protocol": "http", + "host": "h\ufffd", + "port": 80, + "path": "/p\ufffd", + "query": "q\ufffd", + "fragment": "f\ufffd", + "clean_url": "http://h\ufffd/p\ufffd?q\ufffd#f\ufffd", + } + for key, value in [ + ("host", "h\udcff"), + ("path", "/p\udcff"), + ("query", "q\udcff"), + ("fragment", "f\udcff"), + ("clean_url", "http://h\udcff/p\ufffd?q\ufffd#f\ufffd"), + ]: + with pytest.raises(breach): + URL_HARNESS.check_parse_url(url, {**good, key: value}) + URL_HARNESS.check_parse_url(url, good) + + def test_planted_url_oracle_rejects_wrong_results(self) -> None: + """Test that check_planted_url rejects any result off the plant.""" + planted = URL_HARNESS.plant_url(0x25, b"alice\x00s3cret\x00host\x00\x1f\x90") + assert planted.url == "http://alice:s3cret@host:8080" + right = (planted.sanitized, planted.parts, planted.credentials) + wrong = [ + (planted.url, planted.parts, planted.credentials), + (planted.sanitized, {**planted.parts, "port": 80}, planted.credentials), + (planted.sanitized, planted.parts, ("alice", "")), + ] + for sanitized, parts, credentials in wrong: + with pytest.raises(URL_HARNESS.ContractBreach): + URL_HARNESS.check_planted_url(planted, sanitized, parts, credentials) + URL_HARNESS.check_planted_url(planted, *right) + + def test_emit_rejects_text_strict_utf8_cannot_carry(self) -> None: + """Test that emit fails on text a strict UTF-8 stream refuses.""" + for harness, args in [ + (URL_HARNESS, ("http://h/\udc80",)), + (HEADER_BODY_HARNESS, ("Custom Headers", "\udc80")), + ]: + with pytest.raises(UnicodeEncodeError): + harness.emit(*args) + + def test_header_oracle_rejects_wrong_results(self) -> None: + """Test that check_sanitized_headers rejects each kind of wrong result.""" + check = HEADER_BODY_HARNESS.check_sanitized_headers + placeholder = HEADER_BODY_HARNESS.HEADER_PLACEHOLDER + redacted = HEADER_BODY_HARNESS.REDACTED + wrong = [ + ('{"Authorization": "s"}', '{"Authorization": "s"}'), + ('{"X-Api-Key ": "s"}', '{"X-Api-Key ": "s"}'), + ('{"a": 1}', '{"a": true}'), + ('{"a": 1, "b": 2}', '{"b": 2, "a": 1}'), + ('{"a": 1, "b": 2}', '{"a": 1}'), + ('{"a": 1}', '{"a": 1, "a": 1}'), + ('{"a": 1}', placeholder), + ('{"a": 1}', "[1]"), + ("[1]", "[1]"), + ("{", "{"), + ("", placeholder), + ] + for text, result in wrong: + with pytest.raises(HEADER_BODY_HARNESS.ContractBreach): + check(text, result) + check('{"Cookie": 1, "a": NaN}', f'{{"Cookie": "{redacted}", "a": NaN}}') + + def test_header_oracle_checks_up_to_its_own_limit(self) -> None: + """Test that the oracle judges deep headers, and refuses deeper ones.""" + harness = HEADER_BODY_HARNESS + + def decodes(depth: int) -> bool: + try: + harness._object_or_none(deep_auth(depth)) + except harness.OracleExhausted: + return False + return True + + deepest = deepest_depth(decodes) + text = deep_auth(deepest) + with pytest.raises(harness.ContractBreach, match="not redacted"): + harness.check_sanitized_headers(text, text) + harness.check_sanitized_headers(text, '{"Authorization": "*** (redacted)"}') + # Past the limit by the room, so no call depth in this test matters. + text = deep_auth(deepest + harness.ORACLE_ROOM) + with pytest.raises(harness.ContractBreach, match="too deep"): + harness.check_sanitized_headers(text, '{"Authorization": []}') + harness.check_sanitized_headers(text, harness.HEADER_PLACEHOLDER) + + def test_header_oracle_holds_at_the_decoder_limit(self) -> None: + """Test a secret header nested around the depth production can decode.""" + harness = HEADER_BODY_HARNESS + placeholder = harness.HEADER_PLACEHOLDER + deepest = deepest_depth( + lambda depth: ( + harness.sanitize_headers_for_logging(deep_auth(depth)) != placeholder + ) + ) + room = harness.ORACLE_ROOM + for depth in range(max(0, deepest - room), deepest + room): + harness.check_one_input(b"\x00" + deep_auth(depth).encode()) + planted = depth.to_bytes(3, "little").rstrip(b"\x00") + if b"\x00" not in planted: + harness.check_one_input(b"\x01\x01\x00\x02" + planted) + + def test_header_oracle_keeps_its_own_secret_names(self) -> None: + """Test that the oracle requires redaction without the module's list.""" + with patch.object(HEADER_BODY_HARNESS, "SENSITIVE_HEADERS", frozenset()): + for name in HEADER_BODY_HARNESS.KNOWN_SECRET_HEADERS: + text = json.dumps({name: "s"}) + with pytest.raises(HEADER_BODY_HARNESS.ContractBreach): + HEADER_BODY_HARNESS.check_sanitized_headers(text, text) + + def test_header_generator_reaches_every_secret_name(self) -> None: + """Test that a planted key can take every name in the catalogue.""" + reached = { + HEADER_BODY_HARNESS._planted_key(bytes([first]))[0].strip().lower() + for first in range(1, 256, 2) + } + assert reached == set(HEADER_BODY_HARNESS.KNOWN_SECRET_HEADERS) + + def test_header_generator_caps_its_output(self) -> None: + """Test that many deep or long values stay within the budget.""" + budget = HEADER_BODY_HARNESS.GENERATED_BUDGET + for value in (b"\x02\x40\x42\x0f", b"\x01\xff\xff"): + text, _ = HEADER_BODY_HARNESS.plant_headers( + b"\x00" + (value + b"\x00\x00") * 600 + ) + assert budget <= len(text) < budget + 600 * 16 + + def test_planted_header_oracle_rejects_shown_secret(self) -> None: + """Test that check_planted_headers rejects a planted secret left shown.""" + text, secret_keys = HEADER_BODY_HARNESS.plant_headers(b"\x01\x00\x00") + assert secret_keys == ["authorization"] + with pytest.raises(HEADER_BODY_HARNESS.ContractBreach): + HEADER_BODY_HARNESS.check_planted_headers(text, secret_keys, text) + + def test_body_oracle_rejects_wrong_results(self) -> None: + """Test that check_sanitized_body rejects each kind of wrong result.""" + check = HEADER_BODY_HARNESS.check_sanitized_body + placeholder = HEADER_BODY_HARNESS.BODY_PLACEHOLDER + suffix = HEADER_BODY_HARNESS.TRUNCATION_SUFFIX + wrong = [ + ("my password", 100, "my password"), + ("hello world", 5, "hello world"), + ("hello world", 5, "hell" + suffix), + ("hello world", 5, "hello"), + ("hello", 5, "hello" + suffix), + ("hello", 100, placeholder), + ("", 100, placeholder), + ("ab\udcffcd", 100, "ab\udcffcd"), + ("ab\udcffcd", 100, "abcd"), + ("ab\udcffcd", 3, "ab\udcff" + suffix), + ] + for body, max_length, result in wrong: + with pytest.raises(HEADER_BODY_HARNESS.ContractBreach): + check(body, max_length, result) + check("hello world", 5, "hello" + suffix) + check("ab\udcffcd", 3, "ab\ufffd" + suffix) + + def test_body_oracle_keeps_its_own_secret_words(self) -> None: + """Test that the oracle withholds bodies without the module's list.""" + bodies = [*HEADER_BODY_HARNESS.KNOWN_SECRET_WORDS, "api \u212aey"] + # The module's list narrowed from "key" to "api_key" must not pass. + narrowed = ("password", "secret", "token", "api_key", "auth", "credential") + for patterns in ((), narrowed): + with patch.object(HEADER_BODY_HARNESS, "SENSITIVE_BODY_PATTERNS", patterns): + for body in bodies: + with pytest.raises(HEADER_BODY_HARNESS.ContractBreach): + HEADER_BODY_HARNESS.check_sanitized_body(body, 100, body) + + def test_planted_body_check_rejects_shown_secret(self) -> None: + """Test that a planted secret word must be withheld.""" + data = b"\x02\x01\x00\x00\x64hello" + with ( + patch.object(HEADER_BODY_HARNESS, "SENSITIVE_BODY_PATTERNS", ()), + patch.object( + HEADER_BODY_HARNESS, + "sanitize_request_body_for_logging", + lambda body, _max_length: body, + ), + pytest.raises(HEADER_BODY_HARNESS.ContractBreach), + ): + HEADER_BODY_HARNESS.check_one_input(data) + + +@pytest.mark.unit +class TestRedactionRegressions: + """Pin the redaction defects the fuzz harnesses found.""" + + def test_redacted_url_keeps_ipv6_brackets_and_port_zero(self) -> None: + """Test that redaction keeps an IPv6 literal and port 0.""" + assert ( + sanitize_url_for_logging("http://u:p@[::1]:8080/x") == "http://[::1]:8080/x" + ) + assert sanitize_url_for_logging("http://u:p@h:0/x") == "http://h:0/x" + + def test_stray_bracket_in_host_is_refused(self) -> None: + """Test that a bracket outside an IP literal gives the placeholder.""" + # urlparse accepts this and reports the host name as "v1.[". + url = "http://u]:p@[v1.[/x" + assert "p@" not in sanitize_url_for_logging(url) + assert sanitize_url_for_logging(url).startswith("[URL parsing failed") + with pytest.raises(ValueError, match="Invalid host"): + _ = parse_url(url) + + def test_padded_secret_header_is_redacted(self) -> None: + """Test that whitespace around a secret header name does not hide it.""" + result = json.loads( + sanitize_headers_for_logging('{"X-Api-Key ": "s", "\\tCookie": "c"}') + ) + assert result == {"X-Api-Key ": "*** (redacted)", "\tCookie": "*** (redacted)"} + + def test_json_limits_give_the_placeholder(self) -> None: + """Test that the digit and nesting limits do not escape as exceptions.""" + placeholder = "*** (invalid JSON - potentially sensitive)" + assert sanitize_headers_for_logging('{"a": ' + "9" * 5000 + "}") == placeholder + deep = '{"a": ' + "[" * 200_000 + "]" * 200_000 + "}" + assert sanitize_headers_for_logging(deep) == placeholder + + def test_undecodable_input_shows_replacement_character(self) -> None: + """Test that a lone surrogate from os.environ comes back as U+FFFD.""" + assert sanitize_url_for_logging("http://u:p@h/\udcff") == "http://h/\ufffd" + assert sanitize_url_for_logging("http://h/\udcff") == "http://h/\ufffd" + parts = parse_url("http://u:p@h\udcff/p\udcff?q\udcff#f\udcff") + assert parts == { + "protocol": "http", + "host": "h\ufffd", + "port": 80, + "path": "/p\ufffd", + "query": "q\ufffd", + "fragment": "f\ufffd", + "clean_url": "http://h\ufffd/p\ufffd?q\ufffd#f\ufffd", + } + body = "ab\udcffcd" + assert sanitize_request_body_for_logging(body) == "ab\ufffdcd" + truncated = sanitize_request_body_for_logging(body, 3) + assert truncated == "ab\ufffd... (truncated)" + + def test_cli_logs_undecodable_inputs_on_a_strict_stream(self) -> None: + """Test that the configuration log survives a strict UTF-8 stdout.""" + raw = io.BytesIO() + stream = io.TextIOWrapper(raw, encoding="utf-8", errors="strict") + config = {"url": "http://u:p@h/\udcff", "request_body": "ab\udcffcd"} + with patch("sys.stdout", stream): + _log_action_parameters(config) + stream.flush() + shown = raw.getvalue().decode("utf-8") + assert " URL: http://h/\ufffd\n" in shown + assert " Request Body: ab\ufffdcd\n" in shown + + if __name__ == "__main__": _ = pytest.main([__file__, "-v"])