跳轉到主要內容

Documentation Index

Fetch the complete documentation index at: https://docs.arouter.ai/llms.txt

Use this file to discover all available pages before exploring further.

定期輪換 API Key 可以降低金鑰洩露的影響範圍,並滿足許多安全合規要求。ARouter 的金鑰管理 API 支援零停機輪換。

輪換策略

最安全的輪換模式是先建立後刪除
  1. 建立一個與舊金鑰具有相同權限的新金鑰
  2. 將新金鑰部署到您的應用程式
  3. 驗證新金鑰是否正常運作
  4. 刪除舊金鑰
這樣可以確保零停機——在確認新金鑰正常運作之前,流量繼續使用舊金鑰。

第一步:建立新金鑰

使用金鑰管理 API 建立替換金鑰:
curl -X POST https://api.arouter.ai/v1/keys \
  -H "Authorization: Bearer lr_live_xxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "production-v2",
    "allowed_providers": ["openai", "anthropic", "google"],
    "spending_limit": 500.00
  }'
請立即儲存回傳的金鑰值 — ARouter 僅在建立時回傳完整金鑰一次。

第二步:更新您的應用程式

在部署環境中更新 AROUTER_API_KEY 環境變數(或對應的 Secret):
# 使用 .env 檔案範例
AROUTER_API_KEY=lr_live_new_key_here

# 更新 Kubernetes secret 範例
kubectl create secret generic arouter-credentials \
  --from-literal=api-key=lr_live_new_key_here \
  --dry-run=client -o yaml | kubectl apply -f -
重新部署或重啟應用程式以使新金鑰生效。

第三步:驗證新金鑰

在刪除舊金鑰之前,確認新金鑰正常運作:
curl https://api.arouter.ai/v1/models \
  -H "Authorization: Bearer lr_live_new_key_here"
檢查 ARouter 控制台,確認請求已出現在新金鑰下。

第四步:刪除舊金鑰

確認新金鑰正常運作後,使用舊金鑰 ID 將其刪除:
curl -X DELETE https://api.arouter.ai/v1/keys/key_oldid \
  -H "Authorization: Bearer lr_live_new_key_here"

自動輪換

對於高安全性環境,可以使用 CI/CD 系統或金鑰管理器按排程自動輪換:

GitHub Actions 範例

name: Rotate ARouter Key

on:
  schedule:
    - cron: '0 0 1 * *'  # 每月執行

jobs:
  rotate:
    runs-on: ubuntu-latest
    steps:
      - name: Create new key
        id: create
        run: |
          NEW_KEY=$(curl -s -X POST https://api.arouter.ai/v1/keys \
            -H "Authorization: Bearer ${{ secrets.AROUTER_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d '{"name": "production-auto-rotated"}' \
            | jq -r .key)
          echo "new_key=$NEW_KEY" >> $GITHUB_OUTPUT

      - name: Update secret
        uses: gliech/create-github-secret-action@v1
        with:
          name: AROUTER_API_KEY
          value: ${{ steps.create.outputs.new_key }}
          token: ${{ secrets.GH_TOKEN }}

列出活躍金鑰

列出所有活躍金鑰以稽核當前使用情況:
curl https://api.arouter.ai/v1/keys \
  -H "Authorization: Bearer lr_live_xxxx"
回應:
{
  "data": [
    {
      "id": "key_abc123",
      "name": "production-v2",
      "created_at": "2025-01-15T10:00:00Z",
      "last_used_at": "2025-04-01T08:30:00Z",
      "spending_limit": 500.00
    },
    {
      "id": "key_def456",
      "name": "staging",
      "created_at": "2025-03-01T09:00:00Z",
      "last_used_at": "2025-04-01T07:15:00Z",
      "spending_limit": 50.00
    }
  ]
}

最佳實踐

  • 定期輪換 — 對大多數應用程式而言,每月輪換是一個良好的基準
  • 疑似洩露後立即輪換 — 不要等到下次排程輪換
  • 使用描述性名稱 — 在金鑰名稱中包含版本或日期(如 production-2025-04production-v3
  • 設定消費限額 — 始終為生產金鑰配置 spending_limit 以控制風險敞口
  • 不同環境使用獨立金鑰 — 生產環境與預發布環境絕不共用同一金鑰
  • 定期稽核 — 每月檢查金鑰列表,刪除不再使用的金鑰
  • 將金鑰儲存在金鑰管理器中 — 使用 AWS Secrets Manager、HashiCorp Vault 或同類工具,而非版本控制中的 .env 檔案
完整金鑰管理指南請參閱金鑰管理,完整 API 參考請參閱金鑰管理 API