From 74c129ba6cc46b06516f0b0a03e146a12025728a Mon Sep 17 00:00:00 2001 From: mihir Date: Tue, 24 Nov 2026 15:52:49 +0530 Subject: [PATCH] fix(security): rate-limit per client IP behind trusted proxies - Add TRUST_PROXY (IPs, CIDRs or loopback/linklocal/uniquelocal; never "true") so request.ip uses X-Forwarded-For only from known hops. Without it every visitor shares the proxy's rate-limit bucket. - Occasionally sweep long-expired rate_limits rows. - Patch zod, nodemailer, multer, fast-uri and effect advisories; the production audit reports no known vulnerabilities. Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 +++ docs/production-readiness.md | 2 +- package.json | 4 +- pnpm-lock.yaml | 69 +++++++++++++++--------------- pnpm-workspace.yaml | 5 ++- src/config/environment.ts | 24 +++++++++++ src/configure-app.ts | 2 + src/identity/auth-rate.guard.ts | 2 +- src/identity/rate-limit.service.ts | 4 ++ test/environment.spec.ts | 16 +++++++ test/identity-failures.spec.ts | 17 ++++++++ test/trust-proxy.spec.ts | 58 +++++++++++++++++++++++++ 12 files changed, 168 insertions(+), 40 deletions(-) create mode 100644 test/trust-proxy.spec.ts diff --git a/.env.example b/.env.example index 295e27e..dddc381 100644 --- a/.env.example +++ b/.env.example @@ -14,5 +14,10 @@ RECOVERY_TTL_MINUTES=15 # RECOVERY_URL=https://shop.example.com/reset DATABASE_POOL_SIZE=10 +# Reverse proxies whose X-Forwarded-For is trusted for client IPs (rate limits). +# Comma-separated IPs, CIDRs, or loopback/linklocal/uniquelocal. Empty = trust none. +# Behind the local Nginx plus the frontend server's Nginx, list both hops, e.g.: +# TRUST_PROXY=loopback,172.17.0.0/16, + # Optional; defaults to true only in development. # SWAGGER_ENABLED=true diff --git a/docs/production-readiness.md b/docs/production-readiness.md index 8d77957..15720ec 100644 --- a/docs/production-readiness.md +++ b/docs/production-readiness.md @@ -28,7 +28,7 @@ Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only te ## Staging and launch procedure 1. Select a reviewed commit whose two CI jobs pass. Record its SHA, the previous release SHA and migration manifest. Agree on the launch feature cut: payments, carriers, live marketing and automated scheduler invocation remain deferred. -2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). +2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). Rate limits key on the client IP: set `TRUST_PROXY` to exactly the proxy hops in front of the service (for example the backend host's Nginx or Docker bridge, plus the frontend server whose Nginx forwards `/api`), and make every hop append `X-Forwarded-For $proxy_add_x_forwarded_for`. Without it, all visitors share one proxy IP and one rate-limit bucket. Never trust all addresses; a direct caller could then spoof its IP. 3. Build the existing image or compiled application from that exact commit. For a source installation: `pnpm install --frozen-lockfile`, `pnpm db:generate`, `pnpm build`. The current Dockerfile is a development-derived build; non-root runtime, graceful shutdown verification, image scanning and a tested deployment definition remain launch work, not proven by this CI milestone. 4. Take a database backup and restore it into isolated staging. Verify representative immutable audit, order, supplier-payment and inventory records after restore. Keep production secrets and outbound provider access out of the staging restore. 5. Run `pnpm migrations:check`, then `pnpm db:deploy` and `pnpm db:status` against staging with migration credentials. Start the built service with restricted application credentials. Verify `/api/v1/health/live` and `/api/v1/health/ready`; readiness must fail when PostgreSQL is unavailable. diff --git a/package.json b/package.json index 31bd6f1..fe5510d 100644 --- a/package.json +++ b/package.json @@ -41,10 +41,10 @@ "@prisma/client": "^7.0.0", "dotenv": "^17.0.0", "helmet": "^8.0.0", - "nodemailer": "^10.0.2", + "nodemailer": "^10.6.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.2", - "zod": "^4.0.0" + "zod": "^4.6.7" }, "devDependencies": { "@electric-sql/pglite": "^0.5.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index db9adc7..b1234f0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,10 +6,11 @@ settings: overrides: '@prisma/config>deepmerge-ts': 8.0.0 + '@prisma/config>effect': 3.22.5 prisma>mysql2: 3.23.1 - '@nestjs/platform-express>multer': 2.4.0 + '@nestjs/platform-express>multer': 2.5.0 '@nestjs/swagger>js-yaml': 5.4.1 - ajv>fast-uri: 3.1.8 + ajv>fast-uri: 3.1.9 express>proxy-addr: 2.0.8 importers: @@ -41,8 +42,8 @@ importers: specifier: ^8.0.0 version: 8.3.0 nodemailer: - specifier: ^10.0.2 - version: 10.0.11 + specifier: ^10.6.1 + version: 10.6.1 reflect-metadata: specifier: ^0.2.2 version: 0.2.2 @@ -50,8 +51,8 @@ importers: specifier: ^7.8.2 version: 7.8.2 zod: - specifier: ^4.0.0 - version: 4.5.4 + specifier: ^4.6.7 + version: 4.6.7 devDependencies: '@electric-sql/pglite': specifier: ^0.5.8 @@ -1340,8 +1341,8 @@ packages: better-result@2.10.0: resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==} - body-parser@2.3.0: - resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} + body-parser@2.4.0: + resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} brace-expansion@2.1.4: @@ -1611,8 +1612,8 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - effect@3.20.0: - resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==} + effect@3.22.5: + resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==} electron-to-chromium@1.5.422: resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==} @@ -1727,8 +1728,8 @@ packages: fast-safe-stringify@2.1.1: resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} - fast-uri@3.1.8: - resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==} + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} fb-watchman@2.0.2: resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} @@ -2220,8 +2221,8 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - multer@2.4.0: - resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==} + multer@2.5.0: + resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==} engines: {node: '>= 10.16.0'} mysql2@3.23.1: @@ -2259,8 +2260,8 @@ packages: resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==} engines: {node: '>=18'} - nodemailer@10.0.11: - resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==} + nodemailer@10.6.1: + resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==} engines: {node: '>=20.0.0'} normalize-path@3.0.0: @@ -2460,8 +2461,8 @@ packages: pure-rand@7.0.1: resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==} - qs@6.16.0: - resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} range-parser@1.3.0: @@ -2849,8 +2850,8 @@ packages: zeptomatch@2.1.0: resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==} - zod@4.5.4: - resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==} + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} snapshots: @@ -3454,7 +3455,7 @@ snapshots: '@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2) cors: 2.8.6 express: 5.2.1(supports-color@8.1.1) - multer: 2.4.0 + multer: 2.5.0 path-to-regexp: 8.4.2 tslib: 2.8.1 transitivePeerDependencies: @@ -3569,7 +3570,7 @@ snapshots: dependencies: c12: 3.3.4 deepmerge-ts: 8.0.0 - effect: 3.20.0 + effect: 3.22.5 empathic: 2.0.0 transitivePeerDependencies: - magicast @@ -4041,7 +4042,7 @@ snapshots: ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.8 + fast-uri: 3.1.9 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -4140,7 +4141,7 @@ snapshots: better-result@2.10.0: {} - body-parser@2.3.0(supports-color@8.1.1): + body-parser@2.4.0(supports-color@8.1.1): dependencies: bytes: 3.1.2 content-type: 2.1.0 @@ -4148,7 +4149,7 @@ snapshots: http-errors: 2.0.1 iconv-lite: 0.7.3 on-finished: 2.4.1 - qs: 6.16.0 + qs: 6.17.1 raw-body: 3.0.2 type-is: 2.1.0 transitivePeerDependencies: @@ -4380,7 +4381,7 @@ snapshots: ee-first@1.1.1: {} - effect@3.20.0: + effect@3.22.5: dependencies: '@standard-schema/spec': 1.1.0 fast-check: 3.23.2 @@ -4488,7 +4489,7 @@ snapshots: express@5.2.1(supports-color@8.1.1): dependencies: accepts: 2.0.0 - body-parser: 2.3.0(supports-color@8.1.1) + body-parser: 2.4.0(supports-color@8.1.1) content-disposition: 1.1.0 content-type: 1.0.5 cookie: 0.7.2 @@ -4507,7 +4508,7 @@ snapshots: once: 1.4.0 parseurl: 1.3.3 proxy-addr: 2.0.8 - qs: 6.16.0 + qs: 6.17.1 range-parser: 1.3.0 router: 2.2.0(supports-color@8.1.1) send: 1.2.1(supports-color@8.1.1) @@ -4536,7 +4537,7 @@ snapshots: fast-safe-stringify@2.1.1: {} - fast-uri@3.1.8: {} + fast-uri@3.1.9: {} fb-watchman@2.0.2: dependencies: @@ -5174,7 +5175,7 @@ snapshots: ms@2.1.3: {} - multer@2.4.0: + multer@2.5.0: dependencies: append-field: 1.0.0 busboy: 1.6.0 @@ -5212,7 +5213,7 @@ snapshots: node-releases@2.0.54: {} - nodemailer@10.0.11: {} + nodemailer@10.6.1: {} normalize-path@3.0.0: {} @@ -5392,7 +5393,7 @@ snapshots: pure-rand@7.0.1: {} - qs@6.16.0: + qs@6.17.1: dependencies: es-define-property: 1.0.1 side-channel: 1.1.1 @@ -5600,7 +5601,7 @@ snapshots: formidable: 3.5.4 methods: 1.1.2 mime: 2.6.0 - qs: 6.16.0 + qs: 6.17.1 transitivePeerDependencies: - supports-color @@ -5792,4 +5793,4 @@ snapshots: grammex: 3.1.13 graphmatch: 1.1.1 - zod@4.5.4: {} + zod@4.6.7: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 823b15a..190c950 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -7,8 +7,9 @@ allowBuilds: unrs-resolver: true overrides: '@prisma/config>deepmerge-ts': 8.0.0 + '@prisma/config>effect': 3.22.5 'prisma>mysql2': 3.23.1 - '@nestjs/platform-express>multer': 2.4.0 + '@nestjs/platform-express>multer': 2.5.0 '@nestjs/swagger>js-yaml': 5.4.1 - 'ajv>fast-uri': 3.1.8 + 'ajv>fast-uri': 3.1.9 'express>proxy-addr': 2.0.8 diff --git a/src/config/environment.ts b/src/config/environment.ts index a66feac..1183a75 100644 --- a/src/config/environment.ts +++ b/src/config/environment.ts @@ -1,4 +1,5 @@ import { identityEnvironmentShape, validateSmtp } from './identity-environment'; +import { isIP } from 'node:net'; import { z } from 'zod'; const schema = z @@ -12,6 +13,17 @@ const schema = z .enum(['true', 'false']) .transform((value) => value === 'true') .optional(), + // Proxies whose X-Forwarded-For is believed. Never "true": any client could spoof its IP. + TRUST_PROXY: z + .string() + .default('') + .transform((value) => + value + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean), + ) + .pipe(z.array(z.string().refine(isTrustedProxy))), DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10), DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)), CORS_ORIGINS: z @@ -39,6 +51,18 @@ const schema = z export type Environment = z.infer; +const PROXY_NAMES = ['loopback', 'linklocal', 'uniquelocal']; +function isTrustedProxy(entry: string): boolean { + if (PROXY_NAMES.includes(entry)) return true; + const [address, prefix, extra] = entry.split('/'); + const family = isIP(address); + if (!family || extra !== undefined) return false; + if (prefix === undefined) return true; + return ( + /^\d{1,3}$/.test(prefix) && Number(prefix) <= (family === 4 ? 32 : 128) + ); +} + export function parseEnvironment(input: NodeJS.ProcessEnv): Environment { const result = schema.safeParse(input); if (!result.success) { diff --git a/src/configure-app.ts b/src/configure-app.ts index df83db1..b4198be 100644 --- a/src/configure-app.ts +++ b/src/configure-app.ts @@ -10,6 +10,8 @@ export function configureApp( app: INestApplication, environment: Environment, ): void { + if (environment.TRUST_PROXY.length) + (app as NestExpressApplication).set('trust proxy', environment.TRUST_PROXY); app.setGlobalPrefix('api/v1'); app.use(helmet()); app.use((_request: Request, response: Response, next: NextFunction) => { diff --git a/src/identity/auth-rate.guard.ts b/src/identity/auth-rate.guard.ts index 0190289..22a4f8b 100644 --- a/src/identity/auth-rate.guard.ts +++ b/src/identity/auth-rate.guard.ts @@ -7,7 +7,7 @@ export class AuthRateGuard implements CanActivate { constructor(private readonly limits: RateLimitService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); - // Express proxy trust remains disabled; never trust arbitrary forwarded IP headers. + // request.ip honours X-Forwarded-For only from TRUST_PROXY hops; never arbitrary clients. await this.limits.consume(`auth-ip:${request.ip}`, 30, 60); return true; } diff --git a/src/identity/rate-limit.service.ts b/src/identity/rate-limit.service.ts index 0c090a4..d4d5803 100644 --- a/src/identity/rate-limit.service.ts +++ b/src/identity/rate-limit.service.ts @@ -19,6 +19,10 @@ export class RateLimitService { THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END RETURNING hits, expires_at AS "expiresAt" `; + // shortcut: ~1% of calls sweep expired windows; move to the scheduler once one runs in production. + if (Math.random() < 0.01) + await this.db + .$executeRaw`DELETE FROM rate_limits WHERE expires_at < NOW() - INTERVAL '1 hour'`; if (row.hits > limit) throw new AppError( 'RATE_LIMITED', diff --git a/test/environment.spec.ts b/test/environment.spec.ts index 380dcf9..2ca1f14 100644 --- a/test/environment.spec.ts +++ b/test/environment.spec.ts @@ -27,12 +27,28 @@ describe('environment configuration', () => { { NODE_ENV: 'staging' }, { CORS_ORIGINS: '*' }, { CORS_ORIGINS: 'https://shop.example.com/path' }, + { TRUST_PROXY: 'true' }, + { TRUST_PROXY: '*' }, + { TRUST_PROXY: '2' }, + { TRUST_PROXY: '10.0.0.0/33' }, + { TRUST_PROXY: '10.0.0.1/8/1' }, + { TRUST_PROXY: 'proxy.example.com' }, ])('rejects invalid configuration %j', (override) => { expect(() => parseEnvironment({ ...valid, ...override })).toThrow( 'Invalid environment', ); }); + it('parses trusted proxy addresses, subnets and named ranges', () => { + expect(parseEnvironment(valid).TRUST_PROXY).toEqual([]); + expect( + parseEnvironment({ + ...valid, + TRUST_PROXY: ' loopback, 172.17.0.0/16 ,203.0.113.7,::1/128', + }).TRUST_PROXY, + ).toEqual(['loopback', '172.17.0.0/16', '203.0.113.7', '::1/128']); + }); + it('does not leak credentials in validation errors', () => { expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow( 'DATABASE_URL', diff --git a/test/identity-failures.spec.ts b/test/identity-failures.spec.ts index 0f2b260..8f9450f 100644 --- a/test/identity-failures.spec.ts +++ b/test/identity-failures.spec.ts @@ -90,6 +90,23 @@ describe('identity transactional failure paths', () => { }); await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined(); }); + it('sweeps long-expired rate-limit windows', async () => { + const limits = ctx.app.get(RateLimitService); + await ctx.db.rateLimit.create({ + data: { key: hashToken('stale-bucket'), hits: 1, expiresAt: new Date(0) }, + }); + const random = jest.spyOn(Math, 'random').mockReturnValue(0); + try { + await limits.consume('sweep-trigger', 100, 60); + } finally { + random.mockRestore(); + } + expect( + await ctx.db.rateLimit.findUnique({ + where: { key: hashToken('stale-bucket') }, + }), + ).toBeNull(); + }); it('rechecks current permissions inside administration transactions', async () => { const actor = await ctx.app.get(SessionStore).authenticate(ctx.token); const ownerRole = await ctx.db.role.findFirstOrThrow({ diff --git a/test/trust-proxy.spec.ts b/test/trust-proxy.spec.ts new file mode 100644 index 0000000..9792253 --- /dev/null +++ b/test/trust-proxy.spec.ts @@ -0,0 +1,58 @@ +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(); + }); +});