Anatomy of an Invariant-Based Code Review
When reviewing code for security vulnerabilities, scanning for known CVE signatures or regex patterns only scratches the surface. The highest impact security bugs—such as business logic flaws, authorization bypasses, and state desynchronizations—stem from broken invariants.
What is a Security Invariant?
An invariant is a predicate that must always hold true for a system to remain secure across all state transitions.
Key Takeaway: Bugs happen when code assumes an invariant holds without the runtime environment actually enforcing it.
Example: Tenant Boundary Violation
Consider a multi-tenant resource handler:
// Vulnerable implementation assuming session tenant equals resource tenant
async function getTenantDocument(sessionId: string, docId: string): Promise<Document> {
const session = await authService.validateSession(sessionId);
if (!session) {
throw new UnauthorizedError("Invalid session");
}
// BUG: Invariant broken: docId is not scoped to session.tenantId!
const doc = await db.documents.findById(docId);
return doc;
}
To fix this, we enforce the invariant at the query layer:
async function getTenantDocument(sessionId: string, docId: string): Promise<Document> {
const session = await authService.validateSession(sessionId);
if (!session) {
throw new UnauthorizedError("Invalid session");
}
// Invariant strictly enforced by scoping the lookup query
const doc = await db.documents.findOne({
id: docId,
tenantId: session.tenantId,
});
if (!doc) {
throw new NotFoundError("Document not found");
}
return doc;
}
Checklist for Reviewers
- Does every query touching multi-tenant data include tenant filtering?
- Are preconditions explicitly validated before executing state changes?
- Are side effects atomic, preventing partial state commit during failures?