GeezerVison is showing github.com — fix(server,adapters): close the virtual-model scope gap and harden qu… · lidge-jun/opencodex@6a4b584
File treeExpand file treeCollapse file tree Open diff view settings devlog/_plan/260920_meaning_preservation_batch
Expand file treeCollapse file tree Open diff view settings Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -77,6 +77,29 @@ everything". | 77 | 77 | Out of scope and deliberately not started: Redis, a full multi-tenant conversion, | 78 | 78 | and any budget or RPM/TPM system. | 79 | 79 |
| | 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 | + | 80 | 103 | ## Verification | 81 | 104 |
| 82 | 105 | Static source review plus exact-head hosted CI. No local suite, individual test, | |
Collapse file Copy file name to clipboardExpand all lines: src/adapters/run-turn-queue.ts +9Lines changed: 9 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -37,6 +37,11 @@ export const DEFAULT_MAX_BACKLOG_CODE_UNITS = 32 * 1024 * 1024; | 37 | 37 | * however empty the queue is, so it must be refused even with the whole | 38 | 38 | * aggregate free. They also report different terminal messages, so an operator | 39 | 39 | * 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. | 40 | 45 | */ | 41 | 46 | export const DEFAULT_MAX_EVENT_CODE_UNITS = 8 * 1024 * 1024; | 42 | 47 |
| @@ -67,6 +72,10 @@ const RETENTION_MAX_NODES = 4096; | 67 | 72 | * of a kind and not payload anyone is buffering. | 68 | 73 | */ | 69 | 74 | 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; | 70 | 79 | let total = 0; | 71 | 80 | let nodes = 0; | 72 | 81 | const seen = new Set<object>(); | |
Collapse file Copy file name to clipboardExpand all lines: src/server/responses/request-prepare.ts +9Lines changed: 9 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -115,6 +115,7 @@ import { | 115 | 115 | AdmissionModelDeniedError, | 116 | 116 | assertRouteAllowedByScope, | 117 | 117 | resolveAdmissionModelScope, | | 118 | + routeAllowedByScope, | 118 | 119 | } from "../admission-model-scope"; | 119 | 120 | import { nativeContextLimits } from "../../codex/catalog"; | 120 | 121 | import { streamingContextOverflowResponse } from "./context-overflow"; | @@ -1041,6 +1042,14 @@ export async function prepareResponsesRequest( | 1041 | 1042 | inboundTransport: options.inboundTransport, | 1042 | 1043 | claudeGoAffinity: options.claudeGoAffinity, | 1043 | 1044 | }); | | 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 | + } | 1044 | 1053 | // Attribute local auth/cooldown failures to the public selector too; exact auth may fail before | 1045 | 1054 | // the normal post-resolution provider label is assigned. | 1046 | 1055 | if (route.codexAccountNamespace) { | |
Collapse file Copy file name to clipboardExpand all lines: src/server/search.ts +12Lines changed: 12 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -25,6 +25,12 @@ import { codexAccountNamespaceForModel } from "../codex/account-namespace-match" | 25 | 25 | import { NATIVE_RESERVE_MODEL } from "../codex/catalog/native-models"; | 26 | 26 | import { isCodexReserveRequestEligible } from "../codex/loopback-target"; | 27 | 27 | import type { DataPlaneAdmission } from "./auth-cors"; | | 28 | +import { | | 29 | + admissionModelDeniedResponse, | | 30 | + AdmissionModelDeniedError, | | 31 | + resolveAdmissionModelScope, | | 32 | + routeAllowedByScope, | | 33 | +} from "./admission-model-scope"; | 28 | 34 | import { formatCodexProviderForLog } from "../codex/routing"; | 29 | 35 | import { signalWithTimeout } from "../lib/abort"; | 30 | 36 | import { readBoundedResponseBytes } from "../lib/bounded-body"; | @@ -87,6 +93,12 @@ export async function handleSearch( | 87 | 93 | if (!route.codexAccountId || route.codexAccountNamespace !== accountNamespace) { | 88 | 94 | return formatErrorResponse(400, "invalid_request_error", "Invalid Codex account-qualified search model"); | 89 | 95 | } | | 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 | + } | 90 | 102 | exactAccount = { accountId: route.codexAccountId, modelId: route.modelId }; | 91 | 103 | logCtx.provider = `${route.providerName}-${accountNamespace}`; | 92 | 104 | logCtx.routeDecision = route.routeDecision; | |
Collapse file Copy file name to clipboardExpand all lines: tests/adapters/run-turn-queue.test.ts +7-1Lines changed: 7 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -424,7 +424,9 @@ describe("run-turn adapter event queue retained-payload budgets", () => { | 424 | 424 | const pending = iterator.next(); | 425 | 425 | queue.push(text("x".repeat(1_000))); | 426 | 426 |
| 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. | 428 | 430 | expect(await pending).toEqual({ done: false, value: text("x".repeat(1_000)) }); | 429 | 431 | expect(backlogExceeded).toBe(0); | 430 | 432 | expect(queue.retainedCodeUnits()).toBe(0); | @@ -495,6 +497,10 @@ describe("run-turn adapter event queue retained-payload budgets", () => { | 495 | 497 | expect(retainedEventCodeUnits(text("abcd"))).toBe(4); | 496 | 498 | expect(retainedEventCodeUnits(heartbeat)).toBe(0); | 497 | 499 | 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); | 498 | 504 | // Nested provider-shaped payload is counted; a cycle terminates. | 499 | 505 | const cyclic: Record<string, unknown> = { owner: "abc" }; | 500 | 506 | cyclic.self = cyclic; | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
| 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"; | 2 | 9 | import { | 3 | 10 | admissionModelDeniedBody, | 4 | 11 | AdmissionModelDeniedError, | @@ -9,13 +16,36 @@ import { | 9 | 16 | resolveAdmissionModelScope, | 10 | 17 | routeAllowedByScope, | 11 | 18 | } from "../../src/server/admission-model-scope"; | 12 | | -import { apiKeyEntrySchema } from "../../src/config/schema/leaf-validators"; | 13 | 19 | import { routeModel } from "../../src/router"; | 14 | 20 | import type { OcxConfig } from "../../src/types"; | | 21 | +import { removeTreeWithRetry } from "../helpers/remove-tree"; | 15 | 22 |
| 16 | 23 | const KEY = "ocx_data_" + "a".repeat(40); | 17 | 24 | const OTHER_KEY = "ocx_data_" + "b".repeat(40); | 18 | 25 |
| | 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 | + | 19 | 49 | function configWithKey(scope: { allowedProviders?: string[]; allowedModels?: string[] }): Pick<OcxConfig, "apiKeys"> { | 20 | 50 | return { | 21 | 51 | apiKeys: [ | @@ -104,21 +134,26 @@ describe("per-key model and provider scope", () => { | 104 | 134 | }); | 105 | 135 |
| 106 | 136 | 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 | + | 109 | 141 | // Every other field on this record degrades to a default. These two must | 110 | 142 | // 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. | 112 | 146 | 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)] }, | 117 | 151 | ]) { | 118 | | - expect(apiKeyEntrySchema.safeParse(damaged).success).toBe(false); | | 152 | + expect(loadKeysFrom([damaged, open])).toEqual(["coding"]); | 119 | 153 | } | | 154 | + | 120 | 155 | // A degrading neighbour still degrades, so the fail-closed choice is scoped | 121 | 156 | // 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); | 123 | 158 | }); | 124 | 159 | }); |
|