feat(capa): require note and photos via /submit, block PATCH bypass

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 11:10:03 +08:00
co-authored by Claude Sonnet 5.5
parent cf5719883c
commit 51986b7ae5
9 changed files with 275 additions and 2 deletions
+7 -2
View File
@@ -105,6 +105,13 @@ export async function PATCH(
const body = await request.json()
if (body.status === 'pending_verification') {
return NextResponse.json(
{ error: 'Use POST /api/capa/[id]/submit to submit for verification' },
{ status: 403 },
)
}
const privilegedStatuses = ['verified', 'reopened', 'closed']
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
@@ -122,14 +129,12 @@ export async function PATCH(
if ('department' in body && allowed.includes('department')) updateSet.department = body.department
if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref
if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes
if (body.status === 'pending_verification') updateSet.completedAt = new Date()
// Build audit new/old value from original snake_case body keys for consistency
const auditNew: Record<string, unknown> = {}
for (const key of allowed) {
if (key in body) auditNew[key] = body[key]
}
if (body.status === 'pending_verification') auditNew.completed_at = updateSet.completedAt?.toISOString()
await withUser(session.sub, async tx => {
let oldNotes: string | null = null
+88
View File
@@ -0,0 +1,88 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { eq } from 'drizzle-orm'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { capaActions, evidenceFiles } from '@/lib/db/schema'
import { uploadEvidenceFile } from '@/lib/storage/evidence'
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const [capa] = await withUser(session.sub, async tx =>
tx.select({
incidentId: capaActions.incidentId,
ownerUserId: capaActions.ownerUserId,
status: capaActions.status,
}).from(capaActions).where(eq(capaActions.id, id)).limit(1)
)
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isElevated = ['hse', 'admin'].includes(session.role)
if (capa.ownerUserId !== session.sub && !isElevated)
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
if (capa.status !== 'in_progress')
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
const form = await request.formData()
const files = form.getAll('files').filter((f): f is File => f instanceof File)
const check = validateCapaSubmission(String(form.get('note') ?? ''), files)
if (!check.ok)
return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 })
const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = []
try {
for (const file of files) {
const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub)
uploaded.push({ publicUrl, hash, type: file.type })
}
} catch (err) {
return NextResponse.json(
{ error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] },
{ status: 422 },
)
}
const completedAt = new Date()
await withUser(session.sub, async tx => {
const rows = await tx.insert(evidenceFiles).values(
uploaded.map(u => ({
incidentId: capa.incidentId,
capaId: id,
stage: 'capa' as const,
fileUrl: u.publicUrl,
fileType: u.type,
fileHash: u.hash,
uploadedBy: session.sub,
}))
).returning({ id: evidenceFiles.id })
await tx.update(capaActions).set({
status: 'pending_verification',
ownerNotes: check.note,
completedAt,
}).where(eq(capaActions.id, id))
await writeAuditLog(
tx, 'capa_actions', id, 'submitted_for_verification',
{
status: 'pending_verification',
owner_notes: check.note,
completed_at: completedAt.toISOString(),
evidence_file_ids: rows.map(r => r.id),
},
{ status: 'in_progress' },
)
})
return NextResponse.json({ ok: true })
}
+5
View File
@@ -0,0 +1,5 @@
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
BEGIN;
ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id);
COMMIT;
+3
View File
@@ -197,6 +197,9 @@ CREATE INDEX capa_actions_owner_idx ON capa_actions(owner_user_id);
CREATE INDEX capa_actions_status_idx ON capa_actions(status);
CREATE INDEX capa_actions_due_date_idx ON capa_actions(due_date);
ALTER TABLE evidence_files ADD COLUMN capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX evidence_files_capa_id_idx ON evidence_files(capa_id);
CREATE TABLE dosh_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
+18
View File
@@ -0,0 +1,18 @@
export const MAX_CAPA_PHOTOS = 5
export type CapaSubmissionResult =
| { ok: true; note: string }
| { ok: false; errors: string[] }
export function validateCapaSubmission(
note: string,
files: ReadonlyArray<{ type: string }>,
): CapaSubmissionResult {
const errors: string[] = []
const trimmed = note.trim()
if (!trimmed) errors.push('Completion note is required')
if (files.length < 1) errors.push('At least 1 photo is required')
if (files.length > MAX_CAPA_PHOTOS) errors.push(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
if (files.some(f => !f.type.startsWith('image/'))) errors.push('Only image files are allowed')
return errors.length ? { ok: false, errors } : { ok: true, note: trimmed }
}
+2
View File
@@ -10,6 +10,7 @@ import {
date,
jsonb,
customType,
type AnyPgColumn,
} from 'drizzle-orm/pg-core'
// ---------------------------------------------------------------------------
@@ -145,6 +146,7 @@ export const evidenceFiles = pgTable('evidence_files', {
uploadedBy: uuid('uploaded_by').notNull().references(() => users.id),
uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(),
deleted: boolean('deleted').notNull().default(false),
capaId: uuid('capa_id').references((): AnyPgColumn => capaActions.id),
})
export const investigations = pgTable('investigations', {
+35
View File
@@ -0,0 +1,35 @@
// @vitest-environment node
import { describe, it, expect, vi } from 'vitest'
vi.mock('@/lib/auth/get-session', () => ({
getSession: async () => ({ sub: 'owner-1', role: 'capa_owner' }),
}))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) =>
fn({
select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ ownerUserId: 'owner-1', status: 'in_progress' }] }) }) }),
update: () => ({ set: () => ({ where: async () => undefined }) }),
}),
}))
import { PATCH } from '@/app/api/capa/[id]/route'
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
const patch = (body: unknown) =>
new Request('http://localhost/api/capa/capa-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
describe('PATCH /api/capa/[id]', () => {
it('rejects pending_verification (must use /submit)', async () => {
const res = await PATCH(patch({ status: 'pending_verification' }) as never, ctx)
expect(res.status).toBe(403)
})
it('still allows in_progress', async () => {
const res = await PATCH(patch({ status: 'in_progress' }) as never, ctx)
expect(res.status).toBe(200)
})
})
+87
View File
@@ -0,0 +1,87 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
session: null as null | { sub: string; role: string },
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
updates: [] as unknown[],
inserts: [] as unknown[],
}))
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/storage/evidence', () => ({
uploadEvidenceFile: vi.fn(async () => ({ path: 'p', publicUrl: '/api/evidence/p?token=t', hash: 'h' })),
}))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) => {
const tx = {
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }),
update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: async () => undefined } } }),
}
return fn(tx)
},
}))
import { writeAuditLog } from '@/lib/db/audit'
import { POST } from '@/app/api/capa/[id]/submit/route'
function req(note: string | null, fileCount: number) {
const fd = new FormData()
if (note !== null) fd.append('note', note)
for (let i = 0; i < fileCount; i++) fd.append('files', new File(['x'], `p${i}.jpg`, { type: 'image/jpeg' }))
return new Request('http://localhost/api/capa/capa-1/submit', { method: 'POST', body: fd })
}
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
beforeEach(() => {
h.session = { sub: 'owner-1', role: 'capa_owner' }
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
h.updates = []
h.inserts = []
vi.mocked(writeAuditLog).mockClear()
})
describe('POST /api/capa/[id]/submit', () => {
it('401 without a session', async () => {
h.session = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(401)
})
it('404 when the CAPA does not exist', async () => {
h.capa = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(404)
})
it('403 for a user who is neither owner nor hse/admin', async () => {
h.session = { sub: 'other', role: 'reporter' }
expect((await POST(req('done', 1) as never, ctx)).status).toBe(403)
})
it('409 when status is not in_progress', async () => {
h.capa!.status = 'open'
expect((await POST(req('done', 1) as never, ctx)).status).toBe(409)
})
it('422 when no photo is attached', async () => {
const res = await POST(req('done', 0) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('At least 1 photo is required')
})
it('422 when the note is empty', async () => {
expect((await POST(req(' ', 1) as never, ctx)).status).toBe(422)
})
it('stores evidence, sets status and audits on success', async () => {
const res = await POST(req(' fixed the rack ', 2) as never, ctx)
expect(res.status).toBe(200)
expect(h.inserts[0]).toEqual([
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
])
expect(h.updates[0]).toEqual(
expect.objectContaining({ status: 'pending_verification', ownerNotes: 'fixed the rack', completedAt: expect.any(Date) }),
)
expect(writeAuditLog).toHaveBeenCalledWith(
expect.anything(), 'capa_actions', 'capa-1', 'submitted_for_verification',
expect.objectContaining({ status: 'pending_verification' }),
expect.objectContaining({ status: 'in_progress' }),
)
})
})
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { validateCapaSubmission, MAX_CAPA_PHOTOS } from '@/lib/capa/submit-validation'
const img = { type: 'image/jpeg' }
describe('validateCapaSubmission', () => {
it('accepts a note with 1 image and trims the note', () => {
expect(validateCapaSubmission(' done ', [img])).toEqual({ ok: true, note: 'done' })
})
it('rejects an empty or whitespace note', () => {
const r = validateCapaSubmission(' ', [img])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Completion note is required')
})
it('rejects zero files', () => {
const r = validateCapaSubmission('done', [])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('At least 1 photo is required')
})
it('rejects more than the max', () => {
const r = validateCapaSubmission('done', Array(MAX_CAPA_PHOTOS + 1).fill(img))
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
})
it('rejects non-image files', () => {
const r = validateCapaSubmission('done', [{ type: 'application/pdf' }])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Only image files are allowed')
})
})