Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions packages/cli/src/utils/sandbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,27 @@ import {
import { createMockSandboxConfig } from '@google/gemini-cli-test-utils';
import { EventEmitter } from 'node:events';

const { mockedHomedir, mockedGetContainerPath, mockedExecCommands } =
vi.hoisted(() => ({
mockedHomedir: vi.fn().mockReturnValue('/home/user'),
mockedGetContainerPath: vi.fn().mockImplementation((p: string) => p),
mockedExecCommands: [] as string[],
}));
const {
mockedHomedir,
mockedGetContainerPath,
mockedExecCommands,
mockedPersistSandboxState,
mockedRestoreSandboxState,
} = vi.hoisted(() => ({
mockedHomedir: vi.fn().mockReturnValue('/home/user'),
mockedGetContainerPath: vi.fn().mockImplementation((p: string) => p),
mockedExecCommands: [] as string[],
mockedPersistSandboxState: vi.fn(),
mockedRestoreSandboxState: vi.fn(),
}));

vi.mock('./sandboxUtils.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('./sandboxUtils.js')>();
return {
...actual,
getContainerPath: mockedGetContainerPath,
persistSandboxState: mockedPersistSandboxState,
restoreSandboxState: mockedRestoreSandboxState,
};
});

Expand Down Expand Up @@ -1072,6 +1081,14 @@ describe('sandbox', () => {
expect.stringContaining('gemini-sandbox-'),
0o700,
);
expect(mockedRestoreSandboxState).toHaveBeenCalledWith(
'/home/user/.gemini/sandbox',
expect.stringContaining('gemini-sandbox-'),
);
expect(mockedPersistSandboxState).toHaveBeenCalledWith(
expect.stringContaining('gemini-sandbox-'),
'/home/user/.gemini/sandbox',
);
});

it('should tolerate chmod errors on non-POSIX filesystems without crashing', async () => {
Expand Down
27 changes: 24 additions & 3 deletions packages/cli/src/utils/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ import {
BUILTIN_SEATBELT_PROFILES,
isSensitiveHostPath,
sanitizeSettingsForSandbox,
persistSandboxState,
restoreSandboxState,
} from './sandboxUtils.js';
import { BUILTIN_SEATBELT_PROFILE_CONTENTS } from './sandboxBuiltinProfiles.js';

Expand All @@ -67,11 +69,25 @@ export async function start_sandbox(
let stopProxy: (() => void) | undefined = undefined;
let tempProfileFile: string | null = null;
let sandboxTmpDir: string | null = null;
let sandboxStateDir: string | null = null;

const cleanup = () => {
if (sandboxTmpDir) {
const dirToDelete = sandboxTmpDir;
const stateDir = sandboxStateDir;
sandboxTmpDir = null;
sandboxStateDir = null;

if (stateDir && fs.existsSync(dirToDelete)) {
try {
persistSandboxState(dirToDelete, stateDir);
} catch (err) {
debugLogger.warn(
`Failed to persist sandbox state: ${err instanceof Error ? err.message : String(err)}`,
);
}
}

try {
if (fs.existsSync(dirToDelete)) {
fs.rmSync(dirToDelete, { recursive: true, force: true });
Expand Down Expand Up @@ -524,9 +540,9 @@ export async function start_sandbox(
}
}

// Sanitize user settings before mounting into the sandbox container.
// We STRICTLY do NOT mount ~/.gemini root directory or sensitive credential files
// (oauth_creds.json, .env, etc.). We only mount the sanitized settings file as read-only (:ro).
// Sanitize user settings before mounting into the sandbox container. We do
// not expose the user's normal ~/.gemini credentials. State created by the
// sandbox is restored from a separate, sandbox-only directory instead.
const userHomeDirOnHost = homedir();
let rawSettings: Record<string, unknown> = {};

Expand Down Expand Up @@ -560,6 +576,11 @@ export async function start_sandbox(
{ mode: 0o600 },
);

if (userHomeDirOnHost) {
sandboxStateDir = path.join(userHomeDirOnHost, GEMINI_DIR, 'sandbox');
restoreSandboxState(sandboxStateDir, sandboxTmpDir);
}

// Mount isolated sanitized settings directory inside container
const userSettingsDirInSandbox = getContainerPath(
`/home/node/${GEMINI_DIR}`,
Expand Down
141 changes: 141 additions & 0 deletions packages/cli/src/utils/sandboxUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import {
isCredentialOrSensitivePath,
prepareIsolatedSettingsDir,
SENSITIVE_SETTINGS_FILENAMES,
SANDBOX_PERSISTED_STATE_ENTRIES,
persistSandboxState,
restoreSandboxState,
} from './sandboxUtils.js';

vi.mock('node:os');
Expand Down Expand Up @@ -110,6 +113,8 @@ describe('sandboxUtils', () => {
beforeEach(() => {
vi.mocked(os.platform).mockReturnValue('linux');
vi.mocked(fs.existsSync).mockReturnValue(false);
vi.stubEnv('PATH', '');
vi.stubEnv('PYTHONPATH', '');
});

it('should generate default entrypoint', () => {
Expand Down Expand Up @@ -762,4 +767,140 @@ describe('sandboxUtils', () => {
expect(fs.cpSync).not.toHaveBeenCalled();
});
});

describe('sandbox state persistence', () => {
const sandboxSettingsDir = '/tmp/gemini-sandbox-xyz';
const sandboxStateDir = '/home/user/.gemini/sandbox';

it('should persist only explicitly approved sandbox state', () => {
vi.mocked(fs.existsSync).mockImplementation((target) => {
const value = String(target);
return (
value === path.join(sandboxSettingsDir, 'oauth_creds.json') ||
value === path.join(sandboxSettingsDir, 'trustedFolders.json') ||
value === path.join(sandboxSettingsDir, 'tmp') ||
value === path.join(sandboxSettingsDir, 'settings.json')
);
});
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({
security: {
auth: {
selectedType: 'oauth-personal',
useExternal: true,
enforcedType: 'should-not-persist',
},
},
hooks: { BeforeAgent: [{ command: 'unsafe' }] },
}),
);

persistSandboxState(sandboxSettingsDir, sandboxStateDir);

expect(fs.mkdirSync).toHaveBeenCalledWith(sandboxStateDir, {
recursive: true,
mode: 0o700,
});
expect(fs.chmodSync).toHaveBeenCalledWith(sandboxStateDir, 0o700);
expect(fs.cpSync).toHaveBeenCalledWith(
path.join(sandboxSettingsDir, 'oauth_creds.json'),
path.join(sandboxStateDir, 'oauth_creds.json'),
{ recursive: true, force: true },
);
expect(fs.cpSync).toHaveBeenCalledWith(
path.join(sandboxSettingsDir, 'trustedFolders.json'),
path.join(sandboxStateDir, 'trustedFolders.json'),
{ recursive: true, force: true },
);
expect(fs.cpSync).toHaveBeenCalledWith(
path.join(sandboxSettingsDir, 'tmp'),
path.join(sandboxStateDir, 'tmp'),
{ recursive: true, force: true },
);
expect(fs.cpSync).not.toHaveBeenCalledWith(
path.join(sandboxSettingsDir, 'settings.json'),
expect.anything(),
expect.anything(),
);

const authSettingsWrite = vi
.mocked(fs.writeFileSync)
.mock.calls.find(
([target]) =>
String(target) === path.join(sandboxStateDir, 'auth-settings.json'),
);
expect(authSettingsWrite).toBeDefined();
expect(JSON.parse(String(authSettingsWrite?.[1]))).toEqual({
selectedType: 'oauth-personal',
useExternal: true,
});
});

it('should restore persisted state and merge only authentication settings', () => {
vi.mocked(fs.existsSync).mockImplementation((target) => {
const value = String(target);
return (
value === sandboxStateDir ||
value === path.join(sandboxStateDir, 'oauth_creds.json') ||
value === path.join(sandboxStateDir, 'trustedFolders.json') ||
value === path.join(sandboxStateDir, 'tmp') ||
value === path.join(sandboxStateDir, 'auth-settings.json') ||
value === path.join(sandboxSettingsDir, 'settings.json')
);
});
vi.mocked(fs.readFileSync).mockImplementation((target) => {
if (String(target).endsWith('auth-settings.json')) {
return JSON.stringify({
selectedType: 'oauth-personal',
useExternal: true,
hooks: 'ignored',
});
}
return JSON.stringify({
theme: 'dark',
security: { auth: { enforcedType: 'oauth-personal' } },
});
});

restoreSandboxState(sandboxStateDir, sandboxSettingsDir);

for (const entry of ['oauth_creds.json', 'trustedFolders.json', 'tmp']) {
expect(fs.cpSync).toHaveBeenCalledWith(
path.join(sandboxStateDir, entry),
path.join(sandboxSettingsDir, entry),
{ recursive: true, force: true },
);
}

const settingsWrite = vi
.mocked(fs.writeFileSync)
.mock.calls.find(
([target]) =>
String(target) === path.join(sandboxSettingsDir, 'settings.json'),
);
expect(settingsWrite).toBeDefined();
expect(JSON.parse(String(settingsWrite?.[1]))).toEqual({
theme: 'dark',
security: {
auth: {
enforcedType: 'oauth-personal',
selectedType: 'oauth-personal',
useExternal: true,
},
},
});
});

it('should include authentication, trust, and session paths in the allowlist', () => {
expect(SANDBOX_PERSISTED_STATE_ENTRIES).toEqual(
expect.arrayContaining([
'oauth_creds.json',
'google_accounts.json',
'trustedFolders.json',
'history',
'tmp',
]),
);
});
});
});
Loading
Loading