diff --git a/backend/src/webhooks/__tests__/dispatcher.test.ts b/backend/src/webhooks/__tests__/dispatcher.test.ts new file mode 100644 index 00000000..7b3b5df3 --- /dev/null +++ b/backend/src/webhooks/__tests__/dispatcher.test.ts @@ -0,0 +1,249 @@ +/** + * backend/src/webhooks/__tests__/dispatcher.test.ts + * + * Unit tests for the webhook dispatcher JWT gate. + * Run with: npx jest backend/src/webhooks/__tests__/dispatcher.test.ts + */ + +import { + DispatchError, + validateDelivery, + defaultSplitToken, + createWebhookDispatcher, + dispatchWebhook, + type WebhookDelivery, + type DispatcherConfig, + type HandlerContext, +} from '../dispatcher'; + +// ?? Helpers ????????????????????????????????????????????????????????????? + +function enc(obj: unknown): string { + const bytes = new TextEncoder().encode(JSON.stringify(obj)); + let binary = ''; + bytes.forEach((b) => { binary += String.fromCharCode(b); }); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +const NOW = 1_700_000_000; +const POLICY = { + audiences: ['webhook-prod'], + allowedOrigins: ['https://billing.example.com'], + issuer: 'https://issuer.example.com', +}; + +function token(overrides: Record = {}): string { + const claims = { + aud: 'webhook-prod', + origin: 'https://billing.example.com', + iss: 'https://issuer.example.com', + exp: NOW + 600, + ...overrides, + }; + return `${enc({ alg: 'HS256' })}.${enc(claims)}.c2lnbmF0dXJl`; +} + +function delivery(overrides: Partial = {}): WebhookDelivery { + return { + id: 'evt-1', + type: 'invoice.paid', + source: 'billing', + payload: { amount: 100 }, + ...overrides, + }; +} + +function makeHooks(verify = true) { + const calls: Array<{ name: string; labels?: Readonly> }> = []; + const logs: Array<{ level: string; message: string; ctx?: Readonly> }> = []; + return { + calls, + logs, + verifySignature: () => verify, + metrics: { increment: (name: string, labels?: Readonly>) => calls.push({ name, labels }) }, + logger: { + info: (m: string, ctx?: Readonly>) => logs.push({ level: 'info', message: m, ctx }), + warn: (m: string, ctx?: Readonly>) => logs.push({ level: 'warn', message: m, ctx }), + }, + }; +} + +// ?? validateDelivery ???????????????????????????????????????????????????? + +describe('validateDelivery', () => { + it('accepts a valid delivery', () => { + expect(() => validateDelivery(delivery())).not.toThrow(); + }); + + it('rejects a missing id', () => { + expect(() => validateDelivery(delivery({ id: '' }))).toThrow(DispatchError); + }); + + it('rejects a missing type', () => { + expect(() => validateDelivery(delivery({ type: '' }))).toThrow(DispatchError); + }); + + it('rejects a missing source', () => { + expect(() => validateDelivery(delivery({ source: '' }))).toThrow(DispatchError); + }); + + it('rejects an invalid payload', () => { + expect(() => validateDelivery(delivery({ payload: null as unknown as Record }))).toThrow(DispatchError); + }); +}); + +// ?? defaultSplitToken ??????????????????????????????????????????????????? + +describe('defaultSplitToken', () => { + it('splits signing input from signature', () => { + const parts = defaultSplitToken(token()); + expect(parts.signingInput.split('.')).toHaveLength(2); + expect(parts.signature).toBe('c2lnbmF0dXJl'); + }); + + it('rejects a malformed token', () => { + expect(() => defaultSplitToken('a.b')).toThrow(DispatchError); + }); +}); + +// ?? Dispatch happy path ????????????????????????????????????????????????? + +describe('createWebhookDispatcher - accepted deliveries', () => { + it('dispatches a valid delivery to its handler', async () => { + const received: HandlerContext[] = []; + const hooks = makeHooks(); + const dispatcher = createWebhookDispatcher({ + policy: POLICY, + handlers: { 'invoice.paid': (ctx) => { received.push(ctx); } }, + hooks, + }); + // Dispatch uses the real clock, so the token must carry a far-future exp. + const farFuture = token({ exp: Math.floor(Date.now() / 1000) + 3600 }); + const result = await dispatcher.dispatch(farFuture, delivery()); + expect(result.dispatched).toBe(true); + expect(result.handler).toBe('invoice.paid'); + expect(received.length).toBe(1); + expect(received[0].matchedAudience).toBe('webhook-prod'); + expect(hooks.calls.some((c) => c.name === 'webhook.dispatch.accepted')).toBe(true); + }); + + it('passes normalized origin and claims into the handler context', async () => { + let ctx: HandlerContext | undefined; + const dispatcher = createWebhookDispatcher({ + policy: POLICY, + handlers: { 'invoice.paid': (c) => { ctx = c; } }, + }); + const result = await dispatcher.dispatch( + token({ exp: Math.floor(Date.now() / 1000) + 3600, origin: 'https://BILLING.EXAMPLE.COM/' }), + delivery() + ); + expect(result.dispatched).toBe(true); + expect(ctx?.normalizedOrigin).toBe('https://billing.example.com'); + expect(ctx?.claims?.sub).toBeUndefined(); + }); + + it('supports async handlers', async () => { + const seen: string[] = []; + const dispatcher = createWebhookDispatcher({ + policy: POLICY, + handlers: { 'invoice.paid': async () => { seen.push('done'); } }, + }); + const result = await dispatcher.dispatch(token({ exp: Math.floor(Date.now() / 1000) + 3600 }), delivery()); + expect(result.dispatched).toBe(true); + expect(seen).toEqual(['done']); + }); + + it('registers handlers dynamically', async () => { + const dispatcher = createWebhookDispatcher({ policy: POLICY, handlers: {} }); + let called = false; + dispatcher.registerHandler('invoice.paid', () => { called = true; }); + expect(dispatcher.handlerTypes()).toContain('invoice.paid'); + const result = await dispatcher.dispatch(token({ exp: Math.floor(Date.now() / 1000) + 3600 }), delivery()); + expect(result.dispatched).toBe(true); + expect(called).toBe(true); + }); +}); + +// ?? Reject paths ???????????????????????????????????????????????????????? + +describe('createWebhookDispatcher - rejected deliveries', () => { + function cfg(hooks: ReturnType): DispatcherConfig { + return { + policy: POLICY, + handlers: { 'invoice.paid': () => {} }, + hooks, + }; + } + + it('rejects when JWT claims fail', async () => { + const hooks = makeHooks(); + const dispatcher = createWebhookDispatcher(cfg(hooks)); + const result = await dispatcher.dispatch( + token({ exp: Math.floor(Date.now() / 1000) + 3600, aud: 'wrong' }), + delivery() + ); + expect(result.dispatched).toBe(false); + expect(result.error?.code).toBe('JWT_REJECTED'); + expect(result.error?.details.code).toBe('INVALID_AUDIENCE'); + expect(hooks.calls.some((c) => c.name === 'webhook.dispatch.rejected')).toBe(true); + expect(hooks.logs.some((l) => l.level === 'warn')).toBe(true); + }); + + it('rejects when the signature hook returns false', async () => { + const hooks = makeHooks(false); + const dispatcher = createWebhookDispatcher(cfg(hooks)); + const result = await dispatcher.dispatch(token({ exp: Math.floor(Date.now() / 1000) + 3600 }), delivery()); + expect(result.dispatched).toBe(false); + expect(result.error?.code).toBe('SIGNATURE_INVALID'); + }); + + it('rejects when no handler is registered (strict)', async () => { + const dispatcher = createWebhookDispatcher(cfg(makeHooks())); + const result = await dispatcher.dispatch( + token({ exp: Math.floor(Date.now() / 1000) + 3600 }), + delivery({ type: 'unknown.event' }) + ); + expect(result.dispatched).toBe(false); + expect(result.error?.code).toBe('NO_HANDLER'); + }); + + it('skips cleanly when strictHandler is false', async () => { + const dispatcher = createWebhookDispatcher({ ...cfg(makeHooks()), strictHandler: false }); + const result = await dispatcher.dispatch( + token({ exp: Math.floor(Date.now() / 1000) + 3600 }), + delivery({ type: 'unknown.event' }) + ); + expect(result.dispatched).toBe(false); + expect(result.error).toBeUndefined(); + }); + + it('wraps thrown handler errors as HANDLER_FAILED', async () => { + const dispatcher = createWebhookDispatcher({ + policy: POLICY, + handlers: { 'invoice.paid': () => { throw new Error('boom'); } }, + }); + const result = await dispatcher.dispatch(token({ exp: Math.floor(Date.now() / 1000) + 3600 }), delivery()); + expect(result.dispatched).toBe(false); + expect(result.error?.code).toBe('HANDLER_FAILED'); + expect(result.error?.details.message).toBe('boom'); + }); + + it('rejects invalid deliveries before touching the token', async () => { + const dispatcher = createWebhookDispatcher(cfg(makeHooks())); + const result = await dispatcher.dispatch('garbage', delivery({ id: '' })); + expect(result.error?.code).toBe('INVALID_DELIVERY'); + }); +}); + +describe('dispatchWebhook convenience function', () => { + it('dispatches in one shot', async () => { + let called = false; + const result = await dispatchWebhook( + token({ exp: Math.floor(Date.now() / 1000) + 3600 }), + delivery(), + { policy: POLICY, handlers: { 'invoice.paid': () => { called = true; } } } + ); + expect(result.dispatched).toBe(true); + expect(called).toBe(true); + }); +}); diff --git a/backend/src/webhooks/__tests__/jwt.test.ts b/backend/src/webhooks/__tests__/jwt.test.ts new file mode 100644 index 00000000..1c35a815 --- /dev/null +++ b/backend/src/webhooks/__tests__/jwt.test.ts @@ -0,0 +1,329 @@ +/** + * backend/src/webhooks/__tests__/jwt.test.ts + * + * Unit tests for webhook JWT claim validation. + * Run with: npx jest backend/src/webhooks/__tests__/jwt.test.ts + */ + +import { + WebhookJwtError, + base64UrlDecodeToBytes, + utf8Decode, + decodeJsonSegment, + parseWebhookJwt, + normalizeOrigin, + compilePolicy, + validateWebhookClaims, + validateWebhookJwt, + enforceWebhookJwt, + createWebhookJwtValidator, + type WebhookJwtPolicy, + type WebhookJwtClaims, +} from '../jwt'; + +// ?? Test helpers ????????????????????????????????????????????????????????? + +function enc(obj: unknown): string { + const json = JSON.stringify(obj); + return encStr(json); +} + +function encStr(raw: string): string { + const bytes = new TextEncoder().encode(raw); + let binary = ''; + bytes.forEach((b) => { binary += String.fromCharCode(b); }); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +function makeToken( + claims: WebhookJwtClaims, + header: Record = { alg: 'HS256', typ: 'JWT' } +): string { + return `${enc(header)}.${enc(claims)}.c2lnbmF0dXJl`; +} + +const NOW = 1_700_000_000; // 2023-11-14T22:13:20Z + +const POLICY: WebhookJwtPolicy = { + audiences: ['webhook-prod', 'webhook-internal'], + allowedOrigins: ['https://billing.example.com', 'https://api.example.com/'], + issuer: 'https://issuer.example.com', + requireExpiration: true, + clockToleranceSeconds: 30, +}; + +function validClaims(overrides: Partial = {}): WebhookJwtClaims { + return { + aud: 'webhook-prod', + origin: 'https://billing.example.com', + iss: 'https://issuer.example.com', + exp: NOW + 600, + iat: NOW - 10, + sub: 'invoice-123', + jti: 'evt-1', + ...overrides, + }; +} + +// ?? Base64URL / UTF-8 ??????????????????????????????????????????????????? + +describe('Base64URL + UTF-8 decoding', () => { + it('round-trips ASCII', () => { + const bytes = base64UrlDecodeToBytes(encStr('hello world')); + expect(utf8Decode(bytes)).toBe('hello world'); + }); + + it('round-trips multi-byte UTF-8', () => { + const text = 'caf\u00e9 \u20ac \ud83d\ude00'; + expect(utf8Decode(base64UrlDecodeToBytes(encStr(text)))).toBe(text); + }); + + it('decodes Base64URL with standard padding removed', () => { + expect(utf8Decode(base64UrlDecodeToBytes('aGVsbG8'))).toBe('hello'); + }); + + it('rejects invalid Base64URL characters', () => { + expect(() => base64UrlDecodeToBytes('abc+def')).toThrow(WebhookJwtError); + }); + + it('decodes JSON segments into objects', () => { + expect(decodeJsonSegment(enc({ a: 1 }))).toEqual({ a: 1 }); + }); + + it('rejects non-object JSON segments', () => { + expect(() => decodeJsonSegment(enc([1, 2]))).toThrow(WebhookJwtError); + expect(() => decodeJsonSegment(enc('string'))).toThrow(WebhookJwtError); + }); +}); + +// ?? Parsing ????????????????????????????????????????????????????????????? + +describe('parseWebhookJwt', () => { + it('parses header, claims, signature and signing input', () => { + const token = makeToken(validClaims()); + const parsed = parseWebhookJwt(token); + expect(parsed.header.alg).toBe('HS256'); + expect(parsed.claims.aud).toBe('webhook-prod'); + expect(parsed.signature).toBe('c2lnbmF0dXJl'); + expect(parsed.signingInput.split('.')).toHaveLength(2); + }); + + it('rejects empty tokens', () => { + expect(() => parseWebhookJwt('')).toThrow(WebhookJwtError); + }); + + it('rejects tokens with wrong segment count', () => { + expect(() => parseWebhookJwt('a.b')).toThrow(WebhookJwtError); + expect(() => parseWebhookJwt('a.b.c.d')).toThrow(WebhookJwtError); + }); + + it('rejects tokens with empty segments', () => { + expect(() => parseWebhookJwt('a..c')).toThrow(WebhookJwtError); + }); + + it('rejects headers without alg', () => { + const token = makeToken(validClaims(), { typ: 'JWT' }); + expect(() => parseWebhookJwt(token)).toThrow(WebhookJwtError); + }); +}); + +// ?? Origin normalization ???????????????????????????????????????????????? + +describe('normalizeOrigin', () => { + it('lower-cases scheme and host', () => { + expect(normalizeOrigin('HTTPS://Billing.Example.com')).toBe('https://billing.example.com'); + }); + + it('strips trailing slashes', () => { + expect(normalizeOrigin('https://api.example.com///')).toBe('https://api.example.com'); + }); + + it('preserves an explicit port', () => { + expect(normalizeOrigin('http://localhost:3000')).toBe('http://localhost:3000'); + }); + + it('strips path, query and fragment', () => { + expect(normalizeOrigin('https://api.example.com/v1/webhook?x=1#f')).toBe('https://api.example.com'); + }); + + it('rejects non-http schemes', () => { + expect(() => normalizeOrigin('ftp://example.com')).toThrow(WebhookJwtError); + }); + + it('rejects relative values', () => { + expect(() => normalizeOrigin('example.com')).toThrow(WebhookJwtError); + }); +}); + +// ?? Policy compilation ?????????????????????????????????????????????????? + +describe('compilePolicy', () => { + it('fills defaults and normalizes origins', () => { + const policy = compilePolicy({ + audiences: ['a'], + allowedOrigins: ['https://A.Example.com/'], + }); + expect(policy.allowedOrigins).toEqual(['https://a.example.com']); + expect(policy.requireExpiration).toBe(true); + expect(policy.clockToleranceSeconds).toBe(30); + }); + + it('rejects empty audiences', () => { + expect(() => compilePolicy({ audiences: [], allowedOrigins: ['https://a.com'] })).toThrow(WebhookJwtError); + }); + + it('rejects empty origins', () => { + expect(() => compilePolicy({ audiences: ['a'], allowedOrigins: [] })).toThrow(WebhookJwtError); + }); + + it('rejects negative clock tolerance', () => { + expect(() => compilePolicy({ + audiences: ['a'], + allowedOrigins: ['https://a.com'], + clockToleranceSeconds: -1, + })).toThrow(WebhookJwtError); + }); +}); + +// ?? Claim validation ???????????????????????????????????????????????????? + +describe('validateWebhookClaims - happy path', () => { + it('accepts a fully valid token', () => { + const result = validateWebhookClaims(validClaims(), POLICY, NOW); + expect(result.valid).toBe(true); + expect(result.matchedAudience).toBe('webhook-prod'); + expect(result.normalizedOrigin).toBe('https://billing.example.com'); + }); + + it('accepts audience expressed as an array with one intersection', () => { + const claims = validClaims({ aud: ['other', 'webhook-internal'] }); + const result = validateWebhookClaims(claims, POLICY, NOW); + expect(result.valid).toBe(true); + expect(result.matchedAudience).toBe('webhook-internal'); + }); + + it('accepts an origin with a trailing slash in the claim', () => { + const claims = validClaims({ origin: 'https://API.EXAMPLE.COM/' }); + expect(validateWebhookClaims(claims, POLICY, NOW).valid).toBe(true); + }); + + it('accepts a token expiring within the clock tolerance', () => { + const claims = validClaims({ exp: NOW - 10 }); + expect(validateWebhookClaims(claims, POLICY, NOW).valid).toBe(true); + }); + + it('accepts missing exp when requireExpiration is false', () => { + const policy = { ...POLICY, requireExpiration: false }; + const claims = validClaims(); + delete claims.exp; + expect(validateWebhookClaims(claims, policy, NOW).valid).toBe(true); + }); +}); + +describe('validateWebhookClaims - failure modes', () => { + function codesFor(claims: WebhookJwtClaims, policy: WebhookJwtPolicy = POLICY): string | undefined { + return validateWebhookClaims(claims, policy, NOW).error?.code; + } + + it('rejects a missing audience', () => { + const claims = validClaims(); + delete claims.aud; + expect(codesFor(claims)).toBe('MISSING_AUDIENCE'); + }); + + it('rejects a wrong audience', () => { + expect(codesFor(validClaims({ aud: 'webhook-staging' }))).toBe('INVALID_AUDIENCE'); + }); + + it('rejects a missing origin', () => { + const claims = validClaims(); + delete claims.origin; + expect(codesFor(claims)).toBe('MISSING_ORIGIN'); + }); + + it('rejects a non-allow-listed origin', () => { + expect(codesFor(validClaims({ origin: 'https://evil.example.com' }))).toBe('INVALID_ORIGIN'); + }); + + it('rejects a missing issuer when required', () => { + const claims = validClaims(); + delete claims.iss; + expect(codesFor(claims)).toBe('MISSING_ISSUER'); + }); + + it('rejects a wrong issuer', () => { + expect(codesFor(validClaims({ iss: 'https://evil.example.com' }))).toBe('INVALID_ISSUER'); + }); + + it('rejects a missing expiry when required', () => { + const claims = validClaims(); + delete claims.exp; + expect(codesFor(claims)).toBe('MISSING_EXPIRY'); + }); + + it('rejects an expired token beyond tolerance', () => { + expect(codesFor(validClaims({ exp: NOW - 100 }))).toBe('TOKEN_EXPIRED'); + }); + + it('rejects a token that is not yet valid', () => { + expect(codesFor(validClaims({ nbf: NOW + 100 }))).toBe('TOKEN_NOT_YET_VALID'); + }); + + it('accepts nbf within tolerance', () => { + expect(codesFor(validClaims({ nbf: NOW + 10 }))).toBeUndefined(); + }); +}); + +// ?? Public validators ??????????????????????????????????????????????????? + +describe('validateWebhookJwt / enforceWebhookJwt', () => { + it('validates a compact token end-to-end', () => { + const result = validateWebhookJwt(makeToken(validClaims()), POLICY, NOW); + expect(result.valid).toBe(true); + }); + + it('returns a MALFORMED_TOKEN result for garbage input', () => { + expect(validateWebhookJwt('not-a-jwt', POLICY, NOW).error?.code).toBe('MALFORMED_TOKEN'); + }); + + it('enforce throws on a rejected token', () => { + expect(() => enforceWebhookJwt(makeToken(validClaims({ aud: 'bad' })), POLICY, NOW)).toThrow(WebhookJwtError); + }); + + it('enforce returns result for a valid token', () => { + expect(enforceWebhookJwt(makeToken(validClaims()), POLICY, NOW).valid).toBe(true); + }); +}); + +describe('createWebhookJwtValidator with hooks', () => { + function makeHooks() { + const calls: Array<{ name: string; labels?: Readonly> }> = []; + const warnings: Array> = []; + return { + calls, + warnings, + metrics: { increment: (name: string, labels?: Readonly>) => calls.push({ name, labels }) }, + logger: { + info: () => {}, + warn: (_m: string, ctx?: Readonly>) => warnings.push(ctx ?? {}), + }, + }; + } + + it('emits a valid metric and no warning on success', () => { + const hooks = makeHooks(); + const validator = createWebhookJwtValidator(POLICY, hooks); + expect(validator.validate(makeToken(validClaims()), NOW).valid).toBe(true); + expect(hooks.calls.some((c) => c.name === 'webhook.jwt.valid')).toBe(true); + expect(hooks.warnings).toHaveLength(0); + }); + + it('emits a rejected metric and warning on failure', () => { + const hooks = makeHooks(); + const validator = createWebhookJwtValidator(POLICY, hooks); + const result = validator.validate(makeToken(validClaims({ origin: 'https://evil.com' })), NOW); + expect(result.valid).toBe(false); + expect(hooks.calls.some((c) => c.name === 'webhook.jwt.rejected')).toBe(true); + expect(hooks.warnings).toHaveLength(1); + }); +}); diff --git a/backend/src/webhooks/dispatcher.ts b/backend/src/webhooks/dispatcher.ts new file mode 100644 index 00000000..bda7040e --- /dev/null +++ b/backend/src/webhooks/dispatcher.ts @@ -0,0 +1,235 @@ +/** + * backend/src/webhooks/dispatcher.ts + * + * Webhook dispatcher that gates every inbound webhook on validated JWT + * origin + audience claims (issue #2274). A delivery is only routed to a + * handler after the JWT envelope passes policy validation; the JOSE + * signature check remains the caller's responsibility and is represented + * by the injected `verifySignature` hook. + * + * Design rules: + * - Pure routing logic, no I/O. All side effects go through injected hooks. + * - Every decision (accept/reject) emits metrics and an audit log entry. + * - Typed `DispatchError` codes for stable observability and tests. + */ + +import { + compilePolicy, + createWebhookJwtValidator, + WebhookJwtError, + type WebhookJwtPolicy, + type WebhookJwtValidationResult, + type JwtValidationLogger, + type JwtValidationMetrics, +} from './jwt.ts'; + +// ?? Types ??????????????????????????????????????????????????????????????? + +export type DispatchErrorCode = + | 'JWT_REJECTED' + | 'SIGNATURE_INVALID' + | 'NO_HANDLER' + | 'HANDLER_FAILED' + | 'INVALID_DELIVERY' + | 'INVALID_CONFIG'; + +export class DispatchError extends Error { + readonly code: DispatchErrorCode; + readonly details: Readonly>; + + constructor( + code: DispatchErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'DispatchError'; + this.code = code; + this.details = details; + } +} + +export interface WebhookDelivery { + /** Stable event id, used for idempotency + audit correlation. */ + id: string; + /** Event type, e.g. `invoice.paid`. */ + type: string; + /** Emitting source system, for observability. */ + source: string; + /** Arbitrary event payload. */ + payload: Readonly>; +} + +export interface HandlerContext { + delivery: WebhookDelivery; + claims: WebhookJwtValidationResult['claims']; + matchedAudience?: string; + normalizedOrigin?: string; +} + +export type WebhookHandler = (context: HandlerContext) => void | Promise; + +export interface DispatcherHooks { + metrics?: JwtValidationMetrics; + logger?: JwtValidationLogger; + /** + * Verify the cryptographic signature over `signingInput`. Return true to + * accept. Injected so this module stays dependency-free and testable. + */ + verifySignature?: (signingInput: string, signature: string) => boolean | Promise; + /** Parse the token into signing input + signature for the JOSE layer. */ + splitToken?: (token: string) => { signingInput: string; signature: string }; +} + +export interface DispatchResult { + dispatched: boolean; + eventId?: string; + handler?: string; + error?: DispatchError; +} + +export interface DispatcherConfig { + policy: WebhookJwtPolicy; + handlers: Readonly>; + hooks?: DispatcherHooks; + /** Reject deliveries with no matching handler. Default true. */ + strictHandler?: boolean; +} + +// ?? Dispatcher factory ??????????????????????????????????????????????????? + +/** Validate the shape of a delivery object. */ +export function validateDelivery(delivery: WebhookDelivery): void { + if (!delivery || typeof delivery !== 'object') { + throw new DispatchError('INVALID_DELIVERY', 'Delivery must be an object'); + } + if (typeof delivery.id !== 'string' || delivery.id === '') { + throw new DispatchError('INVALID_DELIVERY', 'Delivery.id must be a non-empty string'); + } + if (typeof delivery.type !== 'string' || delivery.type === '') { + throw new DispatchError('INVALID_DELIVERY', 'Delivery.type must be a non-empty string'); + } + if (typeof delivery.source !== 'string' || delivery.source === '') { + throw new DispatchError('INVALID_DELIVERY', 'Delivery.source must be a non-empty string'); + } + if (delivery.payload === null || typeof delivery.payload !== 'object') { + throw new DispatchError('INVALID_DELIVERY', 'Delivery.payload must be an object'); + } +} + +/** Split a compact token without a full parse (for the signature hook). */ +export function defaultSplitToken(token: string): { signingInput: string; signature: string } { + const parts = token.trim().split('.'); + if (parts.length !== 3) { + throw new DispatchError('JWT_REJECTED', 'Token is not a compact JWS'); + } + return { signingInput: `${parts[0]}.${parts[1]}`, signature: parts[2] }; +} + +/** + * Create a dispatcher bound to a JWT policy and a handler map. + */ +export function createWebhookDispatcher(config: DispatcherConfig) { + const compiled = compilePolicy(config.policy); + const validator = createWebhookJwtValidator(compiled, { + metrics: config.hooks?.metrics, + logger: config.hooks?.logger, + }); + const handlers: Readonly> = { ...(config.handlers ?? {}) }; + const strictHandler = config.strictHandler ?? true; + + async function dispatch(token: string, delivery: WebhookDelivery): Promise { + const metrics = config.hooks?.metrics; + const logger = config.hooks?.logger; + try { + validateDelivery(delivery); + + // 1. Claims gate (audience + origin). + const jwt = validator.validate(token); + if (!jwt.valid) { + const err = new DispatchError('JWT_REJECTED', 'Webhook JWT claim validation failed', { + code: jwt.error?.code, + eventId: delivery.id, + }); + metrics?.increment('webhook.dispatch.rejected', { reason: 'jwt', code: jwt.error?.code ?? '' }); + logger?.warn('Webhook rejected: JWT claims invalid', { eventId: delivery.id, code: jwt.error?.code }); + return { dispatched: false, error: err }; + } + + // 2. Signature gate (delegated). + if (config.hooks?.verifySignature) { + const parts = (config.hooks.splitToken ?? defaultSplitToken)(token); + const ok = await config.hooks.verifySignature(parts.signingInput, parts.signature); + if (!ok) { + const err = new DispatchError('SIGNATURE_INVALID', 'Webhook JWT signature is invalid', { + eventId: delivery.id, + }); + metrics?.increment('webhook.dispatch.rejected', { reason: 'signature' }); + logger?.warn('Webhook rejected: signature invalid', { eventId: delivery.id }); + return { dispatched: false, error: err }; + } + } + + // 3. Handler lookup. + const handler = handlers[delivery.type]; + if (!handler) { + if (!strictHandler) { + metrics?.increment('webhook.dispatch.skipped', { type: delivery.type }); + logger?.info('Webhook skipped: no handler', { eventId: delivery.id, type: delivery.type }); + return { dispatched: false, eventId: delivery.id }; + } + const err = new DispatchError('NO_HANDLER', `No handler registered for ${delivery.type}`, { + eventId: delivery.id, + }); + metrics?.increment('webhook.dispatch.rejected', { reason: 'no_handler' }); + logger?.warn('Webhook rejected: no handler', { eventId: delivery.id, type: delivery.type }); + return { dispatched: false, error: err }; + } + + // 4. Invoke handler. + await handler({ + delivery, + claims: jwt.claims, + matchedAudience: jwt.matchedAudience, + normalizedOrigin: jwt.normalizedOrigin, + }); + metrics?.increment('webhook.dispatch.accepted', { type: delivery.type }); + logger?.info('Webhook dispatched', { eventId: delivery.id, type: delivery.type }); + return { dispatched: true, eventId: delivery.id, handler: delivery.type }; + } catch (err) { + if (err instanceof DispatchError) { + return { dispatched: false, error: err }; + } + if (err instanceof WebhookJwtError) { + return { dispatched: false, error: new DispatchError('JWT_REJECTED', err.message, { code: err.code }) }; + } + const wrapped = new DispatchError('HANDLER_FAILED', 'Webhook handler threw an error', { + eventId: delivery.id, + message: err instanceof Error ? err.message : String(err), + }); + metrics?.increment('webhook.dispatch.failed', { type: delivery.type }); + logger?.warn('Webhook handler failed', { eventId: delivery.id }); + return { dispatched: false, error: wrapped }; + } + } + + return { + dispatch, + registerHandler(type: string, handler: WebhookHandler): void { + (handlers as Record)[type] = handler; + }, + handlerTypes(): string[] { + return Object.keys(handlers); + }, + policy: compiled, + }; +} + +/** Convenience one-shot dispatch. */ +export function dispatchWebhook( + token: string, + delivery: WebhookDelivery, + config: DispatcherConfig +): Promise { + return createWebhookDispatcher(config).dispatch(token, delivery); +} diff --git a/backend/src/webhooks/jwt.ts b/backend/src/webhooks/jwt.ts new file mode 100644 index 00000000..a50cf031 --- /dev/null +++ b/backend/src/webhooks/jwt.ts @@ -0,0 +1,402 @@ +/** + * backend/src/webhooks/jwt.ts + * + * Webhook JWT claim validation for the backend. Enforces that every inbound + * webhook JWT carries a correct `aud` (audience) and `origin` claim, so a + * token minted for one webhook consumer cannot be replayed against another + * origin or endpoint. + * + * Design rules (issue #2274): + * - Pure functions only: no I/O, no network calls, no clock reads unless a + * `now` argument is supplied (defaults to Date.now in the validator only). + * - Zero dependencies: Base64URL + UTF-8 decoded with a small lookup table. + * - Every rejection is a typed `WebhookJwtError` with a stable `code`. + * - Audience may be a string or string[]; any intersection with the policy + * audiences is accepted. Origin is normalized (scheme + host + port, + * lower-cased, trailing slashes removed) before exact comparison. + * - Observability hooks for metrics and audit logging on every decision. + * + * Signature verification is intentionally delegated to the caller's JOSE + * layer: this module validates the *claims* envelope only. The dispatcher + * must still verify the cryptographic signature before trusting delivery. + */ + +// ?? Types ??????????????????????????????????????????????????????????????? + +export type WebhookJwtErrorCode = + | 'MALFORMED_TOKEN' + | 'INVALID_BASE64URL' + | 'INVALID_JSON' + | 'MISSING_AUDIENCE' + | 'INVALID_AUDIENCE' + | 'MISSING_ORIGIN' + | 'INVALID_ORIGIN' + | 'MISSING_ISSUER' + | 'INVALID_ISSUER' + | 'MISSING_EXPIRY' + | 'TOKEN_EXPIRED' + | 'TOKEN_NOT_YET_VALID' + | 'INVALID_CONFIG'; + +export class WebhookJwtError extends Error { + readonly code: WebhookJwtErrorCode; + readonly details: Readonly>; + + constructor( + code: WebhookJwtErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'WebhookJwtError'; + this.code = code; + this.details = details; + } +} + +export interface WebhookJwtPolicy { + /** Expected audience value(s). Token `aud` must intersect this list. */ + audiences: readonly string[]; + /** Allowed origin URL(s). Token `origin` must normalize-match one. */ + allowedOrigins: readonly string[]; + /** Expected issuer (`iss`), if the policy requires one. */ + issuer?: string; + /** Require an `exp` claim. Default true. */ + requireExpiration?: boolean; + /** Clock-skew tolerance in seconds. Default 30. */ + clockToleranceSeconds?: number; +} + +export interface WebhookJwtClaims { + aud?: string | readonly string[]; + origin?: string; + iss?: string; + exp?: number; + nbf?: number; + iat?: number; + sub?: string; + jti?: string; + [key: string]: unknown; +} + +export interface WebhookJwtHeader { + alg: string; + typ?: string; + kid?: string; + [key: string]: unknown; +} + +export interface ParsedWebhookJwt { + header: WebhookJwtHeader; + claims: WebhookJwtClaims; + /** Raw (undecoded) signature segment, retained for the JOSE layer. */ + signature: string; + /** Exact signing input `header.payload`, for the JOSE layer. */ + signingInput: string; +} + +export interface WebhookJwtValidationResult { + valid: boolean; + claims?: WebhookJwtClaims; + normalizedOrigin?: string; + matchedAudience?: string; + error?: WebhookJwtError; +} + +export interface JwtValidationMetrics { + /** e.g. increment('webhook.jwt.rejected', { code }) */ + increment(name: string, labels?: Readonly>): void; +} + +export interface JwtValidationLogger { + info(message: string, context?: Readonly>): void; + warn(message: string, context?: Readonly>): void; +} + +// ?? Base64URL / UTF-8 ??????????????????????????????????????????????????? + +const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; + +/** Decode a Base64URL string into raw bytes (pure JS, no Buffer/atob). */ +export function base64UrlDecodeToBytes(input: string): Uint8Array { + if (typeof input !== 'string') { + throw new WebhookJwtError('INVALID_BASE64URL', 'Base64URL input must be a string'); + } + const clean = input.trim().replace(/=+$/, ''); + const bytes: number[] = []; + let buffer = 0; + let bits = 0; + for (let i = 0; i < clean.length; i += 1) { + const idx = B64URL.indexOf(clean[i]); + if (idx === -1) { + throw new WebhookJwtError('INVALID_BASE64URL', `Invalid Base64URL character at index ${i}`); + } + buffer = (buffer << 6) | idx; + bits += 6; + if (bits >= 8) { + bits -= 8; + bytes.push((buffer >> bits) & 0xff); + } + } + return new Uint8Array(bytes); +} + +/** Decode raw bytes into a UTF-8 string (pure JS). */ +export function utf8Decode(bytes: Uint8Array): string { + let out = ''; + let i = 0; + while (i < bytes.length) { + const b = bytes[i]; + if (b < 0x80) { + out += String.fromCharCode(b); + i += 1; + } else if ((b & 0xe0) === 0xc0) { + out += String.fromCharCode(((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f)); + i += 2; + } else if ((b & 0xf0) === 0xe0) { + out += String.fromCharCode( + ((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f) + ); + i += 3; + } else if ((b & 0xf8) === 0xf0) { + let cp = + ((b & 0x07) << 18) | + ((bytes[i + 1] & 0x3f) << 12) | + ((bytes[i + 2] & 0x3f) << 6) | + (bytes[i + 3] & 0x3f); + // Astral code points must be emitted as a UTF-16 surrogate pair. + cp -= 0x10000; + out += String.fromCharCode(0xd800 + (cp >> 10), 0xdc00 + (cp & 0x3ff)); + i += 4; + } else { + throw new WebhookJwtError('INVALID_BASE64URL', 'Invalid UTF-8 byte sequence'); + } + } + return out; +} + +/** Decode a Base64URL JSON segment into a plain object. */ +export function decodeJsonSegment(segment: string): Record { + const json = utf8Decode(base64UrlDecodeToBytes(segment)); + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + throw new WebhookJwtError('INVALID_JSON', 'JWT segment is not valid JSON'); + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new WebhookJwtError('INVALID_JSON', 'JWT segment must be a JSON object'); + } + return parsed as Record; +} + +// ?? Parsing ????????????????????????????????????????????????????????????? + +/** Split and decode a compact JWT without verifying the signature. */ +export function parseWebhookJwt(token: string): ParsedWebhookJwt { + if (typeof token !== 'string' || token.trim() === '') { + throw new WebhookJwtError('MALFORMED_TOKEN', 'Token must be a non-empty string'); + } + const parts = token.trim().split('.'); + if (parts.length !== 3 || parts.some((p) => p === '')) { + throw new WebhookJwtError( + 'MALFORMED_TOKEN', + 'Token must have exactly three non-empty segments (header.payload.signature)' + ); + } + const [headerSeg, payloadSeg, signature] = parts; + const header = decodeJsonSegment(headerSeg) as unknown as WebhookJwtHeader; + if (typeof header.alg !== 'string' || header.alg === '') { + throw new WebhookJwtError('INVALID_JSON', 'JWT header must include a non-empty alg'); + } + const claims = decodeJsonSegment(payloadSeg) as unknown as WebhookJwtClaims; + return { + header, + claims, + signature, + signingInput: `${headerSeg}.${payloadSeg}`, + }; +} + +// ?? Claim validation ???????????????????????????????????????????????????? + +/** Normalize an origin to `scheme://host[:port]`, lower-cased. */ +export function normalizeOrigin(value: string): string { + if (typeof value !== 'string' || value.trim() === '') { + throw new WebhookJwtError('INVALID_ORIGIN', 'Origin claim must be a non-empty string'); + } + const trimmed = value.trim().replace(/\/+$/, ''); + const match = /^([a-z][a-z0-9+.-]*):\/\/([^/?#]+)(.*)$/i.exec(trimmed); + if (!match) { + throw new WebhookJwtError('INVALID_ORIGIN', `Origin is not an absolute URL: ${value}`); + } + const scheme = match[1].toLowerCase(); + if (scheme !== 'http' && scheme !== 'https') { + throw new WebhookJwtError('INVALID_ORIGIN', `Origin scheme must be http or https: ${scheme}`); + } + return `${scheme}://${match[2].toLowerCase()}`; +} + +/** Validate a compiled policy's shape. */ +export function compilePolicy(policy: WebhookJwtPolicy): WebhookJwtPolicy { + if (!policy || !Array.isArray(policy.audiences) || policy.audiences.length === 0) { + throw new WebhookJwtError('INVALID_CONFIG', 'Policy must define at least one audience'); + } + if (!Array.isArray(policy.allowedOrigins) || policy.allowedOrigins.length === 0) { + throw new WebhookJwtError('INVALID_CONFIG', 'Policy must define at least one allowed origin'); + } + const tolerance = policy.clockToleranceSeconds ?? 30; + if (!Number.isFinite(tolerance) || tolerance < 0) { + throw new WebhookJwtError('INVALID_CONFIG', 'clockToleranceSeconds must be a non-negative number'); + } + const normalizedOrigins = policy.allowedOrigins.map((o) => normalizeOrigin(o)); + return { + ...policy, + allowedOrigins: normalizedOrigins, + requireExpiration: policy.requireExpiration ?? true, + clockToleranceSeconds: tolerance, + }; +} + +function claimAudiences(aud: string | readonly string[] | undefined): string[] { + if (typeof aud === 'string') return [aud]; + if (Array.isArray(aud)) return aud.filter((a): a is string => typeof a === 'string'); + return []; +} + +/** + * Validate decoded claims against a compiled policy. Pure: `nowSeconds` is + * supplied by the caller so tests are deterministic. + */ +export function validateWebhookClaims( + claims: WebhookJwtClaims, + policy: WebhookJwtPolicy, + nowSeconds: number +): WebhookJwtValidationResult { + try { + const compiled = compilePolicy(policy); + + // audience + const audiences = claimAudiences(claims.aud); + if (audiences.length === 0) { + throw new WebhookJwtError('MISSING_AUDIENCE', 'JWT is missing an aud claim'); + } + const matchedAudience = audiences.find((a) => compiled.audiences.includes(a)); + if (matchedAudience === undefined) { + throw new WebhookJwtError('INVALID_AUDIENCE', 'JWT aud does not match any policy audience', { + received: audiences, + }); + } + + // origin + if (claims.origin === undefined || claims.origin === null) { + throw new WebhookJwtError('MISSING_ORIGIN', 'JWT is missing an origin claim'); + } + const normalizedOrigin = normalizeOrigin(claims.origin); + if (!compiled.allowedOrigins.includes(normalizedOrigin)) { + throw new WebhookJwtError('INVALID_ORIGIN', 'JWT origin is not in the allow-list', { + received: normalizedOrigin, + }); + } + + // issuer (optional) + if (compiled.issuer !== undefined) { + if (typeof claims.iss !== 'string' || claims.iss === '') { + throw new WebhookJwtError('MISSING_ISSUER', 'JWT is missing an iss claim'); + } + if (claims.iss !== compiled.issuer) { + throw new WebhookJwtError('INVALID_ISSUER', 'JWT iss does not match policy issuer', { + received: claims.iss, + }); + } + } + + // temporal claims + const requireExp = compiled.requireExpiration ?? true; + const tolerance = compiled.clockToleranceSeconds ?? 30; + if (claims.exp === undefined && requireExp) { + throw new WebhookJwtError('MISSING_EXPIRY', 'JWT is missing an exp claim'); + } + if (typeof claims.exp === 'number') { + if (nowSeconds > claims.exp + tolerance) { + throw new WebhookJwtError('TOKEN_EXPIRED', 'JWT has expired', { + exp: claims.exp, + now: nowSeconds, + }); + } + } + if (typeof claims.nbf === 'number' && nowSeconds + tolerance < claims.nbf) { + throw new WebhookJwtError('TOKEN_NOT_YET_VALID', 'JWT is not yet valid', { + nbf: claims.nbf, + now: nowSeconds, + }); + } + + return { valid: true, claims, normalizedOrigin, matchedAudience }; + } catch (err) { + if (err instanceof WebhookJwtError) { + return { valid: false, error: err }; + } + throw err; + } +} + +/** Parse + validate a compact webhook JWT. Never throws on claim failures. */ +export function validateWebhookJwt( + token: string, + policy: WebhookJwtPolicy, + nowSeconds: number = Math.floor(Date.now() / 1000) +): WebhookJwtValidationResult { + let parsed: ParsedWebhookJwt; + try { + parsed = parseWebhookJwt(token); + } catch (err) { + if (err instanceof WebhookJwtError) { + return { valid: false, error: err }; + } + throw err; + } + return validateWebhookClaims(parsed.claims, policy, nowSeconds); +} + +/** Strict variant: throws `WebhookJwtError` on any claim failure. */ +export function enforceWebhookJwt( + token: string, + policy: WebhookJwtPolicy, + nowSeconds?: number +): WebhookJwtValidationResult { + const result = validateWebhookJwt(token, policy, nowSeconds); + if (!result.valid && result.error) throw result.error; + return result; +} + +/** Build a validator bound to a policy, with metrics + logging hooks. */ +export function createWebhookJwtValidator( + policy: WebhookJwtPolicy, + hooks?: { metrics?: JwtValidationMetrics; logger?: JwtValidationLogger } +) { + const compiled = compilePolicy(policy); + return { + policy: compiled, + validate(token: string, nowSeconds?: number): WebhookJwtValidationResult { + const result = validateWebhookJwt(token, compiled, nowSeconds); + if (hooks?.metrics) { + if (result.valid) { + hooks.metrics.increment('webhook.jwt.valid', { audience: result.matchedAudience ?? '' }); + } else { + hooks.metrics.increment('webhook.jwt.rejected', { code: result.error?.code ?? 'UNKNOWN' }); + } + } + if (hooks?.logger && !result.valid) { + hooks.logger.warn('Webhook JWT claim validation failed', { + code: result.error?.code, + details: result.error?.details, + }); + } + return result; + }, + enforce(token: string, nowSeconds?: number): WebhookJwtValidationResult { + return enforceWebhookJwt(token, compiled, nowSeconds); + }, + }; +}