Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(vertex): lead model-list errors with the upstream message
Jack Rudenko14bf07ff995b
diff --git a/packages/cli/src/auth/vertex-access-denied.test.ts b/packages/cli/src/auth/vertex-access-denied.test.tsnew file mode 100644index 00000000..e0f12d74--- /dev/null+++ b/packages/cli/src/auth/vertex-access-denied.test.ts@@ -0,0 +1,56 @@+// REGRESSION: Vertex config TUI showed oauth but offered only "set key" and an unexplained 403 — Fixed in /dev:fix session dev-fix-20261020-235500-vtx01+import { describe, expect, test } from "bun:test";+import * as vertexAuth from "./vertex-auth.js";++const projectId = "vertex-test-project";+const origins: Array<{ label: string; origin: vertexAuth.VertexProjectOrigin | null }> = [+ {+ label: "environment",+ origin: { projectId, source: "env", detail: "VERTEX_PROJECT" },+ },+ {+ label: "ADC file",+ origin: { projectId, source: "adc-file", detail: "vertex-test-credentials.json" },+ },+ {+ label: "gcloud config",+ origin: { projectId, source: "gcloud-config", detail: "gcloud config get project" },+ },+ { label: "unknown source", origin: null },+];++describe("Vertex access-denied explanation", () => {+ for (const { label, origin } of origins) {+ for (const account of ["[email protected]", undefined]) {+ test(`${label}, ${account ? "known account" : "unknown account"}: reports the upstream refusal before account and project facts`, () => {+ const upstream =+ "Caller does not have required permission to use project vertex-test-project.";+ const message = vertexAuth.describeVertexAccessDenied({+ status: 403,+ upstream,+ projectId,+ origin,+ account,+ });++ const segments = [`HTTP 403: ${upstream}`];+ if (account) segments.push(`ADC account ${account}`);+ segments.push(+ `project ${projectId}` ++ (origin ? ` (from ${vertexAuth.describeVertexProjectSource(origin)})` : "")+ );+ segments.push("to sign in as another account: gcloud auth application-default login");+ expect(message).toBe(segments.join(" · "));+ if (account) {+ expect(message.indexOf(upstream)).toBeLessThan(message.indexOf("ADC account"));+ } else {+ expect(message).not.toContain("ADC account");+ }+ for (const diagnosis of ["cannot use", "must be one", "who signs"]) {+ expect(message).not.toContain(diagnosis);+ }+ expect(message).not.toContain("undefined");+ });+ }+ }+});diff --git a/packages/cli/src/auth/vertex-auth.ts b/packages/cli/src/auth/vertex-auth.tsindex 6956d57e..fa28e847 100644--- a/packages/cli/src/auth/vertex-auth.ts+++ b/packages/cli/src/auth/vertex-auth.ts@@ -305,6 +305,29 @@ export function describeVertexProjectSource(origin: VertexProjectOrigin): stringexport const VERTEX_SET_PROJECT_REMEDY ="set VERTEX_PROJECT or run `gcloud config set project <id>`";+/** Report the upstream refusal first, then account and project facts and how to change accounts. */+export function describeVertexAccessDenied({+ status,+ upstream,+ projectId,+ origin,+ account,+}: {+ status: number;+ upstream: string;+ projectId: string;+ origin: VertexProjectOrigin | null;+ account?: string;+}): string {+ const segments = [`HTTP ${status}: ${upstream}`];+ if (account) segments.push(`ADC account ${account}`);+ segments.push(+ `project ${projectId}` + (origin ? ` (from ${describeVertexProjectSource(origin)})` : "")+ );+ segments.push("to sign in as another account: gcloud auth application-default login");+ return segments.join(" · ");+}+/** The same two remedies, plus the fact that rules out the third guess. */export const VERTEX_NO_PROJECT_REMEDY = `${VERTEX_SET_PROJECT_REMEDY} — Vertex takes no API key`;diff --git a/packages/cli/src/providers/transport/vertex-discovery.access-denied.test.ts b/packages/cli/src/providers/transport/vertex-discovery.access-denied.test.tsnew file mode 100644index 00000000..876cf7cf--- /dev/null+++ b/packages/cli/src/providers/transport/vertex-discovery.access-denied.test.ts@@ -0,0 +1,209 @@+// REGRESSION: Vertex config TUI showed oauth but offered only "set key" and an unexplained 403 — Fixed in /dev:fix session dev-fix-20261020-235500-vtx01+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { credentials } from "../../auth/credentials/authority.js";+import { resetVertexProjectDiscovery } from "../../auth/vertex-auth.js";+import { _clearVertexDiscoveryCache, discoverVertexProbeModel } from "./vertex-discovery.js";++const originalFetch = globalThis.fetch;+const originalGetRequestAuth = credentials.getRequestAuth;+const originalProject = process.env.VERTEX_PROJECT;+const originalLocation = process.env.VERTEX_LOCATION;+const originalApplicationCredentials = process.env.GOOGLE_APPLICATION_CREDENTIALS;+const upstreamMessage =+ "Caller does not have required permission to use project vertex-test-project.";++function installHttpResponses(+ tokeninfo: "email" | "400" | "throws",+ response = {+ status: 403,+ body: JSON.stringify({+ error: { code: 403, message: upstreamMessage, status: "PERMISSION_DENIED" },+ }),+ }+): string[] {+ const requests: string[] = [];+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;+ requests.push(url);++ if (url.endsWith("/v1beta1/publishers/google/models")) {+ expect(init?.method).toBe("GET");+ expect(new Headers(init?.headers).get("x-goog-user-project")).toBe("vertex-test-project");+ return new Response(response.body, { status: response.status });+ }++ if (url.startsWith("https://oauth2.googleapis.com/tokeninfo")) {+ expect(init?.method ?? (input instanceof Request ? input.method : "GET")).toBe("GET");+ if (tokeninfo === "throws") throw new Error("offline Vertex tokeninfo request failed");+ if (tokeninfo === "400") {+ return Response.json({ error: "invalid_token" }, { status: 400 });+ }+ return Response.json({ email: "[email protected]" });+ }++ throw new Error(`unexpected Vertex discovery request: ${url}`);+ }) as typeof fetch;+ return requests;+}++function expectAccessDeniedReason(+ reason: string | undefined,+ status = 403,+ upstream = upstreamMessage+): asserts reason is string {+ expect(reason).toStartWith(`Vertex AI model list failed: HTTP ${status}: ${upstream}`);+ expect(reason).toContain("vertex-test-project");+ expect(reason).toContain("gcloud auth application-default login");+ expect(reason).toContain(upstream);+ expect(reason).toContain("$VERTEX_PROJECT");+ expect(reason).not.toContain("undefined");+ for (const diagnosis of ["cannot use", "must be one", "who signs"]) {+ expect(reason).not.toContain(diagnosis);+ }+}++describe.serial("Vertex model-list access denied", () => {+ beforeEach(() => {+ process.env.VERTEX_PROJECT = "vertex-test-project";+ process.env.VERTEX_LOCATION = "us-central1";+ delete process.env.GOOGLE_APPLICATION_CREDENTIALS;+ resetVertexProjectDiscovery();+ _clearVertexDiscoveryCache();+ credentials.getRequestAuth = async () => ({+ headers: { Authorization: "Bearer offline-vertex-test-token" },+ });+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ credentials.getRequestAuth = originalGetRequestAuth;+ if (originalProject === undefined) delete process.env.VERTEX_PROJECT;+ else process.env.VERTEX_PROJECT = originalProject;+ if (originalLocation === undefined) delete process.env.VERTEX_LOCATION;+ else process.env.VERTEX_LOCATION = originalLocation;+ if (originalApplicationCredentials === undefined)+ delete process.env.GOOGLE_APPLICATION_CREDENTIALS;+ else process.env.GOOGLE_APPLICATION_CREDENTIALS = originalApplicationCredentials;+ resetVertexProjectDiscovery();+ _clearVertexDiscoveryCache();+ });++ test("HTTP 403 names the signing account, project source, ADC login and upstream refusal", async () => {+ const requests = installHttpResponses("email");++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason);+ expect(result.reason).toContain("ADC account [email protected]");+ expect(result.reason.indexOf(upstreamMessage)).toBeLessThan(+ result.reason.indexOf("ADC account")+ );+ expect(requests.some((url) => url.startsWith("https://oauth2.googleapis.com/tokeninfo"))).toBe(+ true+ );+ });++ test("HTTP 403 reports a disabled Vertex AI API without diagnosing an account mismatch", async () => {+ const upstream =+ "Vertex AI API has not been used in project vertex-test-project before or it is disabled.";+ installHttpResponses("email", {+ status: 403,+ body: JSON.stringify({+ error: { code: 403, message: upstream, status: "PERMISSION_DENIED" },+ }),+ });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason, 403, upstream);+ expect(result.reason.indexOf(upstream)).toBeLessThan(result.reason.indexOf("ADC account"));+ });++ test("HTTP 401 starts with the upstream authentication refusal and retains the sign-in command", async () => {+ const upstream = "Request had invalid authentication credentials.";+ installHttpResponses("email", {+ status: 401,+ body: JSON.stringify({+ error: { code: 401, message: upstream, status: "UNAUTHENTICATED" },+ }),+ });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason, 401, upstream);+ });++ test("non-JSON HTTP 403 reports the upstream body first", async () => {+ installHttpResponses("email", { status: 403, body: "forbidden" });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason, 403, "forbidden");+ });++ for (const body of ["", " \n\t"]) {+ test(`empty HTTP 403 body ${JSON.stringify(body)} reports no message`, async () => {+ installHttpResponses("email", { status: 403, body });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason, 403, "(no message)");+ });+ }++ test("HTTP 400 reports the upstream sentence before the project source without account lookup", async () => {+ const upstream = "Project 'projects/vertex-test-project' not found or deleted.";+ const requests = installHttpResponses("email", {+ status: 400,+ body: JSON.stringify({+ error: { code: 400, message: upstream, status: "INVALID_ARGUMENT" },+ }),+ });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expect(result.reason).toContain(`HTTP 400: ${upstream}`);+ expect(result.reason).toContain("$VERTEX_PROJECT");+ expect(result.reason).not.toContain("gcloud auth application-default login");+ expect(result.reason).not.toContain("ADC account");+ expect(result.reason).not.toContain("https://");+ expect(result.reason).toContain("project vertex-test-project (from");+ expect(result.reason!.indexOf(upstream)).toBeLessThan(+ result.reason!.indexOf("project vertex-test-project (from")+ );+ expect(requests.some((url) => url.startsWith("https://oauth2.googleapis.com/tokeninfo"))).toBe(+ false+ );+ });++ test("non-JSON HTTP 500 reports the upstream body first", async () => {+ installHttpResponses("email", { status: 500, body: "backend error" });++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expect(result.reason).toContain("HTTP 500: backend error");+ });++ for (const tokeninfo of ["400", "throws"] as const) {+ test(`tokeninfo ${tokeninfo} preserves the actionable HTTP 403 reason without throwing`, async () => {+ const requests = installHttpResponses(tokeninfo);++ const result = await discoverVertexProbeModel();++ expect(result.model).toBeNull();+ expectAccessDeniedReason(result.reason);+ expect(result.reason).not.toContain("[email protected]");+ expect(result.reason).not.toContain("ADC account");+ expect(+ requests.some((url) => url.startsWith("https://oauth2.googleapis.com/tokeninfo"))+ ).toBe(true);+ });+ }+});diff --git a/packages/cli/src/providers/transport/vertex-discovery.ts b/packages/cli/src/providers/transport/vertex-discovery.tsindex d9380713..fbd1db97 100644--- a/packages/cli/src/providers/transport/vertex-discovery.ts+++ b/packages/cli/src/providers/transport/vertex-discovery.ts@@ -64,8 +64,15 @@* for — which is the only honest form the claim can take.*/+import { readFile } from "node:fs/promises";import { credentials } from "../../auth/credentials/authority.js";-import { resolveVertexConfig, vertexApiHost } from "../../auth/vertex-auth.js";+import {+ describeVertexAccessDenied,+ describeVertexProjectSource,+ resolveVertexConfig,+ resolveVertexProjectOrigin,+ vertexApiHost,+} from "../../auth/vertex-auth.js";import { log } from "../../logger.js";import { findEntryByModelId } from "../catalog-query.js";import { type DiscoveredModel, rankDiscoveredModels } from "../model-discovery.js";@@ -215,12 +222,49 @@ export async function listVertexPublisherModels(});if (!response.ok) {- // The upstream sentence is the whole value of this path: a 403 here says- // precisely which permission or quota project is missing, and a guess would- // send the user to the wrong console page.+ log(`[vertex-discovery] HTTP ${response.status} from ${endpoint}`);const detail = await response.text().catch(() => "");+ const upstream = upstreamErrorMessage(detail);+ const origin = await resolveVertexProjectOrigin();+ if (response.status === 401 || response.status === 403) {+ let account: string | undefined;+ try {+ const credPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;+ if (credPath) {+ const credential = JSON.parse(await readFile(credPath, "utf-8")) as {+ client_email?: unknown;+ };+ account = str(credential.client_email);+ } else {+ const token = auth.headers.Authorization?.match(/^Bearer\s+(.+)$/i)?.[1];+ if (token) {+ const tokeninfo = await fetch(+ `https://oauth2.googleapis.com/tokeninfo?access_token=${encodeURIComponent(token)}`,+ { method: "GET", signal: AbortSignal.timeout(3000) }+ );+ if (tokeninfo.ok) {+ account = str(((await tokeninfo.json()) as { email?: unknown }).email);+ }+ }+ }+ } catch {+ // Best-effort account lookup must not hide the upstream refusal or log the token.+ }+ const explanation = describeVertexAccessDenied({+ status: response.status,+ upstream,+ account,+ origin,+ projectId: config.projectId,+ });+ throw new Error(explanation);+ }throw new Error(- `HTTP ${response.status} from ${endpoint}${detail ? ` — ${oneLine(detail)}` : ""}`+ [+ `HTTP ${response.status}: ${upstream}`,+ `project ${config.projectId}` ++ (origin ? ` (from ${describeVertexProjectSource(origin)})` : ""),+ ].join(" · "));}@@ -244,6 +288,17 @@ function oneLine(text: string, max = 200): string {return flat.length > max ? `${flat.slice(0, max)}…` : flat;}+function upstreamErrorMessage(detail: string): string {+ try {+ const body = JSON.parse(detail) as { error?: { message?: unknown } } | null;+ const message = str(body?.error?.message);+ if (message) return message;+ } catch {+ // Non-JSON refusals retain the upstream body.+ }+ return oneLine(detail) || "(no message)";+}+/** What one `:countTokens` check established about one candidate. */interface VerifiedCandidate {id: string;