diff --git a/functions/api/http/appAuth.js b/functions/api/http/appAuth.js index 96ee0df3..c3375f8f 100644 --- a/functions/api/http/appAuth.js +++ b/functions/api/http/appAuth.js @@ -78,14 +78,35 @@ async function resolveActor(decodedToken, db) { } // A pilot with a token of the central login (loginTokens.js). Never an -// admin: admin rights stay with the Firebase accounts of this instance. -function loginActor({ sub, email }) { +// admin for writes: admin rights stay with the Firebase accounts of this +// instance (reading resolves the app user of the e-mail, see +// rtdbMovementRepository.js resolveReader). `scopes`: what the token allows +// (movements:write, movements:read); Firebase actors have none, the app may +// do everything its user may. +function loginActor({ sub, email, scopes = [] }) { return { uid: `${LOGIN_UID_PREFIX}${sub}`, email, isAdmin: false, isGuest: false, isKiosk: false, + scopes: Object.freeze([...scopes]), + }; +} + +/** + * Middleware after appAuth: a caller whose token carries scopes (the central + * login) needs `scope`, otherwise 403 (reason insufficient-scope). + */ +function requireScope(scope) { + return (req, res, next) => { + const { scopes } = req.actor || {}; + if (Array.isArray(scopes) && !scopes.includes(scope)) { + return sendError(req, res, new ApiError('permission-denied', `The token does not allow ${scope}`, { + reason: 'insufficient-scope', + })); + } + return next(); }; } @@ -169,6 +190,7 @@ function appAuth({ auth = getAuth, db = getDatabase, loginTokens = null } = {}) module.exports = { appAuth, + requireScope, resolveActor, loginActor, bearerToken, diff --git a/functions/api/http/appAuth.spec.js b/functions/api/http/appAuth.spec.js index a893563c..609fb54f 100644 --- a/functions/api/http/appAuth.spec.js +++ b/functions/api/http/appAuth.spec.js @@ -9,7 +9,7 @@ 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, loginActor, bearerToken } = require('./appAuth'); +const { appAuth, resolveActor, loginActor, bearerToken, requireScope } = require('./appAuth'); const { LoginTokenRejected } = require('./loginTokens'); const { requestId } = require('./requestId'); const { listen } = require('./testing/listen'); @@ -329,7 +329,7 @@ describe('functions', () => { db = fakeDb({ 'login:sub-1': true }); loginTokens = { isLoginToken: jest.fn(token => token.startsWith('login.')), - verify: jest.fn(async () => ({ sub: 'sub-1', email: 'pilot@example.ch' })), + verify: jest.fn(async () => ({ sub: 'sub-1', email: 'pilot@example.ch', scopes: ['movements:write'] })), }; }); @@ -345,6 +345,7 @@ describe('functions', () => { isAdmin: false, isGuest: false, isKiosk: false, + scopes: ['movements:write'], }); expect(loginTokens.verify).toHaveBeenCalledWith('login.token'); expect(auth.verifyIdToken).not.toHaveBeenCalled(); @@ -384,8 +385,32 @@ describe('functions', () => { }); it('builds the actor with the login uid prefix', () => { - expect(loginActor({ sub: 'abc', email: 'a@b.ch' })).toEqual({ - uid: 'login:abc', email: 'a@b.ch', isAdmin: false, isGuest: false, isKiosk: false, + expect(loginActor({ sub: 'abc', email: 'a@b.ch', scopes: ['movements:read'] })).toEqual({ + uid: 'login:abc', email: 'a@b.ch', isAdmin: false, isGuest: false, isKiosk: false, scopes: ['movements:read'], + }); + }); + }); + + describe('requireScope', () => { + const run = (actor) => { + const req = { actor, requestId: 'r1', get: () => undefined }; + const res = { status: jest.fn(() => res), json: jest.fn(() => res), set: jest.fn(() => res) }; + const next = jest.fn(); + requireScope('movements:read')(req, res, next); + return { res, next }; + }; + + it('lets Firebase actors (no scopes) and tokens with the scope through', () => { + expect(run({ uid: 'u1' }).next).toHaveBeenCalled(); + expect(run(loginActor({ sub: 'a', email: 'a@b.ch', scopes: ['movements:read'] })).next).toHaveBeenCalled(); + }); + + it('answers 403 insufficient-scope for a token without it', () => { + const { res, next } = run(loginActor({ sub: 'a', email: 'a@b.ch', scopes: ['movements:write'] })); + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'permission-denied', message: 'The token does not allow movements:read', details: { reason: 'insufficient-scope' } }, }); }); }); diff --git a/functions/api/http/loginTokens.js b/functions/api/http/loginTokens.js index 378bd0e9..9979cce1 100644 --- a/functions/api/http/loginTokens.js +++ b/functions/api/http/loginTokens.js @@ -14,11 +14,12 @@ const { validateCentralLogin } = require('./centralLoginConfig'); // The hub (odch/mcp-hub) obtains such tokens by token exchange (RFC 8693) // for exactly this instance: a JWT (RFC 9068, typ at+jwt) signed with ES256, // iss = issuer, aud = audience (e.g. "flightbox-lsze-test"), with the -// pilot's verified e-mail and the movements:write scope. +// pilot's verified e-mail and the movements:write and/or movements:read +// scope; the routes check the one they need (appAuth.js requireScope). const ALGORITHMS = ['ES256']; const TOKEN_TYPES = new Set(['at+jwt', 'application/at+jwt']); -const REQUIRED_SCOPE = 'movements:write'; +const MOVEMENT_SCOPES = Object.freeze(['movements:write', 'movements:read']); const CLOCK_TOLERANCE_SECONDS = 30; // The login issues these tokens for 5 minutes; anything longer lived is not // one of them. @@ -203,13 +204,14 @@ function createLoginTokenVerifier(config, { fetchImpl = (...args) => fetch(...ar if (typeof payload.email !== 'string' || payload.email === '' || payload.email_verified !== true) { reject('no verified e-mail'); } - const scopes = typeof payload.scope === 'string' ? payload.scope.split(' ') : []; - if (!scopes.includes(REQUIRED_SCOPE)) { + const scopes = (typeof payload.scope === 'string' ? payload.scope.split(' ') : []) + .filter(scope => MOVEMENT_SCOPES.includes(scope)); + if (scopes.length === 0) { reject('scope'); } // Lower-cased like Firebase Auth stores addresses, so a pilot owns the // same movements whichever way they signed in. - return { sub: payload.sub, email: payload.email.toLowerCase() }; + return { sub: payload.sub, email: payload.email.toLowerCase(), scopes: [...new Set(scopes)] }; } return { @@ -220,8 +222,8 @@ function createLoginTokenVerifier(config, { fetchImpl = (...args) => fetch(...ar } module.exports = { + MOVEMENT_SCOPES, createLoginTokenVerifier, validateCentralLogin, LoginTokenRejected, - REQUIRED_SCOPE, }; diff --git a/functions/api/http/loginTokens.spec.js b/functions/api/http/loginTokens.spec.js index 918d8d6c..d3590fef 100644 --- a/functions/api/http/loginTokens.spec.js +++ b/functions/api/http/loginTokens.spec.js @@ -76,7 +76,7 @@ describe('functions', () => { it('accepts a token of the login and returns the subject and lower-cased e-mail', async () => { const token = sign(keys.privateKey); expect(verifier.isLoginToken(token)).toBe(true); - await expect(verifier.verify(token)).resolves.toEqual({ sub: SUB, email: 'pilot@example.com' }); + await expect(verifier.verify(token)).resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:write'] }); expect(fetchImpl).toHaveBeenCalledWith(CONFIG.jwksUri, expect.objectContaining({ signal: expect.anything() })); }); @@ -126,6 +126,13 @@ describe('functions', () => { expect(await rejection(sign(keys.privateKey, { scope: 'openid email' }))).toBe('scope'); }); + it('accepts movements:read and returns only the movement scopes', async () => { + await expect(verifier.verify(sign(keys.privateKey, { scope: 'movements:read' }))) + .resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:read'] }); + await expect(verifier.verify(sign(keys.privateKey, { scope: 'openid movements:read movements:write account' }))) + .resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:read', 'movements:write'] }); + }); + it('caches the keys and refetches for an unknown kid, rate limited', async () => { await verifier.verify(sign(keys.privateKey)); await verifier.verify(sign(keys.privateKey)); diff --git a/functions/api/index.spec.js b/functions/api/index.spec.js index f54bc31a..52864bf3 100644 --- a/functions/api/index.spec.js +++ b/functions/api/index.spec.js @@ -141,9 +141,11 @@ describe('functions', () => { expect(routes).toEqual([ [['post'], ['/app/movements/:type', '/api/app/movements/:type']], [['patch'], ['/app/movements/:type/:key', '/api/app/movements/:type/:key']], + [['get'], ['/app/movements', '/api/app/movements']], ]); - // requestId, appAuth, JSON body, handler - movementLayers.forEach(layer => expect(layer.route.stack).toHaveLength(4)); + // Writes: requestId, appAuth, requireScope, JSON body, handler; the + // list: requestId, appAuth, requireScope, handler. + expect(movementLayers.map(layer => layer.route.stack.length)).toEqual([5, 5, 4]); }); it('lets admins manage API keys when the tenant has an API feature', () => { diff --git a/functions/movements/adapters/databaseRest.js b/functions/movements/adapters/databaseRest.js index c7b21171..7da7ffe0 100644 --- a/functions/movements/adapters/databaseRest.js +++ b/functions/movements/adapters/databaseRest.js @@ -20,11 +20,11 @@ const TOKEN_RENEWAL_MARGIN_MS = 5 * 60 * 1000; // does when FIREBASE_DATABASE_EMULATOR_HOST is set). const EMULATOR_TOKEN = 'owner'; -// The database denied the write: its rules (`.write` or `.validate`) do not -// allow it for the caller the request was made for. +// The database denied the request: its rules (`.read`, `.write` or +// `.validate`) do not allow it for the caller the request was made for. class RulesRejectedError extends Error { - constructor(path) { - super(`Database rules rejected the write to ${path}`); + constructor(path, operation = 'write') { + super(`Database rules rejected the ${operation} of ${path}`); this.name = 'RulesRejectedError'; this.path = path; } @@ -72,7 +72,7 @@ function assertAuthOverride(authOverride) { && typeof authOverride.uid === 'string' && authOverride.uid !== ''; if (!isValid) { - throw new TypeError('A write on behalf of a caller needs an auth override with a uid'); + throw new TypeError('A request on behalf of a caller needs an auth override with a uid'); } } @@ -172,7 +172,40 @@ function createDatabaseRestClient({ throw new DatabaseRestError(`Database ${method} ${path} answered ${response.status}`, response.status); } - return { write }; + /** + * GET of `path` as the caller, with a query (`orderBy`, `startAt`, + * `endAt`, `limitToFirst`; values are JSON-encoded as the REST API + * expects). Resolves with the parsed value (null when there is none). + */ + async function read(path, query, authOverride) { + assertAuthOverride(authOverride); + const destination = resolve(); + const token = destination.emulator ? EMULATOR_TOKEN : await serviceAccountToken(); + const params = { auth_variable_override: JSON.stringify(authOverride) }; + Object.entries(query || {}).forEach(([name, value]) => { + params[name] = JSON.stringify(value); + }); + let response; + try { + response = await fetchImpl(requestUrl(destination, path, params), { + method: 'GET', + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + throw new DatabaseRestError(`Database GET ${path} failed: ${e.name}: ${e.message}`); + } + const answer = await readJson(response); + if (response.ok) { + return answer; + } + if (isPermissionDenied(response.status, answer)) { + throw new RulesRejectedError(path, 'read'); + } + throw new DatabaseRestError(`Database GET ${path} answered ${response.status}`, response.status); + } + + return { write, read }; } module.exports = { diff --git a/functions/movements/adapters/databaseRest.spec.js b/functions/movements/adapters/databaseRest.spec.js index 501ad031..35f53554 100644 --- a/functions/movements/adapters/databaseRest.spec.js +++ b/functions/movements/adapters/databaseRest.spec.js @@ -200,5 +200,43 @@ describe('functions', () => { await expect(client.write('POST', 'departures', {}, PILOT)).rejects.toThrow(DatabaseRestError); }); }); + + describe('read', () => { + it('queries as the caller with JSON-encoded parameters', async () => { + const { client, call } = setup({ answer: response(200, { k1: { immatriculation: 'HBPIV' } }) }); + + const answer = await client.read('arrivals', { + orderBy: 'createdBy_orderKey', startAt: 'pilot@example.com_1', endAt: 'pilot@example.com_2', limitToFirst: 201, + }, PILOT); + + expect(answer).toEqual({ k1: { immatriculation: 'HBPIV' } }); + const { url, init } = call(0); + expect(url.pathname).toBe('/arrivals.json'); + expect(init.method).toBe('GET'); + expect(init.headers.Authorization).toBe('Bearer access-1'); + expect(JSON.parse(url.searchParams.get('auth_variable_override'))).toEqual(PILOT); + expect(url.searchParams.get('orderBy')).toBe('"createdBy_orderKey"'); + expect(url.searchParams.get('startAt')).toBe('"pilot@example.com_1"'); + expect(url.searchParams.get('limitToFirst')).toBe('201'); + }); + + it('never reads without a caller', async () => { + const { client, fetchImpl } = setup(); + + await expect(client.read('arrivals', {}, { uid: '' })).rejects.toThrow(TypeError); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('reports a rules denial as RulesRejectedError and other failures as DatabaseRestError', async () => { + const denied = await setup({ answer: response(401, { error: 'Permission denied' }) }) + .client.read('arrivals', {}, PILOT).catch(e => e); + expect(denied).toBeInstanceOf(RulesRejectedError); + expect(denied.message).toBe('Database rules rejected the read of arrivals'); + + const failed = await setup({ answer: response(500) }).client.read('arrivals', {}, PILOT).catch(e => e); + expect(failed).toBeInstanceOf(DatabaseRestError); + expect(failed.status).toBe(500); + }); + }); }); }); diff --git a/functions/movements/adapters/rtdbMovementRepository.js b/functions/movements/adapters/rtdbMovementRepository.js index 0707c4ba..621fcdf7 100644 --- a/functions/movements/adapters/rtdbMovementRepository.js +++ b/functions/movements/adapters/rtdbMovementRepository.js @@ -2,14 +2,16 @@ const { getDatabase } = require('firebase-admin/database'); const { createDatabaseRestClient } = require('./databaseRest'); +const { toOrderKey } = require('../domain/orderKey'); // Realtime Database implementation of the movement repository port (see // functions/movements/application/saveMovement.js). // -// Reads use the Admin SDK: they only feed the server's own checks and never -// reach the caller. Writes go through the REST API as the caller +// Reads for the server's own checks use the Admin SDK; they never reach the +// caller. Writes, and the movement lists returned to the caller +// (listMovements), go through the REST API as the caller // (auth_variable_override), so the database rules apply to them exactly as -// they apply to the web client's direct writes today. +// they apply to the web client's requests. const PATHS = Object.freeze({ departure: 'departures', arrival: 'arrivals' }); @@ -35,12 +37,94 @@ async function readValue(db, path) { return snapshot.val(); } +const LOGIN_UID_PREFIX = 'login:'; +const INVALID_KEY_CHARS = /[.#$[\]/]/; + +// The client's canSeeAllMovements and the rules' CAN_SEE_ALL_MOVEMENTS +// (tasks/processFirebaseRules.js): /admins/ or /logins//allMovements. +async function canSeeAllMovements(db, uid) { + if (!uid || INVALID_KEY_CHARS.test(uid)) { + return false; + } + const [admin, allMovements] = await Promise.all([ + readValue(db, `admins/${uid}`), + readValue(db, `logins/${uid}/allMovements`), + ]); + return admin === true || allMovements === true; +} + +// The app's Firebase user of a verified e-mail (the app signs pilots in by +// e-mail code, one user per address; functions/auth/verifySignInCode.js), +// or null. +async function appUserUid(auth, email) { + if (typeof email !== 'string' || email === '') { + return null; + } + try { + const user = await auth.getUserByEmail(email); + return user.emailVerified === true && user.disabled !== true ? user.uid : null; + } catch (error) { + if (error && error.code === 'auth/user-not-found') { + return null; + } + throw error; + } +} + +// RTDB returns a query result as an object; entries ordered by negative +// timestamp (newest first), the order of the queries below. +const byNewest = (a, b) => (a[1].negativeTimestamp ?? 0) - (b[1].negativeTimestamp ?? 0); + /** * db: () => Admin SDK database (reads); * rest: client of databaseRest.js (writes as the caller). */ -function createRtdbMovementRepository({ db = getDatabase, rest = createDatabaseRestClient() } = {}) { +// Loaded on first use: firebase-admin/auth is only needed to list movements +// for callers of the central login. +const defaultAuth = () => require('firebase-admin/auth').getAuth(); + +function createRtdbMovementRepository({ db = getDatabase, auth = defaultAuth, rest = createDatabaseRestClient() } = {}) { return { + /** + * Which movements the actor may list, as in the app: {all, authOverride}. + * all: every movement (shared access, admins and allMovements + * operators), else only the actor's own. A caller with a token of the + * central login has the rights of the app user with the same verified + * e-mail; for an `all` read the request then runs as that user, so the + * database rules see the same uid as for the app. + */ + async resolveReader(actor, policy) { + const own = authOverrideFor(actor); + if (!policy.personalAccess) { + return { all: true, authOverride: own }; + } + const database = db(); + const uid = actor.uid.startsWith(LOGIN_UID_PREFIX) ? await appUserUid(auth(), actor.email) : actor.uid; + if (await canSeeAllMovements(database, uid)) { + return { all: true, authOverride: { uid, token: own.token } }; + } + return { all: false, authOverride: own }; + }, + + /** + * Movements of `type` with dateTime in [fromMs, toMs], newest first, at + * most `limit`; only those created by `owner` unless owner is null. + * Read as the caller (authOverride); resolves with [[key, movement]]. + */ + async listMovements(type, { fromMs, toMs, owner, limit }, authOverride) { + const query = owner + ? { + orderBy: 'createdBy_orderKey', + startAt: toOrderKey(owner, -toMs), + endAt: toOrderKey(owner, -fromMs), + limitToFirst: limit, + } + : { orderBy: 'negativeTimestamp', startAt: -toMs, endAt: -fromMs, limitToFirst: limit }; + const answer = await rest.read(pathOf(type), query, authOverride); + const entries = answer && typeof answer === 'object' ? Object.entries(answer) : []; + return entries.filter(([, movement]) => movement && typeof movement === 'object').sort(byNewest); + }, + // The stored movement, or null. `key` must already be a valid key. async findMovement(type, key) { return readValue(db(), `${pathOf(type)}/${key}`); diff --git a/functions/movements/adapters/rtdbMovementRepository.spec.js b/functions/movements/adapters/rtdbMovementRepository.spec.js index 881a1036..f6f7a648 100644 --- a/functions/movements/adapters/rtdbMovementRepository.spec.js +++ b/functions/movements/adapters/rtdbMovementRepository.spec.js @@ -97,5 +97,109 @@ describe('functions', () => { await expect(repository.updateMovement('departure', 'k1', {}, PILOT)).rejects.toBe(failure); }); }); + + describe('movement lists', () => { + const PERSONAL = { personalAccess: true }; + const SHARED = { personalAccess: false }; + const LOGIN_PILOT = { uid: 'login:sub-1', email: 'pilot@example.com', isAdmin: false, scopes: ['movements:read'] }; + const LOGIN_ADMIN = { uid: 'login:sub-2', email: 'admin@example.com', isAdmin: false, scopes: ['movements:read'] }; + + // Firebase users of the app by e-mail. + function fakeAuth(users) { + return { + getUserByEmail: jest.fn(async email => { + if (!users[email]) { + const error = new Error('no user'); + error.code = 'auth/user-not-found'; + throw error; + } + return { emailVerified: true, disabled: false, ...users[email] }; + }), + }; + } + + const reader = (data, users = {}) => createRtdbMovementRepository({ + db: () => fakeDb(data), auth: () => fakeAuth(users), rest: {}, + }); + + it('lets an app admin or allMovements operator read all, as their own uid', async () => { + const repository = reader({ 'admins/admin-uid': true, 'logins/op-uid/allMovements': true }); + + expect(await repository.resolveReader({ uid: 'admin-uid', email: 'admin@example.com', isAdmin: true }, PERSONAL)) + .toEqual({ all: true, authOverride: { uid: 'admin-uid', token: { email: 'admin@example.com' } } }); + expect((await repository.resolveReader({ uid: 'op-uid', email: null }, PERSONAL)).all).toBe(true); + expect(await repository.resolveReader(PILOT, PERSONAL)) + .toEqual({ all: false, authOverride: { uid: 'pilot-uid', token: { email: 'pilot@example.com' } } }); + }); + + it('gives a login caller the rights of the app user with the same verified e-mail', async () => { + const repository = reader({ 'admins/admin-uid': true }, { + 'admin@example.com': { uid: 'admin-uid' }, + 'pilot@example.com': { uid: 'pilot-uid' }, + }); + + // An all read runs as the app user, so the rules see the admin's uid. + expect(await repository.resolveReader(LOGIN_ADMIN, PERSONAL)) + .toEqual({ all: true, authOverride: { uid: 'admin-uid', token: { email: 'admin@example.com' } } }); + expect(await repository.resolveReader(LOGIN_PILOT, PERSONAL)) + .toEqual({ all: false, authOverride: { uid: 'login:sub-1', token: { email: 'pilot@example.com' } } }); + }); + + it.each([ + ['no app user', {}], + ['an unverified app user', { 'admin@example.com': { uid: 'admin-uid', emailVerified: false } }], + ['a disabled app user', { 'admin@example.com': { uid: 'admin-uid', disabled: true } }], + ])('does not let a login caller read all with %s', async (_, users) => { + const repository = reader({ 'admins/admin-uid': true }, users); + + expect((await repository.resolveReader(LOGIN_ADMIN, PERSONAL)).all).toBe(false); + }); + + it('passes other failures of the user lookup on', async () => { + const failure = Object.assign(new Error('quota'), { code: 'auth/quota-exceeded' }); + const repository = createRtdbMovementRepository({ + db: () => fakeDb({}), auth: () => ({ getUserByEmail: async () => { throw failure; } }), rest: {}, + }); + + await expect(repository.resolveReader(LOGIN_ADMIN, PERSONAL)).rejects.toBe(failure); + }); + + it('lets everyone read all where access is shared', async () => { + expect(await reader({}).resolveReader(PILOT, SHARED)) + .toEqual({ all: true, authOverride: { uid: 'pilot-uid', token: { email: 'pilot@example.com' } } }); + }); + + it('queries the owner\'s index or the timestamp, as the caller, newest first', async () => { + const rest = { + read: jest.fn(async () => ({ + older: { negativeTimestamp: -2000 }, + newer: { negativeTimestamp: -3000 }, + broken: 'x', + })), + }; + const repository = createRtdbMovementRepository({ db: () => fakeDb({}), rest }); + const override = { uid: 'login:sub-1', token: { email: 'pilot@example.com' } }; + + const own = await repository.listMovements('arrival', { fromMs: 1000, toMs: 5000, owner: 'pilot@example.com', limit: 11 }, override); + await repository.listMovements('departure', { fromMs: 1000, toMs: 5000, owner: null, limit: 11 }, override); + + expect(own.map(([key]) => key)).toEqual(['newer', 'older']); + expect(rest.read).toHaveBeenNthCalledWith(1, 'arrivals', { + orderBy: 'createdBy_orderKey', + startAt: 'pilot@example.com_9999999994999', + endAt: 'pilot@example.com_9999999998999', + limitToFirst: 11, + }, override); + expect(rest.read).toHaveBeenNthCalledWith(2, 'departures', { + orderBy: 'negativeTimestamp', startAt: -5000, endAt: -1000, limitToFirst: 11, + }, override); + }); + + it('answers an empty list for no result', async () => { + const repository = createRtdbMovementRepository({ db: () => fakeDb({}), rest: { read: async () => null } }); + + expect(await repository.listMovements('arrival', { fromMs: 0, toMs: 1, owner: null, limit: 1 }, { uid: 'u' })).toEqual([]); + }); + }); }); }); diff --git a/functions/movements/application/listMovements.js b/functions/movements/application/listMovements.js new file mode 100644 index 00000000..e9d77c37 --- /dev/null +++ b/functions/movements/application/listMovements.js @@ -0,0 +1,55 @@ +'use strict'; + +const { toReadView, isOwnMovement } = require('../domain/readView'); + +// Use case: the movements of a period for a caller (GET /app/movements), +// for API clients such as the Open Digital MCP hub; the app reads the +// database directly. +// +// Repository port (functions/movements/adapters/rtdbMovementRepository.js): +// resolveReader(actor, policy) -> {all, authOverride} +// listMovements(type, {fromMs, toMs, owner, limit}, authOverride) +// -> [[key, movement]], newest first +// +// As in the app: pilots get their own movements; admins and allMovements +// operators (and everyone where access is shared) all of them, those of +// others without personal data (domain/readView.js). + +const MAX_PER_TYPE = 200; +const TYPES = Object.freeze(['departure', 'arrival']); + +const timestampOf = (movement) => -movement.negativeTimestamp; + +/** + * from, to: ms since the epoch (from <= to); types: subset of TYPES. + * Resolves with {movements: [view], truncated}, views sorted by dateTime. + */ +async function listMovements({ repository, policy, actor, fromMs, toMs, types = TYPES, limit = MAX_PER_TYPE }) { + const reader = await repository.resolveReader(actor, policy); + // Without the right to see all, only movements created with the caller's + // e-mail; a caller without one (guest, kiosk) has none. + if (!reader.all && !actor.email) { + return { movements: [], truncated: false }; + } + const owner = reader.all ? null : actor.email; + + let truncated = false; + const lists = await Promise.all(types.map(async (type) => { + const entries = await repository.listMovements(type, { fromMs, toMs, owner, limit: limit + 1 }, reader.authOverride); + if (entries.length > limit) { + truncated = true; + } + return entries + .slice(0, limit) + // The query bounds already do this; a second check costs nothing. + .filter(([, movement]) => typeof movement.negativeTimestamp === 'number' + && timestampOf(movement) >= fromMs && timestampOf(movement) <= toMs + && (reader.all || isOwnMovement(movement, actor.email))) + .map(([key, movement]) => toReadView(type, key, movement, actor.email)); + })); + + const movements = lists.flat().sort((a, b) => String(a.dateTime).localeCompare(String(b.dateTime))); + return { movements, truncated }; +} + +module.exports = { listMovements, MAX_PER_TYPE, TYPES }; diff --git a/functions/movements/application/listMovements.spec.js b/functions/movements/application/listMovements.spec.js new file mode 100644 index 00000000..9cd877a7 --- /dev/null +++ b/functions/movements/application/listMovements.spec.js @@ -0,0 +1,88 @@ +'use strict'; + +const { listMovements } = require('./listMovements'); +const { loadVariant } = require('../domain/testing/projectPolicies'); +const { ACTORS } = require('../domain/testing/movementCases'); + +const at = iso => ({ dateTime: iso, negativeTimestamp: -Date.parse(iso) }); +const FROM = Date.parse('2026-11-20T00:00:00.000Z'); +const TO = Date.parse('2026-11-20T23:59:59.999Z'); + +function repositoryWith({ all = false, departures = [], arrivals = [] } = {}) { + const lists = { departure: departures, arrival: arrivals }; + return { + resolveReader: jest.fn(async () => ({ all, authOverride: { uid: 'reader' } })), + listMovements: jest.fn(async (type, query) => lists[type].slice(0, query.limit)), + }; +} + +describe('functions', () => { + describe('movements/application/listMovements', () => { + const { policy } = loadVariant('lsze'); + const list = (repository, props = {}) => + listMovements({ repository, policy, actor: ACTORS.pilot, fromMs: FROM, toMs: TO, ...props }); + + it('lists a pilot\'s own movements of both types, sorted by time', async () => { + const repository = repositoryWith({ + departures: [['d1', { ...at('2026-11-20T14:30:00.000Z'), createdBy: 'pilot@example.com', firstname: 'Hans' }]], + arrivals: [['a1', { ...at('2026-11-20T09:15:00.000Z'), createdBy: 'pilot@example.com', firstname: 'Hans' }]], + }); + + const result = await list(repository); + + expect(result.truncated).toBe(false); + expect(result.movements.map(m => [m.type, m.key, m.own, m.firstname])).toEqual([ + ['arrival', 'a1', true, 'Hans'], + ['departure', 'd1', true, 'Hans'], + ]); + expect(repository.listMovements).toHaveBeenCalledWith( + 'departure', { fromMs: FROM, toMs: TO, owner: 'pilot@example.com', limit: 201 }, { uid: 'reader' }); + }); + + it('asks for all movements for a reader who may see them, others without personal data', async () => { + const repository = repositoryWith({ + all: true, + arrivals: [ + ['a1', { ...at('2026-11-20T09:15:00.000Z'), createdBy: 'other@example.com', firstname: 'Erika', immatriculation: 'HBKOF' }], + ['a2', { ...at('2026-11-20T10:00:00.000Z'), createdBy: 'pilot@example.com', firstname: 'Hans' }], + ], + }); + + const { movements } = await list(repository, { types: ['arrival'] }); + + expect(repository.listMovements).toHaveBeenCalledWith( + 'arrival', expect.objectContaining({ owner: null }), { uid: 'reader' }); + expect(movements).toEqual([ + { type: 'arrival', key: 'a1', own: false, dateTime: '2026-11-20T09:15:00.000Z', immatriculation: 'HBKOF' }, + expect.objectContaining({ key: 'a2', own: true, firstname: 'Hans' }), + ]); + }); + + it('drops what the query should not have returned (defence in depth)', async () => { + const repository = repositoryWith({ + departures: [ + ['d1', { ...at('2026-11-21T08:00:00.000Z'), createdBy: 'pilot@example.com' }], // outside the period + ['d2', { ...at('2026-11-20T08:00:00.000Z'), createdBy: 'other@example.com' }], // not own + ['d3', { dateTime: 'x', createdBy: 'pilot@example.com' }], // no timestamp + ], + }); + + expect((await list(repository, { types: ['departure'] })).movements).toEqual([]); + }); + + it('reports truncation past the limit', async () => { + const departures = [0, 1, 2].map(i => [`d${i}`, { ...at(`2026-11-20T1${i}:00:00.000Z`), createdBy: 'pilot@example.com' }]); + const result = await list(repositoryWith({ departures }), { types: ['departure'], limit: 2 }); + + expect(result.truncated).toBe(true); + expect(result.movements).toHaveLength(2); + }); + + it('gives a caller without e-mail and without the right to see all nothing', async () => { + const repository = repositoryWith(); + + expect(await list(repository, { actor: ACTORS.guest })).toEqual({ movements: [], truncated: false }); + expect(repository.listMovements).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/functions/movements/domain/readView.js b/functions/movements/domain/readView.js new file mode 100644 index 00000000..64ed9cee --- /dev/null +++ b/functions/movements/domain/readView.js @@ -0,0 +1,92 @@ +'use strict'; + +const { hasOwn, isPlainObject } = require('./normalize'); + +// What the movement API returns of a stored movement (GET /app/movements). +// +// The caller's own movements (createdBy is the caller's e-mail) come with +// all their fields except the index fields. Movements of others, which only +// admins and allMovements operators get (rtdbMovementRepository.js +// resolveReader), carry no personal data: only the operational fields below. +// Whitelisted, so a field added to movements later stays out until it is +// listed here. Not listed on purpose: firstname, lastname, email, phone, +// memberNr, createdBy, remarks and route (free text), the customs form +// (customsFormId, customsFormUrl), privacyPolicyAcceptedAt, and of the payment +// method the invoice recipient. + +const INTERNAL_FIELDS = Object.freeze(['negativeTimestamp', 'createdBy_orderKey']); + +const OPERATIONAL_FIELDS = Object.freeze([ + 'dateTime', + 'immatriculation', + 'aircraftType', + 'aircraftCategory', + 'mtow', + 'flightType', + 'location', + 'locationName', + 'locationCountry', + 'departureRoute', + 'arrivalRoute', + 'runway', + 'duration', + 'landingCount', + 'goAroundCount', + 'passengerCount', + 'landingFeeSingle', + 'landingFeeCode', + 'landingFeeTotal', + 'goAroundFeeSingle', + 'goAroundFeeCode', + 'goAroundFeeTotal', + 'feeTotalNet', + 'feeVat', + 'feeRoundingDifference', + 'feeTotalGross', + 'aircraftDataSource', +]); + +const PAYMENT_FIELDS = Object.freeze(['method', 'status']); + +const normalizedEmail = value => (typeof value === 'string' && value !== '' ? value.toLowerCase() : null); + +/** Whether `movement` belongs to the caller with this e-mail. */ +function isOwnMovement(movement, email) { + const caller = normalizedEmail(email); + return caller !== null && normalizedEmail(movement && movement.createdBy) === caller; +} + +function pick(object, fields) { + const result = {}; + fields.forEach(field => { + if (hasOwn(object, field) && object[field] !== null && object[field] !== undefined) { + result[field] = object[field]; + } + }); + return result; +} + +/** + * Pure. The view of the stored `movement` (key `key`, 'departure' or + * 'arrival') for the caller with the e-mail `email` (or null): + * {type, key, own, ...fields}. + */ +function toReadView(type, key, movement, email) { + const own = isOwnMovement(movement, email); + let fields; + if (own) { + fields = { ...movement }; + INTERNAL_FIELDS.forEach(field => delete fields[field]); + } else { + fields = pick(movement, OPERATIONAL_FIELDS); + if (isPlainObject(movement.paymentMethod)) { + const payment = pick(movement.paymentMethod, PAYMENT_FIELDS); + if (Object.keys(payment).length > 0) { + fields.paymentMethod = payment; + } + } + } + return { type, key, own, ...fields }; +} + +module.exports = { toReadView, isOwnMovement, OPERATIONAL_FIELDS, INTERNAL_FIELDS }; diff --git a/functions/movements/domain/readView.spec.js b/functions/movements/domain/readView.spec.js new file mode 100644 index 00000000..379c41c0 --- /dev/null +++ b/functions/movements/domain/readView.spec.js @@ -0,0 +1,92 @@ +'use strict'; + +const { toReadView, isOwnMovement, OPERATIONAL_FIELDS } = require('./readView'); + +const ARRIVAL = Object.freeze({ + dateTime: '2026-11-20T16:05:00.000Z', + negativeTimestamp: -1795190700000, + createdBy: 'pilot@example.com', + createdBy_orderKey: 'pilot@example.com_8204809299999', + firstname: 'Hans', + lastname: 'Muster', + email: 'pilot@example.com', + phone: '+41 79 000 00 00', + memberNr: '123', + remarks: 'Bitte Hans anrufen', + immatriculation: 'HBPIV', + aircraftType: 'P28A', + aircraftCategory: 'Flugzeug', + mtow: 1157, + flightType: 'private', + location: 'LSZH', + arrivalRoute: 'N', + runway: '30', + landingCount: 1, + landingFeeSingle: 27.75, + landingFeeTotal: 27.75, + feeTotalNet: 27.75, + feeVat: 2.25, + feeRoundingDifference: 0, + feeTotalGross: 30, + aircraftDataSource: 'registry', + paymentMethod: { method: 'invoice', invoiceRecipientName: 'Hans Muster', status: 'pending' }, + customsFormId: 'f1', + customsFormUrl: 'https://customs.example.com/f1', + privacyPolicyAcceptedAt: '2026-11-20T16:00:00.000Z', + someFutureField: 'x', +}); + +describe('movement domain', () => { + describe('readView', () => { + it('gives the caller all fields of an own movement, without the index fields', () => { + const { negativeTimestamp, createdBy_orderKey, ...rest } = ARRIVAL; + expect(negativeTimestamp && createdBy_orderKey).toBeTruthy(); + expect(toReadView('arrival', 'k1', ARRIVAL, 'Pilot@Example.com')) + .toEqual({ type: 'arrival', key: 'k1', own: true, ...rest }); + }); + + it('gives only operational fields of the movements of others: no personal data', () => { + const view = toReadView('arrival', 'k1', ARRIVAL, 'admin@example.com'); + expect(view).toEqual({ + type: 'arrival', + key: 'k1', + own: false, + dateTime: '2026-11-20T16:05:00.000Z', + immatriculation: 'HBPIV', + aircraftType: 'P28A', + aircraftCategory: 'Flugzeug', + mtow: 1157, + flightType: 'private', + location: 'LSZH', + arrivalRoute: 'N', + runway: '30', + landingCount: 1, + landingFeeSingle: 27.75, + landingFeeTotal: 27.75, + feeTotalNet: 27.75, + feeVat: 2.25, + feeRoundingDifference: 0, + feeTotalGross: 30, + aircraftDataSource: 'registry', + paymentMethod: { method: 'invoice', status: 'pending' }, + }); + const text = JSON.stringify(view); + ['Hans', 'Muster', 'pilot@example.com', '+41', 'anrufen', 'customs', '123'].forEach(personal => { + expect(text).not.toContain(personal); + }); + }); + + it('treats a movement without owner or a caller without e-mail as not own', () => { + const { createdBy, ...ownerless } = ARRIVAL; + expect(createdBy).toBeTruthy(); + expect(isOwnMovement(ownerless, 'pilot@example.com')).toBe(false); + expect(isOwnMovement(ARRIVAL, null)).toBe(false); + expect(toReadView('departure', 'k2', ownerless, null).firstname).toBeUndefined(); + }); + + it('lists no personal field as operational', () => { + ['firstname', 'lastname', 'email', 'phone', 'memberNr', 'remarks', 'route', 'createdBy', 'customsFormUrl'] + .forEach(field => expect(OPERATIONAL_FIELDS).not.toContain(field)); + }); + }); +}); diff --git a/functions/movements/http/movementRoutes.js b/functions/movements/http/movementRoutes.js index 46715eaa..c6a2cbfa 100644 --- a/functions/movements/http/movementRoutes.js +++ b/functions/movements/http/movementRoutes.js @@ -5,20 +5,29 @@ const { getAuth } = require('firebase-admin/auth'); const { getDatabase } = require('firebase-admin/database'); const logger = require('firebase-functions/logger'); const { requestId } = require('../../api/http/requestId'); -const { appAuth } = require('../../api/http/appAuth'); +const { appAuth, requireScope } = require('../../api/http/appAuth'); const { createLoginTokenVerifier } = require('../../api/http/loginTokens'); const { asyncRoute } = require('../../api/http/asyncRoute'); const { ApiError, validationError, sendError } = require('../../api/http/errors'); const { buildMovementPolicy } = require('../domain'); const { saveMovement, OUTCOMES } = require('../application/saveMovement'); +const { listMovements } = require('../application/listMovements'); const { createRtdbMovementRepository } = require('../adapters/rtdbMovementRepository'); const { RulesRejectedError } = require('../adapters/databaseRest'); // App API for movement writes (flag movementWritesViaApi): the web app's // replacement for writing departures and arrivals to the database directly. +// And, for API clients (the Open Digital MCP hub), the movements of a period. const CREATE_PATHS = ['/app/movements/:type', '/api/app/movements/:type']; const UPDATE_PATHS = ['/app/movements/:type/:key', '/api/app/movements/:type/:key']; +const LIST_PATHS = ['/app/movements', '/api/app/movements']; + +// A list covers at most this period (and MAX_PER_TYPE movements per type). +const MAX_LIST_RANGE_MS = 31 * 24 * 60 * 60 * 1000; +// ISO 8601 in UTC, as the movements store dateTime (seconds optional). +const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?Z$/; +const LIST_TYPES = Object.freeze({ departure: ['departure'], arrival: ['arrival'] }); const TYPES_BY_PATH = Object.freeze({ departures: 'departure', arrivals: 'arrival' }); @@ -175,24 +184,85 @@ function saveHandler({ repository, policy, isCreate }) { }); } +function instantOf(query, field, errors) { + const value = query[field]; + const ms = typeof value === 'string' && ISO_INSTANT.test(value) ? Date.parse(value) : NaN; + if (Number.isNaN(ms)) { + errors.push({ field, reason: value === undefined ? 'required' : 'invalid-format' }); + } + return ms; +} + +// GET ?from=&to=[&type=departure|arrival] +function listQueryOf(req) { + const errors = []; + const fromMs = instantOf(req.query, 'from', errors); + const toMs = instantOf(req.query, 'to', errors); + const { type } = req.query; + if (type !== undefined && !Object.prototype.hasOwnProperty.call(LIST_TYPES, type)) { + errors.push({ field: 'type', reason: 'not-allowed' }); + } + if (errors.length === 0 && !(fromMs <= toMs)) { + errors.push({ field: 'to', reason: 'before-from' }); + } + if (errors.length === 0 && toMs - fromMs > MAX_LIST_RANGE_MS) { + errors.push({ field: 'to', reason: 'range-too-long' }); + } + if (errors.length > 0) { + throw validationError(errors, 'Invalid query'); + } + return { fromMs, toMs, types: type === undefined ? undefined : LIST_TYPES[type] }; +} + +function listHandler({ repository, policy }) { + return asyncRoute(async (req, res) => { + const query = listQueryOf(req); + let result; + try { + result = await listMovements({ repository, policy: policy(), actor: req.actor, ...query }); + } catch (error) { + if (error instanceof RulesRejectedError) { + logger.error('Movement list rejected by database rules after the API allowed it', { + requestId: req.requestId, + uid: req.actor.uid, + }); + throw new ApiError('internal', 'Internal error'); + } + throw error; + } + res.set('Cache-Control', 'no-store'); + res.status(200).json({ + from: new Date(query.fromMs).toISOString(), + to: new Date(query.toMs).toISOString(), + ...result, + }); + }); +} + /** * Registers POST /app/movements/:type (create) and PATCH * /app/movements/:type/:key (update, merged like RTDB update()), also under * /api, for the Firebase ID token of a signed-in user and, where the config * sets centralLogin, for access tokens of the central login (the MCP hub * writing for a pilot). Answers 201/200 {key}; errors in the envelope of - * functions/api/http/errors.js. + * functions/api/http/errors.js. And GET /app/movements?from=&to=[&type=] + * (also under /api): the movements of a period the caller may see, + * {from, to, movements, truncated} (application/listMovements.js). Tokens of + * the central login need the scope movements:write to write and + * movements:read to list. */ function registerMovementRoutes(app, config, { auth = getAuth, db = getDatabase, - repository = createRtdbMovementRepository({ db }), + repository = createRtdbMovementRepository({ db, auth }), loginTokens = createLoginTokenVerifier(config.centralLogin), } = {}) { const policy = lazyPolicy(config); - const common = [requestId, appAuth({ auth, db, loginTokens }), jsonBody()]; - app.post(CREATE_PATHS, ...common, saveHandler({ repository, policy, isCreate: true })); - app.patch(UPDATE_PATHS, ...common, saveHandler({ repository, policy, isCreate: false })); + const authenticate = appAuth({ auth, db, loginTokens }); + const write = [requestId, authenticate, requireScope('movements:write'), jsonBody()]; + app.post(CREATE_PATHS, ...write, saveHandler({ repository, policy, isCreate: true })); + app.patch(UPDATE_PATHS, ...write, saveHandler({ repository, policy, isCreate: false })); + app.get(LIST_PATHS, requestId, authenticate, requireScope('movements:read'), listHandler({ repository, policy })); } -module.exports = { registerMovementRoutes, CREATE_PATHS, UPDATE_PATHS }; +module.exports = { registerMovementRoutes, CREATE_PATHS, UPDATE_PATHS, LIST_PATHS }; diff --git a/functions/movements/http/movementRoutes.spec.js b/functions/movements/http/movementRoutes.spec.js index a140eb5f..ec721075 100644 --- a/functions/movements/http/movementRoutes.spec.js +++ b/functions/movements/http/movementRoutes.spec.js @@ -61,9 +61,14 @@ function fakeRepository({ movements = {}, settings = {} } = {}) { })), createMovement: jest.fn(async () => 'new-key'), updateMovement: jest.fn(async () => undefined), + resolveReader: jest.fn(async actor => ({ all: actor.isAdmin === true, authOverride: { uid: actor.uid, token: {} } })), + listMovements: jest.fn(async () => listed), }; } +// What repository.listMovements answers (per type). +let listed = []; + // {a: {a: ... 1}}, `depth` levels deep. function nested(depth) { let value = 1; @@ -528,6 +533,65 @@ describe('functions', () => { }); }); + describe('GET /api/app/movements', () => { + const FROM = '2026-11-20T00:00:00.000Z'; + const TO = '2026-11-20T23:59:59.999Z'; + const list = (query, uid = 'pilot-uid') => send('GET', `/api/app/movements?${new URLSearchParams(query)}`, { uid }); + + beforeEach(() => { + listed = []; + }); + + it('lists the pilot\'s own movements of the period', async () => { + listed = [['k1', { dateTime: '2026-11-20T09:00:00.000Z', negativeTimestamp: -Date.parse('2026-11-20T09:00:00.000Z'), createdBy: 'pilot@example.com', firstname: 'Hans' }]]; + + const response = await list({ from: FROM, to: TO, type: 'departure' }); + + expect(response.status).toBe(200); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(await response.json()).toEqual({ + from: FROM, + to: TO, + truncated: false, + movements: [{ type: 'departure', key: 'k1', own: true, dateTime: '2026-11-20T09:00:00.000Z', createdBy: 'pilot@example.com', firstname: 'Hans' }], + }); + expect(repository.listMovements).toHaveBeenCalledTimes(1); + expect(repository.listMovements).toHaveBeenCalledWith('departure', { + fromMs: Date.parse(FROM), toMs: Date.parse(TO), owner: 'pilot@example.com', limit: 201, + }, { uid: 'pilot-uid', token: {} }); + }); + + it('answers 400 for a missing, malformed or too long period', async () => { + const cases = [ + [{ to: TO }, [{ field: 'from', reason: 'required' }]], + [{ from: '2026-11-20', to: TO }, [{ field: 'from', reason: 'invalid-format' }]], + [{ from: TO, to: FROM }, [{ field: 'to', reason: 'before-from' }]], + [{ from: '2026-10-01T00:00:00Z', to: TO }, [{ field: 'to', reason: 'range-too-long' }]], + [{ from: FROM, to: TO, type: 'all' }, [{ field: 'type', reason: 'not-allowed' }]], + ]; + for (const [query, validationErrors] of cases) { + await expectError(await list(query), 400, { + code: 'invalid-argument', message: 'Invalid query', details: { reason: 'validation-failed', validationErrors }, + }); + } + expect(repository.listMovements).not.toHaveBeenCalled(); + }); + + it('answers 401 without a token', async () => { + expect((await list({ from: FROM, to: TO }, null)).status).toBe(401); + }); + + it('answers 500 and logs when the database rules deny what the API allowed', async () => { + repository.listMovements.mockRejectedValue(new RulesRejectedError('departures', 'read')); + + const response = await list({ from: FROM, to: TO }); + + expect(response.status).toBe(500); + expect(logger.error).toHaveBeenCalledWith( + 'Movement list rejected by database rules after the API allowed it', expect.objectContaining({ uid: 'pilot-uid' })); + }); + }); + describe('failures', () => { it('answers 500 and logs the disagreement when the rules reject an accepted write', async () => { repository.createMovement.mockRejectedValue(new RulesRejectedError('departures')); @@ -662,8 +726,8 @@ describe('functions', () => { { algorithm: 'ES256', issuer: CENTRAL_LOGIN.issuer, audience, expiresIn: 300, header: { typ: 'at+jwt', kid: 'k1', alg: 'ES256' } } ); - const loginActorOf = (email = 'pilot@example.com') => ({ - uid: `login:${SUB}`, email, isAdmin: false, isGuest: false, isKiosk: false, + const loginActorOf = (email = 'pilot@example.com', scopes = ['movements:write']) => ({ + uid: `login:${SUB}`, email, isAdmin: false, isGuest: false, isKiosk: false, scopes, }); beforeAll(async () => { @@ -730,6 +794,24 @@ describe('functions', () => { expect(repository.createMovement).not.toHaveBeenCalled(); }); + it('needs movements:write to write and movements:read to list', async () => { + const readOnly = loginToken({ scope: 'movements:read' }); + const writeOnly = loginToken({ scope: 'movements:write' }); + const query = '/api/app/movements?from=2026-11-20T00:00:00.000Z&to=2026-11-20T23:59:59.999Z'; + + const write = await sendWith(login, 'POST', '/api/app/movements/departures', readOnly, departureInput(policy)); + expect(write.status).toBe(403); + expect((await write.json()).error.details).toEqual({ reason: 'insufficient-scope' }); + expect(repository.createMovement).not.toHaveBeenCalled(); + + const readWithoutScope = await login.request(query, { headers: { Authorization: `Bearer ${writeOnly}` } }); + expect(readWithoutScope.status).toBe(403); + + const read = await login.request(query, { headers: { Authorization: `Bearer ${readOnly}` } }); + expect(read.status).toBe(200); + expect(repository.resolveReader).toHaveBeenCalledWith(loginActorOf('pilot@example.com', ['movements:read']), policy); + }); + it('rejects login tokens where centralLogin is not configured', async () => { const response = await sendWith(withoutConfig, 'POST', '/api/app/movements/departures', loginToken(), departureInput(policy)); diff --git a/package.json b/package.json index 9302e136..bdf42e49 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "test:watch": "jest --watch", "test:coverage": "jest --coverage", "test:functions": "cd functions && npm test", - "test:rules": "firebase emulators:exec --only database --config firebase.emulator.json --project demo-rules-test \"node test/rules/movementWrite.rules.js && node test/rules/movementDomainParity.rules.js && node test/rules/movementApiWrite.rules.js\"", + "test:rules": "firebase emulators:exec --only database --config firebase.emulator.json --project demo-rules-test \"node test/rules/movementWrite.rules.js && node test/rules/movementDomainParity.rules.js && node test/rules/movementApiWrite.rules.js && node test/rules/movementApiRead.rules.js\"", "test:app": "jest --testPathIgnorePatterns=functions", "codecov": "codecov", "cy:open": "cypress open", diff --git a/projects/Configuration.md b/projects/Configuration.md index 420f1484..ee71dcda 100644 --- a/projects/Configuration.md +++ b/projects/Configuration.md @@ -335,7 +335,7 @@ Lets the app API (the routes of `movementWritesViaApi`) also accept access token Digital account, `odch/odch-login`), next to the Firebase ID tokens of the app. The Open Digital MCP hub (`odch/mcp-hub`) uses them to record departures and arrivals for a pilot from an AI client (Claude etc.): it exchanges the pilot's token at the login (token exchange, RFC 8693) for a token for exactly this instance and -calls `POST/PATCH /api/app/movements/...` with it. +calls `POST/PATCH /api/app/movements/...` with it, and `GET /api/app/movements?from=&to=` to list movements. ```json "centralLogin": { @@ -351,10 +351,20 @@ calls `POST/PATCH /api/app/movements/...` with it. * `audience`: the name of this instance at the login; a token for another instance is rejected. Accepted are JWTs (`typ` `at+jwt`) signed with ES256 that carry a verified e-mail address (`email`, -`email_verified`) and the scope `movements:write`. The caller is the pilot with that address: the movement -domain and the database rules (`auth.token.email`, through `auth_variable_override`) check ownership exactly as -for a pilot signed in to the app with the same address, so the pilot sees and edits the same movements either -way. The uid is `login:`; such callers are never admins, guests or kiosks. +`email_verified`) and the scope `movements:write` (needed to write) and/or `movements:read` (needed to list). The +caller is the pilot with that address: the movement domain and the database rules (`auth.token.email`, through +`auth_variable_override`) check ownership exactly as for a pilot signed in to the app with the same address, so the +pilot sees and edits the same movements either way. The uid is `login:`; for writes such callers are +never admins, guests or kiosks. + +Listing (`GET /api/app/movements?from=&to=[&type=departure|arrival]`, at most 31 days and 200 movements +per type, `truncated` when there are more): the caller gets what the app shows them. For a token of the login these +are the rights of the app's Firebase user with the same verified e-mail: pilots get their own movements, admins +(`/admins`) and allMovements operators (`/logins//allMovements`) all of them. Movements of others come +without personal data, only their operational fields (`functions/movements/domain/readView.js`: aircraft, time, +location, route, runway, counts, fees, payment method and status; not the pilot's name, e-mail, phone, member +number, remarks, route description, customs form or invoice recipient). The API reads as the caller +(`auth_variable_override`; for an admin as their app user), so the read rules apply as in the app. Set it per environment. Only the functions read it (`functions/project-config.generated.json`, validated by `tasks/generateServerConfig.js`); without it, tokens of the login are rejected like any other unknown token. diff --git a/test/rules/movementApiRead.rules.js b/test/rules/movementApiRead.rules.js new file mode 100644 index 00000000..b6de7925 --- /dev/null +++ b/test/rules/movementApiRead.rules.js @@ -0,0 +1,216 @@ +/** + * Emulator test: movement lists through the app API (GET /app/movements, + * functions/movements) against the built database rules of lsze. + * + * Run via: npm run test:rules (starts the RTDB emulator, then runs this). + * + * The API reads as the caller (REST API with auth_variable_override), so the + * rules decide as for the web client. This checks, with the real RTDB adapter: + * - pilots get their own movements, also with a token of the central login; + * - admins and allMovements operators get all, those of others without + * personal data; a caller of the central login with the rights of the app + * user of the same verified e-mail; + * - queries the API would never make for a pilot (unbounded, another + * pilot's index), sent straight through the adapter, are denied by the + * rules. + * Only ID token verification and the app user lookup are faked. + */ +'use strict'; + +const assert = require('assert'); +const path = require('path'); + +const fromFunctions = name => require(require.resolve(name, { paths: [path.join(__dirname, '../../functions')] })); +const express = fromFunctions('express'); +const { initializeApp, deleteApp } = fromFunctions('firebase-admin/app'); +const { getDatabase } = fromFunctions('firebase-admin/database'); + +const { emulatorRulesFor } = require('./emulatorRules'); +const { loadVariant } = require('../../functions/movements/domain/testing/projectPolicies'); +const { stored } = require('../../functions/movements/domain/testing/movementCases'); +const { toOrderKey } = require('../../functions/movements/domain/orderKey'); +const { registerMovementRoutes } = require('../../functions/movements'); +const { listMovements } = require('../../functions/movements/application/listMovements'); +const { loginActor } = require('../../functions/api/http/appAuth'); +const { createRtdbMovementRepository } = require('../../functions/movements/adapters/rtdbMovementRepository'); +const { RulesRejectedError, createDatabaseRestClient } = require('../../functions/movements/adapters/databaseRest'); +const { listen } = require('../../functions/api/http/testing/listen'); + +const NAMESPACE = 'demo-movement-api'; +const EMULATOR_HOST = process.env.FIREBASE_DATABASE_EMULATOR_HOST; + +const EMAILS = { + 'pilot-uid': 'pilot@example.com', + 'other-uid': 'other@example.com', + 'admin-uid': 'admin@example.com', + 'op-uid': 'op@example.com', +}; +// The app's Firebase users by e-mail (the lookup for callers of the central login). +const APP_USERS = { + 'pilot@example.com': { uid: 'pilot-uid', emailVerified: true }, + 'admin@example.com': { uid: 'admin-uid', emailVerified: true }, + 'unverified-admin@example.com': { uid: 'admin-uid', emailVerified: false }, +}; + +const fakeAuth = () => ({ + verifyIdToken: async token => { + const uid = token.replace(/^token-/, ''); + return EMAILS[uid] ? { uid, email: EMAILS[uid] } : { uid }; + }, + getUserByEmail: async email => { + if (!APP_USERS[email]) { + throw Object.assign(new Error('no user'), { code: 'auth/user-not-found' }); + } + return { disabled: false, ...APP_USERS[email] }; + }, +}); + +let failures = 0; +async function check(label, test) { + try { + await test(); + console.log(` ✓ ${label}`); + } catch (e) { + failures++; + console.error(` ✗ ${label} — ${e.message}`); + } +} + +async function rejectedByRules(promise) { + const error = await promise.then(() => null, e => e); + assert.ok(error instanceof RulesRejectedError, `expected a rules rejection, got ${error ? error.stack : 'success'}`); +} + +async function loadRules(rulesConfig) { + const response = await fetch(`http://${EMULATOR_HOST}/.settings/rules.json?ns=${NAMESPACE}`, { + method: 'PUT', + headers: { Authorization: 'Bearer owner' }, + body: emulatorRulesFor(rulesConfig), + }); + assert.strictEqual(response.status, 200, `loading the rules failed: ${await response.text()}`); +} + +const FROM = '2026-11-20T00:00:00.000Z'; +const TO = '2026-11-20T23:59:59.999Z'; + +async function main() { + assert.ok(EMULATOR_HOST, 'FIREBASE_DATABASE_EMULATOR_HOST is not set; run via npm run test:rules'); + const credential = { getAccessToken: async () => ({ access_token: 'owner', expires_in: 3600 }) }; + const app = initializeApp({ + projectId: NAMESPACE, + databaseURL: `https://${NAMESPACE}.firebaseio.com`, + credential, + }, 'movement-api-read'); + const db = getDatabase(app); + const { rulesConfig, serverConfig, policy } = loadVariant('lsze'); + await loadRules(rulesConfig); + + // A stored movement at `iso`, created by `createdBy`, with personal data. + const movement = (type, createdBy, iso) => { + const negativeTimestamp = -Date.parse(iso); + return { + ...stored(type, policy, {}), + dateTime: iso, + negativeTimestamp, + createdBy, + createdBy_orderKey: toOrderKey(createdBy, negativeTimestamp), + firstname: 'Erika', + lastname: 'Beispiel', + email: createdBy, + phone: '+41 79 000 00 00', + remarks: 'Notiz-7Q3', + }; + }; + await db.ref().set(null); + await db.ref('admins').set({ 'admin-uid': true }); + await db.ref('logins/op-uid').set({ allMovements: true }); + await db.ref('departures').set({ + pilotDep: movement('departure', 'pilot@example.com', '2026-11-20T14:30:00.000Z'), + otherDep: movement('departure', 'other@example.com', '2026-11-20T11:00:00.000Z'), + pilotOld: movement('departure', 'pilot@example.com', '2026-11-18T09:00:00.000Z'), + }); + await db.ref('arrivals').set({ + pilotArr: movement('arrival', 'pilot@example.com', '2026-11-20T09:15:00.000Z'), + }); + + const repository = createRtdbMovementRepository({ + db: () => db, + auth: fakeAuth, + rest: createDatabaseRestClient({ app: () => app }), + }); + const api = express(); + registerMovementRoutes(api, serverConfig, { auth: fakeAuth, db: () => db, repository }); + const server = await listen(api); + const get = async (uid) => { + const response = await server.request(`/api/app/movements?from=${FROM}&to=${TO}`, { + headers: { Authorization: `Bearer token-${uid}` }, + }); + const body = await response.json(); + assert.strictEqual(response.status, 200, `${response.status} ${JSON.stringify(body)}`); + return body.movements; + }; + const listFor = actor => listMovements({ repository, policy, actor, fromMs: Date.parse(FROM), toMs: Date.parse(TO) }) + .then(result => result.movements); + const keys = movements => movements.map(m => m.key); + const login = (sub, email) => loginActor({ sub, email, scopes: ['movements:read'] }); + + console.log('movement API lists (rules of lsze, as the caller)'); + + await check('a pilot gets the own movements of the period, with all fields', async () => { + const movements = await get('pilot-uid'); + assert.deepStrictEqual(keys(movements), ['pilotArr', 'pilotDep']); + assert.ok(movements.every(m => m.own && m.firstname === 'Erika')); + }); + + await check('so does a pilot with a token of the central login', async () => { + assert.deepStrictEqual(keys(await listFor(login('sub-1', 'pilot@example.com'))), ['pilotArr', 'pilotDep']); + }); + + await check('an admin gets all, those of others without personal data', async () => { + const movements = await get('admin-uid'); + assert.deepStrictEqual(keys(movements), ['pilotArr', 'otherDep', 'pilotDep']); + const text = JSON.stringify(movements); + ['Erika', 'Beispiel', '@example.com', '+41', 'Notiz-7Q3'].forEach(personal => assert.ok(!text.includes(personal), personal)); + assert.ok(movements.every(m => !m.own && m.immatriculation)); + }); + + await check('so does an allMovements operator', async () => { + assert.deepStrictEqual(keys(await get('op-uid')), ['pilotArr', 'otherDep', 'pilotDep']); + }); + + await check('a caller of the central login has the rights of the app user of the e-mail', async () => { + assert.deepStrictEqual(keys(await listFor(login('sub-2', 'admin@example.com'))), ['pilotArr', 'otherDep', 'pilotDep']); + assert.deepStrictEqual(keys(await listFor(login('sub-3', 'unverified-admin@example.com'))), []); + assert.deepStrictEqual(keys(await listFor(login('sub-4', 'nobody@example.com'))), []); + }); + + await check('the rules deny an unbounded query to a pilot', async () => { + const rest = createDatabaseRestClient({ app: () => app }); + await rejectedByRules(rest.read('departures', { orderBy: 'negativeTimestamp', startAt: -Date.parse(TO), endAt: -Date.parse(FROM) }, + { uid: 'login:sub-1', token: { email: 'pilot@example.com' } })); + }); + + await check('the rules deny a pilot the index of another pilot', async () => { + const rest = createDatabaseRestClient({ app: () => app }); + await rejectedByRules(rest.read('departures', { + orderBy: 'createdBy_orderKey', + startAt: toOrderKey('other@example.com', -Date.parse(TO)), + endAt: toOrderKey('other@example.com', -Date.parse(FROM)), + }, { uid: 'login:sub-1', token: { email: 'pilot@example.com' } })); + }); + + await server.close(); + await deleteApp(app); +} + +main().then(() => { + if (failures > 0) { + console.error(`\n${failures} movement API list assertion(s) failed`); + process.exit(1); + } + console.log('\nAll movement API list assertions passed'); + process.exit(0); +}).catch(e => { + console.error(e); + process.exit(1); +});