security-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity Patterns
安全模式
Comprehensive security patterns for building hardened applications. Each category has individual rule files in loaded on-demand.
rules/用于构建高安全性应用的全面安全模式。每个分类在目录下都有独立的规则文件,可按需加载。
rules/Quick Reference
快速参考
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Authentication | 3 | CRITICAL | JWT tokens, OAuth 2.1/PKCE, RBAC/permissions |
| Defense-in-Depth | 2 | CRITICAL | Multi-layer security, zero-trust architecture |
| Input Validation | 3 | HIGH | Schema validation (Zod/Pydantic), output encoding, file uploads |
| OWASP Top 10 | 2 | CRITICAL | Injection prevention, broken authentication fixes |
| LLM Safety | 3 | HIGH | Prompt injection defense, output guardrails, content filtering |
| PII Masking | 2 | HIGH | PII detection/redaction with Presidio, Langfuse, LLM Guard |
| Scanning | 3 | HIGH | Dependency audit, SAST (Semgrep/Bandit), secret detection |
| Advanced Guardrails | 2 | CRITICAL | NeMo/Guardrails AI validators, red-teaming, OWASP LLM |
Total: 20 rules across 8 categories
| 分类 | 规则数量 | 影响级别 | 使用场景 |
|---|---|---|---|
| 身份认证 | 3 | 关键 | JWT令牌、OAuth 2.1/PKCE、RBAC/权限管理 |
| 深度防御 | 2 | 关键 | 多层安全架构、零信任架构 |
| 输入验证 | 3 | 高 | Schema验证(Zod/Pydantic)、输出编码、文件上传 |
| OWASP Top 10 | 2 | 关键 | 注入攻击预防、身份认证漏洞修复 |
| LLM安全 | 3 | 高 | 提示注入防御、输出管控、内容过滤 |
| PII掩码 | 2 | 高 | 结合Presidio、Langfuse、LLM Guard的PII检测/脱敏 |
| 扫描检测 | 3 | 高 | 依赖审计、SAST(Semgrep/Bandit)、密钥检测 |
| 高级管控 | 2 | 关键 | NeMo/Guardrails AI验证器、红队测试、OWASP LLM合规 |
总计:8个分类共20条规则
Quick Start
快速开始
python
undefinedpython
undefinedArgon2id password hashing
Argon2id密码哈希
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)
```pythonfrom argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)
```pythonJWT access token (15-min expiry)
JWT访问令牌(15分钟过期)
import jwt
from datetime import datetime, timedelta, timezone
payload = {
'sub': user_id, 'type': 'access',
'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
```typescript
// Zod v4 schema validation
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
role: z.enum(['user', 'admin']).default('user'),
});
const result = UserSchema.safeParse(req.body);python
undefinedimport jwt
from datetime import datetime, timedelta, timezone
payload = {
'sub': user_id, 'type': 'access',
'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
```typescript
// Zod v4 Schema验证
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
role: z.enum(['user', 'admin']).default('user'),
});
const result = UserSchema.safeParse(req.body);python
undefinedPII masking with Langfuse
结合Langfuse的PII掩码
import re
from langfuse import Langfuse
def mask_pii(data, **kwargs):
if isinstance(data, str):
data = re.sub(r'\b[\w.-]+@[\w.-]+.\w+\b', '[REDACTED_EMAIL]', data)
data = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED_SSN]', data)
return data
langfuse = Langfuse(mask=mask_pii)
undefinedimport re
from langfuse import Langfuse
def mask_pii(data, **kwargs):
if isinstance(data, str):
data = re.sub(r'\b[\w.-]+@[\w.-]+.\w+\b', '[REDACTED_EMAIL]', data)
data = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED_SSN]', data)
return data
langfuse = Langfuse(mask=mask_pii)
undefinedAuthentication
身份认证
Secure authentication with OAuth 2.1, Passkeys/WebAuthn, JWT tokens, and role-based access control.
| Rule | Description |
|---|---|
| JWT creation, verification, expiry, refresh token rotation |
| OAuth 2.1 with PKCE, DPoP, Passkeys/WebAuthn |
| Role-based access control, permission decorators, MFA |
Key Decisions: Argon2id > bcrypt | Access tokens 15 min | PKCE required | Passkeys > TOTP > SMS
采用OAuth 2.1、Passkeys/WebAuthn、JWT令牌及基于角色的访问控制实现安全身份认证。
| 规则 | 描述 |
|---|---|
| JWT创建、验证、过期处理、刷新令牌轮转 |
| 结合PKCE、DPoP、Passkeys/WebAuthn的OAuth 2.1 |
| 基于角色的访问控制、权限装饰器、多因素认证(MFA) |
核心决策: Argon2id > bcrypt | 访问令牌有效期15分钟 | 强制要求PKCE | Passkeys > TOTP > 短信验证
Defense-in-Depth
深度防御
Multi-layer security architecture with no single point of failure.
| Rule | Description |
|---|---|
| 8-layer security architecture (edge to observability) |
| Immutable request context, tenant isolation, audit logging |
Key Decisions: Immutable dataclass context | Query-level tenant filtering | No IDs in LLM prompts
无单点故障的多层安全架构。
| 规则 | 描述 |
|---|---|
| 8层安全架构(从边缘到可观测性) |
| 不可变请求上下文、租户隔离、审计日志 |
核心决策: 不可变数据类上下文 | 查询级租户过滤 | LLM提示中不包含ID
Input Validation
输入验证
Validate and sanitize all untrusted input using Zod v4 and Pydantic.
| Rule | Description |
|---|---|
| Schema validation with Zod v4 and Pydantic, type coercion |
| HTML sanitization, output encoding, XSS prevention |
| Discriminated unions, file upload validation, URL allowlists |
Key Decisions: Allowlist over blocklist | Server-side always | Validate magic bytes not extensions
使用Zod v4和Pydantic验证并清理所有不可信输入。
| 规则 | 描述 |
|---|---|
| 采用Zod v4和Pydantic的Schema验证、类型转换 |
| HTML清理、输出编码、XSS预防 |
| 可区分联合类型、文件上传验证、URL白名单 |
核心决策: 优先使用白名单而非黑名单 | 始终在服务端验证 | 验证魔术字节而非文件扩展名
OWASP Top 10
OWASP Top 10
Protection against the most critical web application security risks.
| Rule | Description |
|---|---|
| SQL/command injection, parameterized queries, SSRF prevention |
| JWT algorithm confusion, CSRF protection, timing attacks |
Key Decisions: Parameterized queries only | Hardcode JWT algorithm | SameSite=Strict cookies
针对最关键的Web应用安全风险的防护措施。
| 规则 | 描述 |
|---|---|
| SQL/命令注入预防、参数化查询、SSRF防护 |
| JWT算法混淆防护、CSRF防护、时序攻击防护 |
核心决策: 仅使用参数化查询 | 硬编码JWT算法 | SameSite=Strict Cookie
LLM Safety
LLM安全
Security patterns for LLM integrations including context separation and output validation.
| Rule | Description |
|---|---|
| Context separation, prompt auditing, forbidden patterns |
| Output validation pipeline: schema, grounding, safety, size |
| Pre-LLM filtering, post-LLM attribution, three-phase pattern |
Key Decisions: IDs flow around LLM, never through | Attribution is deterministic | Audit every prompt
适用于LLM集成的安全模式,包括上下文分离和输出验证。
| 规则 | 描述 |
|---|---|
| 上下文分离、提示审计、禁用模式 |
| 输出验证流水线:Schema、事实依据、安全、大小 |
| LLM前过滤、LLM后归因、三阶段模式 |
核心决策: ID绕开LLM传递,而非通过LLM | 归因具有确定性 | 审计所有提示
PII Masking
PII掩码
PII detection and masking for LLM observability pipelines and logging.
| Rule | Description |
|---|---|
| Microsoft Presidio, regex patterns, LLM Guard Anonymize |
| Langfuse mask callback, structlog/loguru processors, Vault deanonymization |
Key Decisions: Presidio for enterprise | Replace with type tokens | Use mask callback at init
针对LLM可观测性流水线和日志的PII检测与掩码处理。
| 规则 | 描述 |
|---|---|
| Microsoft Presidio、正则表达式模式、LLM Guard匿名化 |
| Langfuse掩码回调、structlog/loguru处理器、Vault去匿名化 |
核心决策: 企业级场景使用Presidio | 用类型令牌替换敏感数据 | 初始化时使用掩码回调
Scanning
扫描检测
Automated security scanning for dependencies, code, and secrets.
| Rule | Description |
|---|---|
| npm audit, pip-audit, Trivy container scanning, CI gating |
| Semgrep and Bandit static analysis, custom rules, pre-commit |
| Gitleaks, TruffleHog, detect-secrets with baseline management |
Key Decisions: Pre-commit hooks for shift-left | Block on critical/high | Gitleaks + detect-secrets baseline
针对依赖、代码和密钥的自动化安全扫描。
| 规则 | 描述 |
|---|---|
| npm audit、pip-audit、Trivy容器扫描、CI门禁 |
| Semgrep和Bandit静态分析、自定义规则、提交前检查 |
| Gitleaks、TruffleHog、detect-secrets及基线管理 |
核心决策: 左移至提交前钩子 | 阻断关键/高危漏洞 | Gitleaks + detect-secrets基线
Advanced Guardrails
高级管控
Production LLM safety with NeMo Guardrails, Guardrails AI validators, and DeepTeam red-teaming.
| Rule | Description |
|---|---|
| NeMo Guardrails, Colang 2.0 flows, Guardrails AI validators, layered validation |
| DeepTeam red-teaming (40+ vulnerabilities), OWASP LLM Top 10 compliance |
Key Decisions: NeMo for flows, Guardrails AI for validators | Toxicity 0.5 threshold | Red-team pre-release + quarterly
采用NeMo Guardrails、Guardrails AI验证器和DeepTeam红队测试的生产级LLM安全措施。
| 规则 | 描述 |
|---|---|
| NeMo Guardrails、Colang 2.0流程、Guardrails AI验证器、分层验证 |
| DeepTeam红队测试(40+漏洞)、OWASP LLM Top 10合规 |
核心决策: NeMo用于流程,Guardrails AI用于验证器 | 毒性阈值0.5 | 发布前及每季度进行红队测试
Anti-Patterns (FORBIDDEN)
反模式(禁止使用)
python
undefinedpython
undefinedAuthentication
身份认证
user.password = request.form['password'] # Plaintext password storage
response_type=token # Implicit OAuth grant (deprecated)
return "Email not found" # Information disclosure
user.password = request.form['password'] # 明文存储密码
response_type=token # 隐式OAuth授权(已弃用)
return "Email not found" # 信息泄露
Input Validation
输入验证
"SELECT * FROM users WHERE name = '" + name + "'" # SQL injection
if (file.type === 'image/png') {...} # Trusting Content-Type header
"SELECT * FROM users WHERE name = '" + name + "'" # SQL注入
if (file.type === 'image/png') {...} # 信任Content-Type头
LLM Safety
LLM安全
prompt = f"Analyze for user {user_id}" # ID in prompt
artifact.user_id = llm_output["user_id"] # Trusting LLM-generated IDs
prompt = f"Analyze for user {user_id}" # 提示中包含ID
artifact.user_id = llm_output["user_id"] # 信任LLM生成的ID
PII
PII
logger.info(f"User email: {user.email}") # Raw PII in logs
langfuse.trace(input=raw_prompt) # Unmasked observability data
undefinedlogger.info(f"User email: {user.email}") # 日志中包含原始PII
langfuse.trace(input=raw_prompt) # 未掩码的可观测性数据
undefinedDetailed Documentation
详细文档
| Resource | Description |
|---|---|
| references/oauth-2.1-passkeys.md | OAuth 2.1, PKCE, DPoP, Passkeys/WebAuthn |
| references/request-context-pattern.md | Immutable request context for identity flow |
| references/tenant-isolation.md | Tenant-scoped repository, vector/full-text search |
| references/audit-logging.md | Sanitized structured logging, compliance |
| references/zod-v4-api.md | Zod v4 types, coercion, transforms, refinements |
| references/vulnerability-demos.md | OWASP vulnerable vs secure code examples |
| references/context-separation.md | LLM context separation architecture |
| references/output-guardrails.md | Output validation pipeline implementation |
| references/pre-llm-filtering.md | Tenant-scoped retrieval, content extraction |
| references/post-llm-attribution.md | Deterministic attribution pattern |
| references/prompt-audit.md | Prompt audit patterns, safe prompt builder |
| references/presidio-integration.md | Microsoft Presidio setup, custom recognizers |
| references/langfuse-mask-callback.md | Langfuse SDK mask implementation |
| references/llm-guard-sanitization.md | LLM Guard Anonymize/Deanonymize with Vault |
| references/logging-redaction.md | structlog/loguru pre-logging redaction |
| 资源 | 描述 |
|---|---|
| references/oauth-2.1-passkeys.md | OAuth 2.1、PKCE、DPoP、Passkeys/WebAuthn |
| references/request-context-pattern.md | 用于身份流转的不可变请求上下文 |
| references/tenant-isolation.md | 租户范围的存储库、向量/全文搜索 |
| references/audit-logging.md | 已清理的结构化日志、合规性 |
| references/zod-v4-api.md | Zod v4类型、转换、变换、细化 |
| references/vulnerability-demos.md | OWASP漏洞与安全代码示例对比 |
| references/context-separation.md | LLM上下文分离架构 |
| references/output-guardrails.md | 输出验证流水线实现 |
| references/pre-llm-filtering.md | 租户范围的检索、内容提取 |
| references/post-llm-attribution.md | 确定性归因模式 |
| references/prompt-audit.md | 提示审计模式、安全提示构建器 |
| references/presidio-integration.md | Microsoft Presidio设置、自定义识别器 |
| references/langfuse-mask-callback.md | Langfuse SDK掩码实现 |
| references/llm-guard-sanitization.md | 结合Vault的LLM Guard匿名化/去匿名化 |
| references/logging-redaction.md | structlog/loguru日志前脱敏 |
Related Skills
相关技能
- - API security patterns
api-design-framework - - RAG pipeline patterns requiring tenant-scoped retrieval
rag-retrieval - - Output quality assessment including hallucination detection
llm-evaluation
- - API安全模式
api-design-framework - - 需租户范围检索的RAG流水线模式
rag-retrieval - - 输出质量评估,包括幻觉检测
llm-evaluation
Capability Details
能力详情
authentication
authentication
Keywords: password, hashing, JWT, token, OAuth, PKCE, passkey, WebAuthn, RBAC, session
Solves:
- Implement secure authentication with modern standards
- JWT token management with proper expiry
- OAuth 2.1 with PKCE flow
- Passkeys/WebAuthn registration and login
- Role-based access control
关键词: password, hashing, JWT, token, OAuth, PKCE, passkey, WebAuthn, RBAC, session
解决问题:
- 采用现代标准实现安全身份认证
- 带合理过期时间的JWT令牌管理
- 结合PKCE的OAuth 2.1流程
- Passkeys/WebAuthn注册与登录
- 基于角色的访问控制
defense-in-depth
defense-in-depth
Keywords: defense in depth, security layers, multi-layer, request context, tenant isolation
Solves:
- How to secure AI applications end-to-end
- Implement 8-layer security architecture
- Create immutable request context
- Ensure tenant isolation at query level
关键词: defense in depth, security layers, multi-layer, request context, tenant isolation
解决问题:
- 如何端到端保护AI应用
- 实现8层安全架构
- 创建不可变请求上下文
- 在查询级确保租户隔离
input-validation
input-validation
Keywords: schema, validate, Zod, Pydantic, sanitize, HTML, XSS, file upload
Solves:
- Validate input against schemas (Zod v4, Pydantic)
- Prevent injection attacks with allowlists
- Sanitize HTML and prevent XSS
- Validate file uploads by magic bytes
关键词: schema, validate, Zod, Pydantic, sanitize, HTML, XSS, file upload
解决问题:
- 基于Schema验证输入(Zod v4、Pydantic)
- 用白名单预防注入攻击
- 清理HTML并预防XSS
- 通过魔术字节验证文件上传
owasp-top-10
owasp-top-10
Keywords: OWASP, sql injection, broken access control, CSRF, XSS, SSRF
Solves:
- Fix OWASP Top 10 vulnerabilities
- Prevent SQL and command injection
- Implement CSRF protection
- Fix broken authentication
关键词: OWASP, sql injection, broken access control, CSRF, XSS, SSRF
解决问题:
- 修复OWASP Top 10漏洞
- 预防SQL和命令注入
- 实现CSRF防护
- 修复身份认证漏洞
llm-safety
llm-safety
Keywords: prompt injection, context separation, guardrails, hallucination, LLM output
Solves:
- Prevent prompt injection attacks
- Implement context separation (IDs around LLM)
- Validate LLM output with guardrail pipeline
- Deterministic post-LLM attribution
关键词: prompt injection, context separation, guardrails, hallucination, LLM output
解决问题:
- 预防提示注入攻击
- 实现上下文分离(ID绕开LLM)
- 用管控流水线验证LLM输出
- 确定性LLM后归因
pii-masking
pii-masking
Keywords: PII, masking, Presidio, Langfuse, redact, GDPR, privacy
Solves:
- Detect and mask PII in LLM pipelines
- Integrate masking with Langfuse observability
- Implement pre-logging redaction
- GDPR-compliant data handling
关键词: PII, masking, Presidio, Langfuse, redact, GDPR, privacy
解决问题:
- 在LLM流水线中检测并掩码PII
- 将掩码与Langfuse可观测性集成
- 实现日志前脱敏
- GDPR合规的数据处理