incident-reporter-privacy.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { createDecipheriv, hkdfSync, randomUUID } from 'node:crypto';
  2. import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
  3. import { tmpdir } from 'node:os';
  4. import { join } from 'node:path';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import {
  7. createTuiIncidentReporter,
  8. resolveTuiIncidentDirectory,
  9. } from '../../src/observability/incident-reporter.js';
  10. import type {
  11. TuiIncidentCapture,
  12. TuiIncidentReporter,
  13. } from '../../src/observability/incident-reporter.js';
  14. const privateText = 'Unannounced acquisition of Example Company /home/private/client-plan.txt';
  15. const token = 'synthetic-transport-token';
  16. const userId = 'synthetic-user';
  17. const directories: string[] = [];
  18. const reporters: TuiIncidentReporter[] = [];
  19. afterEach(() => {
  20. for (const reporter of reporters.splice(0)) reporter.completeRun();
  21. for (const directory of directories.splice(0))
  22. rmSync(directory, { recursive: true, force: true });
  23. });
  24. function temporaryDirectory() {
  25. const dataDir = mkdtempSync(join(tmpdir(), 'tui-incident-privacy-'));
  26. directories.push(dataDir);
  27. return dataDir;
  28. }
  29. function fixture(dataDir = temporaryDirectory(), authenticated = true) {
  30. const requests: Array<{ url: string; init: RequestInit }> = [];
  31. const fetchImpl = vi.fn<typeof fetch>(async (url, init) => {
  32. requests.push({ url: String(url), init: init! });
  33. return new Response(null, { status: 204 });
  34. });
  35. const reporter = createTuiIncidentReporter({
  36. dataDir,
  37. appVersion: '0.4.12',
  38. region: 'en',
  39. buildEnv: 'prod',
  40. architecture: 'arm64',
  41. platform: 'darwin',
  42. nodeVersion: '26.4.0',
  43. terminal: privateText,
  44. osVersion: privateText,
  45. tuiMode: privateText,
  46. resolveAuthContext: () =>
  47. authenticated ? { accessToken: token, realUserID: userId } : undefined,
  48. fetchImpl,
  49. });
  50. reporters.push(reporter);
  51. return {
  52. reporter,
  53. requests,
  54. fetchImpl,
  55. directory: resolveTuiIncidentDirectory(dataDir),
  56. };
  57. }
  58. function decrypt(event: Record<string, any>) {
  59. const [version, nonce, payload] = event.event_log.split('.');
  60. expect(version).toBe('v1');
  61. const bytes = Buffer.from(payload, 'base64url');
  62. const key = Buffer.from(
  63. hkdfSync(
  64. 'sha256',
  65. Buffer.from(token),
  66. Buffer.from('mcode-desktop-event-log-v1'),
  67. Buffer.from(userId),
  68. 32,
  69. ),
  70. );
  71. const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(nonce, 'base64url'));
  72. decipher.setAAD(
  73. Buffer.from(
  74. JSON.stringify({
  75. event_type: event.event_type,
  76. occurred_at_ms: event.occurred_at_ms,
  77. }),
  78. ),
  79. );
  80. decipher.setAuthTag(bytes.subarray(-16));
  81. return JSON.parse(
  82. Buffer.concat([decipher.update(bytes.subarray(0, -16)), decipher.final()]).toString(),
  83. );
  84. }
  85. function input(error: unknown): TuiIncidentCapture {
  86. return {
  87. eventType: 'cli_runtime_bridge_error',
  88. error,
  89. component: privateText,
  90. operation: privateText,
  91. codeLocation: privateText,
  92. context: {
  93. [privateText]: privateText,
  94. appVersion: privateText,
  95. prompt: privateText,
  96. },
  97. };
  98. }
  99. function diskRecords(directory: string) {
  100. return readdirSync(directory)
  101. .filter((name) => /^(pending|sent)-/.test(name))
  102. .map((name) => JSON.parse(readFileSync(join(directory, name), 'utf8')));
  103. }
  104. describe('TUI automatic incident HTTP privacy boundary', () => {
  105. it('decrypts the final fetch payload without recovering private text from any capture field', async () => {
  106. const { reporter, requests, directory } = fixture();
  107. const getter = vi.fn(() => privateText);
  108. const error = Object.assign(
  109. new AggregateError([new Error(privateText)], privateText, {
  110. cause: new Error(privateText),
  111. }),
  112. {
  113. name: privateText,
  114. code: 'ECONNRESET',
  115. status: 503,
  116. stack: privateText,
  117. },
  118. );
  119. Object.defineProperty(error, 'toJSON', { get: getter });
  120. reporter.breadcrumb(privateText, { [privateText]: privateText });
  121. reporter.breadcrumb('cli.runtime.events.disconnected', {
  122. reason: privateText,
  123. phase: 'runtime',
  124. });
  125. reporter.capture(input(error));
  126. await reporter.drain();
  127. expect(requests).toHaveLength(1);
  128. expect(requests[0]!.init.method).toBe('POST');
  129. const events = JSON.parse(String(requests[0]!.init.body)).events;
  130. expect(events).toHaveLength(1);
  131. const event = events[0];
  132. expect(event.code_location).toBe('tui.cli_runtime_bridge_error');
  133. const log = decrypt(event);
  134. expect(log.error).toEqual({
  135. name: 'AggregateError',
  136. code: 'ECONNRESET',
  137. status: 503,
  138. });
  139. expect(log.context).toEqual({
  140. appVersion: '0.4.12',
  141. platform: 'darwin',
  142. arch: 'arm64',
  143. nodeVersion: '26.4.0',
  144. });
  145. expect(log.breadcrumbs.at(-1)).toMatchObject({
  146. name: 'cli.runtime.events.disconnected',
  147. details: { phase: 'runtime' },
  148. });
  149. expect(Object.keys(log).sort()).toEqual(
  150. [
  151. 'breadcrumbs',
  152. 'context',
  153. 'error',
  154. 'fingerprint',
  155. 'handled',
  156. 'impact',
  157. 'incidentId',
  158. 'phase',
  159. 'runId',
  160. 'schemaVersion',
  161. 'severity',
  162. 'source',
  163. ].sort(),
  164. );
  165. expect(JSON.stringify([requests, log, diskRecords(directory)])).not.toContain(privateText);
  166. expect(getter).not.toHaveBeenCalled();
  167. expect(readdirSync(directory).filter((name) => name.startsWith('sent-'))).toHaveLength(1);
  168. });
  169. it('drops arbitrary thrown values, custom names/codes and invalid enum inputs, and bounds breadcrumbs', async () => {
  170. const { reporter, requests, directory } = fixture();
  171. const getter = vi.fn(() => privateText);
  172. const error = Object.defineProperties(
  173. {},
  174. {
  175. name: { get: getter },
  176. code: { get: getter },
  177. status: { get: getter },
  178. toString: { value: getter },
  179. },
  180. );
  181. for (let i = 0; i < 100; i++)
  182. reporter.breadcrumb('cli.phase.changed', {
  183. phase: privateText,
  184. text: privateText,
  185. });
  186. const invalid = {
  187. ...input(error),
  188. phase: privateText,
  189. severity: privateText,
  190. impact: privateText,
  191. handled: privateText,
  192. } as unknown as TuiIncidentCapture;
  193. reporter.capture(invalid);
  194. reporter.capture(input(privateText)); // Same minimized category is deduplicated.
  195. expect(
  196. reporter.capture({
  197. ...input(error),
  198. eventType: privateText,
  199. } as TuiIncidentCapture),
  200. ).toBeUndefined();
  201. await reporter.drain();
  202. const events = requests.flatMap((request) => JSON.parse(String(request.init.body)).events);
  203. expect(events).toHaveLength(1);
  204. const log = decrypt(events[0]);
  205. expect(log.error).toEqual({ name: 'unknown' });
  206. expect(log.breadcrumbs).toHaveLength(20);
  207. expect(log.phase).toBe('runtime');
  208. expect(log.severity).toBe('error');
  209. expect(log.impact).toBe('action_failed');
  210. expect(log.handled).toBe(true);
  211. expect(Buffer.byteLength(JSON.stringify(log))).toBeLessThan(16 * 1024);
  212. expect(JSON.stringify([log, diskRecords(directory)])).not.toContain(privateText);
  213. expect(getter).not.toHaveBeenCalled();
  214. });
  215. it('purges legacy pending and sent records before authentication, including legacy records added later', async () => {
  216. const dataDir = temporaryDirectory();
  217. const directory = resolveTuiIncidentDirectory(dataDir);
  218. mkdirSync(directory, { recursive: true });
  219. const legacy = {
  220. schemaVersion: 1,
  221. incidentId: randomUUID(),
  222. eventType: 'cli_process_error',
  223. occurredAtMs: Date.now(),
  224. codeLocation: privateText,
  225. eventLog: JSON.stringify({ error: privateText }),
  226. };
  227. for (const prefix of ['pending', 'sent'])
  228. writeFileSync(join(directory, `${prefix}-legacy.json`), JSON.stringify(legacy));
  229. const unauthenticated = fixture(dataDir, false);
  230. await unauthenticated.reporter.drain();
  231. expect(diskRecords(directory)).toEqual([]);
  232. expect(unauthenticated.requests).toEqual([]);
  233. unauthenticated.reporter.completeRun();
  234. const { reporter, requests } = fixture(dataDir);
  235. writeFileSync(join(directory, 'pending-late-legacy.json'), JSON.stringify(legacy));
  236. await reporter.drain();
  237. expect(requests).toEqual([]);
  238. expect(diskRecords(directory)).toEqual([]);
  239. });
  240. it('reprojects a current-schema disk record at retry, including the plaintext envelope and sent copy', async () => {
  241. const { reporter, requests, directory, fetchImpl } = fixture();
  242. const onlineFetch = fetchImpl.getMockImplementation()!;
  243. fetchImpl.mockImplementation(async () => {
  244. throw new Error('Synthetic offline');
  245. });
  246. reporter.capture(input(new Error(privateText)));
  247. await reporter.drain();
  248. expect(requests).toEqual([]);
  249. const name = readdirSync(directory).find((name) => name.startsWith('pending-'))!;
  250. const path = join(directory, name);
  251. const stored = JSON.parse(readFileSync(path, 'utf8'));
  252. const log = JSON.parse(stored.eventLog);
  253. stored.codeLocation = privateText;
  254. stored.extra = privateText;
  255. stored.eventLog = JSON.stringify({
  256. ...log,
  257. component: privateText,
  258. operation: privateText,
  259. fingerprint: privateText,
  260. error: {
  261. name: privateText,
  262. message: privateText,
  263. code: privateText,
  264. cause: privateText,
  265. stack: privateText,
  266. },
  267. context: {
  268. appVersion: privateText,
  269. platform: privateText,
  270. arch: privateText,
  271. nodeVersion: privateText,
  272. custom: privateText,
  273. },
  274. breadcrumbs: [{ name: privateText, details: { text: privateText } }],
  275. });
  276. writeFileSync(path, JSON.stringify(stored));
  277. fetchImpl.mockImplementation(onlineFetch);
  278. await reporter.drain();
  279. expect(requests).toHaveLength(1);
  280. const event = JSON.parse(String(requests[0]!.init.body)).events[0];
  281. expect(event.code_location).toBe('tui.cli_runtime_bridge_error');
  282. const cleanLog = decrypt(event);
  283. expect(cleanLog.error).toEqual({ name: 'unknown' });
  284. expect(cleanLog.context).toEqual({});
  285. expect(cleanLog.breadcrumbs).toEqual([]);
  286. expect(JSON.stringify([event, cleanLog, diskRecords(directory)])).not.toContain(privateText);
  287. });
  288. });