# Transfer Controller Security Fixes Applied

## Date: February 28, 2026

---

## ✅ FIXED: TransferController ngn_transfer Method

### Critical Issues Resolved:

#### 1. **MISSING WALLET DEDUCTION** (CRITICAL)
**Problem**: After fixing `check_wallet_balance()` to only check (not debit), the `ngn_transfer()` method was no longer actually debiting wallets!

**Fix Applied**: Added explicit `update_wallet()` call after successful transfer:
```php
// CRITICAL FIX: Debit the wallet AFTER successful transfer
$update_wallet = $this->update_wallet($user->id, $request->currency, $request->amount, ApiConstants::DEBIT);

if (!$update_wallet) {
    throw new \Exception('Failed to debit wallet balance');
}
```

#### 2. **Missing Database Transaction Wrapping**
**Problem**: No atomic transaction handling - if something failed midway, database could be in inconsistent state.

**Fix Applied**: Wrapped entire transfer logic in DB transaction:
```php
DB::beginTransaction();
try {
    // 1. Check balance (with row lock)
    // 2. Make external API call
    // 3. Debit wallet
    // 4. Record transaction
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}
```

#### 3. **Race Condition Vulnerability**
**Problem**: Multiple simultaneous transfers could bypass balance checks.

**Fix**: `check_wallet_balance()` uses `lockForUpdate()` on wallet row, preventing concurrent access. Combined with DB transaction wrapping, ensures atomicity.

#### 4. **Replay Attack Vulnerability**
**Problem**: No validation to prevent reusing the same reference number.

**Fix Applied**: Added duplicate transaction check:
```php
$existingTxn = Transactions::where('customers_reference', $request->referenceNumber)
    ->where('user_id', $user->id)
    ->first();

if ($existingTxn) {
    return ApiHelper::problemResponse('Duplicate transaction reference. Please use a unique reference.', ...);
}
```

#### 5. **Enhanced Input Validation**
**Improvements**:
- Added max amount validation: `max:999999999`
- Enforced 4-digit PIN: `digits:4`
- Validated currency whitelist: `in:NGN,CAD`
- Added string length limit on reference: `max:255`

#### 6. **Better Error Handling**
- Used `$user` variable consistently (was using `auth()->user()` in some places)
- Added currency to log messages
- Better exception messages

---

## ⚠️ OTHER CONTROLLERS THAT NEED REVIEW

These controllers also use `check_wallet_balance()` and need to be verified to ensure they properly call `update_wallet()`:

### High Priority (Financial Transactions):

1. **TransferSandboxController** (3 methods)
   - `ngn_transfer()` - Line 50 ✅ Already calls update_wallet()
   - `ghs_transfer()` - Line 275 ❓ Needs verification
   - `send_interac()` - Line 387 ❓ Needs verification

2. **PagaBillersController** (5 methods)
   - Various bill payment methods - Lines 349, 430, 512, 626, 710
   - ❌ Need to check if they debit wallets after balance check

3. **RechargeController** (2 methods)
   - Lines 66, 173
   - ❌ Need to check if they debit wallets after balance check

4. **CableTvController**
   - Line 88
   - ❌ Need to check if they debit wallets after balance check

5. **ElectricityController**
   - Line 91
   - ❌ Need to check if they debit wallets after balance check

---

## 🔒 Security Best Practices Applied

### Transaction Flow (Correct Pattern):

```php
// 1. Validate input
$validator = Validator::make($request->all(), [...]);

// 2. Check for duplicate transactions (replay attack prevention)
$existingTxn = Transactions::where('customers_reference', $ref)->first();

// 3. Verify PIN
$check_pin = $this->handlePinVerification($user->id, $request->pin);

// 4. Start database transaction
DB::beginTransaction();

try {
    // 5. Check balance (with row lock to prevent race conditions)
    $check_balance = $this->check_wallet_balance($user->id, $currency, $amount);
    
    if ($check_balance) {
        // 6. Make external API call (transfer, bill payment, etc.)
        $result = $this->external_api_call($request);
        
        if ($result['success']) {
            // 7. CRITICAL: Debit the wallet
            $update_wallet = $this->update_wallet($user->id, $currency, $amount, ApiConstants::DEBIT);
            
            if (!$update_wallet) {
                throw new \Exception('Failed to debit wallet');
            }
            
            // 8. Record transaction in database
            $update_txn = $this->update_debit_transactions($user->id, $reference, $request);
            
            // 9. Commit transaction
            DB::commit();
            
            return success_response();
        }
    }
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}
```

### Security Checklist for Transfer Methods:

- [ ] Input validation with strict rules
- [ ] Duplicate transaction check (replay attack prevention)
- [ ] PIN verification
- [ ] Database transaction wrapping (atomicity)
- [ ] Balance check with row locking
- [ ] External API call
- [ ] **Explicit wallet debit with update_wallet()**
- [ ] Transaction recording
- [ ] Proper error handling and rollback
- [ ] Logging of all actions
- [ ] Email notifications

---

## 🧪 Testing Recommendations

### Test Cases for ngn_transfer:

1. **Normal Transfer**
   ```bash
   # Should succeed and debit wallet
   POST /api/transfer/ngn
   {
     "referenceNumber": "REF123456",
     "amount": 1000,
     "destinationBankUUID": "bank-uuid",
     "destinationBankAccountNumber": "0123456789",
     "accountHolderName": "John Doe",
     "pin": "1234",
     "currency": "NGN"
   }
   ```

2. **Insufficient Balance**
   ```bash
   # Should fail with "Insufficient funds"
   # Wallet should NOT be debited
   ```

3. **Duplicate Reference Number (Replay Attack)**
   ```bash
   # First request should succeed
   # Second request with same referenceNumber should fail
   # Wallet should only be debited once
   ```

4. **Invalid PIN**
   ```bash
   # Should fail immediately
   # Wallet should NOT be debited
   ```

5. **Race Condition Test**
   ```bash
   # Send 2 concurrent requests for same user
   # Only one should succeed
   # Balance should be debited exactly once
   ```

6. **API Failure Test**
   ```bash
   # When external API fails
   # Transaction should rollback
   # Wallet should NOT be debited
   ```

---

## 📋 Next Steps

### Immediate Actions:

1. ✅ **DONE**: Fixed ngn_transfer in TransferController
2. ⏭️ **TODO**: Review and fix PagaBillersController
3. ⏭️ **TODO**: Review and fix RechargeController
4. ⏭️ **TODO**: Review and fix CableTvController
5. ⏭️ **TODO**: Review and fix ElectricityController
6. ⏭️ **TODO**: Verify TransferSandboxController methods

### Database Audit:

```sql
-- Check for transactions without corresponding wallet debits
-- (transactions created but wallet balance unchanged)
SELECT t.id, t.user_id, t.amount, t.currency, t.created_at, t.status,
       w.ngn_balance, w.cad_balance
FROM transactions t
JOIN wallets w ON t.user_id = w.user_id
WHERE t.type = 'debit'
AND t.created_at > '2026-02-27 00:00:00'
ORDER BY t.created_at DESC;

-- Check for multiple transactions with same reference
SELECT customers_reference, COUNT(*) as count
FROM transactions
WHERE customers_reference IS NOT NULL
GROUP BY customers_reference
HAVING count > 1;
```

---

## 🔍 How to Check Other Controllers

Use this pattern to verify if a controller properly debits wallets:

```bash
# Search for the balance check
grep -n "check_wallet_balance" ControllerName.php

# Then check if there's a corresponding update_wallet call
grep -n "update_wallet.*DEBIT" ControllerName.php

# If update_wallet is NOT found, the controller has the same bug!
```

---

## 📞 Support

If any controller is found to be missing wallet debit calls, apply the same fix pattern:

1. Add DB::beginTransaction() at the start
2. Keep check_wallet_balance() call
3. Add update_wallet() call after successful external API call
4. Add DB::commit() at the end
5. Wrap in try-catch with DB::rollBack()

---

**Status**: ✅ TransferController::ngn_transfer() FIXED
**Remaining**: ⚠️ 12+ other methods need verification
