feat(core): implement interactive and non-interactive consent for OAuth (#17699)

This commit is contained in:
Emily Hedlund
2026-01-30 09:57:34 -05:00
committed by GitHub
parent 32cfce16bb
commit 2238802e97
9 changed files with 326 additions and 12 deletions
+93 -1
View File
@@ -9,6 +9,7 @@ import type { Mock } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
getOauthClient,
getConsentForOauth,
resetOauthClientForTesting,
clearCachedCredentialFile,
clearOauthClientCache,
@@ -29,8 +30,12 @@ import { FORCE_ENCRYPTED_FILE_ENV_VAR } from '../mcp/token-storage/index.js';
import { GEMINI_DIR, homedir as pathsHomedir } from '../utils/paths.js';
import { debugLogger } from '../utils/debugLogger.js';
import { writeToStdout } from '../utils/stdio.js';
import { FatalCancellationError } from '../utils/errors.js';
import {
FatalAuthenticationError,
FatalCancellationError,
} from '../utils/errors.js';
import process from 'node:process';
import { coreEvents } from '../utils/events.js';
vi.mock('node:os', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:os')>();
@@ -88,6 +93,13 @@ const mockConfig = {
global.fetch = vi.fn();
describe('oauth2', () => {
beforeEach(() => {
vi.spyOn(coreEvents, 'listenerCount').mockReturnValue(1);
vi.spyOn(coreEvents, 'emitConsentRequest').mockImplementation((payload) => {
payload.onConfirm(true);
});
});
describe('with encrypted flag false', () => {
let tempHomeDir: string;
@@ -1503,4 +1515,84 @@ describe('oauth2', () => {
expect(fs.existsSync(credsPath)).toBe(true); // The unencrypted file should remain
});
});
describe('getConsentForOauth', () => {
it('should use coreEvents when listeners are present', async () => {
vi.restoreAllMocks();
const mockEmitConsentRequest = vi.spyOn(coreEvents, 'emitConsentRequest');
const mockListenerCount = vi
.spyOn(coreEvents, 'listenerCount')
.mockReturnValue(1);
mockEmitConsentRequest.mockImplementation((payload) => {
payload.onConfirm(true);
});
const result = await getConsentForOauth();
expect(result).toBe(true);
expect(mockEmitConsentRequest).toHaveBeenCalled();
mockListenerCount.mockRestore();
mockEmitConsentRequest.mockRestore();
});
it('should use readline when no listeners are present and stdin is a TTY', async () => {
vi.restoreAllMocks();
const mockListenerCount = vi
.spyOn(coreEvents, 'listenerCount')
.mockReturnValue(0);
const originalIsTTY = process.stdin.isTTY;
Object.defineProperty(process.stdin, 'isTTY', {
value: true,
configurable: true,
});
const mockReadline = {
on: vi.fn((event, callback) => {
if (event === 'line') {
callback('y');
}
}),
close: vi.fn(),
};
(readline.createInterface as Mock).mockReturnValue(mockReadline);
const result = await getConsentForOauth();
expect(result).toBe(true);
expect(readline.createInterface).toHaveBeenCalled();
expect(writeToStdout).toHaveBeenCalledWith(
expect.stringContaining('Do you want to continue? [Y/n]: '),
);
mockListenerCount.mockRestore();
Object.defineProperty(process.stdin, 'isTTY', {
value: originalIsTTY,
configurable: true,
});
});
it('should throw FatalAuthenticationError when no listeners and not a TTY', async () => {
vi.restoreAllMocks();
const mockListenerCount = vi
.spyOn(coreEvents, 'listenerCount')
.mockReturnValue(0);
const originalIsTTY = process.stdin.isTTY;
Object.defineProperty(process.stdin, 'isTTY', {
value: false,
configurable: true,
});
await expect(getConsentForOauth()).rejects.toThrow(
FatalAuthenticationError,
);
mockListenerCount.mockRestore();
Object.defineProperty(process.stdin, 'isTTY', {
value: originalIsTTY,
configurable: true,
});
});
});
});
+52
View File
@@ -269,6 +269,11 @@ async function initOauthClient(
await triggerPostAuthCallbacks(client.credentials);
} else {
const userConsent = await getConsentForOauth();
if (!userConsent) {
throw new FatalCancellationError('Authentication cancelled by user.');
}
const webLogin = await authWithWeb(client);
coreEvents.emit(CoreEvent.UserFeedback, {
@@ -372,6 +377,53 @@ async function initOauthClient(
return client;
}
export async function getConsentForOauth(): Promise<boolean> {
const prompt =
'Code Assist login required. Opening authentication page in your browser. ';
if (coreEvents.listenerCount(CoreEvent.ConsentRequest) === 0) {
if (!process.stdin.isTTY) {
throw new FatalAuthenticationError(
'Code Assist login required, but interactive consent could not be obtained.\n' +
'Please run Gemini CLI in an interactive terminal to authenticate, or use NO_BROWSER=true for manual authentication.',
);
}
return getOauthConsentNonInteractive(prompt);
}
return getOauthConsentInteractive(prompt);
}
async function getOauthConsentNonInteractive(prompt: string) {
const rl = readline.createInterface({
input: process.stdin,
output: createWorkingStdio().stdout,
terminal: true,
});
const fullPrompt = prompt + 'Do you want to continue? [Y/n]: ';
writeToStdout(`\n${fullPrompt}`);
return new Promise<boolean>((resolve) => {
rl.on('line', (answer) => {
rl.close();
resolve(['y', ''].includes(answer.trim().toLowerCase()));
});
});
}
async function getOauthConsentInteractive(prompt: string) {
const fullPrompt = prompt + '\n\nDo you want to continue?';
return new Promise<boolean>((resolve) => {
coreEvents.emitConsentRequest({
prompt: fullPrompt,
onConfirm: (confirmed: boolean) => {
resolve(confirmed);
},
});
});
}
export async function getOauthClient(
authType: AuthType,
config: Config,