Skip to content

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

TypeScript

fix(gfs): make upload edge limiter codeql-visible

Alfredo Lopez894c490c4d68
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 d1884d71d..0e96cdeee 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -1,11 +1,33 @@
-import { Router } from 'express'
+import { type Request, Router } from 'express'
import type { NextFunction, Response } from 'express'
+import { type AugmentedRequest, ipKeyGenerator, rateLimit } from 'express-rate-limit'
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'
-import { createRateLimiter } from '../middleware/rateLimit.js'
+
+const UPLOAD_DRIVE_WIRE_RE = /^\S(?:[\s\S]*\S)?$/
+
+type GfsRouterOptions = {
+ edgeRequestLimit?: number
+}
+
+/**
+ * Validate only the public wire format. Drive ownership and authorization are
+ * re-established by control-api/GFSC from the authenticated subject; this
+ * helper must never become an authorization decision.
+ */
+function uploadDriveFromRequest(req: Request): string | null {
+ const rawDrive = req.query.drive
+ return typeof rawDrive === 'string' && UPLOAD_DRIVE_WIRE_RE.test(rawDrive) ? rawDrive : null
+}
+
+function uploadCreateBodyMatchesDrive(req: Request, path: string, drive: string): boolean {
+ if (req.method !== 'POST' || path !== '/external/gfs/uploads') return true
+ if (!req.body || typeof req.body !== 'object' || Array.isArray(req.body)) return false
+ return (req.body as { drive?: unknown }).drive === drive
+}
/**
* End-user gfs (Global File System) surface — the user side of the delegation UI
@@ -54,7 +76,7 @@ function forwardControlApiError(error: unknown, res: Response, next: NextFunctio
next(error)
}
-export function createGfsRouter(): Router {
+export function createGfsRouter(options: GfsRouterOptions = {}): Router {
const router = Router()
router.use('/me/gfs', requireAuth)
@@ -63,13 +85,32 @@ export function createGfsRouter(): Router {
// middleware on every new route). The authoritative replica-safe request,
// weighted-byte, and active-request budgets are enforced again in
// control-api with PostgreSQL before GFSC body forwarding.
- const uploadEdgeRateLimit = createRateLimiter({
+ const edgeRequestLimit = options.edgeRequestLimit ?? config.gfsUploadRequestPerMinute
+ const uploadEdgeRateLimit = rateLimit({
windowMs: 60_000,
- maxRequests: config.gfsUploadRequestPerMinute,
- errorCode: 'gfs_upload_rate_limited',
- keyFn: request => {
+ limit: edgeRequestLimit,
+ legacyHeaders: false,
+ standardHeaders: false,
+ skipFailedRequests: false,
+ skipSuccessfulRequests: false,
+ passOnStoreError: true,
+ keyGenerator: request => {
const req = request as AuthedRequest
- return `${req.auth?.userId || '__no_user__'}:${req.ip || req.socket.remoteAddress || 'unknown'}`
+ const sourceIp = req.ip || req.socket.remoteAddress || 'unknown'
+ const normalizedIp = sourceIp === 'unknown' ? sourceIp : ipKeyGenerator(sourceIp)
+ return `${req.auth?.userId || '__no_user__'}:${normalizedIp}`
+ },
+ handler: (request, res, _next, optionsUsed) => {
+ const info = (request as AugmentedRequest).rateLimit
+ const resetAt = info?.resetTime?.getTime() ?? Date.now() + optionsUsed.windowMs
+ const retryAfterSeconds = Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))
+ res.setHeader('Retry-After', String(retryAfterSeconds))
+ res.setHeader('X-RateLimit-Limit', String(info?.limit ?? edgeRequestLimit))
+ res.setHeader('X-RateLimit-Remaining', '0')
+ res.status(429).json({
+ error: 'gfs_upload_rate_limited',
+ retryAfterSeconds,
+ })
},
})
@@ -393,17 +434,15 @@ async function proxyUploadStream(
path: string
): Promise<void> {
try {
- const drive = typeof req.query.drive === 'string' ? req.query.drive.trim() : ''
- if (!drive || drive !== req.query.drive) {
+ const drive = uploadDriveFromRequest(req)
+ if (!drive) {
res.status(400).json({ error: 'drive_required' })
return
}
if (
method === 'POST' &&
path === '/external/gfs/uploads' &&
- (!req.body ||
- typeof req.body !== 'object' ||
- (req.body as { drive?: unknown }).drive !== drive)
+ !uploadCreateBodyMatchesDrive(req, path, drive)
) {
res.status(400).json({ error: 'drive_mismatch' })
return
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 110cfea61..6bdf15b6e 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -28,10 +28,11 @@ vi.mock('../src/controlApiClient.js', () => ({
const authTokenMock = vi.hoisted(() => ({ verifyToken: vi.fn() }))
vi.mock('../src/authToken.js', () => authTokenMock)
-function buildApp() {
+function buildApp(edgeRequestLimit = 120) {
const app = express()
+ app.set('trust proxy', 1)
app.use(express.json())
- app.use(createGfsRouter())
+ app.use(createGfsRouter({ edgeRequestLimit }))
return app
}
@@ -49,6 +50,86 @@ beforeEach(() => {
})
describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)', () => {
+ it('applies one shared local edge bucket across v2 methods before proxying', async () => {
+ clientMock.controlApiStreamRequest.mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ const app = buildApp(1)
+ const first = await request(app)
+ .get('/me/gfs/capabilities?drive=archive')
+ .set('authorization', 'Bearer sess-xyz')
+ const second = await request(app)
+ .get('/me/gfs/uploads/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/status?drive=archive')
+ .set('authorization', 'Bearer sess-xyz')
+
+ expect(first.status).toBe(200)
+ expect(second.status).toBe(429)
+ expect(second.headers['retry-after']).toMatch(/^[1-9][0-9]*$/)
+ expect(second.headers['x-ratelimit-limit']).toBe('1')
+ expect(second.headers['x-ratelimit-remaining']).toBe('0')
+ expect(second.body).toEqual({
+ error: 'gfs_upload_rate_limited',
+ retryAfterSeconds: expect.any(Number),
+ })
+ expect(clientMock.controlApiStreamRequest).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not spend an authenticated bucket on unauthenticated requests', async () => {
+ const app = buildApp(1)
+ const unauthenticated = await request(app).get('/me/gfs/capabilities?drive=archive')
+ expect(unauthenticated.status).toBe(401)
+
+ clientMock.controlApiStreamRequest.mockResolvedValue(
+ new Response(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ const authenticated = await request(app)
+ .get('/me/gfs/capabilities?drive=archive')
+ .set('authorization', 'Bearer sess-xyz')
+ expect(authenticated.status).toBe(200)
+ })
+
+ it('isolates users and groups IPv6 addresses by the library subnet policy', async () => {
+ authTokenMock.verifyToken.mockImplementation((token: string) => ({
+ userId: token === 'sess-two' ? 'u2' : 'u1',
+ email: `${token}@example.com`,
+ teamId: null,
+ role: 'member',
+ exp: 9_999_999_999,
+ }))
+ clientMock.controlApiStreamRequest.mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ const app = buildApp(1)
+ const first = await request(app)
+ .get('/me/gfs/capabilities?drive=archive')
+ .set('authorization', 'Bearer sess-one')
+ .set('x-forwarded-for', '2001:db8:abcd:0012::1')
+ const differentUser = await request(app)
+ .get('/me/gfs/capabilities?drive=archive')
+ .set('authorization', 'Bearer sess-two')
+ .set('x-forwarded-for', '2001:db8:abcd:0012::1')
+ const sameUserPrefix = await request(app)
+ .get('/me/gfs/capabilities?drive=archive')
+ .set('authorization', 'Bearer sess-one')
+ .set('x-forwarded-for', '2001:db8:abcd:0012::2')
+
+ expect(first.status).toBe(200)
+ expect(differentUser.status).toBe(200)
+ expect(sameUserPrefix.status).toBe(429)
+ expect(clientMock.controlApiStreamRequest).toHaveBeenCalledTimes(2)
+ })
+
it('rejects a missing or create-body-mismatched upload drive at the public edge', async () => {
const missing = await request(buildApp())
.get('/me/gfs/capabilities')
@@ -64,6 +145,23 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(clientMock.controlApiStreamRequest).not.toHaveBeenCalled()
})
+ it('rejects malformed drive wire values without forwarding them upstream', async () => {
+ const malformed = ['', ' archive', 'archive ', '\tarchive', 'archive\n']
+ for (const drive of malformed) {
+ const response = await request(buildApp())
+ .get(`/me/gfs/capabilities?drive=${encodeURIComponent(drive)}`)
+ .set('authorization', 'Bearer sess-xyz')
+ expect(response.status).toBe(400)
+ expect(response.body).toEqual({ error: 'drive_required' })
+ }
+ const arrayValue = await request(buildApp())
+ .get('/me/gfs/capabilities?drive=archive&drive=main')
+ .set('authorization', 'Bearer sess-xyz')
+ expect(arrayValue.status).toBe(400)
+ expect(arrayValue.body).toEqual({ error: 'drive_required' })
+ expect(clientMock.controlApiStreamRequest).not.toHaveBeenCalled()
+ })
+
it('preserves one non-main drive and the part stream through every upload lifecycle relay', async () => {
const uploadId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
let streamedPart = Buffer.alloc(0)