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
26 changes: 24 additions & 2 deletions functions/api/http/appAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,35 @@ async function resolveActor(decodedToken, db) {
}

// A pilot with a token of the central login (loginTokens.js). Never an
// admin: admin rights stay with the Firebase accounts of this instance.
function loginActor({ sub, email }) {
// 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
// (movements:write, movements:read); Firebase actors have none, the app may
// do everything its user may.
function loginActor({ sub, email, scopes = [] }) {
return {
uid: `${LOGIN_UID_PREFIX}${sub}`,
email,
isAdmin: false,
isGuest: false,
isKiosk: false,
scopes: Object.freeze([...scopes]),
};
}

/**
* Middleware after appAuth: a caller whose token carries scopes (the central
* login) needs `scope`, otherwise 403 (reason insufficient-scope).
*/
function requireScope(scope) {
return (req, res, next) => {
const { scopes } = req.actor || {};
if (Array.isArray(scopes) && !scopes.includes(scope)) {
return sendError(req, res, new ApiError('permission-denied', `The token does not allow ${scope}`, {
reason: 'insufficient-scope',
}));
}
return next();
};
}

Expand Down Expand Up @@ -169,6 +190,7 @@ function appAuth({ auth = getAuth, db = getDatabase, loginTokens = null } = {})

module.exports = {
appAuth,
requireScope,
resolveActor,
loginActor,
bearerToken,
Expand Down
33 changes: 29 additions & 4 deletions functions/api/http/appAuth.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const express = require('express');
const logger = require('firebase-functions/logger');
const { getAuth } = require('firebase-admin/auth');
const { getDatabase } = require('firebase-admin/database');
const { appAuth, resolveActor, loginActor, bearerToken } = require('./appAuth');
const { appAuth, resolveActor, loginActor, bearerToken, requireScope } = require('./appAuth');
const { LoginTokenRejected } = require('./loginTokens');
const { requestId } = require('./requestId');
const { listen } = require('./testing/listen');
Expand Down Expand Up @@ -329,7 +329,7 @@ describe('functions', () => {
db = fakeDb({ 'login:sub-1': true });
loginTokens = {
isLoginToken: jest.fn(token => token.startsWith('login.')),
verify: jest.fn(async () => ({ sub: 'sub-1', email: 'pilot@example.ch' })),
verify: jest.fn(async () => ({ sub: 'sub-1', email: 'pilot@example.ch', scopes: ['movements:write'] })),
};
});

Expand All @@ -345,6 +345,7 @@ describe('functions', () => {
isAdmin: false,
isGuest: false,
isKiosk: false,
scopes: ['movements:write'],
});
expect(loginTokens.verify).toHaveBeenCalledWith('login.token');
expect(auth.verifyIdToken).not.toHaveBeenCalled();
Expand Down Expand Up @@ -384,8 +385,32 @@ describe('functions', () => {
});

it('builds the actor with the login uid prefix', () => {
expect(loginActor({ sub: 'abc', email: 'a@b.ch' })).toEqual({
uid: 'login:abc', email: 'a@b.ch', isAdmin: false, isGuest: false, isKiosk: false,
expect(loginActor({ sub: 'abc', email: 'a@b.ch', scopes: ['movements:read'] })).toEqual({
uid: 'login:abc', email: 'a@b.ch', isAdmin: false, isGuest: false, isKiosk: false, scopes: ['movements:read'],
});
});
});

describe('requireScope', () => {
const run = (actor) => {
const req = { actor, requestId: 'r1', get: () => undefined };
const res = { status: jest.fn(() => res), json: jest.fn(() => res), set: jest.fn(() => res) };
const next = jest.fn();
requireScope('movements:read')(req, res, next);
return { res, next };
};

it('lets Firebase actors (no scopes) and tokens with the scope through', () => {
expect(run({ uid: 'u1' }).next).toHaveBeenCalled();
expect(run(loginActor({ sub: 'a', email: 'a@b.ch', scopes: ['movements:read'] })).next).toHaveBeenCalled();
});

it('answers 403 insufficient-scope for a token without it', () => {
const { res, next } = run(loginActor({ sub: 'a', email: 'a@b.ch', scopes: ['movements:write'] }));
expect(next).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith({
error: { code: 'permission-denied', message: 'The token does not allow movements:read', details: { reason: 'insufficient-scope' } },
});
});
});
Expand Down
14 changes: 8 additions & 6 deletions functions/api/http/loginTokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ const { validateCentralLogin } = require('./centralLoginConfig');
// The hub (odch/mcp-hub) obtains such tokens by token exchange (RFC 8693)
// for exactly this instance: a JWT (RFC 9068, typ at+jwt) signed with ES256,
// iss = issuer, aud = audience (e.g. "flightbox-lsze-test"), with the
// pilot's verified e-mail and the movements:write scope.
// pilot's verified e-mail and the movements:write and/or movements:read
// scope; the routes check the one they need (appAuth.js requireScope).

const ALGORITHMS = ['ES256'];
const TOKEN_TYPES = new Set(['at+jwt', 'application/at+jwt']);
const REQUIRED_SCOPE = 'movements:write';
const MOVEMENT_SCOPES = Object.freeze(['movements:write', 'movements:read']);
const CLOCK_TOLERANCE_SECONDS = 30;
// The login issues these tokens for 5 minutes; anything longer lived is not
// one of them.
Expand Down Expand Up @@ -203,13 +204,14 @@ function createLoginTokenVerifier(config, { fetchImpl = (...args) => fetch(...ar
if (typeof payload.email !== 'string' || payload.email === '' || payload.email_verified !== true) {
reject('no verified e-mail');
}
const scopes = typeof payload.scope === 'string' ? payload.scope.split(' ') : [];
if (!scopes.includes(REQUIRED_SCOPE)) {
const scopes = (typeof payload.scope === 'string' ? payload.scope.split(' ') : [])
.filter(scope => MOVEMENT_SCOPES.includes(scope));
if (scopes.length === 0) {
reject('scope');
}
// Lower-cased like Firebase Auth stores addresses, so a pilot owns the
// same movements whichever way they signed in.
return { sub: payload.sub, email: payload.email.toLowerCase() };
return { sub: payload.sub, email: payload.email.toLowerCase(), scopes: [...new Set(scopes)] };
}

return {
Expand All @@ -220,8 +222,8 @@ function createLoginTokenVerifier(config, { fetchImpl = (...args) => fetch(...ar
}

module.exports = {
MOVEMENT_SCOPES,
createLoginTokenVerifier,
validateCentralLogin,
LoginTokenRejected,
REQUIRED_SCOPE,
};
9 changes: 8 additions & 1 deletion functions/api/http/loginTokens.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe('functions', () => {
it('accepts a token of the login and returns the subject and lower-cased e-mail', async () => {
const token = sign(keys.privateKey);
expect(verifier.isLoginToken(token)).toBe(true);
await expect(verifier.verify(token)).resolves.toEqual({ sub: SUB, email: 'pilot@example.com' });
await expect(verifier.verify(token)).resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:write'] });
expect(fetchImpl).toHaveBeenCalledWith(CONFIG.jwksUri, expect.objectContaining({ signal: expect.anything() }));
});

Expand Down Expand Up @@ -126,6 +126,13 @@ describe('functions', () => {
expect(await rejection(sign(keys.privateKey, { scope: 'openid email' }))).toBe('scope');
});

it('accepts movements:read and returns only the movement scopes', async () => {
await expect(verifier.verify(sign(keys.privateKey, { scope: 'movements:read' })))
.resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:read'] });
await expect(verifier.verify(sign(keys.privateKey, { scope: 'openid movements:read movements:write account' })))
.resolves.toEqual({ sub: SUB, email: 'pilot@example.com', scopes: ['movements:read', 'movements:write'] });
});

it('caches the keys and refetches for an unknown kid, rate limited', async () => {
await verifier.verify(sign(keys.privateKey));
await verifier.verify(sign(keys.privateKey));
Expand Down
6 changes: 4 additions & 2 deletions functions/api/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,11 @@ describe('functions', () => {
expect(routes).toEqual([
[['post'], ['/app/movements/:type', '/api/app/movements/:type']],
[['patch'], ['/app/movements/:type/:key', '/api/app/movements/:type/:key']],
[['get'], ['/app/movements', '/api/app/movements']],
]);
// requestId, appAuth, JSON body, handler
movementLayers.forEach(layer => expect(layer.route.stack).toHaveLength(4));
// Writes: requestId, appAuth, requireScope, JSON body, handler; the
// list: requestId, appAuth, requireScope, handler.
expect(movementLayers.map(layer => layer.route.stack.length)).toEqual([5, 5, 4]);
});

it('lets admins manage API keys when the tenant has an API feature', () => {
Expand Down
45 changes: 39 additions & 6 deletions functions/movements/adapters/databaseRest.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ const TOKEN_RENEWAL_MARGIN_MS = 5 * 60 * 1000;
// does when FIREBASE_DATABASE_EMULATOR_HOST is set).
const EMULATOR_TOKEN = 'owner';

// The database denied the write: its rules (`.write` or `.validate`) do not
// allow it for the caller the request was made for.
// The database denied the request: its rules (`.read`, `.write` or
// `.validate`) do not allow it for the caller the request was made for.
class RulesRejectedError extends Error {
constructor(path) {
super(`Database rules rejected the write to ${path}`);
constructor(path, operation = 'write') {
super(`Database rules rejected the ${operation} of ${path}`);
this.name = 'RulesRejectedError';
this.path = path;
}
Expand Down Expand Up @@ -72,7 +72,7 @@ function assertAuthOverride(authOverride) {
&& typeof authOverride.uid === 'string'
&& authOverride.uid !== '';
if (!isValid) {
throw new TypeError('A write on behalf of a caller needs an auth override with a uid');
throw new TypeError('A request on behalf of a caller needs an auth override with a uid');
}
}

Expand Down Expand Up @@ -172,7 +172,40 @@ function createDatabaseRestClient({
throw new DatabaseRestError(`Database ${method} ${path} answered ${response.status}`, response.status);
}

return { write };
/**
* GET of `path` as the caller, with a query (`orderBy`, `startAt`,
* `endAt`, `limitToFirst`; values are JSON-encoded as the REST API
* expects). Resolves with the parsed value (null when there is none).
*/
async function read(path, query, authOverride) {
assertAuthOverride(authOverride);
const destination = resolve();
const token = destination.emulator ? EMULATOR_TOKEN : await serviceAccountToken();
const params = { auth_variable_override: JSON.stringify(authOverride) };
Object.entries(query || {}).forEach(([name, value]) => {
params[name] = JSON.stringify(value);
});
let response;
try {
response = await fetchImpl(requestUrl(destination, path, params), {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new DatabaseRestError(`Database GET ${path} failed: ${e.name}: ${e.message}`);
}
const answer = await readJson(response);
if (response.ok) {
return answer;
}
if (isPermissionDenied(response.status, answer)) {
throw new RulesRejectedError(path, 'read');
}
throw new DatabaseRestError(`Database GET ${path} answered ${response.status}`, response.status);
}

return { write, read };
}

module.exports = {
Expand Down
38 changes: 38 additions & 0 deletions functions/movements/adapters/databaseRest.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,5 +200,43 @@ describe('functions', () => {
await expect(client.write('POST', 'departures', {}, PILOT)).rejects.toThrow(DatabaseRestError);
});
});

describe('read', () => {
it('queries as the caller with JSON-encoded parameters', async () => {
const { client, call } = setup({ answer: response(200, { k1: { immatriculation: 'HBPIV' } }) });

const answer = await client.read('arrivals', {
orderBy: 'createdBy_orderKey', startAt: 'pilot@example.com_1', endAt: 'pilot@example.com_2', limitToFirst: 201,
}, PILOT);

expect(answer).toEqual({ k1: { immatriculation: 'HBPIV' } });
const { url, init } = call(0);
expect(url.pathname).toBe('/arrivals.json');
expect(init.method).toBe('GET');
expect(init.headers.Authorization).toBe('Bearer access-1');
expect(JSON.parse(url.searchParams.get('auth_variable_override'))).toEqual(PILOT);
expect(url.searchParams.get('orderBy')).toBe('"createdBy_orderKey"');
expect(url.searchParams.get('startAt')).toBe('"pilot@example.com_1"');
expect(url.searchParams.get('limitToFirst')).toBe('201');
});

it('never reads without a caller', async () => {
const { client, fetchImpl } = setup();

await expect(client.read('arrivals', {}, { uid: '' })).rejects.toThrow(TypeError);
expect(fetchImpl).not.toHaveBeenCalled();
});

it('reports a rules denial as RulesRejectedError and other failures as DatabaseRestError', async () => {
const denied = await setup({ answer: response(401, { error: 'Permission denied' }) })
.client.read('arrivals', {}, PILOT).catch(e => e);
expect(denied).toBeInstanceOf(RulesRejectedError);
expect(denied.message).toBe('Database rules rejected the read of arrivals');

const failed = await setup({ answer: response(500) }).client.read('arrivals', {}, PILOT).catch(e => e);
expect(failed).toBeInstanceOf(DatabaseRestError);
expect(failed.status).toBe(500);
});
});
});
});
Loading
Loading