7Eki
Race condition in Python
I am trying to teach my students about race conditions on the web, and for that purpose, I am using a simple bank example, in which we transfer an amount from person A to Person B's account. If we use Burp and send simultaneous requests like 20-30 that add operation will complete; however, the subtract operation will complete later. So If person A has $20 and Person B has $0. Once I send a transfer request for $20 from A to B (20 simulatnours request), there is a chance that Person B account will get $20 more than once.. Here is my code
if user['balance'] >= amount:
# Credit the target user's account
conn.execute('UPDATE users SET balance = balance + ? WHERE account_number = ?',
(amount, target_account_number))
conn.close() # Immediately close connection to force an early write
# Simulate a delay to allow race condition
import time
time.sleep(2) # Simulate delay
# Open a new connection for the debit operation
conn = get_db()
# Debit the sender's account
conn.execute('UPDATE users SET balance = balance - ? WHERE account_number = ?',
(amount, session['user']))
conn.close() # Close connection to apply the change immediately
flash(f'Success! Transferred ${amount} to account {target_account_number}.')
else:
flash('Insufficient funds.')
return redirect(url_for('dashboard'))
Is there anything that I am doing wrong for race conditions? my backend is SQLITE