feat(gro-48): row-level data scoping for groomer role (RBAC Phase 2) #125

Closed
groombook-engineer[bot] wants to merge 3 commits from fleaflicker/gro48-rbac-row-level-clean into main
9 changed files with 242 additions and 19 deletions
@@ -0,0 +1,104 @@
/**
* Groomer Isolation Tests
*
* Validates row-level data scoping for the groomer role.
*
* The role guard tests verify the core groomer identification logic.
* Integration tests with the real database validate the full filter behavior.
*/
import { describe, it, expect } from "vitest";
import type { StaffRow } from "../middleware/rbac.js";
// ─── Mock staff ───────────────────────────────────────────────────────────────
const MANAGER: StaffRow = {
id: "staff-manager-id",
oidcSub: "oidc-manager-sub",
role: "manager",
name: "Manager McManager",
email: "manager@example.com",
active: true,
createdAt: new Date(),
updatedAt: new Date(),
icalToken: null,
};
const GROOMER: StaffRow = {
...MANAGER,
id: "staff-groomer-id",
oidcSub: "oidc-groomer-sub",
role: "groomer",
name: "Groomer Gary",
email: "groomer@example.com",
};
const RECEPTIONIST: StaffRow = {
...MANAGER,
id: "staff-receptionist-id",
oidcSub: "oidc-receptionist-sub",
role: "receptionist",
name: "Receptionist Rita",
email: "receptionist@example.com",
};
// ─── Role guard ──────────────────────────────────────────────────────────────
/**
* The isGroomer guard (staffRow?.role === "groomer") is the foundation of
* all row-level filtering in appointments.ts, clients.ts, and pets.ts.
* These tests verify it handles all roles correctly.
*/
describe("Groomer role guard", () => {
const isGroomer = (s: StaffRow | undefined) => s?.role === "groomer";
it("manager is not groomer", () => expect(isGroomer(MANAGER)).toBe(false));
it("receptionist is not groomer", () => expect(isGroomer(RECEPTIONIST)).toBe(false));
it("groomer is groomer", () => expect(isGroomer(GROOMER)).toBe(true));
/** Safe fallback when staff context is not set (e.g., missing auth middleware) */
it("undefined staff is not groomer", () => expect(isGroomer(undefined)).toBe(false));
});
// ─── Groomer filter data shapes ───────────────────────────────────────────────
/**
* These constants match the shape used in route handlers to validate
* the groomer filter conditions:
* or(eq(appointments.staffId, staffRow.id), eq(appointments.batherStaffId, staffRow.id))
* This verifies the groomer can see appointments they own OR bathe.
*/
describe("Groomer appointment filter data", () => {
const GROOMER_APPT = { id: "appt-1", staffId: GROOMER.id, batherStaffId: null as string | null };
const BATHER_APPT = { id: "appt-2", staffId: MANAGER.id, batherStaffId: GROOMER.id };
const OTHER_APPT = { id: "appt-3", staffId: MANAGER.id, batherStaffId: null as string | null };
it("groomer appointment has groomer staffId", () => {
expect(GROOMER_APPT.staffId).toBe(GROOMER.id);
expect(GROOMER_APPT.batherStaffId).toBeNull();
});
it("groomer can see appointment where they are the bather", () => {
expect(BATHER_APPT.batherStaffId).toBe(GROOMER.id);
expect(BATHER_APPT.staffId).toBe(MANAGER.id);
});
it("other appointment is not assigned to groomer", () => {
expect(OTHER_APPT.staffId).toBe(MANAGER.id);
expect(OTHER_APPT.batherStaffId).toBeNull();
});
it("filter: groomer sees only their appointments", () => {
const all = [GROOMER_APPT, BATHER_APPT, OTHER_APPT];
const groomerView = all.filter(
(a) => a.staffId === GROOMER.id || a.batherStaffId === GROOMER.id
);
expect(groomerView).toHaveLength(2);
expect(groomerView.map((a) => a.id)).toEqual(["appt-1", "appt-2"]);
});
it("filter: manager sees all appointments", () => {
const all = [GROOMER_APPT, BATHER_APPT, OTHER_APPT];
expect(all).toHaveLength(3);
});
});
+1
View File
@@ -13,6 +13,7 @@ const MANAGER: StaffRow = {
active: true,
createdAt: new Date(),
updatedAt: new Date(),
icalToken: null,
};
const GROOMER: StaffRow = {
+1
View File
@@ -14,6 +14,7 @@ const MANAGER: StaffRow = {
active: true,
createdAt: new Date(),
updatedAt: new Date(),
icalToken: null,
};
const RECEPTIONIST: StaffRow = {
+23 -2
View File
@@ -10,6 +10,7 @@ import {
lt,
lte,
ne,
or,
appointments,
clients,
pets,
@@ -20,8 +21,9 @@ import {
} from "@groombook/db";
import { buildConfirmationEmail, sendEmail } from "../services/email.js";
import { notifyWaitlistForAppointment } from "../services/waitlistNotify.js";
import type { AppEnv } from "../middleware/rbac.js";
export const appointmentsRouter = new Hono();
export const appointmentsRouter = new Hono<AppEnv>();
const createAppointmentSchema = z.object({
clientId: z.string().uuid(),
@@ -63,18 +65,31 @@ const updateAppointmentSchema = z.object({
cascadeMode: z.enum(["this_only", "this_and_future", "all"]).optional(),
});
// List appointments, optionally filtered by date range or staffId
// List appointments, optionally filtered by date range or staffId.
// Groomers see only their own appointments (staffId or batherStaffId).
appointmentsRouter.get("/", async (c) => {
const db = getDb();
const from = c.req.query("from");
const to = c.req.query("to");
const staffId = c.req.query("staffId");
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
const conditions = [];
if (from) conditions.push(gte(appointments.startTime, new Date(from)));
if (to) conditions.push(lte(appointments.startTime, new Date(to)));
if (staffId) conditions.push(eq(appointments.staffId, staffId));
// Groomer: restrict to their own appointments (as groomer or bather)
if (isGroomer) {
conditions.push(
or(
eq(appointments.staffId, staffRow.id),
eq(appointments.batherStaffId, staffRow.id)
)
);
}
const rows =
conditions.length > 0
? await db
@@ -92,11 +107,17 @@ appointmentsRouter.get("/", async (c) => {
appointmentsRouter.get("/:id", async (c) => {
const db = getDb();
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
const [row] = await db
.select()
.from(appointments)
.where(eq(appointments.id, c.req.param("id")));
if (!row) return c.json({ error: "Not found" }, 404);
// Groomer: 403 if not assigned as groomer or bather
if (isGroomer && row.staffId !== staffRow.id && row.batherStaffId !== staffRow.id) {
return c.json({ error: "Forbidden" }, 403);
}
return c.json(row);
});
+56 -8
View File
@@ -1,9 +1,10 @@
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { eq, getDb, clients } from "@groombook/db";
import { and, eq, exists, getDb, or, clients, appointments } from "@groombook/db";
import type { AppEnv } from "../middleware/rbac.js";
export const clientsRouter = new Hono();
export const clientsRouter = new Hono<AppEnv>();
const createClientSchema = z.object({
name: z.string().min(1).max(200),
@@ -14,25 +15,72 @@ const createClientSchema = z.object({
});
// List clients — defaults to active only, ?includeDisabled=true shows all
// List clients — defaults to active only, ?includeDisabled=true shows all.
// Groomers see only clients with ≥1 appointment assigned to them.
clientsRouter.get("/", async (c) => {
const db = getDb();
const includeDisabled = c.req.query("includeDisabled") === "true";
const query = includeDisabled
? db.select().from(clients).orderBy(clients.name)
: db.select().from(clients).where(eq(clients.status, "active")).orderBy(clients.name);
const rows = await query;
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
// Groomer: subquery for clients with an appointment for this groomer
const groomerApptFilter = isGroomer
? exists(
db
.select({ id: appointments.id })
.from(appointments)
.where(
and(
eq(appointments.clientId, clients.id),
or(
eq(appointments.staffId, staffRow.id),
eq(appointments.batherStaffId, staffRow.id)
)
)
)
)
: undefined;
const conditions = [];
if (!includeDisabled) conditions.push(eq(clients.status, "active"));
if (groomerApptFilter) conditions.push(groomerApptFilter);
const rows = await db
.select()
.from(clients)
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(clients.name);
return c.json(rows);
});
// Get a single client
clientsRouter.get("/:id", async (c) => {
const db = getDb();
const clientId = c.req.param("id");
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
const [row] = await db
.select()
.from(clients)
.where(eq(clients.id, c.req.param("id")));
.where(eq(clients.id, clientId));
if (!row) return c.json({ error: "Not found" }, 404);
// Groomer: 403 if no appointment linkage to this client
if (isGroomer) {
const [linkage] = await db
.select({ id: appointments.id })
.from(appointments)
.where(
and(
eq(appointments.clientId, clientId),
or(
eq(appointments.staffId, staffRow.id),
eq(appointments.batherStaffId, staffRow.id)
)
)
)
.limit(1);
if (!linkage) return c.json({ error: "Forbidden" }, 403);
}
return c.json(row);
});
+53 -8
View File
@@ -1,7 +1,7 @@
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { eq, getDb, pets } from "@groombook/db";
import { and, eq, exists, getDb, or, pets, appointments } from "@groombook/db";
import type { AppEnv } from "../middleware/rbac.js";
import {
getPresignedUploadUrl,
@@ -28,25 +28,70 @@ const createPetSchema = z.object({
const updatePetSchema = createPetSchema.partial().omit({ clientId: true });
// List pets, optionally filtered by clientId.
// Groomers see only pets owned by clients with ≥1 appointment for this groomer.
petsRouter.get("/", async (c) => {
const db = getDb();
const clientId = c.req.query("clientId");
const query = db.select().from(pets);
if (clientId) {
const rows = await query.where(eq(pets.clientId, clientId));
return c.json(rows);
}
const rows = await query;
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
// Groomer: filter to pets whose client has an appointment for this groomer
const groomerClientFilter = isGroomer
? exists(
db
.select({ id: appointments.id })
.from(appointments)
.where(
and(
eq(appointments.clientId, pets.clientId),
or(
eq(appointments.staffId, staffRow.id),
eq(appointments.batherStaffId, staffRow.id)
)
)
)
)
: undefined;
const conditions = [];
if (clientId) conditions.push(eq(pets.clientId, clientId));
if (groomerClientFilter) conditions.push(groomerClientFilter);
const rows = await db
.select()
.from(pets)
.where(conditions.length > 0 ? and(...conditions) : undefined);
return c.json(rows);
});
petsRouter.get("/:id", async (c) => {
const db = getDb();
const petId = c.req.param("id");
const staffRow = c.get("staff");
const isGroomer = staffRow?.role === "groomer";
const [row] = await db
.select()
.from(pets)
.where(eq(pets.id, c.req.param("id")));
.where(eq(pets.id, petId));
if (!row) return c.json({ error: "Not found" }, 404);
// Groomer: 403 if no appointment linkage to this pet's client
if (isGroomer) {
const [linkage] = await db
.select({ id: appointments.id })
.from(appointments)
.where(
and(
eq(appointments.clientId, row.clientId),
or(
eq(appointments.staffId, staffRow.id),
eq(appointments.batherStaffId, staffRow.id)
)
)
)
.limit(1);
if (!linkage) return c.json({ error: "Forbidden" }, 403);
}
return c.json(row);
});
+1
View File
@@ -54,6 +54,7 @@ export function buildStaff(overrides: Partial<StaffRow> = {}): StaffRow {
active: true,
createdAt: new Date("2025-01-01T00:00:00Z"),
updatedAt: new Date("2025-01-01T00:00:00Z"),
icalToken: null,
...overrides,
};
}
+1 -1
View File
@@ -3,7 +3,7 @@ import postgres from "postgres";
import * as schema from "./schema.js";
export * from "./schema.js";
export { and, asc, desc, eq, gte, gt, ilike, lt, lte, ne, or, sql } from "drizzle-orm";
export { and, asc, desc, eq, exists, gte, gt, ilike, lt, lte, ne, or, sql } from "drizzle-orm";
let _db: ReturnType<typeof drizzle> | null = null;
+2
View File
@@ -106,6 +106,8 @@ export const staff = pgTable("staff", {
oidcSub: text("oidc_sub").unique(),
role: staffRoleEnum("role").notNull().default("groomer"),
active: boolean("active").notNull().default(true),
// Token for iCal calendar feed subscription (no auth required)
icalToken: text("ical_token").unique(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
});