Security Hardening & Best Practices
Comprehensive protocols for "Secure by Design" development.
Core Principle: Security is not a feature; it's a baseline requirement. Implement these controls during development, not after.
Table of Contents
1. OWASP Top 10 Quick Reference
Full implementation details in references/owasp-vulnerabilities.md.
| Rank |
Vulnerability |
Prevention Summary |
| A01 |
Broken Access Control |
Verify ownership on every request (IDOR checks). |
| A02 |
Cryptographic Failures |
Use bcrypt/argon2 (cost 12+), Encrypt at rest. |
| A03 |
Injection |
Parameterized queries (SQL), Input validation (NoSQL). |
| A04 |
Insecure Design |
Threat modeling, Rate limiting, Secure defaults. |
| A05 |
Security Misconfiguration |
Hardened headers (Helmet), No default credentials. |
| A06 |
Vulnerable Components |
npm audit, pip-audit, Dependency pinning. |
| A07 |
Auth Failures |
MFA, Session management, Complexity rules. |
| A08 |
Integrity Failures |
Signatures, DOMPurify for XSS. |
| A09 |
Logging Failures |
Log security events, Monitor spikes. |
| A10 |
SSRF |
Private IP blocking, URL allowlists. |
2. Security Audit Protocol (Workflow)
Follow this process when reviewing an application for security gaps.
Phase 1: Reconnaissance
- Identify Entry Points: List all API routes (
/api/*) and public pages.
- Identify Data Flows: Where does user input go? (DB, Logs, External API).
- Check Tech Stack: Run
./scripts/security-audit.sh to find low-hanging fruit (secrets, eval).
Phase 2: Vulnerability Scanning
- Dependencies: Run
npm audit / pip check.
- Static Analysis: Check for commonly misused functions (
dangerouslySetInnerHTML, exec).
- Configuration: Review
.env.example (no real secrets?) and next.config.js.
Phase 3: Logic Review (High Risk)
- AuthZ: Pick 3 critical endpoints (e.g.,
GET /invoice/:id). Can User A access User B's data?
- AuthN: Try to bypass login. Is the session cookie
HttpOnly?
- Injection: Check 3 search/filter inputs. Are they parameterized?
3. Auth Strategy Decision Tree
For detailed patterns, see references/auth-patterns.md.
graph TD
A[Start] --> B{Need User Accounts?}
B -- No --> C[Public / API Key Only]
B -- Yes --> D{Frontend Type?}
d -- SPA / Mobile App --> E{Provider?}
E -- 3rd Party (Google/GitHub) --> F[OAuth 2.0 + JWT Session]
E -- Email/Pass --> G[JWT (Access + Refresh)]
D -- Traditional / SSR (Next.js) --> H[Cookie-based Session (HttpOnly)]
4. CSP & Headers
HTTP Headers are your first line of defense.
See references/csp-deep-dive.md.
- Strict-Transport-Security (HSTS): Force HTTPS.
- Content-Security-Policy (CSP): Prevent XSS.
- X-Content-Type-Options: Prevent MIME sniffing.
5. Logging & Monitoring
"You cannot fight what you cannot see."
See references/security-logging.md.
- Log: Failed logins, Access denied, Sudo actions.
- Do Not Log: Passwords, API Keys, PII.
6. Enhanced Pre-Deployment Checklist
Authentication
Authorization
Input/Output
Infrastructure
7. Production Gotchas
Real-world issues that often slip through:
- Debug Mode Left On: Ensure
NODE_ENV=production is set.
- Verbose Error Messages: API should not return stack traces to clients.
- Default Admin Accounts: Delete or change default CMS credentials.
- Staging vs Prod: Ensure staging secrets are different from production secrets.
- Missing Rate Limits: One API call is fast; 10k/sec will crash you.
1---2name: security-hardening3description: Use when performing security audits, implementing authentication/authorization, hardening an app for production, or reviewing code for OWASP Top 10 vulnerabilities. Covers CSP headers, auth strategy decision trees, and pre-deployment security checklists.4---56# Security Hardening & Best Practices78Comprehensive protocols for "Secure by Design" development.910> **Core Principle**: Security is not a feature; it's a baseline requirement. Implement these controls _during_ development, not after.1112## Table of Contents1314- [OWASP Top 10 Quick Reference](#1-owasp-top-10-quick-reference)15- [Security Audit Protocol](#2-security-audit-protocol-workflow)16- [Auth Strategy Decision Tree](#3-auth-strategy-decision-tree)17- [Pre-Deployment Checklist](#6-enhanced-pre-deployment-checklist)1819---2021## 1. OWASP Top 10 Quick Reference2223Full implementation details in [references/owasp-vulnerabilities.md](./references/owasp-vulnerabilities.md).2425| Rank | Vulnerability | Prevention Summary |26| ------- | ------------------------- | ------------------------------------------------------ |27| **A01** | Broken Access Control | Verify ownership on _every_ request (IDOR checks). |28| **A02** | Cryptographic Failures | Use `bcrypt`/`argon2` (cost 12+), Encrypt at rest. |29| **A03** | Injection | Parameterized queries (SQL), Input validation (NoSQL). |30| **A04** | Insecure Design | Threat modeling, Rate limiting, Secure defaults. |31| **A05** | Security Misconfiguration | Hardened headers (Helmet), No default credentials. |32| **A06** | Vulnerable Components | `npm audit`, `pip-audit`, Dependency pinning. |33| **A07** | Auth Failures | MFA, Session management, Complexity rules. |34| **A08** | Integrity Failures | Signatures, `DOMPurify` for XSS. |35| **A09** | Logging Failures | Log security events, Monitor spikes. |36| **A10** | SSRF | Private IP blocking, URL allowlists. |3738---3940## 2. Security Audit Protocol (Workflow)4142Follow this process when reviewing an application for security gaps.4344### Phase 1: Reconnaissance45461. **Identify Entry Points**: List all API routes (`/api/*`) and public pages.472. **Identify Data Flows**: Where does user input go? (DB, Logs, External API).483. **Check Tech Stack**: Run `./scripts/security-audit.sh` to find low-hanging fruit (secrets, eval).4950### Phase 2: Vulnerability Scanning51521. **Dependencies**: Run `npm audit` / `pip check`.532. **Static Analysis**: Check for commonly misused functions (`dangerouslySetInnerHTML`, `exec`).543. **Configuration**: Review `.env.example` (no real secrets?) and `next.config.js`.5556### Phase 3: Logic Review (High Risk)57581. **AuthZ**: Pick 3 critical endpoints (e.g., `GET /invoice/:id`). Can User A access User B's data?592. **AuthN**: Try to bypass login. Is the session cookie `HttpOnly`?603. **Injection**: Check 3 search/filter inputs. Are they parameterized?6162---6364## 3. Auth Strategy Decision Tree6566For detailed patterns, see [references/auth-patterns.md](./references/auth-patterns.md).6768```mermaid69graph TD70 A[Start] --> B{Need User Accounts?}71 B -- No --> C[Public / API Key Only]72 B -- Yes --> D{Frontend Type?}73 d -- SPA / Mobile App --> E{Provider?}74 E -- 3rd Party (Google/GitHub) --> F[OAuth 2.0 + JWT Session]75 E -- Email/Pass --> G[JWT (Access + Refresh)]76 D -- Traditional / SSR (Next.js) --> H[Cookie-based Session (HttpOnly)]77```7879---8081## 4. CSP & Headers8283HTTP Headers are your first line of defense.84See [references/csp-deep-dive.md](./references/csp-deep-dive.md).8586- **Strict-Transport-Security (HSTS)**: Force HTTPS.87- **Content-Security-Policy (CSP)**: Prevent XSS.88- **X-Content-Type-Options**: Prevent MIME sniffing.8990---9192## 5. Logging & Monitoring9394"You cannot fight what you cannot see."95See [references/security-logging.md](./references/security-logging.md).9697- **Log**: Failed logins, Access denied, Sudo actions.98- **Do Not Log**: Passwords, API Keys, PII.99100---101102## 6. Enhanced Pre-Deployment Checklist103104### Authentication105106- [ ] Passwords hashed with `bcrypt`/`argon2` (cost ≥ 12)107- [ ] Session cookies are `httpOnly`, `secure`, `sameSite=strict`108- [ ] Password reset tokens hashed in DB109- [ ] MFA available for admin accounts110111### Authorization112113- [ ] IDOR checks on all resource-accessing endpoints114- [ ] API routes protected by middleware115- [ ] CORS restricted to specific production domains116117### Input/Output118119- [ ] SQL queries parameterized (No string concat)120- [ ] XSS prevented (CSP + Auto-escaping)121- [ ] JSON body size limited (prevent DoS)122- [ ] File uploads validated (type + size + malware scan)123124### Infrastructure125126- [ ] HTTPS enforced (HSTS)127- [ ] Secrets managed via env vars (not committed)128- [ ] `npm audit` passes with 0 critical129- [ ] Production logs do not contain PII/Secrets130131---132133## 7. Production Gotchas134135Real-world issues that often slip through:1361371. **Debug Mode Left On**: Ensure `NODE_ENV=production` is set.1382. **Verbose Error Messages**: API should not return stack traces to clients.1393. **Default Admin Accounts**: Delete or change default CMS credentials.1404. **Staging vs Prod**: Ensure staging secrets are different from production secrets.1415. **Missing Rate Limits**: One API call is fast; 10k/sec will crash you.