Tenant isolation must be enforced in the backend at every layer. 1. Trusted tenant context - Derive the tenant from the authenticated identity: a tenant claim in the JWT issued by the identity provider (Keycloak, Auth0, Okta), validated by Spring Security's OAuth2 resource server. - If users can belong to several tenants, validate the requested tenant against their memberships on every request. - Store it in a request-scoped TenantContext (cleared after each request, including in thread pools and @Async tasks — ThreadLocal leaks between requests are a classic bug). 2. Data isolation models - Shared schema with a tenant_id column: cheapest and most common. Enforce filtering automatically: - Hibernate 6's @TenantId annotation with a CurrentTenantIdentifierResolver adds tenant filtering and sets the tenant on insert. - Or Hibernate @Filter enabled per session. - Add PostgreSQL Row-Level Security policies as defence in depth (SET app.tenant_id per connection and a policy using current_setting), so even native queries cannot cross tenants. - Schema per tenant or database per tenant: stronger isolation (useful for regulated or large customers), implemented with Hibernate's multi-tenancy connection providers, at higher operational cost. 3. Authorization - Check resource ownership: repositories query by (id, tenantId), never by id alone, preventing IDOR attacks. - Return 404 for other tenants' resources to avoid revealing their existence. - Use method security (@PreAuthorize) for role checks within a tenant. 4. Other shared resources - Cache keys, object storage paths (S3 prefixes), search indexes, message topics and logs include the tenant ID. - Background jobs and message consumers carry the tenant ID explicitly in message headers. - Unique constraints include tenant_id (email unique per tenant). 5. Verification - Integration tests with Testcontainers that create two tenants and attempt cross-tenant reads, updates, deletes and searches through every endpoint. - Code review rules for native queries and any code that bypasses filters. - Security testing and audit logs of cross-tenant access attempts. 6. Operational concerns - Per-tenant rate limits and quotas to prevent noisy neighbours. - Tenant-aware backups and data export or deletion for compliance.
Ravindra Wadile · · 0 likes