Files
OmniRoute/tests/unit/authz/pipeline.test.ts
Diego Rodrigues de Sa e Souza 0d089e7e39 fix(quality): clear the release/v3.8.51 base-reds (#13947)
* fix(quality): clear the release/v3.8.51 base-reds

19 failing unit tests plus the API Route Typecheck and mutation-test-coverage
gates, all reproduced on the clean tip before touching anything.

Ten of the failures share one cause. #13452/#13798 made `*-compatible-*`
buildUrl() refuse a connection with no baseUrl instead of quietly defaulting to
the real OpenAI/Anthropic API — which would ship the operator's stored key to a
public third party. The guard is right; three fixtures still built those
connections unhydrated, and one of them put baseUrl at the top level of
credentials, where the chat path never reads it.

The rest:

- modelDiscovery.ts missed the VertexModelMetadataProvenance cast that its
  read-path twin in db/models/synced.ts already had — both written by #12471.
- A provider-test regexp carried raw 0x00/0x1f bytes, which makes git, GitHub
  and ripgrep treat the file as binary. Same character class, written
  with escapes instead of the bytes themselves.
- #13399 (Agnes AI China) adds "agnes-cn" + "agnescn": the only two provider
  prefixes since the count was last set (412 -> 414). Everything else added in
  that range is model ids.
- The free-tier budget card SVG was stale (443 -> 452 models); regenerated by
  its own script.
- Three new tests were missing from stryker.conf.json tap.testFiles, so the
  mutants they kill did not count.

Three guards asserted syntax rather than the invariant they protect, and broke
when the source legitimately changed. Each was re-expressed and then verified by
mutating the source back:

- #2331 required modelEffort to head the rawEffort chain; #13556 deliberately
  put the server-selected force rule first. The real invariant is relative —
  modelEffort outranks the defaults a client injects — and it still trips when
  explicitReasoning is moved ahead of it.
- The OAuth loopback guard matched the isLocalhost arm literally; #9944 added
  `&& !opts?.manualLoopback`. It now matches the arm whatever guards it, and
  still fails when the hint stops being built.
- The i18n scanner flagged dynamically-built keys — t("effort." + mode) reaches
  it as a literal prefix, never a string. It now accepts a prefix that resolves
  to a namespace holding messages, and still fails when the namespace is gone.

tests/unit/sse-auth.test.ts (#12080) expected a bare null where #13879 now
returns the key-policy diagnostic — the same sentinel shape the terminal-state
path has used since #12441. The assertion was rewritten to the constraint #12080
actually protects: nothing usable comes back and neither connection leaks. The
contract risk that remains — those sentinels are truthy, and executeWebSearch
treats any truthy value as a credential — is filed as #13945 rather than
widened into this PR.

Refs #13866

* fix(quality): clear the second wave of release/v3.8.51 base-reds

The tip moved 13 commits while the first pass was running and brought its own
reds. All reproduced locally on the merged tree first.

vitest 4.1.11 -> 5.0.0 in the #13661 development-group bump is a major, and
vitest 5 moved `vite` from a dependency to a peerDependency. This repo only ever
declared `vite` under `overrides`, which pins a version but installs nothing, so
`npm ci` stopped providing it and the Vitest job died at startup with
ERR_MODULE_NOT_FOUND. Declared as the devDependency it actually is — the same
^8.0.16 the override already pinned, and what @vitejs/plugin-react asks for as a
peer — and regenerated the lockfile: 684 lines added, none changed.

#12909 filtered a mapped array with `toolCall is JsonRecord`, but the element
type is the tool-call literal or null, and a predicate's type has to be
assignable to the parameter's (TS2677). Narrowed by the element's own type
instead; the literal still satisfies JsonRecord at the return.

#12906 added `|| result.errorCode === "empty_response"` to the stream-failure
condition and Prettier rewrapped it, so the #8928 probe — which located the
branch by an exact four-line string — stopped finding it. It now matches on what
the branch tests rather than how it is typeset, and still fails when the
eviction call is removed.

probe-7293 is the visible half of a real conflict, filed as #13948. #7293 merges
a mid-array system into index 0; #12908, landed later, demotes it to "user" in
place instead. Both target the same constraint and only one can win, and the
combination also reorders: the pre-translation hoist moves the turn forward
expecting it to stay a system message, then the demotion converts it where it
now sits, ahead of the conversation. Choosing between the two strategies is a
product call, not a base-red one, so the test was realigned to assert the half
that protects the caller — the instruction survives, as a user turn — and pins
the current ordering with a pointer to the issue, so the eventual decision shows
up as a deliberate test change instead of a silent regression.

Refs #13866, #13948

* fix(quality): allowlist vite, rebaseline tip growth, drop a dead import

Third pass on the release/v3.8.51 base-reds. Declaring `vite` in the previous
commit was correct but incomplete: check-deps is a human review point against
typosquatting, so a newly declared package has to be vouched for by name.
Recorded in dependency-allowlist.json with why it is needed — the official Vite
build tool, already pinned through overrides, and a required peer of both
vitest 5 and @vitejs/plugin-react. That also turns check-deps.test.ts green.

check-file-size went red on nine files. One is mine: sse-auth.test.ts grew when
the #12080 assertion was rewritten. Three of the four assertions I had added
were redundant with the strict deepEqual that follows them, so they are gone and
the file grows by 4 lines instead of 8; the cap absorbs the rest.

The other eight are production and test files this PR does not touch, grown by
other work and never rebaselined — which is the whole reason a base-red drain
exists. Each is attributed to the commit that grew it: #12906 (chat.ts,
chatHelpers.ts, proxyFetch.ts, stream.ts), #12904 + #12910 (chatCore.ts), and
batch_api.test.ts from the same wave. Two of them predate the wave entirely and
were already over cap on 3d5baf13 — imageGeneration.ts (#13748) and
roundRobinCombo.ts (#13776) — so they were base-reds hiding behind a gate that
only surfaced them once the tip was merged in. Both are recorded separately from
the wave so the history stays honest about when each cap actually moved.

Note for whoever reads the gate next: it counts one line more than `wc -l`,
since it measures split length rather than newlines.

Finally, #13290 replaced rmSync with cleanupTempDataDir in
zcode-executor.test.ts but left the import behind, which the frozen-warning
ESLint gate rejects. Removed.

Refs #13866
2026-09-17 05:48:40 -03:00

658 lines
24 KiB
TypeScript

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";
import { SignJWT } from "jose";
import { NextRequest } from "next/server";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omr-authz-pipeline-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "test-secret";
const core = await import("../../../src/lib/db/core.ts");
const apiKeysDb = await import("../../../src/lib/db/apiKeys.ts");
const settingsDb = await import("../../../src/lib/db/settings.ts");
const pipeline = await import("../../../src/server/authz/pipeline.ts");
const csrf = await import("../../../src/server/authz/csrf.ts");
const dashboardCsrfConstants = await import("../../../src/shared/constants/dashboardCsrf.ts");
const ORIGINAL_JWT = process.env.JWT_SECRET;
const ORIGINAL_INITIAL = process.env.INITIAL_PASSWORD;
const ORIGINAL_AUTH_COOKIE_SECURE = process.env.AUTH_COOKIE_SECURE;
const ORIGINAL_REQUIRE_API_KEY = process.env.REQUIRE_API_KEY;
const ORIGINAL_OMNIROUTE_PUBLIC_BASE_URL = process.env.OMNIROUTE_PUBLIC_BASE_URL;
const ORIGINAL_NEXT_PUBLIC_BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const ORIGINAL_NEXT_PUBLIC_APP_URL = process.env.NEXT_PUBLIC_APP_URL;
const ORIGINAL_OMNIROUTE_TRUST_PROXY = process.env.OMNIROUTE_TRUST_PROXY;
const ORIGINAL_OMNIROUTE_PEER_STAMP_TOKEN = process.env.OMNIROUTE_PEER_STAMP_TOKEN;
function resetEnvironment() {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
process.env.JWT_SECRET = "pipeline-jwt-secret";
process.env.INITIAL_PASSWORD = "pipeline-initial-password";
process.env.REQUIRE_API_KEY = "true";
delete process.env.AUTH_COOKIE_SECURE;
delete process.env.OMNIROUTE_PUBLIC_BASE_URL;
delete process.env.NEXT_PUBLIC_BASE_URL;
delete process.env.NEXT_PUBLIC_APP_URL;
delete process.env.OMNIROUTE_TRUST_PROXY;
delete process.env.OMNIROUTE_PEER_STAMP_TOKEN;
globalThis.__omnirouteShutdown = { init: false, shuttingDown: false, activeRequests: 0 };
}
async function forceAuthRequired() {
await settingsDb.updateSettings({ requireLogin: true });
}
async function dashboardCookie(expiresIn = "1h"): Promise<string> {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const token = await new SignJWT({ authenticated: true })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime(expiresIn)
.sign(secret);
return `auth_token=${token}`;
}
function request(url: string, init?: RequestInit): NextRequest {
return new NextRequest(url, init);
}
test.beforeEach(() => {
resetEnvironment();
});
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
if (ORIGINAL_JWT === undefined) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = ORIGINAL_JWT;
if (ORIGINAL_INITIAL === undefined) delete process.env.INITIAL_PASSWORD;
else process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL;
if (ORIGINAL_AUTH_COOKIE_SECURE === undefined) delete process.env.AUTH_COOKIE_SECURE;
else process.env.AUTH_COOKIE_SECURE = ORIGINAL_AUTH_COOKIE_SECURE;
if (ORIGINAL_REQUIRE_API_KEY === undefined) delete process.env.REQUIRE_API_KEY;
else process.env.REQUIRE_API_KEY = ORIGINAL_REQUIRE_API_KEY;
if (ORIGINAL_OMNIROUTE_PUBLIC_BASE_URL === undefined)
delete process.env.OMNIROUTE_PUBLIC_BASE_URL;
else process.env.OMNIROUTE_PUBLIC_BASE_URL = ORIGINAL_OMNIROUTE_PUBLIC_BASE_URL;
if (ORIGINAL_NEXT_PUBLIC_BASE_URL === undefined) delete process.env.NEXT_PUBLIC_BASE_URL;
else process.env.NEXT_PUBLIC_BASE_URL = ORIGINAL_NEXT_PUBLIC_BASE_URL;
if (ORIGINAL_NEXT_PUBLIC_APP_URL === undefined) delete process.env.NEXT_PUBLIC_APP_URL;
else process.env.NEXT_PUBLIC_APP_URL = ORIGINAL_NEXT_PUBLIC_APP_URL;
if (ORIGINAL_OMNIROUTE_TRUST_PROXY === undefined) delete process.env.OMNIROUTE_TRUST_PROXY;
else process.env.OMNIROUTE_TRUST_PROXY = ORIGINAL_OMNIROUTE_TRUST_PROXY;
if (ORIGINAL_OMNIROUTE_PEER_STAMP_TOKEN === undefined) {
delete process.env.OMNIROUTE_PEER_STAMP_TOKEN;
} else {
process.env.OMNIROUTE_PEER_STAMP_TOKEN = ORIGINAL_OMNIROUTE_PEER_STAMP_TOKEN;
}
globalThis.__omnirouteShutdown = { init: false, shuttingDown: false, activeRequests: 0 };
});
test("runAuthzPipeline redirects root to dashboard before management auth", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(request("http://localhost/"), { enforce: true });
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/dashboard");
});
test("runAuthzPipeline redirects unauthenticated dashboard pages to login", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(request("http://localhost/dashboard"), {
enforce: true,
});
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/login");
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
assert.ok(response.headers.get("x-request-id"));
});
test("runAuthzPipeline redirects unauthenticated /home to login (#2712)", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(request("http://localhost/home"), {
enforce: true,
});
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/login");
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
test("runAuthzPipeline redirects unauthenticated /home/* nested paths to login (#2712)", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(request("http://localhost/home/settings"), {
enforce: true,
});
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/login");
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
// PR #1810 (upstream 9router): reverse-proxy subpath deployment via
// OMNIROUTE_BASE_PATH. Next.js strips the basePath from nextUrl.pathname
// before route classification, so the redirect targets must re-add it via
// request.nextUrl.basePath to stay inside the deployed subpath.
test("runAuthzPipeline prefixes the root-to-dashboard redirect with basePath when set", async () => {
await forceAuthRequired();
const req = new NextRequest("http://localhost/omniroute/", {
nextConfig: { basePath: "/omniroute" },
});
const response = await pipeline.runAuthzPipeline(req, { enforce: true });
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/omniroute/dashboard");
});
test("runAuthzPipeline prefixes the dashboard login redirect with basePath when set", async () => {
await forceAuthRequired();
const req = new NextRequest("http://localhost/omniroute/dashboard", {
nextConfig: { basePath: "/omniroute" },
});
const response = await pipeline.runAuthzPipeline(req, { enforce: true });
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/omniroute/login");
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
test("runAuthzPipeline leaves redirect targets unprefixed when basePath is empty", async () => {
await forceAuthRequired();
const req = new NextRequest("http://localhost/dashboard", {
nextConfig: { basePath: "" },
});
const response = await pipeline.runAuthzPipeline(req, { enforce: true });
assert.equal(response.status, 307);
assert.equal(response.headers.get("location"), "http://localhost/login");
});
test("runAuthzPipeline allows onboarding when login is required but no password exists", async () => {
delete process.env.INITIAL_PASSWORD;
await settingsDb.updateSettings({
requireLogin: true,
setupComplete: true,
password: "",
});
const response = await pipeline.runAuthzPipeline(
request("https://example.com/dashboard/onboarding"),
{ enforce: true }
);
assert.equal(response.status, 200);
assert.equal(response.headers.get("x-omniroute-route-class"), "PUBLIC");
});
test("runAuthzPipeline allows first password writes when login is required but no password exists — from the stamped loopback peer only (GHSA-7pq4-8pvv-rx7r)", async () => {
delete process.env.INITIAL_PASSWORD;
await settingsDb.updateSettings({
requireLogin: true,
setupComplete: true,
password: "",
});
// The local operator (real TCP peer 127.0.0.1, stamped by the custom server)
// keeps the first-password flow, whatever hostname they typed.
process.env.OMNIROUTE_PEER_STAMP_TOKEN = "pipeline-test-peer-stamp-token";
const local = await pipeline.runAuthzPipeline(
request("https://example.com/api/settings/require-login", {
method: "POST",
headers: {
"x-omniroute-peer-ip": "pipeline-test-peer-stamp-token|127.0.0.1",
"x-omniroute-via-proxy": "pipeline-test-peer-stamp-token|0",
},
}),
{ enforce: true }
);
assert.equal(local.status, 200);
assert.equal(local.headers.get("x-omniroute-route-class"), "MANAGEMENT");
// A remote peer — even one spelling the URL as localhost and forging the
// pipeline's own locality verdict header — must not reach the anonymous write
// that flips requireLogin=false (the first link of the JWT_SECRET chain).
const spoofed = await pipeline.runAuthzPipeline(
request("http://localhost/api/settings/require-login", {
method: "POST",
headers: {
host: "localhost",
"x-omniroute-peer-locality": "loopback",
"x-omniroute-peer-ip": "pipeline-test-peer-stamp-token|203.0.113.9",
"x-omniroute-via-proxy": "pipeline-test-peer-stamp-token|0",
},
}),
{ enforce: true }
);
assert.equal(spoofed.status, 401);
assert.equal((await spoofed.json()).error.code, "AUTH_001");
// No stamp at all (nothing trustworthy about the peer) → fail closed.
delete process.env.OMNIROUTE_PEER_STAMP_TOKEN;
const unstamped = await pipeline.runAuthzPipeline(
request("https://example.com/api/settings/require-login", { method: "POST" }),
{ enforce: true }
);
assert.equal(unstamped.status, 401);
});
test("runAuthzPipeline keeps management API rejections as JSON", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(request("http://localhost/api/keys"), {
enforce: true,
});
const body = await response.json();
assert.equal(response.status, 401);
assert.equal(response.headers.get("content-type")?.includes("application/json"), true);
assert.equal(body.error.code, "AUTH_001");
});
test("runAuthzPipeline rejects oversized API bodies before auth", async () => {
const response = await pipeline.runAuthzPipeline(
request("http://localhost/api/v1/chat/completions", {
method: "POST",
headers: {
"content-length": String(99 * 1024 * 1024),
origin: "https://app.example.com",
},
}),
{ enforce: true }
);
assert.equal(response.status, 413);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.ok(response.headers.get("x-request-id"));
assert.equal(
response.headers.get("Access-Control-Allow-Methods"),
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
});
test("runAuthzPipeline rejects oversized rewritten alias API bodies before auth", async () => {
const response = await pipeline.runAuthzPipeline(
request("http://localhost/v1/chat/completions", {
method: "POST",
headers: {
"content-length": String(99 * 1024 * 1024),
origin: "https://app.example.com",
},
}),
{ enforce: true }
);
assert.equal(response.status, 413);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.ok(response.headers.get("x-request-id"));
});
test("runAuthzPipeline rejects unauthenticated v1beta Gemini aliases as client API", async () => {
const response = await pipeline.runAuthzPipeline(
request("http://localhost/v1beta/models/gemini-pro:generateContent", {
method: "POST",
}),
{ enforce: true }
);
const body = await response.json();
assert.equal(response.status, 401);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.equal(body.error.code, "AUTH_002");
});
test("runAuthzPipeline rejects unauthenticated internal api v1beta routes as client API", async () => {
const response = await pipeline.runAuthzPipeline(
request("http://localhost/api/v1beta/models/gemini-pro:generateContent", {
method: "POST",
}),
{ enforce: true }
);
const body = await response.json();
assert.equal(response.status, 401);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.equal(body.error.code, "AUTH_002");
});
test("runAuthzPipeline rejects new API requests during shutdown drain", async () => {
globalThis.__omnirouteShutdown = { init: true, shuttingDown: true, activeRequests: 0 };
const response = await pipeline.runAuthzPipeline(request("http://localhost/api/v1/models"), {
enforce: true,
});
const body = await response.json();
assert.equal(response.status, 503);
assert.equal(body.error.code, "SERVICE_UNAVAILABLE");
assert.equal(response.headers.get("retry-after"), "5");
});
test("runAuthzPipeline rejects rewritten API aliases during shutdown drain", async () => {
globalThis.__omnirouteShutdown = { init: true, shuttingDown: true, activeRequests: 0 };
const response = await pipeline.runAuthzPipeline(request("http://localhost/responses"), {
enforce: true,
});
const body = await response.json();
assert.equal(response.status, 503);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.equal(body.error.code, "SERVICE_UNAVAILABLE");
assert.equal(response.headers.get("retry-after"), "5");
});
test("runAuthzPipeline allows dashboard sessions to read model catalog aliases", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(
request("http://localhost/v1/models", {
headers: { cookie: await dashboardCookie() },
}),
{ enforce: true }
);
assert.equal(response.status, 200);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
});
test("runAuthzPipeline gates the DB health API on loopback, not on the session alone", async () => {
await forceAuthRequired();
// #13717 moved /api/db/health to Tier 1 LOCAL_ONLY: runManagedDbHealthCheck()
// forks native diagnostics into a child process (Hard Rules #15 + #17), and the
// route is NOT in LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES. So a dashboard session
// is no longer sufficient by itself — an unstamped peer fails closed, whatever the
// URL says, because requestPeerAddress() never reads the spoofable Host header.
const unstamped = await pipeline.runAuthzPipeline(
request("http://localhost/api/db/health", {
headers: { cookie: await dashboardCookie() },
}),
{ enforce: true }
);
assert.equal(unstamped.status, 403);
// The local operator — real TCP peer 127.0.0.1, stamped by the custom server —
// still reaches it with their session.
process.env.OMNIROUTE_PEER_STAMP_TOKEN = "pipeline-test-peer-stamp-token";
const loopback = await pipeline.runAuthzPipeline(
request("http://localhost/api/db/health", {
headers: {
cookie: await dashboardCookie(),
"x-omniroute-peer-ip": "pipeline-test-peer-stamp-token|127.0.0.1",
"x-omniroute-via-proxy": "pipeline-test-peer-stamp-token|0",
},
}),
{ enforce: true }
);
assert.equal(loopback.status, 200);
assert.equal(loopback.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
test("runAuthzPipeline accepts dashboard mutations from configured public origin", async () => {
await forceAuthRequired();
process.env.NEXT_PUBLIC_BASE_URL = "https://gateway.example.test";
const response = await pipeline.runAuthzPipeline(
request("http://omniroute:20128/api/providers/health-autopilot/actions", {
method: "POST",
headers: {
cookie: await dashboardCookie(),
origin: "https://gateway.example.test",
"content-type": "application/json",
},
body: "{}",
}),
{ enforce: true }
);
assert.equal(response.status, 200);
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
test("runAuthzPipeline rejects dashboard mutations from dynamic public origins without CSRF", async () => {
await forceAuthRequired();
const response = await pipeline.runAuthzPipeline(
request("http://127.0.0.1:20128/api/settings", {
method: "PATCH",
headers: {
cookie: await dashboardCookie(),
host: "127.0.0.1:20128",
origin: "https://random-tunnel.example.test",
"content-type": "application/json",
"sec-fetch-site": "same-origin",
},
body: "{}",
}),
{ enforce: true }
);
const body = await response.json();
assert.equal(response.status, 403);
assert.equal(body.error.code, "INVALID_ORIGIN");
});
test("runAuthzPipeline accepts dashboard mutations from dynamic public origins with CSRF", async () => {
await forceAuthRequired();
const cookie = await dashboardCookie();
const issued = csrf.issueDashboardCsrfToken(
request("http://127.0.0.1:20128/api/auth/csrf", {
headers: { cookie },
})
);
assert.ok(issued);
for (const [method, path] of [
["POST", "/api/models/test"],
["POST", "/api/keys"],
["PATCH", "/api/settings"],
["PUT", "/api/combos/combo-1"],
["DELETE", "/api/webhooks/webhook-1"],
] as const) {
const response = await pipeline.runAuthzPipeline(
request(`http://127.0.0.1:20128${path}`, {
method,
headers: {
cookie,
host: "127.0.0.1:20128",
origin: "https://random-tunnel.example.test",
"content-type": "application/json",
[dashboardCsrfConstants.DASHBOARD_CSRF_HEADER]: issued.token,
"sec-fetch-site": "same-origin",
},
body: "{}",
}),
{ enforce: true }
);
assert.equal(response.status, 200, path);
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
}
});
test("runAuthzPipeline does not let CSRF bypass cross-site fetch metadata", async () => {
await forceAuthRequired();
const cookie = await dashboardCookie();
const issued = csrf.issueDashboardCsrfToken(
request("http://127.0.0.1:20128/api/auth/csrf", {
headers: { cookie },
})
);
assert.ok(issued);
const response = await pipeline.runAuthzPipeline(
request("http://127.0.0.1:20128/api/settings", {
method: "PATCH",
headers: {
cookie,
host: "127.0.0.1:20128",
origin: "https://random-tunnel.example.test",
"content-type": "application/json",
[dashboardCsrfConstants.DASHBOARD_CSRF_HEADER]: issued.token,
"sec-fetch-site": "cross-site",
},
body: "{}",
}),
{ enforce: true }
);
const body = await response.json();
assert.equal(response.status, 403);
assert.equal(body.error.code, "INVALID_ORIGIN");
});
test("runAuthzPipeline rejects dashboard mutations from invalid browser origin", async () => {
await forceAuthRequired();
process.env.NEXT_PUBLIC_BASE_URL = "https://gateway.example.test";
const response = await pipeline.runAuthzPipeline(
request("http://omniroute:20128/api/providers/health-autopilot/actions", {
method: "POST",
headers: {
cookie: await dashboardCookie(),
origin: "https://evil.example",
"content-type": "application/json",
},
body: "{}",
}),
{ enforce: true }
);
const body = await response.json();
assert.equal(response.status, 403);
assert.equal(body.error.code, "INVALID_ORIGIN");
assert.match(body.error.message, /^Invalid request origin\./);
assert.match(body.error.message, /OMNIROUTE_PUBLIC_BASE_URL/);
});
test("runAuthzPipeline answers OPTIONS /v1/models preflight with Allow-Origin (#5242)", async () => {
// Literal Wayland AI / Electron repro: browser preflight with an Origin and
// no CORS_ALLOW_ALL must still receive Access-Control-Allow-Origin so the
// renderer is allowed to read the catalog response.
delete process.env.CORS_ALLOW_ALL;
delete process.env.CORS_ALLOWED_ORIGINS;
const response = await pipeline.runAuthzPipeline(
request("http://localhost/v1/models", {
method: "OPTIONS",
headers: { origin: "http://localhost" },
}),
{ enforce: true }
);
assert.equal(response.status, 204);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.equal(response.headers.get("Access-Control-Allow-Origin"), "http://localhost");
assert.match(response.headers.get("Vary") || "", /Origin/);
// Token-auth surface — must NOT advertise credentials with the echoed origin.
assert.equal(response.headers.get("Access-Control-Allow-Credentials"), null);
});
test("runAuthzPipeline serves GET /v1/models with Allow-Origin to dashboard session (#5242)", async () => {
await forceAuthRequired();
delete process.env.CORS_ALLOW_ALL;
delete process.env.CORS_ALLOWED_ORIGINS;
const response = await pipeline.runAuthzPipeline(
request("http://localhost/v1/models", {
headers: { cookie: await dashboardCookie(), origin: "http://localhost" },
}),
{ enforce: true }
);
assert.equal(response.status, 200);
assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
assert.equal(response.headers.get("Access-Control-Allow-Origin"), "http://localhost");
assert.equal(response.headers.get("Access-Control-Allow-Credentials"), null);
});
test("runAuthzPipeline keeps MANAGEMENT OPTIONS fail-closed for arbitrary origin (#5242)", async () => {
delete process.env.CORS_ALLOW_ALL;
delete process.env.CORS_ALLOWED_ORIGINS;
const response = await pipeline.runAuthzPipeline(
request("http://localhost/api/keys", {
method: "OPTIONS",
headers: { origin: "http://localhost" },
}),
{ enforce: true }
);
assert.equal(response.status, 204);
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
// Management surface is cookie-authed → no permissive origin echo.
assert.equal(response.headers.get("Access-Control-Allow-Origin"), null);
});
test("runAuthzPipeline refreshes dashboard JWTs near expiry", async () => {
await forceAuthRequired();
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const expiringToken = await new SignJWT({ authenticated: true })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("1h")
.sign(secret);
const response = await pipeline.runAuthzPipeline(
request("http://localhost/dashboard", {
headers: { cookie: `auth_token=${expiringToken}` },
}),
{ enforce: true }
);
assert.equal(response.status, 200);
assert.match(response.headers.get("set-cookie") || "", /auth_token=/);
});
test("runAuthzPipeline clears stale dashboard JWTs without error-stack noise", async () => {
await forceAuthRequired();
const oldSecret = new TextEncoder().encode("old-dashboard-jwt-secret");
const staleToken = await new SignJWT({ authenticated: true })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("1h")
.sign(oldSecret);
const errorCalls: unknown[][] = [];
const originalError = console.error;
const originalWarn = console.warn;
console.error = (...args: unknown[]) => {
errorCalls.push(args);
};
console.warn = () => {};
try {
const response = await pipeline.runAuthzPipeline(
request("http://localhost/dashboard", {
headers: { cookie: `auth_token=${staleToken}` },
}),
{ enforce: true }
);
assert.equal(response.status, 307);
const setCookie = response.headers.get("set-cookie") || "";
assert.match(setCookie, /auth_token=/);
assert.match(setCookie, /Max-Age=0|Expires=/i);
assert.equal(errorCalls.length, 0);
} finally {
console.error = originalError;
console.warn = originalWarn;
}
});