Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(api-keys): configurable default rate limits via DEFAULT_RATE_LIMIT_PER_DAY (#2266)
Gleb Peregud3ce114af4488
diff --git a/.env.example b/.env.exampleindex 9b52204332..eccc7f1bea 100644--- a/.env.example+++ b/.env.example@@ -137,6 +137,15 @@ ALLOW_API_KEY_REVEAL=false# Used by: src/lib/compliance/index.ts — suppresses logs for specific keys.# NO_LOG_API_KEY_IDS=key_abc123,key_def456+# Fallback per-day request budget applied to API keys whose `rate_limits`+# column is null. Default (unset/empty/malformed) preserves the legacy+# 1000/day, 5000/week, 20000/month windows so existing deployments do not+# silently lose rate limiting on upgrade.+# Set explicitly to "0" to opt out entirely (unlimited fallback). Any+# positive integer N enables N/day, 5N/week, 20N/month.+# Used by: src/shared/utils/apiKeyPolicy.ts — checkRateLimit() fallback.+# DEFAULT_RATE_LIMIT_PER_DAY=1000+# Maximum request body size in bytes (rejects larger payloads).# Used by: src/shared/middleware/bodySizeGuard.ts — prevents oversized uploads.# Default: 10485760 (10 MB)diff --git a/docs/reference/ENVIRONMENT.md b/docs/reference/ENVIRONMENT.mdindex b131d7505c..2fa87170e3 100644--- a/docs/reference/ENVIRONMENT.md+++ b/docs/reference/ENVIRONMENT.md@@ -147,17 +147,18 @@ OmniRoute uses **SQLite** (via `better-sqlite3`) for all persistence. These vari## 4. Security & Authentication-| Variable | Default | Source File | Description |-| --------------------------------------- | --------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `MACHINE_ID_SALT` | `endpoint-proxy-salt` | `src/lib/auth` | Salt combined with hardware identifiers for machine fingerprinting. Change per-deployment for isolation. |-| `AUTH_COOKIE_SECURE` | `false` | `src/lib/auth` | Sets the `Secure` flag on session cookies. **Must be `true`** when running behind HTTPS. |-| `REQUIRE_API_KEY` | `false` | API middleware | When `true`, all `/v1/*` proxy requests must include a valid API key. |-| `ALLOW_API_KEY_REVEAL` | `false` | Dashboard providers page | Allows revealing full API key values in the Dashboard UI. Security risk on shared instances. |-| `NO_LOG_API_KEY_IDS` | _(empty)_ | `src/lib/compliance/index.ts` | Comma-separated API key IDs that bypass request logging (GDPR compliance). |-| `MAX_BODY_SIZE_BYTES` | `10485760` (10 MB) | `src/shared/middleware/bodySizeGuard.ts` | Maximum allowed request body size. Rejects payloads exceeding this limit. |-| `CORS_ORIGIN` | `*` | Next.js middleware | CORS `Access-Control-Allow-Origin` value. Restrict for production. |-| `OUTBOUND_SSRF_GUARD_ENABLED` | `true` | `src/shared/network/outboundUrlGuard.ts` | Block provider calls targeting private/loopback/link-local IP ranges. Disable only in isolated test envs. |-| `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS` | `false` | `src/shared/network/outboundUrlGuard.ts` | Allow provider URLs pointing to private/local networks (localhost, 192.168.x.x, 10.x.x.x, etc.). **REQUIRED for self-hosted providers** (LM Studio, Ollama, vLLM, Llamafile, Triton, SearXNG). When `false`, the dashboard rejects validation of local URLs. |+| Variable | Default | Source File | Description |+| --------------------------------------- | --------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `MACHINE_ID_SALT` | `endpoint-proxy-salt` | `src/lib/auth` | Salt combined with hardware identifiers for machine fingerprinting. Change per-deployment for isolation. |+| `AUTH_COOKIE_SECURE` | `false` | `src/lib/auth` | Sets the `Secure` flag on session cookies. **Must be `true`** when running behind HTTPS. |+| `REQUIRE_API_KEY` | `false` | API middleware | When `true`, all `/v1/*` proxy requests must include a valid API key. |+| `ALLOW_API_KEY_REVEAL` | `false` | Dashboard providers page | Allows revealing full API key values in the Dashboard UI. Security risk on shared instances. |+| `NO_LOG_API_KEY_IDS` | _(empty)_ | `src/lib/compliance/index.ts` | Comma-separated API key IDs that bypass request logging (GDPR compliance). |+| `DEFAULT_RATE_LIMIT_PER_DAY` | `1000` | `src/shared/utils/apiKeyPolicy.ts` | Fallback per-day request budget applied to API keys whose `rate_limits` column is null. Default (unset/empty/malformed) keeps the legacy 1000/day, 5000/week, 20000/month windows. Set explicitly to `0` to opt out (unlimited). Any positive integer N enables N/day, 5N/week, 20N/month. Zod-validated; invalid values log a warning and use the legacy default. |+| `MAX_BODY_SIZE_BYTES` | `10485760` (10 MB) | `src/shared/middleware/bodySizeGuard.ts` | Maximum allowed request body size. Rejects payloads exceeding this limit. |+| `CORS_ORIGIN` | `*` | Next.js middleware | CORS `Access-Control-Allow-Origin` value. Restrict for production. |+| `OUTBOUND_SSRF_GUARD_ENABLED` | `true` | `src/shared/network/outboundUrlGuard.ts` | Block provider calls targeting private/loopback/link-local IP ranges. Disable only in isolated test envs. |+| `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS` | `false` | `src/shared/network/outboundUrlGuard.ts` | Allow provider URLs pointing to private/local networks (localhost, 192.168.x.x, 10.x.x.x, etc.). **REQUIRED for self-hosted providers** (LM Studio, Ollama, vLLM, Llamafile, Triton, SearXNG). When `false`, the dashboard rejects validation of local URLs. |### Hardening Checklistdiff --git a/src/shared/utils/apiKeyPolicy.ts b/src/shared/utils/apiKeyPolicy.tsindex c750f93361..81000b9695 100644--- a/src/shared/utils/apiKeyPolicy.ts+++ b/src/shared/utils/apiKeyPolicy.ts@@ -8,6 +8,7 @@* @module shared/utils/apiKeyPolicy*/+import { z } from "zod";import { extractApiKey } from "@/sse/services/auth";import { getApiKeyMetadata, isModelAllowedForKey } from "@/lib/localDb";import { checkBudget } from "@/domain/costRules";@@ -16,11 +17,68 @@ import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";import * as log from "@/sse/utils/logger";import { checkRateLimit, RateLimitRule } from "./rateLimiter";-const DEFAULT_RATE_LIMITS: RateLimitRule[] = [- { limit: 1000, window: 86400 }, // 1000 per day- { limit: 5000, window: 604800 }, // 5000 per week- { limit: 20000, window: 2592000 }, // 20000 per month-];+/**+ * Legacy default applied to API keys whose `rate_limits` column is null.+ * Kept as the secure-by-default fallback when DEFAULT_RATE_LIMIT_PER_DAY is+ * unset or malformed — going unlimited silently on an upgrade would expose+ * existing deployments to runaway cost / abuse from old, unconfigured keys.+ */+const LEGACY_DEFAULT_PER_DAY = 1000;++/**+ * Per Repository Style Guide rule 8, env input is validated through Zod+ * rather than `parseInt`. `parseInt("1000 requests", 10)` returns `1000`,+ * silently turning a config typo into a partial value — Zod rejects it.+ */+const DEFAULT_RATE_LIMIT_PER_DAY_SCHEMA = z.coerce.number().int().min(0);++/**+ * Build the fallback rate-limit rules applied to API keys whose+ * `rate_limits` column is null. Configurable via DEFAULT_RATE_LIMIT_PER_DAY:+ *+ * - unset / empty / malformed → 1000/day, 5000/week, 20000/month+ * (the legacy default; preserves existing behavior on upgrade).+ * - `0` (explicit opt-out) → empty rule set; `checkRateLimit()` short-+ * circuits empty input as allowed, so keys without an explicit limit+ * become effectively unlimited.+ * - any positive integer N → N/day, 5N/week, 20N/month.+ *+ * Exported for unit testing; production code should reference the+ * `DEFAULT_RATE_LIMITS` constant below.+ */+export function buildDefaultRateLimits(+ envValue = process.env.DEFAULT_RATE_LIMIT_PER_DAY+): RateLimitRule[] {+ const trimmed = (envValue ?? "").trim();+ let perDay: number;+ if (trimmed === "") {+ perDay = LEGACY_DEFAULT_PER_DAY;+ } else {+ const parsed = DEFAULT_RATE_LIMIT_PER_DAY_SCHEMA.safeParse(trimmed);+ if (!parsed.success) {+ // Malformed value — fall back to the legacy default rather than+ // silently going unlimited from a typo. The runtime cost of the+ // warning is paid once at module load.+ log.warn(+ "API_POLICY",+ `Invalid DEFAULT_RATE_LIMIT_PER_DAY=${JSON.stringify(envValue)}; ` ++ `falling back to ${LEGACY_DEFAULT_PER_DAY}/day. ` ++ `Set to "0" to explicitly disable the fallback.`+ );+ perDay = LEGACY_DEFAULT_PER_DAY;+ } else {+ perDay = parsed.data;+ }+ }+ if (perDay === 0) return [];+ return [+ { limit: perDay, window: 86400 },+ { limit: perDay * 5, window: 604800 },+ { limit: perDay * 20, window: 2592000 },+ ];+}++const DEFAULT_RATE_LIMITS: RateLimitRule[] = buildDefaultRateLimits();interface AccessSchedule {enabled: boolean;diff --git a/tests/unit/apikey-policy-default-rate-limits.test.ts b/tests/unit/apikey-policy-default-rate-limits.test.tsnew file mode 100644index 0000000000..d5d8622269--- /dev/null+++ b/tests/unit/apikey-policy-default-rate-limits.test.ts@@ -0,0 +1,49 @@+import test from "node:test";+import assert from "node:assert/strict";++// Mirror the constants in apiKeyPolicy.ts so the tests document the contract+// rather than re-deriving it from the implementation under test.+const LEGACY_DEFAULT = [+ { limit: 1000, window: 86400 },+ { limit: 5000, window: 604800 },+ { limit: 20000, window: 2592000 },+];++test("buildDefaultRateLimits: unset / empty env falls back to the legacy 1000/day default", async () => {+ const { buildDefaultRateLimits } = await import("../../src/shared/utils/apiKeyPolicy.ts");++ // Unset and empty must both produce the legacy default — going unlimited+ // by accident on an upgrade would expose existing deployments.+ assert.deepEqual(buildDefaultRateLimits(undefined), LEGACY_DEFAULT);+ assert.deepEqual(buildDefaultRateLimits(""), LEGACY_DEFAULT);+ assert.deepEqual(buildDefaultRateLimits(" "), LEGACY_DEFAULT);+});++test("buildDefaultRateLimits: explicit '0' opts out — no fallback rules", async () => {+ const { buildDefaultRateLimits } = await import("../../src/shared/utils/apiKeyPolicy.ts");++ // The only way to become unlimited is to set the env var explicitly to "0".+ assert.deepEqual(buildDefaultRateLimits("0"), []);+});++test("buildDefaultRateLimits: positive N yields N/day, 5N/week, 20N/month", async () => {+ const { buildDefaultRateLimits } = await import("../../src/shared/utils/apiKeyPolicy.ts");++ assert.deepEqual(buildDefaultRateLimits("100"), [+ { limit: 100, window: 86400 },+ { limit: 500, window: 604800 },+ { limit: 2000, window: 2592000 },+ ]);+});++test("buildDefaultRateLimits: malformed input falls back to the legacy default, not unlimited", async () => {+ const { buildDefaultRateLimits } = await import("../../src/shared/utils/apiKeyPolicy.ts");++ // Zod (z.coerce.number().int().min(0)) rejects each of these.+ // The function must keep the secure default rather than silently returning+ // [] — a typo in deployment config should not silently disable rate limits.+ assert.deepEqual(buildDefaultRateLimits("-5"), LEGACY_DEFAULT);+ assert.deepEqual(buildDefaultRateLimits("not-a-number"), LEGACY_DEFAULT);+ assert.deepEqual(buildDefaultRateLimits("1000 requests"), LEGACY_DEFAULT);+ assert.deepEqual(buildDefaultRateLimits("3.14"), LEGACY_DEFAULT);+});