From 65db67235d2219cecd7e379321857dada9d56ae3 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Mon, 16 Nov 2026 10:53:14 +0900 Subject: [PATCH] fix(vertex): bind model discovery to Google destinations Validate the discovery destination before resolving ADC or ambient credentials, bind asynchronous credentials to that origin, and recheck the exact outgoing URL for initial and paginated catalog requests. Add regressions for hostile destinations and provider changes during credential resolution. --- .../content/docs/es/guides/google-vertex.md | 6 + .../src/content/docs/guides/google-vertex.md | 6 + src/codex/catalog/provider-models.ts | 10 +- .../google-vertex-model-discovery.ts | 57 +++++-- src/server/management/provider-routes.ts | 12 +- structure/providers-and-adapters.md | 2 +- structure/providers/google.md | 11 +- .../google/vertex-model-discovery.test.ts | 158 ++++++++++++++++-- ...anagement-provider-model-discovery.test.ts | 47 ++++++ 9 files changed, 269 insertions(+), 40 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/google-vertex.md b/docs-site/src/content/docs/es/guides/google-vertex.md index 1be6c8e4822..9cd29fdd9d2 100644 --- a/docs-site/src/content/docs/es/guides/google-vertex.md +++ b/docs-site/src/content/docs/es/guides/google-vertex.md @@ -21,6 +21,12 @@ o `$VARIABLE`, el descubrimiento se detiene en lugar de probar otra credencial, solicitudes se niegan a empezar. Cuando el listado no se puede leer completo, OpenCodex conserva los modelos anteriores o configurados en lugar de publicar solo una parte. +El descubrimiento en vivo y las pruebas de conexión requieren un endpoint HTTPS de Google: +`aiplatform.googleapis.com` o `-aiplatform.googleapis.com`, con el puerto HTTPS estándar +y sin usuario ni contraseña en la URL. Los endpoints de gateways personalizados no reciben las +credenciales de Vertex. Restablece el endpoint de Google para usar el descubrimiento en vivo; +los modelos configurados siguen disponibles cuando no se puede verificar el destino. + Los niveles de razonamiento siguen el preajuste: Gemini 4 Hydrogen ofrece low, medium, high (el predeterminado) y xhigh; Gemini 4 Carbon y Argon ofrecen low, medium y high. Un modelo al que el preajuste no asigna niveles, como `gemini-3-pro`, no muestra ninguno, porque sus solicitudes no diff --git a/docs-site/src/content/docs/guides/google-vertex.md b/docs-site/src/content/docs/guides/google-vertex.md index 45c841105e5..55e5ab31a2b 100644 --- a/docs-site/src/content/docs/guides/google-vertex.md +++ b/docs-site/src/content/docs/guides/google-vertex.md @@ -20,6 +20,12 @@ configured, `GOOGLE_CLOUD_API_KEY` and then Application Default Credentials. If credential, the same way requests refuse to start. When the listing cannot be read completely, OpenCodex keeps the previous or configured models rather than publishing part of the list. +Live discovery and connection tests require an HTTPS Google endpoint: +`aiplatform.googleapis.com` or `-aiplatform.googleapis.com`, with the standard HTTPS +port and no URL username or password. Custom gateway endpoints do not receive Vertex credentials. +Restore the Google endpoint to use live discovery; configured models remain available when +discovery cannot verify the destination. + Reasoning levels follow the preset: Gemini 4 Hydrogen offers low, medium, high (the default) and xhigh; Gemini 4 Carbon and Argon offer low, medium and high. A model the preset gives no levels to, such as `gemini-3-pro`, shows none, because requests to it carry no thinking level. diff --git a/src/codex/catalog/provider-models.ts b/src/codex/catalog/provider-models.ts index e2a86061b16..10757a4f3e0 100644 --- a/src/codex/catalog/provider-models.ts +++ b/src/codex/catalog/provider-models.ts @@ -762,20 +762,20 @@ export async function fetchProviderModelsWithAuth( // name matches any baseUrl by design. Retargeted or renamed custom rows // fetch a different URL and keep the rejection. if (!maySendAnthropicDiscovery()) return observed(withConfiguredRetention(failedDiscoveryConfigured), "degraded"); - const outboundDependencies = { isCanonicalUrl: isRegistryModelDiscoveryUrl, + const outboundDependencies = (requestUrl: string) => ({ isCanonicalUrl: isRegistryModelDiscoveryUrl, beforeSend: () => maySendAnthropicDiscovery() - && (!vertexSendGuard || (vertexAuth !== undefined && vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers))) }; + && (!vertexSendGuard || (vertexAuth !== undefined && vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers, requestUrl))) }); const antigravityObservation = cloudCodeAssist ? captureAntigravityModelObservation() : undefined; const res = request.method === "POST" ? await providerOutboundPost(name, prov, url, { headers, body: JSON.stringify({ project }), signal: AbortSignal.timeout(8000), - }, outboundDependencies) + }, outboundDependencies(url)) : await providerOutboundGet(name, prov, url, { headers, signal: vertexDeadline ?? AbortSignal.timeout(8000), - }, outboundDependencies); + }, outboundDependencies(url)); const redirectError = await providerRedirectError(res, url); if (redirectError) { const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "http", httpStatus: res.status }); @@ -876,7 +876,7 @@ export async function fetchProviderModelsWithAuth( const listing = effectiveGoogleMode(name, prov) === "vertex" ? await collectVertexPublisherModelPages(url, bounded.value, { ...discovery, firstPageBytes: vertexFirstPage?.bytes(), signal: vertexDeadline }, - (pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies)) + (pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies(pageUrl))) : { ok: true as const, value: bounded.value }; if (!listing.ok) { const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "invalid_response" }); diff --git a/src/providers/google-vertex-model-discovery.ts b/src/providers/google-vertex-model-discovery.ts index 58304ab8398..fcfeda6b96b 100644 --- a/src/providers/google-vertex-model-discovery.ts +++ b/src/providers/google-vertex-model-discovery.ts @@ -8,6 +8,7 @@ import { } from "../lib/gcp-adc"; import type { OcxProviderConfig } from "../types"; import { resolveProviderApiKey } from "./api-key-resolve"; +import { googleVertexLocationConfigError } from "./google-vertex-location"; import { captureVertexAmbientKey } from "./vertex-environment-authority"; import { extractGoogleAiStudioModelItems } from "./google-ai-studio-model-discovery"; import { @@ -33,6 +34,22 @@ const VERTEX_GENERATIVE_MODEL_ID = /^(?:gemini|gemma)-/i; const VERTEX_NON_CHAT_SKU = /(?:^|-)embedding(?:-|$)|-tts(?:-|$)|-transcribe(?:-|$)|(?:^|-)live(?:-|$)/i; const VERTEX_TRAILING_API_VERSION = /\/v1(?:beta1?)?$/i; +/** The same Google authorities inference constructs; a base URL never grants credential access. */ +function vertexDiscoveryOrigin(value: string): string | undefined { + try { + const url = new URL(value); + if (url.protocol !== "https:" || url.username || url.password || url.port || url.hash) return undefined; + const host = "aiplatform.googleapis.com"; + if (url.hostname === host) return url.origin; + const suffix = `-${host}`; + if (url.hostname.endsWith(suffix) + && googleVertexLocationConfigError(url.hostname.slice(0, -suffix.length)) === null) return url.origin; + } catch { + // An invalid destination is unavailable discovery, without resolving a credential. + } + return undefined; +} + /** Time budget for one Vertex discovery: ADC token resolution, then every follow-up page. */ export const VERTEX_DISCOVERY_TIMEOUT_MS = 8_000; /** Request ceiling for one listing, first page included (pageSize=300, so 1,500 rows). */ @@ -150,9 +167,10 @@ export function resolveObservedVertexDiscoveryToken(provider: OcxProviderConfig) /** The passive gather's credential with its authority bound, for the same send-time checks. */ export function resolveObservedVertexDiscoveryAuth(provider: OcxProviderConfig): VertexDiscoveryAuth | undefined { - if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined; + const origin = vertexDiscoveryOrigin(provider.baseUrl); + if (!origin || provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined; const selection = selectVertexDiscoveryCredential(provider); - return selection.kind === "api-key" ? apiKeyDiscoveryAuth(selection) : undefined; + return selection.kind === "api-key" ? apiKeyDiscoveryAuth(selection, origin) : undefined; } /** @@ -175,10 +193,10 @@ function sameVertexSelection(left: VertexDiscoveryCredential, right: VertexDisco * observed when it was read (`captureVertexAmbientKey`, the record inference binds), so an A→B→A * change of the variable invalidates it even though the bytes match again. */ -function apiKeyDiscoveryAuth(selection: { key: string | undefined; ambient?: true }): VertexDiscoveryAuth | undefined { +function apiKeyDiscoveryAuth(selection: { key: string | undefined; ambient?: true }, origin: string): VertexDiscoveryAuth | undefined { if (!selection.key) return undefined; const auth: VertexDiscoveryAuth = { token: selection.key, kind: "api-key" }; - if (selection.ambient) bindVertexRequestAuthority(auth, "", selection.key, { ambientKey: captureVertexAmbientKey(selection.key) }); + if (selection.ambient) bindVertexRequestAuthority(auth, origin, selection.key, { ambientKey: captureVertexAmbientKey(selection.key) }); return auth; } @@ -198,9 +216,10 @@ export async function resolveVertexDiscoveryAuth( provider: OcxProviderConfig, signal: AbortSignal = vertexDiscoveryDeadline(), ): Promise { - if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined; + const origin = vertexDiscoveryOrigin(provider.baseUrl); + if (!origin || provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined; const selection = selectVertexDiscoveryCredential(provider); - if (selection.kind === "api-key") return apiKeyDiscoveryAuth(selection); + if (selection.kind === "api-key") return apiKeyDiscoveryAuth(selection, origin); let authority: Awaited>; try { const markerAccount = gcpCredentialMarkerAccount(selection.marker); @@ -208,9 +227,10 @@ export async function resolveVertexDiscoveryAuth( } catch { return undefined; } - if (!sameVertexSelection(selection, selectVertexDiscoveryCredential(provider))) return undefined; + if (origin !== vertexDiscoveryOrigin(provider.baseUrl) + || !sameVertexSelection(selection, selectVertexDiscoveryCredential(provider))) return undefined; const auth: VertexDiscoveryAuth = { token: authority.token, kind: "adc", ...(selection.marker ? { marker: selection.marker } : {}) }; - bindVertexRequestAuthority(auth, "", `Bearer ${authority.token}`, { + bindVertexRequestAuthority(auth, origin, `Bearer ${authority.token}`, { source: authority.source, generation: authority.generation, ...(authority.markerAccount ? { markerAccount: authority.markerAccount } : {}), @@ -227,7 +247,8 @@ export async function resolveVertexDiscoveryToken( } /** - * Send-time check, run before every discovery request (`beforeSend`): the row still selects the + * Send-time check, run before every discovery request (`beforeSend`): the actual URL stays on the + * approved Google origin, and the row still selects the * credential this token came from, an ADC token's source and generation are still current (the * check inference runs before dispatch), and the outgoing headers carry it in that scheme's header * and not the other one. Any change cancels the send, first page and follow-up pages alike, so a @@ -237,11 +258,14 @@ export function vertexDiscoveryAuthIsCurrent( provider: OcxProviderConfig, auth: VertexDiscoveryAuth, headers: Record, + url: string, ): boolean { - if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return false; - // ADC source/generation and the ambient-key generation, exactly as inference checks them. Checked - // first so every send-time check also observes the current ambient key, as inference does. - if (!vertexRequestAuthorityIsCurrent(auth)) return false; + const origin = vertexDiscoveryOrigin(provider.baseUrl); + if (!origin || vertexDiscoveryOrigin(url) !== origin + || provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return false; + // Recheck ADC source/generation and the ambient-key generation after destination admission, + // before comparing the current selection, exactly as inference checks them. + if (!vertexRequestAuthorityIsCurrent(auth, origin)) return false; const current = selectVertexDiscoveryCredential(provider); const issued: VertexDiscoveryCredential = auth.kind === "api-key" ? { kind: "api-key", key: auth.token } @@ -268,6 +292,11 @@ export function buildVertexModelsDiscoveryRequest( resolveUrl: (defaultUrl: string) => string, ): { url: string; headers: Record } { const base = effectiveProvider.baseUrl.replace(/\/+$/, "").replace(VERTEX_TRAILING_API_VERSION, ""); + // Keep a credential-free request available for catalog capture/fallback, but never attach + // a Google credential to a destination outside the origin admitted before resolution. + const url = resolveUrl(`${base}/v1beta1/publishers/google/models?pageSize=300`); + const origin = vertexDiscoveryOrigin(effectiveProvider.baseUrl); + if (!origin || vertexDiscoveryOrigin(url) !== origin) return { url, headers }; if (usesVertexApiKeyForDiscovery(effectiveProvider)) { if (apiKey) headers["x-goog-api-key"] = apiKey; } else { @@ -282,7 +311,7 @@ export function buildVertexModelsDiscoveryRequest( // Vertex ModelGardenService.ListPublisherModels enforces a maximum pageSize of 300 // (values > 300 return HTTP 400 INVALID_ARGUMENT); later pages follow nextPageToken. return { - url: resolveUrl(`${base}/v1beta1/publishers/google/models?pageSize=300`), + url, headers, }; } diff --git a/src/server/management/provider-routes.ts b/src/server/management/provider-routes.ts index 758c8e34c75..c0cb9ebdc1d 100644 --- a/src/server/management/provider-routes.ts +++ b/src/server/management/provider-routes.ts @@ -1732,21 +1732,21 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers)) + const outboundDependencies = (requestUrl: string) => ({ isCanonicalUrl: isRegistryModelDiscoveryUrl, + beforeSend: () => (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers, requestUrl)) && (prov.authMode !== "oauth" || (mayResolveModelsOAuth(name, config.providers[name]) && modelsOAuthTargetMatches(name, config.providers[name], authorizedTarget) - && (name !== "anthropic2" || new URL(modelsUrl).href === authorizedTarget))) }; + && (name !== "anthropic2" || new URL(requestUrl).href === authorizedTarget))) }); const res = method === "POST" ? await providerOutboundPost(name, prov, modelsUrl, { headers, body: JSON.stringify({ project }), signal: AbortSignal.timeout(8000), - }, outboundDependencies) + }, outboundDependencies(modelsUrl)) : await providerOutboundGet(name, prov, modelsUrl, { headers, signal: vertexDeadline ?? AbortSignal.timeout(8000), - }, outboundDependencies); + }, outboundDependencies(modelsUrl)); const latencyMs = Date.now() - started; const redirectError = await providerRedirectError(res, modelsUrl); if (redirectError) { @@ -1782,7 +1782,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies)) + (pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies(pageUrl))) : { ok: true as const, value: bounded.value }; if (!listing.ok) return jsonResponse({ ok: false, latencyMs, error: `upstream Vertex model listing is incomplete: ${listing.diagnostic}` }); // OpenAI-style lists (and Together top-level arrays) use the same validation/dedupe/filter diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index d4fbba224b5..05bcf2a3b04 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -5,7 +5,7 @@ Reasoning support, thinking on/off control, real reasoning strengths and the thi Public MiMo V2.6 is a registry instance with reasoning and toggle support, no real effort strengths, and thinking enabled by default. `src/providers/mimo-thinking.ts` supplies those facts; `thinkingToggleModels` separately declares its existing `thinking.type` wire protocol. Client compatibility alone projects the switch to legacy `none/high` choices. Internal metadata contains no synthetic MiMo effort ladder or high default. Public model rows expose optional `supports_reasoning`, `supports_thinking_toggle`, `supports_reasoning_effort` and `default_thinking_enabled` flags; chained provider discovery reads those flags back without inferring false from absence. Config hints rederive cached projections from their original discovered reasoning metadata. Free, token-plan and third-party MiMo routes keep their existing contracts. Canonical Mistral request fields, developer defaults, effort clamping and native typed-content projection follow the [Chat wire policy](providers/mistral-chat.md). Canonical key-auth Mistral Chat at `https://api.mistral.ai/v1` defaults to a patient bounded same-key 429 policy (six replays, ten-second fallback) in `src/providers/key-failover.ts`; explicit retry settings/opt-out win. The Mistral preset forwards supplied prompt-cache keys unless explicitly disabled. `src/providers/key-failover.ts` and transport selection use the same canonical-destination check, including custom provider names. `src/providers/mistral-transport.ts` shares explicit Retry-After deadlines across calls by actual credential digest and exact model, with bounded memory/waiters and cancellation. Without Retry-After, only a real 429 with validated exhausted minute capacity or a measured query charge above remaining but within the full token allowance activates a conservative 60-second recovery hold. This local policy does not claim the server reset instant. One probe gates concurrent recovery callers; a successful probe clears recovery unless a newer refusal intervened. Healthy traffic never predicts future query/cache cost; unknown, zero-entitlement, exhausted-monthly and above-full-allowance evidence does not invent a minute reset. Oversized Retry-After stops same-key replay rather than shortening the server delay: a same-target retry hold in `src/lib/upstream-retry.ts` is checked only by the same-key 429 loops, so key rotation and the original upstream status, body and Retry-After stay available. Either `requestPacing.enabled: false` or `retryOn429.respectRetryAfter: false` disables the shared hold. `tests/providers/mistral-recovery.test.ts` covers GLM/Large 4, destination/key/model isolation, absent headers, cache affinity, streamed/buffered replay, cancellation and send ceilings. There is no mid-stream replay or automatic compaction change. The same destination check gates `src/adapters/openai-chat/mistral-image-limit.ts`, the last outbound-copy step of `messagesToChatFormat` and of the native Chat passthrough (`src/adapters/openai-chat/passthrough.ts`): it walks content in reverse with constant traversal bookkeeping (excluding the returned copy-on-write message/content arrays, whose size still scales with the input), counts an `image_url` part only when `image_url` or `image_url.url` is a nonempty string (without validating URL syntax or reachability), replaces image parts lacking either nonempty string shape with a text note without consuming the cap, keeps the newest counted images within `modelCapabilities..mistralMaxImages` (operator declaration over the destination registry row, else the documented 8), and copy-on-write replaces older ones with a text note naming the cap. -GCP JSON storage in `src/providers/api-keys.ts` and durable-row snapshot/post-commit cleanup in `src/providers/gcp-credential-cleanup.ts` follow [Vertex credential markers](providers/google.md#vertex-credential-markers); malformed blank marker accounts do not block cleanup of valid accounts. Vertex ADC dispatch authority is described in [Vertex API-key endpoint selection](providers/google.md#vertex-api-key-endpoint-selection). +GCP JSON storage in `src/providers/api-keys.ts` and durable-row snapshot/post-commit cleanup in `src/providers/gcp-credential-cleanup.ts` follow [Vertex credential markers](providers/google.md#vertex-credential-markers); malformed blank marker accounts do not block cleanup of valid accounts. Vertex ADC dispatch authority is described in [Vertex API-key endpoint selection](providers/google.md#vertex-api-key-endpoint-selection). Live catalogs and provider probes share [Vertex discovery destination authority](providers/google.md#vertex-model-discovery). Combo target `metered` metadata and configured-key opt-in follow the [runtime consent contract](runtime.md#request-local-target-compatibility). Subscription-to-Cursor-to-key regression coverage in `tests/adapters/anthropic/anthropic-subscription-chain.test.ts` checks unchanged healthy subscription wire bodies, effort, key authentication and cache controls, and structured runTurn 429 propagation. OpenCode Go's exact Gemini pin and credential destination guard follow the [Go Gemini transport contract](providers/google.md#opencode-go-gemini-transport). Configured spend ceilings bind adapter inference executors to the [seed and physical-start contract](transports/responses-spend.md#historical-pool-continuity-and-rollback). Zed completion and auth-recovery replays claim separately; token acquisition stays outside inference accounting. Claude CLI, CodeBuddy and Qoder each count one invocation toward the frozen request limit, seed before spawn and retain a producer through completion. Child-internal retries/tool turns are not separately counted; reported actual usage settles in full, including amounts above the seed estimate. Devin combines only [consecutive same-ID tool results](adapters/registry.md#devin-consecutive-tool-results), using linear accumulation while preserving intervening message slots, image parts and error markers without mutating the parsed request. Claude CLI replay, client tool capture and usage admission follow [Claude CLI replay](providers/claude-cli-replay.md). Anthropic account pause, model routes, quota labels, and the separate `anthropic2` pool (its helpers, quota, reset grants and management surfaces) follow the [Anthropic account-pool contract](providers/anthropic-account-pool.md). Devin Messages follows the [per-turn output ordering contract](clients/claude-desktop.md#devin-messages-output-ordering), preserving late signatures before text/tools without changing Responses or Chat ordering. The DeepSeek Harness account provider follows the [DSH account contract](providers/dsh-account.md). WorkBuddy AI subscription authentication, catalog, display-only credit balances and inference follow the [WorkBuddy contract](providers/workbuddy.md). diff --git a/structure/providers/google.md b/structure/providers/google.md index cc58a4af750..fc67f15b0ea 100644 --- a/structure/providers/google.md +++ b/structure/providers/google.md @@ -1,6 +1,6 @@ # Google Provider -Created: 2026-10-16 | Updated: 2026-11-13 | Version: 1.3 (Vertex model discovery) +Created: 2026-10-16 | Updated: 2026-11-16 | Version: 1.4 (Vertex discovery destination authority) ## Streaming input accounting @@ -54,7 +54,14 @@ project. ADC rejects `"auto"`. ## Vertex model discovery `src/providers/google-vertex-model-discovery.ts` lists a non-OAuth Vertex row's models from -`GET /v1beta1/publishers/google/models?pageSize=300` (300 is the server maximum). It selects the +`GET /v1beta1/publishers/google/models?pageSize=300` (300 is the server maximum). Before reading a +key reference or resolving ADC it admits only HTTPS `aiplatform.googleapis.com` or +`-aiplatform.googleapis.com`, using inference's location-label validator and refusing +userinfo, nondefault ports and fragments. Request construction attaches credentials only to that +origin, and every page's send-time guard checks its actual URL against the admitted origin. +Ambient keys and ADC retain that origin in their credential-authority record. An unapproved +destination resolves no credential: catalog discovery degrades and the management probe remains +unverified. It selects the discovery credential the way inference does: a `gcp-sa:` marker uses that service account; an explicit `keychain:` or `$ENV` reference uses that key alone, and when it cannot be read discovery sends nothing and the catalog degrades, matching the routed-config rejection of the same diff --git a/tests/adapters/google/vertex-model-discovery.test.ts b/tests/adapters/google/vertex-model-discovery.test.ts index dad2d95d7b0..04f5d9a69ca 100644 --- a/tests/adapters/google/vertex-model-discovery.test.ts +++ b/tests/adapters/google/vertex-model-discovery.test.ts @@ -5,7 +5,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createGoogleAdapter } from "../../../src/adapters/google"; import { __resetVertexTokenCache } from "../../../src/lib/gcp-adc"; +import { providerOutboundGet } from "../../../src/lib/provider-outbound"; import { + buildVertexModelsDiscoveryRequest, collectVertexPublisherModelPages, extractGoogleNativeModelItems, resolveObservedVertexDiscoveryAuth, @@ -24,6 +26,7 @@ import { clearModelCache } from "../../../src/codex/model-cache"; import { withStubbedProviderFetch } from "../../helpers/catalog-provider-fetch"; import { removeTreeWithRetry } from "../../helpers/remove-tree"; +const VERTEX_MODELS_URL = "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300"; const OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token"; const ENV_KEYS = ["GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_API_KEY", "GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "CLOUDSDK_CONFIG"]; const UNREADABLE_REFERENCES = ["keychain:missing-fixture", "${MISSING_VERTEX_TEST_KEY}", "$MISSING_VERTEX_TEST_KEY", "keychain:"]; @@ -124,6 +127,137 @@ describe("Vertex discovery credential selection", () => { }); }); +describe("Vertex discovery destination authority", () => { + const untrusted = [ + "https://collector.example", "http://aiplatform.googleapis.com", + "https://aiplatform.googleapis.com:8443", Object.assign(new URL("https://aiplatform.googleapis.com"), { username: "fixture" }).href, + "https://aiplatform.googleapis.com.collector.example", "https://fakeaiplatform.googleapis.com", + "https://us.central1-aiplatform.googleapis.com", "https://-us-aiplatform.googleapis.com", + "https://aiplatform.googleapis.com/#fragment", "not a URL", + ]; + + test("untrusted destinations resolve no ambient key, host ADC or stored credential", async () => { + withAmbientCredentials(); + let credentialReads = 0; + setProviderKeychainEntryFactoryForTests(() => ({ + getPassword: () => { credentialReads++; return readFileSync(saPath, "utf8"); }, + setPassword: () => {}, deletePassword: () => true, + })); + for (const baseUrl of untrusted) { + const provider = vertex({ baseUrl }); + expect(resolveObservedVertexDiscoveryAuth(provider)).toBeUndefined(); + expect(await resolveVertexDiscoveryAuth(provider)).toBeUndefined(); + for (const apiKey of ["gcp-sa:blocked-fixture", "keychain:blocked-fixture"]) { + expect(await resolveVertexDiscoveryAuth(vertex({ baseUrl, apiKey }))).toBeUndefined(); + } + const request = buildVertexModelsDiscoveryRequest(provider, "resolved-fixture-token", {}, url => url); + expect(request.headers).toEqual({}); + } + delete process.env.GOOGLE_CLOUD_API_KEY; + expect(await resolveVertexDiscoveryAuth(vertex({ baseUrl: untrusted[0]! }))).toBeUndefined(); + expect(credentialReads).toBe(0); + expect(tokenCalls).toBe(0); + }); + + test("global and regional Google destinations retain their keys and paginated sends", async () => { + withAmbientCredentials(); + for (const baseUrl of [ + "https://aiplatform.googleapis.com", "https://aiplatform.googleapis.com:443/v1", + "https://us-central1-aiplatform.googleapis.com/v1beta1", "https://europe-west4-aiplatform.googleapis.com", + ]) { + const provider = vertex({ baseUrl }); + const auth = (await resolveVertexDiscoveryAuth(provider))!; + expect(auth.token).toBe("ambient-env-key"); + const request = buildVertexModelsDiscoveryRequest(provider, auth.token, {}, url => url); + expect(request.headers["x-goog-api-key"]).toBe(auth.token); + expect(vertexDiscoveryAuthIsCurrent(provider, auth, request.headers, request.url)).toBe(true); + const nextPage = new URL(request.url); + nextPage.searchParams.set("pageToken", "https://collector.example/next"); + expect(vertexDiscoveryAuthIsCurrent(provider, auth, request.headers, nextPage.href)).toBe(true); + } + }); + + test("the actual request and resolved discovery URL must retain the approved Google origin", async () => { + withAmbientCredentials(); + const provider = vertex(); + const auth = (await resolveVertexDiscoveryAuth(provider))!; + const headers = { "x-goog-api-key": auth.token }; + for (const url of [...untrusted, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models"]) { + expect(vertexDiscoveryAuthIsCurrent(provider, auth, headers, url)).toBe(false); + expect(buildVertexModelsDiscoveryRequest(provider, auth.token, {}, () => url).headers).toEqual({}); + } + provider.baseUrl = "https://us-central1-aiplatform.googleapis.com"; + expect(vertexDiscoveryAuthIsCurrent(provider, auth, headers, `${provider.baseUrl}/v1beta1/publishers/google/models`)).toBe(false); + }); + + test("an ADC credential remains bound to the approved origin after resolution", async () => { + withAmbientCredentials(); + delete process.env.GOOGLE_CLOUD_API_KEY; + const provider = vertex(); + const auth = (await resolveVertexDiscoveryAuth(provider))!; + const headers = { Authorization: `Bearer ${auth.token}` }; + expect(vertexDiscoveryAuthIsCurrent(provider, auth, headers, VERTEX_MODELS_URL)).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(provider, auth, headers, "https://collector.example/models")).toBe(false); + provider.baseUrl = "https://us-central1-aiplatform.googleapis.com"; + expect(vertexDiscoveryAuthIsCurrent(provider, auth, headers, `${provider.baseUrl}/models`)).toBe(false); + }); + + test("changing the request URL after credential resolution cancels the actual transport send", async () => { + withAmbientCredentials(); + const provider = vertex(); + const auth = (await resolveVertexDiscoveryAuth(provider))!; + const request = buildVertexModelsDiscoveryRequest(provider, auth.token, {}, url => url); + let sends = 0; + const transportProvider = { ...provider, fetch: (async () => { + sends++; + return Response.json({ publisherModels: [] }); + }) as typeof fetch }; + request.url = "https://collector.example/models"; + await expect(providerOutboundGet("vertex", transportProvider, request.url, { headers: request.headers }, { + beforeSend: () => vertexDiscoveryAuthIsCurrent(provider, auth, request.headers, request.url), + })).rejects.toThrow("provider credential changed before send"); + expect(sends).toBe(0); + }); + + test("an origin change during ADC resolution discards the minted token", async () => { + withAmbientCredentials(); + delete process.env.GOOGLE_CLOUD_API_KEY; + const provider = vertex(); + const tokens = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + provider.baseUrl = "https://us-central1-aiplatform.googleapis.com"; + return tokens(input, init); + }) as typeof fetch; + expect(await resolveVertexDiscoveryAuth(provider)).toBeUndefined(); + expect(tokenCalls).toBe(1); + }); + + test("catalog discovery keeps configured models without sending credentials to an untrusted destination", async () => { + withAmbientCredentials(); + const sends: string[] = []; + const tokens = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === OAUTH_TOKEN_URL) return tokens(input, init); + sends.push(url); + return Response.json({ publisherModels: [{ name: "publishers/google/models/gemini-4-hydrogen" }] }); + }) as typeof fetch; + try { + for (const ambient of [true, false]) { + if (!ambient) delete process.env.GOOGLE_CLOUD_API_KEY; + clearModelCache(); + const config = withStubbedProviderFetch({ providers: { "blocked-vertex": vertex({ + baseUrl: "https://collector.example", liveModels: true, models: ["configured-only"], + }) } } as OcxConfig); + const rows = await gatherRoutedModels(config); + expect(rows.filter(row => row.provider === "blocked-vertex").map(row => row.id)).toContain("configured-only"); + } + expect(sends).toEqual([]); + expect(tokenCalls).toBe(0); + } finally { clearModelCache(); } + }); +}); + function publisher(...ids: string[]): Array<{ name: string }> { return ids.map(id => ({ name: `publishers/google/models/${id}` })); } @@ -343,14 +477,14 @@ describe("Vertex discovery credential stays bound to its selection", () => { __resetVertexTokenCache(); delete process.env.GOOGLE_CLOUD_API_KEY; const adc = { token: "host-adc-token", kind: "adc" as const }; - expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { Authorization: "Bearer host-adc-token" })).toBe(true); - expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { "x-goog-api-key": "host-adc-token" })).toBe(false); + expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { Authorization: "Bearer host-adc-token" }, VERTEX_MODELS_URL)).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { "x-goog-api-key": "host-adc-token" }, VERTEX_MODELS_URL)).toBe(false); process.env.GOOGLE_CLOUD_API_KEY = "ambient-env-key"; - expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { Authorization: "Bearer host-adc-token" })).toBe(false); + expect(vertexDiscoveryAuthIsCurrent(vertex(), adc, { Authorization: "Bearer host-adc-token" }, VERTEX_MODELS_URL)).toBe(false); const key = { token: "ambient-env-key", kind: "api-key" as const }; - expect(vertexDiscoveryAuthIsCurrent(vertex(), key, { "X-Goog-Api-Key": "ambient-env-key" })).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(vertex(), key, { "X-Goog-Api-Key": "ambient-env-key" }, VERTEX_MODELS_URL)).toBe(true); process.env.GOOGLE_CLOUD_API_KEY = "rotated-env-key"; - expect(vertexDiscoveryAuthIsCurrent(vertex(), key, { "x-goog-api-key": "ambient-env-key" })).toBe(false); + expect(vertexDiscoveryAuthIsCurrent(vertex(), key, { "x-goog-api-key": "ambient-env-key" }, VERTEX_MODELS_URL)).toBe(false); }); test("catalog discovery never sends an ADC token after the selection moved to an API key mid-exchange", async () => { @@ -401,9 +535,9 @@ describe("Vertex discovery ADC token stays bound to the authority that minted it const host = await resolveVertexDiscoveryAuth(vertex()); expect(host?.token).toBe("token-for-host-a@example.test"); const hostHeaders = { Authorization: `Bearer ${host!.token}` }; - expect(vertexDiscoveryAuthIsCurrent(vertex(), host!, hostHeaders)).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(vertex(), host!, hostHeaders, VERTEX_MODELS_URL)).toBe(true); writeFileSync(hostFile, serviceAccount("host-b@example.test")); - expect(vertexDiscoveryAuthIsCurrent(vertex(), host!, hostHeaders)).toBe(false); + expect(vertexDiscoveryAuthIsCurrent(vertex(), host!, hostHeaders, VERTEX_MODELS_URL)).toBe(false); const stored: Record = { "rotating-marker": serviceAccount("marker-a@example.test") }; setProviderKeychainEntryFactoryForTests((_service, account) => ({ @@ -413,9 +547,9 @@ describe("Vertex discovery ADC token stays bound to the authority that minted it const marker = await resolveVertexDiscoveryAuth(markerRow); expect(marker?.token).toBe("token-for-marker-a@example.test"); const markerHeaders = { Authorization: `Bearer ${marker!.token}` }; - expect(vertexDiscoveryAuthIsCurrent(markerRow, marker!, markerHeaders)).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(markerRow, marker!, markerHeaders, VERTEX_MODELS_URL)).toBe(true); stored["rotating-marker"] = serviceAccount("marker-b@example.test"); - expect(vertexDiscoveryAuthIsCurrent(markerRow, marker!, markerHeaders)).toBe(false); + expect(vertexDiscoveryAuthIsCurrent(markerRow, marker!, markerHeaders, VERTEX_MODELS_URL)).toBe(false); }); test("an ADC file replaced between pages stops the walk before the next page is sent", async () => { @@ -454,17 +588,17 @@ describe("Vertex discovery ambient key stays bound to the generation it was read const headers = { "x-goog-api-key": "ambient-a" }; for (const auth of [resolved, passive]) { expect(auth).toMatchObject({ token: "ambient-a", kind: "api-key" }); - expect(vertexDiscoveryAuthIsCurrent(vertex(), auth!, headers)).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(vertex(), auth!, headers, VERTEX_MODELS_URL)).toBe(true); } process.env.GOOGLE_CLOUD_API_KEY = "ambient-b"; // Inference routes a request while B is set, observing B as the current ambient authority. routedProviderConfig("google-vertex", vertex({ project: "p", location: "global" })); process.env.GOOGLE_CLOUD_API_KEY = "ambient-a"; - for (const auth of [resolved, passive]) expect(vertexDiscoveryAuthIsCurrent(vertex(), auth!, headers)).toBe(false); + for (const auth of [resolved, passive]) expect(vertexDiscoveryAuthIsCurrent(vertex(), auth!, headers, VERTEX_MODELS_URL)).toBe(false); // A configured literal key is not ambient authority and is unaffected by the variable. const literal = await resolveVertexDiscoveryAuth(vertex({ apiKey: "literal-key" })); process.env.GOOGLE_CLOUD_API_KEY = "ambient-b"; - expect(vertexDiscoveryAuthIsCurrent(vertex({ apiKey: "literal-key" }), literal!, { "x-goog-api-key": "literal-key" })).toBe(true); + expect(vertexDiscoveryAuthIsCurrent(vertex({ apiKey: "literal-key" }), literal!, { "x-goog-api-key": "literal-key" }, VERTEX_MODELS_URL)).toBe(true); }); }); diff --git a/tests/server/management-provider-model-discovery.test.ts b/tests/server/management-provider-model-discovery.test.ts index 2bf9f6c2a7e..2729b66b44a 100644 --- a/tests/server/management-provider-model-discovery.test.ts +++ b/tests/server/management-provider-model-discovery.test.ts @@ -209,6 +209,53 @@ describe("connection test (#7910)", () => { }); }); +describe("Vertex connection-test destination authority", () => { + const originalFetch = globalThis.fetch; + const ambientKey = process.env.GOOGLE_CLOUD_API_KEY; + afterEach(() => { + globalThis.fetch = originalFetch; + if (ambientKey === undefined) delete process.env.GOOGLE_CLOUD_API_KEY; + else process.env.GOOGLE_CLOUD_API_KEY = ambientKey; + }); + + async function probe(baseUrl: string): Promise<{ ok: boolean; models?: number }> { + useHome(); + const cfg = withStubbedProviderFetch({ ...config("127.0.0.1"), providers: { + "google-vertex": { adapter: "google", googleMode: "vertex", authMode: "key", baseUrl, liveModels: true }, + } }); + const url = new URL("http://127.0.0.1/api/providers/test?name=google-vertex"); + const response = await handleManagementAPI(new ManagementRequest(url, { method: "POST" }), url, cfg); + if (!response) throw new Error("route missing"); + return await response.json() as { ok: boolean; models?: number }; + } + + test("an untrusted Vertex destination fails without resolving or sending ambient credentials", async () => { + process.env.GOOGLE_CLOUD_API_KEY = "ambient-probe-fixture"; + let sends = 0; + globalThis.fetch = (async () => { sends++; return Response.json({ publisherModels: [] }); }) as typeof fetch; + expect((await probe("https://collector.example")).ok).toBe(false); + expect(sends).toBe(0); + }); + + test("an approved regional destination sends every page to that origin", async () => { + process.env.GOOGLE_CLOUD_API_KEY = "ambient-probe-fixture"; + const urls: URL[] = []; + const headers: Headers[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + urls.push(new URL(String(input))); + headers.push(new Headers(init?.headers)); + return Response.json({ + publisherModels: [{ name: `publishers/google/models/gemini-page-${urls.length}` }], + ...(urls.length === 1 ? { nextPageToken: "https://collector.example/next" } : {}), + }); + }) as typeof fetch; + expect(await probe("https://us-central1-aiplatform.googleapis.com")).toMatchObject({ ok: true, models: 2 }); + expect(urls.map(url => url.origin)).toEqual(Array(2).fill("https://us-central1-aiplatform.googleapis.com")); + expect(urls[1]!.searchParams.get("pageToken")).toBe("https://collector.example/next"); + expect(headers.map(header => header.get("x-goog-api-key"))).toEqual(Array(2).fill("ambient-probe-fixture")); + }); +}); + describe("live reconciliation (#7910)", () => { test("a hand edit adding the block on disk reaches the live config", () => { useHome();