Skip to content

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

TypeScript

fix(gfs): right-size external edge rate backstop

Alfredo Lopez85ebb7d35069
diff --git a/deploy/base/profiles/configmaps.yaml b/deploy/base/profiles/configmaps.yaml
index e0f872719..17ff947e9 100644
--- a/deploy/base/profiles/configmaps.yaml
+++ b/deploy/base/profiles/configmaps.yaml
@@ -5,6 +5,11 @@ metadata:
namespace: profiles
data:
EXTERNAL_REST_API_JSON_BODY_LIMIT: 150mb
+ # Coarse edge backstop capacity for GFS traffic behind one trusted proxy.
+ # Authoritative per-session/actor budgets remain in control-api.
+ EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN: '1800'
+ EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN: '1200'
+ EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN: '600'
---
apiVersion: v1
kind: ConfigMap
diff --git a/deploy/base/profiles/external-rest-api.yaml b/deploy/base/profiles/external-rest-api.yaml
index 06108c347..f61eb1fed 100644
--- a/deploy/base/profiles/external-rest-api.yaml
+++ b/deploy/base/profiles/external-rest-api.yaml
@@ -39,6 +39,21 @@ spec:
configMapKeyRef:
key: EXTERNAL_REST_API_JSON_BODY_LIMIT
name: external-rest-api-config
+ - name: EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN
+ valueFrom:
+ configMapKeyRef:
+ key: EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN
+ name: external-rest-api-config
+ - name: EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN
+ valueFrom:
+ configMapKeyRef:
+ key: EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN
+ name: external-rest-api-config
+ - name: EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN
+ valueFrom:
+ configMapKeyRef:
+ key: EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN
+ name: external-rest-api-config
- name: EXTERNAL_REST_API_CORS_ORIGIN
value: 'http://localhost:3001'
- name: EXTERNAL_REST_API_GOOGLE_CLIENT_ID
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 43d0000db..40479232b 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
@@ -222,7 +222,8 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
test('@gfs-operator/operator-root-crud root create/upload and nested CRUD use visible Desktop actions', async ({
operatorJourney,
}, testInfo) => {
- const page = operatorJourney.operatorPage!
+ const page = await operatorJourney.launchOperatorDesktop()
+ await operatorJourney.openFiles(page)
const rootId = operatorJourney.rootResourceId!
expect(operatorJourney.operatorSubjectGrantCount()).toBe(0)
await expect(page.getByTestId('gfs-view-operator')).toBeVisible()
@@ -422,7 +423,8 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
test('@gfs-operator/grant-share-lifecycle visible Desktop grant/share create, list, revoke removes recipient access', async ({
operatorJourney,
}, testInfo) => {
- const page = operatorJourney.operatorPage!
+ const page = await operatorJourney.launchOperatorDesktop()
+ await operatorJourney.openFiles(page)
const grantFolder = operatorJourney.resources.get('grantFolder')!
const shareFolder = operatorJourney.resources.get('shareFolder')!
const auditFloor = operatorJourney.auditFloor()
@@ -511,8 +513,10 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
test('@gfs-operator/live-control-ui-unlink visible Control UI revoke immediately denies same Electron session', async ({
operatorJourney,
}) => {
- const controlPage = operatorJourney.controlPage!
- const page = operatorJourney.operatorPage!
+ const controlPage = await operatorJourney.loginControlUi()
+ await operatorJourney.openControlAdmins()
+ const page = await operatorJourney.launchOperatorDesktop()
+ await operatorJourney.openFiles(page)
const link = operatorJourney.operatorLink!
await expect(controlPage).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/)
const revoke = controlPage.getByRole('button', {
@@ -772,7 +776,8 @@ test.describe.serial('GFS Desktop linked-operator parity', () => {
operatorJourney,
}) => {
const link = operatorJourney.operatorLink!
- const controlPage = operatorJourney.controlPage!
+ const controlPage = await operatorJourney.loginControlUi()
+ await operatorJourney.openControlAdmins()
await expect(controlPage).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/)
await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(
'Revoked'
diff --git a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
index 27ec85e3c..574c73edb 100644
--- a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
+++ b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts
@@ -297,6 +297,7 @@ export function evaluateGfsOperatorScenarioResults(
}
export function writeJsonAtomically(filePath: string, value: unknown): void {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 })
const temporaryPath = `${filePath}.${process.pid}.tmp`
try {
fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
diff --git a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
index cd7678136..7ab285398 100644
--- a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts
@@ -270,6 +270,8 @@ export class GfsDesktopOperatorJourney {
operatorContext: BrowserContext | null = null
operatorUserDataDir: string | null = null
operatorVideoDir: string | null = null
+ private operatorSessionSequence = 0
+ private readonly operatorUserDataDirs = new Set<string>()
operatorLink: OperatorLinkRow | null = null
ordinaryUserId: string | null = null
ordinaryTeamId: string | null = null
@@ -314,6 +316,12 @@ export class GfsDesktopOperatorJourney {
}
}
}
+ // Independent journeys must not inherit an authenticated Electron or
+ // Control UI session. Keep the same Electron process only inside the
+ // revoke/reactivate journey itself, which intentionally proves live
+ // denial and recovery for one session.
+ await this.closeOperatorDesktop()
+ await this.closeControlUi()
}
async finish(): Promise<void> {
@@ -334,10 +342,8 @@ export class GfsDesktopOperatorJourney {
cleanupErrors.push(error)
}
}
- for (const app of [this.operatorApp]) {
- await app?.close().catch(error => cleanupErrors.push(error))
- }
- await this.controlContext?.close().catch(error => cleanupErrors.push(error))
+ await this.closeOperatorDesktop().catch(error => cleanupErrors.push(error))
+ await this.closeControlUi().catch(error => cleanupErrors.push(error))
if (this.ordinaryUserId) {
try {
runControlPostgresSql(`
@@ -350,9 +356,9 @@ export class GfsDesktopOperatorJourney {
cleanupErrors.push(error)
}
}
- if (this.operatorUserDataDir) {
+ for (const userDataDir of this.operatorUserDataDirs) {
try {
- const resolved = path.resolve(this.operatorUserDataDir)
+ const resolved = path.resolve(userDataDir)
const allowedRoot = path.resolve(this.workerInfo.project.outputDir)
if (!resolved.startsWith(`${allowedRoot}${path.sep}`)) {
throw new Error(`refusing to remove user data outside ${allowedRoot}`)
@@ -742,6 +748,11 @@ export class GfsDesktopOperatorJourney {
}
async loginControlUi(): Promise<Page> {
+ // A fresh browser context per journey prevents the Control UI session
+ // cookie from becoming shared fixture state across the serial scenarios.
+ await this.closeControlUi()
+ this.controlContext = await this.browser.newContext({ baseURL: this.controlUiUrl })
+ this.controlPage = await this.controlContext.newPage()
const page = this.requiredControlPage()
await page.goto('/')
await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })
@@ -768,8 +779,11 @@ export class GfsDesktopOperatorJourney {
async launchOperatorDesktop(): Promise<Page> {
if (this.operatorApp) throw new Error('operator Electron process already launched')
const outputRoot = this.workerInfo.project.outputDir
- this.operatorUserDataDir = path.join(outputRoot, `gfs-operator-user-data-${this.runTag}`)
- this.operatorVideoDir = path.join(outputRoot, `gfs-operator-video-${this.runTag}`)
+ this.operatorSessionSequence += 1
+ const sessionTag = `${this.runTag}-${this.operatorSessionSequence}`
+ this.operatorUserDataDir = path.join(outputRoot, `gfs-operator-user-data-${sessionTag}`)
+ this.operatorVideoDir = path.join(outputRoot, `gfs-operator-video-${sessionTag}`)
+ this.operatorUserDataDirs.add(this.operatorUserDataDir)
fs.mkdirSync(this.operatorUserDataDir, { recursive: true })
fs.mkdirSync(this.operatorVideoDir, { recursive: true })
this.operatorApp = await electron.launch({
@@ -792,6 +806,23 @@ export class GfsDesktopOperatorJourney {
return this.operatorPage
}
+ async closeOperatorDesktop(): Promise<void> {
+ const app = this.operatorApp
+ const page = this.operatorPage
+ this.operatorApp = null
+ this.operatorPage = null
+ this.operatorContext = null
+ if (page) this.liveDesktopPages.delete(page)
+ await app?.close()
+ }
+
+ async closeControlUi(): Promise<void> {
+ const context = this.controlContext
+ this.controlContext = null
+ this.controlPage = null
+ await context?.close()
+ }
+
async launchOrdinaryDesktop(testInfo: TestInfo): Promise<{
app: ElectronApplication
page: Page
diff --git a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
index f808c4c38..311e68223 100644
--- a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
+++ b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts
@@ -12,6 +12,7 @@ import {
requireGfsOperatorRunId,
reserveGfsOperatorEvidenceRun,
scenarioIdFromTitle,
+ writeJsonAtomically,
} from './e2e-playwright/gfsDesktopOperatorParityContract'
const evidenceRoots: string[] = []
@@ -94,6 +95,16 @@ describe('GFS Desktop operator Playwright gate', () => {
})
})
+ it('creates the evidence directory before an atomic reporter write', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gfs-operator-write-'))
+ evidenceRoots.push(root)
+ const output = path.join(root, 'nested', 'summary.json')
+
+ writeJsonAtomically(output, { ok: true })
+
+ expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toEqual({ ok: true })
+ })
+
it('recognizes only one exact required scenario prefix', () => {
expect(scenarioIdFromTitle('@gfs-operator/setup-linked-operator visible login')).toBe(
'@gfs-operator/setup-linked-operator'
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 386e7dfda..a4226df63 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.66",
+ "version": "0.1.67",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.66",
+ "version": "0.1.67",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index cb06400d7..109e55862 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.66",
+ "version": "0.1.67",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/config.ts b/external-rest-api/src/config.ts
index 5ca49225b..ea6878622 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -14,6 +14,9 @@ type Config = {
desktopRpcProxyBaseUrl: string
desktopAppName: string
desktopReleaseBaseUrl: string
+ externalGfsEdgeAggregateRlPerMin: number
+ externalGfsEdgeAuthenticatedIpRlPerMin: number
+ externalGfsEdgeTokenIpRlPerMin: number
}
function required(name: string): string {
@@ -42,6 +45,14 @@ function positiveIntegerFromEnv(name: string, defaultValue: number): number {
return value
}
+function boundedPositiveIntegerFromEnv(name: string, defaultValue: number, max: number): number {
+ const value = positiveIntegerFromEnv(name, defaultValue)
+ if (value > max) {
+ throw new Error(`${name} must be <= ${max}`)
+ }
+ return value
+}
+
/**
* Parse a CORS-origin env value. A bare `*` stays the literal `'*'` (handled
* specially in app.ts). Anything else is split on commas into a trimmed,
@@ -126,6 +137,24 @@ export const config: Config = {
process.env.EXTERNAL_REST_API_DESKTOP_RELEASE_BASE_URL ||
'https://github.com/evenfire-ai/evenfire/releases'
).replace(/\/+$/, ''),
+ // Coarse edge backstop for GFS traffic behind a shared trusted proxy. These
+ // are deliberately independent values: the Control API's distributed
+ // 10/min token and 30/min session/actor budgets remain authoritative.
+ externalGfsEdgeAggregateRlPerMin: boundedPositiveIntegerFromEnv(
+ 'EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN',
+ 1_800,
+ 1_000_000
+ ),
+ externalGfsEdgeAuthenticatedIpRlPerMin: boundedPositiveIntegerFromEnv(
+ 'EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN',
+ 1_200,
+ 1_000_000
+ ),
+ externalGfsEdgeTokenIpRlPerMin: boundedPositiveIntegerFromEnv(
+ 'EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN',
+ 600,
+ 1_000_000
+ ),
}
if (process.env.NODE_ENV === 'production' && config.corsOrigin === '*') {
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index 322348c7a..7bddf5eac 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -6,6 +6,7 @@ import { randomUUID } from 'node:crypto'
import { isIP } from 'node:net'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
+import { config } from '../config.js'
import { ControlApiError, controlApiRequest, controlApiStreamRequest } from '../controlApiClient.js'
import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'
@@ -33,9 +34,36 @@ 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
+const EXTERNAL_GFS_EDGE_WINDOW_MS = 60_000
+
+export type ExternalGfsEdgeLimits = {
+ aggregatePerMin: number
+ authenticatedIpPerMin: number
+ tokenIpPerMin: number
+}
+
+/**
+ * Derive the coarse edge backstop from the number of users expected to share
+ * one trusted proxy address. The values deliberately scale the edge only:
+ * Control API PG buckets still enforce the 10/min token and 30/min
+ * session/actor product budgets across replicas.
+ */
+export function deriveExternalGfsEdgeLimits(expectedUsers: number): ExternalGfsEdgeLimits {
+ if (!Number.isSafeInteger(expectedUsers) || expectedUsers < 1 || expectedUsers > 1_000) {
+ throw new Error('external GFS expected users must be an integer between 1 and 1000')
+ }
+ return {
+ aggregatePerMin: expectedUsers * 120,
+ authenticatedIpPerMin: expectedUsers * 60,
+ tokenIpPerMin: expectedUsers * 12,
+ }
+}
+
+const DEFAULT_EXTERNAL_GFS_EDGE_LIMITS: ExternalGfsEdgeLimits = {
+ aggregatePerMin: config.externalGfsEdgeAggregateRlPerMin,
+ authenticatedIpPerMin: config.externalGfsEdgeAuthenticatedIpRlPerMin,
+ tokenIpPerMin: config.externalGfsEdgeTokenIpRlPerMin,
+}
type GfsAuthedRequest = AuthedRequest & { gfsRequestId?: string }
type GfsRequestOptions = {
@@ -98,25 +126,37 @@ function forwardControlApiError(error: unknown, res: Response, next: NextFunctio
next(error)
}
-export function createGfsRouter(): Router {
+export function createGfsRouter(options?: { edgeLimits?: ExternalGfsEdgeLimits }): Router {
const router = Router()
+ const edgeLimits = options?.edgeLimits ?? DEFAULT_EXTERNAL_GFS_EDGE_LIMITS
- // 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',
+ const edgeLimiter = (limit: number, bucket: string) =>
rateLimit({
- windowMs: 60_000,
- limit: EXTERNAL_GFS_INGRESS_LIMIT_PER_MIN,
- standardHeaders: false,
+ windowMs: EXTERNAL_GFS_EDGE_WINDOW_MS,
+ limit,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
- message: { error: 'Too Many Requests' },
- }),
- attachGfsRequestId,
- requireAuth
- )
+ identifier: `gfs-edge-${bucket}`,
+ handler: (_req, res) => {
+ res.status(429).json({
+ error: 'Too Many Requests',
+ rateLimitLayer: 'external-rest-edge',
+ rateLimitBucket: bucket,
+ })
+ },
+ })
+
+ // Keep direct, recognised edge guards at this service as well as the
+ // cross-replica Control API buckets. They run before JWT work and prevent a
+ // client from using the proxy hop to make auth or downstream requests
+ // unbounded. The aggregate and authenticated class buckets are deliberately
+ // sized for a shared NAT address; the token bucket remains tighter. The
+ // Control API owns the authoritative per-user/session/actor budgets.
+ router.use('/me/gfs', attachGfsRequestId)
+ router.use('/me/gfs', edgeLimiter(edgeLimits.aggregatePerMin, 'aggregate-ip'))
+ router.use('/me/gfs', edgeLimiter(edgeLimits.authenticatedIpPerMin, 'authenticated-ip'))
+ router.use('/me/gfs/token', edgeLimiter(edgeLimits.tokenIpPerMin, 'token-ip'))
+ router.use('/me/gfs', requireAuth)
router.post('/me/gfs/token', async (req: AuthedRequest, res, next) => {
try {
diff --git a/external-rest-api/test/config.cors.test.ts b/external-rest-api/test/config.cors.test.ts
index 924318a85..e13e7d500 100644
--- a/external-rest-api/test/config.cors.test.ts
+++ b/external-rest-api/test/config.cors.test.ts
@@ -26,4 +26,10 @@ describe('config', () => {
it('uses the configured profile session cookie TTL default', () => {
expect(config.profileSessionCookieTtlSeconds).toBe(60 * 60 * 12)
})
+
+ it('uses the approved independent GFS edge backstop defaults', () => {
+ expect(config.externalGfsEdgeAggregateRlPerMin).toBe(1_800)
+ expect(config.externalGfsEdgeAuthenticatedIpRlPerMin).toBe(1_200)
+ expect(config.externalGfsEdgeTokenIpRlPerMin).toBe(600)
+ })
})
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index c381e1f12..74e37c2e1 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -1,7 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { createGfsRouter } from '../src/routes/gfs.js'
+import {
+ type ExternalGfsEdgeLimits,
+ createGfsRouter,
+ deriveExternalGfsEdgeLimits,
+} from '../src/routes/gfs.js'
const { ControlApiError, clientMock } = vi.hoisted(() => {
class ControlApiError extends Error {
@@ -29,11 +33,12 @@ const authTokenMock = vi.hoisted(() => ({ verifyToken: vi.fn() }))
vi.mock('../src/authToken.js', () => authTokenMock)
const REQUEST_ID = '11111111-2222-4333-8444-555555555555'
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
-function buildApp() {
+function buildApp(edgeLimits?: ExternalGfsEdgeLimits) {
const app = express()
app.use(express.json())
- app.use(createGfsRouter())
+ app.use(createGfsRouter(edgeLimits ? { edgeLimits } : undefined))
return app
}
@@ -181,10 +186,27 @@ 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()
+ it('derives edge capacity for the approved 20- and 50-user NAT cases', () => {
+ expect(deriveExternalGfsEdgeLimits(20)).toEqual({
+ aggregatePerMin: 2_400,
+ authenticatedIpPerMin: 1_200,
+ tokenIpPerMin: 240,
+ })
+ expect(deriveExternalGfsEdgeLimits(50)).toEqual({
+ aggregatePerMin: 6_000,
+ authenticatedIpPerMin: 3_000,
+ tokenIpPerMin: 600,
+ })
+ })
+
+ it('enforces the aggregate edge backstop before auth and emits recovery headers', async () => {
+ const app = buildApp({
+ aggregatePerMin: 2,
+ authenticatedIpPerMin: 10,
+ tokenIpPerMin: 10,
+ })
- for (let attempt = 0; attempt < 30; attempt += 1) {
+ for (let attempt = 0; attempt < 2; attempt += 1) {
await request(app)
.get('/me/gfs/not-classified')
.set('authorization', 'Bearer sess-xyz')
@@ -196,11 +218,46 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
.set('authorization', 'Bearer sess-xyz')
expect(exhausted.status).toBe(429)
- expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(30)
+ expect(exhausted.headers['x-request-id']).toMatch(UUID_RE)
+ expect(exhausted.headers['retry-after']).toMatch(/^\d+$/)
+ expect(exhausted.headers['ratelimit']).toContain('limit=2')
+ expect(exhausted.body).toEqual({
+ error: 'Too Many Requests',
+ rateLimitLayer: 'external-rest-edge',
+ rateLimitBucket: 'aggregate-ip',
+ })
+ expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(2)
expect(clientMock.controlApiRequest).not.toHaveBeenCalled()
expect(clientMock.controlApiStreamRequest).not.toHaveBeenCalled()
})
+ it('keeps the token edge bucket separate from authenticated GFS traffic', async () => {
+ clientMock.controlApiRequest.mockResolvedValue({ token: 'gfs-tok', expiresInSeconds: 300 })
+ const app = buildApp({
+ aggregatePerMin: 10,
+ authenticatedIpPerMin: 10,
+ tokenIpPerMin: 2,
+ })
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ await request(app)
+ .post('/me/gfs/token')
+ .set('authorization', 'Bearer sess-xyz')
+ .send({})
+ .expect(200)
+ }
+ const exhausted = await request(app)
+ .post('/me/gfs/token')
+ .set('authorization', 'Bearer sess-xyz')
+ .send({})
+
+ expect(exhausted.status).toBe(429)
+ expect(exhausted.headers['retry-after']).toMatch(/^\d+$/)
+ expect(exhausted.headers['ratelimit']).toContain('limit=2')
+ expect(exhausted.body.rateLimitBucket).toBe('token-ip')
+ expect(clientMock.controlApiRequest).toHaveBeenCalledTimes(2)
+ })
+
it('propagates a control-api no-escalation 403 verbatim', async () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError('escalation', 403, { error: 'escalation_rejected' })