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
240 changes: 240 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,240 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { normalizeError } from '@agent-device/kernel/errors';
import { mkdtempForTestSync } from '@agent-device/test-kit';
import {
loginWithDeviceAuth,
readCliSession,
resolveCliSessionPath,
resolveRemoteAuth,
writeCliSession,
} from '../auth-session.ts';

const baseFlags = {
json: false,
help: false,
version: false,
daemonBaseUrl: 'https://bridge.agent-device.dev',
tenant: 'acme',
runId: 'run-123',
};

const START = 'https://cloud.example/api/control-plane/device-auth/start';
const POLL = 'https://cloud.example/api/control-plane/device-auth/poll';
const REFRESH = 'https://cloud.example/api/control-plane/cli-session/refresh';

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

/** A refresh of the stored session that records each request URL and answers with a token. */
function refreshWith(stateDir: string, env: Record<string, string>, requests: string[]) {
return resolveRemoteAuth({
command: 'snapshot',
flags: baseFlags,
stateDir,
allowInteractiveLogin: false,
env,
io: {
fetch: async (url) => {
requests.push(String(url));
return jsonResponse({ accessToken: 'adc_agent_fresh' });
},
},
});
}

/** Answers device-auth start and poll with an approved login, and any other URL with a 404. */
const deviceAuthCloud = async (url: URL | RequestInfo): Promise<Response> => {
if (String(url) === START) {
return jsonResponse({
deviceCode: 'device-secret',
userCode: 'ABCD-EFGH',
verificationUri: 'https://cloud.example/authorize',
});
}
if (String(url) === POLL) {
return jsonResponse({
status: 'approved',
accessToken: 'adc_agent_login',
cliSession: { id: 'session-new', refreshCredential: 'adc_refresh_new' },
});
}
return new Response('{}', { status: 404 });
};

function loginAt(stateDir: string, fetch: typeof globalThis.fetch) {
return loginWithDeviceAuth({
stateDir,
flags: baseFlags,
env: { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' },
io: {
stdinIsTTY: true,
stdoutIsTTY: true,
stderr: { write: () => true },
openBrowser: async () => {},
fetch,
},
});
}

/** Writes the session file as raw JSON, the way an older CLI or a hand edit leaves it. */
function writeRawSession(stateDir: string, record: Record<string, unknown>): void {
const filePath = resolveCliSessionPath(stateDir);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(record));
}

const isIssuerUnverified = (error: unknown) => {
const normalized = normalizeError(error);
return (
normalized.details?.reason === 'cli_session_issuer_unverified' &&
String(normalized.hint).includes('agent-device auth login')
);
};

test('a stored CLI session is sent only to the cloud that issued it', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-origin-');
try {
writeCliSession({
stateDir: tempRoot,
session: {
version: 2,
id: 'session-origin',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_secret',
createdAt: '2026-01-01T00:00:00.000Z',
},
});
const requests: string[] = [];

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

const same = await refreshWith(
tempRoot,
{ AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example/' },
requests,
);
assert.equal(same.flags.daemonAuthToken, 'adc_agent_fresh');
assert.deepEqual(requests, [REFRESH]);
} finally {
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-');
try {
const session = {
version: 2 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,
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);
} finally {
fs.rmSync(tempRoot, { recursive: true, force: true });
}
});

test('a version 1 session is refused with a re-login reason, and a fresh login is used', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-origin-legacy-');
try {
writeRawSession(tempRoot, {
version: 1,
id: 'session-legacy',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_legacy',
createdAt: '2026-01-01T00:00:00.000Z',
});
const requests: string[] = [];

await assert.rejects(() => refreshWith(tempRoot, {}, requests), isIssuerUnverified);
assert.deepEqual(requests, []);
assert.equal(readCliSession({ stateDir: tempRoot }), null);

const login = await loginAt(tempRoot, deviceAuthCloud);
assert.equal(login.session.version, 2);

const refreshed = await refreshWith(tempRoot, {}, requests);
assert.equal(refreshed.flags.daemonAuthToken, 'adc_agent_fresh');
assert.deepEqual(requests, [REFRESH]);
} finally {
fs.rmSync(tempRoot, { recursive: true, force: true });
}
});

// Every auth route goes through the redirect-checked transport, whose cases are proven in
// cloud-auth-request.test.ts. A route that called fetch directly would follow this redirect.
test.each([START, POLL, REFRESH])(
'a cross-origin redirect from %s is refused before it is followed, and nothing is stored',
async (redirected) => {
const tempRoot = mkdtempForTestSync('agent-device-auth-origin-redirect-');
try {
const sent: string[] = [];
const fetch = async (url: URL | RequestInfo) => {
sent.push(String(url));
return String(url) === redirected
? new Response(null, {
status: 307,
headers: { location: 'https://elsewhere.example/auth' },
})
: await deviceAuthCloud(url);
};
if (redirected === REFRESH) await loginAt(tempRoot, deviceAuthCloud);
const stored = readCliSession({ stateDir: tempRoot });

await assert.rejects(
() =>
redirected === REFRESH
? resolveRemoteAuth({
command: 'snapshot',
flags: baseFlags,
stateDir: tempRoot,
allowInteractiveLogin: false,
env: {},
io: { fetch },
})
: loginAt(tempRoot, fetch),
(error) => normalizeError(error).details?.reason === 'cloud_auth_redirect_refused',
);
assert.equal(sent.at(-1), redirected);
assert.deepEqual(readCliSession({ stateDir: tempRoot }), stored);
} finally {
fs.rmSync(tempRoot, { recursive: true, force: true });
}
},
);
2 changes: 1 addition & 1 deletion src/cli/__tests__/auth-session-exchange.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function writeStoredSession(stateDir: string, overrides: Record<string, unknown>
writeCliSession({
stateDir,
session: {
version: 1,
version: 2,
id: 'session-pairing',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down
2 changes: 1 addition & 1 deletion src/cli/__tests__/auth-session-refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function writeStoredSession(stateDir: string, overrides: Record<string, unknown>
writeCliSession({
stateDir,
session: {
version: 1,
version: 2,
id: 'session-refresh',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down
2 changes: 1 addition & 1 deletion src/cli/__tests__/auth-session-refusal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function writeStoredSession(stateDir: string): void {
writeCliSession({
stateDir,
session: {
version: 1,
version: 2,
id: 'session-refusal',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_stored',
Expand Down
2 changes: 1 addition & 1 deletion src/cli/__tests__/auth-session-umask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ test.skipIf(process.platform === 'win32')(
() => {
const tempRoot = mkdtempForTestSync('agent-device-auth-session-umask-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-first',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_umask',
Expand Down
20 changes: 10 additions & 10 deletions src/cli/__tests__/auth-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ test('remote auth leaves non-cloud remote daemons to existing daemon auth valida
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
version: 2,
id: 'session-non-cloud',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_should_not_be_used',
Expand Down Expand Up @@ -132,7 +132,7 @@ test('remote auth refreshes a stored CLI session into an agent token', async ()
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
version: 2,
id: 'session-1',
cloudBaseUrl: 'https://cloud.example',
workspaceId: 'acme',
Expand Down Expand Up @@ -175,7 +175,7 @@ test('remote auth refreshes a stored CLI session into an agent token', async ()
test('remote auth stores a refresh credential that the cloud rotated', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-rotate',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down Expand Up @@ -226,7 +226,7 @@ test('remote auth stores a refresh credential that the cloud rotated', async ()
test('a rotated credential does not replace a session another writer changed', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-rotate-race-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-race',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down Expand Up @@ -286,7 +286,7 @@ test('logout without a stored session takes no lock and writes nothing', async (
test('a stored rotation is kept when the lock release fails, and the warning is best effort', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-release-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-release',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down Expand Up @@ -347,7 +347,7 @@ test('a timed-out session lock wait keeps a login waiting and fails a refresh re
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
version: 2,
id: 'session-timeout',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_old',
Expand Down Expand Up @@ -465,7 +465,7 @@ test('device login does not print a user code that carries control characters',
test('remote auth does not fall back to login when session refresh gets 503', async () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-refresh-503-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-503',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_503',
Expand Down Expand Up @@ -515,7 +515,7 @@ test('remote auth fails immediately when stored CLI session is revoked', async (
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
version: 2,
id: 'session-revoked',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_revoked',
Expand Down Expand Up @@ -623,7 +623,7 @@ test('auth summary and logout do not expose stored refresh credentials', async (
writeCliSession({
stateDir: tempRoot,
session: {
version: 1,
version: 2,
id: 'session-3',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_hidden',
Expand Down Expand Up @@ -873,7 +873,7 @@ function assertRefusedWithoutOutput(refused: RefusedDeviceLogin): void {
test('a rewritten CLI session replaces the file, so a reader never sees a partial record', () => {
const tempRoot = mkdtempForTestSync('agent-device-auth-session-replace-');
const session = {
version: 1 as const,
version: 2 as const,
id: 'session-first',
cloudBaseUrl: 'https://cloud.example',
refreshCredential: 'adc_refresh_first',
Expand Down
Loading
Loading