python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Backend Development Skill

Python后端开发技能

File Organization

文件组织结构

This skill uses a split structure for HIGH-RISK requirements:
  • SKILL.md: Core principles, patterns, and essential security (this file)
  • references/security-examples.md: Complete CVE details and OWASP implementations
  • references/advanced-patterns.md: Advanced Python patterns and optimization
  • references/threat-model.md: Attack scenarios and STRIDE analysis
本技能针对高风险需求采用拆分结构:
  • SKILL.md:核心原则、模式和基础安全内容(本文件)
  • references/security-examples.md:完整的CVE细节和OWASP实现方案
  • references/advanced-patterns.md:高级Python模式与优化方案
  • references/threat-model.md:攻击场景与STRIDE分析

Validation Gates

验证关卡

GateStatusNotes
0.1 Domain ExpertisePASSEDType safety, async, security, testing
0.2 Vulnerability ResearchPASSED5+ CVEs documented (2025-11-20)
0.5 Hallucination CheckPASSEDExamples tested on Python 3.11+
0.11 File OrganizationSplitHIGH-RISK, ~450 lines + references

关卡状态说明
0.1 领域专业能力通过类型安全、异步编程、安全、测试
0.2 漏洞研究通过已记录5个以上CVE(2025-11-20)
0.5 幻觉检查通过示例已在Python 3.11+版本测试
0.11 文件组织结构拆分高风险,约450行内容+参考文档

1. Overview

1. 概述

Risk Level: HIGH
Justification: Python backend services handle authentication, database access, file operations, and external API communication. Vulnerabilities in input validation, deserialization, command execution, and cryptography can lead to data breaches and system compromise.
You are an expert Python backend developer specializing in secure, maintainable, and performant services.
风险等级:高
理由:Python后端服务处理身份验证、数据库访问、文件操作和外部API通信。输入验证、反序列化、命令执行和加密方面的漏洞可能导致数据泄露和系统被入侵。
您是专注于安全、可维护和高性能服务的资深Python后端开发专家。

Core Expertise Areas

核心专业领域

  • Type annotations and runtime validation
  • Async programming with asyncio
  • Security: input validation, cryptography, secrets management
  • Testing: pytest, property-based testing, security testing
  • Database access with SQLAlchemy/asyncpg
  • API development with FastAPI/Starlette

  • 类型注解与运行时验证
  • 基于asyncio的异步编程
  • 安全:输入验证、加密、密钥管理
  • 测试:pytest、属性化测试、安全测试
  • 基于SQLAlchemy/asyncpg的数据库访问
  • 基于FastAPI/Starlette的API开发

2. Core Responsibilities

2. 核心职责

Fundamental Principles

基本原则

  1. TDD First: Write tests before implementation, design API through test cases
  2. Performance Aware: Use async, generators, efficient data structures by default
  3. Type Safety: Use type hints everywhere, validate at runtime boundaries
  4. Defense in Depth: Multiple validation layers, fail securely
  5. Secure Defaults: Use safe libraries, reject unsafe operations
  6. Explicit over Implicit: Clear error handling, explicit dependencies
  7. Testability: Design for testing, write security tests
  1. 测试驱动开发优先:先编写测试再实现功能,通过测试用例设计API
  2. 性能感知:默认使用异步、生成器、高效数据结构
  3. 类型安全:全程使用类型提示,在运行时边界进行验证
  4. 纵深防御:多层验证机制,安全失败
  5. 安全默认配置:使用安全库,拒绝不安全操作
  6. 显式优于隐式:清晰的错误处理,显式依赖
  7. 可测试性:为测试设计代码,编写安全测试

Decision Framework

决策框架

SituationApproach
User inputValidate with Pydantic, sanitize output
Database queriesUse ORM or parameterized queries, never format strings
File operationsValidate paths, use pathlib, check containment
SubprocessUse list args, never shell=True with user input
SecretsLoad from environment or secret manager
CryptographyUse cryptography library, never roll your own

场景处理方式
用户输入使用Pydantic验证,清理输出内容
数据库查询使用ORM或参数化查询,绝不格式化字符串
文件操作验证路径,使用pathlib,检查路径包含关系
子进程使用列表形式传参,绝不在用户输入场景下使用shell=True
密钥从环境变量或密钥管理器加载
加密使用cryptography库,绝不自行实现

2.1 Implementation Workflow (TDD)

2.1 实现工作流(测试驱动开发)

Step 1: Write Failing Test First

步骤1:先编写失败的测试

python
import pytest
from my_service import UserService, UserNotFoundError

class TestUserService:
    @pytest.mark.asyncio
    async def test_get_user_returns_user_when_exists(self, db_session):
        service = UserService(db_session)
        user_id = await service.create_user("alice", "alice@example.com")
        user = await service.get_user(user_id)
        assert user.username == "alice"

    @pytest.mark.asyncio
    async def test_get_user_raises_when_not_found(self, db_session):
        service = UserService(db_session)
        with pytest.raises(UserNotFoundError):
            await service.get_user(99999)

    @pytest.mark.asyncio
    async def test_create_user_validates_email(self, db_session):
        service = UserService(db_session)
        with pytest.raises(ValueError, match="Invalid email"):
            await service.create_user("bob", "not-an-email")
python
import pytest
from my_service import UserService, UserNotFoundError

class TestUserService:
    @pytest.mark.asyncio
    async def test_get_user_returns_user_when_exists(self, db_session):
        service = UserService(db_session)
        user_id = await service.create_user("alice", "alice@example.com")
        user = await service.get_user(user_id)
        assert user.username == "alice"

    @pytest.mark.asyncio
    async def test_get_user_raises_when_not_found(self, db_session):
        service = UserService(db_session)
        with pytest.raises(UserNotFoundError):
            await service.get_user(99999)

    @pytest.mark.asyncio
    async def test_create_user_validates_email(self, db_session):
        service = UserService(db_session)
        with pytest.raises(ValueError, match="Invalid email"):
            await service.create_user("bob", "not-an-email")

Step 2: Implement Minimum to Pass

步骤2:实现满足测试的最小代码

python
class UserNotFoundError(Exception): pass

class UserService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_user(self, user_id: int) -> User:
        user = await self.db.get(User, user_id)
        if not user:
            raise UserNotFoundError(f"User {user_id} not found")
        return user

    async def create_user(self, username: str, email: str) -> int:
        if "@" not in email:
            raise ValueError("Invalid email format")
        # ... minimal implementation to pass tests
python
class UserNotFoundError(Exception): pass

class UserService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_user(self, user_id: int) -> User:
        user = await self.db.get(User, user_id)
        if not user:
            raise UserNotFoundError(f"User {user_id} not found")
        return user

    async def create_user(self, username: str, email: str) -> int:
        if "@" not in email:
            raise ValueError("Invalid email format")
        # ... 满足测试的最小实现

Step 3: Refactor if Needed

步骤3:按需重构

  • Extract common patterns, add type hints, ensure errors don't leak internals
  • 提取通用模式,添加类型提示,确保错误信息不泄露内部细节

Step 4: Run Full Verification

步骤4:运行完整验证

bash
pytest --cov=src           # All tests pass
mypy src/ --strict         # Type check passes
bandit -r src/ -ll         # Security scan passes
pip-audit && safety check  # Dependencies clean

bash
pytest --cov=src           # 所有测试通过
mypy src/ --strict         # 类型检查通过
bandit -r src/ -ll         # 安全扫描通过
pip-audit && safety check  # 依赖无风险

2.2 Performance Patterns

2.2 性能优化模式

Pattern 1: Async I/O with asyncio.gather

模式1:使用asyncio.gather实现异步I/O

python
undefined
python
undefined

BAD: Sequential requests (slow)

糟糕:串行请求(速度慢)

for url in urls: response = await client.get(url) # Waits for each one
for url in urls: response = await client.get(url) # 等待每个请求完成

GOOD: Concurrent requests with gather

良好:使用gather实现并发请求

tasks = [client.get(url) for url in urls] responses = await asyncio.gather(*tasks) # All at once
undefined
tasks = [client.get(url) for url in urls] responses = await asyncio.gather(*tasks) # 同时执行所有请求
undefined

Pattern 2: Generators for Large Data Processing

模式2:使用生成器处理大数据

python
undefined
python
undefined

BAD: Load all into memory

糟糕:全部加载到内存

return [process(line) for line in f.readlines()] # OOM risk
return [process(line) for line in f.readlines()] # 有内存溢出风险

GOOD: Generator yields one at a time

良好:生成器逐行返回结果

def process_large_file(filepath: str) -> Iterator[dict]: with open(filepath) as f: for line in f: yield process(line) # Memory efficient
undefined
def process_large_file(filepath: str) -> Iterator[dict]: with open(filepath) as f: for line in f: yield process(line) # 内存高效
undefined

Pattern 3: Efficient Data Structures

模式3:高效数据结构

python
undefined
python
undefined

BAD: List for membership testing - O(n)

糟糕:使用列表做成员检测 - O(n)

required in user_perms_list # Slow for large lists
required in user_perms_list # 大型列表下速度慢

GOOD: Set for membership testing - O(1)

良好:使用集合做成员检测 - O(1)

required in user_perms_set # Fast lookup
required in user_perms_set # 快速查找

BAD: Repeated string concatenation

糟糕:重复字符串拼接

result = ""; for f in fields: result += f + ", " # Creates new string each time
result = ""; for f in fields: result += f + ", " # 每次创建新字符串

GOOD: Join for string building

良好:使用join构建字符串

", ".join(fields) # Single allocation
undefined
", ".join(fields) # 单次内存分配
undefined

Pattern 4: Connection Pooling

模式4:连接池

python
undefined
python
undefined

BAD: New connection per request

糟糕:每次请求新建连接

engine = create_async_engine(DATABASE_URL) # Connection overhead each time
engine = create_async_engine(DATABASE_URL) # 每次请求都有连接开销

GOOD: Reuse pooled connections

良好:复用连接池中的连接

engine = create_async_engine(DATABASE_URL, pool_size=20, max_overflow=10) async_session = sessionmaker(engine, class_=AsyncSession)
async def get_user(user_id: int): async with async_session() as session: # Reuses pooled connection return await session.get(User, user_id)
undefined
engine = create_async_engine(DATABASE_URL, pool_size=20, max_overflow=10) async_session = sessionmaker(engine, class_=AsyncSession)
async def get_user(user_id: int): async with async_session() as session: # 复用连接池中的连接 return await session.get(User, user_id)
undefined

Pattern 5: Batch Database Operations

模式5:数据库批量操作

python
undefined
python
undefined

BAD: Individual inserts (N round trips)

糟糕:单独插入(N次往返)

for user in users: db.add(User(**user)); await db.commit() # N commits = slow
for user in users: db.add(User(**user)); await db.commit() # N次提交 = 速度慢

GOOD: Batch insert (1 round trip)

良好:批量插入(1次往返)

stmt = insert(User).values(users) await db.execute(stmt); await db.commit() # Single commit
stmt = insert(User).values(users) await db.execute(stmt); await db.commit() # 单次提交

GOOD: Chunked for very large datasets

良好:超大数据集分块处理

for i in range(0, len(users), 1000): await db.execute(insert(User).values(users[i:i+1000])) await db.commit()

---
for i in range(0, len(users), 1000): await db.execute(insert(User).values(users[i:i+1000])) await db.commit()

---

3. Technical Foundation

3. 技术基础

Version Recommendations

版本推荐

CategoryVersionNotes
LTS/RecommendedPython 3.11+Performance improvements, better errors
MinimumPython 3.9Security support until Oct 2025
AvoidPython 3.8-EOL, no security patches
分类版本说明
长期支持/推荐版本Python 3.11+性能提升,错误信息更友好
最低版本Python 3.9安全支持至2025年10月
避免使用Python 3.8及以下已停止维护,无安全补丁

Security Dependencies

安全依赖

toml
undefined
toml
undefined

pyproject.toml

pyproject.toml

[project] dependencies = [ "pydantic>=2.0", "email-validator>=2.0", # Validation "cryptography>=41.0", "argon2-cffi>=21.0", # Cryptography "PyJWT>=2.8", "sqlalchemy>=2.0", "asyncpg>=0.28", "httpx>=0.25", "bandit>=1.7", ]
[project.optional-dependencies] dev = ["pytest>=7.0", "pytest-asyncio>=0.21", "hypothesis>=6.0", "safety>=2.0", "pip-audit>=2.0"]

---
[project] dependencies = [ "pydantic>=2.0", "email-validator>=2.0", # 验证库 "cryptography>=41.0", "argon2-cffi>=21.0", # 加密库 "PyJWT>=2.8", "sqlalchemy>=2.0", "asyncpg>=0.28", "httpx>=0.25", "bandit>=1.7", ]
[project.optional-dependencies] dev = ["pytest>=7.0", "pytest-asyncio>=0.21", "hypothesis>=6.0", "safety>=2.0", "pip-audit>=2.0"]

---

4. Implementation Patterns

4. 实现模式

Pattern 1: Type-Safe Input Validation

模式1:类型安全的输入验证

python
from pydantic import BaseModel, Field, field_validator, EmailStr
from typing import Annotated
import re

class UserCreate(BaseModel):
    """Validated user creation request."""
    username: Annotated[str, Field(min_length=3, max_length=50)]
    email: EmailStr
    password: Annotated[str, Field(min_length=12)]

    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if not re.match(r'^[a-zA-Z0-9_-]+$', v):
            raise ValueError('Username must be alphanumeric')
        return v

    @field_validator('password')
    @classmethod
    def validate_password_strength(cls, v: str) -> str:
        if not all([re.search(r'[A-Z]', v), re.search(r'[a-z]', v), re.search(r'\d', v)]):
            raise ValueError('Password needs uppercase, lowercase, and digit')
        return v
python
from pydantic import BaseModel, Field, field_validator, EmailStr
from typing import Annotated
import re

class UserCreate(BaseModel):
    """经过验证的用户创建请求模型。"""
    username: Annotated[str, Field(min_length=3, max_length=50)]
    email: EmailStr
    password: Annotated[str, Field(min_length=12)]

    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if not re.match(r'^[a-zA-Z0-9_-]+$', v):
            raise ValueError('用户名必须是字母数字组合')
        return v

    @field_validator('password')
    @classmethod
    def validate_password_strength(cls, v: str) -> str:
        if not all([re.search(r'[A-Z]', v), re.search(r'[a-z]', v), re.search(r'\d', v)]):
            raise ValueError('密码需要包含大写字母、小写字母和数字')
        return v

Pattern 2: Secure Password Hashing

模式2:安全的密码哈希

python
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)

def hash_password(password: str) -> str:
    return ph.hash(password)

def verify_password(password: str, hash: str) -> bool:
    try:
        ph.verify(hash, password)
        return True
    except VerifyMismatchError:
        return False
python
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)

def hash_password(password: str) -> str:
    return ph.hash(password)

def verify_password(password: str, hash: str) -> bool:
    try:
        ph.verify(hash, password)
        return True
    except VerifyMismatchError:
        return False

Pattern 3: Safe Database Queries

模式3:安全的数据库查询

python
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
python
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession

NEVER: f"SELECT * FROM users WHERE username = '{username}'"

绝对禁止:f"SELECT * FROM users WHERE username = '{username}'"

async def get_user_safe(db: AsyncSession, username: str) -> User | None: stmt = select(User).where(User.username == username) result = await db.execute(stmt) return result.scalar_one_or_none()
async def search_users(db: AsyncSession, pattern: str) -> list: stmt = text("SELECT * FROM users WHERE username LIKE :pattern") result = await db.execute(stmt, {"pattern": f"%{pattern}%"}) return result.fetchall()
undefined
async def get_user_safe(db: AsyncSession, username: str) -> User | None: stmt = select(User).where(User.username == username) result = await db.execute(stmt) return result.scalar_one_or_none()
async def search_users(db: AsyncSession, pattern: str) -> list: stmt = text("SELECT * FROM users WHERE username LIKE :pattern") result = await db.execute(stmt, {"pattern": f"%{pattern}%"}) return result.fetchall()
undefined

Pattern 4: Safe File Operations

模式4:安全的文件操作

python
from pathlib import Path

def safe_read_file(base_dir: Path, user_filename: str) -> str:
    if '..' in user_filename or user_filename.startswith('/'):
        raise ValueError("Invalid filename")

    file_path = (base_dir / user_filename).resolve()
    if not file_path.is_relative_to(base_dir.resolve()):
        raise ValueError("Path traversal detected")

    return file_path.read_text()
python
from pathlib import Path

def safe_read_file(base_dir: Path, user_filename: str) -> str:
    if '..' in user_filename or user_filename.startswith('/'):
        raise ValueError("无效文件名")

    file_path = (base_dir / user_filename).resolve()
    if not file_path.is_relative_to(base_dir.resolve()):
        raise ValueError("检测到路径遍历攻击")

    return file_path.read_text()

Pattern 5: Safe Subprocess Execution

模式5:安全的子进程执行

python
import subprocess

ALLOWED_PROGRAMS = {'git', 'python', 'pip'}

def run_command_safe(program: str, args: list[str]) -> str:
    if program not in ALLOWED_PROGRAMS:
        raise ValueError(f"Program not allowed: {program}")

    result = subprocess.run(
        [program, *args],
        capture_output=True, text=True, timeout=30, check=True,
    )
    return result.stdout

python
import subprocess

ALLOWED_PROGRAMS = {'git', 'python', 'pip'}

def run_command_safe(program: str, args: list[str]) -> str:
    if program not in ALLOWED_PROGRAMS:
        raise ValueError(f"不允许执行该程序:{program}")

    result = subprocess.run(
        [program, *args],
        capture_output=True, text=True, timeout=30, check=True,
    )
    return result.stdout

5. Security Standards

5. 安全标准

5.1 Domain Vulnerability Landscape

5.1 领域漏洞情况

CVE IDSeverityDescriptionMitigation
CVE-2024-12718CRITICALtarfile filter bypassPython 3.12.3+, filter='data'
CVE-2024-12254HIGHasyncio memory exhaustionUpgrade, monitor memory
CVE-2024-5535MEDIUMSSLContext buffer over-readUpgrade OpenSSL
CVE-2023-50782HIGHRSA information disclosureUpgrade cryptography
CVE-2023-27043MEDIUMEmail parsing vulnerabilityStrict email validation
See
references/security-examples.md
for complete CVE details and mitigation code
CVE编号严重程度描述缓解措施
CVE-2024-12718严重tarfile过滤器绕过Python 3.12.3+版本,使用filter='data'
CVE-2024-12254asyncio内存耗尽升级版本,监控内存使用
CVE-2024-5535SSLContext缓冲区溢出读取升级OpenSSL
CVE-2023-50782RSA信息泄露升级cryptography库
CVE-2023-27043邮件解析漏洞严格的邮件验证
完整的CVE细节和缓解代码请查看
references/security-examples.md

5.2 OWASP Top 10 Mapping

5.2 OWASP Top 10映射

CategoryRiskKey Mitigations
A01 Broken Access ControlHIGHValidate permissions, decorators
A02 Cryptographic FailuresHIGHcryptography lib, Argon2
A03 InjectionCRITICALParameterized queries, no shell=True
A04 Insecure DesignMEDIUMType safety, validation layers
A05 MisconfigurationHIGHSafe defaults, audit deps
A06 Vulnerable ComponentsHIGHpip-audit, safety in CI
分类风险核心缓解措施
A01 访问控制失效验证权限,使用装饰器
A02 加密失败使用cryptography库,Argon2哈希
A03 注入攻击严重参数化查询,不使用shell=True
A04 不安全设计类型安全,多层验证
A05 配置错误安全默认配置,审计依赖
A06 易受攻击的组件CI中使用pip-audit和safety

5.3 Essential Security Patterns

5.3 基础安全模式

python
from pydantic import BaseModel, field_validator
import os, logging
python
from pydantic import BaseModel, field_validator
import os, logging

Secure base model - reject unknown fields, strip whitespace

安全基础模型 - 拒绝未知字段,去除空白字符

class SecureInput(BaseModel): model_config = {'extra': 'forbid', 'str_strip_whitespace': True}
@field_validator('*', mode='before')
@classmethod
def reject_null_bytes(cls, v):
    if isinstance(v, str) and '\x00' in v:
        raise ValueError('Null bytes not allowed')
    return v
class SecureInput(BaseModel): model_config = {'extra': 'forbid', 'str_strip_whitespace': True}
@field_validator('*', mode='before')
@classmethod
def reject_null_bytes(cls, v):
    if isinstance(v, str) and '\x00' in v:
        raise ValueError('不允许空字节')
    return v

Secrets from environment (NEVER hardcode)

从环境变量获取密钥(绝对禁止硬编码)

API_KEY = os.environ["API_KEY"] DB_URL = os.environ["DATABASE_URL"]
API_KEY = os.environ["API_KEY"] DB_URL = os.environ["DATABASE_URL"]

Safe error handling - log details, return safe message

安全错误处理 - 记录详细信息,返回安全提示

class AppError(Exception): def init(self, message: str, internal: str = None): self.message = message if internal: logging.error(f"{message}: {internal}")
def to_response(self) -> dict:
    return {"error": self.message}

> **See `references/advanced-patterns.md` for secrets manager integration**

---
class AppError(Exception): def init(self, message: str, internal: str = None): self.message = message if internal: logging.error(f"{message}: {internal}")
def to_response(self) -> dict:
    return {"error": self.message}

> **密钥管理器集成请查看`references/advanced-patterns.md`**

---

6. Testing & Validation

6. 测试与验证

Security Testing Commands

安全测试命令

bash
bandit -r src/ -ll          # Static analysis
pip-audit && safety check   # Dependency vulnerabilities
mypy src/ --strict          # Type checking
bash
bandit -r src/ -ll          # 静态分析
pip-audit && safety check   # 依赖漏洞检查
mypy src/ --strict          # 类型检查

Security Test Examples

安全测试示例

python
import pytest
from pathlib import Path

def test_sql_injection_prevented(db):
    for payload in ["'; DROP TABLE users; --", "' OR '1'='1", "admin'--"]:
        assert get_user_safe(db, payload) is None

def test_path_traversal_blocked():
    base = Path("/app/data")
    for attack in ["../etc/passwd", "..\\windows\\system32", "foo/../../etc/passwd"]:
        with pytest.raises(ValueError, match="traversal|Invalid"):
            safe_read_file(base, attack)

def test_command_injection_blocked():
    with pytest.raises(ValueError, match="not allowed"):
        run_command_safe("rm", ["-rf", "/"])
See
references/security-examples.md
for comprehensive test patterns

python
import pytest
from pathlib import Path

def test_sql_injection_prevented(db):
    for payload in ["'; DROP TABLE users; --", "' OR '1'='1", "admin'--"]:
        assert get_user_safe(db, payload) is None

def test_path_traversal_blocked():
    base = Path("/app/data")
    for attack in ["../etc/passwd", "..\\windows\\system32", "foo/../../etc/passwd"]:
        with pytest.raises(ValueError, match="traversal|Invalid"):
            safe_read_file(base, attack)

def test_command_injection_blocked():
    with pytest.raises(ValueError, match="not allowed"):
        run_command_safe("rm", ["-rf", "/"])
完整的测试模式请查看
references/security-examples.md

7. Common Mistakes & Anti-Patterns

7. 常见错误与反模式

Anti-PatternBadGood
SQL formatting
f"SELECT * WHERE id={id}"
select(User).where(User.id == id)
Pickle untrusted
pickle.loads(data)
json.loads(data)
Shell injection
subprocess.run(f"echo {x}", shell=True)
subprocess.run(["echo", x])
Weak hashing
hashlib.md5(pw).hexdigest()
PasswordHasher().hash(pw)
Hardcoded secrets
API_KEY = "sk-123..."
API_KEY = os.environ["API_KEY"]

反模式错误做法正确做法
SQL格式化
f"SELECT * WHERE id={id}"
select(User).where(User.id == id)
反序列化不可信数据
pickle.loads(data)
json.loads(data)
命令注入
subprocess.run(f"echo {x}", shell=True)
subprocess.run(["echo", x])
弱哈希
hashlib.md5(pw).hexdigest()
PasswordHasher().hash(pw)
硬编码密钥
API_KEY = "sk-123..."
API_KEY = os.environ["API_KEY"]

8. Pre-Deployment Checklist

8. 部署前检查清单

Phase 1: Before Writing Code

阶段1:编写代码前

  • Requirements understood and documented
  • API design reviewed (inputs, outputs, errors)
  • Security threat model considered
  • Test cases written first (TDD)
  • Edge cases and error scenarios identified
  • 理解并记录需求
  • API设计已评审(输入、输出、错误)
  • 已考虑安全威胁模型
  • 先编写测试用例(测试驱动开发)
  • 已识别边缘情况和错误场景

Phase 2: During Implementation

阶段2:实现过程中

  • Following TDD workflow (test -> implement -> refactor)
  • Using performance patterns (async, generators, pooling)
  • All inputs validated with Pydantic
  • DB queries parameterized/ORM
  • File ops check path containment
  • Subprocess uses list args
  • Passwords hashed with Argon2id
  • Secrets from environment only
  • 遵循测试驱动开发工作流(测试→实现→重构)
  • 使用性能优化模式(异步、生成器、连接池)
  • 所有输入都使用Pydantic验证
  • 数据库查询使用参数化/ORM
  • 文件操作检查路径包含关系
  • 子进程使用列表传参
  • 密码使用Argon2id哈希
  • 仅从环境变量获取密钥

Phase 3: Before Committing

阶段3:提交代码前

  • All tests pass:
    pytest --cov=src
  • Type check passes:
    mypy src/ --strict
  • Security scan passes:
    bandit -r src/ -ll
  • Dependency audit passes:
    pip-audit && safety check
  • No hardcoded secrets in code
  • Errors don't leak internal details
  • Debug mode disabled
  • Logging configured (no PII/secrets)

  • 所有测试通过:
    pytest --cov=src
  • 类型检查通过:
    mypy src/ --strict
  • 安全扫描通过:
    bandit -r src/ -ll
  • 依赖审计通过:
    pip-audit && safety check
  • 代码中无硬编码密钥
  • 错误信息不泄露内部细节
  • 调试模式已禁用
  • 日志已配置(无个人信息/密钥)

9. Summary

9. 总结

Create Python code that is type safe, secure, testable, and maintainable.
Security Essentials:
  1. Validate and sanitize all user input
  2. Use parameterized queries for database ops
  3. Never use shell=True with user input
  4. Hash passwords with Argon2id
  5. Load secrets from environment
  6. Keep dependencies updated and audited
For attack scenarios and threat modeling, see
references/threat-model.md
创建类型安全安全可靠可测试可维护的Python代码。
安全要点:
  1. 验证并清理所有用户输入
  2. 数据库操作使用参数化查询
  3. 绝不在用户输入场景下使用shell=True
  4. 使用Argon2id哈希密码
  5. 从环境变量加载密钥
  6. 保持依赖更新并定期审计
攻击场景与威胁建模请查看
references/threat-model.md