Skip to content
Open
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
95 changes: 95 additions & 0 deletions src/cli/__tests__/auth-session-cloud-origin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { normalizeError } from '@agent-device/kernel/errors';
import { mkdtempForTestSync } from '@agent-device/test-kit';
import { readCliSession, resolveRemoteAuth, writeCliSession } from '../auth-session.ts';

const baseFlags = {
json: false,
help: false,
version: false,
daemonBaseUrl: 'https://daemon.example',
tenant: 'acme',
runId: 'run-123',
};

function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}

test('a stored CLI session is sent only to the cloud that issued it, without redirects', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-origin-');
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
id: 'session-origin',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_secret',
createdAt: '2026-01-01T00:00:00.000Z',
},
});
const requests: Array<{ url: string; redirect?: RequestRedirect }> = [];
const refresh = (env: Record<string, string>) =>
resolveRemoteAuth({
command: 'snapshot',
flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' },
stateDir: tempRoot,
allowInteractiveLogin: false,
env,
io: {
fetch: async (url, init) => {
requests.push({ url: String(url), redirect: init?.redirect });
return jsonResponse({ accessToken: 'adc_agent_fresh' });
},
},
});

await assert.rejects(
() => refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://elsewhere.example' }),
(error) => normalizeError(error).details?.reason === 'cloud_login_origin_mismatch',
);
assert.deepEqual(requests, []);

const same = await refresh({ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' });
assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh');
assert.deepEqual(requests, [
{ url: 'https://cloud.example/api/control-plane/cli-session/refresh', redirect: 'error' },
]);
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test('a rotation is not stored over a session that a login moved to another cloud', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-origin-rotate-');
const session = {
version: 1 as const,
id: 'session-moved',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
createdAt: '2026-01-01T00:00:00.000Z',
};
writeCliSession({ stateDir: tempRoot, session });
const moved = { ...session, cloudBaseUrl: 'https://other-cloud.example' };

await resolveRemoteAuth({
command: 'snapshot',
flags: { ...baseFlags, daemonBaseUrl: 'https://bridge.agent-device.dev' },
stateDir: tempRoot,
allowInteractiveLogin: false,
env: {},
io: {
fetch: async () => {
// Another process logs in to another cloud while this refresh is in flight.
writeCliSession({ stateDir: tempRoot, session: moved });
return jsonResponse({ accessToken: 'adc_agent_1', refreshCredential: 'adc_refresh_new' });
},
},
});

assert.deepEqual(readCliSession({ stateDir: tempRoot }), moved);
fs.rmSync(tempRoot, { recursive: true, force: true });
});
46 changes: 36 additions & 10 deletions src/cli/auth-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { acquireProcessLock, publishFileSync } from '@agent-device/host-kit/file';
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { CliFlags } from '@agent-device/contracts/command';
import { type EnvMap } from '@agent-device/kernel/source-value';
import { readCloudJsonResponse } from './cloud-response.ts';
Expand All @@ -20,6 +20,13 @@ const DEFAULT_POLL_INTERVAL_MS = 5_000;
// a stuck live process makes a contender wait this long.
const CLI_SESSION_LOCK_TIMEOUT_MS = 60_000;

const CLOUD_SESSION_REASONS = {
// The cloud API origin named by AGENT_DEVICE_CLOUD_BASE_URL differs from the origin that issued
// the stored CLI session, so the stored credential is not sent. Log in with the named origin, or
// unset the override.
loginOriginMismatch: { reason: 'cloud_login_origin_mismatch' },
} as const satisfies ReasonTable<'cloud auth'>;

export type CliSessionRecord = {
version: 1;
id: string;
Expand Down Expand Up @@ -422,10 +429,25 @@ async function resolveCliSessionAccess(options: {
if (!session || isExpired(session.expiresAt, options.io?.now)) {
return null;
}
// The stored credential goes only to the cloud that issued it. An override that names another
// origin would send it to that origin.
// The refresh goes to the stored URL. A same-origin override still names the connection.
const cloudBaseUrl = resolveCloudBaseUrl({}, session.cloudBaseUrl);
const connectionBaseUrl = resolveCloudBaseUrl(options.env, cloudBaseUrl);
if (new URL(connectionBaseUrl).origin !== new URL(cloudBaseUrl).origin) {
throw new AppError(
'UNAUTHORIZED',
'The stored CLI session belongs to another cloud API origin.',
{
reason: CLOUD_SESSION_REASONS.loginOriginMismatch.reason,
hint: 'Run agent-device auth login with this AGENT_DEVICE_CLOUD_BASE_URL, or unset it.',
},
);
}
const refreshed = await refreshAgentToken({
session,
cloudBaseUrl,
flags: options.flags,
env: options.env,
io: options.io,
});
if (refreshed.refreshCredential) {
Expand All @@ -436,10 +458,7 @@ async function resolveCliSessionAccess(options: {
io: options.io,
});
}
return {
accessToken: refreshed.accessToken,
cloudBaseUrl: resolveCloudBaseUrl(options.env, session.cloudBaseUrl),
};
return { accessToken: refreshed.accessToken, cloudBaseUrl: connectionBaseUrl };
}

/**
Expand All @@ -461,7 +480,13 @@ async function storeRotatedCredential(options: {
options.stateDir,
() => {
const stored = readCliSession({ stateDir: options.stateDir });
if (stored?.id !== sent.id || stored.refreshCredential !== sent.refreshCredential) return;
if (
stored?.id !== sent.id ||
stored.cloudBaseUrl !== sent.cloudBaseUrl ||
stored.refreshCredential !== sent.refreshCredential
) {
return;
}
writeCliSession({ stateDir: options.stateDir, session: { ...stored, refreshCredential } });
},
{ io: options.io, keepWaiting: true },
Expand All @@ -477,13 +502,12 @@ async function storeRotatedCredential(options: {

async function refreshAgentToken(options: {
session: CliSessionRecord;
cloudBaseUrl: string;
flags: CliFlags;
env: EnvMap;
io?: AuthIo;
}): Promise<{ accessToken: string; expiresAt?: string; refreshCredential?: string }> {
const cloudBaseUrl = resolveCloudBaseUrl(options.env, options.session.cloudBaseUrl);
const response = await postJson<CliSessionRefreshResponse>({
baseUrl: cloudBaseUrl,
baseUrl: options.cloudBaseUrl,
pathName: CLI_SESSION_REFRESH_PATH,
body: {
refreshCredential: options.session.refreshCredential,
Expand Down Expand Up @@ -577,6 +601,8 @@ async function postJson<T>(options: {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(options.body),
// A redirect would resend a credential or device code to the redirect target.
redirect: 'error',
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
});
return await readCloudJsonResponse<T>(response, {
Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -2683,7 +2683,7 @@ agent-device disconnect --remote-config ./agent-device.remote.json
```

- `connect` fetches the cloud connection profile; `connect --remote-config <path>` uses a local profile with the host, tenant/run, and optional session, platform, lease backend, and Metro settings. Both save connection state and defer the device lease and Metro preparation until a command needs them (including a `batch` step that opens an app). Direct-provider profiles need their provider credentials when `connect` runs. Cloud profiles must be a JSON object at `connection.remoteConfigProfile`; the older `connection.remoteConfig` string is rejected.
- Cloud auth: `connect` refreshes a stored CLI session into a short-lived `adc_agent_...` token. Without a session, interactive shells start login; CI and non-interactive shells fail with API-token setup instructions. `--no-login` disables implicit login. Use `adc_live_...` service tokens for CI. Manage the CLI session with `agent-device auth status`, `auth login`, and `auth logout`; login never stores an `adc_live_...` token. Interactive login prints the code that the browser page must show; approve only when they match. When the cloud rotates the session credential during a refresh, the CLI stores the replacement.
- Cloud auth: `connect` refreshes a stored CLI session into a short-lived `adc_agent_...` token. Without a session, interactive shells start login; CI and non-interactive shells fail with API-token setup instructions. `--no-login` disables implicit login. Use `adc_live_...` service tokens for CI. Manage the CLI session with `agent-device auth status`, `auth login`, and `auth logout`; login never stores an `adc_live_...` token. Interactive login prints the code that the browser page must show; approve only when they match. When the cloud rotates the session credential during a refresh, the CLI stores the replacement. A refresh goes only to the cloud origin stored with the session: an `AGENT_DEVICE_CLOUD_BASE_URL` with another origin fails with `cloud_login_origin_mismatch` until you log in again, and cloud auth requests do not follow redirects.
- `AGENT_DEVICE_CLOUD_BASE_URL` is the bridge/control-plane API origin, not necessarily the dashboard; its `/api-keys` route may redirect to the dashboard.
- Every command that takes a session on a connection with a lease provider (the cloud, `connect proxy`, a device cloud, or a `leaseProvider` in the profile), including `connect`, must name it with `--session`, `AGENT_DEVICE_SESSION`, or config, or it fails with `REMOTE_SESSION_REQUIRED`. Each session on such a profile leases under its own client and run, derived from the session name, unless the profile names a lease the host issued. For any other profile, `connect` without `--session` creates a fresh remote session and prints the generated `--session`, and commands without one fall back to the most recent connection on the machine, which is safe only for one sequential workflow. To replace a connection, pass `--session <name> --force`.
- After `connect`, normal commands (`install-from-source`, `open`, `snapshot`, `press`, `screenshot`, and others) reuse the connection state. `connection status` shows `leaseId=pending` until the first platform-bound command allocates the lease. Explicit flags override connected defaults; `open` with explicit remote flags but no saved runtime hints warns that React Native apps may launch without Metro hints.
Expand Down
6 changes: 6 additions & 0 deletions website/docs/docs/error-reasons.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r

These reasons can come from more than one command.

### Cloud auth

| Reason | Meaning |
| --- | --- |
| `cloud_login_origin_mismatch` | The cloud API origin named by AGENT_DEVICE_CLOUD_BASE_URL differs from the origin that issued the stored CLI session, so the stored credential is not sent. Log in with the named origin, or unset the override. |

### Daemon lifecycle

| Reason | Meaning |
Expand Down
Loading