Skip to content

Documentation

Enterprise Tenancy & Data-Isolation Inventory

Verified map of every tenant enforcement point — request resolution, REST, GraphQL, SDK, media, search, export, jobs, caches, sessions — with the file:line where isolation is enforced or can be bypassed.

11/11/2026
22 min read Edit on GitHub

Status: current audit of next. The baseline snapshot was efa57c55e on the (now deleted) fix/enterprise-readiness-20261110 branch; PR #566 is merged and every row below was re-verified against the current tree, so a reference that moved cites the symbol. Per-finding status is listed below — entries marked fixed are no longer current defects and must not be read as open risks. Rows without a reachable call site keep their not found result and the search behind it. Re-verified 2026-11-11 on the current tree: the status and evidence of every row this pass touched were checked against the code again; references that moved cite the symbol.

Finding Status Evidence
GraphQL data operations accepted a caller-supplied tenantId (15 fields) Fixed in PR #566 (commit 26dc6ce65) resolveGraphQLTenant() in resolvers/data-operations.ts; tests/unit/api/graphql-tenant-scope.test.ts
Tenant context does not fail closed at the request hook (locals.tenantId = null continues) Fixed in PR #566 (commit c727d45b7) assertTenantRequired() in tenant-required.server.ts, applied in the catch-all dispatcher and at 5 hook boundaries; tests/unit/security/tenant-fail-closed.test.ts (13 tests)
PostgreSQL RLS implemented but unwired (enforceTenantPolicy, getTenantPool/setTenantPool had no callers) Fixed — opt-in, wired TENANT_RLS_ENABLED=true makes createModel() provision ENABLE + FORCE + tenant_isolation and throws when the policy cannot filter (src/databases/postgresql/adapter-core.ts); tenant-scoped db.crud.* calls run in a transaction that binds app.tenant_id (src/databases/core/rls-scoped-crud.ts, composed at boot in src/databases/db.ts); transaction({ tenantId }) passes the tenant per call instead of reading process state. Proof against a non-owner role (pool reuse, concurrent tenants, cross-tenant writes rejected): tests/integration/databases/tenant-rls-request-path.test.ts. Still true: system paths carry no tenant and need a BYPASSRLS role, and setTenantPool still has no boot caller.
FTS adapter scopes by ambient currentTenantId without assertTenantContext Still open (PostgreSQL; MariaDB lost the ambient fallback) postgresql/fts-adapter.ts:321-329, :445-453; mariadb/fts-adapter.ts:155-168
tenant-isolation.test.ts accepted 200 or 401 and skipped its leak assertion unless 200 Fixed in PR #566 (commit c727d45b7) cross-tenant read must be 401/403, or 200 with an explicitly empty tenant-B slice; DB-less runs skip with a reason

This page records where tenant isolation is actually enforced on branch next (baseline snapshot efa57c55e). It is an inventory, not a design document: each row points at the line that does the work, and each gap points at the line where a caller can step around it.

Evidence rule. Every statement carries path:line. A capability that could not be located is written as not found, together with the search that was run. A config key, a UI label or a doc comment is not evidence of enforcement — only a line on the request/query execution path counts. Method (2026-11-10). Read-only audit of the worktree. No source file, config or test was modified, nothing was committed, and no suite was executed (the host was running a performance benchmark). Coverage below is read from the test files and from the package.json suite definitions, not from a run.


1. How tenant context is established per request

Step Where What it does
1. Mode flag src/utils/tenant-isolation.server.ts:33-52 MULTI_TENANT (or DEMO) read through a 5 s cache. A settings read error resolves to false (:47-49) — fail-closed in the safe direction, but it means a transient settings failure silently disables isolation.
2. Pipeline order src/hooks.server.ts:813-834 (READY), :770-787 (API_WRITE), :792-811 (API_READ) security → system-state → turbo-get → compression → authentication → authorization → local-context → api-requests. Tenant binding happens inside authentication.
3. Hostname derivation src/utils/tenant.ts:35-48 localhost, 127.0.0.1 and 192.168.* → literal "default" (:39); a host with ≥3 labels → first label lowercased (:44-46); a bare two-label host → null (:47).
4. Hook binds locals.tenantId src/hooks/handle-authentication.ts:1197-1208 When MULTI_TENANT or demo, locals.tenantId = getTenantIdFromHostname(url.hostname, true); the test-mode worker header can overwrite it (:1204-1207).
5. Test-only override src/hooks/request-tenant.ts:23-35 x-test-tenant-id / x-tenant-id honoured only when TEST_MODE or PLAYWRIGHT_TEST (:28), charset-validated (:21), literal "null" rejected (:30).
6. Session tenant adopted src/hooks/handle-authentication.ts:1413-1416 If no tenant was resolved, the authenticated user’s tenantId is adopted; same fallback on the two turbo-auth fast paths (:1103-1108, :1151-1156).
7. Bound adapter src/databases/tenant-adapter.ts:144-158 bindRequestDbAdapter() wraps the raw adapter in forTenant() only when multiTenant && tenantId; otherwise the raw adapter is exposed (:157).
8. Adapter GUC / pool hint src/databases/tenant-adapter.ts:165-185 applyAdapterTenantContext() calls setTenantContext() on the raw adapter (skips on no-op, :178-180).
9. Dispatcher backstop src/routes/api/[...path]/+server.ts:395-409 Adopts user.tenantId when locals.tenantId is empty; requests with neither stay tenantless.
10. Super-admin override src/routes/api/[...path]/+server.ts:412-418; src/routes/api/[...path]/handlers/system/system-shared.ts:66-83 ?tenantId= may differ from the session tenant only for super-admin; otherwise 403.

Does it fail closed?

  • Missing tenant at the hook: no. src/hooks/handle-authentication.ts:1117 initialises locals.tenantId = null and continues; no hook rejects a tenantless request.
  • Invalid tenant: no validation at all. isValidTenantId() exists (src/utils/tenant.server.ts:91-94) but is called only from the compilation path (src/utils/compilation/compile.ts:200). grep -rn "isValidTenantId" src returns exactly those two hits. An unknown host label becomes a brand-new empty tenant scope rather than an error.
  • First real gate is the DB layer: src/utils/security/safe-query.ts:78-98 throws TENANT_CONTEXT_MISSING only when tenantId is undefined or "" (:86-90); null is treated as the explicit global scope (:72-76 comment, :87-89), which is why assertTenantContext alone cannot stop a tenantless request from reading/writing the global layer.
  • API-boundary gates exist per handler, not centrally: src/routes/api/[...path]/handlers/media.ts:152-155, handlers/system/system-transfer.ts:51-53 and :83-85, handlers/system/system-shared.ts:54-59, handlers/system/system-ai.ts:142.
  • Media file delivery does fail closed: src/routes/files/[...path]/+server.ts:486-499 rejects when MULTI_TENANT is on and locals.tenantId is missing or does not match the path tenant.

2. Capability matrix

Capability Status Implementation (file:line) Enforcement points Existing tests Gap
Per-request tenant resolution partial src/hooks/handle-authentication.ts:1197-1208; src/utils/tenant.ts:35-48 hooks.server.ts:813-834 pipeline; request-tenant.ts:23-35 test override tests/unit/hooks/request-tenant.test.ts; tests/unit/multi-tenancy/00-tenant-utils.test.ts Hooks never reject a tenantless or unknown tenant (handle-authentication.ts:1117, tenant.ts:47). No registry lookup validates the host-derived id.
CRUD adapter guard (core) complete src/databases/crud-tenant-guard.ts:185-334; installed at src/databases/db.ts:265 (replicas too: :340, :477) assertTenantContext on every op (crud-tenant-guard.ts:53-67); body tenantId mismatch → 500 TENANT_MISMATCH (:41-51, :81-108); batch variants :114-179 tests/unit/multi-tenancy/crud-tenant-guard.test.ts:62-113; crud-tenant-guard-batch.test.ts:35-73; tests/unit/security/tenant-isolation-matrix.test.ts:160-200 Guard is built once at boot and re-checks isMultiTenantMode() per call; if the settings cache flips to false for 5 s the whole guard becomes a pass-through (crud-tenant-guard.ts:191, :349).
Domain namespaces (auth/content/media/collection/system) complete src/databases/crud-tenant-guard.ts:341-378; wrapped at src/databases/db.ts:267-288 Last-arg options bag checked via enforceOptionsSync (:363-372); unbranded bypass impossible (system-tenant-scope.ts:94-98) tests/unit/multi-tenancy/crud-tenant-guard.test.ts:123-153; tests/unit/multi-tenancy/create-user-session-scope.test.ts:52-64 Namespaces whose methods take no options bag are left unwrapped (crud-tenant-guard.ts:369) — tenant scope then depends on the data payload only.
Request-bound adapter injection (forTenant) complete src/databases/tenant-adapter.ts:62-137 crud/auth/content/media/collection/system/batch/fts proxied (:83-94); explicit tenantId never overwritten (:71-73); 100-entry cap (:60, :131-134) tests/unit/databases/tenant-adapter.test.ts:20-52; tests/unit/sdk/sdk-fixes-audit.test.ts:120-135 Injection only happens when a tenant was resolved (:153); the fallback branch hands out the raw adapter (:157).
REST collection read/write complete src/routes/api/[...path]/+server.ts:383-418; handlers under src/routes/api/[...path]/handlers/ Dispatcher tenant + locals.dbAdapter; ?tenantId= super-admin only (:412-418) tests/integration/databases/tenant-isolation.test.ts:123-174; tests/integration/api/collections-mutations.test.ts; tests/e2e/multi-tenancy/isolation.spec.ts:179-360 The integration assertion is permissive: it accepts 200 **or** 401 (tenant-isolation.test.ts:157) and skips the leak check entirely when the status is not 200 (:158-161).
GraphQL collection queries complete src/routes/api/graphql/resolvers/collections.ts:512-552 Server tenant vs context tenant → throw (:538-543); user tenant vs context tenant → throw (:546-552); bypassTenantIsolation only set server-side tests/unit/graphql/multi-tenancy-isolation.test.ts:72-221 Check runs only if (isMultiTenantEnabled()) (:540); a 5 s flag miss disables it. ctx.bypassTenantIsolation (:529, :546) is read from context with no provenance check.
GraphQL media queries partial src/routes/api/graphql/resolvers/media.ts:100-117 media:read RBAC (:94-96); filter.tenantId added only when context.tenantId is truthy (:103-105) none found (grep -rn "mediaImages\|mediaDocuments" tests → no tenant assertion) The query relies on the bound adapter to inject tenantId into the options bag (+server.ts:1090, :1118); the explicit filter.tenantId silently disappears when ctx.tenantId is null (media.ts:103).
GraphQL data operations (export / import / backup / migration / sync) complete (fixed) src/routes/api/graphql/resolvers/data-operations.ts:346-367 (resolveGraphQLTenant) Every one of the 15 data-operation fields that accept tenantId resolves it through resolveGraphQLTenant: a caller-supplied value may differ from the session tenant only for super-admin; a multi-tenant deployment with no session tenant throws. tests/unit/api/graphql-tenant-scope.test.ts (7 cases, incl. the former contentExportRun hole and fail-closed tenantless case) The gate covers the 15 fields that accept tenantId; resolvers outside that set keep their own checks. Single-tenant behaviour is unchanged.
Local SDK / LocalCMS partial src/services/sdk/index.ts:102-135 (default tenant/user binding); :225-230 Defaults merged only when caller omits tenantId (:134-135); media namespace fails closed (src/services/sdk/namespaces/media-namespace.ts:141-144, :186-188, :224-226) tests/integration/sdk/local-cms.test.ts; tests/unit/sdk/sdk-hardening.test.ts A caller-supplied tenantId always wins (index.ts:106-107); the SDK therefore trusts its caller, and the only backstop is the adapter guard.
Relationships / populate / joins complete src/services/sdk/namespaces/populate-resolver.ts:160-162, :245-254 Relation reads carry the caller’s tenant (:251); system scope only when the relation read is tenantless (:252-254); relation cache keys tenant-prefixed (:190, :267) tests/unit/sdk/populate-policy.test.ts; tests/unit/sdk/relation-filter.test.ts —
Media / asset delivery (/files/*) complete src/routes/files/[...path]/+server.ts:486-499 Path tenant vs locals.tenantId (:488-498); signed-URL check after the gate (:505-510); transforms only after both (:532-534) tests/unit/hooks/file-server-tenant.test.ts:85-247 (25 cases) A principal whose tenantId is literally "global" bypasses every tenant directory (:492) — deliberate, but the value comes from locals, and the WS/plugin paths can mint "default"/"global" (hooks.ws.ts:261, plugins/[pluginId]/+server.ts:87).
Search / FTS indexing not-found src/databases/postgresql/fts-adapter.ts:321-329, :445-453 (tenant clause options?.tenantId ?? core.currentTenantId at :323, :447); src/databases/mariadb/fts-adapter.ts:155-168 (buildRawTenantClause from options only) No assertTenantContext in either adapter; PostgreSQL falls back to the mutable currentTenantId, MariaDB drops the predicate when options is absent tests/unit/databases/postgresql-fts-adapter.test.ts (no tenant case) No request-path caller exists: grep -rnw "fts" src outside src/databases returns 0 hits, so IFtsAdapter (db-interface.ts:1074, :1635; exposed at :1667) is an unwired capability. If wired as written, a missing options.tenantId on PostgreSQL runs under whichever tenant set context last (core/tenant-pool-manager.ts:41-59); on MariaDB it silently reads the global scope.
Bulk ops / batch partial src/databases/core/batch-module.ts:60-83, :250-278, :395-397 Mixed-tenant batch rejected (:60-83); applyTenantFilter per operation (:278, :397) tests/unit/databases/batch-module.test.ts; tests/integration/databases/bulk-operations-contract.test.ts batch is proxied by forTenant (tenant-adapter.ts:89-91) but is not in the boot-time namespace guard list (db.ts:267), so a db.batch obtained from a raw adapter has no assertTenantContext of its own.
Export / import (REST) partial src/routes/api/[...path]/handlers/system/system-transfer.ts:44-71, :76-99; src/routes/api/migration/import/+server.ts:122-128 TENANT_REQUIRED for export/import (system-transfer.ts:51-53, :83-85) tests/unit/api/export-import-security.test.ts Migration import has no tenant gate: it requires only config:collectionbuilder (migration/import/+server.ts:52-56) and forwards locals.tenantId ?? null (:128), which the guard reads as the global scope (safe-query.ts:87-89).
Background jobs (queue) partial src/services/background/jobs/job-queue-service.ts:94-121 tenantId is optional in the signature (:97) and copied into the job row (:116); under MULTI_TENANT the guarded system.jobs.create throws when it is absent tests/unit/routes/queue-actions.server.test.ts Fail-closed only via the namespace guard’s “last object arg is options” heuristic (crud-tenant-guard.ts:369-371) — the tenant is in the payload, not an options bag, so the guard reads jobData.tenantId by accident of shape.
Scheduled jobs complete src/services/scheduler.ts:310-314 forTenant(rawDb, job.tenantId) per job (:311), tenant passed to the workflow gate (:314, :328) tests/unit/scripts/* (no scheduler-tenant case) Jobs without tenantId run against the raw adapter (:311 ternary).
Webhooks / outbox partial src/services/background/webhook-service.ts:127-136, :175-194; src/services/outbox/outbox-service.ts:177-185, :229-239 Outbox fails closed on undefined/"" under MT (:233-239); webhook list is fetched per tenant (webhook-service.ts:184) tests/unit/api/webhook-security.test.ts; tests/unit/api/webhook-logs.test.ts Missing tenant degrades to "global" instead of failing: webhook-service.ts:132, :144, :175, :183. A tenantless request therefore dispatches the global webhook set.
Caches complete src/databases/cache/cache-service.ts:494-506; src/services/cache/response-cache.ts:642-643 tenant:<id>: key prefix (cache-service.ts:505); response-cache key prefix ${tenantId \|\| "default"} (response-cache.ts:643) tests/unit/databases/cache-service.test.ts; tests/unit/core/response-cache-read-after-write.test.ts null/undefined tenant collapses to the shared "default" namespace (cache-service.ts:189-190, :502), so every tenantless request shares one bucket.
Sessions partial src/databases/core/relational-auth.ts:719-793; src/databases/auth/session-manager.ts:9-11 Tenant predicate added only when options.tenantId !== undefined (relational-auth.ts:737-744, :767-773) tests/unit/databases/relational-auth-session-tenant-isolation.test.ts; tests/unit/databases/relational-auth-validate-session-tenant-isolation.test.ts; tests/unit/auth/sessions/session-user.test.ts With no options.tenantId, validateSession uses the noTenant SQL plan (:744) — any tenant’s session id validates. session-manager.ts:9-11 states the tenant check is the caller’s responsibility.
Collaboration / WebSocket partial src/hooks.ws.ts:238-261, :298-301, :314 Profile tenant vs connection tenant rejected (:298-304); Yjs docs keyed by tenant (src/routes/api/collaboration/yjs/+server.ts:50, :60, :80) tests/unit/routes/collaboration-yjs-server.test.ts Falls back to "default" when nothing resolves (hooks.ws.ts:261, :314) instead of rejecting.
Generated URLs / filesystem paths partial src/utils/path-resolver.ts:56-62, :69-72, :78-83 requireCollections() throws without context (:69-72, context.ts:46-52); media dir is mediaFolder/<tenant> (:82) tests/unit/multi-tenancy/tenant-normalization.test.ts getMedia() falls back to .../global when no tenant is in the ALS store (path-resolver.ts:82). sveltyContext is seeded with a tenantId in exactly one place — handle-authentication.ts:1798-1804; the outer runWithContext at hooks.server.ts:1126-1130 sets only requestId/abortSignal.
Public theme endpoint partial src/routes/api/theme/public/+server.ts:44-63 Tenant from ?tenantId=, ?hostname=, or the request host (:44-52); "default" rejected (:61) tests/unit/routes/theme-public-server.test.ts Unauthenticated and fully caller-selected: any caller can enumerate tenant ids and read each tenant’s branding (:44-49).
Plugin API routes partial src/routes/api/plugins/[pluginId]/+server.ts:36-43, :87-90 Plugin state cached per pluginId:tenantId (:37) tests/unit/routes/plugins-api-server.test.ts locals.tenantId ?? "default" (:87) — a tenantless request is served the default tenant’s plugin state instead of being rejected.
Lint guard (static) complete scripts/lint/lint-tenant-api.ts:9-19, :38-71 Bans positional tenantId on media/content/auth adapters (:244, :297), bans bypassTenantCheck: true outside a 31-entry allowlist (:38-71), requires the brand exports (:381, :403, :411) tests/unit/scripts/lint-tenant-scope.test.ts:18-66; wired into test:tenant (package.json:158) Allowlist is broad enough to include handlers/auth.ts, tenant-adapter.ts, mongo-db-adapter.ts, scheduled-jobs.ts, media-namespace.ts and populate-resolver.ts (:57, :50, :51, :64, :66, :67) — bypasses in exactly the files that matter most are legal by construction.
PostgreSQL Row-Level Security opt-in, wired src/databases/postgresql/adapter-core.ts:2231-2298 (policy + read-back), :2191-2211 (GUC) DDL exists but is never called — see §3. The method now fails closed after the DDL when the policy cannot filter none enables RLS: grep -rIn "\brls\b" tests → 2 hits, both asserting relrowsecurity = false (tests/integration/databases/tenant-pool-isolation.test.ts:210-214) enforceTenantPolicy has no production caller: grep -rn "enforceTenantPolicy" src → the interface declaration (db-interface.ts:1703) and the implementation only. No table gets ENABLE ROW LEVEL SECURITY.

3. Is PostgreSQL Row-Level Security actually implemented?

It is now wired as an opt-in mode (TENANT_RLS_ENABLED, off by default) and still fails closed: after the DDL it reads back the catalog and refuses to report success when the policy cannot filter. The default request path remains the application predicate, because a FORCE policy with an unbound context hides every row — see the prerequisites in multi-tenancy.

Piece Status Evidence
Policy DDL present, fails closed adapter-core.ts:2249 ALTER TABLE ... ENABLE ROW LEVEL SECURITY (deliberately not FORCE — see :2244-2248); :2257-2259 DROP POLICY IF EXISTS + CREATE POLICY tenant_isolation ... USING ("tenantId" = current_setting('app.tenant_id', true)). :2272-2292 reads back relrowsecurity / relforcerowsecurity / ownership from pg_class and throws when RLS did not enable, or when the connecting role owns the table without FORCE (an owner bypasses its own policies).
Session GUC present, unreachable on the request path adapter-core.ts:2191-2211. setTenantContext() writes app.tenant_id only when it is handed a transaction-scoped client (isLocal = Boolean(sql), :2209) or finds a per-tenant pool (:2206-2208). The request path passes neither: applyAdapterTenantContext calls it with the tenant argument only (tenant-adapter.ts:183), and getTenantPool()/setTenantPool() have zero callers outside their own definitions. So exec is undefined and the method returns before set_config (:2208) for every non-transactional query.
Transaction-local context present transaction-module.ts:189-191: set_config('app.tenant_id', <tenant>, true) batched with statement_timeout in one round trip; the third argument true makes it transaction-local.
Pool routing present, connection-level only getSql() (postgresql/adapter-core.ts:1490-1515; tenant branch :1500-1502): when currentTenantId is set, queries go to that tenant’s pool. postgresql/tenant-pool.ts:24-58 creates that pool from DATABASE_URL — the same database, so this is connection partitioning, not data isolation. Real DSN isolation only via setTenantPool() (adapter-core.ts:2368), which no boot path calls.
Policy creation call site wired (opt-in) grep -rn "enforceTenantPolicy" src scripts tests returns: the interface member (db-interface.ts:1703), the implementation (adapter-core.ts:2231), a shape assertion in tests/integration/databases/health-contract.test.ts, and docs. createModel() invokes it when TENANT_RLS_ENABLED=true (src/databases/postgresql/adapter-core.ts, after provisionPostgresTable) and throws when the policy cannot filter.
Tests dedicated suite re-verified 2026-11-11: grep -rIn "\brls\b" src scripts tests → 2 hits, both in tests/integration/databases/tenant-pool-isolation.test.ts:210-214, which asserts relrowsecurity = false (it guards the test’s own premise). Isolation without RLS is proven by tests/integration/databases/tenant-pool-isolation.test.ts (pool of one, stale session GUC, IDOR read/write, concurrency). RLS-on-tables is proven by tests/integration/databases/tenant-rls-request-path.test.ts: FORCE + policy provisioning from createModel(), a non-owner role seeing only its bound tenant (unbound → zero rows), cross-tenant writes rejected, one connection reused across tenants, and concurrent tenants that never cross scopes.

Consequence. Every isolation guarantee on PostgreSQL comes from the application-level WHERE "tenantId" = ? predicate (applyFilterAndOptions(), src/databases/core/sql-query-builder.ts:1367, tenant predicate :1422-1435; applyTenantFilter()/applyTenantFilterToObject() in src/databases/core/relational-utils.ts:989-1010; buildRawTenantClause() :1131-1162). The database has no second line of defence. Even after wiring enforceTenantPolicy, the GUC would only be bound inside an explicit db.transaction() (transaction-module.ts:188-197), because the non-transactional path never reaches set_config — so a plain findMany would still run with app.tenant_id unset and the policy would compare against NULL (hiding every row).

Documentation drift (corrected 2026-11-11). docs/reference/architecture/multi-tenancy.mdx previously stated that enforceTenantPolicy() “is called once” when a collection is provisioned and described per-request app.tenant_id on the shared pool. Neither held; the section is now labelled an opt-in, unwired primitive and keeps the accurate technical detail. docs/project/achievements-2026.mdx no longer claims “per-request SET SESSION app.tenant_id“.


4. Existing automated coverage

Suites: bun run test:tenant = lint:tenant + 4 files / 59 tests (package.json:158, measured 2026-11-11); bun run test:tenant:integration = tests/integration/databases/tenant-isolation.test.ts (package.json:159); bun run test:security = 21 files (package.json:146).

Test file Enforcement point exercised What it asserts
tests/unit/security/tenant-isolation-matrix.test.ts safe-query, media/auth/content entries, system scope 29 cases (12 generated from the operation matrix): missing tenant throws per entry point (:38, :176), branded scope allowed (:49, :181), forged scope rejected (:67, :73), demo implies isolation (:58), tenant-A filter cannot match tenant-B rows (:93, :122, :145), bulk update/delete fail closed (:188), MT-off passes through (:208).
tests/unit/security/safe-query-manual.test.ts assertTenantContext, safeQuery 13 cases: undefined throws (:67, :119), null accepted as global (:48), no object clone on bypass (:33), system scope honoured (:91, :99), single-tenant no-op (:74, :134).
tests/unit/security/system-tenant-scope.test.ts brand registry 7 cases: only createSystemTenantScope output passes (:31), plain look-alikes rejected (:38, :64), survives duplicated module instances (:70).
tests/unit/multi-tenancy/crud-tenant-guard.test.ts createTenantGuardedCrud / Namespace 10 cases: find/insert throw without tenant (:63, :72), explicit tenant allowed (:79), options tenant copied into data (:84), existing tenant preserved (:93), bypass mode passes through (:115), namespace requires options bag (:133, :143), MT-off passes (:156).
tests/unit/multi-tenancy/crud-tenant-guard-batch.test.ts batch write variants options tenant copied into insertMany/upsertMany rows; mismatched body tenant throws (:35-73).
tests/unit/multi-tenancy/create-user-session-scope.test.ts auth namespace guard user/session creation accepted only with a branded system scope (:52-64).
tests/unit/multi-tenancy/physical-pool-partitioning.test.ts setTenantContext, pool map pool chosen per tenant, null tenant clears routing (:60, :116, :135).
tests/unit/multi-tenancy/collections-migration.test.ts tenant config dirs migrateToMultiTenant moves .ts files from the flat dir into the tenant dir (:14, :33), skips existing (:63), ignores non-.ts (:82), runFullMigration (:108).
tests/unit/multi-tenancy/00-tenant-utils.test.ts, tenant-normalization.test.ts utils/tenant, path helpers hostname derivation, normalization, reserved subdomains.
tests/unit/databases/tenant-adapter.test.ts forTenant bound adapter reused per (adapter, tenant) (:21), system scope passes through (:32), explicit tenant untouched (:43).
tests/unit/databases/tenant-pool-manager.test.ts TenantPoolManager acquisition, idle eviction, in-flight protection, close-all.
tests/unit/databases/relational-auth-session-tenant-isolation.test.ts / relational-auth-validate-session-tenant-isolation.test.ts session delete/validate tenant-scoped deletes and validation do not touch another tenant’s rows.
tests/unit/graphql/multi-tenancy-isolation.test.ts collection resolvers context/server tenant mismatch throws (:72), user/context mismatch throws (:111), unauthenticated query rejected (:146), matching tenant scoped (:174), global admin bypass (:222).
tests/unit/hooks/file-server-tenant.test.ts /files/* gate 25 cases across MT-off, matching, non-matching, missing tenant, global bypass, global-scoped files, edge paths (:61-247).
tests/unit/hooks/request-tenant.test.ts resolveRequestTenant header honoured only in test mode, charset and "null" rejection, session fallback.
tests/unit/scripts/lint-tenant-scope.test.ts lint rules flags unconditional system scope (:19, :28), allows conditional spread (:36), honours suppression (:52), scans Svelte blocks (:60).
tests/integration/databases/tenant-isolation.test.ts end-to-end REST A-vs-B marker written under A is absent from B’s list; a cross-tenant read must be 401/403, or 200 with an explicitly empty tenant-B slice (the old 200 or 401 acceptance was removed).
tests/integration/databases/tenant-pool-isolation.test.ts pool-of-one adversarial isolation alternating/concurrent A/B reads, IDOR guessed ids, a stale session app.tenant_id, and a failed statement on the reused connection; also asserts isolation comes from the predicate, not RLS.
tests/unit/api/graphql-tenant-scope.test.ts GraphQL data-operation tenant gate foreign tenantId rejected for tenant admin and plain user, allowed for super-admin, session fallback, fail-closed tenantless multi-tenant case, single-tenant unchanged.
tests/e2e/multi-tenancy/isolation.spec.ts browser-level 5 scenarios: listing blocked (:179), entry access blocked (:228), media isolation (:300), same-tenant works (:361), global resources shared (:426).

Not in any targeted suite (they run only inside the full unit run): tenant-adapter.test.ts, crud-tenant-guard-batch.test.ts, tenant-pool-manager.test.ts, physical-pool-partitioning.test.ts, graphql/multi-tenancy-isolation.test.ts, and the relational-auth-*tenant-isolation* pair. test:tenant lists exactly four files (package.json:158) — 29 + 13 + 7 + 10 = 59 tests.


5. Prioritised missing data-safety tests

Each case is written so it fails on the branch it was written against — that is the point of adding it. Items 1 and 5 have since shipped (their rows above are marked fixed); they are retained as the acceptance criteria that the new tests pin.

1. GraphQL data operations must reject a foreign tenantId argument (shipped)

  • Precondition: MULTI_TENANT=true; logged-in non-admin user of tenant-a; a collection posts with a row owned by tenant-b.
  • Action: mutation { contentExportRun(collections:["posts"], tenantId:"tenant-b") { manifest } } against /api/graphql.
  • Expected behaviour (now implemented): 403 (or GraphQL error), and no tenant-b content in the response. resolveGraphQLTenant() (data-operations.ts:346-367) rejects a differing tenant for anyone below super-admin, and a multi-tenant deployment with no session tenant throws. Pinned by tests/unit/api/graphql-tenant-scope.test.ts.
  • Also covered: the same resolver gate is applied to every data-operation field that accepts tenantId (the 15 fields); other resolvers keep their own checks.
  • Suggested file: tests/unit/api/graphql-tenant-scope.test.ts.

2. Provisioning a collection must enable and be able to prove PostgreSQL RLS

  • Precondition: PostgreSQL adapter, MULTI_TENANT=true, connected as the table owner.
  • Action: create collection rls_probe, then query SELECT relrowsecurity FROM pg_class WHERE relname='collection_rlsprobe' and SELECT polname FROM pg_policy.
  • Expected failure mode (still open): relrowsecurity = true and a tenant_isolation policy exists is the correct end state, but it is not reachable today: relrowsecurity = false and pg_policy is empty, because enforceTenantPolicy has no caller (adapter-core.ts:2231, interface at db-interface.ts:1703). Calling it directly now fails closed (owner-bypass read-back) rather than reporting success.
  • Suggested file: tests/integration/databases/tenant-rls-wiring.test.ts (skip unless DB_TYPE=postgresql).

3. A tenantless request must be rejected at the HTTP boundary, not written to the global layer

  • Precondition: MULTI_TENANT=true; authenticated admin; request to a bare two-label host (cms.example.com) so getTenantIdFromHostname returns null (tenant.ts:47) and no session tenant is present.
  • Action: POST /api/collections/posts with a valid body and no ?tenantId=.
  • Expected failure mode: 400 TENANT_REQUIRED, and SELECT count(*) FROM collection_posts WHERE "tenantId" IS NULL unchanged. Today the hook leaves the tenant null (handle-authentication.ts:1117, :1201), the raw adapter is exposed (tenant-adapter.ts:157), and assertTenantContext accepts null as the global scope (safe-query.ts:87-89), so the row can be written with tenantId NULL — the layer every other tenantless request can read.
  • Suggested file: tests/integration/api/tenantless-write-fails-closed.test.ts.

4. Full-text search must not inherit the ambient tenant of another request

  • Precondition: MULTI_TENANT=true; two tenants with identical titles; adapter fts available.
  • Action: applyAdapterTenantContext(db, "tenant-a"), then applyAdapterTenantContext(db, "tenant-b"), then call db.fts.search(collection, query) without options.tenantId.
  • Expected failure mode: either throw TENANT_CONTEXT_MISSING, or run with the caller’s tenant — never with tenant-b. Today the PostgreSQL clause is built from options?.tenantId ?? core.currentTenantId (postgresql/fts-adapter.ts:323, :447) and currentTenantId is mutable adapter state (core/tenant-pool-manager.ts:41-59), so the search runs under whichever tenant set context last. MariaDB builds the predicate from options only (mariadb/fts-adapter.ts:155-168), so the equivalent failure there is a dropped predicate (a global read), not a stale tenant. Add the converse case: two interleaved requests must not cross.
  • Suggested file: tests/unit/databases/fts-tenant-context.test.ts.

5. An integration leak assertion must not accept “200 or 401” as a pass (shipped)

  • Precondition: MULTI_TENANT=true; marker row seeded under tenant-a; admin session; x-test-tenant-id: tenant-b.
  • Action: GET /api/collections/<coll>?publicationFilter=all as tenant B.
  • Expected behaviour (now implemented): exactly 200 and the marker absent; if the request is unauthenticated it must be 401, and the test fails rather than skips. The former permissive assertion in tenant-isolation.test.ts accepted both statuses and only checked the body on 200; it now requires 401/403, or 200 with an explicitly empty tenant-B slice, and a DB-less run skips with a reason.
  • Suggested file: keep tests/integration/databases/tenant-isolation.test.ts tight, plus the same assertion for GraphQL (/api/graphql).

6. Known bypass inventory (for reviewers)

# Path What it permits Evidence
1 Mutation *(... tenantId: String) in GraphQL data operations (closed) Read/export/backup/sync another tenant by argument — closed: resolveGraphQLTenant() rejects a differing tenant below super-admin data-operations.ts:346-367; tests/unit/api/graphql-tenant-scope.test.ts
2 ?tenantId= on /api/* and /api/system/* Cross-tenant for super-admin only (intended) +server.ts:412-418; system-shared.ts:74-79
3 locals.tenantId === "global" on /files/* Read any tenant’s media directory files/[...path]/+server.ts:492
4 Tenantless write on a two-label host Row written with tenantId NULL (global layer) handle-authentication.ts:1201; safe-query.ts:87-89
5 Ambient currentTenantId in FTS Query scoped to the last request’s tenant postgresql/fts-adapter.ts:323; tenant-pool-manager.ts:41
6 tenantId \|\| "global" fallbacks Tenantless request served the global webhook/collaboration set webhook-service.ts:132, :183; hooks.ws.ts:261
7 locals.tenantId ?? "default" Tenantless request served default tenant’s plugin state plugins/[pluginId]/+server.ts:87
8 validateSession noTenant plan Session validated without any tenant predicate relational-auth.ts:737-744
9 Migration import with null tenant Import written into the global layer by a non-admin config:collectionbuilder holder migration/import/+server.ts:52-56, :128
securitymulti-tenancyinventoryrlsgraphql
Was this page helpful?