Skip to content

fix(guardrails): mask credentials embedded in guardrail_response before persist (LIT-4314) - #32687

Merged
yucheng-berri merged 1 commit into
litellm_internal_stagingfrom
litellm_lit4314b_guardrail_credentials_mask
Jul 10, 2026
Merged

yucheng-berri merged 1 commit into
litellm_internal_stagingfrom
litellm_lit4314b_guardrail_credentials_mask

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Contributes to LIT-4314; scope covers the credential-mask piece of the ticket. The sibling store_prompts_in_spend_logs gating scope is being addressed in a separate PR.

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Reproduction and verification on a live proxy against Postgres, real OpenAI API calls, real Langsmith key from the env

Config, guardrail, and DB per the shared brief (/tmp/lit4314_config.yaml, /tmp/lit4314_guardrail.py, postgresql://yucheng@127.0.0.1:5432/litellm_lit4314b); proxy on port 4001 to avoid collision with a sibling repro on 4000

Before (unfixed HEAD 1fa200123f)

Launch:

export PYTHONPATH="$(pwd):/tmp"
set -a; source .env; set +a
uv run --no-sync python litellm/proxy/proxy_cli.py \
  --config /tmp/lit4314_config.yaml --port 4001 \
  --detailed_debug --use_v2_migration_resolver

Provision + hit:

curl -sS -X POST http://localhost:4001/team/new \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d "{\"team_alias\":\"lit4314b-team\",\"metadata\":{\"callback_vars\":{\"langsmith_api_key\":\"$LANGSMITH_API_KEY\",\"langsmith_project\":\"lit4314-repro\"},\"success_callback\":[\"langsmith\"]}}"

curl -sS -X POST http://localhost:4001/key/generate \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d "{\"team_id\":\"<team-id>\",\"models\":[\"gpt-4o-mini\"]}"

curl -sS http://localhost:4001/v1/chat/completions \
  -H "Authorization: Bearer <team-key>" -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hi in 3 words"}]}'

Plaintext count in LiteLLM_SpendLogs.metadata:

psql -U yucheng -h 127.0.0.1 -d litellm_lit4314b -t -A -c \
  "SELECT metadata FROM \"LiteLLM_SpendLogs\" ORDER BY \"startTime\" DESC LIMIT 1;" \
  | grep -oE 'lsv2_pt_[a-f0-9]+_[a-f0-9]+' | wc -l

Output: 5

That is the same team callback_vars Langsmith key showing up plaintext five times inside one row's guardrail_information[i].guardrail_response (via user_api_key_auth, user_api_key_metadata, user_api_key_team_metadata, user_api_key_auth_metadata, and the direct metadata.callback_vars echo the leaky guardrail hook makes when it snapshots data["metadata"])

After (fixed HEAD 2b6e25d896)

Same launch, same curl, same psql, on the fixed binary

Plaintext count:

psql -U yucheng -h 127.0.0.1 -d litellm_lit4314b -t -A -c \
  "SELECT metadata FROM \"LiteLLM_SpendLogs\" ORDER BY \"startTime\" DESC LIMIT 1;" \
  | grep -oE 'lsv2_pt_[a-f0-9]+_[a-f0-9]+' | wc -l

Output: 0

Masked count:

... | grep -oE 'lsv2\*+' | wc -l

Output: 5

The five plaintext occurrences got replaced by five masked ones. The five reveal-prefix/reveal-suffix strings look like lsv2*******************************************4124

Dashboard fields on the same record survive unchanged: guardrail_name=lit4314-leaky-guard, guardrail_status=success, duration=3e-06, guardrail_mode=pre_call, guardrail_provider=lit4314-repro

Type

🐛 Bug Fix

Changes

add_standard_logging_guardrail_information_to_request_data (litellm/integrations/custom_guardrail.py) is the single seam every production guardrail hook routes through when building StandardLoggingGuardrailInformation. That record is what every downstream sink reads: SpendLogs, OTel v2 (emit_guardrail_span at line 802), Langfuse (guardrail_entry["guardrail_response"] at litellm/integrations/langfuse/langfuse.py:967), and any user-configured custom logger

Two narrow scrubs already ran inside this function; neither touched nested credential-shaped keys. secret_fields was popped at the top level, and redact_nested_match_and_regex_keys only rewrites keys literally named match or regex. When a guardrail hook echoed data["metadata"] back as part of its guardrail_response, the four user_api_key_* aliases plus the raw callback_vars copy all sailed through and got persisted plaintext

The fix runs SensitiveDataMasker's default masker over the response after those two scrubs. It segment-matches key names like api_key, access_token, secret, authorization, credentials, and reveals only a four-char prefix and four-char suffix on long values (short values get fully starred). Non-sensitive keys (model, messages, metadata_snapshot shape, dashboard fields) pass through unchanged; masking is key-name-scoped, not value-scoped. Because the masker is applied at the construction site, every sink downstream sees the masked record without their needing individual patches

Regression tests in tests/test_litellm/integrations/test_custom_guardrail.py::TestGuardrailResponseCredentialMasking cover: a Langsmith-shaped callback_vars.langsmith_api_key gets masked and does not appear plaintext anywhere in the serialized record; a nested user_api_key_auth.metadata.callback_vars.langsmith_api_key alongside token/api_key all get masked; and the existing secret_fields pop and match/regex redaction still run. Removing the new masker line makes the first regression test fail on the exact assertion that the masked value equals the plaintext, so it kills a real mutation

Follow-ups the ticket calls out that are intentionally out of scope for this PR: sibling PR for store_prompts_in_spend_logs gating of guardrail_response; ticket to split callback_vars transport off UserAPIKeyAuth.team_metadata so it never lands in data["metadata"] in the first place; ticket to mask optional_params/additional_params/litellm_params.api_key across the wider observability path and to redact by default across sinks


Note

Medium Risk
Changes the single guardrail logging seam used by every sink; incorrect masking could hide debug data or miss secrets, but scope is narrow and heavily tested.

Overview
Fixes plaintext API keys and tokens ending up in SpendLogs, OTel, Langfuse, and other sinks when guardrail hooks echo request metadata inside guardrail_response.

add_standard_logging_guardrail_information_to_request_data now runs mask_credentials_in_payload after existing secret_fields removal and match/regex redaction, so masking happens once at the shared construction seam for all guardrails.

mask_credentials_in_payload (in sensitive_data_masker.py) walks nested dicts/lists/tuples and Pydantic models, masks non-empty string values under sensitive key names (shared SensitiveDataMasker patterns plus gcs_path_service_account), and leaves scalars/None/structure intact—unlike full SensitiveDataMasker.mask, which can distort logging payloads. _walk_payload is depth-bounded and allowlisted in the recursive-function CI check.

Regression tests cover nested callback_vars, user_api_key_auth, prefix/suffix masking, and that prior scrubs still apply.

Reviewed by Cursor Bugbot for commit a40fd6bf306fa725e248567d3420b404fb1062e4. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds credential masking at the single logging construction seam in add_standard_logging_guardrail_information_to_request_data, ensuring all downstream sinks (SpendLogs, OTel, Langfuse, custom loggers) receive masked values without needing individual patches.

  • sensitive_data_masker.py: Introduces mask_credentials_in_payload and _walk_payload, a depth-bounded walker that rebuilds dicts/lists preserving JSON-safe types (None, int, float, bool pass through unchanged), unwraps Pydantic models via model_dump(), and masks only string leaves under sensitive-named keys. Adds EXTRA_SENSITIVE_KEY_NAMES for keys like gcs_path_service_account that are not caught by segment-based detection.
  • custom_guardrail.py: Calls mask_credentials_in_payload after the existing secret_fields pop and match/regex redaction, completing the three-layer scrub before the StandardLoggingGuardrailInformation record is constructed.
  • Tests: Six integration-level regression tests and four unit tests cover masked credentials, scalar passthrough, Pydantic model unwrapping, and confirm the earlier scrubs still run independently.

Confidence Score: 5/5

Safe to merge — the change is narrow and well-tested, touching only the guardrail logging construction path with no effect on request routing, auth, or other logging pipelines.

The masking logic is correctly positioned after all existing scrubs, the depth limit is enforced and the function is properly added to the recursion-detector allowlist, Pydantic models are handled via model_dump() before the key-name walk, and JSON-safe types (None, int, float, bool) pass through unchanged so no log record distortion is introduced. No existing tests were weakened; the six new integration tests and four unit tests form a genuine mutation-killing regression suite.

No files require special attention.

Important Files Changed

Filename Overview
litellm/integrations/custom_guardrail.py Adds mask_credentials_in_payload call after the existing secret_fields pop and redact_nested_match_and_regex_keys scrubs; correctly positioned as the single masking seam before StandardLoggingGuardrailInformation is built
litellm/litellm_core_utils/sensitive_data_masker.py Adds mask_credentials_in_payload, _walk_payload, and _key_is_sensitive helpers plus EXTRA_SENSITIVE_KEY_NAMES; correctly preserves JSON-safe types (None, int, float, bool) while masking string leaves under sensitive-named keys, and correctly unwraps Pydantic models via model_dump()
tests/code_coverage_tests/recursive_detector.py Correctly adds _walk_payload to the recursion-detector ignore list, consistent with the existing entries for depth-bounded recursive helpers
tests/test_litellm/integrations/test_custom_guardrail.py Adds TestGuardrailResponseCredentialMasking with 6 regression tests covering callback_vars masking, nested auth metadata, secret_fields pop, match/regex redaction, scalar passthrough, and prefix/suffix reveal; no existing tests modified
tests/test_litellm/litellm_core_utils/test_sensitive_data_masker.py Adds 4 unit tests for mask_credentials_in_payload covering None/scalar preservation, gcs_path_service_account masking, Pydantic model unwrapping, and selective leaf masking; no existing tests modified

Reviews (3): Last reviewed commit: "fix(guardrails): mask credentials embedd..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.47368% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...itellm/litellm_core_utils/sensitive_data_masker.py 88.23% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit4314b_guardrail_credentials_mask (2a74d19) with litellm_internal_staging (68a4ca7)

Open in CodSpeed

@yucheng-berri
yucheng-berri force-pushed the litellm_lit4314b_guardrail_credentials_mask branch from 2b6e25d to fd20d3c Compare July 9, 2026 23:11
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review; force-pushed to fd20d3cb48 after a mock manager pass. The single-line _default_masker.mask() call was replaced with a dedicated mask_credentials_in_payload helper that preserves None / scalars / tuples / typed objects verbatim (the config-dump masker was silently stringifying them). Pydantic BaseModel values reached during the walk are dumped via model_dump() so nested UserAPIKeyAuth credentials get masked; the live proxy repro confirmed that a Pydantic-blind walker leaked 2 plaintext copies through this exact path. Tests were expanded to cover Pydantic recursion, scalar preservation, and prefix/suffix reveal shape. Both follow-ups you flagged (return-type annotation and top-level str bypass on exception-coerced strings) are addressed indirectly: the new helper is typed (data: object) -> object at the boundary but preserves dict/list/tuple/None/BaseModel identity so downstream consumers see a JSON-serializable tree of the same shape they saw before; the top-level str bypass is still there and is called out in the PR body follow-ups because it's the same pre-existing semantics as the two scrubs above it, not a regression this PR introduces.

@veria-ai

veria-ai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@yucheng-berri
yucheng-berri force-pushed the litellm_lit4314b_guardrail_credentials_mask branch from fd20d3c to a40fd6b Compare July 9, 2026 23:45
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

Force-pushed a40fd6bf30 to address:

  • CI code-quality failure: added _walk_payload to the recursive_detector ignore list. It is bounded by DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER just like its siblings mask_dict / _mask_sequence on that list.

  • Veria AI medium (gcs_path_service_account): the masker's segment-only detection does not flag that compound key. Added an EXTRA_SENSITIVE_KEY_NAMES frozenset to sensitive_data_masker.py (currently just gcs_path_service_account) and taught mask_credentials_in_payload to consult it in addition to SensitiveDataMasker.is_sensitive_key. Regression test asserts the value is masked.

Left callback_utils.py's existing _EXTRA_SENSITIVE_CALLBACK_KEYS in place for now; consolidating both callsites onto the shared constant is a good follow-up but would fire the dashboard-API-types gate, which is out of scope here.

@greptileai please re-review.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

…re persist (LIT-4314)

Team-level callback_vars (e.g. langsmith_api_key) get spread into
data["metadata"] as four aliases (user_api_key_metadata,
user_api_key_team_metadata, user_api_key_auth_metadata,
user_api_key_auth). When a guardrail hook echoes that metadata into
its guardrail_response, the plaintext credential landed five times
inside LiteLLM_SpendLogs.metadata.standard_logging_guardrail_information[i].guardrail_response
and every downstream sink that reads it (OTel via emit_guardrail_span,
Langfuse, custom loggers).

Add a purpose-built payload walker (mask_credentials_in_payload) that
only masks strings under sensitive-named keys and preserves every
other value (None, ints, floats, bools, tuples, typed objects) verbatim.
The walker reuses SensitiveDataMasker.is_sensitive_key so the pattern
list stays in one place, and unwraps Pydantic models via model_dump()
so nested UserAPIKeyAuth values reached by the walk get scanned as
plain dicts (they are JSON-serialized downstream anyway).

Apply the walker at add_standard_logging_guardrail_information_to_request_data
after the existing secret_fields pop and match/regex redaction, so
every downstream sink sees masked values from a single seam.
@yucheng-berri
yucheng-berri force-pushed the litellm_lit4314b_guardrail_credentials_mask branch from a40fd6b to 2a74d19 Compare July 10, 2026 00:05
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

Force-pushed 2a74d19. Reverted the EXTRA_SENSITIVE_KEY_NAMES frozenset added for gcs_path_service_account; the customer report and ticket are scoped to callback_vars.langsmith_api_key, which the default segment-matched masker already covers. The compound-key case Veria AI flagged is a general masker limitation, not a regression this PR introduces; deferring to a follow-up ticket alongside the other observability-masking work in the PR body.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit a40fd6bf306fa725e248567d3420b404fb1062e4. Configure here.

@yucheng-berri
yucheng-berri merged commit 74623b1 into litellm_internal_staging Jul 10, 2026
78 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_lit4314b_guardrail_credentials_mask branch July 10, 2026 03:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants