Enforce tenant isolation in the data layer instead of per route
Every route had to remember to add the business filter to every query;
nothing stopped one that forgot. The audit for this change found several
that had: the M-Pesa status re-check, the stock ledger's duplicate checks,
the daily-inventory and branch-price upserts, a cash-sale replay lookup,
several load-by-id lookups, and every populate().
- tenantGuard: a Mongoose plugin on all ten business-scoped models. Any
find/update/delete/count/distinct, or an aggregate whose first stage is
not a $match, that does not pin exactly one businessId throws
TenantScopeError before reaching the database ($in, $exists and other
operators do not count).
- crossTenant("reason", fn): the explicit, documented exemption for the
queries that must span businesses - login's email lookup, refresh and
invite-token lookups, the M-Pesa callback, the platform console and the
maintenance scripts. git grep crossTenant lists them all.
- scopedPopulate: populated branch, product and staff names are also
restricted to the business.
- Every flagged query site now names the business (or is exempted with a
reason).
- Tests: a check that every model with a businessId field carries the
guard; the guard refusing unscoped queries of every kind; and a route
sweep where business A sends business B's ids to every read route
(nothing of B's comes back) and every write route (all refused, B's
data unchanged). Test-side database inspections go through db(), an
explicit test exemption. Removing one route's business filter makes the
suite fail.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ import * as login from "@/app/api/auth/login/route";
|
||||
import * as me from "@/app/api/auth/me/route";
|
||||
import * as platformBusinesses from "@/app/api/platform/businesses/route";
|
||||
import { ACCESS_COOKIE } from "@/lib/server/auth";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant } from "./helpers";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant, db } from "./helpers";
|
||||
|
||||
const PERSON = { name: "Wanjiru", email: "wanjiru@aquaflow.test", phoneNumber: "0722000111" };
|
||||
const OPERATOR = "operator@aquaflow.test"; // listed in PLATFORM_ADMIN_EMAILS by tests/setup.ts
|
||||
@@ -35,7 +35,7 @@ describe("email and phone are unique per business", () => {
|
||||
const b = await makeTenant("Beta");
|
||||
expect((await hire(a, a.owner)).status).toBe(201);
|
||||
expect((await hire(b, b.owner)).status).toBe(201);
|
||||
expect(await User.countDocuments({ email: PERSON.email })).toBe(2);
|
||||
expect(await db(() => User.countDocuments({ email: PERSON.email }))).toBe(2);
|
||||
});
|
||||
|
||||
it("still refuses a duplicate inside the same business", async () => {
|
||||
|
||||
Reference in New Issue
Block a user