references/hardening-patterns.md
13.8 KB查看排版效果| 1 | # Hardening Patterns |
| 2 | |
| 3 | Code patterns and decision aids for the `security-and-hardening` skill. The skill states each rule; this file shows one concrete implementation of it. Open the section you need when you reach that code — it is not meant to be read top to bottom. |
| 4 | |
| 5 | Shared checklists (threat modeling, pre-commit checks, security headers, CORS, the package-manager matrix, install-script gate, and the OWASP quick-reference tables) live in `../references/shared/security-checklist.md`. |
| 6 | |
| 7 | ## OWASP Top 10 Prevention Patterns |
| 8 | |
| 9 | These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in `../references/shared/security-checklist.md#owasp-top-10-quick-reference`. |
| 10 | |
| 11 | ### Injection |
| 12 | |
| 13 | ```typescript |
| 14 | // BAD: SQL injection via string concatenation |
| 15 | const query = `SELECT * FROM users WHERE id = '${userId}'`; |
| 16 | |
| 17 | // GOOD: Parameterized query |
| 18 | const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]); |
| 19 | |
| 20 | // GOOD: ORM with parameterized input |
| 21 | const user = await prisma.user.findUnique({ where: { id: userId } }); |
| 22 | ``` |
| 23 | |
| 24 | ### Broken Authentication |
| 25 | |
| 26 | ```typescript |
| 27 | // Password hashing |
| 28 | import { hash, compare } from 'bcrypt'; |
| 29 | |
| 30 | const SALT_ROUNDS = 12; |
| 31 | const hashedPassword = await hash(plaintext, SALT_ROUNDS); |
| 32 | const isValid = await compare(plaintext, hashedPassword); |
| 33 | |
| 34 | // Session management |
| 35 | const SESSION_SECRET = process.env.SESSION_SECRET; // From environment, not code |
| 36 | if (!SESSION_SECRET) throw new Error('SESSION_SECRET not configured'); |
| 37 | app.use(session({ |
| 38 | secret: SESSION_SECRET, |
| 39 | resave: false, |
| 40 | saveUninitialized: false, |
| 41 | cookie: { |
| 42 | httpOnly: true, // Not accessible via JavaScript |
| 43 | secure: true, // HTTPS only |
| 44 | sameSite: 'lax', // CSRF protection |
| 45 | maxAge: 24 * 60 * 60 * 1000, // 24 hours |
| 46 | }, |
| 47 | })); |
| 48 | ``` |
| 49 | |
| 50 | ### Cross-Site Scripting (XSS) |
| 51 | |
| 52 | ```typescript |
| 53 | // BAD: Rendering user input as HTML |
| 54 | element.innerHTML = userInput; |
| 55 | |
| 56 | // GOOD: Use framework auto-escaping (React does this by default) |
| 57 | return <div>{userInput}</div>; |
| 58 | |
| 59 | // If you MUST render HTML, sanitize first |
| 60 | import DOMPurify from 'dompurify'; |
| 61 | const clean = DOMPurify.sanitize(userInput); |
| 62 | ``` |
| 63 | |
| 64 | ### Broken Access Control |
| 65 | |
| 66 | ```typescript |
| 67 | // Always check authorization, not just authentication |
| 68 | app.patch('/api/tasks/:id', authenticate, async (req, res) => { |
| 69 | const task = await taskService.findById(req.params.id); |
| 70 | if (!task) { |
| 71 | return res.status(404).json({ |
| 72 | error: { code: 'NOT_FOUND', message: 'Task not found' } |
| 73 | }); |
| 74 | } |
| 75 | |
| 76 | // Check that the authenticated user owns this resource |
| 77 | if (task.ownerId !== req.user.id) { |
| 78 | return res.status(403).json({ |
| 79 | error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' } |
| 80 | }); |
| 81 | } |
| 82 | |
| 83 | // Proceed with update |
| 84 | const updated = await taskService.update(req.params.id, req.body); |
| 85 | return res.json(updated); |
| 86 | }); |
| 87 | ``` |
| 88 | |
| 89 | ### Security Misconfiguration |
| 90 | |
| 91 | ```typescript |
| 92 | // Security headers (use helmet for Express) |
| 93 | import helmet from 'helmet'; |
| 94 | app.use(helmet()); |
| 95 | |
| 96 | // Content Security Policy |
| 97 | app.use(helmet.contentSecurityPolicy({ |
| 98 | directives: { |
| 99 | defaultSrc: ["'self'"], |
| 100 | scriptSrc: ["'self'"], |
| 101 | styleSrc: ["'self'", "'unsafe-inline'"], // Tighten if possible |
| 102 | imgSrc: ["'self'", 'data:', 'https:'], |
| 103 | connectSrc: ["'self'"], |
| 104 | }, |
| 105 | })); |
| 106 | |
| 107 | // CORS — restrict to known origins |
| 108 | app.use(cors({ |
| 109 | origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000', |
| 110 | credentials: true, |
| 111 | })); |
| 112 | ``` |
| 113 | |
| 114 | ### Sensitive Data Exposure |
| 115 | |
| 116 | ```typescript |
| 117 | // Never return sensitive fields in API responses |
| 118 | function sanitizeUser(user: UserRecord): PublicUser { |
| 119 | const { passwordHash, resetToken, ...publicFields } = user; |
| 120 | return publicFields; |
| 121 | } |
| 122 | |
| 123 | // Use environment variables for secrets |
| 124 | const API_KEY = process.env.STRIPE_API_KEY; |
| 125 | if (!API_KEY) throw new Error('STRIPE_API_KEY not configured'); |
| 126 | ``` |
| 127 | |
| 128 | ### Server-Side Request Forgery (SSRF) |
| 129 | |
| 130 | Any time the server fetches a URL the user influenced — webhooks, "import from URL", image proxies, link previews — an attacker can aim it at internal services (cloud metadata, `localhost`, private IPs). |
| 131 | |
| 132 | **Incomplete example — URL pre-validation only.** The checks below reject disallowed URLs and addresses at validation time, but do not bind the later connection to those addresses. Do not copy this as a complete SSRF defense. |
| 133 | |
| 134 | ```typescript |
| 135 | // BAD: fetch whatever the user gives you |
| 136 | await fetch(req.body.webhookUrl); |
| 137 | |
| 138 | // PARTIAL: allowlist scheme + host, reject private/reserved IPs before connecting |
| 139 | import { lookup } from 'node:dns/promises'; |
| 140 | import ipaddr from 'ipaddr.js'; |
| 141 | |
| 142 | const ALLOWED_HOSTS = new Set(['hooks.example.com']); |
| 143 | |
| 144 | async function prevalidateUrl(raw: string): Promise<URL> { |
| 145 | const url = new URL(raw); |
| 146 | if (url.protocol !== 'https:') throw new Error('https only'); |
| 147 | if (!ALLOWED_HOSTS.has(url.hostname)) throw new Error('host not allowed'); |
| 148 | // Resolve ALL records; a single private/reserved address fails the check. |
| 149 | const addrs = await lookup(url.hostname, { all: true }); |
| 150 | if (addrs.some((a) => ipaddr.parse(a.address).range() !== 'unicast')) { |
| 151 | throw new Error('private/reserved IP'); |
| 152 | } |
| 153 | return url; |
| 154 | } |
| 155 | |
| 156 | // INCOMPLETE: fetch resolves DNS again; the checked addresses are not pinned. |
| 157 | await fetch(await prevalidateUrl(req.body.webhookUrl), { redirect: 'error' }); |
| 158 | ``` |
| 159 | |
| 160 | The `range() !== 'unicast'` check covers loopback, link-local `169.254.169.254` (cloud metadata, the #1 SSRF target), private, and unique-local ranges across IPv4 and IPv6. |
| 161 | |
| 162 | **Close the check/connection gap before using this with untrusted URLs.** An attacker using a short-TTL record can rebind to an internal IP between validation and connection. Use an HTTP transport that connects only to validated addresses, or a filtering transport that enforces the destination policy at connection time. Preserve the original hostname for the HTTP `Host` header, TLS SNI, and certificate verification; keep redirects disabled and enforce the same policy on retries and fallback connections. See the [OWASP SSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html#domain-name). |
| 163 | |
| 164 | ## Input Validation Patterns |
| 165 | |
| 166 | ### Schema Validation at Boundaries |
| 167 | |
| 168 | ```typescript |
| 169 | import { z } from 'zod'; |
| 170 | |
| 171 | const CreateTaskSchema = z.object({ |
| 172 | title: z.string().max(200).trim().min(1), |
| 173 | description: z.string().max(2000).optional(), |
| 174 | priority: z.enum(['low', 'medium', 'high']).default('medium'), |
| 175 | dueDate: z.string().datetime().optional(), |
| 176 | }); |
| 177 | |
| 178 | // Validate at the route handler |
| 179 | app.post('/api/tasks', async (req, res) => { |
| 180 | const result = CreateTaskSchema.safeParse(req.body); |
| 181 | if (!result.success) { |
| 182 | return res.status(422).json({ |
| 183 | error: { |
| 184 | code: 'VALIDATION_ERROR', |
| 185 | message: 'Invalid input', |
| 186 | details: result.error.flatten(), |
| 187 | }, |
| 188 | }); |
| 189 | } |
| 190 | // result.data is now typed and validated |
| 191 | const task = await taskService.create(result.data); |
| 192 | return res.status(201).json(task); |
| 193 | }); |
| 194 | ``` |
| 195 | |
| 196 | ### File Upload Safety |
| 197 | |
| 198 | ```typescript |
| 199 | // Restrict file types and sizes |
| 200 | const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp']; |
| 201 | const MAX_SIZE = 5 * 1024 * 1024; // 5MB |
| 202 | |
| 203 | function validateUpload(file: UploadedFile) { |
| 204 | if (!ALLOWED_TYPES.includes(file.mimetype)) { |
| 205 | throw new ValidationError('File type not allowed'); |
| 206 | } |
| 207 | if (file.size > MAX_SIZE) { |
| 208 | throw new ValidationError('File too large (max 5MB)'); |
| 209 | } |
| 210 | // Don't trust the file extension — check magic bytes if critical |
| 211 | } |
| 212 | ``` |
| 213 | |
| 214 | ### Destructive Operations on Derived Paths |
| 215 | |
| 216 | A delete, move, or overwrite is only as safe as the value that names its target. Reading that value from the kernel, a job payload, or a sibling service proves where it *arrived from*, not who *wrote* it — another process's command line is as attacker-controlled as a form field. A shape check ("absolute path, at least one directory deep") proves well-formedness and gets mistaken for authorization; that is how a cleanup routine deletes the root instead of the leaf. |
| 217 | |
| 218 | Before a destructive call, require all three: the resolved target sits under an **allowlisted root** (compare after resolving symlinks, never on the raw string); it is at least one level **below** that root, so a root is never itself the target; and it carries **evidence that it is yours**, read *before* the operation and before any teardown that removes it — otherwise "absent" and "not mine" are indistinguishable. On refusal, log the rejected target and stop: a cleanup that falls back to a broader default path is the failure this guards against. Worked example in `../references/shared/security-checklist.md#destructive-path-operations`. |
| 219 | |
| 220 | Two limits, because the check reads stronger than it is. A marker inside the tree is self-attestation — anything that can write there can write the marker — so the expected owner has to come from authenticated state, and the marker needs integrity protection (restrictive ownership, or a MAC) before it counts as authorization. And resolving a path and then operating on the *name* is a check/use race wherever an untrusted process can swap an ancestor: on a shared volume, hold the target by descriptor and use no-follow, beneath-the-root operations, or make sure the hierarchy cannot change for the duration. |
| 221 | |
| 222 | ## Dependency Audit Triage |
| 223 | |
| 224 | Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree: |
| 225 | |
| 226 | ``` |
| 227 | The native package-manager audit reports a vulnerability |
| 228 | ├── Severity: critical or high |
| 229 | │ ├── Is the vulnerable code reachable in runtime, build, test, or deployment paths? |
| 230 | │ │ ├── YES --> Fix immediately (update, patch, or replace the dependency) |
| 231 | │ │ └── NO (confirmed unused across those paths) --> Fix soon, but not a blocker |
| 232 | │ └── Is a fix available? |
| 233 | │ ├── YES --> Update to the patched version |
| 234 | │ └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date |
| 235 | ├── Severity: moderate |
| 236 | │ ├── Reachable in production? --> Fix in the next release cycle |
| 237 | │ └── Dev-only? --> Fix when convenient, track in backlog |
| 238 | └── Severity: low |
| 239 | └── Track and fix during regular dependency updates |
| 240 | ``` |
| 241 | |
| 242 | **Key questions:** |
| 243 | - Is the vulnerable function actually called in your code path? |
| 244 | - Is the dependency a runtime dependency or dev-only? |
| 245 | - Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)? |
| 246 | |
| 247 | When you defer a fix, document the reason and set a review date. |
| 248 | |
| 249 | ## Rate Limiting |
| 250 | |
| 251 | ```typescript |
| 252 | import rateLimit from 'express-rate-limit'; |
| 253 | |
| 254 | // General API rate limit |
| 255 | app.use('/api/', rateLimit({ |
| 256 | windowMs: 15 * 60 * 1000, // 15 minutes |
| 257 | max: 100, // 100 requests per window |
| 258 | standardHeaders: true, |
| 259 | legacyHeaders: false, |
| 260 | })); |
| 261 | |
| 262 | // Stricter limit for auth endpoints |
| 263 | app.use('/api/auth/', rateLimit({ |
| 264 | windowMs: 15 * 60 * 1000, |
| 265 | max: 10, // 10 attempts per 15 minutes |
| 266 | })); |
| 267 | ``` |
| 268 | |
| 269 | **Count in a shared store once there is more than one process.** `express-rate-limit` keeps its counters in process memory by default. Behind a load balancer each instance holds its own count, so the effective limit is `max × instances`; on serverless or edge runtimes a fresh invocation starts from zero, so the auth limit above may never fire. Pass a shared `store` (Redis via `rate-limit-redis`), or use an HTTP-based limiter that works where a long-lived TCP connection does not (for example `@upstash/ratelimit`): |
| 270 | |
| 271 | ```typescript |
| 272 | import { Ratelimit } from '@upstash/ratelimit'; |
| 273 | import { Redis } from '@upstash/redis'; |
| 274 | |
| 275 | const authLimiter = new Ratelimit({ |
| 276 | redis: Redis.fromEnv(), // UPSTASH_REDIS_REST_URL + _TOKEN |
| 277 | limiter: Ratelimit.slidingWindow(10, '15 m'), // 10 attempts per 15 minutes, across all instances |
| 278 | }); |
| 279 | const { success } = await authLimiter.limit(`login:${req.ip}`); |
| 280 | if (!success) return res.status(429).end(); |
| 281 | ``` |
| 282 | |
| 283 | ## Secrets Management |
| 284 | |
| 285 | ``` |
| 286 | .env files: |
| 287 | ├── .env.example → Committed (template with placeholder values) |
| 288 | ├── .env → NOT committed (contains real secrets) |
| 289 | └── .env.local → NOT committed (local overrides) |
| 290 | |
| 291 | .gitignore must include: |
| 292 | .env |
| 293 | .env.local |
| 294 | .env.*.local |
| 295 | *.pem |
| 296 | *.key |
| 297 | ``` |
| 298 | |
| 299 | **Always check before committing:** |
| 300 | ```bash |
| 301 | # Check for accidentally staged secrets — prints only the names of files whose |
| 302 | # staged diff matches, so the raw value never lands in terminal output or agent |
| 303 | # tool logs. Any output means review those files before committing. |
| 304 | git diff --cached -i -G'password|secret|api_key|token' --name-only |
| 305 | ``` |
| 306 | |
| 307 | **If a secret is ever committed, rotate it.** Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history. |
| 308 | |
| 309 | ## Data Classification |
| 310 | |
| 311 | Classify personal data as you add fields, so export and deletion requests can find it later: |
| 312 | |
| 313 | | Class | Examples | Handling | |
| 314 | |---|---|---| |
| 315 | | **Non-personal** | Aggregates, anonymized counts | Normal handling | |
| 316 | | **Personal (PII)** | Name, email, IP, device/user IDs | Minimize, access-control, include in export/delete | |
| 317 | | **Sensitive** | Health, finance, location, biometrics, gov IDs, anything about minors | Extra basis to collect, stricter access, often encryption + audit logging | |
| 318 | |
| 319 | ## LLM Output Handling |
| 320 | |
| 321 | ```typescript |
| 322 | // BAD: trusting model output as a command or as markup |
| 323 | const sql = await llm.generate(`Write SQL for: ${userQuestion}`); |
| 324 | await db.query(sql); // arbitrary query execution |
| 325 | container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model |
| 326 | |
| 327 | // GOOD: model output is data — parse defensively, then validate, then encode |
| 328 | let intent; |
| 329 | try { |
| 330 | intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage))); |
| 331 | } catch { |
| 332 | throw new ValidationError('unexpected model output'); // JSON.parse or schema failed |
| 333 | } |
| 334 | await runAllowlistedAction(intent.action, intent.params); |
| 335 | container.textContent = await llm.reply(userMessage); |
| 336 | ``` |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

