← Back to Pull requests

chore(appsec): fix unwrap after re-patching a class method DD_BPPZV3 DD_RXF8ZI DD_MQNBM0 DD_2UATV7 #22032

Closed
unknown closed this pull request without merging on Nov 24, 2026 13:58 UTC
View on GitHub
unknown unknown commented on Nov 23, 2026 16:32 UTC
Author

Description

Related to https://datadoghq.atlassian.net/browse/APPSEC-71951

apply_patch in ddtrace/internal/security/_patch_utils.py (shared by IAST and AAP) decides what to save as the original before wrapping, and had two flaws.

It read the current value with getattr.

  • On a class whose method is already wrapped, getattr goes through FunctionWrapper.__get__(None, cls) and returns a BoundFunctionWrapper. That isn't a FunctionWrapper, so a second patch of the same method replaced the saved original in _DD_ORIGINAL_ATTRIBUTES with the wrapper.

  • try_unwrap then put that wrapper back. The hook kept running and the method could never be unwrapped for the rest of the process.

  • The current value now comes from wrapt's resolve_path, which returns the raw class __dict__ value.
  • It treated any FunctionWrapper as one of ours.

  • When the attribute already held a wrapper installed some other way (for example a library method using a wrapt decorator), the original was never saved, and unwrapping left our hook on top.

  • The original is now recorded with setdefault, so a wrapper installed elsewhere is saved and restored on unwrap.
  • The same-hook check now runs first: a replacement using the same hook as the current value is skipped, whether or not we recorded that value. This also covers a value inherited from a base class that was patched first. try_unwrap sets the saved original directly instead of going back through apply_patch, so a restore can't be skipped by that check; the patch_builtins fallback for immutable types is kept.

    Behavior changes:

  • A second patch with the same hook is skipped instead of stacking a second wrapper. That includes class attributes and a subclass whose base is already patched with that hook.

  • Unwrapping a classmethod or staticmethod now restores the descriptor, even after a single patch and unwrap. Before, a classmethod came back bound to the class it was patched on, so a subclass call got the wrong cls. A staticmethod came back as a plain function, so calling it on an instance raised TypeError.
  • This helper was the underlying cause of the test_weak_cipher_rc4_unpatched flakes (py3.9 / 3.10 / 3.12 / 3.13):

  • #21838 added validator tests that patched IAST twice, once from each of two fixtures. That left the RC4 wrapper on ARC4Cipher.encrypt, and every later unpatch on that xdist worker restored it.

  • It only failed when one worker ran test_replace_aspect.py through test_weak_cipher.py without work-stealing, which is why py3.9 was hit most.

  • #21879 already removed the double patch from those tests, so main has been clean since 2026-11-18; the failures since then are on branches based on older main. This change fixes the helper itself.
  • Customer impact

    None. Production paths don't patch twice (IAST sinks skip a repeat patch outside testing, and AAP common modules have an _is_patched guard), and nothing outside tests unpatches.

    Testing

  • New tests/internal/test_security_patch_utils.py (8 tests):

  • - patches a method, a classmethod, a staticmethod and a module function twice, then unwraps each and checks that the original is restored, its entry is gone and the hook no longer runs;
    - patches a method with two different hooks;
    - patches a method and a module function that already hold a wrapper installed elsewhere;
    - patches a base class and its subclass with the same hook.
  • Results: all 8 pass on Python 3.9 and 3.13. On main, 7 of 8 fail; on the previous revision of this PR, the base-and-subclass case fails.

  • Original flake: with #21879's test change reverted, two validator tests followed by test_weak_cipher_rc4_unpatched fail on main with the same assertion as CI, and pass with this change.

  • appsec_iast_default, full suite: py3.9 19917 passed, py3.12 19931 passed. This includes the weak-hash sink, which patches an immutable C type through patch_builtins.

  • appsec suite: py3.9 966 passed, py3.12 967 passed.

  • scripts/lint checks passes.
  • Risks

    Low. Only how apply_patch and try_unwrap read, record and restore the original changes, and production never patches twice or unpatches. The extra lookup runs once per patch call at startup, never per request, so I didn't run benchmarks.

  • Trade-off: tracking is by entry. If something replaces the attribute outside try_unwrap while our entry exists, a later patch and unwrap puts back the older original.

  • Not covered: when a method is patched through a subclass that inherits it, try_unwrap writes the saved original into the subclass's own __dict__ instead of deleting it. This was already true on main, and it shows up in three ways:

  • - Different hooks on base and subclass: after both are unwrapped, the base wrapper stays on the subclass.
    - Same hook, subclass patched first: the hook is removed, but the subclass keeps its own copy of the original function.
    - A single patch through an inheriting subclass, such as IAST's patch of flask.Response.set_cookie, which flask inherits from werkzeug: after unwrap, flask.Response keeps its own copy.

    The last two leave no hook running, but the copy would hide any later patch on the base class. The follow-up is to delete the attribute in try_unwrap when the subclass didn't define it, which fixes all three.

    Additional Notes

    No release note: there is no customer-visible behavior change (see Customer impact).

    tests/internal/test_security_patch_utils.py is now co-owned by @DataDog/asm-python, which owns the code it tests.

    #21881 (closed) is superseded by this change.

    DD_BPPZV3 DD_RXF8ZI DD_MQNBM0 DD_2UATV7

    🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: avara1986 Review duration: 1285m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #22032"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%