runtime-feedback-diagnostic-upload.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { join } from 'node:path';
  4. import JSZip from 'jszip';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import { SessionReportService } from '@mavis/session-report';
  7. import { uploadTuiFeedbackDiagnostics } from '../../src/runtime/feedback/diagnostic-upload.js';
  8. import { TuiFeedbackService } from '../../src/runtime/feedback/service.js';
  9. import { TuiFeedbackPanel } from '../../src/tui/features/feedback/panel.js';
  10. const PRIVATE = 'SYNTHETIC_PRIVATE_29fa';
  11. const tempDirs: string[] = [];
  12. afterEach(async () => {
  13. await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  14. });
  15. async function directory() {
  16. const dir = await mkdtemp(join(tmpdir(), 'feedback-privacy-'));
  17. tempDirs.push(dir);
  18. return dir;
  19. }
  20. function transport() {
  21. let uploaded: Uint8Array | undefined;
  22. const fetchImpl = vi.fn<typeof fetch>(async (url, init) => {
  23. if (String(url).endsWith('/matrix/api/v1/log/upload')) {
  24. return Response.json({
  25. upload_id: 'synthetic-upload',
  26. upload_url: 'https://upload.example.test/capture',
  27. });
  28. }
  29. expect(init?.method).toBe('PUT');
  30. uploaded = new Uint8Array(await new Response(init?.body).arrayBuffer());
  31. return new Response(null, { status: 200 });
  32. });
  33. return {
  34. fetchImpl,
  35. async archive() {
  36. expect(uploaded).toBeDefined();
  37. const zip = await JSZip.loadAsync(uploaded!);
  38. const files = await Promise.all(
  39. Object.values(zip.files)
  40. .filter((file) => !file.dir)
  41. .map(async (file) => ({
  42. name: file.name,
  43. text: await file.async('string'),
  44. })),
  45. );
  46. return {
  47. zip,
  48. files,
  49. text: JSON.stringify(files),
  50. summaries: files
  51. .filter((file) => file.name !== 'diagnostic-manifest.json')
  52. .map((file) => JSON.parse(file.text)),
  53. };
  54. },
  55. };
  56. }
  57. describe('feedback diagnostic upload privacy', () => {
  58. it('runs review, real session collection, packaging and intercepted PUT with synthetic sensitive artifacts', async () => {
  59. const dataDir = await directory();
  60. const root = join(dataDir, 'session-root');
  61. const child = join(dataDir, 'session-child');
  62. const logs = join(dataDir, 'v2', 'observability', 'logs');
  63. const auth = join(dataDir, 'auth');
  64. await Promise.all([root, child, logs, auth].map((dir) => mkdir(dir, { recursive: true })));
  65. const message = JSON.stringify({
  66. role: 'user',
  67. content: `${PRIVATE}\nquoted "prompt"`,
  68. token: PRIVATE,
  69. properties: {
  70. error: {
  71. statusCode: 429,
  72. message: PRIVATE,
  73. headers: { authorization: PRIVATE },
  74. },
  75. },
  76. });
  77. const fixtures: Record<string, string> = {
  78. 'manifest.json': JSON.stringify({
  79. status: 'failed',
  80. cwd: PRIVATE,
  81. title: PRIVATE,
  82. }),
  83. 'messages.jsonl': `${message}\n`,
  84. 'display.jsonl': `${JSON.stringify({ role: 'assistant', content: PRIVATE })}\n`,
  85. 'snapshot.json': JSON.stringify({
  86. messages: [JSON.parse(message)],
  87. prompt: PRIVATE,
  88. }),
  89. 'llm-call.json': JSON.stringify({
  90. systemPrompt: PRIVATE,
  91. tools: [{ description: PRIVATE }],
  92. error: { code: 'ECONNRESET', cause: { message: PRIVATE } },
  93. }),
  94. [`${PRIVATE}.bin`]: PRIVATE,
  95. 'broken.json': `{"content":"${PRIVATE}`,
  96. };
  97. await Promise.all(
  98. Object.entries(fixtures).map(([name, content]) => writeFile(join(root, name), content)),
  99. );
  100. await writeFile(join(child, 'messages.jsonl'), `${message}\n`);
  101. await writeFile(join(child, 'manifest.json'), '{"status":"completed"}');
  102. await writeFile(
  103. join(logs, `runtime-${PRIVATE}.log`),
  104. `${PRIVATE}\n${JSON.stringify({ level: 'error', prompt: PRIVATE, error: { status: 503 } })}\n`,
  105. );
  106. await writeFile(join(auth, 'auth.json'), JSON.stringify({ accessToken: PRIVATE }));
  107. const reports = new SessionReportService({
  108. sessions: {
  109. listChildren: async (id) => (id === 'root' ? [{ sessionId: 'child' }] : []),
  110. getTaskAgentBinding: async () => ({
  111. definition: { prompt: PRIVATE, description: PRIVATE },
  112. }),
  113. },
  114. locations: {
  115. inspectSession: async (id) => ({
  116. session: {
  117. sessionId: id,
  118. sessionKind: id === 'child' ? 'task' : 'root',
  119. },
  120. paths: {
  121. sessionDir: id === 'root' ? root : child,
  122. snapshots: join(root, 'snapshots'),
  123. },
  124. }),
  125. },
  126. });
  127. const capture = transport();
  128. const service = new TuiFeedbackService({
  129. appVersion: '0.4.12',
  130. authContextGetter: () => ({
  131. accessToken: 'synthetic-account-token',
  132. realUserID: 'synthetic-user',
  133. }),
  134. diagnosticLogUploader: (input) =>
  135. uploadTuiFeedbackDiagnostics(input, {
  136. dataDir,
  137. appVersion: '0.4.12',
  138. fetchImpl: capture.fetchImpl,
  139. collectSessionReport: (id) => reports.collect(id),
  140. }),
  141. fetchImpl: vi.fn<typeof fetch>(async (_url, init) => {
  142. expect(JSON.parse(String(init?.body))).toMatchObject({
  143. description: 'Synthetic feedback',
  144. diagnostic_log: { upload_id: 'synthetic-upload' },
  145. });
  146. return Response.json({ ticket_id: 'synthetic-ticket' });
  147. }),
  148. });
  149. const preview = service.prepare({
  150. description: 'Synthetic feedback',
  151. sessionId: 'root',
  152. });
  153. expect(preview.included.join(' ')).toContain('original contents and filenames are omitted');
  154. const panel = new TuiFeedbackPanel({
  155. preview,
  156. submit: (id, options) => service.submit(id, options),
  157. cancel: async (id) => service.cancel(id),
  158. requestRender() {},
  159. onClose() {},
  160. });
  161. expect(panel.render(120).join('\n')).toContain('No raw attachments');
  162. await service.submit(preview.draftId);
  163. panel.dispose();
  164. const archive = await capture.archive();
  165. expect(archive.text).not.toContain(PRIVATE);
  166. expect(archive.text).not.toContain(dataDir);
  167. expect(archive.text).not.toContain('synthetic-account-token');
  168. expect(archive.summaries).toContainEqual(
  169. expect.objectContaining({
  170. sourceKind: 'messages.jsonl',
  171. counts: expect.objectContaining({
  172. role: { user: 1 },
  173. httpStatus: { '429': 1 },
  174. }),
  175. }),
  176. );
  177. expect(archive.summaries).toContainEqual(
  178. expect.objectContaining({
  179. counts: expect.objectContaining({
  180. level: { error: 1 },
  181. httpStatus: { '503': 1 },
  182. }),
  183. }),
  184. );
  185. expect(archive.summaries.every((summary) => summary.contentOmitted === true)).toBe(true);
  186. expect(
  187. archive.summaries.some((summary) => summary.sourceKind === 'task-agent-definition.json'),
  188. ).toBe(true);
  189. // Redaction affects the upload projection only; local canonical evidence stays intact.
  190. expect(await readFile(join(root, 'messages.jsonl'), 'utf8')).toBe(`${message}\n`);
  191. });
  192. it('never forwards malformed JSON, binary content, unknown keys or nested free text', async () => {
  193. const dataDir = await directory();
  194. const capture = transport();
  195. const contents = [
  196. PRIVATE,
  197. `{"bad":"${PRIVATE}`,
  198. JSON.stringify({
  199. [PRIVATE]: { prompt: PRIVATE },
  200. error: {
  201. cause: {
  202. properties: { headers: [['authorization', PRIVATE]], status: 500 },
  203. },
  204. },
  205. }),
  206. JSON.stringify({ payload: PRIVATE.repeat(200_000) }),
  207. ];
  208. await uploadTuiFeedbackDiagnostics(
  209. {
  210. description: 'Synthetic',
  211. sessionId: PRIVATE,
  212. signal: new AbortController().signal,
  213. },
  214. {
  215. dataDir,
  216. appVersion: PRIVATE,
  217. fetchImpl: capture.fetchImpl,
  218. collectSessionReport: async () => ({
  219. schemaVersion: 1,
  220. rootSessionId: PRIVATE,
  221. sessionIds: [PRIVATE],
  222. artifacts: contents.map((content, index) => ({
  223. name: `session/${PRIVATE}/${index}.json`,
  224. content,
  225. bytes: Buffer.byteLength(content),
  226. required: true,
  227. })),
  228. }),
  229. },
  230. );
  231. const archive = await capture.archive();
  232. expect(archive.text).not.toContain(PRIVATE);
  233. expect(archive.summaries).toHaveLength(4);
  234. expect(archive.summaries[2].counts.httpStatus).toEqual({ '500': 1 });
  235. expect(archive.summaries[0].omittedRecords).toBe(1);
  236. });
  237. it.each(['missing', 'oversized', 'collector'] as const)(
  238. 'keeps safe partial diagnostics when evidence is %s',
  239. async (failure) => {
  240. const dataDir = await directory();
  241. const logs = join(dataDir, 'v2', 'observability', 'logs');
  242. await mkdir(logs, { recursive: true });
  243. await writeFile(join(logs, 'runtime-test.log'), '{"level":"error"}\n');
  244. const capture = transport();
  245. await uploadTuiFeedbackDiagnostics(
  246. {
  247. description: 'Partial',
  248. sessionId: 'root',
  249. signal: new AbortController().signal,
  250. },
  251. {
  252. dataDir,
  253. appVersion: '0.4.12',
  254. fetchImpl: capture.fetchImpl,
  255. collectSessionReport: async () => {
  256. if (failure === 'collector') throw new Error(PRIVATE);
  257. return {
  258. schemaVersion: 1,
  259. rootSessionId: 'root',
  260. sessionIds: ['root'],
  261. artifacts: [
  262. {
  263. name: `session/${PRIVATE}/messages.jsonl`,
  264. path: join(dataDir, PRIVATE),
  265. bytes: failure === 'oversized' ? 17 * 1024 * 1024 : 10,
  266. required: true,
  267. },
  268. ],
  269. };
  270. },
  271. },
  272. );
  273. const archive = await capture.archive();
  274. expect(archive.text).not.toContain(PRIVATE);
  275. const manifest = JSON.parse(
  276. archive.files.find((file) => file.name === 'diagnostic-manifest.json')!.text,
  277. );
  278. expect(manifest.skipped).toHaveLength(1);
  279. expect(archive.summaries[0].counts).toEqual({ level: { error: 1 } });
  280. },
  281. );
  282. it('does not inspect unrelated session manifests or credentials', async () => {
  283. const dataDir = await directory();
  284. const unrelated = join(
  285. dataDir,
  286. 'v2',
  287. 'sessions',
  288. '2026',
  289. '09',
  290. '18',
  291. '10-00-00-000-session_c2Vz',
  292. );
  293. await mkdir(unrelated, { recursive: true });
  294. await writeFile(join(unrelated, 'manifest.json'), '{"status":"failed"}');
  295. const capture = transport();
  296. await uploadTuiFeedbackDiagnostics(
  297. { description: 'No session', signal: new AbortController().signal },
  298. { dataDir, appVersion: '0.4.12', fetchImpl: capture.fetchImpl },
  299. );
  300. expect((await capture.archive()).summaries).toHaveLength(0);
  301. });
  302. it('summarizes all log sources, reads the tail of rotated logs, and keeps whole JSON as one record', async () => {
  303. const dataDir = await directory();
  304. const capture = transport();
  305. const files = [
  306. [
  307. 'v2/observability/logs/archived/runtime-large.log',
  308. `${`${PRIVATE}\n`.repeat(150_000)}{"level":"error"}\n`,
  309. ],
  310. [
  311. 'v2/observability/mcode/mcode-observability-test.jsonl',
  312. '{"level":"warn","password":"hidden"}\n',
  313. ],
  314. [
  315. 'v2/observability/events/2026/09/18/runtime-events-2026-09-18.jsonl',
  316. '{"status":"failed"}\n',
  317. ],
  318. [
  319. 'v2/observability/cli/incidents/pending-test.json',
  320. '{\n "status": "error",\n "eventLog": "private"\n}',
  321. ],
  322. ['logs/cli.log', '{"level":"fatal"}\n'],
  323. ['logs/tui-terminal-test.log', '{"level":"info"}\n'],
  324. ['logs/runtime-legacy.log', '{"level":"debug"}\n'],
  325. ];
  326. for (const [name, content] of files) {
  327. const path = join(dataDir, name!);
  328. await mkdir(path.slice(0, path.lastIndexOf('/')), { recursive: true });
  329. await writeFile(path, content!);
  330. }
  331. const flushLogs = vi.fn(async () => undefined);
  332. await uploadTuiFeedbackDiagnostics(
  333. { description: 'Synthetic', signal: new AbortController().signal },
  334. { dataDir, appVersion: '0.4.12', fetchImpl: capture.fetchImpl, flushLogs },
  335. );
  336. expect(flushLogs).toHaveBeenCalledOnce();
  337. const archive = await capture.archive();
  338. expect(archive.text).not.toContain(PRIVATE);
  339. expect(archive.summaries).toHaveLength(6);
  340. for (const level of ['error', 'warn', 'fatal', 'info']) {
  341. expect(archive.summaries.some((summary) => summary.counts.level?.[level] === 1)).toBe(true);
  342. }
  343. expect(
  344. archive.summaries.some(
  345. (summary) => summary.counts.status?.error === 1 && summary.parsedRecords === 1,
  346. ),
  347. ).toBe(true);
  348. expect(archive.text).not.toContain('debug');
  349. });
  350. it('retains more than 64 prioritized summaries and bounds adversarial nesting', async () => {
  351. const dataDir = await directory();
  352. const capture = transport();
  353. const artifacts = Array.from({ length: 65 }, (_, index) => {
  354. const content = JSON.stringify({ role: 'assistant', content: PRIVATE });
  355. return {
  356. name: `session/root/${index}.json`,
  357. content,
  358. bytes: Buffer.byteLength(content),
  359. required: true as const,
  360. };
  361. });
  362. const nested = `${'{"data":'.repeat(100)}{"status":500,"prompt":"${PRIVATE}"}${'}'.repeat(100)}`;
  363. artifacts.push({
  364. name: 'session/root/deep.json',
  365. content: nested,
  366. bytes: Buffer.byteLength(nested),
  367. required: true,
  368. });
  369. await uploadTuiFeedbackDiagnostics(
  370. { description: 'Synthetic', sessionId: 'root', signal: new AbortController().signal },
  371. {
  372. dataDir,
  373. appVersion: '0.4.12',
  374. fetchImpl: capture.fetchImpl,
  375. collectSessionReport: async () => ({
  376. schemaVersion: 1,
  377. rootSessionId: 'root',
  378. sessionIds: ['root'],
  379. artifacts,
  380. }),
  381. },
  382. );
  383. const archive = await capture.archive();
  384. expect(archive.text).not.toContain(PRIVATE);
  385. expect(archive.summaries).toHaveLength(66);
  386. expect(archive.summaries.at(-1).limited).toBe(true);
  387. });
  388. it('rejects invalid upload receipts and aborts before network transfer', async () => {
  389. const dataDir = await directory();
  390. const fetchImpl = vi.fn<typeof fetch>(async () =>
  391. Response.json({ upload_url: 'https://upload.example.test' }),
  392. );
  393. await expect(
  394. uploadTuiFeedbackDiagnostics(
  395. { description: 'Synthetic', signal: new AbortController().signal },
  396. { dataDir, appVersion: '0.4.12', fetchImpl },
  397. ),
  398. ).rejects.toThrow('invalid upload receipt');
  399. expect(fetchImpl).toHaveBeenCalledOnce();
  400. fetchImpl.mockClear();
  401. await expect(
  402. uploadTuiFeedbackDiagnostics(
  403. { description: 'Synthetic', signal: AbortSignal.abort() },
  404. { dataDir, appVersion: '0.4.12', fetchImpl },
  405. ),
  406. ).rejects.toThrow();
  407. expect(fetchImpl).not.toHaveBeenCalled();
  408. });
  409. });