Skip to content

fix(payment): fix mutable default argument bug in capture and refund - #350

Open
Sreejith088 wants to merge 1 commit into
razorpay:masterfrom
Sreejith088:fix/mutable-default-arguments
Open

Sreejith088 wants to merge 1 commit into
razorpay:masterfrom
Sreejith088:fix/mutable-default-arguments

Conversation

@Sreejith088

Copy link
Copy Markdown

Summary

Closes #134

capture() and refund() both used data={} as a default parameter and then mutated it with data['amount'] = amount. Because Python creates the default dict once at function-definition time, every call that omits the data argument shares the same dict object.

In a threaded server where a single Client is reused across requests (the typical Django/Flask pattern), two threads calling capture() concurrently race on that shared dict — one thread's amount can overwrite the other's before the POST is sent, causing a payment to be captured for the wrong amount.

Single-threaded it stays hidden because the key is simply overwritten each time.

Root cause

# Before — same dict shared across all calls
def capture(self, payment_id, amount, data={}, **kwargs):
    data['amount'] = amount   # mutates the shared default dict

Fix

# After — fresh dict created per call
def capture(self, payment_id, amount, data=None, **kwargs):
    data = dict(data or {})   # never mutates caller's dict either
    data['amount'] = amount

Same fix applied to refund().

Test plan

  • All 157 existing tests pass, 1 skipped (unchanged)
  • No behaviour change for callers who already pass an explicit data dict

Closes razorpay#134

capture() and refund() both used data={} as a default parameter and
then mutated it with data['amount'] = amount. Because Python creates
the default dict once at function definition time, every call that
omits the data argument shares the same dict object.

In a threaded server where a single Client is reused across requests,
two threads calling capture() concurrently race on that shared dict:
one thread's amount can overwrite the other's before the POST is sent.

Fix: change the default to data=None and build a fresh dict per call
with dict(data or {}), which also avoids mutating a dict the caller
passed in.
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.

Avoid using mutable defaults.

1 participant