Skip to content

fix(guard): redact each Anthropic output block independently - #2024

Open
feiiiiii5 wants to merge 2 commits into
openlit:mainfrom
feiiiiii5:feiiiiii5/1126-D278
Open

feiiiiii5 wants to merge 2 commits into
openlit:mainfrom
feiiiiii5:feiiiiii5/1126-D278

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: #2021

Change description:

Anthropic postflight redaction joined all text content blocks into one string, redacted it once, and wrote the result only to the first block. Later blocks kept the original secret and the first block contained the duplicated conversation.

Fix: _apply_postflight() now calls a new helper that runs the pipeline on each text block independently and writes each result back to its own block. A single-block response keeps the original combined path; DENY handling and the choices/response.text branches are unchanged.

Checklist

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented (no API change)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Verification

New two-block regression test: base-red ['First: [REDACTED:email] Second: [REDACTED:email]', 'Second: [email protected]'] (duplication + PII leak); with fix both blocks redacted independently. Target 1/1, module 17/17, guard suite 68/68 passed. py_compile and line-length check clean (pylint unavailable offline, not run).

No live provider calls, network, or credentials — all HTTP/content is faked.

Summary by Sourcery

Fix Anthropic postflight redaction to safely transform each text content block without leaking or duplicating output.

Bug Fixes:

  • Redact Anthropic response text blocks independently so secrets are not leaked or duplicated across blocks.
  • Preserve unscanned text while applying postflight transformations, including content spanning multiple blocks.

Enhancements:

  • Strengthen postflight handling for per-block denial and fail-open or fail-closed guard errors while retaining existing response-shape support.

Tests:

  • Add regression coverage for multi-block redaction, denial and failure behavior, cross-block matches, scan-limit suffix preservation, and empty transformations.

@feiiiiii5
feiiiiii5 requested review from a team and ishanjainn as code owners November 26, 2026 05:06
@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Data structures

Add unscanned_suffix to PipelineResult so postflight redaction can retain text beyond a guard’s scan limit.

  • sdk/python/src/openlit/guard/_base.py L80

Implementation

Track and restore unscanned suffixes as guards transform text, and add helpers to redistribute combined Anthropic redactions to their original text blocks.

  • sdk/python/src/openlit/guard/_integration.py L27, L333-399
  • sdk/python/src/openlit/guard/_pipeline.py L57-64 (+3 small edits)

Apply postflight redactions to the appropriate response fields, propagate per-block denials and strict evaluation errors, then mutate the response with the prepared redactions.

  • sdk/python/src/openlit/guard/_integration.py L415-442

Tests

Add regression tests for independent Anthropic block redaction, cross-block matches, denial and failure handling, and scan-limit suffix preservation.

  • sdk/python/tests/test_guard_integration.py L11-17, L33-92, L276-418 (+2 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix Anthropic postflight redaction across multiple content blocks

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Redact Anthropic output blocks independently to prevent duplicated text and leaked secrets.
• Preserve the existing single-block behavior and add a two-block regression test.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The pipeline, provider wrappers, scan-limit handling, and Anthropic block mutation all implement one bounded behavior: evaluating configured guards and enforcing their result on LLM requests or returned text.
  • They are implementation hops in the same runtime integration, not independent user capabilities.
Sources

sdk/python/src/openlit/guard/_pipeline.py[87-99]

                current_text = result.transformed_text
                if dropped:
                    unscanned_suffix = dropped + unscanned_suffix

            if result.action == GuardAction.DENY:
                break

        transformed = current_text if current_text != text else None
        return PipelineResult(
            action=worst_action,
            results=results,
            transformed_text=transformed,
            unscanned_suffix=unscanned_suffix,

sdk/python/src/openlit/guard/_pipeline.py[57-64]

            scan_text = current_text
            limit = getattr(guard, "_max_scan_length", 0)
            dropped = ""
            if limit and len(scan_text) > limit:
                scan_text, dropped = scan_text[:limit], scan_text[limit:]

            try:
                result = guard.run(scan_text, guard_phase)
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before, postflight mutation used a single transformed string for a limited response shape and the pipeline did not expose scan-limit suffixes.
  • After, each guard may scan a capped prefix while later redactions chain over transformed text, and combined Anthropic output must be redistributed across blocks while block-level denial checks are also performed.
  • New correctness conditions are that unscanned suffixes remain in their correct order, redactions spanning block boundaries map back to the right blocks, and denial behavior is preserved across combined and standalone evaluations.
  • These are newly interacting transformation and provider-shape conditions, not complexity inherited merely from using existing guards.
Sources

sdk/python/src/openlit/guard/_pipeline.py[57-64]

            scan_text = current_text
            limit = getattr(guard, "_max_scan_length", 0)
            dropped = ""
            if limit and len(scan_text) > limit:
                scan_text, dropped = scan_text[:limit], scan_text[limit:]

            try:
                result = guard.run(scan_text, guard_phase)

sdk/python/src/openlit/guard/_pipeline.py[87-99]

                current_text = result.transformed_text
                if dropped:
                    unscanned_suffix = dropped + unscanned_suffix

            if result.action == GuardAction.DENY:
                break

        transformed = current_text if current_text != text else None
        return PipelineResult(
            action=worst_action,
            results=results,
            transformed_text=transformed,
            unscanned_suffix=unscanned_suffix,
Potential damage 🔴 High 🩹 Confidentiality

  • If redaction or denial regresses, sensitive content that the configured guard was intended to remove may reach the application caller.
  • This assessment is conditional because the scenario has no supported concrete fault hypothesis.
  • Reverting prevents future affected processing, but text already returned or externally disclosed cannot be reliably recalled by this package.
Assessed commit 5c6c96e
Diagram

graph TD
  A["Anthropic response"] --> B["Joined text extractor"] --> C["Postflight pipeline"] -->|REDACT| D{"Block count?"}
  D -->|multiple| E["Evaluate each block"] --> F["Update text blocks"]
  D -->|single| F
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Map combined-text redactions back to blocks
  • ➕ Avoids additional pipeline evaluations for multiple blocks.
  • ➖ Requires reliable mapping from transformed text to original block boundaries, which becomes fragile when guards change text length.

Recommendation: Keep per-block evaluation: it preserves block boundaries without requiring an offset-mapping protocol from guards. The trade-off is additional evaluations for multi-block responses.

Files changed (2) +54 / -4

Bug fix (1) +34 / -4
_integration.pyRedact Anthropic content blocks in place +34/-4

Redact Anthropic content blocks in place

• Adds a helper that evaluates each text block separately when a multi-block response requires redaction, then writes each transformed value to its source block. Single-block responses retain the existing combined-text path.

sdk/python/src/openlit/guard/_integration.py

Tests (1) +20 / -0
test_guard_integration.pyCover redaction of two Anthropic output blocks +20/-0

Cover redaction of two Anthropic output blocks

• Adds a postflight regression test with an email address in each block. It asserts that both blocks are redacted without copying their combined text into the first block.

sdk/python/tests/test_guard_integration.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Denied content reaches Anthropic callers ✓ Resolved

Resolving commit: 5c6c96e

Resolution reason
The per-block evaluation was moved into _prepare_anthropic_content_redactions, which now checks each
block's evaluation result and raises GuardDeniedError on DENY (diff lines 107-110). The
_apply_postflight try/except no longer wraps the DENY path: the redaction application is in its own
try block (lines 168-172) that only wraps setattr, and the DENY raise happens before it, so the
denial propagates to the caller. A test test_postflight_propagates_block_deny was added (test file).
The fix is implemented in a different structure than the suggested fix (it does not rewrite the
helper into the same form), but it addresses the same failure.
Description
_redact_anthropic_content_blocks ignores a DENY result from its new per-block evaluation and
handles only REDACT. If the joined response triggers redaction but a custom guard denies an
individual block, that block remains in the response returned to the caller.

2. Guard failures return unredacted blocks ✓ Resolved

Resolving commit: 5c6c96e

Resolution reason
Per-block evaluation was split into a preparation step that runs before the mutation try block, so
guard exceptions (and GuardDeniedError) propagate; only setattr failures are caught and logged. A
regression test covers the fail-closed propagation case.
Description
_redact_anthropic_content_blocks calls pipeline.evaluate inside _apply_postflight’s broad
mutation try, which suppresses exceptions even when the pipeline is configured with
fail_open=False. If a guard succeeds on joined text but raises on an individual block, the caller
receives the response with that block unchanged.


Remediation recommended

3. Cross-block secrets escape redaction ✓ Resolved

Resolving commit: 5c6c96e

Resolution reason
Joined-text transformed output is now preserved and distributed back across Anthropic content blocks
via diff-based projection, so spanning matches are redacted in their blocks; per-block DENY is
propagated and a test covers a pattern spanning two blocks.
Description
_redact_anthropic_content_blocks discards the joined evaluation’s transformed text for multi-block
responses and writes only independently detected block redactions. When a configured pattern matches
text spanning the extractor’s block separator, neither standalone evaluation matches, so the
detected content remains unchanged.

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai sourcery-ai 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.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/guard/_integration.py" line_range="357-360" />
<code_context>
+            continue
+        block_result = pipeline.evaluate(block.text, phase="postflight")
+        if (
+            block_result.action == GuardAction.REDACT
+            and block_result.transformed_text is not None
+        ):
+            block.text = block_result.transformed_text
+
+
</code_context>
<issue_to_address>
**Denied blocks reach callers**

When a per-block evaluation returns DENY while the combined evaluation does not, `_redact_anthropic_content_blocks` handles only `REDACT`, so `_apply_postflight` discards the block-level denial and returns the denied content without raising `GuardDeniedError`; the caller receives content the guard denied.

Propagate block-level `DENY` results by raising `GuardDeniedError` instead of returning the response.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/guard/_integration.py" line_range="355" />
<code_context>
+    for block in content:
+        if not getattr(block, "text", None):
+            continue
+        block_result = pipeline.evaluate(block.text, phase="postflight")
+        if (
+            block_result.action == GuardAction.REDACT
</code_context>
<issue_to_address>
**Strict guard failures expose output**

When `fail_open` is false and an individual block evaluation raises after the combined evaluation succeeds, `pipeline.evaluate` raises, but `_apply_postflight`'s broad exception handler suppresses the error and returns the response, potentially partially redacted with remaining secrets visible to the caller.

Let per-block evaluation errors propagate when `fail_open` is false, without returning a partially processed response.
</issue_to_address>

### Comment 3
<location path="sdk/python/src/openlit/guard/_integration.py" line_range="355" />
<code_context>
+    for block in content:
+        if not getattr(block, "text", None):
+            continue
+        block_result = pipeline.evaluate(block.text, phase="postflight")
+        if (
+            block_result.action == GuardAction.REDACT
</code_context>
<issue_to_address>
**Split secrets remain unredacted**

When the combined Anthropic text matches a redaction but its individual text blocks do not, `_redact_anthropic_content_blocks` discards the combined evaluation's transformed text and applies only per-block results, so `_apply_postflight` returns the original blocks with the secret still visible to the caller.

Use the combined evaluation's transformed text when updating the content blocks instead of relying only on per-block results.

Also at `sdk/python/src/openlit/guard/_integration.py:356-360`.
</issue_to_address>

### Comment 4
<location path="sdk/python/src/openlit/guard/_integration.py" line_range="355-360" />
<code_context>
+    for block in content:
+        if not getattr(block, "text", None):
+            continue
+        block_result = pipeline.evaluate(block.text, phase="postflight")
+        if (
+            block_result.action == GuardAction.REDACT
+            and block_result.transformed_text is not None
+        ):
+            block.text = block_result.transformed_text
+
+
</code_context>
<issue_to_address>
**Long blocks lose their suffix**

When a text block is longer than the guard scan limit and a redaction match occurs within its scanned prefix, when a text block exceeds the scan limit and a redaction occurs within the scanned prefix, `Pipeline.evaluate` returns transformed text only for that prefix, and the helper assigns it over the full block. The response silently loses the remainder of that block.

Preserve the unscanned portion of each block when applying a prefix-only redaction, or avoid writing a truncated transformed result over the full block.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if a block is not redacted when it should be, its original text can be returned to the caller and any exposed data cannot be recalled by reverting. The change reevaluates each text block independently, so review should verify that redaction remains effective for every block.

Blocking findings: sdk/python/src/openlit/guard/_integration.py:360, sdk/python/src/openlit/guard/_integration.py:355, sdk/python/src/openlit/guard/_integration.py:355, sdk/python/src/openlit/guard/_integration.py:360


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Raise on block-level DENY and strict evaluation errors, redistribute redactions
to their original blocks, and carry transformed suffixes across guards with
different scan limits without restoring already-redacted text.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

This branch was successfully deployed

1 active (outdated) deployment
release-notes — d98da43f Deployed Nov 26, 2026 by feiiiiii5 via Normalize / Conventional title #915
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant