feat(quota): add allowed_quotas allow-list field to api_keys (Phase A1)

This commit is contained in:
diegosouzapw
2026-05-30 18:58:23 -03:00
parent 6b0e89fb42
commit 51b586c2af
3 changed files with 164 additions and 1 deletions

View File

@@ -42,6 +42,7 @@ interface ApiKeyMetadata {
allowedModels: string[];
allowedCombos: string[];
allowedConnections: string[];
allowedQuotas: string[];
noLog: boolean;
autoResolve: boolean;
isActive: boolean;
@@ -74,6 +75,8 @@ interface ApiKeyRow extends JsonRecord {
allowedCombos?: unknown;
allowed_connections?: unknown;
allowedConnections?: unknown;
allowed_quotas?: unknown;
allowedQuotas?: unknown;
no_log?: unknown;
noLog?: unknown;
auto_resolve?: unknown;
@@ -111,6 +114,7 @@ interface ApiKeyView extends JsonRecord {
allowedModels: string[];
allowedCombos: string[];
allowedConnections: string[];
allowedQuotas: string[];
noLog: boolean;
autoResolve: boolean;
isActive: boolean;
@@ -156,6 +160,7 @@ const API_KEY_COLUMN_FALLBACKS = [
{ name: "is_banned", definition: "is_banned INTEGER NOT NULL DEFAULT 0" },
{ name: "key_hash", definition: "key_hash TEXT" },
{ name: "allowed_endpoints", definition: "allowed_endpoints TEXT" },
{ name: "allowed_quotas", definition: "allowed_quotas TEXT NOT NULL DEFAULT '[]'" },
] as const;
// Cache for model permission checks
@@ -355,7 +360,7 @@ function getPreparedStatements(db: ApiKeysDbLike): ApiKeysStatements {
"SELECT id, expires_at, revoked_at, is_active, is_banned FROM api_keys WHERE key = ? OR key_hash = ?"
);
_stmtGetKeyMetadata = db.prepare<ApiKeyRow>(
"SELECT id, name, machine_id, allowed_models, allowed_combos, allowed_connections, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute, throttle_delay_ms, max_sessions, revoked_at, expires_at, ip_allowlist, scopes, rate_limits, is_banned, key_hash, allowed_endpoints FROM api_keys WHERE key = ? OR key_hash = ?"
"SELECT id, name, machine_id, allowed_models, allowed_combos, allowed_connections, allowed_quotas, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute, throttle_delay_ms, max_sessions, revoked_at, expires_at, ip_allowlist, scopes, rate_limits, is_banned, key_hash, allowed_endpoints FROM api_keys WHERE key = ? OR key_hash = ?"
);
_stmtInsertKey = db.prepare(
"INSERT INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at, key_prefix, key_hash, scopes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
@@ -393,6 +398,7 @@ export async function getApiKeys() {
camelRow.allowedModels = parseAllowedModels(camelRow.allowedModels);
camelRow.allowedCombos = parseAllowedCombos(camelRow.allowedCombos);
camelRow.allowedConnections = parseAllowedConnections(camelRow.allowedConnections);
camelRow.allowedQuotas = parseAllowedQuotas((camelRow as JsonRecord).allowedQuotas);
camelRow.noLog = parseNoLog(camelRow.noLog);
camelRow.autoResolve = parseAutoResolve(camelRow.autoResolve);
camelRow.isActive = parseIsActive(camelRow.isActive);
@@ -417,6 +423,7 @@ export async function getApiKeyById(id: string) {
camelRow.allowedModels = parseAllowedModels(camelRow.allowedModels);
camelRow.allowedCombos = parseAllowedCombos(camelRow.allowedCombos);
camelRow.allowedConnections = parseAllowedConnections(camelRow.allowedConnections);
camelRow.allowedQuotas = parseAllowedQuotas((camelRow as JsonRecord).allowedQuotas);
camelRow.noLog = parseNoLog(camelRow.noLog);
camelRow.autoResolve = parseAutoResolve(camelRow.autoResolve);
camelRow.isActive = parseIsActive(camelRow.isActive);
@@ -530,6 +537,23 @@ function parseAllowedConnections(value: unknown): string[] {
}
}
/**
* Helper function to safely parse allowed_quotas JSON
*/
function parseAllowedQuotas(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is string => typeof entry === "string")
: [];
} catch {
return [];
}
}
function parseStringList(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") return [];
try {
@@ -647,6 +671,7 @@ export async function updateApiKeyPermissions(
allowedModels?: string[];
allowedCombos?: string[];
allowedConnections?: string[];
allowedQuotas?: string[];
noLog?: boolean;
autoResolve?: boolean;
isActive?: boolean;
@@ -674,6 +699,7 @@ export async function updateApiKeyPermissions(
allowedModels: update.allowedModels,
allowedCombos: update.allowedCombos,
allowedConnections: update.allowedConnections,
allowedQuotas: (update as { allowedQuotas?: string[] }).allowedQuotas,
noLog: update.noLog,
autoResolve: update.autoResolve,
isActive: update.isActive,
@@ -694,6 +720,7 @@ export async function updateApiKeyPermissions(
normalized.allowedModels === undefined &&
normalized.allowedCombos === undefined &&
normalized.allowedConnections === undefined &&
(normalized as Record<string, unknown>).allowedQuotas === undefined &&
normalized.noLog === undefined &&
normalized.autoResolve === undefined &&
normalized.isActive === undefined &&
@@ -718,6 +745,7 @@ export async function updateApiKeyPermissions(
allowedModels?: string;
allowedCombos?: string;
allowedConnections?: string;
allowedQuotas?: string;
noLog?: number;
autoResolve?: number;
isActive?: number;
@@ -755,6 +783,16 @@ export async function updateApiKeyPermissions(
params.allowedConnections = JSON.stringify(normalized.allowedConnections || []);
}
const allowedQuotasUpdate = (normalized as Record<string, unknown>).allowedQuotas;
if (allowedQuotasUpdate !== undefined) {
// Empty array means no quota-pool restriction; non-empty restricts to listed pools
updates.push("allowed_quotas = @allowedQuotas");
const nextQuotas: string[] = Array.isArray(allowedQuotasUpdate)
? (allowedQuotasUpdate as unknown[]).filter((s): s is string => typeof s === "string")
: [];
params.allowedQuotas = JSON.stringify(nextQuotas);
}
if (normalized.noLog !== undefined) {
updates.push("no_log = @noLog");
params.noLog = normalized.noLog ? 1 : 0;
@@ -1155,6 +1193,7 @@ export async function getApiKeyMetadata(
allowedModels: [],
allowedCombos: [],
allowedConnections: [],
allowedQuotas: [],
noLog: false,
autoResolve: true,
isActive: true,
@@ -1208,6 +1247,9 @@ export async function getApiKeyMetadata(
allowedConnections: parseAllowedConnections(
record.allowed_connections ?? record.allowedConnections
),
allowedQuotas: parseAllowedQuotas(
(record as JsonRecord).allowed_quotas ?? (record as JsonRecord).allowedQuotas
),
noLog: parseNoLog(record.no_log ?? record.noLog),
autoResolve: parseAutoResolve(record.auto_resolve ?? record.autoResolve),
isActive: parseIsActive(record.is_active ?? record.isActive),

View File

@@ -0,0 +1,8 @@
-- 085: Per-API-key quota-pool allow-list (Phase A1 — Quota Share redesign).
--
-- Adds `allowed_quotas` as a JSON TEXT array of quota-pool IDs. Empty array
-- means no quota-pool restriction (all pools accessible). Non-empty array
-- limits the key to the listed pool IDs only (enforcement added in Phase A2).
-- Idempotent via ADD COLUMN; safe to run more than once on older schemas.
ALTER TABLE api_keys ADD COLUMN allowed_quotas TEXT NOT NULL DEFAULT '[]';

View File

@@ -0,0 +1,113 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-allowed-quotas-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "allowed-quotas-test-secret";
const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
async function resetStorage() {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: unknown) {
const err = error as NodeJS.ErrnoException;
if ((err?.code === "EBUSY" || err?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("allowedQuotas round-trips: create with pool IDs and read them back via getApiKeyMetadata", async () => {
const created = await apiKeysDb.createApiKey("Quota Key", "machine-quota-01");
await apiKeysDb.updateApiKeyPermissions(created.id, {
allowedQuotas: ["pool-x", "pool-y"],
});
apiKeysDb.clearApiKeyCaches();
const metadata = await apiKeysDb.getApiKeyMetadata(created.key);
assert.ok(metadata, "metadata should not be null");
assert.deepEqual(metadata.allowedQuotas, ["pool-x", "pool-y"]);
});
test("allowedQuotas defaults to [] when not set on a new key", async () => {
const created = await apiKeysDb.createApiKey("No Quota Key", "machine-quota-02");
const metadata = await apiKeysDb.getApiKeyMetadata(created.key);
assert.ok(metadata, "metadata should not be null");
assert.deepEqual(metadata.allowedQuotas, []);
});
test("allowedQuotas can be updated and cleared back to empty", async () => {
const created = await apiKeysDb.createApiKey("Clearable Quota Key", "machine-quota-03");
await apiKeysDb.updateApiKeyPermissions(created.id, {
allowedQuotas: ["pool-a", "pool-b", "pool-c"],
});
apiKeysDb.clearApiKeyCaches();
const metaFilled = await apiKeysDb.getApiKeyMetadata(created.key);
assert.deepEqual(metaFilled?.allowedQuotas, ["pool-a", "pool-b", "pool-c"]);
await apiKeysDb.updateApiKeyPermissions(created.id, { allowedQuotas: [] });
apiKeysDb.clearApiKeyCaches();
const metaCleared = await apiKeysDb.getApiKeyMetadata(created.key);
assert.deepEqual(metaCleared?.allowedQuotas, []);
});
test("allowedQuotas round-trips via getApiKeyById", async () => {
const created = await apiKeysDb.createApiKey("ById Quota Key", "machine-quota-04");
await apiKeysDb.updateApiKeyPermissions(created.id, {
allowedQuotas: ["pool-x", "pool-y"],
});
const row = await apiKeysDb.getApiKeyById(created.id);
assert.ok(row, "row should not be null");
assert.deepEqual((row as Record<string, unknown>).allowedQuotas, ["pool-x", "pool-y"]);
});
test("allowedQuotas round-trips via getApiKeys list", async () => {
const created = await apiKeysDb.createApiKey("List Quota Key", "machine-quota-05");
await apiKeysDb.updateApiKeyPermissions(created.id, {
allowedQuotas: ["pool-list"],
});
const allKeys = await apiKeysDb.getApiKeys();
const found = allKeys.find((k) => k.id === created.id);
assert.ok(found, "key should appear in getApiKeys list");
assert.deepEqual((found as Record<string, unknown>).allowedQuotas, ["pool-list"]);
});