# Traefik Dynamic Configuration
# Middleware definitions for security and rate limiting

http:
  middlewares:
    # Security headers middleware
    security-headers:
      headers:
        # Security headers
        frameDeny: true
        sslRedirect: true
        browserXssFilter: true
        contentTypeNosniff: true
        forceSTSHeader: true
        stsIncludeSubdomains: true
        stsPreload: true
        stsSeconds: 31536000
        customFrameOptionsValue: "SAMEORIGIN"
        customRequestHeaders:
          X-Forwarded-Proto: "https"
        customResponseHeaders:
          X-Robots-Tag: "none"
          X-Content-Type-Options: "nosniff"
          X-Frame-Options: "SAMEORIGIN"
          X-XSS-Protection: "1; mode=block"
          Referrer-Policy: "strict-origin-when-cross-origin"
          Permissions-Policy: "camera=(), microphone=(), geolocation=()"
    
    # Rate limiting middleware
    rate-limit:
      rateLimit:
        burst: 100
        average: 50
        period: "1s"
    
    # Authentication middleware (basic auth)
    auth:
      basicAuth:
        users:
          - "admin:$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"  # password: password
        usersFile: "/etc/traefik/users"
        removeHeader: true
    
    # CORS middleware
    cors:
      headers:
        accessControlAllowMethods:
          - "GET"
          - "POST"
          - "PUT"
          - "DELETE"
          - "OPTIONS"
        accessControlAllowHeaders:
          - "Content-Type"
          - "Authorization"
          - "X-Requested-With"
        accessControlAllowOriginList:
          - "https://yourdomain.com"
          - "https://*.yourdomain.com"
        accessControlMaxAge: 86400
        addVaryHeader: true
    
    # IP whitelist middleware
    ip-whitelist:
      ipWhiteList:
        sourceRange:
          - "192.168.50.0/24"  # Local network
          - "100.64.0.0/10"    # Tailscale network
        ipStrategy:
          depth: 1
          excludedIPs:
            - "127.0.0.1"
    
    # Compression middleware
    compression:
      compress:
        excludedContentTypes:
          - "text/event-stream"
    
    # Strip prefix middleware
    strip-prefix:
      stripPrefix:
        prefixes:
          - "/api"
    
    # Add prefix middleware
    add-prefix:
      addPrefix:
        prefix: "/api"
    
    # Circuit breaker middleware
    circuit-breaker:
      circuitBreaker:
        expression: "NetworkErrorRatio() > 0.5"
    
    # Retry middleware
    retry:
      retry:
        attempts: 3
        initialInterval: "100ms"
    
    # Forward auth middleware
    forward-auth:
      forwardAuth:
        address: "http://auth-service:8080/auth"
        trustForwardHeader: true
        authResponseHeaders:
          - "X-User"
          - "X-Email"
    
    # Load balancing middleware
    load-balancer:
      loadBalancer:
        method: "wrr"
        healthCheck:
          path: "/health"
          interval: "10s"
          timeout: "5s"
    
    # Cache middleware
    cache:
      headers:
        customRequestHeaders:
          X-Cache-Key: "{{ .Host }}{{ .Path }}"
        customResponseHeaders:
          X-Cache-Status: "{{ .CacheStatus }}"
    
    # Metrics middleware
    metrics:
      prometheus:
        buckets:
          - 0.1
          - 0.3
          - 1.2
          - 5.0
        addEntryPointsLabels: true
        addServicesLabels: true
        entryPoint: "metrics"
    
    # Logging middleware
    logging:
      plugin:
        name: "logging"
        config:
          level: "INFO"
          format: "json"
          output: "stdout"
    
    # Error pages middleware
    error-pages:
      errors:
        status:
          - "400-499"
          - "500-599"
        service: "error-service"
        query: "/error/{status}"
    
    # Health check middleware
    health-check:
      healthCheck:
        path: "/health"
        interval: "30s"
        timeout: "5s"
        headers:
          User-Agent: "Traefik Health Check"
    
    # Maintenance mode middleware
    maintenance:
      headers:
        customResponseHeaders:
          Retry-After: "3600"
          X-Maintenance-Mode: "true"
    
    # API gateway middleware
    api-gateway:
      headers:
        customRequestHeaders:
          X-API-Version: "v1"
          X-Client-ID: "{{ .ClientIP }}"
        customResponseHeaders:
          X-API-Limit: "{{ .Limit }}"
          X-API-Remaining: "{{ .Remaining }}"
    
    # WebSocket middleware
    websocket:
      headers:
        customRequestHeaders:
          Upgrade: "websocket"
          Connection: "upgrade"
    
    # File upload middleware
    file-upload:
      headers:
        customRequestHeaders:
          Content-Type: "multipart/form-data"
        customResponseHeaders:
          X-Upload-Size: "{{ .UploadSize }}"
    
    # Mobile optimization middleware
    mobile-optimization:
      headers:
        customResponseHeaders:
          Vary: "User-Agent"
          X-Mobile-Optimized: "true"
    
    # SEO middleware
    seo:
      headers:
        customResponseHeaders:
          X-Robots-Tag: "index, follow"
          X-Sitemap-Location: "https://yourdomain.com/sitemap.xml"
    
    # Security scan middleware
    security-scan:
      headers:
        customRequestHeaders:
          X-Security-Scan: "true"
        customResponseHeaders:
          X-Security-Headers: "enabled"
    
    # Performance monitoring middleware
    performance:
      headers:
        customResponseHeaders:
          X-Response-Time: "{{ .ResponseTime }}"
          X-Processing-Time: "{{ .ProcessingTime }}"
    
    # A/B testing middleware
    ab-testing:
      headers:
        customRequestHeaders:
          X-AB-Test: "{{ .ABTest }}"
        customResponseHeaders:
          X-AB-Variant: "{{ .ABVariant }}"
    
    # Geolocation middleware
    geolocation:
      headers:
        customRequestHeaders:
          X-Client-Country: "{{ .ClientCountry }}"
          X-Client-City: "{{ .ClientCity }}"
    
    # Device detection middleware
    device-detection:
      headers:
        customRequestHeaders:
          X-Device-Type: "{{ .DeviceType }}"
          X-Device-OS: "{{ .DeviceOS }}"
    
    # User agent middleware
    user-agent:
      headers:
        customRequestHeaders:
          X-User-Agent: "{{ .UserAgent }}"
    
    # Request ID middleware
    request-id:
      headers:
        customRequestHeaders:
          X-Request-ID: "{{ .RequestID }}"
        customResponseHeaders:
          X-Request-ID: "{{ .RequestID }}"
    
    # Correlation ID middleware
    correlation-id:
      headers:
        customRequestHeaders:
          X-Correlation-ID: "{{ .CorrelationID }}"
        customResponseHeaders:
          X-Correlation-ID: "{{ .CorrelationID }}"
    
    # Session middleware
    session:
      headers:
        customRequestHeaders:
          X-Session-ID: "{{ .SessionID }}"
        customResponseHeaders:
          Set-Cookie: "session={{ .SessionID }}; HttpOnly; Secure; SameSite=Strict"
    
    # API versioning middleware
    api-versioning:
      headers:
        customRequestHeaders:
          X-API-Version: "{{ .APIVersion }}"
        customResponseHeaders:
          X-API-Version: "{{ .APIVersion }}"
    
    # Feature flags middleware
    feature-flags:
      headers:
        customRequestHeaders:
          X-Feature-Flags: "{{ .FeatureFlags }}"
        customResponseHeaders:
          X-Feature-Flags: "{{ .FeatureFlags }}"
    
    # Debug middleware
    debug:
      headers:
        customRequestHeaders:
          X-Debug: "true"
        customResponseHeaders:
          X-Debug-Info: "{{ .DebugInfo }}"
    
    # Maintenance bypass middleware
    maintenance-bypass:
      headers:
        customRequestHeaders:
          X-Maintenance-Bypass: "{{ .MaintenanceBypass }}"
    
    # Load testing middleware
    load-testing:
      headers:
        customRequestHeaders:
          X-Load-Test: "{{ .LoadTest }}"
        customResponseHeaders:
          X-Load-Test-Response: "{{ .LoadTestResponse }}"
    
    # Monitoring middleware
    monitoring:
      headers:
        customRequestHeaders:
          X-Monitoring: "true"
        customResponseHeaders:
          X-Monitoring-Data: "{{ .MonitoringData }}"
    
    # Analytics middleware
    analytics:
      headers:
        customRequestHeaders:
          X-Analytics: "{{ .Analytics }}"
        customResponseHeaders:
          X-Analytics-Data: "{{ .AnalyticsData }}"
    
    # Backup middleware
    backup:
      headers:
        customRequestHeaders:
          X-Backup: "{{ .Backup }}"
        customResponseHeaders:
          X-Backup-Status: "{{ .BackupStatus }}"
    
    # Migration middleware
    migration:
      headers:
        customRequestHeaders:
          X-Migration: "{{ .Migration }}"
        customResponseHeaders:
          X-Migration-Status: "{{ .MigrationStatus }}"
