AgentSkillsCN

security-patterns

适用于身份验证、纵深防御、输入验证、OWASP十大安全风险、LLM安全以及PII脱敏的安全模式。在实施认证流程、构建安全层级、进行输入净化、预防漏洞、抵御提示注入攻击,或执行数据脱敏操作时使用此功能。

SKILL.md
--- frontmatter
name: security-patterns
license: MIT
compatibility: "Claude Code 2.1.34+."
description: Security patterns for authentication, defense-in-depth, input validation, OWASP Top 10, LLM safety, and PII masking. Use when implementing auth flows, security layers, input sanitization, vulnerability prevention, prompt injection defense, or data redaction.
tags: [security, authentication, authorization, defense-in-depth, owasp, input-validation, llm-safety, pii-masking, jwt, oauth]
context: fork
agent: security-auditor
version: 2.0.0
author: OrchestKit
user-invocable: false
complexity: high
metadata:
  category: document-asset-creation

Security Patterns

Comprehensive security patterns for building hardened applications. Each category has individual rule files in rules/ loaded on-demand.

Quick Reference

CategoryRulesImpactWhen to Use
Authentication3CRITICALJWT tokens, OAuth 2.1/PKCE, RBAC/permissions
Defense-in-Depth2CRITICALMulti-layer security, zero-trust architecture
Input Validation3HIGHSchema validation (Zod/Pydantic), output encoding, file uploads
OWASP Top 102CRITICALInjection prevention, broken authentication fixes
LLM Safety3HIGHPrompt injection defense, output guardrails, content filtering
PII Masking2HIGHPII detection/redaction with Presidio, Langfuse, LLM Guard
Scanning3HIGHDependency audit, SAST (Semgrep/Bandit), secret detection
Advanced Guardrails2CRITICALNeMo/Guardrails AI validators, red-teaming, OWASP LLM

Total: 20 rules across 8 categories

Quick Start

python
# Argon2id password hashing
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)
python
# JWT access token (15-min expiry)
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
# PII masking with Langfuse
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)

Authentication

Secure authentication with OAuth 2.1, Passkeys/WebAuthn, JWT tokens, and role-based access control.

RuleDescription
auth-jwt.mdJWT creation, verification, expiry, refresh token rotation
auth-oauth.mdOAuth 2.1 with PKCE, DPoP, Passkeys/WebAuthn
auth-rbac.mdRole-based access control, permission decorators, MFA

Key Decisions: Argon2id > bcrypt | Access tokens 15 min | PKCE required | Passkeys > TOTP > SMS

Defense-in-Depth

Multi-layer security architecture with no single point of failure.

RuleDescription
defense-layers.md8-layer security architecture (edge to observability)
defense-zero-trust.mdImmutable request context, tenant isolation, audit logging

Key Decisions: Immutable dataclass context | Query-level tenant filtering | No IDs in LLM prompts

Input Validation

Validate and sanitize all untrusted input using Zod v4 and Pydantic.

RuleDescription
validation-input.mdSchema validation with Zod v4 and Pydantic, type coercion
validation-output.mdHTML sanitization, output encoding, XSS prevention
validation-schemas.mdDiscriminated unions, file upload validation, URL allowlists

Key Decisions: Allowlist over blocklist | Server-side always | Validate magic bytes not extensions

OWASP Top 10

Protection against the most critical web application security risks.

RuleDescription
owasp-injection.mdSQL/command injection, parameterized queries, SSRF prevention
owasp-broken-auth.mdJWT algorithm confusion, CSRF protection, timing attacks

Key Decisions: Parameterized queries only | Hardcode JWT algorithm | SameSite=Strict cookies

LLM Safety

Security patterns for LLM integrations including context separation and output validation.

RuleDescription
llm-prompt-injection.mdContext separation, prompt auditing, forbidden patterns
llm-guardrails.mdOutput validation pipeline: schema, grounding, safety, size
llm-content-filtering.mdPre-LLM filtering, post-LLM attribution, three-phase pattern

Key Decisions: IDs flow around LLM, never through | Attribution is deterministic | Audit every prompt

PII Masking

PII detection and masking for LLM observability pipelines and logging.

RuleDescription
pii-detection.mdMicrosoft Presidio, regex patterns, LLM Guard Anonymize
pii-redaction.mdLangfuse mask callback, structlog/loguru processors, Vault deanonymization

Key Decisions: Presidio for enterprise | Replace with type tokens | Use mask callback at init

Scanning

Automated security scanning for dependencies, code, and secrets.

RuleDescription
scanning-dependency.mdnpm audit, pip-audit, Trivy container scanning, CI gating
scanning-sast.mdSemgrep and Bandit static analysis, custom rules, pre-commit
scanning-secrets.mdGitleaks, TruffleHog, detect-secrets with baseline management

Key Decisions: Pre-commit hooks for shift-left | Block on critical/high | Gitleaks + detect-secrets baseline

Advanced Guardrails

Production LLM safety with NeMo Guardrails, Guardrails AI validators, and DeepTeam red-teaming.

RuleDescription
guardrails-nemo.mdNeMo Guardrails, Colang 2.0 flows, Guardrails AI validators, layered validation
guardrails-llm-validation.mdDeepTeam 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

Anti-Patterns (FORBIDDEN)

python
# Authentication
user.password = request.form['password']       # Plaintext password storage
response_type=token                             # Implicit OAuth grant (deprecated)
return "Email not found"                        # Information disclosure

# Input Validation
"SELECT * FROM users WHERE name = '" + name + "'"  # SQL injection
if (file.type === 'image/png') {...}               # Trusting Content-Type header

# LLM Safety
prompt = f"Analyze for user {user_id}"             # ID in prompt
artifact.user_id = llm_output["user_id"]           # Trusting LLM-generated IDs

# PII
logger.info(f"User email: {user.email}")           # Raw PII in logs
langfuse.trace(input=raw_prompt)                   # Unmasked observability data

Detailed Documentation

ResourceDescription
references/oauth-2.1-passkeys.mdOAuth 2.1, PKCE, DPoP, Passkeys/WebAuthn
references/request-context-pattern.mdImmutable request context for identity flow
references/tenant-isolation.mdTenant-scoped repository, vector/full-text search
references/audit-logging.mdSanitized structured logging, compliance
references/zod-v4-api.mdZod v4 types, coercion, transforms, refinements
references/vulnerability-demos.mdOWASP vulnerable vs secure code examples
references/context-separation.mdLLM context separation architecture
references/output-guardrails.mdOutput validation pipeline implementation
references/pre-llm-filtering.mdTenant-scoped retrieval, content extraction
references/post-llm-attribution.mdDeterministic attribution pattern
references/prompt-audit.mdPrompt audit patterns, safe prompt builder
references/presidio-integration.mdMicrosoft Presidio setup, custom recognizers
references/langfuse-mask-callback.mdLangfuse SDK mask implementation
references/llm-guard-sanitization.mdLLM Guard Anonymize/Deanonymize with Vault
references/logging-redaction.mdstructlog/loguru pre-logging redaction

Related Skills

  • api-design-framework - API security patterns
  • rag-retrieval - RAG pipeline patterns requiring tenant-scoped retrieval
  • llm-evaluation - Output quality assessment including hallucination detection

Capability Details

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

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

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

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

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

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