error-reporting-privacy.test.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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() {
  26. const requests: Array<{ url: string; init: RequestInit }> = [];
  27. const reporter = createDesktopErrorReporter({
  28. authContextGetter: () => ({ accessToken: token, realUserID: userId }),
  29. region: () => 'en',
  30. buildEnv: () => 'prod',
  31. 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. });
  36. return { reporter, requests };
  37. }
  38. describe('automatic error upload privacy boundary', () => {
  39. it('captures the final HTTP batch and decrypts it with receiver credentials without recovering provider content', async () => {
  40. const { reporter, requests } = reporterFixture();
  41. const headers = new Headers({
  42. Authorization: `Bearer ${SECRET}`,
  43. 'x-api-key': SECRET,
  44. cookie: SECRET,
  45. 'x-custom': SECRET,
  46. });
  47. const cause = Object.assign(new Error(SECRET), {
  48. statusCode: 503,
  49. code: 'ECONNRESET',
  50. headers,
  51. prompt: SECRET,
  52. });
  53. const error = Object.assign(new AggregateError([cause, SECRET], SECRET, { cause }), {
  54. status: 429,
  55. properties: {
  56. status: 401,
  57. error: cause,
  58. prompt: SECRET,
  59. headers,
  60. [SECRET]: SECRET,
  61. },
  62. request: { body: SECRET },
  63. data: Buffer.from(SECRET),
  64. map: new Map([[SECRET, SECRET]]),
  65. });
  66. error.stack = SECRET;
  67. const getter = vi.fn(() => SECRET);
  68. Object.defineProperty(error, 'toJSON', { get: getter });
  69. Object.defineProperty(cause, 'request', { get: getter });
  70. createLLMFailureReportHook(reporter, { appVersion: '0.4.12' })({
  71. error,
  72. providerError: { error, properties: { headers, prompt: SECRET } },
  73. errorMessage: SECRET,
  74. metricKind: 'rate_limited',
  75. occurredAtMs: 1234,
  76. request: {
  77. api: SECRET,
  78. model: SECRET,
  79. provider: SECRET,
  80. caller: SECRET,
  81. baseUrl: `https://${SECRET}@example.test/${SECRET}?key=${SECRET}`,
  82. },
  83. });
  84. await reporter.flush();
  85. expect(requests).toHaveLength(1);
  86. expect(getter).not.toHaveBeenCalled();
  87. const request = requests[0]!;
  88. expect(request.url).not.toContain(token);
  89. expect(new Headers(request.init.headers).get('Authorization')).toBe(`Bearer ${token}`);
  90. const batch = JSON.parse(String(request.init.body)) as {
  91. events: DesktopErrorLog[];
  92. };
  93. expect(batch.events).toHaveLength(1);
  94. const plaintext = receiverDecrypt(batch.events[0]!);
  95. expect(plaintext).not.toContain(SECRET);
  96. expect(plaintext).not.toMatch(/headers|prompt|stack|message|baseUrl|request/iu);
  97. expect(JSON.parse(plaintext)).toMatchObject({
  98. schemaVersion: 3,
  99. appVersion: '0.4.12',
  100. metricKind: 'rate_limited',
  101. error: {
  102. status: 429,
  103. cause: { statusCode: 503, code: 'ECONNRESET' },
  104. properties: { status: 401 },
  105. },
  106. });
  107. await reporter.close();
  108. });
  109. it('minimizes direct report input and prevents caller mutation and plaintext envelope injection', async () => {
  110. const { reporter, requests } = reporterFixture();
  111. const event = {
  112. event_type: 'llm_request_failure',
  113. occurred_at_ms: 100,
  114. code_location: SECRET,
  115. event_log: JSON.stringify({
  116. error: { status: 500, properties: { prompt: SECRET }, message: SECRET },
  117. request: SECRET,
  118. }),
  119. unexpected: SECRET,
  120. };
  121. reporter.report(event);
  122. event.event_log = SECRET;
  123. event.code_location = SECRET;
  124. reporter.report({ ...event, event_type: SECRET });
  125. reporter.report({ ...event, event_log: SECRET });
  126. await reporter.flush();
  127. const batch = JSON.parse(String(requests[0]!.init.body)) as {
  128. events: DesktopErrorLog[];
  129. };
  130. expect(batch.events).toHaveLength(2);
  131. for (const uploaded of batch.events) {
  132. expect(JSON.stringify(uploaded)).not.toContain(SECRET);
  133. expect(receiverDecrypt(uploaded)).not.toContain(SECRET);
  134. }
  135. expect(JSON.parse(receiverDecrypt(batch.events[0]!)).error.status).toBe(500);
  136. });
  137. it('bounds cyclic/deep errors, rejects unknown scalar fields and never invokes accessors', () => {
  138. const error: Record<string, unknown> = {
  139. name: SECRET,
  140. code: SECRET,
  141. status: SECRET,
  142. message: SECRET,
  143. };
  144. error.cause = error;
  145. const getter = vi.fn(() => {
  146. throw new Error(SECRET);
  147. });
  148. Object.defineProperty(error, 'properties', { get: getter });
  149. const log = formatErrorLog({
  150. error,
  151. providerError: new Headers({ authorization: SECRET }),
  152. appVersion: SECRET,
  153. metricKind: SECRET,
  154. });
  155. expect(log).not.toContain(SECRET);
  156. expect(log.length).toBeLessThan(512);
  157. expect(getter).not.toHaveBeenCalled();
  158. expect(
  159. formatErrorLog({
  160. error: new Proxy(
  161. {},
  162. {
  163. getOwnPropertyDescriptor() {
  164. throw new Error(SECRET);
  165. },
  166. },
  167. ),
  168. }),
  169. ).not.toContain(SECRET);
  170. });
  171. });