File size: 18,586 Bytes
9332ccf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import { Text } from 'ink';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import { render, cleanup } from '../../test-utils/render.js';
import {
requestConsentNonInteractive,
requestConsentInteractive,
maybeRequestConsentOrFail,
} from './consent.js';
import type { ConfirmationRequest } from '../../ui/types.js';
import type { ExtensionConfig } from '../extension.js';
import { debugLogger, type SkillDefinition } from '@google/gemini-cli-core';
const mockReadline = vi.hoisted(() => ({
createInterface: vi.fn().mockReturnValue({
question: vi.fn(),
close: vi.fn(),
}),
}));
const mockReaddir = vi.hoisted(() => vi.fn());
const originalReaddir = vi.hoisted(() => ({
current: null as typeof fs.readdir | null,
}));
// Mocking readline for non-interactive prompts
vi.mock('node:readline', () => ({
default: mockReadline,
createInterface: mockReadline.createInterface,
}));
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
originalReaddir.current = actual.readdir;
return {
...actual,
readdir: mockReaddir,
};
});
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
debugLogger: {
log: vi.fn(),
},
};
});
async function expectConsentSnapshot(consentString: string) {
const renderResult = await render(
React.createElement(Text, null, consentString),
);
await expect(renderResult).toMatchSvgSnapshot();
}
/**
* Normalizes a consent string for snapshot testing by:
* 1. Replacing the dynamic temp directory path with a static placeholder.
* 2. Converting Windows backslashes to forward slashes for platform-agnosticism.
*/
function normalizePathsForSnapshot(str: string, tempDir: string): string {
return str.replaceAll(tempDir, '/mock/temp/dir').replaceAll('\\', '/');
}
describe('consent', () => {
let tempDir: string;
beforeEach(async () => {
vi.clearAllMocks();
if (originalReaddir.current) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockReaddir.mockImplementation(originalReaddir.current as any);
}
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'consent-test-'));
});
afterEach(async () => {
vi.restoreAllMocks();
if (tempDir) {
await fs.rm(tempDir, { recursive: true, force: true });
}
cleanup();
});
describe('requestConsentNonInteractive', () => {
it.each([
{ input: 'y', expected: true },
{ input: 'Y', expected: true },
{ input: '', expected: true },
{ input: 'n', expected: false },
{ input: 'N', expected: false },
{ input: 'yes', expected: true },
])(
'should return $expected for input "$input"',
async ({ input, expected }) => {
const questionMock = vi.fn().mockImplementation((_, callback) => {
callback(input);
});
mockReadline.createInterface.mockReturnValue({
question: questionMock,
close: vi.fn(),
});
const consent = await requestConsentNonInteractive('Test consent');
expect(debugLogger.log).toHaveBeenCalledWith('Test consent');
expect(questionMock).toHaveBeenCalledWith(
'Do you want to continue? [Y/n]: ',
expect.any(Function),
);
expect(consent).toBe(expected);
},
);
});
describe('requestConsentInteractive', () => {
it.each([
{ confirmed: true, expected: true },
{ confirmed: false, expected: false },
])(
'should resolve with $expected when user confirms with $confirmed',
async ({ confirmed, expected }) => {
const addExtensionUpdateConfirmationRequest = vi
.fn()
.mockImplementation((request: ConfirmationRequest) => {
request.onConfirm(confirmed);
});
const consent = await requestConsentInteractive(
'Test consent',
addExtensionUpdateConfirmationRequest,
);
expect(addExtensionUpdateConfirmationRequest).toHaveBeenCalledWith({
prompt: 'Test consent\n\nDo you want to continue?',
onConfirm: expect.any(Function),
});
expect(consent).toBe(expected);
},
);
it('should clear the active confirmation request before resolving', async () => {
const clearConfirmationRequest = vi.fn();
const steps: string[] = [];
const addExtensionUpdateConfirmationRequest = vi
.fn()
.mockImplementation((request: ConfirmationRequest) => {
steps.push('prompted');
request.onConfirm(true);
steps.push('confirmed');
});
const consentPromise = requestConsentInteractive(
'Test consent',
addExtensionUpdateConfirmationRequest,
() => {
steps.push('cleared');
clearConfirmationRequest();
},
).then((consent) => {
steps.push('resolved');
return consent;
});
expect(clearConfirmationRequest).toHaveBeenCalledTimes(1);
expect(steps).toEqual(['prompted', 'cleared', 'confirmed']);
await expect(consentPromise).resolves.toBe(true);
expect(steps).toEqual(['prompted', 'cleared', 'confirmed', 'resolved']);
});
});
describe('maybeRequestConsentOrFail', () => {
const baseConfig: ExtensionConfig = {
name: 'test-ext',
version: '1.0.0',
};
it('should request consent if there is no previous config', async () => {
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
false,
undefined,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should not request consent if configs are identical', async () => {
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
false,
baseConfig,
false,
);
expect(requestConsent).not.toHaveBeenCalled();
});
it('should throw an error if consent is denied', async () => {
const requestConsent = vi.fn().mockResolvedValue(false);
await expect(
maybeRequestConsentOrFail(baseConfig, requestConsent, false, undefined),
).rejects.toThrow('Installation cancelled for "test-ext".');
});
describe('consent string generation', () => {
it('should generate a consent string with all fields', async () => {
const config: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: { command: 'npm', args: ['start'] },
server2: { httpUrl: 'https://remote.com' },
},
contextFileName: 'my-context.md',
excludeTools: ['tool1', 'tool2'],
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
config,
requestConsent,
false,
undefined,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
const consentString = requestConsent.mock.calls[0][0] as string;
await expectConsentSnapshot(consentString);
});
it('should sort environment variables alphabetically and handle undefined envValue', async () => {
const config: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: {
command: 'node',
args: ['server.js'],
env: {
VAR_B: 'b',
VAR_A: 'a',
VAR_C: undefined as unknown as string,
},
},
},
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
config,
requestConsent,
false,
undefined,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
const consentString = requestConsent.mock.calls[0][0] as string;
expect(consentString).toContain(' - VAR_A: a');
expect(consentString).toContain(' - VAR_B: b');
expect(consentString).toContain(' - VAR_C: ');
const posA = consentString.indexOf(' - VAR_A: a');
const posB = consentString.indexOf(' - VAR_B: b');
const posC = consentString.indexOf(' - VAR_C: ');
expect(posA).toBeLessThan(posB);
expect(posB).toBeLessThan(posC);
});
it('should mask sensitive environment variables, headers, and OAuth parameters', async () => {
const config: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: {
command: 'node',
args: ['server.js'],
env: {
SAFE_VAR: 'safe-value',
SUPER_TOKEN: 'secret-token-123',
DB_PASSWORD: 'my-password',
},
headers: {
'X-API-Key': 'some-api-key',
Authorization: 'Bearer 12345',
'Content-Type': 'application/json',
},
oauth: {
clientId: 'my-client-id',
clientSecret: 'secret-oauth-value',
},
},
},
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
config,
requestConsent,
false,
undefined,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
const consentString = requestConsent.mock.calls[0][0] as string;
// Assert sensitive env values are masked
expect(consentString).toContain(' - SAFE_VAR: safe-value');
expect(consentString).toContain(' - SUPER_TOKEN: ********');
expect(consentString).toContain(' - DB_PASSWORD: ********');
// Assert sensitive headers are masked
expect(consentString).toContain(
' - Content-Type: application/json',
);
expect(consentString).toContain(' - Authorization: ********');
expect(consentString).toContain(' - X-API-Key: ********');
// Assert sensitive OAuth parameters are masked
expect(consentString).toContain(' - clientId: my-client-id');
expect(consentString).toContain(' - clientSecret: ********');
});
it('should request consent if mcpServers change', async () => {
const prevConfig: ExtensionConfig = { ...baseConfig };
const newConfig: ExtensionConfig = {
...baseConfig,
mcpServers: { server1: { command: 'npm', args: ['start'] } },
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
newConfig,
requestConsent,
false,
prevConfig,
false,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should request consent if mcpServer env changes', async () => {
const prevConfig: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: { command: 'node', args: ['server.js'] },
},
};
const newConfig: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: {
command: 'node',
args: ['server.js'],
env: { NODE_OPTIONS: '--require=./payload.js' },
},
},
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
newConfig,
requestConsent,
false,
prevConfig,
false,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should request consent if contextFileName changes', async () => {
const prevConfig: ExtensionConfig = { ...baseConfig };
const newConfig: ExtensionConfig = {
...baseConfig,
contextFileName: 'new-context.md',
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
newConfig,
requestConsent,
false,
prevConfig,
false,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should request consent if excludeTools changes', async () => {
const prevConfig: ExtensionConfig = { ...baseConfig };
const newConfig: ExtensionConfig = {
...baseConfig,
excludeTools: ['new-tool'],
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
newConfig,
requestConsent,
false,
prevConfig,
false,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should include warning when hooks are present', async () => {
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
true,
undefined,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
const consentString = requestConsent.mock.calls[0][0] as string;
await expectConsentSnapshot(consentString);
});
it('should request consent if hooks status changes', async () => {
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
true,
baseConfig,
false,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
});
it('should request consent if extension is migrated', async () => {
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
false,
{ ...baseConfig, name: 'old-ext' },
false,
[],
[],
true,
);
expect(requestConsent).toHaveBeenCalledTimes(1);
let consentString = requestConsent.mock.calls[0][0] as string;
consentString = normalizePathsForSnapshot(consentString, tempDir);
await expectConsentSnapshot(consentString);
});
it('should request consent if skills change', async () => {
const skill1Dir = path.join(tempDir, 'skill1');
const skill2Dir = path.join(tempDir, 'skill2');
await fs.mkdir(skill1Dir, { recursive: true });
await fs.mkdir(skill2Dir, { recursive: true });
await fs.writeFile(path.join(skill1Dir, 'SKILL.md'), 'body1');
await fs.writeFile(path.join(skill1Dir, 'extra.txt'), 'extra');
await fs.writeFile(path.join(skill2Dir, 'SKILL.md'), 'body2');
const skill1: SkillDefinition = {
name: 'skill1',
description: 'desc1',
location: path.join(skill1Dir, 'SKILL.md'),
body: 'body1',
};
const skill2: SkillDefinition = {
name: 'skill2',
description: 'desc2',
location: path.join(skill2Dir, 'SKILL.md'),
body: 'body2',
};
const config: ExtensionConfig = {
...baseConfig,
mcpServers: {
server1: { command: 'npm', args: ['start'] },
server2: { httpUrl: 'https://remote.com' },
},
contextFileName: 'my-context.md',
excludeTools: ['tool1', 'tool2'],
};
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
config,
requestConsent,
false,
undefined,
false,
[skill1, skill2],
);
expect(requestConsent).toHaveBeenCalledTimes(1);
let consentString = requestConsent.mock.calls[0][0] as string;
consentString = normalizePathsForSnapshot(consentString, tempDir);
await expectConsentSnapshot(consentString);
});
it('should show a warning if the skill directory cannot be read', async () => {
const lockedDir = path.join(tempDir, 'locked');
await fs.mkdir(lockedDir, { recursive: true });
const skill: SkillDefinition = {
name: 'locked-skill',
description: 'A skill in a locked dir',
location: path.join(lockedDir, 'SKILL.md'),
body: 'body',
};
// Mock readdir to simulate a permission error.
// We do this instead of using fs.mkdir(..., { mode: 0o000 }) because
// directory permissions work differently on Windows and 0o000 doesn't
// effectively block access there, leading to test failures in Windows CI.
mockReaddir.mockRejectedValueOnce(
new Error('EACCES: permission denied, scandir'),
);
const requestConsent = vi.fn().mockResolvedValue(true);
await maybeRequestConsentOrFail(
baseConfig,
requestConsent,
false,
undefined,
false,
[skill],
);
expect(requestConsent).toHaveBeenCalledTimes(1);
let consentString = requestConsent.mock.calls[0][0] as string;
consentString = normalizePathsForSnapshot(consentString, tempDir);
await expectConsentSnapshot(consentString);
});
});
});
describe('skillsConsentString', () => {
it('should generate a consent string for skills', async () => {
const skill1Dir = path.join(tempDir, 'skill1');
await fs.mkdir(skill1Dir, { recursive: true });
await fs.writeFile(path.join(skill1Dir, 'SKILL.md'), 'body1');
const skill1: SkillDefinition = {
name: 'skill1',
description: 'desc1',
location: path.join(skill1Dir, 'SKILL.md'),
body: 'body1',
};
const { skillsConsentString } = await import('./consent.js');
let consentString = await skillsConsentString(
[skill1],
'https://example.com/repo.git',
'/mock/target/dir',
);
consentString = normalizePathsForSnapshot(consentString, tempDir);
await expectConsentSnapshot(consentString);
});
});
});
|