π Security Best Practices β
Writing secure code and preventing common vulnerabilities.
OWASP Top 10 (key items) β
Injection (SQL, NoSQL, OS command) β
// BAD
db.query(`SELECT * FROM users WHERE id = ${userId}`)
// GOOD
db.query('SELECT * FROM users WHERE id = $1', [userId])Always use parameterized queries or ORM methods.
XSS (Cross-Site Scripting) β
- Escape all user input before rendering in HTML
- Use Content Security Policy (CSP) headers
- Use framework auto-escaping (React, Vue do this by default)
- Never use
innerHTMLordangerouslySetInnerHTMLwith user data
Broken Authentication β
- Hash passwords with bcrypt or argon2 (never MD5/SHA1)
- Use JWTs with short expiry + refresh tokens
- Implement rate limiting on login endpoints
- Enforce MFA for sensitive operations
Broken Access Control β
- Check permissions server-side, never rely on client-side only
- Use role-based (RBAC) or attribute-based (ABAC) access control
- Validate that the user owns the resource they're accessing
- Log access control failures
Secrets management β
- Never commit secrets to git
- Use environment variables or a vault (AWS Secrets Manager, HashiCorp Vault)
- Rotate secrets regularly
- Different secrets per environment
- Add
.envto.gitignore
Dependency security β
- Run
npm audit/pip audit/bundler-auditin CI - Use Dependabot or Renovate for automated updates
- Pin dependency versions in production
- Review changelogs before major upgrades
HTTP security headers β
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-originPrinciple of least privilege β
- Give minimum necessary permissions
- Don't run services as root
- Scope API keys to specific operations
- Use read-only database replicas where possible