Skip to content

Commit

Permalink
feat(logging): apply log masks to http exception body
Browse files Browse the repository at this point in the history
  • Loading branch information
LeKer29 committed Nov 28, 2023
1 parent c75572a commit a3abe51
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/logging-interceptor/src/logging.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,17 @@ export class LoggingInterceptor implements NestInterceptor {
const ctx: string = `${this.userPrefix}${this.ctxPrefix} - ${statusCode} - ${method} - ${url}`;
const message: string = `Outgoing response - ${statusCode} - ${method} - ${url}`;

const options: LogOptions | undefined = Reflect.getMetadata(METHOD_LOG_METADATA, context.getHandler());

// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
const maskedBody = options?.mask?.request ? this.maskData(body, options.mask.request) : body;

if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
this.logger.error(
{
method,
url,
body,
body: maskedBody,
message,
error,
},
Expand All @@ -149,7 +154,7 @@ export class LoggingInterceptor implements NestInterceptor {
method,
url,
error,
body,
body: maskedBody,
message,
},
ctx,
Expand Down
30 changes: 30 additions & 0 deletions packages/logging-interceptor/test/logging.interceptor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,5 +366,35 @@ describe('Logging interceptor', () => {

interceptor.setMaskingPlaceholder(placeholder);
});

it('should mask http exception response', async () => {
const logSpy: jest.SpyInstance = jest.spyOn(Logger.prototype, 'log');
const url: string = `/cats`;

await request(app.getHttpServer())
.post(url)
.send({
name: 'dog',
birthdate: '1980-01-01',
})
.expect(HttpStatus.BAD_REQUEST);

const ctx: string = `LoggingInterceptor - POST - ${url}`;
const incomingMsg: string = `Incoming request - POST - ${url}`;

expect(logSpy).toBeCalledTimes(1);
expect(logSpy.mock.calls[0]).toEqual([
{
body: {
name: 'dog',
birthdate: placeholder,
},
headers: expect.any(Object),
message: incomingMsg,
method: `POST`,
},
ctx,
]);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ export class CatsController {
},
})
public createCat(@Body() payload: CreateCatDto) {
if (payload.name === 'dog') {
throw new BadRequestException({ message: 'You cannot name a cat dog' });
}

return { id: 1, ...payload };
}

Expand Down

0 comments on commit a3abe51

Please sign in to comment.