From 50caa2e6378e4862d637c27a1db16c8687eb49bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:23:43 +0000 Subject: [PATCH] Decide in the domain who may list all movements The repository's resolveReader both loaded the reader's rights and decided with them (shared access, admin, allMovements), a business rule in the database adapter. Now the adapter only loads the facts (loadReaderFacts: the app user, its /admins and allMovements entries) and the pure domain function readAccess decides: whether the caller may list all and as which uid to read. listMovements wires the two; the repository builds the auth override from the caller it is given. checkAppRules keeps the airstat tables: they are the server's one port of the client tables (with client parity tests), and the airstat engine may only load files of its own folder. A comment says so. No change in behaviour; readAccess.spec covers the rule, the emulator read test the result against the built rules. --- functions/api/http/appAuth.js | 2 +- .../adapters/rtdbMovementRepository.js | 48 +++++++------------ .../adapters/rtdbMovementRepository.spec.js | 41 +++++++--------- .../movements/application/listMovements.js | 10 ++-- .../application/listMovements.spec.js | 6 +-- functions/movements/domain/checkAppRules.js | 4 ++ functions/movements/domain/index.js | 4 ++ functions/movements/domain/readAccess.js | 30 ++++++++++++ functions/movements/domain/readAccess.spec.js | 36 ++++++++++++++ functions/movements/domain/readView.js | 4 +- .../movements/http/movementRoutes.spec.js | 6 +-- 11 files changed, 123 insertions(+), 68 deletions(-) create mode 100644 functions/movements/domain/readAccess.js create mode 100644 functions/movements/domain/readAccess.spec.js diff --git a/functions/api/http/appAuth.js b/functions/api/http/appAuth.js index c3375f8f..55a1fd64 100644 --- a/functions/api/http/appAuth.js +++ b/functions/api/http/appAuth.js @@ -80,7 +80,7 @@ async function resolveActor(decodedToken, db) { // A pilot with a token of the central login (loginTokens.js). Never an // 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 +// domain/readAccess.js). `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 = [] }) { diff --git a/functions/movements/adapters/rtdbMovementRepository.js b/functions/movements/adapters/rtdbMovementRepository.js index 621fcdf7..fddb6f4f 100644 --- a/functions/movements/adapters/rtdbMovementRepository.js +++ b/functions/movements/adapters/rtdbMovementRepository.js @@ -40,18 +40,6 @@ async function readValue(db, path) { 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), @@ -86,32 +74,32 @@ 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. + * What decides which movements the actor may list (domain/readAccess.js): + * {appUid, admin, allMovements}. appUid: the actor's Firebase uid; for a + * caller of the central login the app user with the same verified + * e-mail, or null. admin, allMovements: that user's /admins/ and + * /logins//allMovements entries (the rules' CAN_SEE_ALL_MOVEMENTS). */ - async resolveReader(actor, policy) { - const own = authOverrideFor(actor); - if (!policy.personalAccess) { - return { all: true, authOverride: own }; + async loadReaderFacts(actor) { + const appUid = actor.uid.startsWith(LOGIN_UID_PREFIX) ? await appUserUid(auth(), actor.email) : actor.uid; + if (!appUid || INVALID_KEY_CHARS.test(appUid)) { + return { appUid: null, admin: false, allMovements: false }; } 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 }; + const [admin, allMovements] = await Promise.all([ + readValue(database, `admins/${appUid}`), + readValue(database, `logins/${appUid}/allMovements`), + ]); + return { appUid, admin: admin === true, allMovements: allMovements === true }; }, /** * 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]]. + * Read as `caller` ({uid, email}, as authOverrideFor presents it to the + * rules); resolves with [[key, movement]]. */ - async listMovements(type, { fromMs, toMs, owner, limit }, authOverride) { + async listMovements(type, { fromMs, toMs, owner, limit }, caller) { const query = owner ? { orderBy: 'createdBy_orderKey', @@ -120,7 +108,7 @@ function createRtdbMovementRepository({ db = getDatabase, auth = defaultAuth, re limitToFirst: limit, } : { orderBy: 'negativeTimestamp', startAt: -toMs, endAt: -fromMs, limitToFirst: limit }; - const answer = await rest.read(pathOf(type), query, authOverride); + const answer = await rest.read(pathOf(type), query, authOverrideFor(caller)); const entries = answer && typeof answer === 'object' ? Object.entries(answer) : []; return entries.filter(([, movement]) => movement && typeof movement === 'object').sort(byNewest); }, diff --git a/functions/movements/adapters/rtdbMovementRepository.spec.js b/functions/movements/adapters/rtdbMovementRepository.spec.js index f6f7a648..a4b3f726 100644 --- a/functions/movements/adapters/rtdbMovementRepository.spec.js +++ b/functions/movements/adapters/rtdbMovementRepository.spec.js @@ -99,8 +99,6 @@ describe('functions', () => { }); 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'] }; @@ -122,37 +120,34 @@ describe('functions', () => { db: () => fakeDb(data), auth: () => fakeAuth(users), rest: {}, }); - it('lets an app admin or allMovements operator read all, as their own uid', async () => { + it('loads the /admins and allMovements entries of a Firebase actor', 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' } } }); + expect(await repository.loadReaderFacts({ uid: 'admin-uid', email: 'admin@example.com', isAdmin: true })) + .toEqual({ appUid: 'admin-uid', admin: true, allMovements: false }); + expect(await repository.loadReaderFacts({ uid: 'op-uid', email: null })) + .toEqual({ appUid: 'op-uid', admin: false, allMovements: true }); + expect(await repository.loadReaderFacts(PILOT)).toEqual({ appUid: 'pilot-uid', admin: false, allMovements: false }); }); - it('gives a login caller the rights of the app user with the same verified e-mail', async () => { + it('takes the app user with the same verified e-mail for a login caller', 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' } } }); + expect(await repository.loadReaderFacts(LOGIN_ADMIN)).toEqual({ appUid: 'admin-uid', admin: true, allMovements: false }); + expect(await repository.loadReaderFacts(LOGIN_PILOT)).toEqual({ appUid: 'pilot-uid', admin: false, allMovements: false }); }); 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) => { + ])('finds no app user for a login caller with %s', async (_, users) => { const repository = reader({ 'admins/admin-uid': true }, users); - expect((await repository.resolveReader(LOGIN_ADMIN, PERSONAL)).all).toBe(false); + expect(await repository.loadReaderFacts(LOGIN_ADMIN)).toEqual({ appUid: null, admin: false, allMovements: false }); }); it('passes other failures of the user lookup on', async () => { @@ -161,12 +156,7 @@ describe('functions', () => { 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' } } }); + await expect(repository.loadReaderFacts(LOGIN_ADMIN)).rejects.toBe(failure); }); it('queries the owner\'s index or the timestamp, as the caller, newest first', async () => { @@ -178,10 +168,11 @@ describe('functions', () => { })), }; const repository = createRtdbMovementRepository({ db: () => fakeDb({}), rest }); + const caller = { uid: 'login:sub-1', email: 'pilot@example.com' }; 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); + const own = await repository.listMovements('arrival', { fromMs: 1000, toMs: 5000, owner: 'pilot@example.com', limit: 11 }, caller); + await repository.listMovements('departure', { fromMs: 1000, toMs: 5000, owner: null, limit: 11 }, caller); expect(own.map(([key]) => key)).toEqual(['newer', 'older']); expect(rest.read).toHaveBeenNthCalledWith(1, 'arrivals', { @@ -198,7 +189,7 @@ describe('functions', () => { 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([]); + expect(await repository.listMovements('arrival', { fromMs: 0, toMs: 1, owner: null, limit: 1 }, { uid: 'u', email: null })).toEqual([]); }); }); }); diff --git a/functions/movements/application/listMovements.js b/functions/movements/application/listMovements.js index e9d77c37..83400df2 100644 --- a/functions/movements/application/listMovements.js +++ b/functions/movements/application/listMovements.js @@ -1,14 +1,15 @@ 'use strict'; const { toReadView, isOwnMovement } = require('../domain/readView'); +const { readAccess } = require('../domain/readAccess'); // 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) +// loadReaderFacts(actor) -> {appUid, admin, allMovements} +// listMovements(type, {fromMs, toMs, owner, limit}, caller {uid, email}) // -> [[key, movement]], newest first // // As in the app: pilots get their own movements; admins and allMovements @@ -25,17 +26,18 @@ const timestampOf = (movement) => -movement.negativeTimestamp; * 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); + const reader = readAccess(actor, policy, await repository.loadReaderFacts(actor)); // 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; + const caller = { uid: reader.uid, email: 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); + const entries = await repository.listMovements(type, { fromMs, toMs, owner, limit: limit + 1 }, caller); if (entries.length > limit) { truncated = true; } diff --git a/functions/movements/application/listMovements.spec.js b/functions/movements/application/listMovements.spec.js index 9cd877a7..6a6d05b5 100644 --- a/functions/movements/application/listMovements.spec.js +++ b/functions/movements/application/listMovements.spec.js @@ -11,7 +11,7 @@ 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' } })), + loadReaderFacts: jest.fn(async () => ({ appUid: all ? 'reader' : null, admin: all, allMovements: false })), listMovements: jest.fn(async (type, query) => lists[type].slice(0, query.limit)), }; } @@ -36,7 +36,7 @@ describe('functions', () => { ['departure', 'd1', true, 'Hans'], ]); expect(repository.listMovements).toHaveBeenCalledWith( - 'departure', { fromMs: FROM, toMs: TO, owner: 'pilot@example.com', limit: 201 }, { uid: 'reader' }); + 'departure', { fromMs: FROM, toMs: TO, owner: 'pilot@example.com', limit: 201 }, { uid: 'pilot-uid', email: 'pilot@example.com' }); }); it('asks for all movements for a reader who may see them, others without personal data', async () => { @@ -51,7 +51,7 @@ describe('functions', () => { const { movements } = await list(repository, { types: ['arrival'] }); expect(repository.listMovements).toHaveBeenCalledWith( - 'arrival', expect.objectContaining({ owner: null }), { uid: 'reader' }); + 'arrival', expect.objectContaining({ owner: null }), { uid: 'reader', email: 'pilot@example.com' }); 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' }), diff --git a/functions/movements/domain/checkAppRules.js b/functions/movements/domain/checkAppRules.js index ad3928ee..b4b64be1 100644 --- a/functions/movements/domain/checkAppRules.js +++ b/functions/movements/domain/checkAppRules.js @@ -2,6 +2,10 @@ const { REASONS } = require('./reasons'); const { hasOwn } = require('./normalize'); +// The server's one port of the client's flight type and category tables +// (with client parity tests, src/util/airstatOracles/tables.spec.js). It +// lives in the airstat engine, which may only load files of its own folder; +// depending on it from here costs nothing (pure data, no packages). const { FLIGHT_TYPES, getAirstatType, isHelicopter } = require('../../reports/airstat/tables'); // What the app's wizard requires beyond the database rules, checked for diff --git a/functions/movements/domain/index.js b/functions/movements/domain/index.js index a5a36a51..ae7b23c8 100644 --- a/functions/movements/domain/index.js +++ b/functions/movements/domain/index.js @@ -11,6 +11,8 @@ const { buildMovementPolicy } = require('./policy'); const { validateMovement, MOVEMENT_TYPES, PAYMENT_METHODS } = require('./validateMovement'); const { checkWriteAccess } = require('./checkWriteAccess'); const { checkAppRules } = require('./checkAppRules'); +const { readAccess } = require('./readAccess'); +const { toReadView } = require('./readView'); const { prepareWrite, SERVER_OWNED } = require('./prepareWrite'); const { toOrderKey } = require('./orderKey'); const { REASONS, CODES } = require('./reasons'); @@ -20,6 +22,8 @@ module.exports = { validateMovement, checkWriteAccess, checkAppRules, + readAccess, + toReadView, prepareWrite, toOrderKey, MOVEMENT_TYPES, diff --git a/functions/movements/domain/readAccess.js b/functions/movements/domain/readAccess.js new file mode 100644 index 00000000..30049888 --- /dev/null +++ b/functions/movements/domain/readAccess.js @@ -0,0 +1,30 @@ +'use strict'; + +// Which movements a caller may list (GET /app/movements), as in the app: +// where access is shared (policy.personalAccess false) everyone sees all; +// otherwise admins and allMovements operators (the client's +// canSeeAllMovements, the rules' CAN_SEE_ALL_MOVEMENTS) see all, pilots only +// their own. +// +// The facts come from the repository (loadReaderFacts): the app user the +// caller is (the Firebase uid; for a caller of the central login the app +// user with the same verified e-mail, or null) and that user's /admins and +// /logins//allMovements entries. + +/** + * Pure. facts: {appUid: string|null, admin: boolean, allMovements: boolean}. + * Returns {all, uid}: whether the caller may list all movements, and the uid + * to read as (for an all read the app user's, so the database rules see the + * same uid as for the app). + */ +function readAccess(actor, policy, facts) { + if (!policy.personalAccess) { + return { all: true, uid: actor.uid }; + } + if (typeof facts.appUid === 'string' && facts.appUid !== '' && (facts.admin === true || facts.allMovements === true)) { + return { all: true, uid: facts.appUid }; + } + return { all: false, uid: actor.uid }; +} + +module.exports = { readAccess }; diff --git a/functions/movements/domain/readAccess.spec.js b/functions/movements/domain/readAccess.spec.js new file mode 100644 index 00000000..9885040a --- /dev/null +++ b/functions/movements/domain/readAccess.spec.js @@ -0,0 +1,36 @@ +'use strict'; + +const { readAccess } = require('./readAccess'); + +const PERSONAL = { personalAccess: true }; +const SHARED = { personalAccess: false }; +const PILOT = { uid: 'pilot-uid', email: 'pilot@example.com' }; +const LOGIN = { uid: 'login:sub-1', email: 'admin@example.com', scopes: ['movements:read'] }; +const facts = (overrides = {}) => ({ appUid: null, admin: false, allMovements: false, ...overrides }); + +describe('movement domain', () => { + describe('readAccess', () => { + it('lets everyone list all where access is shared, as themselves', () => { + expect(readAccess(PILOT, SHARED, facts())).toEqual({ all: true, uid: 'pilot-uid' }); + }); + + it('lets admins and allMovements operators list all, as their app user', () => { + expect(readAccess(PILOT, PERSONAL, facts({ appUid: 'pilot-uid', admin: true }))).toEqual({ all: true, uid: 'pilot-uid' }); + expect(readAccess(LOGIN, PERSONAL, facts({ appUid: 'admin-uid', allMovements: true }))).toEqual({ all: true, uid: 'admin-uid' }); + }); + + it('gives pilots their own movements, as themselves', () => { + expect(readAccess(PILOT, PERSONAL, facts({ appUid: 'pilot-uid' }))).toEqual({ all: false, uid: 'pilot-uid' }); + expect(readAccess(LOGIN, PERSONAL, facts({ appUid: 'other-uid' }))).toEqual({ all: false, uid: 'login:sub-1' }); + }); + + it('needs an app user for the rights (a login caller without one is a pilot)', () => { + expect(readAccess(LOGIN, PERSONAL, facts({ appUid: null, admin: true }))).toEqual({ all: false, uid: 'login:sub-1' }); + expect(readAccess(LOGIN, PERSONAL, facts({ appUid: '', admin: true })).all).toBe(false); + }); + + it('counts only true entries', () => { + expect(readAccess(PILOT, PERSONAL, facts({ appUid: 'pilot-uid', admin: 'true', allMovements: 1 })).all).toBe(false); + }); + }); +}); diff --git a/functions/movements/domain/readView.js b/functions/movements/domain/readView.js index 64ed9cee..e1d6c1eb 100644 --- a/functions/movements/domain/readView.js +++ b/functions/movements/domain/readView.js @@ -6,8 +6,8 @@ const { hasOwn, isPlainObject } = require('./normalize'); // // 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. +// admins and allMovements operators get (readAccess.js), 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 diff --git a/functions/movements/http/movementRoutes.spec.js b/functions/movements/http/movementRoutes.spec.js index ec721075..c59bebf2 100644 --- a/functions/movements/http/movementRoutes.spec.js +++ b/functions/movements/http/movementRoutes.spec.js @@ -61,7 +61,7 @@ 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: {} } })), + loadReaderFacts: jest.fn(async actor => ({ appUid: actor.uid, admin: actor.isAdmin === true, allMovements: false })), listMovements: jest.fn(async () => listed), }; } @@ -558,7 +558,7 @@ describe('functions', () => { 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: {} }); + }, { uid: 'pilot-uid', email: 'pilot@example.com' }); }); it('answers 400 for a missing, malformed or too long period', async () => { @@ -809,7 +809,7 @@ describe('functions', () => { 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); + expect(repository.loadReaderFacts).toHaveBeenCalledWith(loginActorOf('pilot@example.com', ['movements:read'])); }); it('rejects login tokens where centralLogin is not configured', async () => {