Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion functions/api/http/appAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [] }) {
Expand Down
48 changes: 18 additions & 30 deletions functions/movements/adapters/rtdbMovementRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/<uid> or /logins/<uid>/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),
Expand Down Expand Up @@ -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/<uid> and
* /logins/<uid>/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',
Expand All @@ -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);
},
Expand Down
41 changes: 16 additions & 25 deletions functions/movements/adapters/rtdbMovementRepository.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'] };

Expand All @@ -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 () => {
Expand All @@ -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 () => {
Expand All @@ -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', {
Expand All @@ -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([]);
});
});
});
Expand Down
10 changes: 6 additions & 4 deletions functions/movements/application/listMovements.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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;
}
Expand Down
6 changes: 3 additions & 3 deletions functions/movements/application/listMovements.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
};
}
Expand All @@ -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 () => {
Expand All @@ -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' }),
Expand Down
4 changes: 4 additions & 0 deletions functions/movements/domain/checkAppRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions functions/movements/domain/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -20,6 +22,8 @@ module.exports = {
validateMovement,
checkWriteAccess,
checkAppRules,
readAccess,
toReadView,
prepareWrite,
toOrderKey,
MOVEMENT_TYPES,
Expand Down
30 changes: 30 additions & 0 deletions functions/movements/domain/readAccess.js
Original file line number Diff line number Diff line change
@@ -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/<uid>/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 };
36 changes: 36 additions & 0 deletions functions/movements/domain/readAccess.spec.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
});
4 changes: 2 additions & 2 deletions functions/movements/domain/readView.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading