mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-09 17:28:51 +00:00
fix(playground): accept a dashboard session for presets under REQUIRE_API_KEY (#6554)
Merged — thank you, @developerjillur! Accept a valid dashboard session for /api/playground/presets under REQUIRE_API_KEY (the Playground page authenticates via cookie, not an API key). Integrated into release/v3.8.47.
This commit is contained in:
parent
ed0b9c73de
commit
95e4bf72d4
3 changed files with 70 additions and 4 deletions
|
|
@ -29,6 +29,7 @@ _Living section — bullets land here as PRs merge into `release/v3.8.47` (paral
|
|||
- **perf(health):** short-TTL (1s) cache for the frequently-polled `GET /api/monitoring/health` payload — rebuilding it every request (DB reads + status aggregation across 8 subsystems) was wasteful under rapid polling; the cache stays near-real-time and is invalidated immediately on `DELETE` (circuit-breaker reset) so a manual reset is reflected at once. Regression guard: `tests/integration/monitoring-health-cache.test.ts`. ([#6553](https://github.com/diegosouzapw/OmniRoute/pull/6553)) — see PR. (thanks @developerjillur)
|
||||
- **fix(resilience):** `headroom` combo routing did not always select the Codex account with the most free quota ([#6379](https://github.com/diegosouzapw/OmniRoute/issues/6379)) — `orderTargetsByHeadroom` (`open-sse/services/combo/quotaStrategies.ts`) already loaded the per-connection DB snapshot (with decrypted credentials) via `expandTargetsByQuotaAwareConnections`, but discarded it before calling `getSaturation`; for Codex, `fetchCodexSaturation` forwards straight to `fetchCodexQuota(connectionId, connection)`, which needs `connection` (or a prior `registerCodexConnection()` call, which never happens before headroom ranking runs) to read `accessToken` — so it returned `null` for every candidate, saturation failed open to `0` across the board, and ranking fell back to the original combo order regardless of actual free quota. `getSaturation()` and the headroom `SaturationFetcher` seam now accept and thread the loaded connection snapshot through to `fetchCodexQuota`. Kilo's dup flag vs #5903 was a false positive — that issue is about session-sticky reset-aware/least-used selection, not headroom's Codex saturation lookup. Regression guard: `tests/unit/headroom-codex-quota-snapshot-6379.test.ts`. (thanks @eidoog)
|
||||
- **fix(providers):** custom models a provider actually has are no longer dropped from the Free Provider Rankings when both **"Configured only"** and **"Available only"** filters are applied ([#6368](https://github.com/diegosouzapw/OmniRoute/issues/6368)), follow-up to #6150 — `freeProviderRankings.ts::getProviderModels()` only ever walked the static `open-sse/config/providerRegistry.ts` catalog, so a user-added custom model (e.g. a Puter `claude-fable-5` model saved as "Claude Fable 5") never entered the candidate model list the ranking scores against, and could never survive the #6150 configured/available filters even when actually configured and available. It now additively merges the provider's custom models (`db/models.ts::getCustomModels`) into that candidate list via a new pure, de-duping `mergeProviderModels()` helper, before scoring/filtering runs — catalog free/paid filtering elsewhere is untouched. Regression guard: `tests/unit/free-provider-rankings-custom-models-6368.test.ts`. (thanks @shabeer)
|
||||
- **fix(playground):** accept a valid dashboard session for `GET/POST /api/playground/presets` under `REQUIRE_API_KEY=true` — the Playground page calls this route with a cookie/session and no API key, which previously 401'd the authenticated dashboard; `checkAuth()` now accepts a management/dashboard session (`requireManagementAuth`) as an alternative to an API key, while a presented API key must still be valid and the anonymous-allowed default is preserved. Regression guard: `tests/integration/presets-dashboard-auth.test.ts`. ([#6554](https://github.com/diegosouzapw/OmniRoute/pull/6554)) — see PR. (thanks @developerjillur)
|
||||
- **fix(providers):** `cloudflare-ai` no longer silently drops image/non-text content parts ([#6390](https://github.com/diegosouzapw/OmniRoute/issues/6390)) — `transformRequest()`'s `flattenContent()` (added for #2539 to satisfy the Workers AI `/ai/v1/chat/completions` plain-string `content` requirement) mapped any non-text OpenAI content part (e.g. `image_url`) to `""` and joined the rest, so a request carrying an image quietly went out as text-only with the attachment gone and no error surfaced. It now throws a clear error on the first non-text part instead of dropping it silently, which the existing top-level `chatCore.ts` catch already routes through `buildErrorBody()`/`sanitizeErrorMessage()` (same pattern as `buildUrl()`'s missing-Account-ID error). Regression guard: `tests/unit/cloudflare-ai-image-parts-6390.test.ts`.
|
||||
- **fix(providers):** stop Antigravity connections from falsely reporting **all-accounts quota-exhausted** ([#6295](https://github.com/diegosouzapw/OmniRoute/issues/6295)) — `genericQuotaFetcher.ts::percentUsedForQuota()` ignored the `fractionReported` flag and defaulted an unreported model's `remainingPercentage` to 0, which computed as 100% used; since `convertUsageToQuotaInfo()` takes the worst-case window across a connection, a single model with no reported fraction dragged the whole account into `limitReached` and `quotaPreflight` skipped it. `percentUsedForQuota()` now returns `null` (unknown, window ignored) whenever `fractionReported === false`, before falling back to `remainingPercentage`. Regression guard: `tests/unit/generic-quota-fetcher.test.ts`.
|
||||
- **fix(fusion):** the fusion judge no longer replays a panel member's answer via an idempotency-key collision — fusion's panel + judge sub-requests re-enter `chatCore` sharing the client's headers, so they derived the same `Idempotency-Key`/`x-request-id` and a panel answer saved under the key was replayed by the judge's check ~1ms later (inside the 5s window), returning a panel member's answer instead of the judge synthesis (observed live on `nexa/conversation-fusion`). `composeIdempotencyKey()` now namespaces the key by target provider/model + a digest of the request messages, so sub-requests can't collide while a genuine client retry (same key/model/body) still replays. Regression guard: `tests/unit/idempotency-fusion-collision.test.ts`. ([#6558](https://github.com/diegosouzapw/OmniRoute/pull/6558)) — see PR. (thanks @developerjillur)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
import { buildErrorBody, sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
|
||||
import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
|
||||
import { extractApiKey, isValidApiKey } from "@/sse/services/auth";
|
||||
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
|
||||
import { listPlaygroundPresets, createPlaygroundPreset } from "@/lib/db/playgroundPresets";
|
||||
import { PlaygroundPresetCreateSchema } from "@/shared/schemas/playground";
|
||||
import { isRequireApiKeyEnabled } from "@/shared/utils/featureFlags";
|
||||
|
|
@ -28,11 +29,23 @@ function errorResp(status: number, message: string): Response {
|
|||
|
||||
async function checkAuth(request: Request): Promise<Response | null> {
|
||||
const apiKeyRaw = extractApiKey(request);
|
||||
if (isRequireApiKeyEnabled() && !apiKeyRaw) {
|
||||
return errorResp(HTTP_STATUS.UNAUTHORIZED, "Authentication required");
|
||||
// External-client path: if an API key is presented it MUST be valid.
|
||||
if (apiKeyRaw) {
|
||||
if (!(await isValidApiKey(apiKeyRaw))) {
|
||||
return errorResp(HTTP_STATUS.UNAUTHORIZED, "Invalid API key");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (apiKeyRaw && !(await isValidApiKey(apiKeyRaw))) {
|
||||
return errorResp(HTTP_STATUS.UNAUTHORIZED, "Invalid API key");
|
||||
// Dashboard path: the Playground page itself calls this route with a
|
||||
// cookie/session (no API key). Under REQUIRE_API_KEY=true that previously
|
||||
// 401'd the authenticated dashboard (QA P1: preset auth mismatch). Accept a
|
||||
// valid management/dashboard session as an alternative to an API key.
|
||||
const managementError = await requireManagementAuth(request);
|
||||
if (!managementError) return null;
|
||||
// Neither an API key nor a valid dashboard session: enforce only when
|
||||
// API-key enforcement is on (preserves the legacy anonymous-allowed default).
|
||||
if (isRequireApiKeyEnabled()) {
|
||||
return errorResp(HTTP_STATUS.UNAUTHORIZED, "Authentication required");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
52
tests/integration/presets-dashboard-auth.test.ts
Normal file
52
tests/integration/presets-dashboard-auth.test.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/**
|
||||
* Integration test for dashboard-session auth on GET /api/playground/presets.
|
||||
*
|
||||
* The Playground page (dashboard) calls this route with a cookie/session and NO
|
||||
* API key. Under REQUIRE_API_KEY=true that previously 401'd the authenticated
|
||||
* dashboard, because checkAuth only accepted an API key. The fix also accepts a
|
||||
* valid management/dashboard session (requireManagementAuth) as an alternative.
|
||||
*
|
||||
* We forge a real `auth_token` JWT (same shape the login route signs) so the
|
||||
* dashboard-session path is exercised end-to-end against the real route handler.
|
||||
*/
|
||||
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-presets-auth-"));
|
||||
process.env.DATA_DIR = TEST_DATA_DIR;
|
||||
process.env.REQUIRE_API_KEY = "true"; // the scenario where the dashboard used to 401
|
||||
process.env.INITIAL_PASSWORD = "test-dashboard-password"; // makes login/auth required
|
||||
process.env.JWT_SECRET = "test-presets-auth-secret";
|
||||
|
||||
await import("../../src/lib/db/core.ts");
|
||||
const { GET } = await import("../../src/app/api/playground/presets/route.ts");
|
||||
|
||||
const BASE = "http://localhost/api/playground/presets";
|
||||
|
||||
async function dashboardCookie(): Promise<string> {
|
||||
const { SignJWT } = await import("jose");
|
||||
const token = await new SignJWT({ authenticated: true })
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setExpirationTime("30d")
|
||||
.sign(new TextEncoder().encode(process.env.JWT_SECRET as string));
|
||||
return `auth_token=${token}`;
|
||||
}
|
||||
|
||||
test("REQUIRE_API_KEY=true: a valid dashboard session (no API key) is accepted — regression, was 401", async () => {
|
||||
const res = await GET(new Request(BASE, { headers: { cookie: await dashboardCookie() } }));
|
||||
assert.notEqual(res.status, 401, "an authenticated dashboard session must not be rejected");
|
||||
assert.equal(res.status, 200);
|
||||
});
|
||||
|
||||
test("REQUIRE_API_KEY=true: no session and no API key -> 401 (guard still enforces)", async () => {
|
||||
const res = await GET(new Request(BASE));
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
|
||||
test("REQUIRE_API_KEY=true: a tampered/invalid session token -> 401", async () => {
|
||||
const res = await GET(new Request(BASE, { headers: { cookie: "auth_token=not.a.valid.jwt" } }));
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue