Skip to content

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

TypeScript

fix(gfs): preserve per-client edge rate-limit fairness

Alfredo Lopezaf26f793b9b4
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index c43c7c19e..deae760e7 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.74",
+ "version": "0.1.75",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.74",
+ "version": "0.1.75",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 5acf68823..2b5f2fb80 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.74",
+ "version": "0.1.75",
"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 ea6878622..d7fd08f7b 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -91,6 +91,47 @@ aH+oqnwDGbDcDLQ/wTuBtcn4brWTDgW1xA73HVBSImGFvvHCWBiQBiI1nvovUP0u
WQIDAQAB
-----END PUBLIC KEY-----`)
+const EXTERNAL_GFS_EDGE_AGGREGATE_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN'
+const EXTERNAL_GFS_EDGE_CLIENT_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN'
+const EXTERNAL_GFS_EDGE_TOKEN_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN'
+const EXTERNAL_GFS_EDGE_RATE_LIMIT_MAX = 1_000_000
+
+function parseExternalGfsEdgeRateLimits() {
+ const externalGfsEdgeAggregateRlPerMin = boundedPositiveIntegerFromEnv(
+ EXTERNAL_GFS_EDGE_AGGREGATE_ENV,
+ 1_800,
+ EXTERNAL_GFS_EDGE_RATE_LIMIT_MAX
+ )
+ const externalGfsEdgeAuthenticatedIpRlPerMin = boundedPositiveIntegerFromEnv(
+ EXTERNAL_GFS_EDGE_CLIENT_IP_ENV,
+ 1_200,
+ EXTERNAL_GFS_EDGE_RATE_LIMIT_MAX
+ )
+ const externalGfsEdgeTokenIpRlPerMin = boundedPositiveIntegerFromEnv(
+ EXTERNAL_GFS_EDGE_TOKEN_IP_ENV,
+ 600,
+ EXTERNAL_GFS_EDGE_RATE_LIMIT_MAX
+ )
+
+ if (
+ externalGfsEdgeTokenIpRlPerMin > externalGfsEdgeAuthenticatedIpRlPerMin ||
+ externalGfsEdgeAuthenticatedIpRlPerMin >= externalGfsEdgeAggregateRlPerMin
+ ) {
+ throw new Error(
+ `External REST GFS edge rate limits must satisfy ${EXTERNAL_GFS_EDGE_TOKEN_IP_ENV} <= ` +
+ `${EXTERNAL_GFS_EDGE_CLIENT_IP_ENV} < ${EXTERNAL_GFS_EDGE_AGGREGATE_ENV}`
+ )
+ }
+
+ return {
+ externalGfsEdgeAggregateRlPerMin,
+ externalGfsEdgeAuthenticatedIpRlPerMin,
+ externalGfsEdgeTokenIpRlPerMin,
+ }
+}
+
+const externalGfsEdgeRateLimits = parseExternalGfsEdgeRateLimits()
+
export const config: Config = {
port: Number(process.env.EXTERNAL_REST_API_PORT || 8091),
jsonBodyLimit: process.env.EXTERNAL_REST_API_JSON_BODY_LIMIT || '150mb',
@@ -137,24 +178,10 @@ 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
- ),
+ // Coherent GFS-only tiers: token IP <= client IP < process aggregate. The
+ // Control API's distributed 10/min token and 30/min session/actor budgets
+ // remain authoritative.
+ ...externalGfsEdgeRateLimits,
}
if (process.env.NODE_ENV === 'production' && config.corsOrigin === '*') {
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 2fb0956e3..76a00b2e0 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,7 +8,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.7.0',
- externalRestApiVersion: '0.1.74',
+ externalRestApiVersion: '0.1.75',
rpcProxyVersion: '0.1.64',
desktopVersion: '0.7.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index 79ed37cdc..d42b5b4e9 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -171,20 +171,22 @@ export function createGfsRouter(options?: { edgeLimits?: ExternalGfsEdgeLimits }
// 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.
+ // narrower buckets run first so their rejected requests do not consume
+ // broader capacity. The Control API owns the authoritative per-user/session/
+ // actor budgets.
router.use('/me/gfs', attachGfsRequestId)
+ router.use('/me/gfs/token', edgeLimiter(edgeLimits.tokenIpPerMin, 'token-ip'))
+ router.use('/me/gfs', edgeLimiter(edgeLimits.authenticatedIpPerMin, 'authenticated-ip'))
router.use(
'/me/gfs',
edgeLimiter(edgeLimits.aggregatePerMin, 'aggregate-ip', {
// This is intentionally a process-wide backstop, not another per-IP
- // bucket. The authenticated-IP limiter below owns client fairness;
+ // bucket. The authenticated-IP limiter above owns client fairness;
// keeping a constant key makes distributed source-IP floods observable
// at this edge instead of allowing the aggregate budget to be bypassed.
keyGenerator: () => 'gfs-edge-aggregate',
})
)
- 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) => {
diff --git a/external-rest-api/test/config.gfsEdgeRateLimit.test.ts b/external-rest-api/test/config.gfsEdgeRateLimit.test.ts
new file mode 100644
index 000000000..efbb5619c
--- /dev/null
+++ b/external-rest-api/test/config.gfsEdgeRateLimit.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const AGGREGATE_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AGGREGATE_RL_PER_MIN'
+const CLIENT_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_AUTHENTICATED_IP_RL_PER_MIN'
+const TOKEN_IP_ENV = 'EXTERNAL_REST_API_GFS_EDGE_TOKEN_IP_RL_PER_MIN'
+
+type RawGfsEdgeLimits = {
+ aggregate: string
+ clientIp: string
+ tokenIp: string
+}
+
+async function loadConfigWithLimits(limits: RawGfsEdgeLimits) {
+ vi.resetModules()
+ vi.stubEnv('NODE_ENV', 'test')
+ vi.stubEnv(AGGREGATE_ENV, limits.aggregate)
+ vi.stubEnv(CLIENT_IP_ENV, limits.clientIp)
+ vi.stubEnv(TOKEN_IP_ENV, limits.tokenIp)
+ return import('../src/config.js')
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+ vi.resetModules()
+})
+
+describe('external REST GFS edge rate-limit config', () => {
+ it('accepts positive ordered safe integers at startup parse', async () => {
+ const { config } = await loadConfigWithLimits({
+ aggregate: '3',
+ clientIp: '2',
+ tokenIp: '1',
+ })
+
+ expect(config.externalGfsEdgeAggregateRlPerMin).toBe(3)
+ expect(config.externalGfsEdgeAuthenticatedIpRlPerMin).toBe(2)
+ expect(config.externalGfsEdgeTokenIpRlPerMin).toBe(1)
+ })
+
+ it.each([
+ ['invalid aggregate', { aggregate: 'invalid', clientIp: '2', tokenIp: '1' }],
+ ['zero aggregate', { aggregate: '0', clientIp: '2', tokenIp: '1' }],
+ ['fractional client IP', { aggregate: '3', clientIp: '1.5', tokenIp: '1' }],
+ ['NaN token IP', { aggregate: '3', clientIp: '2', tokenIp: 'NaN' }],
+ ['unsafe token IP', { aggregate: '3', clientIp: '2', tokenIp: '9007199254740992' }],
+ ['aggregate above upper bound', { aggregate: '1000001', clientIp: '2', tokenIp: '1' }],
+ ] satisfies Array<[string, RawGfsEdgeLimits]>)('rejects %s', async (_label, limits) => {
+ await expect(loadConfigWithLimits(limits)).rejects.toThrow(/must be (a positive integer|<=)/)
+ })
+
+ it.each([
+ ['token above client IP', { aggregate: '4', clientIp: '2', tokenIp: '3' }],
+ ['client IP equal to aggregate', { aggregate: '3', clientIp: '3', tokenIp: '1' }],
+ ['client IP above aggregate', { aggregate: '2', clientIp: '3', tokenIp: '1' }],
+ ] satisfies Array<[string, RawGfsEdgeLimits]>)(
+ 'rejects inverted order: %s',
+ async (_label, limits) => {
+ await expect(loadConfigWithLimits(limits)).rejects.toThrow(/GFS edge rate limits/)
+ }
+ )
+})
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 32ea0f8df..516e1b883 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -232,31 +232,97 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
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 })
+ it('preserves per-client fairness before spending aggregate capacity', async () => {
const app = buildApp({
- aggregatePerMin: 10,
- authenticatedIpPerMin: 10,
- tokenIpPerMin: 2,
+ aggregatePerMin: 3,
+ authenticatedIpPerMin: 2,
+ tokenIpPerMin: 1,
})
+ app.set('trust proxy', 1)
for (let attempt = 0; attempt < 2; attempt += 1) {
await request(app)
- .post('/me/gfs/token')
+ .get('/me/gfs/not-classified')
.set('authorization', 'Bearer sess-xyz')
- .send({})
- .expect(200)
+ .set('x-forwarded-for', '198.51.100.10')
+ .expect(404)
}
+
+ const clientAExhausted = await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.10')
+ expect(clientAExhausted.status).toBe(429)
+ expect(clientAExhausted.body.rateLimitBucket).toBe('authenticated-ip')
+
+ await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.11')
+ .expect(404)
+
+ const aggregateExhausted = await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.12')
+ expect(aggregateExhausted.status).toBe(429)
+ expect(aggregateExhausted.body.rateLimitBucket).toBe('aggregate-ip')
+
+ const clientAStillExhausted = await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.10')
+ expect(clientAStillExhausted.status).toBe(429)
+ expect(clientAStillExhausted.body.rateLimitBucket).toBe('authenticated-ip')
+ expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(3)
+ })
+
+ it('does not spend wider edge buckets when the token bucket rejects', async () => {
+ clientMock.controlApiRequest.mockResolvedValue({ token: 'gfs-tok', expiresInSeconds: 300 })
+ const app = buildApp({
+ aggregatePerMin: 3,
+ authenticatedIpPerMin: 2,
+ tokenIpPerMin: 1,
+ })
+ app.set('trust proxy', 1)
+
+ await request(app)
+ .post('/me/gfs/token')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.10')
+ .send({})
+ .expect(200)
+
const exhausted = await request(app)
.post('/me/gfs/token')
.set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.10')
.send({})
expect(exhausted.status).toBe(429)
expect(exhausted.headers['retry-after']).toMatch(/^\d+$/)
- expect(exhausted.headers['ratelimit']).toContain('limit=2')
+ expect(exhausted.headers['ratelimit']).toContain('limit=1')
expect(exhausted.body.rateLimitBucket).toBe('token-ip')
- expect(clientMock.controlApiRequest).toHaveBeenCalledTimes(2)
+
+ await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.10')
+ .expect(404)
+ await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.11')
+ .expect(404)
+
+ const aggregateExhausted = await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', '198.51.100.12')
+ expect(aggregateExhausted.status).toBe(429)
+ expect(aggregateExhausted.body.rateLimitBucket).toBe('aggregate-ip')
+ expect(clientMock.controlApiRequest).toHaveBeenCalledTimes(1)
+ expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(3)
})
it('propagates a control-api no-escalation 403 verbatim', async () => {
@@ -517,27 +583,24 @@ describe('GET /me/gfs/shares (delegation list passthrough)', () => {
it('keeps the aggregate edge backstop process-wide across source IPs', async () => {
const app = buildApp({
- aggregatePerMin: 2,
- authenticatedIpPerMin: 100,
- tokenIpPerMin: 100,
+ aggregatePerMin: 3,
+ authenticatedIpPerMin: 2,
+ tokenIpPerMin: 1,
})
app.set('trust proxy', 1)
- await request(app)
- .get('/me/gfs/not-classified')
- .set('authorization', 'Bearer sess-xyz')
- .set('x-forwarded-for', '198.51.100.10')
- .expect(404)
- await request(app)
- .get('/me/gfs/not-classified')
- .set('authorization', 'Bearer sess-xyz')
- .set('x-forwarded-for', '198.51.100.11')
- .expect(404)
+ for (const ip of ['198.51.100.10', '198.51.100.11', '198.51.100.12']) {
+ await request(app)
+ .get('/me/gfs/not-classified')
+ .set('authorization', 'Bearer sess-xyz')
+ .set('x-forwarded-for', ip)
+ .expect(404)
+ }
const exhausted = await request(app)
.get('/me/gfs/not-classified')
.set('authorization', 'Bearer sess-xyz')
- .set('x-forwarded-for', '198.51.100.12')
+ .set('x-forwarded-for', '198.51.100.13')
expect(exhausted.status).toBe(429)
expect(exhausted.body.rateLimitBucket).toBe('aggregate-ip')
})