~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
"""Tests for log string sanitization."""
import time
import pytest
from local_deep_research.security.log_sanitizer import (
redact_secrets,
sanitize_error_for_agent,
sanitize_error_for_client,
sanitize_for_log,
scrub_error,
strip_control_chars,
)
class TestLogSanitizer:
"""Unit tests for sanitize_for_log."""
def test_normal_string_passes_through(self):
assert sanitize_for_log("hello") == "hello"
def test_non_printable_chars_stripped(self):
assert sanitize_for_log("hello\x00world\x07") == "helloworld"
def test_truncation_respects_max_length(self):
result = sanitize_for_log("a" * 100, max_length=10)
assert result == "a" * 7 + "..."
assert len(result) == 10
def test_no_truncation_at_exact_max_length(self):
result = sanitize_for_log("a" * 50, max_length=50)
assert result == "a" * 50
def test_empty_string(self):
assert sanitize_for_log("") == ""
def test_newlines_stripped(self):
assert sanitize_for_log("line1\nline2") == "line1line2"
def test_tabs_stripped(self):
assert sanitize_for_log("col1\tcol2") == "col1col2"
def test_unicode_preserved(self):
assert sanitize_for_log("café") == "café"
def test_cjk_preserved(self):
assert sanitize_for_log("你好") == "你好"
def test_control_chars_stripped_unicode_preserved(self):
assert sanitize_for_log("café\x00\x07") == "café"
class TestStripControlChars:
"""Unit tests for strip_control_chars."""
def test_strips_c0_control_chars(self):
assert strip_control_chars("a\x00b\x1fc") == "abc"
def test_strips_c1_control_chars(self):
assert strip_control_chars("a\x7fb\x9fc") == "abc"
def test_preserves_normal_text(self):
assert strip_control_chars("hello world") == "hello world"
def test_preserves_unicode(self):
assert strip_control_chars("café 你好 émoji") == "café 你好 émoji"
def test_strips_rlo_override(self):
assert strip_control_chars("hello\u202eworld") == "helloworld"
def test_strips_arabic_letter_mark(self):
assert strip_control_chars("hello\u061cworld") == "helloworld"
def test_strips_zero_width_space(self):
assert strip_control_chars("hello\u200bworld") == "helloworld"
def test_strips_bom(self):
assert strip_control_chars("\ufeffhello") == "hello"
def test_strips_word_joiner(self):
assert strip_control_chars("hello\u2060world") == "helloworld"
def test_strips_digit_shape_controls(self):
assert strip_control_chars("hello\u206aworld") == "helloworld"
def test_strips_mixed_format_chars(self):
assert (
strip_control_chars("café\u202e\u200b\ufeff 你好\u2060")
== "café 你好"
)
def test_empty_string(self):
assert strip_control_chars("") == ""
class TestRedactSecrets:
"""Unit tests for redact_secrets."""
def test_redacts_single_secret(self):
result = redact_secrets(
"call to ?key=sk-abc1234567 failed", "sk-abc1234567"
)
assert result == "call to ?key=***REDACTED*** failed"
def test_redacts_multiple_secrets(self):
result = redact_secrets(
"user=alice12345 token=tok-xyz98765",
"alice12345",
"tok-xyz98765",
)
assert "alice12345" not in result
assert "tok-xyz98765" not in result
assert result.count("***REDACTED***") == 2
def test_redacts_all_occurrences(self):
result = redact_secrets("X sk-12345678 Y sk-12345678 Z", "sk-12345678")
assert result == "X ***REDACTED*** Y ***REDACTED*** Z"
def test_none_secret_ignored(self):
assert redact_secrets("message stays put", None) == "message stays put"
def test_empty_secret_ignored(self):
# Replacing the empty string would insert the token between every
# character of the message; this is the load-bearing guard.
assert redact_secrets("message stays put", "") == "message stays put"
def test_short_secret_below_min_length_ignored(self):
# 7 characters is below the default min_length of 8.
result = redact_secrets("password is hunter", "hunter")
assert result == "password is hunter"
def test_min_length_parameter_lowers_threshold(self):
result = redact_secrets("password is hunter", "hunter", min_length=6)
assert result == "password is ***REDACTED***"
def test_no_secrets_returns_message_unchanged(self):
assert redact_secrets("hello world") == "hello world"
def test_empty_message_returned_unchanged(self):
assert redact_secrets("", "sk-abc1234567") == ""
def test_message_without_secret_returned_unchanged(self):
assert redact_secrets("hello world", "sk-abc1234567") == "hello world"
def test_custom_replacement(self):
result = redact_secrets(
"key=sk-abc1234567", "sk-abc1234567", replacement="[KEY]"
)
assert result == "key=[KEY]"
def test_empty_replacement_strips_secret(self):
# Replacement may be empty — strips the secret entirely. This
# is the right answer when the secret's presence itself is
# sensitive (not just its value).
result = redact_secrets(
"before sk-abc1234567 after", "sk-abc1234567", replacement=""
)
assert result == "before after"
def test_overlapping_secrets_redacted_longest_first(self):
# If two secrets overlap (one is a substring of the other), the
# function must apply the longer one first so a shorter
# secret cannot consume part of the longer match. Without
# length-sorting, the test fails: redacting "abc12345" first
# would leave "sk-***REDACTED***" in the message, then the
# longer "sk-abc12345" no longer matches.
result = redact_secrets(
"found sk-abc12345 here", "abc12345", "sk-abc12345"
)
assert result == "found ***REDACTED*** here"
assert "abc12345" not in result
def test_redaction_is_not_recursive(self):
# If a secret happens to equal the replacement token, the
# function does not loop forever — it does a single pass per
# secret and ``str.replace`` is not recursive.
result = redact_secrets("X ***REDACTED*** Y", "***REDACTED***")
# The pre-existing token gets replaced with the same token —
# net no-op, but importantly: no recursion, no exception.
assert result == "X ***REDACTED*** Y"
def test_importable_from_security_package(self):
# ``redact_secrets`` is exported from
# ``local_deep_research.security`` so future callers don't need
# to know the submodule path.
from local_deep_research.security import (
redact_secrets as exported,
)
assert exported is redact_secrets
@pytest.mark.parametrize(
"secret",
[
"sk-abc1234567890",
"AIzaSy-mock-google-key-12345",
"sk-ant-api03-very-long-anthropic-key-12345",
],
)
def test_realistic_provider_key_shapes_redacted(self, secret):
message = f"upstream failed: ?key={secret}&model=x"
assert secret not in redact_secrets(message, secret)
def test_literal_substring_match_only(self):
# Document the contract: URL-encoded or otherwise transformed
# forms are NOT redacted. Callers must pass each form they need
# to scrub.
result = redact_secrets("encoded=%2Bsk-abc12345", "+sk-abc12345")
assert "%2Bsk-abc12345" in result
class TestSanitizeErrorForClient:
"""The client-facing composition used for exception text returned over
HTTP/SSE (e.g. the library download stream)."""
def test_redacts_api_key_in_url(self):
msg = (
"HTTPError for https://api.example.com/doc?api_key=secret1234567890"
)
result = sanitize_error_for_client(msg)
assert "secret1234567890" not in result
def test_redacts_url_embedded_credentials(self):
msg = "ConnectionError: https://alice:hunter2pass@host/file.pdf failed"
result = sanitize_error_for_client(msg)
assert "hunter2pass" not in result
def test_truncates_to_max_length(self):
result = sanitize_error_for_client("e" * 500, max_length=200)
assert len(result) <= 200
def test_credential_scrubbed_before_truncation(self):
# The whole point of scrub-before-truncate: a key sitting past the
# max_length boundary must still be redacted, not merely cut off
# (a truncate-first order would leave the leading chars exposed if
# the cut landed mid-token).
key = "sk-abcdefghijklmnopqrstuvwxyz0123456789"
msg = "x" * 190 + " " + key
result = sanitize_error_for_client(msg, max_length=400)
assert key not in result
assert "sk-abcdefghij" not in result
@pytest.mark.parametrize(
"msg, secret",
[
(
"err https://api.x.com?access_token=SECRET_AT_123 fail",
"SECRET_AT_123",
),
("https://api.x.com?refresh_token=SECRET_RT_123", "SECRET_RT_123"),
(
"https://x.cognitive.microsoft.com?subscription-key=SECRET_SUB1",
"SECRET_SUB1",
),
("oauth ?client_secret=SECRET_CS_123&grant=x", "SECRET_CS_123"),
("?secret_key=SECRET_SK_123&page=2", "SECRET_SK_123"),
(
"401 Authorization: Basic SECRETBASICVALUE123 denied",
"SECRETBASICVALUE123",
),
(
"Authorization: token ghp_TOKENVALUE1234567890 x",
"ghp_TOKENVALUE1234567890",
),
(
"req x-api-key: SECRETXAPIKEYVALUE12345 blocked",
"SECRETXAPIKEYVALUE12345",
),
# Schemeless Authorization carrying a token-shaped raw value.
(
"Authorization: ghp_RAWTOKEN1234567890 rejected",
"ghp_RAWTOKEN1234567890",
),
# Anchored (scheme / x-api-key) values redact regardless of shape,
# incl. purely-alphabetic ones — the anchor rules out prose.
(
"Authorization: Basic ABCDEFGHIJKLMNOP denied",
"ABCDEFGHIJKLMNOP",
),
(
"x-api-key: ALPHAONLYKEYVALUEABCDEFGH blocked",
"ALPHAONLYKEYVALUEABCDEFGH",
),
(
"google AIzaSyD-SECRET_GOOGLE_KEY_1234567890 abc",
"AIzaSyD-SECRET_GOOGLE_KEY_1234567890",
),
# Case-insensitive query params (capitalized names must not bypass).
("https://x.com?API_KEY=SECRET_UP1", "SECRET_UP1"),
("https://x.com?Access_Token=SECRET_MIX1", "SECRET_MIX1"),
],
)
def test_redacts_additional_credential_formats(self, msg, secret):
"""OAuth tokens, Azure subscription keys, Authorization/x-api-key
headers, Google API keys, and case-variant query params must all be
scrubbed (#4633 follow-up)."""
assert secret not in sanitize_error_for_client(msg)
@pytest.mark.parametrize(
"msg, preserved",
[
("page request ?page=2&limit=10", "page=2"),
("Basic understanding of the topic", "understanding"),
("key concepts explained here", "concepts"),
("fetched https://example.com/path?id=42 ok", "id=42"),
# Schemeless "Authorization:" followed by an all-alphabetic word
# is prose, not a token — the token-shaped requirement on the
# schemeless branch keeps it intact.
("401: Authorization: required for this endpoint", "required"),
("Authorization: denied because user lacks role", "denied"),
# Short values below the floors are left intact (x-api-key needs
# >=16, the scheme branch needs >=8).
("Response 403: x-api-key: invalid or expired", "invalid"),
("Header x-api-key: missing from request", "missing"),
("Authorization: bearer ab12 failed", "ab12"),
("x-api-key: abc12 next", "abc12"),
],
)
def test_does_not_over_redact_innocuous_text(self, msg, preserved):
"""Non-credential query params, schemeless-Authorization prose, and
sub-floor values must survive untouched (no false-positive
redaction)."""
result = sanitize_error_for_client(msg)
assert preserved in result
assert "REDACTED" not in result
@pytest.mark.parametrize(
"msg, secret",
[
(
"failed ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 here",
"ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
),
(
"github_pat_11ABCDE0aBcDeFgHiJ_kLmNoPqRsTuVwXyZ0123456789AbCdEf x",
"github_pat_11ABCDE0aBcDeFgHiJ_kLmNoPqRsTuVwXyZ0123456789AbCdEf",
),
("AWS AKIAIOSFODNN7EXAMPLE rejected", "AKIAIOSFODNN7EXAMPLE"),
("creds ASIAY34FZKBOKMUTVV7A expired", "ASIAY34FZKBOKMUTVV7A"),
(
# Prefix split ("xox" + ...) so the literal isn't a scannable
# Slack-token shape that trips GitHub push protection.
"slack " + "xox" + "b-2345678901-abcdefABCDEF123456 failed",
"xox" + "b-2345678901-abcdefABCDEF123456",
),
(
"cfg " + "xox" + "e-1-AB-2345678901-abcdef123456 expired",
"xox" + "e-1-AB-2345678901-abcdef123456",
),
(
"app " + "xa" + "pp-1-A012345-678901234567-abcdef0123 bad",
"xa" + "pp-1-A012345-678901234567-abcdef0123",
),
(
"token ya29.a0AfH6SMBsecretOAUTH_token-12345 expired",
"ya29.a0AfH6SMBsecretOAUTH_token-12345",
),
(
"auth eyJhbGciOiJIUzI1Ni2.eyJzdWIiOiIxMjM0NTY3OD2.dozjgNryP4 bad",
# assert the WHOLE JWT is gone, not just one segment
"eyJhbGciOiJIUzI1Ni2.eyJzdWIiOiIxMjM0NTY3OD2.dozjgNryP4",
),
],
)
def test_redacts_provider_token_prefixes(self, msg, secret):
"""GitHub/AWS/Slack/Google-OAuth tokens and JWTs (canonical gitleaks
prefixes) must be scrubbed from error text."""
assert secret not in sanitize_error_for_client(msg)
@pytest.mark.parametrize(
"msg, preserved",
[
("the AKIApattern doc explains this", "AKIApattern"),
("ghp build pipeline failed", "ghp"),
("see ya29 release notes for details", "ya29"),
("eyJot just an ordinary word here", "eyJot"),
# The generic Slack ``xapp``/``xox`` prefixes require a long
# numeric workspace ID, so hyphenated prose that merely starts
# with them (and carries no 9+ digit run) survives untouched.
("xapp-release-notes-2026 published", "xapp-release-notes-2026"),
("rolling out xapp-config-reload now", "xapp-config-reload"),
("xoxe-release-bundle-2026 attached", "xoxe-release-bundle-2026"),
("module xoxb-internal-doc loaded", "xoxb-internal-doc"),
],
)
def test_token_prefixes_do_not_over_redact_prose(self, msg, preserved):
"""The prefix patterns are distinctive/length-floored — ordinary
prose that merely starts with a prefix is not redacted."""
result = sanitize_error_for_client(msg)
assert preserved in result
assert "REDACTED" not in result
def test_importable_from_security_package(self):
from local_deep_research.security import (
sanitize_error_for_client as exported,
)
assert exported is sanitize_error_for_client
class TestScrubError:
"""Unit tests for scrub_error (the shared dual-scrub helper)."""
def test_scrubs_credential_shapes_from_exception(self):
err = ValueError("401 for Bearer sk-abc1234567890abcdef")
result = scrub_error(err)
assert "sk-abc1234567890abcdef" not in result
def test_redacts_literal_secrets(self):
# A bare key with no recognizable shape only falls to the
# literal pass — the reason the dual-scrub exists.
err = RuntimeError("auth failed for key plainkey12345678")
result = scrub_error(err, "plainkey12345678")
assert "plainkey12345678" not in result
assert "***REDACTED***" in result
def test_accepts_prebuilt_message_string(self):
result = scrub_error("token tok-xyz9876543 rejected", "tok-xyz9876543")
assert "tok-xyz9876543" not in result
def test_non_string_secret_coerced(self):
# A misconfigured numeric secret must not crash the except
# handler that calls this (redact_secrets calls len()).
err = RuntimeError("key 123456789012 invalid")
result = scrub_error(err, 123456789012)
assert "123456789012" not in result
def test_none_and_falsy_secrets_skipped(self):
msg = "plain message"
assert scrub_error(RuntimeError(msg), None, "", 0) == msg
def test_multiple_secrets_all_redacted(self):
# Kills the "forward only the first secret" mutant: every
# truthy secret must survive the coercion. (Longest-first
# ordering itself is pinned by
# test_overlapping_secrets_redacted_longest_first.)
err = RuntimeError("user token1234567 key sk-abc12345 done")
result = scrub_error(err, "token1234567", "abc12345", "sk-abc12345")
assert "token1234567" not in result
assert "abc12345" not in result
def test_pathological_secret_does_not_crash(self):
# The never-raise contract covers secrets too: a value whose
# __bool__/__str__ raises is skipped, not propagated out of the
# except handler; the other secrets are still redacted.
class BadBool:
def __bool__(self):
raise ValueError("nobool")
err = RuntimeError("key goodsecret123456 invalid")
result = scrub_error(err, BadBool(), "goodsecret123456")
assert "goodsecret123456" not in result
def test_unprintable_exception_guarded(self):
class Unprintable(Exception):
def __str__(self):
raise RuntimeError("boom")
result = scrub_error(Unprintable())
assert result == "<unprintable Unprintable>"
def test_combined_pathology_never_raises(self):
"""Lock the documented "must never raise" contract against the two
theoretical edges called out in the review of #5261: the
``<unprintable {type(error).__name__}>`` fallback
(``log_sanitizer.py:328``) and the unguarded per-secret coercion
feeding ``redact_secrets`` (``:340``).
Exercises both at once: an exception built from a custom metaclass
whose ``__str__`` raises (forcing the type-name fallback) together
with a secret whose ``__bool__`` is non-deterministic/raising. The
handler must swallow both, still redact the well-behaved secret, and
render the type-name fallback — never propagate out of the ``except``
block it is meant to protect.
"""
class _RaisingMeta(type):
def __getattribute__(cls, name):
# Even resolving __name__ via the metaclass is hostile;
# scrub_error must still degrade gracefully.
if name == "__name__":
return type.__getattribute__(cls, "__name__")
return type.__getattribute__(cls, name)
class PathologicalError(Exception, metaclass=_RaisingMeta):
def __str__(self):
raise RuntimeError("cannot stringify")
class NonDeterministicBool:
def __bool__(self):
raise ValueError("no truth value")
def __str__(self):
raise ValueError("no string value")
# Must not raise even with a hostile exception AND a hostile secret.
result = scrub_error(
PathologicalError(),
NonDeterministicBool(),
"goodsecret123456",
)
# Type-name fallback is used because __str__ raised.
assert result == "<unprintable PathologicalError>"
# The well-behaved literal secret is unrelated to this message, but
# the point is the call completed without propagating an exception.
assert "goodsecret123456" not in result
def test_matches_engine_scrub_error(self):
# BaseSearchEngine._scrub_error delegates here; the two must
# produce identical output for the same inputs.
from local_deep_research.web_search_engines.search_engine_base import (
BaseSearchEngine,
)
class _Engine(BaseSearchEngine):
def _get_previews(self, query):
return []
def _get_full_content(self, relevant_items):
return relevant_items
# __new__ skips BaseSearchEngine.__init__ — only _scrub_error's
# _secret_attrs lookup matters here.
engine = _Engine.__new__(_Engine)
engine.api_key = "literalsecret123"
err = RuntimeError("denied for literalsecret123")
assert engine._scrub_error(err) == scrub_error(err, "literalsecret123")
def test_exported_from_security_package(self):
from local_deep_research.security import scrub_error as exported
assert exported is scrub_error
@pytest.mark.parametrize("control", ["\r", "\n", "\r\n"])
@pytest.mark.parametrize("long_guarded", [False, True])
def test_p6_premise_scrub_error_does_not_strip_control_chars(
control, long_guarded
):
"""Guard the credential-only classification in the P6 source sweep.
Analysis may inspect a stripped view without stripping returned text.
If output starts neutralizing controls, revisit the sweep's scrubber
classification and inventory rather than preserving this behavior just
to satisfy the premise.
"""
prefix = f"first line{control}second line "
message = prefix
if long_guarded:
message += (
"https://host/path?query=value password=value details "
+ "ordinary detail " * 3_000
)
result = scrub_error(message)
assert result.startswith(prefix), (
"scrub_error now neutralizes controls; revisit pattern 6's "
"credential-only classification and inventory"
)
if long_guarded:
assert "https://host/path?<redacted>" in result
assert result.endswith("characters omitted from log output]")
else:
assert result == message
class TestScrubErrorUrlQueryRedaction:
"""scrub_error() must strip a URL's query string even when it carries no
credential-shaped parameter (#6403) — e.g. a search engine's own query
text, reachable via a library-formatted message such as
``requests.Response.raise_for_status``'s ``"... for url: <url>"``.
Scoped to scrub_error() only: sanitize_error_for_client() (the
client-facing path) must keep preserving non-credential query params,
per TestSanitizeErrorForClient.test_does_not_over_redact_innocuous_text.
Timing convention for this class's budget tests (#6612): elapsed is
measured on the CPU clock (time.process_time) and the wall-clock
backstop is @pytest.mark.timeout(15) — see the note in
test_scrub_error_is_bounded_on_a_run_of_bare_schemes for rationale.
"""
def test_strips_query_string_from_requests_style_http_error(self):
# Reproduces the PubMed 429 case from #6403: raise_for_status()
# embeds the fully-encoded request URL, including the raw query
# text, in the exception message.
probe = "does+my+employer+know+i+have+multiple+sclerosis"
msg = (
"429 Client Error: Too Many Requests for url: "
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
f"?db=pubmed&term={probe}&retmode=json&retmax=100&usehistory=y"
)
result = scrub_error(Exception(msg))
assert probe not in result
assert "term=" not in result
# Endpoint identity (scheme/host/path) survives — only the query
# component is replaced, so the handler's own diagnostic value
# (status, reason, which endpoint) is preserved.
assert (
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
"?<redacted>" in result
)
assert "429 Client Error: Too Many Requests" in result
def test_still_redacts_credential_shaped_query_params(self):
# The existing credential-query-param pass and the new blanket
# strip are not mutually exclusive — a credential-shaped param
# must still end up redacted.
err = Exception(
"err https://api.x.com/search?access_token=SECRET_AT_123 fail"
)
result = scrub_error(err)
assert "SECRET_AT_123" not in result
def test_message_without_a_url_is_untouched(self):
assert scrub_error(Exception("plain failure, no url")) == (
"plain failure, no url"
)
def test_url_without_query_string_is_untouched(self):
msg = "GET https://example.com/health failed"
assert scrub_error(Exception(msg)) == msg
def test_does_not_affect_sanitize_error_for_client(self):
# The blanket URL-query strip is scrub_error-only; the client-facing
# path must keep preserving non-credential query params (locked by
# TestSanitizeErrorForClient.test_does_not_over_redact_innocuous_text).
msg = "fetched https://example.com/path?id=42 ok"
assert "id=42" in sanitize_error_for_client(msg)
def test_one_character_scheme_is_covered(self):
# RFC 3986 §3.1: a scheme is one ALPHA followed by zero or more
# ALPHA/DIGIT/+/-/. — a lower-bound-1 continuation quantifier would
# silently skip a valid single-character scheme (review of #6422).
result = scrub_error(Exception("x://host/path?term=secret"))
assert "secret" not in result
assert "x://host/path?<redacted>" in result
def test_markdown_link_closing_paren_survives(self):
# The query must not consume past the URL's own end when it's
# wrapped in prose punctuation — a markdown link's closing ``)``
# must not be eaten by the redaction (review of #6422).
result = scrub_error(Exception("see [link](https://h/p?q=1) end"))
assert result == "see [link](https://h/p?<redacted>) end"
def test_quoted_url_closing_quote_survives(self):
result = scrub_error(Exception('url "https://h/p?q=1" end'))
assert result == 'url "https://h/p?<redacted>" end'
def test_unspaced_adjacent_urls_fail_closed(self):
# Two URLs with no whitespace between them (e.g. a comma-joined
# list) are not split apart — the first URL's query pattern has no
# way to know where it ends short of whitespace/wrapper chars, so
# the second URL is swallowed into the first's redaction. This is
# accepted (review of #6422): over-redaction, never a leak — no
# raw query value from either URL survives.
result = scrub_error(
Exception("https://x.com/p?k=1,https://y.org/q?z=2")
)
assert result == "https://x.com/p?<redacted>"
assert "k=1" not in result
assert "z=2" not in result
def test_apostrophe_in_query_is_a_known_accepted_edge(self):
# Stopping the query at a closing quote (needed so a *quoted URL*'s
# own trailing quote survives, see
# test_quoted_url_closing_quote_survives) means a literal, unencoded
# apostrophe *inside* query text also stops the redaction early.
# Accepted per review of #6422, on the same footing as the
# already-accepted raw-unencoded-space edge: a URL built by a real
# HTTP client always percent-encodes "'" to "%27", so this shape
# does not occur in a prepared request URL.
result = scrub_error(
Exception("fetch https://h/p?term=what's+up failed")
)
assert "https://h/p?<redacted>" in result
assert "up failed" in result
def test_bare_question_mark_with_no_query_is_untouched(self):
# The query group requires >=1 char (``+``, not ``*``): a bare
# trailing "?" is not a query, so it must not be rewritten into
# "?<redacted>", which would imply a query existed where none did
# (review of #6422).
msg = "try https://h/p? yes"
assert scrub_error(Exception(msg)) == msg
def test_params_after_a_redacted_credential_param_are_stripped(self):
# Regression for #6549. The query strip runs after
# sanitize_error_message, which replaces a credential-shaped value
# with "[REDACTED]". With "]" in the query stop-set the strip halted
# at that marker, so everything after the credential parameter —
# here Google PSE's real order: key, cx, q — reached the log while
# the URL looked scrubbed:
# ...customsearch/v1?<redacted>]&cx=0123456789&q=does+my+employer+know
# The "key=" parameter triggers redaction, so use an obvious
# placeholder that will not be mistaken for a real Google API key.
api_key = "not-a-secret"
probe = "does+my+employer+know+i+have+multiple+sclerosis"
msg = (
"403 Client Error: Forbidden for url: "
"https://www.googleapis.com/customsearch/v1"
f"?key={api_key}&cx=0123456789&q={probe}&num=10"
)
result = scrub_error(Exception(msg))
assert probe not in result
assert "cx=" not in result
assert "num=10" not in result
assert api_key not in result
assert "https://www.googleapis.com/customsearch/v1?<redacted>" in result
# And nothing of the marker's closing bracket leaks through either.
assert "]" not in result
assert "403 Client Error: Forbidden" in result
def test_params_after_a_redacted_token_param_are_stripped(self):
# Same gap via the token-shaped path, which emits "[REDACTED_KEY]".
msg = (
"err https://api.x.com/search?token=eyJhbGciOiJIUzI1NiJ9.abc.def"
"&q=my+secret+query fail"
)
result = scrub_error(Exception(msg))
assert "my+secret+query" not in result
assert "eyJhbGciOiJIUzI1NiJ9" not in result
assert result == "err https://api.x.com/search?<redacted> fail"
def test_bracketed_url_over_redacts_rather_than_leaks(self):
# Consequence of taking "]" out of the stop-set: a URL written inside
# square brackets loses its closing bracket to the redaction. That is
# the safe direction (over-redaction, never a leak) and the price of
# not halting at "[REDACTED]" — pinned so it is a decision, not an
# accident.
result = scrub_error(Exception("see [https://h/p?q=1] end"))
assert "q=1" not in result
assert result == "see [https://h/p?<redacted> end"
@pytest.mark.timeout(15)
def test_scrub_error_is_linear_time_on_a_dense_url_run(self):
# Regression for #6549. The scheme-continuation bound (next test)
# covers one quadratic path; the URL body was the other. With an
# unbounded ``[^\s?#]+`` followed by ``\?``, a whitespace-free run
# dense in "://" (a minified JSON list of URLs — the shape a
# stringified response body has) made the engine consume to the end
# of the run at every "://" and backtrack looking for a "?" that
# never comes: measured ~1s at 36k chars, ~4s at 72k, ~16s at 144k
# (4x per doubling), against milliseconds before the query pass.
# Excluding the quote from the URL body and capping it restores
# linear time (locally: 200k chars in ~30ms). Timing and the
# wall-clock backstop follow the note in the bare-schemes test
# below (#6612).
run = '"https://a.com/x",' * 11_111 # ~200k chars, no "?" anywhere
t0 = time.process_time()
result = scrub_error(Exception(run))
elapsed = time.process_time() - t0
assert result == run # no query string, nothing to redact
assert elapsed < 2.0, (
f"scrub_error took {elapsed:.2f}s cpu on a 200k-char dense-URL "
f"run (budget: 2.0s) — the URL-body quantifier may have regressed "
f"to unbounded, reintroducing quadratic ReDoS."
)
@pytest.mark.timeout(15)
def test_scrub_error_is_bounded_on_a_run_of_bare_schemes(self):
# The worst remaining shape for the capped body: no quote to stop
# at, "://" at every fourth char, no "?" — each start position now
# scans at most 4096 chars instead of the remainder of the run, so
# the cost is linear in the input rather than quadratic.
# Budgets are measured on the CPU clock (process_time), not the
# wall clock: #6612 (a green-main docs PR) failed THIS test at
# 2.17s wall on an xdist-loaded runner — local CPU time for this
# input is ~0.44s, far under budget. The regex is pure in-process
# CPU work, so process_time measures the cost without the
# scheduler-noise component of co-scheduled pytest workers
# (residual cache-pollution inflation is real but bounded:
# measured ≤ ~1.7x here vs the ~4.9x wall inflation in #6612).
# This test carries the tightest healthy margin of the three
# (~0.44s local CPU), so its budget is 2.5s to absorb slow CI
# cores; a cap-removed regression measures >4s CPU locally and
# still trips it.
# The wall-clock backstop is 15s, not 5s: pytest-timeout bounds
# setup + call on the WALL clock, and on an xdist-loaded runner
# several seconds of setup/import can elapse with near-zero CPU
# cost — a 5s wall cap flaked exactly there under load even with
# the CPU budget comfortably met, and a real ~4.3s-CPU regression
# under contention would die by timeout before this assert could
# print its diagnostic. 15s still hard-fails hang-class
# regressions (the marker's actual purpose).
run = "x://" * 20_000 # 80k chars
t0 = time.process_time()
scrub_error(Exception(run))
elapsed = time.process_time() - t0
assert elapsed < 2.5, (
f"scrub_error took {elapsed:.2f}s cpu on an 80k-char run of "
f"bare schemes (budget: 2.5s) — the URL-body cap may have been "
f"removed."
)
@pytest.mark.timeout(15)
@pytest.mark.parametrize(
"unit",
["abcdefghijklmnopqrstuvwxyzabcdef://:", "ab://:"],
ids=["long-scheme", "short-scheme"],
)
def test_slash_dsn_pattern_is_linear_on_userinfo_like_runs(self, unit):
# Regression for the slash-bearing DSN pattern the log-record path
# adds: its password class may run through '/', and uncapped it
# scanned to the end of a whitespace-free "scheme://:" run with no
# '@' at every scheme start (measured ~9s CPU for 32k chars of the
# long-scheme unit, holding the GIL for the whole pass). Capping the
# user and password groups bounds the work per start position.
# CPU-clock budget and wall-clock backstop follow the bare-schemes
# test above (#6612).
run = unit * (32_760 // len(unit))
t0 = time.process_time()
_logged(run)
elapsed = time.process_time() - t0
assert elapsed < 2.0, (
f"the log-record redaction took {elapsed:.2f}s cpu on a "
f"{len(run)}-char run of {unit!r} (budget: 2.0s) — the "
f"slash-bearing DSN pattern may have lost its length caps."
)
@pytest.mark.timeout(15)
@pytest.mark.parametrize(
"unit",
[
"abcdefghijklmnopqrstuvwxyzabcdef://:",
"abcdefghijklmnopqrstuvwxyzabcde://:",
"abcdefghijklmnopqrstuvwxyzabcdef://u:1",
],
ids=["32-letter-scheme", "31-letter-scheme", "32-letter-user-digit"],
)
def test_slash_dsn_pattern_tries_each_scheme_separator_once(self, unit):
# The capped slash-DSN pattern is linear, but tried from every
# scheme start it re-ran the same capped user/password tail up to
# 31 times per '://' on a run of long schemes: ~5-6x the cost of
# the generic URL-credential pattern on the same run. Entering a
# scheme run once (lookbehind + atomic group) makes it a fraction
# of the generic pattern's cost there. The comparison is a ratio
# measured in the same process, so it holds on slow CI cores where
# an absolute budget would have to be loose enough to let a 5x
# slowdown through.
from local_deep_research.security import log_sanitizer
def only(predicate):
found = [
entry
for entry in (
log_sanitizer._CREDENTIAL_PATTERNS
+ log_sanitizer._ADDITIONAL_CREDENTIAL_PATTERNS
)
if predicate(entry[0].pattern)
]
assert len(found) == 1, found
return found[0]
generic = only(
lambda p: p.startswith(r"([A-Za-z][A-Za-z0-9+.\-]{1,31}://)")
)
slash = only(lambda p: "{1,256}" in p)
run = unit * (32_760 // len(unit))
def cpu(entry):
pattern, replacement = entry
best = float("inf")
for _ in range(3):
t0 = time.process_time()
pattern.sub(replacement, run)
best = min(best, time.process_time() - t0)
return best
generic_cpu = cpu(generic)
slash_cpu = cpu(slash)
assert slash_cpu < generic_cpu, (
f"the slash-DSN pattern took {slash_cpu * 1000:.1f} ms cpu on a "
f"{len(run)}-char run of {unit!r}, more than the generic URL "
f"pattern's {generic_cpu * 1000:.1f} ms: it is retrying the "
f"capped tail from every scheme start again."
)
@pytest.mark.timeout(15)
def test_scrub_error_is_linear_time_on_a_long_scheme_like_run(self):
# @pytest.mark.timeout is a hard backstop, not just the assertion
# below: it fails the test outright if scrub_error itself hangs,
# so a regression worse than quadratic can't block CI indefinitely
# waiting for a call that would otherwise never return in time.
#
# Regression for a measured quadratic ReDoS (review of #6422): an
# unbounded scheme-continuation quantifier (``[A-Za-z0-9+.-]*``)
# made matching O(n^2) on a long ALPHA/DIGIT/+/-/. run with no
# following "://" — at every start offset the engine consumes the
# run, fails to find "://", and backtracks the whole remaining run.
# Measured on the unbounded regex: 50k chars ~1.4s, 100k ~5.8s,
# 200k ~23.5s, 400k ~92.9s (clean quadratic, ~4x per doubling) —
# a ~1MB run would hang a worker for ~15 minutes, on a path that
# by definition handles attacker-influenceable exception text.
# Bounding the continuation restores linear time (locally: 200k
# chars in ~50ms). Generous 2s CPU budget absorbs slow CI cores
# while still catching a regression by orders of magnitude
# (timing and wall-clock backstop — see the note in the
# bare-schemes test below, #6612).
run = "a" * 200_000 # no "://" anywhere in this string
t0 = time.process_time()
scrub_error(Exception(run))
elapsed = time.process_time() - t0
assert elapsed < 2.0, (
f"scrub_error took {elapsed:.2f}s cpu on a 200k-char "
f"scheme-like run (budget: 2.0s) — the scheme-continuation "
f"quantifier may have regressed to unbounded, reintroducing "
f"quadratic ReDoS."
)
class TestSanitizeErrorForAgent:
"""The agent-facing composition used for tool errors returned into a
LangGraph / agent reasoning loop. Same redaction as
:class:`TestSanitizeErrorForClient`, but with a 500-char cap so the
agent and the ErrorReporter pattern map keep the categorizable signal.
"""
def test_redacts_api_key_in_url(self):
msg = (
"HTTPError for https://api.example.com/doc?api_key=secret1234567890"
)
result = sanitize_error_for_agent(msg)
assert "secret1234567890" not in result
def test_truncates_to_500_chars(self):
# The HTTP-client default is 200; the agent cap is 500. A 600-char
# message must be capped to 500, not 200.
result = sanitize_error_for_agent("e" * 600)
assert len(result) <= 500
assert len(result) > 200 # would fail under the client cap
def test_credential_scrubbed_before_truncation(self):
# A key sitting past the 500-char boundary must still be redacted,
# not merely cut off (scrub-before-truncate invariant).
key = "sk-abcdefghijklmnopqrstuvwxyz0123456789"
msg = "x" * 490 + " " + key
result = sanitize_error_for_agent(msg)
assert key not in result
assert result == "x" * 490 + " [REDAC..."
def test_preserves_long_categorizable_signal(self):
# The whole reason for the larger cap: an ErrorReporter pattern like
# "RateLimitError: 429 Too Many Requests (forwarded from upstream)"
# must survive intact so the pattern map can categorize it. Under
# the 200-char client cap the error type would be lost entirely.
msg = (
"upstream detail: "
+ "x" * 240
+ (
" RateLimitError: 429 Too Many Requests — the upstream provider "
"is throttling this account. Retry-After suggests backoff."
)
)
result = sanitize_error_for_agent(msg)
assert "RateLimitError" in result
assert "429" in result
assert len(result) == len(msg) # well under cap, unchanged
def test_strips_control_characters(self):
# Falsifiability: the composition is redaction THEN
# sanitize_for_log, and only the latter strips control chars — a
# mutant that drops it (returning sanitize_error_message alone, or
# delegating to a client helper that only redacts) leaves these
# bytes in place. _UNSAFE_CHAR_RE covers C0 (\x00-\x1f) and C1
# (\x7f-\x9f) as separate ranges, so probe one of each alongside
# a secret to pin both halves of the composition at once.
key = "sk-abcdefghijklmnopqrstuvwxyz0123456789"
msg = f"boom \x1b[31m ESC and \x9b CSI carrying {key} inline"
result = sanitize_error_for_agent(msg)
assert "\x1b" not in result # C0
assert "\x9b" not in result # C1
assert key not in result
assert "[REDACTED_KEY]" in result
def test_importable_from_security_package(self):
import local_deep_research.security as security_pkg
from local_deep_research.security import (
sanitize_error_for_agent as exported,
)
assert exported is sanitize_error_for_agent
# ``from ... import`` resolves the attribute directly and never
# consults ``__all__``, so assert the export list separately: a
# name dropped from ``__all__`` would otherwise pass unnoticed.
assert "sanitize_error_for_agent" in security_pkg.__all__
def _logged(msg):
"""*msg* as the loguru patcher (``redact_log_record``) hands it to the
sinks."""
from local_deep_research.security.log_sanitizer import redact_log_record
record = {"message": msg}
redact_log_record(record)
return record["message"]
def _secret_fragments_behind_a_marker(ls, exception_context, seeds):
"""The marker property, over *seeds*, for the module *ls* (a
``log_sanitizer``) and *exception_context* (``_exception_context``).
Each seed plants one secret -- one to three words of ``Q``, ``Z``,
``J``, ``7``, ``8``, ``9`` and ``& # ! $ / . + - @ ' "`` -- as the value
of a quoted key or a ``;``/``,`` parameter (bare, quoted,
string-prefixed, or inside a container, a call or adjacent strings), as
JSON and as a repr, after an ``Authorization`` scheme word, as an
``Api-Key:`` header (after a 16-character key run) or as a slash-bearing
DSN password. The text before it holds no credential shape, so a
marker before it on its line can only be the planted value's own. A
violation is any 4-character fragment of the secret (with one of the
six letters and digits in it, which no other part of the line has)
anywhere after a marker on the secret's line, on the log-record path
(``redact_log_record``) or in the database exception prefix.
Two kinds of case are exempt, each decided by its own check:
``reference``, where the passes that run before the added shapes
already print a fragment after a marker (``_redact_log_text`` for the
record, ``sanitize_error_message`` and the 240-character cap for the
prefix); and ``shaped``, where the planted text holds the shape of a
whole value followed by more structure -- the value's own closing
quote, then one of the quoted-value followers; for the header, the
key run's end, then a structural follower; for a DSN, an '@' and a
host, then a host's end -- which no allowlist can tell from a real
end (see ``log_sanitizer._cuts_a_value``).
"""
import json
import random
import re
from types import SimpleNamespace
distinct = "QZJ789"
symbols = "&#!$/.+-@'\""
quoted_followers = ",}]):;&#"
key_names = [
"password",
"api_key",
"token",
"client_secret",
"db_password",
"X-API-KEY",
"api-key",
"llm.openai.api_key",
"_api_key",
"Authorization",
]
param_names = ["password", "token", "api_key", "key", "secret", "pwd"]
wrappers = [
("", ""),
("'", "'"),
('"', '"'),
("b'", "'"),
("Rb'", "'"),
("(b'", "',)"),
("bytearray(b'", "')"),
("SecretStr('", "')"),
("(1, '", "')"),
("{0: '", "'}"),
("Foo(a, '", "')"),
("'''", "'''"),
('"""', '"""'),
("x'", "'"),
("ab\\'", "'"),
("[1, 2, '", "']"),
]
prefixes = ["", "{", "(", " ", "user=bob ", "{'n': 1, ", '{"m": "m", ']
suffixes = [
"",
"}",
", 'n': 1}",
")",
"]",
" and more",
"\n next",
";x=1",
"&x=1",
"#frag",
" }",
"!",
"'",
'"',
": rejected",
", 'token': 'abc'}",
]
marker = re.compile(r"\[REDACTED|<redacted>|\*\*\*REDACTED")
key_run = re.compile(r"[A-Za-z0-9\-._~+/]{16,}=*")
host = re.compile(r"[A-Za-z0-9][A-Za-z0-9.\-_~%]*(?=[\s:/?#\"'<>,;)\]}\\])")
def word(rng, size):
chars = [rng.choice(distinct) for _ in range(2)]
chars += [rng.choice(distinct + symbols) for _ in range(size - 2)]
rng.shuffle(chars)
return "".join(chars)
def secret(rng):
words = rng.choice([1, 1, 2, 3])
return " ".join(word(rng, rng.randint(3, 8)) for _ in range(words))
def ends_there(rest, followers):
rest = rest.lstrip(" ")
return rest[:1] in ("\n", "\r") or (rest != "" and rest[0] in followers)
def quoted_shape(quote, text):
# The regex's quoted value ends at the first quote of either kind;
# the other kind refuses it.
firsts = [i for i in (text.find("'"), text.find('"')) if i != -1]
if not firsts or text[min(firsts)] != quote:
return False
return ends_there(text[min(firsts) + 1 :], quoted_followers)
def shaped(slot, opener, closer, text):
if slot in ("key", "param"):
if opener == "":
return text[:1] in ("'", '"') and quoted_shape(
text[0], text[1:]
)
quote = opener.lstrip("bBrRuUfF")
if quote in ("'", '"') and closer == quote:
return quoted_shape(quote, text)
return False
if slot == "apikey":
run = key_run.match(text)
if run is None:
return False
rest = text[run.end() :]
if ends_there(rest, ",;)]}"):
return True
rest = rest.lstrip(" ")
return rest[:1] in ("'", '"') and ends_there(
rest[1:], quoted_followers
)
if slot == "dsn":
stops = [
i for i in (text.find(c) for c in "@ \"'<>,?&#") if i != -1
]
if not stops or text[min(stops)] != "@":
return False
return host.match(text, min(stops) + 1) is not None
return False
def lines_with_a_fragment_after_a_marker(out, text):
fragments = {
text[i : i + 4]
for i in range(len(text) - 3)
if any(c in distinct for c in text[i : i + 4])
}
for line in out.split("\n"):
found = marker.search(line)
if found and any(f in line[found.end() :] for f in fragments):
return True
return False
def logged(text):
record = {"message": text}
ls.redact_log_record(record)
return record["message"]
def db_reference(text):
text = ls.sanitize_error_message(text[:4096])
return text[:237] + "…" if len(text) > 240 else text
counts = {"checked": 0, "hidden": 0, "reference": 0, "shaped": 0}
violations = []
for seed in seeds:
rng = random.Random(seed)
planted = secret(rng)
slot = rng.choice(
["key", "key", "param", "json", "repr", "auth", "apikey", "dsn"]
)
opener = closer = ""
quote = rng.choice(["'", '"'])
if slot == "key":
opener, closer = rng.choice(wrappers)
value = (
quote
+ rng.choice(key_names)
+ quote
+ rng.choice([": ", ":"])
+ opener
+ planted
+ closer
)
elif slot == "param":
opener, closer = rng.choice(wrappers)
value = (
rng.choice([",", ";"])
+ rng.choice(param_names)
+ "="
+ opener
+ planted
+ closer
)
elif slot == "json":
value = json.dumps({rng.choice(key_names): planted, "n": 1})
elif slot == "repr":
value = repr({rng.choice(key_names): planted, "n": 1})
elif slot == "auth":
value = (
f"{quote}{rng.choice(['Authorization', 'proxy-authorization'])}"
f"{quote}: {rng.choice(['Basic', 'Bearer', 'Token', 'Digest'])} "
+ planted
)
elif slot == "apikey":
run = "".join(rng.choice(distinct + "/.+-") for _ in range(18))
planted = run + rng.choice(["", " "]) + planted
value = (
rng.choice(["Api-Key: ", "api_key: ", "x-apikey="]) + planted
)
else:
value = f"postgres://u:{planted}@db.example/x"
msg = rng.choice(prefixes) + value + rng.choice(suffixes)
is_shaped = shaped(slot, opener, closer, planted)
for shown, reference in (
(logged(msg), ls._redact_log_text(msg)),
(
exception_context(
{
"exception": SimpleNamespace(
type=ValueError, value=ValueError(msg)
)
}
),
db_reference(msg),
),
):
counts["checked"] += 1
counts["hidden"] += planted not in shown
if not lines_with_a_fragment_after_a_marker(shown, planted):
continue
if lines_with_a_fragment_after_a_marker(reference, planted):
counts["reference"] += 1
elif is_shaped:
counts["shaped"] += 1
else:
violations.append((seed, msg, shown))
return {**counts, "violations": violations}
class TestAddedShapesOnTheLogRecordPath:
"""``_ADDITIONAL_CREDENTIAL_PATTERNS`` on the log-record path.
``redact_log_record`` runs them as the last step over the message and
every ``extra`` string, after the passes ``_redact_log_text`` runs, and
the database log row runs them over its exception prefix
(``log_utils._exception_context``). No other function applies them, so
no redaction pass ever runs over their output.
"""
# One message per added shape, each with a value no other pass redacts.
SHAPES = {
"api-key-header": "upstream said Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET",
"slash-dsn": "connect failed postgresql://ldr:ab/cdSECRET@postgres/x",
"semicolon-param": "GET /v1;key=abcSECRET;v=2",
"quoted-key": "payload={'api-key': 'Kq7ZrXw2Lp9Vt4NsSECRET'}",
}
@pytest.mark.parametrize("msg", SHAPES.values(), ids=SHAPES.keys())
def test_each_shape_is_redacted_in_a_log_record(self, msg):
from local_deep_research.security.log_sanitizer import (
redact_log_extra,
)
assert "SECRET" not in _logged(msg)
assert "SECRET" not in redact_log_extra({"detail": msg})["detail"]
assert "SECRET" not in str(redact_log_extra({"detail": [{"x": msg}]}))
@pytest.mark.parametrize("msg", SHAPES.values(), ids=SHAPES.keys())
def test_only_the_log_record_path_applies_them(self, msg):
"""The scope of the added shapes, pinned: client and agent
responses, ``scrub_error`` text and the rendered exception value
(``redact_log_message``) are redacted exactly as before, without
them. Widening that scope means their output can reach a later
pass of these functions; update the docs and the changelog with
the analysis that makes that safe."""
from local_deep_research.security.log_sanitizer import (
_redact_log_text,
redact_log_message,
sanitize_error_message,
)
for fn in (
sanitize_error_message,
scrub_error,
sanitize_error_for_client,
sanitize_error_for_agent,
redact_log_message,
_redact_log_text,
):
assert "SECRET" in fn(msg), fn.__name__
@pytest.mark.parametrize(
("msg", "secret"),
[
("payload={'api-key': 'Kq7ZrXw2Lp9Vt4Ns'}", "Kq7ZrXw2Lp9Vt4Ns"),
('{"password": "pa ss word123"}', "word123"),
("{'client_secret': Kq7ZrXw2Lp9Vt4Ns}", "Kq7ZrXw2Lp9Vt4Ns"),
],
ids=["dict-repr", "json-with-space", "unquoted-value"],
)
def test_quoted_credential_key_value_is_redacted(self, msg, secret):
assert secret not in _logged(msg)
assert secret not in _logged(scrub_error(msg))
# Assembled so no token-shaped literal appears in the file (gitleaks).
_HEADER_VALUE = "Kq7ZrXw2" + "Lp9Vt4NsHeader"
@pytest.mark.parametrize(
"key",
[
"X-API-KEY",
"x-api-key",
"X-Api-Key",
"X-API-Key",
"x_api_key",
"openai_api_key",
"db_password",
"Ocp-Apim-Subscription-Key",
],
)
@pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])
def test_prefixed_quoted_credential_key_is_redacted(self, key, quote):
"""A credential name after ``word-``/``word_`` segments: the
request-header dicts of the Exa, Semantic Scholar, Serper, Serply
and TinyFish engines (``x-api-key``, ``X-API-KEY``, ``X-Api-Key``,
``X-API-Key``) and prefixed settings names."""
q = quote
msg = f"headers={{{q}{key}{q}: {q}{self._HEADER_VALUE}{q}}}"
out = _logged(msg)
assert self._HEADER_VALUE not in out, out
assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out
@pytest.mark.parametrize(
"msg",
[
'{"secret_name": "prod-db", "password_hint": "pet name"}',
"{'api_key_id': 'k-123', 'token_type': 'bearer'}",
"{'max_tokens': 512, 'x-request-id': 'abc'}",
],
ids=["name-not-last", "id-and-type", "non-credential"],
)
def test_quoted_key_must_end_with_a_credential_name(self, msg):
assert _logged(msg) == msg
def test_record_path_runs_redact_log_text(self, monkeypatch):
"""The record path calls ``_redact_log_text`` rather than a copy of
its passes, so a change to ``_redact_log_text`` reaches the loguru
patcher's message and ``extra`` strings too."""
from local_deep_research.security import log_sanitizer as ls
seen = []
def spy(value):
seen.append(value)
return value.replace("PLAINWORD", "SPIED")
monkeypatch.setattr(ls, "_redact_log_text", spy)
record = {
"message": "msg PLAINWORD",
"extra": {"detail": "extra PLAINWORD"},
}
ls.redact_log_record(record)
assert record["message"] == "msg SPIED"
assert record["extra"]["detail"] == "extra SPIED"
assert seen == ["msg PLAINWORD", "detail", "extra PLAINWORD"]
def test_record_path_bounds_the_text_before_redact_log_text(
self, monkeypatch
):
"""The added patterns and ``_redact_log_text`` both see only the
bounded head; the omission marker is appended after them."""
from local_deep_research.security import log_sanitizer as ls
seen = []
monkeypatch.setattr(
ls, "_redact_log_text", lambda v: seen.append(v) or v
)
long = "word " * (ls._LOG_REDACTION_MAX_CHARS // 5 + 100)
out = ls._redact_log_record_text(long)
assert len(seen[0]) <= ls._LOG_REDACTION_MAX_CHARS
assert out.startswith(seen[0])
assert out.endswith("characters omitted from log output]")
def test_quoted_credential_key_redaction_is_a_fixed_point(self):
# The unquoted-value alternative never starts with '[', so a value
# already redacted is not redacted again into ``[REDACTED]]``.
once = _logged('{"password": "x", "api_key": abc123}')
assert once == '{"password": "[REDACTED]", "api_key": [REDACTED]}'
assert _logged(once) == once
assert "]]" not in once
@pytest.mark.parametrize(
"key",
[
# Dotted settings keys, as the settings manager names them.
"llm.openai.api_key",
"llm.openai_endpoint.api_key",
"embeddings.openai.api_key",
"search.engine.web.serper.api_key",
"search.engine.web.google_pse.api_key",
"search.engine.web.semantic_scholar.api_key",
# Environment variables, five or more segments before the name.
"LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY",
"LDR_SEARCH_ENGINE_WEB_GOOGLE_PSE_API_KEY",
"LDR_LLM_OPENAI_ENDPOINT_API_KEY",
],
)
@pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])
def test_the_projects_own_credential_keys_are_redacted(self, key, quote):
"""The project's settings keys are dotted and its search-engine
environment variables have five or more segments before
``API_KEY``: as an ``extra`` key (``_is_sensitive_log_key``, last
dotted segment) they are redacted, and as a quoted key in message
text too."""
q = quote
msg = f"settings={{{q}{key}{q}: {q}{self._HEADER_VALUE}{q}}}"
out = _logged(msg)
assert self._HEADER_VALUE not in out, out
assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out
@pytest.mark.parametrize(
"msg",
[
'{"password": {"value": "s3cretNested"}}',
"{'password': {'value': 's3cretNested'}}",
'{"password": { "value": "s3cretNested"}}',
'{"password": ["s3cretNested"]}',
"{'password': ('s3cretNested',)}",
'{"llm.openai.api_key": {"value": "s3cretNested"}}',
'{"password": {}}',
',key={"a": "s3cretNested"}',
],
ids=[
"json",
"repr",
"json-spaced",
"list",
"tuple",
"settings-snapshot",
"empty",
"param",
],
)
def test_a_nested_container_value_is_not_corrupted(self, msg):
"""A nested container under a credential key is left whole: matched
as an unquoted run it would stop after its opener, so the marker
would eat the ``{`` and the nested value would still print."""
assert _logged(msg) == msg
@pytest.mark.parametrize(
("msg", "expected"),
[
(
"{b'password': b'Zq7bytesSECRET'}",
"{b'password': b'[REDACTED]'}",
),
('{"password": b"Zq7bytesSECRET"}', '{"password": b"[REDACTED]"}'),
("{'api_key': rb'Zq7bytesSECRET'}", "{'api_key': rb'[REDACTED]'}"),
("q=1,key=b'Zq7bytesSECRET'", "q=1,key=b'[REDACTED]'"),
],
ids=["bytes-keyed", "bytes-value", "raw-bytes", "param"],
)
def test_a_string_prefixed_value_is_redacted_whole(self, msg, expected):
"""``b'...'`` is redacted inside its quotes, prefix kept, rather
than as an unquoted ``b`` with the secret printed after it."""
assert _logged(msg) == expected
@pytest.mark.parametrize(
"msg",
[
"{'password': (b'hunter2 secret',)}",
"{'password': {b'value': b'hunter2 secret'}}",
"{'password': {u'hunter2 secret'}}",
"{'password': bytearray(b'hunter2 secret')}",
"{'password': SecretStr('hunter2 secret')}",
"{'access_token': UUID('hunter2 secret')}",
"{'password': OrderedDict([('a', 'hunter2 secret')])}",
"{'password': Foo(a, 'hunter2 secret')}",
"{'password': f(g(1),'hunter2 secret')}",
'{"password": (1, "hunter2 secret")}',
"{'password': {0: 'hunter2 secret'}}",
"{'password': '''hunter2 secret'''}",
'{"password": """hunter2 secret"""}',
"q=1,key=[b'hunter2 secret']",
"q=1,key=(b'hunter2 secret',)",
"q=1,key={b'hunter2 secret'}",
"q=1;key=[u'hunter2 secret']",
"q=1,key=ab'hunter2 secret'",
"q=1,key=ab\\'hunter2 secret'",
# What follows the value is not a structural follower: the
# allowlist refuses it (#6888 final gate).
"{'Authorization': Digest username=bob, response=Zq7digestRESP}",
"{'Authorization': Basic Zq7basic SECRET}",
"{'password': correct horse battery staple}",
"{'X-API-KEY': abcd1234 efgh5678}",
"{'password': hunter2&rest99}",
"{'password': hunter2#rest99}",
"{'api_key': Zq7live_abc&def&ghi}",
'{"password": "Xy7"!kP@9qZ"}',
"{'password': 'Pa'$$w0rd!'}",
"{'api_key': 'ab'/cdEFgh12'}",
"{'password': 'ab'.cd'}",
'{"password": "abc" "def"}',
'{"password": "abc"\\"def"}',
"{'api_key': ApiKey(key='Zq7SECRETVALUE')}",
"{'password': Secret(key=Zq7SECRET)}",
"{'token': x/key=Zq7SECRET}",
'"password": "abc,key=def ghi"',
"q;key=ab&TAIL",
"q;key=ab#TAIL",
"q,key=correct horse",
'q;key="ab" cd',
"Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET then more",
"Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET&rest",
"Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET!rest",
"'Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET'rest",
# A second '@', a symbol or a space after a DSN password's '@':
# the password may hold an unescaped '@'.
"postgres://u:pa/ss@word@host/db",
"postgres://u:pa/ss@!x/y@db/x",
"postgres://u:pa/ss@ word@db/x",
],
)
def test_a_value_whose_end_is_unclear_is_left_whole(self, msg):
"""A marker must never replace only the start of a value: the rest
would print behind it and the line would look redacted. A value is
redacted only when a structural follower for its syntax, a line
break or the end of the text comes after it; a value that runs into
a quote, a backslash, a symbol or a word after a space, leaves a
bracket it opened unclosed, or is a quoted string followed straight
by another quote is left exactly as the earlier passes left it."""
from local_deep_research.security.log_sanitizer import (
_redact_additional_shapes,
)
assert _logged(msg) == msg
assert _redact_additional_shapes(msg) == msg
@pytest.mark.parametrize(
("msg", "expected"),
[
("{'password': SecretStr(1234)}", "{'password': [REDACTED]}"),
("{'password': f(x)}", "{'password': [REDACTED]}"),
("GET /v1;key=abc(1)SECRET", "GET /v1;key=[REDACTED]"),
(
"{'password': 'hunter2 secret', 'n': 1}",
"{'password': '[REDACTED]', 'n': 1}",
),
# Each structural follower of a quoted value.
("{'password': 'Zq7 secret'}", "{'password': '[REDACTED]'}"),
(
"{'password': 'Zq7 secret' , 'n': 1}",
"{'password': '[REDACTED]' , 'n': 1}",
),
(
"{'password': 'Zq7 secret': rejected}",
"{'password': '[REDACTED]': rejected}",
),
(
"set 'password': 'Zq7 secret'; Path=/",
"set 'password': '[REDACTED]'; Path=/",
),
("f(a=1,key='Zq7 secret')", "f(a=1,key='[REDACTED]')"),
("[1,key='Zq7 secret']", "[1,key='[REDACTED]']"),
('x,key="Zq7 secret"&next=1', 'x,key="[REDACTED]"&next=1'),
('x;key="Zq7 secret"#frag', 'x;key="[REDACTED]"#frag'),
("{'password': 'Zq7 secret", "{'password': '[REDACTED]"),
# Each structural follower of an unquoted value.
(
"{'password': Zq7secret, 'n': 1}",
"{'password': [REDACTED], 'n': 1}",
),
("[{'password': Zq7secret]", "[{'password': [REDACTED]]"),
("{'password': Zq7secret }", "{'password': [REDACTED] }"),
("f(a=1,key=Zq7secret )", "f(a=1,key=[REDACTED] )"),
(
"x;key=Zq7secret;token=abc",
"x;key=[REDACTED];token=[REDACTED]",
),
# A scheme word and one credential token, taken whole.
(
"{'Authorization': Basic Zq7basicSECRET==}",
"{'Authorization': [REDACTED]}",
),
(
"{'Proxy-Authorization': Token Zq7tokenSECRET, 'n': 1}",
"{'Proxy-Authorization': [REDACTED], 'n': 1}",
),
# The header value's followers.
(
"['Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET', 'x']",
"['Api-Key: [REDACTED]', 'x']",
),
(
"Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET, retrying",
"Api-Key: [REDACTED], retrying",
),
# A host and its end after a DSN password's '@'.
(
"postgres://u:pa/ss@${DB_HOST}/x",
"postgres://[REDACTED]:[REDACTED]@${DB_HOST}/x",
),
],
)
def test_a_value_with_a_clear_end_is_still_redacted(self, msg, expected):
assert _logged(msg) == expected
@pytest.mark.parametrize(
"msg",
[
"{'password': 'Zq7 secret'\nnext line",
"x;key=Zq7secret\nnext",
"Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET\nnext",
],
ids=["quoted", "parameter", "header"],
)
def test_a_line_break_ends_a_value_where_one_is_kept(self, msg):
"""A line break ends a value. The record path strips it before the
added shapes run (so the next line is glued on and the allowlist
decides on what follows), but the database exception prefix keeps
it, and there the value before it is redacted."""
from local_deep_research.security.log_sanitizer import (
_redact_additional_shapes,
)
out = _redact_additional_shapes(msg)
assert "Zq7" not in out and "Kq7" not in out, out
assert out.endswith("\nnext line") or out.endswith("\nnext")
def test_no_marker_stands_before_an_unredacted_secret(self):
"""Seeded property over generated messages: a secret planted inside
a credential key's value (wrapped in a container, a call, a string
prefix, adjacent strings or nothing) is never printed straight
after a ``[REDACTED]`` marker, with at most separators and a string
prefix between them, on the log-record path or the database
exception prefix, unless the passes that run before the added
shapes already print it that way."""
import random
import re
from local_deep_research.security import log_sanitizer as ls
marker_then_secret = re.compile(
r"\[REDACTED\][\s,:;]*[bBrRuUfF]{0,2}(?:'''|\"\"\"|[\"'])Zq7S"
)
wrappers = [
("(b'", "',)"),
("{b'k': b'", "'}"),
("{u'", "'}"),
("bytearray(b'", "')"),
("SecretStr('", "')"),
("OrderedDict([('a', '", "')])"),
("[b'", "']"),
("(1, '", "')"),
("{0: '", "'}"),
("Foo(a, '", "')"),
("f(g(1),'", "')"),
("((b'", "',),)"),
("'''", "'''"),
('"""', '"""'),
("{'v': '", "'}"),
("('", "',)"),
("b'", "'"),
("Rb'", "'"),
("'", "'"),
('"', '"'),
("x'", "'"),
("ab\\'", "'"),
("[1, 2, '", "']"),
("", ""),
]
names = sorted(
set(ls.LOG_SENSITIVE_KEYS)
| {"api-key", "key", "X-API-KEY", "_api_key", "llm.x.api_key"}
)
noise = list("\"':=;,/@\\b()[]{} \n&#") + [
"https://",
"u:",
"[REDACTED]",
"'''",
"abc",
"x y",
"Bearer ",
"Api-Key: ",
]
def junk(rng):
out = ""
for _ in range(rng.randint(0, 8)):
if rng.random() < 0.3:
q = rng.choice(['"', "'"])
out += q + rng.choice(names) + q + rng.choice([": ", ":"])
elif rng.random() < 0.2:
out += rng.choice([",", ";"]) + rng.choice(names) + "="
else:
out += rng.choice(noise)
return out
def prefix_path(added, text):
# The database exception prefix (log_utils._exception_context).
text = added(ls.sanitize_error_message(text[:4096]))
if len(text) > 240:
text = added(text[:237]) + "…"
return text
checked = redacted = 0
for seed in range(1500):
rng = random.Random(seed)
secret = f"Zq7S{seed}X"
opener, closer = rng.choice(wrappers)
if rng.random() < 0.5:
q = rng.choice(['"', "'"])
key = q + rng.choice(names) + q + rng.choice([": ", ":"])
else:
key = rng.choice([",", ";"]) + rng.choice(names) + "="
msg = (
junk(rng)
+ rng.choice(["", "{", " "])
+ key
+ opener
+ secret
+ closer
+ rng.choice(["", "}", ", 'n': 1}"])
+ junk(rng)
)
for shown, reference in (
(_logged(msg), ls._redact_log_text(msg)),
(
prefix_path(ls._redact_additional_shapes, msg),
prefix_path(lambda t: t, msg),
),
):
checked += 1
redacted += secret not in shown
if marker_then_secret.search(reference):
continue
assert not marker_then_secret.search(shown), (
f"seed {seed}: {secret} printed behind a marker\n"
f" in: {msg!r}\n out: {shown!r}"
)
# The sample must exercise redaction, or the property is vacuous.
assert redacted > checked // 5, (redacted, checked)
def test_no_fragment_stands_behind_an_added_shape_marker(self):
"""Seeded property: a secret planted as a credential's value, with
quotes, spaces, ``& # ! $ / . + - @`` and several words in it, has
no 4-character fragment printed anywhere after a marker on its
line, on the log-record path or in the database exception prefix
(``_exception_context`` itself). See
``_secret_fragments_behind_a_marker`` for the slots it is planted
in and the two exemptions, each checked rather than assumed."""
from local_deep_research.security import log_sanitizer as ls
from local_deep_research.utilities.log_utils import _exception_context
found = _secret_fragments_behind_a_marker(
ls, _exception_context, range(5000)
)
assert found["violations"] == [], found["violations"][:5]
# The sample must redact the planted secret often and reach the
# exempt shapes rarely, or the property proves little.
assert found["hidden"] > found["checked"] // 4, found
assert found["shaped"] < found["checked"] // 50, found
@pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])
def test_every_log_sensitive_key_is_redacted_as_a_quoted_key(self, quote):
"""Quoted keys in message text use the names an ``extra`` key is
redacted under (``LOG_SENSITIVE_KEYS``) and the same suffix rule,
so the two cannot drift apart: each name, alone or after a prefix
that ends in ``_``, ``.`` or ``-``, is redacted as a quoted key,
as it is as an ``extra`` key."""
from local_deep_research.security.log_sanitizer import (
LOG_SENSITIVE_KEYS,
_is_sensitive_log_key,
redact_log_extra,
)
q = quote
value = self._HEADER_VALUE
for name in sorted(LOG_SENSITIVE_KEYS):
for key in (
name,
name.upper(),
f"_{name}",
f"x__{name}",
f"x..{name}",
f"db_{name}",
f"llm.openai.{name}",
f"X-{name.replace('_', '-')}",
):
if "-" not in key:
assert _is_sensitive_log_key(key), key
assert redact_log_extra({key: value})[key] == "[REDACTED]"
msg = f"payload={{{q}{key}{q}: {q}{value}{q}, {q}n{q}: 1}}"
out = _logged(msg)
assert value not in out, out
assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out, out
@pytest.mark.parametrize(
"msg",
[
"{'Authorization': 'Basic Zq7tokenSECRET'}",
"{'Authorization': 'Token Zq7tokenSECRET'}",
"{'X-Subscription-Token': 'Zq7tokenSECRET'}",
'{"api_token": "Zq7tokenSECRET", "csrf_token": "Zq7tokenSECRET"}',
"{'encryption_key': 'Zq7tokenSECRET'}",
"{'_password': 'Zq7tokenSECRET'}",
],
)
def test_header_and_private_credential_keys_are_redacted(self, msg):
out = _logged(msg)
assert "Zq7tokenSECRET" not in out, out
def test_bare_literal_values_of_quoted_keys_stay_legible(self):
# true/false/None/null is never a secret, and prefixed names make
# it common (``"requires_api_key": True``).
msg = (
"{'requires_api_key': True, 'has_secret': false, "
"'password': None, 'db_password': null}"
)
assert _logged(msg) == msg
assert _logged("{'password': Nonesuch}") == ("{'password': [REDACTED]}")
def test_a_key_header_glued_to_a_label_is_left_to_the_label(self):
"""The header value stops before the ``/client_secret=`` label, but
a ``/`` is not where a header value ends (the key's class holds
``/``, so ``KEY/client_secret=`` could be one base64 run), so the
key is left as the earlier passes left it, and the label's value is
redacted by the record's assignment pass, never by a marker that
covers only part of the run."""
from local_deep_research.security.log_sanitizer import _redact_log_text
msg = "api_key: Ab3Cd5Ef7Gh9Ij1Kl3Mn/client_secret=Zy8Xw6Vu4Ts2Rq;"
out = _logged(msg)
assert out == _redact_log_text(msg)
assert "Zy8Xw6Vu4Ts2Rq" not in out
assert "api_key: [REDACTED]" not in out
@pytest.mark.parametrize(
"dsn",
[
'"postgresql://u:pa/ss@db:5432/x"',
"'postgresql://u:pa/ss@db:5432/x'",
"<postgresql://u:pa/ss@db:5432/x>",
"dsns=postgresql://u:pa/ss@db1,postgresql://v:pb/tt@db2",
],
ids=["double-quoted", "single-quoted", "angle-bracketed", "listed"],
)
def test_delimited_slash_dsn_is_still_redacted(self, dsn):
out = _logged(dsn)
assert "pa/ss" not in out
assert "pb/tt" not in out
@pytest.mark.parametrize(
"msg",
[
'{"base":"https://api.example.com","path":"/users/[email protected]"}',
"http://searxng:8080,http://x/u/[email protected]",
],
ids=["json-path-with-email", "list-path-with-email"],
)
def test_host_is_not_read_as_userinfo_across_a_boundary(self, msg):
assert _logged(msg) == msg
def test_slash_dsn_does_not_redact_through_a_path_label(self):
# A "password" run holding ``/password=`` or ``=api_key=`` is a path
# running into that label's value; redacting it up to the '@' inside
# the value would remove the label and print the tail.
for msg, tail in (
(
"http://localhost:${PORT}/cb/password=SFI_V%hoB@2DOuTAIL;",
"2DOuTAIL",
),
(
"http://svc:http-metrics/x=api_key=Sg7z@55GR9obTAIL ",
"55GR9obTAIL",
),
):
out = _logged(msg)
assert tail not in out, out
@pytest.mark.parametrize(
"msg",
[
'params q=x,key=abc123,password="pass phrase SECRET"',
"retry cfg;key=abc123;password = hunter2SECRET",
"cfg;key=abc,token = hunter2SECRET",
'http://host:8080,key=abc,password="pass phrase SECRET"',
],
ids=["comma-quoted", "semicolon-spaced", "key-then-token", "url"],
)
def test_a_parameter_does_not_swallow_the_next_label(self, msg):
assert "SECRET" not in _logged(msg)
@pytest.mark.parametrize(
"msg",
[
'{"password": "a\\"b\\\\c\\/dSECRET"}',
"{'api_key': 'a\\'b\\\\cSECRET'}",
',token="a\\"bSECRET"',
],
ids=["json-escapes", "repr-escapes", "param-escapes"],
)
def test_a_quoted_value_with_escapes_is_redacted_whole(self, msg):
# The label check after a backslash must not stop an ordinary
# escape: a value with escaped quotes and backslashes and no label
# is still redacted to its closing quote.
out = _logged(msg)
assert "SECRET" not in out
assert "[REDACTED]" in out
@pytest.mark.parametrize(
"msg",
[
'{"api_key": "abc\\,password = "hunter2SECRET"}',
"{'secret': 'abc\\;token = 'hunter2SECRET'}",
"x;key='abc\\/client_secret = 'hunter2SECRET'",
'payload {"client_secret": "abc\\ password="hunter2 SECRET"}',
'{"api_key": "abc\\ token="SECRET tail"}',
'{"secret":"v\\/password="SECRET x"}',
'"password": "x\\"api_secret=SECRET"',
'{"api_key": "abc\\\\\\#password = "hunter2SECRET"}',
'password="abc;token=xyz"foo password="SECRET VALUE"',
'failed: password="x;pwd=y" retry api_key=" SECRET-1234"',
'error: password="p,secret=a"b" client_secret="two SECRET"',
"password='pw \"api_key\": \"it's\" client_secret='pw2 SECRET'",
],
)
def test_labels_inside_values_are_still_redacted(self, msg):
# A label after an escaped separator, or a parameter or quoted key
# inside a quoted value: the record's assignment passes redact the
# value after that label, and the added shapes, running after
# them, only replace more of what those passes left.
for out in (
_logged(msg),
_logged(scrub_error(msg)),
_logged(sanitize_error_for_client(msg)),
_logged(sanitize_error_for_agent(msg)),
):
assert "SECRET" not in out, out
def test_seeded_differential_against_the_record_passes(self):
"""The record path hides whatever ``_redact_log_text`` (its passes
without the added shapes) hides, on a seeded sample of generated
messages, logged as they are or after each public helper.
Each variable part of a message carries unique markers; a marker
the reference hides must be hidden on the record path too. The
added shapes must also fire on part of the sample, or the
comparison proves nothing.
"""
import random
from local_deep_research.security import log_sanitizer as ls
def logged_extra(text):
return ls.redact_log_extra({"detail": text})["detail"]
def make_paths(secrets):
return [
lambda m: m,
ls.sanitize_error_message,
lambda m: ls.scrub_error(m, *secrets),
lambda m: ls.sanitize_error_for_client(m, 10_000),
ls.sanitize_error_for_agent,
ls.strip_control_chars,
]
names = sorted(
set(ls.LOG_SENSITIVE_KEYS)
| {"api-key", "key", "token", "secret", "pwd", "q", "url"}
)
punct = list("@/:?&;,#=\"'+.-_~%[]{}|<>\\ ")
seps = [" ", ",", ";", "&", "?", "|", "\n", "", '","', "/", "#", ":"]
stripped = ["\n", "\t", "\x1c", "\u200b", "\ufeff"]
fired = 0
for seed in range(600):
rng = random.Random(seed)
markers = []
def value(rng=rng, markers=markers):
out = ""
for _ in range(rng.randint(1, 3)):
mark = "Q%c%c%d" % (
rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ"),
rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ"),
rng.randrange(10),
)
markers.append(mark)
out += mark + "".join(
rng.choice(punct + ["a", "b", "7"])
for _ in range(rng.randint(0, 3))
)
return out
segments = []
for _ in range(rng.randint(1, 4)):
kind = rng.randrange(7)
quote = rng.choice(["", '"', "'"])
if kind == 0:
segments.append(
rng.choice(names)
+ rng.choice(["=", " = ", ": "])
+ quote
+ value()
+ quote
)
elif kind == 1:
segments.append(
rng.choice(["x-api-key: ", "Api-Key: ", "api_key: "])
+ value()
+ "abcdefghijklmnop"
)
elif kind == 2:
user = value() + ":" + value() + "/" + value() + "@"
segments.append(
rng.choice(["https", "postgresql+asyncpg", "redis"])
+ "://"
+ (user if rng.random() < 0.7 else "")
+ rng.choice(["db", "localhost", "api.example.com"])
+ rng.choice(["", ":8080", ":${PORT}"])
+ rng.choice(["", "/x", "/a/b@c"])
+ rng.choice(["", "?", ";", ","])
+ rng.choice(names)
+ "="
+ value()
)
elif kind == 3:
q = rng.choice(['"', "'"])
segments.append(
"{"
+ q
+ rng.choice(names)
+ q
+ ": "
+ quote
+ value()
+ quote
+ "}"
)
elif kind == 4:
segments.append(
rng.choice([",", ";"])
+ rng.choice(names)
+ "="
+ quote
+ value()
+ rng.choice(stripped + [""])
+ value()
+ quote
)
elif kind == 5:
name = rng.choice(names)
cut = rng.randint(0, len(name))
segments.append(
rng.choice(
["Api-Key: abcdefghijklmnopqrst/", ",key=abc/", ""]
)
+ name[:cut]
+ rng.choice(stripped)
+ name[cut:]
+ rng.choice(["=", "= ", '="'])
+ value()
)
else:
q = rng.choice(['"', "'"])
inner = rng.choice(
[
rng.choice([";", ","]) + rng.choice(names) + "=",
" " + q + rng.choice(names) + q + ": ",
]
)
segments.append(
rng.choice(names)
+ rng.choice(["=", " = "])
+ q
+ value()
+ inner
+ value()
+ q
)
msg = segments[0]
for segment in segments[1:]:
msg += rng.choice(seps) + segment
secrets = [value() for _ in range(rng.randrange(2))]
for path in make_paths(secrets):
text = path(msg)
hidden = ls._redact_log_text(text)
for shown in (_logged(text), logged_extra(text)):
if shown != hidden:
fired += 1
for mark in markers:
if msg.count(mark) == 1 and mark not in hidden:
assert mark not in shown, (
f"seed {seed}: the record path printed "
f"{mark} that its passes hid\n"
f" in: {text!r}\n ref: {hidden!r}\n"
f" out: {shown!r}"
)
assert fired > 100, fired
# Corpus for TestScrubIsIdempotent: URLs, autolinks, code spans, every
# marker a pass writes, credential shapes and the stop/control characters,
# alone and in every ordered pair.
# Built by concatenation so no literal here is credential-shaped.
_IDEM_SK_KEY = "sk-" + "a" * 24
_IDEM_GOOGLE_KEY = "AIza" + "B" * 30
_IDEM_SECRET = "KnownLiteralSecret123"
_IDEM_PIECES = [
"https://h/p?q=1",
"<https://h/p?q=1>",
"`https://h/p?q=1`",
"(https://h/p?q=1)",
"[https://h/p?q=1]",
'"https://h/p?q=1"',
"https://h/p?q=1#frag",
"https://h/p?<redacted>",
"?<redacted>",
"<redacted>",
"[REDACTED]",
"[REDACTED_KEY]",
"***REDACTED***",
"x://a?b>c",
"https://u:pw@h/p",
# A URL with no path: redacting a query value removes the "/" that kept
# "h?...&z:pw@q" from reading as URL userinfo.
"https://h?token=a/b&z:pw@q",
"https://example.com?next=/x'",
"z:pw@q",
'token="t";password="a b"',
"?api_key=sekrit&q=2",
"&token=t",
"&token=t?\n",
"api_key=abc",
"token='x y'",
'password="a\\"b"',
'secret="unfinished',
"password=hunter2",
"Bearer abcdefghijkl",
_IDEM_SK_KEY,
_IDEM_GOOGLE_KEY,
_IDEM_SECRET,
" ",
"?",
">",
"<",
"`",
")",
"'",
'"',
"\\",
"=",
"\n",
"\x1c",
"\u200b",
]
_IDEM_CORPUS = _IDEM_PIECES + [
a + b for a in _IDEM_PIECES for b in _IDEM_PIECES
]
class TestScrubIsIdempotent:
"""Scrubbing already-scrubbed text must change nothing.
Text is scrubbed twice in practice: Google PSE's ``_validate_connection``
scrubs an error and re-raises ``type(e)(safe_msg)``, and the engine
factory runs ``scrub_error`` over that exception again; the LLM
rate-limit wrapper re-raises its scrubbed text the same way, and the
log patcher runs ``redact_log_message`` over every record, scrubbed or
not. A pass that is not a fixed point corrupts its own output on the
second run (``?<redacted>`` grew one ``>`` per pass, breaking the
autolink and code-span wrappers #6581 set out to keep).
"""
_SK_KEY = _IDEM_SK_KEY
_GOOGLE_KEY = _IDEM_GOOGLE_KEY
_SECRET = _IDEM_SECRET
CORPUS = _IDEM_CORPUS
@staticmethod
def _scrubbers():
from local_deep_research.security.log_sanitizer import (
_redact_log_text,
redact_log_message,
redact_sensitive_assignments,
sanitize_error_message,
)
secret = TestScrubIsIdempotent._SECRET
return {
"scrub_error": scrub_error,
"scrub_error_with_secret": lambda s: scrub_error(s, secret),
"sanitize_error_message": sanitize_error_message,
"redact_log_message": redact_log_message,
"_redact_log_text": _redact_log_text,
"redact_sensitive_assignments": redact_sensitive_assignments,
# Above the length cap truncation is not a fixed point (a cut
# marker can be completed by the next pass); every corpus
# entry fits well under these caps.
"sanitize_error_for_client": lambda s: sanitize_error_for_client(
s, max_length=10_000
),
"sanitize_error_for_agent": sanitize_error_for_agent,
}
@pytest.mark.parametrize(
"name",
[
"scrub_error",
"scrub_error_with_secret",
"sanitize_error_message",
"redact_log_message",
"_redact_log_text",
"redact_sensitive_assignments",
"sanitize_error_for_client",
"sanitize_error_for_agent",
],
)
def test_second_pass_is_a_no_op(self, name):
scrub = self._scrubbers()[name]
failures = []
for text in self.CORPUS:
once = scrub(text)
twice = scrub(once)
if twice != once:
failures.append((text, once, twice))
assert not failures, (
f"{name} is not idempotent on {len(failures)} inputs, "
f"first: {failures[:3]!r}"
)
def test_pse_rescrubbed_error_keeps_a_single_marker(self):
# The live double-scrub path: scrub, re-raise the scrubbed text,
# scrub the re-raised exception again.
err = Exception(
"403 Client Error: Forbidden for url: "
"https://www.googleapis.com/customsearch/v1?cx=1&q=private+query"
)
once = scrub_error(err)
twice = scrub_error(type(err)(once))
assert (
twice
== once
== (
"403 Client Error: Forbidden for url: "
"https://www.googleapis.com/customsearch/v1?<redacted>"
)
)
@pytest.mark.parametrize(
"text, expected",
[
("see <https://h/p?q=1> end", "see <https://h/p?<redacted>> end"),
("run `https://h/p?q=1` now", "run `https://h/p?<redacted>` now"),
],
)
def test_wrappers_survive_a_second_scrub(self, text, expected):
assert scrub_error(scrub_error(text)) == expected
def test_quoted_assignment_glued_suffix_is_redacted_in_one_call(self):
# A closed quote followed by non-whitespace: one pass leaves
# "[REDACTED](tail", which the next pass reads as an unquoted value.
# The function repeats its pass until nothing changes, so a single
# call already returns the settled form.
from local_deep_research.security.log_sanitizer import (
redact_sensitive_assignments,
)
assert (
redact_sensitive_assignments("token='x y'(tail) next")
== "token=[REDACTED] next"
)
assert (
redact_sensitive_assignments('password="abc"def count=3')
== "password=[REDACTED] count=3"
)
def test_client_scrub_catches_a_token_joined_by_a_control_char(self):
# Stripping the newline joins "&token=t?" and the Google key; the
# second credential pass then redacts the joined value, so a
# second call has nothing left to change.
text = "&token=t?\n" + self._GOOGLE_KEY
assert sanitize_error_for_client(text) == "&token=[REDACTED]"
def test_literal_secret_glued_to_a_shaped_key_hides_neither(self):
# "<secret>sk-..." has no word boundary before "sk-", so the shape
# pass skips the key; once the literal pass replaces the secret,
# the second shape pass sees the boundary and redacts the key.
result = scrub_error(
f"auth {self._SECRET}{self._SK_KEY} failed", self._SECRET
)
assert self._SK_KEY not in result
assert result == "auth ***REDACTED***[REDACTED_KEY] failed"
@pytest.mark.parametrize("name", ["redact_log_message", "_redact_log_text"])
@pytest.mark.parametrize(
"text",
[
# Over the bound before redaction.
"token=a " * 5000,
# Under the bound before redaction (32,100 chars), over it after.
"token=a " * 4000 + "x" * 100,
],
)
def test_above_the_log_bound_a_second_call_only_drops_text(
self, name, text
):
# The docstrings promise a fixed point only up to
# _LOG_REDACTION_MAX_CHARS. Above it a second call cuts again, so
# the result changes, but only by dropping more text: what is left
# before the new omission marker is a prefix of the first result.
from local_deep_research.security import log_sanitizer
scrub = getattr(log_sanitizer, name)
once = scrub(text)
assert len(once) > log_sanitizer._LOG_REDACTION_MAX_CHARS
twice = scrub(once)
assert twice != once
marker = log_sanitizer._LOG_OMISSION_MARKER_RE.search(twice)
assert marker is not None
assert once.startswith(twice[: marker.start()])
assert "token=a " not in twice
@pytest.mark.timeout(15)
def test_dense_marker_run_is_linear(self):
# A whitespace-free run of already-scrubbed URLs: the first URL's
# query runs to the end of the run (no stop character in it), so
# the whole run collapses into one marker, and the confirming
# round is on that short result. 20k repeats (~440 KB) keeps the
# scrub well inside the budget on a slow CI core.
run = "https://h/p?<redacted>" * 20_000
t0 = time.process_time()
result = scrub_error(run)
elapsed = time.process_time() - t0
assert result == "https://h/p?<redacted>"
assert elapsed < 2.0, f"took {elapsed:.2f}s cpu on a dense marker run"
class TestScrubNeverRedactsLessThanOnePass:
"""Each public scrub function repeats its passes until nothing changes.
The first round starts with exactly the single pass these functions used
to make, and everything after it only replaces more text, so nothing one
pass redacted can reappear. These are the inputs where an earlier
attempt at idempotence redacted less than one pass did.
"""
@staticmethod
def _log_scrubbers():
from local_deep_research.security.log_sanitizer import (
_redact_log_text,
redact_log_message,
redact_sensitive_assignments,
)
return [
redact_log_message,
_redact_log_text,
redact_sensitive_assignments,
]
@pytest.mark.parametrize(
"text, secret_words",
[
(
'token="t";password="correct horse battery staple"',
["correct", "horse", "battery", "staple"],
),
(
'conn(user="bob",password="a",api_key="long pass phrase here")',
["long", "pass phrase", "here"],
),
("token='x y'token='p q'", ["x", "y'", "p", "q'"]),
('token="t";password= "correct horse"', ["correct", "horse"]),
],
)
def test_glued_assignment_after_a_quoted_value_is_redacted(
self, text, secret_words
):
for scrub in self._log_scrubbers():
once = scrub(text)
leaked = [
w for w in secret_words if w in once.replace("[REDACTED]", "")
]
assert not leaked, f"{scrub.__name__}: {once!r} leaks {leaked}"
assert scrub(once) == once
@pytest.mark.parametrize(
"text, expected",
[
(
"GET https://h/search?q=a>b&term=private",
"GET https://h/search?<redacted>",
),
(
"GET https://h/search?q=a`b&term=private",
"GET https://h/search?<redacted>",
),
(
"403 for url: https://h/search?<redacted>&q=private+query",
"403 for url: https://h/search?<redacted>",
),
("https://h/p?<redacted>?q=leak", "https://h/p?<redacted>"),
("x://a?b>c", "x://a?<redacted>"),
# A wrapper is only given back when it ends the matched query
# and the URL opened right after "<" or a backtick.
("<https://h/p?q=1>tail", "<https://h/p?<redacted>"),
("`https://h/p?q=1`tail", "`https://h/p?<redacted>"),
("see https://h/p?q=1> end", "see https://h/p?<redacted> end"),
("<https://h/p?q=1", "<https://h/p?<redacted>"),
("<https://h/p?<redacted>", "<https://h/p?<redacted>"),
],
)
def test_raw_wrapper_char_or_marker_does_not_end_the_query_redaction(
self, text, expected
):
once = scrub_error(text)
assert once == expected
assert scrub_error(once) == once
def test_pathless_url_query_redaction_then_userinfo_settles_in_one_call(
self,
):
from local_deep_research.security.log_sanitizer import (
_redact_log_text,
redact_log_message,
sanitize_error_message,
)
settled = "https://[REDACTED]:[REDACTED]@q"
text = "https://h?token=a/b&z:pw@q"
for scrub in (
sanitize_error_message,
redact_log_message,
_redact_log_text,
sanitize_error_for_client,
sanitize_error_for_agent,
):
assert scrub(text) == settled, scrub.__name__
assert (
sanitize_error_for_client("https://h?to\nken=a/b&z:pw@q") == settled
)
# scrub_error's query pass removes the "/" itself.
for text, expected in (
(
"https://example.com?next=/x'user:hunter2@db",
"https://[REDACTED]:[REDACTED]@db",
),
(
"https://host?a/b)x:secret@evil",
"https://[REDACTED]:[REDACTED]@evil",
),
):
once = scrub_error(text)
assert once == expected
assert scrub_error(once) == once
@pytest.mark.parametrize("control", ["\n", "\r", "\x1c", "\u2028", "\x85"])
def test_control_character_cannot_split_a_url_query_credential(
self, control
):
text = f"https://h?to{control}ken=a/b&z:pw@q"
once = scrub_error(text)
# The line break is written back after the marker, not deleted.
assert once == f"https://h?<redacted>{control}"
assert scrub_error(once) == once
def test_lines_and_tabs_are_never_joined(self):
text = "Traceback:\n File x\nValueError: bad\tthing\r\nnext\u2028end"
assert scrub_error(text) == text
@pytest.mark.parametrize("control", ["\n", "\t", "\u2028", "\x00"])
def test_known_secret_split_by_a_control_character_is_redacted(
self, control
):
once = scrub_error(
f"key: hunter2{control}secretXY tail", "hunter2secretXY"
)
kept = control if control.isspace() else ""
assert once == f"key: ***REDACTED***{kept} tail"
assert scrub_error(once, "hunter2secretXY") == once
class TestScrubNeverLogsWhatMainRedacted:
"""Inputs where an earlier version of the #6581 change logged a secret
that the code before it redacted, through the log patcher alone or
through ``scrub_error`` followed by the log patcher."""
@staticmethod
def _patcher(text):
from local_deep_research.security.log_sanitizer import (
_redact_log_text,
)
return _redact_log_text(text)
@pytest.mark.parametrize(
"text",
[
'password=a,token="b and api_key="correct horse battery staple"',
"auth failed: user=bob;password=pw;"
'secret="x and password="correct horse battery staple"',
"password=a,token = \"b and api_key='correct horse battery staple'",
],
)
def test_stop_never_pairs_a_quote_with_the_next_credential(self, text):
"""A quoted value still open at whitespace is not a stop: its match
would close on the next credential's opening quote and leave the
rest of that credential's value visible."""
from local_deep_research.security.log_sanitizer import (
redact_log_message,
redact_sensitive_assignments,
)
for once in (
redact_sensitive_assignments(text),
redact_log_message(text),
self._patcher(scrub_error(text)),
):
for word in ("horse", "battery", "staple"):
assert word not in once, once
@pytest.mark.parametrize(
"text, secret",
[
# The stripped view joins the split name; the patcher must not
# take the next line's half name as its value.
(
"Error\nauthorizatio\u200bn=hunt3rq9zxw'api_\nkey=KEY12345678",
"KEY12345678",
),
(
"Error\nauthorizatio\u200bn=hunt3rq9zxw'pass\nword=KEY12345678",
"KEY12345678",
),
# Extending a span over a split credential took the next
# assignment's name; it now takes its value too.
(
'passwd=?clients\necret="&;accesstoken= SECRETVAL9=',
"SECRETVAL9",
),
],
)
def test_glued_view_leaves_no_value_without_its_name(self, text, secret):
once = scrub_error(text)
assert secret not in self._patcher(once)
assert scrub_error(once) == once
def test_glued_view_is_skipped_above_its_bound(self):
from local_deep_research.security.log_sanitizer import (
_GLUED_VIEW_MAX_CHARS,
_scrub_across_controls,
)
split = "https://h/p?to\nken=abc "
short = split + "x" * (_GLUED_VIEW_MAX_CHARS - len(split))
assert _scrub_across_controls(short, []) != short
long = short + "x"
assert _scrub_across_controls(long, []) == long
def test_adversarial_line_breaks_cost_stays_bounded(self):
run = "https://h/p?q=1" + "\nBeare\rr x" * 25_000
t0 = time.process_time()
scrub_error(run)
elapsed = time.process_time() - t0
assert elapsed < 3.0, f"took {elapsed:.2f}s cpu on 250 KB"
def test_glued_view_reads_the_patchers_pass_list(self, monkeypatch):
"""A pass added to the patcher is one the stripped view fits its
redactions around, without a second list to update."""
import re
from local_deep_research.security import log_sanitizer
name = r"(OPENAI_API_KEY)(\s*=\s*)(?:'[^']*'|\S+)"
monkeypatch.setattr(
log_sanitizer,
"_LOG_PATCHER_BARE_PASSES",
(
*log_sanitizer._LOG_PATCHER_BARE_PASSES,
log_sanitizer._BarePass(
re.compile(r"(?<![\w.?&-])" + name),
r"\1\2[REDACTED]",
1,
2,
re.compile(name),
),
),
)
text = "GET https://h/p?q=1\nOPENAI_API_KEY='correct horse'"
once = scrub_error(text)
assert (
once == "GET https://h/p?<redacted>\nOPENAI_API_KEY='correct horse'"
)
logged = log_sanitizer._redact_log_text(once)
assert "correct" not in logged and "horse" not in logged
@pytest.mark.parametrize(
"name", ["api_key", "OPENAI_API_KEY", "db_password", "llm.openai.api_key"]
)
@pytest.mark.parametrize("separator", ["=", "= ", " = "])
@pytest.mark.parametrize(
"value",
["PlainSecret739", '"PlainSecret739 extra"', "'PlainSecret739 extra'"],
)
def test_query_scrub_covers_glued_assignment_values(name, separator, value):
"""URL-query scrubbing must cover a name's whole quoted/spaced value."""
message = f"GET https://h/p?q=1\u200b{name}{separator}{value}"
scrubbed = scrub_error(message)
assert scrubbed == "GET https://h/p?<redacted>"
assert scrub_error(scrubbed) == scrubbed