Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions docs/AUTHORIZATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,18 +127,26 @@ out positively — its technician-availability update already pulls the
technician id from the DB-fetched job row, never the request, i.e. it
already implements this defense correctly.

**Separately flagged, not fixed here:** `POST /api/jobs` and
`PATCH /api/jobs/[id]` both insert `status_events` rows via the
session-scoped Supabase client (from `requireApiRole`), not the admin
client. `supabase/migrations/202506150001_sms_outbox_rls.sql`'s own comment
states writes to `status_events` happen "exclusively via the service role,"
but `status_events` has `force row level security` with only a `SELECT`
policy — if that comment's assumption holds against the table's actual
Postgres grants, these inserts would be silently rejected by RLS in
production (neither call site checks the insert's `error`). This wasn't
verifiable without live Supabase access and is a correctness question, not
a cross-tenant one, so it's flagged here rather than guessed at or silently
left undocumented.
**Resolved (issue #66):** `POST /api/jobs` and `PATCH /api/jobs/[id]` used
to insert `status_events` rows via the session-scoped Supabase client (from
`requireApiRole`), not the admin client. Confirmed directly against the
live Supabase project (`vfpodezcyufjnqkcpzcn`): `status_events` has exactly
one RLS policy, a `SELECT`-only policy for company members — no `INSERT`
policy exists, and `relforcerowsecurity` is `false` (so the finding wasn't
even about the `FORCE` setting; RLS applies to the `authenticated` role
regardless). The `authenticated` role does have a table-level `INSERT`
grant, which is exactly the shape that makes this failure silent rather
than a permission error: the insert simply matches zero rows for the
`with_check` clause and is dropped. Confirmed the real-world impact
directly: 654 non-demo `manual`/`call`-sourced jobs had **zero**
`status_events` rows, and the only `dispatcher`-attributed rows that did
exist all had `actor_id: null` — the exact signature of the demo-seed
script's service-role inserts (`scripts/seed-live-qa.mjs`), not of a real
API request (which always sets `actor_id: profile.id`). Fixed by routing
both call sites through `createSupabaseAdminClient()`, matching how
`intake`/`tech-action` already write `status_events`, and now checking
(and logging) the insert's `error` at both call sites instead of ignoring
it.

## `PATCH /api/jobs/[id]` — technician branch

Expand Down
3 changes: 3 additions & 0 deletions docs/LOAD_TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ LOAD_TECH_CONCURRENCY=25
LOAD_TECH_DURATION_SECONDS=30
LOAD_TECH_JOB_COUNT=75

LOAD_OFFICE_CONCURRENCY=8
LOAD_OFFICE_DURATION_SECONDS=30

LOAD_FLEET_COMPANY_COUNT=4
```

Expand Down
64 changes: 63 additions & 1 deletion src/app/api/jobs/[id]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type Row = Record<string, unknown>;
const requireApiRoleMock = vi.fn();
const queueTechnicianAssignmentSmsMock = vi.fn();
const queueCustomerStatusSmsMock = vi.fn();
const createSupabaseAdminClientMock = vi.fn();

vi.mock("@/lib/auth", () => ({
requireApiRole: requireApiRoleMock,
Expand All @@ -28,6 +29,10 @@ vi.mock("@/lib/jobNotifications", () => ({
queueCustomerStatusSms: queueCustomerStatusSmsMock,
}));

vi.mock("@/lib/supabase/admin", () => ({
createSupabaseAdminClient: () => createSupabaseAdminClientMock(),
}));

const COMPANY_ID = "11111111-1111-4111-8111-111111111111";
const OTHER_COMPANY_ID = "55555555-5555-4555-8555-555555555555";
const JOB_ID = "22222222-2222-4222-8222-222222222222";
Expand Down Expand Up @@ -131,6 +136,19 @@ function createFakeSupabase(db: Db) {
select: () => makeSelectBuilder(() => db.companies, (r) => ({ ...r })),
};
}
// status_events has no INSERT RLS policy for the authenticated role
// (issue #66) -- the route must write it through the admin client
// (see createFakeAdminSupabase below), never this session-scoped one.
// Deliberately no handler here, so a regression back to the session
// client throws instead of silently "working" in the test.
throw new Error(`Unexpected table in test double: ${table}`);
},
};
}

function createFakeAdminSupabase(db: Db) {
return {
from(table: string) {
if (table === "status_events") {
return {
insert: async (row: Row) => {
Expand All @@ -139,7 +157,7 @@ function createFakeSupabase(db: Db) {
},
};
}
throw new Error(`Unexpected table in test double: ${table}`);
throw new Error(`Unexpected table in admin test double: ${table}`);
},
};
}
Expand Down Expand Up @@ -214,6 +232,8 @@ describe("PATCH /api/jobs/[id] - dispatcher assignment", () => {
requireApiRoleMock.mockReset();
queueTechnicianAssignmentSmsMock.mockReset();
queueCustomerStatusSmsMock.mockReset();
createSupabaseAdminClientMock.mockReset();
createSupabaseAdminClientMock.mockImplementation(() => createFakeAdminSupabase(db));
requireApiRoleMock.mockResolvedValue({
profile: { id: DISPATCHER_ID, email: "dispatcher@example.com", company_id: COMPANY_ID, role: "dispatcher" },
response: null,
Expand Down Expand Up @@ -267,6 +287,32 @@ describe("PATCH /api/jobs/[id] - dispatcher assignment", () => {
expect(body.error).toBe("No changes provided");
});

it("records the status-change event through the admin client, not the session client (issue #66)", async () => {
const response = await patchJob({ technician_id: TECH_ID, status: "assigned", note: "Assigned from board" });

expect(response.status).toBe(200);
expect(db.statusEvents).toHaveLength(1);
expect(db.statusEvents[0]).toMatchObject({
job_id: JOB_ID,
from_status: "new",
to_status: "assigned",
actor_id: DISPATCHER_ID,
actor_role: "dispatcher",
note: "Assigned from board",
});
});

it("still persists the job update when the admin-client status event insert fails (non-fatal)", async () => {
createSupabaseAdminClientMock.mockImplementation(() => ({
from: () => ({ insert: async () => ({ error: { message: "status_events insert failed" } }) }),
}));

const response = await patchJob({ technician_id: TECH_ID, status: "assigned" });

expect(response.status).toBe(200);
expect(db.jobs[0].status).toBe("assigned");
});

describe("technician status updates (issue #49)", () => {
beforeEach(() => {
// The job is already assigned to TECH_ID before each technician-path test.
Expand All @@ -291,6 +337,22 @@ describe("PATCH /api/jobs/[id] - dispatcher assignment", () => {
expect(db.jobs[0].status).toBe("en_route");
});

it("records the technician's status-change event through the admin client too (issue #66)", async () => {
asTechnician(TECH_AUTH_USER_ID);

const response = await patchJob({ status: "en_route" });

expect(response.status).toBe(200);
expect(db.statusEvents).toHaveLength(1);
expect(db.statusEvents[0]).toMatchObject({
job_id: JOB_ID,
from_status: "assigned",
to_status: "en_route",
actor_id: TECH_AUTH_USER_ID,
actor_role: "technician",
});
});

it("denies a technician updating a job not assigned to them", async () => {
asTechnician(OTHER_TECH_AUTH_USER_ID);

Expand Down
29 changes: 20 additions & 9 deletions src/app/api/jobs/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireApiRole } from '@/lib/auth'
import { createSupabaseAdminClient } from '@/lib/supabase/admin'
import { assertValidTransition, type JobStatus } from '@/lib/stateMachine'
import { queueCustomerStatusSms, queueTechnicianAssignmentSms } from '@/lib/jobNotifications'
import type { SmsConsentType } from '@/lib/smsGate'
Expand Down Expand Up @@ -231,16 +232,26 @@ export async function PATCH(
: NextResponse.json({ error: 'Job not found' }, { status: 404 })
}

// Write status event if status changed
// Write status event if status changed. status_events has no INSERT RLS
// policy for the authenticated role (only SELECT) -- confirmed against
// the live project for issue #66, so this must go through the admin
// client like intake/tech-action already do, or the row is silently
// dropped.
if (patch.status) {
await supabase.from('status_events').insert({
job_id: id,
from_status: currentJob.status,
to_status: patch.status as string,
actor_id: profile.id,
actor_role: profile.role,
note: note ?? null,
})
const { error: statusEventError } = await createSupabaseAdminClient()
.from('status_events')
.insert({
job_id: id,
from_status: currentJob.status,
to_status: patch.status as string,
actor_id: profile.id,
actor_role: profile.role,
note: note ?? null,
})

if (statusEventError) {
console.error('Failed to record status-change status event:', statusEventError)
}
}

const finalStatus = (data.status ?? currentJob.status) as JobStatus
Expand Down
50 changes: 49 additions & 1 deletion src/app/api/jobs/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type Row = Record<string, unknown>;
const requireApiRoleMock = vi.fn();
const queueTechnicianAssignmentSmsMock = vi.fn();
const queueCustomerStatusSmsMock = vi.fn();
const createSupabaseAdminClientMock = vi.fn();

vi.mock("@/lib/auth", () => ({
requireApiRole: requireApiRoleMock,
Expand All @@ -22,6 +23,10 @@ vi.mock("@/lib/jobNotifications", () => ({
queueCustomerStatusSms: queueCustomerStatusSmsMock,
}));

vi.mock("@/lib/supabase/admin", () => ({
createSupabaseAdminClient: () => createSupabaseAdminClientMock(),
}));

function matchesFilters(row: Row, filters: [string, unknown, unknown?][]) {
return filters.every(([column, op, value]) => {
if (op === "eq") return row[column] === value;
Expand Down Expand Up @@ -146,6 +151,19 @@ function createFakeSupabase(db: Db, actingCompanyId: string) {
if (table === "companies") {
return { select: () => makeReadBuilder(() => db.companies) };
}
// status_events has no INSERT RLS policy for the authenticated role
// (issue #66) -- the route must write it through the admin client
// (see createFakeAdminSupabase below), never this session-scoped one.
// Deliberately no handler here, so a regression back to the session
// client throws instead of silently "working" in the test.
throw new Error(`Unexpected table in test double: ${table}`);
},
};
}

function createFakeAdminSupabase(db: Db) {
return {
from(table: string) {
if (table === "status_events") {
return {
insert: async (row: Row) => {
Expand All @@ -154,7 +172,7 @@ function createFakeSupabase(db: Db, actingCompanyId: string) {
},
};
}
throw new Error(`Unexpected table in test double: ${table}`);
throw new Error(`Unexpected table in admin test double: ${table}`);
},
};
}
Expand Down Expand Up @@ -223,6 +241,8 @@ describe("POST /api/jobs", () => {
requireApiRoleMock.mockReset();
queueTechnicianAssignmentSmsMock.mockReset();
queueCustomerStatusSmsMock.mockReset();
createSupabaseAdminClientMock.mockReset();
createSupabaseAdminClientMock.mockImplementation(() => createFakeAdminSupabase(db));
requireApiRoleAs(db, "dispatcher");
});

Expand All @@ -237,6 +257,34 @@ describe("POST /api/jobs", () => {
expect(queueCustomerStatusSmsMock).not.toHaveBeenCalled();
});

it("records the job-creation status event through the admin client, not the session client (issue #66)", async () => {
const response = await createJob(validJobInput);
const body = (await response.json()) as { job: Row };

expect(response.status).toBe(200);
expect(db.status_events).toHaveLength(1);
expect(db.status_events[0]).toMatchObject({
job_id: body.job.id,
from_status: null,
to_status: "new",
actor_id: DISPATCHER_ID,
actor_role: "dispatcher",
note: "Job created via manual",
});
});

it("still creates the job when the admin-client status event insert fails (non-fatal)", async () => {
createSupabaseAdminClientMock.mockImplementation(() => ({
from: () => ({ insert: async () => ({ error: { message: "status_events insert failed" } }) }),
}));

const response = await createJob(validJobInput);

expect(response.status).toBe(200);
const body = (await response.json()) as { job: Row };
expect(body.job.status).toBe("new");
});

it("creates a job with a technician (status assigned, availability updated, both SMS functions called)", async () => {
const response = await createJob({ ...validJobInput, technician_id: TECH_ID });

Expand Down
30 changes: 21 additions & 9 deletions src/app/api/jobs/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireApiRole } from '@/lib/auth'
import { createSupabaseAdminClient } from '@/lib/supabase/admin'
import { queueCustomerStatusSms, queueTechnicianAssignmentSms } from '@/lib/jobNotifications'
import type { SmsConsentType } from '@/lib/smsGate'

Expand Down Expand Up @@ -126,15 +127,26 @@ export async function POST(request: Request) {
.eq('id', technician_id)
}

// Write initial status event
await supabase.from('status_events').insert({
job_id: data.id,
from_status: null,
to_status: initialStatus,
actor_id: profile.id,
actor_role: profile.role,
note: technician_id ? `Job created and assigned via ${source}` : `Job created via ${source}`,
})
// status_events has no INSERT RLS policy for the authenticated role (only
// a SELECT policy exists -- confirmed against the live project for issue
// #66: session-scoped inserts here were being silently rejected, with
// zero status_events rows for any dispatcher/admin-created job). Route
// this through the admin client, the same way intake/tech-action already
// do for their own status_events writes.
const { error: statusEventError } = await createSupabaseAdminClient()
.from('status_events')
.insert({
job_id: data.id,
from_status: null,
to_status: initialStatus,
actor_id: profile.id,
actor_role: profile.role,
note: technician_id ? `Job created and assigned via ${source}` : `Job created via ${source}`,
})

if (statusEventError) {
console.error('Failed to record job-creation status event:', statusEventError)
}

if (technician_id) {
const [{ data: company }, { data: technician }] = await Promise.all([
Expand Down
Loading