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
29 changes: 29 additions & 0 deletions backend/docs/AUDIT_CHAIN.md
Original file line number Diff line number Diff line change
@@ -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 }
```
53 changes: 53 additions & 0 deletions backend/src/middleware/__tests__/audit-chain.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
69 changes: 42 additions & 27 deletions backend/src/middleware/audit.ts
Original file line number Diff line number Diff line change
@@ -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[];
Expand All @@ -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'];
Expand Down Expand Up @@ -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();
};
}

30 changes: 28 additions & 2 deletions backend/src/routes/audit.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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) => {
Expand Down
13 changes: 11 additions & 2 deletions backend/src/services/auditService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -408,6 +412,11 @@ export class AuditService {
};
}

/** Current tip of the SHA-256 hash chain (genesis when empty). */
async getChainTip(): Promise<string> {
return this.currentHash;
}

async getEntryCount(): Promise<number> {
return this.entries.length;
}
Expand Down
Loading