1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
|
- import fs from 'fs';
- import path from 'path';
- import { ProxyAgent, setGlobalDispatcher } from 'undici';
- import cliState from '../src/cliState';
- import { VERSION } from '../src/constants';
- import { getEnvBool, getEnvString } from '../src/envars';
- import {
- fetchWithProxy,
- fetchWithRetries,
- fetchWithTimeout,
- handleRateLimit,
- isRateLimited,
- sanitizeUrl,
- } from '../src/fetch';
- import logger from '../src/logger';
- import { REQUEST_TIMEOUT_MS } from '../src/providers/shared';
- import { sleep } from '../src/util/time';
- import { createMockResponse } from './util/utils';
- jest.mock('../src/util/time', () => ({
- sleep: jest.fn().mockResolvedValue(undefined),
- }));
- jest.mock('undici', () => {
- const mockProxyAgentConstructor = jest.fn();
- const mockProxyAgentInstance = {
- options: null,
- addRequest: jest.fn(),
- destroy: jest.fn(),
- };
- mockProxyAgentConstructor.mockImplementation((options) => {
- mockProxyAgentInstance.options = options;
- return mockProxyAgentInstance;
- });
- const mockAgentConstructor = jest.fn();
- const mockAgentInstance = {
- addRequest: jest.fn(),
- destroy: jest.fn(),
- };
- mockAgentConstructor.mockImplementation(() => {
- return mockAgentInstance;
- });
- return {
- ProxyAgent: mockProxyAgentConstructor,
- Agent: mockAgentConstructor,
- setGlobalDispatcher: jest.fn(),
- };
- });
- jest.mock('../src/envars', () => {
- return {
- getEnvString: jest.fn().mockImplementation((key: string, defaultValue: string = '') => {
- if (key === 'HTTPS_PROXY' && process.env.HTTPS_PROXY) {
- return process.env.HTTPS_PROXY;
- }
- if (key === 'https_proxy' && process.env.https_proxy) {
- return process.env.https_proxy;
- }
- if (key === 'HTTP_PROXY' && process.env.HTTP_PROXY) {
- return process.env.HTTP_PROXY;
- }
- if (key === 'http_proxy' && process.env.http_proxy) {
- return process.env.http_proxy;
- }
- if (key === 'NO_PROXY' && process.env.NO_PROXY) {
- return process.env.NO_PROXY;
- }
- if (key === 'no_proxy' && process.env.no_proxy) {
- return process.env.no_proxy;
- }
- if (key === 'PROMPTFOO_CA_CERT_PATH' && process.env.PROMPTFOO_CA_CERT_PATH) {
- return process.env.PROMPTFOO_CA_CERT_PATH;
- }
- if (key === 'PROMPTFOO_INSECURE_SSL') {
- return process.env.PROMPTFOO_INSECURE_SSL || defaultValue;
- }
- return defaultValue;
- }),
- getEnvBool: jest.fn().mockImplementation((key: string, defaultValue: boolean = false) => {
- if (key === 'PROMPTFOO_RETRY_5XX_ENABLED') {
- return process.env.PROMPTFOO_RETRY_5XX_ENABLED === 'true' || false;
- }
- if (key === 'PROMPTFOO_INSECURE_SSL') {
- return process.env.PROMPTFOO_INSECURE_SSL === 'true' || false;
- }
- if (key === 'PROMPTFOO_RETRY_5XX') {
- return process.env.PROMPTFOO_RETRY_5XX === 'true' || false;
- }
- return defaultValue;
- }),
- getEnvInt: jest.fn().mockImplementation((key: string, defaultValue: number = 0) => {
- if (key === 'REQUEST_TIMEOUT_MS') {
- return Number.parseInt(process.env.REQUEST_TIMEOUT_MS || '300000', 10);
- }
- return defaultValue;
- }),
- };
- });
- jest.mock('fs', () => ({
- readFileSync: jest.fn(),
- }));
- jest.mock('../src/cliState', () => ({
- default: {
- basePath: undefined,
- },
- }));
- describe('fetchWithProxy', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- jest.spyOn(global, 'fetch').mockImplementation();
- jest.mocked(ProxyAgent).mockClear();
- jest.mocked(setGlobalDispatcher).mockClear();
- delete process.env.HTTPS_PROXY;
- delete process.env.https_proxy;
- delete process.env.HTTP_PROXY;
- delete process.env.http_proxy;
- delete process.env.npm_config_https_proxy;
- delete process.env.npm_config_http_proxy;
- delete process.env.npm_config_proxy;
- delete process.env.all_proxy;
- });
- afterEach(() => {
- jest.resetAllMocks();
- });
- it('should add version header to all requests', async () => {
- const url = 'https://example.com/api';
- await fetchWithProxy(url);
- expect(global.fetch).toHaveBeenCalledWith(
- url,
- expect.objectContaining({
- headers: expect.objectContaining({
- 'x-promptfoo-version': VERSION,
- }),
- }),
- );
- });
- it('should handle URLs with basic auth credentials', async () => {
- const url = 'https://username:password@example.com/api';
- const options = { headers: { 'Content-Type': 'application/json' } };
- await fetchWithProxy(url, options);
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://example.com/api',
- expect.objectContaining({
- headers: {
- 'Content-Type': 'application/json',
- Authorization: expect.any(String),
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should handle URLs without auth credentials', async () => {
- const url = 'https://example.com/api';
- const options = { headers: { 'Content-Type': 'application/json' } };
- await fetchWithProxy(url, options);
- expect(global.fetch).toHaveBeenCalledWith(
- url,
- expect.objectContaining({
- headers: {
- 'Content-Type': 'application/json',
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should handle invalid URLs gracefully', async () => {
- const invalidUrl = 'not-a-url';
- await fetchWithProxy(invalidUrl);
- expect(logger.debug).toHaveBeenCalledWith(
- expect.stringMatching(/URL parsing failed in fetchWithProxy: TypeError/),
- );
- expect(global.fetch).toHaveBeenCalledWith(invalidUrl, expect.any(Object));
- });
- it('should preserve existing Authorization headers when no URL credentials', async () => {
- const url = 'https://example.com/api';
- const options = {
- headers: {
- Authorization: 'Bearer token123',
- 'Content-Type': 'application/json',
- },
- };
- await fetchWithProxy(url, options);
- expect(global.fetch).toHaveBeenCalledWith(
- url,
- expect.objectContaining({
- headers: {
- Authorization: 'Bearer token123',
- 'Content-Type': 'application/json',
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should warn and prefer existing Authorization header over URL credentials', async () => {
- const url = 'https://username:password@example.com/api';
- const options = {
- headers: {
- Authorization: 'Bearer token123',
- },
- };
- await fetchWithProxy(url, options);
- expect(logger.warn).toHaveBeenCalledWith(
- expect.stringContaining('Both URL credentials and Authorization header present'),
- );
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://example.com/api',
- expect.objectContaining({
- headers: {
- Authorization: 'Bearer token123',
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should handle empty username or password in URL', async () => {
- const url = 'https://:password@example.com/api';
- await fetchWithProxy(url);
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://example.com/api',
- expect.objectContaining({
- headers: {
- Authorization: 'Basic OnBhc3N3b3Jk',
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should handle URLs with only username', async () => {
- const url = 'https://username@example.com/api';
- await fetchWithProxy(url);
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://example.com/api',
- expect.objectContaining({
- headers: {
- Authorization: 'Basic dXNlcm5hbWU6',
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should preserve existing headers when adding Authorization from URL credentials', async () => {
- const url = 'https://username:password@example.com/api';
- const options = {
- headers: {
- 'Content-Type': 'application/json',
- 'X-Custom-Header': 'value',
- },
- };
- await fetchWithProxy(url, options);
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://example.com/api',
- expect.objectContaining({
- headers: {
- 'Content-Type': 'application/json',
- 'X-Custom-Header': 'value',
- Authorization: expect.any(String),
- 'x-promptfoo-version': VERSION,
- },
- }),
- );
- });
- it('should use custom CA certificate when PROMPTFOO_CA_CERT_PATH is set', async () => {
- const mockCertPath = path.normalize('/path/to/cert.pem');
- const mockCertContent = 'mock-cert-content';
- const mockProxyUrl = 'http://proxy.example.com';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.PROMPTFOO_CA_CERT_PATH = mockCertPath;
- jest.mocked(getEnvString).mockImplementation((key: string, defaultValue: string = '') => {
- if (key === 'PROMPTFOO_CA_CERT_PATH') {
- return mockCertPath;
- }
- if (key === 'HTTPS_PROXY') {
- return mockProxyUrl;
- }
- return defaultValue;
- });
- jest.mocked(getEnvBool).mockImplementation((key: string, defaultValue: boolean = false) => {
- if (key === 'PROMPTFOO_INSECURE_SSL') {
- return false;
- }
- return defaultValue;
- });
- jest.mocked(fs.readFileSync).mockReturnValue(mockCertContent);
- const mockFetch = jest.fn().mockResolvedValue(new Response());
- global.fetch = mockFetch;
- await fetchWithProxy('https://example.com');
- const actualPath = jest.mocked(fs.readFileSync).mock.calls[0][0] as string;
- const actualEncoding = jest.mocked(fs.readFileSync).mock.calls[0][1];
- const normalizedActual = path.normalize(actualPath).replace(/^\w:/, '');
- const normalizedExpected = path.normalize(mockCertPath).replace(/^\w:/, '');
- expect(normalizedActual).toBe(normalizedExpected);
- expect(actualEncoding).toBe('utf8');
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: mockProxyUrl,
- proxyTls: {
- ca: mockCertContent,
- rejectUnauthorized: true,
- },
- requestTls: {
- ca: mockCertContent,
- rejectUnauthorized: true,
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- it('should handle missing CA certificate file gracefully', async () => {
- const mockCertPath = path.normalize('/path/to/nonexistent.pem');
- const mockProxyUrl = 'http://proxy.example.com';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.PROMPTFOO_CA_CERT_PATH = mockCertPath;
- jest.mocked(getEnvString).mockImplementation((key: string, defaultValue: string = '') => {
- if (key === 'PROMPTFOO_CA_CERT_PATH') {
- return mockCertPath;
- }
- if (key === 'HTTPS_PROXY') {
- return mockProxyUrl;
- }
- return defaultValue;
- });
- jest.mocked(fs.readFileSync).mockImplementation(() => {
- throw new Error('File not found');
- });
- const mockFetch = jest.fn().mockResolvedValue(new Response());
- global.fetch = mockFetch;
- await fetchWithProxy('https://example.com');
- const actualPath = jest.mocked(fs.readFileSync).mock.calls[0][0] as string;
- const normalizedActual = path.normalize(actualPath).replace(/^\w:/, '');
- const normalizedExpected = path.normalize(mockCertPath).replace(/^\w:/, '');
- expect(normalizedActual).toBe(normalizedExpected);
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: mockProxyUrl,
- proxyTls: {
- rejectUnauthorized: true,
- },
- requestTls: {
- rejectUnauthorized: true,
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- it('should disable SSL verification when PROMPTFOO_INSECURE_SSL is true', async () => {
- const mockProxyUrl = 'http://proxy.example.com';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.PROMPTFOO_INSECURE_SSL = 'true';
- jest.mocked(getEnvString).mockImplementation((key: string, defaultValue: string = '') => {
- if (key === 'HTTPS_PROXY') {
- return mockProxyUrl;
- }
- return defaultValue;
- });
- jest.mocked(getEnvBool).mockImplementation((key: string, defaultValue: boolean = false) => {
- if (key === 'PROMPTFOO_INSECURE_SSL') {
- return true;
- }
- return defaultValue;
- });
- const mockFetch = jest.fn().mockResolvedValue(new Response());
- global.fetch = mockFetch;
- await fetchWithProxy('https://example.com');
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: mockProxyUrl,
- proxyTls: {
- rejectUnauthorized: false,
- },
- requestTls: {
- rejectUnauthorized: false,
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- it('should resolve CA certificate path relative to basePath when available', async () => {
- const mockBasePath = path.normalize('/base/path');
- const mockCertPath = 'certs/cert.pem';
- const mockCertContent = 'mock-cert-content';
- const mockProxyUrl = 'http://proxy.example.com';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.PROMPTFOO_CA_CERT_PATH = mockCertPath;
- cliState.basePath = mockBasePath;
- jest.mocked(getEnvString).mockImplementation((key: string, defaultValue: string = '') => {
- if (key === 'PROMPTFOO_CA_CERT_PATH') {
- return mockCertPath;
- }
- if (key === 'HTTPS_PROXY') {
- return mockProxyUrl;
- }
- return defaultValue;
- });
- jest.mocked(getEnvBool).mockImplementation((key: string, defaultValue: boolean = false) => {
- if (key === 'PROMPTFOO_INSECURE_SSL') {
- return false;
- }
- return defaultValue;
- });
- jest.mocked(fs.readFileSync).mockReturnValue(mockCertContent);
- const mockFetch = jest.fn().mockResolvedValue(new Response());
- global.fetch = mockFetch;
- await fetchWithProxy('https://example.com');
- const expectedPath = path.normalize(path.join(mockBasePath, mockCertPath));
- const actualPath = jest.mocked(fs.readFileSync).mock.calls[0][0] as string;
- const actualEncoding = jest.mocked(fs.readFileSync).mock.calls[0][1];
- const normalizedActual = path.normalize(actualPath).replace(/^\w:/, '');
- const normalizedExpected = path.normalize(expectedPath).replace(/^\w:/, '');
- const normalizedBasePath = path.normalize(mockBasePath).replace(/^\w:/, '');
- const normalizedCertPath = path.normalize(mockCertPath);
- expect(normalizedActual).toBe(normalizedExpected);
- expect(actualEncoding).toBe('utf8');
- expect(normalizedActual).toContain(normalizedBasePath);
- expect(normalizedActual).toContain(normalizedCertPath);
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: mockProxyUrl,
- proxyTls: {
- ca: mockCertContent,
- rejectUnauthorized: true,
- },
- requestTls: {
- ca: mockCertContent,
- rejectUnauthorized: true,
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- cliState.basePath = undefined;
- });
- it('should not create ProxyAgent when no proxy URL is found', async () => {
- await fetchWithProxy('https://example.com');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should use proxy URL from environment variables in order of precedence', async () => {
- const mockProxyUrls = {
- HTTPS_PROXY: 'http://https-proxy.example.com',
- https_proxy: 'http://https-proxy-lower.example.com',
- HTTP_PROXY: 'http://http-proxy.example.com',
- http_proxy: 'http://http-proxy-lower.example.com',
- } as const;
- const allProxyVars = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'];
- const httpTestCases = [
- {
- env: { HTTP_PROXY: mockProxyUrls.HTTP_PROXY },
- expected: { url: mockProxyUrls.HTTP_PROXY },
- },
- {
- env: { http_proxy: mockProxyUrls.http_proxy },
- expected: { url: mockProxyUrls.http_proxy },
- },
- ];
- const httpsTestCases = [
- {
- env: { HTTPS_PROXY: mockProxyUrls.HTTPS_PROXY },
- expected: { url: mockProxyUrls.HTTPS_PROXY },
- },
- {
- env: { https_proxy: mockProxyUrls.https_proxy },
- expected: { url: mockProxyUrls.https_proxy },
- },
- ];
- for (const testCase of httpTestCases) {
- jest.clearAllMocks();
- allProxyVars.forEach((key) => {
- delete process.env[key];
- });
- Object.entries(testCase.env).forEach(([key, value]) => {
- process.env[key] = value;
- });
- await fetchWithProxy('http://example.com');
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: testCase.expected.url,
- proxyTls: {
- rejectUnauthorized: !getEnvBool('PROMPTFOO_INSECURE_SSL', true),
- },
- requestTls: {
- rejectUnauthorized: !getEnvBool('PROMPTFOO_INSECURE_SSL', true),
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- const debugCalls = jest.mocked(logger.debug).mock.calls;
- const normalizedCalls = debugCalls.map((call) => call[0].replace(/\/$/, ''));
- const proxyConfigCalls = normalizedCalls.filter((msg) => msg.includes(`Using proxy:`));
- expect(proxyConfigCalls).toEqual([`Using proxy: ${testCase.expected.url}`]);
- allProxyVars.forEach((key) => {
- delete process.env[key];
- });
- }
- for (const testCase of httpsTestCases) {
- jest.clearAllMocks();
- allProxyVars.forEach((key) => {
- delete process.env[key];
- });
- Object.entries(testCase.env).forEach(([key, value]) => {
- process.env[key] = value;
- });
- await fetchWithProxy('https://example.com');
- expect(ProxyAgent).toHaveBeenCalledWith({
- uri: testCase.expected.url,
- proxyTls: {
- rejectUnauthorized: !getEnvBool('PROMPTFOO_INSECURE_SSL', true),
- },
- requestTls: {
- rejectUnauthorized: !getEnvBool('PROMPTFOO_INSECURE_SSL', true),
- },
- headersTimeout: REQUEST_TIMEOUT_MS,
- });
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- const debugCalls = jest.mocked(logger.debug).mock.calls;
- const normalizedCalls = debugCalls.map((call) => call[0].replace(/\/$/, ''));
- const proxyConfigCalls = normalizedCalls.filter((msg) => msg.includes(`Using proxy:`));
- expect(proxyConfigCalls).toEqual([`Using proxy: ${testCase.expected.url}`]);
- allProxyVars.forEach((key) => {
- delete process.env[key];
- });
- }
- });
- it('should use proxy for domains not in NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,internal.example.com';
- await fetchWithProxy('https://api.example.com/v1');
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- });
- describe('fetchWithTimeout', () => {
- beforeEach(() => {
- jest.useFakeTimers();
- jest.spyOn(global, 'fetch').mockImplementation();
- });
- afterEach(() => {
- jest.useRealTimers();
- });
- it('should resolve when fetch completes before timeout', async () => {
- const mockResponse = createMockResponse({ ok: true });
- jest.mocked(global.fetch).mockImplementationOnce(() => Promise.resolve(mockResponse));
- const fetchPromise = fetchWithTimeout('https://example.com', {}, 5000);
- await expect(fetchPromise).resolves.toBe(mockResponse);
- });
- it('should reject when request times out', async () => {
- jest
- .mocked(global.fetch)
- .mockImplementationOnce(() => new Promise((resolve) => setTimeout(resolve, 6000)));
- const fetchPromise = fetchWithTimeout('https://example.com', {}, 5000);
- jest.advanceTimersByTime(5000);
- await expect(fetchPromise).rejects.toThrow('Request timed out after 5000 ms');
- });
- });
- describe('isRateLimited', () => {
- it('should detect standard rate limit headers', () => {
- const response = createMockResponse({
- headers: new Headers({
- 'X-RateLimit-Remaining': '0',
- }),
- status: 200,
- });
- expect(isRateLimited(response)).toBe(true);
- });
- it('should detect 429 status code', () => {
- const response = createMockResponse({
- status: 429,
- });
- expect(isRateLimited(response)).toBe(true);
- });
- it('should detect OpenAI specific rate limits', () => {
- const response = createMockResponse({
- headers: new Headers({
- 'x-ratelimit-remaining-requests': '0',
- }),
- });
- expect(isRateLimited(response)).toBe(true);
- const tokenResponse = createMockResponse({
- headers: new Headers({
- 'x-ratelimit-remaining-tokens': '0',
- }),
- });
- expect(isRateLimited(tokenResponse)).toBe(true);
- });
- it('should return false when not rate limited', () => {
- const response = createMockResponse({
- headers: new Headers({
- 'X-RateLimit-Remaining': '10',
- }),
- status: 200,
- });
- expect(isRateLimited(response)).toBe(false);
- });
- });
- describe('handleRateLimit', () => {
- beforeEach(() => {
- jest.useFakeTimers();
- jest.mocked(sleep).mockClear();
- });
- afterEach(() => {
- jest.useRealTimers();
- });
- it('should handle OpenAI reset headers', async () => {
- const response = createMockResponse({
- headers: new Headers({
- 'x-ratelimit-reset-requests': '5',
- }),
- });
- const promise = handleRateLimit(response);
- jest.advanceTimersByTime(5000);
- await promise;
- expect(logger.debug).toHaveBeenCalledWith('Rate limited, waiting 5000ms before retry');
- });
- it('should handle standard rate limit reset headers', async () => {
- const futureTime = Math.floor((Date.now() + 5000) / 1000);
- const response = createMockResponse({
- headers: new Headers({
- 'X-RateLimit-Reset': futureTime.toString(),
- }),
- });
- const promise = handleRateLimit(response);
- await promise;
- expect(logger.debug).toHaveBeenCalledWith(
- expect.stringMatching(/Rate limited, waiting \d+ms before retry/),
- );
- });
- it('should handle Retry-After headers', async () => {
- const response = createMockResponse({
- headers: new Headers({
- 'Retry-After': '5',
- }),
- });
- const promise = handleRateLimit(response);
- jest.advanceTimersByTime(5000);
- await promise;
- expect(logger.debug).toHaveBeenCalledWith('Rate limited, waiting 5000ms before retry');
- });
- it('should use default wait time when no headers present', async () => {
- const response = createMockResponse();
- const promise = handleRateLimit(response);
- jest.advanceTimersByTime(60000);
- await promise;
- expect(logger.debug).toHaveBeenCalledWith('Rate limited, waiting 60000ms before retry');
- });
- });
- describe('fetchWithRetries', () => {
- beforeEach(() => {
- jest.mocked(sleep).mockClear();
- jest.spyOn(global, 'fetch').mockImplementation();
- jest.clearAllMocks();
- });
- it('should make exactly one attempt when retries is 0', async () => {
- const successResponse = createMockResponse();
- jest.mocked(global.fetch).mockResolvedValueOnce(successResponse);
- await fetchWithRetries('https://example.com', {}, 1000, 0);
- expect(global.fetch).toHaveBeenCalledTimes(1);
- expect(sleep).not.toHaveBeenCalled();
- });
- it('should handle negative retry values by treating them as 0', async () => {
- const successResponse = createMockResponse();
- jest.mocked(global.fetch).mockResolvedValueOnce(successResponse);
- await fetchWithRetries('https://example.com', {}, 1000, -1);
- expect(global.fetch).toHaveBeenCalledTimes(1);
- expect(sleep).not.toHaveBeenCalled();
- });
- it('should make retries+1 total attempts', async () => {
- jest.mocked(global.fetch).mockRejectedValue(new Error('Network error'));
- await expect(fetchWithRetries('https://example.com', {}, 1000, 2)).rejects.toThrow(
- 'Request failed after 2 retries: Error: Network error',
- );
- expect(global.fetch).toHaveBeenCalledTimes(3);
- expect(sleep).toHaveBeenCalledTimes(2);
- });
- it('should not sleep after the final attempt', async () => {
- jest.mocked(global.fetch).mockRejectedValue(new Error('Network error'));
- await expect(fetchWithRetries('https://example.com', {}, 1000, 1)).rejects.toThrow(
- 'Request failed after 1 retries: Error: Network error',
- );
- expect(global.fetch).toHaveBeenCalledTimes(2);
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- it('should handle 5XX errors when PROMPTFOO_RETRY_5XX is true', async () => {
- jest.mocked(getEnvBool).mockImplementation((key: string) => {
- if (key === 'PROMPTFOO_RETRY_5XX') {
- return true;
- }
- return false;
- });
- const errorResponse = createMockResponse({
- status: 502,
- statusText: 'Bad Gateway',
- });
- const successResponse = createMockResponse();
- const mockFetch = jest
- .fn()
- .mockResolvedValueOnce(errorResponse)
- .mockResolvedValueOnce(successResponse);
- global.fetch = mockFetch;
- await fetchWithRetries('https://example.com', {}, 1000, 2);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- it('should handle rate limits with proper backoff', async () => {
- const rateLimitedResponse = createMockResponse({
- status: 429,
- headers: new Headers({
- 'Retry-After': '1',
- }),
- });
- const successResponse = createMockResponse();
- const mockFetch = jest
- .fn()
- .mockResolvedValueOnce(rateLimitedResponse)
- .mockResolvedValueOnce(successResponse);
- global.fetch = mockFetch;
- await fetchWithRetries('https://example.com', {}, 1000, 2);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('Rate limited on URL'));
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- it('should respect maximum retry count', async () => {
- const mockFetch = jest.fn().mockRejectedValue(new Error('Network error'));
- global.fetch = mockFetch;
- await expect(fetchWithRetries('https://example.com', {}, 1000, 2)).rejects.toThrow(
- 'Request failed after 2 retries: Error: Network error',
- );
- expect(mockFetch).toHaveBeenCalledTimes(3);
- expect(sleep).toHaveBeenCalledTimes(2);
- });
- it('should handle detailed error information', async () => {
- const error = new Error('Network error');
- (error as any).code = 'ECONNREFUSED';
- (error as any).cause = 'Connection refused';
- jest.mocked(global.fetch).mockRejectedValue(error);
- await expect(fetchWithRetries('https://example.com', {}, 1000, 1)).rejects.toThrow(
- 'Request failed after 1 retries: Error: Network error (Cause: Connection refused) (Code: ECONNREFUSED)',
- );
- expect(global.fetch).toHaveBeenCalledTimes(2);
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- it('should handle non-Error objects in rejection', async () => {
- jest.mocked(global.fetch).mockRejectedValue('String error');
- await expect(fetchWithRetries('https://example.com', {}, 1000, 1)).rejects.toThrow(
- 'Request failed after 1 retries: String error',
- );
- expect(global.fetch).toHaveBeenCalledTimes(2);
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- it('should handle rate limits with OpenAI specific headers', async () => {
- const rateLimitedResponse = createMockResponse({
- status: 429,
- headers: new Headers({
- 'x-ratelimit-reset-tokens': '5',
- }),
- });
- const successResponse = createMockResponse();
- const mockFetch = jest
- .fn()
- .mockResolvedValueOnce(rateLimitedResponse)
- .mockResolvedValueOnce(successResponse);
- global.fetch = mockFetch;
- await fetchWithRetries('https://example.com', {}, 1000, 2);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('Rate limited on URL'));
- expect(sleep).toHaveBeenCalledTimes(1);
- });
- });
- describe('sanitizeUrl', () => {
- it('should mask credentials in URLs', () => {
- const url = 'https://username:password@example.com/api';
- expect(sanitizeUrl(url)).toBe('https://***:***@example.com/api');
- });
- it('should handle URLs without credentials', () => {
- const url = 'https://example.com/api';
- expect(sanitizeUrl(url)).toBe(url);
- });
- it('should return original string for invalid URLs', () => {
- const invalidUrl = 'not-a-url';
- expect(sanitizeUrl(invalidUrl)).toBe(invalidUrl);
- });
- });
- describe('fetchWithProxy with NO_PROXY', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- jest.spyOn(global, 'fetch').mockImplementation();
- jest.mocked(ProxyAgent).mockClear();
- jest.mocked(setGlobalDispatcher).mockClear();
- delete process.env.HTTPS_PROXY;
- delete process.env.https_proxy;
- delete process.env.HTTP_PROXY;
- delete process.env.http_proxy;
- delete process.env.npm_config_https_proxy;
- delete process.env.npm_config_http_proxy;
- delete process.env.npm_config_proxy;
- delete process.env.all_proxy;
- delete process.env.NO_PROXY;
- delete process.env.no_proxy;
- });
- afterEach(() => {
- delete process.env.HTTPS_PROXY;
- delete process.env.https_proxy;
- delete process.env.HTTP_PROXY;
- delete process.env.http_proxy;
- delete process.env.npm_config_https_proxy;
- delete process.env.npm_config_http_proxy;
- delete process.env.npm_config_proxy;
- delete process.env.all_proxy;
- delete process.env.NO_PROXY;
- delete process.env.no_proxy;
- jest.resetAllMocks();
- });
- it('should respect NO_PROXY for localhost URLs', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost';
- await fetchWithProxy('http://localhost:3000/api');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should respect NO_PROXY for 127.0.0.1', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = '127.0.0.1';
- await fetchWithProxy('http://127.0.0.1:3000/api');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should respect NO_PROXY with multiple entries', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- const noProxyList = 'example.org,localhost,internal.example.com';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = noProxyList;
- await fetchWithProxy('http://localhost:3000/api');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = noProxyList;
- await fetchWithProxy('https://example.org/api');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = noProxyList;
- await fetchWithProxy('https://internal.example.com/api');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = noProxyList;
- await fetchWithProxy('https://example.com/api');
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- it('should use proxy for domains not in NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,internal.example.com';
- await fetchWithProxy('https://api.example.com/v1');
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- expect(setGlobalDispatcher).toHaveBeenCalledWith(expect.any(Object));
- });
- it('should handle wildcard patterns in NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = '*.example.org,localhost';
- await fetchWithProxy('https://api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- await fetchWithProxy('https://subdomain.api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- await fetchWithProxy('https://example.com/v1');
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- });
- it('should handle domain suffix patterns in NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = '.example.org,localhost';
- await fetchWithProxy('https://api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- await fetchWithProxy('https://subdomain.api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- await fetchWithProxy('https://abc.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- await fetchWithProxy('https://abc.example.com/v1');
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- });
- it('should handle URLs without schemes', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,example.org';
- await fetchWithProxy('localhost:3000');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- await fetchWithProxy('example.org');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should properly parse URLs with credentials when checking against NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'api.example.org';
- await fetchWithProxy('https://username:password@api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- expect(global.fetch).toHaveBeenCalledWith(
- 'https://api.example.org/v1',
- expect.objectContaining({
- headers: expect.objectContaining({
- Authorization: expect.any(String),
- }),
- }),
- );
- });
- it('should handle bad URL inputs gracefully when checking NO_PROXY', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost';
- await fetchWithProxy(':::not-a-valid-url:::');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should use lowercase for NO_PROXY checks', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'LOCALHOST,API.EXAMPLE.ORG';
- await fetchWithProxy('http://localhost:3000');
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- await fetchWithProxy('https://api.example.org/v1');
- expect(ProxyAgent).not.toHaveBeenCalled();
- });
- it('should handle URL objects and Request objects', async () => {
- const mockProxyUrl = 'http://proxy.example.com:8080';
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,example.org';
- const urlObj = new URL('http://localhost:3000');
- await fetchWithProxy(urlObj.toString());
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTPS_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,example.org';
- const request = new Request('https://example.org/api');
- await fetchWithProxy(request);
- expect(ProxyAgent).not.toHaveBeenCalled();
- jest.clearAllMocks();
- process.env.HTTP_PROXY = mockProxyUrl;
- process.env.NO_PROXY = 'localhost,example.org';
- const otherRequest = new Request('http://example.com/api');
- await fetchWithProxy(otherRequest);
- expect(ProxyAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- uri: mockProxyUrl,
- }),
- );
- });
- });
|