在生產環境中,API 必須防止未授權訪問。我們使用簡易的 Token 驗證 模式。
# api/security.py
from fastapi import Request, HTTPException
from fastapi.security import APIKeyHeader
API_KEY = "secure-api-key"
api_key_header = APIKeyHeader(name="X-API-Key")
async def verify_token(request: Request, api_key: str = api_key_header):
    if api_key != API_KEY:
        raise HTTPException(status_code=403, detail="Unauthorized")
在主應用中引入:
python
複製程式碼
# app.py
from fastapi import Depends
from security import verify_token
@app.post("/analyze", dependencies=[Depends(verify_token)])
async def analyze_text(data: AnalyzeIn):
    ...
測試請求:
bash
複製程式碼
curl -X POST http://127.0.0.1:8000/analyze \
-H "Content-Type: application/json" \
-H "X-API-Key: secure-api-key" \
-d '{"text": "Verify your account now: https://bit.ly/test"}'
2.2 CORS 與 Rate Limiting
加入跨域允許來源限制與請求速率限制,防止惡意刷 API。
python
複製程式碼
# app.py
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from fastapi.responses import JSONResponse
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://myfrontend.com"],  # 僅允許可信來源
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.exception_handler(RateLimitExceeded)
def rate_limit_handler(request, exc):
    return JSONResponse(status_code=429, content={"error": "Too Many Requests"})
@app.get("/status")
@limiter.limit("10/minute")
async def status_check():
    return {"status": "ok"}
2.3 加入 WAF 防火牆層
可使用 ModSecurity + Nginx 結合作為應用層防火牆,攔截常見攻擊(XSS、SQL Injection、Command Injection 等)。
nginx.conf:
nginx
複製程式碼
load_module modules/ngx_http_modsecurity_module.so;
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/modsecurity.conf;
server {
    listen 80;
    server_name myapi.com;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
    }
}
modsecurity.conf:
swift
複製程式碼
Include /usr/local/modsecurity/crs/crs-setup.conf
Include /usr/local/modsecurity/crs/rules/*.conf
三、自動化更新與回饋系統
3.1 使用者回饋收集
我們讓前端 widget 加入簡單的「回報」功能,讓使用者標記判斷是否正確。
javascript
複製程式碼
function showModal(message, riskLevel, onContinue){
  ...
  const feedbackDiv = document.createElement('div');
  feedbackDiv.innerHTML = `
    <p>此判定正確嗎?</p>
    <button id="fb_yes">✅ 正確</button>
    <button id="fb_no">❌ 錯誤</button>
  `;
  document.getElementById("__phish_widget_modal").appendChild(feedbackDiv);
  document.getElementById("fb_yes").onclick = ()=> fetch(API_BASE+"/feedback",{method:"POST",body:JSON.stringify({result:true})});
  document.getElementById("fb_no").onclick = ()=> fetch(API_BASE+"/feedback",{method:"POST",body:JSON.stringify({result:false})});
}
3.2 後端回饋記錄
在 FastAPI 新增 /feedback 端點:
python
複製程式碼
@app.post("/feedback")
async def feedback(result: bool = Form(...)):
    with open("feedback.log", "a") as f:
        f.write(f"{datetime.now()}: {result}\n")
    return {"message": "Feedback received"}
3.3 模型再訓練排程(Cron Job)
設定排程每週自動再訓練模型,整合新回饋數據。
retrain.py
python
複製程式碼
import joblib, pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
def retrain():
    df = pd.read_csv("training_data.csv")
    model = LogisticRegression(max_iter=1000)
    X = CountVectorizer().fit_transform(df['text'])
    y = df['label']
    model.fit(X, y)
    joblib.dump(model, "phishing_model.pkl")
設定自動排程:
bash
複製程式碼
crontab -e
# 每週一凌晨 3 點重新訓練模型
0 3 * * 1 /usr/bin/python3 /app/retrain.py
四、整合式監控儀表板(Central Dashboard)
4.1 架構
使用 Grafana + ELK Stack(Elasticsearch, Logstash, Kibana) 來建立可視化儀表板:
Elasticsearch:儲存與索引日誌資料。
Logstash:收集 FastAPI 應用與伺服器的日誌。
Kibana:用於視覺化與查詢。
Grafana:整合多種數據源(Prometheus + Elastic)建立綜合控制面板。
4.2 Dashboard 指標
每分鐘請求數量 (Requests per minute)
平均 API 延遲時間 (Average Latency)
高風險 URL 比例 (High-Risk URL Rate)
模型準確率 (Model Accuracy by Feedback)
異常警報(若錯誤率 > 5% 則發 Slack/Email 通知)
Kibana 可以設置自動化報告與警報(Watcher):
json
複製程式碼
{
  "trigger": { "schedule": { "interval": "10m" } },
  "condition": { "script": { "source": "ctx.payload.hits.total > 100" } },
  "actions": {
    "email_admin": {
      "email": {
        "to": "admin@securitylab.com",
        "subject": "Phishing Alerts >100",
        "body": "超過100筆可疑行為被偵測,請檢查系統。"
      }
    }
  }
}
五、生產部署規範(Production Checklist)
類別	項目	狀態
安全	API Token 驗證	✅
安全	CORS 限制	✅
安全	Rate Limit 防刷	✅
系統	自動化回饋與再訓練	✅
系統	Docker 容器化與 K8s 支援	✅
維運	日誌與監控儀表板	✅
維運	錯誤與性能警報機制	✅
維運	每週模型再訓練 Cron	✅
六、後續延伸與研究方向
AI 模型強化學習:導入強化學習(Reinforcement Learning)來優化模型決策。
社交工程情境模擬:開發虛擬釣魚訓練平台(類似 Gophish),用於員工訓練。
隱私保護強化:使用差分隱私(Differential Privacy)技術,確保模型訓練過程中不洩露個資。
多雲部署(Multi-cloud):將服務同時部署於 AWS、GCP、Azure,以提高容錯性與可用性。