fix(api): enforce image generation API key auth (#8306)

* fix(api): enforce image generation API key auth

* fix(api): align image route auth guard with clientApiPolicy

The route-level guard added for image generation was stricter than the
authz middleware that already fronts /api/v1/* (src/proxy.ts →
clientApiPolicy), so requests the pipeline admits were 401'd by the
handler:

- A cookie-authenticated dashboard session was rejected under
  REQUIRE_API_KEY=true. The dashboard Media page
  (dashboard/cache/media) and the Playground call these routes with a
  session and no Bearer — the same mismatch already fixed for
  /api/playground/presets.
- A presented invalid key was rejected even with REQUIRE_API_KEY=false,
  where clientApiPolicy (#2257) and the sibling /v1/embeddings and
  /v1/web/fetch routes degrade a stale CLI key to anonymous instead.

Extract the shared guard into shared/utils/clientApiRouteAuth so both
image routes (and future /v1 handlers) mirror the middleware contract
instead of re-deriving it, and drop the now-dead auth imports.

Also switch the call-log attribution fallback back to `||`: with `??`,
an empty-string apiKeyId/apiKeyName would be persisted verbatim and
would block the request-scoped context, which the previous
`entry.apiKeyId || null` never did.

Tests: cover the dashboard-session and keyless-mode-invalid-key
branches, and split the auth/attribution cases into
image-generation-route-auth.test.ts to stay under the 800-line
new-test-file cap.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: alexey.nazarov@softmg.ru <alexey.nazarov@softmg.ru>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Alex
2026-07-28 04:38:25 +03:00
committed by GitHub
parent 6a59c09460
commit 53f8284842
7 changed files with 479 additions and 15 deletions

View File

@@ -3,8 +3,6 @@ import { withInjectionGuard } from "@/middleware/promptInjectionGuard";
import {
getProviderCredentialsWithQuotaPreflight,
clearRecoveredProviderState,
extractApiKey,
isValidApiKey,
} from "@/sse/services/auth";
import {
parseImageModel,
@@ -28,6 +26,8 @@ import { attachOmniRouteMetaHeaders } from "@/domain/omnirouteResponseMeta";
import { calculateModalCost } from "@/lib/usage/costCalculator";
import { generateRequestId } from "@/shared/utils/requestId";
import { getSpecialtyModelsResponse } from "@/app/api/v1/_shared/specialtyCatalog";
import { enforceClientApiRouteAuth } from "@/shared/utils/clientApiRouteAuth";
import { runWithCallLogApiKeyContext } from "@/lib/usage/callLogApiKeyContext";
export const dynamic = "force-dynamic";
@@ -105,6 +105,11 @@ async function postHandler(request, context) {
const body = validation.data;
const startTime = Date.now();
// Authenticate before policy enforcement. Policy checks intentionally allow
// keyless local mode and assume the route has already rejected invalid keys.
const authRejection = await enforceClientApiRouteAuth(request);
if (authRejection) return authRejection;
// Enforce API key policies (model restrictions + budget limits)
const policy = await enforceApiKeyPolicy(request, body.model);
if (policy.rejection) return policy.rejection;
@@ -231,14 +236,21 @@ async function postHandler(request, context) {
}
const generateImage = () =>
handleImageGeneration({
body,
credentials,
log,
...(isCustomModel && { resolvedProvider: provider }),
signal: request.signal,
clientHeaders: publicBaseUrlHeaders(request.headers),
});
runWithCallLogApiKeyContext(
{
apiKeyId: policy.apiKeyInfo?.id ?? null,
apiKeyName: policy.apiKeyInfo?.name ?? null,
},
() =>
handleImageGeneration({
body,
credentials,
log,
...(isCustomModel && { resolvedProvider: provider }),
signal: request.signal,
clientHeaders: publicBaseUrlHeaders(request.headers),
})
);
// Execute with proxy context when available, direct otherwise (#1904)
const result = await (credentials?.connectionId

View File

@@ -4,8 +4,6 @@ import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
import {
getProviderCredentialsWithQuotaPreflight,
clearRecoveredProviderState,
extractApiKey,
isValidApiKey,
} from "@/sse/services/auth";
import { getImageProvider } from "@omniroute/open-sse/config/imageRegistry.ts";
import * as log from "@/sse/utils/logger";
@@ -13,6 +11,8 @@ import { toJsonErrorPayload } from "@/shared/utils/upstreamError";
import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";
import { v1ImageGenerationSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { enforceClientApiRouteAuth } from "@/shared/utils/clientApiRouteAuth";
import { runWithCallLogApiKeyContext } from "@/lib/usage/callLogApiKeyContext";
/**
* Handle CORS preflight
@@ -55,6 +55,9 @@ export async function POST(request, { params }) {
body.model = `${rawProvider}/${body.model}`;
}
const authRejection = await enforceClientApiRouteAuth(request);
if (authRejection) return authRejection;
// Enforce API key policies (model restrictions + budget limits)
const policy = await enforceApiKeyPolicy(request, body.model);
if (policy.rejection) return policy.rejection;
@@ -84,7 +87,13 @@ export async function POST(request, { params }) {
);
}
const result = await handleImageGeneration({ body, credentials, log });
const result = await runWithCallLogApiKeyContext(
{
apiKeyId: policy.apiKeyInfo?.id ?? null,
apiKeyName: policy.apiKeyInfo?.name ?? null,
},
() => handleImageGeneration({ body, credentials, log })
);
if (result.success) {
await clearRecoveredProviderState(credentials);

View File

@@ -0,0 +1,26 @@
import { AsyncLocalStorage } from "node:async_hooks";
export interface CallLogApiKeyContext {
apiKeyId: string | null;
apiKeyName: string | null;
}
const callLogApiKeyContext = new AsyncLocalStorage<CallLogApiKeyContext>();
/**
* Bind API-key attribution to every call log emitted by one request.
*
* Modal handlers fan out into provider-specific helpers that write their own
* call logs. Request-scoped storage keeps that attribution available without
* threading identity parameters through every provider handler.
*/
export function runWithCallLogApiKeyContext<TResult>(
context: CallLogApiKeyContext,
callback: () => TResult
): TResult {
return callLogApiKeyContext.run(context, callback);
}
export function getCallLogApiKeyContext(): CallLogApiKeyContext | null {
return callLogApiKeyContext.getStore() ?? null;
}

View File

@@ -12,6 +12,7 @@ import { getDbInstance } from "../db/core";
import { collectReferencedArtifacts, selectCallLogIdsBefore } from "./callLogsBoundedQueries";
import { getRequestDetailLogByCallLogId } from "../db/detailedLogs";
import { shouldPersistToDisk } from "./migrations";
import { getCallLogApiKeyContext } from "./callLogApiKeyContext";
import {
getLoggedInputTokens,
getLoggedOutputTokens,
@@ -572,7 +573,12 @@ export async function saveCallLog(entry: any) {
if (!shouldPersistToDisk) return;
try {
const apiKeyId = entry.apiKeyId || null;
const apiKeyContext = getCallLogApiKeyContext();
// `||` (not `??`): an empty-string apiKeyId/apiKeyName is "unattributed",
// same as before this fallback existed — it must not be persisted verbatim
// nor block the request-scoped context.
const apiKeyId = entry.apiKeyId || apiKeyContext?.apiKeyId || null;
const apiKeyName = entry.apiKeyName || apiKeyContext?.apiKeyName || null;
const noLogEnabled = Boolean(entry.noLog) || (apiKeyId ? isNoLog(apiKeyId) : false);
const protectedRequestBody = noLogEnabled ? null : protectPayloadForLog(entry.requestBody);
@@ -619,7 +625,7 @@ export async function saveCallLog(entry: any) {
sourceFormat: entry.sourceFormat || null,
targetFormat: entry.targetFormat || null,
apiKeyId,
apiKeyName: entry.apiKeyName || null,
apiKeyName,
comboName: entry.comboName || null,
comboStepId: toStringOrNull(entry.comboStepId),
comboExecutionKey:

View File

@@ -0,0 +1,50 @@
/**
* Route-level authentication guard for CLIENT_API (`/api/v1/*`) handlers.
*
* Defence-in-depth companion to `clientApiPolicy`
* (src/server/authz/policies/clientApi.ts), which already fronts these routes
* through `src/proxy.ts`. The handler-level check must never be *stricter*
* than the middleware, otherwise callers the pipeline admits get a 401 from
* the route instead:
*
* - a presented key must be valid, but is only rejected while
* `REQUIRE_API_KEY=true`; with enforcement off a stale CLI key degrades to
* anonymous instead of failing the whole request (#2257);
* - a cookie-authenticated dashboard session is accepted in place of a key —
* the dashboard Media page and Playground call these routes with a session
* only (same fix as the preset auth mismatch in
* `src/app/api/playground/presets/route.ts`);
* - anonymous traffic stays allowed while `REQUIRE_API_KEY=false`.
*
* @module shared/utils/clientApiRouteAuth
*/
import { errorResponse } 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 { isRequireApiKeyEnabled } from "@/shared/utils/featureFlags";
import { isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
/**
* Authenticate a client-API request at the route level.
*
* @param request - The incoming request.
* @returns A 401 `Response` the handler must return, or `null` when the
* request may proceed to policy enforcement.
*/
export async function enforceClientApiRouteAuth(request: Request): Promise<Response | null> {
const apiKeyRaw = extractApiKey(request);
if (apiKeyRaw) {
if (await isValidApiKey(apiKeyRaw)) return null;
return isRequireApiKeyEnabled()
? errorResponse(HTTP_STATUS.UNAUTHORIZED, "Invalid API key")
: null;
}
if (await isDashboardSessionAuthenticated(request)) return null;
return isRequireApiKeyEnabled()
? errorResponse(HTTP_STATUS.UNAUTHORIZED, "Authentication required")
: null;
}

View File

@@ -0,0 +1,345 @@
/**
* Auth + call-log attribution contract for the image generation routes.
*
* Split out of image-generation-route.test.ts to stay under the 800-line
* new-test-file cap enforced by `npm run check:file-size`.
*/
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-image-route-auth-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "image-route-test-api-key-secret";
const core = await import("../../src/lib/db/core.ts");
const providersDb = await import("../../src/lib/db/providers.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const { getCallLogs } = await import("../../src/lib/usage/callLogs.ts");
const imageRoute = await import("../../src/app/api/v1/images/generations/route.ts");
const providerImageRoute =
await import("../../src/app/api/v1/providers/[provider]/images/generations/route.ts");
const v1ModelsCatalog = await import("../../src/app/api/v1/models/catalog.ts");
const originalFetch = globalThis.fetch;
async function resetStorage() {
globalThis.fetch = originalFetch;
apiKeysDb.resetApiKeyState();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
v1ModelsCatalog.__resetCatalogBuilderRunsForTest();
}
async function seedConnection(provider: string, apiKey: string) {
return providersDb.createProviderConnection({
provider,
authType: "apikey",
name: `${provider}-${Math.random().toString(16).slice(2, 8)}`,
apiKey,
isActive: true,
testStatus: "active",
providerSpecificData: {},
});
}
async function waitForCallLog(apiKeyId: string, timeoutMs = 2000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const logs = await getCallLogs({ apiKey: apiKeyId, limit: 5 });
const match = logs.find((log: { apiKeyId?: string | null }) => log.apiKeyId === apiKeyId);
if (match) return match;
await new Promise((resolve) => setTimeout(resolve, 25));
}
return null;
}
async function readErrorMessage(response: Response): Promise<string> {
const body = (await response.json()) as { error?: { message?: unknown } };
return typeof body.error?.message === "string" ? body.error.message : "";
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(() => {
globalThis.fetch = originalFetch;
apiKeysDb.resetApiKeyState();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("v1 image generation POST requires an API key when REQUIRE_API_KEY is enabled", async () => {
const originalRequireApiKey = process.env.REQUIRE_API_KEY;
process.env.REQUIRE_API_KEY = "true";
try {
const response = await imageRoute.POST(
new Request("http://localhost/api/v1/images/generations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "openai/gpt-image-2",
prompt: "authentication test",
}),
})
);
assert.equal(response.status, 401);
assert.match(await readErrorMessage(response), /Authentication required/);
} finally {
if (originalRequireApiKey === undefined) {
delete process.env.REQUIRE_API_KEY;
} else {
process.env.REQUIRE_API_KEY = originalRequireApiKey;
}
}
});
test("v1 image generation POST rejects an invalid presented API key", async () => {
const originalOmniRouteApiKey = process.env.OMNIROUTE_API_KEY;
const originalRequireApiKey = process.env.REQUIRE_API_KEY;
process.env.OMNIROUTE_API_KEY = "valid-image-route-key";
process.env.REQUIRE_API_KEY = "true";
try {
const response = await imageRoute.POST(
new Request("http://localhost/api/v1/images/generations", {
method: "POST",
headers: {
Authorization: "Bearer invalid-image-route-key",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "openai/gpt-image-2",
prompt: "invalid authentication test",
}),
})
);
assert.equal(response.status, 401);
assert.match(await readErrorMessage(response), /Invalid API key/);
} finally {
if (originalOmniRouteApiKey === undefined) {
delete process.env.OMNIROUTE_API_KEY;
} else {
process.env.OMNIROUTE_API_KEY = originalOmniRouteApiKey;
}
if (originalRequireApiKey === undefined) {
delete process.env.REQUIRE_API_KEY;
} else {
process.env.REQUIRE_API_KEY = originalRequireApiKey;
}
}
});
// Issue #2257: with enforcement off, a stale key in a CLI config must degrade to
// anonymous exactly like clientApiPolicy does — the route guard must not be
// stricter than the middleware that already fronts it.
test("v1 image generation POST ignores an invalid presented key while REQUIRE_API_KEY is off", async () => {
const originalOmniRouteApiKey = process.env.OMNIROUTE_API_KEY;
const originalRequireApiKey = process.env.REQUIRE_API_KEY;
process.env.OMNIROUTE_API_KEY = "valid-image-route-key";
process.env.REQUIRE_API_KEY = "false";
globalThis.fetch = async (url) => {
assert.equal(String(url), "http://localhost:7860/sdapi/v1/txt2img");
return new Response(JSON.stringify({ images: ["YW5vbnltb3Vz"] }), {
status: 200,
headers: { "content-type": "application/json" },
});
};
try {
const response = await imageRoute.POST(
new Request("http://localhost/api/v1/images/generations", {
method: "POST",
headers: {
Authorization: "Bearer stale-cli-key",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "sdwebui/stable-diffusion-v1-5",
prompt: "stale key degrades to anonymous",
}),
})
);
assert.equal(response.status, 200);
} finally {
if (originalOmniRouteApiKey === undefined) {
delete process.env.OMNIROUTE_API_KEY;
} else {
process.env.OMNIROUTE_API_KEY = originalOmniRouteApiKey;
}
if (originalRequireApiKey === undefined) {
delete process.env.REQUIRE_API_KEY;
} else {
process.env.REQUIRE_API_KEY = originalRequireApiKey;
}
}
});
// The dashboard Media page and Playground call these routes with a session
// cookie and no Bearer. clientApiPolicy admits them; the route guard must too.
test("v1 image generation POST accepts a dashboard session when REQUIRE_API_KEY is enabled", async () => {
const originalRequireApiKey = process.env.REQUIRE_API_KEY;
const originalJwtSecret = process.env.JWT_SECRET;
process.env.REQUIRE_API_KEY = "true";
process.env.JWT_SECRET = "image-route-dashboard-session-secret";
globalThis.fetch = async (url) => {
assert.equal(String(url), "http://localhost:7860/sdapi/v1/txt2img");
return new Response(JSON.stringify({ images: ["ZGFzaGJvYXJk"] }), {
status: 200,
headers: { "content-type": "application/json" },
});
};
try {
const { SignJWT } = await import("jose");
const token = await new SignJWT({ sub: "dashboard" })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("1h")
.sign(new TextEncoder().encode(process.env.JWT_SECRET));
const response = await imageRoute.POST(
new Request("http://localhost/api/v1/images/generations", {
method: "POST",
headers: {
Cookie: `auth_token=${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "sdwebui/stable-diffusion-v1-5",
prompt: "dashboard session test",
}),
})
);
assert.equal(response.status, 200);
} finally {
if (originalRequireApiKey === undefined) {
delete process.env.REQUIRE_API_KEY;
} else {
process.env.REQUIRE_API_KEY = originalRequireApiKey;
}
if (originalJwtSecret === undefined) {
delete process.env.JWT_SECRET;
} else {
process.env.JWT_SECRET = originalJwtSecret;
}
}
});
test("v1 image generation POST attributes its call log to the validated API key", async () => {
const createdKey = await apiKeysDb.createApiKey(
"Image generation caller",
"machine-image-generation"
);
await seedConnection("openai", "image-provider-key");
globalThis.fetch = async (url) => {
assert.equal(String(url), "https://api.openai.com/v1/images/generations");
return new Response(
JSON.stringify({
created: 123,
data: [{ url: "https://cdn.example.com/attributed-image.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
const response = await imageRoute.POST(
new Request("http://localhost/api/v1/images/generations", {
method: "POST",
headers: {
Authorization: `Bearer ${createdKey.key}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "openai/gpt-image-2",
prompt: "call log attribution test",
}),
})
);
assert.equal(response.status, 200);
const logged = await waitForCallLog(createdKey.id);
assert.ok(logged, "expected an attributed image-generation call log");
assert.equal(logged.apiKeyId, createdKey.id);
assert.equal(logged.apiKeyName, "Image generation caller");
});
test("provider-scoped image generation requires an API key when configured", async () => {
const originalRequireApiKey = process.env.REQUIRE_API_KEY;
process.env.REQUIRE_API_KEY = "true";
try {
const response = await providerImageRoute.POST(
new Request("http://localhost/api/v1/providers/openai/images/generations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gpt-image-2",
prompt: "provider-scoped authentication test",
}),
}),
{ params: Promise.resolve({ provider: "openai" }) }
);
assert.equal(response.status, 401);
assert.match(await readErrorMessage(response), /Authentication required/);
} finally {
if (originalRequireApiKey === undefined) {
delete process.env.REQUIRE_API_KEY;
} else {
process.env.REQUIRE_API_KEY = originalRequireApiKey;
}
}
});
test("provider-scoped image generation attributes its call log to the validated API key", async () => {
const createdKey = await apiKeysDb.createApiKey(
"Provider-scoped image caller",
"machine-provider-image"
);
await seedConnection("openai", "provider-scoped-upstream-key");
globalThis.fetch = async (url) => {
assert.equal(String(url), "https://api.openai.com/v1/images/generations");
return new Response(
JSON.stringify({
created: 456,
data: [{ url: "https://cdn.example.com/provider-scoped-image.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
const response = await providerImageRoute.POST(
new Request("http://localhost/api/v1/providers/openai/images/generations", {
method: "POST",
headers: {
Authorization: `Bearer ${createdKey.key}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-image-2",
prompt: "provider-scoped attribution test",
}),
}),
{ params: Promise.resolve({ provider: "openai" }) }
);
assert.equal(response.status, 200);
const logged = await waitForCallLog(createdKey.id);
assert.ok(logged, "expected an attributed provider-scoped image-generation call log");
assert.equal(logged.apiKeyId, createdKey.id);
assert.equal(logged.apiKeyName, "Provider-scoped image caller");
});

View File

@@ -13,6 +13,8 @@ const providersDb = await import("../../src/lib/db/providers.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const imageRoute = await import("../../src/app/api/v1/images/generations/route.ts");
const providerImageRoute =
await import("../../src/app/api/v1/providers/[provider]/images/generations/route.ts");
const imageEditRoute = await import("../../src/app/api/v1/images/edits/route.ts");
const { MAX_BODY_BYTES_IMAGE_EDIT } = await import("../../src/shared/middleware/bodySizeGuard.ts");
const v1ModelsCatalog = await import("../../src/app/api/v1/models/catalog.ts");
@@ -110,6 +112,20 @@ test.after(() => {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("image routes expose CORS preflight handlers", async () => {
const responses = await Promise.all([
imageRoute.OPTIONS(),
providerImageRoute.OPTIONS(),
imageEditRoute.OPTIONS(),
]);
for (const response of responses) {
assert.equal(response.status, 200);
assert.match(response.headers.get("Access-Control-Allow-Methods") ?? "", /POST/);
assert.equal(response.headers.get("Access-Control-Allow-Headers"), "*");
}
});
test("v1 image models GET exposes image-only modalities for credential-backed image-only models", async () => {
await seedConnection("topaz", { apiKey: "topaz-key" });
await seedConnection("stability-ai", { apiKey: "stability-key" });