ui-trails.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /**
  2. * Saved trails (CG-60) — the viewer's only write.
  3. *
  4. * Two things are worth a real end-to-end fixture rather than a unit test, and
  5. * they are the two the feature exists for:
  6. *
  7. * 1. **A trail survives a re-index.** The suite indexes a project, saves a
  8. * trail, then EDITS the files so every node id changes (a symbol shifts down
  9. * a file, another moves to a different file, a third is deleted), re-indexes,
  10. * and asserts the trail still opens and says what became of each hop. That
  11. * cannot be faked: node ids contain a start line, so the ids really do all
  12. * change.
  13. * 2. **The write boundary.** `POST` without the marker header, from a foreign
  14. * `Origin`, or against a `--read-only` server has to be refused — by a real
  15. * loopback server, because the refusals live in the request handler and not
  16. * in the endpoint.
  17. */
  18. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  19. import * as http from 'http';
  20. import * as fs from 'fs';
  21. import * as os from 'os';
  22. import * as path from 'path';
  23. import CodeGraph from '../src/index';
  24. import { createGraphApi, startUiServer, type GraphApi, type UiServerHandle } from '../src/ui-server';
  25. import {
  26. encodeResolvedRun,
  27. isTrailId,
  28. parseTrail,
  29. slugify,
  30. TRAILS_RELATIVE_DIR,
  31. type WireTrailHop,
  32. } from '../src/ui-server/api';
  33. interface Res {
  34. status: number;
  35. headers: http.IncomingHttpHeaders;
  36. body: any;
  37. }
  38. let tempDir: string;
  39. let projectRoot: string;
  40. let viewerDir: string;
  41. let api: GraphApi;
  42. let server: UiServerHandle;
  43. let readOnlyApi: GraphApi;
  44. let readOnlyServer: UiServerHandle;
  45. interface CallOptions {
  46. method?: string;
  47. body?: unknown;
  48. /** Send the write marker header. On by default for a write. */
  49. marker?: boolean;
  50. contentType?: string | null;
  51. origin?: string;
  52. }
  53. /**
  54. * One request against a live server.
  55. *
  56. * `http.request` rather than `fetch` so `Host` is ours to set — undici treats
  57. * it as a forbidden header, and the `Host` allowlist is half of what is being
  58. * tested here.
  59. */
  60. function callOn(port: number, requestPath: string, opts: CallOptions = {}): Promise<Res> {
  61. const method = opts.method ?? 'GET';
  62. const isWrite = method === 'POST' || method === 'DELETE';
  63. const payload = opts.body === undefined ? null : Buffer.from(JSON.stringify(opts.body), 'utf-8');
  64. const headers: Record<string, string> = { Host: `127.0.0.1:${port}` };
  65. if (isWrite && (opts.marker ?? true)) headers['X-CodeGraph-UI'] = '1';
  66. if (opts.origin) headers['Origin'] = opts.origin;
  67. if (payload) {
  68. const type = opts.contentType === undefined ? 'application/json' : opts.contentType;
  69. if (type !== null) headers['Content-Type'] = type;
  70. headers['Content-Length'] = String(payload.length);
  71. }
  72. return new Promise((resolve, reject) => {
  73. const req = http.request(
  74. { host: '127.0.0.1', port, path: requestPath, method, headers, setHost: false },
  75. (res) => {
  76. const chunks: Buffer[] = [];
  77. res.on('data', (c: Buffer) => chunks.push(c));
  78. res.on('end', () => {
  79. const text = Buffer.concat(chunks).toString('utf-8');
  80. let parsed: unknown = text;
  81. try {
  82. parsed = JSON.parse(text);
  83. } catch {
  84. /* a text/plain refusal is a legitimate answer on the static side */
  85. }
  86. resolve({ status: res.statusCode ?? 0, headers: res.headers, body: parsed });
  87. });
  88. }
  89. );
  90. req.on('error', reject);
  91. if (payload) req.write(payload);
  92. req.end();
  93. });
  94. }
  95. function call(requestPath: string, opts: CallOptions = {}): Promise<Res> {
  96. return callOn(server.port, requestPath, opts);
  97. }
  98. /** The id of a fixture symbol, looked up through the API itself. */
  99. async function idOf(name: string): Promise<string> {
  100. const res = await call(`/api/search?q=${encodeURIComponent(name)}`);
  101. const hit = res.body.results.items.find((r: any) => r.name === name);
  102. expect(hit, `no symbol named ${name}`).toBeTruthy();
  103. return hit.id as string;
  104. }
  105. function trailsDir(): string {
  106. return path.join(projectRoot, TRAILS_RELATIVE_DIR);
  107. }
  108. /** Re-index in place, the way a `codegraph sync` would after an edit. */
  109. async function reindex(): Promise<void> {
  110. const cg = CodeGraph.openSync(projectRoot);
  111. await cg.sync();
  112. cg.resolveReferences();
  113. cg.close();
  114. }
  115. const SRC = () => path.join(projectRoot, 'src');
  116. beforeAll(async () => {
  117. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-trails-'));
  118. projectRoot = path.join(tempDir, 'project');
  119. fs.mkdirSync(SRC(), { recursive: true });
  120. fs.writeFileSync(
  121. path.join(SRC(), 'handler.ts'),
  122. `import { load } from './service';
  123. export function handleRequest(key: string): string {
  124. return load(key);
  125. }
  126. `
  127. );
  128. fs.writeFileSync(
  129. path.join(SRC(), 'service.ts'),
  130. `import { read } from './cache';
  131. export function load(key: string): string {
  132. return read(key);
  133. }
  134. export function retired(): string {
  135. return 'nothing calls me after the edit';
  136. }
  137. `
  138. );
  139. fs.writeFileSync(
  140. path.join(SRC(), 'cache.ts'),
  141. `export function read(key: string): string {
  142. return key;
  143. }
  144. `
  145. );
  146. const cg = CodeGraph.initSync(projectRoot, {
  147. config: { include: ['src/**/*.ts'], exclude: [] },
  148. });
  149. await cg.indexAll();
  150. cg.resolveReferences();
  151. cg.close();
  152. viewerDir = path.join(tempDir, 'viewer');
  153. fs.mkdirSync(viewerDir, { recursive: true });
  154. fs.writeFileSync(path.join(viewerDir, 'index.html'), '<!doctype html><div id="app"></div>');
  155. api = createGraphApi({ projectRoot });
  156. server = await startUiServer({ projectRoot, viewerDir, port: 0, api: api.handler });
  157. readOnlyApi = createGraphApi({
  158. projectRoot,
  159. readOnly: true,
  160. readOnlyReason: 'This viewer was started with --read-only, so trails cannot be saved.',
  161. });
  162. readOnlyServer = await startUiServer({
  163. projectRoot,
  164. viewerDir,
  165. port: 0,
  166. api: readOnlyApi.handler,
  167. });
  168. }, 120_000);
  169. afterAll(async () => {
  170. api?.close();
  171. readOnlyApi?.close();
  172. await server?.close();
  173. await readOnlyServer?.close();
  174. if (tempDir && fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  175. });
  176. /* ------------------------------------------------------------- pure bits -- */
  177. describe('trail ids', () => {
  178. it('slugs a name into something that is a filename and not a path', () => {
  179. expect(slugify('How a request reaches the handler')).toBe(
  180. 'how-a-request-reaches-the-handler'
  181. );
  182. expect(slugify(' Spaces and --- dashes ')).toBe('spaces-and-dashes');
  183. expect(slugify('../../etc/passwd')).toBe('etc-passwd');
  184. // A name with no ASCII word characters still has to produce a valid id.
  185. expect(slugify('日本語')).toBe('trail');
  186. expect(isTrailId(slugify('../../etc/passwd'))).toBe(true);
  187. });
  188. it('refuses anything that is not a slug', () => {
  189. for (const bad of ['..', 'a/b', 'A', 'has.dot', '-leading', '', 'a b']) {
  190. expect(isTrailId(bad), bad).toBe(false);
  191. }
  192. });
  193. });
  194. describe('parseTrail', () => {
  195. it('rejects a file that is not a trail rather than half-reading it', () => {
  196. expect(parseTrail('x', 'not json')).toBeNull();
  197. expect(parseTrail('x', '[]')).toBeNull();
  198. expect(parseTrail('x', '{"name":"a"}')).toBeNull();
  199. expect(parseTrail('x', '{"name":"a","hops":[]}')).toBeNull();
  200. expect(parseTrail('x', '{"name":"","hops":[{"qualifiedName":"a"}]}')).toBeNull();
  201. });
  202. it('takes its id from the FILE, not from the field inside it', () => {
  203. const trail = parseTrail('on-disk', '{"name":"a","id":"remembered","hops":[{"name":"f"}]}');
  204. expect(trail?.id).toBe('on-disk');
  205. });
  206. });
  207. describe('encodeResolvedRun', () => {
  208. const hop = (id: string | null, dir: 'start' | 'down' | 'up' = 'down'): WireTrailHop => ({
  209. dir,
  210. name: id ?? 'gone',
  211. qualifiedName: id ?? 'gone',
  212. kind: 'function',
  213. savedFile: 'src/a.ts',
  214. savedLine: 1,
  215. status: id ? 'ok' : 'missing',
  216. id,
  217. file: id ? 'src/a.ts' : null,
  218. line: id ? 1 : null,
  219. note: null,
  220. });
  221. it('never stitches across a hole — it takes the longest consecutive run', () => {
  222. const run = encodeResolvedRun([hop('a', 'start'), hop(null), hop('c'), hop('d')]);
  223. expect(run.encoded).toBe('sc,dd');
  224. expect(run.openFrom).toBe(3);
  225. expect(run.openCount).toBe(2);
  226. expect(run.openId).toBe('d');
  227. });
  228. it('writes the run’s first hop as a start, whatever it was saved as', () => {
  229. const run = encodeResolvedRun([hop(null), hop('b', 'up')]);
  230. expect(run.encoded).toBe('sb');
  231. });
  232. it('answers nothing when nothing resolves', () => {
  233. expect(encodeResolvedRun([hop(null), hop(null)])).toEqual({
  234. encoded: null,
  235. openFrom: 0,
  236. openCount: 0,
  237. openId: null,
  238. });
  239. });
  240. });
  241. /* ----------------------------------------------------------- the endpoint -- */
  242. describe('GET /api/trails', () => {
  243. it('is an empty list, not an error, before anything is saved', async () => {
  244. const res = await call('/api/trails');
  245. expect(res.status).toBe(200);
  246. expect(res.body.trails).toEqual([]);
  247. expect(res.body.readOnly).toBe(false);
  248. expect(res.body.directory).toBe(TRAILS_RELATIVE_DIR);
  249. });
  250. it('is listed by GET /api', async () => {
  251. const res = await call('/api');
  252. expect(res.body.endpoints.some((e: any) => e.path === '/api/trails')).toBe(true);
  253. // The old blanket claim is gone: the server writes exactly one thing.
  254. expect(res.body.readOnly).toBe(false);
  255. expect(res.body.writes).toContain('POST /api/trails');
  256. });
  257. });
  258. describe('POST /api/trails', () => {
  259. it('saves the walk and answers with the whole list', async () => {
  260. const hops = [
  261. { dir: 'start', id: await idOf('handleRequest') },
  262. { dir: 'down', id: await idOf('load') },
  263. { dir: 'down', id: await idOf('read') },
  264. ];
  265. const res = await call('/api/trails', {
  266. method: 'POST',
  267. body: { name: 'How a request is served', note: 'the whole path', hops },
  268. });
  269. expect(res.status).toBe(200);
  270. expect(res.body.saved).toBe('how-a-request-is-served');
  271. expect(res.body.replaced).toBe(false);
  272. expect(res.body.trails).toHaveLength(1);
  273. const trail = res.body.trails[0];
  274. expect(trail.name).toBe('How a request is served');
  275. expect(trail.note).toBe('the whole path');
  276. expect(trail.intact).toBe(true);
  277. expect(trail.resolved).toBe(3);
  278. expect(trail.openCount).toBe(3);
  279. expect(trail.hops.map((h: any) => h.name)).toEqual(['handleRequest', 'load', 'read']);
  280. // The identity that survives an edit, recorded beside the id hint.
  281. expect(trail.hops[1].qualifiedName).toBe('load');
  282. expect(trail.hops[1].savedFile).toBe('src/service.ts');
  283. });
  284. it('writes one readable JSON file into .codegraph/ui/trails', () => {
  285. const file = path.join(trailsDir(), 'how-a-request-is-served.json');
  286. expect(fs.existsSync(file)).toBe(true);
  287. const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
  288. expect(raw.version).toBe(1);
  289. expect(raw.hops).toHaveLength(3);
  290. expect(raw.hops[0].qualifiedName).toBe('handleRequest');
  291. expect(typeof raw.createdAt).toBe('string');
  292. // Nothing but trails lands there — no temp file survives the rename.
  293. expect(fs.readdirSync(trailsDir())).toEqual(['how-a-request-is-served.json']);
  294. });
  295. it('replaces a trail saved under the same name, keeping its createdAt', async () => {
  296. const before = (await call('/api/trails')).body.trails[0];
  297. const res = await call('/api/trails', {
  298. method: 'POST',
  299. body: {
  300. name: 'How a request is served',
  301. hops: [{ dir: 'start', id: await idOf('handleRequest') }],
  302. },
  303. });
  304. expect(res.body.replaced).toBe(true);
  305. expect(res.body.trails).toHaveLength(1);
  306. expect(res.body.trails[0].createdAt).toBe(before.createdAt);
  307. expect(res.body.trails[0].hops).toHaveLength(1);
  308. expect(res.body.trails[0].note).toBe('');
  309. });
  310. it('gives a different name its own file rather than colliding', async () => {
  311. const res = await call('/api/trails', {
  312. method: 'POST',
  313. body: { name: 'How a request is served!', hops: [{ dir: 'start', id: await idOf('load') }] },
  314. });
  315. expect(res.body.saved).toBe('how-a-request-is-served-2');
  316. expect(res.body.trails).toHaveLength(2);
  317. });
  318. it('refuses a hop the index does not hold', async () => {
  319. const res = await call('/api/trails', {
  320. method: 'POST',
  321. body: { name: 'invented', hops: [{ dir: 'start', id: 'function:not-a-real-id' }] },
  322. });
  323. expect(res.status).toBe(400);
  324. expect(res.body.error).toContain('Hop 1 is not in the index');
  325. });
  326. it('refuses a nameless or hopless trail', async () => {
  327. const noName = await call('/api/trails', { method: 'POST', body: { name: ' ', hops: [] } });
  328. expect(noName.status).toBe(400);
  329. const noHops = await call('/api/trails', { method: 'POST', body: { name: 'x', hops: [] } });
  330. expect(noHops.status).toBe(400);
  331. expect(noHops.body.error).toContain('at least one hop');
  332. });
  333. });
  334. describe('DELETE /api/trails/<id>', () => {
  335. it('removes the file and answers with the list that is left', async () => {
  336. const res = await call('/api/trails/how-a-request-is-served-2', { method: 'DELETE' });
  337. expect(res.status).toBe(200);
  338. expect(res.body.deleted).toBe('how-a-request-is-served-2');
  339. expect(res.body.trails).toHaveLength(1);
  340. expect(fs.existsSync(path.join(trailsDir(), 'how-a-request-is-served-2.json'))).toBe(false);
  341. });
  342. it('is a 404 for a trail that is not there', async () => {
  343. const res = await call('/api/trails/never-existed', { method: 'DELETE' });
  344. expect(res.status).toBe(404);
  345. });
  346. it('refuses an id shaped like a path before it is joined to anything', async () => {
  347. const res = await call('/api/trails/..%2f..%2fetc%2fpasswd', { method: 'DELETE' });
  348. // The `..` segments are caught on the RAW url, before WHATWG parsing folds
  349. // them away — a traversal attempt is a 404, never the app shell.
  350. expect([400, 404]).toContain(res.status);
  351. expect(res.headers['content-type']).toContain('application/json');
  352. });
  353. });
  354. /* ------------------------------------------------------- the write boundary */
  355. describe('the write boundary', () => {
  356. it('refuses a POST without the marker header', async () => {
  357. const res = await call('/api/trails', {
  358. method: 'POST',
  359. marker: false,
  360. body: { name: 'forged', hops: [] },
  361. });
  362. expect(res.status).toBe(403);
  363. expect(res.body.code).toBe('refused');
  364. expect(String(res.body.error)).toContain('x-codegraph-ui');
  365. });
  366. it('refuses a POST whose body claims to be a form', async () => {
  367. const res = await call('/api/trails', {
  368. method: 'POST',
  369. contentType: 'application/x-www-form-urlencoded',
  370. body: { name: 'forged', hops: [] },
  371. });
  372. expect(res.status).toBe(403);
  373. expect(String(res.body.error)).toContain('application/json');
  374. });
  375. it('refuses a POST from a foreign origin even with the marker', async () => {
  376. const res = await call('/api/trails', {
  377. method: 'POST',
  378. origin: 'https://evil.example',
  379. body: { name: 'forged', hops: [] },
  380. });
  381. expect(res.status).toBe(403);
  382. });
  383. it('refuses a write anywhere but /api/, and still serves the asset on GET', async () => {
  384. const post = await call('/index.html', { method: 'POST', body: { a: 1 } });
  385. expect(post.status).toBe(405);
  386. expect(post.headers.allow).toBe('GET, HEAD');
  387. const get = await call('/index.html');
  388. expect(get.status).toBe(200);
  389. });
  390. it('still refuses a method it has never answered', async () => {
  391. const res = await call('/api/trails', { method: 'PUT' });
  392. expect(res.status).toBe(405);
  393. });
  394. it('refuses every write under --read-only, but still lists what is there', async () => {
  395. const list = await callOn(readOnlyServer.port, '/api/trails');
  396. expect(list.status).toBe(200);
  397. expect(list.body.readOnly).toBe(true);
  398. expect(list.body.readOnlyReason).toContain('--read-only');
  399. expect(list.body.trails.length).toBeGreaterThan(0);
  400. const save = await callOn(readOnlyServer.port, '/api/trails', {
  401. method: 'POST',
  402. body: { name: 'nope', hops: [{ dir: 'start', id: 'x' }] },
  403. });
  404. expect(save.status).toBe(403);
  405. expect(save.body.code).toBe('refused');
  406. const remove = await callOn(readOnlyServer.port, '/api/trails/how-a-request-is-served', {
  407. method: 'DELETE',
  408. });
  409. expect(remove.status).toBe(403);
  410. });
  411. });
  412. /* ------------------------------------------------- surviving a re-index --- */
  413. describe('a saved trail survives a re-index', () => {
  414. it('re-resolves hops by qualified name once every node id has changed', async () => {
  415. // Save the three-hop walk again, plus a fourth hop that is about to be
  416. // deleted outright, so one trail exercises every outcome at once.
  417. const saved = await call('/api/trails', {
  418. method: 'POST',
  419. body: {
  420. name: 'The whole walk',
  421. hops: [
  422. { dir: 'start', id: await idOf('handleRequest') },
  423. { dir: 'down', id: await idOf('load') },
  424. { dir: 'down', id: await idOf('read') },
  425. { dir: 'down', id: await idOf('retired') },
  426. ],
  427. },
  428. });
  429. const before = saved.body.trails.find((t: any) => t.id === 'the-whole-walk');
  430. expect(before.intact).toBe(true);
  431. const idsBefore = before.hops.map((h: any) => h.id);
  432. // Now move the world underneath it:
  433. // - `handleRequest` shifts down its file (a node id contains its start
  434. // line, so its id changes while it is the same symbol);
  435. // - `read` moves to a different file entirely;
  436. // - `retired` is deleted.
  437. fs.writeFileSync(
  438. path.join(SRC(), 'handler.ts'),
  439. `import { load } from './service';
  440. // A comment inserted above the symbol. This alone renames it.
  441. // Another line.
  442. // And another.
  443. export function handleRequest(key: string): string {
  444. return load(key);
  445. }
  446. `
  447. );
  448. fs.writeFileSync(
  449. path.join(SRC(), 'service.ts'),
  450. `import { read } from './store';
  451. export function load(key: string): string {
  452. return read(key);
  453. }
  454. `
  455. );
  456. fs.writeFileSync(path.join(SRC(), 'cache.ts'), `export const unused = 1;\n`);
  457. fs.writeFileSync(
  458. path.join(SRC(), 'store.ts'),
  459. `export function read(key: string): string {
  460. return key;
  461. }
  462. `
  463. );
  464. await reindex();
  465. const after = (await call('/api/trails')).body.trails.find(
  466. (t: any) => t.id === 'the-whole-walk'
  467. );
  468. // Every id really did change — otherwise this test proves nothing.
  469. const idsAfter = after.hops.map((h: any) => h.id);
  470. expect(idsAfter[0]).not.toBe(idsBefore[0]);
  471. expect(idsAfter[0]).toBeTruthy();
  472. const [handle, load, read, retired] = after.hops;
  473. expect(handle.status).toBe('ok');
  474. expect(handle.file).toBe('src/handler.ts');
  475. expect(handle.line).toBeGreaterThan(handle.savedLine);
  476. expect(load.status).toBe('ok');
  477. // Moved to another file: still resolved, and the row says where from.
  478. expect(read.status).toBe('moved');
  479. expect(read.savedFile).toBe('src/cache.ts');
  480. expect(read.file).toBe('src/store.ts');
  481. expect(read.note).toContain('src/cache.ts');
  482. expect(read.note).toContain('src/store.ts');
  483. // Deleted: named honestly, with no invented target.
  484. expect(retired.status).toBe('missing');
  485. expect(retired.id).toBeNull();
  486. expect(retired.note).toContain('moved or renamed');
  487. // And it still opens — the first three hops, not the fourth.
  488. expect(after.intact).toBe(false);
  489. expect(after.resolved).toBe(3);
  490. expect(after.openFrom).toBe(1);
  491. expect(after.openCount).toBe(3);
  492. expect(after.openId).toBe(idsAfter[2]);
  493. expect(after.encoded?.split(',')).toHaveLength(3);
  494. expect(after.encoded?.startsWith('s')).toBe(true);
  495. }, 120_000);
  496. });