# 🚨 CRITICAL: Race Condition Vulnerabilities Found

## Date: February 28, 2026
## Severity: HIGH to CRITICAL

---

## Executive Summary

Found **7 CRITICAL race condition vulnerabilities** that could lead to:
- ❌ **Free bill payments** (wallets never debited)
- ❌ **Double spending** (concurrent transactions)
- ❌ **Inconsistent wallet balances**
- ❌ **OTP reuse attacks**
- ❌ **PIN change race conditions**

---

## 🔴 CRITICAL ISSUE #1: Bill Payment Controllers Never Debit Wallets

### Affected Files:
1. `app/Http/Controllers/RechargeController.php` (Airtime & Data)
2. `app/Http/Controllers/ElectricityController.php`
3. `app/Http/Controllers/CableTvController.php`
4. `app/Http/Controllers/PagaBillersController.php` (Cable, Electricity, Betting, Mobile)

### The Problem:
**All bill payment controllers call `check_wallet_balance()` but NEVER call `update_wallet()` to debit the balance!**

#### Example from RechargeController (Line 66):
```php
// CHECKING FOR SUFICIENT BALANCE
$check_balance = $this->check_wallet_balance($user_id, $sourceWallet, $amount);
if ($check_balance) {
    // Make API call to purchase airtime
    $response = Http::withoutVerifying()->get($baseUrl)->json();
    
    // Record transaction
    Recharge_record::create([...]);
    Transactions::create([...]);
    
    // ❌ WALLET NEVER DEBITED! Users get free airtime!
    return ApiHelper::validResponse($res, $response);
}
```

#### Same Issue in ElectricityController (Line 91):
```php
$check_balance = $this->check_wallet_balance($user_id, $sourceWallet, $amount);
if ($check_balance) {
    $response = Http::withoutVerifying()->get($baseUrl)->json();
    // Create records...
    // ❌ WALLET NEVER DEBITED! Users get free electricity!
}
```

#### Same Issue in CableTvController (Line 88):
```php
$check_balance = $this->check_wallet_balance($user_id, $sourceWallet, $amount);
if ($check_balance) {
    $response = Http::withoutVerifying()->get($baseUrl)->json();
    // Create records...
    // ❌ WALLET NEVER DEBITED! Users get free cable TV!
}
```

#### Same Issue in PagaBillersController (Lines 349, 430, 512, 626, 710):
All 5 purchase methods follow the same broken pattern.

### Impact:
🔴 **CRITICAL**: Users can make unlimited bill payments without balances being deducted!

### Fix Required:
Add `update_wallet()` call after service success WITH proper DB transaction wrapping.

---

## 🔴 CRITICAL ISSUE #2: update_wallet() Missing Row Locking

### Affected File:
`app/Traits/ManagesTransactions.php` (Line 116)

### The Problem:
The `update_wallet()` function has DB transaction wrapping but doesn't use `lockForUpdate()`:

```php
public function update_wallet($user_id, $currency, $amount, $type)
{
    try {
        DB::beginTransaction();
        
        // ❌ NO ROW LOCK! Race condition possible here
        $wallet = Wallets::where('user_id', $user_id)->first();
        $amount = $this->removeComma($amount);
        
        if ($currency == ApiConstants::CURRENCY_NGN) {
            $wallet_balance = $wallet->ngn_balance;  // READ
            if ($type == ApiConstants::DEBIT) {
                $wallet->update([
                    "ngn_balance" => $wallet_balance - $amount  // WRITE
                ]);
            }
        }
        
        DB::commit();
        return true;
    } catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}
```

### Race Condition Scenario:
```
Time    Transaction A               Transaction B
----    -------------               -------------
T1      Read balance: 1000          
T2                                  Read balance: 1000
T3      Debit 500 (balance = 500)   
T4                                  Debit 300 (balance = 700) 
T5      Commit: balance = 500       
T6                                  Commit: balance = 700
        
RESULT: Balance should be 200, but is 700 (lost 300 debit!)
```

### Impact:
🔴 **HIGH**: Concurrent transactions can cause lost updates, allowing double spending.

### Fix Required:
```php
// Add lockForUpdate() before reading balance
$wallet = Wallets::where('user_id', $user_id)->lockForUpdate()->first();
```

---

## 🔴 CRITICAL ISSUE #3: FincraUpdate Command Race Condition

### Affected File:
`app/Console/Commands/FincraUpdate.php` (Line 48-95)

### The Problem:
The scheduled command updates wallet balances without any locking:

```php
public function handle()
{
    $transactions = Transactions::where('type', ApiConstants::DEBIT)
        ->where('status', ApiConstants::STATUS_PROCESSING)
        ->whereDate('created_at', '>=', $currentDate)
        ->get();

    foreach ($transactions as $transaction) {
        // Check transaction status with Fincra API
        $verify = $this->verify_transfer($request);
        $status = $verify['responseCode'] === 0 ? 'successful' : 'failed';
        
        // ❌ NO LOCKING: What if this transaction is being processed elsewhere?
        $update_transaction = Transactions::where('customers_reference', 
            $transaction->customers_reference)->first();
        
        $update_transaction->status = $status;
        $update_transaction->save();
        
        if ($status === 'failed') {
            // ❌ NO LOCKING: Concurrent update_wallet calls could cause issues
            $this->update_wallet($update_transaction->user_id, 
                $update_transaction->source_currency, 
                $update_transaction->amount, 
                ApiConstants::CREDIT);
        }
        
        if ($status === 'successful') {
            // ❌ WRONG: Transaction already debited, this debits again!
            $this->update_wallet($update_transaction->user_id, 
                $update_transaction->source_currency, 
                $update_transaction->amount, 
                ApiConstants::DEBIT);
        }
    }
}
```

### Multiple Issues:
1. **No transaction locking** - Multiple cron runs could process same transaction
2. **Double debit on success** - Wallet already debited in TransferController, this debits again!
3. **No atomic status update** - Status could be updated mid-verification

### Impact:
🔴 **HIGH**: 
- Users could be double-charged when scheduled job runs
- Failed transactions could be refunded multiple times
- Transaction status inconsistencies

### Fix Required:
1. Add row locking when fetching transactions
2. Remove the successful debit (already done in TransferController)
3. Add DB transaction wrapping

---

## 🟠 MEDIUM ISSUE #4: Transaction Toggle Race Condition

### Affected File:
`app/Http/Controllers/TransactionToggleController.php` (Line 11)

### The Problem:
```php
public function toggle()
{
    // ❌ NO LOCKING: Multiple admins could toggle simultaneously
    $toggle = TransactionToggle::first();
    
    if ($toggle) {
        $toggle->enabled = !$toggle->enabled;  // READ-MODIFY-WRITE race
        $toggle->save();
    }
}
```

### Race Condition Scenario:
```
Admin A calls toggle: enabled=true → reads true → sets false
Admin B calls toggle: enabled=true → reads true → sets false
Both save false (expected: one true, one false)
```

### Impact:
🟠 **MEDIUM**: Toggle state could be inconsistent across multiple admin actions.

### Fix Required:
Use `lockForUpdate()` or database-level atomic toggle.

---

## 🟠 MEDIUM ISSUE #5: PIN Change Without Transactions

### Affected File:
`app/Http/Controllers/TransactionPinController.php` (Line 109)

### The Problem:
```php
public function change_pin(Request $request)
{
    // ❌ NO DB TRANSACTION WRAPPING
    $user_pin = TransactionPin::where('user_id', $user_id);
    $old_pin = $user_pin->first();
    
    if (Hash::check($request->old_pin, $old_pin->new_pin)) {
        // ❌ If this fails midway, database could be in inconsistent state
        $update_pin = $user_pin->update([
            'old_pin' => Hash::make($request->old_pin),
            'new_pin' => Hash::make($request->new_pin),
        ]);
    }
}
```

### Impact:
🟠 **MEDIUM**: PIN updates could fail midway, leaving user unable to transact.

### Fix Required:
Wrap in DB transaction.

---

## 🟠 MEDIUM ISSUE #6: OTP Cache Race Condition

### Affected File:
`app/Http/Controllers/TransactionPinController.php` (Line 140)

### The Problem:
```php
public function reset_pin()
{
    $OTP = rand(1000, 9999);
    
    // ❌ Cache::put is not atomic - concurrent requests could overwrite OTP
    $exp = now()->addMinute(5);
    Cache::put($user->email, $user_record, $exp);
}

public function set_new_pin(Request $request)
{
    // ❌ No protection against OTP reuse
    $get_cached_details = Cache::get($request->email);
    
    if ($request->otp == $get_cached_details['otp']) {
        $pin = TransactionPin::where('user_id', '=', $user_id)
            ->update(['new_pin' => Hash::make($request->new_pin)]);
        
        // ❌ OTP should be deleted after use to prevent reuse!
        // Missing: Cache::forget($request->email);
    }
}
```

### Impact:
🟠 **MEDIUM**: 
- OTP could be reused multiple times
- Concurrent OTP requests could be confusing
- Race condition in OTP generation

### Fix Required:
1. Delete OTP after successful use
2. Add atomic OTP generation/validation
3. Rate limit OTP requests

---

## 🟡 LOW ISSUE #7: User Registration Without Transactions

### Affected File:
`app/Http/Controllers/Authentication/RegisterController.php` (Line 19)

### The Problem:
```php
public function register2(Request $request)
{
    // DB::beginTransaction();  ← COMMENTED OUT!
    try {
        $data = RegisterationService::validate_otp($request->all());
        
        // User creation happens here
        $user = RegisterationService::create($data);
        
        // DB::commit();  ← COMMENTED OUT!
    }
}
```

The `RegisterationService::create()` likely creates both User and Wallet, but without transaction wrapping, if wallet creation fails, user exists without wallet.

### Impact:
🟡 **LOW**: Orphaned users without wallets could exist.

### Fix Required:
Uncomment DB transaction wrapping.

---

## 📊 Summary of Vulnerabilities

| # | Issue | Severity | Impact | Affected Controllers |
|---|-------|----------|--------|---------------------|
| 1 | No wallet debit in bill payments | 🔴 CRITICAL | Free services | RechargeController, ElectricityController, CableTvController, PagaBillersController |
| 2 | update_wallet() missing row lock | 🔴 CRITICAL | Double spending | All financial transactions |
| 3 | FincraUpdate race condition | 🔴 HIGH | Double charges/refunds | FincraUpdate command |
| 4 | Transaction toggle race | 🟠 MEDIUM | Toggle inconsistency | TransactionToggleController |
| 5 | PIN change without transactions | 🟠 MEDIUM | Inconsistent PIN state | TransactionPinController |
| 6 | OTP reuse possible | 🟠 MEDIUM | Security bypass | TransactionPinController |
| 7 | Registration without transactions | 🟡 LOW | Orphaned users | RegisterController |

---

## 🔧 Recommended Fixes (Priority Order)

### 1. IMMEDIATE (Do Today):

#### Fix Bill Payment Controllers:
Add wallet debit after successful service purchase in ALL bill payment methods:

```php
// Pattern to follow (from TransferController):
DB::beginTransaction();
try {
    // 1. Check balance
    $check_balance = $this->check_wallet_balance($user_id, $currency, $amount);
    
    if ($check_balance) {
        // 2. Make external API call
        $response = Http::withoutVerifying()->get($baseUrl)->json();
        
        if ($response['code'] == "success") {
            // 3. ✅ DEBIT THE WALLET!
            $update_wallet = $this->update_wallet($user_id, $currency, $amount, ApiConstants::DEBIT);
            
            if (!$update_wallet) {
                throw new \Exception('Failed to debit wallet');
            }
            
            // 4. Record transaction
            Transactions::create([...]);
            
            DB::commit();
            return ApiHelper::validResponse('Success', $response);
        }
    }
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}
```

Apply this pattern to:
- ✅ `RechargeController::buy_airtime()` (Line 66)
- ✅ `RechargeController::buy_data()` (Line 173)
- ✅ `ElectricityController::buy_electricity()` (Line 91)
- ✅ `CableTvController::cable_sub()` (Line 88)
- ✅ `PagaBillersController::purchase_cable()` (Line 349)
- ✅ `PagaBillersController::purchase_electricity()` (Line 430)
- ✅ `PagaBillersController::purchase_betting()` (Line 512)
- ✅ `PagaBillersController::purchase_mobile_airtime()` (Line 626)
- ✅ `PagaBillersController::purchase_mobile_data()` (Line 710)

#### Fix update_wallet() Row Locking:
```php
public function update_wallet($user_id, $currency, $amount, $type)
{
    try {
        DB::beginTransaction();
        
        // ✅ ADD ROW LOCK HERE
        $wallet = Wallets::where('user_id', $user_id)->lockForUpdate()->first();
        
        // Rest of the logic...
        
        DB::commit();
        return true;
    } catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}
```

### 2. HIGH PRIORITY (This Week):

#### Fix FincraUpdate Command:
```php
public function handle()
{
    DB::beginTransaction();
    try {
        $transactions = Transactions::where('type', ApiConstants::DEBIT)
            ->where('status', ApiConstants::STATUS_PROCESSING)
            ->whereDate('created_at', '>=', $currentDate)
            ->lockForUpdate()  // ✅ Lock rows being processed
            ->get();

        foreach ($transactions as $transaction) {
            $verify = $this->verify_transfer(['referenceNumber' => $transaction->customers_reference]);
            $status = $verify['responseCode'] === 0 ? 'successful' : 'failed';
            
            $transaction->status = $status;
            $transaction->save();
            
            // ✅ ONLY refund on failure (wallet already debited on success)
            if ($status === 'failed') {
                $this->update_wallet(
                    $transaction->user_id, 
                    $transaction->source_currency, 
                    $transaction->amount, 
                    ApiConstants::CREDIT
                );
                
                // Send notification
            }
            // ✅ REMOVE the successful branch that debits again!
        }
        
        DB::commit();
    } catch (\Exception $e) {
        DB::rollBack();
        Log::error('FincraUpdate failed: ' . $e->getMessage());
    }
}
```

### 3. MEDIUM PRIORITY:

#### Fix Transaction Toggle:
```php
public function toggle()
{
    DB::beginTransaction();
    try {
        $toggle = TransactionToggle::lockForUpdate()->first();
        
        if ($toggle) {
            $toggle->enabled = !$toggle->enabled;
            $toggle->save();
        }
        
        DB::commit();
        return ApiHelper::validResponse('Success', [...]);
    } catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}
```

#### Fix PIN Change:
```php
public function change_pin(Request $request)
{
    DB::beginTransaction();
    try {
        $user_pin = TransactionPin::where('user_id', $user_id)->lockForUpdate()->first();
        
        if (Hash::check($request->old_pin, $user_pin->new_pin)) {
            $user_pin->update([
                'old_pin' => Hash::make($request->old_pin),
                'new_pin' => Hash::make($request->new_pin),
            ]);
            
            DB::commit();
            return ApiHelper::validResponse('PIN changed successfully!', []);
        }
        
        DB::rollBack();
        return ApiHelper::problemResponse('Error: no match found!', ApiConstants::SERVER_ERR_CODE);
    } catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}
```

#### Fix OTP Reuse:
```php
public function set_new_pin(Request $request)
{
    $user_id = auth()->user()->id;
    $get_cached_details = Cache::get($request->email);
    
    if ($get_cached_details) {
        if ($request->otp == $get_cached_details['otp']) {
            DB::beginTransaction();
            try {
                $pin = TransactionPin::where('user_id', '=', $user_id)
                    ->update(['new_pin' => Hash::make($request->new_pin)]);
                
                // ✅ DELETE OTP AFTER USE
                Cache::forget($request->email);
                
                DB::commit();
                return ApiHelper::validResponse('PIN reset successful!', []);
            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }
        }
    }
}
```

### 4. LOW PRIORITY:

#### Uncomment Registration Transactions:
```php
public function register2(Request $request)
{
    DB::beginTransaction();  // ✅ UNCOMMENT
    try {
        $data = RegisterationService::validate_otp($request->all());
        $user = RegisterationService::create($data);
        
        DB::commit();  // ✅ UNCOMMENT
        return ApiHelper::validResponse("Success", AuthService::onAuthorized($user, $request->fcm_token));
    } catch (\Exception $e) {
        DB::rollBack();  // ✅ UNCOMMENT
        throw $e;
    }
}
```

---

## 🧪 Testing Recommendations

### Test Race Conditions:
Use parallel curl requests to simulate concurrent transactions:

```bash
# Test concurrent airtime purchases
for i in {1..10}; do
  curl -X POST http://localhost:8000/api/vtu/airtime \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"network_id":"MTN","phone_number":"08012345678","amount":100,"pin":"1234"}' &
done
wait

# Check if wallet was debited correctly (should be debited 1000, not 0)
```

---

## 📈 Impact Assessment

### Before Fixes:
- ❌ Users can get FREE bill payments (wallets never debited)
- ❌ Double spending possible with concurrent transfers
- ❌ FincraUpdate command double-charges successful transactions
- ❌ Lost wallet updates due to race conditions
- ❌ OTP can be reused multiple times

### After Fixes:
- ✅ All bill payments properly debit wallets
- ✅ Row locking prevents double spending
- ✅ Atomic operations ensure consistency
- ✅ OTP single-use enforced
- ✅ All critical operations wrapped in transactions

---

**Status:** 🔴 **CRITICAL FIXES REQUIRED IMMEDIATELY**  
**Priority:** Fix #1 (Bill Payment Controllers) and #2 (update_wallet locking) TODAY  
**Next Review:** After fixes applied, run comprehensive load testing

