# API Security Hardening Recommendations

## Rate Limiting Strategy

### Implementation
```php
// Add to routes/api.php
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
    // API routes
});

// Role-based rate limiting
Route::middleware(['auth:sanctum', 'throttle:investor:100,1'])->prefix('investor')->group(function () {
    // Investor routes: 100 requests per minute
});

Route::middleware(['auth:sanctum', 'throttle:admin:200,1'])->prefix('admin')->group(function () {
    // Admin routes: 200 requests per minute
});
```

### Configure in config/cache.php
```php
'limits' => [
    'investor' => '100,1',  // 100 requests per minute
    'admin' => '200,1',     // 200 requests per minute
    'settlement' => '10,1', // 10 settlement requests per minute
],
```

## Settlement Endpoint Protection

### Additional Security Measures
1. **Idempotency Keys**: Require unique idempotency keys for settlement triggers
2. **Time Window**: Only allow settlement triggers within specific time windows
3. **Admin Only**: Settlement endpoints require admin role
4. **Audit Logging**: All settlement triggers logged with user ID
5. **Rate Limiting**: Strict rate limiting on settlement endpoints (10/minute)

### Implementation
```php
Route::middleware(['auth:sanctum', 'role:admin', 'throttle:settlement:10,1'])
    ->post('/admin/manual-settlement', [SettlementController::class, 'manualSettlement']);
```

## Internal MT5 Endpoint Security

### Current Protection
- API key validation in Mt5SyncController
- No authentication required (internal use)

### Recommendations
1. **IP Whitelist**: Restrict to known MT5 bridge server IPs
2. **HMAC Signature**: Add request signing with shared secret
3. **Timestamp Validation**: Reject requests older than 5 minutes
4. **Replay Attack Prevention**: Use nonce + timestamp

### Implementation Example
```php
// Add to Mt5SyncController
public function sync(Request $request)
{
    // 1. Validate IP whitelist
    if (!in_array($request->ip(), config('mt5.allowed_ips'))) {
        abort(403, 'IP not allowed');
    }

    // 2. Validate timestamp (prevent replay)
    $timestamp = $request->header('X-Timestamp');
    if (abs(time() - $timestamp) > 300) {
        abort(403, 'Request too old');
    }

    // 3. Validate HMAC signature
    $signature = $request->header('X-Signature');
    $expected = hash_hmac('sha256', $request->getContent(), config('mt5.shared_secret'));
    if (!hash_equals($expected, $signature)) {
        abort(403, 'Invalid signature');
    }

    // 4. Validate nonce (prevent replay)
    $nonce = $request->header('X-Nonce');
    if (Cache::has("nonce:{$nonce}")) {
        abort(403, 'Replay attack detected');
    }
    Cache::put("nonce:{$nonce}", true, 300);

    // Process sync...
}
```

## Replay Attack Prevention

### Strategy
1. **Nonce**: Unique identifier per request
2. **Timestamp**: Request must be fresh (within 5 minutes)
3. **Cache**: Store nonces for 5 minutes to detect duplicates
4. **HMAC**: Sign requests with shared secret

### Configuration
```php
// config/mt5.php
return [
    'allowed_ips' => env('MT5_ALLOWED_IPS', '127.0.0.1'),
    'shared_secret' => env('MT5_SHARED_SECRET'),
    'max_request_age' => 300, // 5 minutes
];
```

## Request Signing Recommendations

### For Mobile Apps
1. **API Key**: Each app installation gets unique API key
2. **Device Fingerprint**: Include device identifier
3. **Timestamp**: Request timestamp
4. **HMAC**: Sign request with device secret

### Implementation
```php
// Mobile app request signing
$payload = $timestamp . $method . $endpoint . json_encode($data);
$signature = hash_hmac('sha256', $payload, $device_secret);

$headers = [
    'X-API-Key' => $apiKey,
    'X-Timestamp' => $timestamp,
    'X-Signature' => $signature,
    'X-Device-ID' => $deviceId,
];
```

## Security Headers

### Add to app/Http/Middleware/TrustProxies.php
```php
protected $headers = Request::HEADER_X_FORWARDED_ALL;
```

### Add to public/.htaccess or Nginx config
```
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
```

## API Key Validation

### For MT5 Sync
```php
public function validateSyncRequest(array $data): bool
{
    $apiKey = $data['api_key'] ?? null;
    $expectedKey = config('mt5.api_key');

    if (!$apiKey || $apiKey !== $expectedKey) {
        Log::warning('Invalid MT5 API key', ['ip' => request()->ip()]);
        return false;
    }

    return true;
}
```

## CORS Configuration

### config/cors.php
```php
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
'allowed_origins' => env('CORS_ALLOWED_ORIGINS', '*'),
'allowed_headers' => ['Content-Type', 'Authorization', 'X-API-Key', 'X-Device-ID'],
'exposed_headers' => [],
'max_age' => 86400,
'supports_credentials' => true,
```

## Security Checklist

- [ ] Rate limiting configured per role
- [ ] Settlement endpoints have strict rate limiting
- [ ] MT5 sync endpoint has IP whitelist
- [ ] Request signing implemented for MT5 sync
- [ ] Replay attack prevention in place
- [ ] CORS configured appropriately
- [ ] Security headers set
- [ ] API key validation for internal endpoints
- [ ] Sanctum tokens have appropriate expiration
- [ ] HTTPS enforced in production
- [ ] Input validation on all endpoints
- [ ] SQL injection prevention (use Eloquent)
- [ ] XSS prevention (use Blade escaping)
- [ ] CSRF protection enabled
