# DDoS Protection Module

This module provides comprehensive protection against Distributed Denial of Service (DDoS) attacks by orchestrating multiple security components and analyzing traffic patterns, geographic anomalies, and request signatures.

## Architecture

The DDoS Protection Module follows a modular architecture with specialized components for different aspects of DDoS detection and mitigation:

### Core Components

- **DDoSProtectionEngine**: The main orchestrator that coordinates all components and produces a comprehensive threat assessment.
- **AdaptiveResponseSystem**: Executes appropriate responses based on the threat assessment.

### Analysis Components

- **ThreatLevelCalculator**: Calculates overall threat levels from multi-layer analysis results.
- **AttackPatternDetector**: Identifies specific attack patterns such as volumetric, protocol, application layer, distributed, and botnet attacks.
- **RequestAnalyzer**: Analyzes HTTP requests for suspicious patterns and bot signatures.
- **ServiceHealthAnalyzer**: Monitors service health using CircuitBreaker metrics to detect service degradation.
- **WafAnalysisAdapter**: Provides a unified interface for WAF analysis, supporting both the general WafEngine and the specialized DDoSWafLayer.

### Value Objects

- **DDoSAssessment**: Comprehensive assessment of a request's threat level, attack patterns, and confidence.
- **DDoSResponse**: Response actions to be taken based on the threat assessment.
- **ThreatLevel**: Enumeration of threat levels (LOW, MEDIUM, HIGH, CRITICAL).
- **AttackPattern**: Enumeration of attack patterns (VOLUMETRIC, PROTOCOL, APPLICATION_LAYER, DISTRIBUTED, BOTNET).

## Integration in Framework Lifecycle

### Current Integration

The DDoS Protection Module is currently integrated as a high-priority middleware in the HTTP request lifecycle:

```php
#[MiddlewarePriorityAttribute(MiddlewarePriority::SECURITY, 10)] // Higher than standard security
final readonly class DDoSProtectionMiddleware implements HttpMiddleware
```

This middleware:
1. Runs early in the request lifecycle (before other security middleware)
2. Analyzes incoming requests for DDoS patterns
3. Takes appropriate actions based on the threat level:
   - Critical threats: Immediately block with 429 status
   - High threats: Block or add security headers
   - Medium threats: Add monitoring headers
   - Low threats: Allow with logging

### Optimal Integration Point

**The current integration as a high-priority middleware is optimal** for the following reasons:

1. **Early Detection**: Running early in the request lifecycle allows for blocking malicious requests before they consume server resources.

2. **Access to Full Request**: The middleware has access to the complete HTTP request, including headers, path, and client IP, which are essential for accurate DDoS detection.

3. **Response Modification**: The middleware can modify responses by adding security headers or returning error responses for blocked requests.

4. **Separation of Concerns**: The middleware pattern keeps the DDoS protection logic separate from the core application logic.

5. **Configurable Priority**: The middleware priority can be adjusted if needed to run before or after other security middleware.

### Alternative Integration Points

While the current middleware integration is optimal, there are alternative integration points that could be considered in specific scenarios:

1. **Kernel-Level Integration**: For extremely high-traffic applications, integrating at the web server level (Nginx, Apache) could provide better performance but would limit the sophistication of detection.

2. **Event-Based Integration**: For applications with complex event systems, integrating as event listeners could provide more flexibility but might introduce latency.

3. **API Gateway Integration**: For microservice architectures, implementing DDoS protection at the API gateway level could centralize protection but might miss service-specific patterns.

## Usage

### Basic Usage

```php
// The DDoSProtectionEngine is typically injected into the DDoSProtectionMiddleware
$assessment = $ddosEngine->analyzeRequest($request);

// Check threat level
if ($assessment->isCriticalThreat()) {
    // Take immediate action
}

// Execute response
$response = $ddosEngine->executeResponse($assessment, $request);
```

### Configuration

The DDoS protection can be configured through the `WafConfig` class:

```php
// Enable/disable DDoS protection
$config->enableDdosProtection = true;

// Configure trusted IPs
$config->addTrustedIp('192.168.1.1');

// Configure exempt paths
$config->addExemptPath('/health-check');

// Get DDoS-specific configuration
$ddosConfig = $config->getDdosConfig();
```

## Performance Considerations

The DDoS Protection Module is designed to be efficient, but it does add some overhead to request processing. To minimize this overhead:

1. **Use Caching**: The module uses caching for expensive operations like geographic analysis.
2. **Configure Exempt Paths**: Exempt non-critical paths like health checks and static assets.
3. **Adjust Sensitivity**: Configure the threat thresholds based on your application's traffic patterns.
4. **Monitor Performance**: Use the built-in performance metrics to monitor the module's impact.

## Error Handling

The module includes comprehensive error handling to ensure that if any component fails, it doesn't block legitimate requests:

1. **Component-Level Recovery**: Each analysis component has its own error handling.
2. **Fallback Values**: If a component fails, fallback values are used to ensure the analysis continues.
3. **Middleware Protection**: The middleware catches all exceptions to prevent blocking legitimate requests.

## Future Improvements

Potential future improvements to the DDoS Protection Module:

1. **Machine Learning Integration**: Implement ML-based detection for more sophisticated attacks.
2. **Distributed Coordination**: Coordinate DDoS protection across multiple instances.
3. **Real-time Monitoring Dashboard**: Provide a real-time dashboard for monitoring DDoS attacks.
4. **Adaptive Thresholds**: Automatically adjust thresholds based on traffic patterns.
5. **Integration with External Services**: Integrate with cloud-based DDoS protection services.
