Security Architecture Principles
Build security into the structure, not as an afterthought.
Defense in Depth
Multiple layers, not single points of failure:
Request β Rate Limit β Auth β Validation β Sanitization β Query β Response
(layer 1) (2) (3) (4) (5)If one layer fails, others still protect. Never rely on a single check.
Least Privilege
Minimum necessary permissions only:
// β Bad: Admin access for everything
const db = connectAsAdmin();
// β
Good: Scoped access
const db = connectAsReadOnly(); // for queries
const db = connectWithWriteScope(['users']); // for specific writesApply to:
- Database connections
- API keys
- User roles
- File system access
- Network access
Fail Secure
Default to deny, not allow:
// β Bad: Allow unless explicitly denied
if (!user.isBanned) {
allowAccess();
}
// β
Good: Deny unless explicitly allowed
if (user.hasPermission('read:posts')) {
allowAccess();
}
else {
denyAccess(); // Explicit denial
}Input/Output Discipline
Validate ALL Inputs
// Never trust user data
const schema = z.object({
email: z.string().email(),
age: z.number().min(0).max(150),
name: z.string().max(100).regex(/^[a-zA-Z\s]+$/)
});
const validated = schema.parse(userInput);Encode ALL Outputs
// Prevent XSS
const safeHtml = escapeHtml(userContent);
// In React, this is automatic for {}
<div>{userContent}</div> // Safe
// But not for dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{__html: userContent}} /> // UNSAFESanitize Before Storage AND Display
// Before storing
const cleanInput = sanitize(userInput);
await db.save(cleanInput);
// Before displaying (belt and suspenders)
const safeOutput = escapeHtml(storedContent);Architecture Diagram
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INTERNET β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β LAYER 1: Edge / CDN / WAF β
β - DDoS protection β
β - Basic filtering β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β LAYER 2: Load Balancer / Rate Limiter β
β - Request limits β
β - IP blocking β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β LAYER 3: Application β
β - Authentication β
β - Authorization β
β - Input validation β
β - Business logic β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β LAYER 4: Data β
β - Encrypted at rest β
β - Access controls β
β - Audit logging β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ