diff --git a/functions/movements/application/saveMovement.js b/functions/movements/application/saveMovement.js index 61e07b8b..61829a18 100644 --- a/functions/movements/application/saveMovement.js +++ b/functions/movements/application/saveMovement.js @@ -3,6 +3,7 @@ const { prepareWrite, validateMovement, + checkAppRules, checkWriteAccess, CODES, } = require('../domain'); @@ -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) { diff --git a/functions/movements/application/saveMovement.spec.js b/functions/movements/application/saveMovement.spec.js index 55a7ad1d..53066bd3 100644 --- a/functions/movements/application/saveMovement.spec.js +++ b/functions/movements/application/saveMovement.spec.js @@ -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'); diff --git a/functions/movements/domain/checkAppRules.js b/functions/movements/domain/checkAppRules.js new file mode 100644 index 00000000..ad3928ee --- /dev/null +++ b/functions/movements/domain/checkAppRules.js @@ -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 }; diff --git a/functions/movements/domain/checkAppRules.spec.js b/functions/movements/domain/checkAppRules.spec.js new file mode 100644 index 00000000..86884554 --- /dev/null +++ b/functions/movements/domain/checkAppRules.spec.js @@ -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]); + }); + }); +}); diff --git a/functions/movements/domain/index.js b/functions/movements/domain/index.js index ad08c55f..a5a36a51 100644 --- a/functions/movements/domain/index.js +++ b/functions/movements/domain/index.js @@ -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'); @@ -16,6 +19,7 @@ module.exports = { buildMovementPolicy, validateMovement, checkWriteAccess, + checkAppRules, prepareWrite, toOrderKey, MOVEMENT_TYPES, diff --git a/functions/movements/domain/policy.js b/functions/movements/domain/policy.js index e91ab0ac..afe3f468 100644 --- a/functions/movements/domain/policy.js +++ b/functions/movements/domain/policy.js @@ -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}`); @@ -62,6 +64,7 @@ function buildMovementPolicy(config) { // ownerless ones (processFirebaseRules.js processMovementOwnership). personalAccess: config.loginForm === 'email', lockOnDateTime: config.lockOnDateTime, + noRunwayIfHelicopter: aerodrome.noRunwayIfHelicopter === true, }); } diff --git a/functions/movements/domain/policy.spec.js b/functions/movements/domain/policy.spec.js index 2267ab05..2436ccd1 100644 --- a/functions/movements/domain/policy.spec.js +++ b/functions/movements/domain/policy.spec.js @@ -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); diff --git a/functions/movements/domain/reasons.js b/functions/movements/domain/reasons.js index 2d6cd56b..3adb4013 100644 --- a/functions/movements/domain/reasons.js +++ b/functions/movements/domain/reasons.js @@ -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', diff --git a/functions/movements/domain/testing/movementCases.js b/functions/movements/domain/testing/movementCases.js index a3ebfa2f..7b5e3ee6 100644 --- a/functions/movements/domain/testing/movementCases.js +++ b/functions/movements/domain/testing/movementCases.js @@ -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, }; } @@ -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, }; } diff --git a/functions/movements/http/movementRoutes.spec.js b/functions/movements/http/movementRoutes.spec.js index dda324ac..a140eb5f 100644 --- a/functions/movements/http/movementRoutes.spec.js +++ b/functions/movements/http/movementRoutes.spec.js @@ -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 }); diff --git a/projects/Configuration.md b/projects/Configuration.md index bff1d019..420f1484 100644 --- a/projects/Configuration.md +++ b/projects/Configuration.md @@ -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. diff --git a/tasks/generateServerConfig.js b/tasks/generateServerConfig.js index 31cef839..b41b89fb 100644 --- a/tasks/generateServerConfig.js +++ b/tasks/generateServerConfig.js @@ -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 }; } diff --git a/tasks/generateServerConfig.spec.js b/tasks/generateServerConfig.spec.js index 186f4731..43122787 100644 --- a/tasks/generateServerConfig.spec.js +++ b/tasks/generateServerConfig.spec.js @@ -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 } : {}) }); @@ -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',