Skip to content

Commit

Permalink
refactor(logging): handle potential errors in masking function
Browse files Browse the repository at this point in the history
  • Loading branch information
amarlankri committed Dec 7, 2023
1 parent a4630b1 commit 0d23fd3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
17 changes: 13 additions & 4 deletions packages/logging-interceptor/src/logging.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,10 +288,19 @@ export class LoggingInterceptor implements NestInterceptor {
}

if (typeof mask === 'function') {
return {
...maskedHeaders,
[headerKey]: mask(headerValue),
};
try {
return {
...maskedHeaders,
[headerKey]: mask(headerValue),
};
} catch (err) {
this.logger.warn(`LoggingInterceptor - Masking error for header ${headerKey}`, err);

return {
...maskedHeaders,
[headerKey]: this.maskingPlaceholder,
};
}
}

return maskedHeaders;
Expand Down
17 changes: 17 additions & 0 deletions packages/logging-interceptor/test/logging.interceptor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,5 +470,22 @@ describe('Logging interceptor', () => {

expect(logSpy.mock.calls[0][0].headers.authorization).toBeUndefined();
});

it('should not fail if the masking function throws an error and mask the whole header as fallback', async () => {
const interceptor = app.get(ApplicationConfig).getGlobalInterceptors()[0] as LoggingInterceptor;
interceptor.setMask({
requestHeader: {
authorization: () => {
throw new Error('This is an error');
},
},
});
const logSpy: jest.SpyInstance = jest.spyOn(Logger.prototype, 'log');
const url: string = `/cats/ok`;

await request(app.getHttpServer()).get(url).set('authorization', 'Bearer JWT').expect(HttpStatus.OK);

expect(logSpy.mock.calls[0][0].headers.authorization).toBe(placeholder);
});
});
});

0 comments on commit 0d23fd3

Please sign in to comment.