security-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Patterns Skill

Security Patterns Skill

Security best practices and patterns for secure development.
See: code-examples.md for Python implementations See: templates.md for checklists and config templates
安全开发的安全最佳实践与模式。
参考: code-examples.md 中的Python实现代码 参考: templates.md 中的检查清单与配置模板

When This Activates

触发场景

  • API key handling
  • User input validation
  • File operations
  • Security-sensitive code
  • Keywords: "security", "api key", "secret", "validate", "input"

  • API密钥处理
  • 用户输入验证
  • 文件操作
  • 安全敏感代码
  • 关键词:"security"、"api key"、"secret"、"validate"、"input"

API Keys & Secrets

API密钥与敏感信息

Environment Variables (REQUIRED)

环境变量(必填)

Rule: Never hardcode secrets. Always use environment variables via
.env
files.
python
undefined
规则: 切勿硬编码敏感信息。始终通过
.env
文件使用环境变量。
python
undefined

✅ CORRECT

✅ 正确写法

api_key = os.getenv("ANTHROPIC_API_KEY")
api_key = os.getenv("ANTHROPIC_API_KEY")

❌ WRONG

❌ 错误写法

api_key = "sk-ant-1234567890abcdef" # NEVER!

**See:** [code-examples.md#api-keys--secrets](code-examples.md#api-keys--secrets) for full validation code

---
api_key = "sk-ant-1234567890abcdef" # 绝对不要这样做!

**参考:** [code-examples.md#api-keys--secrets](code-examples.md#api-keys--secrets) 中的完整验证代码

---

Input Validation

输入验证

Path Traversal Prevention

路径遍历防护

Rule: Always validate paths are within allowed directories.
python
undefined
规则: 始终验证路径是否在允许的目录范围内。
python
undefined

Use is_relative_to() to prevent ../ attacks

使用is_relative_to()防止../攻击

if not file_path.is_relative_to(base_dir): raise ValueError("Path traversal detected")
undefined
if not file_path.is_relative_to(base_dir): raise ValueError("Path traversal detected")
undefined

Command Injection Prevention

命令注入防护

Rule: Never use
shell=True
. Pass arguments as lists.
python
undefined
规则: 切勿使用
shell=True
。以列表形式传递参数。
python
undefined

✅ CORRECT

✅ 正确写法

subprocess.run([command] + args, shell=False)
subprocess.run([command] + args, shell=False)

❌ WRONG

❌ 错误写法

subprocess.run(f"ls {user_input}", shell=True) # Injection risk!
undefined
subprocess.run(f"ls {user_input}", shell=True) # 存在注入风险!
undefined

SQL Injection Prevention

SQL注入防护

Rule: Always use parameterized queries.
python
undefined
规则: 始终使用参数化查询。
python
undefined

✅ CORRECT

✅ 正确写法

cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))

❌ WRONG

❌ 错误写法

cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")

**See:** [code-examples.md#input-validation](code-examples.md#input-validation) for complete examples

---
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")

**参考:** [code-examples.md#input-validation](code-examples.md#input-validation) 中的完整示例

---

File Operations Security

文件操作安全

Secure Permissions

安全权限设置

Use CasePermissionOctal
Sensitive files
rw-------
0o600
Sensitive dirs
rwx------
0o700
Public files
rw-r--r--
0o644
使用场景权限八进制值
敏感文件
rw-------
0o600
敏感目录
rwx------
0o700
公共文件
rw-r--r--
0o644

File Upload Validation

文件上传验证

  • Validate extensions (whitelist only)
  • Check file size limits
  • Reject executable files
See: code-examples.md#file-operations-security

  • 验证文件扩展名(仅允许白名单内的类型)
  • 检查文件大小限制
  • 拒绝可执行文件
参考: code-examples.md#file-operations-security

Cryptographic Operations

加密操作

Secure Random

安全随机数生成

Rule: Use
secrets
module for security-sensitive random values.
python
undefined
规则: 对于安全敏感的随机值,使用
secrets
模块。
python
undefined

✅ CORRECT

✅ 正确写法

token = secrets.token_hex(32)
token = secrets.token_hex(32)

❌ WRONG

❌ 错误写法

token = str(random.randint(0, 999999)) # Not cryptographically secure!

**See:** [code-examples.md#cryptographic-operations](code-examples.md#cryptographic-operations) for password hashing

---
token = str(random.randint(0, 999999)) # 不具备密码学安全性!

**参考:** [code-examples.md#cryptographic-operations](code-examples.md#cryptographic-operations) 中的密码哈希示例

---

Logging Security

日志安全

Rule: Never log full secrets. Mask sensitive values.
python
undefined
规则: 切勿记录完整的敏感信息。对敏感值进行掩码处理。
python
undefined

✅ CORRECT

✅ 正确写法

masked_key = api_key[:7] + "***" + api_key[-4:] logging.info(f"Using key {masked_key}")
masked_key = api_key[:7] + "***" + api_key[-4:] logging.info(f"Using key {masked_key}")

❌ WRONG

❌ 错误写法

logging.info(f"Using key {api_key}") # Exposes full key!

---
logging.info(f"Using key {api_key}") # 暴露完整密钥!

---

Dependencies Security

依赖项安全

bash
undefined
bash
undefined

Check for vulnerabilities

检查漏洞

pip install safety && safety check
pip install safety && safety check

OR

或者

pip install pip-audit && pip-audit

---
pip install pip-audit && pip-audit

---

Key Takeaways

核心要点

  1. Never hardcode secrets - Use environment variables
  2. Validate all inputs - User data, file paths, commands
  3. Prevent path traversal - Use
    is_relative_to()
  4. No shell=True - Use list arguments with subprocess
  5. Parameterized queries - Never string interpolation
  6. Secure random - Use
    secrets
    module
  7. Restrict permissions - Files 0o600, dirs 0o700
  8. Mask secrets in logs - Show only first/last few chars
  9. Scan dependencies - Use safety/pip-audit
  10. .gitignore secrets - .env, *.key, *.pem

  1. 切勿硬编码敏感信息 - 使用环境变量
  2. 验证所有输入 - 用户数据、文件路径、命令
  3. 防止路径遍历 - 使用
    is_relative_to()
  4. 禁用shell=True - 与subprocess配合使用列表参数
  5. 使用参数化查询 - 切勿使用字符串插值
  6. 安全随机数 - 使用
    secrets
    模块
  7. 限制权限 - 文件设为0o600,目录设为0o700
  8. 日志中掩码敏感信息 - 仅显示首尾部分字符
  9. 扫描依赖项 - 使用safety或pip-audit
  10. 通过.gitignore忽略敏感信息 - .env、.key、.pem

Related Files

相关文件

  • code-examples.md - Complete Python code examples
  • templates.md - .env, .gitignore, and security checklists
  • code-examples.md - 完整的Python代码示例
  • templates.md - .env、.gitignore及安全检查清单

OWASP Top 10 Quick Reference

OWASP Top 10快速参考

See: templates.md#owasp-top-10-quick-reference
参考: templates.md#owasp-top-10-quick-reference