Skip to content

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

TypeScript

fix(config): tolerate independent external rate limit overrides

Alfredo Lopez387b6a1e5b37
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 55d9289fc..6126190d2 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.454",
+ "version": "0.1.455",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.454",
+ "version": "0.1.455",
"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 b93ab5c7c..1bb4bec0a 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.454",
+ "version": "0.1.455",
"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 c2cddcdc0..4c9a3259a 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -359,21 +359,47 @@ function parseRegistryConnectionMode(): 'managed' | 'self-hosted' {
throw new Error(`REGISTRY_CONNECTION_MODE must be 'managed' or 'self-hosted' (got '${raw}')`)
}
-// External routes intentionally have three independent dimensions: the
-// operation/user budget is the narrowest, the session edge budget is wider,
-// and the source-IP backstop is widest so a shared NAT cannot become a
-// platform-wide choke point. Reject an incoherent deployment at boot instead
-// of silently running with a different security/capacity contract.
+type ExternalRateLimitSource = 'default' | 'environment'
+
+function externalRateLimitSettingFromEnv(
+ name: string,
+ defaultValue: number
+): { value: number; source: ExternalRateLimitSource } {
+ const raw = process.env[name]
+ return {
+ value: positiveIntegerFromEnv(name, defaultValue),
+ source: raw === undefined || raw.trim() === '' ? 'default' : 'environment',
+ }
+}
+
+// External routes intentionally have three independent dimensions with
+// different scopes. operation <= session < clientIp is the recommended
+// capacity topology, but it is not a correctness invariant: an operator may
+// deliberately tune any one scope without changing the other two. Keep scalar
+// values fail-closed, preserve exact overrides, and make a crossed topology an
+// actionable boot advisory instead of a service-startup failure.
const externalRateLimitConfig = (() => {
- const operation = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_PER_MIN', 60)
- const session = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', 120)
- const clientIp = positiveIntegerFromEnv('APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN', 1200)
- if (!(operation <= session && session < clientIp)) {
- throw new Error(
- 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
+ const operation = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_PER_MIN', 60)
+ const session = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', 120)
+ const clientIp = externalRateLimitSettingFromEnv('APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN', 1200)
+ const followsRecommendedTopology =
+ operation.value <= session.value && session.value < clientIp.value
+
+ if (!followsRecommendedTopology) {
+ console.warn(
+ '[ControlAPI] External rate-limit configuration crosses the recommended operation <= session < clientIp topology; preserving exact configured values',
+ {
+ resolved: { operation, session, clientIp },
+ recommendedTopology: 'operation <= session < clientIp',
+ }
)
}
- return { operation, session, clientIp }
+
+ return {
+ operation: operation.value,
+ session: session.value,
+ clientIp: clientIp.value,
+ }
})()
function failClosedBooleanFromEnv(name: string): boolean {
diff --git a/control-api/test/config.approvalRateLimit.test.ts b/control-api/test/config.approvalRateLimit.test.ts
index da37c216a..b0507dc27 100644
--- a/control-api/test/config.approvalRateLimit.test.ts
+++ b/control-api/test/config.approvalRateLimit.test.ts
@@ -32,6 +32,7 @@ async function loadConfigWith(
describe('control-api approval rate limit config', () => {
afterEach(() => {
vi.resetModules()
+ vi.restoreAllMocks()
})
it('defaults approval request rate limit to multi-agent channel-reader capacity', async () => {
@@ -48,43 +49,124 @@ describe('control-api approval rate limit config', () => {
expect(config.approvalRlRequestPerMin).toBe(30)
})
- it('keeps the external client IP backstop wider than the session edge bucket', async () => {
+ it('uses the recommended external defaults without a boot advisory', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const config = await loadConfigWith({})
+ expect(config.approvalRlExternalPerMin).toBe(60)
expect(config.approvalRlExternalEdgePerMin).toBe(120)
expect(config.approvalRlExternalClientIpPerMin).toBe(1200)
- expect(config.approvalRlExternalClientIpPerMin).toBeGreaterThan(
- config.approvalRlExternalEdgePerMin
- )
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ {
+ label: 'operation above the default session budget',
+ override: { APPROVAL_RL_EXTERNAL_PER_MIN: '121' },
+ expected: [121, 120, 1200],
+ },
+ {
+ label: 'session equal to the default client-IP budget',
+ override: { APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '1200' },
+ expected: [60, 1200, 1200],
+ },
+ {
+ label: 'client-IP equal to the default session budget',
+ override: { APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '120' },
+ expected: [60, 120, 120],
+ },
+ {
+ label: 'session below the default operation budget',
+ override: { APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '30' },
+ expected: [60, 30, 1200],
+ },
+ ])('boots with and preserves a partial override: $label', async ({ override, expected }) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const config = await loadConfigWith(override)
+
+ expect([
+ config.approvalRlExternalPerMin,
+ config.approvalRlExternalEdgePerMin,
+ config.approvalRlExternalClientIpPerMin,
+ ]).toEqual(expected)
+ expect(warn).toHaveBeenCalledTimes(1)
})
- it('rejects malformed external rate-limit configuration at startup', async () => {
- await expect(loadConfigWith({ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '0' })).rejects.toThrow(
- 'APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN must be a positive integer'
+ it('accepts equality and reversed scopes while preserving every explicit value', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const config = await loadConfigWith({
+ APPROVAL_RL_EXTERNAL_PER_MIN: '500',
+ APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '120',
+ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '120',
+ })
+
+ expect(config.approvalRlExternalPerMin).toBe(500)
+ expect(config.approvalRlExternalEdgePerMin).toBe(120)
+ expect(config.approvalRlExternalClientIpPerMin).toBe(120)
+ expect(warn).toHaveBeenCalledTimes(1)
+ })
+
+ it('warns once with the resolved tuple and source without mutating values', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const config = await loadConfigWith({ APPROVAL_RL_EXTERNAL_PER_MIN: '121' })
+
+ expect(config.approvalRlExternalPerMin).toBe(121)
+ expect(config.approvalRlExternalEdgePerMin).toBe(120)
+ expect(config.approvalRlExternalClientIpPerMin).toBe(1200)
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('preserving exact configured values'),
+ {
+ resolved: {
+ operation: { value: 121, source: 'environment' },
+ session: { value: 120, source: 'default' },
+ clientIp: { value: 1200, source: 'default' },
+ },
+ recommendedTopology: 'operation <= session < clientIp',
+ }
)
})
- it('rejects an incoherent external limiter hierarchy at startup', async () => {
- await expect(
- loadConfigWith({
- APPROVAL_RL_EXTERNAL_PER_MIN: '60',
- APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '1200',
- APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '120',
- })
- ).rejects.toThrow(
- 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
+ it.each([
+ ['APPROVAL_RL_EXTERNAL_PER_MIN', '0'],
+ ['APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', '-1'],
+ ['APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN', '1.5'],
+ ['APPROVAL_RL_EXTERNAL_PER_MIN', 'not-a-number'],
+ ['APPROVAL_RL_EXTERNAL_EDGE_PER_MIN', '9007199254740992'],
+ ] as const)('rejects malformed scalar %s=%s at startup', async (key, value) => {
+ await expect(loadConfigWith({ [key]: value })).rejects.toThrow(
+ `${key} must be a positive integer`
)
})
- it('rejects an operation budget wider than the session budget', async () => {
- await expect(
- loadConfigWith({
- APPROVAL_RL_EXTERNAL_PER_MIN: '121',
- APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '120',
- APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '1200',
+ it.each(['', ' ', '\t'])(
+ 'treats a blank external rate-limit override (%j) as the default',
+ async blank => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const config = await loadConfigWith({
+ APPROVAL_RL_EXTERNAL_PER_MIN: blank,
+ APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: blank,
+ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: blank,
})
- ).rejects.toThrow(
- 'APPROVAL_RL_EXTERNAL_PER_MIN must be <= APPROVAL_RL_EXTERNAL_EDGE_PER_MIN < APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN'
- )
+
+ expect(config.approvalRlExternalPerMin).toBe(60)
+ expect(config.approvalRlExternalEdgePerMin).toBe(120)
+ expect(config.approvalRlExternalClientIpPerMin).toBe(1200)
+ expect(warn).not.toHaveBeenCalled()
+ }
+ )
+
+ it('does not warn for a coherent explicit topology', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const config = await loadConfigWith({
+ APPROVAL_RL_EXTERNAL_PER_MIN: '30',
+ APPROVAL_RL_EXTERNAL_EDGE_PER_MIN: '60',
+ APPROVAL_RL_EXTERNAL_CLIENT_IP_PER_MIN: '600',
+ })
+
+ expect(config.approvalRlExternalPerMin).toBe(30)
+ expect(config.approvalRlExternalEdgePerMin).toBe(60)
+ expect(config.approvalRlExternalClientIpPerMin).toBe(600)
+ expect(warn).not.toHaveBeenCalled()
})
})
diff --git a/control-api/test/middleware.externalSessionAuth.legacyToken.test.ts b/control-api/test/middleware.externalSessionAuth.legacyToken.test.ts
new file mode 100644
index 000000000..03729084e
--- /dev/null
+++ b/control-api/test/middleware.externalSessionAuth.legacyToken.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import jwt from 'jsonwebtoken'
+import { createPublicKey } from 'node:crypto'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { requireValidExternalSessionToken } from '../src/middleware/externalSessionAuth.js'
+import { verifyExternalSessionToken } from '../src/utils/auth/externalSessionAuthToken.js'
+
+const poolQuery = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => poolQuery(...args) },
+}))
+
+const sessionJwtPublicKey = createPublicKey(config.sessionJwtPrivateKey).export({
+ type: 'spki',
+ format: 'pem',
+})
+
+function legacySessionToken(): string {
+ return jwt.sign(
+ {
+ userId: '11111111-1111-4111-8111-111111111111',
+ email: '[email protected]',
+ teamId: null,
+ role: 'member',
+ },
+ config.sessionJwtPrivateKey,
+ {
+ algorithm: 'RS256',
+ expiresIn: 60 * 60,
+ issuer: config.jwtIssuer,
+ audience: config.jwtAudience,
+ }
+ )
+}
+
+function app() {
+ const server = express()
+ server.get('/protected', requireValidExternalSessionToken, (_req, res) => {
+ res.status(200).json({ ok: true })
+ })
+ return server
+}
+
+describe('external session legacy token cut-over', () => {
+ beforeEach(() => {
+ poolQuery.mockClear()
+ poolQuery.mockResolvedValue({
+ rows: [{ lifecycle_state: 'active', lifecycle_version: '1' }],
+ rowCount: 1,
+ })
+ })
+
+ it('rejects a valid RS256 legacy token that has no auth generation', async () => {
+ const token = legacySessionToken()
+
+ const cryptographicallyValidClaims = jwt.verify(token, sessionJwtPublicKey, {
+ algorithms: ['RS256'],
+ issuer: config.jwtIssuer,
+ audience: config.jwtAudience,
+ }) as jwt.JwtPayload
+ expect(cryptographicallyValidClaims.authGeneration).toBeUndefined()
+ expect(verifyExternalSessionToken(token)).toBeNull()
+
+ const response = await request(app()).get('/protected').set('x-user-session-token', token)
+
+ expect(response.status).toBe(401)
+ expect(response.body).toEqual({ error: 'Unauthorized' })
+ expect(poolQuery).not.toHaveBeenCalled()
+ })
+})
diff --git a/docs/architecture/gfs-desktop-operator-parity.md b/docs/architecture/gfs-desktop-operator-parity.md
index 742f93812..8aa7e3f46 100644
--- a/docs/architecture/gfs-desktop-operator-parity.md
+++ b/docs/architecture/gfs-desktop-operator-parity.md
@@ -66,12 +66,18 @@ header coherence are tracked as independent global follow-ups:
The non-GFS external directory, team, member, invitation, workflow, decision,
notification, and OAuth route families also retain two independent edge gates:
-the source-IP backstop is 1,200/min and the per-session fairness bucket is
-120/min; authenticated operation buckets remain at 60/min where the route
-defines them. The enforced hierarchy is `60 <= 120 < 1,200`. The IP gate is intentionally first, so rotating or malformed session
-tokens cannot evade the source-IP ceiling, while a shared NAT is not limited to
-the narrower per-session budget. These gates do not change the GFS
-read/mutation budgets above.
+the source-IP backstop defaults to 1,200/min and the per-session fairness
+bucket defaults to 120/min; authenticated operation buckets default to 60/min
+where the route defines them. These are independent scopes, not one global
+numeric hierarchy: an operator may override any value without making the
+Control API fail to boot, and the service preserves the exact positive integer
+provided. At startup, a crossed recommendation (`operation > session` or
+`session >= client-IP`) emits an advisory diagnostic because one bucket may
+dominate or become redundant; it never silently clamps the operator's value.
+The IP gate is intentionally first, so rotating or malformed session tokens
+cannot evade the source-IP ceiling, while a shared NAT is not limited to the
+narrower per-session budget. These gates do not change the GFS read/mutation
+budgets above.
## Migration sequence
@@ -105,6 +111,11 @@ using the external API directly must adopt this contract before upgrading; the
server does not synthesize an idempotency key because doing so would make a
retry non-deterministic and could duplicate a retirement side effect.
+This is a version-one contract change: a direct caller that omits either field
+receives `400` and must be upgraded before the new Control API is rolled out.
+The first generation-aware deployment likewise invalidates pre-existing session
+tokens without `authGeneration`; users must sign in once after the rollout.
+
## Validation surface
- Unit and integration suites cover setup, authority resolution, lifecycle
diff --git a/docs/deploy/production.md b/docs/deploy/production.md
index 59bbdd7cd..097dc2d74 100644
--- a/docs/deploy/production.md
+++ b/docs/deploy/production.md
@@ -60,6 +60,12 @@ kubectl apply -f ./charts/clerum-crds/crds/
`member-registration-service` instead and leave the mode `remote`.
11. **Observability** — metrics + log stack; alert on approval backlog and 5xx.
+For the generation-aware Desktop GFS rollout, read the [operator parity
+compatibility contract](../architecture/gfs-desktop-operator-parity.md#rollout-and-compatibility-contract)
+before upgrading. The first rollout intentionally requires one sign-in per
+existing external session, and direct callers of `DELETE /api/v1/members/:userId`
+must send both a non-empty `reason` and an `Idempotency-Key`.
+
Use [minikube.md](minikube.md) as the **order-of-operations reference** even when
the target is not minikube: the dependency graph is the same. One exception:
minikube's `127.0.0.1` UI defaults cannot use hosted member-registration mode,
diff --git a/external-rest-api/README.md b/external-rest-api/README.md
index a243109d9..9b242751c 100644
--- a/external-rest-api/README.md
+++ b/external-rest-api/README.md
@@ -23,6 +23,9 @@
- `GET /api/v1/team/members` - list team members
- `POST /api/v1/team/members/invite` - invite member (`admin/inviter`)
- `DELETE /api/v1/team/members/:userId` - remove member (`admin`)
+- `DELETE /api/v1/members/:userId` - retire a member account (`admin`); requires
+ JSON `{ "reason": "<non-empty>" }` and an `Idempotency-Key` header. Missing
+ fields return `400`; this is a breaking v1 contract for direct clients.
- `POST /api/v1/invitations/accept` - accept invitation after profile-ui sign-in
- `GET /api/v1/directory/search?q=...` - lookup directory users for channel mapping
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 660d39ec3..3f4fb19f6 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.77",
+ "version": "0.1.78",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.77",
+ "version": "0.1.78",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 714f06ede..22f4b0bbe 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.77",
+ "version": "0.1.78",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index ba6348093..7f3e1156e 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.77',
+ externalRestApiVersion: '0.1.78',
rpcProxyVersion: '0.1.64',
desktopVersion: '0.7.0',
minimumDesktopVersion: '0.1.252',