diff --git a/functions/api/http/appAuth.js b/functions/api/http/appAuth.js index 0b87ed12..96ee0df3 100644 --- a/functions/api/http/appAuth.js +++ b/functions/api/http/appAuth.js @@ -4,11 +4,17 @@ const { getAuth } = require('firebase-admin/auth'); const { getDatabase } = require('firebase-admin/database'); const logger = require('firebase-functions/logger'); const { ApiError, sendError } = require('./errors'); +const { LoginTokenRejected } = require('./loginTokens'); // Shared sessions sign in with a fixed uid (functions/auth/modes). const GUEST_UID = 'guest'; const KIOSK_UID = 'kiosk'; +// Callers with a token of the central login get this uid prefix, so they +// can never collide with a Firebase uid (no ':' in those), e.g. the admin +// lookup or the guest and kiosk uids. +const LOGIN_UID_PREFIX = 'login:'; + // Characters that are not allowed in a Realtime Database key. const INVALID_KEY_CHARS = /[.#$[\]/]/; @@ -71,6 +77,18 @@ 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 }) { + return { + uid: `${LOGIN_UID_PREFIX}${sub}`, + email, + isAdmin: false, + isGuest: false, + isKiosk: false, + }; +} + function rejectUnauthenticated(req, res, message) { res.set('WWW-Authenticate', 'Bearer'); sendError(req, res, new ApiError('unauthenticated', message)); @@ -87,6 +105,24 @@ async function verifyToken(auth, idToken) { } } +async function authenticateLoginToken(req, res, next, loginTokens, token) { + let identity; + try { + identity = await loginTokens.verify(token); + } catch (error) { + if (error instanceof LoginTokenRejected) { + logger.info('Login token rejected', { + requestId: req.requestId, + reason: error.message, + }); + return rejectUnauthenticated(req, res, 'Invalid or expired token'); + } + return sendError(req, res, error); + } + req.actor = loginActor(identity); + return next(); +} + /** * Middleware for routes the web app calls with the user's Firebase ID token * (`Authorization: Bearer `). Revoked tokens and disabled users are @@ -95,13 +131,21 @@ async function verifyToken(auth, idToken) { * token is answered 401 in the error envelope; infrastructure faults * (signing keys or revocation lookup unavailable, failed admin lookup) are * logged and answered 500, so an outage does not look like a sign-out. + * + * With `loginTokens` (createLoginTokenVerifier of loginTokens.js, only where + * the project config sets centralLogin), access tokens of the central login + * are accepted as well: the actor is then the pilot with the token's + * verified e-mail, uid "login:", never an admin. */ -function appAuth({ auth = getAuth, db = getDatabase } = {}) { +function appAuth({ auth = getAuth, db = getDatabase, loginTokens = null } = {}) { return async (req, res, next) => { const idToken = bearerToken(req.get('Authorization')); if (!idToken) { return rejectUnauthenticated(req, res, 'Authentication required'); } + if (loginTokens && loginTokens.isLoginToken(idToken)) { + return authenticateLoginToken(req, res, next, loginTokens, idToken); + } let actor; try { @@ -123,4 +167,12 @@ function appAuth({ auth = getAuth, db = getDatabase } = {}) { }; } -module.exports = { appAuth, resolveActor, bearerToken, GUEST_UID, KIOSK_UID }; +module.exports = { + appAuth, + resolveActor, + loginActor, + bearerToken, + GUEST_UID, + KIOSK_UID, + LOGIN_UID_PREFIX, +}; diff --git a/functions/api/http/appAuth.spec.js b/functions/api/http/appAuth.spec.js index c7702cc3..a893563c 100644 --- a/functions/api/http/appAuth.spec.js +++ b/functions/api/http/appAuth.spec.js @@ -9,7 +9,8 @@ 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, bearerToken } = require('./appAuth'); +const { appAuth, resolveActor, loginActor, bearerToken } = require('./appAuth'); +const { LoginTokenRejected } = require('./loginTokens'); const { requestId } = require('./requestId'); const { listen } = require('./testing/listen'); @@ -296,6 +297,99 @@ describe('functions', () => { }); }); + describe('central login tokens', () => { + let auth; + let db; + let loginTokens; + let server; + + beforeAll(async () => { + const app = express(); + app.use(requestId); + app.get( + '/me', + appAuth({ + auth: () => auth, + db: () => db, + loginTokens: { + isLoginToken: token => loginTokens.isLoginToken(token), + verify: token => loginTokens.verify(token), + }, + }), + (req, res) => res.json(req.actor) + ); + server = await listen(app); + }); + + afterAll(() => server.close()); + + beforeEach(() => { + auth = fakeAuth(); + // Even an /admins entry for the uid must not make it an admin. + 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' })), + }; + }); + + const get = token => server.request('/me', { headers: { Authorization: `Bearer ${token}` } }); + + it('describes the pilot of a login token, never as admin', async () => { + const response = await get('login.token'); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + uid: 'login:sub-1', + email: 'pilot@example.ch', + isAdmin: false, + isGuest: false, + isKiosk: false, + }); + expect(loginTokens.verify).toHaveBeenCalledWith('login.token'); + expect(auth.verifyIdToken).not.toHaveBeenCalled(); + expect(db.ref).not.toHaveBeenCalled(); + }); + + it('answers 401 for a rejected login token', async () => { + loginTokens.verify.mockRejectedValue(new LoginTokenRejected('expired')); + + const response = await get('login.token'); + + expect(response.status).toBe(401); + expect(response.headers.get('www-authenticate')).toBe('Bearer'); + expect(await response.json()).toEqual({ + error: { code: 'unauthenticated', message: 'Invalid or expired token' }, + }); + expect(logger.info).toHaveBeenCalledWith('Login token rejected', expect.objectContaining({ reason: 'expired' })); + }); + + it('answers 500 when the login keys cannot be fetched', async () => { + loginTokens.verify.mockRejectedValue(new Error('Fetching the login keys failed')); + + const response = await get('login.token'); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: { code: 'internal', message: 'Internal error' } }); + expect(logger.error).toHaveBeenCalled(); + }); + + it('still verifies Firebase ID tokens with Firebase', async () => { + const response = await get('token-u1'); + + expect(response.status).toBe(200); + expect((await response.json()).uid).toBe('u1'); + expect(loginTokens.verify).not.toHaveBeenCalled(); + expect(auth.verifyIdToken).toHaveBeenCalledWith('token-u1', true); + }); + + 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, + }); + }); + }); + describe('defaults', () => { it('uses the Firebase Admin SDK', async () => { const auth = fakeAuth(); diff --git a/functions/api/http/centralLoginConfig.js b/functions/api/http/centralLoginConfig.js new file mode 100644 index 00000000..d5ffca27 --- /dev/null +++ b/functions/api/http/centralLoginConfig.js @@ -0,0 +1,46 @@ +'use strict'; + +// Validation of the `centralLogin` project config (see loginTokens.js). +// Without dependencies: tasks/generateServerConfig.js loads it at deploy +// time, outside the functions' node_modules. + +const AUDIENCE = /^[a-z0-9][a-z0-9-]{1,62}$/; + +function isHttpsUrl(value, { allowPath }) { + let url; + try { + url = new URL(value); + } catch (e) { + return false; + } + const isLocal = url.hostname === 'localhost' || url.hostname === '127.0.0.1'; + return (url.protocol === 'https:' || (url.protocol === 'http:' && isLocal)) + && !url.search && !url.hash && !url.username && !url.password + && (allowPath || url.href === `${url.origin}/`); +} + +/** + * Returns `config` when it is a valid centralLogin config + * ({issuer, jwksUri, audience}), else throws a TypeError naming the problem. + */ +function validateCentralLogin(config) { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw new TypeError('must be an object'); + } + const keys = Object.keys(config).sort().join(); + if (keys !== 'audience,issuer,jwksUri') { + throw new TypeError('must have exactly issuer, jwksUri and audience'); + } + if (typeof config.issuer !== 'string' || !isHttpsUrl(config.issuer, { allowPath: false }) || config.issuer.endsWith('/')) { + throw new TypeError('issuer must be an https origin without a trailing slash'); + } + if (typeof config.jwksUri !== 'string' || !isHttpsUrl(config.jwksUri, { allowPath: true })) { + throw new TypeError('jwksUri must be an https URL'); + } + if (typeof config.audience !== 'string' || !AUDIENCE.test(config.audience)) { + throw new TypeError(`audience must match ${AUDIENCE}`); + } + return config; +} + +module.exports = { validateCentralLogin }; diff --git a/functions/api/http/loginTokens.js b/functions/api/http/loginTokens.js new file mode 100644 index 00000000..378bd0e9 --- /dev/null +++ b/functions/api/http/loginTokens.js @@ -0,0 +1,227 @@ +'use strict'; + +const crypto = require('crypto'); +const jwt = require('jsonwebtoken'); +const logger = require('firebase-functions/logger'); +const { validateCentralLogin } = require('./centralLoginConfig'); + +// Access tokens of the central login (Open Digital account, odch/odch-login) +// as an alternative to Firebase ID tokens, for the app API routes. Only +// where the project config sets `centralLogin` (tasks/generateServerConfig.js): +// +// centralLogin: { issuer, jwksUri, audience } +// +// 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. + +const ALGORITHMS = ['ES256']; +const TOKEN_TYPES = new Set(['at+jwt', 'application/at+jwt']); +const REQUIRED_SCOPE = 'movements:write'; +const CLOCK_TOLERANCE_SECONDS = 30; +// The login issues these tokens for 5 minutes; anything longer lived is not +// one of them. +const MAX_LIFETIME_SECONDS = 60 * 60; +const SUBJECT = /^[A-Za-z0-9-]{1,128}$/; + +const KEYS_MAX_AGE_MS = 10 * 60 * 1000; +// An unknown kid triggers a refetch (key rotation), at most this often. +const REFETCH_COOLDOWN_MS = 30 * 1000; +const FETCH_TIMEOUT_MS = 5000; + +// The token itself is not acceptable: answered 401. Every other error (keys +// not reachable) is an infrastructure fault: answered 500. +class LoginTokenRejected extends Error { + constructor(reason) { + super(reason); + this.name = 'LoginTokenRejected'; + } +} + +const reject = reason => { + throw new LoginTokenRejected(reason); +}; + +// The claims of a JWT without verifying it, only to see which issuer it +// claims to be from; null if it is no JWT. +function unverifiedIssuer(token) { + const parts = token.split('.'); + if (parts.length !== 3) { + return null; + } + try { + const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); + return payload !== null && typeof payload === 'object' && typeof payload.iss === 'string' ? payload.iss : null; + } catch (e) { + return null; + } +} + +function toKeyObject(jwk) { + const isSigningKey = jwk !== null && typeof jwk === 'object' + && jwk.kty === 'EC' && jwk.crv === 'P-256' + && typeof jwk.kid === 'string' && jwk.kid !== '' + && (jwk.use === undefined || jwk.use === 'sig') + && (jwk.alg === undefined || jwk.alg === 'ES256') + && jwk.d === undefined; + if (!isSigningKey) { + return null; + } + try { + return crypto.createPublicKey({ key: { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }, format: 'jwk' }); + } catch (e) { + return null; + } +} + +/** + * The login's signing keys by kid, from its JWKS. Cached for + * KEYS_MAX_AGE_MS; an unknown kid refetches (rate limited). When a refetch + * fails, keys fetched before keep working. + */ +function createKeySource({ jwksUri, fetchImpl, now }) { + let keys = new Map(); + let fetchedAt = -Infinity; + let pending = null; + + async function refetch() { + let response; + try { + response = await fetchImpl(jwksUri, { + headers: { Accept: 'application/json' }, + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + } catch (e) { + throw new Error(`Fetching the login keys failed: ${e.name}: ${e.message}`); + } + if (!response.ok) { + throw new Error(`Fetching the login keys answered ${response.status}`); + } + const body = await response.json(); + const next = new Map(); + (Array.isArray(body && body.keys) ? body.keys : []).forEach(jwk => { + const key = toKeyObject(jwk); + if (key) { + next.set(jwk.kid, key); + } + }); + keys = next; + fetchedAt = now(); + } + + function refetchOnce() { + if (!pending) { + pending = refetch().finally(() => { + pending = null; + }); + } + return pending; + } + + return async function getKey(kid) { + const age = now() - fetchedAt; + const stale = age >= KEYS_MAX_AGE_MS; + if (stale || (!keys.has(kid) && age >= REFETCH_COOLDOWN_MS)) { + try { + await refetchOnce(); + } catch (error) { + if (!keys.has(kid)) { + throw error; + } + logger.warn('Using cached login keys, refetch failed', { error: error.message }); + } + } + return keys.get(kid) || null; + }; +} + +/** + * Returns null when `config` (the project config's centralLogin) is absent, + * else a verifier with + * - isLoginToken(token): whether the token claims to be from the login + * (only then is verify() the right check for it); + * - verify(token): resolves with {sub, email} or rejects with + * LoginTokenRejected (bad token) or another error (keys not reachable). + * An invalid config is logged and treated as absent, so it cannot break the + * api function; the deploy already rejects it (generateServerConfig.js). + */ +function createLoginTokenVerifier(config, { fetchImpl = (...args) => fetch(...args), now = Date.now } = {}) { + if (config === undefined || config === null) { + return null; + } + try { + validateCentralLogin(config); + } catch (error) { + logger.error(`Invalid centralLogin config, login tokens disabled: ${error.message}`); + return null; + } + const { issuer, audience } = config; + const getKey = createKeySource({ jwksUri: config.jwksUri, fetchImpl, now }); + + async function verify(token) { + const decoded = jwt.decode(token, { complete: true }); + if (!decoded || !decoded.header || typeof decoded.payload !== 'object' || decoded.payload === null) { + reject('malformed'); + } + const { header } = decoded; + if (!ALGORITHMS.includes(header.alg)) { + reject('algorithm'); + } + if (typeof header.typ !== 'string' || !TOKEN_TYPES.has(header.typ.toLowerCase())) { + reject('type'); + } + if (typeof header.kid !== 'string' || header.kid === '') { + reject('kid'); + } + const key = await getKey(header.kid); + if (!key) { + reject('unknown key'); + } + + let payload; + try { + payload = jwt.verify(token, key, { + algorithms: ALGORITHMS, + issuer, + audience, + clockTolerance: CLOCK_TOLERANCE_SECONDS, + }); + } catch (error) { + reject(error.name === 'TokenExpiredError' ? 'expired' : `invalid: ${error.message}`); + } + + const nowSeconds = Math.floor(now() / 1000); + if (!Number.isInteger(payload.exp) || !Number.isInteger(payload.iat) + || payload.exp - payload.iat > MAX_LIFETIME_SECONDS + || payload.iat > nowSeconds + CLOCK_TOLERANCE_SECONDS) { + reject('lifetime'); + } + if (typeof payload.sub !== 'string' || !SUBJECT.test(payload.sub)) { + reject('subject'); + } + 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)) { + 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 { + issuer, + isLoginToken: token => unverifiedIssuer(token) === issuer, + verify, + }; +} + +module.exports = { + createLoginTokenVerifier, + validateCentralLogin, + LoginTokenRejected, + REQUIRED_SCOPE, +}; diff --git a/functions/api/http/loginTokens.spec.js b/functions/api/http/loginTokens.spec.js new file mode 100644 index 00000000..918d8d6c --- /dev/null +++ b/functions/api/http/loginTokens.spec.js @@ -0,0 +1,197 @@ +/** @jest-environment node */ +'use strict'; + +jest.mock('firebase-functions/logger', () => ({ error: jest.fn(), info: jest.fn(), warn: jest.fn() })); + +const crypto = require('crypto'); +const jwt = require('jsonwebtoken'); +const logger = require('firebase-functions/logger'); +const { createLoginTokenVerifier, LoginTokenRejected } = require('./loginTokens'); +const { validateCentralLogin } = require('./centralLoginConfig'); + +const CONFIG = Object.freeze({ + issuer: 'https://login.example.ch', + jwksUri: 'https://login.example.ch/jwks', + audience: 'flightbox-lsze-test', +}); +const SUB = '7f3c1a52-0d7e-4c43-9a55-2a1f1a0e8b11'; + +const keyPair = () => crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); +const publicJwk = (publicKey, kid) => ({ ...publicKey.export({ format: 'jwk' }), kid, alg: 'ES256', use: 'sig' }); + +function sign(privateKey, claims = {}, { kid = 'k1', typ = 'at+jwt', alg = 'ES256', expiresIn = 300 } = {}) { + return jwt.sign( + { + sub: SUB, + email: 'Pilot@Example.com', + email_verified: true, + scope: 'movements:write', + client_id: 'mcp-hub', + ...claims, + }, + privateKey, + { + algorithm: alg, + issuer: CONFIG.issuer, + audience: CONFIG.audience, + expiresIn, + header: { typ, kid, alg }, + } + ); +} + +describe('functions', () => { + describe('api/http/loginTokens', () => { + let keys; + let jwks; + let fetchImpl; + let clock; + let verifier; + + beforeEach(() => { + jest.clearAllMocks(); + keys = keyPair(); + jwks = { keys: [publicJwk(keys.publicKey, 'k1')] }; + clock = Date.now(); + fetchImpl = jest.fn(async () => ({ ok: true, status: 200, json: async () => jwks })); + verifier = createLoginTokenVerifier(CONFIG, { fetchImpl, now: () => clock }); + }); + + const rejection = async token => { + const error = await verifier.verify(token).then(() => null, e => e); + expect(error).toBeInstanceOf(LoginTokenRejected); + return error.message; + }; + + it('is null without config', () => { + expect(createLoginTokenVerifier(undefined)).toBeNull(); + expect(createLoginTokenVerifier(null)).toBeNull(); + }); + + it('is null and logs for an invalid config', () => { + expect(createLoginTokenVerifier({ ...CONFIG, issuer: 'http://login.example.ch' })).toBeNull(); + expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Invalid centralLogin config')); + }); + + 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' }); + expect(fetchImpl).toHaveBeenCalledWith(CONFIG.jwksUri, expect.objectContaining({ signal: expect.anything() })); + }); + + it('recognises only tokens that claim the login as issuer', () => { + const firebaseLike = jwt.sign({ iss: 'https://securetoken.google.com/lsze-test', sub: 'u1' }, 'secret'); + expect(verifier.isLoginToken(firebaseLike)).toBe(false); + expect(verifier.isLoginToken('token-pilot-uid')).toBe(false); + expect(verifier.isLoginToken('a.b.c')).toBe(false); + expect(verifier.isLoginToken('')).toBe(false); + }); + + it('rejects tokens for another audience or issuer', async () => { + expect(await rejection(jwt.sign({ sub: SUB }, keys.privateKey, { + algorithm: 'ES256', issuer: CONFIG.issuer, audience: 'flightbox-lszt-prod', expiresIn: 300, header: { typ: 'at+jwt', kid: 'k1', alg: 'ES256' }, + }))).toMatch(/^invalid: jwt audience invalid/); + expect(await rejection(jwt.sign({ sub: SUB }, keys.privateKey, { + algorithm: 'ES256', issuer: 'https://evil.example', audience: CONFIG.audience, expiresIn: 300, header: { typ: 'at+jwt', kid: 'k1', alg: 'ES256' }, + }))).toMatch(/^invalid: jwt issuer invalid/); + }); + + it('rejects expired tokens and tokens that live too long', async () => { + expect(await rejection(sign(keys.privateKey, {}, { expiresIn: -60 }))).toBe('expired'); + expect(await rejection(sign(keys.privateKey, {}, { expiresIn: 2 * 60 * 60 }))).toBe('lifetime'); + }); + + it('rejects other algorithms, types and missing key ids', async () => { + const publicPem = keys.publicKey.export({ format: 'pem', type: 'spki' }); + expect(await rejection(sign(publicPem, {}, { alg: 'HS256' }))).toBe('algorithm'); + const unsigned = `${Buffer.from(JSON.stringify({ alg: 'none', typ: 'at+jwt', kid: 'k1' })).toString('base64url')}.${ + Buffer.from(JSON.stringify({ iss: CONFIG.issuer, aud: CONFIG.audience, sub: SUB })).toString('base64url')}.`; + expect(await rejection(unsigned)).toBe('algorithm'); + expect(await rejection(sign(keys.privateKey, {}, { typ: 'JWT' }))).toBe('type'); + expect(await rejection(sign(keys.privateKey, {}, { kid: '' }))).toBe('kid'); + expect(await rejection('not-a-jwt')).toBe('malformed'); + }); + + it('rejects a signature of another key, also under a known kid', async () => { + const other = keyPair(); + expect(await rejection(sign(other.privateKey))).toMatch(/^invalid: invalid signature/); + expect(await rejection(sign(other.privateKey, {}, { kid: 'unknown' }))).toBe('unknown key'); + }); + + it('requires a verified e-mail, a subject and the movements scope', async () => { + expect(await rejection(sign(keys.privateKey, { email: undefined }))).toBe('no verified e-mail'); + expect(await rejection(sign(keys.privateKey, { email_verified: false }))).toBe('no verified e-mail'); + expect(await rejection(sign(keys.privateKey, { sub: 'a/b' }))).toBe('subject'); + expect(await rejection(sign(keys.privateKey, { scope: 'openid email' }))).toBe('scope'); + }); + + 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)); + expect(fetchImpl).toHaveBeenCalledTimes(1); + + // Rotation: the new key appears in the JWKS later. + const rotated = keyPair(); + expect(await rejection(sign(rotated.privateKey, {}, { kid: 'k2' }))).toBe('unknown key'); + expect(fetchImpl).toHaveBeenCalledTimes(1); + jwks = { keys: [...jwks.keys, publicJwk(rotated.publicKey, 'k2')] }; + clock += 31 * 1000; + await expect(verifier.verify(sign(rotated.privateKey, {}, { kid: 'k2' }))).resolves.toEqual(expect.objectContaining({ sub: SUB })); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it('ignores keys that are not EC P-256 signing keys', async () => { + const rsa = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); + jwks = { keys: [{ ...rsa.publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'RS256' }] }; + expect(await rejection(sign(keys.privateKey))).toBe('unknown key'); + }); + + it('fails as an infrastructure error when the keys cannot be fetched', async () => { + fetchImpl.mockImplementation(async () => { + throw new TypeError('fetch failed'); + }); + const error = await verifier.verify(sign(keys.privateKey)).then(() => null, e => e); + expect(error).not.toBeInstanceOf(LoginTokenRejected); + expect(error.message).toMatch(/Fetching the login keys failed/); + + fetchImpl.mockImplementation(async () => ({ ok: false, status: 503, json: async () => ({}) })); + clock += 31 * 1000; + const unavailable = await verifier.verify(sign(keys.privateKey)).then(() => null, e => e); + expect(unavailable.message).toMatch(/answered 503/); + }); + + it('keeps using cached keys when a refetch fails', async () => { + await verifier.verify(sign(keys.privateKey)); + fetchImpl.mockImplementation(async () => { + throw new TypeError('fetch failed'); + }); + clock += 11 * 60 * 1000; + await expect(verifier.verify(sign(keys.privateKey))).resolves.toEqual(expect.objectContaining({ sub: SUB })); + expect(logger.warn).toHaveBeenCalled(); + }); + }); + + describe('api/http/centralLoginConfig', () => { + it('accepts a complete config', () => { + expect(validateCentralLogin(CONFIG)).toBe(CONFIG); + expect(validateCentralLogin({ ...CONFIG, issuer: 'http://localhost:4000', jwksUri: 'http://localhost:4000/jwks' })).toBeTruthy(); + }); + + it.each([ + [null, 'must be an object'], + [[], 'must be an object'], + [{ issuer: CONFIG.issuer, audience: CONFIG.audience }, 'exactly'], + [{ ...CONFIG, extra: 1 }, 'exactly'], + [{ ...CONFIG, issuer: 'http://login.example.ch' }, 'issuer'], + [{ ...CONFIG, issuer: 'https://login.example.ch/' }, 'issuer'], + [{ ...CONFIG, issuer: 'https://login.example.ch/path' }, 'issuer'], + [{ ...CONFIG, jwksUri: 'ftp://login.example.ch/jwks' }, 'jwksUri'], + [{ ...CONFIG, jwksUri: 'https://login.example.ch/jwks?x=1' }, 'jwksUri'], + [{ ...CONFIG, audience: 'Flightbox LSZE' }, 'audience'], + [{ ...CONFIG, audience: 42 }, 'audience'], + ])('rejects %j', (config, message) => { + expect(() => validateCentralLogin(config)).toThrow(message); + }); + }); +}); diff --git a/functions/movements/http/movementRoutes.js b/functions/movements/http/movementRoutes.js index a63b9a51..46715eaa 100644 --- a/functions/movements/http/movementRoutes.js +++ b/functions/movements/http/movementRoutes.js @@ -6,6 +6,7 @@ const { getDatabase } = require('firebase-admin/database'); const logger = require('firebase-functions/logger'); const { requestId } = require('../../api/http/requestId'); const { appAuth } = require('../../api/http/appAuth'); +const { createLoginTokenVerifier } = require('../../api/http/loginTokens'); const { asyncRoute } = require('../../api/http/asyncRoute'); const { ApiError, validationError, sendError } = require('../../api/http/errors'); const { buildMovementPolicy } = require('../domain'); @@ -177,16 +178,19 @@ function saveHandler({ repository, policy, isCreate }) { /** * Registers POST /app/movements/:type (create) and PATCH * /app/movements/:type/:key (update, merged like RTDB update()), also under - * /api, for the Firebase ID token of a signed-in user. Answers 201/200 - * {key}; errors in the envelope of functions/api/http/errors.js. + * /api, for the Firebase ID token of a signed-in user and, where the config + * sets centralLogin, for access tokens of the central login (the MCP hub + * writing for a pilot). Answers 201/200 {key}; errors in the envelope of + * functions/api/http/errors.js. */ function registerMovementRoutes(app, config, { auth = getAuth, db = getDatabase, repository = createRtdbMovementRepository({ db }), + loginTokens = createLoginTokenVerifier(config.centralLogin), } = {}) { const policy = lazyPolicy(config); - const common = [requestId, appAuth({ auth, db }), jsonBody()]; + const common = [requestId, appAuth({ auth, db, loginTokens }), jsonBody()]; app.post(CREATE_PATHS, ...common, saveHandler({ repository, policy, isCreate: true })); app.patch(UPDATE_PATHS, ...common, saveHandler({ repository, policy, isCreate: false })); } diff --git a/functions/movements/http/movementRoutes.spec.js b/functions/movements/http/movementRoutes.spec.js index 23b9a4f4..dda324ac 100644 --- a/functions/movements/http/movementRoutes.spec.js +++ b/functions/movements/http/movementRoutes.spec.js @@ -14,6 +14,9 @@ const { listen } = require('../../api/http/testing/listen'); const { loadVariant } = require('../domain/testing/projectPolicies'); const { departureInput, arrivalInput, stored, DATE_TIME } = require('../domain/testing/movementCases'); const { toOrderKey } = require('../domain/orderKey'); +const crypto = require('crypto'); +const jwt = require('jsonwebtoken'); +const { createLoginTokenVerifier } = require('../../api/http/loginTokens'); const KEY = '-Nabc123_XYZ-def4567'; const NEGATIVE_TIMESTAMP = -Date.parse(DATE_TIME); @@ -623,6 +626,101 @@ describe('functions', () => { }); }); + describe('with tokens of the central login (centralLogin)', () => { + const CENTRAL_LOGIN = { + issuer: 'https://login.example.ch', + jwksUri: 'https://login.example.ch/jwks', + audience: 'flightbox-lsze-test', + }; + const SUB = '7f3c1a52-0d7e-4c43-9a55-2a1f1a0e8b11'; + const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); + const jwks = { keys: [{ ...publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'ES256', use: 'sig' }] }; + let login; + let withoutConfig; + + // What the login issues to the hub by token exchange. + const loginToken = (claims = {}, audience = CENTRAL_LOGIN.audience) => jwt.sign( + { sub: SUB, email: 'pilot@example.com', email_verified: true, scope: 'movements:write', ...claims }, + privateKey, + { algorithm: 'ES256', issuer: CENTRAL_LOGIN.issuer, audience, expiresIn: 300, header: { typ: 'at+jwt', kid: 'k1', alg: 'ES256' } } + ); + + const loginActorOf = (email = 'pilot@example.com') => ({ + uid: `login:${SUB}`, email, isAdmin: false, isGuest: false, isKiosk: false, + }); + + beforeAll(async () => { + const fetchImpl = jest.fn(async () => ({ ok: true, status: 200, json: async () => jwks })); + const repositoryProxy = new Proxy({}, { get: (_, method) => repository[method] }); + const app = express(); + registerMovementRoutes(app, { ...serverConfig, centralLogin: CENTRAL_LOGIN }, { + auth: fakeAuth, + db: fakeDb, + repository: repositoryProxy, + loginTokens: createLoginTokenVerifier(CENTRAL_LOGIN, { fetchImpl }), + }); + login = await listen(app); + + const plain = express(); + registerMovementRoutes(plain, serverConfig, { auth: fakeAuth, db: fakeDb, repository: repositoryProxy }); + withoutConfig = await listen(plain); + }); + + afterAll(() => Promise.all([login.close(), withoutConfig.close()])); + + const sendWith = (target, method, path, token, body) => target.request(path, { + method, + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + body: JSON.stringify(body), + }); + + it('creates a departure owned by the pilot of the token', async () => { + const response = await sendWith(login, 'POST', '/api/app/movements/departures', loginToken(), departureInput(policy)); + + expect(response.status).toBe(201); + expect(repository.createMovement).toHaveBeenCalledWith('departure', { + ...departureInput(policy), + createdBy: 'pilot@example.com', + negativeTimestamp: NEGATIVE_TIMESTAMP, + createdBy_orderKey: toOrderKey('pilot@example.com', NEGATIVE_TIMESTAMP), + }, loginActorOf()); + }); + + it('updates the pilot\'s own movement, also one recorded in the app', async () => { + storeArrival(KEY, { createdBy: 'pilot@example.com' }); + + const response = await sendWith(login, 'PATCH', `/api/app/movements/arrivals/${KEY}`, loginToken(), { landingCount: 2 }); + + expect(response.status).toBe(200); + expect(repository.updateMovement).toHaveBeenCalledWith( + 'arrival', KEY, expect.objectContaining({ landingCount: 2 }), loginActorOf()); + }); + + it('answers 403 for a movement of another pilot', async () => { + storeArrival(KEY, { createdBy: 'other@example.com' }); + + const response = await sendWith(login, 'PATCH', `/api/app/movements/arrivals/${KEY}`, loginToken(), { landingCount: 2 }); + + expect(response.status).toBe(403); + expect(repository.updateMovement).not.toHaveBeenCalled(); + }); + + it('answers 401 for a token of another instance or without the scope', async () => { + for (const token of [loginToken({}, 'flightbox-lszt-prod'), loginToken({ scope: 'openid' }), loginToken({ email_verified: false })]) { + const response = await sendWith(login, 'POST', '/api/app/movements/departures', token, departureInput(policy)); + expect(response.status).toBe(401); + } + expect(repository.createMovement).not.toHaveBeenCalled(); + }); + + it('rejects login tokens where centralLogin is not configured', async () => { + const response = await sendWith(withoutConfig, 'POST', '/api/app/movements/departures', loginToken(), departureInput(policy)); + + expect(response.status).toBe(401); + expect(repository.createMovement).not.toHaveBeenCalled(); + }); + }); + it('answers 500 when the config lacks the policy fields', async () => { const app = express(); registerMovementRoutes(app, { movementWritesViaApi: true }, { diff --git a/functions/package-lock.json b/functions/package-lock.json index 2b22b812..772ab675 100644 --- a/functions/package-lock.json +++ b/functions/package-lock.json @@ -12,6 +12,7 @@ "express": "^5.2.1", "firebase-admin": "^14.5.0", "firebase-functions": "^7.0.0", + "jsonwebtoken": "^9.0.3", "moment": "^2.30.1", "nodemailer": "^10.0.13" }, diff --git a/functions/package.json b/functions/package.json index a3895a7a..ae04386f 100644 --- a/functions/package.json +++ b/functions/package.json @@ -11,6 +11,7 @@ "express": "^5.2.1", "firebase-admin": "^14.5.0", "firebase-functions": "^7.0.0", + "jsonwebtoken": "^9.0.3", "moment": "^2.30.1", "nodemailer": "^10.0.13" }, diff --git a/projects/Configuration.md b/projects/Configuration.md index 85118f66..2715de02 100644 --- a/projects/Configuration.md +++ b/projects/Configuration.md @@ -30,6 +30,7 @@ deployed tenant should not use `extends`. * `enabledFlightTypes` * `reportApiEnabled` * `movementWritesViaApi` +* `centralLogin` * `customsSelfDeclarationEnabled` * `ppr` * `pprGuestRequests` @@ -253,8 +254,8 @@ The functions get this flag and the aerodrome data they need from `functions/pro the deploy writes with `node tasks/generateServerConfig.js []` (with the Firebase project given, a config for another project fails instead of being ignored at runtime). The generated config holds only whitelisted fields: the feature flags, `memberManagement`, `loginForm`, -`lockOnDateTime`, `enabledFlightTypes`, the aircraft category names and, of the `aerodrome`, the `ICAO`, the -runways (name and type) and the names of the departure and arrival routes. +`lockOnDateTime`, `enabledFlightTypes`, the aircraft category names, `centralLogin` (if set) and, of the +`aerodrome`, the `ICAO`, the runways (name and type) and the names of the departure and arrival routes. Example: `true` @@ -311,6 +312,38 @@ The database triggers (fees, payment status, associated movements, lock date) ru Example: `true` +### `centralLogin` + +Lets the app API (the routes of `movementWritesViaApi`) also accept access tokens of the central login (the Open +Digital account, `odch/odch-login`), next to the Firebase ID tokens of the app. The Open Digital MCP hub +(`odch/mcp-hub`) uses them to record departures and arrivals for a pilot from an AI client (Claude etc.): it +exchanges the pilot's token at the login (token exchange, RFC 8693) for a token for exactly this instance and +calls `POST/PATCH /api/app/movements/...` with it. + +```json +"centralLogin": { + "issuer": "https://", + "jwksUri": "https:///jwks", + "audience": "flightbox-lsze-test" +} +``` + +* `issuer`: origin of the login, without a trailing slash; only tokens whose `iss` is exactly this are checked + as login tokens, all others go through Firebase as before. +* `jwksUri`: the login's signing keys (cached for 10 minutes, refetched when a token names an unknown key). +* `audience`: the name of this instance at the login; a token for another instance is rejected. + +Accepted are JWTs (`typ` `at+jwt`) signed with ES256 that carry a verified e-mail address (`email`, +`email_verified`) and the scope `movements:write`. The caller is the pilot with that address: the movement +domain and the database rules (`auth.token.email`, through `auth_variable_override`) check ownership exactly as +for a pilot signed in to the app with the same address, so the pilot sees and edits the same movements either +way. The uid is `login:`; such callers are never admins, guests or kiosks. + +Set it per environment. Only the functions read it (`functions/project-config.generated.json`, validated by +`tasks/generateServerConfig.js`); without it, tokens of the login are rejected like any other unknown token. +Set on `lsze` test, with the dev login (`odch-login-dev`) at its `*.run.app` address until +`login.opendigital.ch` exists. + ### `customsSelfDeclarationEnabled` Enables the "Zoll-Selbstdeklaration" tab in the admin area, where admins list the logins (e-mail addresses) whose diff --git a/projects/lsze.json b/projects/lsze.json index e41be54a..f7401584 100644 --- a/projects/lsze.json +++ b/projects/lsze.json @@ -50,7 +50,12 @@ "firebaseDatabaseUrl": "https://lsze-test-default-rtdb.europe-west1.firebasedatabase.app", "firebaseApiKey": "AIzaSyCKIaIc2zz5Stb9gbBriFaGOsdKz8M-bvo", "passkeysEnabled": true, - "movementWritesViaApi": true + "movementWritesViaApi": true, + "centralLogin": { + "issuer": "https://odch-login-422294830636.europe-west1.run.app", + "jwksUri": "https://odch-login-422294830636.europe-west1.run.app/jwks", + "audience": "flightbox-lsze-test" + } }, "production": { "reportApiEnabled": true, diff --git a/tasks/generateServerConfig.js b/tasks/generateServerConfig.js index 8be9c35c..31cef839 100644 --- a/tasks/generateServerConfig.js +++ b/tasks/generateServerConfig.js @@ -4,6 +4,7 @@ const fs = require('fs'); const projects = require('../projects'); const defaultConf = require('../projects/default.json'); const aircraftCategoriesData = require('../src/util/aircraftCategoriesData'); +const { validateCentralLogin } = require('../functions/api/http/centralLoginConfig'); // Builds the tenant config the Cloud Functions need (airstat report, // movement writes) from a project file, resolved exactly like the client's @@ -166,6 +167,20 @@ function assertMovementAerodromeMatchesRules(project, env, conf, aerodrome) { } } +// Optional: access tokens of the central login for the app API +// (functions/api/http/loginTokens.js). Only in the output when configured. +function buildCentralLogin(project, env, merged) { + if (!hasOwn(merged, 'centralLogin')) { + return {}; + } + try { + const { issuer, jwksUri, audience } = validateCentralLogin(merged.centralLogin); + return { centralLogin: { issuer, jwksUri, audience } }; + } catch (e) { + throw configError(project, env, 'centralLogin', e.message); + } +} + // Optional flags: absent means false, like the client's `=== true` checks. function readFlag(project, env, merged, key) { if (hasOwn(merged, key) && typeof merged[key] !== 'boolean') { @@ -207,7 +222,8 @@ function buildServerConfig(project, conf, env) { enabledFlightTypes: buildFlightTypes(project, env, merged), // Not per project: the list the database rules accept (aircraftCategory). aircraftCategories: aircraftCategoriesData.map(category => category.name), - aerodrome + aerodrome, + ...buildCentralLogin(project, env, merged) }; } diff --git a/tasks/generateServerConfig.spec.js b/tasks/generateServerConfig.spec.js index 578e449a..186f4731 100644 --- a/tasks/generateServerConfig.spec.js +++ b/tasks/generateServerConfig.spec.js @@ -131,7 +131,8 @@ describe('tasks/generateServerConfig', () => { 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 })) - } + }, + ...(client.centralLogin ? { centralLogin: client.centralLogin } : {}) }); }); @@ -158,6 +159,17 @@ describe('tasks/generateServerConfig', () => { // cypress-testing-api only builds the Cypress run of the movement specs // with the flag (same Firebase project as cypress-testing). + it('accepts central login tokens on lsze test only', () => { + CASES.forEach(([project, env]) => { + const { centralLogin } = buildServerConfigFor(project, env); + if (`${project}/${env}` === 'lsze/test') { + expect(centralLogin).toEqual(expect.objectContaining({ audience: 'flightbox-lsze-test' })); + } else { + expect(centralLogin).toBeUndefined(); + } + }); + }); + it('enables movementWritesViaApi on lsze test and the Cypress API run only', () => { const enabled = ['lsze/test', 'cypress-testing-api/test']; CASES.forEach(([project, env]) => { @@ -211,6 +223,21 @@ describe('tasks/generateServerConfig', () => { }); }); + it('emits centralLogin only for the environment that configures it', () => { + const centralLogin = { + issuer: 'https://login.example.ch', + jwksUri: 'https://login.example.ch/jwks', + audience: 'flightbox-lsxy-test' + }; + const conf = makeConf({}, { + test: { firebaseProjectId: 'flightbox-test', centralLogin }, + production: { firebaseProjectId: 'flightbox-prod' } + }); + + expect(buildServerConfig('lsxy', conf, 'test').centralLogin).toEqual(centralLogin); + expect(buildServerConfig('lsxy', conf, 'production')).not.toHaveProperty('centralLogin'); + }); + it('disables movementWritesViaApi when it is absent', () => { const conf = makeConf(); expect(buildServerConfig('lszt', conf, 'test').movementWritesViaApi).toBe(false); @@ -369,6 +396,22 @@ describe('tasks/generateServerConfig', () => { expectError(makeConf({ loginForm: true }), 'test', 'loginForm'); }); + it('rejects a malformed centralLogin', () => { + const centralLogin = { + issuer: 'https://login.example.ch', + jwksUri: 'https://login.example.ch/jwks', + audience: 'flightbox-lsxy-test' + }; + const inTest = value => makeConf({}, { + test: { firebaseProjectId: 'flightbox-test', centralLogin: value }, + production: { firebaseProjectId: 'flightbox-prod' } + }); + expectError(inTest('https://login.example.ch'), 'test', 'centralLogin'); + expectError(inTest({ ...centralLogin, issuer: 'http://login.example.ch' }), 'test', 'centralLogin'); + expectError(inTest({ ...centralLogin, audience: '' }), 'test', 'centralLogin'); + expectError(inTest({ issuer: centralLogin.issuer }), 'test', 'centralLogin'); + }); + it('rejects non-boolean lockOnDateTime and movementWritesViaApi', () => { expectError(makeConf({ lockOnDateTime: 'true' }), 'test', 'lockOnDateTime'); expectError(makeConf({ movementWritesViaApi: 1 }), 'test', 'movementWritesViaApi');