Skip to content

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

TypeScript

fix(gfs): close adversarial authority and proxy gaps

Alfredo Lopez94a7ee65631b
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d6369407a..bfa0d0a98 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index a9613931e..1459f79eb 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 1340fc9e8..7fe310e2c 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -131,6 +131,7 @@ type Config = {
approvalRlRequestPerMin: number
approvalRlRefreshPerMin: number
approvalRlExternalPerMin: number
+ approvalRlExternalEdgePerMin: number
oauthBrokerRlPerMin: number
adminPublicTokenRlPerMin: number
// External Desktop GFS is a separate authority plane. The process-local
@@ -743,6 +744,7 @@ export const config: Config = {
approvalRlRequestPerMin: Number(process.env.APPROVAL_RL_REQUEST_PER_MIN || 120),
approvalRlRefreshPerMin: Number(process.env.APPROVAL_RL_REFRESH_PER_MIN || 20),
approvalRlExternalPerMin: Number(process.env.APPROVAL_RL_EXTERNAL_PER_MIN || 60),
+ approvalRlExternalEdgePerMin: Number(process.env.APPROVAL_RL_EXTERNAL_EDGE_PER_MIN || 120),
oauthBrokerRlPerMin: Number(process.env.CONTROL_API_OAUTH_BROKER_RL_PER_MIN || 60),
adminPublicTokenRlPerMin: Number(process.env.CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN || 20),
// Approved GFS authority-boundary budgets. Keep them fixed here rather than
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index bf1841a4c..b5a7890da 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2953,6 +2953,22 @@ async function applyGfsLifecycleAuthorityProjectionSchema(db: DbClient): Promise
`)
}
+/**
+ * The authorization epoch is one-based. Keep this as a new migration rather
+ * than editing the shipped baseline/session-version migrations: existing
+ * installations must receive the same default as fresh installations, and
+ * invitation inserts also stamp the first epoch explicitly.
+ */
+async function applyControlAdminSessionVersionDefaultSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ UPDATE control_admin_users
+ SET session_version = 1
+ WHERE session_version IS NULL OR session_version < 1;
+ ALTER TABLE control_admin_users
+ ALTER COLUMN session_version SET DEFAULT 1;
+ `)
+}
+
// Exported (read-only) so the migration-order invariant test can assert the
// array is monotonic by version-string. Applied strictly in array order and
// tracked by full version-string in `schema_migrations`, so a non-monotonic
@@ -5835,6 +5851,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0095_gfs_lifecycle_authority_projection',
apply: applyGfsLifecycleAuthorityProjectionSchema,
},
+ {
+ version: '0096_control_admin_session_version_default',
+ apply: applyControlAdminSessionVersionDefaultSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/middleware/externalClientIdentity.ts b/control-api/src/middleware/externalClientIdentity.ts
new file mode 100644
index 000000000..48ca78ec5
--- /dev/null
+++ b/control-api/src/middleware/externalClientIdentity.ts
@@ -0,0 +1,28 @@
+import type { Request } from 'express'
+import { ipKeyGenerator } from 'express-rate-limit'
+import { createHash } from 'node:crypto'
+import { isIP } from 'node:net'
+
+/**
+ * Resolve the client identity asserted by the authenticated external-rest
+ * boundary. The service header is only meaningful after the internal-service
+ * gate has run; callers that exercise a router directly fall back to
+ * Express's proxy-aware address instead of trusting arbitrary text.
+ */
+export function externalClientIp(req: Request): string {
+ const asserted = req.header('x-external-client-ip')?.trim()
+ if (asserted && isIP(asserted) !== 0) return asserted
+ const forwarded = req.header('x-forwarded-for')?.split(',', 1)[0]?.trim()
+ if (forwarded && isIP(forwarded) !== 0) return forwarded
+ const fallback = req.ip?.trim() || req.socket.remoteAddress?.trim()
+ return fallback && isIP(fallback) !== 0 ? fallback : '__unknown_peer__'
+}
+
+/** Stable per-client key for express-rate-limit's pre-auth edge buckets. */
+export function externalClientRateLimitKey(req: Request): string {
+ const ipKey = ipKeyGenerator(externalClientIp(req))
+ const sessionToken = req.header('x-user-session-token')?.trim()
+ if (!sessionToken) return `external-client-ip:${ipKey}`
+ const sessionKey = createHash('sha256').update(sessionToken).digest('hex').slice(0, 24)
+ return `external-client-ip:${ipKey}:session:${sessionKey}`
+}
diff --git a/control-api/src/profileTypes.ts b/control-api/src/profileTypes.ts
index 604663ecd..acc295940 100644
--- a/control-api/src/profileTypes.ts
+++ b/control-api/src/profileTypes.ts
@@ -45,7 +45,7 @@ export type AuthClaims = {
teamId: string | null
role: TeamRole
/** Authoritative users.lifecycle_version captured when the session was issued. */
- authGeneration?: number
+ authGeneration: number
exp: number
}
diff --git a/control-api/src/routes/external/decisions.routes.ts b/control-api/src/routes/external/decisions.routes.ts
index 077186c64..65e17de47 100644
--- a/control-api/src/routes/external/decisions.routes.ts
+++ b/control-api/src/routes/external/decisions.routes.ts
@@ -2,6 +2,7 @@ import { NextFunction, Request, Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { requireApprovalDecisionAccess } from '../../middleware/approvalDecisionAccess.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import { requireValidExternalSessionToken } from '../../middleware/externalSessionAuth.js'
import type { ExternalAuthedRequest } from '../../middleware/externalSessionAuth.js'
import { mcpHostHttpMetrics } from '../../middleware/mcpHostHttpMetrics.js'
@@ -46,9 +47,10 @@ export function createExternalUserApprovalDecisionsRouter(): Router {
const router = Router()
const externalApprovalEdgeRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.get(
diff --git a/control-api/src/routes/external/directory.ts b/control-api/src/routes/external/directory.ts
index 87bb228a3..1160726e4 100644
--- a/control-api/src/routes/external/directory.ts
+++ b/control-api/src/routes/external/directory.ts
@@ -1,6 +1,7 @@
import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
requireExternalTeamParamMatch,
requireValidExternalSessionToken,
@@ -11,9 +12,10 @@ export function createExternalDirectoryRouter(): Router {
const router = Router()
const externalDirectoryRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.use('/external/directory', externalDirectoryRateLimit, requireValidExternalSessionToken)
diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.ts
index 13ad81a20..5907d9d68 100644
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@ -1,4 +1,4 @@
-import { type NextFunction, Router } from 'express'
+import { type Response as ExpressResponse, type NextFunction, type Request, Router } from 'express'
import { ipKeyGenerator, rateLimit } from 'express-rate-limit'
import { createHash, randomUUID } from 'node:crypto'
import {
@@ -258,80 +258,90 @@ export function createExternalGfsRouter(): Router {
// routing-boundary backstop so static analysis can prove every
// auth/authority/handler path is metered. The all-route ingress guard is
// deliberately wider than the product quotas; the per-class guards and
- // distributed buckets retain the narrower security budgets. They keep no
- // response quota headers: the distributed guard owns the externally
- // forwarded values.
+ // distributed buckets retain the narrower security budgets. Edge rejects
+ // still expose a bounded Retry-After body/header so Desktop can recover
+ // without treating the backstop as an opaque 500.
+ const edgeRateLimitHandler = (_req: Request, res: ExpressResponse): void => {
+ const raw = res.getHeader('Retry-After')
+ const retryAfterSeconds =
+ typeof raw === 'number' && Number.isSafeInteger(raw) && raw > 0
+ ? raw
+ : typeof raw === 'string' && /^\d+$/.test(raw)
+ ? Math.max(1, Number(raw))
+ : 60
+ res.status(429).json({ error: 'Too Many Requests', retryAfterSeconds })
+ }
const externalGfsIngressRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsIngressRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsIngressRateKey,
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsTokenRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsTokenUserRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsTokenRateKey,
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsResourceRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsReadRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('resource'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsProxyReadRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsReadRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('proxy-read'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsMutationRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsOperationRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('resource-mutation'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsGrantsReadRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsReadRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('grants-read'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsGrantsMutationRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsOperationRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('grants-mutation'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsSharesReadRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsReadRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('shares-read'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
const externalGfsSharesMutationRouteRateLimit = rateLimit({
windowMs: 60_000,
limit: config.externalGfsOperationRlPerMin,
- standardHeaders: false,
+ standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: externalGfsActorRateKey('shares-mutation'),
- message: { error: 'Too Many Requests' },
+ handler: edgeRateLimitHandler,
})
// The source-IP guard intentionally precedes authentication and authority
diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.ts
index a7c6efd07..e989045ff 100644
--- a/control-api/src/routes/external/invitations.ts
+++ b/control-api/src/routes/external/invitations.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { randomBytes } from 'node:crypto'
import { config } from '../../config.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
rejectBodyUserTeamMismatch,
@@ -36,12 +37,13 @@ export function createExternalInvitationsRouter(): Router {
const router = Router()
const externalInvitationsEdgeRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
// Keep one edge limiter at the common prefix so every invitation endpoint,
- // including Desktop authorization, is covered without double-counting.
+ // including Desktop authorization, is covered once.
router.use('/external/invitations', externalInvitationsEdgeRateLimit)
router.get(
'/external/invitations/token/:token',
diff --git a/control-api/src/routes/external/members.ts b/control-api/src/routes/external/members.ts
index 9e306bfed..2b56e0285 100644
--- a/control-api/src/routes/external/members.ts
+++ b/control-api/src/routes/external/members.ts
@@ -1,6 +1,7 @@
import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -30,9 +31,10 @@ export function createExternalMembersRouter(): Router {
const router = Router()
const externalMembersRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.use('/external/members', externalMembersRateLimit, requireValidExternalSessionToken)
diff --git a/control-api/src/routes/external/notifications.routes.ts b/control-api/src/routes/external/notifications.routes.ts
index 044daa254..029ec289b 100644
--- a/control-api/src/routes/external/notifications.routes.ts
+++ b/control-api/src/routes/external/notifications.routes.ts
@@ -2,6 +2,7 @@ import { Request, Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -94,9 +95,10 @@ export function createExternalNotificationsRouter(): Router {
const router = Router()
const externalNotificationsEdgeRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.get(
diff --git a/control-api/src/routes/external/oauthGrants.ts b/control-api/src/routes/external/oauthGrants.ts
index ef7e2c6f9..0fbd21ebd 100644
--- a/control-api/src/routes/external/oauthGrants.ts
+++ b/control-api/src/routes/external/oauthGrants.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { pool } from '../../db.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -25,9 +26,10 @@ export function createExternalOauthGrantsRouter(): Router {
const router = Router()
const externalOauthGrantsRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
// GET /external/oauth/grants
diff --git a/control-api/src/routes/external/sharedFilesystems.ts b/control-api/src/routes/external/sharedFilesystems.ts
index 3688b5465..4ffa398bb 100644
--- a/control-api/src/routes/external/sharedFilesystems.ts
+++ b/control-api/src/routes/external/sharedFilesystems.ts
@@ -3,6 +3,7 @@ import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -184,9 +185,10 @@ export function createExternalSharedFilesystemsRouter(gateway: K8sGateway): Rout
const router = Router()
const externalSharedFilesystemsRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
const sfsNs = config.sharedFilesystemsNamespace
const ctxNs = config.contextsNamespace
diff --git a/control-api/src/routes/external/teams.ts b/control-api/src/routes/external/teams.ts
index 04b663a96..d543d35cd 100644
--- a/control-api/src/routes/external/teams.ts
+++ b/control-api/src/routes/external/teams.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import type { ExternalAuthedRequest } from '../../middleware/externalSessionAuth.js'
import {
rejectBodyUserTeamMismatch,
@@ -43,9 +44,10 @@ export function createExternalTeamsRouter(gateway: K8sGateway): Router {
const router = Router()
const externalTeamsRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.use('/external/teams', externalTeamsRateLimit, requireValidExternalSessionToken)
diff --git a/control-api/src/routes/external/users.ts b/control-api/src/routes/external/users.ts
index 3d97d3c49..b752950de 100644
--- a/control-api/src/routes/external/users.ts
+++ b/control-api/src/routes/external/users.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
rejectBodyUserTeamMismatch,
@@ -78,9 +79,10 @@ export function createExternalUsersRouter(gateway: K8sGateway): Router {
const router = Router()
const externalUsersRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.use('/external/users', externalUsersRateLimit, requireValidExternalSessionToken)
diff --git a/control-api/src/routes/external/workflow-approval-mediums.routes.ts b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
index ade1bd33d..9e84831da 100644
--- a/control-api/src/routes/external/workflow-approval-mediums.routes.ts
+++ b/control-api/src/routes/external/workflow-approval-mediums.routes.ts
@@ -2,6 +2,7 @@ import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { config } from '../../config.js'
import type { K8sGateway } from '../../k8s.js'
+import { externalClientRateLimitKey } from '../../middleware/externalClientIdentity.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
@@ -74,9 +75,10 @@ export function createExternalWorkflowApprovalMediumsRouter(gateway: K8sGateway)
const router = Router()
const externalWorkflowApprovalEdgeRateLimit = rateLimit({
windowMs: 60_000,
- limit: config.approvalRlExternalPerMin,
+ limit: config.approvalRlExternalEdgePerMin,
standardHeaders: 'draft-7',
legacyHeaders: false,
+ keyGenerator: externalClientRateLimitKey,
})
router.post(
diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.ts
index 65f5ee26c..5f51538ae 100644
--- a/control-api/src/services/adminAuthService.ts
+++ b/control-api/src/services/adminAuthService.ts
@@ -941,8 +941,8 @@ export async function completeControlAdminInvitation(input: {
if (row.username_exists) return { error: 'duplicate_username' as const }
const inserted = await db.query(
- `INSERT INTO control_admin_users(email, username, password_hash, role, status)
- VALUES($1, $2, $3, 'admin', 'active')
+ `INSERT INTO control_admin_users(email, username, password_hash, role, status, session_version)
+ VALUES($1, $2, $3, 'admin', 'active', 1)
RETURNING id, username, email, password_hash, session_version, role, status, failed_attempts, locked_until`,
[email, username, input.passwordHash]
)
diff --git a/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts b/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts
new file mode 100644
index 000000000..0c8a807c9
--- /dev/null
+++ b/control-api/test/db.controlAdminSessionVersionDefaultMigration.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('pg', () => ({
+ Pool: vi.fn(function MockPool() {
+ return { connect: vi.fn(), query: vi.fn() }
+ }),
+}))
+
+describe('0096_control_admin_session_version_default migration', () => {
+ it('runs after the lifecycle projection and makes the authorization epoch one-based', async () => {
+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')
+ const versions = CONTROL_API_MIGRATIONS.map(migration => migration.version)
+ const sessionVersionMigration = versions.indexOf('0031_control_admin_session_version')
+ const lifecycleProjectionMigration = versions.indexOf('0095_gfs_lifecycle_authority_projection')
+ const defaultMigration = versions.indexOf('0096_control_admin_session_version_default')
+ expect(sessionVersionMigration).toBeGreaterThanOrEqual(0)
+ expect(lifecycleProjectionMigration).toBeGreaterThan(sessionVersionMigration)
+ expect(defaultMigration).toBeGreaterThan(lifecycleProjectionMigration)
+ expect(defaultMigration).toBe(versions.length - 1)
+
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0096_control_admin_session_version_default'
+ )
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+ await migration!.apply({ query })
+ const sql = String(query.mock.calls[0]?.[0])
+
+ expect(sql).toContain('SET session_version = 1')
+ expect(sql).toContain('ALTER COLUMN session_version SET DEFAULT 1')
+ })
+})
diff --git a/control-api/test/middleware.externalClientIdentity.test.ts b/control-api/test/middleware.externalClientIdentity.test.ts
new file mode 100644
index 000000000..1ad37e9f6
--- /dev/null
+++ b/control-api/test/middleware.externalClientIdentity.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest'
+import { ipKeyGenerator } from 'express-rate-limit'
+import {
+ externalClientIp,
+ externalClientRateLimitKey,
+} from '../src/middleware/externalClientIdentity.js'
+
+function request(headers: Record<string, string>, ip = '10.0.0.9') {
+ return {
+ header(name: string) {
+ return headers[name.toLowerCase()]
+ },
+ ip,
+ socket: { remoteAddress: '10.0.0.10' },
+ } as never
+}
+
+describe('external client rate-limit identity', () => {
+ it('uses the authenticated external-rest identity before the funnel address', () => {
+ const req = request({ 'x-external-client-ip': '203.0.113.41' })
+ expect(externalClientIp(req)).toBe('203.0.113.41')
+ expect(externalClientRateLimitKey(req)).toBe('external-client-ip:203.0.113.41')
+ })
+
+ it('rejects malformed asserted identity and falls back to the proxy-aware request IP', () => {
+ const req = request({ 'x-external-client-ip': 'not-an-ip' }, '198.51.100.7')
+ expect(externalClientIp(req)).toBe('198.51.100.7')
+ })
+
+ it('uses express-rate-limit IPv6 masking so address rotation cannot evade the bucket', () => {
+ const ipv6 = '2001:db8:abcd:1234:5678:9abc:def0:1234'
+ const req = request({ 'x-external-client-ip': ipv6 })
+ expect(externalClientRateLimitKey(req)).toBe(`external-client-ip:${ipKeyGenerator(ipv6)}`)
+ expect(externalClientRateLimitKey(req)).not.toContain(ipv6)
+ })
+
+ it('separates authenticated sessions sharing one external address without exposing the token', () => {
+ const first = request({ 'x-user-session-token': 'session-one' })
+ const second = request({ 'x-user-session-token': 'session-two' })
+ expect(externalClientRateLimitKey(first)).not.toBe(externalClientRateLimitKey(second))
+ expect(externalClientRateLimitKey(first)).not.toContain('session-one')
+ })
+})
diff --git a/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
index d0e95dfc4..9627e1329 100644
--- a/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
+++ b/control-api/test/middleware.externalSessionAuth.lifecycle.test.ts
@@ -42,7 +42,7 @@ describe('external session lifecycle gate', () => {
poolQuery.mockClear()
verifyToken.mockClear()
poolQuery.mockResolvedValue({
- rows: [{ lifecycle_state: 'active', lifecycle_version: 4 }],
+ rows: [{ lifecycle_state: 'active', lifecycle_version: '4' }],
rowCount: 1,
})
})
@@ -50,7 +50,7 @@ describe('external session lifecycle gate', () => {
it('accepts an active session whose generation matches the user row', async () => {
verifyToken.mockReturnValueOnce(claims)
poolQuery.mockResolvedValueOnce({
- rows: [{ lifecycle_state: 'active', lifecycle_version: 4 }],
+ rows: [{ lifecycle_state: 'active', lifecycle_version: '4' }],
rowCount: 1,
})
const response = await request(app()).get('/protected').set('x-user-session-token', 'session')
@@ -58,8 +58,8 @@ describe('external session lifecycle gate', () => {
})
it.each([
- [{ lifecycle_state: 'retired', lifecycle_version: 5 }],
- [{ lifecycle_state: 'active', lifecycle_version: 5 }],
+ [{ lifecycle_state: 'retired', lifecycle_version: '5' }],
+ [{ lifecycle_state: 'active', lifecycle_version: '5' }],
[[]],
])('denies retired, stale, or missing authoritative rows', async row => {
verifyToken.mockReturnValueOnce(claims)
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 91c5834f0..b7fdd7950 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -644,6 +644,30 @@ describe('linked Desktop operator authority contract', () => {
expect(mockQuery.mock.calls[0]?.[0]).toContain('lifecycle_state')
})
+ it('returns a bounded retry body and header when the express edge backstop is exhausted', async () => {
+ const previous = config.externalGfsIngressRlPerMin
+ config.externalGfsIngressRlPerMin = 1
+ try {
+ auth()
+ const app = await buildApp()
+ await request(app)
+ .get('/external/gfs/not-classified')
+ .set('x-user-session-token', 'sess')
+ .expect(404)
+ const res = await request(app)
+ .get('/external/gfs/not-classified')
+ .set('x-user-session-token', 'sess')
+ expect(res.status).toBe(429)
+ expect(res.headers['retry-after']).toMatch(/^\d+$/)
+ expect(res.body).toEqual({
+ error: 'Too Many Requests',
+ retryAfterSeconds: expect.any(Number),
+ })
+ } finally {
+ config.externalGfsIngressRlPerMin = previous
+ }
+ })
+
it('rejects a pre-resolution rate limit before resolver or route work', async () => {
auth()
;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =
@@ -1504,6 +1528,18 @@ describe('user resource mutations via gfsc proxy', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
+ it('rejects a mutation with no session header before minting or proxying', async () => {
+ mockVerifyExternalSessionToken.mockReturnValue(null)
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const app = await buildApp()
+ const res = await request(app).delete(`/external/gfs/resources/${R}`).send({ ifMatch: 1 })
+
+ expect(res.status).toBe(401)
+ expect(mockSignGfsToken).not.toHaveBeenCalled()
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
it('creates a child with a user gfs.write token', async () => {
auth()
const fetchMock = vi.fn(
diff --git a/control-ui/lib/__tests__/adminUsersApi.test.ts b/control-ui/lib/__tests__/adminUsersApi.test.ts
index 0ee4c2e42..95f37c3f4 100644
--- a/control-ui/lib/__tests__/adminUsersApi.test.ts
+++ b/control-ui/lib/__tests__/adminUsersApi.test.ts
@@ -37,4 +37,26 @@ describe('deleteAdminUser', () => {
})
)
})
+
+ it('generates governed metadata when the caller uses the default request', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ deleted: true, id: USER_ID }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ await deleteAdminUser(USER_ID)
+
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit
+ const headers = init.headers as Record<string, string>
+ expect(JSON.parse(String(init.body))).toEqual({ reason: 'control_ui_user_retirement' })
+ expect(headers['Idempotency-Key']).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+ )
+ expect(headers['x-correlation-id']).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+ )
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index e278cbee1..9be8f5680 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -95,6 +95,7 @@ function Probe({ grantsListEnabled = false }: { grantsListEnabled?: boolean }) {
<div data-testid="accessible-count">{ctrl.accessibleResources.length}</div>
<div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div>
<div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div>
+ <div data-testid="open-error">{ctrl.openError ?? 'none'}</div>
<div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div>
{ctrl.accessibleResources.map(resource => (
<button key={resource.resourceId} type="button" onClick={() => ctrl.openResource(resource)}>
@@ -599,6 +600,44 @@ describe('useGfsBrowserController', () => {
expect(screen.getByTestId('current').textContent).toBe('shared-folder')
})
+ it.each([
+ ['403 Forbidden: resource policy denied', '403 Forbidden: resource policy denied'],
+ ['401 Unauthorized', '401 Unauthorized'],
+ ] as const)('keeps the URI operation scoped for %s', async (_label, message) => {
+ const resolve = vi.fn(async () => {
+ throw new Error(message)
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve,
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+ await act(async () => {
+ screen.getByRole('button', { name: 'open' }).click()
+ })
+ await waitFor(() => expect(resolve).toHaveBeenCalledWith('gfs://main/root'))
+
+ expect(screen.getByTestId('access-state').textContent).toBe(
+ message.startsWith('401') ? 'revoked' : 'active'
+ )
+ expect(screen.getByTestId('open-error').textContent).toBe(
+ message.startsWith('401') ? 'none' : message
+ )
+ })
+
it('refreshes cached affordances after permissions change outside Desktop', async () => {
let held = ['read']
const affordances = vi.fn(async () => ({
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 16af91510..5ab683d21 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -132,7 +132,16 @@ export function isGfsSessionAuthorityFailure(
): boolean {
const normalized = message.toLowerCase()
if (SESSION_AUTHORITY_ERROR_CODES.some(code => normalized.includes(code))) return true
- if (surface !== 'discovery') return false
+ if (surface !== 'discovery') {
+ // A bare 401 means the authenticated session is no longer accepted. It is
+ // distinct from a generic 403, which may be only a resource-policy denial
+ // and must not clear the whole browser session.
+ return (
+ /(^|\D)401(\D|$)/.test(normalized) ||
+ normalized.includes('not authenticated') ||
+ normalized.includes('unauthenticated')
+ )
+ }
return (
/(^|\D)(401|403)(\D|$)/.test(normalized) ||
normalized.includes('unauthorized') ||
@@ -534,7 +543,10 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
return crumb
} catch (error) {
const message = toMessage(error)
- if (isGfsSessionAuthorityFailure(message, 'discovery')) revokeAccess()
+ // Opening a URI is an operation on one resource. A generic 403 may be
+ // a per-resource policy decision; only typed lifecycle failures or a
+ // bare 401 invalidate the session-wide authority state.
+ if (isGfsSessionAuthorityFailure(message, 'operation')) revokeAccess()
else setOpenError(message)
return false
} finally {
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 4e99e8980..a0782edd0 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -233,12 +233,16 @@ describe('FilesPage', () => {
)
})
- it.each(['401 Unauthorized', '403 Forbidden'])(
+ it.each([
+ ['401 Unauthorized', 'gfs_operator_link_invalid'],
+ ['401 Unauthorized', 'Unauthorized'],
+ ['403 Forbidden', 'gfs_operator_link_invalid'],
+ ])(
'fails closed with a stable alert after a %s root mutation denial',
- async status => {
+ async (status, errorCode) => {
const rootResourceId = '11111111-1111-1111-1111-111111111111'
const createFolder = vi.fn(async () => {
- throw new Error(`${status}: gfs_operator_link_invalid`)
+ throw new Error(`${status}: ${errorCode}`)
})
const pushToast = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index c190ad8df..d149cfba2 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.72",
+ "version": "0.1.73",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.72",
+ "version": "0.1.73",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 74887d709..2012fd655 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.72",
+ "version": "0.1.73",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/app.ts b/external-rest-api/src/app.ts
index 65a8ae08a..a21a58c0e 100644
--- a/external-rest-api/src/app.ts
+++ b/external-rest-api/src/app.ts
@@ -1,6 +1,7 @@
import express, { NextFunction, Request, Response } from 'express'
import cors from 'cors'
import { config } from './config.js'
+import { withExternalRequestContext } from './requestContext.js'
import { createAuthRouter } from './routes/auth.js'
import { createContextSharedFilesystemsRouter } from './routes/contextSharedFilesystems.js'
import { createDesktopRouter } from './routes/desktop.js'
@@ -22,6 +23,11 @@ import { createExternalWorkflowsRouter } from './routes/workflows.js'
export function createApp() {
const app = express()
app.set('trust proxy', 1)
+ // Capture the proxy-attested client once at the external boundary. The
+ // control-api receives it through the authenticated service channel so its
+ // non-GFS edge buckets do not collapse every Desktop client onto the funnel
+ // pod address.
+ app.use(withExternalRequestContext)
app.use(
cors({
origin: config.corsOrigin === '*' ? true : config.corsOrigin,
diff --git a/external-rest-api/src/controlApiClient.ts b/external-rest-api/src/controlApiClient.ts
index 38efea234..03798aec2 100644
--- a/external-rest-api/src/controlApiClient.ts
+++ b/external-rest-api/src/controlApiClient.ts
@@ -1,12 +1,20 @@
import { config } from './config.js'
+import { currentExternalClientIp } from './requestContext.js'
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
+function addExternalClientIdentity(headers: Record<string, string>): void {
+ const clientIp = currentExternalClientIp()
+ if (clientIp) headers['x-external-client-ip'] = clientIp
+}
+
// Response headers are an API contract only where a caller can safely act on
// them. In particular, never relay Set-Cookie, server identity, CORS, or
// arbitrary proxy headers from the internal control-api boundary.
const FORWARDABLE_RESPONSE_HEADERS = [
'retry-after',
+ 'ratelimit',
+ 'ratelimit-policy',
'x-ratelimit-limit',
'x-ratelimit-remaining',
'x-ratelimit-reset',
@@ -84,6 +92,7 @@ export async function controlApiRequestWithStatus<T>(
authorization: `Bearer ${config.controlApiServiceToken}`,
'x-service-token': config.controlApiServiceName,
}
+ addExternalClientIdentity(headers)
if (options?.userSessionToken) {
headers['x-user-session-token'] = options.userSessionToken
}
@@ -165,6 +174,7 @@ export async function controlApiBinaryRequestWithStatus(
authorization: `Bearer ${config.controlApiServiceToken}`,
'x-service-token': config.controlApiServiceName,
}
+ addExternalClientIdentity(headers)
if (options?.userSessionToken) {
headers['x-user-session-token'] = options.userSessionToken
}
@@ -212,12 +222,14 @@ export async function controlApiStreamRequest(
userSessionToken?: string
extraHeaders?: Record<string, string>
signal?: AbortSignal
+ throwOnHttpError?: boolean
}
): Promise<Response> {
const headers: Record<string, string> = {
authorization: `Bearer ${config.controlApiServiceToken}`,
'x-service-token': config.controlApiServiceName,
}
+ addExternalClientIdentity(headers)
if (options?.userSessionToken) {
headers['x-user-session-token'] = options.userSessionToken
}
@@ -230,7 +242,7 @@ export async function controlApiStreamRequest(
headers,
signal: options?.signal,
})
- if (!response.ok) {
+ if (!response.ok && options?.throwOnHttpError !== false) {
let parsed: unknown = null
const raw = await readResponseText(response)
try {
@@ -268,6 +280,7 @@ export async function controlApiPassthroughGet(
headers: {
authorization: `Bearer ${config.controlApiServiceToken}`,
'x-service-token': config.controlApiServiceName,
+ ...(currentExternalClientIp() ? { 'x-external-client-ip': currentExternalClientIp()! } : {}),
},
})
return {
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 04e6ebd44..4677676c6 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.66',
+ externalRestApiVersion: '0.1.73',
rpcProxyVersion: '0.1.64',
desktopVersion: '0.7.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/requestContext.ts b/external-rest-api/src/requestContext.ts
new file mode 100644
index 000000000..7ae81774c
--- /dev/null
+++ b/external-rest-api/src/requestContext.ts
@@ -0,0 +1,20 @@
+import type { NextFunction, Request } from 'express'
+import { AsyncLocalStorage } from 'node:async_hooks'
+import { isIP } from 'node:net'
+
+type ExternalRequestContext = { clientIp: string | null }
+const storage = new AsyncLocalStorage<ExternalRequestContext>()
+
+function trustedClientIp(req: Request): string | null {
+ const ip = req.ip?.trim() || req.socket.remoteAddress?.trim() || ''
+ return ip && isIP(ip) !== 0 ? ip : null
+}
+
+/** Install the proxy-attested client identity for every external-rest route. */
+export function withExternalRequestContext(req: Request, _res: unknown, next: NextFunction): void {
+ storage.run({ clientIp: trustedClientIp(req) }, next)
+}
+
+export function currentExternalClientIp(): string | null {
+ return storage.getStore()?.clientIp ?? null
+}
diff --git a/external-rest-api/src/routes/contextSharedFilesystems.ts b/external-rest-api/src/routes/contextSharedFilesystems.ts
index 4c65163d5..d5b6f25cd 100644
--- a/external-rest-api/src/routes/contextSharedFilesystems.ts
+++ b/external-rest-api/src/routes/contextSharedFilesystems.ts
@@ -1,7 +1,6 @@
import type { NextFunction, Response } from 'express'
import { Router } from 'express'
-import { config } from '../config.js'
-import { ControlApiError, controlApiRequest } from '../controlApiClient.js'
+import { ControlApiError, controlApiRequest, controlApiStreamRequest } from '../controlApiClient.js'
import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'
/**
@@ -23,6 +22,15 @@ export type ContextSharedFilesystemSummary = {
}
const PROPAGATED_STATUSES = new Set([400, 403, 404, 409, 410, 422])
+const PASSTHROUGH_HEADERS = [
+ 'retry-after',
+ 'ratelimit',
+ 'ratelimit-policy',
+ 'x-ratelimit-limit',
+ 'x-ratelimit-remaining',
+ 'x-ratelimit-reset',
+ 'x-request-id',
+] as const
function forwardControlApiError(error: unknown, res: Response, next: NextFunction): void {
if (error instanceof ControlApiError && PROPAGATED_STATUSES.has(error.status)) {
@@ -77,21 +85,21 @@ export function createContextSharedFilesystemsRouter(): Router {
const idx = req.originalUrl.indexOf('?')
return idx === -1 ? '' : req.originalUrl.slice(idx)
})()
- const target =
- `${config.controlApiBaseUrl.replace(/\/+$/, '')}` +
+ const upstreamRes = await controlApiStreamRequest(
+ 'GET',
`/external/contexts/${encodeURIComponent(req.params.contextId)}` +
- `/shared-filesystems/${encodeURIComponent(req.params.sfsName)}/proxy${subPath}${queryString}`
-
- const upstreamRes = await fetch(target, {
- method: req.method,
- headers: {
- authorization: `Bearer ${config.controlApiServiceToken}`,
- 'x-service-token': config.controlApiServiceName,
- 'x-user-session-token': sessionToken,
- },
- })
+ `/shared-filesystems/${encodeURIComponent(req.params.sfsName)}/proxy${subPath}${queryString}`,
+ {
+ userSessionToken: sessionToken,
+ throwOnHttpError: false,
+ }
+ )
res.status(upstreamRes.status)
+ for (const name of PASSTHROUGH_HEADERS) {
+ const value = upstreamRes.headers.get(name)
+ if (value) res.setHeader(name, value)
+ }
const ct = upstreamRes.headers.get('content-type')
if (ct) res.setHeader('content-type', ct)
const cd = upstreamRes.headers.get('content-disposition')
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index 9542648a5..79ed37cdc 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -28,6 +28,8 @@ const PROPAGATED = new Set([400, 401, 403, 404, 409, 410, 412, 422, 429, 500, 50
const STREAM_HEADERS = ['content-type', 'content-length', 'content-disposition']
const CONTROL_API_ERROR_HEADERS = [
'retry-after',
+ 'ratelimit',
+ 'ratelimit-policy',
'x-ratelimit-limit',
'x-ratelimit-remaining',
'x-ratelimit-reset',
diff --git a/external-rest-api/test/controlApiClient.test.ts b/external-rest-api/test/controlApiClient.test.ts
index 07d8625b2..cfde01db1 100644
--- a/external-rest-api/test/controlApiClient.test.ts
+++ b/external-rest-api/test/controlApiClient.test.ts
@@ -2,9 +2,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
ControlApiError,
controlApiBinaryRequestWithStatus,
+ controlApiRequest,
controlApiRequestWithStatus,
controlApiStreamRequest,
} from '../src/controlApiClient.js'
+import { withExternalRequestContext } from '../src/requestContext.js'
const ALLOWED_HEADERS = {
'retry-after': '17',
@@ -58,3 +60,36 @@ describe('controlApiClient error headers', () => {
expect(error.headers).not.toHaveProperty('x-internal-debug')
})
})
+
+describe('controlApiClient request identity', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('forwards the proxy-attested client IP on non-GFS control-api calls', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 }))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await new Promise<void>((resolve, reject) => {
+ withExternalRequestContext(
+ {
+ ip: '203.0.113.41',
+ socket: { remoteAddress: '10.0.0.10' },
+ } as never,
+ {},
+ () => {
+ void controlApiRequest('GET', '/external/members')
+ .then(() => resolve())
+ .catch(reject)
+ }
+ )
+ })
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'x-external-client-ip': '203.0.113.41' }),
+ })
+ )
+ })
+})
diff --git a/external-rest-api/test/routes.contextSharedFilesystems.test.ts b/external-rest-api/test/routes.contextSharedFilesystems.test.ts
index 91e8f4922..65cff7471 100644
--- a/external-rest-api/test/routes.contextSharedFilesystems.test.ts
+++ b/external-rest-api/test/routes.contextSharedFilesystems.test.ts
@@ -9,6 +9,7 @@ const authTokenMock = vi.hoisted(() => ({
const controlApiClientMock = vi.hoisted(() => ({
controlApiRequest: vi.fn(),
+ controlApiStreamRequest: vi.fn(),
}))
vi.mock('../src/authToken.js', () => authTokenMock)
@@ -43,6 +44,7 @@ function buildApp() {
beforeEach(() => {
authTokenMock.verifyToken.mockReset()
controlApiClientMock.controlApiRequest.mockReset()
+ controlApiClientMock.controlApiStreamRequest.mockReset()
})
describe('GET /me/contexts/:contextId/shared-filesystems', () => {
@@ -99,4 +101,47 @@ describe('Method gating', () => {
}
expect(controlApiClientMock.controlApiRequest).not.toHaveBeenCalled()
})
+
+ it('uses the identity-aware stream client for proxy reads', async () => {
+ authTokenMock.verifyToken.mockReturnValue(claims)
+ controlApiClientMock.controlApiStreamRequest.mockResolvedValue(
+ new Response('file-data', {
+ status: 200,
+ headers: { 'content-type': 'application/octet-stream' },
+ })
+ )
+
+ const res = await request(buildApp())
+ .get('/me/contexts/ctx-a/shared-filesystems/team-mission/proxy/files?download=1')
+ .set('authorization', 'Bearer good-token')
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual(Buffer.from('file-data'))
+ expect(controlApiClientMock.controlApiStreamRequest).toHaveBeenCalledWith(
+ 'GET',
+ '/external/contexts/ctx-a/shared-filesystems/team-mission/proxy/files?download=1',
+ { userSessionToken: 'good-token', throwOnHttpError: false }
+ )
+ })
+
+ it('preserves upstream error status, body, and retry headers for proxy reads', async () => {
+ authTokenMock.verifyToken.mockReturnValue(claims)
+ controlApiClientMock.controlApiStreamRequest.mockResolvedValue(
+ new Response(JSON.stringify({ error: 'forbidden' }), {
+ status: 429,
+ headers: {
+ 'content-type': 'application/json',
+ 'retry-after': '7',
+ },
+ })
+ )
+
+ const res = await request(buildApp())
+ .get('/me/contexts/ctx-a/shared-filesystems/team-mission/proxy/files')
+ .set('authorization', 'Bearer good-token')
+
+ expect(res.status).toBe(429)
+ expect(res.body).toEqual({ error: 'forbidden' })
+ expect(res.headers['retry-after']).toBe('7')
+ })
})
diff --git a/gfs-controller/src/authz/dbAuditSink.test.ts b/gfs-controller/src/authz/dbAuditSink.test.ts
index e855e8293..638d536f2 100644
--- a/gfs-controller/src/authz/dbAuditSink.test.ts
+++ b/gfs-controller/src/authz/dbAuditSink.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
+import { createHash } from "node:crypto";
import { AuditEvent, DbAuditSink, Queryable } from "./audit";
class AuditDb implements Queryable {
@@ -104,6 +105,48 @@ describe("DbAuditSink", () => {
]);
});
+ it("uses a deterministic hash that changes when only actor attribution changes", async () => {
+ const ordinary = new AuditDb();
+ const linked = new AuditDb();
+ await new DbAuditSink(ordinary).record({
+ ...directDecision,
+ subject: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ authoritySource: "user-session",
+ });
+ await new DbAuditSink(linked).record({
+ ...directDecision,
+ subject: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ actorOnBehalfOf: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ authoritySource: "linked-admin",
+ });
+
+ const expected = createHash("sha256")
+ .update(
+ JSON.stringify([
+ "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "linked-admin",
+ "read",
+ "gfs://main/resource-id",
+ "allow",
+ null,
+ "req-7",
+ "authorization_decision",
+ "agent:reader-1",
+ "direct_grant",
+ null,
+ null,
+ ])
+ )
+ .digest("hex");
+
+ expect(linked.values[6]).toBe(expected);
+ expect(linked.values[6]).not.toBe(ordinary.values[6]);
+ });
+
it("rejects a non-UUID Desktop actor before reaching the UUID audit cast", async () => {
const db = new AuditDb();
await expect(
diff --git a/gfs-controller/src/authz/subjectResolver.test.ts b/gfs-controller/src/authz/subjectResolver.test.ts
index 8ad250b42..3d8ff2799 100644
--- a/gfs-controller/src/authz/subjectResolver.test.ts
+++ b/gfs-controller/src/authz/subjectResolver.test.ts
@@ -8,6 +8,7 @@ import { SubjectsDb, resolveAuthzContext } from "./subjectResolver";
*/
function fakeDb(opts: {
operators?: Set<string>;
+ adminGenerations?: Record<string, number | string>;
teamsByUser?: Record<string, string[]>;
users?: Record<string, { lifecycle_state?: string; lifecycle_version?: number | string }>;
links?: Array<{
@@ -20,6 +21,7 @@ function fakeDb(opts: {
calls: string[];
} {
const operators = opts.operators ?? new Set<string>();
+ const adminGenerations = opts.adminGenerations ?? {};
const teamsByUser = opts.teamsByUser ?? {};
const users = opts.users ?? {};
const links = opts.links ?? [];
@@ -44,7 +46,9 @@ function fakeDb(opts: {
if (text.includes("control_admin_users")) {
const id = String(values?.[0]);
return {
- rows: operators.has(id) ? [{ id, status: "active", session_version: 1 }] : [],
+ rows: operators.has(id)
+ ? [{ id, status: "active", session_version: adminGenerations[id] ?? 1 }]
+ : [],
};
}
if (text.includes("team_members")) {
@@ -106,6 +110,23 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
expect(db.calls.some((q) => q.includes("team_members"))).toBe(false);
});
+ it("denies a stale direct control-admin bearer after the admin session epoch changes", async () => {
+ const adminId = "12121212-1212-4121-8121-121212121212";
+ const db = fakeDb({
+ operators: new Set([adminId]),
+ adminGenerations: { [adminId]: 2 },
+ });
+
+ await expect(
+ resolveAuthzContext(db, {
+ sub: adminId,
+ drive: "main",
+ principalType: "control-admin",
+ authGeneration: 1,
+ })
+ ).rejects.toThrow("control admin is not active");
+ });
+
it("keeps an unmarked colliding UUID on the conservative user path", async () => {
const collidingId = "88888888-8888-4888-8888-888888888888";
const db = fakeDb({
@@ -359,6 +380,41 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =
).rejects.toThrow("linked Desktop operator generation is not active");
});
+ it("denies a linked-admin bearer when the control-admin session epoch is stale", async () => {
+ const desktopUserId = "abababab-abab-4aba-8aba-abababababab";
+ const controlAdminId = "bcbcbcbc-bcbc-4bcb-8bcb-bcbcbcbcbcbc";
+ const db = fakeDb({
+ operators: new Set([controlAdminId]),
+ adminGenerations: { [controlAdminId]: 2 },
+ users: { [desktopUserId]: { lifecycle_state: "active", lifecycle_version: "1" } },
+ links: [
+ {
+ user_id: desktopUserId,
+ control_admin_id: controlAdminId,
+ lineage_id: "cdcdcdcd-cdcd-4cdc-8dcd-cdcdcdcdcdcd",
+ generation: "1",
+ },
+ ],
+ });
+
+ await expect(
+ resolveAuthzContext(db, {
+ sub: controlAdminId,
+ drive: "main",
+ principalType: "control-admin",
+ authGeneration: 1,
+ brokeredAuthority: {
+ desktopUserId,
+ controlAdminId,
+ authoritySource: "linked-admin",
+ linkLineageId: "cdcdcdcd-cdcd-4cdc-8dcd-cdcdcdcdcdcd",
+ linkGeneration: 1,
+ desktopUserGeneration: 1,
+ },
+ })
+ ).rejects.toThrow("linked admin is not active");
+ });
+
it("denies a linked-admin bearer when the Desktop user is retired even if the admin remains active", async () => {
const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";