Bảo vệ API AI khỏi các mối đe dọa an ninh mạng không còn là lựa chọn — đó là yêu cầu bắt buộc. Với sự gia tăng đột biột của các cuộc tấn công vào hệ thống AI, việc cấu hình WAF (Web Application Firewall) đúng cách có thể giúp bạn tiết kiệm hàng nghìn đô la mỗi tháng và bảo vệ dữ liệu khách hàng. Trong bài viết này, tôi sẽ chia sẻ kinh nghiệm thực chiến từ việc triển khai WAF cho nhiều dự án AI, bao gồm cả cách tích hợp với HolySheep AI để đạt hiệu suất tối ưu.

Mục lục

Tại sao AI Services cần WAF đặc biệt?

AI API endpoints có những đặc điểm riêng biệt khiến chúng trở thành mục tiêu hấp dẫn cho kẻ tấn công:

Kiến trúc bảo mật đề xuất

Sơ đồ luồng request

Internet Request
      │
      ▼
┌─────────────────┐
│  Cloudflare/AWS │
│  WAF (Layer 7)  │
│  - Rate Limit   │
│  - Geo-block    │
│  - Bot Detect   │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  API Gateway    │
│  - Auth/JWT     │
│  - Input Valid  │
│  - Transform    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  HolySheep AI   │
│  Proxy Layer    │
│  - Token Count  │
│  - Caching      │
│  - Fallback     │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  AI Provider    │
│  (OpenAI/Claude)│
└─────────────────┘

Cấu hình WAF Rules chi tiết

1. Cloudflare WAF Rules cho AI API

(curl)

Cloudflare WAF - Tạo Custom Rule cho AI Endpoint Protection

Áp dụng tại Cloudflare Dashboard > Security > WAF > Custom Rules

Rule 1: Rate Limiting nghiêm ngặt cho /api/ai/*

cf.api.combined: (cf.threat_score gt 15) or (cf.waf.score eq "high") or (http.request.uri.path contains "/v1/chat/completions") or (http.request.uri.path contains "/v1/completions") or (http.request.uri.path contains "/api/ai")

Action: Challenge with CAPTCHA,天津 5 phút

Sensitivity: High

Rule 2: Block known malicious ASNs

Tại IP Access Rules:

ip.src ne 103.21.244.0/22 ip.src ne 104.16.0.0/13 ip.src ne 108.162.192.0/18

2. AWS WAF Rules (Terraform Configuration)

# terraform/aws_waf_ai_protection.tf

resource "aws_wafv2_web_acl" "ai_api_protection" {
  name        = "ai-api-protection"
  description = "WAF Rules bảo vệ AI API endpoints"
  scope       = "REGIONAL"
  
  rule {
    name     = "rate_limit_chat_completions"
    priority = 1
    
    statement {
      rate_based_statement {
        limit              = 100  # 100 requests/phút
        aggregate_key_type = "IP"
        
        scope_down_statement {
          byte_match_statement {
            search_string = "/v1/chat/completions"
            field_to_match {
              uri_path {}
            }
            text_transformations {
              priority = 1
              type     = "LOWERCASE"
            }
            positional_constraint = "CONTAINS"
            action                 = "BLOCK"
          }
        }
      }
    }
    
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "rateLimitChatCompletions"
      sampled_requests_enabled   = true
    }
  }
  
  rule {
    name     = "block_sql_injection_prompts"
    priority = 2
    
    statement {
      sqli_match_statement {
        field_to_match {
          json_body {
            required_statement {
              byte_match_statement {
                search_string = "UNION"
                field_to_match {
                  body {}
                }
                positional_constraint = "CONTAINS"
              }
            }
          }
        }
      }
    }
    
    action {
      block {
        custom_response {
          response_code            = 400
          custom_response_body_key = "sql_injection_block"
        }
      }
    }
  }
  
  default_action {
    allow {}
  }
}

3. HolySheep AI Integration với WAF

# holysheep_waf_integration.py
import requests
import time
from typing import Dict, Optional
from dataclasses import dataclass

@dataclass
class HolySheepConfig:
    api_key: str
    base_url: str = "https://api.holysheep.ai/v1"
    rate_limit_per_minute: int = 60
    timeout: int = 30

class HolySheepAIClient:
    """Client bảo mật với tích hợp WAF Rate Limiting"""
    
    def __init__(self, config: HolySheepConfig):
        self.config = config
        self.request_timestamps: list = []
        
    def _check_rate_limit(self) -> bool:
        """Kiểm tra rate limit trước khi gọi API"""
        current_time = time.time()
        # Loại bỏ timestamps cũ hơn 1 phút
        self.request_timestamps = [
            ts for ts in self.request_timestamps 
            if current_time - ts < 60
        ]
        
        if len(self.request_timestamps) >= self.config.rate_limit_per_minute:
            return False
        return True
    
    def _validate_prompt(self, prompt: str) -> tuple[bool, str]:
        """Sanitize prompt để ngăn Prompt Injection"""
        dangerous_patterns = [
            "ignore previous instructions",
            "ignore all previous",
            "system prompt",
            "you are now",
            "##instructions",
            "