security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese/security — Security-First Design Enforcement
/security — 安全优先设计强制规范
Every design, plan, and implementation MUST treat security as a first-class constraint, not an afterthought. Vulnerabilities are bugs — the most expensive kind.
Why this matters: A single security vulnerability can compromise user data, destroy trust, and cost millions in breach response. Security cannot be "added later" — it must be designed in from the start. Every line of code is an attack surface.
When to invoke: During PLANNING (after brainstorming, before or alongside writing-plans) and during REVIEW (as part of code review criteria). This skill applies to ALL code — there are no exceptions for "internal" or "low-risk" systems.
所有设计、规划和落地工作都必须将安全视为第一优先级约束,而非事后补充项。漏洞是代价最高的一类bug。
为什么这很重要: 单个安全漏洞就可能泄露用户数据、摧毁用户信任,还会产生数百万的漏洞响应成本。安全无法“事后补上”——必须从一开始就纳入设计。每一行代码都是攻击面。
何时适用: 规划阶段(头脑风暴后,编写方案期间或之前)以及评审阶段(作为代码评审标准的一部分)。本规范适用于所有代码——“内部”或“低风险”系统也不例外。
The Rules
规范规则
Rule 1: Validate All Input at System Boundaries
规则1:在系统边界校验所有输入
Every piece of data entering the system MUST be validated before use:
| Boundary | What to validate |
|---|---|
| HTTP requests | Body, query params, headers, path params — type, length, format, range |
| File uploads | Type, size, content (not just extension), filename sanitization |
| Database reads | Assume data could be corrupted — validate on read if used in security decisions |
| Environment variables | Type, format, required vs optional — fail fast on invalid config |
| External API responses | Schema validation — don't trust upstream services blindly |
| User-generated content | Sanitize for XSS, SQL injection, path traversal, command injection |
Allowlist over denylist. Define what IS allowed, never what ISN'T. Attackers are creative; your denylist isn't.
所有进入系统的数据在使用前必须完成校验:
| 边界 | 校验内容 |
|---|---|
| HTTP 请求 | 请求体、查询参数、请求头、路径参数 — 校验类型、长度、格式、取值范围 |
| 文件上传 | 文件类型、大小、实际内容(不单单校验扩展名)、文件名 sanitization |
| 数据库读取 | 假设数据可能已损坏,若用于安全决策则读取时必须校验 |
| 环境变量 | 校验类型、格式、必填/可选属性,配置非法时快速失败 |
| 外部 API 响应 | 做 schema 校验,不要盲目信任上游服务 |
| 用户生成内容 | 做XSS、SQL注入、路径遍历、命令注入防护的 sanitization 处理 |
优先用允许名单而非禁止名单。 明确定义允许的内容,而非列举禁止的内容。攻击者的手段层出不穷,你的禁止名单永远覆盖不全。
Rule 2: Authentication and Authorization
规则2:身份认证与权限控制
| Principle | Requirement |
|---|---|
| Authentication | Every endpoint must know who is calling. No anonymous access unless explicitly designed. |
| Authorization | Every operation must check if the caller is ALLOWED to do this. Auth ≠ authz. |
| Least privilege | Grant the minimum permissions needed. No admin-by-default. |
| Session management | Secure tokens (HttpOnly, Secure, SameSite), reasonable TTL, revocation support. |
| Password handling | bcrypt/scrypt/argon2 only. Never MD5/SHA for passwords. Never store plaintext. |
| API keys | Scoped, rotatable, revocable. Never embedded in client-side code. |
Every endpoint MUST have an explicit auth decision — either "this requires auth" or "this is intentionally public" (documented why).
| 原则 | 要求 |
|---|---|
| 身份认证(Authentication) | 每个接口必须识别调用方身份,除非明确设计为匿名访问 |
| 权限授权(Authorization) | 每个操作都必须校验调用方是否拥有执行权限,身份认证≠权限授权 |
| 最小权限原则 | 授予操作所需的最低权限,默认不分配管理员权限 |
| 会话管理 | 使用安全令牌(开启HttpOnly、Secure、SameSite属性)、合理的有效期、支持吊销机制 |
| 密码处理 | 仅使用bcrypt/scrypt/argon2算法加密,禁止用MD5/SHA处理密码,永远不存储明文密码 |
| API 密钥 | 限定作用范围、支持轮换、支持吊销,永远不要嵌入到客户端代码中 |
每个接口必须有明确的身份认证决策 —— 要么“该接口需要身份认证”,要么“该接口特意设为公开”(需文档说明原因)。
Rule 3: Secrets Management
规则3:密钥管理
Secrets MUST NEVER appear in:
- Source code (no hardcoded passwords, API keys, tokens)
- Git history (if committed accidentally, rotate immediately — don't just delete)
- Logs (mask/redact sensitive fields)
- Error messages (no stack traces with connection strings in production)
- Client-side code (no API keys in JavaScript bundles)
Secrets MUST live in:
- Environment variables (minimum)
- Secrets manager (AWS Secrets Manager, Vault, 1Password) for production
- files that are in
.envfor local development.gitignore
密钥永远不能出现在以下位置:
- 源代码中(不要硬编码密码、API密钥、令牌)
- Git 历史中(如果不小心提交了,立刻轮换密钥 —— 不要只是删除文件)
- 日志中(敏感字段要做掩码/脱敏处理)
- 错误信息中(生产环境不要返回带连接字符串的栈追踪信息)
- 客户端代码中(JavaScript 打包产物中不要包含API密钥)
密钥必须存储在:
- 环境变量(最低要求)
- 生产环境使用密钥管理工具(AWS Secrets Manager、Vault、1Password)
- 本地开发环境使用加入的
.gitignore文件存储.env
Rule 4: Defense in Depth
规则4:深度防御
No single security control is sufficient. Layer defenses:
Layer 1: Network — firewalls, VPN, TLS everywhere
Layer 2: Application — input validation, output encoding
Layer 3: Authentication — verify identity at every boundary
Layer 4: Authorization — check permissions for every operation
Layer 5: Data — encryption at rest and in transit
Layer 6: Monitoring — log security events, alert on anomaliesIf any single layer fails, the remaining layers MUST still protect the system. Never rely on "the firewall will stop it" or "users won't do that."
单一安全控制措施是不够的,要做分层防御:
Layer 1: Network — firewalls, VPN, TLS everywhere
Layer 2: Application — input validation, output encoding
Layer 3: Authentication — verify identity at every boundary
Layer 4: Authorization — check permissions for every operation
Layer 5: Data — encryption at rest and in transit
Layer 6: Monitoring — log security events, alert on anomalies如果任意一层失效,剩余的层必须仍能保护系统安全。永远不要依赖“防火墙会拦住攻击”或者“用户不会这么操作”这类假设。
Rule 5: Secure Defaults
规则5:安全默认配置
Every configuration, feature flag, and permission MUST default to the secure option:
- New users get minimum permissions, not admin.
- New endpoints require authentication, not allow anonymous.
- New features are disabled until explicitly enabled.
- CORS is restrictive until explicitly opened.
- CSP is strict until explicitly relaxed.
- TLS is required, not optional.
"Opt into risk, never opt out of safety."
所有配置、功能开关、权限的默认值都必须是最安全的选项:
- 新用户默认分配最低权限,而非管理员权限
- 新接口默认需要身份认证,而非允许匿名访问
- 新功能默认关闭,直到明确开启
- CORS 默认限制访问,直到明确放开
- CSP 默认严格限制,直到明确放宽
- TLS 默认强制开启,而非可选
“永远选择主动规避风险,而不是主动放弃安全”。
Rule 6: Dependency Security
规则6:依赖安全
| Practice | Frequency |
|---|---|
| Audit dependencies for known CVEs | Every build (CI) |
| Pin dependency versions | Always (lockfile) |
| Review new dependencies before adding | Every time |
| Remove unused dependencies | Every release |
| Prefer well-maintained dependencies | >1000 stars, active maintainer, no critical CVEs |
Before adding a dependency, ask: "Does this dependency have access to our users' data? What happens if it's compromised?" If the answer is scary, vendor it or find an alternative.
| 实践 | 执行频率 |
|---|---|
| 扫描依赖的已知CVE漏洞 | 每次构建(CI流程中) |
| 锁定依赖版本 | 始终(用锁文件) |
| 新增依赖前做评审 | 每次新增时 |
| 移除未使用的依赖 | 每次发版时 |
| 优先选择维护良好的依赖 | Star数>1000、维护者活跃、无严重CVE漏洞的依赖 |
新增依赖前先问自己: “这个依赖是否能接触到我们的用户数据?如果它被攻陷了会有什么后果?”如果后果很严重,要么做vendor处理要么找替代方案。
Rule 7: Output Encoding and Injection Prevention
规则7:输出编码与注入防护
| Attack | Prevention |
|---|---|
| SQL Injection | Parameterized queries ONLY. Never string concatenation. |
| XSS | Context-aware output encoding. CSP headers. |
| Command Injection | Never pass user input to shell commands. Use libraries. |
| Path Traversal | Validate and canonicalize file paths. Never use raw user input. |
| SSRF | Allowlist outbound URLs. Block internal network ranges. |
| Deserialization | Never deserialize untrusted data with native serializers. Use JSON. |
| CSRF | Anti-CSRF tokens for state-changing operations. SameSite cookies. |
If user input touches a query, command, path, or URL — it MUST be parameterized or sanitized.
| 攻击类型 | 防护手段 |
|---|---|
| SQL 注入 | 仅使用参数化查询,永远不要拼接SQL字符串 |
| XSS | 上下文感知的输出编码,配置CSP请求头 |
| 命令注入 | 永远不要把用户输入传给shell命令,使用封装好的库 |
| 路径遍历 | 校验并规范化文件路径,永远不要直接使用原始用户输入 |
| SSRF | 对外访问URL用允许名单限制,屏蔽内部网络地址段 |
| 反序列化漏洞 | 永远不要用原生序列化器反序列化不可信数据,使用JSON |
| CSRF | 状态变更操作添加CSRF令牌,使用SameSite属性的Cookie |
如果用户输入会接触到查询语句、命令、文件路径或者URL —— 必须做参数化处理或者sanitization校验。
Applying This Skill
规范落地方式
During Planning (brainstorming / writing-plans)
规划阶段(头脑风暴/编写方案)
Before finalizing any design or plan, run the Security Checklist:
- All system boundaries have input validation (allowlist-based)
- Every endpoint has an explicit auth/authz decision
- No secrets in source code, logs, or error messages
- Defense in depth — at least 3 layers protect sensitive operations
- All defaults are secure (auth required, permissions minimal, features disabled)
- Dependencies are audited and pinned
- All user input that touches queries/commands/paths is parameterized
If any item fails: redesign before proceeding to implementation.
最终确定任何设计或方案前,先跑一遍安全检查清单:
- 所有系统边界都做了基于允许名单的输入校验
- 每个接口都有明确的身份认证/权限授权决策
- 源代码、日志、错误信息中没有密钥
- 满足深度防御要求 —— 敏感操作至少有3层防护
- 所有默认配置都是安全的(需要认证、最小权限、功能默认关闭)
- 依赖都做了漏洞扫描并且锁定了版本
- 所有接触查询/命令/路径的用户输入都做了参数化处理
如果任意一项不满足:重新设计后再进入开发阶段。
During Implementation (executing-plans)
开发阶段(执行方案)
As you write code:
- Use parameterized queries for ALL database access. No exceptions.
- Add input validation at every API endpoint before any business logic.
- Never log sensitive data (passwords, tokens, PII, credit cards).
- Set security headers on every response (CSP, HSTS, X-Frame-Options).
- Use crypto libraries, never roll your own encryption.
- Add rate limiting to authentication endpoints.
写代码时要注意:
- 所有数据库访问都使用参数化查询,没有例外
- 所有API接口在执行业务逻辑前先做输入校验
- 永远不要打印敏感数据(密码、令牌、PII、信用卡信息)到日志
- 所有响应都添加安全请求头(CSP、HSTS、X-Frame-Options)
- 使用成熟的加密库,永远不要自己实现加密算法
- 身份认证接口添加限流配置
During Review (code-review / receiving-code-review)
评审阶段(代码评审/接收代码评审)
Verify these as part of every code review:
- No hardcoded secrets or credentials
- Input validation on all boundaries
- Parameterized queries (no string concatenation in SQL)
- Proper output encoding (no raw HTML insertion)
- Auth/authz checks on every endpoint
- No sensitive data in logs or error messages
- Security headers present
每次代码评审都要校验以下内容:
- 没有硬编码的密钥或凭证
- 所有边界都做了输入校验
- 使用参数化查询(SQL中没有字符串拼接)
- 做了正确的输出编码(没有直接插入原始HTML)
- 每个接口都做了身份认证/权限授权校验
- 日志和错误信息中没有敏感数据
- 响应包含安全请求头
When Modifying Existing Code
修改现有代码时
If existing code violates these rules:
- Security violations ARE required to fix if they're in code you're touching.
- If you discover a hardcoded secret, flag it immediately — even in unrelated code.
- If you're adding a new endpoint, it MUST have auth even if neighboring endpoints don't.
- Never make security worse. If existing code has validation, don't remove it.
如果现有代码违反了这些规则:
- 如果你正在修改的代码存在安全违规,必须修复
- 如果你发现了硬编码的密钥,立刻上报 —— 哪怕是不相关的代码里的
- 如果你新增了接口,哪怕相邻的接口没有身份认证,你的新接口也必须加
- 永远不要降低安全等级。如果现有代码有校验逻辑,不要删除它
OWASP Top 10 Quick Reference
OWASP Top 10 速查表
| # | Risk | Key Defense |
|---|---|---|
| A01 | Broken Access Control | Authz checks on every operation, deny by default |
| A02 | Cryptographic Failures | TLS everywhere, strong algorithms, no plaintext secrets |
| A03 | Injection | Parameterized queries, input validation |
| A04 | Insecure Design | Threat modeling during planning, not after |
| A05 | Security Misconfiguration | Secure defaults, no default credentials |
| A06 | Vulnerable Components | Dependency scanning, pinned versions |
| A07 | Auth Failures | MFA, rate limiting, secure session management |
| A08 | Data Integrity Failures | Signed updates, CI/CD security, input validation |
| A09 | Logging Failures | Log security events, don't log secrets, monitor |
| A10 | SSRF | Allowlist outbound URLs, block internal ranges |
| 序号 | 风险 | 核心防御手段 |
|---|---|---|
| A01 | 访问控制失效 | 每次操作都做权限校验,默认拒绝 |
| A02 | 加密失效 | 全链路开启TLS,使用强加密算法,不存储明文密钥 |
| A03 | 注入漏洞 | 使用参数化查询,做输入校验 |
| A04 | 不安全设计 | 规划阶段做威胁建模,不要事后补 |
| A05 | 安全配置错误 | 安全默认配置,不使用默认凭证 |
| A06 | 存在漏洞的组件 | 依赖漏洞扫描,锁定依赖版本 |
| A07 | 身份认证失效 | 开启MFA,接口限流,安全的会话管理 |
| A08 | 数据完整性失效 | 签名更新,CI/CD安全防护,输入校验 |
| A09 | 日志与监控失效 | 记录安全事件,不打印密钥,做异常监控 |
| A10 | SSRF | 对外访问URL用允许名单限制,屏蔽内部地址段 |
Anti-Patterns
反模式
| Pattern | Problem | Fix |
|---|---|---|
| "Security through obscurity" | Hiding ≠ protecting | Proper access controls |
| Trusting client-side validation | Trivially bypassed | Server-side validation always |
Broad CORS ( | Any origin can access API | Explicit origin allowlist |
| Admin-by-default | Over-privileged users | Least privilege, role-based access |
| Logging everything | Secrets in logs | Structured logging with redaction |
| Rolling your own crypto | Guaranteed vulnerabilities | Use vetted libraries (libsodium, etc.) |
| 反模式 | 问题 | 修复方案 |
|---|---|---|
| “模糊式安全” | 隐藏不等于保护 | 做完善的访问控制 |
| 只依赖客户端校验 | 可以轻松绕过 | 永远要做服务端校验 |
宽松CORS配置( | 任何来源都可以访问API | 明确配置允许的来源名单 |
| 默认管理员权限 | 用户权限过大 | 最小权限原则,基于角色的权限控制 |
| 不加区分打印所有日志 | 日志中泄露密钥 | 结构化日志+自动脱敏 |
| 自己实现加密算法 | 必然存在漏洞 | 使用经过验证的加密库(如libsodium等) |
Rationalization Prevention
常见借口纠偏
| Excuse | Reality |
|---|---|
| "It's just an internal tool" | Internal tools get compromised. Insider threats are real. |
| "We'll add security later" | Later never comes. Vulnerabilities ship. |
| "Nobody would try that" | They will. And they have automated tools. |
| "It's behind a firewall" | Firewalls get bypassed. Defense in depth. |
| "We don't have sensitive data" | User emails, passwords, and usage patterns are sensitive. |
| "This is just a prototype" | Prototypes become production. Secure from day one. |
| 借口 | 现实 |
|---|---|
| “这只是个内部工具” | 内部工具也会被攻陷,内部威胁是真实存在的 |
| “我们后面再加安全” | 后面永远不会来,漏洞会直接上线 |
| “没人会这么攻击的” | 他们会的,而且还有自动化攻击工具 |
| “它在防火墙后面” | 防火墙可以被绕过,要做深度防御 |
| “我们没有敏感数据” | 用户邮箱、密码、使用行为都是敏感数据 |
| “这只是个原型” | 原型最终会变成生产代码,从第一天就做安全 |