feat(cli): disable folder trust in headless mode (#18407)

This commit is contained in:
Gal Zahavi
2026-02-09 15:46:49 -08:00
committed by GitHub
parent 80057c5208
commit bce1caefd0
14 changed files with 587 additions and 48 deletions

View File

@@ -141,6 +141,22 @@ vi.mock('@google/gemini-cli-core', async () => {
defaultDecision: ServerConfig.PolicyDecision.ASK_USER,
approvalMode: ServerConfig.ApprovalMode.DEFAULT,
})),
isHeadlessMode: vi.fn((opts) => {
if (process.env['VITEST'] === 'true') {
return (
!!opts?.prompt ||
(!!process.stdin && !process.stdin.isTTY) ||
(!!process.stdout && !process.stdout.isTTY)
);
}
return (
!!opts?.prompt ||
process.env['CI'] === 'true' ||
process.env['GITHUB_ACTIONS'] === 'true' ||
(!!process.stdin && !process.stdin.isTTY) ||
(!!process.stdout && !process.stdout.isTTY)
);
}),
};
});
@@ -154,6 +170,8 @@ vi.mock('./extension-manager.js', () => {
// Global setup to ensure clean environment for all tests in this file
const originalArgv = process.argv;
const originalGeminiModel = process.env['GEMINI_MODEL'];
const originalStdoutIsTTY = process.stdout.isTTY;
const originalStdinIsTTY = process.stdin.isTTY;
beforeEach(() => {
delete process.env['GEMINI_MODEL'];
@@ -162,6 +180,18 @@ beforeEach(() => {
ExtensionManager.prototype.loadExtensions = vi
.fn()
.mockResolvedValue(undefined);
// Default to interactive mode for tests unless otherwise specified
Object.defineProperty(process.stdout, 'isTTY', {
value: true,
configurable: true,
writable: true,
});
Object.defineProperty(process.stdin, 'isTTY', {
value: true,
configurable: true,
writable: true,
});
});
afterEach(() => {
@@ -171,6 +201,16 @@ afterEach(() => {
} else {
delete process.env['GEMINI_MODEL'];
}
Object.defineProperty(process.stdout, 'isTTY', {
value: originalStdoutIsTTY,
configurable: true,
writable: true,
});
Object.defineProperty(process.stdin, 'isTTY', {
value: originalStdinIsTTY,
configurable: true,
writable: true,
});
});
describe('parseArguments', () => {
@@ -249,6 +289,16 @@ describe('parseArguments', () => {
});
describe('positional arguments and @commands', () => {
beforeEach(() => {
// Default to headless mode for these tests as they mostly expect one-shot behavior
process.stdin.isTTY = false;
Object.defineProperty(process.stdout, 'isTTY', {
value: false,
configurable: true,
writable: true,
});
});
it.each([
{
description:
@@ -379,8 +429,12 @@ describe('parseArguments', () => {
);
it('should include a startup message when converting positional query to interactive prompt', async () => {
const originalIsTTY = process.stdin.isTTY;
process.stdin.isTTY = true;
Object.defineProperty(process.stdout, 'isTTY', {
value: true,
configurable: true,
writable: true,
});
process.argv = ['node', 'script.js', 'hello'];
try {
@@ -389,7 +443,7 @@ describe('parseArguments', () => {
'Positional arguments now default to interactive mode. To run in non-interactive mode, use the --prompt (-p) flag.',
);
} finally {
process.stdin.isTTY = originalIsTTY;
// beforeEach handles resetting
}
});
});
@@ -1732,14 +1786,29 @@ describe('loadCliConfig model selection', () => {
});
describe('loadCliConfig folderTrust', () => {
let originalVitest: string | undefined;
let originalIntegrationTest: string | undefined;
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(os.homedir).mockReturnValue('/mock/home/user');
vi.stubEnv('GEMINI_API_KEY', 'test-api-key');
vi.spyOn(ExtensionManager.prototype, 'getExtensions').mockReturnValue([]);
originalVitest = process.env['VITEST'];
originalIntegrationTest = process.env['GEMINI_CLI_INTEGRATION_TEST'];
delete process.env['VITEST'];
delete process.env['GEMINI_CLI_INTEGRATION_TEST'];
});
afterEach(() => {
if (originalVitest !== undefined) {
process.env['VITEST'] = originalVitest;
}
if (originalIntegrationTest !== undefined) {
process.env['GEMINI_CLI_INTEGRATION_TEST'] = originalIntegrationTest;
}
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
@@ -2779,6 +2848,16 @@ describe('Output format', () => {
describe('parseArguments with positional prompt', () => {
const originalArgv = process.argv;
beforeEach(() => {
// Default to headless mode for these tests as they mostly expect one-shot behavior
process.stdin.isTTY = false;
Object.defineProperty(process.stdout, 'isTTY', {
value: false,
configurable: true,
writable: true,
});
});
afterEach(() => {
process.argv = originalArgv;
});

View File

@@ -35,6 +35,7 @@ import {
coreEvents,
GEMINI_MODEL_ALIAS_AUTO,
getAdminErrorMessage,
isHeadlessMode,
Config,
applyAdminAllowlist,
getAdminBlockedMcpServersMessage,
@@ -352,7 +353,7 @@ export async function parseArguments(
// -p/--prompt forces non-interactive mode; positional args default to interactive in TTY
if (q && !result['prompt']) {
if (process.stdin.isTTY) {
if (!isHeadlessMode()) {
startupMessages.push(
'Positional arguments now default to interactive mode. To run in non-interactive mode, use the --prompt (-p) flag.',
);
@@ -436,7 +437,11 @@ export async function loadCliConfig(
const ideMode = settings.ide?.enabled ?? false;
const folderTrust = settings.security?.folderTrust?.enabled ?? false;
const folderTrust =
process.env['GEMINI_CLI_INTEGRATION_TEST'] === 'true' ||
process.env['VITEST'] === 'true'
? false
: (settings.security?.folderTrust?.enabled ?? false);
const trustedFolder = isWorkspaceTrusted(settings, cwd)?.isTrusted ?? false;
// Set the context filename in the server's memoryTool module BEFORE loading memory
@@ -592,7 +597,9 @@ export async function loadCliConfig(
const interactive =
!!argv.promptInteractive ||
!!argv.experimentalAcp ||
(process.stdin.isTTY && !argv.query && !argv.prompt && !argv.isCommand);
(!isHeadlessMode({ prompt: argv.prompt }) &&
!argv.query &&
!argv.isCommand);
const allowedTools = argv.allowedTools || settings.tools?.allowed || [];
const allowedToolsSet = new Set(allowedTools);

View File

@@ -32,6 +32,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
return {
...actual,
homedir: () => '/mock/home/user',
isHeadlessMode: vi.fn(() => false),
coreEvents: {
emitFeedback: vi.fn(),
},
@@ -280,6 +281,26 @@ describe('Trusted Folders', () => {
});
});
it('should return true for a child of a trusted folder', () => {
const config = { '/projectA': TrustLevel.TRUST_FOLDER };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(isWorkspaceTrusted(mockSettings, '/projectA/src')).toEqual({
isTrusted: true,
source: 'file',
});
});
it('should return true for a child of a trusted parent folder', () => {
const config = { '/projectB/somefile.txt': TrustLevel.TRUST_PARENT };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(isWorkspaceTrusted(mockSettings, '/projectB')).toEqual({
isTrusted: true,
source: 'file',
});
});
it('should return false for a directly untrusted folder', () => {
const config = { '/untrusted': TrustLevel.DO_NOT_TRUST };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
@@ -290,6 +311,15 @@ describe('Trusted Folders', () => {
});
});
it('should return false for a child of an untrusted folder', () => {
const config = { '/untrusted': TrustLevel.DO_NOT_TRUST };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(isWorkspaceTrusted(mockSettings, '/untrusted/src').isTrusted).toBe(
false,
);
});
it('should return undefined when no rules match', () => {
fs.writeFileSync(trustedFoldersPath, '{}', 'utf-8');
expect(
@@ -297,6 +327,47 @@ describe('Trusted Folders', () => {
).toBeUndefined();
});
it('should prioritize specific distrust over parent trust', () => {
const config = {
'/projectA': TrustLevel.TRUST_FOLDER,
'/projectA/untrusted': TrustLevel.DO_NOT_TRUST,
};
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(isWorkspaceTrusted(mockSettings, '/projectA/untrusted')).toEqual({
isTrusted: false,
source: 'file',
});
});
it('should use workspaceDir instead of process.cwd() when provided', () => {
const config = {
'/projectA': TrustLevel.TRUST_FOLDER,
'/untrusted': TrustLevel.DO_NOT_TRUST,
};
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
vi.spyOn(process, 'cwd').mockImplementation(() => '/untrusted');
// process.cwd() is untrusted, but workspaceDir is trusted
expect(isWorkspaceTrusted(mockSettings, '/projectA')).toEqual({
isTrusted: true,
source: 'file',
});
});
it('should handle path normalization', () => {
const config = { '/home/user/projectA': TrustLevel.TRUST_FOLDER };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(
isWorkspaceTrusted(mockSettings, '/home/user/../user/projectA'),
).toEqual({
isTrusted: true,
source: 'file',
});
});
it('should prioritize IDE override over file config', () => {
const config = { '/projectA': TrustLevel.DO_NOT_TRUST };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
@@ -313,6 +384,30 @@ describe('Trusted Folders', () => {
}
});
it('should return false when IDE override is false', () => {
const config = { '/projectA': TrustLevel.TRUST_FOLDER };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
ideContextStore.set({ workspaceState: { isTrusted: false } });
try {
expect(isWorkspaceTrusted(mockSettings, '/projectA')).toEqual({
isTrusted: false,
source: 'ide',
});
} finally {
ideContextStore.clear();
}
});
it('should throw FatalConfigError when the config file is invalid', () => {
fs.writeFileSync(trustedFoldersPath, 'invalid json', 'utf-8');
expect(() => isWorkspaceTrusted(mockSettings, '/any')).toThrow(
FatalConfigError,
);
});
it('should always return true if folderTrust setting is disabled', () => {
const disabledSettings: Settings = {
security: { folderTrust: { enabled: false } },
@@ -324,7 +419,75 @@ describe('Trusted Folders', () => {
});
});
describe('isWorkspaceTrusted headless mode', () => {
const mockSettings: Settings = {
security: {
folderTrust: {
enabled: true,
},
},
};
it('should return true when isHeadlessMode is true, ignoring config', async () => {
const geminiCore = await import('@google/gemini-cli-core');
vi.spyOn(geminiCore, 'isHeadlessMode').mockReturnValue(true);
expect(isWorkspaceTrusted(mockSettings)).toEqual({
isTrusted: true,
source: undefined,
});
});
it('should fall back to config when isHeadlessMode is false', async () => {
const geminiCore = await import('@google/gemini-cli-core');
vi.spyOn(geminiCore, 'isHeadlessMode').mockReturnValue(false);
const config = { '/projectA': TrustLevel.DO_NOT_TRUST };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
expect(isWorkspaceTrusted(mockSettings, '/projectA').isTrusted).toBe(
false,
);
});
});
describe('Trusted Folders Caching', () => {
it('should cache the loaded folders object', () => {
// First call should load and cache
const folders1 = loadTrustedFolders();
// Second call should return the same instance from cache
const folders2 = loadTrustedFolders();
expect(folders1).toBe(folders2);
// Resetting should clear the cache
resetTrustedFoldersForTesting();
// Third call should return a new instance
const folders3 = loadTrustedFolders();
expect(folders3).not.toBe(folders1);
});
});
describe('invalid trust levels', () => {
it('should create a comprehensive error message for invalid trust level', () => {
const config = { '/user/folder': 'INVALID_TRUST_LEVEL' };
fs.writeFileSync(trustedFoldersPath, JSON.stringify(config), 'utf-8');
const { errors } = loadTrustedFolders();
const possibleValues = Object.values(TrustLevel).join(', ');
expect(errors.length).toBe(1);
expect(errors[0].message).toBe(
`Invalid trust level "INVALID_TRUST_LEVEL" for path "/user/folder". Possible values are: ${possibleValues}.`,
);
});
});
describe('Symlinks Support', () => {
const mockSettings: Settings = {
security: { folderTrust: { enabled: true } },
};
it('should trust a folder if the rule matches the realpath', () => {
// Create a real directory and a symlink
const realDir = path.join(tempDir, 'real');
@@ -339,10 +502,6 @@ describe('Trusted Folders', () => {
// Check against symlink path
expect(isWorkspaceTrusted(mockSettings, symlinkDir).isTrusted).toBe(true);
});
const mockSettings: Settings = {
security: { folderTrust: { enabled: true } },
};
});
describe('Verification: Auth and Trust Interaction', () => {

View File

@@ -15,6 +15,7 @@ import {
ideContextStore,
GEMINI_DIR,
homedir,
isHeadlessMode,
coreEvents,
} from '@google/gemini-cli-core';
import type { Settings } from './settings.js';
@@ -354,6 +355,10 @@ export function isWorkspaceTrusted(
workspaceDir: string = process.cwd(),
trustConfig?: Record<string, TrustLevel>,
): TrustResult {
if (isHeadlessMode()) {
return { isTrusted: true, source: undefined };
}
if (!isFolderTrustEnabled(settings)) {
return { isTrusted: true, source: undefined };
}

View File

@@ -23,11 +23,22 @@ import { FolderTrustChoice } from '../components/FolderTrustDialog.js';
import type { LoadedTrustedFolders } from '../../config/trustedFolders.js';
import { TrustLevel } from '../../config/trustedFolders.js';
import * as trustedFolders from '../../config/trustedFolders.js';
import { coreEvents, ExitCodes } from '@google/gemini-cli-core';
import { coreEvents, ExitCodes, isHeadlessMode } from '@google/gemini-cli-core';
import { MessageType } from '../types.js';
const mockedCwd = vi.hoisted(() => vi.fn());
const mockedExit = vi.hoisted(() => vi.fn());
vi.mock('@google/gemini-cli-core', async () => {
const actual = await vi.importActual<
typeof import('@google/gemini-cli-core')
>('@google/gemini-cli-core');
return {
...actual,
isHeadlessMode: vi.fn().mockReturnValue(false),
};
});
vi.mock('node:process', async () => {
const actual =
await vi.importActual<typeof import('node:process')>('node:process');
@@ -46,8 +57,24 @@ describe('useFolderTrust', () => {
let onTrustChange: (isTrusted: boolean | undefined) => void;
let addItem: Mock;
const originalStdoutIsTTY = process.stdout.isTTY;
const originalStdinIsTTY = process.stdin.isTTY;
beforeEach(() => {
vi.useFakeTimers();
// Default to interactive mode for tests
Object.defineProperty(process.stdout, 'isTTY', {
value: true,
configurable: true,
writable: true,
});
Object.defineProperty(process.stdin, 'isTTY', {
value: true,
configurable: true,
writable: true,
});
mockSettings = {
merged: {
security: {
@@ -75,6 +102,16 @@ describe('useFolderTrust', () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
Object.defineProperty(process.stdout, 'isTTY', {
value: originalStdoutIsTTY,
configurable: true,
writable: true,
});
Object.defineProperty(process.stdin, 'isTTY', {
value: originalStdinIsTTY,
configurable: true,
writable: true,
});
});
it('should not open dialog when folder is already trusted', () => {
@@ -318,4 +355,28 @@ describe('useFolderTrust', () => {
);
expect(mockedExit).toHaveBeenCalledWith(ExitCodes.FATAL_CONFIG_ERROR);
});
describe('headless mode', () => {
it('should force trust and hide dialog in headless mode', () => {
vi.mocked(isHeadlessMode).mockReturnValue(true);
isWorkspaceTrustedSpy.mockReturnValue({
isTrusted: false,
source: 'file',
});
const { result } = renderHook(() =>
useFolderTrust(mockSettings, onTrustChange, addItem),
);
expect(result.current.isFolderTrustDialogOpen).toBe(false);
expect(onTrustChange).toHaveBeenCalledWith(true);
expect(addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: expect.stringContaining('This folder is untrusted'),
}),
expect.any(Number),
);
});
});
});

View File

@@ -14,7 +14,7 @@ import {
} from '../../config/trustedFolders.js';
import * as process from 'node:process';
import { type HistoryItemWithoutId, MessageType } from '../types.js';
import { coreEvents, ExitCodes } from '@google/gemini-cli-core';
import { coreEvents, ExitCodes, isHeadlessMode } from '@google/gemini-cli-core';
import { runExitCleanup } from '../../utils/cleanup.js';
export const useFolderTrust = (
@@ -30,21 +30,39 @@ export const useFolderTrust = (
const folderTrust = settings.merged.security.folderTrust.enabled ?? true;
useEffect(() => {
let isMounted = true;
const { isTrusted: trusted } = isWorkspaceTrusted(settings.merged);
setIsTrusted(trusted);
setIsFolderTrustDialogOpen(trusted === undefined);
onTrustChange(trusted);
if (trusted === false && !startupMessageSent.current) {
addItem(
{
type: MessageType.INFO,
text: 'This folder is untrusted, project settings, hooks, MCPs, and GEMINI.md files will not be applied for this folder.\nUse the `/permissions` command to change the trust level.',
},
Date.now(),
);
startupMessageSent.current = true;
const showUntrustedMessage = () => {
if (trusted === false && !startupMessageSent.current) {
addItem(
{
type: MessageType.INFO,
text: 'This folder is untrusted, project settings, hooks, MCPs, and GEMINI.md files will not be applied for this folder.\nUse the `/permissions` command to change the trust level.',
},
Date.now(),
);
startupMessageSent.current = true;
}
};
if (isHeadlessMode()) {
if (isMounted) {
setIsTrusted(trusted);
setIsFolderTrustDialogOpen(false);
onTrustChange(true);
showUntrustedMessage();
}
} else if (isMounted) {
setIsTrusted(trusted);
setIsFolderTrustDialogOpen(trusted === undefined);
onTrustChange(trusted);
showUntrustedMessage();
}
return () => {
isMounted = false;
};
}, [folderTrust, onTrustChange, settings.merged, addItem]);
const handleFolderTrustSelect = useCallback(