feat(01-03): Prisma tenant middleware, PostgreSQL RLS, and isolation tests

- Create src/lib/prisma-tenant.ts:
  - withTenantContext(tenantId) / createTenantPrisma — Prisma $extends client
  - Intercepts findMany, findFirst, findUnique, create, createMany, update,
    updateMany, delete, deleteMany, upsert, count, aggregate, groupBy on User
  - Auto-injects tenantId filter on all reads, writes, and deletes
  - setTenantRLS() helper for explicit RLS enforcement in transactions
  - TENANT_SCOPED_MODELS constant for future extensibility
- Create prisma/migrations/20260304104214_initial_schema — baseline migration
  capturing schema created by initial db push
- Create prisma/migrations/20260304104245_add_rls_policies:
  - ALTER TABLE User ENABLE ROW LEVEL SECURITY
  - CREATE POLICY tenant_isolation_user USING app.current_tenant_id session var
  - Defense-in-depth architecture comments explaining primary vs secondary enforcement
- Create src/lib/__tests__/tenant-isolation.test.ts (6 tests, all passing):
  - Test 1: Tenant A context returns only Tenant A's users (zero from B)
  - Test 2: Tenant B context returns only Tenant B's users (zero from A)
  - Test 3: create() auto-sets tenantId, invisible to other tenant
  - Test 4: findUnique by Tenant B's ID under Tenant A context returns null
  - Additional: findFirst cross-tenant blocked, count() is tenant-scoped
This commit is contained in:
kevin-asprec
2026-03-04 18:45:13 +08:00
parent cf790c3257
commit 69eac9ffaa
5 changed files with 552 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
-- =============================================================================
-- Initial Schema Migration
-- Created as a baseline to capture the state created by `prisma db push`
-- during project initialization (01-01-PLAN.md).
--
-- This migration is marked as applied without running it (baseline approach)
-- since the schema already exists in the database from the initial db push.
-- =============================================================================
-- CreateEnum
CREATE TYPE "TenantStatus" AS ENUM ('ACTIVE', 'PENDING_SUSPENSION', 'SUSPENDED');
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('ADMIN', 'OFFICE_STAFF', 'COLLECTOR', 'TECHNICIAN', 'CLIENT');
-- CreateTable
CREATE TABLE "Tenant" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"ownerEmail" TEXT NOT NULL,
"businessAddress" TEXT,
"contactPhone" TEXT,
"status" "TenantStatus" NOT NULL DEFAULT 'ACTIVE',
"suspendedAt" TIMESTAMP(3),
"gracePeriodEndsAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Tenant_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"passwordHash" TEXT NOT NULL,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"tenantId" TEXT,
"roles" "Role"[],
"isActive" BOOLEAN NOT NULL DEFAULT true,
"isSuperAdmin" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Tenant_slug_key" ON "Tenant"("slug");
-- CreateIndex
CREATE INDEX "User_tenantId_idx" ON "User"("tenantId");
-- CreateIndex
CREATE UNIQUE INDEX "User_email_tenantId_key" ON "User"("email", "tenantId");
-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_tenantId_fkey" FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,41 @@
-- =============================================================================
-- PostgreSQL Row-Level Security (RLS) Policies
-- Defense-in-depth tenant isolation for NetForge
-- =============================================================================
--
-- ARCHITECTURE NOTE:
-- The primary multi-tenancy enforcement is at the application layer via
-- Prisma query extensions in src/lib/prisma-tenant.ts (withTenantContext).
--
-- RLS policies here serve as DEFENSE-IN-DEPTH:
-- - They catch bugs where application code bypasses the Prisma middleware
-- - They provide an independent enforcement layer at the database level
-- - They document data isolation intent in the database schema itself
--
-- IMPORTANT: The Prisma client connects as the database OWNER, which by
-- default bypasses RLS (PostgreSQL superusers and table owners bypass RLS
-- unless FORCE ROW LEVEL SECURITY is set on the table). This means these
-- policies will NOT block queries from the standard Prisma client unless
-- FORCE ROW LEVEL SECURITY is enabled, or a non-owner role is used.
--
-- To enforce RLS for a query, use setTenantRLS() from src/lib/prisma-tenant.ts
-- within a transaction before executing queries. This sets the session variable
-- app.current_tenant_id which the policy USING clause reads.
-- =============================================================================
-- Enable RLS on the User table
ALTER TABLE "User" ENABLE ROW LEVEL SECURITY;
-- Policy: tenant_isolation_user
-- Restricts access to rows matching the current tenant context.
-- The app.current_tenant_id session variable is set by setTenantRLS().
-- When no tenant context is set (super-admin operations), all rows are visible.
CREATE POLICY tenant_isolation_user ON "User"
USING (
"tenantId" = current_setting('app.current_tenant_id', true)::text
OR current_setting('app.current_tenant_id', true) IS NULL
OR current_setting('app.current_tenant_id', true) = ''
)
WITH CHECK (
"tenantId" = current_setting('app.current_tenant_id', true)::text
);

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"