Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update openid-client to v6 #1394

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
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
42 changes: 25 additions & 17 deletions lib/resources/oidc.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@
// OpenID Connect auth handling using Authorization Code Flow with PKCE.
// TODO document _why_ auth-code-flow, and not e.g. implicit flow?

const { generators } = require('openid-client');
const { // eslint-disable-line object-curly-newline
authorizationCodeGrant,
buildAuthorizationUrl,
calculatePKCECodeChallenge,
fetchUserInfo,
randomPKCECodeVerifier,
randomState,
} = require('openid-client'); // eslint-disable-line object-curly-newline
const config = require('config');
const { parse, render } = require('mustache');

Expand All @@ -22,9 +29,8 @@ 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 @@ -95,7 +101,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 @@ -105,19 +111,20 @@ module.exports = (service, endpoint) => {

service.get('/oidc/login', endpoint.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 @@ -137,20 +144,21 @@ module.exports = (service, endpoint) => {

service.get('/oidc/callback', endpoint.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 @@ -164,7 +172,7 @@ module.exports = (service, endpoint) => {

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 (err) {
// 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: ${err}`);
Expand Down
88 changes: 37 additions & 51 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": "~2.3",
"nodemailer": "~6",
"odata-v4-parser": "~0.1",
"openid-client": "^5.4.3",
"openid-client": "^6.1.7",
"path-to-regexp": "^6.2.2",
"pg": "~8",
"pg-query-stream": "~4",
Expand Down
Loading