Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): separate acl reads from mutation budgets
Alfredo Lopezd01c40ea0ea4
diff --git a/control-api/src/middleware/externalGfsRateLimit.ts b/control-api/src/middleware/externalGfsRateLimit.tsindex 1ac27b980..bd7b8f1ab 100644--- a/control-api/src/middleware/externalGfsRateLimit.ts+++ b/control-api/src/middleware/externalGfsRateLimit.ts@@ -21,8 +21,10 @@ export type ExternalGfsOperationClass =| 'resource'| 'proxy-read'| 'resource-mutation'- | 'grants'- | 'shares'+ | 'grants-read'+ | 'grants-mutation'+ | 'shares-read'+ | 'shares-mutation'export type ExternalGfsOperation = {operationClass: ExternalGfsOperationClass@@ -92,17 +94,23 @@ export function externalGfsOperationFor(if (/^\/proxy\/[^/]+$/.test(path) && method === 'GET') {return { operationClass: 'proxy-read', route: `${GFS_PREFIX}/proxy/:rid` }}- if (path === '/grants' && (method === 'GET' || method === 'PUT')) {- return { operationClass: 'grants', route: `${GFS_PREFIX}/grants` }+ if (path === '/grants' && method === 'GET') {+ return { operationClass: 'grants-read', route: `${GFS_PREFIX}/grants` }+ }+ if (path === '/grants' && method === 'PUT') {+ return { operationClass: 'grants-mutation', route: `${GFS_PREFIX}/grants` }}if (/^\/grants\/[^/]+$/.test(path) && method === 'DELETE') {- return { operationClass: 'grants', route: `${GFS_PREFIX}/grants/:id` }+ return { operationClass: 'grants-mutation', route: `${GFS_PREFIX}/grants/:id` }+ }+ if (path === '/shares' && method === 'GET') {+ return { operationClass: 'shares-read', route: `${GFS_PREFIX}/shares` }}- if (path === '/shares' && (method === 'GET' || method === 'POST')) {- return { operationClass: 'shares', route: `${GFS_PREFIX}/shares` }+ if (path === '/shares' && method === 'POST') {+ return { operationClass: 'shares-mutation', route: `${GFS_PREFIX}/shares` }}if (/^\/shares\/[^/]+$/.test(path) && method === 'DELETE') {- return { operationClass: 'shares', route: `${GFS_PREFIX}/shares/:id` }+ return { operationClass: 'shares-mutation', route: `${GFS_PREFIX}/shares/:id` }}return null}@@ -145,7 +153,10 @@ function sourceIpDigest(req: Request): string {}function operationLimit(operationClass: ExternalGfsOperationClass): number {- return operationClass === 'resource' || operationClass === 'proxy-read'+ return operationClass === 'resource' ||+ operationClass === 'proxy-read' ||+ operationClass === 'grants-read' ||+ operationClass === 'shares-read'? config.externalGfsReadRlPerMin: config.externalGfsOperationRlPerMin}diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex 5b5758da6..d64d9a4c7 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -301,20 +301,36 @@ export function createExternalGfsRouter(): Router {keyGenerator: externalGfsActorRateKey('resource-mutation'),message: { error: 'Too Many Requests' },})- const externalGfsGrantsRouteRateLimit = rateLimit({+ const externalGfsGrantsReadRouteRateLimit = rateLimit({+ windowMs: 60_000,+ limit: config.externalGfsReadRlPerMin,+ standardHeaders: false,+ legacyHeaders: false,+ keyGenerator: externalGfsActorRateKey('grants-read'),+ message: { error: 'Too Many Requests' },+ })+ const externalGfsGrantsMutationRouteRateLimit = rateLimit({windowMs: 60_000,limit: config.externalGfsOperationRlPerMin,standardHeaders: false,legacyHeaders: false,- keyGenerator: externalGfsActorRateKey('grants'),+ keyGenerator: externalGfsActorRateKey('grants-mutation'),message: { error: 'Too Many Requests' },})- const externalGfsSharesRouteRateLimit = rateLimit({+ const externalGfsSharesReadRouteRateLimit = rateLimit({+ windowMs: 60_000,+ limit: config.externalGfsReadRlPerMin,+ standardHeaders: false,+ legacyHeaders: false,+ keyGenerator: externalGfsActorRateKey('shares-read'),+ message: { error: 'Too Many Requests' },+ })+ const externalGfsSharesMutationRouteRateLimit = rateLimit({windowMs: 60_000,limit: config.externalGfsOperationRlPerMin,standardHeaders: false,legacyHeaders: false,- keyGenerator: externalGfsActorRateKey('shares'),+ keyGenerator: externalGfsActorRateKey('shares-mutation'),message: { error: 'Too Many Requests' },})@@ -334,18 +350,32 @@ export function createExternalGfsRouter(): Router {// session/IP and effective-actor operation-class matrix.router.use('/external/gfs', externalGfsPreResolutionRateLimit)- // Per-user token bucket on the DELEGATION plane only (grants + shares),- // mirroring the admin plane's grantsRateLimit but in a DISTINCT bucket so the- // two planes never share quota. requireValidExternalSessionToken runs at- // router level first, so externalAuth.userId is always present by the time the- // limiter keys; the no-user branch is therefore unreachable, but it returns a- // shared sentinel (never null) so the limiter fails CLOSED — per- // rateLimitMiddleware's guidance for strict enforcement — instead of the- // default fail-open, keeping this plane strictly metered under any future- // auth-ordering change.- const externalGrantsRateLimit = rateLimitMiddleware({+ // ACL listing is still a privileged manage_acl operation, but it must not+ // consume the smaller mutation budget: opening the Manage dialog performs+ // several list/refetch reads before one visible grant/share action. Keep+ // those reads in the existing bounded GFS read budget and in a distinct+ // actor bucket from mutations.+ const externalGrantsReadRateLimit = rateLimitMiddleware({+ bucketType: 'gfs_grants_external_read',+ maxPerMinute: config.externalGfsReadRlPerMin,+ getBucketKey: req => {+ const authority = (req as RequestWithExternalGfsAuthority).gfsAuthority+ if (authority?.kind === 'linked-admin') {+ return `gfsgrants-ext-read:linked-admin:${authority.controlAdminId}`+ }+ if (authority?.kind === 'user-session') {+ return `gfsgrants-ext-read:user:${authority.desktopUserId}`+ }+ return 'gfsgrants-ext-read:__no_authority__'+ },+ })++ // Keep the existing mutation bucket identity and 30/min budget for+ // compatibility with telemetry and abuse controls; only read/list calls+ // move to the separate read bucket above.+ const externalGrantsMutationRateLimit = rateLimitMiddleware({bucketType: 'gfs_grants_external',- maxPerMinute: 30,+ maxPerMinute: config.externalGfsOperationRlPerMin,getBucketKey: req => {const authority = (req as RequestWithExternalGfsAuthority).gfsAuthorityif (authority?.kind === 'linked-admin') {@@ -400,44 +430,44 @@ export function createExternalGfsRouter(): Router {// (view-ACL = manage-ACL); handleGrantListForCaller enforces that.router.get('/external/gfs/grants',- externalGfsGrantsRouteRateLimit,- externalGrantsRateLimit,+ externalGfsGrantsReadRouteRateLimit,+ externalGrantsReadRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleGrantListForCaller))router.put('/external/gfs/grants',- externalGfsGrantsRouteRateLimit,- externalGrantsRateLimit,+ externalGfsGrantsMutationRouteRateLimit,+ externalGrantsMutationRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(assertHostTargetsWithinCallerAgents),asyncHandler(handleGrantWrite))router.delete('/external/gfs/grants/:id',- externalGfsGrantsRouteRateLimit,- externalGrantsRateLimit,+ externalGfsGrantsMutationRouteRateLimit,+ externalGrantsMutationRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleGrantDelete))router.post('/external/gfs/shares',- externalGfsSharesRouteRateLimit,- externalGrantsRateLimit,+ externalGfsSharesMutationRouteRateLimit,+ externalGrantsMutationRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleShareWrite))router.get('/external/gfs/shares',- externalGfsSharesRouteRateLimit,- externalGrantsRateLimit,+ externalGfsSharesReadRouteRateLimit,+ externalGrantsReadRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleShareListForCaller))router.delete('/external/gfs/shares/:id',- externalGfsSharesRouteRateLimit,- externalGrantsRateLimit,+ externalGfsSharesMutationRouteRateLimit,+ externalGrantsMutationRateLimit,asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleShareDelete))diff --git a/control-api/test/middleware.externalGfsRateLimit.test.ts b/control-api/test/middleware.externalGfsRateLimit.test.tsindex 7bdf774c0..19c41394a 100644--- a/control-api/test/middleware.externalGfsRateLimit.test.ts+++ b/control-api/test/middleware.externalGfsRateLimit.test.ts@@ -141,12 +141,12 @@ describe('external GFS rate boundary', () => {'/external/gfs/resources/:id/content',],['DELETE', `/resources/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/resources/:id'],- ['GET', '/grants', 'grants', '/external/gfs/grants'],- ['PUT', '/grants', 'grants', '/external/gfs/grants'],- ['DELETE', `/grants/${RESOURCE_ID}`, 'grants', '/external/gfs/grants/:id'],- ['GET', '/shares', 'shares', '/external/gfs/shares'],- ['POST', '/shares', 'shares', '/external/gfs/shares'],- ['DELETE', `/shares/${RESOURCE_ID}`, 'shares', '/external/gfs/shares/:id'],+ ['GET', '/grants', 'grants-read', '/external/gfs/grants'],+ ['PUT', '/grants', 'grants-mutation', '/external/gfs/grants'],+ ['DELETE', `/grants/${RESOURCE_ID}`, 'grants-mutation', '/external/gfs/grants/:id'],+ ['GET', '/shares', 'shares-read', '/external/gfs/shares'],+ ['POST', '/shares', 'shares-mutation', '/external/gfs/shares'],+ ['DELETE', `/shares/${RESOURCE_ID}`, 'shares-mutation', '/external/gfs/shares/:id'],] as const)('classifies %s /external/gfs%s as %s', (method, path, operationClass, route) => {expect(externalGfsOperationFor({@@ -332,6 +332,43 @@ describe('external GFS rate boundary', () => {expect(calls.filter(([, limit]) => limit === 1200)).toHaveLength(2)})+ it('assigns ACL listing to the read budget and ACL writes to the mutation budget', async () => {+ const { app } = buildApp()++ await request(app).get('/external/gfs/grants').set('x-user-session-token', 'session-acl-read')+ await request(app).put('/external/gfs/grants').set('x-user-session-token', 'session-acl-write')+ await request(app).get('/external/gfs/shares').set('x-user-session-token', 'session-acl-read')+ await request(app).post('/external/gfs/shares').set('x-user-session-token', 'session-acl-write')++ const calls = checkAndIncrement.mock.calls.map(call => [String(call[0]), Number(call[1])])+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:pre:grants-read:session:/), 120])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:resolved:grants-read:actor:/),+ 120,+ ])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:pre:grants-mutation:session:/),+ 30,+ ])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:resolved:grants-mutation:actor:/),+ 30,+ ])+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:pre:shares-read:session:/), 120])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:resolved:shares-read:actor:/),+ 120,+ ])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:pre:shares-mutation:session:/),+ 30,+ ])+ expect(calls).toContainEqual([+ expect.stringMatching(/^gfs-ext:resolved:shares-mutation:actor:/),+ 30,+ ])+ })+it('enforces the 1200/min aggregate IP ceiling after the 120/min read buckets', async () => {checkAndIncrement.mockImplementation((key: string, limit: number) => {if (key.startsWith('gfs-ext:pre:ip:')) return denied(1200)diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.tsindex 29c0d4c4e..8710be53e 100644--- a/control-api/test/routes.externalGfs.test.ts+++ b/control-api/test/routes.externalGfs.test.ts@@ -1777,7 +1777,7 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {expect(res.body.error).toBe('manage_acl_required')})- it('rate limits the grants operation class before authority resolution', async () => {+ it('rate limits the grants mutation class before authority resolution', async () => {auth()authority(['manage_acl', 'read'], { rateLimitCount: 31 })const app = await buildApp()@@ -1788,9 +1788,9 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {const bucketCall = mockQuery.mock.calls.find(call =>String(call[0]).includes('rate_limit_buckets') &&- String(call[1]?.[0]).startsWith('gfs-ext:pre:grants:session:')+ String(call[1]?.[0]).startsWith('gfs-ext:pre:grants-mutation:session:'))- expect(bucketCall?.[1]?.[0]).toMatch(/^gfs-ext:pre:grants:session:[0-9a-f]{64}$/)+ expect(bucketCall?.[1]?.[0]).toMatch(/^gfs-ext:pre:grants-mutation:session:[0-9a-f]{64}$/)})it('keys the external delegation plane in a bucket DISTINCT from the admin plane for the same subject', async () => {@@ -1829,6 +1829,25 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {expect(String(adminKey).startsWith('gfsgrants:')).toBe(true)})+ it('keeps external ACL reads in a distinct read bucket from mutation delegation', async () => {+ auth()+ authority(['manage_acl', 'read'])+ const app = await buildApp()+ await request(app)+ .get('/external/gfs/grants')+ .query({ drive: 'main', resourceId: R })+ .set('x-user-session-token', 'sess')++ const readKey = mockQuery.mock.calls.find(+ call =>+ String(call[0]).includes('rate_limit_buckets') &&+ String(call[1]?.[0]).startsWith('gfsgrants-ext-read:')+ )?.[1]?.[0]++ expect(readKey).toBe(`gfsgrants-ext-read:user:${U1}`)+ expect(String(readKey).startsWith('gfsgrants-ext:')).toBe(false)+ })+it('adjudicates only well-formed foreign hosts in foreignHostSubjectIndexes', async () => {const { foreignHostSubjectIndexes } = await import('../src/routes/external/gfs.js')const allowed = new Set([H1])