From f3d5e1d8328d57b4d1a799b20b329a2a61cd3042 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:50:24 +0000 Subject: [PATCH 1/5] Add error envelope and request IDs for new API routes New app API routes (movement writes via the API) need one error format, traceable requests and token auth that yields an actor. functions/api/http/ adds an ApiError with the {error:{code,message, details}} envelope and its status mapping, an X-Request-Id middleware, an async route wrapper that logs internal errors without leaking them, and appAuth, which verifies the ID token (checkRevoked) and answers 401 for rejected tokens but 500 for infrastructure faults such as unreachable signing keys. Existing routes are not wired to it. The new specs run in the node environment, so the root jest setup only sets the language in localStorage where localStorage exists. --- functions/api/http/appAuth.js | 126 ++++++++++ functions/api/http/appAuth.spec.js | 318 ++++++++++++++++++++++++++ functions/api/http/asyncRoute.js | 21 ++ functions/api/http/asyncRoute.spec.js | 138 +++++++++++ functions/api/http/errors.js | 116 ++++++++++ functions/api/http/errors.spec.js | 270 ++++++++++++++++++++++ functions/api/http/requestId.js | 24 ++ functions/api/http/requestId.spec.js | 90 ++++++++ functions/api/http/testing/listen.js | 19 ++ test/jestPolyfills.js | 7 +- 10 files changed, 1127 insertions(+), 2 deletions(-) create mode 100644 functions/api/http/appAuth.js create mode 100644 functions/api/http/appAuth.spec.js create mode 100644 functions/api/http/asyncRoute.js create mode 100644 functions/api/http/asyncRoute.spec.js create mode 100644 functions/api/http/errors.js create mode 100644 functions/api/http/errors.spec.js create mode 100644 functions/api/http/requestId.js create mode 100644 functions/api/http/requestId.spec.js create mode 100644 functions/api/http/testing/listen.js diff --git a/functions/api/http/appAuth.js b/functions/api/http/appAuth.js new file mode 100644 index 00000000..0b87ed12 --- /dev/null +++ b/functions/api/http/appAuth.js @@ -0,0 +1,126 @@ +'use strict'; + +const { getAuth } = require('firebase-admin/auth'); +const { getDatabase } = require('firebase-admin/database'); +const logger = require('firebase-functions/logger'); +const { ApiError, sendError } = require('./errors'); + +// Shared sessions sign in with a fixed uid (functions/auth/modes). +const GUEST_UID = 'guest'; +const KIOSK_UID = 'kiosk'; + +// Characters that are not allowed in a Realtime Database key. +const INVALID_KEY_CHARS = /[.#$[\]/]/; + +// The token of an `Authorization: Bearer ` header; the scheme is +// case-insensitive (RFC 7235). +function bearerToken(header) { + const match = /^bearer\s+(\S+)\s*$/i.exec(header || ''); + return match ? match[1] : null; +} + +// Codes with which verifyIdToken rejects the token itself (malformed or +// forged, expired, revoked, disabled or deleted user). Every other error, +// e.g. auth/quota-exceeded or auth/insufficient-permission of the +// revocation lookup, is our problem and not the caller's. +const TOKEN_REJECTION_CODES = new Set([ + 'auth/argument-error', + 'auth/id-token-expired', + 'auth/id-token-revoked', + 'auth/user-disabled', + 'auth/user-not-found', +]); + +// firebase-admin also reports a failure to fetch Google's signing keys as +// auth/argument-error. Its message then starts with "Error fetching ..." +// (bad response) or "Error while making request: ..." (network failure). +const KEY_FETCH_FAILURE = /^Error (fetching|while making request)/; + +function isKeyFetchFailure(error) { + return ( + error.code === 'auth/argument-error' && + KEY_FETCH_FAILURE.test(String(error.message)) + ); +} + +function isTokenRejection(error) { + return ( + Boolean(error) && + TOKEN_REJECTION_CODES.has(error.code) && + !isKeyFetchFailure(error) + ); +} + +// Same check as the database rules: /admins/ === true. +async function isAdmin(db, uid) { + if (!uid || INVALID_KEY_CHARS.test(uid)) { + return false; + } + const snapshot = await db.ref(`/admins/${uid}`).once('value'); + return snapshot.val() === true; +} + +async function resolveActor(decodedToken, db) { + const { uid } = decodedToken; + return { + uid, + email: typeof decodedToken.email === 'string' ? decodedToken.email : null, + isAdmin: await isAdmin(db, uid), + isGuest: uid === GUEST_UID, + isKiosk: uid === KIOSK_UID, + }; +} + +function rejectUnauthenticated(req, res, message) { + res.set('WWW-Authenticate', 'Bearer'); + sendError(req, res, new ApiError('unauthenticated', message)); +} + +async function verifyToken(auth, idToken) { + try { + return { decoded: await auth.verifyIdToken(idToken, true) }; + } catch (error) { + if (isTokenRejection(error)) { + return { rejection: error.code }; + } + throw error; + } +} + +/** + * Middleware for routes the web app calls with the user's Firebase ID token + * (`Authorization: Bearer `). Revoked tokens and disabled users are + * rejected (checkRevoked). On success req.actor is + * {uid, email|null, isAdmin, isGuest, isKiosk}. A missing or rejected + * token is answered 401 in the error envelope; infrastructure faults + * (signing keys or revocation lookup unavailable, failed admin lookup) are + * logged and answered 500, so an outage does not look like a sign-out. + */ +function appAuth({ auth = getAuth, db = getDatabase } = {}) { + return async (req, res, next) => { + const idToken = bearerToken(req.get('Authorization')); + if (!idToken) { + return rejectUnauthenticated(req, res, 'Authentication required'); + } + + let actor; + try { + const { decoded, rejection } = await verifyToken(auth(), idToken); + if (rejection) { + logger.info('ID token rejected', { + requestId: req.requestId, + reason: rejection, + }); + return rejectUnauthenticated(req, res, 'Invalid or expired ID token'); + } + actor = await resolveActor(decoded, db()); + } catch (error) { + return sendError(req, res, error); + } + + req.actor = actor; + return next(); + }; +} + +module.exports = { appAuth, resolveActor, bearerToken, GUEST_UID, KIOSK_UID }; diff --git a/functions/api/http/appAuth.spec.js b/functions/api/http/appAuth.spec.js new file mode 100644 index 00000000..c7702cc3 --- /dev/null +++ b/functions/api/http/appAuth.spec.js @@ -0,0 +1,318 @@ +/** @jest-environment node */ +'use strict'; + +jest.mock('firebase-functions/logger', () => ({ error: jest.fn(), info: jest.fn() })); +jest.mock('firebase-admin/auth', () => ({ getAuth: jest.fn() })); +jest.mock('firebase-admin/database', () => ({ getDatabase: jest.fn() })); + +const express = require('express'); +const logger = require('firebase-functions/logger'); +const { getAuth } = require('firebase-admin/auth'); +const { getDatabase } = require('firebase-admin/database'); +const { appAuth, resolveActor, bearerToken } = require('./appAuth'); +const { requestId } = require('./requestId'); +const { listen } = require('./testing/listen'); + +function authError(code, message = `Firebase: ${code}`) { + const error = new Error(message); + error.code = code; + return error; +} + +// Tokens are "token-"; admins is the content of /admins. +function fakeAuth({ error } = {}) { + return { + verifyIdToken: jest.fn(async token => { + if (error) { + throw error; + } + if (!token.startsWith('token-')) { + throw authError('auth/argument-error'); + } + const uid = token.slice('token-'.length); + return uid.startsWith('anon') + ? { uid } + : { uid, email: `${uid}@example.ch` }; + }), + }; +} + +function fakeDb(admins = {}, { error } = {}) { + return { + ref: jest.fn(path => ({ + once: async () => { + if (error) { + throw error; + } + const uid = path.replace('/admins/', ''); + return { val: () => (uid in admins ? admins[uid] : null) }; + }, + })), + }; +} + +describe('functions', () => { + describe('api/http/appAuth', () => { + beforeEach(() => jest.clearAllMocks()); + + describe('bearerToken', () => { + it.each([ + ['Bearer abc', 'abc'], + ['bearer abc', 'abc'], + ['BEARER abc ', 'abc'], + ])('reads %j', (header, token) => { + expect(bearerToken(header)).toBe(token); + }); + + it.each([undefined, '', 'Bearer', 'Bearer ', 'Basic abc', 'Bearer a b'])( + 'rejects %j', + header => { + expect(bearerToken(header)).toBeNull(); + } + ); + }); + + describe('resolveActor', () => { + it('describes a pilot', async () => { + const db = fakeDb(); + + expect( + await resolveActor({ uid: 'u1', email: 'pilot@example.ch' }, db) + ).toEqual({ + uid: 'u1', + email: 'pilot@example.ch', + isAdmin: false, + isGuest: false, + isKiosk: false, + }); + expect(db.ref).toHaveBeenCalledWith('/admins/u1'); + }); + + it('marks admins only for /admins/ === true', async () => { + const db = fakeDb({ a1: true, a2: 'true', a3: 1 }); + + expect((await resolveActor({ uid: 'a1' }, db)).isAdmin).toBe(true); + expect((await resolveActor({ uid: 'a2' }, db)).isAdmin).toBe(false); + expect((await resolveActor({ uid: 'a3' }, db)).isAdmin).toBe(false); + }); + + it.each([ + ['guest', { isGuest: true, isKiosk: false }], + ['kiosk', { isGuest: false, isKiosk: true }], + ])('recognizes the %s session', async (uid, flags) => { + expect(await resolveActor({ uid }, fakeDb())).toEqual({ + uid, + email: null, + isAdmin: false, + ...flags, + }); + }); + + it('does not read paths for uids that are no database key', async () => { + const db = fakeDb(); + + const actor = await resolveActor({ uid: 'x/../admins' }, db); + + expect(actor.isAdmin).toBe(false); + expect(db.ref).not.toHaveBeenCalled(); + }); + + it('uses null for a missing or non-string email', async () => { + expect( + (await resolveActor({ uid: 'u', email: 42 }, fakeDb())).email + ).toBeNull(); + }); + }); + + describe('middleware', () => { + let auth; + let db; + let server; + let route; + + beforeAll(async () => { + const app = express(); + app.use(requestId); + app.get( + '/me', + appAuth({ auth: () => auth, db: () => db }), + (req, res, next) => route(req, res, next) + ); + server = await listen(app); + }); + + afterAll(() => server.close()); + + beforeEach(() => { + auth = fakeAuth(); + db = fakeDb({ admin1: true }); + route = (req, res) => res.json(req.actor); + }); + + const get = authorization => + server.request('/me', { + headers: authorization + ? { Authorization: authorization, 'X-Request-Id': 'trace-0123456789' } + : {}, + }); + + const expectUnauthenticated = async (response, message) => { + expect(response.status).toBe(401); + expect(response.headers.get('www-authenticate')).toBe('Bearer'); + expect(response.headers.get('x-request-id')).toBeTruthy(); + expect(await response.json()).toEqual({ + error: { code: 'unauthenticated', message }, + }); + }; + + it('sets req.actor for a valid token, checking revocation', async () => { + const response = await get('Bearer token-admin1'); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + uid: 'admin1', + email: 'admin1@example.ch', + isAdmin: true, + isGuest: false, + isKiosk: false, + }); + expect(auth.verifyIdToken).toHaveBeenCalledWith('token-admin1', true); + }); + + it('answers 401 without an Authorization header', async () => { + await expectUnauthenticated(await get(), 'Authentication required'); + expect(auth.verifyIdToken).not.toHaveBeenCalled(); + }); + + it('answers 401 for another scheme', async () => { + await expectUnauthenticated( + await get('Basic dXNlcjpwYXNz'), + 'Authentication required' + ); + }); + + it.each([ + 'auth/argument-error', + 'auth/id-token-expired', + 'auth/id-token-revoked', + 'auth/user-disabled', + 'auth/user-not-found', + ])('answers 401 when the token is rejected with %s', async code => { + auth = fakeAuth({ error: authError(code) }); + + await expectUnauthenticated( + await get('Bearer token-u1'), + 'Invalid or expired ID token' + ); + expect(logger.info).toHaveBeenCalledWith('ID token rejected', { + requestId: 'trace-0123456789', + reason: code, + }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + // Messages as firebase-admin words key-fetch failures (checked + // against a real verifyIdToken with an unreachable cert URL). + it.each([ + ['auth/internal-error', authError('auth/internal-error')], + [ + 'an unreachable cert endpoint', + authError( + 'auth/argument-error', + 'Error while making request: getaddrinfo ENOTFOUND ' + + 'www.googleapis.com. Error code: ENOTFOUND' + ), + ], + [ + 'a failing cert endpoint', + authError( + 'auth/argument-error', + 'Error fetching public keys for Google certs: down' + ), + ], + ['auth/quota-exceeded', authError('auth/quota-exceeded')], + [ + 'auth/insufficient-permission', + authError('auth/insufficient-permission'), + ], + ['auth/project-not-found', authError('auth/project-not-found')], + ['auth/invalid-credential', authError('auth/invalid-credential')], + ['an error without code', new Error('socket hang up')], + ])('answers 500 when verification fails with %s', async (_, error) => { + auth = fakeAuth({ error }); + + const response = await get('Bearer token-u1'); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: { code: 'internal', message: 'Internal error' }, + }); + expect(logger.error).toHaveBeenCalledWith( + 'API request failed', + expect.objectContaining({ requestId: 'trace-0123456789' }) + ); + expect(logger.info).not.toHaveBeenCalled(); + }); + + it('answers 500 when the admin lookup fails', async () => { + db = fakeDb({}, { error: new Error('permission denied at /admins') }); + + const response = await get('Bearer token-u1'); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: { code: 'internal', message: 'Internal error' }, + }); + expect(logger.error).toHaveBeenCalledWith( + 'API request failed', + expect.objectContaining({ requestId: 'trace-0123456789' }) + ); + }); + + it('does not catch errors of the following handlers', async () => { + route = () => { + throw new Error('route failure'); + }; + + const response = await get('Bearer token-u1'); + + // Express' own final handler, not the envelope of appAuth. + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).not.toMatch(/json/); + }); + + it('describes guest and kiosk sessions', async () => { + const guest = await (await get('Bearer token-guest')).json(); + const kiosk = await (await get('Bearer token-kiosk')).json(); + + expect(guest).toMatchObject({ uid: 'guest', isGuest: true, isKiosk: false }); + expect(kiosk).toMatchObject({ uid: 'kiosk', isGuest: false, isKiosk: true }); + }); + + it('gives a null email for tokens without one', async () => { + const actor = await (await get('Bearer token-anon1')).json(); + + expect(actor.email).toBeNull(); + }); + }); + + describe('defaults', () => { + it('uses the Firebase Admin SDK', async () => { + const auth = fakeAuth(); + getAuth.mockReturnValue(auth); + getDatabase.mockReturnValue(fakeDb()); + const req = { + get: () => 'Bearer token-u1', + requestId: 'r', + }; + const next = jest.fn(); + + await appAuth()(req, {}, next); + + expect(auth.verifyIdToken).toHaveBeenCalledWith('token-u1', true); + expect(req.actor.uid).toBe('u1'); + expect(next).toHaveBeenCalled(); + }); + }); + }); +}); diff --git a/functions/api/http/asyncRoute.js b/functions/api/http/asyncRoute.js new file mode 100644 index 00000000..f689efe0 --- /dev/null +++ b/functions/api/http/asyncRoute.js @@ -0,0 +1,21 @@ +'use strict'; + +const { sendError } = require('./errors'); + +/** + * Wraps an (async) route handler or middleware: a thrown ApiError is + * answered in the error envelope, anything else as a logged internal + * error. Works without an error-handling middleware on the app, so routes + * can be added to the shared API app without changing existing routes. + */ +function asyncRoute(handler) { + return async (req, res, next) => { + try { + await handler(req, res, next); + } catch (error) { + sendError(req, res, error); + } + }; +} + +module.exports = { asyncRoute }; diff --git a/functions/api/http/asyncRoute.spec.js b/functions/api/http/asyncRoute.spec.js new file mode 100644 index 00000000..485ffb0d --- /dev/null +++ b/functions/api/http/asyncRoute.spec.js @@ -0,0 +1,138 @@ +/** @jest-environment node */ +'use strict'; + +jest.mock('firebase-functions/logger', () => ({ error: jest.fn() })); + +const express = require('express'); +const logger = require('firebase-functions/logger'); +const { asyncRoute } = require('./asyncRoute'); +const { ApiError, validationError } = require('./errors'); +const { requestId } = require('./requestId'); +const { listen } = require('./testing/listen'); + +describe('functions', () => { + describe('api/http/asyncRoute', () => { + let server; + + beforeAll(async () => { + const app = express(); + app.use(requestId); + app.get( + '/ok', + asyncRoute(async (req, res) => { + await Promise.resolve(); + res.json({ ok: true }); + }) + ); + app.get( + '/locked', + asyncRoute(async () => { + throw new ApiError('failed-precondition', 'Movement is locked', { + reason: 'movement-locked', + }); + }) + ); + app.get( + '/invalid', + asyncRoute(async () => { + throw validationError([{ field: 'runway', reason: 'invalid' }]); + }) + ); + app.get( + '/crash', + asyncRoute(async () => { + throw new Error('Firebase internals: /secret/path'); + }) + ); + app.get( + '/sync-crash', + asyncRoute(() => { + throw new TypeError('x is undefined'); + }) + ); + app.get( + '/middleware', + asyncRoute(async (req, res, next) => { + req.fromMiddleware = 'yes'; + next(); + }), + (req, res) => res.json({ fromMiddleware: req.fromMiddleware }) + ); + // An existing-style route without the wrapper keeps its own answer. + app.get('/legacy', (req, res) => res.status(401).send('Unauthorized')); + server = await listen(app); + }); + + afterAll(() => server.close()); + beforeEach(() => jest.clearAllMocks()); + + it('passes successful responses through', async () => { + const response = await server.request('/ok'); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + }); + + it('answers a thrown ApiError in the envelope', async () => { + const response = await server.request('/locked'); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: { + code: 'failed-precondition', + message: 'Movement is locked', + details: { reason: 'movement-locked' }, + }, + }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('answers validation errors with their details', async () => { + const response = await server.request('/invalid'); + + expect(response.status).toBe(400); + expect((await response.json()).error.details).toEqual({ + reason: 'validation-failed', + validationErrors: [{ field: 'runway', reason: 'invalid' }], + }); + }); + + it.each(['/crash', '/sync-crash'])( + 'answers other errors from %s as a logged internal error', + async path => { + const response = await server.request(path, { + headers: { 'X-Request-Id': 'trace-0123456789' }, + }); + const body = await response.text(); + + expect(response.status).toBe(500); + expect(JSON.parse(body)).toEqual({ + error: { code: 'internal', message: 'Internal error' }, + }); + expect(body).not.toMatch(/secret|undefined|at /); + expect(response.headers.get('X-Request-Id')).toBe('trace-0123456789'); + expect(logger.error).toHaveBeenCalledWith( + 'API request failed', + expect.objectContaining({ + requestId: 'trace-0123456789', + method: 'GET', + path, + }) + ); + } + ); + + it('lets wrapped middleware call next', async () => { + const response = await server.request('/middleware'); + + expect(await response.json()).toEqual({ fromMiddleware: 'yes' }); + }); + + it('leaves unwrapped routes alone', async () => { + const response = await server.request('/legacy'); + + expect(response.status).toBe(401); + expect(await response.text()).toBe('Unauthorized'); + }); + }); +}); diff --git a/functions/api/http/errors.js b/functions/api/http/errors.js new file mode 100644 index 00000000..10c6df64 --- /dev/null +++ b/functions/api/http/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const logger = require('firebase-functions/logger'); + +// Error codes of the API envelope and their HTTP status (same family as +// the Google API / Firebase error codes). +const STATUS_BY_CODE = Object.freeze({ + 'invalid-argument': 400, + unauthenticated: 401, + 'permission-denied': 403, + 'not-found': 404, + 'failed-precondition': 409, + 'resource-exhausted': 429, + internal: 500, +}); + +const INTERNAL_MESSAGE = 'Internal error'; + +class ApiError extends Error { + constructor(code, message, details) { + if (!Object.prototype.hasOwnProperty.call(STATUS_BY_CODE, code)) { + throw new TypeError(`Unknown API error code: ${code}`); + } + super(message); + this.name = 'ApiError'; + this.code = code; + this.status = STATUS_BY_CODE[code]; + if (details !== undefined) { + this.details = details; + } + } +} + +// `validationErrors` is a list of {field, reason}. +function validationError(validationErrors, message = 'Validation failed') { + return new ApiError('invalid-argument', message, { + reason: 'validation-failed', + validationErrors, + }); +} + +// Errors of express.json() / body-parser that are the caller's fault. +const BODY_PARSER_REASONS = Object.freeze({ + 'entity.parse.failed': 'malformed-body', + 'entity.too.large': 'body-too-large', + 'encoding.unsupported': 'unsupported-encoding', + 'charset.unsupported': 'unsupported-encoding', +}); + +function toClientError(error) { + if (error instanceof ApiError && error.code !== 'internal') { + return error; + } + const bodyReason = error && BODY_PARSER_REASONS[error.type]; + if (bodyReason) { + return new ApiError('invalid-argument', 'Malformed request body', { + reason: bodyReason, + }); + } + return null; +} + +function envelope(error) { + const body = { code: error.code, message: error.message }; + if (error.details !== undefined) { + body.details = error.details; + } + return { error: body }; +} + +function logInternalError(req, error) { + logger.error('API request failed', { + requestId: req && req.requestId, + method: req && req.method, + path: req && req.path, + error: error instanceof Error ? error.stack || error.message : error, + }); +} + +/** + * Answers `error` in the envelope {error: {code, message, details?}}. An + * ApiError keeps its code, message and details; anything else (and an + * ApiError with code 'internal') is logged and answered as a generic + * internal error, so messages and stack traces never reach the client. + */ +function sendError(req, res, error) { + const clientError = toClientError(error); + if (!clientError) { + logInternalError(req, error); + } + if (res.headersSent) { + return; + } + const answer = + clientError || new ApiError('internal', INTERNAL_MESSAGE); + res.status(answer.status).json(envelope(answer)); +} + +// Express error-handling middleware for routers that use the envelope. +// eslint-disable-next-line no-unused-vars +function errorHandler(error, req, res, next) { + if (res.headersSent) { + // Let Express close the connection of a half-sent response. + logInternalError(req, error); + return next(error); + } + sendError(req, res, error); +} + +module.exports = { + ApiError, + STATUS_BY_CODE, + validationError, + sendError, + errorHandler, +}; diff --git a/functions/api/http/errors.spec.js b/functions/api/http/errors.spec.js new file mode 100644 index 00000000..4e794938 --- /dev/null +++ b/functions/api/http/errors.spec.js @@ -0,0 +1,270 @@ +/** @jest-environment node */ +'use strict'; + +jest.mock('firebase-functions/logger', () => ({ error: jest.fn() })); + +const express = require('express'); +const logger = require('firebase-functions/logger'); +const { + ApiError, + STATUS_BY_CODE, + validationError, + sendError, + errorHandler, +} = require('./errors'); +const { listen } = require('./testing/listen'); + +function fakeRes({ headersSent = false } = {}) { + return { + headersSent, + status: jest.fn().mockReturnThis(), + json: jest.fn().mockReturnThis(), + }; +} + +const req = { requestId: 'req-12345678', method: 'POST', path: '/x' }; + +describe('functions', () => { + describe('api/http/errors', () => { + beforeEach(() => jest.clearAllMocks()); + + describe('ApiError', () => { + it.each([ + ['invalid-argument', 400], + ['unauthenticated', 401], + ['permission-denied', 403], + ['not-found', 404], + ['failed-precondition', 409], + ['resource-exhausted', 429], + ['internal', 500], + ])('maps %s to HTTP %i', (code, status) => { + const error = new ApiError(code, 'Message'); + + expect(error).toBeInstanceOf(Error); + expect(error.code).toBe(code); + expect(error.status).toBe(status); + expect(error.message).toBe('Message'); + expect(STATUS_BY_CODE[code]).toBe(status); + }); + + it('keeps details', () => { + const error = new ApiError('failed-precondition', 'Locked', { + reason: 'movement-locked', + }); + + expect(error.details).toEqual({ reason: 'movement-locked' }); + }); + + it('rejects unknown codes', () => { + expect(() => new ApiError('teapot', 'x')).toThrow(TypeError); + expect(() => new ApiError('toString', 'x')).toThrow(TypeError); + }); + }); + + describe('validationError', () => { + it('is an invalid-argument error with the validation errors', () => { + const error = validationError([ + { field: 'runway', reason: 'invalid' }, + ]); + + expect(error.code).toBe('invalid-argument'); + expect(error.status).toBe(400); + expect(error.details).toEqual({ + reason: 'validation-failed', + validationErrors: [{ field: 'runway', reason: 'invalid' }], + }); + }); + }); + + describe('sendError', () => { + it('answers an ApiError in the envelope', () => { + const res = fakeRes(); + + sendError(req, res, new ApiError('not-found', 'Movement not found')); + + expect(res.status).toHaveBeenCalledWith(404); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'not-found', message: 'Movement not found' }, + }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('includes details when present', () => { + const res = fakeRes(); + + sendError(req, res, validationError([{ field: 'a', reason: 'b' }])); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + error: { + code: 'invalid-argument', + message: 'Validation failed', + details: { + reason: 'validation-failed', + validationErrors: [{ field: 'a', reason: 'b' }], + }, + }, + }); + }); + + it('hides and logs any other error', () => { + const res = fakeRes(); + const error = new Error('secret database path /admins/xyz'); + + sendError(req, res, error); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'internal', message: 'Internal error' }, + }); + expect(logger.error).toHaveBeenCalledWith('API request failed', { + requestId: 'req-12345678', + method: 'POST', + path: '/x', + error: error.stack, + }); + }); + + it('hides the message and details of an internal ApiError', () => { + const res = fakeRes(); + + sendError( + req, + res, + new ApiError('internal', 'Lost connection', { host: 'db' }) + ); + + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'internal', message: 'Internal error' }, + }); + expect(logger.error).toHaveBeenCalled(); + }); + + it('logs non-Error values as they are', () => { + const res = fakeRes(); + + sendError(req, res, 'boom'); + + expect(res.status).toHaveBeenCalledWith(500); + expect(logger.error.mock.calls[0][1].error).toBe('boom'); + }); + + it('does not answer twice', () => { + const res = fakeRes({ headersSent: true }); + + sendError(req, res, new Error('late')); + + expect(res.status).not.toHaveBeenCalled(); + expect(logger.error).toHaveBeenCalled(); + }); + }); + + describe('errorHandler', () => { + it('answers through the envelope', () => { + const res = fakeRes(); + const next = jest.fn(); + + errorHandler(new ApiError('permission-denied', 'No'), req, res, next); + + expect(res.status).toHaveBeenCalledWith(403); + expect(next).not.toHaveBeenCalled(); + }); + + it('hands a half-sent response to Express', () => { + const res = fakeRes({ headersSent: true }); + const next = jest.fn(); + const error = new Error('stream broke'); + + errorHandler(error, req, res, next); + + expect(next).toHaveBeenCalledWith(error); + expect(logger.error).toHaveBeenCalled(); + }); + + describe('over HTTP', () => { + let server; + + beforeAll(async () => { + const app = express(); + const router = express.Router(); + router.use(express.json({ limit: '1kb' })); + router.post('/echo', (request, response) => + response.json(request.body) + ); + router.get('/fail', () => { + throw new Error('sync failure'); + }); + router.use(errorHandler); + app.use(router); + server = await listen(app); + }); + + afterAll(() => server.close()); + + const post = body => + server.request('/echo', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body, + }); + + it('answers malformed JSON as invalid-argument', async () => { + const response = await post('{"a":'); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: { + code: 'invalid-argument', + message: 'Malformed request body', + details: { reason: 'malformed-body' }, + }, + }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('answers a too large body as invalid-argument', async () => { + const response = await post( + JSON.stringify({ a: 'x'.repeat(2048) }) + ); + + expect(response.status).toBe(400); + expect((await response.json()).error.details).toEqual({ + reason: 'body-too-large', + }); + }); + + it.each([ + ['charset', { 'Content-Type': 'application/json; charset=klingon' }], + [ + 'content encoding', + { 'Content-Type': 'application/json', 'Content-Encoding': 'br2' }, + ], + ])('answers an unsupported %s as invalid-argument', async (_, headers) => { + const response = await server.request('/echo', { + method: 'POST', + headers, + body: '{}', + }); + + expect(response.status).toBe(400); + expect((await response.json()).error.details).toEqual({ + reason: 'unsupported-encoding', + }); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('answers thrown errors as internal without details', async () => { + const response = await server.request('/fail'); + + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toMatch( + /application\/json/ + ); + expect(await response.json()).toEqual({ + error: { code: 'internal', message: 'Internal error' }, + }); + }); + }); + }); + }); +}); diff --git a/functions/api/http/requestId.js b/functions/api/http/requestId.js new file mode 100644 index 00000000..4f94c98a --- /dev/null +++ b/functions/api/http/requestId.js @@ -0,0 +1,24 @@ +'use strict'; + +const { randomUUID } = require('crypto'); + +const REQUEST_ID_HEADER = 'X-Request-Id'; + +// Incoming ids are echoed into headers and logs, so only short, plain +// tokens are accepted (e.g. UUIDs or hex trace ids). +const ACCEPTED_REQUEST_ID = /^[A-Za-z0-9_-]{8,64}$/; + +function resolveRequestId(incoming, generate = randomUUID) { + return typeof incoming === 'string' && ACCEPTED_REQUEST_ID.test(incoming) + ? incoming + : generate(); +} + +// Sets req.requestId and the X-Request-Id response header. +function requestId(req, res, next) { + req.requestId = resolveRequestId(req.get(REQUEST_ID_HEADER)); + res.set(REQUEST_ID_HEADER, req.requestId); + next(); +} + +module.exports = { requestId, resolveRequestId, REQUEST_ID_HEADER }; diff --git a/functions/api/http/requestId.spec.js b/functions/api/http/requestId.spec.js new file mode 100644 index 00000000..6d7e6be8 --- /dev/null +++ b/functions/api/http/requestId.spec.js @@ -0,0 +1,90 @@ +/** @jest-environment node */ +'use strict'; + +const express = require('express'); +const { requestId, resolveRequestId, REQUEST_ID_HEADER } = require('./requestId'); +const { listen } = require('./testing/listen'); + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +describe('functions', () => { + describe('api/http/requestId', () => { + describe('resolveRequestId', () => { + it.each([ + '3f1c2a9e-8d4b-4c6a-9e2f-1b7d5a3c8e01', + '0123456789abcdef0123456789abcdef', + 'client_req-42abc', + ])('accepts %j', id => { + expect(resolveRequestId(id)).toBe(id); + }); + + it.each([ + undefined, + '', + 'short', + 'x'.repeat(65), + 'abc def ghi', + 'abcdefgh\r\nSet-Cookie: a=b', + 'abcdefgh