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(quota): restrict quota-exclusive keys to their quotaShared-* models (Phase B4)
diegosouzapw78c5a30cf922
diff --git a/src/lib/quota/quotaKey.ts b/src/lib/quota/quotaKey.tsindex 5ec87bffac..90dc715736 100644--- a/src/lib/quota/quotaKey.ts+++ b/src/lib/quota/quotaKey.ts@@ -8,6 +8,7 @@import { getPool } from "@/lib/db/quotaPools";import { getProviderConnectionById } from "@/lib/db/providers";+import { quotaPoolSlug } from "./quotaModelNaming";// ---------------------------------------------------------------------------// Public interface@@ -18,6 +19,8 @@ export interface QuotaKeyScope {connectionIds: string[];/** Provider slugs of those connections (deduplicated). */providers: string[];+ /** Alphanumeric pool slugs the key is scoped to (from quotaPoolSlug(pool.name)), deduplicated. */+ poolSlugs: string[];}/**@@ -56,11 +59,12 @@ export async function resolveQuotaKeyScope(allowedQuotas: string[] | null | undefined): Promise<QuotaKeyScope> {if (!allowedQuotas || allowedQuotas.length === 0) {- return { connectionIds: [], providers: [] };+ return { connectionIds: [], providers: [], poolSlugs: [] };}const connectionIdSet = new Set<string>();const providerSet = new Set<string>();+ const poolSlugSet = new Set<string>();for (const poolId of allowedQuotas) {const pool = getPool(poolId);@@ -74,10 +78,12 @@ export async function resolveQuotaKeyScope(connectionIdSet.add(pool.connectionId);providerSet.add(provider);+ poolSlugSet.add(quotaPoolSlug(pool.name));}return {connectionIds: Array.from(connectionIdSet),providers: Array.from(providerSet),+ poolSlugs: Array.from(poolSlugSet),};}diff --git a/src/shared/utils/apiKeyPolicy.ts b/src/shared/utils/apiKeyPolicy.tsindex 52a319e4cc..feb07cb100 100644--- a/src/shared/utils/apiKeyPolicy.ts+++ b/src/shared/utils/apiKeyPolicy.ts@@ -19,7 +19,7 @@ import * as log from "@/sse/utils/logger";import { checkRateLimit, RateLimitRule } from "./rateLimiter";import { resolveEndpointCategory } from "@/shared/constants/endpointCategories";import { resolveQuotaKeyScope } from "@/lib/quota/quotaKey";-import { parseModel } from "@omniroute/open-sse/services/model.ts";+import { isQuotaModelName, parseQuotaModelName } from "@/lib/quota/quotaModelNaming";// Default to no per-key request cap. API keys can still opt into explicit// limits via Settings/API Manager, while provider/account quota controls remain@@ -320,19 +320,35 @@ export async function enforceApiKeyPolicy(}}- // ── Check 3: Quota-exclusive enforcement (Phase A3) ──+ // ── Check 3: Quota-exclusive enforcement (Phase B4) ──//- // When a key has allowedQuotas, its access is governed entirely by its- // pools' providers — normal allowedModels/allowedCombos checks are skipped.+ // When a key has allowedQuotas its access is governed exclusively by the+ // quotaShared-* virtual models of its pools — raw model names are rejected,+ // and quotaShared-* names belonging to OTHER pools are also rejected.+ // Normal allowedModels/allowedCombos checks are skipped for these keys.if (modelStr && apiKeyInfo.allowedQuotas && apiKeyInfo.allowedQuotas.length > 0) {try {const scope = await resolveQuotaKeyScope(apiKeyInfo.allowedQuotas);- const { provider } = parseModel(modelStr);- if (provider === null || scope.providers.length === 0 || !scope.providers.includes(provider)) {- const quotaBody = buildErrorBody(- HTTP_STATUS.FORBIDDEN,- `Model "${modelStr}" is not allowed for this quota-exclusive API key`- );+ let quotaRejectionMsg: string | null = null;++ if (isQuotaModelName(modelStr)) {+ // Virtual quota model — must belong to one of this key's pools AND its provider must be in scope.+ const parsed = parseQuotaModelName(modelStr);+ const allowed =+ parsed !== null &&+ scope.poolSlugs.length > 0 &&+ scope.poolSlugs.includes(parsed.poolSlug) &&+ scope.providers.includes(parsed.provider);+ if (!allowed) {+ quotaRejectionMsg = `Model "${modelStr}" is not in this key's quota pools`;+ }+ } else {+ // Raw (non-quotaShared) model name — always rejected for quota-exclusive keys.+ quotaRejectionMsg = `This quota-exclusive API key may only use quotaShared-* models`;+ }++ if (quotaRejectionMsg !== null) {+ const quotaBody = buildErrorBody(HTTP_STATUS.FORBIDDEN, quotaRejectionMsg);quotaBody.error.code = "QUOTA_ONLY";return {apiKey,@@ -343,7 +359,7 @@ export async function enforceApiKeyPolicy(}),};}- // Provider is in scope — quota key governed by pools; skip allowedModels/allowedCombos.+ // Model is an in-scope quotaShared-* name — skip allowedModels/allowedCombos.// Continue to budget / rate-limit checks below.} catch (error) {log.error("API_POLICY", "Quota scope check failed. Request blocked.", { error });diff --git a/tests/unit/apikeypolicy-quota-only.test.ts b/tests/unit/apikeypolicy-quota-only.test.tsindex ee4812e7d2..65fd8e81d7 100644--- a/tests/unit/apikeypolicy-quota-only.test.ts+++ b/tests/unit/apikeypolicy-quota-only.test.ts@@ -1,13 +1,17 @@/*** tests/unit/apikeypolicy-quota-only.test.ts*- * TDD coverage for Phase A3: quota-exclusive enforcement in enforceApiKeyPolicy.+ * TDD coverage for Phase B4: quota-exclusive enforcement in enforceApiKeyPolicy.** Cases:- * 1. Key with allowedQuotas pointing to a "codex" connection → requesting a- * "cx/…" (codex) model → ALLOWED (no rejection).- * 2. Same key → requesting "openai/gpt-4.1" → REJECTED 403 QUOTA_ONLY.- * 3. Key with empty allowedQuotas → existing behavior unchanged (allowed model passes).+ * 1. Key with allowedQuotas (pool "Times" → codex connection) + the canonical+ * quotaShared-* virtual model for that pool → ALLOWED (rejection null).+ * 2. Same key + raw model "cx/gpt-5.5" → REJECTED 403 QUOTA_ONLY+ * (message: "This quota-exclusive API key may only use quotaShared-* models").+ * 3. Same key + quotaShared-* belonging to a DIFFERENT pool → REJECTED 403 QUOTA_ONLY+ * (message: "not in this key's quota pools").+ * 4. Key with empty allowedQuotas → existing behavior unchanged.+ * 5. Dangling pool (non-existent pool ID) → fail-closed 403 QUOTA_ONLY.*/import test from "node:test";@@ -29,6 +33,7 @@ const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");const poolsDb = await import("../../src/lib/db/quotaPools.ts");const providersDb = await import("../../src/lib/db/providers.ts");const rateLimiter = await import("../../src/shared/utils/rateLimiter.ts");+const { quotaModelName } = await import("../../src/lib/quota/quotaModelNaming.ts");rateLimiter.setRateLimiterTestMode(true);@@ -92,105 +97,117 @@ test.after(async () => {// Tests// ----------------------------------------------------------------------------test("quota-only key requesting a model in the allowed provider is passed through", async () => {- // Seed a provider connection with provider "codex" (matches "cx/gpt-5.5")+test("quota-only key requesting its quotaShared-* virtual model is allowed", async () => {+ // Pool name "Times" → slug "times"; provider "codex"const conn = await providersDb.createProviderConnection({provider: "codex",authType: "apikey",- name: "quota-only-codex-conn",- apiKey: "sk-codex-quota-only",+ name: "quota-b4-codex-conn",+ apiKey: "sk-codex-b4-allowed",});const connId = (conn as Record<string, unknown>).id as string;assert.ok(connId);- // Seed a pool referencing that connection- const pool = poolsDb.createPool({ connectionId: connId, name: "Codex Pool A3" });+ const pool = poolsDb.createPool({ connectionId: connId, name: "Times" });- // Create an API key bound to that pool- const created = await apiKeysDb.createApiKey("Quota-Only Key", "machine-a3");+ const created = await apiKeysDb.createApiKey("Quota-B4 Key Allowed", "machine-b4-allowed");await apiKeysDb.updateApiKeyPermissions(created.id, {allowedQuotas: [pool.id],});- const policy = await loadPolicy("quota-only-allowed");+ const policy = await loadPolicy("b4-quota-allowed");- // "cx/gpt-5.5" → provider resolves to "codex" (cx alias) — should be allowed- const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), "cx/gpt-5.5");+ // Build the canonical virtual model name using the same helper the B4 implementation uses.+ // Pool "Times" → slug "times"; provider "codex" (canonical, not alias "cx"); model "gpt-5.5"+ // → quotaShared-times-codex/gpt-5.5+ const virtualModel = quotaModelName("Times", "codex", "gpt-5.5");+ assert.equal(virtualModel, "quotaShared-times-codex/gpt-5.5");++ const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), virtualModel);assert.equal(result.rejection,null,- "quota-exclusive key should pass through for a model in its pools' providers"+ "quota-exclusive key should pass through for its own quotaShared-* model");});-test("quota-only key requesting a model outside allowed providers is rejected 403 QUOTA_ONLY", async () => {- // Seed a provider connection with provider "codex"+test("quota-only key requesting raw model name is rejected 403 QUOTA_ONLY", async () => {const conn = await providersDb.createProviderConnection({provider: "codex",authType: "apikey",- name: "quota-only-codex-conn-reject",- apiKey: "sk-codex-quota-only-reject",+ name: "quota-b4-codex-conn-raw",+ apiKey: "sk-codex-b4-raw",});const connId = (conn as Record<string, unknown>).id as string;- const pool = poolsDb.createPool({ connectionId: connId, name: "Codex Pool A3 Reject" });+ const pool = poolsDb.createPool({ connectionId: connId, name: "Times" });- const created = await apiKeysDb.createApiKey("Quota-Only Key Reject", "machine-a3-reject");+ const created = await apiKeysDb.createApiKey("Quota-B4 Key Raw Reject", "machine-b4-raw");await apiKeysDb.updateApiKeyPermissions(created.id, {allowedQuotas: [pool.id],});- const policy = await loadPolicy("quota-only-rejected");+ const policy = await loadPolicy("b4-quota-raw-rejected");- // "openai/gpt-4.1" → provider "openai" is NOT in the codex pool scope → reject- const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), "openai/gpt-4.1");+ // Raw model name (not a quotaShared-* name) → must be rejected+ const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), "cx/gpt-5.5");- assert.ok(result.rejection, "should produce a rejection Response");+ assert.ok(result.rejection, "should produce a rejection Response for raw model name");assert.equal(result.rejection.status, 403, "rejection should be 403 Forbidden");const body = await readBody(result.rejection);assert.equal(body.error.code, "QUOTA_ONLY", "error code should be QUOTA_ONLY");assert.match(body.error.message,- /not allowed for this quota-exclusive API key/,- "error message should mention quota-exclusive"+ /quota-exclusive API key may only use quotaShared-\* models/,+ "error message should indicate only quotaShared-* models are allowed");- // Must not leak stack tracesassert.ok(!body.error.message.includes(" at "), "message must not contain stack trace");});-test("quota-only key whose allowedQuotas references a non-existent pool is rejected 403 QUOTA_ONLY (fail-closed)", async () => {- // Create an API key bound to a pool ID that does not exist in the DB (dangling reference)- const created = await apiKeysDb.createApiKey("Dangling Quota Key", "machine-a3-dangling");+test("quota-only key requesting a quotaShared-* model from a different pool is rejected 403 QUOTA_ONLY", async () => {+ const conn = await providersDb.createProviderConnection({+ provider: "codex",+ authType: "apikey",+ name: "quota-b4-codex-conn-otherpool",+ apiKey: "sk-codex-b4-otherpool",+ });+ const connId = (conn as Record<string, unknown>).id as string;+ const pool = poolsDb.createPool({ connectionId: connId, name: "Times" });++ const created = await apiKeysDb.createApiKey("Quota-B4 Key Other Pool", "machine-b4-other");await apiKeysDb.updateApiKeyPermissions(created.id, {- allowedQuotas: ["non-existent-pool-id-00000000"],+ allowedQuotas: [pool.id],});- const policy = await loadPolicy("quota-dangling-pool");+ const policy = await loadPolicy("b4-quota-otherpool-rejected");- // resolveQuotaKeyScope will return empty providers for the dangling pool id → fail-closed- const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), "openai/gpt-4.1");+ // quotaShared-* for a DIFFERENT pool slug ("otherpool") — must be rejected+ const otherPoolVirtualModel = quotaModelName("OtherPool", "codex", "gpt-5.5");+ assert.equal(otherPoolVirtualModel, "quotaShared-otherpool-codex/gpt-5.5");- assert.ok(result.rejection, "should produce a rejection Response for a dangling pool");+ const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), otherPoolVirtualModel);++ assert.ok(result.rejection, "should produce a rejection Response for other-pool quotaShared-* model");assert.equal(result.rejection.status, 403, "rejection should be 403 Forbidden");const body = await readBody(result.rejection);assert.equal(body.error.code, "QUOTA_ONLY", "error code should be QUOTA_ONLY");assert.match(body.error.message,- /not allowed for this quota-exclusive API key/,- "error message should mention quota-exclusive"+ /not in this key's quota pools/,+ "error message should mention quota pools");assert.ok(!body.error.message.includes(" at "), "message must not contain stack trace");});test("key with empty allowedQuotas is subject to normal model restriction checks", async () => {- // A key with no allowedQuotas but with allowedModels = ["openai/*"]- const created = await apiKeysDb.createApiKey("Normal Key", "machine-a3-normal");+ // A key with no allowedQuotas but with allowedModels = ["openai/gpt-4.1"]+ const created = await apiKeysDb.createApiKey("Normal Key", "machine-b4-normal");await apiKeysDb.updateApiKeyPermissions(created.id, {allowedModels: ["openai/gpt-4.1"],});- const policy = await loadPolicy("quota-empty-normal");+ const policy = await loadPolicy("b4-quota-empty-normal");// Allowed model should passconst allowed = await policy.enforceApiKeyPolicy(makeRequest(created.key), "openai/gpt-4.1");@@ -211,3 +228,24 @@ test("key with empty allowedQuotas is subject to normal model restriction checks// rather than QUOTA_ONLY — confirming paths are separateassert.notEqual(body.error.code, "QUOTA_ONLY", "normal key rejection must NOT use QUOTA_ONLY code");});++test("quota-only key whose allowedQuotas references a non-existent pool is rejected 403 QUOTA_ONLY (fail-closed)", async () => {+ // Create an API key bound to a pool ID that does not exist in the DB (dangling reference)+ const created = await apiKeysDb.createApiKey("Dangling Quota Key", "machine-b4-dangling");+ await apiKeysDb.updateApiKeyPermissions(created.id, {+ allowedQuotas: ["non-existent-pool-id-00000000"],+ });++ const policy = await loadPolicy("b4-quota-dangling-pool");++ // resolveQuotaKeyScope will return empty scope for the dangling pool id → fail-closed+ // A raw model name will also be rejected by the "raw model" branch+ const result = await policy.enforceApiKeyPolicy(makeRequest(created.key), "openai/gpt-4.1");++ assert.ok(result.rejection, "should produce a rejection Response for a dangling pool");+ assert.equal(result.rejection.status, 403, "rejection should be 403 Forbidden");++ const body = await readBody(result.rejection);+ assert.equal(body.error.code, "QUOTA_ONLY", "error code should be QUOTA_ONLY");+ assert.ok(!body.error.message.includes(" at "), "message must not contain stack trace");+});diff --git a/tests/unit/quota-key-resolve.test.ts b/tests/unit/quota-key-resolve.test.tsindex 9e15a24ea0..4e36b17ece 100644--- a/tests/unit/quota-key-resolve.test.ts+++ b/tests/unit/quota-key-resolve.test.ts@@ -62,25 +62,25 @@ test.after(async () => {test("resolveQuotaKeyScope: empty array input returns empty scope", async () => {const scope = await resolveQuotaKeyScope([]);- assert.deepEqual(scope, { connectionIds: [], providers: [] });+ assert.deepEqual(scope, { connectionIds: [], providers: [], poolSlugs: [] });});test("resolveQuotaKeyScope: null input returns empty scope", async () => {const scope = await resolveQuotaKeyScope(null);- assert.deepEqual(scope, { connectionIds: [], providers: [] });+ assert.deepEqual(scope, { connectionIds: [], providers: [], poolSlugs: [] });});test("resolveQuotaKeyScope: undefined input returns empty scope", async () => {const scope = await resolveQuotaKeyScope(undefined);- assert.deepEqual(scope, { connectionIds: [], providers: [] });+ assert.deepEqual(scope, { connectionIds: [], providers: [], poolSlugs: [] });});test("resolveQuotaKeyScope: unknown pool id returns empty scope (no throw)", async () => {const scope = await resolveQuotaKeyScope(["pool-does-not-exist"]);- assert.deepEqual(scope, { connectionIds: [], providers: [] });+ assert.deepEqual(scope, { connectionIds: [], providers: [], poolSlugs: [] });});-test("resolveQuotaKeyScope: valid pool returns its connectionId and provider", async () => {+test("resolveQuotaKeyScope: valid pool returns its connectionId, provider, and poolSlug", async () => {// Seed a real provider connectionconst conn = await providersDb.createProviderConnection({provider: "openai",@@ -98,6 +98,8 @@ test("resolveQuotaKeyScope: valid pool returns its connectionId and provider", aassert.deepEqual(scope.connectionIds, [connId]);assert.deepEqual(scope.providers, ["openai"]);+ // "Test Pool A2" slugifies to "testpoola2"+ assert.deepEqual(scope.poolSlugs, ["testpoola2"]);});test("resolveQuotaKeyScope: multiple pools same provider deduplicates providers", async () => {@@ -166,7 +168,7 @@ test("resolveQuotaKeyScope: pool referencing non-existent connectionId is skippe});const scope = await resolveQuotaKeyScope([pool.id]);- assert.deepEqual(scope, { connectionIds: [], providers: [] });+ assert.deepEqual(scope, { connectionIds: [], providers: [], poolSlugs: [] });});test("resolveQuotaKeyScope: mix of valid and invalid pool ids — only valid contribute", async () => {@@ -183,4 +185,6 @@ test("resolveQuotaKeyScope: mix of valid and invalid pool ids — only valid conassert.deepEqual(scope.connectionIds, [connId]);assert.deepEqual(scope.providers, ["openai"]);+ // "Pool Mix" slugifies to "poolmix"+ assert.deepEqual(scope.poolSlugs, ["poolmix"]);});