diff --git a/.github/workflows/test-pull-request.yml b/.github/workflows/test-pull-request.yml index 7b944da4..4b896c83 100644 --- a/.github/workflows/test-pull-request.yml +++ b/.github/workflows/test-pull-request.yml @@ -20,6 +20,10 @@ jobs: - run: npm run build - run: npm run test:app - run: npm run cy:test + # The movement specs again, with the app built with + # movementWritesViaApi (projects/cypress-testing-api.json), plus the + # specs of cypress/integration/movements_api + - run: npm run cy:test:api build_functions: if: '${{ github.event.pull_request.head.repo.full_name == github.repository }}' runs-on: ubuntu-latest diff --git a/README.md b/README.md index dc3666df..fe408a69 100755 --- a/README.md +++ b/README.md @@ -179,10 +179,13 @@ with it. All routes answer CORS requests from any origin. | `POST` | `/api/customs/prepopulated-forms` | user, not guest or kiosk | [Customs](#customs) form for a movement | | `GET` | `/api/customs/availability` | user | Whether [customs](#customs) is configured | | `GET` | `/api/users/me/invoice-recipients` | user | [Invoice recipients](#invoice-recipients) of the user | +| `POST` | `/api/app/movements/` | user | Creates a departure or arrival, see [Movement writes](#movement-writes) | +| `PATCH` | `/api/app/movements//` | user | Updates a departure or arrival, see [Movement writes](#movement-writes) | *Anyone* needs no authentication, *user* the Firebase ID token of a logged-in user, *admin* that of an admin (see [Authentication](#authentication)). The airstat report and the API keys exist only on projects with -`reportApiEnabled` (see `projects/Configuration.md`). +`reportApiEnabled`, the movement writes only on projects with `movementWritesViaApi` (see +`projects/Configuration.md`). #### Authentication #### @@ -190,7 +193,8 @@ with it. All routes answer CORS requests from any origin. * **Firebase ID token** (the app): `Authorization: Bearer ` of a logged-in user. Without a valid, unrevoked token the answer is `401 Unauthorized`. Routes for admins answer `403 Forbidden: Admins only` to other users, and the customs form answers `403 Forbidden: not available to shared sessions` to guest and kiosk - logins. These answers are not JSON: the body is just that text (sent as `text/html`). + logins. These answers are not JSON: the body is just that text (sent as `text/html`). The + [movement writes](#movement-writes) answer in their JSON error format instead. #### Aerodrome status #### @@ -307,6 +311,29 @@ For the first two, the outcome is stored in `/settings/customsSyncStatus/` is `departures` or `arrivals`; the body is a JSON object +with the movement's fields, as the app stores them in the database. + +* `POST /api/app/movements/` (user): creates the movement, `201 {"key": ""}`. +* `PATCH /api/app/movements//` (user): updates it like a Realtime Database `update()`: each field of the + body replaces the stored one, `null` removes it, other fields stay. `200 {"key": ""}`. + +The checks are those of the database rules (fields, runways, routes, flight types, ownership, movement lock); +`negativeTimestamp`, `createdBy` and `createdBy_orderKey` are set by the server, values sent for them are +ignored. The function writes as the caller, so the database rules apply to the write as well. Errors are JSON, +`{"error": {"code", "message", "details"}}`, with an `X-Request-Id` header: + +* `400 invalid-argument`: `details.validationErrors` lists `{field, reason}`, or `details.reason` is + `invalid-body` / `malformed-body`; +* `401 unauthenticated`: no valid ID token; +* `403 permission-denied`: the movement belongs to someone else (only on projects with `loginForm` `email`: + pilots write their own movements, guest and kiosk only those without owner, admins all); +* `404 not-found`: unknown `` or key; +* `409 failed-precondition`: the movement is in a locked period; +* `500 internal`: anything else, also when the database rules reject a write the checks accepted. + #### Invoice recipients #### `GET /api/users/me/invoice-recipients` (user): the names of the invoice recipients (`/settings/invoiceRecipients`) diff --git a/cypress/CYPRESS_TESTING_SETUP.md b/cypress/CYPRESS_TESTING_SETUP.md index 9050df10..bb539ca2 100644 --- a/cypress/CYPRESS_TESTING_SETUP.md +++ b/cypress/CYPRESS_TESTING_SETUP.md @@ -101,13 +101,38 @@ npm run cy:open npm run cy:run ``` +### Movement writes via the API + +The movement specs also run with the app built with `movementWritesViaApi` +(see `projects/Configuration.md`), so they cover saving through the app API +as well as direct database writes: + +```bash +npm run cy:test:api +``` + +It builds the app from `projects/cypress-testing-api.json` (which extends +`cypress-testing` and only switches the flag on), exposes +`movementWritesViaApi=true` to the specs (`cypress run --expose`, read +with `Cypress.expose()`; `Cypress.env()` is gone since Cypress 16) and runs `cypress/integration/movements/**` and +`cypress/integration/movements_api/**`. The specs in `movements_api` cover +behaviour that only exists on the API path; the default run skips them. CI +runs both (`.github/workflows/test-pull-request.yml`). + +The API run needs the movement routes in the deployed functions: +`npm run deploy:cypress` generates the functions config from +`cypress-testing-api`, so the `cypress-testing` functions have the flag. The +default run is not affected: its app keeps writing to the database directly. + ## Cloud Functions deployment The association E2E tests (Scenarios 3–6) require the **fixed** trigger functions -to be deployed to the `cypress-testing` Firebase project: +to be deployed to the `cypress-testing` Firebase project. Deploy with +`npm run deploy:cypress` (see above), not a plain `firebase deploy`: without +the generated config the movement routes the API run needs are missing. ```bash -firebase deploy --only functions --project cypress-testing +cd functions && npm run deploy:cypress ``` Scenarios 1–2 (basic bidirectional linking) work with both old and new trigger code. diff --git a/cypress/integration/movements_api/save_movement_api_spec.js b/cypress/integration/movements_api/save_movement_api_spec.js new file mode 100644 index 00000000..736185dd --- /dev/null +++ b/cypress/integration/movements_api/save_movement_api_spec.js @@ -0,0 +1,182 @@ +// Behaviour that only exists when the app saves movements through the app +// API (movementWritesViaApi). Runs in `npm run cy:test:api`, which builds +// the app from projects/cypress-testing-api.json and exposes the Cypress value +// movementWritesViaApi; skipped in the default run (direct database writes). +// The other movement specs run in both modes. + +const describeWithApi = Cypress.expose('movementWritesViaApi') ? describe : describe.skip; + +const CREATE_DEPARTURE = '**/api/app/movements/departures'; +const UPDATE_DEPARTURE = '**/api/app/movements/departures/*'; + +const readDepartures = () => + cy.window().then(win => + win.firebase.getRef('/departures').once('value').then(snapshot => snapshot.val() || {}) + ); + +// After "next" on the departure/arrival page the wizard checks the location +// asynchronously; confirm the dialog if it shows up. +const confirmLocationIfAsked = () => { + cy.get('[data-cy=location-confirmation-dialog-confirm], [data-cy=remarks]', {timeout: 8000}) + .then($els => { + if ($els.filter('[data-cy=location-confirmation-dialog-confirm]').length > 0) { + cy.get('[data-cy=location-confirmation-dialog-confirm]').click(); + } + }); +}; + +// Fills the new-departure wizard up to the commit dialog (not confirmed). +const fillNewDeparture = remarks => { + cy.visit('#/departure/new'); + + cy.get('[data-cy=immatriculation]').type('HBKOF'); + cy.get('[data-cy=aircraftType]').type('DR40'); + cy.get('[data-cy=mtow]').type('1000'); + cy.get('[data-cy=aircraftCategory]').click(); + cy.get('[data-cy=aircraftCategory-option-Flugzeug]').click(); + cy.get('[data-cy=next-button]').click(); + + cy.get('[data-cy=lastname]').type('Muster'); + cy.get('[data-cy=firstname]').type('Max'); + cy.get('[data-cy=email]').type('max@example.com'); + cy.get('[data-cy=phone]').type('0791234567'); + cy.get('[data-cy=next-button]').click(); + + cy.get('[data-cy=next-button]').click(); + + cy.get('[data-cy=location]').type('LSZR'); + cy.get('[data-cy=duration-hours-increment]').click(); + cy.get('[data-cy=next-button]').click(); + confirmLocationIfAsked(); + + cy.get('[data-cy=flightType-private]').click(); + cy.get('[data-cy=runway-36]').click(); + cy.get('[data-cy=departureRoute-west]').click(); + cy.get('[data-cy=remarks]').type(remarks); + cy.get('[data-cy=next-button]').click(); +}; + +describeWithApi('movements_api', () => { + describe('save_movement_api', () => { + beforeEach(() => { + cy.visit('#/'); + cy.loginAdmin(); + cy.resetMovementsTestData(); + cy.logout(); + cy.login(); + }); + + afterEach(() => { + cy.logout(); + }); + + it('creates and edits a departure through the API, not the database', () => { + cy.intercept('POST', CREATE_DEPARTURE).as('create'); + cy.intercept('PATCH', UPDATE_DEPARTURE).as('update'); + + fillNewDeparture('Created via API'); + cy.get('[data-cy=commit-requirement-dialog-confirm]').click(); + + cy.wait('@create').then(({request, response}) => { + expect(request.headers.authorization).to.match(/^Bearer \S+$/); + expect(response.statusCode).to.equal(201); + expect(response.body.key).to.be.a('string'); + cy.wrap(response.body.key).as('key'); + }); + cy.get('[data-cy=finish-button]').should('be.visible'); + + cy.get('@key').then(key => readDepartures().then(departures => { + expect(Object.keys(departures)).to.deep.equal([key]); + const stored = departures[key]; + expect(stored.remarks).to.equal('Created via API'); + // Set by the server, derived from dateTime + expect(stored.negativeTimestamp).to.equal(-Date.parse(stored.dateTime)); + // The static Cypress login has no e-mail, so the movement may be + // ownerless; the order key exists exactly when createdBy does. + if (stored.createdBy) { + expect(stored.createdBy_orderKey.startsWith(`${stored.createdBy}_`)).to.equal(true); + } else { + expect(stored).not.to.have.property('createdBy_orderKey'); + } + })); + + // Edit it from the movement list as admin, like edit_movement_spec + cy.logout(); + cy.loginAdmin(); + cy.viewport(1400, 900); + cy.visit('#/movements'); + cy.get('@key').then(key => { + cy.get(`[data-id="${key}"]`).find('.immatriculation').click(); + cy.get('[data-cy=action-edit]').first().click(); + cy.hash().should('include', `/departure/${key}`); + }); + cy.get('[data-cy=next-button]').click(); + cy.get('[data-cy=next-button]').click(); + cy.get('[data-cy=next-button]').click(); + cy.get('[data-cy=next-button]').click(); + confirmLocationIfAsked(); + cy.get('[data-cy=remarks]').clear().type('Edited via API'); + cy.get('[data-cy=next-button]').click(); + cy.get('[data-cy=commit-requirement-dialog-confirm], [data-cy=finish-button]') + .then($els => { + if ($els.filter('[data-cy=commit-requirement-dialog-confirm]').length > 0) { + cy.get('[data-cy=commit-requirement-dialog-confirm]').click(); + } + }); + + cy.wait('@update').its('response.statusCode').should('equal', 200); + cy.get('[data-cy=finish-button]').should('be.visible'); + + cy.get('@key').then(key => readDepartures().then(departures => { + expect(departures[key].remarks).to.equal('Edited via API'); + })); + }); + + it('shows the validation error of the API and stores nothing', () => { + // The forms only offer valid values, so the request is altered on its + // way to the real API, which rejects the unknown runway. + cy.intercept('POST', CREATE_DEPARTURE, req => { + req.body = {...req.body, runway: '99'}; + }).as('create'); + + fillNewDeparture('Rejected by the API'); + cy.get('[data-cy=commit-requirement-dialog-confirm]').click(); + + cy.wait('@create').then(({response}) => { + expect(response.statusCode).to.equal(400); + expect(response.body.error.code).to.equal('invalid-argument'); + expect(response.body.error.details.validationErrors) + .to.deep.include({field: 'runway', reason: 'not-allowed'}); + }); + cy.contains('Validation failed: runway').should('be.visible'); + cy.get('[data-cy=finish-button]').should('not.exist'); + + readDepartures().then(departures => { + expect(departures).to.deep.equal({}); + }); + }); + + it('saves a new departure only once on a double click', () => { + // Slow the answer down so the second click lands while the first + // save is still running. + cy.intercept('POST', CREATE_DEPARTURE, req => { + req.on('response', res => { + res.setDelay(1500); + }); + }).as('create'); + + fillNewDeparture('Double click'); + cy.get('[data-cy=commit-requirement-dialog-confirm]').dblclick(); + + cy.wait('@create'); + cy.get('[data-cy=finish-button]').should('be.visible'); + // Leave time for a second request to show up, then count + cy.wait(2000); + cy.get('@create.all').should('have.length', 1); + + readDepartures().then(departures => { + expect(Object.keys(departures)).to.have.length(1); + }); + }); + }); +}); 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