Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
76 changes: 52 additions & 24 deletions src/http_api_tool/sanitize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down Expand Up @@ -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."""
Expand All @@ -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]"

Expand All @@ -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)"


Expand All @@ -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]:
Expand All @@ -93,31 +123,29 @@ 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)

port = parsed.port
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),
}


Expand Down
Loading
Loading