Skip to content

Commit 3422bba

Browse files
committed
fix(google): honor Cloud SDK credential location and Vertex billing project
1 parent 7fabb55 commit 3422bba

7 files changed

Lines changed: 446 additions & 28 deletions

File tree

‎extensions/google/index.test.ts‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Google tests cover index plugin behavior.
2-
import { mkdtemp, writeFile } from "node:fs/promises";
2+
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import type { Context, Model } from "openclaw/plugin-sdk/llm";
@@ -327,6 +327,86 @@ describe("google provider plugin hooks", () => {
327327
).toBe("gcp-vertex-credentials");
328328
});
329329

330+
it("prefers relocated Google Cloud SDK ADC over the home fallback", async () => {
331+
const tempDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-google-vertex-cloud-sdk-"));
332+
const cloudSdkDir = path.join(tempDir, "cloud-sdk");
333+
const homeCredentialsDir = path.join(tempDir, "home", ".config", "gcloud");
334+
await Promise.all([
335+
mkdir(cloudSdkDir, { recursive: true }),
336+
mkdir(homeCredentialsDir, { recursive: true }),
337+
]);
338+
const relocatedCredentialsPath = path.join(cloudSdkDir, "application_default_credentials.json");
339+
const homeCredentialsPath = path.join(
340+
homeCredentialsDir,
341+
"application_default_credentials.json",
342+
);
343+
await Promise.all([
344+
writeFile(
345+
relocatedCredentialsPath,
346+
JSON.stringify({
347+
type: "authorized_user",
348+
client_id: "fixture-client",
349+
client_secret: "fixture-secret",
350+
refresh_token: "fixture-refresh",
351+
}),
352+
"utf8",
353+
),
354+
writeFile(homeCredentialsPath, JSON.stringify({ type: "unsupported" }), "utf8"),
355+
]);
356+
const { providers } = await registerProviderPlugin({
357+
plugin: googleProviderPlugin,
358+
id: "google",
359+
name: "Google Provider",
360+
});
361+
const provider = requireRegisteredProvider(providers, "google-vertex");
362+
const env = {
363+
CLOUDSDK_CONFIG: cloudSdkDir,
364+
HOME: path.join(tempDir, "home"),
365+
GOOGLE_CLOUD_PROJECT: "fixture-project",
366+
GOOGLE_CLOUD_LOCATION: "global",
367+
};
368+
369+
expect(provider.resolveConfigApiKey?.({ provider: "google-vertex", env })).toBe(
370+
"gcp-vertex-credentials",
371+
);
372+
expect(googleProviderDiscovery.resolveConfigApiKey?.({ provider: "google-vertex", env })).toBe(
373+
"gcp-vertex-credentials",
374+
);
375+
expect(
376+
provider.resolveConfigApiKey?.({
377+
provider: "google-vertex",
378+
env: { ...env, GOOGLE_APPLICATION_CREDENTIALS: homeCredentialsPath },
379+
}),
380+
).toBeUndefined();
381+
382+
await writeFile(
383+
homeCredentialsPath,
384+
JSON.stringify({
385+
type: "authorized_user",
386+
client_id: "stale-client",
387+
client_secret: "stale-secret",
388+
refresh_token: "stale-refresh",
389+
}),
390+
"utf8",
391+
);
392+
const missingRelocatedCredentialsEnv = {
393+
...env,
394+
CLOUDSDK_CONFIG: path.join(tempDir, "missing-cloud-sdk"),
395+
};
396+
expect(
397+
provider.resolveConfigApiKey?.({
398+
provider: "google-vertex",
399+
env: missingRelocatedCredentialsEnv,
400+
}),
401+
).toBeUndefined();
402+
expect(
403+
googleProviderDiscovery.resolveConfigApiKey?.({
404+
provider: "google-vertex",
405+
env: missingRelocatedCredentialsEnv,
406+
}),
407+
).toBeUndefined();
408+
});
409+
330410
it("owns Gemini tool schema normalization for direct and CLI providers", async () => {
331411
const { providers } = await registerProviderPlugin({
332412
plugin: googleProviderPlugin,

‎extensions/google/manifest.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@ import type { JsonSchemaObject } from "openclaw/plugin-sdk/json-schema-runtime";
55
import { describe, expect, it } from "vitest";
66

77
type GoogleManifest = {
8+
setup?: {
9+
providers?: Array<{
10+
id?: string;
11+
authEvidence?: Array<{
12+
fileEnvVar?: string;
13+
fallbackPaths?: string[];
14+
}>;
15+
}>;
16+
};
817
providerAuthChoices?: Array<{
918
provider?: string;
1019
method?: string;
@@ -86,6 +95,23 @@ function loadManifest(): GoogleManifest {
8695
}
8796

8897
describe("google manifest model catalog", () => {
98+
it("checks relocated Cloud SDK ADC before platform-specific fallback paths", () => {
99+
const vertex = loadManifest().setup?.providers?.find(
100+
(provider) => provider.id === "google-vertex",
101+
);
102+
103+
expect(vertex?.authEvidence).toEqual([
104+
expect.objectContaining({
105+
fileEnvVar: "GOOGLE_APPLICATION_CREDENTIALS",
106+
fallbackPaths: [
107+
"${CLOUDSDK_CONFIG}/application_default_credentials.json",
108+
"${HOME}/.config/gcloud/application_default_credentials.json",
109+
"${APPDATA}/gcloud/application_default_credentials.json",
110+
],
111+
}),
112+
]);
113+
});
114+
89115
it("offers Google AI Studio API keys without consumer CLI OAuth", () => {
90116
const choices = loadManifest().providerAuthChoices ?? [];
91117

‎extensions/google/openclaw.plugin.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -669,6 +669,7 @@
669669
"type": "local-file-with-env",
670670
"fileEnvVar": "GOOGLE_APPLICATION_CREDENTIALS",
671671
"fallbackPaths": [
672+
"${CLOUDSDK_CONFIG}/application_default_credentials.json",
672673
"${HOME}/.config/gcloud/application_default_credentials.json",
673674
"${APPDATA}/gcloud/application_default_credentials.json"
674675
],

‎extensions/google/transport-stream.test.ts‎

Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,11 @@ async function runGoogleVertexStreamResult(params: {
137137
return stream.result();
138138
}
139139

140-
async function useGoogleAuthorizedUserCredentials(label: string, refreshToken: string) {
140+
async function useGoogleAuthorizedUserCredentials(
141+
label: string,
142+
refreshToken: string,
143+
quotaProjectId?: string,
144+
) {
141145
const tempDir = await mkdtemp(path.join(os.tmpdir(), `openclaw-google-vertex-${label}-`));
142146
const credentialsPath = path.join(tempDir, "application_default_credentials.json");
143147
await writeFile(
@@ -147,6 +151,7 @@ async function useGoogleAuthorizedUserCredentials(label: string, refreshToken: s
147151
client_id: "client-id",
148152
client_secret: "client-secret",
149153
refresh_token: refreshToken,
154+
...(quotaProjectId ? { quota_project_id: quotaProjectId } : {}),
150155
}),
151156
"utf8",
152157
);
@@ -1469,6 +1474,37 @@ describe("google transport stream", () => {
14691474
expect(tokenFetchMock).not.toHaveBeenCalled();
14701475
});
14711476

1477+
it("never refreshes stale home ADC when the selected Cloud SDK directory has no credentials", async () => {
1478+
const tempDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-google-vertex-stale-home-"));
1479+
const homeCredentialsDir = path.join(tempDir, "home", ".config", "gcloud");
1480+
await mkdir(homeCredentialsDir, { recursive: true });
1481+
await writeFile(
1482+
path.join(homeCredentialsDir, "application_default_credentials.json"),
1483+
JSON.stringify({
1484+
type: "authorized_user",
1485+
client_id: "stale-client",
1486+
client_secret: "stale-secret",
1487+
refresh_token: "stale-refresh",
1488+
}),
1489+
"utf8",
1490+
);
1491+
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", "");
1492+
vi.stubEnv("CLOUDSDK_CONFIG", path.join(tempDir, "missing-cloud-sdk"));
1493+
vi.stubEnv("HOME", path.join(tempDir, "home"));
1494+
vi.stubEnv("APPDATA", "");
1495+
googleAuthGetAccessTokenMock.mockResolvedValueOnce("fixture-google-auth-token");
1496+
const tokenFetchMock = vi.fn();
1497+
1498+
await expect(resolveGoogleVertexAuthorizedUserHeaders(tokenFetchMock)).resolves.toEqual({
1499+
Authorization: "Bearer fixture-google-auth-token",
1500+
});
1501+
expect(googleAuthMock).toHaveBeenCalledWith({
1502+
scopes: ["https://www.googleapis.com/auth/cloud-platform"],
1503+
clientOptions: { transporterOptions: { timeout: 30_000 } },
1504+
});
1505+
expect(tokenFetchMock).not.toHaveBeenCalled();
1506+
});
1507+
14721508
it("bounds Google Vertex ADC files before google-auth-library reads them", async () => {
14731509
const tempDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-google-vertex-adc-file-"));
14741510
const credentialsPath = path.join(tempDir, "application_default_credentials.json");
@@ -1593,6 +1629,97 @@ describe("google transport stream", () => {
15931629
expect(new Headers(guardedInit.headers).has("x-goog-api-key")).toBe(false);
15941630
});
15951631

1632+
it.each([
1633+
{
1634+
scenario: "authorized-user ADC quota project",
1635+
credentialType: "authorized_user",
1636+
credentialQuotaProject: "fixture-json-billing",
1637+
envQuotaProject: "",
1638+
expectedQuotaProject: "fixture-json-billing",
1639+
},
1640+
{
1641+
scenario: "environment quota project overriding authorized-user ADC",
1642+
credentialType: "authorized_user",
1643+
credentialQuotaProject: "fixture-json-billing",
1644+
envQuotaProject: "fixture-env-billing",
1645+
expectedQuotaProject: "fixture-env-billing",
1646+
},
1647+
{
1648+
scenario: "google-auth service-account ADC quota project",
1649+
credentialType: "service_account",
1650+
credentialQuotaProject: "fixture-service-billing",
1651+
envQuotaProject: "",
1652+
expectedQuotaProject: "fixture-service-billing",
1653+
},
1654+
{
1655+
scenario: "google-auth metadata ADC environment quota project",
1656+
credentialType: "metadata",
1657+
credentialQuotaProject: "",
1658+
envQuotaProject: "fixture-metadata-billing",
1659+
expectedQuotaProject: "fixture-metadata-billing",
1660+
},
1661+
])(
1662+
"forwards the $scenario on the actual Vertex request",
1663+
async ({ credentialType, credentialQuotaProject, envQuotaProject, expectedQuotaProject }) => {
1664+
const tokenFetchMock = vi.fn();
1665+
vi.stubEnv("GOOGLE_CLOUD_PROJECT", "fixture-project");
1666+
vi.stubEnv("GOOGLE_CLOUD_LOCATION", "global");
1667+
vi.stubEnv("GOOGLE_CLOUD_QUOTA_PROJECT", envQuotaProject);
1668+
if (credentialType === "authorized_user") {
1669+
await useGoogleAuthorizedUserCredentials(
1670+
"quota-authorized-user",
1671+
"fixture-refresh-token",
1672+
credentialQuotaProject,
1673+
);
1674+
tokenFetchMock.mockResolvedValueOnce(
1675+
new Response(JSON.stringify({ access_token: "fixture-vertex-token", expires_in: 3600 }), {
1676+
status: 200,
1677+
headers: { "content-type": "application/json" },
1678+
}),
1679+
);
1680+
} else if (credentialType === "service_account") {
1681+
const tempDir = await mkdtemp(
1682+
path.join(os.tmpdir(), "openclaw-google-vertex-quota-service-"),
1683+
);
1684+
const credentialsPath = path.join(tempDir, "application_default_credentials.json");
1685+
await writeFile(
1686+
credentialsPath,
1687+
JSON.stringify({
1688+
type: "service_account",
1689+
client_email: "[email protected]",
1690+
quota_project_id: credentialQuotaProject,
1691+
}),
1692+
"utf8",
1693+
);
1694+
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", credentialsPath);
1695+
googleAuthGetAccessTokenMock.mockResolvedValueOnce("fixture-vertex-token");
1696+
} else {
1697+
const tempDir = await mkdtemp(
1698+
path.join(os.tmpdir(), "openclaw-google-vertex-quota-metadata-"),
1699+
);
1700+
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", "");
1701+
vi.stubEnv("HOME", path.join(tempDir, "home"));
1702+
vi.stubEnv("APPDATA", "");
1703+
googleAuthGetAccessTokenMock.mockResolvedValueOnce("fixture-vertex-token");
1704+
}
1705+
guardedFetchMock.mockResolvedValueOnce(
1706+
buildSseResponse([
1707+
{
1708+
candidates: [{ content: { parts: [{ text: "ok" }] }, finishReason: "STOP" }],
1709+
},
1710+
]),
1711+
);
1712+
1713+
await runGoogleVertexStreamResult({ fetch: tokenFetchMock });
1714+
1715+
const guardedCall = requireMockCall(guardedFetchMock, 0, "guarded fetch");
1716+
expectHeaders(requireRequestInit(guardedCall, "guarded fetch"), {
1717+
Authorization: "Bearer fixture-vertex-token",
1718+
"x-goog-user-project": expectedQuotaProject,
1719+
});
1720+
},
1721+
);
1722+
15961723
it("strips redundant google provider prefixes from Google Vertex model paths", async () => {
15971724
const tempDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-google-vertex-prefix-"));
15981725
vi.stubEnv("HOME", path.join(tempDir, "home"));

‎extensions/google/vertex-adc.ts‎

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ function resolveGoogleApplicationCredentialsPath(
132132
if (explicit) {
133133
return existsSync(explicit) ? explicit : undefined;
134134
}
135+
const cloudSdkDir = normalizeOptionalString(env.CLOUDSDK_CONFIG);
136+
if (cloudSdkDir) {
137+
const cloudSdkFallback = path.join(cloudSdkDir, "application_default_credentials.json");
138+
return existsSync(cloudSdkFallback) ? cloudSdkFallback : undefined;
139+
}
135140
const homeDir = normalizeOptionalString(env.HOME) ?? os.homedir();
136141
const homeFallback = path.join(
137142
homeDir,
@@ -449,22 +454,23 @@ export async function resolveGoogleVertexAuthorizedUserHeaders(
449454
fetchImpl?: typeof fetch,
450455
): Promise<Record<string, string>> {
451456
const adcPath = resolveGoogleApplicationCredentialsPath();
452-
let adcConfig: GoogleAdcConfig | undefined;
453-
if (adcPath) {
454-
adcConfig = readGoogleAdcCredentials(adcPath);
455-
const userAdc = resolveGoogleAuthorizedUserCredentials(adcConfig);
456-
if (userAdc) {
457-
const token = await refreshGoogleVertexAuthorizedUserAccessToken({
458-
credentialsPath: adcPath,
459-
credentials: userAdc,
460-
fetchImpl,
461-
});
462-
return { Authorization: `Bearer ${token}` };
463-
}
464-
}
465-
// No file-based authorized_user ADC. Fall back to google-auth-library which
466-
// handles GKE Workload Identity (metadata server), Workload Identity
467-
// Federation (external_account), and service-account keys.
468-
const token = await resolveGoogleVertexAccessTokenViaGoogleAuth(adcConfig);
469-
return { Authorization: `Bearer ${token}` };
457+
const adcConfig = adcPath ? readGoogleAdcCredentials(adcPath) : undefined;
458+
const userAdc = adcConfig ? resolveGoogleAuthorizedUserCredentials(adcConfig) : undefined;
459+
// Google auth owns metadata, federation, and service-account ADC variants.
460+
const token =
461+
userAdc && adcPath
462+
? await refreshGoogleVertexAuthorizedUserAccessToken({
463+
credentialsPath: adcPath,
464+
credentials: userAdc,
465+
fetchImpl,
466+
})
467+
: await resolveGoogleVertexAccessTokenViaGoogleAuth(adcConfig);
468+
// Google auth gives the explicit billing project precedence over ADC metadata.
469+
const quotaProject =
470+
normalizeOptionalString(process.env.GOOGLE_CLOUD_QUOTA_PROJECT) ??
471+
normalizeOptionalString((adcConfig as Record<string, unknown> | undefined)?.quota_project_id);
472+
return {
473+
Authorization: `Bearer ${token}`,
474+
...(quotaProject ? { "x-goog-user-project": quotaProject } : {}),
475+
};
470476
}

0 commit comments

Comments
 (0)