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
56 changes: 54 additions & 2 deletions functions/api/http/appAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = /[.#$[\]/]/;

Expand Down Expand Up @@ -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));
Expand All @@ -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 <idToken>`). Revoked tokens and disabled users are
Expand All @@ -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:<account id>", 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 {
Expand All @@ -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,
};
96 changes: 95 additions & 1 deletion functions/api/http/appAuth.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -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();
Expand Down
46 changes: 46 additions & 0 deletions functions/api/http/centralLoginConfig.js
Original file line number Diff line number Diff line change
@@ -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 };
Loading
Loading