From ffa0f46dbacb76593a389ee99f49f89dbd79af5e Mon Sep 17 00:00:00 2001 From: Dev Luharuwalla Date: Mon, 16 Nov 2026 20:12:01 -0500 Subject: [PATCH] pr --- .../internal-serving-lambda/openapi.yml | 239 ++++++++++++++++ .../src/__tests__/audit-log.test.ts | 185 +++++++++++++ .../src/__tests__/get-audit-log-entry.test.ts | 141 ++++++++++ .../src/__tests__/list-audit-log.test.ts | 259 ++++++++++++++++++ .../internal-serving-lambda/src/audit-log.ts | 63 +++++ .../internal-serving-lambda/src/routes.ts | 4 + .../src/routes/get-audit-log-entry.ts | 25 ++ .../src/routes/get-import.ts | 2 +- .../src/routes/list-audit-log.ts | 102 +++++++ .../src/routes/list-imports.ts | 6 +- 10 files changed, 1022 insertions(+), 4 deletions(-) create mode 100644 apps/backend/internal-serving-lambda/src/__tests__/audit-log.test.ts create mode 100644 apps/backend/internal-serving-lambda/src/__tests__/get-audit-log-entry.test.ts create mode 100644 apps/backend/internal-serving-lambda/src/__tests__/list-audit-log.test.ts create mode 100644 apps/backend/internal-serving-lambda/src/audit-log.ts create mode 100644 apps/backend/internal-serving-lambda/src/routes/get-audit-log-entry.ts create mode 100644 apps/backend/internal-serving-lambda/src/routes/list-audit-log.ts diff --git a/apps/backend/internal-serving-lambda/openapi.yml b/apps/backend/internal-serving-lambda/openapi.yml index 06334dae4..223e2b339 100644 --- a/apps/backend/internal-serving-lambda/openapi.yml +++ b/apps/backend/internal-serving-lambda/openapi.yml @@ -207,6 +207,170 @@ paths: '500': $ref: '#/components/responses/InternalServerError' + /audit-log: + get: + summary: List audit log entries + description: >- + Returns one page of changes to the data tables, newest `changedAt` + first. Filters combine with AND. + operationId: listAuditLog + tags: + - Audit log + security: + - bearerAuth: [] + parameters: + - name: changedFrom + in: query + description: >- + Only changes at or after this time. ISO 8601 in UTC, e.g. + `2026-10-01T00:00:00Z`. + schema: + type: string + format: date-time + - name: changedTo + in: query + description: >- + Only changes at or before this time. ISO 8601 in UTC. Must not be + before `changedFrom`. + schema: + type: string + format: date-time + - name: tableName + in: query + schema: + type: string + enum: + - daily_observations + - hourly_observations + - scheduled_observations + - daily_records + - name: importId + in: query + description: Only changes made by this import. + schema: + type: integer + minimum: 1 + maximum: 2147483647 + - name: rowKey + in: query + description: >- + Only changes to the row with this primary key, as URL-encoded JSON, + e.g. `{"stationId":1,"date":"2026-10-26"}`. Must match the stored + key exactly, including value types. Key order doesn't matter. + schema: + type: string + - name: limit + in: query + description: Page size. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 25 + - name: offset + in: query + description: Number of entries to skip. + schema: + type: integer + minimum: 0 + default: 0 + responses: + '200': + description: One page of audit log entries. + content: + application/json: + schema: + $ref: '#/components/schemas/AuditLogList' + example: + items: + - id: 2 + tableName: daily_observations + rowKey: + stationId: 1 + date: '2026-10-26' + action: update + oldData: + stationId: 1 + date: '2026-10-26' + maxTempF: 61 + newData: + stationId: 1 + date: '2026-10-26' + maxTempF: 62 + changedBy: 1 + importId: 7 + changedAt: '2026-10-26T12:00:00.000Z' + total: 1 + limit: 25 + offset: 0 + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '500': + $ref: '#/components/responses/InternalServerError' + + /audit-log/{id}: + get: + summary: Get an audit log entry + description: Returns one change, with the row before and after. + operationId: getAuditLogEntry + tags: + - Audit log + security: + - bearerAuth: [] + parameters: + - name: id + in: path + required: true + schema: + type: integer + minimum: 1 + maximum: 2147483647 + responses: + '200': + description: The audit log entry. + content: + application/json: + schema: + $ref: '#/components/schemas/AuditLogEntry' + example: + id: 2 + tableName: daily_observations + rowKey: + stationId: 1 + date: '2026-10-26' + action: update + oldData: + stationId: 1 + date: '2026-10-26' + maxTempF: 61 + newData: + stationId: 1 + date: '2026-10-26' + maxTempF: 62 + changedBy: 1 + importId: 7 + changedAt: '2026-10-26T12:00:00.000Z' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + description: No audit log entry has this id. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + example: + message: Audit log entry not found + '500': + $ref: '#/components/responses/InternalServerError' + components: securitySchemes: bearerAuth: @@ -326,6 +490,81 @@ components: type: integer offset: type: integer + AuditLogEntry: + type: object + description: >- + One inserted, updated, or deleted row in a data table, recorded by a + database trigger. See `docs/database-schema.md`. + required: + - id + - tableName + - rowKey + - action + - oldData + - newData + - changedBy + - importId + - changedAt + properties: + id: + type: integer + tableName: + type: string + enum: + - daily_observations + - hourly_observations + - scheduled_observations + - daily_records + rowKey: + type: object + description: Primary key of the changed row. + additionalProperties: true + action: + type: string + enum: + - insert + - update + - delete + oldData: + type: object + nullable: true + description: The whole row before the change. Null on insert. + additionalProperties: true + newData: + type: object + nullable: true + description: The whole row after the change. Null on delete. + additionalProperties: true + changedBy: + type: integer + nullable: true + description: Id of the user who made the change. Null for system writes. + importId: + type: integer + nullable: true + description: Id of the import that made the change, if any. + changedAt: + type: string + format: date-time + AuditLogList: + type: object + required: + - items + - total + - limit + - offset + properties: + items: + type: array + items: + $ref: '#/components/schemas/AuditLogEntry' + total: + type: integer + description: Number of entries matching the filters, across all pages. + limit: + type: integer + offset: + type: integer HealthResponse: type: object required: diff --git a/apps/backend/internal-serving-lambda/src/__tests__/audit-log.test.ts b/apps/backend/internal-serving-lambda/src/__tests__/audit-log.test.ts new file mode 100644 index 000000000..97ba65dc5 --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/__tests__/audit-log.test.ts @@ -0,0 +1,185 @@ +import { + Kysely, + PostgresAdapter, + PostgresIntrospector, + PostgresQueryCompiler, + type CompiledQuery, + type DatabaseConnection, + type Driver, +} from 'kysely'; +import type { Database } from '@bho/db-client'; +import { getAuditLogEntry, listAuditLog } from '../audit-log'; + +const ROWS = [ + { id: 2, tableName: 'daily_observations', action: 'update' }, + { id: 1, tableName: 'daily_records', action: 'insert' }, +]; + +// Records each query instead of running it. The count query gets a total; +// every other query gets `rows`. +const buildDb = (rows: unknown[] = ROWS) => { + const queries: CompiledQuery[] = []; + const connection: DatabaseConnection = { + executeQuery: async (query: CompiledQuery) => { + queries.push(query); + const result = query.sql.includes('count(*)') ? [{ total: '42' }] : rows; + return { rows: result as R[] }; + }, + streamQuery: () => { + throw new Error('not implemented'); + }, + }; + const driver: Driver = { + init: async () => undefined, + acquireConnection: async () => connection, + beginTransaction: async () => undefined, + commitTransaction: async () => undefined, + rollbackTransaction: async () => undefined, + releaseConnection: async () => undefined, + destroy: async () => undefined, + }; + const db = new Kysely({ + dialect: { + createAdapter: () => new PostgresAdapter(), + createDriver: () => driver, + createIntrospector: (db) => new PostgresIntrospector(db), + createQueryCompiler: () => new PostgresQueryCompiler(), + }, + }); + const [select, count] = [ + () => queries.find((q) => !q.sql.includes('count(*)')), + () => queries.find((q) => q.sql.includes('count(*)')), + ]; + return { db, select, count }; +}; + +const PAGE = { limit: 25, offset: 0 }; + +describe('listAuditLog', () => { + it('returns the rows and the total as a number', async () => { + const { db } = buildDb(); + + expect(await listAuditLog(db, {}, PAGE)).toEqual({ + items: ROWS, + total: 42, + }); + }); + + it('selects every column', async () => { + const { db, select } = buildDb(); + + await listAuditLog(db, {}, PAGE); + + expect(select()?.sql).toMatch(/^select \* from "audit_log"/); + }); + + it('orders newest changedAt first, then by id', async () => { + const { db, select } = buildDb(); + + await listAuditLog(db, {}, PAGE); + + expect(select()?.sql).toContain('order by "changedAt" desc, "id" desc'); + }); + + it('applies the limit and offset to the page but not the count', async () => { + const { db, select, count } = buildDb(); + + await listAuditLog(db, {}, { limit: 10, offset: 20 }); + + expect(select()?.sql).toMatch(/limit \$1 offset \$2$/); + expect(select()?.parameters).toEqual([10, 20]); + expect(count()?.sql).not.toMatch(/limit|offset/); + }); + + it('has no where clause without filters', async () => { + const { db, select, count } = buildDb(); + + await listAuditLog(db, {}, PAGE); + + expect(select()?.sql).not.toContain('where'); + expect(count()?.sql).not.toContain('where'); + }); + + it.each([ + [ + 'changedFrom', + { changedFrom: new Date('2026-10-01T00:00:00Z') }, + '"changedAt" >= $1', + new Date('2026-10-01T00:00:00Z'), + ], + [ + 'changedTo', + { changedTo: new Date('2026-10-31T23:59:59Z') }, + '"changedAt" <= $1', + new Date('2026-10-31T23:59:59Z'), + ], + [ + 'tableName', + { tableName: 'hourly_observations' as const }, + '"tableName" = $1', + 'hourly_observations', + ], + ['importId', { importId: 7 }, '"importId" = $1', 7], + [ + 'rowKey', + { rowKey: { stationId: 1, date: '2026-10-26' } }, + '"rowKey" = $1::jsonb', + '{"stationId":1,"date":"2026-10-26"}', + ], + ])( + 'filters by %s in both queries', + async (_name, filters, condition, value) => { + const { db, select, count } = buildDb(); + + await listAuditLog(db, filters, PAGE); + + for (const query of [select(), count()]) { + expect(query?.sql).toContain(`where ${condition}`); + expect(query?.parameters[0]).toEqual(value); + } + }, + ); + + it('combines every filter', async () => { + const { db, count } = buildDb(); + + await listAuditLog( + db, + { + changedFrom: new Date('2026-10-01T00:00:00Z'), + changedTo: new Date('2026-10-31T23:59:59Z'), + tableName: 'daily_observations', + importId: 7, + rowKey: { stationId: 1, date: '2026-10-26' }, + }, + PAGE, + ); + + expect(count()?.sql).toBe( + 'select count(*) as "total" from "audit_log" where "changedAt" >= $1 and "changedAt" <= $2 and "tableName" = $3 and "importId" = $4 and "rowKey" = $5::jsonb', + ); + }); +}); + +describe('getAuditLogEntry', () => { + it('selects every column for one id', async () => { + const { db, select } = buildDb(); + + await getAuditLogEntry(db, 7); + + expect(select()?.sql).toBe('select * from "audit_log" where "id" = $1'); + expect(select()?.parameters).toEqual([7]); + }); + + it('returns the first matching row', async () => { + const { db } = buildDb(); + + expect(await getAuditLogEntry(db, 2)).toEqual(ROWS[0]); + }); + + it('returns undefined when no entry has the id', async () => { + const { db } = buildDb([]); + + expect(await getAuditLogEntry(db, 999)).toBeUndefined(); + }); +}); diff --git a/apps/backend/internal-serving-lambda/src/__tests__/get-audit-log-entry.test.ts b/apps/backend/internal-serving-lambda/src/__tests__/get-audit-log-entry.test.ts new file mode 100644 index 000000000..5bbdd7912 --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/__tests__/get-audit-log-entry.test.ts @@ -0,0 +1,141 @@ +import type { APIGatewayProxyEvent } from 'aws-lambda'; +import { handler } from '../handler'; +import { getCurrentUser } from '../auth'; +import { getDb } from '../db'; +import { getAuditLogEntry } from '../audit-log'; +import { getAuditLogEntryHandler } from '../routes/get-audit-log-entry'; + +jest.mock('../auth'); +jest.mock('../db'); +jest.mock('../audit-log', () => ({ + ...jest.requireActual('../audit-log'), + getAuditLogEntry: jest.fn(), +})); + +const db = { fake: 'db' }; + +const ENTRY = { + id: 2, + tableName: 'daily_observations', + rowKey: { stationId: 1, date: '2026-10-26' }, + action: 'update', + oldData: { stationId: 1, date: '2026-10-26', maxTempF: 61 }, + newData: { stationId: 1, date: '2026-10-26', maxTempF: 62 }, + changedBy: 1, + importId: 7, + changedAt: new Date('2026-10-26T12:00:00Z'), +}; + +const buildEvent = (id: string): APIGatewayProxyEvent => + ({ + httpMethod: 'GET', + resource: '/audit-log/{id}', + path: `/audit-log/${id}`, + headers: {}, + pathParameters: { id }, + queryStringParameters: null, + body: null, + } as unknown as APIGatewayProxyEvent); + +const call = async (id: string) => { + const result = await getAuditLogEntryHandler(buildEvent(id)); + return { statusCode: result.statusCode, body: JSON.parse(result.body) }; +}; + +describe('getAuditLogEntryHandler', () => { + beforeEach(() => { + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest.mocked(getDb).mockReturnValue(db as never); + jest + .mocked(getAuditLogEntry) + .mockImplementation(async (_db, id) => + id === ENTRY.id ? (ENTRY as never) : undefined, + ); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + it('returns the entry, including the old and new data', async () => { + const { statusCode, body } = await call('2'); + + expect(statusCode).toBe(200); + expect(body).toEqual(JSON.parse(JSON.stringify(ENTRY))); + }); + + it('returns changedAt as an ISO 8601 string', async () => { + const { body } = await call('2'); + + expect(body.changedAt).toBe('2026-10-26T12:00:00.000Z'); + }); + + it('looks up the id as a number', async () => { + await call('2'); + + expect(getAuditLogEntry).toHaveBeenCalledWith(db, 2); + }); + + it('returns 404 for an unknown id', async () => { + const { statusCode, body } = await call('999'); + + expect(statusCode).toBe(404); + expect(body).toEqual({ message: 'Audit log entry not found' }); + }); + + it('accepts the largest Postgres integer', async () => { + const { statusCode } = await call('2147483647'); + + expect(statusCode).toBe(404); + expect(getAuditLogEntry).toHaveBeenCalledWith(db, 2147483647); + }); + + it.each(['abc', '0', '-1', '1.5', '1e3', ' 2', '2147483648', ''])( + 'returns 400 for id %p', + async (id) => { + const { statusCode, body } = await call(id); + + expect(statusCode).toBe(400); + expect(body).toEqual({ message: 'id must be a positive integer' }); + expect(getAuditLogEntry).not.toHaveBeenCalled(); + }, + ); + + it('returns 401 without a signed-in user', async () => { + jest.mocked(getCurrentUser).mockResolvedValue(null); + + const { statusCode, body } = await call('2'); + + expect(statusCode).toBe(401); + expect(body).toEqual({ message: 'Unauthorized' }); + expect(getAuditLogEntry).not.toHaveBeenCalled(); + }); +}); + +describe('GET /audit-log/{id} through the lambda handler', () => { + afterEach(() => { + jest.resetAllMocks(); + }); + + it('routes to the get audit log entry handler', async () => { + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest.mocked(getAuditLogEntry).mockResolvedValue(ENTRY as never); + + const result = await handler(buildEvent('2')); + + expect(result.statusCode).toBe(200); + expect(JSON.parse(result.body).id).toBe(2); + }); + + it('returns 500 when the query fails', async () => { + jest.spyOn(console, 'error').mockImplementation(() => undefined); + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest + .mocked(getAuditLogEntry) + .mockRejectedValue(new Error('connection refused')); + + const result = await handler(buildEvent('2')); + + expect(result.statusCode).toBe(500); + }); +}); diff --git a/apps/backend/internal-serving-lambda/src/__tests__/list-audit-log.test.ts b/apps/backend/internal-serving-lambda/src/__tests__/list-audit-log.test.ts new file mode 100644 index 000000000..06455de7b --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/__tests__/list-audit-log.test.ts @@ -0,0 +1,259 @@ +import type { APIGatewayProxyEvent } from 'aws-lambda'; +import { handler } from '../handler'; +import { getCurrentUser } from '../auth'; +import { getDb } from '../db'; +import { listAuditLog } from '../audit-log'; +import { listAuditLogHandler } from '../routes/list-audit-log'; + +jest.mock('../auth'); +jest.mock('../db'); +jest.mock('../audit-log', () => ({ + ...jest.requireActual('../audit-log'), + listAuditLog: jest.fn(), +})); + +const db = { fake: 'db' }; + +const ENTRIES = [ + { + id: 2, + tableName: 'daily_observations', + rowKey: { stationId: 1, date: '2026-10-26' }, + action: 'update', + oldData: { stationId: 1, date: '2026-10-26', maxTempF: 61 }, + newData: { stationId: 1, date: '2026-10-26', maxTempF: 62 }, + changedBy: 1, + importId: 7, + changedAt: new Date('2026-10-26T12:00:00Z'), + }, + { + id: 1, + tableName: 'daily_records', + rowKey: { stationId: 1, month: 10, day: 26 }, + action: 'insert', + oldData: null, + newData: { stationId: 1, month: 10, day: 26, highF: 80 }, + changedBy: null, + importId: 3, + changedAt: new Date('2026-10-25T09:30:00Z'), + }, +]; + +const buildEvent = ( + query: Record | null = null, +): APIGatewayProxyEvent => + ({ + httpMethod: 'GET', + resource: '/audit-log', + path: '/audit-log', + headers: {}, + pathParameters: null, + queryStringParameters: query, + body: null, + } as unknown as APIGatewayProxyEvent); + +const call = async (query: Record | null = null) => { + const result = await listAuditLogHandler(buildEvent(query)); + return { statusCode: result.statusCode, body: JSON.parse(result.body) }; +}; + +describe('listAuditLogHandler', () => { + beforeEach(() => { + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest.mocked(getDb).mockReturnValue(db as never); + jest + .mocked(listAuditLog) + .mockResolvedValue({ items: ENTRIES, total: 2 } as never); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + it('returns the page of entries with the total and paging', async () => { + const { statusCode, body } = await call(); + + expect(statusCode).toBe(200); + expect(body).toEqual({ + items: JSON.parse(JSON.stringify(ENTRIES)), + total: 2, + limit: 25, + offset: 0, + }); + }); + + it('returns changedAt as an ISO 8601 string', async () => { + const { body } = await call(); + + expect(body.items[0].changedAt).toBe('2026-10-26T12:00:00.000Z'); + }); + + it('defaults to no filters and the first 25 entries', async () => { + await call(); + + expect(listAuditLog).toHaveBeenCalledWith( + db, + { + changedFrom: undefined, + changedTo: undefined, + tableName: undefined, + importId: undefined, + rowKey: undefined, + }, + { limit: 25, offset: 0 }, + ); + }); + + it('passes every filter and the paging through', async () => { + const { body } = await call({ + changedFrom: '2026-10-01T00:00:00Z', + changedTo: '2026-10-31T23:59:59.999Z', + tableName: 'daily_observations', + importId: '7', + // API Gateway URL-decodes query strings before the lambda sees them + rowKey: '{"stationId":1,"date":"2026-10-26"}', + limit: '10', + offset: '20', + }); + + expect(listAuditLog).toHaveBeenCalledWith( + db, + { + changedFrom: new Date('2026-10-01T00:00:00Z'), + changedTo: new Date('2026-10-31T23:59:59.999Z'), + tableName: 'daily_observations', + importId: 7, + rowKey: { stationId: 1, date: '2026-10-26' }, + }, + { limit: 10, offset: 20 }, + ); + expect(body).toMatchObject({ limit: 10, offset: 20 }); + }); + + it.each([ + 'daily_observations', + 'hourly_observations', + 'scheduled_observations', + 'daily_records', + ])('accepts tableName=%s', async (tableName) => { + const { statusCode } = await call({ tableName }); + + expect(statusCode).toBe(200); + expect(jest.mocked(listAuditLog).mock.calls[0][1]).toMatchObject({ + tableName, + }); + }); + + it.each(['1', '2147483647'])('accepts importId=%s', async (importId) => { + const { statusCode } = await call({ importId }); + + expect(statusCode).toBe(200); + expect(jest.mocked(listAuditLog).mock.calls[0][1]).toMatchObject({ + importId: Number(importId), + }); + }); + + it('accepts changedFrom equal to changedTo', async () => { + const { statusCode } = await call({ + changedFrom: '2026-10-01T00:00:00Z', + changedTo: '2026-10-01T00:00:00Z', + }); + + expect(statusCode).toBe(200); + }); + + it.each(['1', '100'])('accepts limit=%s', async (limit) => { + const { statusCode } = await call({ limit }); + + expect(statusCode).toBe(200); + }); + + it.each([ + ['limit', '0'], + ['limit', '101'], + ['limit', 'ten'], + ['offset', '-1'], + ['offset', 'abc'], + ['changedFrom', '2026-10-01'], + ['changedFrom', '2026-10-01T00:00:00-04:00'], + ['changedFrom', '2026-13-01T00:00:00Z'], + ['changedTo', 'yesterday'], + ['tableName', 'audit_log'], + ['tableName', 'users'], + ['tableName', 'DAILY_RECORDS'], + ['tableName', ''], + ['importId', '0'], + ['importId', '-1'], + ['importId', '1.5'], + ['importId', 'abc'], + ['importId', '2147483648'], + ['importId', ''], + ['rowKey', 'stationId=1'], + ['rowKey', '{"stationId":1'], + ['rowKey', '[1]'], + ['rowKey', '1'], + ['rowKey', 'null'], + ['rowKey', '"2026-10-26"'], + ['rowKey', ''], + ])('returns 400 for %s=%p', async (param, value) => { + const { statusCode, body } = await call({ [param]: value }); + + expect(statusCode).toBe(400); + expect(body.message).toContain(param); + expect(listAuditLog).not.toHaveBeenCalled(); + }); + + it('returns 400 when changedFrom is after changedTo', async () => { + const { statusCode, body } = await call({ + changedFrom: '2026-10-02T00:00:00Z', + changedTo: '2026-10-01T00:00:00Z', + }); + + expect(statusCode).toBe(400); + expect(body.message).toContain('changedFrom'); + expect(listAuditLog).not.toHaveBeenCalled(); + }); + + it('returns 401 without a signed-in user', async () => { + jest.mocked(getCurrentUser).mockResolvedValue(null); + + const { statusCode, body } = await call(); + + expect(statusCode).toBe(401); + expect(body).toEqual({ message: 'Unauthorized' }); + expect(listAuditLog).not.toHaveBeenCalled(); + }); +}); + +describe('GET /audit-log through the lambda handler', () => { + afterEach(() => { + jest.resetAllMocks(); + }); + + it('routes to the list audit log handler', async () => { + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest.mocked(listAuditLog).mockResolvedValue({ items: [], total: 0 }); + + const result = await handler(buildEvent()); + + expect(result.statusCode).toBe(200); + expect(JSON.parse(result.body)).toEqual({ + items: [], + total: 0, + limit: 25, + offset: 0, + }); + }); + + it('returns 500 when the query fails', async () => { + jest.spyOn(console, 'error').mockImplementation(() => undefined); + jest.mocked(getCurrentUser).mockResolvedValue({ id: 'user-123' }); + jest + .mocked(listAuditLog) + .mockRejectedValue(new Error('connection refused')); + + const result = await handler(buildEvent()); + + expect(result.statusCode).toBe(500); + }); +}); diff --git a/apps/backend/internal-serving-lambda/src/audit-log.ts b/apps/backend/internal-serving-lambda/src/audit-log.ts new file mode 100644 index 000000000..226e85858 --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/audit-log.ts @@ -0,0 +1,63 @@ +import { sql, type Kysely } from 'kysely'; +import type { Database } from '@bho/db-client'; +import type { Page } from './imports'; + +// The tables with an audit trigger (see db/migrations), so the only values +// tableName can have +export const AUDITED_TABLES = [ + 'daily_observations', + 'hourly_observations', + 'scheduled_observations', + 'daily_records', +] as const; +export type AuditedTable = (typeof AUDITED_TABLES)[number]; + +export interface AuditLogFilters { + changedFrom?: Date; + changedTo?: Date; + tableName?: AuditedTable; + importId?: number; + rowKey?: Record; +} + +// Newest changedAt first; id breaks ties, since every row changed in one +// transaction gets the same changedAt +export const listAuditLog = async ( + db: Kysely, + { changedFrom, changedTo, tableName, importId, rowKey }: AuditLogFilters, + { limit, offset }: Page, +) => { + let query = db.selectFrom('audit_log'); + if (changedFrom) query = query.where('changedAt', '>=', changedFrom); + if (changedTo) query = query.where('changedAt', '<=', changedTo); + if (tableName) query = query.where('tableName', '=', tableName); + if (importId !== undefined) query = query.where('importId', '=', importId); + // jsonb equality ignores key order, but a value's type must match the + // column's ("1" doesn't match a stationId of 1) + if (rowKey) { + query = query.where('rowKey', '=', sql`${JSON.stringify(rowKey)}::jsonb`); + } + + const [items, { total }] = await Promise.all([ + query + .selectAll() + .orderBy('changedAt', 'desc') + .orderBy('id', 'desc') + .limit(limit) + .offset(offset) + .execute(), + query + .select((eb) => eb.fn.countAll().as('total')) + .executeTakeFirstOrThrow(), + ]); + + return { items, total: Number(total) }; +}; + +// undefined if no audit log entry has this id +export const getAuditLogEntry = (db: Kysely, id: number) => + db + .selectFrom('audit_log') + .selectAll() + .where('id', '=', id) + .executeTakeFirst(); diff --git a/apps/backend/internal-serving-lambda/src/routes.ts b/apps/backend/internal-serving-lambda/src/routes.ts index 151003f10..3ebd09922 100644 --- a/apps/backend/internal-serving-lambda/src/routes.ts +++ b/apps/backend/internal-serving-lambda/src/routes.ts @@ -1,7 +1,9 @@ import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; import { createUploadUrlHandler } from './routes/create-upload-url'; +import { getAuditLogEntryHandler } from './routes/get-audit-log-entry'; import { getImportHandler } from './routes/get-import'; import { healthHandler } from './routes/health'; +import { listAuditLogHandler } from './routes/list-audit-log'; import { listImportsHandler } from './routes/list-imports'; export type RouteHandler = ( @@ -13,4 +15,6 @@ export const routes: Record = { 'POST /imports/upload-url/{kind}': createUploadUrlHandler, 'GET /imports': listImportsHandler, 'GET /imports/{id}': getImportHandler, + 'GET /audit-log': listAuditLogHandler, + 'GET /audit-log/{id}': getAuditLogEntryHandler, }; diff --git a/apps/backend/internal-serving-lambda/src/routes/get-audit-log-entry.ts b/apps/backend/internal-serving-lambda/src/routes/get-audit-log-entry.ts new file mode 100644 index 000000000..a845869b1 --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/routes/get-audit-log-entry.ts @@ -0,0 +1,25 @@ +import type { RouteHandler } from '../routes'; +import { response } from '../response'; +import { getCurrentUser } from '../auth'; +import { getDb } from '../db'; +import { getAuditLogEntry } from '../audit-log'; +import { MAX_ID } from './get-import'; + +// GET /audit-log/{id} +export const getAuditLogEntryHandler: RouteHandler = async (event) => { + const user = await getCurrentUser(event); + if (!user) return response(401, { message: 'Unauthorized' }); + + const rawId = event.pathParameters?.id ?? ''; + const id = Number(rawId); + if (!/^\d+$/.test(rawId) || id < 1 || id > MAX_ID) { + return response(400, { message: 'id must be a positive integer' }); + } + + const found = await getAuditLogEntry(getDb(), id); + if (!found) { + return response(404, { message: 'Audit log entry not found' }); + } + + return response(200, found); +}; diff --git a/apps/backend/internal-serving-lambda/src/routes/get-import.ts b/apps/backend/internal-serving-lambda/src/routes/get-import.ts index 76b983f7a..0f4137d1d 100644 --- a/apps/backend/internal-serving-lambda/src/routes/get-import.ts +++ b/apps/backend/internal-serving-lambda/src/routes/get-import.ts @@ -5,7 +5,7 @@ import { getDb } from '../db'; import { getImport } from '../imports'; // imports.id is a Postgres integer, so larger ids would fail the query -const MAX_ID = 2_147_483_647; +export const MAX_ID = 2_147_483_647; // GET /imports/{id} export const getImportHandler: RouteHandler = async (event) => { diff --git a/apps/backend/internal-serving-lambda/src/routes/list-audit-log.ts b/apps/backend/internal-serving-lambda/src/routes/list-audit-log.ts new file mode 100644 index 000000000..20e7b9d05 --- /dev/null +++ b/apps/backend/internal-serving-lambda/src/routes/list-audit-log.ts @@ -0,0 +1,102 @@ +import type { APIGatewayProxyEvent } from 'aws-lambda'; +import type { RouteHandler } from '../routes'; +import { response } from '../response'; +import { getCurrentUser } from '../auth'; +import { getDb } from '../db'; +import { + AUDITED_TABLES, + listAuditLog, + type AuditLogFilters, +} from '../audit-log'; +import type { Page } from '../imports'; +import { MAX_ID } from './get-import'; +import { + DEFAULT_LIMIT, + MAX_LIMIT, + oneOf, + parseInteger, + parseTimestamp, +} from './list-imports'; + +// rowKey is always a JSON object of the changed row's primary key, e.g. +// {"stationId":1,"date":"2026-10-26"} +const parseRowKey = (value: string | undefined) => { + let rowKey: unknown; + if (value === undefined) return undefined; + try { + rowKey = JSON.parse(value); + } catch { + return null; + } + const isObject = + typeof rowKey === 'object' && rowKey !== null && !Array.isArray(rowKey); + return isObject ? (rowKey as Record) : null; +}; + +// Returns the parsed query, or a message describing the first invalid param +const parseQuery = ( + event: APIGatewayProxyEvent, +): { filters: AuditLogFilters; page: Page } | string => { + const query = event.queryStringParameters ?? {}; + + const limit = parseInteger(query.limit, DEFAULT_LIMIT); + if (!(limit >= 1 && limit <= MAX_LIMIT)) { + return `limit must be an integer from 1 to ${MAX_LIMIT}`; + } + const offset = parseInteger(query.offset, 0); + if (isNaN(offset)) return 'offset must be a non-negative integer'; + + const changedFrom = parseTimestamp(query.changedFrom); + if (changedFrom === null) { + return 'changedFrom must be an ISO 8601 UTC timestamp'; + } + const changedTo = parseTimestamp(query.changedTo); + if (changedTo === null) { + return 'changedTo must be an ISO 8601 UTC timestamp'; + } + if (changedFrom && changedTo && changedFrom > changedTo) { + return 'changedFrom must not be after changedTo'; + } + + const { tableName } = query; + if (tableName !== undefined && !oneOf(AUDITED_TABLES, tableName)) { + return `tableName must be one of: ${AUDITED_TABLES.join(', ')}`; + } + + const importId = + query.importId === undefined ? undefined : parseInteger(query.importId, 0); + if (importId !== undefined && !(importId >= 1 && importId <= MAX_ID)) { + return 'importId must be a positive integer'; + } + + const rowKey = parseRowKey(query.rowKey); + if (rowKey === null) return 'rowKey must be a JSON object'; + + return { + filters: { + changedFrom, + changedTo, + tableName: tableName as AuditLogFilters['tableName'], + importId, + rowKey, + }, + page: { limit, offset }, + }; +}; + +// GET /audit-log?changedFrom&changedTo&tableName&importId&rowKey&limit&offset +export const listAuditLogHandler: RouteHandler = async (event) => { + const user = await getCurrentUser(event); + if (!user) return response(401, { message: 'Unauthorized' }); + + const parsed = parseQuery(event); + if (typeof parsed === 'string') return response(400, { message: parsed }); + + const { items, total } = await listAuditLog( + getDb(), + parsed.filters, + parsed.page, + ); + + return response(200, { items, total, ...parsed.page }); +}; diff --git a/apps/backend/internal-serving-lambda/src/routes/list-imports.ts b/apps/backend/internal-serving-lambda/src/routes/list-imports.ts index 552595d94..88c5e5089 100644 --- a/apps/backend/internal-serving-lambda/src/routes/list-imports.ts +++ b/apps/backend/internal-serving-lambda/src/routes/list-imports.ts @@ -17,16 +17,16 @@ export const MAX_LIMIT = 100; // ISO 8601 in UTC, e.g. 2026-10-26T12:00:00Z or 2026-10-26T12:00:00.000Z const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/; -const parseInteger = (value: string | undefined, fallback: number) => +export const parseInteger = (value: string | undefined, fallback: number) => value === undefined ? fallback : /^\d+$/.test(value) ? Number(value) : NaN; -const parseTimestamp = (value: string | undefined) => { +export const parseTimestamp = (value: string | undefined) => { if (value === undefined) return undefined; const date = new Date(value); return ISO_UTC.test(value) && !isNaN(date.getTime()) ? date : null; }; -const oneOf = (values: readonly T[], value: unknown) => +export const oneOf = (values: readonly T[], value: unknown) => values.includes(value as T); // Returns the parsed query, or a message describing the first invalid param