-
Notifications
You must be signed in to change notification settings - Fork 0
feat(api): add correlation IDs and structured telemetry #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
df3b8b8
feat(api): add correlation IDs and structured telemetry
patoperpetua 6bf9b3d
fixup: address CodeRabbit inline feedback
patoperpetua 9638a0d
fix(api): classify validation errors before emitting telemetry in con…
patoperpetua adba09d
Merge origin/main into feat/21-correlation-telemetry.
patoperpetua 86a1d13
fix(api): put request correlation IDs on contact error bodies
patoperpetua File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { describe, it } from 'node:test'; | ||
| import type { HttpRequest, InvocationContext } from '@azure/functions'; | ||
| import { getContactRateLimiter } from '../contact-rate-limit'; | ||
| import { contactHandler } from './contact'; | ||
|
|
||
| function fakeRequest(options: { | ||
| method?: string; | ||
| headers?: Record<string, string>; | ||
| json?: unknown; | ||
| }): HttpRequest { | ||
| const headers = new Headers(options.headers); | ||
| return { | ||
| method: options.method ?? 'POST', | ||
| headers: { | ||
| get: (name: string) => headers.get(name), | ||
| }, | ||
| json: async () => options.json ?? null, | ||
| } as unknown as HttpRequest; | ||
| } | ||
|
|
||
| function fakeContext(): InvocationContext & { errors: unknown[] } { | ||
| const errors: unknown[] = []; | ||
| return { | ||
| error: (...args: unknown[]) => { | ||
| errors.push(args); | ||
| }, | ||
| errors, | ||
| } as unknown as InvocationContext & { errors: unknown[] }; | ||
| } | ||
|
|
||
| describe('contactHandler', () => { | ||
| it('propagates a valid X-Correlation-Id on validation errors and includes it in the body', async () => { | ||
| getContactRateLimiter().reset(); | ||
| const correlationId = 'client-corr-id-01'; | ||
| const response = await contactHandler( | ||
| fakeRequest({ | ||
| headers: { 'x-correlation-id': correlationId }, | ||
| json: { name: 'bad' }, | ||
| }), | ||
| fakeContext(), | ||
| ); | ||
|
|
||
| assert.equal(response.status, 400); | ||
| assert.equal(response.headers?.['X-Correlation-Id'], correlationId); | ||
| assert.equal((response.jsonBody as { correlationId?: string }).correlationId, correlationId); | ||
| assert.equal(typeof (response.jsonBody as { error?: string }).error, 'string'); | ||
| }); | ||
|
|
||
| it('generates a correlation ID when the header is absent', async () => { | ||
| getContactRateLimiter().reset(); | ||
| const response = await contactHandler(fakeRequest({ json: { name: 'bad' } }), fakeContext()); | ||
|
|
||
| assert.equal(response.status, 400); | ||
| const headerId = response.headers?.['X-Correlation-Id']; | ||
| assert.equal(typeof headerId, 'string'); | ||
| assert.match(headerId ?? '', /^[0-9a-f-]{36}$/i); | ||
| assert.equal((response.jsonBody as { correlationId?: string }).correlationId, headerId); | ||
| }); | ||
|
|
||
| it('logs the request correlation ID on native error output, not the provider ID', async () => { | ||
| getContactRateLimiter().reset(); | ||
| const correlationId = 'handler-corr-id-01'; | ||
| const context = fakeContext(); | ||
| await contactHandler( | ||
| fakeRequest({ | ||
| headers: { 'x-correlation-id': correlationId }, | ||
| json: { name: 'bad' }, | ||
| }), | ||
| context, | ||
| ); | ||
|
|
||
| const logged = context.errors[0] as [string, { correlationId?: string }]; | ||
| assert.equal(logged[1]?.correlationId, correlationId); | ||
| assert.ok(!('emailCorrelationId' in (logged[1] ?? {}) && logged[1].emailCorrelationId)); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { describe, it } from 'node:test'; | ||
| import { generateCorrelationId, resolveCorrelationId } from './correlation'; | ||
|
|
||
| const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | ||
|
|
||
| describe('generateCorrelationId', () => { | ||
| it('returns a non-empty string matching UUID v4 pattern', () => { | ||
| const id = generateCorrelationId(); | ||
| assert.ok(id.length > 0, 'should be non-empty'); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('returns a different value on each call', () => { | ||
| assert.notEqual(generateCorrelationId(), generateCorrelationId()); | ||
| }); | ||
| }); | ||
|
|
||
| describe('resolveCorrelationId', () => { | ||
| it('generates a fresh ID when headerValue is undefined', () => { | ||
| const id = resolveCorrelationId(undefined); | ||
| assert.ok(id.length > 0); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('returns a valid header value as-is', () => { | ||
| assert.equal(resolveCorrelationId('valid-id-123'), 'valid-id-123'); | ||
| }); | ||
|
|
||
| it('accepts UUIDs as valid header values', () => { | ||
| const uuid = generateCorrelationId(); | ||
| assert.equal(resolveCorrelationId(uuid), uuid); | ||
| }); | ||
|
|
||
| it('sanitises a value containing HTML/script injection characters', () => { | ||
| const id = resolveCorrelationId('<script>alert(1)</script>'); | ||
| assert.notEqual(id, '<script>alert(1)</script>'); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('generates a fresh ID when headerValue exceeds 128 chars', () => { | ||
| const id = resolveCorrelationId('a'.repeat(200)); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('generates a fresh ID when headerValue is an empty string', () => { | ||
| const id = resolveCorrelationId(''); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('generates a fresh ID when headerValue is fewer than 8 chars', () => { | ||
| const id = resolveCorrelationId('short'); | ||
| assert.match(id, UUID_V4); | ||
| }); | ||
|
|
||
| it('accepts an ID at the minimum boundary (8 chars)', () => { | ||
| assert.equal(resolveCorrelationId('abcd1234'), 'abcd1234'); | ||
| }); | ||
|
|
||
| it('accepts an ID at the maximum boundary (128 chars)', () => { | ||
| const max = 'a'.repeat(128); | ||
| assert.equal(resolveCorrelationId(max), max); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| /** | ||
| * Correlation ID utilities for per-request tracing. | ||
| * | ||
| * No external UUID library — Node 20 ships crypto.randomUUID() natively. | ||
| */ | ||
|
|
||
| /** Valid correlation ID: 8–128 alphanumeric / hyphen / underscore characters. */ | ||
| const VALID_CORRELATION_ID = /^[a-zA-Z0-9_-]{8,128}$/; | ||
|
|
||
| /** | ||
| * Generate a new UUID v4 correlation ID. | ||
| */ | ||
| export function generateCorrelationId(): string { | ||
| return crypto.randomUUID(); | ||
| } | ||
|
|
||
| /** | ||
| * Sanitise a caller-supplied X-Correlation-Id header value. | ||
| * | ||
| * Rules: must be 8–128 alphanumeric/hyphen/underscore characters only. | ||
| * If the value is missing, empty, or fails validation, a fresh ID is generated. | ||
| */ | ||
| export function resolveCorrelationId(headerValue: string | undefined): string { | ||
| if (headerValue && VALID_CORRELATION_ID.test(headerValue)) { | ||
| return headerValue; | ||
| } | ||
| return generateCorrelationId(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export { generateCorrelationId, resolveCorrelationId } from './correlation'; | ||
| export { createLogger } from './logger'; | ||
| export type { LogEntry, Logger } from './logger'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.