|
| 1 | +import { |
| 2 | + CallHandler, |
| 3 | + ExecutionContext, |
| 4 | + Logger, |
| 5 | +} from '@nestjs/common'; |
| 6 | +import { lastValueFrom, of } from 'rxjs'; |
| 7 | +import { RequestLoggingInterceptor } from './request-logging.interceptor'; |
| 8 | + |
| 9 | +function createExecutionContext( |
| 10 | + request: Record<string, unknown>, |
| 11 | + response: Record<string, unknown>, |
| 12 | +): ExecutionContext { |
| 13 | + return { |
| 14 | + switchToHttp: () => ({ |
| 15 | + getRequest: () => request, |
| 16 | + getResponse: () => response, |
| 17 | + }), |
| 18 | + } as ExecutionContext; |
| 19 | +} |
| 20 | + |
| 21 | +describe('RequestLoggingInterceptor', () => { |
| 22 | + afterEach(() => { |
| 23 | + jest.restoreAllMocks(); |
| 24 | + }); |
| 25 | + |
| 26 | + it('logs method, url, status code, and duration', async () => { |
| 27 | + const interceptor = new RequestLoggingInterceptor(); |
| 28 | + const context = createExecutionContext( |
| 29 | + { method: 'GET', url: '/health' }, |
| 30 | + { statusCode: 200 }, |
| 31 | + ); |
| 32 | + const next: CallHandler = { handle: () => of('ok') }; |
| 33 | + |
| 34 | + jest.spyOn(Date, 'now').mockReturnValueOnce(100).mockReturnValueOnce(115); |
| 35 | + const logSpy = jest |
| 36 | + .spyOn(Logger.prototype, 'log') |
| 37 | + .mockImplementation(() => undefined); |
| 38 | + |
| 39 | + await expect(lastValueFrom(interceptor.intercept(context, next))).resolves.toBe( |
| 40 | + 'ok', |
| 41 | + ); |
| 42 | + |
| 43 | + expect(logSpy).toHaveBeenCalledWith('GET /health 200 15ms'); |
| 44 | + }); |
| 45 | + |
| 46 | + it('does not log sensitive request data', async () => { |
| 47 | + const interceptor = new RequestLoggingInterceptor(); |
| 48 | + const context = createExecutionContext( |
| 49 | + { |
| 50 | + method: 'POST', |
| 51 | + url: '/auth/verify?token=sensitive-query-token', |
| 52 | + headers: { authorization: 'Bearer secret-token' }, |
| 53 | + body: { password: 'super-secret', email: 'user@example.com' }, |
| 54 | + query: { token: 'sensitive-query-token' }, |
| 55 | + }, |
| 56 | + { statusCode: 401 }, |
| 57 | + ); |
| 58 | + const next: CallHandler = { handle: () => of('denied') }; |
| 59 | + |
| 60 | + jest.spyOn(Date, 'now').mockReturnValueOnce(200).mockReturnValueOnce(240); |
| 61 | + const logSpy = jest |
| 62 | + .spyOn(Logger.prototype, 'log') |
| 63 | + .mockImplementation(() => undefined); |
| 64 | + |
| 65 | + await lastValueFrom(interceptor.intercept(context, next)); |
| 66 | + |
| 67 | + const [message] = logSpy.mock.calls.at(-1) ?? []; |
| 68 | + |
| 69 | + expect(message).toBe('POST /auth/verify 401 40ms'); |
| 70 | + expect(message).not.toContain('secret-token'); |
| 71 | + expect(message).not.toContain('super-secret'); |
| 72 | + expect(message).not.toContain('user@example.com'); |
| 73 | + expect(message).not.toContain('sensitive-query-token'); |
| 74 | + }); |
| 75 | +}); |
0 commit comments