@optimizely-opal/opal-tool-ocp-sdk 1.0.0-beta.1 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +169 -3
  2. package/dist/auth/AuthUtils.d.ts +12 -5
  3. package/dist/auth/AuthUtils.d.ts.map +1 -1
  4. package/dist/auth/AuthUtils.js +80 -25
  5. package/dist/auth/AuthUtils.js.map +1 -1
  6. package/dist/auth/AuthUtils.test.js +161 -117
  7. package/dist/auth/AuthUtils.test.js.map +1 -1
  8. package/dist/function/GlobalToolFunction.d.ts +5 -3
  9. package/dist/function/GlobalToolFunction.d.ts.map +1 -1
  10. package/dist/function/GlobalToolFunction.js +32 -8
  11. package/dist/function/GlobalToolFunction.js.map +1 -1
  12. package/dist/function/GlobalToolFunction.test.js +73 -12
  13. package/dist/function/GlobalToolFunction.test.js.map +1 -1
  14. package/dist/function/ToolFunction.d.ts +11 -4
  15. package/dist/function/ToolFunction.d.ts.map +1 -1
  16. package/dist/function/ToolFunction.js +45 -9
  17. package/dist/function/ToolFunction.js.map +1 -1
  18. package/dist/function/ToolFunction.test.js +278 -11
  19. package/dist/function/ToolFunction.test.js.map +1 -1
  20. package/dist/index.d.ts +2 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +3 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/logging/ToolLogger.d.ts +42 -0
  25. package/dist/logging/ToolLogger.d.ts.map +1 -0
  26. package/dist/logging/ToolLogger.js +255 -0
  27. package/dist/logging/ToolLogger.js.map +1 -0
  28. package/dist/logging/ToolLogger.test.d.ts +2 -0
  29. package/dist/logging/ToolLogger.test.d.ts.map +1 -0
  30. package/dist/logging/ToolLogger.test.js +864 -0
  31. package/dist/logging/ToolLogger.test.js.map +1 -0
  32. package/dist/service/Service.d.ts +88 -2
  33. package/dist/service/Service.d.ts.map +1 -1
  34. package/dist/service/Service.js +228 -39
  35. package/dist/service/Service.js.map +1 -1
  36. package/dist/service/Service.test.js +558 -22
  37. package/dist/service/Service.test.js.map +1 -1
  38. package/dist/types/Models.d.ts +7 -1
  39. package/dist/types/Models.d.ts.map +1 -1
  40. package/dist/types/Models.js +5 -1
  41. package/dist/types/Models.js.map +1 -1
  42. package/dist/types/ToolError.d.ts +72 -0
  43. package/dist/types/ToolError.d.ts.map +1 -0
  44. package/dist/types/ToolError.js +107 -0
  45. package/dist/types/ToolError.js.map +1 -0
  46. package/dist/types/ToolError.test.d.ts +2 -0
  47. package/dist/types/ToolError.test.d.ts.map +1 -0
  48. package/dist/types/ToolError.test.js +185 -0
  49. package/dist/types/ToolError.test.js.map +1 -0
  50. package/dist/validation/ParameterValidator.d.ts +31 -0
  51. package/dist/validation/ParameterValidator.d.ts.map +1 -0
  52. package/dist/validation/ParameterValidator.js +129 -0
  53. package/dist/validation/ParameterValidator.js.map +1 -0
  54. package/dist/validation/ParameterValidator.test.d.ts +2 -0
  55. package/dist/validation/ParameterValidator.test.d.ts.map +1 -0
  56. package/dist/validation/ParameterValidator.test.js +323 -0
  57. package/dist/validation/ParameterValidator.test.js.map +1 -0
  58. package/package.json +3 -3
  59. package/src/auth/AuthUtils.test.ts +176 -157
  60. package/src/auth/AuthUtils.ts +96 -33
  61. package/src/function/GlobalToolFunction.test.ts +78 -14
  62. package/src/function/GlobalToolFunction.ts +46 -11
  63. package/src/function/ToolFunction.test.ts +298 -13
  64. package/src/function/ToolFunction.ts +61 -13
  65. package/src/index.ts +2 -1
  66. package/src/logging/ToolLogger.test.ts +1020 -0
  67. package/src/logging/ToolLogger.ts +292 -0
  68. package/src/service/Service.test.ts +712 -28
  69. package/src/service/Service.ts +288 -38
  70. package/src/types/Models.ts +8 -1
  71. package/src/types/ToolError.test.ts +222 -0
  72. package/src/types/ToolError.ts +125 -0
  73. package/src/validation/ParameterValidator.test.ts +371 -0
  74. package/src/validation/ParameterValidator.ts +150 -0
@@ -0,0 +1,1020 @@
1
+ import { ToolLogger } from './ToolLogger';
2
+ import { logger, LogVisibility } from '@zaiusinc/app-sdk';
3
+ import * as App from '@zaiusinc/app-sdk';
4
+
5
+ // Mock the logger
6
+ jest.mock('@zaiusinc/app-sdk', () => ({
7
+ logger: {
8
+ info: jest.fn()
9
+ },
10
+ LogVisibility: {
11
+ Zaius: 'zaius'
12
+ },
13
+ Headers: jest.fn(),
14
+ Response: jest.fn()
15
+ }));
16
+
17
+ describe('ToolLogger', () => {
18
+ const mockLogger = logger as jest.Mocked<typeof logger>;
19
+
20
+ beforeEach(() => {
21
+ jest.clearAllMocks();
22
+ });
23
+
24
+ // Helper function to check JSON string logs
25
+ const expectJsonLog = (expectedData: any) => {
26
+ expect(mockLogger.info).toHaveBeenCalledWith(
27
+ LogVisibility.Zaius,
28
+ JSON.stringify(expectedData)
29
+ );
30
+ };
31
+
32
+ const createMockRequest = (overrides: any = {}): App.Request => {
33
+ const defaultRequest = {
34
+ path: '/test-tool',
35
+ method: 'POST',
36
+ bodyJSON: {
37
+ parameters: {
38
+ name: 'test',
39
+ value: 'data'
40
+ }
41
+ },
42
+ headers: {
43
+ get: jest.fn().mockReturnValue('application/json')
44
+ }
45
+ };
46
+
47
+ return { ...defaultRequest, ...overrides };
48
+ };
49
+
50
+ const createMockResponse = (status = 200, bodyJSON: any = {}, headers: any = {}): App.Response => {
51
+ const mockHeaders = {
52
+ get: jest.fn().mockImplementation((name: string) => {
53
+ if (name === 'content-type') return 'application/json';
54
+ return headers[name] || null;
55
+ })
56
+ };
57
+
58
+ const response = {
59
+ status,
60
+ headers: mockHeaders,
61
+ _bodyJSON: bodyJSON
62
+ } as any;
63
+
64
+ // Add getter for bodyJSON that returns the stored value
65
+ Object.defineProperty(response, 'bodyJSON', {
66
+ get() {
67
+ return this._bodyJSON;
68
+ },
69
+ set(value) {
70
+ this._bodyJSON = value;
71
+ },
72
+ enumerable: true
73
+ });
74
+
75
+ // Add getter for bodyAsU8Array that recalculates based on current bodyJSON
76
+ Object.defineProperty(response, 'bodyAsU8Array', {
77
+ get() {
78
+ if (this._bodyJSON !== null && this._bodyJSON !== undefined) {
79
+ // This will throw for circular references, which matches real behavior
80
+ const jsonString = JSON.stringify(this._bodyJSON);
81
+ return new Uint8Array(Buffer.from(jsonString));
82
+ }
83
+ return undefined;
84
+ },
85
+ enumerable: true
86
+ });
87
+
88
+ return response;
89
+ };
90
+
91
+ const createMockResponseWithBody = (
92
+ status: number,
93
+ bodyData: Uint8Array | undefined,
94
+ contentType: string
95
+ ): App.Response => {
96
+ const mockHeaders = {
97
+ get: jest.fn().mockReturnValue(contentType)
98
+ };
99
+
100
+ const response = {
101
+ status,
102
+ headers: mockHeaders
103
+ } as any;
104
+
105
+ Object.defineProperty(response, 'bodyAsU8Array', {
106
+ get() {
107
+ return bodyData;
108
+ },
109
+ enumerable: true
110
+ });
111
+
112
+ return response;
113
+ };
114
+
115
+ describe('logRequest', () => {
116
+ it('should log request with parameters', () => {
117
+ const req = createMockRequest();
118
+
119
+ ToolLogger.logRequest(req);
120
+
121
+ const expectedLog = {
122
+ event: 'opal_tool_request',
123
+ path: '/test-tool',
124
+ method: 'POST',
125
+ parameters: {
126
+ name: 'test',
127
+ value: 'data'
128
+ }
129
+ };
130
+
131
+ expect(mockLogger.info).toHaveBeenCalledWith(
132
+ LogVisibility.Zaius,
133
+ JSON.stringify(expectedLog)
134
+ );
135
+ });
136
+
137
+ it('should handle request without parameters', () => {
138
+ const req = createMockRequest({
139
+ bodyJSON: null
140
+ });
141
+
142
+ ToolLogger.logRequest(req);
143
+
144
+ expectJsonLog({
145
+ event: 'opal_tool_request',
146
+ path: '/test-tool',
147
+ method: 'POST',
148
+ parameters: null
149
+ });
150
+ });
151
+
152
+ it('should use bodyJSON as parameters when no parameters field exists', () => {
153
+ const req = createMockRequest({
154
+ bodyJSON: {
155
+ name: 'direct',
156
+ action: 'test'
157
+ }
158
+ });
159
+
160
+ ToolLogger.logRequest(req);
161
+
162
+ expectJsonLog({
163
+ event: 'opal_tool_request',
164
+ path: '/test-tool',
165
+ method: 'POST',
166
+ parameters: {
167
+ name: 'direct',
168
+ action: 'test'
169
+ }
170
+ });
171
+ });
172
+
173
+ it('should redact all sensitive field variations', () => {
174
+ const req = createMockRequest({
175
+ bodyJSON: {
176
+ parameters: {
177
+ username: 'john',
178
+ password: 'secret123',
179
+ api_key: 'key123',
180
+ secret: 'mysecret',
181
+ token: 'abc123',
182
+ auth: 'authdata',
183
+ credentials: 'creds',
184
+ access_token: 'access123',
185
+ refresh_token: 'refresh123',
186
+ private_key: 'privatekey',
187
+ client_secret: 'clientsecret',
188
+ normal_field: 'visible'
189
+ }
190
+ }
191
+ });
192
+
193
+ ToolLogger.logRequest(req);
194
+
195
+ expectJsonLog({
196
+ event: 'opal_tool_request',
197
+ path: '/test-tool',
198
+ method: 'POST',
199
+ parameters: {
200
+ username: 'john',
201
+ password: '[REDACTED]',
202
+ api_key: '[REDACTED]',
203
+ secret: '[REDACTED]',
204
+ token: '[REDACTED]',
205
+ auth: '[REDACTED]',
206
+ credentials: '[REDACTED]',
207
+ access_token: '[REDACTED]',
208
+ refresh_token: '[REDACTED]',
209
+ private_key: '[REDACTED]',
210
+ client_secret: '[REDACTED]',
211
+ normal_field: 'visible'
212
+ }
213
+ });
214
+ });
215
+
216
+ it('should redact sensitive fields with case variations', () => {
217
+ const req = createMockRequest({
218
+ bodyJSON: {
219
+ parameters: {
220
+ PASSWORD: 'secret1',
221
+ API_KEY: 'secret2',
222
+ clientSecret: 'secret3',
223
+ user_password: 'secret4',
224
+ oauth_token: 'secret5',
225
+ ssh_key: 'secret6',
226
+ normal_field: 'visible'
227
+ }
228
+ }
229
+ });
230
+
231
+ ToolLogger.logRequest(req);
232
+
233
+ expectJsonLog({
234
+ event: 'opal_tool_request',
235
+ path: '/test-tool',
236
+ method: 'POST',
237
+ parameters: {
238
+ PASSWORD: '[REDACTED]',
239
+ API_KEY: '[REDACTED]',
240
+ clientSecret: '[REDACTED]',
241
+ user_password: '[REDACTED]',
242
+ oauth_token: '[REDACTED]',
243
+ ssh_key: '[REDACTED]',
244
+ normal_field: 'visible'
245
+ }
246
+ });
247
+ });
248
+
249
+ it('should truncate long string values', () => {
250
+ const longString = 'a'.repeat(150);
251
+ const req = createMockRequest({
252
+ bodyJSON: {
253
+ parameters: {
254
+ description: longString,
255
+ short_field: 'normal'
256
+ }
257
+ }
258
+ });
259
+
260
+ ToolLogger.logRequest(req);
261
+
262
+ expectJsonLog({
263
+ event: 'opal_tool_request',
264
+ path: '/test-tool',
265
+ method: 'POST',
266
+ parameters: {
267
+ description: `${'a'.repeat(118)}...[22 truncated]...${'a'.repeat(10)}`,
268
+ short_field: 'normal'
269
+ }
270
+ });
271
+ });
272
+
273
+ it('should truncate large arrays', () => {
274
+ const largeArray = Array.from({ length: 15 }, (_, i) => `item${i}`);
275
+ const req = createMockRequest({
276
+ bodyJSON: {
277
+ parameters: {
278
+ items: largeArray,
279
+ small_array: ['a', 'b']
280
+ }
281
+ }
282
+ });
283
+
284
+ ToolLogger.logRequest(req);
285
+
286
+ expectJsonLog({
287
+ event: 'opal_tool_request',
288
+ path: '/test-tool',
289
+ method: 'POST',
290
+ parameters: {
291
+ items: [
292
+ ...largeArray.slice(0, 2),
293
+ '... (13 more items truncated)'
294
+ ],
295
+ small_array: ['a', 'b']
296
+ }
297
+ });
298
+ });
299
+
300
+ it('should handle nested objects with sensitive fields', () => {
301
+ const req = createMockRequest({
302
+ bodyJSON: {
303
+ parameters: {
304
+ user: {
305
+ name: 'John',
306
+ email: 'john@example.com',
307
+ password: 'secret123'
308
+ },
309
+ config: {
310
+ database: {
311
+ host: 'localhost',
312
+ port: 5432,
313
+ password: 'dbpass'
314
+ },
315
+ api_key: 'apikey123'
316
+ }
317
+ }
318
+ }
319
+ });
320
+
321
+ ToolLogger.logRequest(req);
322
+
323
+ expectJsonLog({
324
+ event: 'opal_tool_request',
325
+ path: '/test-tool',
326
+ method: 'POST',
327
+ parameters: {
328
+ user: {
329
+ name: 'John',
330
+ email: '[REDACTED]',
331
+ password: '[REDACTED]'
332
+ },
333
+ config: {
334
+ database: {
335
+ host: 'localhost',
336
+ port: 5432,
337
+ password: '[REDACTED]'
338
+ },
339
+ api_key: '[REDACTED]'
340
+ }
341
+ }
342
+ });
343
+ });
344
+
345
+ it('should handle null and undefined values', () => {
346
+ const req = createMockRequest({
347
+ bodyJSON: {
348
+ parameters: {
349
+ nullValue: null,
350
+ undefinedValue: undefined,
351
+ emptyString: '',
352
+ zero: 0,
353
+ false: false,
354
+ password: null // sensitive field with null value
355
+ }
356
+ }
357
+ });
358
+
359
+ ToolLogger.logRequest(req);
360
+
361
+ expectJsonLog({
362
+ event: 'opal_tool_request',
363
+ path: '/test-tool',
364
+ method: 'POST',
365
+ parameters: {
366
+ nullValue: null,
367
+ emptyString: '',
368
+ zero: 0,
369
+ false: false,
370
+ password: '[REDACTED]'
371
+ }
372
+ });
373
+ });
374
+
375
+ it('should handle arrays in sensitive fields', () => {
376
+ const req = createMockRequest({
377
+ bodyJSON: {
378
+ parameters: {
379
+ credentials: ['user', 'pass', 'token'],
380
+ public_list: ['item1', 'item2']
381
+ }
382
+ }
383
+ });
384
+
385
+ ToolLogger.logRequest(req);
386
+
387
+ expectJsonLog({
388
+ event: 'opal_tool_request',
389
+ path: '/test-tool',
390
+ method: 'POST',
391
+ parameters: {
392
+ credentials: '[REDACTED]',
393
+ public_list: ['item1', 'item2']
394
+ }
395
+ });
396
+ });
397
+
398
+ it('should handle objects in sensitive fields', () => {
399
+ const req = createMockRequest({
400
+ bodyJSON: {
401
+ parameters: {
402
+ auth: {
403
+ username: 'john',
404
+ password: 'secret'
405
+ },
406
+ public_config: {
407
+ timeout: 30,
408
+ retries: 3
409
+ }
410
+ }
411
+ }
412
+ });
413
+
414
+ ToolLogger.logRequest(req);
415
+
416
+ expectJsonLog({
417
+ event: 'opal_tool_request',
418
+ path: '/test-tool',
419
+ method: 'POST',
420
+ parameters: {
421
+ auth: '[REDACTED]',
422
+ public_config: {
423
+ timeout: 30,
424
+ retries: 3
425
+ }
426
+ }
427
+ });
428
+ });
429
+
430
+ it('should respect max depth to prevent infinite recursion', () => {
431
+ const deepObject: any = { level: 0, data: 'test' };
432
+ let current = deepObject;
433
+
434
+ // Create a very deep nested object (deeper than maxDepth)
435
+ for (let i = 1; i <= 10; i++) {
436
+ current.nested = { level: i, data: `level${i}` };
437
+ current = current.nested;
438
+ }
439
+
440
+ const req = createMockRequest({
441
+ bodyJSON: { parameters: { deep: deepObject } }
442
+ });
443
+
444
+ // Should not throw error or cause infinite recursion
445
+ expect(() => ToolLogger.logRequest(req)).not.toThrow();
446
+ expect(mockLogger.info).toHaveBeenCalled();
447
+
448
+ // Verify that deeply nested parts are replaced with placeholder
449
+ const logCall = mockLogger.info.mock.calls[0];
450
+ const loggedData = JSON.parse(logCall[1]);
451
+
452
+ // Navigate to a deeply nested level that should be truncated
453
+ // At maxDepth=5, objects beyond depth 5 should be replaced
454
+ const nested1 = loggedData.parameters.deep.nested;
455
+ expect(nested1).toBeDefined(); // depth 2
456
+ const nested2 = nested1.nested;
457
+ expect(nested2).toBeDefined(); // depth 3
458
+ const nested3 = nested2.nested;
459
+ expect(nested3).toBeDefined(); // depth 4
460
+ const nested4 = nested3.nested;
461
+ expect(nested4).toBe('[MAX_DEPTH_EXCEEDED]'); // depth 5, should be truncated
462
+ });
463
+
464
+ it('should replace deeply nested objects with MAX_DEPTH_EXCEEDED placeholder', () => {
465
+ // Create an object with exactly 6 levels (exceeds maxDepth of 5)
466
+ const deepObject = {
467
+ level1: {
468
+ level2: {
469
+ level3: {
470
+ level4: {
471
+ level5: {
472
+ level6: {
473
+ password: 'should-not-be-visible',
474
+ credit_card: '1234-5678-9012-3456',
475
+ data: 'sensitive-info'
476
+ }
477
+ }
478
+ }
479
+ }
480
+ }
481
+ }
482
+ };
483
+
484
+ const req = createMockRequest({
485
+ bodyJSON: { parameters: { deep: deepObject } }
486
+ });
487
+
488
+ ToolLogger.logRequest(req);
489
+
490
+ // Verify that the deeply nested object is replaced with placeholder
491
+ const logCall = mockLogger.info.mock.calls[0];
492
+ const loggedData = JSON.parse(logCall[1]);
493
+
494
+ // Navigate to the deeply nested part that should be replaced
495
+ // At maxDepth=5, the 5th level (level4) gets replaced with the placeholder
496
+ const level4 = loggedData.parameters.deep.level1.level2.level3.level4;
497
+ expect(level4).toBe('[MAX_DEPTH_EXCEEDED]');
498
+ });
499
+
500
+ it('should handle arrays containing deeply nested objects that exceed max depth', () => {
501
+ // Create a structure where the array is shallow enough to be processed (depth 3),
502
+ // but individual objects within the array exceed the max depth
503
+ const arrayWithDeepObjects = {
504
+ level1: {
505
+ items: [
506
+ {
507
+ shallow: 'data',
508
+ level2: {
509
+ level3: {
510
+ level4: {
511
+ level5: {
512
+ password: 'secret-in-deep-array-object',
513
+ credit_card: '1234-5678-9012-3456'
514
+ }
515
+ }
516
+ }
517
+ }
518
+ },
519
+ 'simple-item',
520
+ {
521
+ shallow: 'data'
522
+ },
523
+ {
524
+ level2: {
525
+ level3: {
526
+ level4: {
527
+ another: 'deep-object'
528
+ }
529
+ }
530
+ }
531
+ }
532
+ ]
533
+ }
534
+ };
535
+
536
+ const req = createMockRequest({
537
+ bodyJSON: { parameters: arrayWithDeepObjects }
538
+ });
539
+
540
+ ToolLogger.logRequest(req);
541
+
542
+ // Verify the array structure and depth handling
543
+ const logCall = mockLogger.info.mock.calls[0];
544
+ const loggedData = JSON.parse(logCall[1]);
545
+
546
+ const items = loggedData.parameters.level1.items;
547
+ expect(items.length).toBe(3);
548
+
549
+ // First item: deeply nested object with inner parts replaced by placeholder
550
+ // shallow object should be processed normally
551
+ expect(items[0]).toEqual({
552
+ shallow: 'data',
553
+ level2: {
554
+ level3: {
555
+ level4: '[MAX_DEPTH_EXCEEDED]'
556
+ }
557
+ }
558
+ });
559
+
560
+ // Second item: simple string should remain unchanged
561
+ expect(items[1]).toBe('simple-item');
562
+ });
563
+ });
564
+
565
+ describe('logResponse', () => {
566
+ it('should log successful response with all details', () => {
567
+ const req = createMockRequest();
568
+ const response = createMockResponse(200, { result: 'success', data: 'test' });
569
+
570
+ ToolLogger.logResponse(req, response, 150);
571
+
572
+ const expectedLog = {
573
+ event: 'opal_tool_response',
574
+ path: '/test-tool',
575
+ duration: '150ms',
576
+ status: 200,
577
+ contentType: 'application/json',
578
+ contentLength: 34, // JSON.stringify({ result: 'success', data: 'test' }).length
579
+ success: true,
580
+ responseBody: { result: 'success', data: 'test' }
581
+ };
582
+
583
+ expect(mockLogger.info).toHaveBeenCalledWith(
584
+ LogVisibility.Zaius,
585
+ JSON.stringify(expectedLog)
586
+ );
587
+ });
588
+
589
+ it('should log error response', () => {
590
+ const req = createMockRequest();
591
+ const response = createMockResponse(400, { error: 'Bad request' });
592
+
593
+ ToolLogger.logResponse(req, response, 75);
594
+
595
+ expectJsonLog({
596
+ event: 'opal_tool_response',
597
+ path: '/test-tool',
598
+ duration: '75ms',
599
+ status: 400,
600
+ contentType: 'application/json',
601
+ contentLength: 23,
602
+ success: false,
603
+ responseBody: { error: 'Bad request' }
604
+ });
605
+ });
606
+
607
+ it('should handle response without body data', () => {
608
+ const req = createMockRequest();
609
+ const response = createMockResponseWithBody(204, undefined, 'application/json');
610
+
611
+ ToolLogger.logResponse(req, response);
612
+
613
+ expectJsonLog({
614
+ event: 'opal_tool_response',
615
+ path: '/test-tool',
616
+ status: 204,
617
+ contentType: 'application/json',
618
+ contentLength: 'unknown',
619
+ success: true
620
+ });
621
+ });
622
+
623
+ it('should handle response without processing time', () => {
624
+ const req = createMockRequest();
625
+ const response = createMockResponse(200, { data: 'test' });
626
+
627
+ ToolLogger.logResponse(req, response);
628
+
629
+ expectJsonLog({
630
+ event: 'opal_tool_response',
631
+ path: '/test-tool',
632
+ status: 200,
633
+ contentType: 'application/json',
634
+ contentLength: 15,
635
+ success: true,
636
+ responseBody: { data: 'test' }
637
+ });
638
+ });
639
+
640
+ it('should handle unknown content type - response body not logged', () => {
641
+ const req = createMockRequest();
642
+ const response = createMockResponse(200, { data: 'test' });
643
+ response.headers.get = jest.fn().mockReturnValue(null);
644
+
645
+ ToolLogger.logResponse(req, response);
646
+
647
+ expectJsonLog({
648
+ event: 'opal_tool_response',
649
+ path: '/test-tool',
650
+ status: 200,
651
+ contentType: 'unknown',
652
+ contentLength: 15,
653
+ success: true
654
+ });
655
+ });
656
+
657
+ it('should handle content length calculation error', () => {
658
+ const req = createMockRequest();
659
+
660
+ // Simulate a response that will cause errors when trying to calculate content length
661
+ // by providing a Uint8Array but the underlying data causes issues
662
+ const mockHeaders = {
663
+ get: jest.fn().mockReturnValue('application/json')
664
+ };
665
+
666
+ const response = {
667
+ status: 200,
668
+ headers: mockHeaders
669
+ } as any;
670
+
671
+ // Create a getter that throws when accessed (simulating serialization error)
672
+ Object.defineProperty(response, 'bodyAsU8Array', {
673
+ get() {
674
+ throw new Error('Circular structure');
675
+ },
676
+ enumerable: true
677
+ });
678
+
679
+ ToolLogger.logResponse(req, response);
680
+
681
+ // The error causes both contentLength and responseBody to fail gracefully
682
+ const logCall = mockLogger.info.mock.calls[0];
683
+ const loggedData = JSON.parse(logCall[1]);
684
+
685
+ expect(loggedData.event).toBe('opal_tool_response');
686
+ expect(loggedData.contentLength).toBe('unknown');
687
+ expect(loggedData.responseBody).toBeUndefined();
688
+ });
689
+
690
+ it('should correctly identify success status codes', () => {
691
+ const req = createMockRequest();
692
+
693
+ const testCases = [
694
+ { status: 200, expected: true },
695
+ { status: 201, expected: true },
696
+ { status: 204, expected: true },
697
+ { status: 299, expected: true },
698
+ { status: 300, expected: false },
699
+ { status: 400, expected: false },
700
+ { status: 404, expected: false },
701
+ { status: 500, expected: false }
702
+ ];
703
+
704
+ testCases.forEach(({ status, expected }) => {
705
+ mockLogger.info.mockClear();
706
+ const response = createMockResponse(status);
707
+ ToolLogger.logResponse(req, response);
708
+
709
+ const logCall = mockLogger.info.mock.calls[0];
710
+ const loggedData = JSON.parse(logCall[1]);
711
+
712
+ expect(loggedData.event).toBe('opal_tool_response');
713
+ expect(loggedData.path).toBe('/test-tool');
714
+ expect(loggedData.status).toBe(status);
715
+ expect(loggedData.contentType).toBe('application/json');
716
+ expect(loggedData.contentLength).toBe(2);
717
+ expect(loggedData.success).toBe(expected);
718
+ expect(loggedData.responseBody).toEqual({});
719
+ });
720
+ });
721
+
722
+ it('should handle different content types', () => {
723
+ const req = createMockRequest();
724
+
725
+ const testCases = [
726
+ { contentType: 'application/json', expectedBody: { data: 'test' } },
727
+ { contentType: 'text/plain', expectedBody: '{"data":"test"}' },
728
+ { contentType: 'text/html', expectedBody: '{"data":"test"}' }
729
+ ];
730
+
731
+ testCases.forEach(({ contentType, expectedBody }) => {
732
+ mockLogger.info.mockClear();
733
+ const response = createMockResponse(200, { data: 'test' });
734
+ response.headers.get = jest.fn().mockReturnValue(contentType);
735
+
736
+ ToolLogger.logResponse(req, response);
737
+
738
+ const logCall = mockLogger.info.mock.calls[0];
739
+ const loggedData = JSON.parse(logCall[1]);
740
+
741
+ expect(loggedData.event).toBe('opal_tool_response');
742
+ expect(loggedData.path).toBe('/test-tool');
743
+ expect(loggedData.status).toBe(200);
744
+ expect(loggedData.contentType).toBe(contentType);
745
+ expect(loggedData.contentLength).toBe(15);
746
+ expect(loggedData.success).toBe(true);
747
+ expect(loggedData.responseBody).toEqual(expectedBody);
748
+ });
749
+ });
750
+
751
+ it('should log short successful response body', () => {
752
+ const req = createMockRequest();
753
+ const response = createMockResponse(200, { result: 'success', data: 'test' });
754
+
755
+ ToolLogger.logResponse(req, response);
756
+
757
+ const logCall = mockLogger.info.mock.calls[0];
758
+ const loggedData = JSON.parse(logCall[1]);
759
+
760
+ expect(loggedData.responseBody).toEqual({ result: 'success', data: 'test' });
761
+ expect(loggedData.success).toBe(true);
762
+ });
763
+
764
+ it('should truncate long successful response body to 256 chars', () => {
765
+ const req = createMockRequest();
766
+ const longData = 'a'.repeat(300);
767
+ const response = createMockResponse(200, { message: longData });
768
+
769
+ ToolLogger.logResponse(req, response);
770
+
771
+ const logCall = mockLogger.info.mock.calls[0];
772
+ const loggedData = JSON.parse(logCall[1]);
773
+
774
+ // The response body should be truncated when stringified
775
+ expect(loggedData.responseBody.message).toContain(' truncated]...');
776
+ });
777
+
778
+ it('truncates long properties of failed responses', () => {
779
+ const req = createMockRequest();
780
+ const longData = 'a'.repeat(150);
781
+ const response = createMockResponse(400, { error: 'Bad request', details: longData });
782
+
783
+ ToolLogger.logResponse(req, response);
784
+
785
+ const logCall = mockLogger.info.mock.calls[0];
786
+ const loggedData = JSON.parse(logCall[1]);
787
+
788
+ // Failed responses should include full body, not truncated
789
+ expect(loggedData.responseBody.error).toEqual('Bad request');
790
+ expect(loggedData.responseBody.details).toContain(' truncated]...');
791
+ expect(loggedData.success).toBe(false);
792
+ });
793
+
794
+ it('should redact sensitive data in response body', () => {
795
+ const req = createMockRequest();
796
+ const response = createMockResponse(200, {
797
+ user: 'john',
798
+ password: 'secret123',
799
+ api_key: 'key456',
800
+ data: 'public'
801
+ });
802
+
803
+ ToolLogger.logResponse(req, response);
804
+
805
+ const logCall = mockLogger.info.mock.calls[0];
806
+ const loggedData = JSON.parse(logCall[1]);
807
+
808
+ expect(loggedData.responseBody).toEqual({
809
+ user: 'john',
810
+ password: '[REDACTED]',
811
+ api_key: '[REDACTED]',
812
+ data: 'public'
813
+ });
814
+ });
815
+
816
+ it('should handle response with no body', () => {
817
+ const req = createMockRequest();
818
+ const response = createMockResponseWithBody(204, undefined, 'application/json');
819
+
820
+ ToolLogger.logResponse(req, response);
821
+
822
+ const logCall = mockLogger.info.mock.calls[0];
823
+ const loggedData = JSON.parse(logCall[1]);
824
+
825
+ expect(loggedData.responseBody).toBeUndefined();
826
+ expect(loggedData.success).toBe(true);
827
+ });
828
+
829
+ it('should handle plain text response body', () => {
830
+ const req = createMockRequest();
831
+ const plainText = 'This is a plain text response';
832
+ const response = createMockResponseWithBody(200, new Uint8Array(Buffer.from(plainText)), 'text/plain');
833
+
834
+ ToolLogger.logResponse(req, response);
835
+
836
+ const logCall = mockLogger.info.mock.calls[0];
837
+ const loggedData = JSON.parse(logCall[1]);
838
+
839
+ expect(loggedData.responseBody).toBe(plainText);
840
+ });
841
+
842
+ it('should truncate long plain text successful responses', () => {
843
+ const req = createMockRequest();
844
+ const longText = 'a'.repeat(300);
845
+ const response = createMockResponseWithBody(200, new Uint8Array(Buffer.from(longText)), 'text/plain');
846
+
847
+ ToolLogger.logResponse(req, response);
848
+
849
+ const logCall = mockLogger.info.mock.calls[0];
850
+ const loggedData = JSON.parse(logCall[1]);
851
+
852
+ expect(loggedData.responseBody).toBe(`${'a'.repeat(256)}... (truncated)`);
853
+ });
854
+
855
+ it('should not truncate long plain text failed responses', () => {
856
+ const req = createMockRequest();
857
+ const longText = 'a'.repeat(150);
858
+ const response = createMockResponseWithBody(500, new Uint8Array(Buffer.from(longText)), 'text/plain');
859
+
860
+ ToolLogger.logResponse(req, response);
861
+
862
+ const logCall = mockLogger.info.mock.calls[0];
863
+ const loggedData = JSON.parse(logCall[1]);
864
+
865
+ expect(loggedData.responseBody).toBe(longText);
866
+ expect(loggedData.success).toBe(false);
867
+ });
868
+ });
869
+
870
+ describe('edge cases', () => {
871
+ it('should handle empty request bodyJSON', () => {
872
+ const req = createMockRequest({
873
+ bodyJSON: {}
874
+ });
875
+
876
+ ToolLogger.logRequest(req);
877
+
878
+ expectJsonLog({
879
+ event: 'opal_tool_request',
880
+ path: '/test-tool',
881
+ method: 'POST',
882
+ parameters: {}
883
+ });
884
+ });
885
+
886
+ it('should handle request with only parameters field', () => {
887
+ const req = createMockRequest({
888
+ bodyJSON: {
889
+ parameters: {
890
+ field: 'value' // Changed from 'key' to 'field' to avoid sensitive field detection
891
+ }
892
+ }
893
+ });
894
+
895
+ ToolLogger.logRequest(req);
896
+
897
+ expectJsonLog({
898
+ event: 'opal_tool_request',
899
+ path: '/test-tool',
900
+ method: 'POST',
901
+ parameters: {
902
+ field: 'value'
903
+ }
904
+ });
905
+ });
906
+
907
+ it('should handle mixed data types in parameters', () => {
908
+ const req = createMockRequest({
909
+ bodyJSON: {
910
+ parameters: {
911
+ string: 'text',
912
+ number: 42,
913
+ boolean: true,
914
+ array: [1, 2],
915
+ object: { nested: 'value' },
916
+ nullValue: null,
917
+ password: 'secret'
918
+ }
919
+ }
920
+ });
921
+
922
+ ToolLogger.logRequest(req);
923
+
924
+ expectJsonLog({
925
+ event: 'opal_tool_request',
926
+ path: '/test-tool',
927
+ method: 'POST',
928
+ parameters: {
929
+ string: 'text',
930
+ number: 42,
931
+ boolean: true,
932
+ array: [1, 2],
933
+ object: { nested: 'value' },
934
+ nullValue: null,
935
+ password: '[REDACTED]'
936
+ }
937
+ });
938
+ });
939
+
940
+ it('should handle tool override request with enhanced parameter descriptions', () => {
941
+ const overrideRequest = {
942
+ tools: [
943
+ {
944
+ name: 'calculate_experiment_runtime',
945
+ description: 'OVERRIDDEN: Enhanced experiment runtime calculator with advanced features',
946
+ parameters: [
947
+ {
948
+ name: 'BCR',
949
+ type: 'number',
950
+ description: 'OVERRIDDEN: Enhanced baseline conversion rate with validation',
951
+ required: true
952
+ },
953
+ {
954
+ name: 'MDE',
955
+ type: 'number',
956
+ description: 'OVERRIDDEN: Enhanced minimum detectable effect calculation',
957
+ required: true
958
+ },
959
+ {
960
+ name: 'sigLevel',
961
+ type: 'number',
962
+ description: 'OVERRIDDEN: Enhanced statistical significance level',
963
+ required: true
964
+ },
965
+ {
966
+ name: 'numVariations',
967
+ type: 'number',
968
+ description: 'OVERRIDDEN: Enhanced number of variations handling',
969
+ required: true
970
+ },
971
+ {
972
+ name: 'dailyVisitors',
973
+ type: 'number',
974
+ description: 'OVERRIDDEN: Enhanced daily visitor count with forecasting',
975
+ required: true
976
+ }
977
+ ]
978
+ }
979
+ // Note: NOT including calculate_sample_size in override
980
+ ]
981
+ };
982
+
983
+ const req = createMockRequest({
984
+ path: '/overrides',
985
+ bodyJSON: overrideRequest
986
+ });
987
+
988
+ ToolLogger.logRequest(req);
989
+
990
+ expectJsonLog({
991
+ event: 'opal_tool_request',
992
+ path: '/overrides',
993
+ method: 'POST',
994
+ parameters: {
995
+ tools: [
996
+ {
997
+ name: 'calculate_experiment_runtime',
998
+ description: 'OVERRIDDEN: Enhanced experiment runtime calculator with advanced features',
999
+ parameters: [
1000
+ {
1001
+ name: 'BCR',
1002
+ type: 'number',
1003
+ description: 'OVERRIDDEN: Enhanced baseline conversion rate with validation',
1004
+ required: true
1005
+ },
1006
+ {
1007
+ name: 'MDE',
1008
+ type: 'number',
1009
+ description: 'OVERRIDDEN: Enhanced minimum detectable effect calculation',
1010
+ required: true
1011
+ },
1012
+ '... (3 more items truncated)'
1013
+ ]
1014
+ }
1015
+ ]
1016
+ }
1017
+ });
1018
+ });
1019
+ });
1020
+ });