Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d51a116001 | |||
| e2dc230b7f |
@@ -146,7 +146,6 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
|||||||
| TC-API-3.19a | Get pet profile summary — customer owner-bypass (GRO-2013) | Sign in as `uat-customer@groombook.dev`; `POST /api/portal/session-from-auth`; then `GET /api/pets/{ownPetId}/profile-summary` with header `X-Impersonation-Session-Id: {sessionId}` for either of the customer's seeded pets (`c0000001-0000-0000-0000-000000000002` UAT Pup Alpha, `c0000001-0000-0000-0000-000000000003` UAT Pup Beta) | 200 OK, aggregated profile returned (owner-bypass: customer with valid portal session for pet's clientId is allowed even though rbac.ts auto-provisions them as a `groomer` staff row with no appointment linkage) |
|
| TC-API-3.19a | Get pet profile summary — customer owner-bypass (GRO-2013) | Sign in as `uat-customer@groombook.dev`; `POST /api/portal/session-from-auth`; then `GET /api/pets/{ownPetId}/profile-summary` with header `X-Impersonation-Session-Id: {sessionId}` for either of the customer's seeded pets (`c0000001-0000-0000-0000-000000000002` UAT Pup Alpha, `c0000001-0000-0000-0000-000000000003` UAT Pup Beta) | 200 OK, aggregated profile returned (owner-bypass: customer with valid portal session for pet's clientId is allowed even though rbac.ts auto-provisions them as a `groomer` staff row with no appointment linkage) |
|
||||||
| TC-API-3.19b | Get pet profile summary — customer cross-tenant blocked (GRO-2013) | Sign in as `uat-customer@groombook.dev`; reuse the customer's sessionId from TC-API-3.19a; `GET /api/pets/{otherClientPetId}/profile-summary` for a pet owned by a different client (`c0000002-...` or any non-customer pet) | 403 Forbidden (owner-bypass requires session.clientId === pet.clientId) |
|
| TC-API-3.19b | Get pet profile summary — customer cross-tenant blocked (GRO-2013) | Sign in as `uat-customer@groombook.dev`; reuse the customer's sessionId from TC-API-3.19a; `GET /api/pets/{otherClientPetId}/profile-summary` for a pet owned by a different client (`c0000002-...` or any non-customer pet) | 403 Forbidden (owner-bypass requires session.clientId === pet.clientId) |
|
||||||
| TC-API-3.19c | Get pet profile summary — customer without portal session header | Same as TC-API-3.19a but omit the `X-Impersonation-Session-Id` header | 403 Forbidden (no owner-bypass without valid portal session) |
|
| TC-API-3.19c | Get pet profile summary — customer without portal session header | Same as TC-API-3.19a but omit the `X-Impersonation-Session-Id` header | 403 Forbidden (no owner-bypass without valid portal session) |
|
||||||
| TC-API-3.19d | Get pet profile summary — owner-bypass writes audit row (GRO-2063) | Same setup as TC-API-3.19a (sign in as `uat-customer@groombook.dev`, establish a portal session for the customer's own clientId, call `GET /api/pets/{ownPetId}/profile-summary` with `X-Impersonation-Session-Id: {sessionId}` and a 200 OK response). Then call `GET /api/impersonation/sessions/{sessionId}/audit-log` and confirm there is exactly one entry with `action === "read_profile_summary"`, `pageVisited` matching the profile-summary path, and `metadata` containing `petId` and `actorStaffId` for the customer. Repeat TC-API-3.19b (cross-tenant attempt) and confirm NO new `read_profile_summary` row was written for the cross-tenant attempt. | 200 OK on the profile-summary call AND an audit log entry is present with the correct shape (defense-in-depth audit row; bypass attempts against other clients must NOT log) |
|
|
||||||
| TC-API-3.29 | Get pet profile summary — unknown UUID returns 404 (GRO-2014) | GET /api/pets/00000000-0000-0000-0000-000000000001/profile-summary while authenticated (any role) | 404 Not Found with body `{"error":"Not found"}` (was empty-body 500 in GRO-2014) |
|
| TC-API-3.29 | Get pet profile summary — unknown UUID returns 404 (GRO-2014) | GET /api/pets/00000000-0000-0000-0000-000000000001/profile-summary while authenticated (any role) | 404 Not Found with body `{"error":"Not found"}` (was empty-body 500 in GRO-2014) |
|
||||||
| TC-API-3.30 | Get pet profile summary — malformed UUID returns 404 (GRO-2014) | GET /api/pets/not-a-uuid/profile-summary while authenticated | 404 Not Found with body `{"error":"Not found"}` (was empty-body 500 in GRO-2014 — Postgres uuid cast failure) |
|
| TC-API-3.30 | Get pet profile summary — malformed UUID returns 404 (GRO-2014) | GET /api/pets/not-a-uuid/profile-summary while authenticated | 404 Not Found with body `{"error":"Not found"}` (was empty-body 500 in GRO-2014 — Postgres uuid cast failure) |
|
||||||
| TC-API-3.31 | Get pet profile summary — never empty-body 500 (GRO-2014) | GET /api/pets/{anyId}/profile-summary across the test sweep | No response has status 500 with an empty body. Any 500 must include a JSON body `{"error":"Internal Server Error"}` |
|
| TC-API-3.31 | Get pet profile summary — never empty-body 500 (GRO-2014) | GET /api/pets/{anyId}/profile-summary across the test sweep | No response has status 500 with an empty body. Any 500 must include a JSON body `{"error":"Internal Server Error"}` |
|
||||||
@@ -166,7 +165,6 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
|||||||
| TC-API-3.26 | Verify 25-35% medicalAlerts distribution | GET /api/pets (first 30 pets), count how many have non-empty medicalAlerts | Ratio is 25-35% (seed uses rand() < 0.3 for ~30% distribution) |
|
| TC-API-3.26 | Verify 25-35% medicalAlerts distribution | GET /api/pets (first 30 pets), count how many have non-empty medicalAlerts | Ratio is 25-35% (seed uses rand() < 0.3 for ~30% distribution) |
|
||||||
| TC-API-3.27 | Verify coat_type enum has all seed values | After UAT seed completes, inspect the coat_type enum on the UAT DB — it must contain: short, medium, long, double, wire, silky, curly, hairless | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; coat_type includes all 8 values used by seed.ts `coatTypePool` |
|
| TC-API-3.27 | Verify coat_type enum has all seed values | After UAT seed completes, inspect the coat_type enum on the UAT DB — it must contain: short, medium, long, double, wire, silky, curly, hairless | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; coat_type includes all 8 values used by seed.ts `coatTypePool` |
|
||||||
| TC-API-3.28 | Verify pet_size_category enum has all seed values | After UAT seed completes, inspect the pet_size_category enum on the UAT DB — it must contain: small, medium, large, extra_large | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; pet_size_category includes all 4 values used by seed.ts `petSizeCategoryPool` (regression for GRO-1999, mirrors TC-API-3.27) |
|
| TC-API-3.28 | Verify pet_size_category enum has all seed values | After UAT seed completes, inspect the pet_size_category enum on the UAT DB — it must contain: small, medium, large, extra_large | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; pet_size_category includes all 4 values used by seed.ts `petSizeCategoryPool` (regression for GRO-1999, mirrors TC-API-3.27) |
|
||||||
| TC-API-3.29 | Verify `reset-demo-data` CronJob does not fail with FK 23503 on `invoice_tip_splits` (GRO-2123) | Trigger the CronJob manually: `kubectl create job --from=cronjob/reset-demo-data verify-gro2123 -n groombook-uat`. Wait for pod to terminate. Inspect logs: `kubectl logs -n groombook-uat -l job-name=verify-gro2123` | Pod reaches `Completed` state; logs show `✓ Acquired seed advisory lock` and `✓ Released seed advisory lock` from `seed.ts`; no `PostgresError: … violates foreign key constraint "invoice_tip_splits_invoice_id_invoices_id_fk"` (code 23503); final counts unchanged (500 clients, ~4000 invoices) |
|
|
||||||
|
|
||||||
### 4.4 Appointment Scheduling
|
### 4.4 Appointment Scheduling
|
||||||
|
|
||||||
@@ -193,33 +191,6 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
|||||||
| TC-API-5.4 | Update service | PATCH /api/services/{id} with updated fields | 200 OK, service updated |
|
| TC-API-5.4 | Update service | PATCH /api/services/{id} with updated fields | 200 OK, service updated |
|
||||||
| TC-API-5.5 | Delete service | DELETE /api/services/{id} | 200 OK, service deleted |
|
| TC-API-5.5 | Delete service | DELETE /api/services/{id} | 200 OK, service deleted |
|
||||||
|
|
||||||
#### 4.5.1 Seed/Reset idempotency (GRO-2064)
|
|
||||||
|
|
||||||
Services seeding is now keyed on the deterministic `services.id` (not `name`) and
|
|
||||||
the reset path now `TRUNCATE`s `services` alongside the other dynamic tables.
|
|
||||||
This means:
|
|
||||||
|
|
||||||
- Running the seed Job twice in a row (no reset in between) converges to the
|
|
||||||
same catalogue — no `services_pkey` collision.
|
|
||||||
- A `pnpm reset` followed by `pnpm seed` (or a CronJob reset fire) leaves the
|
|
||||||
catalogue exactly matching `servicesDef` (10 rows, ids `b0000001-…-001` …
|
|
||||||
`…-00a`), regardless of any stale rows that were present beforehand.
|
|
||||||
- Mixed `seedKnownUsers` + full `seed()` invocations are safe — the
|
|
||||||
`demoSvcs` subset (Bath & Brush, Full Groom Small/Medium, Nail Trim) is
|
|
||||||
keyed on ids `…-001`, `…-002`, `…-003`, `…-005` and the upsert target
|
|
||||||
is `services.id`, so the same-id / different-name collision that broke
|
|
||||||
GRO-2033 (id `…-004` = "Nail Trim" vs servicesDef `…-004` =
|
|
||||||
"Full Groom — Large") cannot recur.
|
|
||||||
|
|
||||||
**UAT regression** (verify after a new image is rolled out):
|
|
||||||
|
|
||||||
| # | Scenario | Steps | Expected |
|
|
||||||
|---|----------|-------|----------|
|
|
||||||
| TC-SEED-1 | Reset → seed converges | `kubectl -n groombook exec deploy/api -- pnpm reset && pnpm seed` | Seed completes 1/1, `services` count = 10, all ids match `servicesDef` |
|
|
||||||
| TC-SEED-2 | Idempotent re-seed | Re-run `pnpm seed` without reset | Seed completes 1/1, no `services_pkey` errors, `services` count still 10 |
|
|
||||||
| TC-SEED-3 | Catalogue matches servicesDef | `psql -c "SELECT id, name FROM services ORDER BY id"` | Rows `…-001`…`…-00a` with names "Bath & Brush"…"Sanitary Trim" exactly as in `servicesDef` |
|
|
||||||
| TC-SEED-4 | Demo subset coexists | Run `seedKnownUsers` then full `seed` | No collision, demo subset (4 services) ends up with the same rows the full seed would write |
|
|
||||||
|
|
||||||
### 4.6 Staff Management
|
### 4.6 Staff Management
|
||||||
|
|
||||||
| # | Scenario | Steps | Expected |
|
| # | Scenario | Steps | Expected |
|
||||||
|
|||||||
@@ -12,8 +12,8 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "drizzle-kit migrate",
|
"db:migrate": "drizzle-kit migrate",
|
||||||
"db:seed": "pnpm --filter @groombook/db seed",
|
"db:seed": "tsx src/db/seed.ts",
|
||||||
"db:reset": "pnpm --filter @groombook/db reset",
|
"db:reset": "tsx src/db/reset.ts && drizzle-kit migrate && tsx src/db/seed.ts",
|
||||||
"db:studio": "drizzle-kit studio"
|
"db:studio": "drizzle-kit studio"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -20,7 +20,7 @@
|
|||||||
"generate": "drizzle-kit generate",
|
"generate": "drizzle-kit generate",
|
||||||
"migrate": "drizzle-kit migrate",
|
"migrate": "drizzle-kit migrate",
|
||||||
"seed": "tsx src/seed.ts",
|
"seed": "tsx src/seed.ts",
|
||||||
"reset": "tsx src/reset.ts",
|
"reset": "tsx src/reset.ts && drizzle-kit migrate && tsx src/seed.ts",
|
||||||
"studio": "drizzle-kit studio",
|
"studio": "drizzle-kit studio",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
|
|||||||
+38
-103
@@ -1,51 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* reset.ts — Drop all application tables, re-run migrations, and re-seed.
|
* reset.ts — Drop all application tables and re-run migrations + seed.
|
||||||
*
|
*
|
||||||
* Intended for local development only. Never run against production.
|
* Intended for local development only. Never run against production.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
||||||
*
|
|
||||||
* GRO-2139: the entire drop→migrate→seed chain runs inside a single
|
|
||||||
* Postgres advisory lock (SEED_ADVISORY_LOCK_KEY) so a concurrent
|
|
||||||
* `seed.ts` (e.g. the dev `seed-test-data-*` Job being recreated at
|
|
||||||
* the top of the hour) cannot interleave between `reset.ts` (DROP)
|
|
||||||
* and `seed.ts` (TRUNCATE+insert) and collide on `invoices_pkey`.
|
|
||||||
*
|
|
||||||
* Why this matters: `seed.ts` derives every primary key from a single
|
|
||||||
* shared Mulberry32 PRNG seeded with 42 (see `createPrng(42)` and
|
|
||||||
* `uuid()` in seed.ts). Two concurrent same-profile seeders therefore
|
|
||||||
* emit *identical* ids for the same logical row, and any moment
|
|
||||||
* between a concurrent `seed.ts` TRUNCATE and INSERT is exactly the
|
|
||||||
* window in which the second seeder's INSERT can hit a pkey already
|
|
||||||
* taken by the first. Pre-GRO-2123 this raced unconditionally;
|
|
||||||
* GRO-2123 added the advisory lock around `runSeedBody` but left
|
|
||||||
* `reset.ts` and `drizzle-kit migrate` outside the lock. This script
|
|
||||||
* now wraps the *whole* chain in the same lock, using `max: 1` so the
|
|
||||||
* single Postgres session that holds the lock is the one that runs
|
|
||||||
* the DROP, the migrations, and the seed body.
|
|
||||||
*
|
|
||||||
* See: groombook/infra `apps/base/reset-cronjob.yaml` (CronJob) and
|
|
||||||
* `apps/base/seed-job.yaml` (one-shot Job) — both invoke the same
|
|
||||||
* `seed.ts` code path on the same database in `groombook-dev`.
|
|
||||||
*/
|
*/
|
||||||
import postgres from "postgres";
|
|
||||||
import { drizzle } from "drizzle-orm/postgres-js";
|
|
||||||
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import { dirname, resolve } from "node:path";
|
|
||||||
import * as schema from "./schema.js";
|
|
||||||
import {
|
|
||||||
SEED_ADVISORY_LOCK_KEY,
|
|
||||||
withSeedAdvisoryLock,
|
|
||||||
getProfile,
|
|
||||||
runSeedBody,
|
|
||||||
profiles,
|
|
||||||
} from "./seed.js";
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
import postgres from "postgres";
|
||||||
const __dirname = dirname(__filename);
|
|
||||||
const MIGRATIONS_FOLDER = resolve(__dirname, "../migrations");
|
|
||||||
|
|
||||||
async function reset() {
|
async function reset() {
|
||||||
const url = process.env.DATABASE_URL;
|
const url = process.env.DATABASE_URL;
|
||||||
@@ -54,79 +16,52 @@ async function reset() {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (process.env.NODE_ENV === "production" && process.env.ALLOW_RESET !== "true") {
|
||||||
process.env.NODE_ENV === "production" &&
|
console.error("[FATAL] db:reset must not be run in production without ALLOW_RESET=true.");
|
||||||
process.env.ALLOW_RESET !== "true"
|
|
||||||
) {
|
|
||||||
console.error(
|
|
||||||
"[FATAL] db:reset must not be run in production without ALLOW_RESET=true.",
|
|
||||||
);
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// max: 1 so the advisory lock and every DROP / migrate / seed query
|
|
||||||
// share a single Postgres session. With max > 1 postgres-js could
|
|
||||||
// route a query to a different pooled connection that does NOT hold
|
|
||||||
// the lock, defeating the point of "lock spans the whole chain".
|
|
||||||
const client = postgres(url, { max: 1 });
|
const client = postgres(url, { max: 1 });
|
||||||
const db = drizzle(client, { schema });
|
|
||||||
|
|
||||||
try {
|
console.log("Dropping all application tables...\n");
|
||||||
await withSeedAdvisoryLock(client, async () => {
|
|
||||||
console.log("Dropping all application tables...\n");
|
|
||||||
|
|
||||||
// Drop dependencies (tables) first
|
// Drop in dependency order (children before parents)
|
||||||
await client`
|
await client`
|
||||||
DO $$ DECLARE
|
DO $$ DECLARE
|
||||||
r RECORD;
|
r RECORD;
|
||||||
BEGIN
|
BEGIN
|
||||||
FOR r IN (
|
FOR r IN (
|
||||||
SELECT tablename FROM pg_tables
|
SELECT tablename FROM pg_tables
|
||||||
WHERE schemaname = 'public'
|
WHERE schemaname = 'public'
|
||||||
) LOOP
|
) LOOP
|
||||||
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
||||||
END LOOP;
|
END LOOP;
|
||||||
END $$;
|
END $$;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Drop custom enums
|
// Drop custom enums
|
||||||
await client`
|
await client`
|
||||||
DO $$ DECLARE
|
DO $$ DECLARE
|
||||||
r RECORD;
|
r RECORD;
|
||||||
BEGIN
|
BEGIN
|
||||||
FOR r IN (
|
FOR r IN (
|
||||||
SELECT typname FROM pg_type
|
SELECT typname FROM pg_type
|
||||||
WHERE typtype = 'e' AND typnamespace = (
|
WHERE typtype = 'e' AND typnamespace = (
|
||||||
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
||||||
)
|
)
|
||||||
) LOOP
|
) LOOP
|
||||||
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
||||||
END LOOP;
|
END LOOP;
|
||||||
END $$;
|
END $$;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Drop the drizzle migrations tracking table
|
// Drop the drizzle migrations tracking table
|
||||||
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
||||||
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
||||||
|
|
||||||
console.log("✓ All tables and enums dropped\n");
|
console.log("✓ All tables and enums dropped\n");
|
||||||
|
|
||||||
console.log("Running migrations...");
|
await client.end();
|
||||||
await migrate(db, { migrationsFolder: MIGRATIONS_FOLDER });
|
|
||||||
console.log("✓ Migrations applied\n");
|
|
||||||
|
|
||||||
console.log("Seeding database...");
|
|
||||||
const profile = getProfile();
|
|
||||||
const cfg = profiles[profile];
|
|
||||||
await runSeedBody(client, db, profile, cfg);
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`\n✓ Reset complete (advisory lock key=0x${SEED_ADVISORY_LOCK_KEY.toString(16)})`,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
await client.end();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
reset().catch((err) => {
|
reset().catch((err) => {
|
||||||
|
|||||||
+20
-248
@@ -24,9 +24,9 @@ import type { MedicalAlert } from "@groombook/types";
|
|||||||
|
|
||||||
// ── Seed profile configuration ─────────────────────────────────────────────
|
// ── Seed profile configuration ─────────────────────────────────────────────
|
||||||
|
|
||||||
export type SeedProfile = "dev" | "uat" | "demo";
|
type SeedProfile = "dev" | "uat" | "demo";
|
||||||
|
|
||||||
export interface ProfileConfig {
|
interface ProfileConfig {
|
||||||
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
||||||
clientCount: number;
|
clientCount: number;
|
||||||
appointmentsBackDays: number;
|
appointmentsBackDays: number;
|
||||||
@@ -35,7 +35,7 @@ export interface ProfileConfig {
|
|||||||
includeUatClients: boolean;
|
includeUatClients: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const profiles: Record<SeedProfile, ProfileConfig> = {
|
const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||||
dev: {
|
dev: {
|
||||||
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
||||||
clientCount: 100,
|
clientCount: 100,
|
||||||
@@ -70,8 +70,6 @@ function getProfile(): SeedProfile {
|
|||||||
return "uat";
|
return "uat";
|
||||||
}
|
}
|
||||||
|
|
||||||
export { getProfile };
|
|
||||||
|
|
||||||
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -403,9 +401,7 @@ const servicesDef = [
|
|||||||
*
|
*
|
||||||
* In seedKnownUsers() this replaces the inline UAT-staff block.
|
* In seedKnownUsers() this replaces the inline UAT-staff block.
|
||||||
*/
|
*/
|
||||||
async function seedUatStaffAccounts(
|
async function seedUatStaffAccounts(db: ReturnType<typeof drizzle>) {
|
||||||
db: ReturnType<typeof drizzle>,
|
|
||||||
): Promise<string | null> {
|
|
||||||
// ── Staff: UAT Super User (oidcSub from SEED_UAT_SUPER_OIDC_SUB env var) ──
|
// ── Staff: UAT Super User (oidcSub from SEED_UAT_SUPER_OIDC_SUB env var) ──
|
||||||
const uatSuperOidcSub = process.env.SEED_UAT_SUPER_OIDC_SUB;
|
const uatSuperOidcSub = process.env.SEED_UAT_SUPER_OIDC_SUB;
|
||||||
if (uatSuperOidcSub) {
|
if (uatSuperOidcSub) {
|
||||||
@@ -672,132 +668,6 @@ async function seedUatStaffAccounts(
|
|||||||
console.log(`✓ Created UAT pet '${pet.name}' with extended fields`);
|
console.log(`✓ Created UAT pet '${pet.name}' with extended fields`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── GRO-2100: deterministic uat-groomer ↔ pet linkage ───────────────────────
|
|
||||||
// The UAT groomer (`uat-groomer@groombook.dev`, staffId 00000000-0000-0000-0000-000000000004)
|
|
||||||
// needs at least one linked pet/appointment or GRO-1987 TC-UAT-2/3 cannot run
|
|
||||||
// (the pet profile-summary endpoint returns 404 instead of 200/403).
|
|
||||||
//
|
|
||||||
// We deterministically link the UAT groomer to the UAT customer's first pet
|
|
||||||
// ("UAT Pup Alpha") and leave the second pet ("UAT Pup Beta") UNLINKED so
|
|
||||||
// TC-UAT-2 (200) and TC-UAT-3 (403) can both hardcode the stable petIds.
|
|
||||||
//
|
|
||||||
// The linkage call itself is performed by the caller AFTER the `services`
|
|
||||||
// catalogue has been seeded (this helper runs before services exist,
|
|
||||||
// which previously caused the linkage to be silently skipped on every
|
|
||||||
// reset). GRO-2100 follow-up.
|
|
||||||
return uatCustomerClientId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GRO-2100: create a deterministic completed appointment linking the UAT groomer
|
|
||||||
* to "UAT Pup Alpha" (c0000001-0000-0000-0000-000000000002). "UAT Pup Beta"
|
|
||||||
* (c0000001-0000-0000-0000-000000000003) is intentionally left UNLINKED so
|
|
||||||
* GRO-1987 TC-UAT-3 can verify the 403 forbidden response.
|
|
||||||
*
|
|
||||||
* Idempotent: the deterministic appointment id (`a0000001-…-0001`) is the
|
|
||||||
* upsert key, so re-running the seed on every reset-demo-data CronJob
|
|
||||||
* (hourly per apps/overlays/uat/reset-cronjob.yaml) is safe.
|
|
||||||
*/
|
|
||||||
async function seedUatGroomerLinkage(
|
|
||||||
db: ReturnType<typeof drizzle>,
|
|
||||||
customerClientId: string | null,
|
|
||||||
): Promise<void> {
|
|
||||||
const uatGroomerEmail = "uat-groomer@groombook.dev";
|
|
||||||
const LINKED_PET_ID = "c0000001-0000-0000-0000-000000000002"; // UAT Pup Alpha
|
|
||||||
const APPT_ID = "a0000001-0000-0000-0000-000000000001";
|
|
||||||
|
|
||||||
// Skip silently if the UAT Customer client wasn't created (non-UAT seed
|
|
||||||
// profile, e.g. seedKnownUsers() in an env without the UAT personas).
|
|
||||||
if (!customerClientId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only run if the UAT groomer staff record actually exists — dev/test seeds
|
|
||||||
// that don't set SEED_UAT_STAFF_OIDC_SUB should not crash.
|
|
||||||
const [uatGroomerStaff] = await db
|
|
||||||
.select({ id: schema.staff.id })
|
|
||||||
.from(schema.staff)
|
|
||||||
.where(eq(schema.staff.email, uatGroomerEmail))
|
|
||||||
.limit(1);
|
|
||||||
if (!uatGroomerStaff) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip if this exact appointment already exists (idempotent on re-seed).
|
|
||||||
const [existing] = await db
|
|
||||||
.select({ id: schema.appointments.id })
|
|
||||||
.from(schema.appointments)
|
|
||||||
.where(eq(schema.appointments.id, APPT_ID))
|
|
||||||
.limit(1);
|
|
||||||
if (existing) {
|
|
||||||
console.log(`✓ GRO-2100: uat-groomer linkage appointment already exists — skipping`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip if the linked pet hasn't been seeded yet (defensive: caller should
|
|
||||||
// ensure pets exist; if the helper is re-ordered later we don't want to
|
|
||||||
// crash here).
|
|
||||||
const [linkedPet] = await db
|
|
||||||
.select({ id: schema.pets.id })
|
|
||||||
.from(schema.pets)
|
|
||||||
.where(eq(schema.pets.id, LINKED_PET_ID))
|
|
||||||
.limit(1);
|
|
||||||
if (!linkedPet) {
|
|
||||||
console.warn(`⚠ GRO-2100: UAT Pup Alpha (${LINKED_PET_ID}) not found — skipping uat-groomer linkage`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The "Bath & Brush" service id is stable across the reset; falls back to
|
|
||||||
// any active service if it has not been seeded yet (e.g. seedKnownUsers
|
|
||||||
// runs in isolation).
|
|
||||||
const BATH_AND_BRUSH_ID = "b0000001-0000-0000-0000-000000000001";
|
|
||||||
const [bathService] = await db
|
|
||||||
.select({ id: schema.services.id })
|
|
||||||
.from(schema.services)
|
|
||||||
.where(eq(schema.services.id, BATH_AND_BRUSH_ID))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
let serviceId: string;
|
|
||||||
if (bathService) {
|
|
||||||
serviceId = bathService.id;
|
|
||||||
} else {
|
|
||||||
const [fallback] = await db
|
|
||||||
.select({ id: schema.services.id })
|
|
||||||
.from(schema.services)
|
|
||||||
.where(eq(schema.services.active, true))
|
|
||||||
.limit(1);
|
|
||||||
if (!fallback) {
|
|
||||||
console.warn(`⚠ GRO-2100: no active services found — skipping uat-groomer linkage`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
serviceId = fallback.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schedule the completed appointment 7 days ago so the profile-summary's
|
|
||||||
// "recentGroomingHistory" window (last 10) reliably includes it.
|
|
||||||
const startTime = new Date();
|
|
||||||
startTime.setDate(startTime.getDate() - 7);
|
|
||||||
startTime.setHours(10, 0, 0, 0);
|
|
||||||
const endTime = new Date(startTime.getTime() + 45 * 60 * 1000);
|
|
||||||
|
|
||||||
await db.insert(schema.appointments).values({
|
|
||||||
id: APPT_ID,
|
|
||||||
clientId: customerClientId,
|
|
||||||
petId: LINKED_PET_ID,
|
|
||||||
serviceId,
|
|
||||||
staffId: uatGroomerStaff.id,
|
|
||||||
batherStaffId: null,
|
|
||||||
status: "completed",
|
|
||||||
startTime,
|
|
||||||
endTime,
|
|
||||||
notes: "GRO-2100: deterministic uat-groomer linkage for TC-UAT-2/3.",
|
|
||||||
priceCents: null,
|
|
||||||
confirmationStatus: "confirmed",
|
|
||||||
});
|
|
||||||
console.log(
|
|
||||||
`✓ GRO-2100: linked uat-groomer (${uatGroomerStaff.id}) → UAT Pup Alpha (${LINKED_PET_ID}) via appointment ${APPT_ID}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Known-users-only seed (prod/demo) ───────────────────────────────────────
|
// ── Known-users-only seed (prod/demo) ───────────────────────────────────────
|
||||||
@@ -875,40 +745,27 @@ async function seedKnownUsers() {
|
|||||||
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
||||||
// Extracted into seedUatStaffAccounts() so it runs in both seedKnownUsers()
|
// Extracted into seedUatStaffAccounts() so it runs in both seedKnownUsers()
|
||||||
// and the full seed() UAT branch.
|
// and the full seed() UAT branch.
|
||||||
const uatCustomerClientId = await seedUatStaffAccounts(db);
|
await seedUatStaffAccounts(db);
|
||||||
|
|
||||||
// ── Services: idempotent upsert keyed on `id` ─────────────────────────────
|
// ── Services: idempotent upsert using name as unique key ─────────────────────
|
||||||
// GRO-2064: previously keyed on `services.name` while writing a
|
// UNIQUE constraint on services.name (migration 0020) must exist first.
|
||||||
// deterministic `id`. If a stale row existed with the same `id` but a
|
// Uses b0000001-... IDs to match main seed servicesDef for same-named services.
|
||||||
// different `name`, PostgreSQL raised `services_pkey` (id collision)
|
|
||||||
// before the name-targeted ON CONFLICT could fire. Switch the conflict
|
|
||||||
// target to `services.id` so deterministic ids always win; pair with
|
|
||||||
// `TRUNCATE services … CASCADE` above so each reset rebuilds the
|
|
||||||
// catalogue from `servicesDef` cleanly. GRO-2033 close-out.
|
|
||||||
// Id↔name map MUST stay in sync with `servicesDef` (the canonical source
|
|
||||||
// of truth in the main `seed()` function).
|
|
||||||
const demoSvcs = [
|
const demoSvcs = [
|
||||||
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
||||||
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
||||||
{ id: "b0000001-0000-0000-0000-000000000003", name: "Full Groom — Medium", description: "Complete grooming for dogs 25-50 lbs", basePriceCents: 8000, durationMinutes: 75 },
|
{ id: "b0000001-0000-0000-0000-000000000003", name: "Full Groom — Medium", description: "Complete grooming for dogs 25-50 lbs", basePriceCents: 8000, durationMinutes: 75 },
|
||||||
{ id: "b0000001-0000-0000-0000-000000000005", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||||
];
|
];
|
||||||
for (const svc of demoSvcs) {
|
for (const svc of demoSvcs) {
|
||||||
await db.insert(schema.services)
|
await db.insert(schema.services)
|
||||||
.values({ ...svc, active: true })
|
.values({ ...svc, active: true })
|
||||||
.onConflictDoUpdate({
|
.onConflictDoUpdate({
|
||||||
target: schema.services.id,
|
target: schema.services.name,
|
||||||
set: { name: svc.name, description: svc.description, basePriceCents: svc.basePriceCents, durationMinutes: svc.durationMinutes, active: true },
|
set: { description: svc.description, basePriceCents: svc.basePriceCents, durationMinutes: svc.durationMinutes, active: true },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
console.log(`✓ Seeded ${demoSvcs.length} services`);
|
console.log(`✓ Seeded ${demoSvcs.length} services`);
|
||||||
|
|
||||||
// GRO-2100: deterministic uat-groomer ↔ UAT Pup Alpha linkage. Must run
|
|
||||||
// AFTER services are seeded (this helper looks up an active service id
|
|
||||||
// to attach to the appointment; on a fresh reset there are none yet at
|
|
||||||
// the time seedUatStaffAccounts() returns).
|
|
||||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
|
||||||
|
|
||||||
// ── Client: Demo Client ──
|
// ── Client: Demo Client ──
|
||||||
const [existingClient] = await db
|
const [existingClient] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -978,63 +835,6 @@ async function seedKnownUsers() {
|
|||||||
|
|
||||||
// ── Main seed ────────────────────────────────────────────────────────────────
|
// ── Main seed ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
// ── GRO-2123: serialize reset+seed with a Postgres advisory lock ────────
|
|
||||||
// The reset-demo-data CronJob runs on an hourly schedule. With
|
|
||||||
// concurrencyPolicy=Replace, a new pod can start while the previous one
|
|
||||||
// is still mid-seed; the new pod's TRUNCATE then deletes rows the old pod
|
|
||||||
// is still inserting, producing FK 23503 errors non-deterministically
|
|
||||||
// (see GRO-2123: invoice_tip_splits → invoices).
|
|
||||||
//
|
|
||||||
// We hold a session-level advisory lock for the full duration of the
|
|
||||||
// seed so that overlapping invocations block then proceed in order —
|
|
||||||
// not skip. The key is a stable 32-bit constant so it can be referenced
|
|
||||||
// from runbooks without ambiguity and binds to the single-argument
|
|
||||||
// `pg_advisory_lock(int)` form, which postgres-js serializes as a plain
|
|
||||||
// number (no bigint type plumbing required).
|
|
||||||
export const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
|
||||||
* on it, run `fn`, and release the lock + connection in a try/finally.
|
|
||||||
*
|
|
||||||
* CRITICAL: with postgres-js connection pooling, a session-level
|
|
||||||
* `pg_advisory_lock(KEY)` acquired on one pooled connection and released
|
|
||||||
* on a *different* one is a no-op (the lock is bound to the session /
|
|
||||||
* pg-backend that took it). We therefore reserve a dedicated connection
|
|
||||||
* for the lock and release it from the same reserved connection. The
|
|
||||||
* seed work itself still runs on the pooled connections.
|
|
||||||
*/
|
|
||||||
export async function withSeedAdvisoryLock<T>(
|
|
||||||
pool: ReturnType<typeof postgres>,
|
|
||||||
fn: () => Promise<T>,
|
|
||||||
): Promise<T> {
|
|
||||||
const lockConnection = await pool.reserve();
|
|
||||||
let lockHeld = false;
|
|
||||||
try {
|
|
||||||
await lockConnection`SELECT pg_advisory_lock(${SEED_ADVISORY_LOCK_KEY})`;
|
|
||||||
lockHeld = true;
|
|
||||||
console.log(`✓ Acquired seed advisory lock (key=${SEED_ADVISORY_LOCK_KEY})`);
|
|
||||||
const result = await fn();
|
|
||||||
await lockConnection`SELECT pg_advisory_unlock(${SEED_ADVISORY_LOCK_KEY})`;
|
|
||||||
lockHeld = false;
|
|
||||||
console.log(`✓ Released seed advisory lock`);
|
|
||||||
return result;
|
|
||||||
} finally {
|
|
||||||
if (lockHeld) {
|
|
||||||
try {
|
|
||||||
await lockConnection`SELECT pg_advisory_unlock(${SEED_ADVISORY_LOCK_KEY})`;
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to release seed advisory lock during cleanup:", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
lockConnection.release();
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to release reserved lock connection:", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function seed() {
|
async function seed() {
|
||||||
const url = process.env.DATABASE_URL;
|
const url = process.env.DATABASE_URL;
|
||||||
if (!url) {
|
if (!url) {
|
||||||
@@ -1052,22 +852,6 @@ async function seed() {
|
|||||||
const client = postgres(url, { max: 5 });
|
const client = postgres(url, { max: 5 });
|
||||||
const db = drizzle(client, { schema });
|
const db = drizzle(client, { schema });
|
||||||
|
|
||||||
// GRO-2123: hold the seed advisory lock for the full body of runSeedBody.
|
|
||||||
// See the withSeedAdvisoryLock comment for why a reserved connection is
|
|
||||||
// required (postgres-js pooling would silently drop the lock otherwise).
|
|
||||||
await withSeedAdvisoryLock(client, async () => {
|
|
||||||
return await runSeedBody(client, db, profile, cfg);
|
|
||||||
});
|
|
||||||
|
|
||||||
await client.end();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function runSeedBody(
|
|
||||||
client: ReturnType<typeof postgres>,
|
|
||||||
db: ReturnType<typeof drizzle>,
|
|
||||||
profile: SeedProfile,
|
|
||||||
cfg: ProfileConfig,
|
|
||||||
): Promise<void> {
|
|
||||||
console.log(`Seeding Groom Book database (profile: ${profile})...\n`);
|
console.log(`Seeding Groom Book database (profile: ${profile})...\n`);
|
||||||
|
|
||||||
// ── Staff ──
|
// ── Staff ──
|
||||||
@@ -1084,13 +868,7 @@ export async function runSeedBody(
|
|||||||
({ id: uuid(), name: `Bather ${i + 1}`, email: `bather${i + 1}@groombook.dev`, role: "groomer" as const, isSuperUser: false })
|
({ id: uuid(), name: `Bather ${i + 1}`, email: `bather${i + 1}@groombook.dev`, role: "groomer" as const, isSuperUser: false })
|
||||||
);
|
);
|
||||||
|
|
||||||
// GRO-2064: also TRUNCATE `services` so each reset rebuilds the catalogue
|
await db.execute(sql`TRUNCATE impersonation_sessions, impersonation_audit_logs, appointments, invoices, invoice_line_items, invoice_tip_splits, grooming_visit_logs CASCADE`);
|
||||||
// from `servicesDef` (deterministic IDs + UNIQUE(name)). Stale service rows
|
|
||||||
// (e.g. a prior `seedKnownUsers` run that wrote a different `name` for the
|
|
||||||
// same `id`) would otherwise cause the deterministic upsert to PK-collide
|
|
||||||
// on `services.id` — see CTO review on infra PR #605 (rev #4230). TRUNCATE
|
|
||||||
// CASCADE handles appointments/invoices FKs to services.id.
|
|
||||||
await db.execute(sql`TRUNCATE services, impersonation_sessions, impersonation_audit_logs, appointments, invoices, invoice_line_items, invoice_tip_splits, grooming_visit_logs CASCADE`);
|
|
||||||
|
|
||||||
const allStaff = [...managerStaff, ...receptionistStaff, ...groomers, ...bathers];
|
const allStaff = [...managerStaff, ...receptionistStaff, ...groomers, ...bathers];
|
||||||
for (const s of allStaff) {
|
for (const s of allStaff) {
|
||||||
@@ -1138,14 +916,12 @@ export async function runSeedBody(
|
|||||||
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
||||||
// Seeds deterministic UAT staff with numeric OIDC subs and Better Auth credentials.
|
// Seeds deterministic UAT staff with numeric OIDC subs and Better Auth credentials.
|
||||||
// Must run AFTER random staff are created so upserts land correctly.
|
// Must run AFTER random staff are created so upserts land correctly.
|
||||||
const uatCustomerClientId = await seedUatStaffAccounts(db);
|
await seedUatStaffAccounts(db);
|
||||||
|
|
||||||
// ── Services ──
|
// ── Services ──
|
||||||
// GRO-2064: key the upsert on `services.id` (not `name`) so deterministic
|
// Upsert services using name as unique key. With deterministic IDs in
|
||||||
// ids always win, and rely on the TRUNCATE above to clear stale rows before
|
// servicesDef and TRUNCATE clearing downstream tables first, this is
|
||||||
// the catalogue is rebuilt. The previous name-targeted upsert failed with
|
// idempotent: first run inserts, subsequent runs update existing rows.
|
||||||
// `services_pkey` when a prior run had left a row with the same id but a
|
|
||||||
// different name (CTO review on infra PR #605, rev #4230).
|
|
||||||
const serviceIds: string[] = [];
|
const serviceIds: string[] = [];
|
||||||
for (const s of servicesDef) {
|
for (const s of servicesDef) {
|
||||||
serviceIds.push(s.id);
|
serviceIds.push(s.id);
|
||||||
@@ -1159,18 +935,12 @@ export async function runSeedBody(
|
|||||||
active: true,
|
active: true,
|
||||||
})
|
})
|
||||||
.onConflictDoUpdate({
|
.onConflictDoUpdate({
|
||||||
target: schema.services.id,
|
target: schema.services.name,
|
||||||
set: { name: s.name, description: s.desc, basePriceCents: s.price, durationMinutes: s.dur, active: true },
|
set: { description: s.desc, basePriceCents: s.price, durationMinutes: s.dur, active: true },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
console.log(`✓ Created ${servicesDef.length} services`);
|
console.log(`✓ Created ${servicesDef.length} services`);
|
||||||
|
|
||||||
// GRO-2100: deterministic uat-groomer ↔ UAT Pup Alpha linkage. Must run
|
|
||||||
// AFTER services are seeded (this helper looks up an active service id
|
|
||||||
// to attach to the appointment; on a fresh reset there are none yet at
|
|
||||||
// the time seedUatStaffAccounts() returns).
|
|
||||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
|
||||||
|
|
||||||
// ── Clients & Pets ──
|
// ── Clients & Pets ──
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const appointmentsBackDate = new Date(now);
|
const appointmentsBackDate = new Date(now);
|
||||||
@@ -1689,6 +1459,8 @@ export async function runSeedBody(
|
|||||||
}
|
}
|
||||||
console.log(`✓ Created ${visitLogCount} grooming visit logs`);
|
console.log(`✓ Created ${visitLogCount} grooming visit logs`);
|
||||||
console.log("\nSeed complete!");
|
console.log("\nSeed complete!");
|
||||||
|
|
||||||
|
await client.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
seed().catch((err) => {
|
seed().catch((err) => {
|
||||||
|
|||||||
@@ -182,11 +182,6 @@ let selectQueue: Array<{
|
|||||||
throw?: string;
|
throw?: string;
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
// Captured `db.insert(table).values(vals)` calls. Mirrors the pattern from
|
|
||||||
// src/__tests__/impersonation.test.ts so the GRO-2063 audit row assertions
|
|
||||||
// can inspect what the route tried to write without needing a real DB.
|
|
||||||
let insertCapture: Array<{ table: string; vals: Record<string, unknown> }> = [];
|
|
||||||
|
|
||||||
function enqueue(table: string, rows: unknown[] = []) {
|
function enqueue(table: string, rows: unknown[] = []) {
|
||||||
selectQueue.push({ table, rows });
|
selectQueue.push({ table, rows });
|
||||||
}
|
}
|
||||||
@@ -201,7 +196,6 @@ function resetMock() {
|
|||||||
servicesTable = [makeService()];
|
servicesTable = [makeService()];
|
||||||
sessionsTable = [makeSession()];
|
sessionsTable = [makeSession()];
|
||||||
selectQueue = [];
|
selectQueue = [];
|
||||||
insertCapture = [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Module mocks ───────────────────────────────────────────────────────────
|
// ─── Module mocks ───────────────────────────────────────────────────────────
|
||||||
@@ -275,12 +269,7 @@ vi.mock("@groombook/db", () => {
|
|||||||
select: (_cols?: Record<string, unknown>) => ({
|
select: (_cols?: Record<string, unknown>) => ({
|
||||||
from: (table: { _name?: string }) => wrapRows(takeQueuedRows(table._name ?? "")),
|
from: (table: { _name?: string }) => wrapRows(takeQueuedRows(table._name ?? "")),
|
||||||
}),
|
}),
|
||||||
insert: (table: { _name?: string }) => ({
|
insert: () => ({ values: () => ({ returning: () => [{}] }) }),
|
||||||
values: (vals: Record<string, unknown>) => {
|
|
||||||
insertCapture.push({ table: table._name ?? "unknown", vals });
|
|
||||||
return { returning: () => [{}] };
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
update: () => ({ set: () => ({ where: () => ({ returning: () => [{}] }) }) }),
|
update: () => ({ set: () => ({ where: () => ({ returning: () => [{}] }) }) }),
|
||||||
delete: () => ({ where: () => ({ returning: () => [{}] }) }),
|
delete: () => ({ where: () => ({ returning: () => [{}] }) }),
|
||||||
}),
|
}),
|
||||||
@@ -289,7 +278,6 @@ vi.mock("@groombook/db", () => {
|
|||||||
staff: makeTable("staff"),
|
staff: makeTable("staff"),
|
||||||
services: makeTable("services"),
|
services: makeTable("services"),
|
||||||
impersonationSessions: makeTable("impersonationSessions"),
|
impersonationSessions: makeTable("impersonationSessions"),
|
||||||
impersonationAuditLogs: makeTable("impersonation_audit_logs"),
|
|
||||||
and: vi.fn((..._args: unknown[]) => ({})),
|
and: vi.fn((..._args: unknown[]) => ({})),
|
||||||
desc: vi.fn((c: unknown) => c),
|
desc: vi.fn((c: unknown) => c),
|
||||||
eq: vi.fn((_a: unknown, _b: unknown) => ({})),
|
eq: vi.fn((_a: unknown, _b: unknown) => ({})),
|
||||||
@@ -579,69 +567,3 @@ describe("GET /:id/profile-summary — owner-bypass (GRO-2013)", () => {
|
|||||||
expect(res.status).toBe(403);
|
expect(res.status).toBe(403);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── GRO-2063 owner-bypass audit write ──────────────────────────────────────
|
|
||||||
|
|
||||||
describe("GET /:id/profile-summary — owner-bypass audit row (GRO-2063)", () => {
|
|
||||||
it("writes exactly one audit row on the owner-bypass success path", async () => {
|
|
||||||
enqueue("pets", petsTable);
|
|
||||||
enqueue("impersonationSessions", sessionsTable); // valid active session for CLIENT_ID
|
|
||||||
enqueue("appointments", appointmentsTable);
|
|
||||||
enqueue("appointments", [{ count: 1 }]);
|
|
||||||
enqueue("appointments", []);
|
|
||||||
|
|
||||||
const app = buildApp(CUSTOMER_STAFF);
|
|
||||||
const res = await app.request(`/pets/${PET_ID}/profile-summary`, {
|
|
||||||
headers: { "X-Impersonation-Session-Id": "sess-owner" },
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const auditInserts = insertCapture.filter((c) => c.table === "impersonation_audit_logs");
|
|
||||||
expect(auditInserts).toHaveLength(1);
|
|
||||||
const vals = auditInserts[0]!.vals;
|
|
||||||
expect(vals.action).toBe("read_profile_summary");
|
|
||||||
expect(vals.sessionId).toBe("sess-owner");
|
|
||||||
expect(vals.pageVisited).toBe(`/pets/${PET_ID}/profile-summary`);
|
|
||||||
expect(vals.metadata).toEqual({
|
|
||||||
petId: PET_ID,
|
|
||||||
actorStaffId: CUSTOMER_STAFF.id,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does NOT write an audit row on the normal groomer-linkage success path", async () => {
|
|
||||||
// GROOMER is a "real" groomer with appointment linkage, NOT the
|
|
||||||
// auto-provisioned customer-as-groomer. No impersonation header is
|
|
||||||
// present, so the owner-bypass branch never executes.
|
|
||||||
enqueue("pets", petsTable);
|
|
||||||
enqueue("appointments", [{ id: "appt-1" }]); // linkage found
|
|
||||||
enqueue("appointments", appointmentsTable);
|
|
||||||
enqueue("appointments", [{ count: 1 }]);
|
|
||||||
enqueue("appointments", []);
|
|
||||||
|
|
||||||
const app = buildApp(GROOMER);
|
|
||||||
const res = await app.request(`/pets/${PET_ID}/profile-summary`);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const auditInserts = insertCapture.filter((c) => c.table === "impersonation_audit_logs");
|
|
||||||
expect(auditInserts).toHaveLength(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does NOT write an audit row when the owner-bypass attempt is denied (cross-tenant)", async () => {
|
|
||||||
// Customer has a valid session but it points at a different client.
|
|
||||||
// isOwner=false, falls through to groomer linkage check, returns 403.
|
|
||||||
enqueue("pets", [
|
|
||||||
makePet({ id: OTHER_CLIENT_PET_ID, clientId: "c0000002-0000-0000-0000-000000000002" }),
|
|
||||||
]);
|
|
||||||
enqueue("impersonationSessions", sessionsTable); // session is for CLIENT_ID
|
|
||||||
enqueue("appointments", []); // no linkage → 403
|
|
||||||
|
|
||||||
const app = buildApp(CUSTOMER_STAFF);
|
|
||||||
const res = await app.request(`/pets/${OTHER_CLIENT_PET_ID}/profile-summary`, {
|
|
||||||
headers: { "X-Impersonation-Session-Id": "sess-owner" },
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
|
|
||||||
const auditInserts = insertCapture.filter((c) => c.table === "impersonation_audit_logs");
|
|
||||||
expect(auditInserts).toHaveLength(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
eq,
|
eq,
|
||||||
exists,
|
exists,
|
||||||
getDb,
|
getDb,
|
||||||
impersonationAuditLogs,
|
|
||||||
impersonationSessions,
|
impersonationSessions,
|
||||||
or,
|
or,
|
||||||
pets,
|
pets,
|
||||||
@@ -157,40 +156,6 @@ async function resolveImpersonationClientId(
|
|||||||
return session.clientId;
|
return session.clientId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Defense-in-depth audit write for the staff-side owner-bypass path in
|
|
||||||
* GET /pets/:id/profile-summary. Mirrors the failure-isolation pattern in
|
|
||||||
* src/middleware/portalAudit.ts: errors are logged but never thrown, so a
|
|
||||||
* misbehaving audit insert cannot turn a working read into a 500.
|
|
||||||
*
|
|
||||||
* Called only when the owner-bypass actually fires (i.e. the requester is a
|
|
||||||
* groomer-role staff row with no appointment linkage, but supplies a valid
|
|
||||||
* X-Impersonation-Session-Id whose clientId matches the pet's owner). The
|
|
||||||
* `petId` and `actorStaffId` are written inside `metadata` because the
|
|
||||||
* impersonation_audit_logs schema has no first-class columns for them and
|
|
||||||
* adding a migration is out of scope.
|
|
||||||
*/
|
|
||||||
async function writeOwnerBypassAudit(
|
|
||||||
db: ReturnType<typeof getDb>,
|
|
||||||
args: {
|
|
||||||
sessionId: string;
|
|
||||||
petId: string;
|
|
||||||
actorStaffId: string;
|
|
||||||
pageVisited: string;
|
|
||||||
}
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
await db.insert(impersonationAuditLogs).values({
|
|
||||||
sessionId: args.sessionId,
|
|
||||||
action: "read_profile_summary",
|
|
||||||
pageVisited: args.pageVisited,
|
|
||||||
metadata: { petId: args.petId, actorStaffId: args.actorStaffId },
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error("[pets] failed to write owner-bypass audit log:", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
petsRouter.get("/:id/profile-summary", async (c) => {
|
petsRouter.get("/:id/profile-summary", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const petId = c.req.param("id");
|
const petId = c.req.param("id");
|
||||||
@@ -223,22 +188,8 @@ petsRouter.get("/:id/profile-summary", async (c) => {
|
|||||||
// `groomer` staff row with no appointment linkage.
|
// `groomer` staff row with no appointment linkage.
|
||||||
let isOwner = false;
|
let isOwner = false;
|
||||||
if (isGroomer) {
|
if (isGroomer) {
|
||||||
const headerSessionId = c.req.header("X-Impersonation-Session-Id");
|
|
||||||
const ownerClientId = await resolveImpersonationClientId(db, c);
|
const ownerClientId = await resolveImpersonationClientId(db, c);
|
||||||
isOwner = !!ownerClientId && ownerClientId === pet.clientId;
|
isOwner = !!ownerClientId && ownerClientId === pet.clientId;
|
||||||
if (isOwner && headerSessionId) {
|
|
||||||
// GRO-2063: defense-in-depth audit row. Only fires when the bypass
|
|
||||||
// is actually granted; never on the normal groomer-linkage path,
|
|
||||||
// 403/404/401, or when the header is absent. Failure is swallowed
|
|
||||||
// (try/catch inside writeOwnerBypassAudit) so this can never turn a
|
|
||||||
// working read into a 500.
|
|
||||||
await writeOwnerBypassAudit(db, {
|
|
||||||
sessionId: headerSessionId,
|
|
||||||
petId: pet.id,
|
|
||||||
actorStaffId: staffRow.id,
|
|
||||||
pageVisited: c.req.path,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Groomer RBAC: check appointment linkage to this pet's client
|
// Groomer RBAC: check appointment linkage to this pet's client
|
||||||
|
|||||||
Reference in New Issue
Block a user