1
0

security.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /**
  2. * Security Tests
  3. *
  4. * Tests for P0/P1 security fixes:
  5. * - FileLock (cross-process locking)
  6. * - Path traversal prevention
  7. * - MCP input validation
  8. * - Atomic writes
  9. */
  10. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  11. import * as fs from 'fs';
  12. import * as path from 'path';
  13. import * as os from 'os';
  14. import { FileLock, validateProjectPath } from '../src/utils';
  15. import CodeGraph from '../src/index';
  16. import { ToolHandler, tools } from '../src/mcp/tools';
  17. import { scanDirectory, isSourceFile } from '../src/extraction';
  18. import { DatabaseConnection, getDatabasePath } from '../src/db';
  19. import { QueryBuilder } from '../src/db/queries';
  20. function createTempDir(): string {
  21. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-security-test-'));
  22. }
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('FileLock', () => {
  29. let tempDir: string;
  30. let lockPath: string;
  31. beforeEach(() => {
  32. tempDir = createTempDir();
  33. lockPath = path.join(tempDir, 'test.lock');
  34. });
  35. afterEach(() => {
  36. cleanupTempDir(tempDir);
  37. });
  38. it('should acquire and release a lock', () => {
  39. const lock = new FileLock(lockPath);
  40. lock.acquire();
  41. expect(fs.existsSync(lockPath)).toBe(true);
  42. const content = fs.readFileSync(lockPath, 'utf-8').trim();
  43. expect(parseInt(content, 10)).toBe(process.pid);
  44. lock.release();
  45. expect(fs.existsSync(lockPath)).toBe(false);
  46. });
  47. it('should prevent double acquisition within same process', () => {
  48. const lock1 = new FileLock(lockPath);
  49. const lock2 = new FileLock(lockPath);
  50. lock1.acquire();
  51. // Second lock should fail because our PID is alive
  52. expect(() => lock2.acquire()).toThrow(/locked by another process/);
  53. lock1.release();
  54. });
  55. it('should detect and remove stale locks from dead processes', () => {
  56. // Write a lock file with a PID that doesn't exist
  57. // PID 99999999 is extremely unlikely to be a real process
  58. fs.writeFileSync(lockPath, '99999999');
  59. const lock = new FileLock(lockPath);
  60. // Should succeed because the PID is dead
  61. expect(() => lock.acquire()).not.toThrow();
  62. lock.release();
  63. });
  64. it('should execute function with withLock', () => {
  65. const lock = new FileLock(lockPath);
  66. const result = lock.withLock(() => {
  67. expect(fs.existsSync(lockPath)).toBe(true);
  68. return 42;
  69. });
  70. expect(result).toBe(42);
  71. expect(fs.existsSync(lockPath)).toBe(false);
  72. });
  73. it('should release lock even if function throws', () => {
  74. const lock = new FileLock(lockPath);
  75. expect(() => {
  76. lock.withLock(() => {
  77. throw new Error('test error');
  78. });
  79. }).toThrow('test error');
  80. expect(fs.existsSync(lockPath)).toBe(false);
  81. });
  82. it('should execute async function with withLockAsync', async () => {
  83. const lock = new FileLock(lockPath);
  84. const result = await lock.withLockAsync(async () => {
  85. expect(fs.existsSync(lockPath)).toBe(true);
  86. return 'async-result';
  87. });
  88. expect(result).toBe('async-result');
  89. expect(fs.existsSync(lockPath)).toBe(false);
  90. });
  91. it('should release lock even if async function throws', async () => {
  92. const lock = new FileLock(lockPath);
  93. await expect(
  94. lock.withLockAsync(async () => {
  95. throw new Error('async error');
  96. })
  97. ).rejects.toThrow('async error');
  98. expect(fs.existsSync(lockPath)).toBe(false);
  99. });
  100. it('release should be idempotent', () => {
  101. const lock = new FileLock(lockPath);
  102. lock.acquire();
  103. lock.release();
  104. // Second release should not throw
  105. expect(() => lock.release()).not.toThrow();
  106. });
  107. });
  108. describe('Path Traversal Prevention', () => {
  109. let testDir: string;
  110. let cg: CodeGraph;
  111. beforeEach(async () => {
  112. testDir = createTempDir();
  113. const srcDir = path.join(testDir, 'src');
  114. fs.mkdirSync(srcDir);
  115. fs.writeFileSync(
  116. path.join(srcDir, 'hello.ts'),
  117. `export function hello(): string { return "hi"; }\n`
  118. );
  119. cg = CodeGraph.initSync(testDir, {
  120. config: { include: ['**/*.ts'], exclude: [] },
  121. });
  122. await cg.indexAll();
  123. });
  124. afterEach(() => {
  125. if (cg) cg.close();
  126. cleanupTempDir(testDir);
  127. });
  128. it('should read code for valid nodes within project', async () => {
  129. const nodes = cg.getNodesByKind('function');
  130. const hello = nodes.find((n) => n.name === 'hello');
  131. expect(hello).toBeDefined();
  132. const code = await cg.getCode(hello!.id);
  133. expect(code).toContain('hello');
  134. });
  135. it('should return null for non-existent node', async () => {
  136. const code = await cg.getCode('does-not-exist');
  137. expect(code).toBeNull();
  138. });
  139. });
  140. describe('validateProjectPath — sensitive directory blocking', () => {
  141. // POSIX-only: on Windows '/etc' resolves to C:\etc (non-existent), not a
  142. // sensitive dir — the Windows case is covered by the win32-gated test below.
  143. it.runIf(process.platform !== 'win32')('blocks POSIX system directories (exact match)', () => {
  144. expect(validateProjectPath('/')).toMatch(/sensitive system directory/i);
  145. expect(validateProjectPath('/etc')).toMatch(/sensitive system directory/i);
  146. });
  147. it('allows a normal, existing directory', () => {
  148. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-validate-'));
  149. try {
  150. expect(validateProjectPath(dir)).toBeNull();
  151. } finally {
  152. fs.rmSync(dir, { recursive: true, force: true });
  153. }
  154. });
  155. // SENSITIVE_PATHS stores the Windows entries lowercase and validateProjectPath
  156. // matches via resolved.toLowerCase(), so 'C:\\Windows' and 'c:\\windows' are
  157. // both blocked. path.resolve is platform-specific, so this only runs on Windows.
  158. it.runIf(process.platform === 'win32')(
  159. 'blocks Windows system directories regardless of case',
  160. () => {
  161. expect(validateProjectPath('C:\\Windows')).toMatch(/sensitive system directory/i);
  162. expect(validateProjectPath('c:\\windows')).toMatch(/sensitive system directory/i);
  163. expect(validateProjectPath('C:\\WINDOWS\\System32')).toMatch(/sensitive system directory/i);
  164. }
  165. );
  166. });
  167. describe('MCP Input Validation', () => {
  168. let testDir: string;
  169. let cg: CodeGraph;
  170. let handler: ToolHandler;
  171. beforeEach(async () => {
  172. testDir = createTempDir();
  173. const srcDir = path.join(testDir, 'src');
  174. fs.mkdirSync(srcDir);
  175. fs.writeFileSync(
  176. path.join(srcDir, 'example.ts'),
  177. `export function exampleFunc(): void {}\nexport class ExampleClass {}\n`
  178. );
  179. cg = CodeGraph.initSync(testDir, {
  180. config: { include: ['**/*.ts'], exclude: [] },
  181. });
  182. await cg.indexAll();
  183. handler = new ToolHandler(cg);
  184. });
  185. afterEach(() => {
  186. if (cg) cg.close();
  187. cleanupTempDir(testDir);
  188. });
  189. it('should reject non-string query in codegraph_search', async () => {
  190. const result = await handler.execute('codegraph_search', { query: null });
  191. expect(result.isError).toBe(true);
  192. expect(result.content[0].text).toContain('non-empty string');
  193. });
  194. it('should reject empty string query in codegraph_search', async () => {
  195. const result = await handler.execute('codegraph_search', { query: '' });
  196. expect(result.isError).toBe(true);
  197. expect(result.content[0].text).toContain('non-empty string');
  198. });
  199. it('should accept valid query in codegraph_search', async () => {
  200. const result = await handler.execute('codegraph_search', { query: 'example' });
  201. expect(result.isError).toBeFalsy();
  202. });
  203. it('should clamp limit to valid range in codegraph_search', async () => {
  204. // Extremely large limit should still work (clamped to 100)
  205. const result = await handler.execute('codegraph_search', { query: 'example', limit: 999999 });
  206. expect(result.isError).toBeFalsy();
  207. });
  208. it('should reject non-string symbol in codegraph_callers', async () => {
  209. const result = await handler.execute('codegraph_callers', { symbol: 123 });
  210. expect(result.isError).toBe(true);
  211. expect(result.content[0].text).toContain('non-empty string');
  212. });
  213. it('should reject non-string task in codegraph_context', async () => {
  214. const result = await handler.execute('codegraph_context', { task: undefined });
  215. expect(result.isError).toBe(true);
  216. expect(result.content[0].text).toContain('non-empty string');
  217. });
  218. it('should truncate oversized codegraph_context output', async () => {
  219. const oversizedContext = Array.from({ length: 400 }, (_, i) => `line-${i} ${'x'.repeat(80)}`).join('\n');
  220. const fakeCg = {
  221. buildContext: async () => oversizedContext,
  222. };
  223. const fakeHandler = new ToolHandler(fakeCg as unknown as CodeGraph);
  224. const result = await fakeHandler.execute('codegraph_context', { task: 'find example' });
  225. expect(result.isError).toBeFalsy();
  226. expect(result.content[0].text.length).toBeLessThan(oversizedContext.length);
  227. expect(result.content[0].text).toContain('... (output truncated)');
  228. });
  229. it('should reject non-string symbol in codegraph_impact', async () => {
  230. const result = await handler.execute('codegraph_impact', { symbol: [] });
  231. expect(result.isError).toBe(true);
  232. });
  233. it('should reject non-string symbol in codegraph_node', async () => {
  234. const result = await handler.execute('codegraph_node', { symbol: false });
  235. expect(result.isError).toBe(true);
  236. });
  237. it('should reject non-string symbol in codegraph_callees', async () => {
  238. const result = await handler.execute('codegraph_callees', { symbol: {} });
  239. expect(result.isError).toBe(true);
  240. });
  241. it('should handle NaN limit gracefully', async () => {
  242. const result = await handler.execute('codegraph_search', { query: 'example', limit: 'abc' });
  243. expect(result.isError).toBeFalsy();
  244. });
  245. it('should handle negative limit gracefully', async () => {
  246. const result = await handler.execute('codegraph_search', { query: 'example', limit: -5 });
  247. expect(result.isError).toBeFalsy();
  248. });
  249. // #230: getCodeGraph must reject a sensitive system directory passed as
  250. // projectPath before opening it. The error surfaces through execute()'s
  251. // catch as an isError result. /etc is sensitive on POSIX; C:\Windows on
  252. // Windows (path.resolve is platform-specific, so each case is gated).
  253. it.runIf(process.platform !== 'win32')(
  254. 'rejects a sensitive POSIX projectPath (/etc) via the MCP handler',
  255. async () => {
  256. const result = await handler.execute('codegraph_search', {
  257. query: 'example',
  258. projectPath: '/etc',
  259. });
  260. expect(result.isError).toBe(true);
  261. expect(result.content[0].text).toMatch(/sensitive system directory/i);
  262. }
  263. );
  264. it.runIf(process.platform === 'win32')(
  265. 'rejects a sensitive Windows projectPath (C:\\Windows) via the MCP handler',
  266. async () => {
  267. const result = await handler.execute('codegraph_search', {
  268. query: 'example',
  269. projectPath: 'C:\\Windows',
  270. });
  271. expect(result.isError).toBe(true);
  272. expect(result.content[0].text).toMatch(/sensitive system directory/i);
  273. }
  274. );
  275. });
  276. describe('Atomic Writes', () => {
  277. let tempDir: string;
  278. beforeEach(() => {
  279. tempDir = createTempDir();
  280. });
  281. afterEach(() => {
  282. cleanupTempDir(tempDir);
  283. });
  284. it('should not leave temp files on success', () => {
  285. // We test this indirectly through the config-writer module
  286. // by checking that no .tmp files remain after writing
  287. const configDir = path.join(tempDir, '.claude');
  288. fs.mkdirSync(configDir, { recursive: true });
  289. const testFile = path.join(configDir, 'test.json');
  290. // Simulate what atomicWriteFileSync does
  291. const tmpPath = testFile + '.tmp.' + process.pid;
  292. fs.writeFileSync(tmpPath, '{"test": true}');
  293. fs.renameSync(tmpPath, testFile);
  294. expect(fs.existsSync(testFile)).toBe(true);
  295. expect(fs.existsSync(tmpPath)).toBe(false);
  296. const content = JSON.parse(fs.readFileSync(testFile, 'utf-8'));
  297. expect(content.test).toBe(true);
  298. });
  299. });
  300. describe('Source file detection (isSourceFile)', () => {
  301. it('selects files by supported extension', () => {
  302. expect(isSourceFile('src/index.ts')).toBe(true);
  303. expect(isSourceFile('src/deep/nested/file.ts')).toBe(true);
  304. expect(isSourceFile('src/component.tsx')).toBe(true);
  305. expect(isSourceFile('lib/util.js')).toBe(true);
  306. expect(isSourceFile('src/main.py')).toBe(true);
  307. });
  308. it('rejects unsupported extensions and extensionless files', () => {
  309. expect(isSourceFile('src/component.css')).toBe(false);
  310. expect(isSourceFile('README.md')).toBe(false);
  311. expect(isSourceFile('Makefile')).toBe(false);
  312. expect(isSourceFile('.gitignore')).toBe(false);
  313. });
  314. it('matches regardless of leading dot directories', () => {
  315. expect(isSourceFile('.hidden/index.ts')).toBe(true);
  316. });
  317. });
  318. describe('JSON.parse Error Boundaries in DB', () => {
  319. let tempDir: string;
  320. beforeEach(() => {
  321. tempDir = createTempDir();
  322. });
  323. afterEach(() => {
  324. cleanupTempDir(tempDir);
  325. });
  326. it('should not crash when node has malformed JSON in decorators column', () => {
  327. const dbPath = path.join(tempDir, 'test.db');
  328. const db = DatabaseConnection.initialize(dbPath);
  329. const queries = new QueryBuilder(db.getDb());
  330. // Insert a node with malformed JSON in the decorators column
  331. db.getDb().prepare(`
  332. INSERT INTO nodes (id, kind, name, qualified_name, file_path, language, start_line, end_line, start_column, end_column, decorators, is_exported, is_async, is_static, is_abstract, updated_at)
  333. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  334. `).run(
  335. 'test-node-1', 'function', 'myFunc', 'myFunc', 'test.ts', 'typescript',
  336. 1, 5, 0, 0,
  337. '{not valid json!!!}', // malformed decorators
  338. 0, 0, 0, 0, Date.now()
  339. );
  340. // Should not throw - should return node with undefined decorators
  341. const node = queries.getNodeById('test-node-1');
  342. expect(node).not.toBeNull();
  343. expect(node!.name).toBe('myFunc');
  344. expect(node!.decorators).toBeUndefined();
  345. db.close();
  346. });
  347. it('should not crash when edge has malformed JSON in metadata column', () => {
  348. const dbPath = path.join(tempDir, 'test.db');
  349. const db = DatabaseConnection.initialize(dbPath);
  350. const queries = new QueryBuilder(db.getDb());
  351. // Insert two nodes first
  352. const insertNode = db.getDb().prepare(`
  353. INSERT INTO nodes (id, kind, name, qualified_name, file_path, language, start_line, end_line, start_column, end_column, is_exported, is_async, is_static, is_abstract, updated_at)
  354. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  355. `);
  356. insertNode.run('node-a', 'function', 'funcA', 'funcA', 'a.ts', 'typescript', 1, 5, 0, 0, 0, 0, 0, 0, Date.now());
  357. insertNode.run('node-b', 'function', 'funcB', 'funcB', 'b.ts', 'typescript', 1, 5, 0, 0, 0, 0, 0, 0, Date.now());
  358. // Insert edge with malformed metadata
  359. db.getDb().prepare(`
  360. INSERT INTO edges (source, target, kind, metadata)
  361. VALUES (?, ?, ?, ?)
  362. `).run('node-a', 'node-b', 'calls', 'broken json {{{');
  363. // Should not throw - should return edge with undefined metadata
  364. const edges = queries.getOutgoingEdges('node-a');
  365. expect(edges.length).toBe(1);
  366. expect(edges[0].source).toBe('node-a');
  367. expect(edges[0].target).toBe('node-b');
  368. expect(edges[0].metadata).toBeUndefined();
  369. db.close();
  370. });
  371. it('should not crash when file record has malformed JSON in errors column', () => {
  372. const dbPath = path.join(tempDir, 'test.db');
  373. const db = DatabaseConnection.initialize(dbPath);
  374. const queries = new QueryBuilder(db.getDb());
  375. // Insert a file with malformed errors JSON
  376. db.getDb().prepare(`
  377. INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
  378. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  379. `).run('test.ts', 'abc123', 'typescript', 100, Date.now(), Date.now(), 5, 'not-an-array');
  380. // Should not throw - should return file with undefined errors
  381. const file = queries.getFileByPath('test.ts');
  382. expect(file).not.toBeNull();
  383. expect(file!.path).toBe('test.ts');
  384. expect(file!.errors).toBeUndefined();
  385. db.close();
  386. });
  387. });
  388. describe('Symlink Cycle Detection', () => {
  389. let tempDir: string;
  390. beforeEach(() => {
  391. tempDir = createTempDir();
  392. });
  393. afterEach(() => {
  394. cleanupTempDir(tempDir);
  395. });
  396. it('should handle symlink cycle without infinite loop', () => {
  397. // Create directory structure with a symlink cycle
  398. const srcDir = path.join(tempDir, 'src');
  399. fs.mkdirSync(srcDir);
  400. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;\n');
  401. // Create a symlink from src/loop -> tempDir (parent directory)
  402. try {
  403. fs.symlinkSync(tempDir, path.join(srcDir, 'loop'), 'dir');
  404. } catch {
  405. // Skip test if symlinks not supported (e.g., Windows without admin)
  406. return;
  407. }
  408. // This should complete without hanging
  409. const files = scanDirectory(tempDir);
  410. // Should find the real file but not loop infinitely
  411. expect(files).toContain('src/index.ts');
  412. // Should not find duplicates via the symlink path
  413. const indexFiles = files.filter(f => f.endsWith('index.ts'));
  414. expect(indexFiles.length).toBe(1);
  415. });
  416. it('should follow valid symlinks to directories', () => {
  417. // Create source directory with a file
  418. const realDir = path.join(tempDir, 'real');
  419. fs.mkdirSync(realDir);
  420. fs.writeFileSync(path.join(realDir, 'hello.ts'), 'export function hello() {}\n');
  421. // Create a symlink to realDir
  422. const srcDir = path.join(tempDir, 'src');
  423. fs.mkdirSync(srcDir);
  424. try {
  425. fs.symlinkSync(realDir, path.join(srcDir, 'linked'), 'dir');
  426. } catch {
  427. return;
  428. }
  429. const files = scanDirectory(tempDir);
  430. // Should find files from both the real dir and via the symlink
  431. // But deduplicate since they resolve to the same real path
  432. expect(files.some(f => f.includes('hello.ts'))).toBe(true);
  433. });
  434. it('should skip broken symlinks gracefully', () => {
  435. const srcDir = path.join(tempDir, 'src');
  436. fs.mkdirSync(srcDir);
  437. fs.writeFileSync(path.join(srcDir, 'valid.ts'), 'export const y = 2;\n');
  438. try {
  439. fs.symlinkSync('/nonexistent/path', path.join(srcDir, 'broken'), 'dir');
  440. } catch {
  441. return;
  442. }
  443. // Should not throw
  444. const files = scanDirectory(tempDir);
  445. expect(files).toContain('src/valid.ts');
  446. });
  447. });
  448. describe('Session marker symlink resistance', () => {
  449. // The marker write lives in src/mcp/tools.ts behind handleContext. We exercise
  450. // it end-to-end via ToolHandler.execute so the test exercises the same code
  451. // path Claude Code drives. The session id is per-test so other parallel test
  452. // runs can't collide with the marker file we plant a symlink at.
  453. const SESSION_ID = `cg-test-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  454. const crypto = require('crypto') as typeof import('crypto');
  455. const hash = crypto.createHash('md5').update(SESSION_ID).digest('hex').slice(0, 16);
  456. const markerPath = path.join(os.tmpdir(), `codegraph-consulted-${hash}`);
  457. let projectDir: string;
  458. let victimDir: string;
  459. let victimFile: string;
  460. beforeEach(async () => {
  461. projectDir = createTempDir();
  462. victimDir = createTempDir();
  463. victimFile = path.join(victimDir, 'private.txt');
  464. fs.writeFileSync(victimFile, 'SECRET-DO-NOT-OVERWRITE\n');
  465. if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
  466. // A real .codegraph/ has to exist for handleContext to get past the
  467. // "not initialized" guard — index a tiny fixture so the call reaches the
  468. // marker write step rather than short-circuiting on missing project state.
  469. fs.writeFileSync(path.join(projectDir, 'a.ts'), 'export const x = 1;\n');
  470. const cg = await CodeGraph.init(projectDir);
  471. await cg.indexAll();
  472. cg.close();
  473. });
  474. afterEach(() => {
  475. if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
  476. cleanupTempDir(projectDir);
  477. cleanupTempDir(victimDir);
  478. });
  479. it('does not follow a pre-planted symlink at the marker path', async () => {
  480. // Skip on platforms where the user can't create symlinks (Windows without
  481. // dev mode + admin). The CWE-59 risk we're guarding against doesn't apply
  482. // when symlinks aren't creatable, so the skip is correct, not a gap.
  483. try {
  484. fs.symlinkSync(victimFile, markerPath);
  485. } catch {
  486. return;
  487. }
  488. const cg = await CodeGraph.open(projectDir);
  489. const handler = new ToolHandler(cg);
  490. process.env.CLAUDE_SESSION_ID = SESSION_ID;
  491. try {
  492. await handler.execute('codegraph_context', { task: 'find x' });
  493. } finally {
  494. delete process.env.CLAUDE_SESSION_ID;
  495. cg.close();
  496. }
  497. // The victim file's contents must be untouched — the old writeFileSync
  498. // path would have followed the symlink and written an ISO timestamp here.
  499. expect(fs.readFileSync(victimFile, 'utf8')).toBe('SECRET-DO-NOT-OVERWRITE\n');
  500. // And the marker path itself must still be the symlink we planted —
  501. // no fallback path that quietly unlinked + recreated it (which would
  502. // also work, but is a behavior we don't want to silently rely on).
  503. expect(fs.lstatSync(markerPath).isSymbolicLink()).toBe(true);
  504. });
  505. it('writes the marker file with 0o600 perms on a clean path', async () => {
  506. // No symlink planted — happy path. Verifies the new openSync(mode: 0o600)
  507. // call is what actually lands on disk (regression guard for the perm
  508. // tightening that came with the O_NOFOLLOW fix).
  509. const cg = await CodeGraph.open(projectDir);
  510. const handler = new ToolHandler(cg);
  511. process.env.CLAUDE_SESSION_ID = SESSION_ID;
  512. try {
  513. await handler.execute('codegraph_context', { task: 'find x' });
  514. } finally {
  515. delete process.env.CLAUDE_SESSION_ID;
  516. cg.close();
  517. }
  518. expect(fs.existsSync(markerPath)).toBe(true);
  519. // chmod's low 9 bits — strip the file-type bits for a clean compare.
  520. // Windows can't enforce 0o600 in the POSIX sense; skip the assertion
  521. // there since the underlying OS will normalize the mode anyway.
  522. if (process.platform !== 'win32') {
  523. const mode = fs.statSync(markerPath).mode & 0o777;
  524. expect(mode).toBe(0o600);
  525. }
  526. });
  527. });