mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-03-24 21:10:43 -07:00
Co-authored-by: christine betts <chrstn@uw.edu> Co-authored-by: Gal Zahavi <38544478+galz10@users.noreply.github.com>
This commit is contained in:
@@ -53,6 +53,8 @@
|
||||
"ajv-formats": "^3.0.0",
|
||||
"chardet": "^2.1.0",
|
||||
"diff": "^8.0.3",
|
||||
"dotenv": "^17.2.4",
|
||||
"dotenv-expand": "^12.0.3",
|
||||
"fast-levenshtein": "^2.0.6",
|
||||
"fdir": "^6.4.6",
|
||||
"fzf": "^0.5.2",
|
||||
|
||||
@@ -1696,6 +1696,114 @@ describe('mcp-client', () => {
|
||||
expect(callArgs.env!['GEMINI_CLI_EXT_VAR']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include extension settings with defined values in environment', async () => {
|
||||
const mockedTransport = vi
|
||||
.spyOn(SdkClientStdioLib, 'StdioClientTransport')
|
||||
.mockReturnValue({} as SdkClientStdioLib.StdioClientTransport);
|
||||
|
||||
await createTransport(
|
||||
'test-server',
|
||||
{
|
||||
command: 'test-command',
|
||||
extension: {
|
||||
name: 'test-ext',
|
||||
resolvedSettings: [
|
||||
{
|
||||
envVar: 'GEMINI_CLI_EXT_VAR',
|
||||
value: 'defined-value',
|
||||
sensitive: false,
|
||||
name: 'ext-setting',
|
||||
},
|
||||
],
|
||||
version: '',
|
||||
isActive: false,
|
||||
path: '',
|
||||
contextFiles: [],
|
||||
id: '',
|
||||
},
|
||||
},
|
||||
false,
|
||||
EMPTY_CONFIG,
|
||||
);
|
||||
|
||||
const callArgs = mockedTransport.mock.calls[0][0];
|
||||
expect(callArgs.env).toBeDefined();
|
||||
expect(callArgs.env!['GEMINI_CLI_EXT_VAR']).toBe('defined-value');
|
||||
});
|
||||
|
||||
it('should resolve environment variables in mcpServerConfig.env using extension settings', async () => {
|
||||
const mockedTransport = vi
|
||||
.spyOn(SdkClientStdioLib, 'StdioClientTransport')
|
||||
.mockReturnValue({} as SdkClientStdioLib.StdioClientTransport);
|
||||
|
||||
await createTransport(
|
||||
'test-server',
|
||||
{
|
||||
command: 'test-command',
|
||||
env: {
|
||||
RESOLVED_VAR: '$GEMINI_CLI_EXT_VAR',
|
||||
},
|
||||
extension: {
|
||||
name: 'test-ext',
|
||||
resolvedSettings: [
|
||||
{
|
||||
envVar: 'GEMINI_CLI_EXT_VAR',
|
||||
value: 'ext-value',
|
||||
sensitive: false,
|
||||
name: 'ext-setting',
|
||||
},
|
||||
],
|
||||
version: '',
|
||||
isActive: false,
|
||||
path: '',
|
||||
contextFiles: [],
|
||||
id: '',
|
||||
},
|
||||
},
|
||||
false,
|
||||
EMPTY_CONFIG,
|
||||
);
|
||||
|
||||
const callArgs = mockedTransport.mock.calls[0][0];
|
||||
expect(callArgs.env).toBeDefined();
|
||||
expect(callArgs.env!['GEMINI_CLI_EXT_VAR']).toBe('ext-value');
|
||||
expect(callArgs.env!['RESOLVED_VAR']).toBe('ext-value');
|
||||
});
|
||||
|
||||
it('should expand environment variables in mcpServerConfig.env and not redact them', async () => {
|
||||
const mockedTransport = vi
|
||||
.spyOn(SdkClientStdioLib, 'StdioClientTransport')
|
||||
.mockReturnValue({} as SdkClientStdioLib.StdioClientTransport);
|
||||
|
||||
const originalEnv = process.env;
|
||||
process.env = {
|
||||
...originalEnv,
|
||||
GEMINI_TEST_VAR: 'expanded-value',
|
||||
};
|
||||
|
||||
try {
|
||||
await createTransport(
|
||||
'test-server',
|
||||
{
|
||||
command: 'test-command',
|
||||
env: {
|
||||
TEST_EXPANDED: 'Value is $GEMINI_TEST_VAR',
|
||||
SECRET_KEY: 'intentional-secret-123',
|
||||
},
|
||||
},
|
||||
false,
|
||||
EMPTY_CONFIG,
|
||||
);
|
||||
|
||||
const callArgs = mockedTransport.mock.calls[0][0];
|
||||
expect(callArgs.env).toBeDefined();
|
||||
expect(callArgs.env!['TEST_EXPANDED']).toBe('Value is expanded-value');
|
||||
expect(callArgs.env!['SECRET_KEY']).toBe('intentional-secret-123');
|
||||
} finally {
|
||||
process.env = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
describe('useGoogleCredentialProvider', () => {
|
||||
beforeEach(() => {
|
||||
// Mock GoogleAuth client
|
||||
|
||||
@@ -34,7 +34,11 @@ import {
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import { ApprovalMode, PolicyDecision } from '../policy/types.js';
|
||||
import { parse } from 'shell-quote';
|
||||
import type { Config, MCPServerConfig } from '../config/config.js';
|
||||
import type {
|
||||
Config,
|
||||
MCPServerConfig,
|
||||
GeminiCLIExtension,
|
||||
} from '../config/config.js';
|
||||
import { AuthProviderType } from '../config/config.js';
|
||||
import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js';
|
||||
import { ServiceAccountImpersonationProvider } from '../mcp/sa-impersonation-provider.js';
|
||||
@@ -67,6 +71,7 @@ import {
|
||||
sanitizeEnvironment,
|
||||
type EnvironmentSanitizationConfig,
|
||||
} from '../services/environmentSanitization.js';
|
||||
import { expandEnvVars } from '../utils/envExpansion.js';
|
||||
import {
|
||||
GEMINI_CLI_IDENTIFICATION_ENV_VAR,
|
||||
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
|
||||
@@ -727,14 +732,31 @@ async function handleAutomaticOAuth(
|
||||
*
|
||||
* @param mcpServerConfig The MCP server configuration
|
||||
* @param headers Additional headers
|
||||
* @param sanitizationConfig Configuration for environment sanitization
|
||||
*/
|
||||
function createTransportRequestInit(
|
||||
mcpServerConfig: MCPServerConfig,
|
||||
headers: Record<string, string>,
|
||||
sanitizationConfig: EnvironmentSanitizationConfig,
|
||||
): RequestInit {
|
||||
const extensionEnv = getExtensionEnvironment(mcpServerConfig.extension);
|
||||
const expansionEnv = { ...process.env, ...extensionEnv };
|
||||
|
||||
const sanitizedEnv = sanitizeEnvironment(expansionEnv, {
|
||||
...sanitizationConfig,
|
||||
enableEnvironmentVariableRedaction: true,
|
||||
});
|
||||
|
||||
const expandedHeaders: Record<string, string> = {};
|
||||
if (mcpServerConfig.headers) {
|
||||
for (const [key, value] of Object.entries(mcpServerConfig.headers)) {
|
||||
expandedHeaders[key] = expandEnvVars(value, sanitizedEnv);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
headers: {
|
||||
...mcpServerConfig.headers,
|
||||
...expandedHeaders,
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
@@ -768,12 +790,14 @@ function createAuthProvider(
|
||||
* @param mcpServerName The name of the MCP server
|
||||
* @param mcpServerConfig The MCP server configuration
|
||||
* @param accessToken The OAuth access token
|
||||
* @param sanitizationConfig Configuration for environment sanitization
|
||||
* @returns The transport with OAuth token, or null if creation fails
|
||||
*/
|
||||
async function createTransportWithOAuth(
|
||||
mcpServerName: string,
|
||||
mcpServerConfig: MCPServerConfig,
|
||||
accessToken: string,
|
||||
sanitizationConfig: EnvironmentSanitizationConfig,
|
||||
): Promise<StreamableHTTPClientTransport | SSEClientTransport | null> {
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
@@ -782,7 +806,11 @@ async function createTransportWithOAuth(
|
||||
const transportOptions:
|
||||
| StreamableHTTPClientTransportOptions
|
||||
| SSEClientTransportOptions = {
|
||||
requestInit: createTransportRequestInit(mcpServerConfig, headers),
|
||||
requestInit: createTransportRequestInit(
|
||||
mcpServerConfig,
|
||||
headers,
|
||||
sanitizationConfig,
|
||||
),
|
||||
};
|
||||
|
||||
return createUrlTransport(mcpServerName, mcpServerConfig, transportOptions);
|
||||
@@ -1366,6 +1394,7 @@ async function showAuthRequiredMessage(serverName: string): Promise<never> {
|
||||
* @param config The MCP server configuration
|
||||
* @param accessToken The OAuth access token to use
|
||||
* @param httpReturned404 Whether the HTTP transport returned 404 (indicating SSE-only server)
|
||||
* @param sanitizationConfig Configuration for environment sanitization
|
||||
*/
|
||||
async function retryWithOAuth(
|
||||
client: Client,
|
||||
@@ -1373,6 +1402,7 @@ async function retryWithOAuth(
|
||||
config: MCPServerConfig,
|
||||
accessToken: string,
|
||||
httpReturned404: boolean,
|
||||
sanitizationConfig: EnvironmentSanitizationConfig,
|
||||
): Promise<void> {
|
||||
if (httpReturned404) {
|
||||
// HTTP returned 404, only try SSE
|
||||
@@ -1393,6 +1423,7 @@ async function retryWithOAuth(
|
||||
serverName,
|
||||
config,
|
||||
accessToken,
|
||||
sanitizationConfig,
|
||||
);
|
||||
if (!httpTransport) {
|
||||
throw new Error(
|
||||
@@ -1672,6 +1703,7 @@ export async function connectToMcpServer(
|
||||
mcpServerConfig,
|
||||
accessToken,
|
||||
httpReturned404,
|
||||
sanitizationConfig,
|
||||
);
|
||||
return mcpClient;
|
||||
} else {
|
||||
@@ -1743,6 +1775,7 @@ export async function connectToMcpServer(
|
||||
mcpServerName,
|
||||
mcpServerConfig,
|
||||
accessToken,
|
||||
sanitizationConfig,
|
||||
);
|
||||
if (!oauthTransport) {
|
||||
throw new Error(
|
||||
@@ -1890,7 +1923,11 @@ export async function createTransport(
|
||||
const transportOptions:
|
||||
| StreamableHTTPClientTransportOptions
|
||||
| SSEClientTransportOptions = {
|
||||
requestInit: createTransportRequestInit(mcpServerConfig, headers),
|
||||
requestInit: createTransportRequestInit(
|
||||
mcpServerConfig,
|
||||
headers,
|
||||
sanitizationConfig,
|
||||
),
|
||||
authProvider,
|
||||
};
|
||||
|
||||
@@ -1898,15 +1935,37 @@ export async function createTransport(
|
||||
}
|
||||
|
||||
if (mcpServerConfig.command) {
|
||||
const extensionEnv = getExtensionEnvironment(mcpServerConfig.extension);
|
||||
const expansionEnv = { ...process.env, ...extensionEnv };
|
||||
|
||||
// 1. Sanitize the base process environment to prevent unintended leaks of system-wide secrets.
|
||||
const sanitizedEnv = sanitizeEnvironment(expansionEnv, {
|
||||
...sanitizationConfig,
|
||||
enableEnvironmentVariableRedaction: true,
|
||||
});
|
||||
|
||||
const finalEnv: Record<string, string> = {
|
||||
[GEMINI_CLI_IDENTIFICATION_ENV_VAR]:
|
||||
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
|
||||
...extensionEnv,
|
||||
};
|
||||
for (const [key, value] of Object.entries(sanitizedEnv)) {
|
||||
if (value !== undefined) {
|
||||
finalEnv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// Expand and merge explicit environment variables from the MCP configuration.
|
||||
if (mcpServerConfig.env) {
|
||||
for (const [key, value] of Object.entries(mcpServerConfig.env)) {
|
||||
finalEnv[key] = expandEnvVars(value, expansionEnv);
|
||||
}
|
||||
}
|
||||
|
||||
let transport: Transport = new StdioClientTransport({
|
||||
command: mcpServerConfig.command,
|
||||
args: mcpServerConfig.args || [],
|
||||
env: {
|
||||
...sanitizeEnvironment(process.env, sanitizationConfig),
|
||||
...(mcpServerConfig.env || {}),
|
||||
[GEMINI_CLI_IDENTIFICATION_ENV_VAR]:
|
||||
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
|
||||
} as Record<string, string>,
|
||||
env: finalEnv,
|
||||
cwd: mcpServerConfig.cwd,
|
||||
stderr: 'pipe',
|
||||
});
|
||||
@@ -1955,6 +2014,20 @@ interface NamedTool {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
function getExtensionEnvironment(
|
||||
extension?: GeminiCLIExtension,
|
||||
): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
if (extension?.resolvedSettings) {
|
||||
for (const setting of extension.resolvedSettings) {
|
||||
if (setting.value !== undefined) {
|
||||
env[setting.envVar] = setting.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Visible for testing */
|
||||
export function isEnabled(
|
||||
funcDecl: NamedTool,
|
||||
|
||||
117
packages/core/src/utils/envExpansion.test.ts
Normal file
117
packages/core/src/utils/envExpansion.test.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { expandEnvVars } from './envExpansion.js';
|
||||
|
||||
describe('expandEnvVars', () => {
|
||||
const defaultEnv = {
|
||||
USER: 'morty',
|
||||
HOME: '/home/morty',
|
||||
TEMP: 'C:\\Temp',
|
||||
EMPTY: '',
|
||||
};
|
||||
|
||||
describe('POSIX behavior (non-Windows)', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['$VAR (POSIX)', 'Hello $USER', defaultEnv, 'Hello morty'],
|
||||
[
|
||||
'${VAR} (POSIX)',
|
||||
'Welcome to ${HOME}',
|
||||
defaultEnv,
|
||||
'Welcome to /home/morty',
|
||||
],
|
||||
[
|
||||
'should NOT expand %VAR% on non-Windows',
|
||||
'Data in %TEMP%',
|
||||
defaultEnv,
|
||||
'Data in %TEMP%',
|
||||
],
|
||||
[
|
||||
'mixed formats (only POSIX expanded)',
|
||||
'$USER lives in ${HOME} on %TEMP%',
|
||||
defaultEnv,
|
||||
'morty lives in /home/morty on %TEMP%',
|
||||
],
|
||||
[
|
||||
'missing variables (POSIX only)',
|
||||
'Missing $UNDEFINED and ${NONE} and %MISSING%',
|
||||
defaultEnv,
|
||||
'Missing and and %MISSING%',
|
||||
],
|
||||
[
|
||||
'empty or undefined values',
|
||||
'Value is "$EMPTY"',
|
||||
defaultEnv,
|
||||
'Value is ""',
|
||||
],
|
||||
[
|
||||
'original string if no variables',
|
||||
'No vars here',
|
||||
defaultEnv,
|
||||
'No vars here',
|
||||
],
|
||||
['literal values like "1234"', '1234', defaultEnv, '1234'],
|
||||
['empty input string', '', defaultEnv, ''],
|
||||
[
|
||||
'complex paths',
|
||||
'${HOME}/bin:$PATH',
|
||||
{ ...defaultEnv, PATH: '/usr/bin' },
|
||||
'/home/morty/bin:/usr/bin',
|
||||
],
|
||||
])('should handle %s', (_, input, env, expected) => {
|
||||
expect(expandEnvVars(input, env)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Windows behavior', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['$VAR (POSIX)', 'Hello $USER', defaultEnv, 'Hello morty'],
|
||||
[
|
||||
'${VAR} (POSIX)',
|
||||
'Welcome to ${HOME}',
|
||||
defaultEnv,
|
||||
'Welcome to /home/morty',
|
||||
],
|
||||
[
|
||||
'should expand %VAR% on Windows',
|
||||
'Data in %TEMP%',
|
||||
defaultEnv,
|
||||
'Data in C:\\Temp',
|
||||
],
|
||||
[
|
||||
'mixed formats (both expanded)',
|
||||
'$USER lives in ${HOME} on %TEMP%',
|
||||
defaultEnv,
|
||||
'morty lives in /home/morty on C:\\Temp',
|
||||
],
|
||||
[
|
||||
'missing variables (all expanded to empty)',
|
||||
'Missing $UNDEFINED and ${NONE} and %MISSING%',
|
||||
defaultEnv,
|
||||
'Missing and and ',
|
||||
],
|
||||
])('should handle %s', (_, input, env, expected) => {
|
||||
expect(expandEnvVars(input, env)).toBe(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
54
packages/core/src/utils/envExpansion.ts
Normal file
54
packages/core/src/utils/envExpansion.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { expand } from 'dotenv-expand';
|
||||
|
||||
/**
|
||||
* Expands environment variables in a string using the provided environment record.
|
||||
* Uses the standard `dotenv-expand` library to handle expansion consistently with
|
||||
* other tools.
|
||||
*
|
||||
* Supports POSIX/Bash syntax ($VAR, ${VAR}).
|
||||
* Note: Windows syntax (%VAR%) is not natively supported by dotenv-expand.
|
||||
*
|
||||
* @param str - The string containing environment variable placeholders.
|
||||
* @param env - A record of environment variable names and their values.
|
||||
* @returns The string with environment variables expanded. Missing variables resolve to an empty string.
|
||||
*/
|
||||
export function expandEnvVars(
|
||||
str: string,
|
||||
env: Record<string, string | undefined>,
|
||||
): string {
|
||||
if (!str) return str;
|
||||
|
||||
// 1. Pre-process Windows-style variables (%VAR%) since dotenv-expand only handles POSIX ($VAR).
|
||||
// We only do this on Windows to limit the blast radius and avoid conflicts with other
|
||||
// systems where % might be a literal character (e.g. in URLs or shell commands).
|
||||
const isWindows = process.platform === 'win32';
|
||||
const processedStr = isWindows
|
||||
? str.replace(/%(\w+)%/g, (_, name) => env[name] ?? '')
|
||||
: str;
|
||||
|
||||
// 2. Use dotenv-expand for POSIX/Bash syntax ($VAR, ${VAR}).
|
||||
// dotenv-expand is designed to process an object of key-value pairs (like a .env file).
|
||||
// To expand a single string, we wrap it in an object with a temporary key.
|
||||
const dummyKey = '__GCLI_EXPAND_TARGET__';
|
||||
|
||||
// Filter out undefined values to satisfy the Record<string, string> requirement safely
|
||||
const processEnv: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (value !== undefined) {
|
||||
processEnv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const result = expand({
|
||||
parsed: { [dummyKey]: processedStr },
|
||||
processEnv,
|
||||
});
|
||||
|
||||
return result.parsed?.[dummyKey] ?? '';
|
||||
}
|
||||
Reference in New Issue
Block a user