enhancement(oidc): refetch discovery documents regularly

Signed-off-by: Erik Michelson <github@erik.michelson.eu>
This commit is contained in:
Erik Michelson 2024-10-09 00:23:07 +02:00 committed by Philip Molares
parent 19f4baf79b
commit f71bf7a974

View file

@ -9,6 +9,7 @@ import {
InternalServerErrorException, InternalServerErrorException,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { Client, generators, Issuer, UserinfoResponse } from 'openid-client'; import { Client, generators, Issuer, UserinfoResponse } from 'openid-client';
import appConfiguration, { AppConfig } from '../../config/app.config'; import appConfiguration, { AppConfig } from '../../config/app.config';
@ -43,10 +44,7 @@ export class OidcService {
@Inject(appConfiguration.KEY) @Inject(appConfiguration.KEY)
private appConfig: AppConfig, private appConfig: AppConfig,
) { ) {
this.initializeAllClients(); this.updateClientConfigs();
// TODO The previous line should be regularly called again (@nestjs/cron?).
// If the HedgeDoc instance is running for a long time,
// the OIDC metadata or keys might change and the client needs to be reinitialized.
this.logger.setContext(OidcService.name); this.logger.setContext(OidcService.name);
this.logger.debug('OIDC service initialized', 'constructor'); this.logger.debug('OIDC service initialized', 'constructor');
} }
@ -54,7 +52,7 @@ export class OidcService {
/** /**
* Initializes clients for all OIDC configurations by fetching their metadata and storing them in the clientConfigs map. * Initializes clients for all OIDC configurations by fetching their metadata and storing them in the clientConfigs map.
*/ */
private initializeAllClients(): void { private updateClientConfigs(): void {
this.authConfig.oidc.forEach((oidcConfig) => { this.authConfig.oidc.forEach((oidcConfig) => {
this.fetchClientConfig(oidcConfig) this.fetchClientConfig(oidcConfig)
.then((config) => { .then((config) => {
@ -62,9 +60,9 @@ export class OidcService {
}) })
.catch((error) => { .catch((error) => {
this.logger.error( this.logger.error(
`Failed to initialize OIDC client "${oidcConfig.identifier}": ${String(error)}`, `Failed to update OIDC client config "${oidcConfig.identifier}": ${String(error)}`,
undefined, undefined,
'initializeClient', 'updateClientConfigs',
); );
}); });
}); });
@ -110,6 +108,12 @@ export class OidcService {
}; };
} }
// Update all client configs every sunday on 3:30 AM
@Cron('30 3 * * 0')
handleCronUpdateClientConfigs(): void {
this.updateClientConfigs();
}
/** /**
* Generates a secure code verifier for the OIDC login. * Generates a secure code verifier for the OIDC login.
* *