Skip to content

Commit c67e596

Browse files
committed
fix: stop masking a failed pool read and a dead pool credential
Two CodeRabbit findings on #4292. getPoolSettings tolerated an unparseable 2xx body, and toDto fills defaults, so a failed read rendered as a disabled pool with default values that the panel treated as loaded -- and the next save would have written that fabricated state over the real configuration. Empty-body tolerance now belongs to the write only, where an empty 2xx really is a success. The keyed image path fell back to the pre-pick key snapshot when the selected reference would not resolve. The pick commits before returning, so that sent a non-idempotent POST with a credential the config no longer treats as active -- and specifically the key that was cooling. It is a configuration error now, and the new regression test asserts nothing reaches the upstream.
1 parent 6318374 commit c67e596

3 files changed

Lines changed: 72 additions & 9 deletions

File tree

‎gui/src/pool-settings.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,12 @@ export async function getPoolSettings(
9191
try {
9292
const response = await fetchImpl(`${apiBase}/api/pool/settings?provider=${encodeURIComponent(provider)}`, init);
9393
if (!response.ok) return null;
94-
return toDto(await response.json().catch(() => ({})), provider);
94+
// No empty-body tolerance on the READ. `toDto` fills defaults, so `{}` would render as a
95+
// disabled pool with default values and the panel would treat that as a loaded state --
96+
// letting the next save overwrite the real configuration from fabricated input. A read
97+
// with no parseable body is a failed read. The write below is the opposite case: there,
98+
// an empty 2xx is a real success and the fallback is the settings just sent.
99+
return toDto(await response.json(), provider);
95100
} catch {
96101
return null;
97102
}
@@ -141,4 +146,3 @@ export async function putCodexPoolStrategy(
141146
if (!settings) return { ok: false };
142147
return { ok: true, strategy: settings.strategy, stickyLimit: settings.stickyLimit };
143148
}
144-

‎src/server/images.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ import { sidecarEnter } from "../lib/sidecar-tracker";
2929
import type { OcxConfig } from "../types";
3030
import { resolveFirstUsableOpenAiSidecar, selectImagesProvider } from "../providers/openai-sidecar";
3131
import { selectProactiveApiKeyTransport } from "../providers/key-failover";
32-
import { resolveProviderApiKey } from "../providers/key-store";
3332
import { getProviderRegistryEntry } from "../providers/registry";
3433
import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress";
3534
import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "./auth-cors";
@@ -706,17 +705,27 @@ export async function handleImages(
706705
//
707706
// Two things about the placement. It stays INSIDE this branch because higher up it would
708707
// also run for requests ChatGPT forward goes on to serve, spending a rotation on a path
709-
// that never used the key. And the header is rebuilt from the returned clone rather than
708+
// that never used the key. And the header is rebuilt from the returned route rather than
710709
// from candidates.keyed.apiKey, which is a snapshot resolved earlier: reusing it would
711710
// send the OLD key while the picker had already persisted the new one.
711+
//
712712
// Transport variant: this branch reads `provider.baseUrl` and `provider.headers` to build
713-
// the URL and the request, and the persisted row carries neither for a built-in provider
714-
// stored in its minimal form.
713+
// the URL and the request, and it comes back with the credential already resolved.
715714
const warmKeyProvider = selectProactiveApiKeyTransport(config, providerName, candidates.keyed.provider);
716715
const provider = warmKeyProvider ?? candidates.keyed.provider;
717-
const apiKey = warmKeyProvider?.apiKey
718-
? (resolveProviderApiKey(warmKeyProvider.apiKey) ?? candidates.keyed.apiKey)
719-
: candidates.keyed.apiKey;
716+
// No fall back to the earlier snapshot once a pick has happened. The picker COMMITS its
717+
// choice before returning, so if the chosen reference will not resolve -- revoked keychain
718+
// entry, unset env var -- sending the previous key would authenticate a non-idempotent
719+
// POST with a credential the config no longer considers active, and the previous key is
720+
// the one that was cooling. Fail loudly instead.
721+
if (warmKeyProvider && !warmKeyProvider.apiKey?.trim()) {
722+
return formatErrorResponse(
723+
500,
724+
"configuration_error",
725+
`image generation selected an API key for "${providerName}" that cannot be resolved`,
726+
);
727+
}
728+
const apiKey = warmKeyProvider?.apiKey ?? candidates.keyed.apiKey;
720729
if (provider.headers) Object.assign(headers, provider.headers);
721730
headers["authorization"] = `Bearer ${apiKey}`;
722731
logCtx.provider = providerName;

‎tests/server/server-images.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,56 @@ test("a cooled committed key is replaced before the first keyed image send", asy
734734
}
735735
});
736736

737+
/**
738+
* The pick COMMITS its choice before returning, so an unresolvable selection is not a reason to
739+
* quietly reuse the previous key: that would authenticate a non-idempotent image POST with a
740+
* credential the config no longer treats as active, and the previous key is the one that was
741+
* cooling. Raised by CodeRabbit on #4292.
742+
*/
743+
test("an unresolvable selected key fails the keyed image send instead of reusing the old one", async () => {
744+
const captured: CapturedRequest[] = [];
745+
const upstream = fakeImagesUpstream(captured);
746+
clearKeyCooldowns();
747+
delete process.env.OCX_IMAGES_MISSING_KEY;
748+
const pooled = {
749+
...keyedProvider(upstream.url.toString().replace(/\/$/, "")),
750+
apiKeyPoolStrategy: "round-robin",
751+
apiKeyPool: [
752+
{ id: "first", key: "sk-platform-key" },
753+
// An env reference that is deliberately not set: a revoked keychain entry looks the same.
754+
{ id: "second", key: "\${OCX_IMAGES_MISSING_KEY}" },
755+
],
756+
};
757+
saveConfig({
758+
port: 0,
759+
defaultProvider: "openai-apikey",
760+
openaiProviderTierVersion: 2,
761+
providers: { openai: disabledOpenAiProvider, "openai-apikey": pooled },
762+
} as unknown as OcxConfig);
763+
const live = loadConfig();
764+
rotateKeyOn429(live, "openai-apikey", null, Date.now(), "sk-platform-key");
765+
const restored = loadConfig();
766+
restored.providers["openai-apikey"]!.apiKey = "sk-platform-key";
767+
saveConfig(restored);
768+
769+
const server = startServer(0);
770+
try {
771+
const response = await fetch(new URL("/v1/images/generations", server.url), {
772+
method: "POST",
773+
headers: { "content-type": "application/json", authorization: `Bearer ${DIRECT_CHATGPT_TOKEN}` },
774+
body: JSON.stringify({ prompt: "a cat", model: "gpt-image-2" }),
775+
});
776+
expect(response.status).toBe(500);
777+
// Nothing was sent. Red control: restore the `?? candidates.keyed.apiKey` fallback and this
778+
// becomes a 200 carrying Bearer sk-platform-key -- the cooled key the pool had left.
779+
expect(captured).toHaveLength(0);
780+
} finally {
781+
await server.stop(true);
782+
await upstream.stop(true);
783+
clearKeyCooldowns();
784+
}
785+
});
786+
737787
test("without a configured strategy the keyed image send keeps the cooled key", async () => {
738788
const captured: CapturedRequest[] = [];
739789
const upstream = fakeImagesUpstream(captured);

0 commit comments

Comments
 (0)