/** * Findings: A-05 (tenant isolation for TenantEase / Revio), S-05 (don't rely on middleware alone) * * Layer 1 of 2: application-level scoping. Every query made through `forTenant()` gets the * caller's organizationId injected, so a developer can't forget the WHERE clause. * Layer 2 is Postgres row-level security (rls.sql), which still holds if layer 1 is bypassed. * * Authorisation happens inside each server action / route handler, not only in middleware: * CVE-2025-29927 showed middleware can be skipped, and defence in depth is cheap here. */ import { db } from "@/lib/db"; export type Role = "ADMIN" | "MANAGER" | "ADVISOR"; // Revio's published role hierarchy export type Session = { userId: string; organizationId: string; role: Role; locationIds: string[] }; const TENANT_MODELS = new Set(["Property", "Unit", "Tenant", "RentPayment", "Review", "Location"]); const FILTERED_OPS = new Set([ "findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "findMany", "update", "updateMany", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", ]); /** Least-privilege permission table. The UI may hide buttons; the server decides. */ const PERMISSIONS: Record> = { ADMIN: new Set(["review:read", "review:reply", "location:manage", "user:manage", "billing:manage"]), MANAGER: new Set(["review:read", "review:reply", "location:manage"]), ADVISOR: new Set(["review:read", "review:reply"]), // and only for their own locations }; export class Forbidden extends Error {} export function authorize(session: Session, permission: string, locationId?: string) { if (!PERMISSIONS[session.role].has(permission)) throw new Forbidden(permission); if (session.role === "ADVISOR" && locationId && !session.locationIds.includes(locationId)) { throw new Forbidden(`${permission} @ ${locationId}`); } } /** * Returns a Prisma client that (a) adds organizationId to every read/update/delete filter, * (b) stamps it on every create, and (c) sets the Postgres session variable RLS reads. */ export function forTenant(session: Session) { const orgId = session.organizationId; return db.$extends({ query: { $allModels: { async $allOperations({ model, operation, args, query }: { model: string; operation: string; args: any; query: (a: any) => Promise }) { if (!TENANT_MODELS.has(model)) return query(args); if (operation === "create") { args.data = { ...args.data, organizationId: orgId }; } else if (operation === "createMany") { args.data = (Array.isArray(args.data) ? args.data : [args.data]).map((d: object) => ({ ...d, organizationId: orgId })); } else if (FILTERED_OPS.has(operation)) { // Spread (not AND) keeps findUnique valid: Prisma 5+ accepts extra non-unique // filters next to the unique key. Spreading last also overrides any orgId a // caller passed in, so another tenant's id can never be smuggled through. args.where = { ...(args.where ?? {}), organizationId: orgId }; if (operation === "upsert") args.create = { ...args.create, organizationId: orgId }; } // Layer 2 handshake: RLS policies read app.org_id. set_config(..., true) is // transaction-local, so it can't bleed into another request on a pooled connection. const [, result] = await db.$transaction([ db.$executeRaw`SELECT set_config('app.org_id', ${orgId}, true)`, query(args) as any, ]); return result; }, }, }, }); } /* * Usage in a server action: * * export async function replyToReview(reviewId: string, text: string) { * const session = await requireSession(); // re-validate here, not just in middleware * const tdb = forTenant(session); * const review = await tdb.review.findUnique({ where: { id: reviewId } }); // null if other tenant * if (!review) throw new Forbidden("review"); * authorize(session, "review:reply", review.locationId); * ... * } */