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,adapters): close the virtual-model scope gap and harden qu… · lidge-jun/opencodex@6a4b584

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • devlog/_plan/260920_meaning_preservation_batch
    • 050_lane_e.md
  • src
    • adapters
      • run-turn-queue.ts
    • server
      • responses
        • request-prepare.ts
      • search.ts
  • tests
    • adapters
      • run-turn-queue.test.ts
    • server
      • api-key-model-scope.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎devlog/_plan/260920_meaning_preservation_batch/050_lane_e.md‎

Copy file name to clipboardExpand all lines: devlog/_plan/260920_meaning_preservation_batch/050_lane_e.md
+23Lines changed: 23 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,29 @@ everything".
7777
Out of scope and deliberately not started: Redis, a full multi-tenant conversion,
7878
and any budget or RPM/TPM system.
7979

80+
#### What the scope does not cover, stated rather than implied
81+
82+
An adversarial review of the branch found authenticated data-plane endpoints that
83+
spend provider quota without resolving a model through the router, so the scope
84+
does not reach them:
85+
86+
- `/v1/images/generations` and `/v1/images/edits`,
87+
- `/v1/audio/transcriptions` and its streaming form,
88+
- `/v1/live`, `/v1/realtime/calls` and the standalone realtime sockets,
89+
- the non-account-qualified branch of `/v1/alpha/search`, which forwards the caller's
90+
model to a search sidecar without routing it.
91+
92+
The account-qualified search branch does route a model and is checked. The rest
93+
need a destination definition this lane does not own — an image or audio endpoint
94+
has a fixed-purpose model rather than a routed one — and inventing one here would
95+
be the multi-tenant expansion this batch rules out. They are recorded so the
96+
contract is not read as broader than it is.
97+
98+
The review also found that resolving an OpenAI virtual model rewrites
99+
`route.modelId` to the wire id after the initial check. That one was a real hole in
100+
the stated contract and is fixed: the settled route is re-checked after
101+
normalization, so the id that is billed is the id that was authorized.
102+
80103
## Verification
81104

82105
Static source review plus exact-head hosted CI. No local suite, individual test,
Collapse file

‎src/adapters/run-turn-queue.ts‎

Copy file name to clipboardExpand all lines: src/adapters/run-turn-queue.ts
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ export const DEFAULT_MAX_BACKLOG_CODE_UNITS = 32 * 1024 * 1024;
3737
* however empty the queue is, so it must be refused even with the whole
3838
* aggregate free. They also report different terminal messages, so an operator
3939
* reading the turn's error learns which happened.
40+
*
41+
* Like the aggregate, this governs what the queue RETAINS. An event handed
42+
* straight to a waiting consumer is never held here, so neither budget applies
43+
* to it: refusing it would abort a turn over memory this queue does not own,
44+
* and the consumer's own per-event bound governs that payload instead.
4045
*/
4146
export const DEFAULT_MAX_EVENT_CODE_UNITS = 8 * 1024 * 1024;
4247

@@ -67,6 +72,10 @@ const RETENTION_MAX_NODES = 4096;
6772
* of a kind and not payload anyone is buffering.
6873
*/
6974
export function retainedEventCodeUnits(event: AdapterEvent): number {
75+
// Defensive: this measures values an adapter produced. A malformed emission
76+
// has to become a terminal event, not a TypeError thrown out of push() with
77+
// the queue half-updated.
78+
if (!event || typeof event !== "object") return 0;
7079
let total = 0;
7180
let nodes = 0;
7281
const seen = new Set<object>();
Collapse file

‎src/server/responses/request-prepare.ts‎

Copy file name to clipboardExpand all lines: src/server/responses/request-prepare.ts
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ import {
115115
AdmissionModelDeniedError,
116116
assertRouteAllowedByScope,
117117
resolveAdmissionModelScope,
118+
routeAllowedByScope,
118119
} from "../admission-model-scope";
119120
import { nativeContextLimits } from "../../codex/catalog";
120121
import { streamingContextOverflowResponse } from "./context-overflow";
@@ -1041,6 +1042,14 @@ export async function prepareResponsesRequest(
10411042
inboundTransport: options.inboundTransport,
10421043
claudeGoAffinity: options.claudeGoAffinity,
10431044
});
1045+
// Normalization is the last thing that can move the destination: resolving an
1046+
// OpenAI virtual model rewrites route.modelId to the wire id that will
1047+
// actually be billed. A scope checked only before this would authorize the
1048+
// public selector and send the wire model, so the settled route is checked
1049+
// once more here.
1050+
if (!routeAllowedByScope(admissionScope, route)) {
1051+
return admissionModelDeniedResponse(new AdmissionModelDeniedError(inboundSelector, route));
1052+
}
10441053
// Attribute local auth/cooldown failures to the public selector too; exact auth may fail before
10451054
// the normal post-resolution provider label is assigned.
10461055
if (route.codexAccountNamespace) {
Collapse file

‎src/server/search.ts‎

Copy file name to clipboardExpand all lines: src/server/search.ts
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ import { codexAccountNamespaceForModel } from "../codex/account-namespace-match"
2525
import { NATIVE_RESERVE_MODEL } from "../codex/catalog/native-models";
2626
import { isCodexReserveRequestEligible } from "../codex/loopback-target";
2727
import type { DataPlaneAdmission } from "./auth-cors";
28+
import {
29+
admissionModelDeniedResponse,
30+
AdmissionModelDeniedError,
31+
resolveAdmissionModelScope,
32+
routeAllowedByScope,
33+
} from "./admission-model-scope";
2834
import { formatCodexProviderForLog } from "../codex/routing";
2935
import { signalWithTimeout } from "../lib/abort";
3036
import { readBoundedResponseBytes } from "../lib/bounded-body";
@@ -87,6 +93,12 @@ export async function handleSearch(
8793
if (!route.codexAccountId || route.codexAccountNamespace !== accountNamespace) {
8894
return formatErrorResponse(400, "invalid_request_error", "Invalid Codex account-qualified search model");
8995
}
96+
// This branch resolves a model through the router and bills the account it
97+
// names, so a scoped key is held to the same destination rule it is held
98+
// to on the inference path.
99+
if (!routeAllowedByScope(resolveAdmissionModelScope(config, admission), route)) {
100+
return admissionModelDeniedResponse(new AdmissionModelDeniedError(model, route));
101+
}
90102
exactAccount = { accountId: route.codexAccountId, modelId: route.modelId };
91103
logCtx.provider = `${route.providerName}-${accountNamespace}`;
92104
logCtx.routeDecision = route.routeDecision;
Collapse file

‎tests/adapters/run-turn-queue.test.ts‎

Copy file name to clipboardExpand all lines: tests/adapters/run-turn-queue.test.ts
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,9 @@ describe("run-turn adapter event queue retained-payload budgets", () => {
424424
const pending = iterator.next();
425425
queue.push(text("x".repeat(1_000)));
426426

427-
// The queue never held it, so neither budget has anything to say about it.
427+
// The queue never held it, so neither budget has anything to say about it:
428+
// both govern retained payload, and refusing this would abort a turn over
429+
// memory the queue does not own.
428430
expect(await pending).toEqual({ done: false, value: text("x".repeat(1_000)) });
429431
expect(backlogExceeded).toBe(0);
430432
expect(queue.retainedCodeUnits()).toBe(0);
@@ -495,6 +497,10 @@ describe("run-turn adapter event queue retained-payload budgets", () => {
495497
expect(retainedEventCodeUnits(text("abcd"))).toBe(4);
496498
expect(retainedEventCodeUnits(heartbeat)).toBe(0);
497499
expect(retainedEventCodeUnits(phasedText("ab", "commentary"))).toBe(12);
500+
// A malformed adapter emission has to become a terminal event, not a
501+
// TypeError thrown out of push() with the queue half-updated.
502+
expect(retainedEventCodeUnits(null as unknown as AdapterEvent)).toBe(0);
503+
expect(retainedEventCodeUnits("oops" as unknown as AdapterEvent)).toBe(0);
498504
// Nested provider-shaped payload is counted; a cycle terminates.
499505
const cyclic: Record<string, unknown> = { owner: "abc" };
500506
cyclic.self = cyclic;
Collapse file

‎tests/server/api-key-model-scope.test.ts‎

Copy file name to clipboardExpand all lines: tests/server/api-key-model-scope.test.ts
+46-11Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { describe, expect, test } from "bun:test";
1+
import { afterEach, describe, expect, test } from "bun:test";
2+
import { mkdtempSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
// The schema this exercises is reached through `src/config`, the entry the
6+
// runtime evaluates first. Importing `config/schema/*` directly enters that
7+
// module cycle from the wrong end and throws a TDZ ReferenceError.
8+
import { loadConfig } from "../../src/config";
29
import {
310
admissionModelDeniedBody,
411
AdmissionModelDeniedError,
@@ -9,13 +16,36 @@ import {
916
resolveAdmissionModelScope,
1017
routeAllowedByScope,
1118
} from "../../src/server/admission-model-scope";
12-
import { apiKeyEntrySchema } from "../../src/config/schema/leaf-validators";
1319
import { routeModel } from "../../src/router";
1420
import type { OcxConfig } from "../../src/types";
21+
import { removeTreeWithRetry } from "../helpers/remove-tree";
1522

1623
const KEY = "ocx_data_" + "a".repeat(40);
1724
const OTHER_KEY = "ocx_data_" + "b".repeat(40);
1825

26+
const previousHome = process.env.OPENCODEX_HOME;
27+
const homes: string[] = [];
28+
29+
afterEach(() => {
30+
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
31+
else process.env.OPENCODEX_HOME = previousHome;
32+
for (const home of homes.splice(0)) removeTreeWithRetry(home);
33+
});
34+
35+
/** Load a hand-written config.json the way a startup would, and report the keys that survived. */
36+
function loadKeysFrom(apiKeys: unknown[]): string[] {
37+
const home = mkdtempSync(join(tmpdir(), "ocx-key-scope-"));
38+
homes.push(home);
39+
process.env.OPENCODEX_HOME = home;
40+
writeFileSync(join(home, "config.json"), JSON.stringify({
41+
port: 10100,
42+
defaultProvider: "allowed",
43+
providers: { allowed: { adapter: "openai-chat", baseUrl: "https://allowed.test/v1", models: ["small"] } },
44+
apiKeys,
45+
}));
46+
return (loadConfig().apiKeys ?? []).map(entry => entry.name);
47+
}
48+
1949
function configWithKey(scope: { allowedProviders?: string[]; allowedModels?: string[] }): Pick<OcxConfig, "apiKeys"> {
2050
return {
2151
apiKeys: [
@@ -104,21 +134,26 @@ describe("per-key model and provider scope", () => {
104134
});
105135

106136
test("a malformed scope drops the key instead of widening it", () => {
107-
const valid = { key: KEY, id: "scoped", name: "mail", createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: ["zai-discount"] };
108-
expect(apiKeyEntrySchema.safeParse(valid).success).toBe(true);
137+
const scoped = { key: KEY, id: "scoped", name: "mail", createdAt: "2026-01-01T00:00:00.000Z", allowedProviders: ["zai-discount"] };
138+
const open = { key: OTHER_KEY, id: "open", name: "coding", createdAt: "2026-01-01T00:00:00.000Z" };
139+
expect(loadKeysFrom([scoped, open])).toEqual(["mail", "coding"]);
140+
109141
// Every other field on this record degrades to a default. These two must
110142
// not: degrading a damaged permission field reads as "allowed everything",
111-
// which is the one direction it can never fail.
143+
// which is the one direction it can never fail. The damaged key is dropped
144+
// and its still-valid neighbour survives, so one bad record does not take
145+
// the whole array with it.
112146
for (const damaged of [
113-
{ ...valid, allowedProviders: "zai-discount" },
114-
{ ...valid, allowedProviders: [""] },
115-
{ ...valid, allowedModels: [123] },
116-
{ ...valid, allowedModels: ["x".repeat(257)] },
147+
{ ...scoped, allowedProviders: "zai-discount" },
148+
{ ...scoped, allowedProviders: [""] },
149+
{ ...scoped, allowedModels: [123] },
150+
{ ...scoped, allowedModels: ["x".repeat(257)] },
117151
]) {
118-
expect(apiKeyEntrySchema.safeParse(damaged).success).toBe(false);
152+
expect(loadKeysFrom([damaged, open])).toEqual(["coding"]);
119153
}
154+
120155
// A degrading neighbour still degrades, so the fail-closed choice is scoped
121156
// to the permission fields rather than hardening the whole record.
122-
expect(apiKeyEntrySchema.safeParse({ ...valid, name: 7 }).success).toBe(true);
157+
expect(loadKeysFrom([{ ...scoped, name: 7 }, open])).toHaveLength(2);
123158
});
124159
});

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.