Repository navigation
fix(guardrails): mask credentials embedded in guardrail_response before persist (LIT-4314) - #32687
Conversation
Greptile SummaryThis PR adds credential masking at the single logging construction seam in
Confidence Score: 5/5Safe 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.
|
| 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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
2b6e25d to
fd20d3c
Compare
|
@greptileai please re-review; force-pushed to fd20d3cb48 after a mock manager pass. The single-line |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
fd20d3c to
a40fd6b
Compare
|
Force-pushed a40fd6bf30 to address:
Left @greptileai please re-review. |
|
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.
a40fd6b to
2a74d19
Compare
|
Force-pushed 2a74d19. Reverted the |
There was a problem hiding this comment.
✅ 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.
Relevant issues
Linear ticket
Contributes to LIT-4314; scope covers the credential-mask piece of the ticket. The sibling
store_prompts_in_spend_logsgating scope is being addressed in a separate PR.Pre-Submission checklist
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 4000Before (unfixed HEAD
1fa200123f)Launch:
Provision + hit:
Plaintext count in
LiteLLM_SpendLogs.metadata:Output:
5That is the same team callback_vars Langsmith key showing up plaintext five times inside one row's
guardrail_information[i].guardrail_response(viauser_api_key_auth,user_api_key_metadata,user_api_key_team_metadata,user_api_key_auth_metadata, and the directmetadata.callback_varsecho the leaky guardrail hook makes when it snapshotsdata["metadata"])After (fixed HEAD
2b6e25d896)Same launch, same curl, same psql, on the fixed binary
Plaintext count:
Output:
0Masked count:
Output:
5The five plaintext occurrences got replaced by five masked ones. The five reveal-prefix/reveal-suffix strings look like
lsv2*******************************************4124Dashboard 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-reproType
🐛 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 buildingStandardLoggingGuardrailInformation. That record is what every downstream sink reads: SpendLogs, OTel v2 (emit_guardrail_spanat line 802), Langfuse (guardrail_entry["guardrail_response"]atlitellm/integrations/langfuse/langfuse.py:967), and any user-configured custom loggerTwo narrow scrubs already ran inside this function; neither touched nested credential-shaped keys.
secret_fieldswas popped at the top level, andredact_nested_match_and_regex_keysonly rewrites keys literally namedmatchorregex. When a guardrail hook echoeddata["metadata"]back as part of itsguardrail_response, the fouruser_api_key_*aliases plus the rawcallback_varscopy all sailed through and got persisted plaintextThe fix runs
SensitiveDataMasker's default masker over the response after those two scrubs. It segment-matches key names likeapi_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_snapshotshape, 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 patchesRegression tests in
tests/test_litellm/integrations/test_custom_guardrail.py::TestGuardrailResponseCredentialMaskingcover: a Langsmith-shapedcallback_vars.langsmith_api_keygets masked and does not appear plaintext anywhere in the serialized record; a nesteduser_api_key_auth.metadata.callback_vars.langsmith_api_keyalongsidetoken/api_keyall get masked; and the existingsecret_fieldspop 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 mutationFollow-ups the ticket calls out that are intentionally out of scope for this PR: sibling PR for
store_prompts_in_spend_logsgating ofguardrail_response; ticket to splitcallback_varstransport offUserAPIKeyAuth.team_metadataso it never lands indata["metadata"]in the first place; ticket to maskoptional_params/additional_params/litellm_params.api_keyacross the wider observability path and to redact by default across sinksNote
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_datanow runsmask_credentials_in_payloadafter existingsecret_fieldsremoval andmatch/regexredaction, so masking happens once at the shared construction seam for all guardrails.mask_credentials_in_payload(insensitive_data_masker.py) walks nested dicts/lists/tuples and Pydantic models, masks non-empty string values under sensitive key names (sharedSensitiveDataMaskerpatterns plusgcs_path_service_account), and leaves scalars/None/structure intact—unlike fullSensitiveDataMasker.mask, which can distort logging payloads._walk_payloadis 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.