@google/gemini-cli-core 0.6.0-nightly.20250910.a31830a3 → 0.6.0-preview.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -2
- package/README.md +12 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/src/code_assist/converter.d.ts +1 -0
- package/dist/src/code_assist/converter.js +1 -0
- package/dist/src/code_assist/converter.js.map +1 -1
- package/dist/src/code_assist/converter.test.js +10 -0
- package/dist/src/code_assist/converter.test.js.map +1 -1
- package/dist/src/code_assist/oauth-credential-storage.d.ts +5 -7
- package/dist/src/code_assist/oauth-credential-storage.js +5 -8
- package/dist/src/code_assist/oauth-credential-storage.js.map +1 -1
- package/dist/src/code_assist/oauth-credential-storage.test.js +35 -33
- package/dist/src/code_assist/oauth-credential-storage.test.js.map +1 -1
- package/dist/src/code_assist/oauth2.js +28 -2
- package/dist/src/code_assist/oauth2.js.map +1 -1
- package/dist/src/code_assist/oauth2.test.js +674 -536
- package/dist/src/code_assist/oauth2.test.js.map +1 -1
- package/dist/src/config/config.d.ts +32 -1
- package/dist/src/config/config.js +74 -17
- package/dist/src/config/config.js.map +1 -1
- package/dist/src/config/config.test.js +104 -16
- package/dist/src/config/config.test.js.map +1 -1
- package/dist/src/config/models.d.ts +15 -0
- package/dist/src/config/models.js +27 -0
- package/dist/src/config/models.js.map +1 -1
- package/dist/src/config/models.test.d.ts +6 -0
- package/dist/src/config/models.test.js +55 -0
- package/dist/src/config/models.test.js.map +1 -0
- package/dist/src/confirmation-bus/index.d.ts +7 -0
- package/dist/src/confirmation-bus/index.js +8 -0
- package/dist/src/confirmation-bus/index.js.map +1 -0
- package/dist/src/confirmation-bus/message-bus.d.ts +17 -0
- package/dist/src/confirmation-bus/message-bus.js +81 -0
- package/dist/src/confirmation-bus/message-bus.js.map +1 -0
- package/dist/src/confirmation-bus/message-bus.test.d.ts +6 -0
- package/dist/src/confirmation-bus/message-bus.test.js +164 -0
- package/dist/src/confirmation-bus/message-bus.test.js.map +1 -0
- package/dist/src/confirmation-bus/types.d.ts +38 -0
- package/dist/src/confirmation-bus/types.js +15 -0
- package/dist/src/confirmation-bus/types.js.map +1 -0
- package/dist/src/core/baseLlmClient.d.ts +1 -0
- package/dist/src/core/baseLlmClient.js +24 -0
- package/dist/src/core/baseLlmClient.js.map +1 -1
- package/dist/src/core/baseLlmClient.test.js +63 -0
- package/dist/src/core/baseLlmClient.test.js.map +1 -1
- package/dist/src/core/client.d.ts +5 -4
- package/dist/src/core/client.js +80 -140
- package/dist/src/core/client.js.map +1 -1
- package/dist/src/core/client.test.js +247 -186
- package/dist/src/core/client.test.js.map +1 -1
- package/dist/src/core/contentGenerator.d.ts +0 -1
- package/dist/src/core/contentGenerator.js +0 -4
- package/dist/src/core/contentGenerator.js.map +1 -1
- package/dist/src/core/contentGenerator.test.js +0 -3
- package/dist/src/core/contentGenerator.test.js.map +1 -1
- package/dist/src/core/coreToolScheduler.d.ts +4 -3
- package/dist/src/core/coreToolScheduler.js +42 -5
- package/dist/src/core/coreToolScheduler.js.map +1 -1
- package/dist/src/core/coreToolScheduler.test.js +43 -0
- package/dist/src/core/coreToolScheduler.test.js.map +1 -1
- package/dist/src/core/geminiChat.d.ts +3 -30
- package/dist/src/core/geminiChat.js +32 -228
- package/dist/src/core/geminiChat.js.map +1 -1
- package/dist/src/core/geminiChat.test.js +58 -489
- package/dist/src/core/geminiChat.test.js.map +1 -1
- package/dist/src/core/loggingContentGenerator.js +5 -5
- package/dist/src/core/loggingContentGenerator.js.map +1 -1
- package/dist/src/core/nonInteractiveToolExecutor.test.js +49 -0
- package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -1
- package/dist/src/core/subagent.js +1 -1
- package/dist/src/core/subagent.js.map +1 -1
- package/dist/src/core/subagent.test.js +9 -8
- package/dist/src/core/subagent.test.js.map +1 -1
- package/dist/src/core/turn.d.ts +2 -1
- package/dist/src/core/turn.js +2 -2
- package/dist/src/core/turn.js.map +1 -1
- package/dist/src/core/turn.test.js +18 -18
- package/dist/src/core/turn.test.js.map +1 -1
- package/dist/src/generated/git-commit.d.ts +2 -2
- package/dist/src/generated/git-commit.js +2 -2
- package/dist/src/generated/git-commit.js.map +1 -1
- package/dist/src/ide/constants.d.ts +1 -0
- package/dist/src/ide/constants.js +1 -0
- package/dist/src/ide/constants.js.map +1 -1
- package/dist/src/ide/ide-client.d.ts +51 -13
- package/dist/src/ide/ide-client.js +184 -37
- package/dist/src/ide/ide-client.js.map +1 -1
- package/dist/src/ide/ide-client.test.js +93 -3
- package/dist/src/ide/ide-client.test.js.map +1 -1
- package/dist/src/ide/ide-installer.js +8 -2
- package/dist/src/ide/ide-installer.js.map +1 -1
- package/dist/src/ide/ide-installer.test.js +13 -2
- package/dist/src/ide/ide-installer.test.js.map +1 -1
- package/dist/src/ide/ideContext.d.ts +34 -113
- package/dist/src/ide/ideContext.js +20 -78
- package/dist/src/ide/ideContext.js.map +1 -1
- package/dist/src/ide/ideContext.test.js +37 -39
- package/dist/src/ide/ideContext.test.js.map +1 -1
- package/dist/src/ide/types.d.ts +141 -0
- package/dist/src/ide/types.js +73 -0
- package/dist/src/ide/types.js.map +1 -1
- package/dist/src/index.d.ts +3 -1
- package/dist/src/index.js +3 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcp/oauth-token-storage.d.ts +2 -0
- package/dist/src/mcp/oauth-token-storage.js +25 -0
- package/dist/src/mcp/oauth-token-storage.js.map +1 -1
- package/dist/src/mcp/oauth-token-storage.test.js +251 -160
- package/dist/src/mcp/oauth-token-storage.test.js.map +1 -1
- package/dist/src/mcp/token-storage/index.d.ts +11 -0
- package/dist/src/mcp/token-storage/index.js +12 -0
- package/dist/src/mcp/token-storage/index.js.map +1 -0
- package/dist/src/output/json-formatter.d.ts +11 -0
- package/dist/src/output/json-formatter.js +30 -0
- package/dist/src/output/json-formatter.js.map +1 -0
- package/dist/src/output/json-formatter.test.d.ts +6 -0
- package/dist/src/output/json-formatter.test.js +266 -0
- package/dist/src/output/json-formatter.test.js.map +1 -0
- package/dist/src/output/types.d.ts +20 -0
- package/dist/src/output/types.js +11 -0
- package/dist/src/output/types.js.map +1 -0
- package/dist/src/policy/index.d.ts +7 -0
- package/dist/src/policy/index.js +8 -0
- package/dist/src/policy/index.js.map +1 -0
- package/dist/src/policy/policy-engine.d.ts +30 -0
- package/dist/src/policy/policy-engine.js +83 -0
- package/dist/src/policy/policy-engine.js.map +1 -0
- package/dist/src/policy/policy-engine.test.d.ts +6 -0
- package/dist/src/policy/policy-engine.test.js +470 -0
- package/dist/src/policy/policy-engine.test.js.map +1 -0
- package/dist/src/policy/stable-stringify.d.ts +58 -0
- package/dist/src/policy/stable-stringify.js +122 -0
- package/dist/src/policy/stable-stringify.js.map +1 -0
- package/dist/src/policy/types.d.ts +47 -0
- package/dist/src/policy/types.js +12 -0
- package/dist/src/policy/types.js.map +1 -0
- package/dist/src/routing/modelRouterService.d.ts +23 -0
- package/dist/src/routing/modelRouterService.js +70 -0
- package/dist/src/routing/modelRouterService.js.map +1 -0
- package/dist/src/routing/modelRouterService.test.d.ts +6 -0
- package/dist/src/routing/modelRouterService.test.js +98 -0
- package/dist/src/routing/modelRouterService.test.js.map +1 -0
- package/dist/src/routing/routingStrategy.d.ts +62 -0
- package/dist/src/routing/routingStrategy.js +7 -0
- package/dist/src/routing/routingStrategy.js.map +1 -0
- package/dist/src/routing/strategies/classifierStrategy.d.ts +12 -0
- package/dist/src/routing/strategies/classifierStrategy.js +173 -0
- package/dist/src/routing/strategies/classifierStrategy.js.map +1 -0
- package/dist/src/routing/strategies/classifierStrategy.test.d.ts +6 -0
- package/dist/src/routing/strategies/classifierStrategy.test.js +192 -0
- package/dist/src/routing/strategies/classifierStrategy.test.js.map +1 -0
- package/dist/src/routing/strategies/compositeStrategy.d.ts +26 -0
- package/dist/src/routing/strategies/compositeStrategy.js +67 -0
- package/dist/src/routing/strategies/compositeStrategy.js.map +1 -0
- package/dist/src/routing/strategies/compositeStrategy.test.d.ts +6 -0
- package/dist/src/routing/strategies/compositeStrategy.test.js +123 -0
- package/dist/src/routing/strategies/compositeStrategy.test.js.map +1 -0
- package/dist/src/routing/strategies/defaultStrategy.d.ts +12 -0
- package/dist/src/routing/strategies/defaultStrategy.js +20 -0
- package/dist/src/routing/strategies/defaultStrategy.js.map +1 -0
- package/dist/src/routing/strategies/defaultStrategy.test.d.ts +6 -0
- package/dist/src/routing/strategies/defaultStrategy.test.js +26 -0
- package/dist/src/routing/strategies/defaultStrategy.test.js.map +1 -0
- package/dist/src/routing/strategies/fallbackStrategy.d.ts +12 -0
- package/dist/src/routing/strategies/fallbackStrategy.js +25 -0
- package/dist/src/routing/strategies/fallbackStrategy.js.map +1 -0
- package/dist/src/routing/strategies/fallbackStrategy.test.d.ts +6 -0
- package/dist/src/routing/strategies/fallbackStrategy.test.js +55 -0
- package/dist/src/routing/strategies/fallbackStrategy.test.js.map +1 -0
- package/dist/src/routing/strategies/overrideStrategy.d.ts +15 -0
- package/dist/src/routing/strategies/overrideStrategy.js +28 -0
- package/dist/src/routing/strategies/overrideStrategy.js.map +1 -0
- package/dist/src/routing/strategies/overrideStrategy.test.d.ts +6 -0
- package/dist/src/routing/strategies/overrideStrategy.test.js +42 -0
- package/dist/src/routing/strategies/overrideStrategy.test.js.map +1 -0
- package/dist/src/services/chatRecordingService.d.ts +2 -1
- package/dist/src/services/chatRecordingService.js +3 -3
- package/dist/src/services/chatRecordingService.js.map +1 -1
- package/dist/src/services/chatRecordingService.test.js +8 -3
- package/dist/src/services/chatRecordingService.test.js.map +1 -1
- package/dist/src/services/fileDiscoveryService.d.ts +10 -0
- package/dist/src/services/fileDiscoveryService.js +31 -17
- package/dist/src/services/fileDiscoveryService.js.map +1 -1
- package/dist/src/services/gitService.js +9 -12
- package/dist/src/services/gitService.js.map +1 -1
- package/dist/src/services/gitService.test.js +10 -20
- package/dist/src/services/gitService.test.js.map +1 -1
- package/dist/src/services/loopDetectionService.d.ts +5 -0
- package/dist/src/services/loopDetectionService.js +36 -20
- package/dist/src/services/loopDetectionService.js.map +1 -1
- package/dist/src/services/loopDetectionService.test.js +41 -12
- package/dist/src/services/loopDetectionService.test.js.map +1 -1
- package/dist/src/services/shellExecutionService.d.ts +34 -2
- package/dist/src/services/shellExecutionService.js +177 -43
- package/dist/src/services/shellExecutionService.js.map +1 -1
- package/dist/src/services/shellExecutionService.test.js +153 -56
- package/dist/src/services/shellExecutionService.test.js.map +1 -1
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +10 -2
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +85 -5
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +63 -5
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -1
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +12 -2
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +31 -2
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
- package/dist/src/telemetry/constants.d.ts +3 -0
- package/dist/src/telemetry/constants.js +3 -0
- package/dist/src/telemetry/constants.js.map +1 -1
- package/dist/src/telemetry/gcp-exporters.d.ts +34 -0
- package/dist/src/telemetry/gcp-exporters.js +117 -0
- package/dist/src/telemetry/gcp-exporters.js.map +1 -0
- package/dist/src/telemetry/gcp-exporters.test.d.ts +6 -0
- package/dist/src/telemetry/gcp-exporters.test.js +318 -0
- package/dist/src/telemetry/gcp-exporters.test.js.map +1 -0
- package/dist/src/telemetry/index.d.ts +3 -2
- package/dist/src/telemetry/index.js +3 -2
- package/dist/src/telemetry/index.js.map +1 -1
- package/dist/src/telemetry/loggers.d.ts +4 -1
- package/dist/src/telemetry/loggers.js +42 -7
- package/dist/src/telemetry/loggers.js.map +1 -1
- package/dist/src/telemetry/loggers.test.js +84 -36
- package/dist/src/telemetry/loggers.test.js.map +1 -1
- package/dist/src/telemetry/metrics.d.ts +3 -1
- package/dist/src/telemetry/metrics.js +32 -3
- package/dist/src/telemetry/metrics.js.map +1 -1
- package/dist/src/telemetry/metrics.test.js +42 -0
- package/dist/src/telemetry/metrics.test.js.map +1 -1
- package/dist/src/telemetry/sdk.js +16 -1
- package/dist/src/telemetry/sdk.js.map +1 -1
- package/dist/src/telemetry/sdk.test.js +95 -0
- package/dist/src/telemetry/sdk.test.js.map +1 -1
- package/dist/src/telemetry/types.d.ts +47 -3
- package/dist/src/telemetry/types.js +67 -3
- package/dist/src/telemetry/types.js.map +1 -1
- package/dist/src/tools/edit.js +6 -5
- package/dist/src/tools/edit.js.map +1 -1
- package/dist/src/tools/edit.test.js +79 -9
- package/dist/src/tools/edit.test.js.map +1 -1
- package/dist/src/tools/glob.d.ts +5 -1
- package/dist/src/tools/glob.js +24 -17
- package/dist/src/tools/glob.js.map +1 -1
- package/dist/src/tools/glob.test.js +51 -0
- package/dist/src/tools/glob.test.js.map +1 -1
- package/dist/src/tools/ls.js +19 -32
- package/dist/src/tools/ls.js.map +1 -1
- package/dist/src/tools/ls.test.js +140 -280
- package/dist/src/tools/ls.test.js.map +1 -1
- package/dist/src/tools/read-many-files.d.ts +1 -1
- package/dist/src/tools/read-many-files.js +17 -49
- package/dist/src/tools/read-many-files.js.map +1 -1
- package/dist/src/tools/ripGrep.d.ts +4 -0
- package/dist/src/tools/ripGrep.js +11 -1
- package/dist/src/tools/ripGrep.js.map +1 -1
- package/dist/src/tools/ripGrep.test.js +51 -1
- package/dist/src/tools/ripGrep.test.js.map +1 -1
- package/dist/src/tools/shell.d.ts +12 -2
- package/dist/src/tools/shell.js +20 -27
- package/dist/src/tools/shell.js.map +1 -1
- package/dist/src/tools/shell.test.js +33 -68
- package/dist/src/tools/shell.test.js.map +1 -1
- package/dist/src/tools/smart-edit.d.ts +0 -1
- package/dist/src/tools/smart-edit.js +5 -18
- package/dist/src/tools/smart-edit.js.map +1 -1
- package/dist/src/tools/smart-edit.test.js +18 -9
- package/dist/src/tools/smart-edit.test.js.map +1 -1
- package/dist/src/tools/tools.d.ts +7 -5
- package/dist/src/tools/tools.js +2 -2
- package/dist/src/tools/tools.js.map +1 -1
- package/dist/src/tools/write-file.js +4 -5
- package/dist/src/tools/write-file.js.map +1 -1
- package/dist/src/tools/write-file.test.js +94 -10
- package/dist/src/tools/write-file.test.js.map +1 -1
- package/dist/src/utils/bfsFileSearch.js +11 -5
- package/dist/src/utils/bfsFileSearch.js.map +1 -1
- package/dist/src/utils/editCorrector.d.ts +7 -6
- package/dist/src/utils/editCorrector.js +61 -18
- package/dist/src/utils/editCorrector.js.map +1 -1
- package/dist/src/utils/editCorrector.test.js +30 -79
- package/dist/src/utils/editCorrector.test.js.map +1 -1
- package/dist/src/utils/editor.js +31 -44
- package/dist/src/utils/editor.js.map +1 -1
- package/dist/src/utils/editor.test.js +61 -75
- package/dist/src/utils/editor.test.js.map +1 -1
- package/dist/src/utils/errorParsing.js +2 -2
- package/dist/src/utils/errorParsing.js.map +1 -1
- package/dist/src/utils/errorParsing.test.js +7 -7
- package/dist/src/utils/errorParsing.test.js.map +1 -1
- package/dist/src/utils/errors.d.ts +6 -0
- package/dist/src/utils/errors.js +10 -0
- package/dist/src/utils/errors.js.map +1 -1
- package/dist/src/utils/fileUtils.test.js +17 -8
- package/dist/src/utils/fileUtils.test.js.map +1 -1
- package/dist/src/utils/geminiIgnoreParser.d.ts +18 -0
- package/dist/src/utils/geminiIgnoreParser.js +61 -0
- package/dist/src/utils/geminiIgnoreParser.js.map +1 -0
- package/dist/src/utils/geminiIgnoreParser.test.d.ts +6 -0
- package/dist/src/utils/geminiIgnoreParser.test.js +50 -0
- package/dist/src/utils/geminiIgnoreParser.test.js.map +1 -0
- package/dist/src/utils/gitIgnoreParser.d.ts +3 -9
- package/dist/src/utils/gitIgnoreParser.js +60 -69
- package/dist/src/utils/gitIgnoreParser.js.map +1 -1
- package/dist/src/utils/gitIgnoreParser.test.js +18 -53
- package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
- package/dist/src/utils/memoryDiscovery.test.js +12 -6
- package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
- package/dist/src/utils/nextSpeakerChecker.d.ts +2 -2
- package/dist/src/utils/nextSpeakerChecker.js +8 -2
- package/dist/src/utils/nextSpeakerChecker.js.map +1 -1
- package/dist/src/utils/nextSpeakerChecker.test.js +40 -33
- package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -1
- package/dist/src/utils/shell-utils.d.ts +5 -0
- package/dist/src/utils/shell-utils.js +23 -0
- package/dist/src/utils/shell-utils.js.map +1 -1
- package/dist/src/utils/terminalSerializer.d.ts +28 -0
- package/dist/src/utils/terminalSerializer.js +432 -0
- package/dist/src/utils/terminalSerializer.js.map +1 -0
- package/dist/src/utils/terminalSerializer.test.d.ts +6 -0
- package/dist/src/utils/terminalSerializer.test.js +176 -0
- package/dist/src/utils/terminalSerializer.test.js.map +1 -0
- package/dist/src/utils/textUtils.d.ts +5 -0
- package/dist/src/utils/textUtils.js +14 -0
- package/dist/src/utils/textUtils.js.map +1 -1
- package/dist/src/utils/textUtils.test.d.ts +6 -0
- package/dist/src/utils/textUtils.test.js +59 -0
- package/dist/src/utils/textUtils.test.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -1
- package/dist/src/utils/ide-trust.d.ts +0 -10
- package/dist/src/utils/ide-trust.js +0 -14
- package/dist/src/utils/ide-trust.js.map +0 -1
|
@@ -15,6 +15,7 @@ import crypto from 'node:crypto';
|
|
|
15
15
|
import * as os from 'node:os';
|
|
16
16
|
import { AuthType } from '../core/contentGenerator.js';
|
|
17
17
|
import readline from 'node:readline';
|
|
18
|
+
import { FORCE_ENCRYPTED_FILE_ENV_VAR } from '../mcp/token-storage/index.js';
|
|
18
19
|
vi.mock('os', async (importOriginal) => {
|
|
19
20
|
const os = await importOriginal();
|
|
20
21
|
return {
|
|
@@ -30,6 +31,13 @@ vi.mock('node:readline');
|
|
|
30
31
|
vi.mock('../utils/browser.js', () => ({
|
|
31
32
|
shouldAttemptBrowserLaunch: () => true,
|
|
32
33
|
}));
|
|
34
|
+
vi.mock('./oauth-credential-storage.js', () => ({
|
|
35
|
+
OAuthCredentialStorage: {
|
|
36
|
+
saveCredentials: vi.fn(),
|
|
37
|
+
loadCredentials: vi.fn(),
|
|
38
|
+
clearCredentials: vi.fn(),
|
|
39
|
+
},
|
|
40
|
+
}));
|
|
33
41
|
const mockConfig = {
|
|
34
42
|
getNoBrowser: () => false,
|
|
35
43
|
getProxy: () => 'http://test.proxy.com:8080',
|
|
@@ -38,498 +46,665 @@ const mockConfig = {
|
|
|
38
46
|
// Mock fetch globally
|
|
39
47
|
global.fetch = vi.fn();
|
|
40
48
|
describe('oauth2', () => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
|
|
44
|
-
os.homedir.mockReturnValue(tempHomeDir);
|
|
45
|
-
});
|
|
46
|
-
afterEach(() => {
|
|
47
|
-
fs.rmSync(tempHomeDir, { recursive: true, force: true });
|
|
48
|
-
vi.clearAllMocks();
|
|
49
|
-
resetOauthClientForTesting();
|
|
50
|
-
vi.unstubAllEnvs();
|
|
51
|
-
});
|
|
52
|
-
it('should perform a web login', async () => {
|
|
53
|
-
const mockAuthUrl = 'https://example.com/auth';
|
|
54
|
-
const mockCode = 'test-code';
|
|
55
|
-
const mockState = 'test-state';
|
|
56
|
-
const mockTokens = {
|
|
57
|
-
access_token: 'test-access-token',
|
|
58
|
-
refresh_token: 'test-refresh-token',
|
|
59
|
-
};
|
|
60
|
-
const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
|
|
61
|
-
const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
|
|
62
|
-
const mockSetCredentials = vi.fn();
|
|
63
|
-
const mockGetAccessToken = vi
|
|
64
|
-
.fn()
|
|
65
|
-
.mockResolvedValue({ token: 'mock-access-token' });
|
|
66
|
-
const mockOAuth2Client = {
|
|
67
|
-
generateAuthUrl: mockGenerateAuthUrl,
|
|
68
|
-
getToken: mockGetToken,
|
|
69
|
-
setCredentials: mockSetCredentials,
|
|
70
|
-
getAccessToken: mockGetAccessToken,
|
|
71
|
-
credentials: mockTokens,
|
|
72
|
-
on: vi.fn(),
|
|
73
|
-
};
|
|
74
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
75
|
-
vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
|
|
76
|
-
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
77
|
-
// Mock the UserInfo API response
|
|
78
|
-
global.fetch.mockResolvedValue({
|
|
79
|
-
ok: true,
|
|
80
|
-
json: vi
|
|
81
|
-
.fn()
|
|
82
|
-
.mockResolvedValue({ email: 'test-google-account@gmail.com' }),
|
|
83
|
-
});
|
|
84
|
-
let requestCallback;
|
|
85
|
-
let serverListeningCallback;
|
|
86
|
-
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
87
|
-
let capturedPort = 0;
|
|
88
|
-
const mockHttpServer = {
|
|
89
|
-
listen: vi.fn((port, _host, callback) => {
|
|
90
|
-
capturedPort = port;
|
|
91
|
-
if (callback) {
|
|
92
|
-
callback();
|
|
93
|
-
}
|
|
94
|
-
serverListeningCallback(undefined);
|
|
95
|
-
}),
|
|
96
|
-
close: vi.fn((callback) => {
|
|
97
|
-
if (callback) {
|
|
98
|
-
callback();
|
|
99
|
-
}
|
|
100
|
-
}),
|
|
101
|
-
on: vi.fn(),
|
|
102
|
-
address: () => ({ port: capturedPort }),
|
|
103
|
-
};
|
|
104
|
-
http.createServer.mockImplementation((cb) => {
|
|
105
|
-
requestCallback = cb;
|
|
106
|
-
return mockHttpServer;
|
|
107
|
-
});
|
|
108
|
-
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
109
|
-
// wait for server to start listening.
|
|
110
|
-
await serverListeningPromise;
|
|
111
|
-
const mockReq = {
|
|
112
|
-
url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
|
|
113
|
-
};
|
|
114
|
-
const mockRes = {
|
|
115
|
-
writeHead: vi.fn(),
|
|
116
|
-
end: vi.fn(),
|
|
117
|
-
};
|
|
118
|
-
await requestCallback(mockReq, mockRes);
|
|
119
|
-
const client = await clientPromise;
|
|
120
|
-
expect(client).toBe(mockOAuth2Client);
|
|
121
|
-
expect(open).toHaveBeenCalledWith(mockAuthUrl);
|
|
122
|
-
expect(mockGetToken).toHaveBeenCalledWith({
|
|
123
|
-
code: mockCode,
|
|
124
|
-
redirect_uri: `http://localhost:${capturedPort}/oauth2callback`,
|
|
125
|
-
});
|
|
126
|
-
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
|
|
127
|
-
// Verify Google Account was cached
|
|
128
|
-
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
129
|
-
expect(fs.existsSync(googleAccountPath)).toBe(true);
|
|
130
|
-
const cachedGoogleAccount = fs.readFileSync(googleAccountPath, 'utf-8');
|
|
131
|
-
expect(JSON.parse(cachedGoogleAccount)).toEqual({
|
|
132
|
-
active: 'test-google-account@gmail.com',
|
|
133
|
-
old: [],
|
|
134
|
-
});
|
|
135
|
-
// Verify the getCachedGoogleAccount function works
|
|
136
|
-
const userAccountManager = new UserAccountManager();
|
|
137
|
-
expect(userAccountManager.getCachedGoogleAccount()).toBe('test-google-account@gmail.com');
|
|
138
|
-
});
|
|
139
|
-
it('should perform login with user code', async () => {
|
|
140
|
-
const mockConfigWithNoBrowser = {
|
|
141
|
-
getNoBrowser: () => true,
|
|
142
|
-
getProxy: () => 'http://test.proxy.com:8080',
|
|
143
|
-
isBrowserLaunchSuppressed: () => true,
|
|
144
|
-
};
|
|
145
|
-
const mockCodeVerifier = {
|
|
146
|
-
codeChallenge: 'test-challenge',
|
|
147
|
-
codeVerifier: 'test-verifier',
|
|
148
|
-
};
|
|
149
|
-
const mockAuthUrl = 'https://example.com/auth-user-code';
|
|
150
|
-
const mockCode = 'test-user-code';
|
|
151
|
-
const mockTokens = {
|
|
152
|
-
access_token: 'test-access-token-user-code',
|
|
153
|
-
refresh_token: 'test-refresh-token-user-code',
|
|
154
|
-
};
|
|
155
|
-
const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
|
|
156
|
-
const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
|
|
157
|
-
const mockSetCredentials = vi.fn();
|
|
158
|
-
const mockGenerateCodeVerifierAsync = vi
|
|
159
|
-
.fn()
|
|
160
|
-
.mockResolvedValue(mockCodeVerifier);
|
|
161
|
-
const mockOAuth2Client = {
|
|
162
|
-
generateAuthUrl: mockGenerateAuthUrl,
|
|
163
|
-
getToken: mockGetToken,
|
|
164
|
-
setCredentials: mockSetCredentials,
|
|
165
|
-
generateCodeVerifierAsync: mockGenerateCodeVerifierAsync,
|
|
166
|
-
on: vi.fn(),
|
|
167
|
-
};
|
|
168
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
169
|
-
const mockReadline = {
|
|
170
|
-
question: vi.fn((_query, callback) => callback(mockCode)),
|
|
171
|
-
close: vi.fn(),
|
|
172
|
-
};
|
|
173
|
-
readline.createInterface.mockReturnValue(mockReadline);
|
|
174
|
-
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
175
|
-
const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser);
|
|
176
|
-
expect(client).toBe(mockOAuth2Client);
|
|
177
|
-
// Verify the auth flow
|
|
178
|
-
expect(mockGenerateCodeVerifierAsync).toHaveBeenCalled();
|
|
179
|
-
expect(mockGenerateAuthUrl).toHaveBeenCalled();
|
|
180
|
-
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(mockAuthUrl));
|
|
181
|
-
expect(mockReadline.question).toHaveBeenCalledWith('Enter the authorization code: ', expect.any(Function));
|
|
182
|
-
expect(mockGetToken).toHaveBeenCalledWith({
|
|
183
|
-
code: mockCode,
|
|
184
|
-
codeVerifier: mockCodeVerifier.codeVerifier,
|
|
185
|
-
redirect_uri: 'https://codeassist.google.com/authcode',
|
|
186
|
-
});
|
|
187
|
-
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
|
|
188
|
-
consoleLogSpy.mockRestore();
|
|
189
|
-
});
|
|
190
|
-
describe('in Cloud Shell', () => {
|
|
191
|
-
const mockGetAccessToken = vi.fn();
|
|
192
|
-
let mockComputeClient;
|
|
49
|
+
describe('with encrypted flag false', () => {
|
|
50
|
+
let tempHomeDir;
|
|
193
51
|
beforeEach(() => {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
getAccessToken: mockGetAccessToken,
|
|
198
|
-
};
|
|
199
|
-
Compute.mockImplementation(() => mockComputeClient);
|
|
200
|
-
});
|
|
201
|
-
it('should attempt to load cached credentials first', async () => {
|
|
202
|
-
const cachedCreds = { refresh_token: 'cached-token' };
|
|
203
|
-
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
204
|
-
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
205
|
-
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
206
|
-
const mockClient = {
|
|
207
|
-
setCredentials: vi.fn(),
|
|
208
|
-
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
209
|
-
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
210
|
-
on: vi.fn(),
|
|
211
|
-
};
|
|
212
|
-
// To mock the new OAuth2Client() inside the function
|
|
213
|
-
OAuth2Client.mockImplementation(() => mockClient);
|
|
214
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
215
|
-
expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
216
|
-
expect(mockClient.getAccessToken).toHaveBeenCalled();
|
|
217
|
-
expect(mockClient.getTokenInfo).toHaveBeenCalled();
|
|
218
|
-
expect(Compute).not.toHaveBeenCalled(); // Should not fetch new client if cache is valid
|
|
52
|
+
process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] = 'false';
|
|
53
|
+
tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
|
|
54
|
+
os.homedir.mockReturnValue(tempHomeDir);
|
|
219
55
|
});
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
56
|
+
afterEach(() => {
|
|
57
|
+
fs.rmSync(tempHomeDir, { recursive: true, force: true });
|
|
58
|
+
vi.clearAllMocks();
|
|
59
|
+
resetOauthClientForTesting();
|
|
60
|
+
vi.unstubAllEnvs();
|
|
224
61
|
});
|
|
225
|
-
it('should
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
});
|
|
233
|
-
it('should return the Compute client on successful ADC authentication', async () => {
|
|
234
|
-
const client = await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
|
|
235
|
-
expect(client).toBe(mockComputeClient);
|
|
236
|
-
});
|
|
237
|
-
it('should throw an error if ADC fails', async () => {
|
|
238
|
-
const testError = new Error('ADC Failed');
|
|
239
|
-
mockGetAccessToken.mockRejectedValue(testError);
|
|
240
|
-
await expect(getOauthClient(AuthType.CLOUD_SHELL, mockConfig)).rejects.toThrow('Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ADC Failed');
|
|
241
|
-
});
|
|
242
|
-
});
|
|
243
|
-
describe('credential loading order', () => {
|
|
244
|
-
it('should prioritize default cached credentials over GOOGLE_APPLICATION_CREDENTIALS', async () => {
|
|
245
|
-
// Setup default cached credentials
|
|
246
|
-
const defaultCreds = { refresh_token: 'default-cached-token' };
|
|
247
|
-
const defaultCredsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
248
|
-
await fs.promises.mkdir(path.dirname(defaultCredsPath), {
|
|
249
|
-
recursive: true,
|
|
250
|
-
});
|
|
251
|
-
await fs.promises.writeFile(defaultCredsPath, JSON.stringify(defaultCreds));
|
|
252
|
-
// Setup credentials via environment variable
|
|
253
|
-
const envCreds = { refresh_token: 'env-var-token' };
|
|
254
|
-
const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
|
|
255
|
-
await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
|
|
256
|
-
vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
|
|
257
|
-
const mockClient = {
|
|
258
|
-
setCredentials: vi.fn(),
|
|
259
|
-
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
260
|
-
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
261
|
-
on: vi.fn(),
|
|
262
|
-
};
|
|
263
|
-
OAuth2Client.mockImplementation(() => mockClient);
|
|
264
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
265
|
-
// Assert the correct credentials were used
|
|
266
|
-
expect(mockClient.setCredentials).toHaveBeenCalledWith(defaultCreds);
|
|
267
|
-
expect(mockClient.setCredentials).not.toHaveBeenCalledWith(envCreds);
|
|
268
|
-
});
|
|
269
|
-
it('should fall back to GOOGLE_APPLICATION_CREDENTIALS if default cache is missing', async () => {
|
|
270
|
-
// Setup credentials via environment variable
|
|
271
|
-
const envCreds = { refresh_token: 'env-var-token' };
|
|
272
|
-
const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
|
|
273
|
-
await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
|
|
274
|
-
vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
|
|
275
|
-
const mockClient = {
|
|
276
|
-
setCredentials: vi.fn(),
|
|
277
|
-
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
278
|
-
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
279
|
-
on: vi.fn(),
|
|
62
|
+
it('should perform a web login', async () => {
|
|
63
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
64
|
+
const mockCode = 'test-code';
|
|
65
|
+
const mockState = 'test-state';
|
|
66
|
+
const mockTokens = {
|
|
67
|
+
access_token: 'test-access-token',
|
|
68
|
+
refresh_token: 'test-refresh-token',
|
|
280
69
|
};
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
// Assert the correct credentials were used
|
|
284
|
-
expect(mockClient.setCredentials).toHaveBeenCalledWith(envCreds);
|
|
285
|
-
});
|
|
286
|
-
});
|
|
287
|
-
describe('with GCP environment variables', () => {
|
|
288
|
-
it('should use GOOGLE_CLOUD_ACCESS_TOKEN when GOOGLE_GENAI_USE_GCA is true', async () => {
|
|
289
|
-
vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
|
|
290
|
-
vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
|
|
70
|
+
const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
|
|
71
|
+
const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
|
|
291
72
|
const mockSetCredentials = vi.fn();
|
|
292
73
|
const mockGetAccessToken = vi
|
|
293
74
|
.fn()
|
|
294
|
-
.mockResolvedValue({ token: '
|
|
75
|
+
.mockResolvedValue({ token: 'mock-access-token' });
|
|
295
76
|
const mockOAuth2Client = {
|
|
77
|
+
generateAuthUrl: mockGenerateAuthUrl,
|
|
78
|
+
getToken: mockGetToken,
|
|
296
79
|
setCredentials: mockSetCredentials,
|
|
297
80
|
getAccessToken: mockGetAccessToken,
|
|
81
|
+
credentials: mockTokens,
|
|
298
82
|
on: vi.fn(),
|
|
299
83
|
};
|
|
300
84
|
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
301
|
-
|
|
85
|
+
vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
|
|
86
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
87
|
+
// Mock the UserInfo API response
|
|
302
88
|
global.fetch.mockResolvedValue({
|
|
303
89
|
ok: true,
|
|
304
90
|
json: vi
|
|
305
91
|
.fn()
|
|
306
|
-
.mockResolvedValue({ email: 'test-
|
|
307
|
-
});
|
|
308
|
-
const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
309
|
-
expect(client).toBe(mockOAuth2Client);
|
|
310
|
-
expect(mockSetCredentials).toHaveBeenCalledWith({
|
|
311
|
-
access_token: 'gcp-access-token',
|
|
312
|
-
});
|
|
313
|
-
// Verify fetchAndCacheUserInfo was effectively called
|
|
314
|
-
expect(mockGetAccessToken).toHaveBeenCalled();
|
|
315
|
-
expect(global.fetch).toHaveBeenCalledWith('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
316
|
-
headers: {
|
|
317
|
-
Authorization: 'Bearer gcp-access-token',
|
|
318
|
-
},
|
|
319
|
-
});
|
|
320
|
-
// Verify Google Account was cached
|
|
321
|
-
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
322
|
-
const cachedContent = fs.readFileSync(googleAccountPath, 'utf-8');
|
|
323
|
-
expect(JSON.parse(cachedContent)).toEqual({
|
|
324
|
-
active: 'test-gcp-account@gmail.com',
|
|
325
|
-
old: [],
|
|
92
|
+
.mockResolvedValue({ email: 'test-google-account@gmail.com' }),
|
|
326
93
|
});
|
|
327
|
-
});
|
|
328
|
-
it('should not use GCP token if GOOGLE_CLOUD_ACCESS_TOKEN is not set', async () => {
|
|
329
|
-
vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
|
|
330
|
-
const mockSetCredentials = vi.fn();
|
|
331
|
-
const mockGetAccessToken = vi
|
|
332
|
-
.fn()
|
|
333
|
-
.mockResolvedValue({ token: 'cached-access-token' });
|
|
334
|
-
const mockGetTokenInfo = vi.fn().mockResolvedValue({});
|
|
335
|
-
const mockOAuth2Client = {
|
|
336
|
-
setCredentials: mockSetCredentials,
|
|
337
|
-
getAccessToken: mockGetAccessToken,
|
|
338
|
-
getTokenInfo: mockGetTokenInfo,
|
|
339
|
-
on: vi.fn(),
|
|
340
|
-
};
|
|
341
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
342
|
-
// Make it fall through to cached credentials path
|
|
343
|
-
const cachedCreds = { refresh_token: 'cached-token' };
|
|
344
|
-
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
345
|
-
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
346
|
-
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
347
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
348
|
-
// It should be called with the cached credentials, not the GCP access token.
|
|
349
|
-
expect(mockSetCredentials).toHaveBeenCalledTimes(1);
|
|
350
|
-
expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
351
|
-
});
|
|
352
|
-
it('should not use GCP token if GOOGLE_GENAI_USE_GCA is not set', async () => {
|
|
353
|
-
vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
|
|
354
|
-
const mockSetCredentials = vi.fn();
|
|
355
|
-
const mockGetAccessToken = vi
|
|
356
|
-
.fn()
|
|
357
|
-
.mockResolvedValue({ token: 'cached-access-token' });
|
|
358
|
-
const mockGetTokenInfo = vi.fn().mockResolvedValue({});
|
|
359
|
-
const mockOAuth2Client = {
|
|
360
|
-
setCredentials: mockSetCredentials,
|
|
361
|
-
getAccessToken: mockGetAccessToken,
|
|
362
|
-
getTokenInfo: mockGetTokenInfo,
|
|
363
|
-
on: vi.fn(),
|
|
364
|
-
};
|
|
365
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
366
|
-
// Make it fall through to cached credentials path
|
|
367
|
-
const cachedCreds = { refresh_token: 'cached-token' };
|
|
368
|
-
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
369
|
-
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
370
|
-
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
371
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
372
|
-
// It should be called with the cached credentials, not the GCP access token.
|
|
373
|
-
expect(mockSetCredentials).toHaveBeenCalledTimes(1);
|
|
374
|
-
expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
375
|
-
});
|
|
376
|
-
});
|
|
377
|
-
describe('error handling', () => {
|
|
378
|
-
it('should handle browser launch failure with FatalAuthenticationError', async () => {
|
|
379
|
-
const mockError = new Error('Browser launch failed');
|
|
380
|
-
open.mockRejectedValue(mockError);
|
|
381
|
-
const mockOAuth2Client = {
|
|
382
|
-
generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
|
|
383
|
-
on: vi.fn(),
|
|
384
|
-
};
|
|
385
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
386
|
-
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Failed to open browser: Browser launch failed');
|
|
387
|
-
});
|
|
388
|
-
it('should handle authentication timeout with proper error message', async () => {
|
|
389
|
-
const mockAuthUrl = 'https://example.com/auth';
|
|
390
|
-
const mockOAuth2Client = {
|
|
391
|
-
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
392
|
-
on: vi.fn(),
|
|
393
|
-
};
|
|
394
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
395
|
-
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
396
|
-
const mockHttpServer = {
|
|
397
|
-
listen: vi.fn(),
|
|
398
|
-
close: vi.fn(),
|
|
399
|
-
on: vi.fn(),
|
|
400
|
-
address: () => ({ port: 3000 }),
|
|
401
|
-
};
|
|
402
|
-
http.createServer.mockImplementation(() => mockHttpServer);
|
|
403
|
-
// Mock setTimeout to trigger timeout immediately
|
|
404
|
-
const originalSetTimeout = global.setTimeout;
|
|
405
|
-
global.setTimeout = vi.fn((callback) => (callback(), {}));
|
|
406
|
-
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Authentication timed out after 5 minutes. The browser tab may have gotten stuck in a loading state. Please try again or use NO_BROWSER=true for manual authentication.');
|
|
407
|
-
global.setTimeout = originalSetTimeout;
|
|
408
|
-
});
|
|
409
|
-
it('should handle OAuth callback errors with descriptive messages', async () => {
|
|
410
|
-
const mockAuthUrl = 'https://example.com/auth';
|
|
411
|
-
const mockOAuth2Client = {
|
|
412
|
-
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
413
|
-
on: vi.fn(),
|
|
414
|
-
};
|
|
415
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
416
|
-
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
417
94
|
let requestCallback;
|
|
418
95
|
let serverListeningCallback;
|
|
419
96
|
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
97
|
+
let capturedPort = 0;
|
|
420
98
|
const mockHttpServer = {
|
|
421
|
-
listen: vi.fn((
|
|
422
|
-
|
|
99
|
+
listen: vi.fn((port, _host, callback) => {
|
|
100
|
+
capturedPort = port;
|
|
101
|
+
if (callback) {
|
|
423
102
|
callback();
|
|
103
|
+
}
|
|
424
104
|
serverListeningCallback(undefined);
|
|
425
105
|
}),
|
|
426
|
-
close: vi.fn()
|
|
106
|
+
close: vi.fn((callback) => {
|
|
107
|
+
if (callback) {
|
|
108
|
+
callback();
|
|
109
|
+
}
|
|
110
|
+
}),
|
|
427
111
|
on: vi.fn(),
|
|
428
|
-
address: () => ({ port:
|
|
112
|
+
address: () => ({ port: capturedPort }),
|
|
429
113
|
};
|
|
430
114
|
http.createServer.mockImplementation((cb) => {
|
|
431
115
|
requestCallback = cb;
|
|
432
116
|
return mockHttpServer;
|
|
433
117
|
});
|
|
434
118
|
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
119
|
+
// wait for server to start listening.
|
|
435
120
|
await serverListeningPromise;
|
|
436
|
-
// Test OAuth error with description
|
|
437
121
|
const mockReq = {
|
|
438
|
-
url:
|
|
122
|
+
url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
|
|
439
123
|
};
|
|
440
124
|
const mockRes = {
|
|
441
125
|
writeHead: vi.fn(),
|
|
442
126
|
end: vi.fn(),
|
|
443
127
|
};
|
|
444
|
-
await
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
128
|
+
await requestCallback(mockReq, mockRes);
|
|
129
|
+
const client = await clientPromise;
|
|
130
|
+
expect(client).toBe(mockOAuth2Client);
|
|
131
|
+
expect(open).toHaveBeenCalledWith(mockAuthUrl);
|
|
132
|
+
expect(mockGetToken).toHaveBeenCalledWith({
|
|
133
|
+
code: mockCode,
|
|
134
|
+
redirect_uri: `http://localhost:${capturedPort}/oauth2callback`,
|
|
135
|
+
});
|
|
136
|
+
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
|
|
137
|
+
// Verify Google Account was cached
|
|
138
|
+
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
139
|
+
expect(fs.existsSync(googleAccountPath)).toBe(true);
|
|
140
|
+
const cachedGoogleAccount = fs.readFileSync(googleAccountPath, 'utf-8');
|
|
141
|
+
expect(JSON.parse(cachedGoogleAccount)).toEqual({
|
|
142
|
+
active: 'test-google-account@gmail.com',
|
|
143
|
+
old: [],
|
|
144
|
+
});
|
|
145
|
+
// Verify the getCachedGoogleAccount function works
|
|
146
|
+
const userAccountManager = new UserAccountManager();
|
|
147
|
+
expect(userAccountManager.getCachedGoogleAccount()).toBe('test-google-account@gmail.com');
|
|
448
148
|
});
|
|
449
|
-
it('should
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
};
|
|
455
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
456
|
-
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
457
|
-
let requestCallback;
|
|
458
|
-
let serverListeningCallback;
|
|
459
|
-
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
460
|
-
const mockHttpServer = {
|
|
461
|
-
listen: vi.fn((_port, _host, callback) => {
|
|
462
|
-
if (callback)
|
|
463
|
-
callback();
|
|
464
|
-
serverListeningCallback(undefined);
|
|
465
|
-
}),
|
|
466
|
-
close: vi.fn(),
|
|
467
|
-
on: vi.fn(),
|
|
468
|
-
address: () => ({ port: 3000 }),
|
|
149
|
+
it('should perform login with user code', async () => {
|
|
150
|
+
const mockConfigWithNoBrowser = {
|
|
151
|
+
getNoBrowser: () => true,
|
|
152
|
+
getProxy: () => 'http://test.proxy.com:8080',
|
|
153
|
+
isBrowserLaunchSuppressed: () => true,
|
|
469
154
|
};
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
});
|
|
474
|
-
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
475
|
-
await serverListeningPromise;
|
|
476
|
-
// Test OAuth error without description
|
|
477
|
-
const mockReq = {
|
|
478
|
-
url: '/oauth2callback?error=server_error',
|
|
155
|
+
const mockCodeVerifier = {
|
|
156
|
+
codeChallenge: 'test-challenge',
|
|
157
|
+
codeVerifier: 'test-verifier',
|
|
479
158
|
};
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
159
|
+
const mockAuthUrl = 'https://example.com/auth-user-code';
|
|
160
|
+
const mockCode = 'test-user-code';
|
|
161
|
+
const mockTokens = {
|
|
162
|
+
access_token: 'test-access-token-user-code',
|
|
163
|
+
refresh_token: 'test-refresh-token-user-code',
|
|
483
164
|
};
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
const mockAuthUrl = 'https://example.com/auth';
|
|
491
|
-
const mockCode = 'test-code';
|
|
492
|
-
const mockState = 'test-state';
|
|
165
|
+
const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
|
|
166
|
+
const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
|
|
167
|
+
const mockSetCredentials = vi.fn();
|
|
168
|
+
const mockGenerateCodeVerifierAsync = vi
|
|
169
|
+
.fn()
|
|
170
|
+
.mockResolvedValue(mockCodeVerifier);
|
|
493
171
|
const mockOAuth2Client = {
|
|
494
|
-
generateAuthUrl:
|
|
495
|
-
getToken:
|
|
172
|
+
generateAuthUrl: mockGenerateAuthUrl,
|
|
173
|
+
getToken: mockGetToken,
|
|
174
|
+
setCredentials: mockSetCredentials,
|
|
175
|
+
generateCodeVerifierAsync: mockGenerateCodeVerifierAsync,
|
|
496
176
|
on: vi.fn(),
|
|
497
177
|
};
|
|
498
178
|
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
let requestCallback;
|
|
502
|
-
let serverListeningCallback;
|
|
503
|
-
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
504
|
-
const mockHttpServer = {
|
|
505
|
-
listen: vi.fn((_port, _host, callback) => {
|
|
506
|
-
if (callback)
|
|
507
|
-
callback();
|
|
508
|
-
serverListeningCallback(undefined);
|
|
509
|
-
}),
|
|
179
|
+
const mockReadline = {
|
|
180
|
+
question: vi.fn((_query, callback) => callback(mockCode)),
|
|
510
181
|
close: vi.fn(),
|
|
511
|
-
on: vi.fn(),
|
|
512
|
-
address: () => ({ port: 3000 }),
|
|
513
182
|
};
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
183
|
+
readline.createInterface.mockReturnValue(mockReadline);
|
|
184
|
+
const consoleLogSpy = vi
|
|
185
|
+
.spyOn(console, 'log')
|
|
186
|
+
.mockImplementation(() => { });
|
|
187
|
+
const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser);
|
|
188
|
+
expect(client).toBe(mockOAuth2Client);
|
|
189
|
+
// Verify the auth flow
|
|
190
|
+
expect(mockGenerateCodeVerifierAsync).toHaveBeenCalled();
|
|
191
|
+
expect(mockGenerateAuthUrl).toHaveBeenCalled();
|
|
192
|
+
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(mockAuthUrl));
|
|
193
|
+
expect(mockReadline.question).toHaveBeenCalledWith('Enter the authorization code: ', expect.any(Function));
|
|
194
|
+
expect(mockGetToken).toHaveBeenCalledWith({
|
|
195
|
+
code: mockCode,
|
|
196
|
+
codeVerifier: mockCodeVerifier.codeVerifier,
|
|
197
|
+
redirect_uri: 'https://codeassist.google.com/authcode',
|
|
517
198
|
});
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
199
|
+
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
|
|
200
|
+
consoleLogSpy.mockRestore();
|
|
201
|
+
});
|
|
202
|
+
describe('in Cloud Shell', () => {
|
|
203
|
+
const mockGetAccessToken = vi.fn();
|
|
204
|
+
let mockComputeClient;
|
|
205
|
+
beforeEach(() => {
|
|
206
|
+
mockGetAccessToken.mockResolvedValue({ token: 'test-access-token' });
|
|
207
|
+
mockComputeClient = {
|
|
208
|
+
credentials: { refresh_token: 'test-refresh-token' },
|
|
209
|
+
getAccessToken: mockGetAccessToken,
|
|
210
|
+
};
|
|
211
|
+
Compute.mockImplementation(() => mockComputeClient);
|
|
212
|
+
});
|
|
213
|
+
it('should attempt to load cached credentials first', async () => {
|
|
214
|
+
const cachedCreds = { refresh_token: 'cached-token' };
|
|
215
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
216
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
217
|
+
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
218
|
+
const mockClient = {
|
|
219
|
+
setCredentials: vi.fn(),
|
|
220
|
+
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
221
|
+
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
222
|
+
on: vi.fn(),
|
|
223
|
+
};
|
|
224
|
+
// To mock the new OAuth2Client() inside the function
|
|
225
|
+
OAuth2Client.mockImplementation(() => mockClient);
|
|
226
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
227
|
+
expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
228
|
+
expect(mockClient.getAccessToken).toHaveBeenCalled();
|
|
229
|
+
expect(mockClient.getTokenInfo).toHaveBeenCalled();
|
|
230
|
+
expect(Compute).not.toHaveBeenCalled(); // Should not fetch new client if cache is valid
|
|
231
|
+
});
|
|
232
|
+
it('should use Compute to get a client if no cached credentials exist', async () => {
|
|
233
|
+
await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
|
|
234
|
+
expect(Compute).toHaveBeenCalledWith({});
|
|
235
|
+
expect(mockGetAccessToken).toHaveBeenCalled();
|
|
236
|
+
});
|
|
237
|
+
it('should not cache the credentials after fetching them via ADC', async () => {
|
|
238
|
+
const newCredentials = { refresh_token: 'new-adc-token' };
|
|
239
|
+
mockComputeClient.credentials = newCredentials;
|
|
240
|
+
mockGetAccessToken.mockResolvedValue({ token: 'new-adc-token' });
|
|
241
|
+
await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
|
|
242
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
243
|
+
expect(fs.existsSync(credsPath)).toBe(false);
|
|
244
|
+
});
|
|
245
|
+
it('should return the Compute client on successful ADC authentication', async () => {
|
|
246
|
+
const client = await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
|
|
247
|
+
expect(client).toBe(mockComputeClient);
|
|
248
|
+
});
|
|
249
|
+
it('should throw an error if ADC fails', async () => {
|
|
250
|
+
const testError = new Error('ADC Failed');
|
|
251
|
+
mockGetAccessToken.mockRejectedValue(testError);
|
|
252
|
+
await expect(getOauthClient(AuthType.CLOUD_SHELL, mockConfig)).rejects.toThrow('Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ADC Failed');
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
describe('credential loading order', () => {
|
|
256
|
+
it('should prioritize default cached credentials over GOOGLE_APPLICATION_CREDENTIALS', async () => {
|
|
257
|
+
// Setup default cached credentials
|
|
258
|
+
const defaultCreds = { refresh_token: 'default-cached-token' };
|
|
259
|
+
const defaultCredsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
260
|
+
await fs.promises.mkdir(path.dirname(defaultCredsPath), {
|
|
261
|
+
recursive: true,
|
|
262
|
+
});
|
|
263
|
+
await fs.promises.writeFile(defaultCredsPath, JSON.stringify(defaultCreds));
|
|
264
|
+
// Setup credentials via environment variable
|
|
265
|
+
const envCreds = { refresh_token: 'env-var-token' };
|
|
266
|
+
const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
|
|
267
|
+
await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
|
|
268
|
+
vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
|
|
269
|
+
const mockClient = {
|
|
270
|
+
setCredentials: vi.fn(),
|
|
271
|
+
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
272
|
+
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
273
|
+
on: vi.fn(),
|
|
274
|
+
};
|
|
275
|
+
OAuth2Client.mockImplementation(() => mockClient);
|
|
276
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
277
|
+
// Assert the correct credentials were used
|
|
278
|
+
expect(mockClient.setCredentials).toHaveBeenCalledWith(defaultCreds);
|
|
279
|
+
expect(mockClient.setCredentials).not.toHaveBeenCalledWith(envCreds);
|
|
280
|
+
});
|
|
281
|
+
it('should fall back to GOOGLE_APPLICATION_CREDENTIALS if default cache is missing', async () => {
|
|
282
|
+
// Setup credentials via environment variable
|
|
283
|
+
const envCreds = { refresh_token: 'env-var-token' };
|
|
284
|
+
const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
|
|
285
|
+
await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
|
|
286
|
+
vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
|
|
287
|
+
const mockClient = {
|
|
288
|
+
setCredentials: vi.fn(),
|
|
289
|
+
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
290
|
+
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
291
|
+
on: vi.fn(),
|
|
292
|
+
};
|
|
293
|
+
OAuth2Client.mockImplementation(() => mockClient);
|
|
294
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
295
|
+
// Assert the correct credentials were used
|
|
296
|
+
expect(mockClient.setCredentials).toHaveBeenCalledWith(envCreds);
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
describe('with GCP environment variables', () => {
|
|
300
|
+
it('should use GOOGLE_CLOUD_ACCESS_TOKEN when GOOGLE_GENAI_USE_GCA is true', async () => {
|
|
301
|
+
vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
|
|
302
|
+
vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
|
|
303
|
+
const mockSetCredentials = vi.fn();
|
|
304
|
+
const mockGetAccessToken = vi
|
|
305
|
+
.fn()
|
|
306
|
+
.mockResolvedValue({ token: 'gcp-access-token' });
|
|
307
|
+
const mockOAuth2Client = {
|
|
308
|
+
setCredentials: mockSetCredentials,
|
|
309
|
+
getAccessToken: mockGetAccessToken,
|
|
310
|
+
on: vi.fn(),
|
|
311
|
+
};
|
|
312
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
313
|
+
// Mock the UserInfo API response for fetchAndCacheUserInfo
|
|
314
|
+
global.fetch.mockResolvedValue({
|
|
315
|
+
ok: true,
|
|
316
|
+
json: vi
|
|
317
|
+
.fn()
|
|
318
|
+
.mockResolvedValue({ email: 'test-gcp-account@gmail.com' }),
|
|
319
|
+
});
|
|
320
|
+
const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
321
|
+
expect(client).toBe(mockOAuth2Client);
|
|
322
|
+
expect(mockSetCredentials).toHaveBeenCalledWith({
|
|
323
|
+
access_token: 'gcp-access-token',
|
|
324
|
+
});
|
|
325
|
+
// Verify fetchAndCacheUserInfo was effectively called
|
|
326
|
+
expect(mockGetAccessToken).toHaveBeenCalled();
|
|
327
|
+
expect(global.fetch).toHaveBeenCalledWith('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
328
|
+
headers: {
|
|
329
|
+
Authorization: 'Bearer gcp-access-token',
|
|
330
|
+
},
|
|
331
|
+
});
|
|
332
|
+
// Verify Google Account was cached
|
|
333
|
+
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
334
|
+
const cachedContent = fs.readFileSync(googleAccountPath, 'utf-8');
|
|
335
|
+
expect(JSON.parse(cachedContent)).toEqual({
|
|
336
|
+
active: 'test-gcp-account@gmail.com',
|
|
337
|
+
old: [],
|
|
338
|
+
});
|
|
339
|
+
});
|
|
340
|
+
it('should not use GCP token if GOOGLE_CLOUD_ACCESS_TOKEN is not set', async () => {
|
|
341
|
+
vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
|
|
342
|
+
const mockSetCredentials = vi.fn();
|
|
343
|
+
const mockGetAccessToken = vi
|
|
344
|
+
.fn()
|
|
345
|
+
.mockResolvedValue({ token: 'cached-access-token' });
|
|
346
|
+
const mockGetTokenInfo = vi.fn().mockResolvedValue({});
|
|
347
|
+
const mockOAuth2Client = {
|
|
348
|
+
setCredentials: mockSetCredentials,
|
|
349
|
+
getAccessToken: mockGetAccessToken,
|
|
350
|
+
getTokenInfo: mockGetTokenInfo,
|
|
351
|
+
on: vi.fn(),
|
|
352
|
+
};
|
|
353
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
354
|
+
// Make it fall through to cached credentials path
|
|
355
|
+
const cachedCreds = { refresh_token: 'cached-token' };
|
|
356
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
357
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
358
|
+
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
359
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
360
|
+
// It should be called with the cached credentials, not the GCP access token.
|
|
361
|
+
expect(mockSetCredentials).toHaveBeenCalledTimes(1);
|
|
362
|
+
expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
363
|
+
});
|
|
364
|
+
it('should not use GCP token if GOOGLE_GENAI_USE_GCA is not set', async () => {
|
|
365
|
+
vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
|
|
366
|
+
const mockSetCredentials = vi.fn();
|
|
367
|
+
const mockGetAccessToken = vi
|
|
368
|
+
.fn()
|
|
369
|
+
.mockResolvedValue({ token: 'cached-access-token' });
|
|
370
|
+
const mockGetTokenInfo = vi.fn().mockResolvedValue({});
|
|
371
|
+
const mockOAuth2Client = {
|
|
372
|
+
setCredentials: mockSetCredentials,
|
|
373
|
+
getAccessToken: mockGetAccessToken,
|
|
374
|
+
getTokenInfo: mockGetTokenInfo,
|
|
375
|
+
on: vi.fn(),
|
|
376
|
+
};
|
|
377
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
378
|
+
// Make it fall through to cached credentials path
|
|
379
|
+
const cachedCreds = { refresh_token: 'cached-token' };
|
|
380
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
381
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
382
|
+
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
383
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
384
|
+
// It should be called with the cached credentials, not the GCP access token.
|
|
385
|
+
expect(mockSetCredentials).toHaveBeenCalledTimes(1);
|
|
386
|
+
expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
describe('error handling', () => {
|
|
390
|
+
it('should handle browser launch failure with FatalAuthenticationError', async () => {
|
|
391
|
+
const mockError = new Error('Browser launch failed');
|
|
392
|
+
open.mockRejectedValue(mockError);
|
|
393
|
+
const mockOAuth2Client = {
|
|
394
|
+
generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
|
|
395
|
+
on: vi.fn(),
|
|
396
|
+
};
|
|
397
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
398
|
+
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Failed to open browser: Browser launch failed');
|
|
399
|
+
});
|
|
400
|
+
it('should handle authentication timeout with proper error message', async () => {
|
|
401
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
402
|
+
const mockOAuth2Client = {
|
|
403
|
+
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
404
|
+
on: vi.fn(),
|
|
405
|
+
};
|
|
406
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
407
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
408
|
+
const mockHttpServer = {
|
|
409
|
+
listen: vi.fn(),
|
|
410
|
+
close: vi.fn(),
|
|
411
|
+
on: vi.fn(),
|
|
412
|
+
address: () => ({ port: 3000 }),
|
|
413
|
+
};
|
|
414
|
+
http.createServer.mockImplementation(() => mockHttpServer);
|
|
415
|
+
// Mock setTimeout to trigger timeout immediately
|
|
416
|
+
const originalSetTimeout = global.setTimeout;
|
|
417
|
+
global.setTimeout = vi.fn((callback) => (callback(), {}));
|
|
418
|
+
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Authentication timed out after 5 minutes. The browser tab may have gotten stuck in a loading state. Please try again or use NO_BROWSER=true for manual authentication.');
|
|
419
|
+
global.setTimeout = originalSetTimeout;
|
|
420
|
+
});
|
|
421
|
+
it('should handle OAuth callback errors with descriptive messages', async () => {
|
|
422
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
423
|
+
const mockOAuth2Client = {
|
|
424
|
+
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
425
|
+
on: vi.fn(),
|
|
426
|
+
};
|
|
427
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
428
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
429
|
+
let requestCallback;
|
|
430
|
+
let serverListeningCallback;
|
|
431
|
+
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
432
|
+
const mockHttpServer = {
|
|
433
|
+
listen: vi.fn((_port, _host, callback) => {
|
|
434
|
+
if (callback)
|
|
435
|
+
callback();
|
|
436
|
+
serverListeningCallback(undefined);
|
|
437
|
+
}),
|
|
438
|
+
close: vi.fn(),
|
|
439
|
+
on: vi.fn(),
|
|
440
|
+
address: () => ({ port: 3000 }),
|
|
441
|
+
};
|
|
442
|
+
http.createServer.mockImplementation((cb) => {
|
|
443
|
+
requestCallback = cb;
|
|
444
|
+
return mockHttpServer;
|
|
445
|
+
});
|
|
446
|
+
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
447
|
+
await serverListeningPromise;
|
|
448
|
+
// Test OAuth error with description
|
|
449
|
+
const mockReq = {
|
|
450
|
+
url: '/oauth2callback?error=access_denied&error_description=User+denied+access',
|
|
451
|
+
};
|
|
452
|
+
const mockRes = {
|
|
453
|
+
writeHead: vi.fn(),
|
|
454
|
+
end: vi.fn(),
|
|
455
|
+
};
|
|
456
|
+
await expect(async () => {
|
|
457
|
+
await requestCallback(mockReq, mockRes);
|
|
458
|
+
await clientPromise;
|
|
459
|
+
}).rejects.toThrow('Google OAuth error: access_denied. User denied access');
|
|
460
|
+
});
|
|
461
|
+
it('should handle OAuth error without description', async () => {
|
|
462
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
463
|
+
const mockOAuth2Client = {
|
|
464
|
+
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
465
|
+
on: vi.fn(),
|
|
466
|
+
};
|
|
467
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
468
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
469
|
+
let requestCallback;
|
|
470
|
+
let serverListeningCallback;
|
|
471
|
+
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
472
|
+
const mockHttpServer = {
|
|
473
|
+
listen: vi.fn((_port, _host, callback) => {
|
|
474
|
+
if (callback)
|
|
475
|
+
callback();
|
|
476
|
+
serverListeningCallback(undefined);
|
|
477
|
+
}),
|
|
478
|
+
close: vi.fn(),
|
|
479
|
+
on: vi.fn(),
|
|
480
|
+
address: () => ({ port: 3000 }),
|
|
481
|
+
};
|
|
482
|
+
http.createServer.mockImplementation((cb) => {
|
|
483
|
+
requestCallback = cb;
|
|
484
|
+
return mockHttpServer;
|
|
485
|
+
});
|
|
486
|
+
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
487
|
+
await serverListeningPromise;
|
|
488
|
+
// Test OAuth error without description
|
|
489
|
+
const mockReq = {
|
|
490
|
+
url: '/oauth2callback?error=server_error',
|
|
491
|
+
};
|
|
492
|
+
const mockRes = {
|
|
493
|
+
writeHead: vi.fn(),
|
|
494
|
+
end: vi.fn(),
|
|
495
|
+
};
|
|
496
|
+
await expect(async () => {
|
|
497
|
+
await requestCallback(mockReq, mockRes);
|
|
498
|
+
await clientPromise;
|
|
499
|
+
}).rejects.toThrow('Google OAuth error: server_error. No additional details provided');
|
|
500
|
+
});
|
|
501
|
+
it('should handle token exchange failure with descriptive error', async () => {
|
|
502
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
503
|
+
const mockCode = 'test-code';
|
|
504
|
+
const mockState = 'test-state';
|
|
505
|
+
const mockOAuth2Client = {
|
|
506
|
+
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
507
|
+
getToken: vi
|
|
508
|
+
.fn()
|
|
509
|
+
.mockRejectedValue(new Error('Token exchange failed')),
|
|
510
|
+
on: vi.fn(),
|
|
511
|
+
};
|
|
512
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
513
|
+
vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
|
|
514
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
515
|
+
let requestCallback;
|
|
516
|
+
let serverListeningCallback;
|
|
517
|
+
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
518
|
+
const mockHttpServer = {
|
|
519
|
+
listen: vi.fn((_port, _host, callback) => {
|
|
520
|
+
if (callback)
|
|
521
|
+
callback();
|
|
522
|
+
serverListeningCallback(undefined);
|
|
523
|
+
}),
|
|
524
|
+
close: vi.fn(),
|
|
525
|
+
on: vi.fn(),
|
|
526
|
+
address: () => ({ port: 3000 }),
|
|
527
|
+
};
|
|
528
|
+
http.createServer.mockImplementation((cb) => {
|
|
529
|
+
requestCallback = cb;
|
|
530
|
+
return mockHttpServer;
|
|
531
|
+
});
|
|
532
|
+
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
533
|
+
await serverListeningPromise;
|
|
534
|
+
const mockReq = {
|
|
535
|
+
url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
|
|
536
|
+
};
|
|
537
|
+
const mockRes = {
|
|
538
|
+
writeHead: vi.fn(),
|
|
539
|
+
end: vi.fn(),
|
|
540
|
+
};
|
|
541
|
+
await expect(async () => {
|
|
542
|
+
await requestCallback(mockReq, mockRes);
|
|
543
|
+
await clientPromise;
|
|
544
|
+
}).rejects.toThrow('Failed to exchange authorization code for tokens: Token exchange failed');
|
|
545
|
+
});
|
|
546
|
+
it('should handle fetchAndCacheUserInfo failure gracefully', async () => {
|
|
547
|
+
const mockAuthUrl = 'https://example.com/auth';
|
|
548
|
+
const mockCode = 'test-code';
|
|
549
|
+
const mockState = 'test-state';
|
|
550
|
+
const mockTokens = {
|
|
551
|
+
access_token: 'test-access-token',
|
|
552
|
+
refresh_token: 'test-refresh-token',
|
|
553
|
+
};
|
|
554
|
+
const mockOAuth2Client = {
|
|
555
|
+
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
556
|
+
getToken: vi.fn().mockResolvedValue({ tokens: mockTokens }),
|
|
557
|
+
setCredentials: vi.fn(),
|
|
558
|
+
getAccessToken: vi
|
|
559
|
+
.fn()
|
|
560
|
+
.mockResolvedValue({ token: 'test-access-token' }),
|
|
561
|
+
on: vi.fn(),
|
|
562
|
+
};
|
|
563
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
564
|
+
vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
|
|
565
|
+
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
566
|
+
// Mock fetch to fail
|
|
567
|
+
global.fetch.mockResolvedValue({
|
|
568
|
+
ok: false,
|
|
569
|
+
status: 500,
|
|
570
|
+
statusText: 'Internal Server Error',
|
|
571
|
+
});
|
|
572
|
+
const consoleErrorSpy = vi
|
|
573
|
+
.spyOn(console, 'error')
|
|
574
|
+
.mockImplementation(() => { });
|
|
575
|
+
let requestCallback;
|
|
576
|
+
let serverListeningCallback;
|
|
577
|
+
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
578
|
+
const mockHttpServer = {
|
|
579
|
+
listen: vi.fn((_port, _host, callback) => {
|
|
580
|
+
if (callback)
|
|
581
|
+
callback();
|
|
582
|
+
serverListeningCallback(undefined);
|
|
583
|
+
}),
|
|
584
|
+
close: vi.fn(),
|
|
585
|
+
on: vi.fn(),
|
|
586
|
+
address: () => ({ port: 3000 }),
|
|
587
|
+
};
|
|
588
|
+
http.createServer.mockImplementation((cb) => {
|
|
589
|
+
requestCallback = cb;
|
|
590
|
+
return mockHttpServer;
|
|
591
|
+
});
|
|
592
|
+
const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
593
|
+
await serverListeningPromise;
|
|
594
|
+
const mockReq = {
|
|
595
|
+
url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
|
|
596
|
+
};
|
|
597
|
+
const mockRes = {
|
|
598
|
+
writeHead: vi.fn(),
|
|
599
|
+
end: vi.fn(),
|
|
600
|
+
};
|
|
528
601
|
await requestCallback(mockReq, mockRes);
|
|
529
|
-
await clientPromise;
|
|
530
|
-
|
|
602
|
+
const client = await clientPromise;
|
|
603
|
+
// Authentication should succeed even if fetchAndCacheUserInfo fails
|
|
604
|
+
expect(client).toBe(mockOAuth2Client);
|
|
605
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to fetch user info:', 500, 'Internal Server Error');
|
|
606
|
+
consoleErrorSpy.mockRestore();
|
|
607
|
+
});
|
|
608
|
+
it('should handle user code authentication failure with descriptive error', async () => {
|
|
609
|
+
const mockConfigWithNoBrowser = {
|
|
610
|
+
getNoBrowser: () => true,
|
|
611
|
+
getProxy: () => 'http://test.proxy.com:8080',
|
|
612
|
+
isBrowserLaunchSuppressed: () => true,
|
|
613
|
+
};
|
|
614
|
+
const mockOAuth2Client = {
|
|
615
|
+
generateCodeVerifierAsync: vi.fn().mockResolvedValue({
|
|
616
|
+
codeChallenge: 'test-challenge',
|
|
617
|
+
codeVerifier: 'test-verifier',
|
|
618
|
+
}),
|
|
619
|
+
generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
|
|
620
|
+
getToken: vi
|
|
621
|
+
.fn()
|
|
622
|
+
.mockRejectedValue(new Error('Invalid authorization code')),
|
|
623
|
+
on: vi.fn(),
|
|
624
|
+
};
|
|
625
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
626
|
+
const mockReadline = {
|
|
627
|
+
question: vi.fn((_query, callback) => callback('invalid-code')),
|
|
628
|
+
close: vi.fn(),
|
|
629
|
+
};
|
|
630
|
+
readline.createInterface.mockReturnValue(mockReadline);
|
|
631
|
+
const consoleLogSpy = vi
|
|
632
|
+
.spyOn(console, 'log')
|
|
633
|
+
.mockImplementation(() => { });
|
|
634
|
+
const consoleErrorSpy = vi
|
|
635
|
+
.spyOn(console, 'error')
|
|
636
|
+
.mockImplementation(() => { });
|
|
637
|
+
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser)).rejects.toThrow('Failed to authenticate with user code.');
|
|
638
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to authenticate with authorization code:', 'Invalid authorization code');
|
|
639
|
+
consoleLogSpy.mockRestore();
|
|
640
|
+
consoleErrorSpy.mockRestore();
|
|
641
|
+
});
|
|
642
|
+
});
|
|
643
|
+
describe('clearCachedCredentialFile', () => {
|
|
644
|
+
it('should clear cached credentials and Google account', async () => {
|
|
645
|
+
const cachedCreds = { refresh_token: 'test-token' };
|
|
646
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
647
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
648
|
+
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
649
|
+
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
650
|
+
const accountData = { active: 'test@example.com', old: [] };
|
|
651
|
+
await fs.promises.writeFile(googleAccountPath, JSON.stringify(accountData));
|
|
652
|
+
const userAccountManager = new UserAccountManager();
|
|
653
|
+
expect(fs.existsSync(credsPath)).toBe(true);
|
|
654
|
+
expect(fs.existsSync(googleAccountPath)).toBe(true);
|
|
655
|
+
expect(userAccountManager.getCachedGoogleAccount()).toBe('test@example.com');
|
|
656
|
+
await clearCachedCredentialFile();
|
|
657
|
+
expect(fs.existsSync(credsPath)).toBe(false);
|
|
658
|
+
expect(userAccountManager.getCachedGoogleAccount()).toBeNull();
|
|
659
|
+
const updatedAccountData = JSON.parse(fs.readFileSync(googleAccountPath, 'utf-8'));
|
|
660
|
+
expect(updatedAccountData.active).toBeNull();
|
|
661
|
+
expect(updatedAccountData.old).toContain('test@example.com');
|
|
662
|
+
});
|
|
663
|
+
it('should clear the in-memory OAuth client cache', async () => {
|
|
664
|
+
const mockSetCredentials = vi.fn();
|
|
665
|
+
const mockGetAccessToken = vi
|
|
666
|
+
.fn()
|
|
667
|
+
.mockResolvedValue({ token: 'test-token' });
|
|
668
|
+
const mockGetTokenInfo = vi.fn().mockResolvedValue({});
|
|
669
|
+
const mockOAuth2Client = {
|
|
670
|
+
setCredentials: mockSetCredentials,
|
|
671
|
+
getAccessToken: mockGetAccessToken,
|
|
672
|
+
getTokenInfo: mockGetTokenInfo,
|
|
673
|
+
on: vi.fn(),
|
|
674
|
+
};
|
|
675
|
+
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
676
|
+
// Pre-populate credentials to make getOauthClient resolve quickly
|
|
677
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
678
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
679
|
+
await fs.promises.writeFile(credsPath, JSON.stringify({ refresh_token: 'token' }));
|
|
680
|
+
// First call, should create a client
|
|
681
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
682
|
+
expect(OAuth2Client).toHaveBeenCalledTimes(1);
|
|
683
|
+
// Second call, should use cached client
|
|
684
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
685
|
+
expect(OAuth2Client).toHaveBeenCalledTimes(1);
|
|
686
|
+
clearOauthClientCache();
|
|
687
|
+
// Third call, after clearing cache, should create a new client
|
|
688
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
689
|
+
expect(OAuth2Client).toHaveBeenCalledTimes(2);
|
|
690
|
+
});
|
|
691
|
+
});
|
|
692
|
+
});
|
|
693
|
+
describe('with encrypted flag true', () => {
|
|
694
|
+
let tempHomeDir;
|
|
695
|
+
beforeEach(() => {
|
|
696
|
+
process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] = 'true';
|
|
697
|
+
tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
|
|
698
|
+
os.homedir.mockReturnValue(tempHomeDir);
|
|
531
699
|
});
|
|
532
|
-
|
|
700
|
+
afterEach(() => {
|
|
701
|
+
fs.rmSync(tempHomeDir, { recursive: true, force: true });
|
|
702
|
+
vi.clearAllMocks();
|
|
703
|
+
resetOauthClientForTesting();
|
|
704
|
+
vi.unstubAllEnvs();
|
|
705
|
+
});
|
|
706
|
+
it('should save credentials using OAuthCredentialStorage during web login', async () => {
|
|
707
|
+
const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
|
|
533
708
|
const mockAuthUrl = 'https://example.com/auth';
|
|
534
709
|
const mockCode = 'test-code';
|
|
535
710
|
const mockState = 'test-state';
|
|
@@ -537,39 +712,54 @@ describe('oauth2', () => {
|
|
|
537
712
|
access_token: 'test-access-token',
|
|
538
713
|
refresh_token: 'test-refresh-token',
|
|
539
714
|
};
|
|
715
|
+
let onTokensCallback = () => { };
|
|
716
|
+
const mockOn = vi.fn((event, callback) => {
|
|
717
|
+
if (event === 'tokens') {
|
|
718
|
+
onTokensCallback = callback;
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
const mockGetToken = vi.fn().mockImplementation(async () => {
|
|
722
|
+
onTokensCallback(mockTokens);
|
|
723
|
+
return { tokens: mockTokens };
|
|
724
|
+
});
|
|
540
725
|
const mockOAuth2Client = {
|
|
541
726
|
generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
|
|
542
|
-
getToken:
|
|
727
|
+
getToken: mockGetToken,
|
|
543
728
|
setCredentials: vi.fn(),
|
|
544
729
|
getAccessToken: vi
|
|
545
730
|
.fn()
|
|
546
|
-
.mockResolvedValue({ token: '
|
|
547
|
-
on:
|
|
731
|
+
.mockResolvedValue({ token: 'mock-access-token' }),
|
|
732
|
+
on: mockOn,
|
|
733
|
+
credentials: mockTokens,
|
|
548
734
|
};
|
|
549
735
|
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
550
736
|
vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
|
|
551
737
|
open.mockImplementation(async () => ({ on: vi.fn() }));
|
|
552
|
-
// Mock fetch to fail
|
|
553
738
|
global.fetch.mockResolvedValue({
|
|
554
|
-
ok:
|
|
555
|
-
|
|
556
|
-
|
|
739
|
+
ok: true,
|
|
740
|
+
json: vi
|
|
741
|
+
.fn()
|
|
742
|
+
.mockResolvedValue({ email: 'test-google-account@gmail.com' }),
|
|
557
743
|
});
|
|
558
|
-
const consoleErrorSpy = vi
|
|
559
|
-
.spyOn(console, 'error')
|
|
560
|
-
.mockImplementation(() => { });
|
|
561
744
|
let requestCallback;
|
|
562
745
|
let serverListeningCallback;
|
|
563
746
|
const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
|
|
747
|
+
let capturedPort = 0;
|
|
564
748
|
const mockHttpServer = {
|
|
565
|
-
listen: vi.fn((
|
|
566
|
-
|
|
749
|
+
listen: vi.fn((port, _host, callback) => {
|
|
750
|
+
capturedPort = port;
|
|
751
|
+
if (callback) {
|
|
567
752
|
callback();
|
|
753
|
+
}
|
|
568
754
|
serverListeningCallback(undefined);
|
|
569
755
|
}),
|
|
570
|
-
close: vi.fn()
|
|
756
|
+
close: vi.fn((callback) => {
|
|
757
|
+
if (callback) {
|
|
758
|
+
callback();
|
|
759
|
+
}
|
|
760
|
+
}),
|
|
571
761
|
on: vi.fn(),
|
|
572
|
-
address: () => ({ port:
|
|
762
|
+
address: () => ({ port: capturedPort }),
|
|
573
763
|
};
|
|
574
764
|
http.createServer.mockImplementation((cb) => {
|
|
575
765
|
requestCallback = cb;
|
|
@@ -584,95 +774,43 @@ describe('oauth2', () => {
|
|
|
584
774
|
writeHead: vi.fn(),
|
|
585
775
|
end: vi.fn(),
|
|
586
776
|
};
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
expect(client).toBe(mockOAuth2Client);
|
|
591
|
-
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to fetch user info:', 500, 'Internal Server Error');
|
|
592
|
-
consoleErrorSpy.mockRestore();
|
|
593
|
-
});
|
|
594
|
-
it('should handle user code authentication failure with descriptive error', async () => {
|
|
595
|
-
const mockConfigWithNoBrowser = {
|
|
596
|
-
getNoBrowser: () => true,
|
|
597
|
-
getProxy: () => 'http://test.proxy.com:8080',
|
|
598
|
-
isBrowserLaunchSuppressed: () => true,
|
|
599
|
-
};
|
|
600
|
-
const mockOAuth2Client = {
|
|
601
|
-
generateCodeVerifierAsync: vi.fn().mockResolvedValue({
|
|
602
|
-
codeChallenge: 'test-challenge',
|
|
603
|
-
codeVerifier: 'test-verifier',
|
|
604
|
-
}),
|
|
605
|
-
generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
|
|
606
|
-
getToken: vi
|
|
607
|
-
.fn()
|
|
608
|
-
.mockRejectedValue(new Error('Invalid authorization code')),
|
|
609
|
-
on: vi.fn(),
|
|
610
|
-
};
|
|
611
|
-
OAuth2Client.mockImplementation(() => mockOAuth2Client);
|
|
612
|
-
const mockReadline = {
|
|
613
|
-
question: vi.fn((_query, callback) => callback('invalid-code')),
|
|
614
|
-
close: vi.fn(),
|
|
615
|
-
};
|
|
616
|
-
readline.createInterface.mockReturnValue(mockReadline);
|
|
617
|
-
const consoleLogSpy = vi
|
|
618
|
-
.spyOn(console, 'log')
|
|
619
|
-
.mockImplementation(() => { });
|
|
620
|
-
const consoleErrorSpy = vi
|
|
621
|
-
.spyOn(console, 'error')
|
|
622
|
-
.mockImplementation(() => { });
|
|
623
|
-
await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser)).rejects.toThrow('Failed to authenticate with user code.');
|
|
624
|
-
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to authenticate with authorization code:', 'Invalid authorization code');
|
|
625
|
-
consoleLogSpy.mockRestore();
|
|
626
|
-
consoleErrorSpy.mockRestore();
|
|
627
|
-
});
|
|
628
|
-
});
|
|
629
|
-
describe('clearCachedCredentialFile', () => {
|
|
630
|
-
it('should clear cached credentials and Google account', async () => {
|
|
631
|
-
const cachedCreds = { refresh_token: 'test-token' };
|
|
777
|
+
requestCallback(mockReq, mockRes);
|
|
778
|
+
await clientPromise;
|
|
779
|
+
expect(OAuthCredentialStorage.saveCredentials).toHaveBeenCalledWith(mockTokens);
|
|
632
780
|
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
633
|
-
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
634
|
-
await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
|
|
635
|
-
const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
|
|
636
|
-
const accountData = { active: 'test@example.com', old: [] };
|
|
637
|
-
await fs.promises.writeFile(googleAccountPath, JSON.stringify(accountData));
|
|
638
|
-
const userAccountManager = new UserAccountManager();
|
|
639
|
-
expect(fs.existsSync(credsPath)).toBe(true);
|
|
640
|
-
expect(fs.existsSync(googleAccountPath)).toBe(true);
|
|
641
|
-
expect(userAccountManager.getCachedGoogleAccount()).toBe('test@example.com');
|
|
642
|
-
await clearCachedCredentialFile();
|
|
643
781
|
expect(fs.existsSync(credsPath)).toBe(false);
|
|
644
|
-
expect(userAccountManager.getCachedGoogleAccount()).toBeNull();
|
|
645
|
-
const updatedAccountData = JSON.parse(fs.readFileSync(googleAccountPath, 'utf-8'));
|
|
646
|
-
expect(updatedAccountData.active).toBeNull();
|
|
647
|
-
expect(updatedAccountData.old).toContain('test@example.com');
|
|
648
782
|
});
|
|
649
|
-
it('should
|
|
650
|
-
const
|
|
651
|
-
const
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
783
|
+
it('should load credentials using OAuthCredentialStorage and not from file', async () => {
|
|
784
|
+
const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
|
|
785
|
+
const cachedCreds = { refresh_token: 'cached-encrypted-token' };
|
|
786
|
+
OAuthCredentialStorage.loadCredentials.mockResolvedValue(cachedCreds);
|
|
787
|
+
// Create a dummy unencrypted credential file.
|
|
788
|
+
// If the logic is correct, this file should be ignored.
|
|
789
|
+
const unencryptedCreds = { refresh_token: 'unencrypted-token' };
|
|
790
|
+
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
791
|
+
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
792
|
+
await fs.promises.writeFile(credsPath, JSON.stringify(unencryptedCreds));
|
|
793
|
+
const mockClient = {
|
|
794
|
+
setCredentials: vi.fn(),
|
|
795
|
+
getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
|
|
796
|
+
getTokenInfo: vi.fn().mockResolvedValue({}),
|
|
659
797
|
on: vi.fn(),
|
|
660
798
|
};
|
|
661
|
-
OAuth2Client.mockImplementation(() =>
|
|
662
|
-
|
|
799
|
+
OAuth2Client.mockImplementation(() => mockClient);
|
|
800
|
+
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
801
|
+
expect(OAuthCredentialStorage.loadCredentials).toHaveBeenCalled();
|
|
802
|
+
expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
|
|
803
|
+
expect(mockClient.setCredentials).not.toHaveBeenCalledWith(unencryptedCreds);
|
|
804
|
+
});
|
|
805
|
+
it('should clear credentials using OAuthCredentialStorage', async () => {
|
|
806
|
+
const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
|
|
807
|
+
// Create a dummy unencrypted credential file. It should not be deleted.
|
|
663
808
|
const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
|
|
664
809
|
await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
|
|
665
|
-
await fs.promises.writeFile(credsPath,
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
expect(
|
|
669
|
-
// Second call, should use cached client
|
|
670
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
671
|
-
expect(OAuth2Client).toHaveBeenCalledTimes(1);
|
|
672
|
-
clearOauthClientCache();
|
|
673
|
-
// Third call, after clearing cache, should create a new client
|
|
674
|
-
await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
|
|
675
|
-
expect(OAuth2Client).toHaveBeenCalledTimes(2);
|
|
810
|
+
await fs.promises.writeFile(credsPath, '{}');
|
|
811
|
+
await clearCachedCredentialFile();
|
|
812
|
+
expect(OAuthCredentialStorage.clearCredentials).toHaveBeenCalled();
|
|
813
|
+
expect(fs.existsSync(credsPath)).toBe(true); // The unencrypted file should remain
|
|
676
814
|
});
|
|
677
815
|
});
|
|
678
816
|
});
|