Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): bound the ingress route on the client IP too
Yudhi Armyndharis5b26fa4cffe0
diff --git a/.env.example b/.env.exampleindex 627122055..f81e6a5d1 100644--- a/.env.example+++ b/.env.example@@ -582,6 +582,11 @@ WEBHOOK_SSRF_PROTECT=true# Independent of, and in addition to, the IP-keyed tiers above.# INGRESS_INSTANCE_LIMIT=120 # max requests per instance per window (default 120)# INGRESS_INSTANCE_TTL=60000 # window in ms (default 60000 = 60s)+# Second bucket on the same window, keyed on the client instead of the path. The per-instance key is+# built from the caller-supplied :pluginId/:instanceId, so varying them mints a fresh bucket; this+# bound is what an unauthenticated caller cannot walk around. Sized 10x the per-instance default so+# it never binds before it, raise it if one IP legitimately drives more than that.+# INGRESS_IP_LIMIT=1200 # max ingress requests per client IP per window (default 1200)# Integration Fabric delivery retry + retention (the queued path taken when QUEUE_ENABLED=true).# INGRESS_MAX_ATTEMPTS=3 # delivery attempts before an event is dead-lettered (min 1)diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b23861c4d..9d79edb78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -61,6 +61,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The SQLite database files are tightened to owner-only (`0600`, plus `-wal`/`-shm`/`-journal`) on every boot; they hold plaintext webhook/plugin secrets and were group/world-readable while sibling secret files were `0600`.- `PUT /sessions/{sessionId}/webhooks/{id}` now enforces the same 16-character webhook-secret floor as create; an empty string still clears signing.+- The ingress route enforces a second rate-limit window keyed on the client IP (`INGRESS_IP_LIMIT`, default 1200 per window). Its per-instance window is keyed on the caller-supplied `:pluginId/:instanceId`, so varying those segments minted a fresh bucket per request and left this unauthenticated route with no effective bound.## [0.20.0] - 2026-08-16diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex ea8fe6741..8c6c0026c 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -198,6 +198,7 @@ services:# Integration Fabric ingress: fairness, retries, retention, reconciler, workers.- INGRESS_INSTANCE_LIMIT=${INGRESS_INSTANCE_LIMIT:-}- INGRESS_INSTANCE_TTL=${INGRESS_INSTANCE_TTL:-}+ - INGRESS_IP_LIMIT=${INGRESS_IP_LIMIT:-}- INGRESS_MAX_ATTEMPTS=${INGRESS_MAX_ATTEMPTS:-}- INGRESS_RETRY_DELAY_MS=${INGRESS_RETRY_DELAY_MS:-}- INGRESS_DEDUP_RETENTION_DAYS=${INGRESS_DEDUP_RETENTION_DAYS:-}diff --git a/docker-compose.yml b/docker-compose.ymlindex 18898f38c..49f300414 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -295,6 +295,7 @@ services:# Integration Fabric ingress: per-instance fairness, retries, retention, reconciler, workers.- INGRESS_INSTANCE_LIMIT=${INGRESS_INSTANCE_LIMIT:-}- INGRESS_INSTANCE_TTL=${INGRESS_INSTANCE_TTL:-}+ - INGRESS_IP_LIMIT=${INGRESS_IP_LIMIT:-}- INGRESS_MAX_ATTEMPTS=${INGRESS_MAX_ATTEMPTS:-}- INGRESS_RETRY_DELAY_MS=${INGRESS_RETRY_DELAY_MS:-}- INGRESS_DEDUP_RETENTION_DAYS=${INGRESS_DEDUP_RETENTION_DAYS:-}diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 699d8e2f6..1e0fffc38 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -276,7 +276,12 @@ Exceeding a window returns `429 Too Many Requests`. Because the windows are **na- On success, each response carries one header triple per window: `X-RateLimit-Limit-short` / `-Remaining-short` / `-Reset-short`, plus the `-medium` and `-long` equivalents.- On `429`, the exceeded window sets `Retry-After-short`, `Retry-After-medium`, or `Retry-After-long` (seconds until the block expires) — read whichever is present rather than a plain `Retry-After`.-The ingress route (`ALL /api/ingress/:pluginId/:instanceId/*path`) additionally evaluates a per-instance window named `instance` (env: `INGRESS_INSTANCE_LIMIT`, default 120, per `INGRESS_INSTANCE_TTL`, default 60000 ms), so its responses carry `X-RateLimit-*-instance` and, on saturation, `Retry-After-instance`.+The ingress route (`ALL /api/ingress/:pluginId/:instanceId/*path`) is exempt from the global per-IP tiers (their 100/min medium window sits below the per-instance limit, so a provider fanning every tenant's webhooks through one egress IP was shed before the per-instance bound could fire). It carries its own two windows instead, both on `INGRESS_INSTANCE_TTL` (default 60000 ms):++- `instance`, keyed on `(pluginId, instanceId)`, env `INGRESS_INSTANCE_LIMIT`, default 120. Sheds one noisy tenant without touching its neighbours.+- `ingress-ip`, keyed on the client (proxy-aware, see `TRUSTED_PROXIES`), env `INGRESS_IP_LIMIT`, default 1200. The `instance` key is built from path segments the caller supplies, so varying them mints a fresh bucket; this window is the bound an unauthenticated caller cannot walk around. It is sized 10x the per-instance default so it never binds first for legitimate traffic.++Responses therefore carry `X-RateLimit-*-instance` and `X-RateLimit-*-ingress-ip`, and on saturation the `Retry-After-*` of whichever window shed the request.The API exposes the rate-limit headers via CORS (`exposedHeaders`) so browser clients can read them. The simplest backpressure signal remains the `429` status itself, with the suffixed `Retry-After-*` as the retry delay.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 11030962b..640d5a784 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6543,7 +6543,7 @@ plugin processing. `200` means the `GET` verification-challenge echo, or a duplialready persisted (idempotent re-delivery). A route may shape the synchronous status/body/headersthe provider sees via its declarative `ack` config (doc 25); the plugin itself always runs async.-**Errors:** `401` signature verification failed (missing, stale, or wrong secret) · `403` `GET` verification challenge failed (`verifyToken` mismatch) · `404` unknown pluginId/instanceId, or no such claimed route · `413` body over the route's `maxBodyBytes` · `429` per-instance rate limit (`INGRESS_INSTANCE_LIMIT` per `INGRESS_INSTANCE_TTL`; the per-instance bound is this route's only rate limit - the global per-IP tiers skip it)+**Errors:** `401` signature verification failed (missing, stale, or wrong secret) · `403` `GET` verification challenge failed (`verifyToken` mismatch) · `404` unknown pluginId/instanceId, or no such claimed route · `413` body over the route's `maxBodyBytes` · `429` rate limit: the per-instance bucket (`INGRESS_INSTANCE_LIMIT`) or the per-client-IP bucket (`INGRESS_IP_LIMIT`), both per `INGRESS_INSTANCE_TTL`; the global per-IP tiers skip this route, so these two are its bounds, and `Retry-After-instance` / `Retry-After-ingress-ip` names the one that shed the request## 6.5 Real-time API (WebSocket)diff --git a/openapi.json b/openapi.jsonindex 63c412d3b..26534044f 100644--- a/openapi.json+++ b/openapi.json@@ -8672,7 +8672,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -8730,7 +8730,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -8788,7 +8788,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -8846,7 +8846,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -8904,7 +8904,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -8962,7 +8962,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [@@ -9020,7 +9020,7 @@"description": "Request body exceeds the route maxBodyBytes limit."},"429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."+ "description": "Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request."}},"tags": [diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 790b2bd29..8364223a7 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -162,6 +162,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['WEBHOOK_WORKER_CONCURRENCY','INGRESS_INSTANCE_LIMIT','INGRESS_INSTANCE_TTL',+ 'INGRESS_IP_LIMIT','INGRESS_MAX_ATTEMPTS','INGRESS_RETRY_DELAY_MS','INGRESS_DEDUP_RETENTION_DAYS',diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 1aba20862..d843f855b 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -243,6 +243,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {'WS_MAX_SOCKETS_PER_KEY','WEBHOOK_TIMEOUT','INGRESS_INSTANCE_LIMIT',+ 'INGRESS_IP_LIMIT','REQUEST_TIMEOUT_MS','HEADERS_TIMEOUT_MS','KEEPALIVE_TIMEOUT_MS',diff --git a/src/main.ts b/src/main.tsindex 66f35762d..80b5fa398 100644--- a/src/main.ts+++ b/src/main.ts@@ -326,10 +326,14 @@ async function bootstrap() {'X-RateLimit-Limit-instance','X-RateLimit-Remaining-instance','X-RateLimit-Reset-instance',+ 'X-RateLimit-Limit-ingress-ip',+ 'X-RateLimit-Remaining-ingress-ip',+ 'X-RateLimit-Reset-ingress-ip','Retry-After-short','Retry-After-medium','Retry-After-long','Retry-After-instance',+ 'Retry-After-ingress-ip',],maxAge: 86400, // 24 hours});diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.tsindex 767bb1042..dc1707ff2 100644--- a/src/modules/integration/ingress.controller.ts+++ b/src/modules/integration/ingress.controller.ts@@ -25,15 +25,17 @@ export class IngressController {// Express 5 (path-to-regexp v8) has no bare `*` — Nest's route converter rewrites it to the named// wildcard `*path`, so the trailing segments land in req.params.path (an array), not req.params[0].//- // InstanceThrottlerGuard is the route's ONLY rate bound: the global per-IP guard skips this+ // InstanceThrottlerGuard carries this route's rate bounds: the global per-IP guard skips this// controller (@SkipThrottle above) because its medium tier (100/min) sits below this guard's// per-instance default (120/min), which 429'd every tenant of a shared-egress-IP provider at// the IP tier before the instance bound ever fired. This guard ignores the bare @SkipThrottle- // (see its shouldSkip) and keys on (pluginId, instanceId), so a noisy tenant sheds alone.- // Its limit/ttl (INGRESS_INSTANCE_LIMIT / INGRESS_INSTANCE_TTL) are read directly by the guard- // itself, NOT via @Throttle: @Throttle metadata is reflected on the route and read by every- // ThrottlerGuard subclass that walks a tier of that name. See InstanceThrottlerGuard's- // onModuleInit for how it keeps its tier fully independent.+ // (see its shouldSkip) and enforces TWO buckets: one keyed on (pluginId, instanceId), so a noisy+ // tenant sheds alone, and one keyed on the client IP, because the first key comes from the path+ // the caller supplies and would otherwise leave this @Public route with no bound it cannot walk+ // around. Their limits/ttl (INGRESS_INSTANCE_LIMIT / INGRESS_INSTANCE_TTL / INGRESS_IP_LIMIT) are+ // read directly by the guard itself, NOT via @Throttle: @Throttle metadata is reflected on the+ // route and read by every ThrottlerGuard subclass that walks a tier of that name. See+ // InstanceThrottlerGuard's onModuleInit for how it keeps its tiers fully independent.@UseGuards(InstanceThrottlerGuard)@All(':pluginId/:instanceId/*path')// The wildcard segment is part of the published path template, so it needs a parameter of its own —@@ -57,7 +59,11 @@ export class IngressController {@ApiResponse({ status: 403, description: 'GET verification challenge failed (verifyToken mismatch).' })@ApiResponse({ status: 404, description: 'Unknown pluginId/instanceId, or no route claimed by the plugin.' })@ApiResponse({ status: 413, description: 'Request body exceeds the route maxBodyBytes limit.' })- @ApiResponse({ status: 429, description: 'Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT).' })+ @ApiResponse({+ status: 429,+ description:+ 'Rate limit exceeded: the per-instance bucket (INGRESS_INSTANCE_LIMIT) or the per-client-IP bucket (INGRESS_IP_LIMIT). The `Retry-After-instance` / `Retry-After-ingress-ip` header names which one shed the request.',+ })async receive(@Param('pluginId') pluginId: string,@Param('instanceId') instanceId: string,diff --git a/src/modules/integration/instance-throttler.guard.spec.ts b/src/modules/integration/instance-throttler.guard.spec.tsindex b897233e5..e9e83a896 100644--- a/src/modules/integration/instance-throttler.guard.spec.ts+++ b/src/modules/integration/instance-throttler.guard.spec.ts@@ -27,7 +27,7 @@ describe('InstanceThrottlerGuard', () => {// A blank compose `${KEY:-}` forward must never become a limit of 0: the throttler would then// reject the first hit on every instance, silently 429ing all inbound webhooks.describe('tier resolution from the environment', () => {- const KEYS = ['INGRESS_INSTANCE_LIMIT', 'INGRESS_INSTANCE_TTL'] as const;+ const KEYS = ['INGRESS_INSTANCE_LIMIT', 'INGRESS_INSTANCE_TTL', 'INGRESS_IP_LIMIT'] as const;const saved: Array<[string, string | undefined]> = [];beforeEach(() => {saved.length = 0;@@ -40,9 +40,11 @@ describe('InstanceThrottlerGuard', () => {}});- const resolveTiers = async (): Promise<Array<{ limit: number; ttl: number }>> => {+ type Tier = { name: string; limit: number; ttl: number; getTracker?: (req: unknown) => Promise<string> };++ const resolveTiers = async (): Promise<Tier[]> => {const guard = Object.create(InstanceThrottlerGuard.prototype) as InstanceThrottlerGuard & {- throttlers: Array<{ limit: number; ttl: number }>;+ throttlers: Tier[];onModuleInit(): Promise<void>;};// Skip ThrottlerGuard's own onModuleInit (needs the injected storage/options).@@ -51,16 +53,50 @@ describe('InstanceThrottlerGuard', () => {return guard.throttlers;};+ const sizes = (tiers: Tier[]): Array<{ name: string; limit: number; ttl: number }> =>+ tiers.map(({ name, limit, ttl }) => ({ name, limit, ttl }));+it.each(['', ' '])('treats a blank value (%p) as unset instead of a limit of 0', async blank => {process.env.INGRESS_INSTANCE_LIMIT = blank;process.env.INGRESS_INSTANCE_TTL = blank;- expect(await resolveTiers()).toEqual([{ name: 'instance', limit: 120, ttl: 60000 }]);+ process.env.INGRESS_IP_LIMIT = blank;+ expect(sizes(await resolveTiers())).toEqual([+ { name: 'instance', limit: 120, ttl: 60000 },+ { name: 'ingress-ip', limit: 1200, ttl: 60000 },+ ]);});it('honors real values', async () => {process.env.INGRESS_INSTANCE_LIMIT = '5';process.env.INGRESS_INSTANCE_TTL = '1000';- expect(await resolveTiers()).toEqual([{ name: 'instance', limit: 5, ttl: 1000 }]);+ process.env.INGRESS_IP_LIMIT = '9';+ expect(sizes(await resolveTiers())).toEqual([+ { name: 'instance', limit: 5, ttl: 1000 },+ { name: 'ingress-ip', limit: 9, ttl: 1000 },+ ]);+ });++ /**+ * The point of the second tier: the per-instance bucket is keyed on caller-supplied path+ * segments, so varying them mints a fresh bucket per request. The IP tier must stay keyed on the+ * client even when those params ARE present, or the route has no bound an unauthenticated caller+ * cannot walk around.+ */+ it('keys the ip tier on the client even when instance params are present', async () => {+ const tiers = await resolveTiers();+ const ipTier = tiers.find(t => t.name === 'ingress-ip');+ expect(ipTier?.getTracker).toBeDefined();+ const req = { params: { pluginId: 'chatwoot', instanceId: 'acct1' }, ip: '203.0.113.9' };+ const tracked = await ipTier!.getTracker!(req);+ expect(tracked).toContain('203.0.113.9');+ expect(tracked).not.toContain('acct1');+ });++ it('leaves the instance tier keyed on the instance', async () => {+ const tiers = await resolveTiers();+ const instanceTier = tiers.find(t => t.name === 'instance');+ // No per-tier override: it inherits the class getTracker, proven by the first tests above.+ expect(instanceTier?.getTracker).toBeUndefined();});});});diff --git a/src/modules/integration/instance-throttler.guard.ts b/src/modules/integration/instance-throttler.guard.tsindex bc9806026..2dccc1abb 100644--- a/src/modules/integration/instance-throttler.guard.ts+++ b/src/modules/integration/instance-throttler.guard.ts@@ -18,8 +18,12 @@ import { resolveNonNegativeIntEnv } from '../../config/configuration';* `ThrottlerModule.forRootAsync` config. Overriding one of those tiers here would silently retarget the* global guard's tolerance for this route too (proven by an earlier version of this guard's e2e test:* a second, unrelated instance got 429'd purely for sharing the test client's IP with a throttled one).- * Instead, `onModuleInit` below replaces `this.throttlers` with a single self-contained tier that only- * this guard instance evaluates, so its limit is fully independent of the global guard's tiers.+ * Instead, `onModuleInit` below replaces `this.throttlers` with its own self-contained tiers that only+ * this guard instance evaluates, so their limits are fully independent of the global guard's tiers.+ *+ * It carries TWO tiers on the same window: `instance`, keyed on the route params, and `ingress-ip`,+ * keyed on the client. The instance key is caller-supplied, so the ip tier is the only bound a caller+ * cannot walk around by varying the path. See `onModuleInit` for the sizing.*/@Injectable()export class InstanceThrottlerGuard extends ProxyAwareThrottlerGuard {@@ -30,22 +34,47 @@ export class InstanceThrottlerGuard extends ProxyAwareThrottlerGuard {// webhook. Boot validation cannot catch it either (env.validation treats a blank value as// unset). resolveNonNegativeIntEnv treats blank as unset and only accepts plain decimals; an// explicit 0 is still rejected at boot by the positive-int check on INGRESS_INSTANCE_LIMIT.+ const ttl = resolveNonNegativeIntEnv(process.env.INGRESS_INSTANCE_TTL, 60000);this.throttlers = [{name: 'instance',limit: resolveNonNegativeIntEnv(process.env.INGRESS_INSTANCE_LIMIT, 120),- ttl: resolveNonNegativeIntEnv(process.env.INGRESS_INSTANCE_TTL, 60000),+ ttl,+ },+ {+ // Second bucket, same window, keyed on the CLIENT rather than the route params. The instance+ // bucket alone cannot bound this route: its key comes from `:pluginId/:instanceId`, which the+ // caller supplies, so varying them mints a fresh bucket per request. An unauthenticated+ // caller (the route is `@Public`) therefore walks around the limit entirely, and grows the+ // throttler's key space while doing it. Sized well ABOVE the per-instance limit so it never+ // becomes the binding constraint for a legitimate provider fanning many tenants through one+ // egress IP (the case the instance bucket exists for): 10x the instance default. Raise it+ // with `INGRESS_IP_LIMIT` when one IP legitimately drives more than that.+ name: 'ingress-ip',+ limit: resolveNonNegativeIntEnv(process.env.INGRESS_IP_LIMIT, 1200),+ ttl,+ getTracker: req => this.trackClientIp(req),},];}+ /**+ * The inherited proxy-aware, IP-keyed tracker, reachable from the tier list above (an arrow+ * function there cannot say `super`). `getTracker` below is overridden for the instance tier, so+ * the ip tier has to reach past that override deliberately.+ */+ private trackClientIp(req: Record<string, unknown>): Promise<string> {+ return super.getTracker(req);+ }+/*** This guard does NOT honour a bare `@SkipThrottle()`. The ingress controller carries one so the* GLOBAL per-IP guard skips the route: its medium tier (default 100/min) sits BELOW this guard's* per-instance default (120/min), so a provider delivering every tenant's webhooks from one* shared egress IP - the exact scenario this guard exists for - was 429'd at the IP tier before- * the instance bound ever fired, and sustained traffic hit the 1000/h long tier at ~16/min. The- * instance fairness bound is the better-keyed limit for this route and stays unconditional.+ * the instance bound ever fired, and sustained traffic hit the 1000/h long tier at ~16/min. This+ * guard carries the route's own better-keyed limits instead, and both of its tiers stay+ * unconditional: skipping them would leave a `@Public` route with no rate bound at all.*/protected shouldSkip(): Promise<boolean> {return Promise.resolve(false);diff --git a/test/ingress-ip-throttle.e2e-spec.ts b/test/ingress-ip-throttle.e2e-spec.tsnew file mode 100644index 000000000..7b522757e--- /dev/null+++ b/test/ingress-ip-throttle.e2e-spec.ts@@ -0,0 +1,67 @@+// archiver v8 is ESM-only and is pulled in transitively via the @Global StorageModule when+// AppModule boots; stub it so ts-jest (CommonJS) can load the module graph.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++// Set BEFORE AppModule is imported: InstanceThrottlerGuard reads these in onModuleInit (once, at+// boot), not per request. A low ip limit with the per-instance limit left at its default isolates+// the tier under test: the instance bucket can never bind here, because every request below uses a+// different (pluginId, instanceId) pair and therefore its own instance bucket.+process.env.INGRESS_IP_LIMIT = '4';+process.env.INGRESS_INSTANCE_LIMIT = '120';+process.env.INGRESS_INSTANCE_TTL = '60000';++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';++/**+ * The ingress route is `@Public` and carries `@SkipThrottle()` so the global per-IP tiers leave it+ * alone (their 100/min sits below the per-instance 120/min and would 429 a shared-egress provider+ * before the instance bound ever fired). That left the per-instance bucket as the only limiter, and+ * its key is built from the caller-supplied `:pluginId/:instanceId` path segments, so walking those+ * segments minted a fresh bucket per request: an unauthenticated client had no effective bound at+ * all. This proves the client-keyed tier now binds regardless of the path.+ *+ * The pairs below name no registered instance, so each request 404s at the handler. That is the+ * point: the guard runs BEFORE the handler, so a 404 still consumes budget, and an unknown-instance+ * flood is exactly the shape that had no limit.+ */+describe('Ingress per-IP rate bound (e2e)', () => {+ let app: INestApplication<App>;++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();+ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ const sendTo = (n: number) =>+ request(app.getHttpServer()).post(`/api/ingress/plugin-${n}/instance-${n}/hook`).send({});++ it('sheds a flood that varies the instance path segments, from one client', async () => {+ // INGRESS_IP_LIMIT=4: four distinct paths pass the guard (and 404 at the handler), the fifth is+ // shed. Without the client-keyed tier every one of these answers 404 and the flood is unbounded.+ for (let n = 0; n < 4; n++) {+ const res = await sendTo(n);+ expect(res.status).toBe(404);+ }++ const shed = await sendTo(99);+ expect(shed.status).toBe(429);+ // Names the tier that shed it, so an operator can tell this from the per-instance bound.+ expect(shed.headers['retry-after-ingress-ip']).toBeDefined();+ expect(shed.body).toMatchObject({ statusCode: 429 });+ });+});