Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Vertex AI login for Claude on managed machines (#756)

Louis Amaudruz071011f4eea2
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
index c1bdb3c35..f17af9ec4 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
@@ -1,7 +1,9 @@
import {
+ parseGoogleCredentials,
type ProviderLogin,
sealingKeyId,
sealProviderLogin,
+ vertexLoginCredential,
} from '@switch-console/agent-providers';
import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';
import { hostControllerService } from '@main/core/host-controllers/host-controllers';
@@ -18,6 +20,10 @@ import {
setManagedAgentDesiredState,
updateManagedAgent,
} from '@main/core/switch-servers/gateway-client';
+import {
+ localGoogleCredentialsPath,
+ readLocalGoogleCredentials,
+} from '@main/core/switch-servers/local-google-sign-in';
import {
localProviderAuthPath,
readLocalProviderSignIn,
@@ -244,6 +250,21 @@ async function loginToGive(
provider: AgentProviderId,
input: MachineLoginInput
): Promise<ProviderLogin> {
+ if (input.source === 'vertex') {
+ if (provider !== 'claude') throw new Error('Only Claude signs in through Vertex AI.');
+ const text =
+ input.credentials.from === 'key'
+ ? input.credentials.json.trim()
+ : await readLocalGoogleCredentials(localGoogleCredentialsPath());
+ if (!text) throw new Error('Paste the service account key, or pick its JSON file.');
+ const credential = vertexLoginCredential({
+ project: input.project,
+ region: input.region,
+ credentials: parseGoogleCredentials(text),
+ });
+ if (credential.length > 16384) throw new Error('The Google credential is too large to give.');
+ return { kind: 'vertex', credential };
+ }
if (input.source === 'typed') {
const credential = input.credential.trim();
if (!credential) throw new Error('Enter the key or token to give the machine.');
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
index 44cd89522..ec73bdb92 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/give-machine-login.test.ts
@@ -1,9 +1,17 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import {
generateSealingKeyPair,
openProviderLogin,
+ parseVertexLogin,
sealingKeyId,
} from '@switch-console/agent-providers';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ AUTHORIZED_USER_FIXTURE,
+ SERVICE_ACCOUNT_KEY_FIXTURE,
+} from '@switch-console/agent-providers/testing';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
fetchManagementControllers: vi.fn(),
@@ -99,6 +107,83 @@ describe('giving a machine a provider login', () => {
).rejects.toThrow(/cannot be given/);
});
+ describe('through Vertex AI', () => {
+ let gcloud: string;
+ const previous = process.env.CLOUDSDK_CONFIG;
+ beforeEach(() => {
+ gcloud = mkdtempSync(join(tmpdir(), 'gcloud-'));
+ process.env.CLOUDSDK_CONFIG = gcloud;
+ mocks.fetchManagementControllers.mockResolvedValue([
+ machine({ key: keys.publicKey, keyId: sealingKeyId(keys.publicKey) }),
+ ]);
+ });
+ afterEach(() => {
+ if (previous === undefined) delete process.env.CLOUDSDK_CONFIG;
+ else process.env.CLOUDSDK_CONFIG = previous;
+ rmSync(gcloud, { recursive: true, force: true });
+ });
+
+ const give = (
+ credentials: { from: 'key'; json: string } | { from: 'this-computer' },
+ provider: 'claude' | 'codex' = 'claude',
+ project = 'cg-vertexai'
+ ) =>
+ managedAgentsController.giveMachineLogin({
+ serverId: 'server-1',
+ machineId: 'controller-1',
+ provider,
+ login: { source: 'vertex', project, region: 'global', credentials },
+ });
+
+ function given() {
+ const [, , provider, sealed] = mocks.giveMachineLogin.mock.calls.at(-1)!;
+ const login = openProviderLogin({ keys, controllerId: 'controller-1', provider, sealed });
+ expect(login.kind).toBe('vertex');
+ return parseVertexLogin(login.credential);
+ }
+
+ it('seals a pasted service account key with the project and region', async () => {
+ await give({ from: 'key', json: ` ${JSON.stringify(SERVICE_ACCOUNT_KEY_FIXTURE)}\n` });
+ expect(JSON.stringify(mocks.giveMachineLogin.mock.calls[0]![3])).not.toContain('PRIVATE KEY');
+ expect(given()).toEqual({
+ v: 1,
+ project: 'cg-vertexai',
+ region: 'global',
+ credentials: SERVICE_ACCOUNT_KEY_FIXTURE,
+ });
+ });
+
+ it("seals this computer's Google sign-in, from CLOUDSDK_CONFIG", async () => {
+ writeFileSync(
+ join(gcloud, 'application_default_credentials.json'),
+ JSON.stringify(AUTHORIZED_USER_FIXTURE)
+ );
+ await give({ from: 'this-computer' });
+ expect(given().credentials).toEqual(AUTHORIZED_USER_FIXTURE);
+ });
+
+ it('says to sign in with gcloud when this computer has no Google sign-in', async () => {
+ await expect(give({ from: 'this-computer' })).rejects.toThrow(
+ 'Run `gcloud auth application-default login` on this computer first.'
+ );
+ expect(mocks.giveMachineLogin).not.toHaveBeenCalled();
+ });
+
+ it('refuses another provider, another credential type, or a bad project', async () => {
+ const key = { from: 'key' as const, json: JSON.stringify(SERVICE_ACCOUNT_KEY_FIXTURE) };
+ await expect(give(key, 'codex')).rejects.toThrow(/Only Claude/);
+ await expect(
+ give({ from: 'key', json: JSON.stringify({ type: 'external_account' }) })
+ ).rejects.toThrow(/Only a service account key/);
+ await expect(give({ from: 'key', json: '{' })).rejects.toThrow(/not JSON/);
+ await expect(give({ from: 'key', json: ' ' })).rejects.toThrow(
+ /Paste the service account key/
+ );
+ await expect(give(key, 'claude', 'Not A Project')).rejects.toThrow(/project id/);
+ expect(mocks.giveMachineLogin).not.toHaveBeenCalled();
+ });
+ });
+
it('refuses a machine with no key, or a key that does not match its id', async () => {
mocks.fetchManagementControllers.mockResolvedValue([machine(null)]);
const give = () =>
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/local-google-sign-in.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-google-sign-in.ts
new file mode 100644
index 000000000..1e4a5fd73
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-google-sign-in.ts
@@ -0,0 +1,43 @@
+import { open } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+/** Where `gcloud auth application-default login` writes this computer's Google sign-in. */
+export function localGoogleCredentialsPath(): string {
+ const config =
+ process.env.CLOUDSDK_CONFIG ||
+ (process.platform === 'win32' && process.env.APPDATA
+ ? join(process.env.APPDATA, 'gcloud')
+ : join(homedir(), '.config', 'gcloud'));
+ return join(config, 'application_default_credentials.json');
+}
+
+const MAX_BYTES = 16384;
+
+/** This computer's Google application-default sign-in, as its file holds it. */
+export async function readLocalGoogleCredentials(path: string): Promise<string> {
+ let file;
+ try {
+ file = await open(path, 'r');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ throw new Error(
+ 'This computer has no Google sign-in. Run `gcloud auth application-default login` on this computer first.'
+ );
+ throw new Error(
+ `Could not read this computer's Google sign-in at ${path}. Check its permissions.`
+ );
+ }
+ try {
+ const stat = await file.stat();
+ if (!stat.isFile() || stat.size > MAX_BYTES)
+ throw new Error(`This computer's Google sign-in at ${path} is not a JSON file under 16 KiB.`);
+ const buffer = Buffer.alloc(MAX_BYTES + 1);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > MAX_BYTES)
+ throw new Error(`This computer's Google sign-in at ${path} is too large.`);
+ return buffer.toString('utf8', 0, bytesRead);
+ } finally {
+ await file.close();
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/give-machine-login.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/give-machine-login.tsx
index bf4e0f934..e99347b8f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/give-machine-login.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/give-machine-login.tsx
@@ -1,19 +1,30 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { CircleAlert, CircleCheck, KeyRound } from 'lucide-react';
-import { useEffect, useState } from 'react';
+import { CircleAlert, CircleCheck, KeyRound, TriangleAlert, Upload } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
import { MANAGED_AGENTS_KEY } from '@renderer/features/managed-agents/use-managed-agents';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
import { Spinner } from '@renderer/lib/ui/spinner';
+import { Textarea } from '@renderer/lib/ui/textarea';
import type { MachineLoginInput, OwnedMachine } from '@shared/core/managed-agents/managed-agents';
import {
type AgentProviderId,
providerDisplayName,
} from '@shared/core/providers/agent-provider-registry';
-type LoginKind = 'setup-token' | 'api-key' | 'this-computer';
+type LoginKind = 'setup-token' | 'api-key' | 'this-computer' | 'vertex';
+type VertexSource = 'key' | 'this-computer';
+
+const VERTEX_SOURCES: { value: VertexSource; label: string }[] = [
+ { value: 'key', label: 'Service account key (recommended)' },
+ { value: 'this-computer', label: "This computer's Google sign-in" },
+];
+
+/** What Claude Code on Vertex AI is set up with at SandboxAQ (`cg-claude-code-starter`). */
+const VERTEX_DEFAULTS = { project: 'cg-vertexai', region: 'global' };
/** The ways a machine can be given each provider's login. */
export function loginKindsFor(provider: AgentProviderId): { value: LoginKind; label: string }[] {
@@ -22,6 +33,7 @@ export function loginKindsFor(provider: AgentProviderId): { value: LoginKind; la
return [
{ value: 'setup-token', label: 'Setup token' },
{ value: 'api-key', label: 'API key' },
+ { value: 'vertex', label: 'Vertex AI' },
];
case 'codex':
return [
@@ -39,7 +51,11 @@ function displayName(provider: AgentProviderId): string {
return providerDisplayName(provider) ?? provider;
}
-function hint(provider: AgentProviderId, kind: LoginKind): string {
+function hint(provider: AgentProviderId, kind: LoginKind, source: VertexSource): string {
+ if (kind === 'vertex')
+ return source === 'key'
+ ? `${displayName(provider)} signs in to Google Vertex AI with a service account key. Make one for a service account that can use only Vertex AI (roles/aiplatform.user), and paste its JSON or pick its file.`
+ : `${displayName(provider)} signs in to Google Vertex AI as you, with the sign-in \`gcloud auth application-default login\` made on this computer.`;
if (kind === 'setup-token')
return 'Run `claude setup-token` on any computer signed in to Claude, and paste the token it prints.';
if (kind === 'this-computer')
@@ -67,15 +83,31 @@ export function GiveMachineLogin({
const kinds = loginKindsFor(provider);
const [kind, setKind] = useState<LoginKind>(kinds[0]!.value);
const [credential, setCredential] = useState('');
+ const [vertexSource, setVertexSource] = useState<VertexSource>('key');
+ const [project, setProject] = useState(VERTEX_DEFAULTS.project);
+ const [region, setRegion] = useState(VERTEX_DEFAULTS.region);
+ const [pickedFile, setPickedFile] = useState<string | null>(null);
+ const [pickError, setPickError] = useState<string | null>(null);
+ const fileInput = useRef<HTMLInputElement>(null);
const [operationId, setOperationId] = useState<string | null>(null);
const name = displayName(provider);
const give = useMutation({
mutationFn: () => {
const login: MachineLoginInput =
- kind === 'this-computer'
- ? { source: 'this-computer' }
- : { source: 'typed', kind, credential };
+ kind === 'vertex'
+ ? {
+ source: 'vertex',
+ project,
+ region,
+ credentials:
+ vertexSource === 'key'
+ ? { from: 'key', json: credential }
+ : { from: 'this-computer' },
+ }
+ : kind === 'this-computer'
+ ? { source: 'this-computer' }
+ : { source: 'typed', kind, credential };
return rpc.managedAgents.giveMachineLogin({
serverId,
machineId: machine.id,
@@ -85,6 +117,7 @@ export function GiveMachineLogin({
},
onSuccess: ({ operationId: id }) => {
setCredential('');
+ setPickedFile(null);
setOperationId(id);
},
});
@@ -110,6 +143,26 @@ export function GiveMachineLogin({
}, [succeeded, queryClient, serverId]);
const waiting =
give.isPending || (operationId !== null && (!result || result.state === 'pending'));
+ const needsCredential = kind === 'vertex' ? vertexSource === 'key' : kind !== 'this-computer';
+ const ready =
+ (!needsCredential || credential.trim() !== '') &&
+ (kind !== 'vertex' || (project.trim() !== '' && region.trim() !== ''));
+
+ const pickKey = async (file: File | undefined) => {
+ if (!file) return;
+ setPickError(null);
+ if (file.size > 16384) {
+ setPickError(`${file.name} is too large to be a service account key.`);
+ return;
+ }
+ try {
+ setCredential(await file.text());
+ setPickedFile(file.name);
+ give.reset();
+ } catch (error) {
+ setPickError(failureText(error, `Could not read ${file.name}.`));
+ }
+ };
return (
<div className="space-y-3 rounded-lg border bg-background-1 p-3 text-sm" role="group">
@@ -125,14 +178,99 @@ export function GiveMachineLogin({
onChange={(next) => {
setKind(next);
setCredential('');
+ setPickedFile(null);
+ setPickError(null);
give.reset();
}}
options={kinds}
ariaLabel={`${name} login`}
/>
)}
- <p className="text-xs text-foreground-muted">{hint(provider, kind)}</p>
- {kind !== 'this-computer' && (
+ {kind === 'vertex' && (
+ <SegmentedControl
+ value={vertexSource}
+ onChange={(next) => {
+ setVertexSource(next);
+ setCredential('');
+ setPickedFile(null);
+ setPickError(null);
+ give.reset();
+ }}
+ options={VERTEX_SOURCES}
+ ariaLabel="Google credential"
+ />
+ )}
+ <p className="text-xs text-foreground-muted">{hint(provider, kind, vertexSource)}</p>
+ {kind === 'vertex' && vertexSource === 'this-computer' && (
+ <p className="flex items-start gap-2 text-xs" role="note">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
+ This gives {machine.name} all of your Google Cloud access, and agents there run any
+ command they choose. A key for a Vertex-only service account gives it only Vertex AI.
+ </p>
+ )}
+ {kind === 'vertex' && vertexSource === 'key' && (
+ <div className="space-y-2">
+ <Textarea
+ aria-label="Service account key"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder='{"type": "service_account", …}'
+ className="max-h-32 font-mono text-xs [-webkit-text-security:disc]"
+ value={credential}
+ onChange={(event) => {
+ setCredential(event.target.value);
+ setPickedFile(null);
+ }}
+ disabled={waiting}
+ />
+ <div className="flex items-center gap-2">
+ <input
+ ref={fileInput}
+ type="file"
+ accept=".json,application/json"
+ className="hidden"
+ aria-label="Service account key file"
+ onChange={(event) => {
+ void pickKey(event.target.files?.[0]);
+ event.target.value = '';
+ }}
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={waiting}
+ onClick={() => fileInput.current?.click()}
+ >
+ <Upload className="mr-1.5 size-3.5" />
+ Pick a file…
+ </Button>
+ {pickedFile && <span className="text-xs text-foreground-muted">Read {pickedFile}</span>}
+ </div>
+ </div>
+ )}
+ {kind === 'vertex' && (
+ <div className="flex gap-2">
+ <label className="flex-1 space-y-1 text-xs text-foreground-muted">
+ <span>Google Cloud project</span>
+ <Input
+ aria-label="Google Cloud project"
+ value={project}
+ onChange={(event) => setProject(event.target.value)}
+ disabled={waiting}
+ />
+ </label>
+ <label className="w-32 space-y-1 text-xs text-foreground-muted">
+ <span>Region</span>
+ <Input
+ aria-label="Region"
+ value={region}
+ onChange={(event) => setRegion(event.target.value)}
+ disabled={waiting}
+ />
+ </label>
+ </div>
+ )}
+ {kind !== 'this-computer' && kind !== 'vertex' && (
<Input
type="password"
autoComplete="off"
@@ -154,14 +292,15 @@ export function GiveMachineLogin({
{name} signs in on {machine.name}.
</p>
)}
- {(give.error || result?.state === 'failed') && (
+ {(pickError || give.error || result?.state === 'failed') && (
<p className="flex items-start gap-2 text-xs" role="alert">
<CircleAlert className="mt-0.5 size-3.5 shrink-0 text-amber-500" />
- {give.error
- ? String(give.error instanceof Error ? give.error.message : give.error)
- : result?.state === 'failed'
- ? result.message
- : null}
+ {pickError ??
+ (give.error
+ ? String(give.error instanceof Error ? give.error.message : give.error)
+ : result?.state === 'failed'
+ ? result.message
+ : null)}
</p>
)}
<div className="flex justify-end gap-2">
@@ -171,7 +310,7 @@ export function GiveMachineLogin({
{result?.state !== 'succeeded' && (
<Button
size="sm"
- disabled={waiting || (kind !== 'this-computer' && !credential.trim())}
+ disabled={waiting || !ready}
onClick={() => {
setOperationId(null);
give.mutate();
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx
new file mode 100644
index 000000000..04755e352
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx
@@ -0,0 +1,235 @@
+/**
+ * Giving a machine a Claude login through Google Vertex AI: a service account
+ * key, pasted or picked, which the form recommends, or this computer's own
+ * Google sign-in, which it warns gives the machine all of the user's Google
+ * Cloud access.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const giveMachineLogin = vi.hoisted(() => vi.fn());
+const machineLoginOutcome = vi.hoisted(() => vi.fn());
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: { managedAgents: { giveMachineLogin, machineLoginOutcome } },
+ events: { on: () => () => {}, emit: () => {} },
+}));
+
+import {
+ GiveMachineLogin,
+ loginKindsFor,
+} from '@renderer/features/locations/components/add-agent-modal/give-machine-login';
+import type { OwnedMachine } from '@shared/core/managed-agents/managed-agents';
+import '@renderer/index.css';
+
+const KEY = JSON.stringify({
+ type: 'service_account',
+ client_email: '[email protected]',
+});
+
+const MACHINE: OwnedMachine = {
+ id: 'controller-1',
+ name: 'cloud-box',
+ kind: 'ec2',
+ state: 'online',
+ providers: [],
+ acceptsLogins: true,
+ cloud: true,
+ workspacesDir: null,
+ local: null,
+};
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ giveMachineLogin.mockReset().mockResolvedValue({ operationId: 'op-1' });
+ machineLoginOutcome.mockReset().mockResolvedValue({ state: 'succeeded' });
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(): Promise<HTMLElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <GiveMachineLogin
+ serverId="server-1"
+ machine={MACHINE}
+ provider="claude"
+ onClose={() => {}}
+ />
+ </QueryClientProvider>
+ )
+ );
+ await settle();
+ return container;
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());
+}
+
+function byLabel<T extends HTMLElement>(el: HTMLElement, label: string): T {
+ const found = el.querySelector<T>(`[aria-label="${label}"]`);
+ expect(found, `nothing labelled ${label}`).not.toBeNull();
+ return found!;
+}
+
+function button(el: HTMLElement, text: string): HTMLButtonElement {
+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find(
+ (b) => b.textContent?.trim() === text
+ );
+ expect(found, `no ${text} button`).toBeDefined();
+ return found!;
+}
+
+async function click(element: HTMLElement): Promise<void> {
+ await act(async () => element.click());
+ await settle();
+}
+
+/** Types into a React-controlled field: sets the value as the browser would, then fires input. */
+async function type(field: HTMLInputElement | HTMLTextAreaElement, value: string): Promise<void> {
+ const prototype =
+ field instanceof HTMLTextAreaElement
+ ? HTMLTextAreaElement.prototype
+ : HTMLInputElement.prototype;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(field, value);
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+async function chooseVertex(el: HTMLElement): Promise<void> {
+ await click(byLabel(el, 'Vertex AI'));
+}
+
+describe('giving a machine a Claude login through Vertex AI', () => {
+ it('offers Vertex AI as a third Claude login', () => {
+ expect(loginKindsFor('claude').map((kind) => kind.label)).toEqual([
+ 'Setup token',
+ 'API key',
+ 'Vertex AI',
+ ]);
+ expect(loginKindsFor('codex').map((kind) => kind.value)).not.toContain('vertex');
+ });
+
+ it('recommends a service account key, and sends a pasted one with the project and region', async () => {
+ const el = await render();
+ await chooseVertex(el);
+
+ expect(byLabel(el, 'Service account key (recommended)').getAttribute('aria-pressed')).toBe(
+ 'true'
+ );
+ expect(el.textContent).toContain('roles/aiplatform.user');
+ expect(el.textContent).not.toContain('all of your Google Cloud access');
+ expect(byLabel<HTMLInputElement>(el, 'Google Cloud project').value).toBe('cg-vertexai');
+ expect(byLabel<HTMLInputElement>(el, 'Region').value).toBe('global');
+ expect(button(el, 'Give login').disabled).toBe(true);
+
+ await type(byLabel<HTMLTextAreaElement>(el, 'Service account key'), KEY);
+ await type(byLabel<HTMLInputElement>(el, 'Region'), 'us-east5');
+ await click(button(el, 'Give login'));
+
+ expect(giveMachineLogin).toHaveBeenCalledWith({
+ serverId: 'server-1',
+ machineId: 'controller-1',
+ provider: 'claude',
+ login: {
+ source: 'vertex',
+ project: 'cg-vertexai',
+ region: 'us-east5',
+ credentials: { from: 'key', json: KEY },
+ },
+ });
+ expect(el.textContent).toContain('Claude Code signs in on cloud-box.');
+ });
+
+ it('reads a picked key file', async () => {
+ const el = await render();
+ await chooseVertex(el);
+
+ const input = byLabel<HTMLInputElement>(el, 'Service account key file');
+ const files = new DataTransfer();
+ files.items.add(new File([KEY], 'vertex-sa.json', { type: 'application/json' }));
+ await act(async () => {
+ input.files = files.files;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await vi.waitFor(async () => {
+ await settle();
+ expect(byLabel<HTMLTextAreaElement>(el, 'Service account key').value).toBe(KEY);
+ });
+ expect(el.textContent).toContain('Read vertex-sa.json');
+ await click(button(el, 'Give login'));
+ expect(giveMachineLogin.mock.calls[0]![0].login.credentials).toEqual({
+ from: 'key',
+ json: KEY,
+ });
+ });
+
+ it("warns that this computer's Google sign-in gives all of the user's access, and sends it", async () => {
+ const el = await render();
+ await chooseVertex(el);
+ await click(byLabel(el, "This computer's Google sign-in"));
+
+ expect(el.querySelector('[role="note"]')?.textContent).toContain(
+ 'This gives cloud-box all of your Google Cloud access'
+ );
+ expect(el.querySelector('[aria-label="Service account key"]')).toBeNull();
+ expect(button(el, 'Give login').disabled).toBe(false);
+
+ await click(button(el, 'Give login'));
+ expect(giveMachineLogin.mock.calls[0]![0].login).toEqual({
+ source: 'vertex',
+ project: 'cg-vertexai',
+ region: 'global',
+ credentials: { from: 'this-computer' },
+ });
+ });
+
+ it('shows why this computer has no Google sign-in to give', async () => {
+ giveMachineLogin.mockRejectedValue(
+ new Error(
+ 'This computer has no Google sign-in. Run `gcloud auth application-default login` on this computer first.'
+ )
+ );
+ const el = await render();
+ await chooseVertex(el);
+ await click(byLabel(el, "This computer's Google sign-in"));
+ await click(button(el, 'Give login'));
+
+ expect(el.querySelector('[role="alert"]')?.textContent).toContain(
+ 'Run `gcloud auth application-default login` on this computer first.'
+ );
+ expect(machineLoginOutcome).not.toHaveBeenCalled();
+ });
+
+ it('needs a project and a region', async () => {
+ const el = await render();
+ await chooseVertex(el);
+ await click(byLabel(el, "This computer's Google sign-in"));
+ await type(byLabel<HTMLInputElement>(el, 'Google Cloud project'), ' ');
+ expect(button(el, 'Give login').disabled).toBe(true);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
index c689ef301..e80e8b859 100644
--- a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
@@ -69,12 +69,20 @@ export type MachineProvider = {
};
/**
- * A provider login to give a machine: a key or token typed in, or this
- * computer's own sign-in for the provider, read from its file.
+ * A provider login to give a machine: a key or token typed in, this
+ * computer's own sign-in for the provider, read from its file, or (Claude
+ * only) Google Vertex AI, with a service account key pasted or picked, or this
+ * computer's Google application-default sign-in.
*/
export type MachineLoginInput =
| { source: 'typed'; kind: 'api-key' | 'setup-token'; credential: string }
- | { source: 'this-computer' };
+ | { source: 'this-computer' }
+ | {
+ source: 'vertex';
+ project: string;
+ region: string;
+ credentials: { from: 'key'; json: string } | { from: 'this-computer' };
+ };
/** How giving a machine a login went: still being taken up, taken up, or why not. */
export type MachineLoginOutcome =
diff --git a/console/packages/agent-controller/README.md b/console/packages/agent-controller/README.md
index 597441ebb..5fd7e6514 100644
--- a/console/packages/agent-controller/README.md
+++ b/console/packages/agent-controller/README.md
@@ -274,6 +274,16 @@ when there is none. From then on the provider is reported ready with
Antigravity) is written by the agent host in its own state. The agent runs in
a process of its own, as a separate user under `--separate-users`, and is
restarted when the login changes or is withdrawn.
+- Claude can also be given a Vertex AI login: a Google Cloud project, a region,
+ and a Google credential, either a service account key (recommended: one for a
+ service account that can use only Vertex AI, `roles/aiplatform.user`) or the
+ owner's own `gcloud auth application-default login` sign-in, which carries
+ all of their Google Cloud access. The agent host writes the credential to
+ `provider-home/google-credentials.json` in its own state (mode 0600), and the
+ agent's environment gets `CLAUDE_CODE_USE_VERTEX=1`,
+ `ANTHROPIC_VERTEX_PROJECT_ID`, `CLOUD_ML_REGION` and
+ `GOOGLE_APPLICATION_CREDENTIALS` pointing at that file, with
+ `ANTHROPIC_API_KEY` and `CLAUDE_CODE_OAUTH_TOKEN` blanked.
- Logins are kept in memory only, and fetched again every ten minutes and on
each `provider.login` and `provider.recheck`. When Switch cannot be reached,
the login already held is kept.
diff --git a/console/packages/agent-controller/src/runtime.test.ts b/console/packages/agent-controller/src/runtime.test.ts
index f5a935650..c86a65c8a 100644
--- a/console/packages/agent-controller/src/runtime.test.ts
+++ b/console/packages/agent-controller/src/runtime.test.ts
@@ -13,10 +13,14 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { type OpenAgentStream, readSharedCredentials } from '@switch-console/agent-providers';
+import {
+ SERVICE_ACCOUNT_KEY_FIXTURE,
+ vertexCredentialFixture,
+} from '@switch-console/agent-providers/testing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { silentLogger } from './log';
import { dataLayout } from './paths';
-import { InProcessRuntime, isInside, observeOnDisk } from './runtime';
+import { InProcessRuntime, isInside, loginProbeEnvironment, observeOnDisk } from './runtime';
import { buildWatcherTemplate } from './template';
/** Stands in for the shared-host bundle: answers `--probe`. Sessions are never started here. */
@@ -264,6 +268,30 @@ describe('InProcessRuntime', () => {
});
});
+ it('probes a Vertex AI login with its Google credential written in a directory of its own', async () => {
+ const checkDir = join(dir, 'login-check', 'claude');
+ const env = await loginProbeEnvironment(
+ checkDir,
+ {
+ status: 'connected',
+ provider: 'claude',
+ revision: '1',
+ kind: 'vertex',
+ credential: vertexCredentialFixture(),
+ },
+ '/usr/bin/claude'
+ );
+ const path = join(checkDir, 'provider-home', 'google-credentials.json');
+ expect(env).toEqual({
+ CLAUDE_CODE_USE_VERTEX: '1',
+ ANTHROPIC_VERTEX_PROJECT_ID: 'cg-vertexai',
+ CLOUD_ML_REGION: 'global',
+ GOOGLE_APPLICATION_CREDENTIALS: path,
+ });
+ expect(statSync(path).mode & 0o777).toBe(0o600);
+ expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(SERVICE_ACCOUNT_KEY_FIXTURE);
+ });
+
it('resolves working directories', async () => {
expect(await runtime.workingDirectory('agent-1', 'scout', null)).toBe(
join(dir, 'data', 'workspaces', 'scout')
diff --git a/console/packages/agent-controller/src/sealed-logins.ts b/console/packages/agent-controller/src/sealed-logins.ts
index ced6e911c..3f39dc32e 100644
--- a/console/packages/agent-controller/src/sealed-logins.ts
+++ b/console/packages/agent-controller/src/sealed-logins.ts
@@ -1,6 +1,7 @@
import {
generateSealingKeyPair,
type HostedCredential,
+ hostedCredentialSchema,
openProviderLogin,
type SealingKeyPair,
} from '@switch-console/agent-providers';
@@ -105,15 +106,18 @@ export class SealedLogins {
provider,
sealed: answer.sealed,
});
- return {
- login: {
- status: 'connected',
- provider,
- revision: String(answer.revision),
- kind: opened.kind,
- credential: opened.credential,
- },
- };
+ const login = hostedCredentialSchema.safeParse({
+ status: 'connected',
+ provider,
+ revision: String(answer.revision),
+ kind: opened.kind,
+ credential: opened.credential,
+ });
+ if (!login.success || login.data.status !== 'connected')
+ throw new Error(
+ `The ${provider} login given to this machine cannot be used: ${login.error?.issues[0]?.message ?? 'it is not a connected login'}`
+ );
+ return { login: login.data };
} catch (error) {
return { problem: { code: 'internal', message: errorMessage(error) } };
}
diff --git a/console/packages/agent-controller/src/status.test.ts b/console/packages/agent-controller/src/status.test.ts
index 22a12eb51..9d438eea0 100644
--- a/console/packages/agent-controller/src/status.test.ts
+++ b/console/packages/agent-controller/src/status.test.ts
@@ -2,6 +2,7 @@ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { generateSealingKeyPair, sealProviderLogin } from '@switch-console/agent-providers';
+import { vertexCredentialFixture } from '@switch-console/agent-providers/testing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { silentLogger } from './log';
import { type AgentObservation, emptyObservation } from './runtime';
@@ -264,15 +265,20 @@ describe('ProviderStatuses with logins given to the machine', () => {
let answer: SealedLoginResponse | null;
let reachable: boolean;
- function sealedAnswer(credential: string, revision = 1): SealedLoginResponse {
+ function sealedAnswer(
+ credential: string,
+ revision = 1,
+ kind: 'setup-token' | 'vertex' = 'setup-token',
+ provider: 'claude' | 'codex' = 'claude'
+ ): SealedLoginResponse {
return {
- provider: 'claude',
+ provider,
revision,
sealed: sealProviderLogin({
publicKey: keys.publicKey,
controllerId: 'controller-1',
- provider: 'claude',
- login: { kind: 'setup-token', credential },
+ provider,
+ login: { kind, credential },
}),
};
}
@@ -328,6 +334,35 @@ describe('ProviderStatuses with logins given to the machine', () => {
expect(runtime.loginProbes.map((login) => login.credential)).toEqual(['sk-ant-oat-given']);
});
+ it('uses a given Vertex AI login once Claude signs in with it', async () => {
+ const runtime = new FakeRuntime();
+ runtime.readiness = { status: 'unauthenticated', message: 'Not signed in.', models: [] };
+ answer = sealedAnswer(vertexCredentialFixture(), 4, 'vertex');
+ const statuses = build(runtime);
+ expect(await statuses.check('claude')).toMatchObject({ auth: 'ok', auth_source: 'sealed' });
+ expect(await statuses.givenLogin('claude')).toEqual({
+ status: 'connected',
+ provider: 'claude',
+ revision: '4',
+ kind: 'vertex',
+ credential: vertexCredentialFixture(),
+ });
+ expect(runtime.loginProbes.map((login) => login.kind)).toEqual(['vertex']);
+ });
+
+ it('refuses a Vertex AI login given for another provider than Claude', async () => {
+ const runtime = new FakeRuntime();
+ runtime.readiness = { status: 'unauthenticated', message: '', models: [] };
+ answer = sealedAnswer(vertexCredentialFixture(), 1, 'vertex', 'codex');
+ const statuses = build(runtime);
+ expect(await statuses.check('codex')).toMatchObject({ auth: 'missing' });
+ expect(statuses.loginProblem('codex')).toEqual({
+ code: 'internal',
+ message: expect.stringContaining('Only Claude signs in through Vertex AI.'),
+ });
+ expect(runtime.loginProbes).toEqual([]);
+ });
+
it('says why a given login is not used', async () => {
const runtime = new FakeRuntime();
runtime.readiness = { status: 'unauthenticated', message: '', models: [] };
diff --git a/console/packages/agent-providers/src/host/hosted-provider.test.ts b/console/packages/agent-providers/src/host/hosted-provider.test.ts
index b5f045185..ad85dff52 100644
--- a/console/packages/agent-providers/src/host/hosted-provider.test.ts
+++ b/console/packages/agent-providers/src/host/hosted-provider.test.ts
@@ -1,8 +1,13 @@
-import { mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';
+import { mkdtemp, readdir, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { prepareCodexSessionHome } from '../codex/home';
+import {
+ AUTHORIZED_USER_FIXTURE,
+ SERVICE_ACCOUNT_KEY_FIXTURE,
+ vertexCredentialFixture,
+} from '../testing/vertex-fixtures';
import { materializeHostedProvider, type HostedCredential } from './hosted-provider';
let root: string;
@@ -107,3 +112,66 @@ it('keeps the prepared Codex home and refreshes its auth before provider startup
expect(await readFile(join(home, 'auth.json'), 'utf8')).toContain('replacement');
expect(await readFile(join(home, 'config.toml'), 'utf8')).toContain('fixture-model');
});
+
+const vertex = (credentials: object): Extract<HostedCredential, { status: 'connected' }> => ({
+ ...credential(vertexCredentialFixture(credentials)),
+ provider: 'claude',
+ kind: 'vertex',
+});
+
+it('writes a Vertex AI login’s Google credential under the root, and signs Claude in with it', async () => {
+ const env: Record<string, string> = {
+ ANTHROPIC_API_KEY: 'sk-ant-inherited',
+ CLAUDE_CODE_OAUTH_TOKEN: 'sk-ant-oat-inherited',
+ };
+ await materializeHostedProvider(root, env, vertex(SERVICE_ACCOUNT_KEY_FIXTURE), 'fixture-cli');
+ const path = join(root, 'provider-home', 'google-credentials.json');
+ expect(env).toEqual({
+ CLAUDE_CODE_USE_VERTEX: '1',
+ ANTHROPIC_VERTEX_PROJECT_ID: 'cg-vertexai',
+ CLOUD_ML_REGION: 'global',
+ GOOGLE_APPLICATION_CREDENTIALS: path,
+ });
+ expect((await stat(path)).mode & 0o777).toBe(0o600);
+ expect((await stat(join(root, 'provider-home'))).mode & 0o777).toBe(0o700);
+ expect(JSON.parse(await readFile(path, 'utf8'))).toEqual(SERVICE_ACCOUNT_KEY_FIXTURE);
+
+ await materializeHostedProvider(root, env, vertex(AUTHORIZED_USER_FIXTURE), 'fixture-cli');
+ expect(JSON.parse(await readFile(path, 'utf8'))).toEqual(AUTHORIZED_USER_FIXTURE);
+ expect((await readdir(join(root, 'provider-home'))).sort()).toEqual([
+ 'google-credentials.json',
+ 'google-credentials.json.switch-credential',
+ ]);
+});
+
+it('clears the Vertex AI variables when Claude is given another login', async () => {
+ const env: Record<string, string> = {};
+ await materializeHostedProvider(root, env, vertex(SERVICE_ACCOUNT_KEY_FIXTURE), 'fixture-cli');
+ await materializeHostedProvider(
+ root,
+ env,
+ { ...credential('sk-ant-oat-given'), provider: 'claude', kind: 'setup-token' },
+ 'fixture-cli'
+ );
+ expect(env).toEqual({ CLAUDE_CODE_OAUTH_TOKEN: 'sk-ant-oat-given' });
+});
+
+it('refuses a Vertex AI login for another provider than Claude, or one that is not valid', async () => {
+ await expect(
+ materializeHostedProvider(
+ root,
+ {},
+ { ...vertex(SERVICE_ACCOUNT_KEY_FIXTURE), provider: 'codex' },
+ 'fixture-cli'
+ )
+ ).rejects.toThrow(/Only Claude/);
+ await expect(
+ materializeHostedProvider(
+ root,
+ {},
+ vertex({ ...SERVICE_ACCOUNT_KEY_FIXTURE, type: 'external_account' }),
+ 'fixture-cli'
+ )
+ ).rejects.toThrow(/Only a service account key/);
+ await expect(stat(join(root, 'provider-home'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
diff --git a/console/packages/agent-providers/src/host/hosted-provider.ts b/console/packages/agent-providers/src/host/hosted-provider.ts
index 1315e52d7..0d98d00e8 100644
--- a/console/packages/agent-providers/src/host/hosted-provider.ts
+++ b/console/packages/agent-providers/src/host/hosted-provider.ts
@@ -3,14 +3,28 @@ import { constants } from 'node:fs';
import { lstat, mkdir, open, readFile, rename } from 'node:fs/promises';
import { join } from 'node:path';
import { refreshCodexAuthentication } from '../codex/home';
+import { parseVertexLogin, VERTEX_CREDENTIALS_FILE } from '../vertex-login';
import { importOpenCodeConsole } from './opencode-console';
import type { HostedCredential } from './provider-login';
export type { HostedCredential } from './provider-login';
+const VERTEX_VARIABLES = [
+ 'CLAUDE_CODE_USE_VERTEX',
+ 'ANTHROPIC_VERTEX_PROJECT_ID',
+ 'CLOUD_ML_REGION',
+ 'GOOGLE_APPLICATION_CREDENTIALS',
+];
+
+/**
+ * Sets the variables `credential` signs in with in `env`, removing the others
+ * a provider could sign in with. For a `vertex` login, `root` is where its
+ * Google credential is written (`materializeHostedProvider`).
+ */
export function applyHostedProvider(
env: Record<string, string>,
- credential: HostedCredential
+ credential: HostedCredential,
+ root: string
): void {
for (const key of [
'ANTHROPIC_API_KEY',
@@ -23,6 +37,17 @@ export function applyHostedProvider(
throw new Error(
'The provider was disconnected. Reconnect it in Console before resuming this session.'
);
+ if (credential.provider === 'claude') for (const key of VERTEX_VARIABLES) delete env[key];
+ if (credential.kind === 'vertex') {
+ if (credential.provider !== 'claude')
+ throw new Error('Only Claude signs in through Vertex AI.');
+ const login = parseVertexLogin(credential.credential);
+ env.CLAUDE_CODE_USE_VERTEX = '1';
+ env.ANTHROPIC_VERTEX_PROJECT_ID = login.project;
+ env.CLOUD_ML_REGION = login.region;
+ env.GOOGLE_APPLICATION_CREDENTIALS = join(root, VERTEX_CREDENTIALS_FILE);
+ return;
+ }
if (credential.kind === 'auth-json') return;
if (!/^[\x21-\x7e]+$/.test(credential.credential))
throw new Error('Provider credential format is invalid.');
@@ -88,8 +113,16 @@ export async function materializeHostedProvider(
credential: HostedCredential,
binaryPath: string
): Promise<void> {
- applyHostedProvider(env, credential);
+ applyHostedProvider(env, credential, root);
if (credential.status !== 'connected') return;
+ if (credential.kind === 'vertex') {
+ await writeAuthentication(
+ root,
+ VERTEX_CREDENTIALS_FILE,
+ JSON.stringify(parseVertexLogin(credential.credential).credentials)
+ );
+ return;
+ }
if (credential.kind === 'auth-json') {
try {
const value = JSON.parse(credential.credential);
diff --git a/console/packages/agent-providers/src/host/provider-login.test.ts b/console/packages/agent-providers/src/host/provider-login.test.ts
index fdb31366b..46d1eaa6c 100644
--- a/console/packages/agent-providers/src/host/provider-login.test.ts
+++ b/console/packages/agent-providers/src/host/provider-login.test.ts
@@ -2,7 +2,8 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { providerLoginEnvironment } from './provider-login';
+import { SERVICE_ACCOUNT_KEY_FIXTURE, vertexCredentialFixture } from '../testing/vertex-fixtures';
+import { hostedCredentialSchema, providerLoginEnvironment } from './provider-login';
import { readProviderLogin, type SharedHostConfig } from './shared-config';
const login = {
@@ -44,9 +45,13 @@ describe('provider logins handed to an agent host', () => {
it('gives sessions the token, or the directory the login file is written in', () => {
expect(providerLoginEnvironment('/root', login)).toEqual({
CLAUDE_CODE_OAUTH_TOKEN: 'sk-ant-oat-given',
+ ANTHROPIC_API_KEY: '',
+ CLAUDE_CODE_USE_VERTEX: '',
});
expect(providerLoginEnvironment('/root', { ...login, kind: 'api-key' })).toEqual({
ANTHROPIC_API_KEY: 'sk-ant-oat-given',
+ CLAUDE_CODE_OAUTH_TOKEN: '',
+ CLAUDE_CODE_USE_VERTEX: '',
});
expect(
providerLoginEnvironment('/root', { ...login, provider: 'codex', kind: 'auth-json' })
@@ -55,4 +60,39 @@ describe('provider logins handed to an agent host', () => {
providerLoginEnvironment('/root', { ...login, provider: 'opencode', kind: 'auth-json' })
).toEqual({ XDG_DATA_HOME: '/root/provider-data' });
});
+
+ it('signs Claude in through Vertex AI with the credential file under the root', () => {
+ const vertex = { ...login, kind: 'vertex' as const, credential: vertexCredentialFixture() };
+ expect(providerLoginEnvironment('/root', vertex)).toEqual({
+ CLAUDE_CODE_USE_VERTEX: '1',
+ ANTHROPIC_VERTEX_PROJECT_ID: 'cg-vertexai',
+ CLOUD_ML_REGION: 'global',
+ GOOGLE_APPLICATION_CREDENTIALS: '/root/provider-home/google-credentials.json',
+ ANTHROPIC_API_KEY: '',
+ CLAUDE_CODE_OAUTH_TOKEN: '',
+ });
+ expect(() => providerLoginEnvironment('/root', { ...vertex, provider: 'codex' })).toThrow(
+ /Only Claude/
+ );
+ expect(() => providerLoginEnvironment('/root', { ...vertex, credential: '{}' })).toThrow(
+ /Vertex AI login/
+ );
+ });
+
+ it('takes a Vertex AI login handed over only for Claude, and only a valid one', () => {
+ const vertex = { ...login, kind: 'vertex' as const, credential: vertexCredentialFixture() };
+ expect(hostedCredentialSchema.parse(vertex)).toEqual(vertex);
+ expect(hostedCredentialSchema.safeParse({ ...vertex, provider: 'antigravity' }).success).toBe(
+ false
+ );
+ expect(
+ hostedCredentialSchema.safeParse({
+ ...vertex,
+ credential: vertexCredentialFixture({
+ ...SERVICE_ACCOUNT_KEY_FIXTURE,
+ type: 'external_account',
+ }),
+ }).success
+ ).toBe(false);
+ });
});
diff --git a/console/packages/agent-providers/src/host/provider-login.ts b/console/packages/agent-providers/src/host/provider-login.ts
index 42df97ca2..12bc7815a 100644
--- a/console/packages/agent-providers/src/host/provider-login.ts
+++ b/console/packages/agent-providers/src/host/provider-login.ts
@@ -1,23 +1,36 @@
import { join } from 'node:path';
import { z } from 'zod';
+import { refineVertexCredential } from '../sealed-login';
+import { parseVertexLogin, VERTEX_CREDENTIALS_FILE } from '../vertex-login';
/** A provider login Switch holds for an agent, as an agent host applies it (`materializeHostedProvider`). */
export const hostedCredentialSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('revoked') }),
- z.object({
- status: z.literal('connected'),
- revision: z.string(),
- provider: z.enum(['claude', 'codex', 'cursor', 'opencode', 'antigravity']),
- kind: z.enum(['api-key', 'setup-token', 'auth-json']),
- credential: z.string().min(1).max(16384),
- }),
+ z
+ .object({
+ status: z.literal('connected'),
+ revision: z.string(),
+ provider: z.enum(['claude', 'codex', 'cursor', 'opencode', 'antigravity']),
+ kind: z.enum(['api-key', 'setup-token', 'auth-json', 'vertex']),
+ credential: z.string().min(1).max(16384),
+ })
+ .superRefine((login, context) => {
+ if (login.kind === 'vertex' && login.provider !== 'claude')
+ context.addIssue({
+ code: 'custom',
+ path: ['kind'],
+ message: 'Only Claude signs in through Vertex AI.',
+ });
+ refineVertexCredential(login, context);
+ }),
]);
export type HostedCredential = z.infer<typeof hostedCredentialSchema>;
/**
* The environment the sessions of an agent host rooted at `root` run with to
* use `credential`: the provider's token variable, or the directory
- * `materializeHostedProvider` writes its login file into under `root`. What
+ * `materializeHostedProvider` writes its login file into under `root`, or for
+ * Claude on Vertex AI the project, the region and that file. What
* an agents controller puts in the agent's configuration, so the sessions
* get it whatever environment they would otherwise inherit.
*/
@@ -25,11 +38,31 @@ export function providerLoginEnvironment(
root: string,
credential: Extract<HostedCredential, { status: 'connected' }>
): Record<string, string> {
+ if (credential.kind === 'vertex' && credential.provider !== 'claude')
+ throw new Error('Only Claude signs in through Vertex AI.');
switch (credential.provider) {
- case 'claude':
- return credential.kind === 'api-key'
- ? { ANTHROPIC_API_KEY: credential.credential }
- : { CLAUDE_CODE_OAUTH_TOKEN: credential.credential };
+ case 'claude': {
+ // Blank is unset to Claude Code: a variable the sessions inherit for
+ // another way of signing in would otherwise be used instead of this one.
+ const cleared = { ANTHROPIC_API_KEY: '', CLAUDE_CODE_OAUTH_TOKEN: '' };
+ if (credential.kind === 'vertex') {
+ const login = parseVertexLogin(credential.credential);
+ return {
+ ...cleared,
+ CLAUDE_CODE_USE_VERTEX: '1',
+ ANTHROPIC_VERTEX_PROJECT_ID: login.project,
+ CLOUD_ML_REGION: login.region,
+ GOOGLE_APPLICATION_CREDENTIALS: join(root, VERTEX_CREDENTIALS_FILE),
+ };
+ }
+ return {
+ ...cleared,
+ CLAUDE_CODE_USE_VERTEX: '',
+ ...(credential.kind === 'api-key'
+ ? { ANTHROPIC_API_KEY: credential.credential }
+ : { CLAUDE_CODE_OAUTH_TOKEN: credential.credential }),
+ };
+ }
case 'cursor':
return { CURSOR_API_KEY: credential.credential };
case 'codex':
diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.ts
index 4f94d01d8..eb9a620c5 100644
--- a/console/packages/agent-providers/src/index.ts
+++ b/console/packages/agent-providers/src/index.ts
@@ -109,6 +109,16 @@ export {
sealProviderLogin,
type SealingKeyPair,
} from './sealed-login';
+export {
+ type GoogleCredentials,
+ googleCredentialsSchema,
+ parseGoogleCredentials,
+ parseVertexLogin,
+ VERTEX_CREDENTIALS_FILE,
+ type VertexLogin,
+ vertexLoginCredential,
+ vertexLoginSchema,
+} from './vertex-login';
export {
SessionHostFailedError,
SessionLinks,
diff --git a/console/packages/agent-providers/src/sealed-login.ts b/console/packages/agent-providers/src/sealed-login.ts
index 6d41936fb..85263cf55 100644
--- a/console/packages/agent-providers/src/sealed-login.ts
+++ b/console/packages/agent-providers/src/sealed-login.ts
@@ -11,6 +11,7 @@ import {
randomBytes,
} from 'node:crypto';
import { z } from 'zod';
+import { parseVertexLogin } from './vertex-login';
/**
* Provider logins sealed to an agents controller's own key, so Switch stores
@@ -41,11 +42,16 @@ export const sealedLoginSchema = z.strictObject({
});
export type SealedLogin = z.infer<typeof sealedLoginSchema>;
-/** What is sealed: a login as Switch's provider connections hold one. */
-export const providerLoginSchema = z.strictObject({
- kind: z.enum(['api-key', 'setup-token', 'auth-json']),
- credential: z.string().min(1).max(16384),
-});
+/**
+ * What is sealed: a login as Switch's provider connections hold one. A
+ * `vertex` login (Claude only) holds a `VertexLogin` as JSON.
+ */
+export const providerLoginSchema = z
+ .strictObject({
+ kind: z.enum(['api-key', 'setup-token', 'auth-json', 'vertex']),
+ credential: z.string().min(1).max(16384),
+ })
+ .superRefine(refineVertexCredential);
export type ProviderLogin = z.infer<typeof providerLoginSchema>;
/** A controller's keypair, each half the raw 32 bytes in base64. */
@@ -136,6 +142,23 @@ export function openProviderLogin(input: {
return providerLoginSchema.parse(JSON.parse(plaintext.toString('utf8')));
}
+/** Adds why a `vertex` login's credential is not one, as an issue on `credential`. */
+export function refineVertexCredential(
+ login: { kind: string; credential: string },
+ context: z.core.$RefinementCtx
+): void {
+ if (login.kind !== 'vertex') return;
+ try {
+ parseVertexLogin(login.credential);
+ } catch (error) {
+ context.addIssue({
+ code: 'custom',
+ path: ['credential'],
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
function aad(controllerId: string, provider: string): Buffer {
return Buffer.from(`switch-provider-login-v1\n${controllerId}\n${provider}`);
}
diff --git a/console/packages/agent-providers/src/testing/index.ts b/console/packages/agent-providers/src/testing/index.ts
index dcaeb2309..91e829b17 100644
--- a/console/packages/agent-providers/src/testing/index.ts
+++ b/console/packages/agent-providers/src/testing/index.ts
@@ -2,3 +2,8 @@ export { EventRecorder } from './event-recorder';
export type { ConformanceOptions, ConformanceScenario } from './conformance';
export { conformanceScenarios, describeConformance } from './conformance';
export { echoMcpServerSpec } from './fixtures/index';
+export {
+ AUTHORIZED_USER_FIXTURE,
+ SERVICE_ACCOUNT_KEY_FIXTURE,
+ vertexCredentialFixture,
+} from './vertex-fixtures';
diff --git a/console/packages/agent-providers/src/testing/vertex-fixtures.ts b/console/packages/agent-providers/src/testing/vertex-fixtures.ts
new file mode 100644
index 000000000..73e986a67
--- /dev/null
+++ b/console/packages/agent-providers/src/testing/vertex-fixtures.ts
@@ -0,0 +1,25 @@
+/** Google credentials shaped as real ones are, holding nothing that signs in. */
+export const SERVICE_ACCOUNT_KEY_FIXTURE = {
+ type: 'service_account',
+ project_id: 'cg-vertexai',
+ private_key_id: 'fixture-key-id',
+ private_key: '-----BEGIN PRIVATE KEY-----\nfixture\n-----END PRIVATE KEY-----\n',
+ client_email: '[email protected]',
+ client_id: '1234567890',
+ token_uri: 'https://oauth2.googleapis.com/token',
+ universe_domain: 'googleapis.com',
+} as const;
+
+export const AUTHORIZED_USER_FIXTURE = {
+ type: 'authorized_user',
+ client_id: 'fixture.apps.googleusercontent.com',
+ client_secret: 'fixture-secret',
+ refresh_token: 'fixture-refresh',
+ account: '',
+ universe_domain: 'googleapis.com',
+} as const;
+
+/** A `vertex` login's credential for project `cg-vertexai` in `global`. */
+export function vertexCredentialFixture(credentials: object = SERVICE_ACCOUNT_KEY_FIXTURE): string {
+ return JSON.stringify({ v: 1, project: 'cg-vertexai', region: 'global', credentials });
+}
diff --git a/console/packages/agent-providers/src/vertex-login.test.ts b/console/packages/agent-providers/src/vertex-login.test.ts
new file mode 100644
index 000000000..336f2126b
--- /dev/null
+++ b/console/packages/agent-providers/src/vertex-login.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+import {
+ generateSealingKeyPair,
+ openProviderLogin,
+ providerLoginSchema,
+ sealProviderLogin,
+} from './sealed-login';
+import { AUTHORIZED_USER_FIXTURE, SERVICE_ACCOUNT_KEY_FIXTURE } from './testing/vertex-fixtures';
+import {
+ parseGoogleCredentials,
+ parseVertexLogin,
+ vertexLoginCredential,
+ type GoogleCredentials,
+} from './vertex-login';
+
+const SERVICE_ACCOUNT_KEY = SERVICE_ACCOUNT_KEY_FIXTURE;
+const AUTHORIZED_USER = AUTHORIZED_USER_FIXTURE;
+
+function credential(credentials: unknown, project = 'cg-vertexai', region = 'global'): string {
+ return vertexLoginCredential({ project, region, credentials: credentials as GoogleCredentials });
+}
+
+describe('Vertex AI logins', () => {
+ it('takes a service account key or a user sign-in, keeping their other fields', () => {
+ for (const credentials of [SERVICE_ACCOUNT_KEY, AUTHORIZED_USER]) {
+ expect(parseVertexLogin(credential(credentials))).toEqual({
+ v: 1,
+ project: 'cg-vertexai',
+ region: 'global',
+ credentials,
+ });
+ expect(parseGoogleCredentials(JSON.stringify(credentials))).toEqual(credentials);
+ }
+ expect(parseVertexLogin(credential(SERVICE_ACCOUNT_KEY, ' my-project-1 ', 'us-east5'))).toEqual(
+ expect.objectContaining({ project: 'my-project-1', region: 'us-east5' })
+ );
+ });
+
+ it('refuses other Google credential types', () => {
+ for (const type of ['external_account', 'impersonated_service_account', undefined])
+ expect(() => credential({ type, audience: 'x' })).toThrow(
+ /Only a service account key or a Google sign-in/
+ );
+ expect(() => parseGoogleCredentials('not json')).toThrow(/not JSON/);
+ expect(() => parseGoogleCredentials('[]')).toThrow(/not a JSON object/);
+ });
+
+ it('says which field of a credential is missing or wrong', () => {
+ const { refresh_token: _, ...noRefresh } = AUTHORIZED_USER;
+ expect(() => credential(noRefresh)).toThrow(/Google sign-in .*refresh_token/);
+ expect(() => credential({ ...SERVICE_ACCOUNT_KEY, private_key: 'nope' })).toThrow(
+ /service account key .*private_key/
+ );
+ expect(() => credential({ ...SERVICE_ACCOUNT_KEY, client_email: 'nope' })).toThrow(
+ /client_email/
+ );
+ expect(() =>
+ credential({ ...SERVICE_ACCOUNT_KEY, token_uri: 'http://attacker.example/token' })
+ ).toThrow(/token_uri/);
+ });
+
+ it('checks the project and region', () => {
+ for (const project of ['Upper-Case', 'short', '1starts-with-digit', 'ends-with-hyphen-', ''])
+ expect(() => credential(SERVICE_ACCOUNT_KEY, project)).toThrow(/project id/);
+ for (const region of ['', 'us east', 'US-EAST5', 'us_east5'])
+ expect(() => credential(SERVICE_ACCOUNT_KEY, 'cg-vertexai', region)).toThrow(/region/);
+ });
+
+ it('refuses a login that is not one', () => {
+ expect(() => parseVertexLogin('{')).toThrow(/not JSON/);
+ expect(() =>
+ parseVertexLogin(
+ JSON.stringify({ v: 2, project: 'cg-vertexai', region: 'global', credentials: {} })
+ )
+ ).toThrow(/invalid v/);
+ expect(() =>
+ parseVertexLogin(
+ JSON.stringify({
+ v: 1,
+ project: 'cg-vertexai',
+ region: 'global',
+ credentials: AUTHORIZED_USER,
+ extra: true,
+ })
+ )
+ ).toThrow(/invalid/);
+ });
+
+ it('is sealed and opened as a provider login of kind vertex, and checked when it is', () => {
+ const keys = generateSealingKeyPair();
+ const login = { kind: 'vertex' as const, credential: credential(SERVICE_ACCOUNT_KEY) };
+ const sealed = sealProviderLogin({
+ publicKey: keys.publicKey,
+ controllerId: 'controller-1',
+ provider: 'claude',
+ login,
+ });
+ expect(sealed.ciphertext).not.toContain('PRIVATE KEY');
+ expect(
+ openProviderLogin({ keys, controllerId: 'controller-1', provider: 'claude', sealed })
+ ).toEqual(login);
+ expect(() =>
+ sealProviderLogin({
+ publicKey: keys.publicKey,
+ controllerId: 'controller-1',
+ provider: 'claude',
+ login: { kind: 'vertex', credential: '{"v":1}' },
+ })
+ ).toThrow(/Vertex AI login/);
+ expect(
+ providerLoginSchema.safeParse({
+ kind: 'vertex',
+ credential: credential(AUTHORIZED_USER).replace('authorized_user', 'external_account'),
+ }).success
+ ).toBe(false);
+ });
+});
diff --git a/console/packages/agent-providers/src/vertex-login.ts b/console/packages/agent-providers/src/vertex-login.ts
new file mode 100644
index 000000000..8cac5a5d8
--- /dev/null
+++ b/console/packages/agent-providers/src/vertex-login.ts
@@ -0,0 +1,124 @@
+import { z } from 'zod';
+
+/**
+ * A Claude login through Google Vertex AI: the Google Cloud project and region
+ * Claude Code calls Vertex in, and the Google credential it signs in with. It
+ * is the `credential` of a provider login of kind `vertex`, as JSON.
+ *
+ * The credential is a service account key, or a user's own sign-in as
+ * `gcloud auth application-default login` writes it (`authorized_user`).
+ * Other Google credential types are refused: workload identity federation
+ * (`external_account`) and impersonation name files, commands or a source
+ * credential on the computer that made them, which the machine does not have.
+ */
+const nonEmpty = z.string().trim().min(1);
+
+const authorizedUserSchema = z.looseObject({
+ type: z.literal('authorized_user'),
+ client_id: nonEmpty,
+ client_secret: nonEmpty,
+ refresh_token: nonEmpty,
+});
+
+const serviceAccountSchema = z.looseObject({
+ type: z.literal('service_account'),
+ client_email: z.email(),
+ private_key: z.string().includes('PRIVATE KEY'),
+ private_key_id: nonEmpty.optional(),
+ token_uri: z.url({ protocol: /^https$/ }).optional(),
+});
+
+export const googleCredentialsSchema = z.discriminatedUnion('type', [
+ authorizedUserSchema,
+ serviceAccountSchema,
+]);
+export type GoogleCredentials = z.infer<typeof googleCredentialsSchema>;
+
+/** A Google Cloud project id: 6 to 30 lowercase letters, digits and hyphens, starting with a letter. */
+export const VERTEX_PROJECT_PATTERN = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
+export const VERTEX_REGION_PATTERN = /^[a-z0-9-]{1,64}$/;
+
+export const vertexLoginSchema = z.strictObject({
+ v: z.literal(1),
+ project: z.string().regex(VERTEX_PROJECT_PATTERN),
+ region: z.string().regex(VERTEX_REGION_PATTERN),
+ credentials: googleCredentialsSchema,
+});
+export type VertexLogin = z.infer<typeof vertexLoginSchema>;
+
+/** Where a Vertex login's Google credential is written, under the agent host's state root. */
+export const VERTEX_CREDENTIALS_FILE = 'provider-home/google-credentials.json';
+
+/**
+ * The Google credential JSON `text` names, checked: a service account key or a
+ * user's application-default sign-in. Throws, saying what is wrong, for
+ * anything else.
+ */
+export function parseGoogleCredentials(text: string): GoogleCredentials {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ throw new Error('The Google credential is not JSON.');
+ }
+ return googleCredentials(value);
+}
+
+function googleCredentials(value: unknown): GoogleCredentials {
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw new Error('The Google credential is not a JSON object.');
+ const type = (value as { type?: unknown }).type;
+ if (type !== 'service_account' && type !== 'authorized_user')
+ throw new Error(
+ `Only a service account key or a Google sign-in from \`gcloud auth application-default login\` can be given, not ${typeof type === 'string' ? `a credential of type '${type}'` : 'this credential'}.`
+ );
+ const parsed = googleCredentialsSchema.safeParse(value);
+ if (!parsed.success) {
+ const fields = [...new Set(parsed.error.issues.map((issue) => issue.path.join('.')))];
+ throw new Error(
+ `The ${type === 'service_account' ? 'service account key' : 'Google sign-in'} is missing or has an invalid ${fields.join(', ')}.`
+ );
+ }
+ return parsed.data;
+}
+
+/** The credential of a `vertex` login, checked; throws, saying what is wrong. */
+export function vertexLoginCredential(input: {
+ project: string;
+ region: string;
+ credentials: GoogleCredentials;
+}): string {
+ const project = input.project.trim();
+ const region = input.region.trim();
+ if (!VERTEX_PROJECT_PATTERN.test(project))
+ throw new Error(
+ `'${project}' is not a Google Cloud project id: 6 to 30 lowercase letters, digits and hyphens, starting with a letter.`
+ );
+ if (!VERTEX_REGION_PATTERN.test(region))
+ throw new Error(`'${region}' is not a Vertex AI region, such as global or us-east5.`);
+ return JSON.stringify({
+ v: 1,
+ project,
+ region,
+ credentials: googleCredentials(input.credentials),
+ } satisfies VertexLogin);
+}
+
+/** A `vertex` login's credential, parsed; throws, saying what is wrong. */
+export function parseVertexLogin(credential: string): VertexLogin {
+ let value: unknown;
+ try {
+ value = JSON.parse(credential);
+ } catch {
+ throw new Error('The Vertex AI login is not JSON.');
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw new Error('The Vertex AI login is not a JSON object.');
+ const { credentials, ...rest } = value as Record<string, unknown>;
+ const outer = vertexLoginSchema.omit({ credentials: true }).safeParse(rest);
+ if (!outer.success)
+ throw new Error(
+ `The Vertex AI login has an invalid ${[...new Set(outer.error.issues.map((issue) => issue.path.join('.') || 'field'))].join(', ')}.`
+ );
+ return { ...outer.data, credentials: googleCredentials(credentials) };
+}
diff --git a/docs/design/controller-contract-v1.md b/docs/design/controller-contract-v1.md
index f7dff8f83..1e919d5b0 100644
--- a/docs/design/controller-contract-v1.md
+++ b/docs/design/controller-contract-v1.md
@@ -223,7 +223,7 @@ type SealedLogin = {
```
- **The key.** The controller makes an X25519 keypair at enrollment and sends `public_key`. A controller enrolled before then registers it once with `PATCH /v1/management/controllers/{id}` `{ public_key }`. A different key afterwards is refused (409): the machine is enrolled again. A controller that keeps no secrets across starts (its credential handed over by a parent) registers none, and uses only the machine's own logins.
-- **Sealing.** The owner's client (Console) seals `{ kind: "api-key" | "setup-token" | "auth-json", credential }` to that key: an ephemeral X25519 key, `HKDF-SHA256(shared, salt = ephemeral public ‖ controller public, info = "switch provider login v1")`, and AES-256-GCM with `aad = "switch-provider-login-v1\n<controller id>\n<provider>"`. The server checks the envelope's shape and that `key_id` names the machine's current key, stores only the ciphertext, and can never open it. The same construction is in `core/switch_core/management/sealed_logins.py` (checks) and `@switch-console/agent-providers` `sealed-login.ts` (seal and open).
+- **Sealing.** The owner's client (Console) seals `{ kind: "api-key" | "setup-token" | "auth-json" | "vertex", credential }` to that key (a `vertex` login, Claude only, holds `{"v": 1, "project", "region", "credentials"}` as JSON, `credentials` being a Google service account key or `authorized_user` sign-in): an ephemeral X25519 key, `HKDF-SHA256(shared, salt = ephemeral public ‖ controller public, info = "switch provider login v1")`, and AES-256-GCM with `aad = "switch-provider-login-v1\n<controller id>\n<provider>"`. The server checks the envelope's shape and that `key_id` names the machine's current key, stores only the ciphertext, and can never open it. The same construction is in `core/switch_core/management/sealed_logins.py` (checks) and `@switch-console/agent-providers` `sealed-login.ts` (seal and open).
- **On demand.** The owner gives a machine a login with `PUT /gateway/management/controllers/{id}/provider-logins/{provider}` `{ sealed }`, which answers `{ login: { provider, revision, key_id, updated_at }, operation }`. The operation is `provider.login` `{ provider, method: "sealed", revision }`: the controller fetches the login, opens it, checks the provider signs in with it, and reports `succeeded` with its provider status, or `failed` with `provider_login_missing`, `provider_login_expired` or `internal`. `GET …/provider-logins` lists what was given (never the ciphertext). `DELETE …/provider-logins/{provider}` takes it back and queues `provider.recheck`. Revoking the machine deletes its logins.
- The controller **prefers a local login** (`auth_source: "local"`). It uses a sealed one (`auth_source: "sealed"`) only for a provider it has no local login for, and only once the provider signs in with it. An agent using one gets it with its relay credentials, and is restarted when the login changes or is withdrawn.
- On Switch EC2, the same sealed logins apply: no KMS is involved.