diff --git a/backend/docs/AUDIT_CHAIN.md b/backend/docs/AUDIT_CHAIN.md new file mode 100644 index 00000000..01c89841 --- /dev/null +++ b/backend/docs/AUDIT_CHAIN.md @@ -0,0 +1,29 @@ +# Tamper-Evident Audit Logging + +Issue #1356 — cryptographic hash chain over audit entries. + +## How it works + +Each audit entry stores: + +- `previousHash` — SHA-256 of the prior entry (genesis `00…00` for the first) +- `hash` — SHA-256 over identity fields + `previousHash` + +Verification walks the retained chain from the chain anchor and recomputes hashes. Any edit or deletion in the hot log breaks verification. + +## Surfaces + +| Path | Purpose | +|------|---------| +| Middleware `backend/src/middleware/audit.ts` | Writes chained entries after each response | +| `GET /api/v1/audit/verify` | Integrity check + `chainTip`, `entryCount`, `algorithm` | +| `GET /api/v1/audit/chain` | Chain tip without requiring a full CSV/JSON export | + +Middleware entries carry `details.hashAlgorithm = sha256` so exported logs identify the chain algorithm. Chain tips are read from the endpoints below rather than response headers, since entries are written after the response finishes. + +## Example + +```bash +curl -s "$API/api/v1/audit/chain" | jq +# { "algorithm": "sha256", "chainTip": "...", "entryCount": 12, "valid": true } +``` diff --git a/backend/src/middleware/__tests__/audit-chain.test.ts b/backend/src/middleware/__tests__/audit-chain.test.ts new file mode 100644 index 00000000..83ebd22a --- /dev/null +++ b/backend/src/middleware/__tests__/audit-chain.test.ts @@ -0,0 +1,53 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { + AUDIT_CHAIN_GENESIS, + AUDIT_HASH_ALGORITHM, + deriveAuditResource, +} from '../audit.js'; +import { AuditService } from '../../services/auditService.js'; + +describe('tamper-evident audit chain (#1356)', () => { + let service: AuditService; + + beforeEach(() => { + service = new AuditService({ alerting: false }); + }); + + it('exports chain constants used by middleware', () => { + expect(AUDIT_CHAIN_GENESIS).toHaveLength(64); + expect(AUDIT_HASH_ALGORITHM).toBe('sha256'); + }); + + it('links each entry to the previous hash and verifies integrity', async () => { + const first = await service.logAction({ action: 'a.create', resource: 'a' }); + expect(first.previousHash).toBe(AUDIT_CHAIN_GENESIS); + + const second = await service.logAction({ action: 'b.create', resource: 'b' }); + expect(second.previousHash).toBe(first.hash); + + const tip = await service.getChainTip(); + expect(tip).toBe(second.hash); + + await expect(service.verifyIntegrity()).resolves.toEqual({ valid: true }); + }); + + it('detects tampering when an entry hash is altered', async () => { + await service.logAction({ action: 'a.create', resource: 'a' }); + const second = await service.logAction({ action: 'b.create', resource: 'b' }); + + // Simulate tampering via private entries array + (second as { hash: string }).hash = 'deadbeef'.repeat(8); + + const result = await service.verifyIntegrity(); + expect(result.valid).toBe(false); + expect(result.brokenAt).toBe(second.id); + }); + + it('derives resource names past the API version segment', () => { + const req = { + baseUrl: '/api/v1/payments', + path: '/123', + } as unknown as import('express').Request; + expect(deriveAuditResource(req)).toBe('payments'); + }); +}); diff --git a/backend/src/middleware/audit.ts b/backend/src/middleware/audit.ts index 7519d3e0..67bc6649 100644 --- a/backend/src/middleware/audit.ts +++ b/backend/src/middleware/audit.ts @@ -1,5 +1,11 @@ import type { Request, Response, NextFunction } from 'express'; -import { auditService } from '../services/auditService.js'; +import { + AUDIT_CHAIN_GENESIS, + AUDIT_HASH_ALGORITHM, + auditService, +} from '../services/auditService.js'; + +export { AUDIT_CHAIN_GENESIS, AUDIT_HASH_ALGORITHM }; export interface AuditMiddlewareOptions { excludePaths?: string[]; @@ -22,7 +28,8 @@ export function deriveAuditResource(req: Request): string { } /** - * Express middleware that records user and system operations to the tamper-evident audit log. + * Express middleware that records user and system operations to the + * tamper-evident, hash-chained audit log (issue #1356). */ export function auditMiddleware(options: AuditMiddlewareOptions = {}) { const excludePaths = options.excludePaths || ['/health', '/metrics', '/api-docs']; @@ -58,34 +65,42 @@ export function auditMiddleware(options: AuditMiddlewareOptions = {}) { // Capture request body (sanitization happens inside auditService.logAction) const requestBody = req.body; - void auditService.logAction({ - userId: String(userId), - action, - resource, - resourceId: req.params?.id || (req.body?.id ? String(req.body.id) : undefined), - details: { - durationMs, - query: req.query, - headers: { - host: req.headers.host, - accept: req.headers.accept, + void auditService + .logAction({ + userId: String(userId), + action, + resource, + resourceId: req.params?.id + ? String(req.params.id) + : req.body?.id + ? String(req.body.id) + : undefined, + details: { + durationMs, + query: req.query, + headers: { + host: req.headers.host, + accept: req.headers.accept, + }, + hashAlgorithm: AUDIT_HASH_ALGORITHM, + }, + ipAddress: req.ip || req.socket.remoteAddress, + userAgent: typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : undefined, + request: { + method: req.method, + path: req.path, + body: requestBody, }, - }, - ipAddress: req.ip || req.socket.remoteAddress, - userAgent: typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : undefined, - request: { - method: req.method, - path: req.path, - body: requestBody, - }, - response: { - status: res.statusCode, - }, - }).catch((err) => { - console.error('[audit] Failed to write audit entry', err); - }); + response: { + status: res.statusCode, + }, + }) + .catch((err) => { + console.error('[audit] Failed to write audit entry', err); + }); }); next(); }; } + diff --git a/backend/src/routes/audit.ts b/backend/src/routes/audit.ts index 5b12ca0d..326ccad4 100644 --- a/backend/src/routes/audit.ts +++ b/backend/src/routes/audit.ts @@ -1,6 +1,10 @@ import { Router, Request, Response } from 'express'; import { asyncHandler } from '../middleware/errorHandler.js'; -import { auditService } from '../services/auditService.js'; +import { + AUDIT_CHAIN_GENESIS, + AUDIT_HASH_ALGORITHM, + auditService, +} from '../services/auditService.js'; import { AuditEventValidationError, normalizeAuditEvent } from '../audit/event-schema.js'; import type { ComplianceFramework } from '../audit/compliance-report.js'; @@ -81,7 +85,29 @@ auditRouter.get('/entries/:id', asyncHandler(async (req: Request, res: Response) auditRouter.get('/verify', asyncHandler(async (req: Request, res: Response) => { const result = await auditService.verifyIntegrity(); - res.status(200).json(result); + const count = await auditService.getEntryCount(); + const tip = await auditService.getChainTip(); + res.status(200).json({ + ...result, + algorithm: AUDIT_HASH_ALGORITHM, + entryCount: count, + chainTip: tip, + }); +})); + +/** Return the current chain tip together with a full integrity check. */ +auditRouter.get('/chain', asyncHandler(async (_req: Request, res: Response) => { + const tip = await auditService.getChainTip(); + const count = await auditService.getEntryCount(); + const integrity = await auditService.verifyIntegrity(); + res.status(200).json({ + algorithm: AUDIT_HASH_ALGORITHM, + genesis: AUDIT_CHAIN_GENESIS, + chainTip: tip, + entryCount: count, + valid: integrity.valid, + brokenAt: integrity.brokenAt, + }); })); auditRouter.post('/flag/:id', asyncHandler(async (req: Request, res: Response) => { diff --git a/backend/src/services/auditService.ts b/backend/src/services/auditService.ts index a08f8760..5c34881b 100644 --- a/backend/src/services/auditService.ts +++ b/backend/src/services/auditService.ts @@ -26,6 +26,10 @@ import { type RetentionEnforcementResult, } from '../audit/retention.js'; +/** Hash algorithm and genesis value shared by writers and verification endpoints. */ +export const AUDIT_HASH_ALGORITHM = 'sha256'; +export const AUDIT_CHAIN_GENESIS = '0'.repeat(64); + /** Whether a sensitive operation succeeded or failed. */ export type AuditOutcome = 'success' | 'failure'; @@ -80,13 +84,13 @@ export interface AuditServiceOptions { export class AuditService { private entries: AuditEntry[] = []; - private currentHash = '0000000000000000000000000000000000000000000000000000000000000000'; + private currentHash = AUDIT_CHAIN_GENESIS; /** * Hash immediately preceding the oldest retained entry. Archival/eviction * moves this forward so `verifyIntegrity()` keeps validating the retained * chain instead of reporting a break at the first evicted entry (issue #396). */ - private chainAnchor = '0000000000000000000000000000000000000000000000000000000000000000'; + private chainAnchor = AUDIT_CHAIN_GENESIS; private retentionPolicy: RetentionPolicy = { retentionDays: 2555, archiveAfterDays: 2190, @@ -408,6 +412,11 @@ export class AuditService { }; } + /** Current tip of the SHA-256 hash chain (genesis when empty). */ + async getChainTip(): Promise { + return this.currentHash; + } + async getEntryCount(): Promise { return this.entries.length; }