Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/ai-provider-bridge/src/google-vertex-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ function adcKeyFile(source: GoogleVertexCredentialSource & { kind: "adc" }): str
);
}

/**
* The `GOOGLE_APPLICATION_CREDENTIALS` path ADC reads, or undefined when it
* uses gcloud's file or the metadata server (or the source isn't ADC).
*/
export function googleVertexKeyFile(source: GoogleVertexCredentialSource): string | undefined {
return source.kind === "adc" ? adcKeyFile(source) : undefined;
}

/**
* The `GOOGLE_APPLICATION_CREDENTIALS` path when it points at a file that does
* not exist. google-auth-library does not fall back to gcloud's file then, so
Expand Down
7 changes: 6 additions & 1 deletion packages/ai-provider-bridge/src/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export {
} from "./providers/foundry-provider";
export { registerCustomGeminiProvider, registerGeminiProvider } from "./providers/gemini-provider";
export {
checkGoogleVertexSignIn,
registerCustomGoogleVertexProvider,
registerGoogleVertexProvider,
} from "./providers/google-vertex-provider";
Expand All @@ -53,7 +54,11 @@ export {
resolveGoogleVertexCredentialSource,
} from "./google-vertex-credentials";
export type { GoogleVertexCredentialSource } from "./google-vertex-credentials";
export type { GoogleVertexProviderCallbacks } from "./providers/google-vertex-provider";
export type {
GoogleVertexProviderCallbacks,
GoogleVertexProviderStatusUpdate,
GoogleVertexSignInCheck,
} from "./providers/google-vertex-provider";
export {
registerCustomLitellmProvider,
registerLitellmProvider,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ import {
getEffectiveLocation,
isVertexAnthropicModel,
} from "../../model-clients/GoogleVertexClient";
import type { Logger } from "../../types";
import type { GoogleCloudCredentials, Logger } from "../../types";
import {
checkGoogleVertexSignIn,
claudeDisplayName,
registerCustomGoogleVertexProvider,
registerGoogleVertexProvider,
Expand Down Expand Up @@ -507,6 +508,83 @@ describe("resolveGoogleVertexAccessToken", () => {
});
});

describe("checkGoogleVertexSignIn", () => {
const credentials: GoogleCloudCredentials = { type: "google-cloud", project: "my-project" };

beforeEach(() => {
vi.clearAllMocks();
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", undefined);
authMocks.getClient.mockResolvedValue({ getAccessToken: authMocks.getAccessToken });
// A `function` (not an arrow) so the code under test can call it with
// `new GoogleAuth(...)`; returning an object makes it the instance.
authMocks.googleAuth.mockImplementation(function () {
return { getClient: authMocks.getClient };
});
});

afterEach(() => {
vi.unstubAllEnvs();
});

it("requires sign-in when ADC is expired, returning a userInitiated adc_expired update", async () => {
authMocks.getAccessToken.mockRejectedValueOnce(new Error("invalid_grant"));

const result = await checkGoogleVertexSignIn("custom-vertex", credentials, mockLogger, {});

expect(result).toEqual({
status: "sign-in-required",
update: expect.objectContaining({
providerId: "custom-vertex",
authMethodId: "google-cloud",
status: "auth_error",
error: expect.objectContaining({ code: "adc_expired" }),
userInitiated: true,
}),
});
});

it("is unknown when GOOGLE_APPLICATION_CREDENTIALS points at a missing file", async () => {
authMocks.getClient.mockRejectedValueOnce(new Error("Could not load the default credentials."));

await expect(
checkGoogleVertexSignIn("google-vertex", credentials, mockLogger, {
GOOGLE_APPLICATION_CREDENTIALS: "/no/such/adc.json",
}),
).resolves.toEqual({ status: "unknown" });
});

it("is unknown when an existing GOOGLE_APPLICATION_CREDENTIALS file is rejected", async () => {
// A gcloud login writes gcloud's own file, which this explicit file
// overrides, so prompting to sign in again could not fix it.
const dir = mkdtempSync(join(tmpdir(), "vertex-key-"));
try {
const keyFile = join(dir, "service-account.json");
writeFileSync(keyFile, "{}");
authMocks.getAccessToken.mockRejectedValueOnce(new Error("invalid_grant"));

await expect(
checkGoogleVertexSignIn("google-vertex", credentials, mockLogger, {
GOOGLE_APPLICATION_CREDENTIALS: keyFile,
}),
).resolves.toEqual({ status: "unknown" });
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it("is ok for a brokered token without minting", async () => {
await expect(
checkGoogleVertexSignIn(
"google-vertex",
{ ...credentials, accessToken: "brokered-token" },
mockLogger,
undefined,
),
).resolves.toEqual({ status: "ok" });
expect(authMocks.googleAuth).not.toHaveBeenCalled();
});
});

describe("describeGoogleVertexCredentialSource", () => {
let dir: string;

Expand Down
6 changes: 3 additions & 3 deletions packages/ai-provider-bridge/src/providers/bedrock-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ export interface BedrockProviderStatusUpdate {
};
};
/**
* Set when a user action (a send-time sign-in check) produced the update rather than model
* discovery. Hosts re-show the prompt even if it was already shown or dismissed, and must not
* count the update as discovery evidence (e.g. as a reconnect verification verdict).
* Set when a sign-in check (before a send or after a failed turn) produced the update rather
* than model discovery. Hosts re-show the prompt even if it was already shown or dismissed, and
* must not count the update as discovery evidence (e.g. as a reconnect verification verdict).
*/
userInitiated?: true;
}
Expand Down
116 changes: 89 additions & 27 deletions packages/ai-provider-bridge/src/providers/google-vertex-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,42 @@ import {
type GoogleVertexCredentialSource,
isInlineServiceAccountError,
mintGoogleVertexAccessToken,
googleVertexKeyFile,
missingGoogleVertexKeyFile,
resolveGoogleVertexCredentialSource,
} from "../google-vertex-credentials";
import { GoogleVertexClient } from "../model-clients/GoogleVertexClient";
import type { Logger, ModelInfo, ProviderCredentials } from "../types";
import type { GoogleCloudCredentials, Logger, ModelInfo, ProviderCredentials } from "../types";
import { NOTIFICATION_ACTIONS } from "../types";
import type { ClientFactory, ProviderRegistry } from "./ProviderRegistry";

/** A Google Vertex provider status update, with full provider context. */
export interface GoogleVertexProviderStatusUpdate {
providerId: string;
authMethodId: string;
status: "ok" | "auth_error" | "network_error";
error?: {
code: string;
message: string;
action?: {
label: string;
commandId: string;
};
};
/**
* Set when a sign-in check (before a send or after a failed turn) produced the update rather
* than model discovery. Hosts re-show the prompt even if it was already shown or dismissed, and
* must not count the update as discovery evidence (e.g. as a reconnect verification verdict).
*/
userInitiated?: true;
}

/**
* Optional callbacks for platform-specific Google Vertex provider status updates.
* Same interface shape as BedrockProviderCallbacks.
*/
export interface GoogleVertexProviderCallbacks {
onProviderStatusChange?: (update: {
providerId: string;
authMethodId: string;
status: "ok" | "auth_error" | "network_error";
error?: {
code: string;
message: string;
action?: {
label: string;
commandId: string;
};
};
}) => Promise<void>;
onProviderStatusChange?: (update: GoogleVertexProviderStatusUpdate) => Promise<void>;
}

/**
Expand Down Expand Up @@ -103,6 +113,70 @@ function authErrorGuidance(source: GoogleVertexCredentialSource): {
return AUTH_ERROR_GUIDANCE[source.kind];
}

function vertexAuthErrorUpdate(
providerId: string,
guidance: { code: string; message: string },
): GoogleVertexProviderStatusUpdate {
return {
providerId,
authMethodId: "google-cloud",
status: "auth_error",
error: {
code: guidance.code,
message: guidance.message,
action: {
label: "Reload model list",
commandId: NOTIFICATION_ACTIONS.REFRESH_MODELS,
},
},
};
}

/** Result of {@link checkGoogleVertexSignIn}. */
export type GoogleVertexSignInCheck =
| { status: "ok" }
| { status: "unknown" }
| { status: "sign-in-required"; update: GoogleVertexProviderStatusUpdate };

/**
* Mint a Vertex access token and report whether the user must sign in again. Publishes nothing:
* on `sign-in-required` the result carries the `adc_expired` status update (the model list's copy,
* flagged `userInitiated`) for the caller to deliver to its status callbacks. Any other failure,
* including other auth errors (a missing key file, rejected inline credentials), is `unknown`.
* So is a rejected `GOOGLE_APPLICATION_CREDENTIALS` file: it overrides gcloud's file, so signing
* in again with gcloud could not repair it. A brokered token is returned as-is by minting, so it is `ok` without being validated.
* `credentialEnvironment` is the same captured environment the client factory receives
* (undefined reads `process.env`).
*/
export async function checkGoogleVertexSignIn(
providerId: string,
credentials: GoogleCloudCredentials,
logger: Logger,
credentialEnvironment: Readonly<Record<string, string | undefined>> | undefined,
): Promise<GoogleVertexSignInCheck> {
const credentialSource = resolveGoogleVertexCredentialSource(
credentials.accessToken,
credentialEnvironment,
);
try {
await mintGoogleVertexAccessToken(credentialSource);
return { status: "ok" };
} catch (error) {
const guidance = isAuthError(error) ? authErrorGuidance(credentialSource) : undefined;
if (guidance?.code !== "adc_expired" || googleVertexKeyFile(credentialSource)) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.warn(
`[GoogleVertex] Sign-in check for ${providerId} could not mint a token from ${describeGoogleVertexCredentialSource(credentialSource)}: ${errorMsg}`,
);
return { status: "unknown" };
}
return {
status: "sign-in-required",
update: { ...vertexAuthErrorUpdate(providerId, guidance), userInitiated: true },
};
}
}

/**
* Fetch models from a single Vertex AI publisher endpoint.
*/
Expand Down Expand Up @@ -393,19 +467,7 @@ function createGoogleVertexModelFetcher(
`[GoogleVertex] ${guidance.message} Credential source: ${sourceDescription}. Error: ${errorMsg}`,
);

await callbacks?.onProviderStatusChange?.({
providerId,
authMethodId: "google-cloud",
status: "auth_error",
error: {
code: guidance.code,
message: guidance.message,
action: {
label: "Reload model list",
commandId: NOTIFICATION_ACTIONS.REFRESH_MODELS,
},
},
});
await callbacks?.onProviderStatusChange?.(vertexAuthErrorUpdate(providerId, guidance));

// Clear cache so subsequent requests don't short-circuit
cachedModels = null;
Expand Down
Loading