diff --git a/apps/backend/AGENTS.md b/apps/backend/AGENTS.md index 367974e7..2aa213f8 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -77,9 +77,9 @@ Automatic on push to `main` touching `apps/backend/lambdas/**` or `shared/types/ **`branch.users.is_admin` is the single source of truth for admin.** There is no promotion from a Cognito group, and no pre-token-generation trigger, so `is_admin` is not a JWT claim — `GET /auth/me` is the only way a client can learn it. -**Account provisioning is invitation-only.** A `branch.users` row with `cognito_sub IS NULL` is a pending invitation, created by `db/seed.sql` or by admin `POST /users` (ADMIN-gated). `POST /auth/register` is public, so it deliberately **cannot create a row** — it only claims an existing invitation, setting `cognito_sub` and never touching `is_admin`. An email with no pending invitation gets 403 `INVITATION_REQUIRED`; an already-claimed one gets 409. +**Account provisioning is invitation-only.** A `branch.users` row with `cognito_sub IS NULL` is a pending invitation, created by `db/seed.sql` or by admin `POST /users` (ADMIN-gated). `POST /auth/register` is public, so it deliberately **cannot create a row** — it only claims an existing invitation, setting `cognito_sub` and never touching `is_admin`. An email with no pending invitation, or one already claimed, gets 403 `INVITATION_REQUIRED`. -The 403 is intentionally identical whether or not the address exists, so registration cannot be used to enumerate staff emails. +The 403 is intentionally identical in both cases, so registration cannot be used to enumerate staff emails. This is the real control, not the Cognito pool config: `authenticateRequest` rejects any Cognito identity whose `sub` has no `branch.users` row, so a Cognito user created out of band is inert. Full flow: admin `POST /users` → invitee `POST /auth/register` with that email → `POST /auth/verify-email` with the emailed code → `POST /auth/login`. diff --git a/apps/backend/db/migrations/V20261015200000__index_project_donations_donor_id.sql b/apps/backend/db/migrations/V20261015200000__index_project_donations_donor_id.sql new file mode 100644 index 00000000..295a4d6c --- /dev/null +++ b/apps/backend/db/migrations/V20261015200000__index_project_donations_donor_id.sql @@ -0,0 +1,2 @@ +-- Replaces the donor_id-leading UNIQUE index dropped next; removeDonor filters on donor_id. +CREATE INDEX ${async} project_donations_donor_id_idx ON project_donations (donor_id); diff --git a/apps/backend/db/migrations/V20261015200100__allow_repeat_donations.sql b/apps/backend/db/migrations/V20261015200100__allow_repeat_donations.sql new file mode 100644 index 00000000..0c852255 --- /dev/null +++ b/apps/backend/db/migrations/V20261015200100__allow_repeat_donations.sql @@ -0,0 +1,2 @@ +-- A donor may give to the same project more than once. No IF EXISTS: a wrong name must fail the deploy, not no-op. +ALTER TABLE project_donations DROP CONSTRAINT project_donations_donor_id_project_id_key; diff --git a/apps/backend/lambdas/auth/controllers/register.ts b/apps/backend/lambdas/auth/controllers/register.ts index 1b6d76a5..c39818e6 100644 --- a/apps/backend/lambdas/auth/controllers/register.ts +++ b/apps/backend/lambdas/auth/controllers/register.ts @@ -54,10 +54,6 @@ export async function handleRegister(event: any): Promise .selectAll() .executeTakeFirst(); - if (existingUser && existingUser.cognito_sub) { - return json(409, { message: 'User with this email already exists' }); - } - // REGISTRATION IS INVITATION-ONLY. This endpoint is public and // unauthenticated, so without this gate anyone could create a working // account for themselves. An account is only meaningful once a branch.users @@ -69,8 +65,8 @@ export async function handleRegister(event: any): Promise // // 403 rather than 404: this endpoint must not become an oracle for which // email addresses have been invited, so the response is deliberately the - // same whether or not the address is known. - if (!existingUser) { + // same whether the address is unknown or already has an account. + if (!existingUser || existingUser.cognito_sub) { return json(403, { message: 'Registration is by invitation only. Ask an administrator to create your account.', diff --git a/apps/backend/lambdas/auth/test/auth.e2e.test.ts b/apps/backend/lambdas/auth/test/auth.e2e.test.ts index d5349dfb..08d1de61 100644 --- a/apps/backend/lambdas/auth/test/auth.e2e.test.ts +++ b/apps/backend/lambdas/auth/test/auth.e2e.test.ts @@ -37,9 +37,9 @@ afterAll(async () => { await pool.end(); }); -test("duplicate email returns 409", async () => { - // A CLAIMED row (cognito_sub set) is a genuine conflict. A row without one is - // a pending invitation and would be claimed instead -- see the test below. +test("an already-claimed email gets the same 403 as an uninvited one", async () => { + // A CLAIMED row (cognito_sub set) must not be distinguishable from no row, or + // registration becomes an oracle for which emails have accounts. const client = await pool.connect(); try { await client.query( @@ -60,9 +60,9 @@ test("duplicate email returns 409", async () => { }) }); - expect(res.status).toBe(409); + expect(res.status).toBe(403); const body = await res.json(); - expect(body.message).toContain("already exists"); + expect(body.code).toBe("INVITATION_REQUIRED"); }); test("email normalization uppercase matches lowercase in DB", async () => { @@ -87,9 +87,9 @@ test("email normalization uppercase matches lowercase in DB", async () => { }) }); - expect(res.status).toBe(409); + expect(res.status).toBe(403); const body = await res.json(); - expect(body.message).toContain("already exists"); + expect(body.code).toBe("INVITATION_REQUIRED"); }); test("uninvited email is refused before Cognito is ever called", async () => { diff --git a/apps/backend/lambdas/auth/test/auth.login.unit.test.ts b/apps/backend/lambdas/auth/test/auth.login.unit.test.ts index c1eb98c4..c032ef0b 100644 --- a/apps/backend/lambdas/auth/test/auth.login.unit.test.ts +++ b/apps/backend/lambdas/auth/test/auth.login.unit.test.ts @@ -559,16 +559,19 @@ describe('POST /register — claim-on-register', () => { expect(mockSet.mock.calls[0][0]).not.toHaveProperty('is_admin'); }); - it('returns 409 without calling Cognito when the row is already claimed', async () => { + it('answers an already-claimed email exactly like an unknown one, without calling Cognito', async () => { mockExecuteTakeFirst.mockResolvedValue({ user_id: 1, email: 'ashley@branch.org', cognito_sub: 'existing-sub', }); + const claimed = await handler(event('/register', 'POST', validBody)); - const res = await handler(event('/register', 'POST', validBody)); + mockExecuteTakeFirst.mockResolvedValue(undefined); + const unknown = await handler(event('/register', 'POST', validBody)); - expect(res.statusCode).toBe(409); + expect(claimed.statusCode).toBe(403); + expect(claimed.body).toBe(unknown.body); expect(mockSend).not.toHaveBeenCalled(); }); diff --git a/apps/backend/lambdas/donors/controllers/donations.ts b/apps/backend/lambdas/donors/controllers/donations.ts index 3e816a7f..5bacfc27 100644 --- a/apps/backend/lambdas/donors/controllers/donations.ts +++ b/apps/backend/lambdas/donors/controllers/donations.ts @@ -141,9 +141,6 @@ export async function createDonation({ event }: RouteCtx) { return json(201, { data: donation }); } catch (err: any) { - if (err?.code === '23505') { - return json(409, { message: 'A donation from this donor to this project already exists' }); - } if (err?.code === '23503') { return json(404, { message: 'Donor or project not found' }); } diff --git a/apps/backend/lambdas/donors/test/donors.test.ts b/apps/backend/lambdas/donors/test/donors.test.ts index e591b2d3..7717068e 100644 --- a/apps/backend/lambdas/donors/test/donors.test.ts +++ b/apps/backend/lambdas/donors/test/donors.test.ts @@ -368,6 +368,15 @@ describe("Donor API with data", () => { expect(Number(body.data.amount)).toBe(500); }); + test("POST /donations records a repeat gift from the same donor to the same project", async () => { + // Seed donor 1 has already given to project 1. + mockAuthenticateRequest.mockResolvedValueOnce(adminUser); + const res = await handler(createEvent('POST', '/donations', { + donor_id: 1, project_id: 1, amount: 250, + })); + expect(res.statusCode).toBe(201); + }); + test("POST /donations honours an explicit donated_at", async () => { mockAuthenticateRequest.mockResolvedValueOnce(adminUser); const res = await handler(createEvent('POST', '/donations', { diff --git a/apps/backend/lambdas/expenditures/controllers/expenditures.ts b/apps/backend/lambdas/expenditures/controllers/expenditures.ts index 78e33068..caac291e 100644 --- a/apps/backend/lambdas/expenditures/controllers/expenditures.ts +++ b/apps/backend/lambdas/expenditures/controllers/expenditures.ts @@ -2,6 +2,7 @@ import type { RouteHandler } from '@branch/lambda-http'; import { json, requirePermission, serverError } from '@branch/lambda-http'; import { can } from '@branch/rbac'; import type { ExpenseResource } from '@branch/rbac'; +import { ExpenditureStatusChangedError } from '@branch/store'; import { ExpenditureValidationUtils } from '../validation-utils'; import * as expendituresService from '../services/expenditures'; import { expenditureScope } from '../services/scope'; @@ -27,6 +28,11 @@ function resourceOf(expenditure: { }; } +// The row was reviewed between the permission check and the locked write. +function statusChanged(err: ExpenditureStatusChangedError) { + return json(409, { message: `This expense was just marked ${err.status}; reload and try again` }); +} + // GET /expenditures export const getExpenditures: RouteHandler = async ({ event, auth }) => { const queryParams = event.queryStringParameters || {}; @@ -105,6 +111,10 @@ export const createExpenditure: RouteHandler = async ({ event, auth }) => { const denied = requirePermission(auth.subject, 'expense:create', { projectId: projectID }); if (denied) return denied; + if (receiptUrl && !expendituresService.receiptKeyForProject(receiptUrl, projectID)) { + return json(400, { message: "receiptUrl must point at this project's receipts" }); + } + // A submitter cannot file an already-approved expense. The status field is // still accepted so an admin can record a decision at creation time. const effectiveStatus = can(auth.subject, 'expense:review') ? status : 'pending'; @@ -153,7 +163,11 @@ export const getUploadUrl: RouteHandler = async ({ event, auth }) => { if (!fileName || typeof fileName !== 'string') { return json(400, { message: 'fileName is required' }); } - if (fileName.split('.').pop()?.toLowerCase() !== 'pdf') { + const safeFileName = expendituresService.safeReceiptFileName(fileName); + if (!safeFileName) { + return json(400, { message: 'Invalid fileName' }); + } + if (safeFileName.split('.').pop()?.toLowerCase() !== 'pdf') { return json(400, { message: 'Only PDF receipts are supported' }); } if (!projectIdStr || !/^\d+$/.test(projectIdStr) || parseInt(projectIdStr, 10) < 1) { @@ -166,7 +180,7 @@ export const getUploadUrl: RouteHandler = async ({ event, auth }) => { const denied = requirePermission(auth.subject, 'expense:uploadReceipt', { projectId }); if (denied) return denied; - const { uploadUrl, objectUrl } = await expendituresService.presignUploadUrl(projectId, fileName); + const { uploadUrl, objectUrl } = await expendituresService.presignUploadUrl(projectId, safeFileName); return json(200, { uploadUrl, objectUrl }); }; @@ -188,7 +202,7 @@ export const getReceipt: RouteHandler = async ({ params, auth }) => { return json(404, { message: 'Expenditure has no receipt' }); } - const key = expendituresService.receiptKeyFromUrl(expenditure.receipt_url); + const key = expendituresService.receiptKeyForProject(expenditure.receipt_url, expenditure.project_id); if (!key) { return json(422, { message: 'Receipt is not stored in the receipts bucket' }); } @@ -265,16 +279,29 @@ export const updateExpenditure: RouteHandler = async ({ event, params, auth }) = if (update instanceof Error) { return json(400, { message: update.message }); } + if (update.receiptUrl && !expendituresService.receiptKeyForProject(update.receiptUrl, expenditure.project_id)) { + return json(400, { message: "receiptUrl must point at this project's receipts" }); + } // RETURNING hands back the row the re-read used to fetch. An empty patch // writes nothing, so the row already in hand is the current one. - const written = await expendituresService.updateExpenditure(Number(id), { - ...(update.amount !== undefined ? { amount: update.amount } : {}), - ...(update.category !== undefined ? { category: update.category } : {}), - ...(update.description !== undefined ? { description: update.description } : {}), - ...(update.receiptUrl !== undefined ? { receipt_url: update.receiptUrl } : {}), - ...(update.spentOn !== undefined ? { spent_on: new Date(update.spentOn) } : {}), - }); + let written; + try { + written = await expendituresService.updateExpenditure( + Number(id), + { + ...(update.amount !== undefined ? { amount: update.amount } : {}), + ...(update.category !== undefined ? { category: update.category } : {}), + ...(update.description !== undefined ? { description: update.description } : {}), + ...(update.receiptUrl !== undefined ? { receipt_url: update.receiptUrl } : {}), + ...(update.spentOn !== undefined ? { spent_on: new Date(update.spentOn) } : {}), + }, + expenditure.status, + ); + } catch (err) { + if (err instanceof ExpenditureStatusChangedError) return statusChanged(err); + throw err; + } const updated = written ?? expenditure; return json(200, { @@ -312,14 +339,23 @@ export const deleteExpenditure: RouteHandler = async ({ params, auth }) => { const denied = requirePermission(auth.subject, 'expense:delete', resourceOf(expenditure)); if (denied) return denied; - const numDeletedRows = await expendituresService.deleteExpenditureById(Number(id)); + let numDeletedRows: bigint; + try { + numDeletedRows = await expendituresService.deleteExpenditureById(Number(id), expenditure.status); + } catch (err) { + if (err instanceof ExpenditureStatusChangedError) return statusChanged(err); + throw err; + } if (numDeletedRows === 0n) { return json(404, { message: 'Expenditure not found' }); } // After the row, never before: if the object went first and the delete // below failed, the receipt would be gone with a row still pointing at it. - const receiptDeleted = await expendituresService.deleteReceiptObject(expenditure.receipt_url); + const receiptDeleted = await expendituresService.deleteReceiptObject( + expenditure.receipt_url, + expenditure.project_id, + ); return json(200, { ok: true, route: 'DELETE /expenditures/{id}', pathParams: { id }, receiptDeleted }); }; diff --git a/apps/backend/lambdas/expenditures/services/expenditures.ts b/apps/backend/lambdas/expenditures/services/expenditures.ts index 9de79f78..1a147f3d 100644 --- a/apps/backend/lambdas/expenditures/services/expenditures.ts +++ b/apps/backend/lambdas/expenditures/services/expenditures.ts @@ -18,7 +18,18 @@ export const RECEIPT_CONTENT_TYPE = 'application/pdf'; // Receipts live in the same bucket as reports, under their own prefix. export function receiptKeyFromUrl(objectUrl: string): string | null { const match = objectUrl.match(/^https:\/\/[^/]+\/(receipts\/.+)$/); - return match ? decodeURIComponent(match[1]) : null; + if (!match) return null; + try { + return decodeURIComponent(match[1]); + } catch { + return null; + } +} + +/** The key only if it sits under this project's prefix, so one project's row cannot name another's receipt. */ +export function receiptKeyForProject(objectUrl: string, projectId: number): string | null { + const key = receiptKeyFromUrl(objectUrl); + return key && key.startsWith(`receipts/${projectId}/`) && !key.includes('..') ? key : null; } /** @@ -29,9 +40,9 @@ export function receiptKeyFromUrl(objectUrl: string): string | null { * unreachable or the role is missing `s3:DeleteObject`. A leftover object is * recoverable; a row that cannot be deleted is not. */ -export async function deleteReceiptObject(receiptUrl: string | null): Promise { +export async function deleteReceiptObject(receiptUrl: string | null, projectId: number): Promise { if (!receiptUrl) return true; - const key = receiptKeyFromUrl(receiptUrl); + const key = receiptKeyForProject(receiptUrl, projectId); if (!key) return false; // Read at call time rather than using the module-level BUCKET: the value is // then observable to callers that set it after import, which is what the @@ -79,7 +90,9 @@ export async function queryExpenditures( ) { let query = db.selectFrom('branch.expenditures').selectAll(); if (projectId !== null) query = query.where('project_id', '=', projectId); - const scoped = applyExpenditureScope(query, scope).orderBy('spent_on', 'desc'); + const scoped = applyExpenditureScope(query, scope) + .orderBy('spent_on', 'desc') + .orderBy('expenditure_id', 'desc'); return page ? scoped.limit(page.limit).offset(page.offset).execute() : scoped.execute(); } @@ -123,8 +136,9 @@ export async function findExpenditureById(id: number) { return db.selectFrom('branch.expenditures').where('expenditure_id', '=', id).selectAll().executeTakeFirst(); } -export async function deleteExpenditureById(id: number): Promise { - return removeExpenditure(id); +/** `expectedStatus` is the status the caller was authorized against; a change under the lock throws. */ +export async function deleteExpenditureById(id: number, expectedStatus: string): Promise { + return removeExpenditure(id, expectedStatus); } /** @@ -143,9 +157,9 @@ export type ExpenditureEdit = Pick< * `undefined` when there was nothing to set (the caller already holds the row) * or when no row matched the id. */ -export async function updateExpenditure(id: number, values: ExpenditureEdit) { +export async function updateExpenditure(id: number, values: ExpenditureEdit, expectedStatus: string) { if (Object.keys(values).length === 0) return undefined; - return editExpenditure(id, values); + return editExpenditure(id, values, expectedStatus); } export async function getUserContact(userId: number) { @@ -168,6 +182,12 @@ export async function updateExpenditureStatus( ); } +/** Same rule as report uploads: basename only, URL-safe characters only. */ +export function safeReceiptFileName(fileName: string): string | null { + const safe = fileName.replace(/^.*[\\/]/, '').replace(/[^A-Za-z0-9._-]/g, '_'); + return /[A-Za-z0-9]/.test(safe) ? safe : null; +} + export async function presignUploadUrl(projectId: number, fileName: string): Promise<{ uploadUrl: string; objectUrl: string }> { const key = `receipts/${projectId}/${Date.now()}-${fileName}`; const uploadUrl = await getSignedUrl(s3, new PutObjectCommand({ diff --git a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts index 5f4f8fb4..60767b2f 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts @@ -313,14 +313,14 @@ describe('Expenditures integration tests', () => { projectID: 1, amount: 300, status: 'approved', - receipt_url: 'https://s3.amazonaws.com/branch-receipts/receipt.pdf', + receipt_url: 'https://branch-reports.s3.us-east-2.amazonaws.com/receipts/1/receipt.pdf', }) ); expect(res.statusCode).toBe(201); const body = JSON.parse(res.body); expect(body.body.status).toBe('approved'); - expect(body.body.receiptUrl).toBe('https://s3.amazonaws.com/branch-receipts/receipt.pdf'); + expect(body.body.receiptUrl).toBe('https://branch-reports.s3.us-east-2.amazonaws.com/receipts/1/receipt.pdf'); const client = await pool.connect(); try { @@ -329,7 +329,7 @@ describe('Expenditures integration tests', () => { ); expect(result.rows.length).toBe(1); expect(result.rows[0].status).toBe('approved'); - expect(result.rows[0].receipt_url).toBe('https://s3.amazonaws.com/branch-receipts/receipt.pdf'); + expect(result.rows[0].receipt_url).toBe('https://branch-reports.s3.us-east-2.amazonaws.com/receipts/1/receipt.pdf'); } finally { client.release(); } diff --git a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts index 39e55f78..d34b03ee 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts @@ -49,9 +49,16 @@ jest.mock('@aws-sdk/client-s3', () => ({ jest.mock('../mailer'); import { handler } from '../handler'; -import { db, recordExpenditure, editExpenditure, removeExpenditure } from '@branch/store'; +import { + db, + recordExpenditure, + editExpenditure, + removeExpenditure, + ExpenditureStatusChangedError, +} from '@branch/store'; import { authenticateRequest } from '../auth'; import { sendExpenseStatusEmail } from '../mailer'; +import { ExpenditureValidationUtils } from '../validation-utils'; const mockDb = db as any; const mockRecordExpenditure = recordExpenditure as jest.MockedFunction; @@ -517,14 +524,27 @@ describe('POST /expenditures unit tests', () => { projectID: 1, amount: 800, status: 'approved', - receipt_url: 'https://s3.amazonaws.com/branch-receipts/receipt.pdf', + receipt_url: 'https://branch-reports.s3.us-east-2.amazonaws.com/receipts/1/receipt.pdf', }) ); expect(res.statusCode).toBe(201); const json = JSON.parse(res.body); expect(json.body.status).toBe('approved'); - expect(json.body.receiptUrl).toBe('https://s3.amazonaws.com/branch-receipts/receipt.pdf'); + expect(json.body.receiptUrl).toBe('https://branch-reports.s3.us-east-2.amazonaws.com/receipts/1/receipt.pdf'); + }); + + test("400: rejects a receipt stored under another project's prefix", async () => { + const res = await handler( + postEvent({ + projectID: 1, + amount: 800, + receiptUrl: 'https://branch-reports.s3.us-east-2.amazonaws.com/receipts/2/other.pdf', + }) + ); + + expect(res.statusCode).toBe(400); + expect(mockRecordExpenditure).not.toHaveBeenCalled(); }); test('404: returns 404 when project not found', async () => { @@ -646,7 +666,9 @@ describe('POST /expenditures unit tests', () => { mockDb.selectFrom.mockReturnValue({ selectAll: jest.fn().mockReturnValue({ orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeExpenditures as any), + orderBy: jest.fn().mockReturnValue({ + execute: jest.fn().mockReturnValue(fakeExpenditures as any), + }), }), }), }); @@ -669,9 +691,11 @@ describe('POST /expenditures unit tests', () => { mockDb.selectFrom.mockReturnValueOnce({ selectAll: jest.fn().mockReturnValue({ orderBy: jest.fn().mockReturnValue({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([fakeExpenditures[0]] as any), + orderBy: jest.fn().mockReturnValue({ + limit: jest.fn().mockReturnValue({ + offset: jest.fn().mockReturnValue({ + execute: jest.fn().mockReturnValue([fakeExpenditures[0]] as any), + }), }), }), }), @@ -968,6 +992,36 @@ describe('DELETE /expenditures/{id} unit tests', () => { expect(mockS3Send).not.toHaveBeenCalled(); }); + test("never deletes a receipt stored under another project's prefix", async () => { + process.env.REPORTS_BUCKET_NAME = 'bucket'; + mockDb.selectFrom.mockReturnValueOnce( + mockSelectExpenditure({ + ...fakeExpenditure, + receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/2/theirs.pdf', + }), + ); + mockRemoveExpenditure.mockResolvedValue(1n); + + const res = await handler(idEvent('DELETE', '5')); + + expect(res.statusCode).toBe(200); + expect(JSON.parse(res.body).receiptDeleted).toBe(false); + expect(mockS3Send).not.toHaveBeenCalled(); + }); + + test('409 when the expense was reviewed between the check and the delete', async () => { + mockAuthenticateRequest.mockResolvedValue(studentAuthContext); + mockDb.selectFrom.mockReturnValue(mockSelectExpenditure({ ...fakeExpenditure, entered_by: 2 })); + mockRemoveExpenditure.mockRejectedValue( + Object.assign(new ExpenditureStatusChangedError('approved'), { status: 'approved' }), + ); + + const res = await handler(idEvent('DELETE', '5')); + + expect(res.statusCode).toBe(409); + expect(mockRemoveExpenditure).toHaveBeenCalledWith(5, 'pending'); + }); + describe('Success cases', () => { test('200: admin can delete without a membership lookup', async () => { mockDb.selectFrom.mockReturnValueOnce(mockSelectExpenditure(fakeExpenditure)); @@ -1376,4 +1430,15 @@ describe('GET /expenditures/{id}/receipt unit tests', () => { const res = await handler(receiptEvent(5)); expect(res.statusCode).toBe(401); }); -}); \ No newline at end of file +}); +describe('ExpenditureValidationUtils.validateExpenditureUpdate', () => { + test('an explicit null clears category, description and receipt', () => { + expect( + ExpenditureValidationUtils.validateExpenditureUpdate({ + category: null, + description: null, + receiptUrl: null, + }), + ).toEqual({ category: null, description: null, receiptUrl: null }); + }); +}); diff --git a/apps/backend/lambdas/expenditures/validation-utils.ts b/apps/backend/lambdas/expenditures/validation-utils.ts index 6496eaff..4e34a387 100644 --- a/apps/backend/lambdas/expenditures/validation-utils.ts +++ b/apps/backend/lambdas/expenditures/validation-utils.ts @@ -14,9 +14,9 @@ export interface ExpenditureInput { /** The subset of an expenditure its author may revise. */ export interface ExpenditureUpdate { amount?: number; - category?: string; - description?: string; - receiptUrl?: string; + category?: string | null; + description?: string | null; + receiptUrl?: string | null; spentOn?: string; } @@ -151,23 +151,24 @@ export class ExpenditureValidationUtils { update.amount = amount; } + // An explicit null clears the field. if (body.category !== undefined) { const category = this.validateCategory(body.category); if (category instanceof Error) return category; - update.category = category; + update.category = category ?? null; } if (body.description !== undefined) { const description = this.validateDescription(body.description); if (description instanceof Error) return description; - update.description = description; + update.description = description ?? null; } - const rawReceipt = body.receiptUrl ?? body.receipt_url; + const rawReceipt = body.receiptUrl !== undefined ? body.receiptUrl : body.receipt_url; if (rawReceipt !== undefined) { const receiptUrl = this.validateReceiptUrl(rawReceipt); if (receiptUrl instanceof Error) return receiptUrl; - update.receiptUrl = receiptUrl; + update.receiptUrl = receiptUrl ?? null; } if (body.spentOn !== undefined) { diff --git a/apps/backend/lambdas/projects/controllers/dashboard.ts b/apps/backend/lambdas/projects/controllers/dashboard.ts index 334e878d..758a9e7f 100644 --- a/apps/backend/lambdas/projects/controllers/dashboard.ts +++ b/apps/backend/lambdas/projects/controllers/dashboard.ts @@ -1,5 +1,6 @@ import { sql } from 'kysely'; import { json, RouteHandler, serverError } from '@branch/lambda-http'; +import { can } from '@branch/rbac'; import { db } from '@branch/store'; import { APPROVED_EXPENDITURE_STATUS } from '../validation-utils'; import { isProjectActive, listRoster, loadAdminHeadcount } from '../services/projects'; @@ -221,7 +222,10 @@ export const getOverview: RouteHandler = async (ctx) => { expenditureCount: approved.length, }, members, - expenditures, + // Reviewer notes are admin-only, as on GET /expenditures. + expenditures: can(ctx.auth.subject, 'expense:viewAdminNotes') + ? expenditures + : expenditures.map(({ admin_notes: _adminNotes, ...rest }) => rest), isActive: isProjectActive(project.end_date), }); }; diff --git a/apps/backend/lambdas/projects/test/project-page.unit.test.ts b/apps/backend/lambdas/projects/test/project-page.unit.test.ts index 9f380c31..10a68fbc 100644 --- a/apps/backend/lambdas/projects/test/project-page.unit.test.ts +++ b/apps/backend/lambdas/projects/test/project-page.unit.test.ts @@ -176,6 +176,21 @@ test('overview returns the project, stats, members and expenditures together', a expect(body.isActive).toBe(true); }); +test('overview hides admin notes from non-admin members', async () => { + await pool.query(`UPDATE branch.expenditures SET admin_notes = 'internal' WHERE project_id = 1`); + + const asAdmin = parse(await handler(event('/1/overview', 'GET'))); + expect(asAdmin.expenditures[0].admin_notes).toBe('internal'); + + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'sam-sub', userId: 4, email: 'sam@branch.org', isAdmin: false }, + }); + const asMember = parse(await handler(event('/1/overview', 'GET'))); + expect(asMember.expenditures.length).toBeGreaterThan(0); + for (const e of asMember.expenditures) expect(e).not.toHaveProperty('admin_notes'); +}); + test('overview reports 0% rather than NaN when no budget is set', async () => { const created = parse(await handler(event('/', 'POST', { name: 'No budget', members: [4] }))); const body = parse(await handler(event(`/${created.project_id}/overview`, 'GET'))); @@ -209,6 +224,28 @@ test('PUT replaces the roster rather than appending to it', async () => { expect(stored(body.members).map((m) => m.user_id)).toEqual([6]); }); +test('PUT keeps hours and start dates of members who stay on the roster', async () => { + const before = await pool.query( + `SELECT user_id, membership_id, hours, start_date FROM branch.project_memberships + WHERE project_id = 1 ORDER BY user_id`, + ); + + // Seeded project 1 has users 4 and 5; drop 5, add 6. + const res = await handler(event('/1', 'PUT', { members: [4, 6] })); + expect(res.statusCode).toBe(200); + + const after = await pool.query( + `SELECT user_id, membership_id, hours, start_date FROM branch.project_memberships + WHERE project_id = 1 ORDER BY user_id`, + ); + expect(after.rows.map((r) => r.user_id)).toEqual([4, 6]); + expect(after.rows[0]).toEqual(before.rows[0]); + const rollup = await pool.query( + `SELECT member_count FROM branch.project_rollup WHERE project_id = 1`, + ); + expect(rollup.rows[0].member_count).toBe(2); +}); + test('PUT without a members key leaves the roster alone', async () => { const created = parse( await handler(event('/', 'POST', { name: 'Untouched', total_budget: 5, members: [4, 5] })), diff --git a/apps/backend/lambdas/reports/controllers/reports.ts b/apps/backend/lambdas/reports/controllers/reports.ts index 4530b247..04882b84 100644 --- a/apps/backend/lambdas/reports/controllers/reports.ts +++ b/apps/backend/lambdas/reports/controllers/reports.ts @@ -165,7 +165,7 @@ export const listReports: RouteHandler = async ({ event }) => { ? db.selectFrom('branch.project_rollup').where('project_id', '=', projectId).select('report_count as count').executeTakeFirst() : db.selectFrom('branch.project_rollup').select(db.fn.sum('report_count').as('count')).executeTakeFirst(); - let pageQuery = db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc'); + let pageQuery = db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc'); if (projectId !== null) pageQuery = pageQuery.where('project_id', '=', projectId); const [totalCount, reports] = await Promise.all([ @@ -183,8 +183,8 @@ export const listReports: RouteHandler = async ({ event }) => { } const reports = projectId !== null - ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).selectAll().orderBy('date_created', 'desc').execute() - : await db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').execute(); + ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute() + : await db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute(); return json(200, { data: reports }); }; @@ -261,6 +261,15 @@ export const createReport: RouteHandler = async ({ event }) => { return json(400, { message: "objectUrl must point at this project's prefix in the reports bucket" }); } + // Two rows on one object would let deleting either break the other's download. + const alreadyRegistered = await db.selectFrom('branch.reports') + .where('object_url', '=', objectUrl) + .select('report_id') + .executeTakeFirst(); + if (alreadyRegistered) { + return json(409, { message: 'This file is already registered as a report', reportId: alreadyRegistered.report_id }); + } + const report = await recordReport({ project_id: projectId, title: (title as string).trim(), @@ -318,7 +327,12 @@ export const deleteReport: RouteHandler = async ({ params, path, method }) => { // After the row, never before: if the file went first and this delete // failed, the report would be gone with a row still pointing at it. - const fileDeleted = await deleteReportObject(report.object_url); + // Rows registered before the duplicate check may still share the object. + const stillReferenced = await db.selectFrom('branch.reports') + .where('object_url', '=', report.object_url) + .select('report_id') + .executeTakeFirst(); + const fileDeleted = stillReferenced ? false : await deleteReportObject(report.object_url); return json(200, { ok: true, route: 'DELETE /reports/{id}', pathParams: { id }, fileDeleted }); }; diff --git a/apps/backend/lambdas/reports/test/reports.unit.test.ts b/apps/backend/lambdas/reports/test/reports.unit.test.ts index 5d3545d8..a96fb20a 100644 --- a/apps/backend/lambdas/reports/test/reports.unit.test.ts +++ b/apps/backend/lambdas/reports/test/reports.unit.test.ts @@ -114,6 +114,13 @@ function postEvent(body: Record) { }; } +// Every list query orders by date then id; this lets one mock answer both calls. +function orderable(next: T): T { + const node: any = { ...next }; + node.orderBy = jest.fn().mockReturnValue(node); + return node; +} + describe('POST /reports unit tests', () => { beforeEach(() => { jest.clearAllMocks(); @@ -282,9 +289,9 @@ describe('GET /reports unit tests', () => { test('200: returns data array without pagination when no params', async () => { mockDb.selectFrom.mockReturnValue({ selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ + orderBy: jest.fn().mockReturnValue(orderable({ execute: jest.fn().mockReturnValue(fakeReports as any), - }), + })), }), }); @@ -321,13 +328,13 @@ describe('GET /reports unit tests', () => { }); mockDb.selectFrom.mockReturnValueOnce({ selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ + orderBy: jest.fn().mockReturnValue(orderable({ limit: jest.fn().mockReturnValue({ offset: jest.fn().mockReturnValue({ execute: jest.fn().mockReturnValue(rows as any), }), }), - }), + })), }), }); } @@ -364,13 +371,13 @@ describe('GET /reports unit tests', () => { // data query mockDb.selectFrom.mockReturnValueOnce({ selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ + orderBy: jest.fn().mockReturnValue(orderable({ limit: jest.fn().mockReturnValue({ offset: jest.fn().mockReturnValue({ execute: jest.fn().mockReturnValue([fakeReports[0]] as any), }), }), - }), + })), }), }); @@ -387,9 +394,9 @@ describe('GET /reports unit tests', () => { test('200: only page provided returns all without pagination', async () => { mockDb.selectFrom.mockReturnValue({ selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ + orderBy: jest.fn().mockReturnValue(orderable({ execute: jest.fn().mockReturnValue(fakeReports as any), - }), + })), }), }); @@ -402,9 +409,9 @@ describe('GET /reports unit tests', () => { test('200: only limit provided returns all without pagination', async () => { mockDb.selectFrom.mockReturnValue({ selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ + orderBy: jest.fn().mockReturnValue(orderable({ execute: jest.fn().mockReturnValue(fakeReports as any), - }), + })), }), }); @@ -469,7 +476,8 @@ describe('GET /reports/upload-url unit tests', () => { mockDb.selectFrom = jest.fn().mockReturnValue({ where: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(project as any), + // First the project lookup; POST /reports then checks for a duplicate objectUrl. + executeTakeFirst: jest.fn().mockReturnValueOnce(project as any).mockReturnValue(undefined), }), }), }); @@ -661,7 +669,8 @@ describe('POST /reports unit tests', () => { mockDb.selectFrom = jest.fn().mockReturnValue({ where: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(project as any), + // First the project lookup; POST /reports then checks for a duplicate objectUrl. + executeTakeFirst: jest.fn().mockReturnValueOnce(project as any).mockReturnValue(undefined), }), }), }); @@ -748,6 +757,19 @@ describe('POST /reports unit tests', () => { expect(JSON.parse(res.body).message).toBe('Only administrators can do this'); }); + test('409: an objectUrl already registered as a report is refused', async () => { + mockDb.selectFrom = jest.fn().mockReturnValue({ + where: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + executeTakeFirst: jest.fn().mockReturnValue({ project_id: 1, report_id: 7 } as any), + }), + }), + }); + const res = await handler(postEvent({ title: 'T', projectId: 1, objectUrl: fakeObjectUrl })); + expect(res.statusCode).toBe(409); + expect(mockRecordReport).not.toHaveBeenCalled(); + }); + test('404: nonexistent project returns 404', async () => { setupProjectMock(undefined); const res = await handler(postEvent({ title: 'T', projectId: 999, objectUrl: fakeObjectUrl })); @@ -992,12 +1014,19 @@ describe('DELETE /reports/{id} unit tests', () => { date_created: new Date('2025-01-01'), }; - function setupReportMock(report: Record | undefined) { + function setupReportMock( + report: Record | undefined, + sharedWith?: Record, + ) { mockDb.selectFrom = jest.fn().mockReturnValue({ where: jest.fn().mockReturnValue({ selectAll: jest.fn().mockReturnValue({ executeTakeFirst: jest.fn().mockReturnValue(report as any), }), + // Whether another row still points at the same object. + select: jest.fn().mockReturnValue({ + executeTakeFirst: jest.fn().mockReturnValue(sharedWith as any), + }), }), }); } @@ -1110,6 +1139,15 @@ describe('DELETE /reports/{id} unit tests', () => { ); }); + test('keeps the object while another report still points at it', async () => { + setupReportMock(storedReport, { report_id: 6 }); + const res = await handler(idEvent('DELETE', '5')); + + expect(res.statusCode).toBe(200); + expect(JSON.parse(res.body).fileDeleted).toBe(false); + expect(mockS3Send).not.toHaveBeenCalled(); + }); + test('a failing S3 delete still deletes the row', async () => { // An orphaned object is recoverable; a row that cannot be deleted is // not, so S3 trouble must not turn a successful delete into a 500. diff --git a/apps/frontend/src/app/components/AddExpenseModal.tsx b/apps/frontend/src/app/components/AddExpenseModal.tsx index d34d6e5e..49156abf 100644 --- a/apps/frontend/src/app/components/AddExpenseModal.tsx +++ b/apps/frontend/src/app/components/AddExpenseModal.tsx @@ -10,10 +10,18 @@ import { FiDollarSign } from 'react-icons/fi'; import { getReceiptUploadUrl, uploadReceiptToS3 } from '@/lib/expenditures'; import { Project } from '@/types'; -function formatAmountDisplay(digits: string): string { - if (!digits) return ''; - const trimmed = digits.replace(/^0+(?=\d)/, ''); - return trimmed.replace(/\B(?=(\d{3})+(?!\d))/g, ','); +/** Keeps digits and one decimal point, at most 9 whole digits and 2 decimals. */ +export function normalizeAmountInput(raw: string): string { + const [whole, ...rest] = raw.replace(/[^\d.]/g, '').split('.'); + const wholeDigits = whole.slice(0, 9); + return rest.length > 0 ? `${wholeDigits}.${rest.join('').slice(0, 2)}` : wholeDigits; +} + +function formatAmountDisplay(amount: string): string { + if (!amount) return ''; + const [whole, decimals] = amount.split('.'); + const grouped = (whole.replace(/^0+(?=\d)/, '') || '0').replace(/\B(?=(\d{3})+(?!\d))/g, ','); + return decimals === undefined ? grouped : `${grouped}.${decimals}`; } interface AddExpenseModalProps { open: boolean; @@ -100,6 +108,7 @@ export default function AddExpenseModal({ ); async function handleSubmit() { + if (submitting) return; const hasDateError = !newDate.trim(); const hasTypeError = !newType.trim(); const hasDescError = !newDescription.trim(); @@ -247,11 +256,10 @@ export default function AddExpenseModal({ { - const digitsOnly = e.target.value.replace(/\D/g, ''); - setAmountDigits(digitsOnly.slice(0, 9)); + setAmountDigits(normalizeAmountInput(e.target.value)); setAmountError(false); }} placeholder="Enter the Amount" @@ -302,6 +310,11 @@ export default function AddExpenseModal({ multiSelect={false} value={newProject} onChange={(val) => { + // The receipt was uploaded under the old project's prefix. + if (val !== newProject && receiptUrl) { + setNewFile(null); + setReceiptUrl(null); + } setNewProject(val as string); setProjectError(false); }} diff --git a/apps/frontend/src/app/components/ExpensesTable.tsx b/apps/frontend/src/app/components/ExpensesTable.tsx index 72a0a1c6..943ed003 100644 --- a/apps/frontend/src/app/components/ExpensesTable.tsx +++ b/apps/frontend/src/app/components/ExpensesTable.tsx @@ -6,6 +6,7 @@ import StatusBadge from './StatusBadge'; import RowDeleteButton from './RowDeleteButton'; import Tooltip from './Tooltip'; import { usePermissions } from '@/hooks/usePermissions'; +import { formatDateNumeric } from '@/lib/format'; interface ExpensesTableProps { expenditures: Expenditure[]; @@ -64,12 +65,7 @@ export default function ExpensesTable({ key: 'date', header: 'Date', width: widths.date, - cell: (e) => - new Date(e.spent_on).toLocaleDateString('en-US', { - month: '2-digit', - day: '2-digit', - year: 'numeric', - }), + cell: (e) => formatDateNumeric(e.spent_on), skeleton: { width: '75%' }, }, { diff --git a/apps/frontend/src/app/components/ReviewExpenseModal.tsx b/apps/frontend/src/app/components/ReviewExpenseModal.tsx index 9edf7a3e..886c3fb9 100644 --- a/apps/frontend/src/app/components/ReviewExpenseModal.tsx +++ b/apps/frontend/src/app/components/ReviewExpenseModal.tsx @@ -20,6 +20,7 @@ import { import DropdownSelector from './DropdownSelector'; import LoadingState from './LoadingState'; import StatusBadge from './StatusBadge'; +import { parseApiDate } from '@/lib/format'; const INPUT_STYLE: React.CSSProperties = { border: '1px solid var(--color-black-400)', @@ -100,8 +101,9 @@ function Field({ } function formatDate(value: string | null): string { - if (!value) return '---'; - return new Date(value).toLocaleDateString('en-US', { + const date = parseApiDate(value); + if (!date) return '---'; + return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', diff --git a/apps/frontend/src/app/donations/page.tsx b/apps/frontend/src/app/donations/page.tsx index f6cb41c2..144650a6 100644 --- a/apps/frontend/src/app/donations/page.tsx +++ b/apps/frontend/src/app/donations/page.tsx @@ -45,8 +45,11 @@ export default function DonationsPage() { // server-side aggregates it does not have yet. What changed is only that the // three reads are cached, so returning here is free, and that `/projects` is // the same cache entry the navbar and every other page reads. + // The donor roster is admin + director only; members still see the donations + // themselves, with donors shown by id. + const canViewDonors = can('donors:view'); const donationsList = useQuery(donationsQuery()); - const donorsList = useQuery(donorsQuery()); + const donorsList = useQuery({ ...donorsQuery(), enabled: canViewDonors }); const projectsList = useQuery(projectsQuery()); const donations = donationsList.data ?? NO_DONATIONS; @@ -54,10 +57,10 @@ export default function DonationsPage() { const projects = projectsList.data ?? NO_PROJECTS; const loading = - donationsList.isPending || donorsList.isPending || projectsList.isPending; + donationsList.isPending || (canViewDonors && donorsList.isPending) || projectsList.isPending; const loadError = - donationsList.error ?? donorsList.error ?? projectsList.error; + donationsList.error ?? (canViewDonors ? donorsList.error : null) ?? projectsList.error; const error = loadError ? loadError instanceof Error ? loadError.message diff --git a/apps/frontend/src/app/expenses/page.tsx b/apps/frontend/src/app/expenses/page.tsx index 067526c9..e5f8c1fb 100644 --- a/apps/frontend/src/app/expenses/page.tsx +++ b/apps/frontend/src/app/expenses/page.tsx @@ -28,7 +28,7 @@ import { IoClose } from 'react-icons/io5'; import ExpensesTable from '../components/ExpensesTable'; import ConfirmDeleteDialog from '../components/ConfirmDeleteDialog'; import { getReceiptDownloadUrl } from '@/lib/expenditures'; -import { formatCurrencyPrecise } from '@/lib/format'; +import { formatCurrencyPrecise, parseApiDate } from '@/lib/format'; import { EXPENDITURE_STATUSES, EXPENDITURE_STATUS_LABELS, @@ -200,8 +200,8 @@ function ExpensePageContent() { if (!matchesId && !matchesDesc && !matchesCat) return false; } if (selectedMonths.length > 0) { - const month = new Date(e.spent_on).getMonth(); - if (!selectedMonths.includes(MONTHS[month])) return false; + const month = parseApiDate(e.spent_on)?.getMonth(); + if (month === undefined || !selectedMonths.includes(MONTHS[month])) return false; } if (selectedTypes.length > 0) { if (!e.category || !selectedTypes.includes(e.category)) return false; diff --git a/apps/frontend/src/app/login/page.tsx b/apps/frontend/src/app/login/page.tsx index 79839207..1a2e2151 100644 --- a/apps/frontend/src/app/login/page.tsx +++ b/apps/frontend/src/app/login/page.tsx @@ -131,7 +131,17 @@ function LoginPageContent() { try { handleResult(await respondToChallenge({ ...challenge, newPassword })); } catch (err) { - reportError(err); + // Not reportError(): its passwordError only renders on the credentials step. + if (err instanceof ApiError && err.status === 401) { + setChallenge(null); + setStep('credentials'); + setFormError('Your sign-in session expired. Sign in again with your temporary password.'); + } else if (err instanceof ApiError) { + setFormError(err.message); + } else { + console.error('Set-password failed with a non-ApiError:', err); + setFormError('Cannot reach the server. Check your connection and try again.'); + } } finally { setIsLoading(false); } diff --git a/apps/frontend/src/app/reports/page.tsx b/apps/frontend/src/app/reports/page.tsx index 39a00a0e..59fd202d 100644 --- a/apps/frontend/src/app/reports/page.tsx +++ b/apps/frontend/src/app/reports/page.tsx @@ -20,6 +20,7 @@ import { useQuery, useQueryClient, keepPreviousData } from '@tanstack/react-quer import { projectsQuery, reportsPageQuery, reportsAllQuery } from '@/lib/queries'; import ExpenseFilterMenu, { type FilterGroup } from '../components/ExpenseFilterMenu'; import { type Project } from '@/lib/reports'; +import { parseApiDate } from '@/lib/format'; import UploadReportModal from '../components/UploadReportModal'; import ConfirmDeleteDialog from '../components/ConfirmDeleteDialog'; import { FaPlus } from 'react-icons/fa'; @@ -87,9 +88,8 @@ const REPORT_TYPE_OPTIONS: { value: 'technical' | 'narrative'; label: string }[] ]; function formatDate(dateString: string | null): string { - if (!dateString) return 'MM/DD/YYYY'; - const date = new Date(dateString); - if (Number.isNaN(date.getTime())) return 'MM/DD/YYYY'; + const date = parseApiDate(dateString); + if (!date) return 'MM/DD/YYYY'; const mm = String(date.getMonth() + 1).padStart(2, '0'); const dd = String(date.getDate()).padStart(2, '0'); const yyyy = date.getFullYear(); @@ -160,9 +160,8 @@ function ReportsPageContent() { const YEAR_OPTIONS = React.useMemo(() => { const years = new Set(); for (const r of reportsAll.data ?? []) { - if (r.date_created) { - years.add(new Date(r.date_created).getFullYear().toString()); - } + const created = parseApiDate(r.date_created); + if (created) years.add(created.getFullYear().toString()); } return Array.from(years).sort((a, b) => Number(b) - Number(a)); }, [reportsAll.data]); @@ -176,7 +175,7 @@ function ReportsPageContent() { return all.filter((r) => { if (q && !(r.title ?? '').toLowerCase().includes(q)) return false; if (selectedYears.length > 0) { - const year = r.date_created ? new Date(r.date_created).getFullYear().toString() : ''; + const year = parseApiDate(r.date_created)?.getFullYear().toString() ?? ''; if (!selectedYears.includes(year)) return false; } if (selectedTypes.length > 0) { @@ -233,10 +232,10 @@ function ReportsPageContent() { }, [searchTerm, selectedYears, selectedTypes]); useEffect(() => { - // Selection is scoped to the visible page, so it must not survive a page - // change — bulk delete would otherwise remove rows the user can't see. + // Selection is scoped to the visible rows, so it must not survive a page + // or filter change — bulk delete would otherwise remove rows the user can't see. setSelectedIds([]); - }, [currentPage]); + }, [currentPage, searchTerm, selectedYears, selectedTypes]); // Default the generate-report picker to the first project once the shared // projects query resolves. Was a side effect inside the old fetchProjects. diff --git a/apps/frontend/src/context/AuthContext.tsx b/apps/frontend/src/context/AuthContext.tsx index 29ed46ec..d24ae702 100644 --- a/apps/frontend/src/context/AuthContext.tsx +++ b/apps/frontend/src/context/AuthContext.tsx @@ -16,6 +16,7 @@ import { endSession, onSessionExpired, refreshSession, + refreshSessionOutcome, } from '@/lib/authClient'; import { clearTokens, @@ -137,6 +138,7 @@ interface AuthRawResponse { /** Refresh this many ms before the access token actually expires. */ const REFRESH_LEAD_MS = 120_000; const MIN_REFRESH_DELAY_MS = 5_000; +const TRANSIENT_RETRY_MS = 30_000; // --------------------------------------------------------------------------- // Context @@ -153,6 +155,10 @@ const MIN_REFRESH_DELAY_MS = 5_000; * can be newer than the API. Failing the bootstrap sends the user to /login, * which is at least honest about the session being unusable. */ +function isAuthFailure(error: unknown): boolean { + return error instanceof ApiError && (error.status === 401 || error.status === 403); +} + function isValidUser(candidate: unknown): candidate is AuthUser { if (typeof candidate !== 'object' || candidate === null) return false; const user = candidate as AuthUser; @@ -196,9 +202,18 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const fetchMe = useCallback(() => authedFetch('/auth/me'), []); - /** Writes the session straight into the cache, the one source of `user`. */ + /** + * Writes the session straight into the cache, the one source of `user`. A + * change of identity drops every other query, so the next user never sees + * the previous user's rows. + */ const setUser = useCallback( (next: AuthUser | null) => { + const previous = queryClient.getQueryData(AUTH_ME_KEY); + if (previous?.userId !== next?.userId || next === null) { + const meKey = JSON.stringify(AUTH_ME_KEY); + queryClient.removeQueries({ predicate: (q) => JSON.stringify(q.queryKey) !== meKey }); + } queryClient.setQueryData(AUTH_ME_KEY, next); }, [queryClient], @@ -220,14 +235,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // The session is re-read explicitly (`reloadUser`) and rewritten by every // path that changes it, so a background refetch could only add requests. staleTime: Infinity, - retry: false, + // Transient failures (network, 5xx) retry and keep the tokens, so a cold + // start or a dropped connection on reload does not sign the user out. + retry: (failureCount, error) => !isAuthFailure(error) && failureCount < 2, queryFn: async () => { try { const me = await fetchMe(); return isValidUser(me) ? me : null; - } catch { - // Resolving null rather than rejecting preserves the original contract: - // a failed bootstrap is a signed-out session, not an error to render. + } catch (error) { + if (!isAuthFailure(error)) throw error; + // A refused session resolves null: signed out, not an error to render. clearTokens(); return null; } @@ -272,11 +289,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { exp - Date.now() - REFRESH_LEAD_MS, MIN_REFRESH_DELAY_MS, ); - timer = setTimeout(async () => { - if (cancelled) return; - if (await refreshSession()) schedule(); - else endSession(); - }, delay); + timer = setTimeout(attempt, delay); + }; + + // A transient failure retries rather than signing the user out. + const attempt = async () => { + if (cancelled) return; + const outcome = await refreshSessionOutcome(); + if (outcome === 'ok') schedule(); + else if (outcome === 'rejected') endSession(); + else timer = setTimeout(attempt, TRANSIENT_RETRY_MS); }; schedule(); diff --git a/apps/frontend/src/lib/authClient.ts b/apps/frontend/src/lib/authClient.ts index afe374b6..3b589a2e 100644 --- a/apps/frontend/src/lib/authClient.ts +++ b/apps/frontend/src/lib/authClient.ts @@ -47,22 +47,31 @@ export function endSession(): void { } } -let refreshInFlight: Promise | null = null; +/** + * `rejected`: the server refused the refresh token, so the session is over. + * `unavailable`: network failure, 5xx or 429; the refresh token may still be good. + */ +export type RefreshOutcome = 'ok' | 'rejected' | 'unavailable'; + +let refreshInFlight: Promise | null = null; + +function isAuthRejection(error: unknown): boolean { + return error instanceof ApiError && [400, 401, 403].includes(error.status); +} /** * Exchanges the stored refresh token for a new access/ID token pair. * * Single-flight: concurrent callers share one in-flight request, so a burst of * simultaneous 401s produces exactly one POST /auth/refresh rather than one per - * request. Resolves false rather than throwing — callers treat that as "session - * is over". + * request. */ -export function refreshSession(): Promise { +export function refreshSessionOutcome(): Promise { if (refreshInFlight) return refreshInFlight; - const attempt = (async (): Promise => { + const attempt = (async (): Promise => { const refreshToken = getRefreshToken(); - if (!refreshToken) return false; + if (!refreshToken) return 'rejected'; try { // apiFetch, not authedFetch: this call carries no bearer token and must @@ -72,14 +81,14 @@ export function refreshSession(): Promise { body: JSON.stringify({ refreshToken }), }); - if (!data?.AccessToken || !data?.IdToken) return false; + if (!data?.AccessToken || !data?.IdToken) return 'rejected'; // No refreshToken here on purpose — Cognito does not return a new one, and // saveTokens leaves the stored value alone when it is absent. saveTokens({ accessToken: data.AccessToken, idToken: data.IdToken }); - return true; - } catch { - return false; + return 'ok'; + } catch (error) { + return isAuthRejection(error) ? 'rejected' : 'unavailable'; } })(); @@ -91,6 +100,22 @@ export function refreshSession(): Promise { return attempt; } +/** Resolves true only when new tokens were stored. */ +export async function refreshSession(): Promise { + return (await refreshSessionOutcome()) === 'ok'; +} + +/** Ends the session only when the server refused it; a transient failure keeps the tokens. */ +async function refreshOrThrow(): Promise { + const outcome = await refreshSessionOutcome(); + if (outcome === 'ok') return; + if (outcome === 'rejected') { + endSession(); + throw new ApiError('Session expired', 401); + } + throw new ApiError('Could not reach the server. Check your connection and try again.', 503); +} + export interface AuthedRequestOptions extends RequestInit { /** Set false to skip the refresh-and-retry dance (used when signing out). */ retryOn401?: boolean; @@ -106,17 +131,14 @@ export async function authedFetch( ): Promise { let token = getAccessToken(); - if (!token) { + if (!token && !getRefreshToken()) { endSession(); throw new ApiError('Not authenticated', 401); } // Pre-emptive refresh: skips a round trip that would certainly 401. - if (isExpiredOrExpiring(token)) { - if (!(await refreshSession())) { - endSession(); - throw new ApiError('Session expired', 401); - } + if (!token || isExpiredOrExpiring(token)) { + await refreshOrThrow(); token = getAccessToken(); } @@ -126,10 +148,7 @@ export async function authedFetch( const isUnauthorized = error instanceof ApiError && error.status === 401; if (!isUnauthorized || !retryOn401) throw error; - if (!(await refreshSession())) { - endSession(); - throw new ApiError('Session expired', 401); - } + await refreshOrThrow(); // Retry through apiFetch directly, so a second 401 propagates to the caller // instead of looping. diff --git a/apps/frontend/src/lib/queries.ts b/apps/frontend/src/lib/queries.ts index c271427f..92181e66 100644 --- a/apps/frontend/src/lib/queries.ts +++ b/apps/frontend/src/lib/queries.ts @@ -159,7 +159,9 @@ export const routeQueries: Record< reportsPageQuery(pageFrom(search)), projectsQuery(), ], - '/donations': () => [donationsQuery(), donorsQuery(), projectsQuery()], + // Not donorsQuery(): `/donors` is admin + director only, and the prefetcher + // cannot tell whether this caller may read it. + '/donations': () => [donationsQuery(), projectsQuery()], '/expenses': (search) => [ // Mirrors the page's own choice of query. A filtered deep link cannot be // served by a page request, so prefetch what the page will actually ask for. diff --git a/infrastructure/aws/api_gateway.tf b/infrastructure/aws/api_gateway.tf index 79fb92ce..4ec13dd7 100644 --- a/infrastructure/aws/api_gateway.tf +++ b/infrastructure/aws/api_gateway.tf @@ -50,7 +50,7 @@ locals { donors = ["GET", "POST"] expenditures = ["GET", "POST", "PATCH"] projects = ["GET", "POST"] - reports = ["GET"] + reports = ["GET", "POST"] users = ["GET", "POST", "DELETE", "PATCH"] } lambda_methods = { for svc, methods in local.base_methods : svc => concat(methods, ["OPTIONS"]) } diff --git a/infrastructure/preview/api_gateway.tf b/infrastructure/preview/api_gateway.tf index 3fc22f5a..50d67939 100644 --- a/infrastructure/preview/api_gateway.tf +++ b/infrastructure/preview/api_gateway.tf @@ -40,7 +40,7 @@ locals { donors = ["GET", "POST"] expenditures = ["GET", "POST"] projects = ["GET", "POST"] - reports = ["GET"] + reports = ["GET", "POST"] users = ["GET", "POST", "DELETE", "PATCH"] } lambda_methods = { for svc, methods in local.base_methods : svc => concat(methods, ["OPTIONS"]) } diff --git a/shared/store/src/expenditures.ts b/shared/store/src/expenditures.ts index 9853bb84..dfd7c047 100644 --- a/shared/store/src/expenditures.ts +++ b/shared/store/src/expenditures.ts @@ -17,9 +17,17 @@ export async function recordExpenditure(values: NewExpenditure): Promise { return tx(async (trx) => { const before = await trx @@ -29,6 +37,9 @@ export async function editExpenditure( .forUpdate() .executeTakeFirst() if (!before) return undefined + if (expectedStatus !== undefined && before.status !== expectedStatus) { + throw new ExpenditureStatusChangedError(before.status) + } const after = await trx .updateTable('branch.expenditures') @@ -43,7 +54,7 @@ export async function editExpenditure( }) } -export async function removeExpenditure(id: number): Promise { +export async function removeExpenditure(id: number, expectedStatus?: string): Promise { return tx(async (trx) => { const before = await trx .selectFrom('branch.expenditures') @@ -52,6 +63,9 @@ export async function removeExpenditure(id: number): Promise { .forUpdate() .executeTakeFirst() if (!before) return 0n + if (expectedStatus !== undefined && before.status !== expectedStatus) { + throw new ExpenditureStatusChangedError(before.status) + } const deleted = await trx .deleteFrom('branch.expenditures') diff --git a/shared/store/src/index.ts b/shared/store/src/index.ts index cdf8d430..bd538549 100644 --- a/shared/store/src/index.ts +++ b/shared/store/src/index.ts @@ -22,7 +22,12 @@ export function closeConnection(): Promise { return writeDb.destroy() } -export { recordExpenditure, editExpenditure, removeExpenditure } from './expenditures' +export { + recordExpenditure, + editExpenditure, + removeExpenditure, + ExpenditureStatusChangedError, +} from './expenditures' export { recordDonation, removeDonation, createDonor, removeDonor } from './donations' export { createProject, updateProject, removeProject } from './projects' export { recordReport, removeReport } from './reports' diff --git a/shared/store/src/projects.ts b/shared/store/src/projects.ts index 4e24d794..b35dc0da 100644 --- a/shared/store/src/projects.ts +++ b/shared/store/src/projects.ts @@ -18,27 +18,53 @@ async function syncMemberships( .select(['user_id', 'role']) .execute() const heldRole = new Map(existing.map((row) => [row.user_id, row.role])) + const wanted = new Map(members.map((m) => [m.user_id, m.role])) - const cleared = await trx - .deleteFrom('branch.project_memberships') - .where('project_id', '=', projectId) - .executeTakeFirst() + // Diffed rather than replaced, so kept members keep their hours and start_date. + const removed = existing.map((row) => row.user_id).filter((id) => !wanted.has(id)) + const cleared = + removed.length > 0 + ? await trx + .deleteFrom('branch.project_memberships') + .where('project_id', '=', projectId) + .where('user_id', 'in', removed) + .executeTakeFirst() + : undefined - if (members.length > 0) { + const roleChanges = new Map() + for (const [userId, role] of wanted) { + const held = heldRole.get(userId) + if (held === undefined || role == null || role === held) continue + roleChanges.set(role, [...(roleChanges.get(role) ?? []), userId]) + } + for (const [role, userIds] of roleChanges) { await trx - .insertInto('branch.project_memberships') - .values( - members.map((m) => ({ - project_id: projectId, - user_id: m.user_id, - role: m.role ?? heldRole.get(m.user_id) ?? defaultRole, - })), - ) + .updateTable('branch.project_memberships') + .set({ role }) + .where('project_id', '=', projectId) + .where('user_id', 'in', userIds) .execute() } - // Counted from the DELETE: a concurrent roster edit makes `existing` stale. - const delta = members.length - Number(cleared?.numDeletedRows ?? 0n) + const added = [...wanted].filter(([userId]) => !heldRole.has(userId)) + const inserted = + added.length > 0 + ? await trx + .insertInto('branch.project_memberships') + .values( + added.map(([userId, role]) => ({ + project_id: projectId, + user_id: userId, + role: role ?? defaultRole, + })), + ) + .onConflict((oc) => oc.columns(['project_id', 'user_id']).doNothing()) + .returning('membership_id') + .execute() + : [] + + // Counted from what the statements touched: a concurrent roster edit makes `existing` stale. + const delta = inserted.length - Number(cleared?.numDeletedRows ?? 0n) if (delta !== 0) await projectRollupBump(trx, projectId, { members: delta }) }