Skip to content

Commit bfaddd6

Browse files
author
Xinwei Gao
committed
fix(security): guard Antigravity model discovery
Route Cloud Code Assist discovery POSTs through the provider outbound policy and invalidate account-scoped live model cache when OAuth credentials change.
1 parent 929ef8b commit bfaddd6

8 files changed

Lines changed: 199 additions & 30 deletions

File tree

‎src/codex/catalog/provider-fetch.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import type { NormalizedComboConfig } from "../../combos/types";
4949
import {
5050
ProviderOutboundPolicyError,
5151
providerOutboundGet,
52+
providerOutboundPost,
5253
providerRedirectError,
5354
} from "../../lib/provider-outbound";
5455
import { redactSecretString } from "../../lib/redact";
@@ -948,13 +949,10 @@ async function fetchProviderModelsWithAuth(
948949
};
949950
};
950951
try {
951-
const providerFetch = (prov as OcxProviderConfig & { fetch?: typeof fetch }).fetch;
952952
const res = request.method === "POST"
953-
? await (providerFetch ?? globalThis.fetch)(url, {
954-
method: "POST",
953+
? await providerOutboundPost(name, prov, url, {
955954
headers,
956955
body: JSON.stringify({ project: auth.oauthProjectId }),
957-
redirect: "manual",
958956
signal: AbortSignal.timeout(8000),
959957
})
960958
: await providerOutboundGet(name, prov, url, {

‎src/lib/pinned-http.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,24 @@ import https from "node:https";
33

44
export type PinnedAddress = { address: string; family: number };
55

6-
export interface PinnedHttpGetOptions {
6+
export interface PinnedHttpRequestOptions {
77
headers?: HeadersInit;
88
maxBytes?: number;
99
idleTimeoutMs?: number;
1010
rejectUnauthorized?: boolean;
1111
context?: string;
1212
}
1313

14-
/**
15-
* GET a URL through one previously validated address. The original hostname
16-
* remains authoritative for Host, SNI, and certificate verification.
17-
*/
18-
export function pinnedHttpGet(
14+
/** @deprecated Use {@link PinnedHttpRequestOptions}. */
15+
export type PinnedHttpGetOptions = PinnedHttpRequestOptions;
16+
17+
function pinnedHttpRequest(
1918
url: string,
2019
pinned: PinnedAddress,
20+
method: "GET" | "POST",
21+
body: string | undefined,
2122
signal?: AbortSignal,
22-
options?: PinnedHttpGetOptions,
23+
options?: PinnedHttpRequestOptions,
2324
): Promise<Response> {
2425
const parsed = new URL(url);
2526
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
@@ -30,6 +31,9 @@ export function pinnedHttpGet(
3031
const maxBytes = options?.maxBytes;
3132
const headers = new Headers(options?.headers);
3233
headers.set("host", parsed.host);
34+
if (body !== undefined && !headers.has("content-length")) {
35+
headers.set("content-length", String(Buffer.byteLength(body)));
36+
}
3337
const requestHeaders: Record<string, string> = {};
3438
headers.forEach((value, key) => { requestHeaders[key] = value; });
3539

@@ -51,7 +55,7 @@ export function pinnedHttpGet(
5155
hostname: parsed.hostname,
5256
port: parsed.port || (parsed.protocol === "https:" ? 443 : 80),
5357
path: `${parsed.pathname}${parsed.search}`,
54-
method: "GET",
58+
method,
5559
headers: requestHeaders,
5660
...(parsed.protocol === "https:"
5761
? {
@@ -146,6 +150,33 @@ export function pinnedHttpGet(
146150
fail(error);
147151
});
148152
req.on("close", () => signal?.removeEventListener("abort", onAbort));
149-
req.end();
153+
req.end(body);
150154
});
151155
}
156+
157+
/**
158+
* GET a URL through one previously validated address. The original hostname
159+
* remains authoritative for Host, SNI, and certificate verification.
160+
*/
161+
export function pinnedHttpGet(
162+
url: string,
163+
pinned: PinnedAddress,
164+
signal?: AbortSignal,
165+
options?: PinnedHttpRequestOptions,
166+
): Promise<Response> {
167+
return pinnedHttpRequest(url, pinned, "GET", undefined, signal, options);
168+
}
169+
170+
/**
171+
* POST a string body through one previously validated address. The original
172+
* hostname remains authoritative for Host, SNI, and certificate verification.
173+
*/
174+
export function pinnedHttpPost(
175+
url: string,
176+
pinned: PinnedAddress,
177+
body: string,
178+
signal?: AbortSignal,
179+
options?: PinnedHttpRequestOptions,
180+
): Promise<Response> {
181+
return pinnedHttpRequest(url, pinned, "POST", body, signal, options);
182+
}

‎src/lib/provider-outbound.ts‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,19 @@ import {
66
providerDestinationConfigError,
77
resolvePublicAddresses,
88
} from "./destination-policy";
9-
import { pinnedHttpGet } from "./pinned-http";
9+
import { pinnedHttpGet, pinnedHttpPost } from "./pinned-http";
1010
import { outboundProxyConfigured } from "./proxy-env";
1111
import { publicProviderBaseUrl } from "./provider-url";
1212

1313
type ProviderGetInit = Omit<RequestInit, "body" | "method" | "redirect">;
14+
type ProviderPostInit = ProviderGetInit & { body: string };
1415
type ProviderOutboundConfig = Pick<OcxProviderConfig, "baseUrl" | "allowPrivateNetwork"> & {
1516
fetch?: typeof globalThis.fetch;
1617
};
1718
export interface ProviderOutboundDependencies {
1819
resolveAddresses?: typeof resolvePublicAddresses;
1920
pinnedGet?: typeof pinnedHttpGet;
21+
pinnedPost?: typeof pinnedHttpPost;
2022
}
2123

2224
export class ProviderOutboundPolicyError extends Error {
@@ -102,13 +104,18 @@ export async function providerRedirectError(response: Response, requestUrl: stri
102104
return `provider returned ${response.status} redirect to ${target}; configure the final provider URL directly`;
103105
}
104106

105-
export async function providerOutboundGet(
107+
async function providerOutboundRequest(
106108
name: string,
107109
provider: ProviderOutboundConfig,
108110
url: string,
109-
init: ProviderGetInit = {},
111+
method: "GET" | "POST",
112+
init: ProviderGetInit | ProviderPostInit,
110113
dependencies: ProviderOutboundDependencies = {},
111114
): Promise<Response> {
115+
const postUrl = method === "POST" ? new URL(url) : undefined;
116+
if (postUrl?.protocol !== undefined && postUrl.protocol !== "https:") {
117+
throw new ProviderOutboundPolicyError("provider POST URL must use HTTPS");
118+
}
112119
if (provider.fetch) {
113120
// A caller-owned executor cannot be peer-pinned here. This branch keeps literal/config
114121
// checks and redirect blocking, but does not provide the resolved-address guarantees of
@@ -128,12 +135,13 @@ export async function providerOutboundGet(
128135
});
129136
if (destinationError) throw new ProviderOutboundPolicyError(destinationError);
130137
}
131-
return provider.fetch(url, { ...init, method: "GET", redirect: "manual" });
138+
return provider.fetch(url, { ...init, method, redirect: "manual" });
132139
}
133-
const parsed = new URL(url);
140+
const parsed = postUrl ?? new URL(url);
134141
const proxyConfigured = configuredProxyFor();
135142
const resolveAddresses = dependencies.resolveAddresses ?? resolvePublicAddresses;
136143
const pinnedGet = dependencies.pinnedGet ?? pinnedHttpGet;
144+
const pinnedPost = dependencies.pinnedPost ?? pinnedHttpPost;
137145
const allowPrivate = providerAllowsPrivateNetwork(name, provider);
138146
let resolved: Awaited<ReturnType<typeof resolvePublicAddresses>>;
139147
try {
@@ -150,21 +158,46 @@ export async function providerOutboundGet(
150158
if (!proxyConfigured) throw error;
151159
warnProxyBoundaryOnce();
152160
warnProxyDnsDegradationOnce();
153-
return globalThis.fetch(url, { ...init, method: "GET", redirect: "manual" });
161+
return globalThis.fetch(url, { ...init, method, redirect: "manual" });
154162
}
155163
if (proxyConfigured && !resolved.privateNetwork) {
156164
warnProxyBoundaryOnce();
157-
return globalThis.fetch(url, { ...init, method: "GET", redirect: "manual" });
165+
return globalThis.fetch(url, { ...init, method, redirect: "manual" });
158166
}
159167
if (proxyConfigured && resolved.privateNetwork && !noProxyMatches(parsed)) {
160168
const hostname = normalizeProxyHostname(parsed.hostname);
161169
throw new Error(
162170
`provider URL resolves to a private-network destination; add ${hostname} to NO_PROXY before using allowPrivateNetwork with an outbound proxy`,
163171
);
164172
}
165-
return pinnedGet(url, pickPinnedAddress(resolved.addresses), init.signal ?? undefined, {
173+
const requestOptions = {
166174
headers: init.headers,
167175
rejectUnauthorized: true,
168176
context: "provider response",
169-
});
177+
};
178+
const pinned = pickPinnedAddress(resolved.addresses);
179+
if (method === "POST") {
180+
return pinnedPost(url, pinned, (init as ProviderPostInit).body, init.signal ?? undefined, requestOptions);
181+
}
182+
return pinnedGet(url, pinned, init.signal ?? undefined, requestOptions);
183+
}
184+
185+
export async function providerOutboundGet(
186+
name: string,
187+
provider: ProviderOutboundConfig,
188+
url: string,
189+
init: ProviderGetInit = {},
190+
dependencies: ProviderOutboundDependencies = {},
191+
): Promise<Response> {
192+
return providerOutboundRequest(name, provider, url, "GET", init, dependencies);
193+
}
194+
195+
export async function providerOutboundPost(
196+
name: string,
197+
provider: ProviderOutboundConfig,
198+
url: string,
199+
init: ProviderPostInit,
200+
dependencies: ProviderOutboundDependencies = {},
201+
): Promise<Response> {
202+
return providerOutboundRequest(name, provider, url, "POST", init, dependencies);
170203
}

‎src/oauth/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1003,11 +1003,13 @@ export async function runLogin(
10031003
settleKiroTransaction(rawCred, true);
10041004
if (provider !== "chatgpt") {
10051005
try {
1006+
const { clearModelCache } = await import("../codex/model-cache");
1007+
clearModelCache(provider);
10061008
const { clearAccountQuotaCache, clearProviderQuotaCache } = await import("../providers/quota");
10071009
clearProviderQuotaCache();
10081010
clearAccountQuotaCache(provider);
10091011
} catch {
1010-
// Quota module may be unavailable in tightly scoped unit tests.
1012+
// Optional state modules may be unavailable in tightly scoped unit tests.
10111013
}
10121014
}
10131015
return cred;

‎src/server/management/oauth-account-routes.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
210210
await removeCredential(provider);
211211
reconcileLiveStateStores();
212212
clearLoginState(provider);
213+
const { clearModelCache } = await import("../../codex/model-cache");
214+
clearModelCache(provider);
213215
// Drop cached/last-good quota rows tied to the removed credential.
214216
const { clearProviderQuotaCache, clearAccountQuotaCache } = await import("../../providers/quota");
215217
clearProviderQuotaCache();
@@ -281,6 +283,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
281283
const { resetAnthropicRoutingForManualSelection } = await import("../../oauth/anthropic-routing");
282284
resetAnthropicRoutingForManualSelection(body.accountId);
283285
}
286+
const { clearModelCache } = await import("../../codex/model-cache");
287+
clearModelCache(provider);
284288
const { clearProviderQuotaCache } = await import("../../providers/quota");
285289
clearProviderQuotaCache();
286290
return jsonResponse({ ok: true, provider, activeAccountId: body.accountId });
@@ -404,6 +408,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
404408
clearAnthropicSessionAffinityForAccount(id);
405409
}
406410
if (!getAccountSet(provider)) clearLoginState(provider);
411+
const { clearModelCache } = await import("../../codex/model-cache");
412+
clearModelCache(provider);
407413
const { clearProviderQuotaCache, clearAccountQuotaCache } = await import("../../providers/quota");
408414
clearProviderQuotaCache();
409415
clearAccountQuotaCache(provider);

‎src/server/management/provider-routes.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
import { removeCredential } from "../../oauth/store";
2626
import { providerDestinationResolvedError } from "../../lib/destination-policy";
2727
import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
28-
import { ProviderOutboundPolicyError, providerOutboundGet, providerRedirectError } from "../../lib/provider-outbound";
28+
import { ProviderOutboundPolicyError, providerOutboundGet, providerOutboundPost, providerRedirectError } from "../../lib/provider-outbound";
2929
import { parseAntigravityAvailableModels } from "../../providers/antigravity-models";
3030
import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
3131
import { deriveProviderPresets } from "../../providers/derive";
@@ -482,13 +482,10 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
482482
const discovery = resolveProviderModelDiscovery(name, prov);
483483
const started = Date.now();
484484
try {
485-
const providerFetch = (prov as OcxProviderConfig & { fetch?: typeof fetch }).fetch;
486485
const res = method === "POST"
487-
? await (providerFetch ?? globalThis.fetch)(modelsUrl, {
488-
method,
486+
? await providerOutboundPost(name, prov, modelsUrl, {
489487
headers,
490488
body: JSON.stringify({ project: snapshot!.projectId }),
491-
redirect: "manual",
492489
signal: AbortSignal.timeout(8000),
493490
})
494491
: await providerOutboundGet(name, prov, modelsUrl, {

‎tests/oauth-accounts-api.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
import { saveConfig } from "../src/config";
77
import { startServer } from "../src/server";
8+
import { clearModelCache, getStaleCached, setCached } from "../src/codex/model-cache";
89
import type { OcxConfig } from "../src/types";
910
import { installIsolatedCodexHome, type IsolatedCodexHome } from "./helpers/isolated-codex-home";
1011

@@ -45,6 +46,7 @@ beforeEach(() => {
4546
});
4647

4748
afterEach(() => {
49+
clearModelCache("google-antigravity");
4850
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
4951
else process.env.OPENCODEX_HOME = previousHome;
5052
isolatedCodexHome?.restore();
@@ -175,6 +177,31 @@ describe("multiauth accounts API", () => {
175177
}
176178
});
177179

180+
test("switching an Antigravity account clears its account-scoped live-model cache", async () => {
181+
writeFileSync(join(testDir, "auth.json"), JSON.stringify({
182+
"google-antigravity": {
183+
activeAccountId: "antigravity-a",
184+
accounts: [
185+
{ id: "antigravity-a", credential: { access: "a", refresh: "ra", expires: 9999999999999, projectId: "project-a" } },
186+
{ id: "antigravity-b", credential: { access: "b", refresh: "rb", expires: 9999999999999, projectId: "project-b" } },
187+
],
188+
},
189+
}), { mode: 0o600 });
190+
const server = startServer(0);
191+
try {
192+
setCached("google-antigravity", [{ provider: "google-antigravity", id: "account-a-only-model" }]);
193+
const response = await fetch(new URL("/api/oauth/accounts/active", server.url), {
194+
method: "PUT", headers: { "Content-Type": "application/json" },
195+
body: JSON.stringify({ provider: "google-antigravity", accountId: "antigravity-b" }),
196+
});
197+
198+
expect(response.status).toBe(200);
199+
expect(getStaleCached("google-antigravity")).toBeNull();
200+
} finally {
201+
await server.stop(true);
202+
}
203+
});
204+
178205
test("DELETE removes one account; active removal promotes the other", async () => {
179206
const server = startServer(0);
180207
try {

0 commit comments

Comments
 (0)