🔒 Sec10

10 Security Rules for Writing Safe Code

1
Validate All Input, Sanitize All Output

Never trust external data. Validate on entry, sanitize on exit. Use parameterized queries.

// ❌ BAD: SQL Injection
db.query(`SELECT * WHERE name = '${query}'`)

// ✅ GOOD: Parameterized
db.query('SELECT * WHERE name = $1', [query])
2
Principle of Least Privilege

Every component runs with minimum permissions. Database users should have only needed access. Don't use admin credentials for app connections.

3
Never Expose Secrets in Code

No API keys, passwords, or tokens in source code. Use environment variables or secrets managers.

// ❌ BAD
const API_KEY = 'sk_live_123';

// ✅ GOOD
const apiKey = process.env.API_KEY;
4
Proper Authentication & Session Management

Use established libraries (Passport, Auth0). Never roll your own auth. Use secure, httpOnly, sameSite cookies.

5
Encrypt Data at Rest and in Transit

Use TLS 1.2+ for all connections. Encrypt sensitive data in database with AES-256-GCM.

6
Implement Access Control

Check permissions on every request. Deny by default. Test for horizontal and vertical privilege escalation.

7
Protect Against Injection

SQL, NoSQL, Command, and LDAP injection: never concatenate untrusted data into commands.

8
Secure Dependencies

Run npm audit in CI. Use Dependabot. Remove unused dependencies. Pin versions in production.

9
Secure File Handling

Validate file type (magic bytes), limit size, generate random filenames, store outside webroot. Never execute uploaded files.

10
Log Security Events

Log authentication failures, authorization denials. Never log passwords, tokens, or secrets.

✅ Pre-Commit Security Checklist