Tenant Isolation
Multi-tenant data isolation by default.
What it shows
Section titled “What it shows”- Tenant filter on ordinary handlers
ctx.db.upsert: insert-or-update on a tenant-scoped, non-event-sourced table.conflictTargetmust containtenantIdand match a declared unique index (heretenant_id, key); event-fed tables are rejected- What breaks if you forget tenancy (and how the framework prevents it)
Source
Section titled “Source”Feature entry point: src/feature.ts.
Needs the Postgres from the repo root’s docker-compose.yml (docker compose up -d); TEST_DATABASE_URL defaults to postgresql://kumiko:kumiko@localhost:15432/kumiko_test.
cd samples/recipes/tenant-isolationbun testSource code
Section titled “Source code”The feature entry point — embedded straight from the source file, so the code here is exactly what runs. Multi-file samples keep their remaining files next to it on GitHub (link below):
import { defineUnmanagedTable } from "@cosmicdrift/kumiko-framework/db";import { createEntity, createTextField, defineFeature } from "@cosmicdrift/kumiko-framework/engine";import * as z from "zod";
export const noteEntity = createEntity({ name: "note", table: "read_sample_notes", fields: { title: createTextField({ personal: false, reason: "is_business_data", required: true }), content: createTextField({ personal: false, reason: "is_business_data" }), },});
// Not event-sourced: ctx.db.upsert rejects executor-managed tables.export const preferenceTable = defineUnmanagedTable({ tableName: "sample_tenant_preferences", columns: [ { name: "id", pgType: "uuid", notNull: true, primaryKey: true, defaultSql: "gen_random_uuid()", }, { name: "tenant_id", pgType: "uuid", notNull: true }, { name: "key", pgType: "text", notNull: true }, { name: "value", pgType: "text", notNull: true }, { name: "changes", pgType: "integer", notNull: true, defaultSql: "0" }, ], indexes: [ { name: "sample_tenant_preferences_tenant_key", columns: ["tenant_id", "key"], unique: true }, ],});
const adminWrite = { access: { roles: ["Admin"] } } as const;const openRead = { access: { openToAll: { reason: "any signed-in user may list and view notes in their own tenant (tenant " + "isolation, not per-user); writes are still gated by adminWrite", }, },} as const;
export const noteFeature = defineFeature("notes", (r) => { r.crud(noteEntity, { write: adminWrite, read: openRead, verbs: { update: false, delete: false, restore: false }, });
r.storeTable(preferenceTable, { reason: "settings.tenant_preferences" });
r.writeHandler({ name: "preference:set", schema: z.object({ key: z.string().min(1), value: z.string() }), handler: async (event, ctx) => { const row = await ctx.db.upsert<{ value: string; changes: number }>( preferenceTable, event.payload, { conflictTarget: ["tenantId", "key"], increment: { changes: 1 } }, ); return { isSuccess: true, data: { value: row?.value, changes: row?.changes } }; }, ...adminWrite, });});📄 On GitHub: samples/recipes/tenant-isolation/src/feature.ts