Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): accept only canonical decimal integers in env settings
Alfredo Lopezbd43979a9fdd
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex e09311723..8090d616a 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.616",+ "version": "0.1.617","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.616",+ "version": "0.1.617","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 9e41085c9..9e658aedb 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.616",+ "version": "0.1.617","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.tsindex 5690aabb2..8e96800f9 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -190,6 +190,7 @@ type Config = {approvalRlExternalClientIpPerMin: numberoauthBrokerRlPerMin: numberadminPublicTokenRlPerMin: number+ adminPublicTokenIpRlPerMin: number// Plugin Workload SDK platform rate limits (issue #348): per-minute// ceilings on the plugin abuse surface (data-path + pre-auth). Platform// protection, not per-service business quotas — usage/cost stays governed@@ -388,12 +389,17 @@ function requiredOrDevDefault(name: string, devDefault: string): string {return required(name)}+// Canonical decimal text only. Number() alone also reads '0x5A', '90.0', '9e1',+// ' 90' and '+90' as 90, which boots with a value the operator never wrote.+const CANONICAL_POSITIVE_INTEGER = /^[1-9]\d*$/+const CANONICAL_NON_NEGATIVE_INTEGER = /^(0|[1-9]\d*)$/+function positiveIntegerFromEnv(name: string, defaultValue: number): number {const raw = process.env[name]if (raw === undefined || raw.trim() === '') return defaultValueconst value = Number(raw)- if (!Number.isSafeInteger(value) || value < 1) {+ if (!CANONICAL_POSITIVE_INTEGER.test(raw) || !Number.isSafeInteger(value)) {throw new Error(`${name} must be a positive integer`)}return value@@ -409,7 +415,7 @@ function nonNegativeIntegerFromEnv(name: string, defaultValue: number): number {const raw = process.env[name]if (raw === undefined || raw.trim() === '') return defaultValueconst value = Number(raw)- if (!Number.isSafeInteger(value) || value < 0) {+ if (!CANONICAL_NON_NEGATIVE_INTEGER.test(raw) || !Number.isSafeInteger(value)) {throw new Error(`${name} must be a non-negative integer`)}return value@@ -478,6 +484,8 @@ const EXTERNAL_GFS_PROXY_READ_RL_PER_MIN_CEILING = 960const EXTERNAL_GFS_GRANTS_READ_RL_PER_MIN_CEILING = 480const EXTERNAL_GFS_SHARES_READ_RL_PER_MIN_CEILING = 480const EXTERNAL_GFS_OPERATION_RL_PER_MIN_CEILING = 180+// 100 requests per second from one source on one public admin route.+const ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN_CEILING = 6_000function normalizePem(value: string): string {return value.replace(/\\n/g, '\n').trim()@@ -993,7 +1001,19 @@ export const config: Config = {// crossed values are preserved after the boot advisory above.approvalRlExternalClientIpPerMin: externalRateLimitConfig.clientIp,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),+ // The public control-admin token routes (password reset, invitation, email+ // confirmation) have two buckets per route. The first keys on source IP and+ // the submitted value (email, login or token prefix): one person retrying.+ // The second keys on source IP alone and caps value rotation from one+ // source. Many admins can share one public IP (a corporate VPN egress, an+ // office NAT), so the IP ceiling is 15x the per-value one, and a request the+ // per-value bucket refuses is not charged to the IP bucket.+ adminPublicTokenRlPerMin: positiveIntegerFromEnv('CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN', 20),+ adminPublicTokenIpRlPerMin: boundedIntegerFromEnv(+ 'CONTROL_API_ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN',+ 300,+ ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN_CEILING+ ),// Plugin Workload SDK platform rate limits (issue #348). Parsed via// positiveIntegerFromEnv so invalid operator config (non-integer, zero,// negative) fails loud at boot instead of running with NaN limits, which@@ -1299,6 +1319,28 @@ assertExternalGfsBudgetInvariants({ipPerMin: config.externalGfsIpRlPerMin,})+/**+ * A per-IP ceiling below the per-value limit would let one shared IP (an+ * office, a VPN egress) be refused before a single admin on it reached their+ * own limit, so that combination is refused at boot.+ */+export function assertAdminPublicTokenBudgetInvariants(budgets: {+ perValuePerMin: number+ perIpPerMin: number+}): void {+ if (budgets.perIpPerMin < budgets.perValuePerMin) {+ throw new Error(+ `CONTROL_API_ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN (${budgets.perIpPerMin}) must not be below ` ++ `CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN (${budgets.perValuePerMin})`+ )+ }+}++assertAdminPublicTokenBudgetInvariants({+ perValuePerMin: config.adminPublicTokenRlPerMin,+ perIpPerMin: config.adminPublicTokenIpRlPerMin,+})+// Namespace config validation: fail fast if any namespace is empty.// Empty namespace would target the K8s default namespace — a silent security gap.const NAMESPACE_KEYS: (keyof Config)[] = [diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex 5ceb8076d..9a6e8de87 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -137,14 +137,15 @@ export const RATE_LIMIT_POOL_SESSION_OPTIONS = '-c synchronous_commit=off'/*** Unset (or empty) means the default. A set value outside `[min, max]`, or one- * that is not an integer, stops startup instead of silently becoming the- * default.+ * that is not canonical decimal integer text, stops startup instead of+ * silently becoming the default. Number() alone would also read '6.0', '0x6',+ * '6e0' and ' 6' as 6.*/function boundedEnvInteger(name: string, fallback: number, min: number, max: number): number {const raw = process.env[name]if (!raw) return fallbackconst value = Number(raw)- if (!Number.isInteger(value) || value < min || value > max) {+ if (!/^(0|[1-9]\d*)$/.test(raw) || value < min || value > max) {throw new Error(`${name} must be an integer in [${min}, ${max}], got ${JSON.stringify(raw)}`)}return valuediff --git a/control-api/test/config.adminPublicTokenBudgets.test.ts b/control-api/test/config.adminPublicTokenBudgets.test.tsnew file mode 100644index 000000000..61fe031af--- /dev/null+++ b/control-api/test/config.adminPublicTokenBudgets.test.ts@@ -0,0 +1,70 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++/**+ * The public control-admin token routes have a per-value bucket and a per-IP+ * bucket. The per-IP ceiling exists for value rotation from one source; it+ * must stay wide enough for many admins behind one shared public IP.+ */++const PER_VALUE_ENV = 'CONTROL_API_ADMIN_PUBLIC_TOKEN_RL_PER_MIN'+const PER_IP_ENV = 'CONTROL_API_ADMIN_PUBLIC_TOKEN_IP_RL_PER_MIN'+const ENV_KEYS = [PER_VALUE_ENV, PER_IP_ENV]++async function loadConfigWith(env: Partial<Record<string, string>>) {+ const originalValues = new Map(ENV_KEYS.map(key => [key, process.env[key]]))+ for (const key of ENV_KEYS) delete process.env[key]+ for (const [key, value] of Object.entries(env)) process.env[key] = value+ vi.resetModules()+ try {+ return await import('../src/config.js')+ } finally {+ for (const key of ENV_KEYS) {+ const original = originalValues.get(key)+ if (original === undefined) delete process.env[key]+ else process.env[key] = original+ }+ }+}++describe('public control-admin token budgets', () => {+ afterEach(() => {+ vi.resetModules()+ })++ it('defaults to 20 per value and 300 per IP', async () => {+ const { config } = await loadConfigWith({})+ expect(config.adminPublicTokenRlPerMin).toBe(20)+ expect(config.adminPublicTokenIpRlPerMin).toBe(300)+ })++ it('reads both values from the environment', async () => {+ const { config } = await loadConfigWith({ [PER_VALUE_ENV]: '10', [PER_IP_ENV]: '600' })+ expect(config.adminPublicTokenRlPerMin).toBe(10)+ expect(config.adminPublicTokenIpRlPerMin).toBe(600)+ })++ // Number() read '0x14' as 20 and 'twenty' as NaN; a NaN limit refuses every request.+ it.each([+ [PER_VALUE_ENV, '0x14', `${PER_VALUE_ENV} must be a positive integer`],+ [PER_VALUE_ENV, 'twenty', `${PER_VALUE_ENV} must be a positive integer`],+ [PER_VALUE_ENV, '0', `${PER_VALUE_ENV} must be a positive integer`],+ [PER_IP_ENV, '300.0', `${PER_IP_ENV} must be a positive integer`],+ [PER_IP_ENV, '6001', `${PER_IP_ENV} must be an integer between 1 and 6000`],+ ])('refuses %s=%j at startup', async (name, value, message) => {+ await expect(loadConfigWith({ [name]: value })).rejects.toThrow(message)+ })++ it('accepts the per-IP ceiling itself', async () => {+ const { config } = await loadConfigWith({ [PER_IP_ENV]: '6000' })+ expect(config.adminPublicTokenIpRlPerMin).toBe(6000)+ })++ it('refuses a per-IP ceiling below the per-value limit, and accepts an equal one', async () => {+ await expect(loadConfigWith({ [PER_VALUE_ENV]: '50', [PER_IP_ENV]: '40' })).rejects.toThrow(+ `${PER_IP_ENV} (40) must not be below ${PER_VALUE_ENV} (50)`+ )++ const { config } = await loadConfigWith({ [PER_VALUE_ENV]: '50', [PER_IP_ENV]: '50' })+ expect(config.adminPublicTokenIpRlPerMin).toBe(50)+ })+})diff --git a/control-api/test/config.canonicalIntegerEnv.test.ts b/control-api/test/config.canonicalIntegerEnv.test.tsnew file mode 100644index 000000000..325194f98--- /dev/null+++ b/control-api/test/config.canonicalIntegerEnv.test.ts@@ -0,0 +1,91 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++/**+ * Integer settings accept only canonical decimal text. `Number()` alone also+ * reads '0x5A', '90.0', '9e1', ' 90' and '+90' as 90, so a typo or a templated+ * value would boot with a number the operator never wrote. One variable per+ * parser: positiveIntegerFromEnv, boundedIntegerFromEnv (and every parser+ * built on positiveIntegerFromEnv), nonNegativeIntegerFromEnv.+ */++type IntegerField =+ | 'userApprovalRequestArchiveBatchSize'+ | 'externalGfsOperationRlPerMin'+ | 'llmCatalogSyncProviderMinLive'++const CASES: Array<{+ parser: string+ env: string+ field: IntegerField+ accepted: Array<[string, number]>+ message: string+}> = [+ {+ parser: 'positiveIntegerFromEnv',+ env: 'APPROVAL_ARCHIVE_BATCH_SIZE',+ field: 'userApprovalRequestArchiveBatchSize',+ accepted: [+ ['90', 90],+ ['1', 1],+ ],+ message: 'APPROVAL_ARCHIVE_BATCH_SIZE must be a positive integer',+ },+ {+ parser: 'boundedIntegerFromEnv',+ env: 'CONTROL_API_EXTERNAL_GFS_OPERATION_RL_PER_MIN',+ field: 'externalGfsOperationRlPerMin',+ accepted: [+ ['90', 90],+ ['1', 1],+ ],+ message: 'CONTROL_API_EXTERNAL_GFS_OPERATION_RL_PER_MIN must be a positive integer',+ },+ {+ parser: 'nonNegativeIntegerFromEnv',+ env: 'LLM_CATALOG_SYNC_PROVIDER_MIN_LIVE',+ field: 'llmCatalogSyncProviderMinLive',+ accepted: [+ ['90', 90],+ ['0', 0],+ ],+ message: 'LLM_CATALOG_SYNC_PROVIDER_MIN_LIVE must be a non-negative integer',+ },+]++// Each reads as a valid integer through Number().+const NON_CANONICAL = ['0x5A', '90.0', '9e1', ' 90', '90 ', '+90', '090', '9007199254740993']++const ENV_KEYS = CASES.map(testCase => testCase.env)++async function loadConfigWith(name: string, value: string) {+ const originalValues = new Map(ENV_KEYS.map(key => [key, process.env[key]]))+ for (const key of ENV_KEYS) delete process.env[key]+ process.env[name] = value+ vi.resetModules()+ try {+ return await import('../src/config.js')+ } finally {+ for (const key of ENV_KEYS) {+ const original = originalValues.get(key)+ if (original === undefined) delete process.env[key]+ else process.env[key] = original+ }+ }+}++describe('canonical integer environment values', () => {+ afterEach(() => {+ vi.resetModules()+ })++ describe.each(CASES)('$parser ($env)', testCase => {+ it.each(testCase.accepted)('accepts %j as %d', async (value, expected) => {+ const { config } = await loadConfigWith(testCase.env, value)+ expect(config[testCase.field]).toBe(expected)+ })++ it.each(NON_CANONICAL)('refuses %j at startup', async value => {+ await expect(loadConfigWith(testCase.env, value)).rejects.toThrow(testCase.message)+ })+ })+})diff --git a/control-api/test/db.poolFactory.test.ts b/control-api/test/db.poolFactory.test.tsindex e22c5e739..d2ca8309b 100644--- a/control-api/test/db.poolFactory.test.ts+++ b/control-api/test/db.poolFactory.test.ts@@ -116,6 +116,13 @@ describe('rate limiter Postgres pool', () => {['RATE_LIMIT_POOL_CONNECTION_TIMEOUT_MS', '99', '[100, 30000]', 1],['RATE_LIMIT_POOL_STATEMENT_TIMEOUT_MS', '30001', '[100, 30000]', 1],['RATE_LIMIT_POOL_MAX', '6.5', '[1, 16]', 1],+ // Number() reads each of these as 6; only canonical decimal is accepted.+ ['RATE_LIMIT_POOL_MAX', '6.0', '[1, 16]', 1],+ ['RATE_LIMIT_POOL_MAX', '0x6', '[1, 16]', 1],+ ['RATE_LIMIT_POOL_MAX', '6e0', '[1, 16]', 1],+ ['RATE_LIMIT_POOL_MAX', ' 6', '[1, 16]', 1],+ ['RATE_LIMIT_POOL_MAX', '+6', '[1, 16]', 1],+ ['RATE_LIMIT_POOL_MAX', '06', '[1, 16]', 1],['CORE_POOL_MAX', 'twelve', '[1, 64]', 0],['CORE_POOL_MAX', '65', '[1, 64]', 0],] as const)(