Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(gfs): make rate limits visible at route boundaries

Alfredo Lopezb4adad2189f7
diff --git a/control-api/src/middleware/externalGfsRateLimit.ts b/control-api/src/middleware/externalGfsRateLimit.ts
index 5745c7bec..841092b0d 100644
--- a/control-api/src/middleware/externalGfsRateLimit.ts
+++ b/control-api/src/middleware/externalGfsRateLimit.ts
@@ -116,7 +116,15 @@ function authenticatedSessionDigest(req: Request): string | null {
return token ? digest(token) : null
}
-function sourceIpDigest(req: Request): string {
+/**
+ * Source address forwarded by the authenticated external-rest-api boundary.
+ *
+ * The first XFF element is accepted only when it is an IP literal. This is
+ * intentionally exported for the recognisable edge limiter as well as the
+ * durable Postgres buckets below: the two guards must meter the same trusted
+ * client identity, never a caller-selected header fragment.
+ */
+export function externalGfsSourceIp(req: Request): string {
// The app-level /external gate accepts only the authenticated
// external-rest-api service. That service overwrites X-Forwarded-For with
// its proxy-attested client address; profile-control-funnel then appends its
@@ -129,7 +137,11 @@ function sourceIpDigest(req: Request): string {
forwardedIp && isIP(forwardedIp) !== 0
? forwardedIp
: req.ip || req.socket.remoteAddress || '__unknown_peer__'
- return digest(ip)
+ return ip
+}
+
+function sourceIpDigest(req: Request): string {
+ return digest(externalGfsSourceIp(req))
}
function applyRateLimitHeaders(
diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.ts
index 71709f62d..df8a85bb6 100644
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@ -1,5 +1,6 @@
import { type NextFunction, Router } from 'express'
-import { randomUUID } from 'node:crypto'
+import { ipKeyGenerator, rateLimit } from 'express-rate-limit'
+import { createHash, randomUUID } from 'node:crypto'
import {
GFS_DELETE_SCOPE,
GFS_READ_SCOPE,
@@ -27,6 +28,7 @@ import { asyncHandler } from '../../http/asyncHandler.js'
import {
externalGfsPreResolutionRateLimit,
externalGfsResolvedOperationRateLimit,
+ externalGfsSourceIp,
} from '../../middleware/externalGfsRateLimit.js'
import {
type ExternalAuthedRequest,
@@ -78,6 +80,37 @@ function attachExternalGfsRequestId(
next()
}
+function externalGfsRateKey(value: string): string {
+ return createHash('sha256').update(value).digest('hex')
+}
+
+/**
+ * These key factories back the recognised in-process edge guards. The durable
+ * Postgres limiter remains the source of cross-replica enforcement and emits
+ * the public quota headers. These guards are deliberately direct
+ * express-rate-limit middleware so CodeQL can prove every external GFS route
+ * is bounded before auth, authority resolution, or route-specific work.
+ */
+function externalGfsIngressRateKey(req: import('express').Request): string {
+ return `external-gfs:ingress:${externalGfsRateKey(ipKeyGenerator(externalGfsSourceIp(req)))}`
+}
+
+function externalGfsTokenRateKey(req: import('express').Request): string {
+ const userId = (req as ExternalGfsRequest).externalAuth?.userId ?? '__missing_user__'
+ return `external-gfs:token:user:${externalGfsRateKey(userId)}`
+}
+
+function externalGfsActorRateKey(operationClass: string) {
+ return (req: import('express').Request): string => {
+ const externalReq = req as ExternalGfsRequest
+ const authority = externalReq.gfsAuthority
+ const actor = authority
+ ? `${authority.kind}:${authority.tokenSubject}`
+ : `session:${externalReq.externalAuth?.userId ?? '__missing_user__'}`
+ return `external-gfs:${operationClass}:actor:${externalGfsRateKey(actor)}`
+ }
+}
+
function authorityOf(req: ExternalGfsRequest): ExternalGfsAuthority {
const authority = req.gfsAuthority
if (!authority) throw new GfsGrantError(401, 'unauthenticated')
@@ -219,6 +252,74 @@ async function assertHostTargetsWithinCallerAgents(
export function createExternalGfsRouter(): Router {
const router = Router()
+ // The durable externalGfs* guards below are the authoritative distributed
+ // limiter. These direct express-rate-limit guards intentionally mirror the
+ // approved quotas at the routing boundary so static analysis can prove that
+ // every auth/authority/handler path is metered. They keep no response quota
+ // headers: the distributed guard owns the externally forwarded values.
+ const externalGfsIngressRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsIpRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsIngressRateKey,
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsTokenRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsTokenUserRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsTokenRateKey,
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsResourceRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsOperationRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsActorRateKey('resource'),
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsProxyReadRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsOperationRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsActorRateKey('proxy-read'),
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsMutationRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsOperationRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsActorRateKey('resource-mutation'),
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsGrantsRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsOperationRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsActorRateKey('grants'),
+ message: { error: 'Too Many Requests' },
+ })
+ const externalGfsSharesRouteRateLimit = rateLimit({
+ windowMs: 60_000,
+ limit: config.externalGfsOperationRlPerMin,
+ standardHeaders: false,
+ legacyHeaders: false,
+ keyGenerator: externalGfsActorRateKey('shares'),
+ message: { error: 'Too Many Requests' },
+ })
+
+ // The source-IP guard intentionally precedes authentication and authority
+ // lookup. The authenticated external-rest-api boundary overwrites XFF with
+ // its trust-proxy-derived client address; externalGfsSourceIp accepts only
+ // that valid first IP, so a raw caller cannot select a bucket.
+ router.use('/external/gfs', externalGfsIngressRateLimit)
+
// Every gfs user route is on the Session-JWT plane: the user session token
// (x-user-session-token, forwarded by external-rest-api) is required.
router.use('/external/gfs', requireValidExternalSessionToken)
@@ -256,6 +357,7 @@ export function createExternalGfsRouter(): Router {
// ── token mint (mirror /external/rpc/token, but a gfs token sub=users.id) ──
router.post(
'/external/gfs/token',
+ externalGfsTokenRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const claims = req.externalAuth!
const body = (req.body ?? {}) as { drive?: unknown; scopes?: unknown }
@@ -293,12 +395,14 @@ export function createExternalGfsRouter(): Router {
// (view-ACL = manage-ACL); handleGrantListForCaller enforces that.
router.get(
'/external/gfs/grants',
+ externalGfsGrantsRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleGrantListForCaller)
)
router.put(
'/external/gfs/grants',
+ externalGfsGrantsRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(assertHostTargetsWithinCallerAgents),
@@ -306,24 +410,28 @@ export function createExternalGfsRouter(): Router {
)
router.delete(
'/external/gfs/grants/:id',
+ externalGfsGrantsRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleGrantDelete)
)
router.post(
'/external/gfs/shares',
+ externalGfsSharesRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleShareWrite)
)
router.get(
'/external/gfs/shares',
+ externalGfsSharesRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleShareListForCaller)
)
router.delete(
'/external/gfs/shares/:id',
+ externalGfsSharesRouteRateLimit,
externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleShareDelete)
@@ -334,6 +442,7 @@ export function createExternalGfsRouter(): Router {
// EXISTING checkAccess (same allow() engine as assertMayGrant). Read-only.
router.get(
'/external/gfs/resources/:id/affordances',
+ externalGfsResourceRouteRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const caller = resolveCaller(req)
@@ -351,12 +460,14 @@ export function createExternalGfsRouter(): Router {
router.patch(
'/external/gfs/resources/:id',
+ externalGfsMutationRouteRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handlePatch)
)
router.post(
'/external/gfs/resources/:id/children',
+ externalGfsMutationRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const rid = String(req.params.id)
if (!UUID_RE.test(rid)) {
@@ -376,6 +487,7 @@ export function createExternalGfsRouter(): Router {
router.put(
'/external/gfs/resources/:id/content',
+ externalGfsMutationRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const rid = String(req.params.id)
if (!UUID_RE.test(rid)) {
@@ -395,6 +507,7 @@ export function createExternalGfsRouter(): Router {
router.delete(
'/external/gfs/resources/:id',
+ externalGfsMutationRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const rid = String(req.params.id)
if (!UUID_RE.test(rid)) {
@@ -414,6 +527,7 @@ export function createExternalGfsRouter(): Router {
router.get(
'/external/gfs/resources',
+ externalGfsResourceRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const drive = driveOf(req.query.drive)
const authority = authorityOf(req as ExternalGfsRequest)
@@ -548,6 +662,7 @@ export function createExternalGfsRouter(): Router {
// (deny-by-default), so a user only reads what it is granted. GET only. ──
router.get(
'/external/gfs/resolve',
+ externalGfsResourceRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const uri = typeof req.query.uri === 'string' ? req.query.uri : ''
if (!uri) {
@@ -569,6 +684,7 @@ export function createExternalGfsRouter(): Router {
router.get(
'/external/gfs/resources/:id/children',
+ externalGfsResourceRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const rid = String(req.params.id)
if (!UUID_RE.test(rid)) {
@@ -591,6 +707,7 @@ export function createExternalGfsRouter(): Router {
router.get(
'/external/gfs/proxy/:rid',
+ externalGfsProxyReadRouteRateLimit,
asyncHandler(async (req: ExternalAuthedRequest, res) => {
const rid = String(req.params.rid)
if (!UUID_RE.test(rid)) {
diff --git a/control-api/test/middleware.externalGfsRateLimit.test.ts b/control-api/test/middleware.externalGfsRateLimit.test.ts
index 8ac4d957c..28fa5e56e 100644
--- a/control-api/test/middleware.externalGfsRateLimit.test.ts
+++ b/control-api/test/middleware.externalGfsRateLimit.test.ts
@@ -6,6 +6,7 @@ import {
externalGfsOperationFor,
externalGfsPreResolutionRateLimit,
externalGfsResolvedOperationRateLimit,
+ externalGfsSourceIp,
} from '../src/middleware/externalGfsRateLimit.js'
const checkAndIncrement = vi.hoisted(() => vi.fn())
@@ -269,6 +270,17 @@ describe('external GFS rate boundary', () => {
)
})
+ it('uses only a valid first forwarded IP and rejects a spoofed first fragment', () => {
+ const requestWithSpoofedForwarding = {
+ header: (name: string) =>
+ name.toLowerCase() === 'x-forwarded-for' ? 'not-an-ip, 198.51.100.99' : undefined,
+ ip: '203.0.113.41',
+ socket: { remoteAddress: '10.42.0.18' },
+ } as unknown as import('express').Request
+
+ expect(externalGfsSourceIp(requestWithSpoofedForwarding)).toBe('203.0.113.41')
+ })
+
it('uses distinct session, source-IP, and effective-actor buckets for each operation class', async () => {
const { app } = buildApp()
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 508532079..b86f82a84 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -231,6 +231,48 @@ function dbReturning(
}
describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)', () => {
+ it('enforces the recognised ingress limit before session authentication or authority resolution', async () => {
+ auth()
+ const app = await buildApp()
+
+ for (let attempt = 0; attempt < 30; attempt += 1) {
+ const response = await request(app)
+ .post('/external/gfs/not-classified')
+ .set('x-user-session-token', 'sess')
+ expect(response.status).toBe(404)
+ }
+
+ const exhausted = await request(app)
+ .post('/external/gfs/not-classified')
+ .set('x-user-session-token', 'sess')
+
+ expect(exhausted.status).toBe(429)
+ expect(mockVerifyExternalSessionToken).toHaveBeenCalledTimes(30)
+ expect(mockResolveActiveLink).not.toHaveBeenCalled()
+ expect(mockQuery).not.toHaveBeenCalled()
+ })
+
+ it('enforces the recognised 10/min token route limit per authenticated user', async () => {
+ auth()
+ const app = await buildApp()
+
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'sess')
+ .send({})
+ .expect(200)
+ }
+
+ const exhausted = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'sess')
+ .send({})
+
+ expect(exhausted.status).toBe(429)
+ expect(mockSignGfsToken).toHaveBeenCalledTimes(10)
+ })
+
it('mints a gfs token for the user with the EXISTING signGfsToken (sub=users.id)', async () => {
auth()
const app = await buildApp()
diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts
index 84d7ace10..9d23a560d 100644
--- a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts
+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts
@@ -462,13 +462,13 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
await expect(resourceRow(ordinary.page, grantFolder)).toBeVisible()
await expect(resourceRow(ordinary.page, shareFolder)).toBeVisible()
- dialog = await openResourceManage(page, grantFolder)
+ await openResourceManage(page, grantFolder)
await page.getByTestId(`gfs-revoke-grant-${grant.id}`).click()
await expectToast(page, `Access revoked for ${operatorJourney.ordinaryName}`)
await expect.poll(() => operatorJourney.findGrant(grantFolder.resourceId)).toBeNull()
await closeManageDialog(page)
- dialog = await openResourceManage(page, shareFolder)
+ await openResourceManage(page, shareFolder)
await page.getByTestId(`gfs-revoke-share-${share.id}`).click()
await expectToast(page, `Shared access revoked for ${operatorJourney.ordinaryName}`)
await expect.poll(() => operatorJourney.findShare(shareFolder.resourceId)).toBeNull()
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 915335b92..386e7dfda 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
+ "express-rate-limit": "^8.5.1",
"google-auth-library": "^10.9.0",
"jsonwebtoken": "^9.0.3",
"pg": "^8.13.1"
@@ -1825,6 +1826,48 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/express-rate-limit": {
+ "version": "8.6.2",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.2.tgz",
+ "integrity": "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "ip-address": "^10.2.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": ">= 4.11"
+ }
+ },
+ "node_modules/express-rate-limit/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/express-rate-limit/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -2203,6 +2246,15 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
+ "node_modules/ip-address": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
+ "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 2351eba3c..cb06400d7 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -18,6 +18,7 @@
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
+ "express-rate-limit": "^8.5.1",
"google-auth-library": "^10.9.0",
"jsonwebtoken": "^9.0.3",
"pg": "^8.13.1"
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index c1f1fac27..322348c7a 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -1,6 +1,7 @@
import { Router } from 'express'
import type { NextFunction, Response } from 'express'
import type { Request } from 'express'
+import { rateLimit } from 'express-rate-limit'
import { randomUUID } from 'node:crypto'
import { isIP } from 'node:net'
import { Readable } from 'node:stream'
@@ -32,6 +33,9 @@ const CONTROL_API_ERROR_HEADERS = [
'x-request-id',
] as const
const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+// Approved GFS source-IP boundary; control-api adds the class-specific
+// per-session/IP/effective-actor 10/30 limits after this public edge.
+const EXTERNAL_GFS_INGRESS_LIMIT_PER_MIN = 30
type GfsAuthedRequest = AuthedRequest & { gfsRequestId?: string }
type GfsRequestOptions = {
@@ -97,7 +101,22 @@ function forwardControlApiError(error: unknown, res: Response, next: NextFunctio
export function createGfsRouter(): Router {
const router = Router()
- router.use('/me/gfs', attachGfsRequestId, requireAuth)
+ // Keep a direct, recognised edge guard at this service as well as the
+ // cross-replica control-api buckets. It runs before JWT work and prevents a
+ // client from using the proxy hop to make auth or downstream requests
+ // unbounded. Headers remain owned by control-api's durable limiter.
+ router.use(
+ '/me/gfs',
+ rateLimit({
+ windowMs: 60_000,
+ limit: EXTERNAL_GFS_INGRESS_LIMIT_PER_MIN,
+ standardHeaders: false,
+ legacyHeaders: false,
+ message: { error: 'Too Many Requests' },
+ }),
+ attachGfsRequestId,
+ requireAuth
+ )
router.post('/me/gfs/token', async (req: AuthedRequest, res, next) => {
try {
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 07213816b..c381e1f12 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -132,6 +132,30 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
})
})
+ it('overwrites a caller-spoofed XFF prefix with the trusted one-hop client address', async () => {
+ clientMock.controlApiRequest.mockResolvedValue({
+ ok: true,
+ data: { items: [], nextCursor: null },
+ })
+ const app = buildApp()
+ // createApp uses this same contract: only its immediately adjacent public
+ // proxy is trusted. A caller cannot choose the leftmost XFF value.
+ app.set('trust proxy', 1)
+
+ await request(app)
+ .get('/me/gfs/resources')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-request-id', REQUEST_ID)
+ .set('x-forwarded-for', '198.51.100.250, 203.0.113.41')
+ .expect(200)
+
+ const options = clientMock.controlApiRequest.mock.calls.at(-1)?.[2] as {
+ extraHeaders?: Record<string, string>
+ }
+ expect(options.extraHeaders?.['x-forwarded-for']).toBe('203.0.113.41')
+ expect(options.extraHeaders?.['x-forwarded-for']).not.toBe('198.51.100.250')
+ })
+
it('does not forward a caller-supplied XFF value when the hop is untrusted', async () => {
clientMock.controlApiRequest.mockResolvedValue({
ok: true,
@@ -157,6 +181,26 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(forwarded).not.toBe('203.0.113.99')
})
+ it('enforces the recognised ingress limit before auth or a control-api request', async () => {
+ const app = buildApp()
+
+ for (let attempt = 0; attempt < 30; attempt += 1) {
+ await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .expect(404)
+ }
+
+ const exhausted = await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+
+ expect(exhausted.status).toBe(429)
+ expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(30)
+ expect(clientMock.controlApiRequest).not.toHaveBeenCalled()
+ expect(clientMock.controlApiStreamRequest).not.toHaveBeenCalled()
+ })
+
it('propagates a control-api no-escalation 403 verbatim', async () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError('escalation', 403, { error: 'escalation_rejected' })