Мақала Kazakh тілінде әлі жарияланбаған. English нұсқасы көрсетілуде.
Multi-Tenant Data Isolation: Row-Level Security (RLS), Tenant Indexes, and Fail-Closed Defaults
Жарияланды
2 мин оқу
In multi-tenant SaaS, forgetting a single WHERE workspace_id = $1 clause in an endpoint or background worker can expose one company's private messages to another. Relying purely on developer memory does not scale. Defense-in-depth enforces tenant boundaries at both the application layer and the database layer.
Defense-in-Depth Isolation Checklist
| Control Layer | Mechanism | What It Stops |
|---|---|---|
| Auth Middleware | Resolve membership from verified JWT + DB role check | Forged workspaceId headers or URL params |
| Database RLS | PostgreSQL Row-Level Security policies enabled on every tenant table | Accidental unfiltered queries from client or RPC roles |
| Composite Indexes | Lead indexes with (tenant_id, ...) | Slow cross-tenant table scans and noisy-neighbor lockups |
| Cache & Queue Keys | Prefix every cache key and pub/sub channel with tenantId: | Cross-tenant cache pollution and real-time event leaks |
Writing Performant PostgreSQL RLS Policies
RLS is powerful, yet poorly written RLS policies calling unindexed subqueries per row can devastate query latency. Always index membership foreign keys and wrap auth.uid() in a scalar (SELECT auth.uid()) so Postgres evaluates it once per statement instead of once per scanned row:
sql
ALTER TABLE workspace_documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY workspace_members_read_documents
ON workspace_documents
FOR SELECT
TO authenticated
USING (
EXISTS (
SELECT 1
FROM workspace_members wm
WHERE wm.workspace_id = workspace_documents.workspace_id
AND wm.user_id = (SELECT auth.uid())
)
);
Fail-Closed Defaults for Sensitive Tables
- Revoke
PUBLICandanonprivileges on private tables and RPC functions explicitly. - Restrict client-side writes on security-critical tables (billing subscriptions, OAuth credentials, role grants) so mutations flow exclusively through audited server-side endpoints or
SECURITY DEFINERprocedures with lockedsearch_path. - Add automated integration tests that authenticate as User B and assert
403/ empty results when attempting to read or mutate Tenant A's IDs.
Next: deliver tenant-scoped real-time events smoothly across browser tabs in Real-Time Messaging Architecture.
Бұл пайдалы болды ма?