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
13 changes: 9 additions & 4 deletions functions/movements/application/saveMovement.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
prepareWrite,
validateMovement,
checkAppRules,
checkWriteAccess,
CODES,
} = require('../domain');
Expand Down Expand Up @@ -60,10 +61,14 @@ async function saveMovement({ repository, policy, actor, type, key = null, input
}

const prepared = prepareWrite({ type, actor, existing, input });
const errors = validateMovement(type, prepared.movement, policy, {
writtenFields: prepared.writtenFields,
customsBaseUrl: settings.customsBaseUrl,
});
const errors = [
...validateMovement(type, prepared.movement, policy, {
writtenFields: prepared.writtenFields,
customsBaseUrl: settings.customsBaseUrl,
}),
// What the app's wizard requires beyond the database rules.
...checkAppRules(prepared.movement, policy, { writtenFields: prepared.writtenFields, isCreate }),
];
const access = checkWriteAccess({ actor, existing, next: prepared.movement, policy, settings });
const rejection = decide({ errors, access });
if (rejection) {
Expand Down
31 changes: 31 additions & 0 deletions functions/movements/application/saveMovement.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,37 @@ describe('functions', () => {
expect(repository.createMovement).not.toHaveBeenCalled();
});

it('rejects what the app would not record: no runway, a flight type of another category', async () => {
const repository = repositoryWith();

const result = await save(repository, { input: departureInput(policy, { runway: undefined, flightType: 'glider_private_winch' }) });

expect(result).toEqual({
ok: false,
code: 'invalid-argument',
validationErrors: [
{ field: 'runway', reason: 'required' },
{ field: 'flightType', reason: 'not-for-aircraft-category' },
],
});
expect(repository.createMovement).not.toHaveBeenCalled();
});

it('records a helicopter without a runway where the aerodrome says so (lsze)', async () => {
const repository = repositoryWith();

const input = departureInput(policy, { runway: undefined, aircraftCategory: 'Hubschrauber', flightType: 'private' });
expect(await save(repository, { input })).toEqual({ ok: true, key: '-Nnew', created: true });
});

it('does not ask a stored movement without a runway for one when other fields change', async () => {
const repository = repositoryWith({
existing: stored('departure', policy, { createdBy: ACTORS.pilot.email, runway: undefined }),
});

expect(await save(repository, { key: 'k1', input: { remarks: 'x' } })).toEqual({ ok: true, key: 'k1', created: false });
});

it('passes write failures on', async () => {
const repository = repositoryWith();
const failure = new Error('rules');
Expand Down
58 changes: 58 additions & 0 deletions functions/movements/domain/checkAppRules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';

const { REASONS } = require('./reasons');
const { hasOwn } = require('./normalize');
const { FLIGHT_TYPES, getAirstatType, isHelicopter } = require('../../reports/airstat/tables');

// What the app's wizard requires beyond the database rules, checked for
// writes through the API so that other clients (e.g. the Open Digital MCP
// hub) cannot record movements the app would not:
// - a runway (src/components/wizards/validate.tsx), except for helicopters
// where the aerodrome sets noRunwayIfHelicopter (the flight page
// containers hide the field);
// - a flight type the app offers for the aircraft category
// (getEnabledFlightTypes in src/util/flightTypes.ts: the category's
// aircraft type has an airstat code for it).
//
// Deliberately not in the database rules: movements stored before may lack a
// runway or have a flight type of another category. So a create checks the
// whole movement; an update only what it writes (the runway when runway or
// aircraftCategory is written, the flight type when flightType or
// aircraftCategory is). The app sends the whole movement when it edits one,
// which its wizard has checked the same way.

const isPresent = (movement, field) =>
hasOwn(movement, field) && movement[field] !== null && movement[field] !== undefined;

const KNOWN_FLIGHT_TYPES = new Set(FLIGHT_TYPES.map(type => type.value));

/**
* Pure. movement: the movement as it would be stored (prepareWrite);
* writtenFields: the fields the write sets or removes; isCreate.
* Returns [{field, reason}] like validateMovement.
*/
function checkAppRules(movement, policy, { writtenFields, isCreate }) {
const written = field => isCreate || writtenFields.includes(field);
const errors = [];
const category = movement.aircraftCategory;

if ((written('runway') || written('aircraftCategory')) && !isPresent(movement, 'runway')) {
const exempt = policy.noRunwayIfHelicopter && isHelicopter(movement.immatriculation, category);
if (!exempt) {
errors.push({ field: 'runway', reason: REASONS.REQUIRED });
}
}

// Unknown flight types and categories are validateMovement's (not-allowed).
const flightType = movement.flightType;
if ((written('flightType') || written('aircraftCategory'))
&& typeof flightType === 'string' && KNOWN_FLIGHT_TYPES.has(flightType)
&& typeof category === 'string' && policy.aircraftCategories.includes(category)
&& getAirstatType(flightType, category) === undefined) {
errors.push({ field: 'flightType', reason: REASONS.NOT_FOR_AIRCRAFT_CATEGORY });
}

return errors;
}

module.exports = { checkAppRules };
86 changes: 86 additions & 0 deletions functions/movements/domain/checkAppRules.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
'use strict';

const { checkAppRules } = require('./checkAppRules');
const { REASONS } = require('./reasons');
const { loadVariant } = require('./testing/projectPolicies');

const lsze = loadVariant('lsze').policy; // noRunwayIfHelicopter
const lszt = loadVariant('lszt').policy;

const plane = { immatriculation: 'HBKOF', aircraftCategory: 'Flugzeug', flightType: 'private', runway: '30' };
const create = (movement, policy = lsze) => checkAppRules(movement, policy, { writtenFields: [], isCreate: true });
const update = (movement, writtenFields, policy = lsze) => checkAppRules(movement, policy, { writtenFields, isCreate: false });

const runwayRequired = { field: 'runway', reason: REASONS.REQUIRED };
const notForCategory = { field: 'flightType', reason: REASONS.NOT_FOR_AIRCRAFT_CATEGORY };

describe('movement domain', () => {
describe('checkAppRules (what the app wizard requires beyond the rules)', () => {
it('accepts a complete movement', () => {
expect(create(plane)).toEqual([]);
});

describe('runway', () => {
it('is required on a create', () => {
expect(create({ ...plane, runway: undefined })).toEqual([runwayRequired]);
expect(create({ ...plane, runway: null })).toEqual([runwayRequired]);
});

it.each(['Hubschrauber', 'Eigenbauhubschrauber'])('is not required for a %s where the aerodrome says so', category => {
expect(create({ ...plane, aircraftCategory: category, flightType: 'sar', runway: undefined })).toEqual([]);
});

it('is required for helicopters where the aerodrome does not say so', () => {
expect(lszt.noRunwayIfHelicopter).toBe(false);
expect(create({ ...plane, aircraftCategory: 'Hubschrauber', runway: undefined }, lszt)).toEqual([runwayRequired]);
});

it('is checked on an update only when runway or aircraftCategory is written', () => {
const legacy = { ...plane, runway: undefined };
expect(update(legacy, ['remarks'])).toEqual([]);
expect(update(legacy, ['runway'])).toEqual([runwayRequired]);
expect(update(legacy, ['aircraftCategory'])).toEqual([runwayRequired]);
expect(update({ ...legacy, aircraftCategory: 'Hubschrauber' }, ['aircraftCategory'])).toEqual([]);
});
});

describe('flight type', () => {
it.each([
['Flugzeug', 'glider_private_winch'],
['Flugzeug', 'sar'],
['Segelflugzeug', 'private'],
['Hubschrauber', 'aerotow'],
['Motorsegler', 'military'],
])('rejects for a %s: %s', (category, flightType) => {
expect(create({ ...plane, aircraftCategory: category, flightType })).toEqual([notForCategory]);
});

it.each([
['Flugzeug', 'aerotow'],
['Motorsegler', 'aerotow'],
['Segelflugzeug', 'glider_instruction_self'],
['Eigenbausegelflugzeug', 'glider_private_aerotow'],
['Hubschrauber', 'sar'],
['Ballon (Heissluft)', 'private'],
])('accepts for a %s: %s', (category, flightType) => {
expect(create({ ...plane, aircraftCategory: category, flightType })).toEqual([]);
});

it('leaves unknown flight types and categories to validateMovement', () => {
expect(create({ ...plane, flightType: 'not-a-flight-type' })).toEqual([]);
expect(create({ ...plane, aircraftCategory: 'Rakete' })).toEqual([]);
});

it('is checked on an update only when flightType or aircraftCategory is written', () => {
const legacy = { ...plane, flightType: 'glider_private_winch' };
expect(update(legacy, ['remarks'])).toEqual([]);
expect(update(legacy, ['flightType'])).toEqual([notForCategory]);
expect(update(legacy, ['aircraftCategory'])).toEqual([notForCategory]);
});
});

it('reports both', () => {
expect(create({ ...plane, runway: undefined, flightType: 'sar' })).toEqual([runwayRequired, notForCategory]);
});
});
});
4 changes: 4 additions & 0 deletions functions/movements/domain/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
// write rules of the Realtime Database (firebase-rules-template.json as
// processed by tasks/processFirebaseRules.js) so that movement writes can go
// through the API (flag `movementWritesViaApi`) with the same outcome.
// checkAppRules adds, for the API only, what the app's wizard requires
// beyond the rules.

const { buildMovementPolicy } = require('./policy');
const { validateMovement, MOVEMENT_TYPES, PAYMENT_METHODS } = require('./validateMovement');
const { checkWriteAccess } = require('./checkWriteAccess');
const { checkAppRules } = require('./checkAppRules');
const { prepareWrite, SERVER_OWNED } = require('./prepareWrite');
const { toOrderKey } = require('./orderKey');
const { REASONS, CODES } = require('./reasons');
Expand All @@ -16,6 +19,7 @@ module.exports = {
buildMovementPolicy,
validateMovement,
checkWriteAccess,
checkAppRules,
prepareWrite,
toOrderKey,
MOVEMENT_TYPES,
Expand Down
3 changes: 3 additions & 0 deletions functions/movements/domain/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// database rules of the project: the allowed runways, routes, flight types and
// aircraft categories, the aerodrome ICAO (for 'circuits'), whether movements
// are owner-scoped (loginForm 'email') and which movement lock applies.
// Beyond the rules, for the app-level checks of the API (checkAppRules.js):
// whether helicopters record no runway (aerodrome.noRunwayIfHelicopter).

function policyError(field, problem) {
return new TypeError(`Invalid movement policy config: ${field} ${problem}`);
Expand Down Expand Up @@ -62,6 +64,7 @@ function buildMovementPolicy(config) {
// ownerless ones (processFirebaseRules.js processMovementOwnership).
personalAccess: config.loginForm === 'email',
lockOnDateTime: config.lockOnDateTime,
noRunwayIfHelicopter: aerodrome.noRunwayIfHelicopter === true,
});
}

Expand Down
8 changes: 8 additions & 0 deletions functions/movements/domain/policy.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,17 @@ describe('movement domain', () => {
aircraftCategories: ['Flugzeug', 'Motorsegler'],
personalAccess: true,
lockOnDateTime: false,
noRunwayIfHelicopter: false,
});
});

it('takes noRunwayIfHelicopter from the aerodrome (only true counts)', () => {
expect(buildMovementPolicy(withAerodrome({ noRunwayIfHelicopter: true })).noRunwayIfHelicopter).toBe(true);
expect(buildMovementPolicy(withAerodrome({ noRunwayIfHelicopter: 'yes' })).noRunwayIfHelicopter).toBe(false);
expect(loadVariant('lsze').policy.noRunwayIfHelicopter).toBe(true);
expect(loadVariant('lszt').policy.noRunwayIfHelicopter).toBe(false);
});

it('scopes movements to their owner only for the e-mail login', () => {
expect(buildMovementPolicy(withConfig({ loginForm: 'usernamePassword' })).personalAccess).toBe(false);
expect(buildMovementPolicy(withConfig({ loginForm: 'Email' })).personalAccess).toBe(false);
Expand Down
2 changes: 2 additions & 0 deletions functions/movements/domain/reasons.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const REASONS = Object.freeze({
MUST_BE_POSITIVE: 'must-be-positive',
MUST_NOT_BE_NEGATIVE: 'must-not-be-negative',
MUST_BE_NEGATIVE: 'must-be-negative',
// checkAppRules: {field, reason}
NOT_FOR_AIRCRAFT_CATEGORY: 'not-for-aircraft-category',
// checkWriteAccess: {code, reason}
UNAUTHENTICATED: 'unauthenticated',
NOT_OWNER: 'not-owner',
Expand Down
4 changes: 4 additions & 0 deletions functions/movements/domain/testing/movementCases.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ function departureInput(policy, overrides = {}) {
location: OTHER_LOCATION,
mtow: 1000,
aircraftCategory: policy.aircraftCategories[0],
// Not required by the rules; the app (and checkAppRules) asks for it.
runway: policy.runways[0],
...overrides,
};
}
Expand All @@ -89,6 +91,8 @@ function arrivalInput(policy, overrides = {}) {
location: OTHER_LOCATION,
mtow: 1000,
aircraftCategory: policy.aircraftCategories[0],
// Not required by the rules; the app (and checkAppRules) asks for it.
runway: policy.runways[0],
...overrides,
};
}
Expand Down
17 changes: 17 additions & 0 deletions functions/movements/http/movementRoutes.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,23 @@ describe('functions', () => {
expect(repository.createMovement).not.toHaveBeenCalled();
});

it('answers 400 for a movement the app would not record', async () => {
const body = departureInput(policy, { runway: undefined, aircraftCategory: 'Segelflugzeug', flightType: 'private' });

await expectError(await send('POST', '/api/app/movements/departures', { body }), 400, {
code: 'invalid-argument',
message: 'Validation failed',
details: {
reason: 'validation-failed',
validationErrors: [
{ field: 'runway', reason: 'required' },
{ field: 'flightType', reason: 'not-for-aircraft-category' },
],
},
});
expect(repository.createMovement).not.toHaveBeenCalled();
});

it('reports validation errors before the lock', async () => {
repository = fakeRepository({ settings: { lockDate: Date.parse('2026-12-01T00:00:00.000Z') } });
const body = departureInput(policy, { dateTime: undefined });
Expand Down
7 changes: 6 additions & 1 deletion projects/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,12 @@ Example: `true`
Moves the app's movement writes (creating and editing departures and arrivals, setting the payment method of an
arrival) from direct Realtime Database writes to the API of the Cloud Functions. The functions check each write
with the same rules as the database (required fields, formats, runways, routes, flight types, ownership,
movement lock) and derive `negativeTimestamp`, `createdBy` and `createdBy_orderKey` themselves. They write as
movement lock) and derive `negativeTimestamp`, `createdBy` and `createdBy_orderKey` themselves. On top of the
database rules they check what the app's wizard requires (`functions/movements/domain/checkAppRules.js`), so that
other API clients (the Open Digital MCP hub) cannot record movements the app would not: a runway, except for
helicopters where `aerodrome.noRunwayIfHelicopter` is set, and a flight type that exists for the aircraft category
(e.g. `glider_*` only for gliders; reason `not-for-aircraft-category`). A new movement is checked as a whole; a
change only in what it writes, so movements stored before without a runway can still be changed. They write as
the signed-in user, so the database rules still apply to every write. Deleting movements and reading them still
go to the database directly. Disabled by default; without it the app writes to the database as before.

Expand Down
9 changes: 8 additions & 1 deletion tasks/generateServerConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,18 @@ function buildAerodrome(project, env, aerodrome, field = 'aerodrome') {
if (typeof aerodrome.ICAO !== 'string' || !ICAO_RE.test(aerodrome.ICAO)) {
throw configError(project, env, `${field}.ICAO`, `must match ${ICAO_RE}: ${JSON.stringify(aerodrome.ICAO)}`);
}
const noRunwayIfHelicopter = hasOwn(aerodrome, 'noRunwayIfHelicopter') ? aerodrome.noRunwayIfHelicopter : false;
if (typeof noRunwayIfHelicopter !== 'boolean') {
throw configError(project, env, `${field}.noRunwayIfHelicopter`, `must be a boolean: ${JSON.stringify(noRunwayIfHelicopter)}`);
}
return {
ICAO: aerodrome.ICAO,
runways: buildRunways(project, env, aerodrome.runways),
departureRoutes: buildRoutes(project, env, aerodrome.departureRoutes, `${field}.departureRoutes`),
arrivalRoutes: buildRoutes(project, env, aerodrome.arrivalRoutes, `${field}.arrivalRoutes`)
arrivalRoutes: buildRoutes(project, env, aerodrome.arrivalRoutes, `${field}.arrivalRoutes`),
// Not in the database rules: the app's wizard asks for no runway for
// helicopters, and the movement API checks the same (checkAppRules.js).
noRunwayIfHelicopter
};
}

Expand Down
16 changes: 13 additions & 3 deletions tasks/generateServerConfig.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ describe('tasks/generateServerConfig', () => {
ICAO: client.aerodrome.ICAO,
runways: objectToArray(client.aerodrome.runways).map(({ name, type }) => ({ name, type })),
departureRoutes: objectToArray(client.aerodrome.departureRoutes).map(({ name }) => ({ name })),
arrivalRoutes: objectToArray(client.aerodrome.arrivalRoutes).map(({ name }) => ({ name }))
arrivalRoutes: objectToArray(client.aerodrome.arrivalRoutes).map(({ name }) => ({ name })),
noRunwayIfHelicopter: client.aerodrome.noRunwayIfHelicopter === true
},
...(client.centralLogin ? { centralLogin: client.centralLogin } : {})
});
Expand Down Expand Up @@ -213,16 +214,25 @@ describe('tasks/generateServerConfig', () => {
ICAO: 'LSXX',
runways: [{ name: '36', type: 'A' }],
departureRoutes: [],
arrivalRoutes: [{ name: 'west' }]
arrivalRoutes: [{ name: 'west' }],
noRunwayIfHelicopter: false
});
expect(buildServerConfig('lszt', conf, 'production').aerodrome).toEqual({
ICAO: 'LSZT',
runways: RUNWAYS,
departureRoutes: [{ name: 'south' }, { name: 'matzingen' }],
arrivalRoutes: [{ name: 'north' }]
arrivalRoutes: [{ name: 'north' }],
noRunwayIfHelicopter: false
});
});

it('takes noRunwayIfHelicopter from the aerodrome and rejects non-booleans', () => {
const withFlag = value => makeConf({ aerodrome: makeAerodrome({ noRunwayIfHelicopter: value }) });
expect(buildServerConfig('lszt', withFlag(true), 'test').aerodrome.noRunwayIfHelicopter).toBe(true);
expect(buildServerConfig('lszt', withFlag(false), 'test').aerodrome.noRunwayIfHelicopter).toBe(false);
expect(() => buildServerConfig('lszt', withFlag('true'), 'test')).toThrow(/aerodrome\.noRunwayIfHelicopter/);
});

it('emits centralLogin only for the environment that configures it', () => {
const centralLogin = {
issuer: 'https://login.example.ch',
Expand Down
Loading