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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions src/cli/commands/__tests__/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { afterEach, test, vi } from 'vitest';
import { runCliCapture } from '../../../__tests__/cli-capture.ts';
import { writeCliSession } from '../../auth-session.ts';
import { mkdtempForTestSync } from '../../../__tests__/test-utils/tmp-dir.ts';

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

function writeStoredCliSession(
stateDir: string,
overrides: Partial<Parameters<typeof writeCliSession>[0]['session']> = {},
) {
writeCliSession({
stateDir,
session: {
version: 1,
id: 'cli-1',
cloudBaseUrl: 'https://cloud.example.test',
refreshCredential: 'refresh-credential',
createdAt: '2026-01-01T00:00:00.000Z',
...overrides,
},
});
}

test('auth with no subcommand renders an unauthenticated status', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-status-');
const result = await runCliCapture(['auth', '--state-dir', stateDir]);

assert.equal(result.code, null);
assert.equal(result.stdout, 'Not authenticated.\n');
});

test('auth status renders every stored session field', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-status-full-');
writeStoredCliSession(stateDir, {
id: 'cli-42',
workspaceId: 'ws-7',
accountId: 'acct-9',
expiresAt: '2020-01-01T00:00:00.000Z',
});

const result = await runCliCapture(['auth', 'status', '--state-dir', stateDir]);

assert.equal(result.code, null);
assert.deepEqual(result.stdout.trim().split('\n'), [
'Authenticated with cloud CLI session.',
'cloud=https://cloud.example.test',
'session=cli-42',
'workspace=ws-7',
'account=acct-9',
'expiresAt=2020-01-01T00:00:00.000Z',
'status=expired',
]);
});

test('auth status omits optional fields a minimal session does not carry', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-status-minimal-');
writeStoredCliSession(stateDir);

const result = await runCliCapture(['auth', 'status', '--state-dir', stateDir]);

assert.equal(result.code, null);
assert.deepEqual(result.stdout.trim().split('\n'), [
'Authenticated with cloud CLI session.',
'cloud=https://cloud.example.test',
'session=cli-1',
]);
});

test('auth login completes a device-code flow and stores the CLI session', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-login-');
const requestUrls: string[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: URL | RequestInfo) => {
const url = new URL(String(input));
requestUrls.push(url.pathname);
if (url.pathname === '/api/control-plane/device-auth/start') {
return new Response(
JSON.stringify({
deviceCode: 'device-code-1',
userCode: 'ABCD-1234',
verificationUri: 'https://cloud.example.test/login',
interval: 1,
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
}
return new Response(
JSON.stringify({
status: 'approved',
accessToken: 'access-token-1',
expiresAt: '2026-02-01T00:00:00.000Z',
cliSession: {
id: 'cli-7',
refreshCredential: 'refresh-credential-7',
workspaceId: 'ws-7',
accountId: 'acct-7',
expiresAt: '2026-06-01T00:00:00.000Z',
},
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
}),
);

const previousStdinIsTTY = process.stdin.isTTY;
const previousStdoutIsTTY = process.stdout.isTTY;
(process.stdin as { isTTY?: boolean }).isTTY = true;
(process.stdout as { isTTY?: boolean }).isTTY = true;
try {
const result = await runCliCapture(['auth', 'login', '--state-dir', stateDir], {
env: {
AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example.test',
// A remote shell with interactive TTYs takes the device-code branch,
// which prints the URL instead of launching a browser.
SSH_CONNECTION: '10.0.0.1 50000 10.0.0.2 22',
CI: undefined,
GITHUB_ACTIONS: undefined,
BUILDKITE: undefined,
},
});

assert.equal(result.code, null);
assert.equal(result.stdout, 'Authenticated with cloud CLI session.\n');
assert.match(result.stderr, /Open this URL on your machine/);
assert.deepEqual(requestUrls, [
'/api/control-plane/device-auth/start',
'/api/control-plane/device-auth/poll',
]);
const stored = JSON.parse(
fs.readFileSync(path.join(stateDir, 'auth', 'cli-session.json'), 'utf8'),
) as { id: string; workspaceId?: string };
assert.equal(stored.id, 'cli-7');
assert.equal(stored.workspaceId, 'ws-7');
} finally {
(process.stdin as { isTTY?: boolean }).isTTY = previousStdinIsTTY;
(process.stdout as { isTTY?: boolean }).isTTY = previousStdoutIsTTY;
}
});

test('auth logout removes a stored session and reports it', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-logout-removed-');
writeStoredCliSession(stateDir);

const result = await runCliCapture(['auth', 'logout', '--state-dir', stateDir]);

assert.equal(result.code, null);
assert.equal(result.stdout, 'Removed stored cloud CLI session.\n');
assert.equal(fs.existsSync(path.join(stateDir, 'auth', 'cli-session.json')), false);
});

test('auth logout without a stored session reports nothing to remove', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-logout-none-');
const result = await runCliCapture(['auth', 'logout', '--state-dir', stateDir]);

assert.equal(result.code, null);
assert.equal(result.stdout, 'No stored cloud CLI session.\n');
});

test('auth rejects a subcommand outside status, login, and logout', async () => {
const stateDir = mkdtempForTestSync('agent-device-auth-invalid-');
const result = await runCliCapture(['auth', 'rotate', '--state-dir', stateDir]);

assert.equal(result.code, 1);
assert.match(result.stderr, /INVALID_ARGS/);
assert.match(result.stderr, /auth accepts only: status, login, logout/);
});
160 changes: 160 additions & 0 deletions src/cli/commands/__tests__/connection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Human rendering of `connection status` (#3420): the shipped status block is the operator-
// facing projection of a stored remote connection, so its pending-vs-bound lease axes, the
// metro prepared marker, and the deferred notices are pinned through the CLI route.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test } from 'vitest';
import { runCliCapture } from '../../../__tests__/cli-capture.ts';
import {
hashRemoteConfigFile,
writeRemoteConnectionState,
type RemoteConnectionState,
} from '../../../remote/remote-connection-state.ts';
import { mkdtempForTestSync } from '../../../__tests__/test-utils/tmp-dir.ts';

type ConnectionFixture = {
stateDir: string;
remoteConfigPath: string;
};

function connectionFixture(prefix: string): ConnectionFixture {
const tempRoot = mkdtempForTestSync(prefix);
return {
stateDir: path.join(tempRoot, '.state'),
remoteConfigPath: path.join(tempRoot, 'remote.json'),
};
}

function seedConnection(
fixture: ConnectionFixture,
remoteConfig: Record<string, unknown>,
state: Partial<RemoteConnectionState> & Pick<RemoteConnectionState, 'session'>,
): void {
fs.writeFileSync(fixture.remoteConfigPath, JSON.stringify(remoteConfig));
const now = new Date().toISOString();
writeRemoteConnectionState({
stateDir: fixture.stateDir,
state: {
version: 1,
remoteConfigPath: fixture.remoteConfigPath,
remoteConfigHash: hashRemoteConfigFile(fixture.remoteConfigPath),
tenant: 'acme',
runId: 'run-123',
connectedAt: now,
updatedAt: now,
...state,
},
});
}

test('connection status without a stored connection says so for the default session', async () => {
const fixture = connectionFixture('agent-device-connection-status-none-');
const result = await runCliCapture(['connection', 'status', '--state-dir', fixture.stateDir]);

assert.equal(result.code, null);
assert.equal(result.stdout, 'No remote connection for "default".\n');
});

test('connection status rejects a subcommand other than status', async () => {
const fixture = connectionFixture('agent-device-connection-status-invalid-');
const result = await runCliCapture(['connection', 'rotate', '--state-dir', fixture.stateDir]);

assert.equal(result.code, 1);
assert.match(result.stderr, /INVALID_ARGS/);
assert.match(result.stderr, /connection accepts only: status/);
});

test('connection status renders a pending lease and the deferred allocation notice', async () => {
const fixture = connectionFixture('agent-device-connection-status-pending-');
seedConnection(
fixture,
{ daemonBaseUrl: 'https://daemon.example.test' },
{
session: 'adc-pending',
leaseProvider: 'proxy',
},
);

const result = await runCliCapture([
'connection',
'status',
'--state-dir',
fixture.stateDir,
'--session',
'adc-pending',
]);

assert.equal(result.code, null);
assert.match(result.stdout, /Configured remote session "adc-pending"\./);
assert.match(result.stdout, /tenant=acme runId=run-123 leaseId=pending backend=pending/);
assert.match(result.stdout, new RegExp(`remoteConfig=${fixture.remoteConfigPath}`));
assert.match(result.stdout, /metro=not-prepared/);
assert.match(result.stdout, /No live device session has been created/);
});

test('connection status renders a bound lease and a prepared runtime without notices', async () => {
const fixture = connectionFixture('agent-device-connection-status-bound-');
seedConnection(
fixture,
{ daemonBaseUrl: 'https://daemon.example.test' },
{
session: 'adc-bound',
leaseId: 'lease-1',
leaseBackend: 'android-instance',
leaseProvider: 'proxy',
runtime: { platform: 'android' },
},
);

const result = await runCliCapture([
'connection',
'status',
'--state-dir',
fixture.stateDir,
'--session',
'adc-bound',
]);

assert.equal(result.code, null);
assert.match(result.stdout, /tenant=acme runId=run-123 leaseId=lease-1 backend=android-instance/);
assert.match(result.stdout, /metro=prepared/);
assert.doesNotMatch(result.stdout, /No live device session has been created/);
Comment thread
thymikee marked this conversation as resolved.
assert.doesNotMatch(result.stdout, /Metro runtime is not prepared yet/);
});

test('connection status re-emits the deferred Metro notice for a bound lease', async () => {
const fixture = connectionFixture('agent-device-connection-status-metro-');
seedConnection(
fixture,
{
daemonBaseUrl: 'https://daemon.example.test',
metroPublicBaseUrl: 'https://sandbox.example.test',
},
{
session: 'adc-metro',
leaseId: 'lease-2',
leaseBackend: 'android-instance',
leaseProvider: 'proxy',
},
);

const result = await runCliCapture([
'connection',
'status',
'--state-dir',
fixture.stateDir,
'--session',
'adc-metro',
]);

assert.equal(result.code, null);
assert.match(result.stdout, /metro=not-prepared/);
assert.match(result.stdout, /Metro runtime is not prepared yet/);
assert.match(
result.stdout,
new RegExp(
`agent-device metro prepare --remote-config ${fixture.remoteConfigPath} --session adc-metro`,
),
);
});
Loading
Loading