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
4 changes: 4 additions & 0 deletions .github/workflows/test-pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ jobs:
- run: npm run build
- run: npm run test:app
- run: npm run cy:test
# The movement specs again, with the app built with
# movementWritesViaApi (projects/cypress-testing-api.json), plus the
# specs of cypress/integration/movements_api
- run: npm run cy:test:api
build_functions:
if: '${{ github.event.pull_request.head.repo.full_name == github.repository }}'
runs-on: ubuntu-latest
Expand Down
31 changes: 29 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,22 @@ with it. All routes answer CORS requests from any origin.
| `POST` | `/api/customs/prepopulated-forms` | user, not guest or kiosk | [Customs](#customs) form for a movement |
| `GET` | `/api/customs/availability` | user | Whether [customs](#customs) is configured |
| `GET` | `/api/users/me/invoice-recipients` | user | [Invoice recipients](#invoice-recipients) of the user |
| `POST` | `/api/app/movements/<type>` | user | Creates a departure or arrival, see [Movement writes](#movement-writes) |
| `PATCH` | `/api/app/movements/<type>/<key>` | user | Updates a departure or arrival, see [Movement writes](#movement-writes) |

*Anyone* needs no authentication, *user* the Firebase ID token of a logged-in user, *admin* that of an admin
(see [Authentication](#authentication)). The airstat report and the API keys exist only on projects with
`reportApiEnabled` (see `projects/Configuration.md`).
`reportApiEnabled`, the movement writes only on projects with `movementWritesViaApi` (see
`projects/Configuration.md`).

#### Authentication ####

* **API key** (external programs): `Authorization: Bearer fbx_...`, see [API keys](#api-keys).
* **Firebase ID token** (the app): `Authorization: Bearer <ID token>` of a logged-in user. Without a valid,
unrevoked token the answer is `401 Unauthorized`. Routes for admins answer `403 Forbidden: Admins only` to
other users, and the customs form answers `403 Forbidden: not available to shared sessions` to guest and kiosk
logins. These answers are not JSON: the body is just that text (sent as `text/html`).
logins. These answers are not JSON: the body is just that text (sent as `text/html`). The
[movement writes](#movement-writes) answer in their JSON error format instead.

#### Aerodrome status ####

Expand Down Expand Up @@ -307,6 +311,29 @@ For the first two, the outcome is stored in `/settings/customsSyncStatus/<invoic
(`status` `ok` or `error`, `timestamp`, `rejected` entries, `httpStatus`) and shown on their admin tabs. A failed
push is not retried automatically; the next change of the list pushes the whole list again.

#### Movement writes ####

Only on projects with `movementWritesViaApi`. `<type>` is `departures` or `arrivals`; the body is a JSON object
with the movement's fields, as the app stores them in the database.

* `POST /api/app/movements/<type>` (user): creates the movement, `201 {"key": "<key>"}`.
* `PATCH /api/app/movements/<type>/<key>` (user): updates it like a Realtime Database `update()`: each field of the
body replaces the stored one, `null` removes it, other fields stay. `200 {"key": "<key>"}`.

The checks are those of the database rules (fields, runways, routes, flight types, ownership, movement lock);
`negativeTimestamp`, `createdBy` and `createdBy_orderKey` are set by the server, values sent for them are
ignored. The function writes as the caller, so the database rules apply to the write as well. Errors are JSON,
`{"error": {"code", "message", "details"}}`, with an `X-Request-Id` header:

* `400 invalid-argument`: `details.validationErrors` lists `{field, reason}`, or `details.reason` is
`invalid-body` / `malformed-body`;
* `401 unauthenticated`: no valid ID token;
* `403 permission-denied`: the movement belongs to someone else (only on projects with `loginForm` `email`:
pilots write their own movements, guest and kiosk only those without owner, admins all);
* `404 not-found`: unknown `<type>` or key;
* `409 failed-precondition`: the movement is in a locked period;
* `500 internal`: anything else, also when the database rules reject a write the checks accepted.

#### Invoice recipients ####

`GET /api/users/me/invoice-recipients` (user): the names of the invoice recipients (`/settings/invoiceRecipients`)
Expand Down
29 changes: 27 additions & 2 deletions cypress/CYPRESS_TESTING_SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,38 @@ npm run cy:open
npm run cy:run
```

### Movement writes via the API

The movement specs also run with the app built with `movementWritesViaApi`
(see `projects/Configuration.md`), so they cover saving through the app API
as well as direct database writes:

```bash
npm run cy:test:api
```

It builds the app from `projects/cypress-testing-api.json` (which extends
`cypress-testing` and only switches the flag on), exposes
`movementWritesViaApi=true` to the specs (`cypress run --expose`, read
with `Cypress.expose()`; `Cypress.env()` is gone since Cypress 16) and runs `cypress/integration/movements/**` and
`cypress/integration/movements_api/**`. The specs in `movements_api` cover
behaviour that only exists on the API path; the default run skips them. CI
runs both (`.github/workflows/test-pull-request.yml`).

The API run needs the movement routes in the deployed functions:
`npm run deploy:cypress` generates the functions config from
`cypress-testing-api`, so the `cypress-testing` functions have the flag. The
default run is not affected: its app keeps writing to the database directly.

## Cloud Functions deployment

The association E2E tests (Scenarios 3–6) require the **fixed** trigger functions
to be deployed to the `cypress-testing` Firebase project:
to be deployed to the `cypress-testing` Firebase project. Deploy with
`npm run deploy:cypress` (see above), not a plain `firebase deploy`: without
the generated config the movement routes the API run needs are missing.

```bash
firebase deploy --only functions --project cypress-testing
cd functions && npm run deploy:cypress
```

Scenarios 1–2 (basic bidirectional linking) work with both old and new trigger code.
Expand Down
182 changes: 182 additions & 0 deletions cypress/integration/movements_api/save_movement_api_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// Behaviour that only exists when the app saves movements through the app
// API (movementWritesViaApi). Runs in `npm run cy:test:api`, which builds
// the app from projects/cypress-testing-api.json and exposes the Cypress value
// movementWritesViaApi; skipped in the default run (direct database writes).
// The other movement specs run in both modes.

const describeWithApi = Cypress.expose('movementWritesViaApi') ? describe : describe.skip;

const CREATE_DEPARTURE = '**/api/app/movements/departures';
const UPDATE_DEPARTURE = '**/api/app/movements/departures/*';

const readDepartures = () =>
cy.window().then(win =>
win.firebase.getRef('/departures').once('value').then(snapshot => snapshot.val() || {})
);

// After "next" on the departure/arrival page the wizard checks the location
// asynchronously; confirm the dialog if it shows up.
const confirmLocationIfAsked = () => {
cy.get('[data-cy=location-confirmation-dialog-confirm], [data-cy=remarks]', {timeout: 8000})
.then($els => {
if ($els.filter('[data-cy=location-confirmation-dialog-confirm]').length > 0) {
cy.get('[data-cy=location-confirmation-dialog-confirm]').click();
}
});
};

// Fills the new-departure wizard up to the commit dialog (not confirmed).
const fillNewDeparture = remarks => {
cy.visit('#/departure/new');

cy.get('[data-cy=immatriculation]').type('HBKOF');
cy.get('[data-cy=aircraftType]').type('DR40');
cy.get('[data-cy=mtow]').type('1000');
cy.get('[data-cy=aircraftCategory]').click();
cy.get('[data-cy=aircraftCategory-option-Flugzeug]').click();
cy.get('[data-cy=next-button]').click();

cy.get('[data-cy=lastname]').type('Muster');
cy.get('[data-cy=firstname]').type('Max');
cy.get('[data-cy=email]').type('max@example.com');
cy.get('[data-cy=phone]').type('0791234567');
cy.get('[data-cy=next-button]').click();

cy.get('[data-cy=next-button]').click();

cy.get('[data-cy=location]').type('LSZR');
cy.get('[data-cy=duration-hours-increment]').click();
cy.get('[data-cy=next-button]').click();
confirmLocationIfAsked();

cy.get('[data-cy=flightType-private]').click();
cy.get('[data-cy=runway-36]').click();
cy.get('[data-cy=departureRoute-west]').click();
cy.get('[data-cy=remarks]').type(remarks);
cy.get('[data-cy=next-button]').click();
};

describeWithApi('movements_api', () => {
describe('save_movement_api', () => {
beforeEach(() => {
cy.visit('#/');
cy.loginAdmin();
cy.resetMovementsTestData();
cy.logout();
cy.login();
});

afterEach(() => {
cy.logout();
});

it('creates and edits a departure through the API, not the database', () => {
cy.intercept('POST', CREATE_DEPARTURE).as('create');
cy.intercept('PATCH', UPDATE_DEPARTURE).as('update');

fillNewDeparture('Created via API');
cy.get('[data-cy=commit-requirement-dialog-confirm]').click();

cy.wait('@create').then(({request, response}) => {
expect(request.headers.authorization).to.match(/^Bearer \S+$/);
expect(response.statusCode).to.equal(201);
expect(response.body.key).to.be.a('string');
cy.wrap(response.body.key).as('key');
});
cy.get('[data-cy=finish-button]').should('be.visible');

cy.get('@key').then(key => readDepartures().then(departures => {
expect(Object.keys(departures)).to.deep.equal([key]);
const stored = departures[key];
expect(stored.remarks).to.equal('Created via API');
// Set by the server, derived from dateTime
expect(stored.negativeTimestamp).to.equal(-Date.parse(stored.dateTime));
// The static Cypress login has no e-mail, so the movement may be
// ownerless; the order key exists exactly when createdBy does.
if (stored.createdBy) {
expect(stored.createdBy_orderKey.startsWith(`${stored.createdBy}_`)).to.equal(true);
} else {
expect(stored).not.to.have.property('createdBy_orderKey');
}
}));

// Edit it from the movement list as admin, like edit_movement_spec
cy.logout();
cy.loginAdmin();
cy.viewport(1400, 900);
cy.visit('#/movements');
cy.get('@key').then(key => {
cy.get(`[data-id="${key}"]`).find('.immatriculation').click();
cy.get('[data-cy=action-edit]').first().click();
cy.hash().should('include', `/departure/${key}`);
});
cy.get('[data-cy=next-button]').click();
cy.get('[data-cy=next-button]').click();
cy.get('[data-cy=next-button]').click();
cy.get('[data-cy=next-button]').click();
confirmLocationIfAsked();
cy.get('[data-cy=remarks]').clear().type('Edited via API');
cy.get('[data-cy=next-button]').click();
cy.get('[data-cy=commit-requirement-dialog-confirm], [data-cy=finish-button]')
.then($els => {
if ($els.filter('[data-cy=commit-requirement-dialog-confirm]').length > 0) {
cy.get('[data-cy=commit-requirement-dialog-confirm]').click();
}
});

cy.wait('@update').its('response.statusCode').should('equal', 200);
cy.get('[data-cy=finish-button]').should('be.visible');

cy.get('@key').then(key => readDepartures().then(departures => {
expect(departures[key].remarks).to.equal('Edited via API');
}));
});

it('shows the validation error of the API and stores nothing', () => {
// The forms only offer valid values, so the request is altered on its
// way to the real API, which rejects the unknown runway.
cy.intercept('POST', CREATE_DEPARTURE, req => {
req.body = {...req.body, runway: '99'};
}).as('create');

fillNewDeparture('Rejected by the API');
cy.get('[data-cy=commit-requirement-dialog-confirm]').click();

cy.wait('@create').then(({response}) => {
expect(response.statusCode).to.equal(400);
expect(response.body.error.code).to.equal('invalid-argument');
expect(response.body.error.details.validationErrors)
.to.deep.include({field: 'runway', reason: 'not-allowed'});
});
cy.contains('Validation failed: runway').should('be.visible');
cy.get('[data-cy=finish-button]').should('not.exist');

readDepartures().then(departures => {
expect(departures).to.deep.equal({});
});
});

it('saves a new departure only once on a double click', () => {
// Slow the answer down so the second click lands while the first
// save is still running.
cy.intercept('POST', CREATE_DEPARTURE, req => {
req.on('response', res => {
res.setDelay(1500);
});
}).as('create');

fillNewDeparture('Double click');
cy.get('[data-cy=commit-requirement-dialog-confirm]').dblclick();

cy.wait('@create');
cy.get('[data-cy=finish-button]').should('be.visible');
// Leave time for a second request to show up, then count
cy.wait(2000);
cy.get('@create.all').should('have.length', 1);

readDepartures().then(departures => {
expect(Object.keys(departures)).to.have.length(1);
});
});
});
});
Loading
Loading