import 'reflect-metadata'; import { Controller, Get, Module, Req } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import type { INestApplication } from '@nestjs/common'; import type { Request } from 'express'; import request from 'supertest'; import { configureApp } from '../src/configure-app'; import { parseEnvironment } from '../src/config/environment'; @Controller('ip') class IpController { @Get() ip(@Req() req: Request) { return { ip: req.ip }; } } @Module({ controllers: [IpController] }) class IpModule {} async function appWith(TRUST_PROXY?: string): Promise { const module = await Test.createTestingModule({ imports: [IpModule], }).compile(); const app = module.createNestApplication(); configureApp( app, parseEnvironment({ DATABASE_URL: 'postgresql://localhost/mani', TRUST_PROXY, }), ); await app.init(); return app; } const ipOf = async (app: INestApplication, forwarded: string) => ( await request(app.getHttpServer()) .get('/api/v1/ip') .set('X-Forwarded-For', forwarded) .expect(200) ).body.ip as string; describe('client IP behind reverse proxies', () => { it('ignores forwarded headers when no proxy is trusted', async () => { const app = await appWith(); expect(await ipOf(app, '198.51.100.4')).not.toBe('198.51.100.4'); await app.close(); }); it('uses the forwarded client address from trusted hops only', async () => { // supertest connects over loopback, standing in for the local Nginx. const app = await appWith('loopback,203.0.113.7'); expect(await ipOf(app, '198.51.100.4, 203.0.113.7')).toBe('198.51.100.4'); // A client that skips the trusted frontend proxy cannot spoof an address. expect(await ipOf(app, '198.51.100.4, 192.0.2.66')).toBe('192.0.2.66'); await app.close(); }); });