docs: 完成所有文档的中文翻译并应用到项目

This commit is contained in:
xuxiang
2026-01-28 00:12:54 +08:00
parent 0ced59a26b
commit e133f58e1c
76 changed files with 6808 additions and 6170 deletions

View File

@@ -1,64 +1,64 @@
---
name: security-review
description: Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist and patterns.
description: 当添加身份认证authentication、处理用户输入、使用凭据secrets、创建 API 端点或实现支付/敏感功能时,请使用此技能。提供全面的安全检查清单和模式。
---
# Security Review Skill
# 安全审查技能 (Security Review Skill)
This skill ensures all code follows security best practices and identifies potential vulnerabilities.
此技能确保所有代码遵循安全最佳实践,并识别潜在的漏洞。
## When to Activate
## 何时激活
- Implementing authentication or authorization
- Handling user input or file uploads
- Creating new API endpoints
- Working with secrets or credentials
- Implementing payment features
- Storing or transmitting sensitive data
- Integrating third-party APIs
- 实现身份认证(authentication)或授权(authorization)时
- 处理用户输入或文件上传时
- 创建新的 API 端点时
- 处理凭据(secrets)或证书(credentials)时
- 实现支付功能时
- 存储或传输敏感数据时
- 集成第三方 API
## Security Checklist
## 安全检查清单
### 1. Secrets Management
### 1. 凭据管理 (Secrets Management)
#### ❌ NEVER Do This
#### ❌ 严禁这样做
```typescript
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
const apiKey = "sk-proj-xxxxx" // 硬编码凭据
const dbPassword = "password123" // 在源代码中
```
#### ✅ ALWAYS Do This
#### ✅ 务必这样做
```typescript
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
// Verify secrets exist
// 验证凭据是否存在
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
```
#### Verification Steps
- [ ] No hardcoded API keys, tokens, or passwords
- [ ] All secrets in environment variables
- [ ] `.env.local` in .gitignore
- [ ] No secrets in git history
- [ ] Production secrets in hosting platform (Vercel, Railway)
#### 验证步骤
- [ ] 不存在硬编码的 API 密钥、令牌tokens或密码
- [ ] 所有凭据均存储在环境变量中
- [ ] `.env.local` 已包含在 .gitignore
- [ ] Git 历史记录中没有凭据
- [ ] 生产环境凭据配置在托管平台(如 Vercel, Railway
### 2. Input Validation
### 2. 输入校验 (Input Validation)
#### Always Validate User Input
#### 始终校验用户输入
```typescript
import { z } from 'zod'
// Define validation schema
// 定义校验模式 (Schema)
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150)
})
// Validate before processing
// 在处理前校验
export async function createUser(input: unknown) {
try {
const validated = CreateUserSchema.parse(input)
@@ -72,22 +72,22 @@ export async function createUser(input: unknown) {
}
```
#### File Upload Validation
#### 文件上传校验
```typescript
function validateFileUpload(file: File) {
// Size check (5MB max)
// 大小检查 (最大 5MB)
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error('File too large (max 5MB)')
}
// Type check
// 类型检查
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type')
}
// Extension check
// 后缀检查
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
if (!extension || !allowedExtensions.includes(extension)) {
@@ -98,59 +98,59 @@ function validateFileUpload(file: File) {
}
```
#### Verification Steps
- [ ] All user inputs validated with schemas
- [ ] File uploads restricted (size, type, extension)
- [ ] No direct use of user input in queries
- [ ] Whitelist validation (not blacklist)
- [ ] Error messages don't leak sensitive info
#### 验证步骤
- [ ] 所有用户输入均通过模式(schemas)校验
- [ ] 限制文件上传(大小、类型、后缀)
- [ ] 不在查询中直接使用原始用户输入
- [ ] 使用白名单校验(而非黑名单)
- [ ] 错误消息不泄露敏感信息
### 3. SQL Injection Prevention
### 3. SQL 注入防护 (SQL Injection Prevention)
#### ❌ NEVER Concatenate SQL
#### ❌ 严禁拼接 SQL 字符串
```typescript
// DANGEROUS - SQL Injection vulnerability
// 危险 - 存在 SQL 注入漏洞
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
```
#### ✅ ALWAYS Use Parameterized Queries
#### ✅ 始终使用参数化查询
```typescript
// Safe - parameterized query
// 安全 - 参数化查询
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
// Or with raw SQL
// 或者使用原生 SQL
await db.query(
'SELECT * FROM users WHERE email = $1',
[userEmail]
)
```
#### Verification Steps
- [ ] All database queries use parameterized queries
- [ ] No string concatenation in SQL
- [ ] ORM/query builder used correctly
- [ ] Supabase queries properly sanitized
#### 验证步骤
- [ ] 所有数据库查询均使用参数化查询
- [ ] SQL 中没有字符串拼接
- [ ] 正确使用 ORM 或查询构建器query builder
- [ ] Supabase 查询已正确清理(sanitized
### 4. Authentication & Authorization
### 4. 认证与授权 (Authentication & Authorization)
#### JWT Token Handling
#### JWT 令牌处理
```typescript
// ❌ WRONG: localStorage (vulnerable to XSS)
// ❌ 错误:使用 localStorage (易受 XSS 攻击)
localStorage.setItem('token', token)
// ✅ CORRECT: httpOnly cookies
// ✅ 正确:使用 httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
```
#### Authorization Checks
#### 授权检查
```typescript
export async function deleteUser(userId: string, requesterId: string) {
// ALWAYS verify authorization first
// 始终先验证授权
const requester = await db.users.findUnique({
where: { id: requesterId }
})
@@ -162,41 +162,41 @@ export async function deleteUser(userId: string, requesterId: string) {
)
}
// Proceed with deletion
// 执行删除
await db.users.delete({ where: { id: userId } })
}
```
#### Row Level Security (Supabase)
#### 行级安全性 (Supabase RLS)
```sql
-- Enable RLS on all tables
-- 在所有表上启用 RLS
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- Users can only view their own data
-- 用户只能查看自己的数据
CREATE POLICY "Users view own data"
ON users FOR SELECT
USING (auth.uid() = id);
-- Users can only update their own data
-- 用户只能更新自己的数据
CREATE POLICY "Users update own data"
ON users FOR UPDATE
USING (auth.uid() = id);
```
#### Verification Steps
- [ ] Tokens stored in httpOnly cookies (not localStorage)
- [ ] Authorization checks before sensitive operations
- [ ] Row Level Security enabled in Supabase
- [ ] Role-based access control implemented
- [ ] Session management secure
#### 验证步骤
- [ ] 令牌存储在 httpOnly cookies 中(而非 localStorage
- [ ] 在敏感操作前进行授权检查
- [ ] 在 Supabase 中启用了行级安全性Row Level Security
- [ ] 实现了基于角色的访问控制RBAC
- [ ] 会话管理(Session management)安全
### 5. XSS Prevention
### 5. XSS 防护 (XSS Prevention)
#### Sanitize HTML
#### 清理 HTML
```typescript
import DOMPurify from 'isomorphic-dompurify'
// ALWAYS sanitize user-provided HTML
// 始终清理用户提供的 HTML
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
@@ -206,7 +206,7 @@ function renderUserContent(html: string) {
}
```
#### Content Security Policy
#### 内容安全策略 (CSP)
```typescript
// next.config.js
const securityHeaders = [
@@ -224,15 +224,15 @@ const securityHeaders = [
]
```
#### Verification Steps
- [ ] User-provided HTML sanitized
- [ ] CSP headers configured
- [ ] No unvalidated dynamic content rendering
- [ ] React's built-in XSS protection used
#### 验证步骤
- [ ] 已清理用户提供的 HTML
- [ ] 配置了 CSP 响应头
- [ ] 没有未经校验的动态内容渲染
- [ ] 使用了 React 内置的 XSS 防护机制
### 6. CSRF Protection
### 6. CSRF 防护 (CSRF Protection)
#### CSRF Tokens
#### CSRF 令牌
```typescript
import { csrf } from '@/lib/csrf'
@@ -246,7 +246,7 @@ export async function POST(request: Request) {
)
}
// Process request
// 处理请求
}
```
@@ -256,61 +256,61 @@ res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
```
#### Verification Steps
- [ ] CSRF tokens on state-changing operations
- [ ] SameSite=Strict on all cookies
- [ ] Double-submit cookie pattern implemented
#### 验证步骤
- [ ] 对状态变更操作使用了 CSRF 令牌
- [ ] 所有 cookies 均设置了 SameSite=Strict
- [ ] 实现了双重提交 cookie 模式double-submit cookie pattern
### 7. Rate Limiting
### 7. 速率限制 (Rate Limiting)
#### API Rate Limiting
#### API 速率限制
```typescript
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
windowMs: 15 * 60 * 1000, // 15 分钟
max: 100, // 每个窗口 100 次请求
message: 'Too many requests'
})
// Apply to routes
// 应用到路由
app.use('/api/', limiter)
```
#### Expensive Operations
#### 高消耗操作
```typescript
// Aggressive rate limiting for searches
// 对搜索操作执行更严格的速率限制
const searchLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 10 requests per minute
windowMs: 60 * 1000, // 1 分钟
max: 10, // 每分钟 10 次请求
message: 'Too many search requests'
})
app.use('/api/search', searchLimiter)
```
#### Verification Steps
- [ ] Rate limiting on all API endpoints
- [ ] Stricter limits on expensive operations
- [ ] IP-based rate limiting
- [ ] User-based rate limiting (authenticated)
#### 验证步骤
- [ ] 在所有 API 端点上启用了速率限制
- [ ] 对高消耗操作执行更严格的限制
- [ ] 基于 IP 的速率限制
- [ ] 基于用户的速率限制(已认证用户)
### 8. Sensitive Data Exposure
### 8. 敏感数据泄露 (Sensitive Data Exposure)
#### Logging
#### 日志记录
```typescript
// ❌ WRONG: Logging sensitive data
// ❌ 错误:记录敏感数据
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })
// ✅ CORRECT: Redact sensitive data
// ✅ 正确:脱敏敏感数据
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })
```
#### Error Messages
#### 错误消息
```typescript
// ❌ WRONG: Exposing internal details
// ❌ 错误:暴露内部细节
catch (error) {
return NextResponse.json(
{ error: error.message, stack: error.stack },
@@ -318,7 +318,7 @@ catch (error) {
)
}
// ✅ CORRECT: Generic error messages
// ✅ 正确:通用的错误消息
catch (error) {
console.error('Internal error:', error)
return NextResponse.json(
@@ -328,15 +328,15 @@ catch (error) {
}
```
#### Verification Steps
- [ ] No passwords, tokens, or secrets in logs
- [ ] Error messages generic for users
- [ ] Detailed errors only in server logs
- [ ] No stack traces exposed to users
#### 验证步骤
- [ ] 日志中不含密码、令牌或凭据
- [ ] 向用户展示通用的错误消息
- [ ] 仅在服务器日志中记录详细错误
- [ ] 不向用户暴露堆栈轨迹(stack traces
### 9. Blockchain Security (Solana)
### 9. 区块链安全 (Solana)
#### Wallet Verification
#### 钱包验证
```typescript
import { verify } from '@solana/web3.js'
@@ -358,20 +358,20 @@ async function verifyWalletOwnership(
}
```
#### Transaction Verification
#### 交易验证
```typescript
async function verifyTransaction(transaction: Transaction) {
// Verify recipient
// 验证收款人
if (transaction.to !== expectedRecipient) {
throw new Error('Invalid recipient')
}
// Verify amount
// 验证金额
if (transaction.amount > maxAmount) {
throw new Error('Amount exceeds limit')
}
// Verify user has sufficient balance
// 验证用户余额是否充足
const balance = await getBalance(transaction.from)
if (balance < transaction.amount) {
throw new Error('Insufficient balance')
@@ -381,56 +381,56 @@ async function verifyTransaction(transaction: Transaction) {
}
```
#### Verification Steps
- [ ] Wallet signatures verified
- [ ] Transaction details validated
- [ ] Balance checks before transactions
- [ ] No blind transaction signing
#### 验证步骤
- [ ] 验证了钱包签名
- [ ] 校验了交易详情
- [ ] 交易前进行余额检查
- [ ] 不存在盲签blind signing)交易
### 10. Dependency Security
### 10. 依赖项安全 (Dependency Security)
#### Regular Updates
#### 定期更新
```bash
# Check for vulnerabilities
# 检查漏洞
npm audit
# Fix automatically fixable issues
# 自动修复可修复的问题
npm audit fix
# Update dependencies
# 更新依赖
npm update
# Check for outdated packages
# 检查过期的包
npm outdated
```
#### Lock Files
#### 锁定文件 (Lock Files)
```bash
# ALWAYS commit lock files
# 始终提交 lock 文件
git add package-lock.json
# Use in CI/CD for reproducible builds
npm ci # Instead of npm install
# CI/CD 中使用以确保可重现的构建
npm ci # 而非 npm install
```
#### Verification Steps
- [ ] Dependencies up to date
- [ ] No known vulnerabilities (npm audit clean)
- [ ] Lock files committed
- [ ] Dependabot enabled on GitHub
- [ ] Regular security updates
#### 验证步骤
- [ ] 依赖项保持最新
- [ ] 无已知漏洞(npm audit clean
- [ ] 已提交 lock 文件
- [ ] 在 GitHub 上启用了 Dependabot
- [ ] 定期执行安全更新
## Security Testing
## 安全测试
### Automated Security Tests
### 自动化安全测试
```typescript
// Test authentication
// 测试身份认证
test('requires authentication', async () => {
const response = await fetch('/api/protected')
expect(response.status).toBe(401)
})
// Test authorization
// 测试授权
test('requires admin role', async () => {
const response = await fetch('/api/admin', {
headers: { Authorization: `Bearer ${userToken}` }
@@ -438,7 +438,7 @@ test('requires admin role', async () => {
expect(response.status).toBe(403)
})
// Test input validation
// 测试输入校验
test('rejects invalid input', async () => {
const response = await fetch('/api/users', {
method: 'POST',
@@ -447,7 +447,7 @@ test('rejects invalid input', async () => {
expect(response.status).toBe(400)
})
// Test rate limiting
// 测试速率限制
test('enforces rate limits', async () => {
const requests = Array(101).fill(null).map(() =>
fetch('/api/endpoint')
@@ -460,35 +460,35 @@ test('enforces rate limits', async () => {
})
```
## Pre-Deployment Security Checklist
## 部署前安全检查清单
Before ANY production deployment:
在**任何**生产环境部署之前:
- [ ] **Secrets**: No hardcoded secrets, all in env vars
- [ ] **Input Validation**: All user inputs validated
- [ ] **SQL Injection**: All queries parameterized
- [ ] **XSS**: User content sanitized
- [ ] **CSRF**: Protection enabled
- [ ] **Authentication**: Proper token handling
- [ ] **Authorization**: Role checks in place
- [ ] **Rate Limiting**: Enabled on all endpoints
- [ ] **HTTPS**: Enforced in production
- [ ] **Security Headers**: CSP, X-Frame-Options configured
- [ ] **Error Handling**: No sensitive data in errors
- [ ] **Logging**: No sensitive data logged
- [ ] **Dependencies**: Up to date, no vulnerabilities
- [ ] **Row Level Security**: Enabled in Supabase
- [ ] **CORS**: Properly configured
- [ ] **File Uploads**: Validated (size, type)
- [ ] **Wallet Signatures**: Verified (if blockchain)
- [ ] **凭据 (Secrets)**:无硬编码凭据,全部位于环境变量中
- [ ] **输入校验**:所有用户输入均已校验
- [ ] **SQL 注入**:所有查询均已参数化
- [ ] **XSS**:用户内容已清理
- [ ] **CSRF**:防护已启用
- [ ] **身份认证**:正确的令牌处理
- [ ] **授权**:角色检查已就位
- [ ] **速率限制**:在所有端点上启用
- [ ] **HTTPS**:在生产环境中强制执行
- [ ] **安全响应头**:已配置 CSP, X-Frame-Options
- [ ] **错误处理**:错误信息中无敏感数据
- [ ] **日志记录**:日志中无敏感数据
- [ ] **依赖项**:已更新且无漏洞
- [ ] **行级安全性**:在 Supabase 中启用
- [ ] **CORS**:已正确配置
- [ ] **文件上传**:已校验(大小、类型)
- [ ] **钱包签名**:已验证(如果是区块链项目)
## Resources
## 资源
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Next.js Security](https://nextjs.org/docs/security)
- [Supabase Security](https://supabase.com/docs/guides/auth)
- [Next.js 安全指南](https://nextjs.org/docs/security)
- [Supabase 安全指南](https://supabase.com/docs/guides/auth)
- [Web Security Academy](https://portswigger.net/web-security)
---
**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
**请记住**:安全并非可选项。一个漏洞就可能危害整个平台。如有疑虑,请宁可信其有,从严处理。

View File

@@ -1,49 +1,49 @@
| name | description |
|------|-------------|
| cloud-infrastructure-security | Use this skill when deploying to cloud platforms, configuring infrastructure, managing IAM policies, setting up logging/monitoring, or implementing CI/CD pipelines. Provides cloud security checklist aligned with best practices. |
| cloud-infrastructure-security | 当部署到云平台、配置基础设施、管理 IAM 策略、设置日志/监控或实现 CI/CD 流水线时,请使用此技能。提供符合最佳实践的云安全检查清单。 |
# Cloud & Infrastructure Security Skill
# 云与基础设施安全技能 (Cloud & Infrastructure Security Skill)
This skill ensures cloud infrastructure, CI/CD pipelines, and deployment configurations follow security best practices and comply with industry standards.
此技能旨在确保云基础设施、CI/CD 流水线(CI/CD Pipeline)和部署配置遵循安全最佳实践,并符合行业标准。
## When to Activate
## 何时激活
- Deploying applications to cloud platforms (AWS, Vercel, Railway, Cloudflare)
- Configuring IAM roles and permissions
- Setting up CI/CD pipelines
- Implementing infrastructure as code (Terraform, CloudFormation)
- Configuring logging and monitoring
- Managing secrets in cloud environments
- Setting up CDN and edge security
- Implementing disaster recovery and backup strategies
- 将应用程序部署到云平台(AWS, Vercel, Railway, Cloudflare
- 配置身份与访问管理IAM角色和权限
- 设置 CI/CD 流水线(CI/CD Pipeline
- 实现基础设施即代码Infrastructure as Code, IaC Terraform, CloudFormation
- 配置日志记录Logging与监控Monitoring
- 在云环境中管理机密Secrets
- 设置 CDN 与边缘安全
- 实现容灾Disaster Recovery)与备份策略
## Cloud Security Checklist
## 云安全检查清单
### 1. IAM & Access Control
### 1. IAM 与访问控制 (IAM & Access Control)
#### Principle of Least Privilege
#### 最小特权原则 (Principle of Least Privilege)
```yaml
# ✅ CORRECT: Minimal permissions
# ✅ 正确:最小权限
iam_role:
permissions:
- s3:GetObject # Only read access
- s3:GetObject # 仅读取权限
- s3:ListBucket
resources:
- arn:aws:s3:::my-bucket/* # Specific bucket only
- arn:aws:s3:::my-bucket/* # 仅限特定存储桶
# ❌ WRONG: Overly broad permissions
# ❌ 错误:权限过大
iam_role:
permissions:
- s3:* # All S3 actions
- s3:* # 所有 S3 操作
resources:
- "*" # All resources
- "*" # 所有资源
```
#### Multi-Factor Authentication (MFA)
#### 多因素身份验证 (Multi-Factor Authentication, MFA)
```bash
# ALWAYS enable MFA for root/admin accounts
# 务必为 root/管理员账户启用 MFA
aws iam enable-mfa-device \
--user-name admin \
--serial-number arn:aws:iam::123456789:mfa/admin \
@@ -51,98 +51,98 @@ aws iam enable-mfa-device \
--authentication-code2 789012
```
#### Verification Steps
#### 验证步骤
- [ ] No root account usage in production
- [ ] MFA enabled for all privileged accounts
- [ ] Service accounts use roles, not long-lived credentials
- [ ] IAM policies follow least privilege
- [ ] Regular access reviews conducted
- [ ] Unused credentials rotated or removed
- [ ] 生产环境中不使用 root 账户
- [ ] 所有特权账户均启用 MFA
- [ ] 服务账号(Service accounts使用角色Roles而非长期凭据
- [ ] IAM 策略遵循最小特权原则
- [ ] 定期进行访问权限审查
- [ ] 轮换或移除未使用的凭据
### 2. Secrets Management
### 2. 机密管理 (Secrets Management)
#### Cloud Secrets Managers
#### 云端机密管理器 (Cloud Secrets Managers)
```typescript
// ✅ CORRECT: Use cloud secrets manager
// ✅ 正确:使用云端机密管理器
import { SecretsManager } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManager({ region: 'us-east-1' });
const secret = await client.getSecretValue({ SecretId: 'prod/api-key' });
const apiKey = JSON.parse(secret.SecretString).key;
// ❌ WRONG: Hardcoded or in environment variables only
const apiKey = process.env.API_KEY; // Not rotated, not audited
// ❌ 错误:硬编码或仅存在于环境变量中
const apiKey = process.env.API_KEY; // 无法轮换,无法审计
```
#### Secrets Rotation
#### 机密轮换 (Secrets Rotation)
```bash
# Set up automatic rotation for database credentials
# 为数据库凭据设置自动轮换
aws secretsmanager rotate-secret \
--secret-id prod/db-password \
--rotation-lambda-arn arn:aws:lambda:region:account:function:rotate \
--rotation-rules AutomaticallyAfterDays=30
```
#### Verification Steps
#### 验证步骤
- [ ] All secrets stored in cloud secrets manager (AWS Secrets Manager, Vercel Secrets)
- [ ] Automatic rotation enabled for database credentials
- [ ] API keys rotated at least quarterly
- [ ] No secrets in code, logs, or error messages
- [ ] Audit logging enabled for secret access
- [ ] 所有机密均存储在云端机密管理器中(如 AWS Secrets Manager, Vercel Secrets
- [ ] 数据库凭据已启用自动轮换
- [ ] API 密钥至少每季度轮换一次
- [ ] 代码、日志或错误消息中不包含机密
- [ ] 已为机密访问启用审计日志
### 3. Network Security
### 3. 网络安全 (Network Security)
#### VPC and Firewall Configuration
#### VPC 与防火墙配置 (VPC and Firewall Configuration)
```terraform
# ✅ CORRECT: Restricted security group
# ✅ 正确:受限的安全组
resource "aws_security_group" "app" {
name = "app-sg"
ingress {
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["10.0.0.0/16"] # Internal VPC only
cidr_blocks = ["10.0.0.0/16"] # 仅限内部 VPC
}
egress {
egres s {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Only HTTPS outbound
cidr_blocks = ["0.0.0.0/0"] # 仅允许 HTTPS 出站
}
}
# ❌ WRONG: Open to the internet
# ❌ 错误:对互联网开放
resource "aws_security_group" "bad" {
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # All ports, all IPs!
cidr_blocks = ["0.0.0.0/0"] # 所有端口,所有 IP
}
}
```
#### Verification Steps
#### 验证步骤
- [ ] Database not publicly accessible
- [ ] SSH/RDP ports restricted to VPN/bastion only
- [ ] Security groups follow least privilege
- [ ] Network ACLs configured
- [ ] VPC flow logs enabled
- [ ] 数据库不可通过公网访问
- [ ] SSH/RDP 端口仅限制在 VPN/堡垒机访问
- [ ] 安全组遵循最小特权原则
- [ ] 已配置网络 ACLNetwork ACLs
- [ ] 已启用 VPC 流日志(VPC flow logs
### 4. Logging & Monitoring
### 4. 日志记录与监控 (Logging & Monitoring)
#### CloudWatch/Logging Configuration
#### CloudWatch/日志配置 (CloudWatch/Logging Configuration)
```typescript
// ✅ CORRECT: Comprehensive logging
// ✅ 正确:全面的日志记录
import { CloudWatchLogsClient, CreateLogStreamCommand } from '@aws-sdk/client-cloudwatch-logs';
const logSecurityEvent = async (event: SecurityEvent) => {
@@ -156,28 +156,28 @@ const logSecurityEvent = async (event: SecurityEvent) => {
userId: event.userId,
ip: event.ip,
result: event.result,
// Never log sensitive data
// 严禁记录敏感数据
})
}]
});
};
```
#### Verification Steps
#### 验证步骤
- [ ] CloudWatch/logging enabled for all services
- [ ] Failed authentication attempts logged
- [ ] Admin actions audited
- [ ] Log retention configured (90+ days for compliance)
- [ ] Alerts configured for suspicious activity
- [ ] Logs centralized and tamper-proof
- [ ] 所有服务均启用了 CloudWatch/日志记录
- [ ] 已记录失败的身份验证尝试
- [ ] 管理员操作已审计
- [ ] 已配置日志保留策略(合规性要求通常为 90 天以上)
- [ ] 为可疑活动配置了告警
- [ ] 日志采用集中化存储且具备防篡改能力
### 5. CI/CD Pipeline Security
### 5. CI/CD 流水线安全 (CI/CD Pipeline Security)
#### Secure Pipeline Configuration
#### 安全流水线配置 (Secure Pipeline Configuration)
```yaml
# ✅ CORRECT: Secure GitHub Actions workflow
# ✅ 正确:安全的 GitHub Actions 工作流
name: Deploy
on:
@@ -188,20 +188,20 @@ jobs:
deploy:
runs-on: ubuntu-latest
permissions:
contents: read # Minimal permissions
contents: read # 最小权限
steps:
- uses: actions/checkout@v4
# Scan for secrets
# 扫描机密
- name: Secret scanning
uses: trufflesecurity/trufflehog@main
# Dependency audit
# 依赖项审计
- name: Audit dependencies
run: npm audit --audit-level=high
# Use OIDC, not long-lived tokens
# 使用 OIDC,而非长期令牌
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
@@ -209,40 +209,40 @@ jobs:
aws-region: us-east-1
```
#### Supply Chain Security
#### 供应链安全 (Supply Chain Security)
```json
// package.json - Use lock files and integrity checks
// package.json - 使用 lock 文件和完整性检查
{
"scripts": {
"install": "npm ci", // Use ci for reproducible builds
"install": "npm ci", // 使用 ci 以获得可复现的构建
"audit": "npm audit --audit-level=moderate",
"check": "npm outdated"
}
}
```
#### Verification Steps
#### 验证步骤
- [ ] OIDC used instead of long-lived credentials
- [ ] Secrets scanning in pipeline
- [ ] Dependency vulnerability scanning
- [ ] Container image scanning (if applicable)
- [ ] Branch protection rules enforced
- [ ] Code review required before merge
- [ ] Signed commits enforced
- [ ] 使用 OIDC 代替长期凭据
- [ ] 在流水线中进行机密扫描
- [ ] 依赖项漏洞扫描
- [ ] 容器镜像扫描(如适用)
- [ ] 强制执行分支保护规则
- [ ] 合并前必须进行代码审查
- [ ] 强制执行签名提交(Signed commits
### 6. Cloudflare & CDN Security
### 6. Cloudflare 与 CDN 安全 (Cloudflare & CDN Security)
#### Cloudflare Security Configuration
#### Cloudflare 安全配置
```typescript
// ✅ CORRECT: Cloudflare Workers with security headers
// ✅ 正确:带有安全响应头的 Cloudflare Workers
export default {
async fetch(request: Request): Promise<Response> {
const response = await fetch(request);
// Add security headers
// 添加安全响应头
const headers = new Headers(response.headers);
headers.set('X-Frame-Options', 'DENY');
headers.set('X-Content-Type-Options', 'nosniff');
@@ -257,105 +257,105 @@ export default {
};
```
#### WAF Rules
#### WAF 规则
```bash
# Enable Cloudflare WAF managed rules
# - OWASP Core Ruleset
# - Cloudflare Managed Ruleset
# - Rate limiting rules
# - Bot protection
# 启用 Cloudflare WAF 托管规则
# - OWASP 核心规则集
# - Cloudflare 托管规则集
# - 速率限制规则
# - 机器人保护
```
#### Verification Steps
#### 验证步骤
- [ ] WAF enabled with OWASP rules
- [ ] Rate limiting configured
- [ ] Bot protection active
- [ ] DDoS protection enabled
- [ ] Security headers configured
- [ ] SSL/TLS strict mode enabled
- [ ] 已启用 WAF 并配置了 OWASP 规则
- [ ] 已配置速率限制(Rate limiting
- [ ] 机器人保护(Bot protection)已激活
- [ ] 已启用 DDoS 防护
- [ ] 已配置安全响应头
- [ ] 已启用 SSL/TLS 严格模式
### 7. Backup & Disaster Recovery
### 7. 备份与容灾 (Backup & Disaster Recovery)
#### Automated Backups
#### 自动化备份
```terraform
# ✅ CORRECT: Automated RDS backups
# ✅ 正确RDS 自动化备份
resource "aws_db_instance" "main" {
allocated_storage = 20
engine = "postgres"
backup_retention_period = 30 # 30 days retention
backup_retention_period = 30 # 保留 30 天
backup_window = "03:00-04:00"
maintenance_window = "mon:04:00-mon:05:00"
enabled_cloudwatch_logs_exports = ["postgresql"]
deletion_protection = true # Prevent accidental deletion
deletion_protection = true # 防止误删
}
```
#### Verification Steps
#### 验证步骤
- [ ] Automated daily backups configured
- [ ] Backup retention meets compliance requirements
- [ ] Point-in-time recovery enabled
- [ ] Backup testing performed quarterly
- [ ] Disaster recovery plan documented
- [ ] RPO and RTO defined and tested
- [ ] 已配置每日自动化备份
- [ ] 备份保留时间符合合规性要求
- [ ] 已启用时间点恢复(Point-in-time recovery
- [ ] 每季度进行备份测试
- [ ] 已记录容灾计划文档
- [ ] 已定义并测试 RPO恢复点目标和 RTO恢复时间目标
## Pre-Deployment Cloud Security Checklist
## 部署前云安全检查表 (Pre-Deployment Cloud Security Checklist)
Before ANY production cloud deployment:
在任何生产环境云部署之前:
- [ ] **IAM**: Root account not used, MFA enabled, least privilege policies
- [ ] **Secrets**: All secrets in cloud secrets manager with rotation
- [ ] **Network**: Security groups restricted, no public databases
- [ ] **Logging**: CloudWatch/logging enabled with retention
- [ ] **Monitoring**: Alerts configured for anomalies
- [ ] **CI/CD**: OIDC auth, secrets scanning, dependency audits
- [ ] **CDN/WAF**: Cloudflare WAF enabled with OWASP rules
- [ ] **Encryption**: Data encrypted at rest and in transit
- [ ] **Backups**: Automated backups with tested recovery
- [ ] **Compliance**: GDPR/HIPAA requirements met (if applicable)
- [ ] **Documentation**: Infrastructure documented, runbooks created
- [ ] **Incident Response**: Security incident plan in place
- [ ] **IAM**:不使用 root 账户,启用 MFA执行最小特权策略
- [ ] **机密 (Secrets)**:所有机密均存放在带轮换机制的云端机密管理器中
- [ ] **网络 (Network)**:受限的安全组,无公网数据库
- [ ] **日志 (Logging)**:启用带保留策略的 CloudWatch/日志记录
- [ ] **监控 (Monitoring)**:为异常活动配置告警
- [ ] **CI/CD**OIDC 认证、机密扫描、依赖项审计
- [ ] **CDN/WAF**:启用带 OWASP 规则的 Cloudflare WAF
- [ ] **加密 (Encryption)**:数据在静态(at rest)和传输(in transit)中均已加密
- [ ] **备份 (Backups)**:带有恢复测试的自动化备份
- [ ] **合规性 (Compliance)**:满足 GDPR/HIPAA 等要求(如适用)
- [ ] **文档 (Documentation)**基础设施已记录文档创建了运行手册Runbooks
- [ ] **事件响应 (Incident Response)**:已制定安全事件响应计划
## Common Cloud Security Misconfigurations
## 常见的云安全错误配置 (Common Cloud Security Misconfigurations)
### S3 Bucket Exposure
### S3 存储桶暴露
```bash
# ❌ WRONG: Public bucket
# ❌ 错误:公共存储桶
aws s3api put-bucket-acl --bucket my-bucket --acl public-read
# ✅ CORRECT: Private bucket with specific access
# ✅ 正确:具有特定访问权限的私有存储桶
aws s3api put-bucket-acl --bucket my-bucket --acl private
aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json
```
### RDS Public Access
### RDS 公网访问
```terraform
# ❌ WRONG
# ❌ 错误
resource "aws_db_instance" "bad" {
publicly_accessible = true # NEVER do this!
publicly_accessible = true # 绝不要这样做!
}
# ✅ CORRECT
# ✅ 正确
resource "aws_db_instance" "good" {
publicly_accessible = false
vpc_security_group_ids = [aws_security_group.db.id]
}
```
## Resources
## 资源 (Resources)
- [AWS Security Best Practices](https://aws.amazon.com/security/best-practices/)
- [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services)
- [Cloudflare Security Documentation](https://developers.cloudflare.com/security/)
- [OWASP Cloud Security](https://owasp.org/www-project-cloud-security/)
- [Terraform Security Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/)
- [AWS 安全最佳实践](https://aws.amazon.com/security/best-practices/)
- [CIS AWS 基础基准](https://www.cisecurity.org/benchmark/amazon_web_services)
- [Cloudflare 安全文档](https://developers.cloudflare.com/security/)
- [OWASP 云安全](https://owasp.org/www-project-cloud-security/)
- [Terraform 安全最佳实践](https://www.terraform.io/docs/cloud/guides/recommended-practices/)
**Remember**: Cloud misconfigurations are the leading cause of data breaches. A single exposed S3 bucket or overly permissive IAM policy can compromise your entire infrastructure. Always follow the principle of least privilege and defense in depth.
**请记住**:云端配置错误是导致数据泄露的主要原因。一个暴露的 S3 存储桶或权限过大的 IAM 策略就可能危害您的整个基础设施。请务必遵循最小特权原则和纵深防御原则。