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
4 changes: 2 additions & 2 deletions apps/backend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
Original file line number Diff line number Diff line change
@@ -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);
Original file line number Diff line number Diff line change
@@ -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;
8 changes: 2 additions & 6 deletions apps/backend/lambdas/auth/controllers/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,6 @@ export async function handleRegister(event: any): Promise<APIGatewayProxyResult>
.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
Expand All @@ -69,8 +65,8 @@ export async function handleRegister(event: any): Promise<APIGatewayProxyResult>
//
// 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.',
Expand Down
14 changes: 7 additions & 7 deletions apps/backend/lambdas/auth/test/auth.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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 () => {
Expand All @@ -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 () => {
Expand Down
9 changes: 6 additions & 3 deletions apps/backend/lambdas/auth/test/auth.login.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

Expand Down
3 changes: 0 additions & 3 deletions apps/backend/lambdas/donors/controllers/donations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
}
Expand Down
9 changes: 9 additions & 0 deletions apps/backend/lambdas/donors/test/donors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', {
Expand Down
60 changes: 48 additions & 12 deletions apps/backend/lambdas/expenditures/controllers/expenditures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 || {};
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand All @@ -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 });
};

Expand All @@ -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' });
}
Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -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 });
};
Expand Down
36 changes: 28 additions & 8 deletions apps/backend/lambdas/expenditures/services/expenditures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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<boolean> {
export async function deleteReceiptObject(receiptUrl: string | null, projectId: number): Promise<boolean> {
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
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -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<bigint> {
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<bigint> {
return removeExpenditure(id, expectedStatus);
}

/**
Expand All @@ -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) {
Expand All @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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();
}
Expand Down
Loading
Loading