Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
33 changes: 31 additions & 2 deletions packages/cli/src/config/trustedFolders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ vi.mock('fs', async (importOriginal) => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
renameSync: vi.fn(),
unlinkSync: vi.fn(),
realpathSync: vi.fn().mockImplementation((p) => p),
};
});
Expand All @@ -70,12 +72,14 @@ vi.mock('strip-json-comments', () => ({
describe('Trusted Folders Loading', () => {
let mockStripJsonComments: Mocked<typeof stripJsonComments>;
let mockFsWriteFileSync: Mocked<typeof fs.writeFileSync>;
let mockFsRenameSync: Mocked<typeof fs.renameSync>;

beforeEach(() => {
resetTrustedFoldersForTesting();
vi.resetAllMocks();
mockStripJsonComments = vi.mocked(stripJsonComments);
mockFsWriteFileSync = vi.mocked(fs.writeFileSync);
mockFsRenameSync = vi.mocked(fs.renameSync);
vi.mocked(osActual.homedir).mockReturnValue('/mock/home/user');
(mockStripJsonComments as unknown as Mock).mockImplementation(
(jsonString: string) => jsonString,
Expand Down Expand Up @@ -248,18 +252,43 @@ describe('Trusted Folders Loading', () => {
delete process.env['GEMINI_CLI_TRUSTED_FOLDERS_PATH'];
});

it('setValue should update the user config and save it', () => {
it('setValue should update the user config and save it atomically', () => {
const loadedFolders = loadTrustedFolders();
loadedFolders.setValue('/new/path', TrustLevel.TRUST_FOLDER);

expect(loadedFolders.user.config['/new/path']).toBe(
TrustLevel.TRUST_FOLDER,
);
expect(mockFsWriteFileSync).toHaveBeenCalledWith(
getTrustedFoldersPath(),
expect.stringContaining('trustedFolders.json.tmp.'),
JSON.stringify({ '/new/path': TrustLevel.TRUST_FOLDER }, null, 2),
{ encoding: 'utf-8', mode: 0o600 },
);
expect(mockFsRenameSync).toHaveBeenCalledWith(
expect.stringContaining('trustedFolders.json.tmp.'),
getTrustedFoldersPath(),
);
});

it('setValue should throw FatalConfigError if there were load errors', () => {
const userPath = getTrustedFoldersPath();
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockImplementation((p) => {
if (p === userPath) return 'invalid json';
return '{}';
});

const loadedFolders = loadTrustedFolders();
expect(loadedFolders.errors.length).toBe(1);

expect(() =>
loadedFolders.setValue('/some/path', TrustLevel.TRUST_FOLDER),
).toThrow(FatalConfigError);
expect(() =>
loadedFolders.setValue('/some/path', TrustLevel.TRUST_FOLDER),
).toThrow(
/Cannot update trusted folders because the configuration file is invalid/,
);
});
});

Expand Down
35 changes: 30 additions & 5 deletions packages/cli/src/config/trustedFolders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ export class LoadedTrustedFolders {
}

setValue(path: string, trustLevel: TrustLevel): void {
if (this.errors.length > 0) {
const errorMessages = this.errors.map(
(error) => `Error in ${error.path}: ${error.message}`,
);
throw new FatalConfigError(
`Cannot update trusted folders because the configuration file is invalid:\n${errorMessages.join('\n')}\nPlease fix the file manually before trying to update it.`,
);
}

const originalTrustLevel = this.user.config[path];
this.user.config[path] = trustLevel;
try {
Expand Down Expand Up @@ -241,11 +250,27 @@ export function saveTrustedFolders(
fs.mkdirSync(dirPath, { recursive: true });
}

fs.writeFileSync(
trustedFoldersFile.path,
JSON.stringify(trustedFoldersFile.config, null, 2),
{ encoding: 'utf-8', mode: 0o600 },
);
const tempPath = `${trustedFoldersFile.path}.tmp.${Math.random().toString(36).slice(2)}`;
try {
fs.writeFileSync(
tempPath,
JSON.stringify(trustedFoldersFile.config, null, 2),
{
encoding: 'utf-8',
mode: 0o600,
},
);
fs.renameSync(tempPath, trustedFoldersFile.path);
} catch (error) {
if (fs.existsSync(tempPath)) {
try {
fs.unlinkSync(tempPath);
} catch {
// Ignore errors during cleanup
}
}
throw error;
}
}

/** Is folder trust feature enabled per the current applied settings */
Expand Down
Loading