GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): hold the images relay to the calling key's model scope · lidge-jun/opencodex@35160ac

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • scripts/test-layout
    • layout.json
  • src/server
    • admission-model-scope.ts
    • images.ts
    • index
      • serve-options.ts
  • tests
    • fixtures
      • test-layout-expected.json
    • server
      • api-key-scope-images.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎scripts/test-layout/layout.json‎

Copy file name to clipboardExpand all lines: scripts/test-layout/layout.json
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1584,7 +1584,8 @@
15841584
"chat-inline-document-bytes.test.ts": "responses",
15851585
"devin-output-budget.test.ts": "providers",
15861586
"api-key-model-scope.test.ts": "server",
1587-
"docs-provider-discovery-limits.test.ts": "ci-workflows"
1587+
"docs-provider-discovery-limits.test.ts": "ci-workflows",
1588+
"api-key-scope-images.test.ts": "server"
15881589
},
15891590
"migrated": [
15901591
"adapters",
Collapse file

‎src/server/admission-model-scope.ts‎

Copy file name to clipboardExpand all lines: src/server/admission-model-scope.ts
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,26 @@ export function assertRouteAllowedByScope(
164164
throw new AdmissionModelDeniedError(requestedModel, route);
165165
}
166166
}
167+
168+
/**
169+
* The refusal a non-routed data-plane surface returns, or undefined when the
170+
* destination is permitted.
171+
*
172+
* The Responses path resolves a route inside a try/catch and throws from the
173+
* point the destination becomes concrete. The endpoints beside it -- images,
174+
* audio, voice and the search relay -- have no router and no such boundary:
175+
* each picks its own upstream inline and returns a Response. This is the same
176+
* predicate against the same kind of resolved destination, shaped for that
177+
* control flow, so a key that may not reach a provider is refused identically
178+
* whichever surface it asked through.
179+
*/
180+
export function admissionScopeDenial(
181+
config: Pick<OcxConfig, "apiKeys">,
182+
admission: DataPlaneAdmission | undefined,
183+
requestedModel: string,
184+
route: ScopedRoute,
185+
): Response | undefined {
186+
const scope = resolveAdmissionModelScope(config, admission);
187+
if (routeAllowedByScope(scope, route)) return undefined;
188+
return admissionModelDeniedResponse(new AdmissionModelDeniedError(requestedModel, route));
189+
}
Collapse file

‎src/server/images.ts‎

Copy file name to clipboardExpand all lines: src/server/images.ts
+65-6Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ import { selectProactiveApiKeyTransport } from "../providers/key-failover";
3333
import { getProviderRegistryEntry } from "../providers/registry";
3434
import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress";
3535
import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "./auth-cors";
36+
import type { DataPlaneAdmission } from "./auth-cors";
37+
import { admissionScopeDenial } from "./admission-model-scope";
3638
import type { RequestLogContext } from "./request-log";
3739
import { codexLogAccountId, decodeRequestErrorResponse } from "./responses";
3840
import { getValidAccessToken, getOAuthCredentialProjectId } from "../oauth/index";
@@ -115,6 +117,24 @@ export async function readImageResponseBytes(
115117
}
116118

117119
const CCA_IMAGE_MODEL = "gemini-3.1-flash-image";
120+
const XAI_IMAGE_BRIDGE_MODEL = "grok-imagine-image-quality";
121+
122+
/**
123+
* What a body that names no model resolves to for a scope decision.
124+
*
125+
* This relay copies the body through, so an absent `model` leaves the upstream
126+
* to pick one and there is no destination a scoped key could be shown to be
127+
* allowed to reach. A key with a model list is refused rather than sent to
128+
* whatever the provider defaults to; a key scoped only by provider is not
129+
* affected, and an unscoped key never reaches this at all.
130+
*/
131+
export const UNNAMED_IMAGE_MODEL = "(unnamed)";
132+
133+
/** The selector to echo in a refusal: the string the caller itself sent. */
134+
function requestedImageSelector(body: unknown): string {
135+
const model = (body as { model?: unknown } | null)?.model;
136+
return typeof model === "string" && model.trim() ? model : UNNAMED_IMAGE_MODEL;
137+
}
118138

119139
/**
120140
* Google Gemini finishReasons that indicate a permanent content/safety block.
@@ -207,11 +227,21 @@ async function tryCcaImageGeneration(
207227
logCtx: RequestLogContext,
208228
signal: AbortSignal,
209229
endpoint: ImagesEndpoint,
230+
admission: DataPlaneAdmission | undefined,
210231
): Promise<Response | undefined> {
211232
if (endpoint !== "generations") return undefined;
212233
const provider = config.providers?.["google-antigravity"];
213234
if (!provider || provider.disabled) return undefined;
214235

236+
// The destination is decided here, not by the caller: this branch always
237+
// bills Antigravity for CCA_IMAGE_MODEL whatever the body named. That is the
238+
// pair a scoped key is held to.
239+
const denial = admissionScopeDenial(config, admission, requestedImageSelector(body), {
240+
providerName: "google-antigravity",
241+
modelId: CCA_IMAGE_MODEL,
242+
});
243+
if (denial) return denial;
244+
215245
const prompt = (body as { prompt?: unknown })?.prompt;
216246
if (typeof prompt !== "string" || !prompt.trim()) {
217247
return formatErrorResponse(400, "invalid_request_error", "prompt is required and must not be empty");
@@ -446,10 +476,20 @@ async function tryXaiImageRelay(
446476
logCtx: RequestLogContext,
447477
signal: AbortSignal | undefined,
448478
endpoint: ImagesEndpoint,
479+
admission: DataPlaneAdmission | undefined,
449480
): Promise<Response | undefined> {
450481
if (config.images?.bridgeEnabled !== true) return undefined;
451482
const found = findXaiProvider(config);
452483
if (!found) return undefined;
484+
const bridgeModel = config.images?.bridgeModel ?? XAI_IMAGE_BRIDGE_MODEL;
485+
// The bridge sends this request to the configured xAI provider and the bridge
486+
// model regardless of the selector in the body, so that is what the key is
487+
// checked against.
488+
const denial = admissionScopeDenial(config, admission, requestedImageSelector(body), {
489+
providerName: found.name,
490+
modelId: bridgeModel,
491+
});
492+
if (denial) return denial;
453493
const obj = body && typeof body === "object" && !Array.isArray(body)
454494
? body as Record<string, unknown>
455495
: {};
@@ -496,11 +536,11 @@ async function tryXaiImageRelay(
496536
}
497537
if (!token) return xaiImageAuthMissing();
498538
logCtx.provider = "xai";
499-
logCtx.model = config.images?.bridgeModel ?? "grok-imagine-image-quality";
539+
logCtx.model = bridgeModel;
500540
const result = await callXaiImages(
501541
{
502542
prompt,
503-
model: logCtx.model,
543+
model: bridgeModel,
504544
n,
505545
size,
506546
quality,
@@ -602,6 +642,7 @@ export async function handleImages(
602642
endpoint: ImagesEndpoint,
603643
logCtx: RequestLogContext,
604644
turnAdmissionLease?: AdmissionLease,
645+
admission?: DataPlaneAdmission,
605646
): Promise<Response> {
606647
let body: unknown;
607648
try {
@@ -616,7 +657,7 @@ export async function handleImages(
616657
// Explicit images.provider owns the route, including its validation errors.
617658
// Do not divert that selection to the xAI Imagine relay.
618659
if (config.images?.provider === undefined) {
619-
const xaiRelay = await tryXaiImageRelay(body, config, logCtx, req.signal, endpoint);
660+
const xaiRelay = await tryXaiImageRelay(body, config, logCtx, req.signal, endpoint, admission);
620661
if (xaiRelay) return xaiRelay;
621662
}
622663
if (candidates.error) {
@@ -641,7 +682,7 @@ export async function handleImages(
641682
const canUseOpenAiForward = !skipOpenAiForwardForAdmissionBearer && candidates.forwardCandidates.length > 0;
642683

643684
if (!canUseOpenAiForward && !candidates.keyed) {
644-
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
685+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint, admission);
645686
if (ccaResponse) return ccaResponse;
646687
// 400, not 5xx: codex retries every 5xx up to 5 total attempts, and this is a permanent
647688
// configuration state that must surface on the first attempt.
@@ -688,7 +729,20 @@ export async function handleImages(
688729

689730
const headers: Record<string, string> = { "content-type": "application/json" };
690731
let url: string;
732+
// Both relay branches copy the body upstream, so the destination is the
733+
// provider chosen in that branch and the model the caller named. Each branch
734+
// is checked as it is entered, before it resolves a credential or commits a
735+
// key rotation, so a refused request spends nothing.
736+
const relaySelector = requestedImageSelector(body);
691737
if (forward) {
738+
const denial = admissionScopeDenial(config, admission, relaySelector, {
739+
providerName: forward.providerName,
740+
modelId: relaySelector,
741+
});
742+
if (denial) {
743+
forward.releaseProbeLease?.();
744+
return denial;
745+
}
692746
const { provider } = forward;
693747
if (provider.headers) Object.assign(headers, provider.headers);
694748
for (const [name, value] of forward.headers) headers[name] = value;
@@ -697,13 +751,18 @@ export async function handleImages(
697751
} else if (forwardAuthError) {
698752
// Before surfacing the OpenAI auth failure, try CCA — the user may have a
699753
// valid Google Antigravity login even though their OpenAI pool is broken.
700-
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
754+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint, admission);
701755
if (ccaResponse) return ccaResponse;
702756
// No CCA either: a configured OpenAI pool mode owns its authentication failure.
703757
// Do not hide a broken/expired pool behind separately billed API-key image generation.
704758
return forwardAuthError;
705759
} else if (candidates.keyed) {
706760
const { providerName } = candidates.keyed;
761+
const denial = admissionScopeDenial(config, admission, relaySelector, {
762+
providerName,
763+
modelId: relaySelector,
764+
});
765+
if (denial) return denial;
707766
// The keyed image path builds its own URL and Authorization header and never enters
708767
// handleResponses, so the pre-dispatch key pick happens here.
709768
//
@@ -737,7 +796,7 @@ export async function handleImages(
737796
url = `${provider.baseUrl.replace(/\/v1\/?$/, "")}/v1/images/${endpoint}`;
738797
} else {
739798
// No usable OpenAI credential — try CCA before giving up.
740-
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
799+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint, admission);
741800
if (ccaResponse) return ccaResponse;
742801
return formatErrorResponse(
743802
401,
Collapse file

‎src/server/index/serve-options.ts‎

Copy file name to clipboardExpand all lines: src/server/index/serve-options.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
12701270
};
12711271
const endpoint = url.pathname.endsWith("/edits") ? "edits" as const : "generations" as const;
12721272
return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => {
1273-
const response = await handleImages(req, config, endpoint, logCtx, turnAdmissionLease);
1273+
const response = await handleImages(req, config, endpoint, logCtx, turnAdmissionLease, admission);
12741274
addFinalRequestLog(requestId, start, logCtx, response.status, response.status === 499 ? { closeReason: "client_cancel" } : undefined);
12751275
return withCors(response, req, policy);
12761276
}, { requestId, start, logCtx });
Collapse file

‎tests/fixtures/test-layout-expected.json‎

Copy file name to clipboardExpand all lines: tests/fixtures/test-layout-expected.json
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1416,5 +1416,6 @@
14161416
"chat-inline-document-bytes.test.ts": "responses",
14171417
"devin-output-budget.test.ts": "providers",
14181418
"api-key-model-scope.test.ts": "server",
1419-
"docs-provider-discovery-limits.test.ts": "ci-workflows"
1419+
"docs-provider-discovery-limits.test.ts": "ci-workflows",
1420+
"api-key-scope-images.test.ts": "server"
14201421
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.