跳到主要内容

安全加固

收藏0

按 OWASP Top Ten 加固代码:处理不可信输入、登录与会话、数据存储、第三方集成,审计依赖供应链,附两份可勾选的安全清单。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-25下载 0 次

references/hardening-patterns.md

13.8 KB查看排版效果
1# Hardening Patterns
2
3Code 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
5Shared 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
9These 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
15const query = `SELECT * FROM users WHERE id = '${userId}'`;
16
17// GOOD: Parameterized query
18const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
19
20// GOOD: ORM with parameterized input
21const user = await prisma.user.findUnique({ where: { id: userId } });
22```
23
24### Broken Authentication
25
26```typescript
27// Password hashing
28import { hash, compare } from 'bcrypt';
29
30const SALT_ROUNDS = 12;
31const hashedPassword = await hash(plaintext, SALT_ROUNDS);
32const isValid = await compare(plaintext, hashedPassword);
33
34// Session management
35const SESSION_SECRET = process.env.SESSION_SECRET; // From environment, not code
36if (!SESSION_SECRET) throw new Error('SESSION_SECRET not configured');
37app.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
54element.innerHTML = userInput;
55
56// GOOD: Use framework auto-escaping (React does this by default)
57return <div>{userInput}</div>;
58
59// If you MUST render HTML, sanitize first
60import DOMPurify from 'dompurify';
61const clean = DOMPurify.sanitize(userInput);
62```
63
64### Broken Access Control
65
66```typescript
67// Always check authorization, not just authentication
68app.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)
93import helmet from 'helmet';
94app.use(helmet());
95
96// Content Security Policy
97app.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
108app.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
118function sanitizeUser(user: UserRecord): PublicUser {
119 const { passwordHash, resetToken, ...publicFields } = user;
120 return publicFields;
121}
122
123// Use environment variables for secrets
124const API_KEY = process.env.STRIPE_API_KEY;
125if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');
126```
127
128### Server-Side Request Forgery (SSRF)
129
130Any 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
136await fetch(req.body.webhookUrl);
137
138// PARTIAL: allowlist scheme + host, reject private/reserved IPs before connecting
139import { lookup } from 'node:dns/promises';
140import ipaddr from 'ipaddr.js';
141
142const ALLOWED_HOSTS = new Set(['hooks.example.com']);
143
144async 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.
157await fetch(await prevalidateUrl(req.body.webhookUrl), { redirect: 'error' });
158```
159
160The `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
169import { z } from 'zod';
170
171const 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
179app.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
200const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
201const MAX_SIZE = 5 * 1024 * 1024; // 5MB
202
203function 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
216A 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
218Before 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
220Two 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
224Package-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```
227The 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
247When you defer a fix, document the reason and set a review date.
248
249## Rate Limiting
250
251```typescript
252import rateLimit from 'express-rate-limit';
253
254// General API rate limit
255app.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
263app.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
272import { Ratelimit } from '@upstash/ratelimit';
273import { Redis } from '@upstash/redis';
274
275const 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});
279const { success } = await authLimiter.limit(`login:${req.ip}`);
280if (!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.
304git 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
311Classify 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
323const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
324await db.query(sql); // arbitrary query execution
325container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model
326
327// GOOD: model output is data — parse defensively, then validate, then encode
328let intent;
329try {
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}
334await runAllowlistedAction(intent.action, intent.params);
335container.textContent = await llm.reply(userMessage);
336```

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。