error-reporting-privacy.test.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import { createDecipheriv } from 'node:crypto';
  2. import { describe, expect, it, vi } from 'vitest';
  3. import { createDesktopErrorReporter, formatErrorLog } from '../../src/error-reporting/reporter.js';
  4. import { createLLMFailureReportHook } from '../../src/error-reporting/llm-integration.js';
  5. import { buildAssociatedData, deriveEventLogKey } from '../../src/error-reporting/crypto.js';
  6. import type { DesktopErrorLog } from '../../src/error-reporting/types.js';
  7. const SECRET = 'SYNTHETIC_PRIVATE_4cd7';
  8. const token = 'synthetic-managed-transport-token';
  9. const userId = 'synthetic-user';
  10. function receiverDecrypt(event: DesktopErrorLog): string {
  11. const [version, nonce, payload] = event.event_log.split('.');
  12. expect(version).toBe('v1');
  13. const bytes = Buffer.from(payload!, 'base64url');
  14. const decipher = createDecipheriv(
  15. 'aes-256-gcm',
  16. deriveEventLogKey(token, userId),
  17. Buffer.from(nonce!, 'base64url'),
  18. );
  19. decipher.setAAD(buildAssociatedData(event));
  20. decipher.setAuthTag(bytes.subarray(-16));
  21. return Buffer.concat([decipher.update(bytes.subarray(0, -16)), decipher.final()]).toString(
  22. 'utf8',
  23. );
  24. }
  25. function reporterFixture(readTelemetryEnabled: () => boolean | undefined = () => true) {
  26. const requests: Array<{ url: string; init: RequestInit }> = [];
  27. const reporter = createDesktopErrorReporter({
  28. readTelemetryEnabled,
  29. authContextGetter: () => ({ accessToken: token, realUserID: userId }),
  30. region: () => 'en',
  31. buildEnv: () => 'prod',
  32. fetchImpl: vi.fn<typeof fetch>(async (url, init) => {
  33. requests.push({ url: String(url), init: init! });
  34. return new Response(null, { status: 204 });
  35. }),
  36. });
  37. return { reporter, requests };
  38. }
  39. describe('automatic error upload privacy boundary', () => {
  40. it.each([undefined, false])('does not upload without an explicit diagnostics opt-in (%s)', async (enabled) => {
  41. const { reporter, requests } = reporterFixture(() => enabled);
  42. reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
  43. await reporter.flush();
  44. expect(requests).toEqual([]);
  45. });
  46. it.each(['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('%s overrides the diagnostics opt-in', async (key) => {
  47. vi.stubEnv(key, '1');
  48. try {
  49. const { reporter, requests } = reporterFixture(() => true);
  50. reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
  51. await reporter.flush();
  52. expect(requests).toEqual([]);
  53. } finally {
  54. vi.unstubAllEnvs();
  55. }
  56. });
  57. it.each(['config', 'MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('drops buffered diagnostics when %s revokes consent before flushing', async (source) => {
  58. let enabled = true;
  59. const { reporter, requests } = reporterFixture(() => enabled);
  60. try {
  61. reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
  62. if (source === 'config') enabled = false;
  63. else vi.stubEnv(source, '1');
  64. await reporter.flush();
  65. expect(requests).toEqual([]);
  66. enabled = true;
  67. vi.unstubAllEnvs();
  68. await reporter.flush();
  69. expect(requests).toEqual([]);
  70. } finally {
  71. await reporter.close();
  72. vi.unstubAllEnvs();
  73. }
  74. });
  75. it('captures the final HTTP batch and decrypts it with receiver credentials without recovering provider content', async () => {
  76. const { reporter, requests } = reporterFixture();
  77. const headers = new Headers({
  78. Authorization: `Bearer ${SECRET}`,
  79. 'x-api-key': SECRET,
  80. cookie: SECRET,
  81. 'x-custom': SECRET,
  82. });
  83. const cause = Object.assign(new Error(SECRET), {
  84. statusCode: 503,
  85. code: 'ECONNRESET',
  86. headers,
  87. prompt: SECRET,
  88. });
  89. const error = Object.assign(new AggregateError([cause, SECRET], SECRET, { cause }), {
  90. status: 429,
  91. properties: {
  92. status: 401,
  93. error: cause,
  94. prompt: SECRET,
  95. headers,
  96. [SECRET]: SECRET,
  97. },
  98. request: { body: SECRET },
  99. data: Buffer.from(SECRET),
  100. map: new Map([[SECRET, SECRET]]),
  101. });
  102. error.stack = SECRET;
  103. const getter = vi.fn(() => SECRET);
  104. Object.defineProperty(error, 'toJSON', { get: getter });
  105. Object.defineProperty(cause, 'request', { get: getter });
  106. createLLMFailureReportHook(reporter, { appVersion: '0.4.12' })({
  107. error,
  108. providerError: { error, properties: { headers, prompt: SECRET } },
  109. errorMessage: SECRET,
  110. metricKind: 'rate_limited',
  111. occurredAtMs: 1234,
  112. request: {
  113. api: SECRET,
  114. model: SECRET,
  115. provider: SECRET,
  116. caller: SECRET,
  117. baseUrl: `https://${SECRET}@example.test/${SECRET}?key=${SECRET}`,
  118. },
  119. });
  120. await reporter.flush();
  121. expect(requests).toHaveLength(1);
  122. expect(getter).not.toHaveBeenCalled();
  123. const request = requests[0]!;
  124. expect(request.url).not.toContain(token);
  125. expect(new Headers(request.init.headers).get('Authorization')).toBe(`Bearer ${token}`);
  126. const batch = JSON.parse(String(request.init.body)) as {
  127. events: DesktopErrorLog[];
  128. };
  129. expect(batch.events).toHaveLength(1);
  130. const plaintext = receiverDecrypt(batch.events[0]!);
  131. expect(plaintext).not.toContain(SECRET);
  132. expect(plaintext).not.toMatch(/headers|prompt|stack|message|baseUrl|request/iu);
  133. expect(JSON.parse(plaintext)).toMatchObject({
  134. schemaVersion: 3,
  135. appVersion: '0.4.12',
  136. metricKind: 'rate_limited',
  137. error: {
  138. status: 429,
  139. cause: { statusCode: 503, code: 'ECONNRESET' },
  140. properties: { status: 401 },
  141. },
  142. });
  143. await reporter.close();
  144. });
  145. it('minimizes direct report input and prevents caller mutation and plaintext envelope injection', async () => {
  146. const { reporter, requests } = reporterFixture();
  147. const event = {
  148. event_type: 'llm_request_failure',
  149. occurred_at_ms: 100,
  150. code_location: SECRET,
  151. event_log: JSON.stringify({
  152. error: { status: 500, properties: { prompt: SECRET }, message: SECRET },
  153. request: SECRET,
  154. }),
  155. unexpected: SECRET,
  156. };
  157. reporter.report(event);
  158. event.event_log = SECRET;
  159. event.code_location = SECRET;
  160. reporter.report({ ...event, event_type: SECRET });
  161. reporter.report({ ...event, event_log: SECRET });
  162. await reporter.flush();
  163. const batch = JSON.parse(String(requests[0]!.init.body)) as {
  164. events: DesktopErrorLog[];
  165. };
  166. expect(batch.events).toHaveLength(2);
  167. for (const uploaded of batch.events) {
  168. expect(JSON.stringify(uploaded)).not.toContain(SECRET);
  169. expect(receiverDecrypt(uploaded)).not.toContain(SECRET);
  170. }
  171. expect(JSON.parse(receiverDecrypt(batch.events[0]!)).error.status).toBe(500);
  172. });
  173. it('bounds cyclic/deep errors, rejects unknown scalar fields and never invokes accessors', () => {
  174. const error: Record<string, unknown> = {
  175. name: SECRET,
  176. code: SECRET,
  177. status: SECRET,
  178. message: SECRET,
  179. };
  180. error.cause = error;
  181. const getter = vi.fn(() => {
  182. throw new Error(SECRET);
  183. });
  184. Object.defineProperty(error, 'properties', { get: getter });
  185. const log = formatErrorLog({
  186. error,
  187. providerError: new Headers({ authorization: SECRET }),
  188. appVersion: SECRET,
  189. metricKind: SECRET,
  190. });
  191. expect(log).not.toContain(SECRET);
  192. expect(log.length).toBeLessThan(512);
  193. expect(getter).not.toHaveBeenCalled();
  194. expect(
  195. formatErrorLog({
  196. error: new Proxy(
  197. {},
  198. {
  199. getOwnPropertyDescriptor() {
  200. throw new Error(SECRET);
  201. },
  202. },
  203. ),
  204. }),
  205. ).not.toContain(SECRET);
  206. });
  207. });