From a059f9cdf13732a51610f6a878c1fa5677875760 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Mon, 12 Aug 2024 14:03:45 +0200 Subject: [PATCH 01/11] remove global logger, add logs to login flow, error logs, one omslogger instance, instance id logging --- libs/logger/src/oms/oms.logger.service.ts | 8 +++++- libs/oidc/src/services/oidc.service.ts | 24 +++++++++++------- src/filters/http-exception-global.filter.ts | 27 --------------------- src/main.ts | 2 -- 4 files changed, 22 insertions(+), 39 deletions(-) delete mode 100644 src/filters/http-exception-global.filter.ts diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index 1e66b066..6cee670d 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -1,7 +1,8 @@ import { ConsoleLogger, Injectable, Scope } from '@nestjs/common'; +import { v4 as uuid } from 'uuid'; import { OMSLogLevel } from './OMSLog.interface'; -@Injectable({ scope: Scope.TRANSIENT }) +@Injectable({ scope: Scope.DEFAULT }) export class OMSLogger extends ConsoleLogger { private print(logLevel: OMSLogLevel, message: string, context?: string, stackTrace?: string) { let currentContext = context; @@ -15,11 +16,16 @@ export class OMSLogger extends ConsoleLogger { msg: message, logger: currentContext, stack_trace: stackTrace, + instanceID: this.instanceID }; console.log(JSON.stringify(logEntry)); } + constructor(private instanceID: string = uuid()) { + super(); + } + log(message: string, context?: string) { process.stdout.isTTY ? super.log.apply(this, arguments) : this.print(OMSLogLevel.INFO, message, context); } diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 9f1153a8..5998905d 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -1,4 +1,5 @@ -import { HttpStatus, Inject, Injectable, Logger, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; +import { OMSLogger } from '@finastra/nestjs-logger'; +import { HttpStatus, Inject, Injectable, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; import axios from 'axios'; import { Request, Response } from 'express'; import * as handlebars from 'handlebars'; @@ -13,7 +14,7 @@ import { loginPopupTemplate } from '../templates/login-popup.hbs'; import { SSRPagesService } from './ssr-pages.service'; import passport = require('passport'); -const logger = new Logger('OidcService'); +// const logger = new Logger('OidcService'); declare module 'express-session' { interface SessionData { @@ -38,6 +39,7 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, private ssrPagesService: SSRPagesService, + private logger: OMSLogger, ) { this.isMultitenant = !!this.options.issuerOrigin; } @@ -93,21 +95,21 @@ export class OidcService implements OnModuleInit { return strategy; } catch (err) { if (this.isMultitenant) { - const errorMsg = { + const errorMsg = JSON.stringify({ error: err.message, debug: { origin: this.options.origin, tenantId, channelType, }, - }; - logger.error(errorMsg); + }); + this.logger.error(err.message, err.stack, errorMsg); throw new Error(); } const docUrl = 'https://github.com/finastra/finastra-nodejs-libs/blob/develop/libs/oidc/README.md'; const msg = `Error accessing the issuer/tokenStore. Check if the url is valid or increase the timeout in the defaultHttpOptions : ${docUrl}`; - logger.error(msg); - logger.log('Terminating application'); + this.logger.error(msg, err.stack); + this.logger.log('Terminating application'); process.exit(1); } } @@ -125,6 +127,8 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { + const reqstring = JSON.stringify(req); + this.logger.log(req.url, reqstring); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -173,10 +177,12 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { + this.logger.error(err.message, err.stack); return next(err || info); } req.logIn(user, err => { if (err) { + this.logger.error(err.message, err.stack); return next(err); } this.updateSessionDuration(req); @@ -200,6 +206,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { + this.logger.error(err.message, err.stack) res.status(HttpStatus.NOT_FOUND).send(); } } @@ -215,8 +222,7 @@ export class OidcService implements OnModuleInit { this.idpInfos[this.getIdpInfosKey(tenantId, channelType)].trustIssuer.metadata.end_session_endpoint; if (end_session_endpoint) { res.redirect( - `${end_session_endpoint}?post_logout_redirect_uri=${ - this.options.redirectUriLogout ? this.options.redirectUriLogout : this.options.origin + `${end_session_endpoint}?post_logout_redirect_uri=${this.options.redirectUriLogout ? this.options.redirectUriLogout : this.options.origin }&client_id=${this.options.clientMetadata.client_id}${id_token ? '&id_token_hint=' + id_token : ''}`, ); } else { diff --git a/src/filters/http-exception-global.filter.ts b/src/filters/http-exception-global.filter.ts deleted file mode 100644 index b082d7a9..00000000 --- a/src/filters/http-exception-global.filter.ts +++ /dev/null @@ -1,27 +0,0 @@ - -import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common'; -import { Request, Response } from 'express'; - -@Catch(HttpException) -export class HttpExceptionGlobalFilter implements ExceptionFilter { - readonly logger = new Logger(HttpExceptionGlobalFilter.name); - - catch(exception: HttpException, host: ArgumentsHost) { - const ctx = host.switchToHttp(); - const response = ctx.getResponse(); - const request = ctx.getRequest(); - const status = exception.getStatus(); - - const { body, headers, method, params, query, url, user } = request; - - this.logger.error({ request: { body, headers, method, params, query, url, user }, exception }); - - response - .status(status) - .json({ - statusCode: status, - timestamp: new Date().toISOString(), - path: request.url - }); - } -} diff --git a/src/main.ts b/src/main.ts index f0f48c84..3e715896 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,7 +4,6 @@ import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { readFileSync } from 'fs'; import { AppModule } from './app.module'; -import { HttpExceptionGlobalFilter } from './filters/http-exception-global.filter'; async function bootstrap() { const logger = new OMSLogger(); @@ -23,7 +22,6 @@ async function bootstrap() { }); app.useLogger(logger); app.useGlobalInterceptors(new HttpLoggingInterceptor()); - app.useGlobalFilters(new HttpExceptionGlobalFilter()); app.useGlobalGuards(app.get(TokenGuard)); From 13d949ae15f050853798083a143da65e2acebe6d Mon Sep 17 00:00:00 2001 From: SebastianW Date: Mon, 12 Aug 2024 15:51:34 +0200 Subject: [PATCH 02/11] server instance id as injection token, injecting generic logger class --- .../src/interceptors/common-http.interceptor.ts | 4 +++- libs/logger/src/oms/oms.logger.service.ts | 16 ++++++++++------ libs/oidc/src/services/oidc.service.ts | 7 ++----- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.ts b/libs/logger/src/interceptors/common-http.interceptor.ts index 2d0c3455..221c828f 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.ts @@ -4,7 +4,9 @@ import { tap } from 'rxjs/operators'; @Injectable() export class HttpLoggingInterceptor implements NestInterceptor { - readonly logger = new Logger(HttpLoggingInterceptor.name); + // readonly logger = new Logger(HttpLoggingInterceptor.name); + + constructor(private logger: Logger) { } intercept(context: ExecutionContext, next: CallHandler): Observable { let req = context.switchToHttp().getRequest(); diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index 6cee670d..2131c9c4 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -1,9 +1,16 @@ -import { ConsoleLogger, Injectable, Scope } from '@nestjs/common'; -import { v4 as uuid } from 'uuid'; +import { ConsoleLogger, Inject, Injectable, Scope } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import { OMSLogLevel } from './OMSLog.interface'; @Injectable({ scope: Scope.DEFAULT }) export class OMSLogger extends ConsoleLogger { + #serverInstanceId: string = randomUUID(); + + constructor(@Inject('SERVER_INSTANCE_ID') serverInstanceId: string) { + super(); + this.#serverInstanceId = serverInstanceId; + } + private print(logLevel: OMSLogLevel, message: string, context?: string, stackTrace?: string) { let currentContext = context; if (typeof context === 'undefined') { @@ -16,15 +23,12 @@ export class OMSLogger extends ConsoleLogger { msg: message, logger: currentContext, stack_trace: stackTrace, - instanceID: this.instanceID + instanceID: this.#serverInstanceId }; console.log(JSON.stringify(logEntry)); } - constructor(private instanceID: string = uuid()) { - super(); - } log(message: string, context?: string) { process.stdout.isTTY ? super.log.apply(this, arguments) : this.print(OMSLogLevel.INFO, message, context); diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 5998905d..76cf4794 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -1,5 +1,4 @@ -import { OMSLogger } from '@finastra/nestjs-logger'; -import { HttpStatus, Inject, Injectable, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; +import { HttpStatus, Inject, Injectable, Logger, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; import axios from 'axios'; import { Request, Response } from 'express'; import * as handlebars from 'handlebars'; @@ -14,8 +13,6 @@ import { loginPopupTemplate } from '../templates/login-popup.hbs'; import { SSRPagesService } from './ssr-pages.service'; import passport = require('passport'); -// const logger = new Logger('OidcService'); - declare module 'express-session' { interface SessionData { tenant: string; @@ -39,7 +36,7 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, private ssrPagesService: SSRPagesService, - private logger: OMSLogger, + private logger: Logger, ) { this.isMultitenant = !!this.options.issuerOrigin; } From b8329d413271f57cb45fa8e006c91456b123a25f Mon Sep 17 00:00:00 2001 From: SebastianW Date: Tue, 13 Aug 2024 13:37:12 +0200 Subject: [PATCH 03/11] server instance id injection token, dynamic module configuration --- .../interceptors/common-http.interceptor.ts | 12 ++++++---- libs/logger/src/logger.module.ts | 20 ++++++++++++---- libs/logger/src/oms/oms.logger.service.ts | 24 ++++++++----------- libs/oidc/src/oidc.module.ts | 4 ++-- libs/oidc/src/services/oidc.service.ts | 12 +++++----- 5 files changed, 41 insertions(+), 31 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.ts b/libs/logger/src/interceptors/common-http.interceptor.ts index 221c828f..58315e39 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.ts @@ -1,12 +1,14 @@ -import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'; +import { CallHandler, ExecutionContext, Inject, Injectable, Logger, NestInterceptor } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; +import { SERVER_INSTANCE_ID } from '../logger.module'; @Injectable() export class HttpLoggingInterceptor implements NestInterceptor { - // readonly logger = new Logger(HttpLoggingInterceptor.name); + readonly logger = new Logger(HttpLoggingInterceptor.name); - constructor(private logger: Logger) { } + constructor(@Inject(SERVER_INSTANCE_ID) private serverInstanceID: string) { + } intercept(context: ExecutionContext, next: CallHandler): Observable { let req = context.switchToHttp().getRequest(); @@ -14,13 +16,13 @@ export class HttpLoggingInterceptor implements NestInterceptor { if (context['contextType'] !== 'graphql') { log = true; - this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url}`); + this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.serverInstanceID}`); } return next.handle().pipe( tap(() => { if (log) { - this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url}`); + this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.serverInstanceID}`); } }), ); diff --git a/libs/logger/src/logger.module.ts b/libs/logger/src/logger.module.ts index 83abcd26..7e1c2a51 100644 --- a/libs/logger/src/logger.module.ts +++ b/libs/logger/src/logger.module.ts @@ -1,8 +1,20 @@ -import { Module } from '@nestjs/common'; +import { DynamicModule, Module } from '@nestjs/common'; import { OMSLogger } from './oms/oms.logger.service'; +export const SERVER_INSTANCE_ID = 'SERVER_INSTANCE_ID'; + @Module({ - providers: [ OMSLogger ], - exports: [ OMSLogger ], + providers: [ + OMSLogger + ], + exports: [OMSLogger], }) -export class LoggerModule {} +export class LoggerModule { + static register(serverInstanceID: string): DynamicModule { + return { + module: LoggerModule, + providers: [{ provide: SERVER_INSTANCE_ID, useValue: serverInstanceID }], + exports: [SERVER_INSTANCE_ID], + }; + } +} diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index 2131c9c4..e0688be5 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -1,14 +1,11 @@ import { ConsoleLogger, Inject, Injectable, Scope } from '@nestjs/common'; -import { randomUUID } from 'crypto'; +import { SERVER_INSTANCE_ID } from '../logger.module'; import { OMSLogLevel } from './OMSLog.interface'; -@Injectable({ scope: Scope.DEFAULT }) +@Injectable({ scope: Scope.TRANSIENT }) export class OMSLogger extends ConsoleLogger { - #serverInstanceId: string = randomUUID(); - - constructor(@Inject('SERVER_INSTANCE_ID') serverInstanceId: string) { + constructor(@Inject(SERVER_INSTANCE_ID) private serverInstanceID: string) { super(); - this.#serverInstanceId = serverInstanceId; } private print(logLevel: OMSLogLevel, message: string, context?: string, stackTrace?: string) { @@ -23,32 +20,31 @@ export class OMSLogger extends ConsoleLogger { msg: message, logger: currentContext, stack_trace: stackTrace, - instanceID: this.#serverInstanceId + instanceID: this.serverInstanceID, }; - console.log(JSON.stringify(logEntry)); + super.log.apply(this, [...arguments, JSON.stringify(logEntry)]); } - log(message: string, context?: string) { - process.stdout.isTTY ? super.log.apply(this, arguments) : this.print(OMSLogLevel.INFO, message, context); + process.stdout.isTTY ? super.log.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.INFO, message, context); } error(message: string, stackTrace: string, context?: string) { process.stdout.isTTY - ? super.error.apply(this, arguments) + ? super.error.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.ERROR, message, context, `${JSON.stringify(stackTrace)}`); } warn(message: string, context?: string) { - process.stdout.isTTY ? super.warn.apply(this, arguments) : this.print(OMSLogLevel.WARNING, message, context); + process.stdout.isTTY ? super.warn.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.WARNING, message, context); } debug(message: string, context?: string) { - process.stdout.isTTY ? super.debug.apply(this, arguments) : this.print(OMSLogLevel.DEBUG, message, context); + process.stdout.isTTY ? super.debug.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.DEBUG, message, context); } verbose(message: string, context?: string) { - process.stdout.isTTY ? super.verbose.apply(this, arguments) : this.print(OMSLogLevel.VERBOSE, message, context); + process.stdout.isTTY ? super.verbose.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.VERBOSE, message, context); } } diff --git a/libs/oidc/src/oidc.module.ts b/libs/oidc/src/oidc.module.ts index 31aa7df0..e933cd4e 100644 --- a/libs/oidc/src/oidc.module.ts +++ b/libs/oidc/src/oidc.module.ts @@ -71,11 +71,11 @@ export class OidcModule implements NestModule { }; } - static forRootAsync(options: OidcModuleAsyncOptions): DynamicModule { + static forRootAsync(options: OidcModuleAsyncOptions, serverInstanceID: string): DynamicModule { return { module: OidcModule, imports: options.imports, - providers: [...this.createAsyncProviders(options)], + providers: [...this.createAsyncProviders(options), { provide: 'SERVER_INSTANCE_ID', useValue: serverInstanceID }], }; } diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 76cf4794..0958a6ec 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -22,6 +22,7 @@ declare module 'express-session' { @Injectable() export class OidcService implements OnModuleInit { + readonly logger = new Logger(OidcService.name); isMultitenant: boolean = false; strategy: any; idpInfos: { @@ -35,8 +36,8 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, + @Inject('SERVER_INSTANCE_ID') private serverInstanceID: string, private ssrPagesService: SSRPagesService, - private logger: Logger, ) { this.isMultitenant = !!this.options.issuerOrigin; } @@ -124,8 +125,7 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { - const reqstring = JSON.stringify(req); - this.logger.log(req.url, reqstring); + this.logger.log(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}`); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -174,12 +174,12 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { - this.logger.error(err.message, err.stack); + this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); return next(err || info); } req.logIn(user, err => { if (err) { - this.logger.error(err.message, err.stack); + this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); return next(err); } this.updateSessionDuration(req); @@ -203,7 +203,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { - this.logger.error(err.message, err.stack) + this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); res.status(HttpStatus.NOT_FOUND).send(); } } From 0ac8e7398876fc8c0b402975028c7de88adc4ac6 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Tue, 13 Aug 2024 15:14:28 +0200 Subject: [PATCH 04/11] tests, console.log logger method --- .../common-http.interceptor.spec.ts | 3 ++- libs/logger/src/oms/oms.logger.service.ts | 2 +- libs/oidc/src/services/oidc.service.spec.ts | 21 ++++++++++--------- libs/oidc/src/services/oidc.service.ts | 2 +- .../oidc/src/strategies/oidc.strategy.spec.ts | 3 ++- libs/oidc/src/utils/user-info.spec.ts | 3 ++- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.spec.ts b/libs/logger/src/interceptors/common-http.interceptor.spec.ts index 80be662f..0d54cdf0 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.spec.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.spec.ts @@ -1,5 +1,6 @@ import { createMock } from '@golevelup/nestjs-testing'; import { CallHandler, ExecutionContext } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import { of } from 'rxjs'; import { HttpLoggingInterceptor } from './common-http.interceptor'; @@ -7,7 +8,7 @@ describe('HttpLoggingInterceptor', () => { let interceptor; beforeEach(() => { - interceptor = new HttpLoggingInterceptor(); + interceptor = new HttpLoggingInterceptor(randomUUID()); }); it('should be defined', () => { diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index e0688be5..1696c3f0 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -23,7 +23,7 @@ export class OMSLogger extends ConsoleLogger { instanceID: this.serverInstanceID, }; - super.log.apply(this, [...arguments, JSON.stringify(logEntry)]); + console.log(JSON.stringify(logEntry)); } log(message: string, context?: string) { diff --git a/libs/oidc/src/services/oidc.service.spec.ts b/libs/oidc/src/services/oidc.service.spec.ts index ed1619cd..40ae6d2f 100644 --- a/libs/oidc/src/services/oidc.service.spec.ts +++ b/libs/oidc/src/services/oidc.service.spec.ts @@ -1,4 +1,5 @@ import axios from 'axios'; +import { randomUUID } from 'crypto'; import * as handlebars from 'handlebars'; import { JWKS } from 'jose'; import { createRequest, createResponse } from 'node-mocks-http'; @@ -11,7 +12,7 @@ import { SSRPagesService } from './ssr-pages.service'; import passport = require('passport'); describe('OidcService', () => { - let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new SSRPagesService()); + let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); let options: OidcModuleOptions = MOCK_OIDC_MODULE_OPTIONS; const idpKey = 'idpKey'; @@ -154,7 +155,7 @@ describe('OidcService', () => { it('should call passport authenticate for single tenant login', async () => { service.strategy = new OidcStrategy(service, idpKey); const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => { - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); expect(spy).toHaveBeenCalled(); @@ -167,7 +168,7 @@ describe('OidcService', () => { channelType: 'b2c', }; const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => { - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); expect(spy).toHaveBeenCalled(); @@ -180,7 +181,7 @@ describe('OidcService', () => { tenantId: 'tenant', }; const spy = jest.spyOn(passport, 'authenticate').mockImplementation(() => { - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); expect(spy).toHaveBeenCalled(); @@ -211,7 +212,7 @@ describe('OidcService', () => { const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => { cb(); - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); @@ -233,7 +234,7 @@ describe('OidcService', () => { const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => { const user = {}; cb(null, user, null); - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); @@ -254,7 +255,7 @@ describe('OidcService', () => { const spy = jest.spyOn(passport, 'authenticate').mockImplementation((strategy, options, cb) => { cb(null, {}, null); - return (req, res, next) => {}; + return (req, res, next) => { }; }); await service.login(req, res, next, params); @@ -279,7 +280,7 @@ describe('OidcService', () => { state: options.state, }; cb(null, {}, null); - return (req, res, next) => {}; + return (req, res, next) => { }; }); const spyRes = jest.spyOn(res, 'redirect'); @@ -332,7 +333,7 @@ describe('OidcService', () => { state: options.state, }; cb(null, {}, null); - return (req, res, next) => {}; + return (req, res, next) => { }; }); const spyRes = jest.spyOn(res, 'redirect'); @@ -364,7 +365,7 @@ describe('OidcService', () => { state: options.state, }; cb(null, {}, null); - return (req, res, next) => {}; + return (req, res, next) => { }; }); const spyRes = jest.spyOn(res, 'redirect'); diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 0958a6ec..2d1153ec 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -106,7 +106,7 @@ export class OidcService implements OnModuleInit { } const docUrl = 'https://github.com/finastra/finastra-nodejs-libs/blob/develop/libs/oidc/README.md'; const msg = `Error accessing the issuer/tokenStore. Check if the url is valid or increase the timeout in the defaultHttpOptions : ${docUrl}`; - this.logger.error(msg, err.stack); + this.logger.error(msg, err?.stack); this.logger.log('Terminating application'); process.exit(1); } diff --git a/libs/oidc/src/strategies/oidc.strategy.spec.ts b/libs/oidc/src/strategies/oidc.strategy.spec.ts index 20563974..5be4d971 100644 --- a/libs/oidc/src/strategies/oidc.strategy.spec.ts +++ b/libs/oidc/src/strategies/oidc.strategy.spec.ts @@ -1,4 +1,5 @@ import { createMock } from '@golevelup/nestjs-testing'; +import { randomUUID } from 'crypto'; import { JWKS } from 'jose'; import { TokenSet } from 'openid-client'; import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks'; @@ -12,7 +13,7 @@ describe('OidcStrategy', () => { let mockTokenset: TokenSet; beforeEach(() => { - const mockOidcService = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new SSRPagesService()); + const mockOidcService = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); const idpKey = 'idpKey'; mockOidcService.idpInfos[idpKey] = { client: MOCK_CLIENT_INSTANCE, diff --git a/libs/oidc/src/utils/user-info.spec.ts b/libs/oidc/src/utils/user-info.spec.ts index 93b467d7..5d2f3765 100644 --- a/libs/oidc/src/utils/user-info.spec.ts +++ b/libs/oidc/src/utils/user-info.spec.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'crypto'; import { JWKS } from 'jose'; import { UserInfoMethod } from '../interfaces'; import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks'; @@ -15,7 +16,7 @@ describe('OidcStrategy', () => { let service; beforeEach(() => { - service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new SSRPagesService()); + service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); service.idpInfos[idpKey] = { client: MOCK_CLIENT_INSTANCE, tokenStore: new JWKS.KeyStore([]), From f384b3912bfce5e0b22d7f7b16c582edb2b57a1f Mon Sep 17 00:00:00 2001 From: SebastianW Date: Tue, 13 Aug 2024 16:24:35 +0200 Subject: [PATCH 05/11] oidc module test --- libs/oidc/src/oidc.module.spec.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libs/oidc/src/oidc.module.spec.ts b/libs/oidc/src/oidc.module.spec.ts index 3336564d..5ba85e26 100644 --- a/libs/oidc/src/oidc.module.spec.ts +++ b/libs/oidc/src/oidc.module.spec.ts @@ -1,9 +1,10 @@ -import { TestingModule, Test } from '@nestjs/testing'; import { createMock } from '@golevelup/nestjs-testing'; +import { MiddlewareConsumer } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { randomUUID } from 'crypto'; import { Issuer } from 'openid-client'; +import { MOCK_ISSUER_INSTANCE, MOCK_OIDC_MODULE_OPTIONS } from './mocks'; import { OidcModule } from './oidc.module'; -import { MOCK_OIDC_MODULE_OPTIONS, MOCK_ISSUER_INSTANCE } from './mocks'; -import { MiddlewareConsumer } from '@nestjs/common'; describe('OidcModule', () => { describe('register sync', () => { @@ -34,7 +35,7 @@ describe('OidcModule', () => { imports: [ OidcModule.forRootAsync({ useFactory: async () => MOCK_OIDC_MODULE_OPTIONS, - }), + }, randomUUID()), ], }).compile(); }); @@ -63,7 +64,7 @@ describe('OidcModule', () => { imports: [ OidcModule.forRootAsync({ useClass: oidcModuleOptions, - }), + }, randomUUID()), ], }).compile(); }); From 48e8d6c9e9346be70cc4db11b080c5602fc8ee4e Mon Sep 17 00:00:00 2001 From: SebastianW Date: Wed, 21 Aug 2024 15:02:21 +0200 Subject: [PATCH 06/11] remove req.body and req.headers logging, http exception filer name, instance id for oidc --- libs/oidc/src/filters/http-exception.filter.ts | 7 ++++--- libs/oidc/src/oidc.module.spec.ts | 2 +- libs/oidc/src/oidc.module.ts | 4 +++- libs/oidc/src/services/oidc.service.ts | 15 ++++++++------- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/libs/oidc/src/filters/http-exception.filter.ts b/libs/oidc/src/filters/http-exception.filter.ts index 57abff05..587d8a15 100644 --- a/libs/oidc/src/filters/http-exception.filter.ts +++ b/libs/oidc/src/filters/http-exception.filter.ts @@ -7,7 +7,7 @@ import { SSRPagesService } from '../services'; export class HttpExceptionFilter implements ExceptionFilter { readonly logger = new Logger(HttpExceptionFilter.name); - constructor(private ssrPagesService: SSRPagesService) {} + constructor(private ssrPagesService: SSRPagesService) { } catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); @@ -15,9 +15,10 @@ export class HttpExceptionFilter implements ExceptionFilter { const request = ctx.getRequest(); const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR; - const { body, headers, method, params, query, url, user } = request; + const { method, params, query, url, user } = request; - this.logger.error({ request: { body, headers, method, params, query, url, user }, exception }); + // this.logger.error({ request: { method, params, query, url, user }, exception }); + this.logger.error(`${{ 'HttpExceptionFilter': method, params, query, url, user, exception }}`); switch (status) { case MisdirectedStatus.MISDIRECTED: diff --git a/libs/oidc/src/oidc.module.spec.ts b/libs/oidc/src/oidc.module.spec.ts index 5ba85e26..36b60dd9 100644 --- a/libs/oidc/src/oidc.module.spec.ts +++ b/libs/oidc/src/oidc.module.spec.ts @@ -15,7 +15,7 @@ describe('OidcModule', () => { IssuerMock.keystore = jest.fn(); jest.spyOn(Issuer, 'discover').mockImplementation(() => Promise.resolve(IssuerMock)); module = await Test.createTestingModule({ - imports: [OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS)], + imports: [OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS, randomUUID())], }).compile(); }); diff --git a/libs/oidc/src/oidc.module.ts b/libs/oidc/src/oidc.module.ts index e933cd4e..cee8515b 100644 --- a/libs/oidc/src/oidc.module.ts +++ b/libs/oidc/src/oidc.module.ts @@ -1,3 +1,4 @@ +import { SERVER_INSTANCE_ID } from '@finastra/nestjs-logger'; import { DynamicModule, Global, MiddlewareConsumer, Module, NestModule, Provider, RequestMethod } from '@nestjs/common'; import { APP_FILTER, APP_GUARD } from '@nestjs/core'; import { JwtModule } from '@nestjs/jwt'; @@ -58,7 +59,7 @@ export class OidcModule implements NestModule { ); } - static forRoot(options: OidcModuleOptions): DynamicModule { + static forRoot(options: OidcModuleOptions, serverInstanceID: string): DynamicModule { options = mergeDefaults(options); return { module: OidcModule, @@ -67,6 +68,7 @@ export class OidcModule implements NestModule { provide: OIDC_MODULE_OPTIONS, useValue: options, }, + { provide: SERVER_INSTANCE_ID, useValue: serverInstanceID } ], }; } diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 2d1153ec..a81a32db 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -1,3 +1,4 @@ +import { SERVER_INSTANCE_ID } from '@finastra/nestjs-logger'; import { HttpStatus, Inject, Injectable, Logger, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; import axios from 'axios'; import { Request, Response } from 'express'; @@ -36,7 +37,7 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, - @Inject('SERVER_INSTANCE_ID') private serverInstanceID: string, + @Inject(SERVER_INSTANCE_ID) private serverInstanceID: string, private ssrPagesService: SSRPagesService, ) { this.isMultitenant = !!this.options.issuerOrigin; @@ -94,14 +95,14 @@ export class OidcService implements OnModuleInit { } catch (err) { if (this.isMultitenant) { const errorMsg = JSON.stringify({ - error: err.message, + error: err?.message, debug: { origin: this.options.origin, tenantId, channelType, }, }); - this.logger.error(err.message, err.stack, errorMsg); + this.logger.error(err?.message, err?.stack, errorMsg); throw new Error(); } const docUrl = 'https://github.com/finastra/finastra-nodejs-libs/blob/develop/libs/oidc/README.md'; @@ -125,7 +126,7 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { - this.logger.log(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}`); + this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}`); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -174,12 +175,12 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { - this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, error message: ${err?.message}`); return next(err || info); } req.logIn(user, err => { if (err) { - this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, error message: ${err?.message}`); return next(err); } this.updateSessionDuration(req); @@ -203,7 +204,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { - this.logger.error(`url: ${req.url}, body: ${JSON.stringify(req.body)}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); res.status(HttpStatus.NOT_FOUND).send(); } } From ebab1144fc6c48e66ea170896382a17c7dc99072 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Thu, 22 Aug 2024 08:55:24 +0200 Subject: [PATCH 07/11] remove instance id from oidc module, remove logging of res.body --- libs/oidc/src/oidc.module.ts | 10 ++++------ libs/oidc/src/services/oidc.service.ts | 12 +++++------- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/libs/oidc/src/oidc.module.ts b/libs/oidc/src/oidc.module.ts index cee8515b..d1ef0b92 100644 --- a/libs/oidc/src/oidc.module.ts +++ b/libs/oidc/src/oidc.module.ts @@ -1,4 +1,3 @@ -import { SERVER_INSTANCE_ID } from '@finastra/nestjs-logger'; import { DynamicModule, Global, MiddlewareConsumer, Module, NestModule, Provider, RequestMethod } from '@nestjs/common'; import { APP_FILTER, APP_GUARD } from '@nestjs/core'; import { JwtModule } from '@nestjs/jwt'; @@ -59,7 +58,7 @@ export class OidcModule implements NestModule { ); } - static forRoot(options: OidcModuleOptions, serverInstanceID: string): DynamicModule { + static forRoot(options: OidcModuleOptions): DynamicModule { options = mergeDefaults(options); return { module: OidcModule, @@ -67,17 +66,16 @@ export class OidcModule implements NestModule { { provide: OIDC_MODULE_OPTIONS, useValue: options, - }, - { provide: SERVER_INSTANCE_ID, useValue: serverInstanceID } + } ], }; } - static forRootAsync(options: OidcModuleAsyncOptions, serverInstanceID: string): DynamicModule { + static forRootAsync(options: OidcModuleAsyncOptions): DynamicModule { return { module: OidcModule, imports: options.imports, - providers: [...this.createAsyncProviders(options), { provide: 'SERVER_INSTANCE_ID', useValue: serverInstanceID }], + providers: this.createAsyncProviders(options), }; } diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index a81a32db..25f8beab 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -1,4 +1,3 @@ -import { SERVER_INSTANCE_ID } from '@finastra/nestjs-logger'; import { HttpStatus, Inject, Injectable, Logger, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; import axios from 'axios'; import { Request, Response } from 'express'; @@ -37,7 +36,6 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, - @Inject(SERVER_INSTANCE_ID) private serverInstanceID: string, private ssrPagesService: SSRPagesService, ) { this.isMultitenant = !!this.options.issuerOrigin; @@ -102,7 +100,7 @@ export class OidcService implements OnModuleInit { channelType, }, }); - this.logger.error(err?.message, err?.stack, errorMsg); + this.logger.error(`err?.message`, err?.stack, errorMsg); throw new Error(); } const docUrl = 'https://github.com/finastra/finastra-nodejs-libs/blob/develop/libs/oidc/README.md'; @@ -126,7 +124,7 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { - this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}`); + this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}`); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -175,12 +173,12 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, error message: ${err?.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}`); return next(err || info); } req.logIn(user, err => { if (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, error message: ${err?.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}`); return next(err); } this.updateSessionDuration(req); @@ -204,7 +202,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.serverInstanceID}, message: ${err.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, message: ${err.message}`); res.status(HttpStatus.NOT_FOUND).send(); } } From 66f3114ad3e701b41eb06a293cb6affd9c6cd7d0 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Tue, 10 Sep 2024 15:31:56 +0200 Subject: [PATCH 08/11] instance id passed trough config service --- .../interceptors/common-http.interceptor.ts | 12 ++++++----- libs/logger/src/logger.module.ts | 8 ++------ libs/logger/src/oms/oms.logger.service.ts | 20 ++++++++++--------- libs/oidc/src/services/oidc.service.ts | 12 +++++++---- 4 files changed, 28 insertions(+), 24 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.ts b/libs/logger/src/interceptors/common-http.interceptor.ts index 58315e39..e64da8cd 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.ts @@ -1,13 +1,15 @@ -import { CallHandler, ExecutionContext, Inject, Injectable, Logger, NestInterceptor } from '@nestjs/common'; +import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; -import { SERVER_INSTANCE_ID } from '../logger.module'; @Injectable() export class HttpLoggingInterceptor implements NestInterceptor { readonly logger = new Logger(HttpLoggingInterceptor.name); + #instanceID: string; - constructor(@Inject(SERVER_INSTANCE_ID) private serverInstanceID: string) { + constructor(private configService: ConfigService) { + this.#instanceID = configService.get('SERVER_INSTANCE_ID'); } intercept(context: ExecutionContext, next: CallHandler): Observable { @@ -16,13 +18,13 @@ export class HttpLoggingInterceptor implements NestInterceptor { if (context['contextType'] !== 'graphql') { log = true; - this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.serverInstanceID}`); + this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); } return next.handle().pipe( tap(() => { if (log) { - this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.serverInstanceID}`); + this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); } }), ); diff --git a/libs/logger/src/logger.module.ts b/libs/logger/src/logger.module.ts index 7e1c2a51..e232f569 100644 --- a/libs/logger/src/logger.module.ts +++ b/libs/logger/src/logger.module.ts @@ -1,8 +1,6 @@ import { DynamicModule, Module } from '@nestjs/common'; import { OMSLogger } from './oms/oms.logger.service'; -export const SERVER_INSTANCE_ID = 'SERVER_INSTANCE_ID'; - @Module({ providers: [ OMSLogger @@ -10,11 +8,9 @@ export const SERVER_INSTANCE_ID = 'SERVER_INSTANCE_ID'; exports: [OMSLogger], }) export class LoggerModule { - static register(serverInstanceID: string): DynamicModule { + static register(): DynamicModule { return { - module: LoggerModule, - providers: [{ provide: SERVER_INSTANCE_ID, useValue: serverInstanceID }], - exports: [SERVER_INSTANCE_ID], + module: LoggerModule }; } } diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index 1696c3f0..b756d836 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -1,11 +1,13 @@ -import { ConsoleLogger, Inject, Injectable, Scope } from '@nestjs/common'; -import { SERVER_INSTANCE_ID } from '../logger.module'; +import { ConsoleLogger, Injectable, Scope } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import { OMSLogLevel } from './OMSLog.interface'; @Injectable({ scope: Scope.TRANSIENT }) export class OMSLogger extends ConsoleLogger { - constructor(@Inject(SERVER_INSTANCE_ID) private serverInstanceID: string) { + #instanceID: string; + constructor(private configService: ConfigService) { super(); + this.#instanceID = configService.get('SERVER_INSTANCE_ID'); } private print(logLevel: OMSLogLevel, message: string, context?: string, stackTrace?: string) { @@ -20,31 +22,31 @@ export class OMSLogger extends ConsoleLogger { msg: message, logger: currentContext, stack_trace: stackTrace, - instanceID: this.serverInstanceID, + instanceID: this.#instanceID, }; console.log(JSON.stringify(logEntry)); } log(message: string, context?: string) { - process.stdout.isTTY ? super.log.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.INFO, message, context); + process.stdout.isTTY ? super.log.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.INFO, message, context); } error(message: string, stackTrace: string, context?: string) { process.stdout.isTTY - ? super.error.apply(this, [...arguments, this.serverInstanceID]) + ? super.error.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.ERROR, message, context, `${JSON.stringify(stackTrace)}`); } warn(message: string, context?: string) { - process.stdout.isTTY ? super.warn.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.WARNING, message, context); + process.stdout.isTTY ? super.warn.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.WARNING, message, context); } debug(message: string, context?: string) { - process.stdout.isTTY ? super.debug.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.DEBUG, message, context); + process.stdout.isTTY ? super.debug.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.DEBUG, message, context); } verbose(message: string, context?: string) { - process.stdout.isTTY ? super.verbose.apply(this, [...arguments, this.serverInstanceID]) : this.print(OMSLogLevel.VERBOSE, message, context); + process.stdout.isTTY ? super.verbose.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.VERBOSE, message, context); } } diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index 25f8beab..bffaadf0 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -1,4 +1,5 @@ import { HttpStatus, Inject, Injectable, Logger, Next, OnModuleInit, Param, Req, Res } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import axios from 'axios'; import { Request, Response } from 'express'; import * as handlebars from 'handlebars'; @@ -25,6 +26,7 @@ export class OidcService implements OnModuleInit { readonly logger = new Logger(OidcService.name); isMultitenant: boolean = false; strategy: any; + #instanceID: string; idpInfos: { [tokenName: string]: { trustIssuer: Issuer; @@ -36,9 +38,11 @@ export class OidcService implements OnModuleInit { constructor( @Inject(OIDC_MODULE_OPTIONS) public options: OidcModuleOptions, + configService: ConfigService, private ssrPagesService: SSRPagesService, ) { this.isMultitenant = !!this.options.issuerOrigin; + this.#instanceID = configService.get('SERVER_INSTANCE_ID'); } async onModuleInit() { @@ -124,7 +128,7 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { - this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}`); + this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.#instanceID}`); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -173,12 +177,12 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); return next(err || info); } req.logIn(user, err => { if (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); return next(err); } this.updateSessionDuration(req); @@ -202,7 +206,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, message: ${err.message}`); + this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, message: ${err.message}, instanceID: ${this.#instanceID}`); res.status(HttpStatus.NOT_FOUND).send(); } } From 3e93ee27ee95973f1a7a98d8f8abfd3b763c8cfa Mon Sep 17 00:00:00 2001 From: SebastianW Date: Tue, 10 Sep 2024 15:45:53 +0200 Subject: [PATCH 09/11] fix tests --- .../src/interceptors/common-http.interceptor.spec.ts | 6 ++++-- libs/logger/src/oms/oms.logger.service.spec.ts | 11 ++++++++--- libs/oidc/src/oidc.module.spec.ts | 9 ++++----- libs/oidc/src/oidc.module.ts | 2 ++ libs/oidc/src/services/oidc.service.spec.ts | 4 ++-- libs/oidc/src/strategies/oidc.strategy.spec.ts | 4 ++-- libs/oidc/src/utils/user-info.spec.ts | 4 ++-- 7 files changed, 24 insertions(+), 16 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.spec.ts b/libs/logger/src/interceptors/common-http.interceptor.spec.ts index 0d54cdf0..f04f0d52 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.spec.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.spec.ts @@ -1,14 +1,16 @@ import { createMock } from '@golevelup/nestjs-testing'; import { CallHandler, ExecutionContext } from '@nestjs/common'; -import { randomUUID } from 'crypto'; +import { ConfigService } from '@nestjs/config'; import { of } from 'rxjs'; import { HttpLoggingInterceptor } from './common-http.interceptor'; describe('HttpLoggingInterceptor', () => { let interceptor; + let configService; beforeEach(() => { - interceptor = new HttpLoggingInterceptor(randomUUID()); + configService = new ConfigService(); + interceptor = new HttpLoggingInterceptor(configService); }); it('should be defined', () => { diff --git a/libs/logger/src/oms/oms.logger.service.spec.ts b/libs/logger/src/oms/oms.logger.service.spec.ts index 6f451d17..b35cf151 100644 --- a/libs/logger/src/oms/oms.logger.service.spec.ts +++ b/libs/logger/src/oms/oms.logger.service.spec.ts @@ -1,15 +1,18 @@ +import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { OMSLogger } from './oms.logger.service'; describe('OMSLogger', () => { let service: OMSLogger; + let configService: ConfigService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ - providers: [OMSLogger], + providers: [OMSLogger, ConfigService], }).compile(); service = await module.resolve(OMSLogger); + configService = await module.resolve(ConfigService); jest.spyOn(console, 'log').mockImplementation(() => 'test'); process.stdout.isTTY = false; @@ -52,16 +55,18 @@ describe('OMSLogger', () => { describe('OMSLogger - with mocked interactive console', () => { let service: OMSLogger; + let configService: ConfigService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ - providers: [OMSLogger], + providers: [OMSLogger, ConfigService], }).compile(); service = await module.resolve(OMSLogger); + configService = await module.resolve(ConfigService); jest.spyOn(console, 'log').mockImplementation(() => 'test'); - process.stdout.isTTY = true; + process.stdout.isTTY = false; }); it('should show debug message', () => { diff --git a/libs/oidc/src/oidc.module.spec.ts b/libs/oidc/src/oidc.module.spec.ts index 36b60dd9..1e212dd9 100644 --- a/libs/oidc/src/oidc.module.spec.ts +++ b/libs/oidc/src/oidc.module.spec.ts @@ -1,12 +1,11 @@ import { createMock } from '@golevelup/nestjs-testing'; import { MiddlewareConsumer } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { randomUUID } from 'crypto'; import { Issuer } from 'openid-client'; import { MOCK_ISSUER_INSTANCE, MOCK_OIDC_MODULE_OPTIONS } from './mocks'; import { OidcModule } from './oidc.module'; -describe('OidcModule', () => { +describe(OidcModule.name, () => { describe('register sync', () => { let module: TestingModule; @@ -15,7 +14,7 @@ describe('OidcModule', () => { IssuerMock.keystore = jest.fn(); jest.spyOn(Issuer, 'discover').mockImplementation(() => Promise.resolve(IssuerMock)); module = await Test.createTestingModule({ - imports: [OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS, randomUUID())], + imports: [OidcModule.forRoot(MOCK_OIDC_MODULE_OPTIONS)], }).compile(); }); @@ -35,7 +34,7 @@ describe('OidcModule', () => { imports: [ OidcModule.forRootAsync({ useFactory: async () => MOCK_OIDC_MODULE_OPTIONS, - }, randomUUID()), + }), ], }).compile(); }); @@ -64,7 +63,7 @@ describe('OidcModule', () => { imports: [ OidcModule.forRootAsync({ useClass: oidcModuleOptions, - }, randomUUID()), + }), ], }).compile(); }); diff --git a/libs/oidc/src/oidc.module.ts b/libs/oidc/src/oidc.module.ts index d1ef0b92..ff7aa0e5 100644 --- a/libs/oidc/src/oidc.module.ts +++ b/libs/oidc/src/oidc.module.ts @@ -1,4 +1,5 @@ import { DynamicModule, Global, MiddlewareConsumer, Module, NestModule, Provider, RequestMethod } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import { APP_FILTER, APP_GUARD } from '@nestjs/core'; import { JwtModule } from '@nestjs/jwt'; import { TenantSwitchController } from './controllers'; @@ -30,6 +31,7 @@ import { SessionSerializer } from './utils/session.serializer'; TokenGuard, GuestTokenGuard, OidcService, + ConfigService, SSRPagesService, { provide: APP_GUARD, diff --git a/libs/oidc/src/services/oidc.service.spec.ts b/libs/oidc/src/services/oidc.service.spec.ts index 40ae6d2f..9440d1be 100644 --- a/libs/oidc/src/services/oidc.service.spec.ts +++ b/libs/oidc/src/services/oidc.service.spec.ts @@ -1,5 +1,5 @@ +import { ConfigService } from '@nestjs/config'; import axios from 'axios'; -import { randomUUID } from 'crypto'; import * as handlebars from 'handlebars'; import { JWKS } from 'jose'; import { createRequest, createResponse } from 'node-mocks-http'; @@ -12,7 +12,7 @@ import { SSRPagesService } from './ssr-pages.service'; import passport = require('passport'); describe('OidcService', () => { - let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); + let service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService()); let options: OidcModuleOptions = MOCK_OIDC_MODULE_OPTIONS; const idpKey = 'idpKey'; diff --git a/libs/oidc/src/strategies/oidc.strategy.spec.ts b/libs/oidc/src/strategies/oidc.strategy.spec.ts index 5be4d971..c373fac0 100644 --- a/libs/oidc/src/strategies/oidc.strategy.spec.ts +++ b/libs/oidc/src/strategies/oidc.strategy.spec.ts @@ -1,5 +1,5 @@ import { createMock } from '@golevelup/nestjs-testing'; -import { randomUUID } from 'crypto'; +import { ConfigService } from '@nestjs/config'; import { JWKS } from 'jose'; import { TokenSet } from 'openid-client'; import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks'; @@ -13,7 +13,7 @@ describe('OidcStrategy', () => { let mockTokenset: TokenSet; beforeEach(() => { - const mockOidcService = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); + const mockOidcService = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService()); const idpKey = 'idpKey'; mockOidcService.idpInfos[idpKey] = { client: MOCK_CLIENT_INSTANCE, diff --git a/libs/oidc/src/utils/user-info.spec.ts b/libs/oidc/src/utils/user-info.spec.ts index 5d2f3765..93204cc8 100644 --- a/libs/oidc/src/utils/user-info.spec.ts +++ b/libs/oidc/src/utils/user-info.spec.ts @@ -1,4 +1,4 @@ -import { randomUUID } from 'crypto'; +import { ConfigService } from '@nestjs/config'; import { JWKS } from 'jose'; import { UserInfoMethod } from '../interfaces'; import { MOCK_CLIENT_INSTANCE, MOCK_OIDC_MODULE_OPTIONS, MOCK_TRUST_ISSUER } from '../mocks'; @@ -16,7 +16,7 @@ describe('OidcStrategy', () => { let service; beforeEach(() => { - service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, randomUUID(), new SSRPagesService()); + service = new OidcService(MOCK_OIDC_MODULE_OPTIONS, new ConfigService(), new SSRPagesService()); service.idpInfos[idpKey] = { client: MOCK_CLIENT_INSTANCE, tokenStore: new JWKS.KeyStore([]), From 69f61d4f806c43a6650892f46373632b8eb27f52 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Wed, 18 Sep 2024 15:10:59 +0200 Subject: [PATCH 10/11] session logging, restore httpexceptionfilter, added logging to different login stages --- .../interceptors/common-http.interceptor.ts | 4 +-- .../logger/src/oms/oms.logger.service.spec.ts | 2 +- libs/logger/src/oms/oms.logger.service.ts | 12 ++++----- .../oidc/src/filters/http-exception.filter.ts | 5 ++-- libs/oidc/src/services/oidc.service.ts | 25 +++++++++++-------- 5 files changed, 26 insertions(+), 22 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.ts b/libs/logger/src/interceptors/common-http.interceptor.ts index e64da8cd..410490e7 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.ts @@ -18,13 +18,13 @@ export class HttpLoggingInterceptor implements NestInterceptor { if (context['contextType'] !== 'graphql') { log = true; - this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); + this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID} session: ${req.session}`); } return next.handle().pipe( tap(() => { if (log) { - this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); + this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID} session: ${req.session}`); } }), ); diff --git a/libs/logger/src/oms/oms.logger.service.spec.ts b/libs/logger/src/oms/oms.logger.service.spec.ts index b35cf151..7ec3538e 100644 --- a/libs/logger/src/oms/oms.logger.service.spec.ts +++ b/libs/logger/src/oms/oms.logger.service.spec.ts @@ -66,7 +66,7 @@ describe('OMSLogger - with mocked interactive console', () => { configService = await module.resolve(ConfigService); jest.spyOn(console, 'log').mockImplementation(() => 'test'); - process.stdout.isTTY = false; + process.stdout.isTTY = true; }); it('should show debug message', () => { diff --git a/libs/logger/src/oms/oms.logger.service.ts b/libs/logger/src/oms/oms.logger.service.ts index b756d836..49e21964 100644 --- a/libs/logger/src/oms/oms.logger.service.ts +++ b/libs/logger/src/oms/oms.logger.service.ts @@ -29,24 +29,24 @@ export class OMSLogger extends ConsoleLogger { } log(message: string, context?: string) { - process.stdout.isTTY ? super.log.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.INFO, message, context); + process.stdout.isTTY ? super.log.apply(this, arguments) : this.print(OMSLogLevel.INFO, message, context); } error(message: string, stackTrace: string, context?: string) { process.stdout.isTTY - ? super.error.apply(this, [...arguments, this.#instanceID]) + ? super.error.apply(this, arguments) : this.print(OMSLogLevel.ERROR, message, context, `${JSON.stringify(stackTrace)}`); } warn(message: string, context?: string) { - process.stdout.isTTY ? super.warn.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.WARNING, message, context); + process.stdout.isTTY ? super.warn.apply(this, arguments) : this.print(OMSLogLevel.WARNING, message, context); } debug(message: string, context?: string) { - process.stdout.isTTY ? super.debug.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.DEBUG, message, context); + process.stdout.isTTY ? super.debug.apply(this, arguments) : this.print(OMSLogLevel.DEBUG, message, context); } verbose(message: string, context?: string) { - process.stdout.isTTY ? super.verbose.apply(this, [...arguments, this.#instanceID]) : this.print(OMSLogLevel.VERBOSE, message, context); + process.stdout.isTTY ? super.verbose.apply(this, arguments) : this.print(OMSLogLevel.VERBOSE, message, context); } -} +} \ No newline at end of file diff --git a/libs/oidc/src/filters/http-exception.filter.ts b/libs/oidc/src/filters/http-exception.filter.ts index 587d8a15..da286bea 100644 --- a/libs/oidc/src/filters/http-exception.filter.ts +++ b/libs/oidc/src/filters/http-exception.filter.ts @@ -15,10 +15,9 @@ export class HttpExceptionFilter implements ExceptionFilter { const request = ctx.getRequest(); const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR; - const { method, params, query, url, user } = request; + const { body, headers, method, params, query, url, user } = request; - // this.logger.error({ request: { method, params, query, url, user }, exception }); - this.logger.error(`${{ 'HttpExceptionFilter': method, params, query, url, user, exception }}`); + this.logger.error({ request: { body, headers, method, params, query, url, user }, exception }); switch (status) { case MisdirectedStatus.MISDIRECTED: diff --git a/libs/oidc/src/services/oidc.service.ts b/libs/oidc/src/services/oidc.service.ts index bffaadf0..f39729cf 100644 --- a/libs/oidc/src/services/oidc.service.ts +++ b/libs/oidc/src/services/oidc.service.ts @@ -14,12 +14,12 @@ import { loginPopupTemplate } from '../templates/login-popup.hbs'; import { SSRPagesService } from './ssr-pages.service'; import passport = require('passport'); -declare module 'express-session' { - interface SessionData { - tenant: string; - channel: string; - } -} +// declare module 'express-session' { +// interface SessionData { +// tenant: string; +// channel: string; +// } +// } @Injectable() export class OidcService implements OnModuleInit { @@ -128,7 +128,7 @@ export class OidcService implements OnModuleInit { } async login(@Req() req: Request, @Res() res: Response, @Next() next: Function, @Param() params) { - this.logger.log(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.#instanceID}`); + this.logger.log(`LOGIN url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.#instanceID}`); try { const tenantId = params.tenantId || req.session['tenant']; const channel = this.options.channelType || params.channelType || req.session['channel']; @@ -168,6 +168,8 @@ export class OidcService implements OnModuleInit { JSON.stringify({ redirect_url: `${prefix}${redirect_url}`, loginpopup: loginpopup }), 'utf-8', ).toString('base64'); + this.logger.log(`PRE_AUTHENTICATE url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.#instanceID}`); + passport.authenticate( Object.create(strategy), { @@ -177,12 +179,13 @@ export class OidcService implements OnModuleInit { }, (err, user, info) => { if (err || !user) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); + this.logger.error(`AUTHENTICATE url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); return next(err || info); } + this.logger.log(`PRE_LOGIN_REQ url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); req.logIn(user, err => { if (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); + this.logger.error(`LOGIN_REQ url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); return next(err); } this.updateSessionDuration(req); @@ -192,6 +195,7 @@ export class OidcService implements OnModuleInit { let url: string = state['redirect_url']; url = !url.startsWith('/') ? `/${url}` : url; const loginpopup = state['loginpopup']; + this.logger.log(`PRE_REDIRECT url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, error message: ${err?.message}, instanceID: ${this.#instanceID}`); if (loginpopup) { return res.send(` `); } else { + this.logger.log(`REDIRECT url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, instanceID: ${this.#instanceID}`); return res.redirect(url); } }); @@ -206,7 +211,7 @@ export class OidcService implements OnModuleInit { )(req, res, next); } } catch (err) { - this.logger.error(`url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, message: ${err.message}, instanceID: ${this.#instanceID}`); + this.logger.error(`CATCH url: ${req.url}, session: ${JSON.stringify(req.session)}, ip: ${req.ip}, method: ${req.method}, message: ${err.message}, instanceID: ${this.#instanceID}`); res.status(HttpStatus.NOT_FOUND).send(); } } From 7c73c9b941eefdc267f48266727818c64e56c3b6 Mon Sep 17 00:00:00 2001 From: SebastianW Date: Mon, 30 Sep 2024 12:51:21 +0200 Subject: [PATCH 11/11] remove req.session from log --- libs/logger/src/interceptors/common-http.interceptor.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libs/logger/src/interceptors/common-http.interceptor.ts b/libs/logger/src/interceptors/common-http.interceptor.ts index 410490e7..084fb45e 100644 --- a/libs/logger/src/interceptors/common-http.interceptor.ts +++ b/libs/logger/src/interceptors/common-http.interceptor.ts @@ -8,7 +8,7 @@ export class HttpLoggingInterceptor implements NestInterceptor { readonly logger = new Logger(HttpLoggingInterceptor.name); #instanceID: string; - constructor(private configService: ConfigService) { + constructor(configService: ConfigService) { this.#instanceID = configService.get('SERVER_INSTANCE_ID'); } @@ -18,13 +18,13 @@ export class HttpLoggingInterceptor implements NestInterceptor { if (context['contextType'] !== 'graphql') { log = true; - this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID} session: ${req.session}`); + this.logger.log(`START: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); } return next.handle().pipe( tap(() => { if (log) { - this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID} session: ${req.session}`); + this.logger.log(`STOP: ${context.getClass().name}.${context.getHandler().name}(): ${req.method} ${req.url} instanceID: ${this.#instanceID}`); } }), );