Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import { type ExternalGfsEdgeLimits, createGfsRouter } from '../src/routes/gfs.js'
const { ControlApiError, clientMock } = vi.hoisted(() => {
class ControlApiError extends Error {
constructor(
message: string,
public status: number,
public body: unknown,
headers: Record<string, string> | Headers = {}
) {
super(message)
this.headers = headers instanceof Headers ? Object.fromEntries(headers.entries()) : headers
}
public headers: Record<string, string>
}
return {
ControlApiError,
clientMock: { controlApiRequest: vi.fn(), controlApiStreamRequest: vi.fn() },
}
})
vi.mock('../src/controlApiClient.js', () => ({
controlApiRequest: clientMock.controlApiRequest,
controlApiStreamRequest: clientMock.controlApiStreamRequest,
ControlApiError,
}))
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(options: number | ExternalGfsEdgeLimits = 120) {
const app = express()
app.set('trust proxy', 1)
app.use(express.json())
app.use(
createGfsRouter(
typeof options === 'number' ? { edgeRequestLimit: options } : { edgeLimits: options }
)
)
return app
}
beforeEach(() => {
clientMock.controlApiRequest.mockReset()
clientMock.controlApiStreamRequest.mockReset()
authTokenMock.verifyToken.mockReset()
authTokenMock.verifyToken.mockReturnValue({
userId: 'u1',
email: '[email protected]',
teamId: null,
role: 'member',
exp: 9_999_999_999,
})
})
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-gfs-ratelimit-scope']).toBe('public_edge_requests')
expect(second.headers['x-ratelimit-remaining']).toBe('0')
expect(second.body).toEqual({
error: 'gfs_upload_rate_limited',
limit: 'public_edge_requests',
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('keeps capabilities drive-independent while control-api rejects mismatched creates', async () => {
clientMock.controlApiStreamRequest.mockImplementation(
async (
method: string,
path: string,
options: { query?: { drive?: string }; body?: unknown }
) => {
const drive = options.query?.drive
const body = typeof options.body === 'string' ? JSON.parse(options.body) : undefined
if (method === 'POST' && path === '/external/gfs/uploads' && body?.drive !== drive) {
throw new ControlApiError('drive mismatch', 400, { error: 'drive_mismatch' })
}
return new Response(JSON.stringify({ upload: { resumableV2: { enabled: true } } }), {
status: 200,
headers: { 'content-type': 'application/json' },
})
}
)
const missing = await request(buildApp())
.get('/me/gfs/capabilities')
.set('authorization', 'Bearer sess-xyz')
const mismatched = await request(buildApp())
.post('/me/gfs/uploads?drive=archive')
.set('authorization', 'Bearer sess-xyz')
.send({ drive: 'main', operation: 'create' })
expect(missing.status).toBe(200)
expect(missing.body).toEqual({ upload: { resumableV2: { enabled: true } } })
expect(mismatched.status).toBe(400)
expect(mismatched.body).toEqual({ error: 'drive_mismatch' })
expect(clientMock.controlApiStreamRequest).toHaveBeenCalledTimes(2)
})
it('forwards malformed drive values unchanged for control-api to reject', async () => {
const forwardedDrives: unknown[] = []
clientMock.controlApiStreamRequest.mockImplementation(
async (_method: string, _path: string, options: { query?: { drive?: string } }) => {
const drive = options.query?.drive
forwardedDrives.push(drive)
if (!drive || drive.trim() !== drive) {
throw new ControlApiError('drive required', 400, { error: 'drive_required' })
}
return new Response(JSON.stringify({ ok: true }), { status: 200 })
}
)
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).toHaveBeenCalledTimes(6)
expect(forwardedDrives).toEqual([...malformed, undefined])
})
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)
clientMock.controlApiStreamRequest.mockImplementation(
async (method: string, _path: string, options: { body?: unknown }) => {
if (method === 'PUT' && options.body && typeof options.body !== 'string') {
const chunks: Buffer[] = []
for await (const chunk of options.body as AsyncIterable<Buffer>) {
chunks.push(Buffer.from(chunk))
}
streamedPart = Buffer.concat(chunks)
}
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'content-type': 'application/json' },
})
}
)
const app = buildApp()
const authed = (builder: request.Test) => builder.set('authorization', 'Bearer sess-xyz')
await authed(request(app).get('/me/gfs/capabilities?drive=archive')).expect(200)
await authed(request(app).post('/me/gfs/uploads?drive=archive'))
.send({ drive: 'archive', operation: 'create' })
.expect(200)
await authed(request(app).head(`/me/gfs/uploads/${uploadId}?drive=archive`)).expect(200)
await authed(
request(app).get(`/me/gfs/uploads/${uploadId}/status?drive=archive&limit=256&cursor=next`)
).expect(200)
await authed(
request(app)
.put(`/me/gfs/uploads/${uploadId}/parts/0?drive=archive`)
.set('content-type', 'application/offset+octet-stream')
.set('upload-part-number', '0')
.set('upload-offset', '0')
.set('upload-chunk-length', '4')
.set('upload-checksum', 'sha256 dGVzdA==')
)
.send(Buffer.from('test'))
.expect(200)
for (const action of ['pause', 'resume', 'complete']) {
await authed(request(app).post(`/me/gfs/uploads/${uploadId}/${action}?drive=archive`))
.send({})
.expect(200)
}
await authed(request(app).delete(`/me/gfs/uploads/${uploadId}?drive=archive`)).expect(200)
expect(streamedPart.toString()).toBe('test')
expect(clientMock.controlApiStreamRequest).toHaveBeenCalledTimes(9)
for (const call of clientMock.controlApiStreamRequest.mock.calls) {
expect(call[2]).toMatchObject({
userSessionToken: 'sess-xyz',
query: { drive: 'archive' },
})
}
const partOptions = clientMock.controlApiStreamRequest.mock.calls[4][2]
expect(partOptions.extraHeaders).toMatchObject({
'content-length': '4',
'upload-chunk-length': '4',
'x-gfs-upload-source-ip': expect.any(String),
})
})
it('propagates the authoritative upload 429 and Retry-After header unchanged', async () => {
clientMock.controlApiStreamRequest.mockRejectedValue(
new ControlApiError(
'rate limited',
429,
{ error: 'gfs_upload_rate_limited', limit: 'principal_bytes', retryAfterSeconds: 7 },
new Headers({
'retry-after': '7',
'x-ratelimit-limit': '512',
'x-gfs-ratelimit-scope': 'principal_bytes',
})
)
)
const response = await request(buildApp())
.get('/me/gfs/capabilities?drive=archive')
.set('authorization', 'Bearer sess-xyz')
expect(response.status).toBe(429)
expect(response.headers['retry-after']).toBe('7')
expect(response.headers['x-ratelimit-limit']).toBe('512')
expect(response.headers['x-gfs-ratelimit-scope']).toBe('principal_bytes')
expect(response.body).toEqual({
error: 'gfs_upload_rate_limited',
limit: 'principal_bytes',
retryAfterSeconds: 7,
})
})
it('mints a user gfs token, forwarding the session token to control-api', async () => {
clientMock.controlApiRequest.mockResolvedValue({ token: 'gfs-tok', expiresInSeconds: 300 })
const res = await request(buildApp())
.post('/me/gfs/token')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send({ scopes: ['gfs.read'] })
expect(res.status).toBe(200)
expect(res.body.token).toBe('gfs-tok')
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('POST', '/external/gfs/token', {
userSessionToken: 'sess-xyz',
body: { scopes: ['gfs.read'] },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
expect(res.headers['x-request-id']).toBe(REQUEST_ID)
})
it('forwards a user delegation grant to /external/gfs/grants', async () => {
clientMock.controlApiRequest.mockResolvedValue({ ok: true })
const body = {
resourceId: 'r',
subject: { type: 'user', id: '22222222-2222-4222-8222-222222222222' },
permissions: ['read'],
inherit: false,
}
const res = await request(buildApp())
.put('/me/gfs/grants')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send(body)
expect(res.status).toBe(200)
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('PUT', '/external/gfs/grants', {
userSessionToken: 'sess-xyz',
body,
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
it('lists accessible resources through /external/gfs/resources', async () => {
clientMock.controlApiRequest.mockResolvedValue({
ok: true,
data: { items: [], nextCursor: 'next-page' },
})
const res = await request(buildApp())
.get('/me/gfs/resources?drive=main&limit=25&cursor=cursor-1')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
expect(res.status).toBe(200)
expect(res.body.data.nextCursor).toBe('next-page')
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/resources', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', limit: '25', cursor: 'cursor-1' },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
it('forwards the proxy-attested client IP for the control-api GFS rate boundary', async () => {
clientMock.controlApiRequest.mockResolvedValue({
ok: true,
data: { items: [], nextCursor: null },
})
const app = buildApp()
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.42')
.expect(200)
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/resources', {
userSessionToken: 'sess-xyz',
query: { drive: undefined, limit: undefined, cursor: undefined },
extraHeaders: {
'x-request-id': REQUEST_ID,
'x-forwarded-for': '198.51.100.42',
},
})
})
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,
data: { items: [], nextCursor: null },
})
const app = buildApp()
// The production app trusts exactly its configured proxy hop. This test
// exercises the fail-closed behavior when that trust is absent: the
// incoming XFF must not become the attestation sent to control-api.
app.set('trust proxy', false)
await request(app)
.get('/me/gfs/resources')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.set('x-forwarded-for', '203.0.113.99')
.expect(200)
const call = clientMock.controlApiRequest.mock.calls.at(-1)
const forwarded = (call?.[2] as { extraHeaders?: Record<string, string> } | undefined)
?.extraHeaders?.['x-forwarded-for']
expect(forwarded).toBeDefined()
expect(forwarded).not.toBe('203.0.113.99')
})
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 < 2; 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(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',
retryAfterSeconds: expect.any(Number),
})
expect(authTokenMock.verifyToken).toHaveBeenCalledTimes(2)
expect(clientMock.controlApiRequest).not.toHaveBeenCalled()
expect(clientMock.controlApiStreamRequest).not.toHaveBeenCalled()
})
it('preserves per-client fairness before spending aggregate capacity', async () => {
const app = buildApp({
aggregatePerMin: 3,
authenticatedIpPerMin: 2,
tokenIpPerMin: 1,
})
app.set('trust proxy', 1)
for (let attempt = 0; attempt < 2; attempt += 1) {
await request(app)
.get('/me/gfs/not-classified')
.set('authorization', 'Bearer sess-xyz')
.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=1')
expect(exhausted.body.rateLimitBucket).toBe('token-ip')
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 () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError('escalation', 403, { error: 'escalation_rejected' })
)
const res = await request(buildApp())
.put('/me/gfs/grants')
.set('authorization', 'Bearer sess-xyz')
.send({
resourceId: 'r',
subject: { type: 'user', id: '22222222-2222-4222-8222-222222222222' },
permissions: ['write'],
})
expect(res.status).toBe(403)
expect(res.body).toEqual({ error: 'escalation_rejected' })
})
it('preserves a public 413 payload_too_large response and its safe transport headers', async () => {
const body = {
ok: false,
error: {
code: 'payload_too_large',
message: 'upload exceeds the 200 MiB product limit',
},
}
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError(
'payload too large',
413,
body,
new Headers({
'content-type': 'application/json',
'retry-after': '9',
'upload-length': '209715200',
'x-ratelimit-limit': '16',
'x-internal-secret': 'must-not-cross-the-public-boundary',
})
)
)
const res = await request(buildApp())
.put('/me/gfs/resources/abc/content?drive=main')
.set('authorization', 'Bearer sess-xyz')
.send({ contentBase64: 'AAAA' })
expect(res.status).toBe(413)
expect(res.body).toEqual(body)
expect(res.headers['retry-after']).toBe('9')
expect(res.headers['upload-length']).toBe('209715200')
expect(res.headers['x-ratelimit-limit']).toBe('16')
expect(res.headers['x-internal-secret']).toBeUndefined()
})
it('propagates GFS transport statuses/body/headers without changing retry semantics', async () => {
// 507 is terminal for Desktop/Control UI, while 408/425 and the transient
// 5xx family are retryable. The public relay must not turn any of them into
// a generic 500 before the client can apply that policy.
for (const [status, error] of [
[408, 'request_timeout'],
[425, 'too_early'],
[500, 'gfsc_internal'],
[502, 'gfsc_unreachable'],
[503, 'gfsc_unavailable'],
[504, 'gfsc_timeout'],
[507, 'insufficient_storage'],
[599, 'upstream_unknown'],
] as const) {
clientMock.controlApiRequest.mockReset()
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError(
'gfsc failure',
status,
{ error },
new Headers({ 'retry-after': '7', 'x-ratelimit-limit': '16' })
)
)
const res = await request(buildApp())
.put('/me/gfs/resources/abc/content?drive=main')
.set('authorization', 'Bearer sess-xyz')
.send({ contentBase64: 'AAAA' })
expect(res.status).toBe(status)
expect(res.body).toEqual({ error })
expect(res.headers['retry-after']).toBe('7')
expect(res.headers['x-ratelimit-limit']).toBe('16')
}
})
it('streams a content download (binary) from the proxy', async () => {
clientMock.controlApiStreamRequest.mockResolvedValue(
new Response('hello', {
status: 200,
headers: { 'content-type': 'application/octet-stream', 'content-length': '5' },
})
)
const res = await request(buildApp())
.get('/me/gfs/proxy/abc?drive=main')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
expect(res.status).toBe(200)
const bytes = Buffer.isBuffer(res.body) ? res.body : Buffer.from(res.text ?? '')
expect(bytes.toString('utf8')).toBe('hello')
expect(clientMock.controlApiStreamRequest).toHaveBeenCalledWith(
'GET',
'/external/gfs/proxy/abc',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
})
it('forwards user resource mutations to control-api on the session plane', async () => {
clientMock.controlApiRequest.mockResolvedValue({ ok: true, data: { resourceId: 'abc' } })
await request(buildApp())
.patch('/me/gfs/resources/abc?drive=main')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send({ newName: 'renamed.md', ifMatch: 1 })
.expect(200)
await request(buildApp())
.post('/me/gfs/resources/abc/children?drive=main')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send({ name: 'docs', kind: 'directory' })
.expect(201)
await request(buildApp())
.put('/me/gfs/resources/abc/content?drive=main')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send({ content: 'hello', ifMatch: 2 })
.expect(200)
await request(buildApp())
.delete('/me/gfs/resources/abc?drive=main')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
.send({ ifMatch: 3 })
.expect(200)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
1,
'PATCH',
'/external/gfs/resources/abc',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { newName: 'renamed.md', ifMatch: 1 },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
2,
'POST',
'/external/gfs/resources/abc/children',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { name: 'docs', kind: 'directory' },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
3,
'PUT',
'/external/gfs/resources/abc/content',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { content: 'hello', ifMatch: 2 },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(
4,
'DELETE',
'/external/gfs/resources/abc',
{
userSessionToken: 'sess-xyz',
query: { drive: 'main' },
body: { ifMatch: 3 },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
}
)
})
it('401 without a session token', async () => {
authTokenMock.verifyToken.mockReturnValue(null)
const res = await request(buildApp()).post('/me/gfs/token').send({})
expect(res.status).toBe(401)
expect(res.headers['x-request-id']).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
)
})
})
describe('GET /me/gfs/grants (delegation list passthrough)', () => {
it('forwards drive + resourceId and returns the id-bearing items verbatim', async () => {
const items = [
{
id: 'aaaa1111-0000-4000-8000-000000000001',
drive: 'main',
resourceId: '11111111-1111-1111-1111-111111111111',
subject: { type: 'host', id: '1st:mcp-host/agent-a' },
permissions: ['read', 'write'],
inherit: true,
},
]
clientMock.controlApiRequest.mockResolvedValue({ items })
const res = await request(buildApp())
.get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
expect(res.status).toBe(200)
expect(res.body).toEqual({ items })
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/grants', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
})
it('propagates the manage_acl_required 403 verbatim', async () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError('forbidden', 403, { error: 'manage_acl_required' })
)
const res = await request(buildApp())
.get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
expect(res.status).toBe(403)
expect(res.body).toEqual({ error: 'manage_acl_required' })
})
it('forwards only the allowlisted rate-limit and request headers on a control-api 429', async () => {
clientMock.controlApiRequest.mockRejectedValue(
new ControlApiError(
'rate limited',
429,
{
error: 'Too Many Requests',
retryAfterSeconds: 17,
},
{
'retry-after': '17',
'x-ratelimit-limit': '30',
'x-ratelimit-remaining': '0',
'x-ratelimit-reset': '1776000000',
'x-request-id': REQUEST_ID,
'set-cookie': 'internal-session=never-forward',
server: 'control-api-internal',
'x-internal-debug': 'never-forward',
}
)
)
const res = await request(buildApp())
.get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
expect(res.status).toBe(429)
expect(res.body).toEqual({ error: 'Too Many Requests', retryAfterSeconds: 17 })
expect(res.headers['retry-after']).toBe('17')
expect(res.headers['x-ratelimit-limit']).toBe('30')
expect(res.headers['x-ratelimit-remaining']).toBe('0')
expect(res.headers['x-ratelimit-reset']).toBe('1776000000')
expect(res.headers['x-request-id']).toBe(REQUEST_ID)
expect(res.headers['set-cookie']).toBeUndefined()
expect(res.headers.server).toBeUndefined()
expect(res.headers['x-internal-debug']).toBeUndefined()
})
})
describe('GET /me/gfs/shares (delegation list passthrough)', () => {
it('forwards drive, resource, session, and request id without exposing an admin route', async () => {
const items = [
{
id: 'aaaaaaaa-0000-4000-8000-000000000001',
drive: 'main',
resourceId: '11111111-1111-1111-1111-111111111111',
subject: { type: 'user', id: '22222222-2222-4222-8222-222222222222' },
permissions: ['read'],
includeDescendants: true,
},
]
clientMock.controlApiRequest.mockResolvedValue({ items })
const res = await request(buildApp())
.get('/me/gfs/shares?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
expect(res.status).toBe(200)
expect(res.body).toEqual({ items })
expect(res.headers['x-request-id']).toBe(REQUEST_ID)
expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/shares', {
userSessionToken: 'sess-xyz',
query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },
extraHeaders: expect.objectContaining({ 'x-request-id': REQUEST_ID }),
})
clientMock.controlApiRequest.mockClear()
await request(buildApp())
.get('/me/gfs/admin/shares')
.set('authorization', 'Bearer sess-xyz')
.expect(404)
expect(clientMock.controlApiRequest).not.toHaveBeenCalled()
})
it('keeps the aggregate edge backstop process-wide across source IPs', async () => {
const app = buildApp({
aggregatePerMin: 3,
authenticatedIpPerMin: 2,
tokenIpPerMin: 1,
})
app.set('trust proxy', 1)
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.13')
expect(exhausted.status).toBe(429)
expect(exhausted.body.rateLimitBucket).toBe('aggregate-ip')
})
it.each([
[401, 'unauthorized'],
[403, 'manage_acl_required'],
[503, 'gfs_authority_unavailable'],
] as const)('propagates %s %s verbatim with the same request id', async (status, error) => {
clientMock.controlApiRequest.mockRejectedValue(new ControlApiError(error, status, { error }))
const res = await request(buildApp())
.get('/me/gfs/shares?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
.set('authorization', 'Bearer sess-xyz')
.set('x-request-id', REQUEST_ID)
expect(res.status).toBe(status)
expect(res.body).toEqual({ error })
expect(res.headers['x-request-id']).toBe(REQUEST_ID)
})
})