claude-code/claude-zh/rules/swift/security.md

34 lines
1.1 KiB
Markdown
Raw Permalink Normal View History

2026-02-27 13:45:37 +00:00
---
paths:
- "**/*.swift"
- "**/Package.swift"
---
# Swift 安全性 (Security)
> 本檔案擴展了 [common/security.md](../common/security.md),包含 Swift 特定內容。
## 金鑰管理 (Secret Management)
- 對於敏感數據 (Tokens, 密碼, 金鑰),請使用 **Keychain Services** — 絕對不要使用 `UserDefaults`
- 使用環境變數或 `.xcconfig` 檔案處理建置時的金鑰。
- 絕對不要在原始碼中硬編碼金鑰 — 反編譯工具可以輕易地擷取它們。
```swift
let apiKey = ProcessInfo.processInfo.environment["API_KEY"]
guard let apiKey, !apiKey.isEmpty else {
fatalError("未配置 API_KEY")
}
```
## 傳輸安全 (Transport Security)
- App Transport Security (ATS) 預設為強制執行 — 請勿將其停用。
- 針對關鍵端點 (Endpoints) 使用憑證固定 (Certificate pinning)。
- 驗證所有的伺服器憑證。
## 輸入驗證 (Input Validation)
- 在顯示之前清理所有使用者輸入,以防止注入。
- 使用 `URL(string:)` 搭配驗證,而非強制解包 (Force-unwrapping)。
- 在處理前驗證來自外部來源 (API, Deep links, 剪貼簿) 的數據。