Merge pull request 'fix(security): rate-limit per client IP behind trusted proxies' (#52) from fix/client-ip-behind-proxy into main
continuous-integration/drone/push Build is passing Details

Reviewed-on: #52
This commit is contained in:
Mihir Motiyani 2026-11-24 16:03:53 +05:30
commit 1b7d7362de
12 changed files with 168 additions and 40 deletions

View File

@ -14,5 +14,10 @@ RECOVERY_TTL_MINUTES=15
# RECOVERY_URL=https://shop.example.com/reset # RECOVERY_URL=https://shop.example.com/reset
DATABASE_POOL_SIZE=10 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,<frontend server IP>
# Optional; defaults to true only in development. # Optional; defaults to true only in development.
# SWAGGER_ENABLED=true # SWAGGER_ENABLED=true

View File

@ -28,7 +28,7 @@ Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only te
## Staging and launch procedure ## 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. 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. 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. 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. 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.

View File

@ -41,10 +41,10 @@
"@prisma/client": "^7.0.0", "@prisma/client": "^7.0.0",
"dotenv": "^17.0.0", "dotenv": "^17.0.0",
"helmet": "^8.0.0", "helmet": "^8.0.0",
"nodemailer": "^10.0.2", "nodemailer": "^10.6.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2", "rxjs": "^7.8.2",
"zod": "^4.0.0" "zod": "^4.6.7"
}, },
"devDependencies": { "devDependencies": {
"@electric-sql/pglite": "^0.5.8", "@electric-sql/pglite": "^0.5.8",

View File

@ -6,10 +6,11 @@ settings:
overrides: overrides:
'@prisma/config>deepmerge-ts': 8.0.0 '@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
prisma>mysql2: 3.23.1 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 '@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 express>proxy-addr: 2.0.8
importers: importers:
@ -41,8 +42,8 @@ importers:
specifier: ^8.0.0 specifier: ^8.0.0
version: 8.3.0 version: 8.3.0
nodemailer: nodemailer:
specifier: ^10.0.2 specifier: ^10.6.1
version: 10.0.11 version: 10.6.1
reflect-metadata: reflect-metadata:
specifier: ^0.2.2 specifier: ^0.2.2
version: 0.2.2 version: 0.2.2
@ -50,8 +51,8 @@ importers:
specifier: ^7.8.2 specifier: ^7.8.2
version: 7.8.2 version: 7.8.2
zod: zod:
specifier: ^4.0.0 specifier: ^4.6.7
version: 4.5.4 version: 4.6.7
devDependencies: devDependencies:
'@electric-sql/pglite': '@electric-sql/pglite':
specifier: ^0.5.8 specifier: ^0.5.8
@ -1340,8 +1341,8 @@ packages:
better-result@2.10.0: better-result@2.10.0:
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==} resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
body-parser@2.3.0: body-parser@2.4.0:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
brace-expansion@2.1.4: brace-expansion@2.1.4:
@ -1611,8 +1612,8 @@ packages:
ee-first@1.1.1: ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
effect@3.20.0: effect@3.22.5:
resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==} resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==}
electron-to-chromium@1.5.422: electron-to-chromium@1.5.422:
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==} resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
@ -1727,8 +1728,8 @@ packages:
fast-safe-stringify@2.1.1: fast-safe-stringify@2.1.1:
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
fast-uri@3.1.8: fast-uri@3.1.9:
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==} resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
fb-watchman@2.0.2: fb-watchman@2.0.2:
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
@ -2220,8 +2221,8 @@ packages:
ms@2.1.3: ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
multer@2.4.0: multer@2.5.0:
resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==} resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==}
engines: {node: '>= 10.16.0'} engines: {node: '>= 10.16.0'}
mysql2@3.23.1: mysql2@3.23.1:
@ -2259,8 +2260,8 @@ packages:
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==} resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
nodemailer@10.0.11: nodemailer@10.6.1:
resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==} resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==}
engines: {node: '>=20.0.0'} engines: {node: '>=20.0.0'}
normalize-path@3.0.0: normalize-path@3.0.0:
@ -2460,8 +2461,8 @@ packages:
pure-rand@7.0.1: pure-rand@7.0.1:
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==} resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
qs@6.16.0: qs@6.17.1:
resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==}
engines: {node: '>=0.6'} engines: {node: '>=0.6'}
range-parser@1.3.0: range-parser@1.3.0:
@ -2849,8 +2850,8 @@ packages:
zeptomatch@2.1.0: zeptomatch@2.1.0:
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==} resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
zod@4.5.4: zod@4.6.7:
resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==} resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
snapshots: 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) '@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 cors: 2.8.6
express: 5.2.1(supports-color@8.1.1) express: 5.2.1(supports-color@8.1.1)
multer: 2.4.0 multer: 2.5.0
path-to-regexp: 8.4.2 path-to-regexp: 8.4.2
tslib: 2.8.1 tslib: 2.8.1
transitivePeerDependencies: transitivePeerDependencies:
@ -3569,7 +3570,7 @@ snapshots:
dependencies: dependencies:
c12: 3.3.4 c12: 3.3.4
deepmerge-ts: 8.0.0 deepmerge-ts: 8.0.0
effect: 3.20.0 effect: 3.22.5
empathic: 2.0.0 empathic: 2.0.0
transitivePeerDependencies: transitivePeerDependencies:
- magicast - magicast
@ -4041,7 +4042,7 @@ snapshots:
ajv@8.20.0: ajv@8.20.0:
dependencies: dependencies:
fast-deep-equal: 3.1.3 fast-deep-equal: 3.1.3
fast-uri: 3.1.8 fast-uri: 3.1.9
json-schema-traverse: 1.0.0 json-schema-traverse: 1.0.0
require-from-string: 2.0.2 require-from-string: 2.0.2
@ -4140,7 +4141,7 @@ snapshots:
better-result@2.10.0: {} 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: dependencies:
bytes: 3.1.2 bytes: 3.1.2
content-type: 2.1.0 content-type: 2.1.0
@ -4148,7 +4149,7 @@ snapshots:
http-errors: 2.0.1 http-errors: 2.0.1
iconv-lite: 0.7.3 iconv-lite: 0.7.3
on-finished: 2.4.1 on-finished: 2.4.1
qs: 6.16.0 qs: 6.17.1
raw-body: 3.0.2 raw-body: 3.0.2
type-is: 2.1.0 type-is: 2.1.0
transitivePeerDependencies: transitivePeerDependencies:
@ -4380,7 +4381,7 @@ snapshots:
ee-first@1.1.1: {} ee-first@1.1.1: {}
effect@3.20.0: effect@3.22.5:
dependencies: dependencies:
'@standard-schema/spec': 1.1.0 '@standard-schema/spec': 1.1.0
fast-check: 3.23.2 fast-check: 3.23.2
@ -4488,7 +4489,7 @@ snapshots:
express@5.2.1(supports-color@8.1.1): express@5.2.1(supports-color@8.1.1):
dependencies: dependencies:
accepts: 2.0.0 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-disposition: 1.1.0
content-type: 1.0.5 content-type: 1.0.5
cookie: 0.7.2 cookie: 0.7.2
@ -4507,7 +4508,7 @@ snapshots:
once: 1.4.0 once: 1.4.0
parseurl: 1.3.3 parseurl: 1.3.3
proxy-addr: 2.0.8 proxy-addr: 2.0.8
qs: 6.16.0 qs: 6.17.1
range-parser: 1.3.0 range-parser: 1.3.0
router: 2.2.0(supports-color@8.1.1) router: 2.2.0(supports-color@8.1.1)
send: 1.2.1(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-safe-stringify@2.1.1: {}
fast-uri@3.1.8: {} fast-uri@3.1.9: {}
fb-watchman@2.0.2: fb-watchman@2.0.2:
dependencies: dependencies:
@ -5174,7 +5175,7 @@ snapshots:
ms@2.1.3: {} ms@2.1.3: {}
multer@2.4.0: multer@2.5.0:
dependencies: dependencies:
append-field: 1.0.0 append-field: 1.0.0
busboy: 1.6.0 busboy: 1.6.0
@ -5212,7 +5213,7 @@ snapshots:
node-releases@2.0.54: {} node-releases@2.0.54: {}
nodemailer@10.0.11: {} nodemailer@10.6.1: {}
normalize-path@3.0.0: {} normalize-path@3.0.0: {}
@ -5392,7 +5393,7 @@ snapshots:
pure-rand@7.0.1: {} pure-rand@7.0.1: {}
qs@6.16.0: qs@6.17.1:
dependencies: dependencies:
es-define-property: 1.0.1 es-define-property: 1.0.1
side-channel: 1.1.1 side-channel: 1.1.1
@ -5600,7 +5601,7 @@ snapshots:
formidable: 3.5.4 formidable: 3.5.4
methods: 1.1.2 methods: 1.1.2
mime: 2.6.0 mime: 2.6.0
qs: 6.16.0 qs: 6.17.1
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@ -5792,4 +5793,4 @@ snapshots:
grammex: 3.1.13 grammex: 3.1.13
graphmatch: 1.1.1 graphmatch: 1.1.1
zod@4.5.4: {} zod@4.6.7: {}

View File

@ -7,8 +7,9 @@ allowBuilds:
unrs-resolver: true unrs-resolver: true
overrides: overrides:
'@prisma/config>deepmerge-ts': 8.0.0 '@prisma/config>deepmerge-ts': 8.0.0
'@prisma/config>effect': 3.22.5
'prisma>mysql2': 3.23.1 '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 '@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 'express>proxy-addr': 2.0.8

View File

@ -1,4 +1,5 @@
import { identityEnvironmentShape, validateSmtp } from './identity-environment'; import { identityEnvironmentShape, validateSmtp } from './identity-environment';
import { isIP } from 'node:net';
import { z } from 'zod'; import { z } from 'zod';
const schema = z const schema = z
@ -12,6 +13,17 @@ const schema = z
.enum(['true', 'false']) .enum(['true', 'false'])
.transform((value) => value === 'true') .transform((value) => value === 'true')
.optional(), .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_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10),
DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)), DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)),
CORS_ORIGINS: z CORS_ORIGINS: z
@ -39,6 +51,18 @@ const schema = z
export type Environment = z.infer<typeof schema>; export type Environment = z.infer<typeof schema>;
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 { export function parseEnvironment(input: NodeJS.ProcessEnv): Environment {
const result = schema.safeParse(input); const result = schema.safeParse(input);
if (!result.success) { if (!result.success) {

View File

@ -10,6 +10,8 @@ export function configureApp(
app: INestApplication, app: INestApplication,
environment: Environment, environment: Environment,
): void { ): void {
if (environment.TRUST_PROXY.length)
(app as NestExpressApplication).set('trust proxy', environment.TRUST_PROXY);
app.setGlobalPrefix('api/v1'); app.setGlobalPrefix('api/v1');
app.use(helmet()); app.use(helmet());
app.use((_request: Request, response: Response, next: NextFunction) => { app.use((_request: Request, response: Response, next: NextFunction) => {

View File

@ -7,7 +7,7 @@ export class AuthRateGuard implements CanActivate {
constructor(private readonly limits: RateLimitService) {} constructor(private readonly limits: RateLimitService) {}
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>(); const request = context.switchToHttp().getRequest<Request>();
// 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); await this.limits.consume(`auth-ip:${request.ip}`, 30, 60);
return true; return true;
} }

View File

@ -19,6 +19,10 @@ export class RateLimitService {
THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END
RETURNING hits, expires_at AS "expiresAt" 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) if (row.hits > limit)
throw new AppError( throw new AppError(
'RATE_LIMITED', 'RATE_LIMITED',

View File

@ -27,12 +27,28 @@ describe('environment configuration', () => {
{ NODE_ENV: 'staging' }, { NODE_ENV: 'staging' },
{ CORS_ORIGINS: '*' }, { CORS_ORIGINS: '*' },
{ CORS_ORIGINS: 'https://shop.example.com/path' }, { 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) => { ])('rejects invalid configuration %j', (override) => {
expect(() => parseEnvironment({ ...valid, ...override })).toThrow( expect(() => parseEnvironment({ ...valid, ...override })).toThrow(
'Invalid environment', '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', () => { it('does not leak credentials in validation errors', () => {
expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow( expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow(
'DATABASE_URL', 'DATABASE_URL',

View File

@ -90,6 +90,23 @@ describe('identity transactional failure paths', () => {
}); });
await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined(); 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 () => { it('rechecks current permissions inside administration transactions', async () => {
const actor = await ctx.app.get(SessionStore).authenticate(ctx.token); const actor = await ctx.app.get(SessionStore).authenticate(ctx.token);
const ownerRole = await ctx.db.role.findFirstOrThrow({ const ownerRole = await ctx.db.role.findFirstOrThrow({

58
test/trust-proxy.spec.ts Normal file
View File

@ -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<INestApplication> {
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();
});
});