Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
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
42 changes: 25 additions & 17 deletions lib/resources/oidc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,24 @@

const { createHash } = require('node:crypto');

const { generators } = require('openid-client');
const config = require('config');
const { parse, render } = require('mustache');
const { // eslint-disable-line object-curly-newline
authorizationCodeGrant,
buildAuthorizationUrl,
calculatePKCECodeChallenge,
fetchUserInfo,
randomPKCECodeVerifier,
randomState,
} = require('openid-client'); // eslint-disable-line object-curly-newline
Comment on lines +20 to +27
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a nit / preference: we can const client = require('openid-client'); then the rest of the code in this file will be easier to read and understand, specially knowing which functions are coming from the external library.


const { safeNextPathFrom } = require('../util/html');
const { redirect } = require('../util/http');
const { createUserSession } = require('../http/sessions');
const { // eslint-disable-line object-curly-newline
CODE_CHALLENGE_METHOD,
RESPONSE_TYPE,
SCOPES,
getClient,
getOidcConfig,
getRedirectUri,
isEnabled,
} = require('../util/oidc'); // eslint-disable-line camelcase,object-curly-newline
Expand Down Expand Up @@ -101,7 +107,7 @@ const loaderTemplate = `
`;
parse(loaderTemplate); // caches template for future perf.

const stateFor = next => [ generators.state(), Buffer.from(next).toString('base64url') ].join(':');
const stateFor = next => [ randomState(), Buffer.from(next).toString('base64url') ].join(':');
const nextFrom = state => {
if (state) return Buffer.from(state.split(':')[1], 'base64url').toString();
};
Expand All @@ -111,19 +117,20 @@ module.exports = (service, __, anonymousEndpoint) => {

service.get('/oidc/login', anonymousEndpoint.html(async ({ Sentry }, _, req, res) => {
try {
const client = await getClient();
const code_verifier = generators.codeVerifier(); // eslint-disable-line camelcase
const oidcConfig = await getOidcConfig();
const code_verifier = randomPKCECodeVerifier(); // eslint-disable-line camelcase

const code_challenge = generators.codeChallenge(code_verifier); // eslint-disable-line camelcase
const code_challenge = await calculatePKCECodeChallenge(code_verifier); // eslint-disable-line camelcase

const next = req.query.next ?? '';
const state = stateFor(next);

const authUrl = client.authorizationUrl({
const authUrl = buildAuthorizationUrl(oidcConfig, {
scope: SCOPES.join(' '),
resource: `${envDomain}/v1`,
code_challenge,
code_challenge_method: CODE_CHALLENGE_METHOD,
redirect_uri: getRedirectUri(),
state,
});

Expand All @@ -143,20 +150,21 @@ module.exports = (service, __, anonymousEndpoint) => {

service.get('/oidc/callback', anonymousEndpoint.html(async (container, _, req, res) => {
try {
const code_verifier = req.cookies[CODE_VERIFIER_COOKIE]; // eslint-disable-line camelcase
const state = req.cookies[STATE_COOKIE]; // eslint-disable-line no-multi-spaces
const pkceCodeVerifier = req.cookies[CODE_VERIFIER_COOKIE];
const expectedState = req.cookies[STATE_COOKIE]; // eslint-disable-line no-multi-spaces
res.clearCookie(CODE_VERIFIER_COOKIE, callbackCookieProps);
res.clearCookie(STATE_COOKIE, callbackCookieProps); // eslint-disable-line no-multi-spaces

const client = await getClient();

const params = client.callbackParams(req);
const oidcConfig = await getOidcConfig();

const tokenSet = await client.callback(getRedirectUri(), params, { response_type: RESPONSE_TYPE, code_verifier, state });
// N.B. use req.originalUrl in preference to req.url, as the latter is corrupted somewhere upstream.
const requestUrl = new URL(req.originalUrl, getRedirectUri());

const { access_token } = tokenSet;
const tokens = await authorizationCodeGrant(oidcConfig, requestUrl, { pkceCodeVerifier, expectedState });

const userinfo = await client.userinfo(access_token);
const { access_token } = tokens;
const expectedSubject = tokens.claims().sub;
const userinfo = await fetchUserInfo(oidcConfig, access_token, expectedSubject);

const { email, email_verified } = userinfo;
if (!email) {
Expand All @@ -170,7 +178,7 @@ module.exports = (service, __, anonymousEndpoint) => {

await initSession(container, req, res, user);

const nextPath = safeNextPathFrom(nextFrom(state));
const nextPath = safeNextPathFrom(nextFrom(expectedState));

// This redirect would be ideal, but breaks `SameSite: Secure` cookies.
// return redirect(303, nextPath);
Expand Down
33 changes: 13 additions & 20 deletions lib/util/oidc.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ module.exports = {
CODE_CHALLENGE_METHOD,
RESPONSE_TYPE,
SCOPES,
getClient,
getOidcConfig,
getRedirectUri,
isEnabled,
};

const config = require('config');
const { Issuer } = require('openid-client');
const { allowInsecureRequests, discovery } = require('openid-client');

const oidcConfig = (config.has('default.oidc') && config.get('default.oidc')) || {};

Expand All @@ -48,19 +48,21 @@ function getRedirectUri() {
return `${config.get('default.env.domain')}/v1/oidc/callback`;
}

let clientLoader; // single instance, initialised lazily
function getClient() {
if (!clientLoader) clientLoader = initClient();
return clientLoader;
let configLoader; // single instance, initialised lazily
function getOidcConfig() {
if (!configLoader) configLoader = initConfig();
return configLoader;
}
async function initClient() {
async function initConfig() {
if (!isEnabled()) throw new Error('OIDC is not enabled.');

try {
assertHasAll('config keys', Object.keys(oidcConfig), ['issuerUrl', 'clientId', 'clientSecret']);

const { issuerUrl } = oidcConfig;
const issuer = await Issuer.discover(issuerUrl);
const { issuerUrl, clientId, clientSecret } = oidcConfig;
const _issuerUrl = new URL(issuerUrl);
const execute = _issuerUrl.hostname === 'localhost' ? [ allowInsecureRequests ] : undefined;
const discoveredConfig = await discovery(_issuerUrl, clientId, clientSecret, undefined, { execute });

// eslint-disable-next-line object-curly-newline
const {
Expand All @@ -70,7 +72,7 @@ async function initClient() {
response_types_supported,
scopes_supported,
token_endpoint_auth_methods_supported,
} = issuer.metadata; // eslint-disable-line object-curly-newline
} = discoveredConfig.serverMetadata(); // eslint-disable-line object-curly-newline

// This code uses email to verify a user's identity. An unverified email
// address is not suitable for verification.
Expand Down Expand Up @@ -106,16 +108,7 @@ async function initClient() {
assertHas('token signing alg', id_token_signing_alg_values_supported, TOKEN_SIGNING_ALG);
assertHas('token endpoint auth method', token_endpoint_auth_methods_supported, TOKEN_ENDPOINT_AUTH_METHOD);

const client = new issuer.Client({
client_id: oidcConfig.clientId,
client_secret: oidcConfig.clientSecret,
redirect_uris: [getRedirectUri()],
response_types: [RESPONSE_TYPE],
id_token_signed_response_alg: TOKEN_SIGNING_ALG,
token_endpoint_auth_method: TOKEN_ENDPOINT_AUTH_METHOD,
});

return client;
return discoveredConfig;
} catch (cause) {
// N.B. don't include the config here - it might include the client secret, perhaps in the wrong place.
throw new Error('Failed to configure OpenID Connect client', { cause });
Expand Down
70 changes: 34 additions & 36 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"mustache": "^4.2.0",
"nodemailer": "^7.0.10",
"odata-v4-parser": "~0.1",
"openid-client": "^5.7.1",
"openid-client": "^6.8.1",
"path-to-regexp": "^8.3.0",
"pg": "~8.8.0",
"pg-query-stream": "^4.10.3",
Expand Down