AI 辅助开发的安全最佳实践
安全使用 AI 编程助手的基本指南。保护你的代码库、凭证和敏感数据。
C
CCJK 团队2025年1月6日
11 分钟阅读
2,253 次阅读
AI 辅助开发的安全最佳实践
AI 编程助手是强大的工具,但需要谨慎处理以维护安全。本指南涵盖保护代码、凭证和敏感数据的基本实践。
理解风险
AI 助手可以访问什么
当你使用 Claude Code 时,它可以:
- 读取项目目录中的文件
- 在终端中执行命令
- 访问环境变量(如果允许)
- 查看对话历史
潜在的安全问题
- 凭证暴露:意外分享 API 密钥或密码
- 代码泄露:敏感业务逻辑发送到外部服务
- 恶意建议:AI 生成的代码包含漏洞
- 供应链风险:建议的依赖存在安全问题
保护凭证
永远不要提交密钥
使用 .gitignore 和 .claudeignore:
hljs gitignore# .gitignore .env .env.* *.pem *.key secrets/ config/local.json
hljs gitignore# .claudeignore .env* secrets/ *.pem *.key **/credentials* config/production.json
使用环境变量
hljs bash# ✅ 好:引用环境变量
DATABASE_URL=$DATABASE_URL
# ❌ 差:硬编码凭证
DATABASE_URL=postgres://user:password@host:5432/db
密钥管理
使用密钥管理器:
hljs typescript// ✅ 好:从密钥管理器获取
import { SecretsManager } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManager({ region: 'us-east-1' });
const secret = await client.getSecretValue({ SecretId: 'my-app/prod' });
// ❌ 差:硬编码在代码中
const API_KEY = 'sk-1234567890abcdef';
安全配置 Claude Code
权限设置
限制 Claude Code 可以访问的内容:
hljs json// .claude/config.json
{
"permissions": {
"read": {
"allow": ["src/**", "tests/**", "docs/**"],
"deny": [".env*", "secrets/**", "*.pem"]
},
"write": {
"allow": ["src/**", "tests/**"],
"deny": ["config/production.*"]
},
"execute": {
"allow": ["npm test", "npm run lint", "npm run build"],
"deny": ["rm -rf", "curl", "wget", "> /dev/*"]
}
}
}
自动批准设置
对自动批准要有选择性:
hljs json{
"autoApprove": {
"read": true, // 安全:读取文件
"glob": true, // 安全:列出文件
"grep": true, // 安全:搜索内容
"write": false, // 需要批准
"bash": false // 需要批准
}
}
审计日志
启用日志以进行安全审查:
hljs json{
"logging": {
"enabled": true,
"level": "info",
"file": ".claude/audit.log",
"includePrompts": false, // 不记录敏感提示
"includeCommands": true
}
}
AI 生成代码的代码审查
安全检查清单
始终审查 AI 生成的代码:
输入验证
hljs typescript// ✅ 好:验证和清理输入
function getUser(id: string) {
if (!isValidUUID(id)) {
throw new ValidationError('无效的用户 ID');
}
return db.users.findUnique({ where: { id } });
}
// ❌ 差:直接使用用户输入
function getUser(id: string) {
return db.query(`SELECT * FROM users WHERE id = '${id}'`);
}
认证和授权
hljs typescript// ✅ 好:适当的权限检查
async function deleteUser(requesterId: string, targetId: string) {
const requester = await getUser(requesterId);
if (!requester.isAdmin && requesterId !== targetId) {
throw new ForbiddenError('未授权');
}
return db.users.delete({ where: { id: targetId } });
}
// ❌ 差:缺少授权
async function deleteUser(targetId: string) {
return db.users.delete({ where: { id: targetId } });
}
错误处理
hljs typescript// ✅ 好:安全的错误消息
catch (error) {
logger.error('数据库错误', { error, userId });
throw new AppError('无法处理请求');
}
// ❌ 差:暴露内部细节
catch (error) {
throw new Error(`数据库错误:${error.message}`);
}
依赖安全
hljs bash# 检查建议的依赖
npm audit
# 使用特定版本
npm install package@1.2.3 # 不是 package@latest
处理敏感数据
数据分类
识别项目中的敏感数据:
| 分类 | 示例 | 处理方式 |
|---|---|---|
| 关键 | API 密钥、密码、个人信息 | 永不与 AI 分享 |
| 机密 | 业务逻辑、算法 | 谨慎分享 |
| 内部 | 架构、模式 | 通常安全 |
| 公开 | 开源代码 | 可以分享 |
分享前脱敏
请求帮助处理敏感代码时:
hljs typescript// 原始(不要分享)
const stripe = new Stripe('sk_live_abc123...');
await stripe.charges.create({
amount: order.total,
customer: user.stripeId,
});
// 脱敏后(可以分享)
const stripe = new Stripe(process.env.STRIPE_KEY);
await stripe.charges.create({
amount: order.total,
customer: user.paymentProviderId,
});
使用占位符
hljs typescript// 使用明显的占位符
const config = {
apiKey: 'YOUR_API_KEY_HERE',
secret: 'YOUR_SECRET_HERE',
endpoint: 'https://api.example.com',
};
网络安全
API 通信
Claude Code 与 Anthropic API 通信:
你的机器 → HTTPS → Anthropic API
确保:
- 流量通过 HTTPS
- 企业代理不记录内容
- VPN 不通过不受信任的网络路由
防火墙考虑
如果使用企业防火墙:
hljs bash# 必需的端点
api.anthropic.com:443
团队安全策略
共享配置
创建团队范围的安全设置:
hljs yaml# .claude/team-policy.yaml
security:
# 所有团队成员必需
required:
- claudeignore_secrets
- audit_logging
- approval_for_writes
# 禁止的操作
prohibited:
- sharing_credentials
- disabling_security
- auto_approve_bash
# 审查要求
review:
ai_generated_code: required
security_changes: senior_review
入职检查清单
新团队成员:
- 配置
.claudeignore包含密钥模式 - 设置环境变量(不是硬编码)
- 启用审计日志
- 审查安全策略文档
- 完成 AI 安全培训
事件响应
如果凭证被暴露
- 立即轮换:更改暴露的凭证
- 审计使用:检查未授权访问
- 更新代码:删除硬编码值
- 审查历史:检查 git 历史中的暴露
hljs bash# 从 git 历史中删除
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch path/to/secret" \
--prune-empty --tag-name-filter cat -- --all
如果敏感代码被分享
- 评估影响:暴露了什么?
- 记录:记录分享的内容
- 缓解:如需要,更改受影响的系统
- 预防:更新
.claudeignore
安全检查清单
日常实践
- 提交前审查 AI 生成的代码
- 检查硬编码凭证
- 验证建议的依赖
- 使用环境变量存储密钥
每周审查
- 审计 Claude Code 日志
- 审查权限设置
- 检查新的安全公告
- 更新依赖
每月评估
- AI 生成代码的完整安全审计
- 审查和更新安全策略
- 团队安全培训复习
- 如适用,进行渗透测试
总结
安全使用 AI 编程助手的关键原则:
- 永不分享凭证给 AI 助手
- 审查所有生成的代码的安全问题
- 适当配置权限
- 维护审计日志以便追责
- 培训团队安全使用 AI
安全不是要避免 AI 工具——而是负责任地使用它们。
下一步:探索 AI 辅助的性能优化技术。
继续阅读
相关文章
#性能#优化#ai工具
#提示工程#ai#最佳实践