-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathserver.test.js
More file actions
662 lines (545 loc) · 25.7 KB
/
Copy pathserver.test.js
File metadata and controls
662 lines (545 loc) · 25.7 KB
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
/**
* Tests for api-proxy server.js
*/
const http = require('http');
const tls = require('tls');
const { EventEmitter } = require('events');
const { normalizeApiTarget, deriveCopilotApiTarget, normalizeBasePath, buildUpstreamPath, proxyWebSocket, resolveCopilotAuthToken } = require('./server');
describe('normalizeApiTarget', () => {
it('should strip https:// prefix', () => {
expect(normalizeApiTarget('https://my-gateway.example.com')).toBe('my-gateway.example.com');
});
it('should strip http:// prefix', () => {
expect(normalizeApiTarget('http://my-gateway.example.com')).toBe('my-gateway.example.com');
});
it('should preserve bare hostname', () => {
expect(normalizeApiTarget('api.openai.com')).toBe('api.openai.com');
});
it('should normalize a URL with a path to just the hostname', () => {
expect(normalizeApiTarget('https://my-gateway.example.com/some-path')).toBe('my-gateway.example.com');
});
it('should trim whitespace', () => {
expect(normalizeApiTarget(' https://api.openai.com ')).toBe('api.openai.com');
});
it('should return undefined for falsy input', () => {
expect(normalizeApiTarget(undefined)).toBeUndefined();
expect(normalizeApiTarget('')).toBe('');
});
it('should not strip scheme-like substrings in the middle', () => {
expect(normalizeApiTarget('api.https.example.com')).toBe('api.https.example.com');
});
it('should discard port from URL', () => {
expect(normalizeApiTarget('https://my-gateway.example.com:8443')).toBe('my-gateway.example.com');
});
it('should discard query and fragment from URL', () => {
expect(normalizeApiTarget('https://my-gateway.example.com/path?key=val#frag')).toBe('my-gateway.example.com');
});
});
describe('deriveCopilotApiTarget', () => {
let originalEnv;
beforeEach(() => {
// Save original env vars
originalEnv = {
COPILOT_API_TARGET: process.env.COPILOT_API_TARGET,
GITHUB_SERVER_URL: process.env.GITHUB_SERVER_URL,
};
// Clear env vars before each test
delete process.env.COPILOT_API_TARGET;
delete process.env.GITHUB_SERVER_URL;
});
afterEach(() => {
// Restore original env vars
if (originalEnv.COPILOT_API_TARGET !== undefined) {
process.env.COPILOT_API_TARGET = originalEnv.COPILOT_API_TARGET;
} else {
delete process.env.COPILOT_API_TARGET;
}
if (originalEnv.GITHUB_SERVER_URL !== undefined) {
process.env.GITHUB_SERVER_URL = originalEnv.GITHUB_SERVER_URL;
} else {
delete process.env.GITHUB_SERVER_URL;
}
});
describe('COPILOT_API_TARGET env var (highest priority)', () => {
it('should return COPILOT_API_TARGET when explicitly set', () => {
process.env.COPILOT_API_TARGET = 'custom.api.com';
expect(deriveCopilotApiTarget()).toBe('custom.api.com');
});
it('should prefer COPILOT_API_TARGET over GITHUB_SERVER_URL', () => {
process.env.COPILOT_API_TARGET = 'custom.api.com';
process.env.GITHUB_SERVER_URL = 'https://mycompany.ghe.com';
expect(deriveCopilotApiTarget()).toBe('custom.api.com');
});
});
describe('GitHub Enterprise Cloud (*.ghe.com)', () => {
it('should derive copilot-api.<subdomain>.ghe.com for GHEC tenants', () => {
process.env.GITHUB_SERVER_URL = 'https://mycompany.ghe.com';
expect(deriveCopilotApiTarget()).toBe('copilot-api.mycompany.ghe.com');
});
it('should handle GHEC URLs with trailing slash', () => {
process.env.GITHUB_SERVER_URL = 'https://example.ghe.com/';
expect(deriveCopilotApiTarget()).toBe('copilot-api.example.ghe.com');
});
it('should handle GHEC URLs with path components', () => {
process.env.GITHUB_SERVER_URL = 'https://acme.ghe.com/some/path';
expect(deriveCopilotApiTarget()).toBe('copilot-api.acme.ghe.com');
});
it('should handle multi-part subdomain for GHEC', () => {
process.env.GITHUB_SERVER_URL = 'https://dev.mycompany.ghe.com';
expect(deriveCopilotApiTarget()).toBe('copilot-api.dev.mycompany.ghe.com');
});
});
describe('GitHub Enterprise Server (GHES)', () => {
it('should return api.enterprise.githubcopilot.com for GHES', () => {
process.env.GITHUB_SERVER_URL = 'https://github.example.com';
expect(deriveCopilotApiTarget()).toBe('api.enterprise.githubcopilot.com');
});
it('should handle GHES with IP address', () => {
process.env.GITHUB_SERVER_URL = 'https://192.168.1.100';
expect(deriveCopilotApiTarget()).toBe('api.enterprise.githubcopilot.com');
});
it('should handle GHES with custom port', () => {
process.env.GITHUB_SERVER_URL = 'https://github.internal:8443';
expect(deriveCopilotApiTarget()).toBe('api.enterprise.githubcopilot.com');
});
});
describe('GitHub.com (public)', () => {
it('should return api.githubcopilot.com for github.com', () => {
process.env.GITHUB_SERVER_URL = 'https://github.com';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
it('should handle github.com with trailing slash', () => {
process.env.GITHUB_SERVER_URL = 'https://github.com/';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
it('should handle github.com with path', () => {
process.env.GITHUB_SERVER_URL = 'https://github.com/github/hub';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
});
describe('Default behavior', () => {
it('should return api.githubcopilot.com when no env vars are set', () => {
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
it('should return default when GITHUB_SERVER_URL is empty string', () => {
process.env.GITHUB_SERVER_URL = '';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
it('should return default when GITHUB_SERVER_URL is invalid', () => {
process.env.GITHUB_SERVER_URL = 'not-a-valid-url';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
it('should return default when GITHUB_SERVER_URL is malformed', () => {
process.env.GITHUB_SERVER_URL = 'ht!tp://bad-url';
expect(deriveCopilotApiTarget()).toBe('api.githubcopilot.com');
});
});
});
describe('normalizeBasePath', () => {
it('should return empty string for undefined', () => {
expect(normalizeBasePath(undefined)).toBe('');
});
it('should return empty string for null', () => {
expect(normalizeBasePath(null)).toBe('');
});
it('should return empty string for empty string', () => {
expect(normalizeBasePath('')).toBe('');
});
it('should return empty string for whitespace-only string', () => {
expect(normalizeBasePath(' ')).toBe('');
});
it('should preserve a well-formed path', () => {
expect(normalizeBasePath('/serving-endpoints')).toBe('/serving-endpoints');
});
it('should add leading slash when missing', () => {
expect(normalizeBasePath('serving-endpoints')).toBe('/serving-endpoints');
});
it('should strip trailing slash', () => {
expect(normalizeBasePath('/serving-endpoints/')).toBe('/serving-endpoints');
});
it('should handle multi-segment paths', () => {
expect(normalizeBasePath('/openai/deployments/gpt-4')).toBe('/openai/deployments/gpt-4');
});
it('should normalize a path missing the leading slash and with trailing slash', () => {
expect(normalizeBasePath('openai/deployments/gpt-4/')).toBe('/openai/deployments/gpt-4');
});
it('should preserve a root-only path', () => {
expect(normalizeBasePath('/')).toBe('/');
});
});
describe('buildUpstreamPath', () => {
const HOST = 'api.example.com';
describe('no base path (empty string)', () => {
it('should return the request path unchanged when basePath is empty', () => {
expect(buildUpstreamPath('/v1/chat/completions', HOST, '')).toBe('/v1/chat/completions');
});
it('should preserve query string when basePath is empty', () => {
expect(buildUpstreamPath('/v1/chat/completions?stream=true', HOST, '')).toBe('/v1/chat/completions?stream=true');
});
it('should preserve multiple query params when basePath is empty', () => {
expect(buildUpstreamPath('/v1/models?limit=10&order=asc', HOST, '')).toBe('/v1/models?limit=10&order=asc');
});
it('should handle root path with no base path', () => {
expect(buildUpstreamPath('/', HOST, '')).toBe('/');
});
});
describe('Databricks serving-endpoints (single-segment base path)', () => {
it('should prepend /serving-endpoints to chat completions path', () => {
expect(buildUpstreamPath('/v1/chat/completions', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/chat/completions');
});
it('should prepend /serving-endpoints and preserve query string', () => {
expect(buildUpstreamPath('/v1/chat/completions?stream=true', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/chat/completions?stream=true');
});
it('should prepend /serving-endpoints to models path', () => {
expect(buildUpstreamPath('/v1/models', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/models');
});
it('should prepend /serving-endpoints to embeddings path', () => {
expect(buildUpstreamPath('/v1/embeddings', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/embeddings');
});
});
describe('Azure OpenAI deployments (multi-segment base path)', () => {
it('should prepend Azure deployment path to chat completions', () => {
expect(buildUpstreamPath('/chat/completions', HOST, '/openai/deployments/gpt-4'))
.toBe('/openai/deployments/gpt-4/chat/completions');
});
it('should prepend Azure deployment path and preserve api-version query param', () => {
expect(buildUpstreamPath('/chat/completions?api-version=2024-02-01', HOST, '/openai/deployments/gpt-4'))
.toBe('/openai/deployments/gpt-4/chat/completions?api-version=2024-02-01');
});
it('should handle a deeply nested Azure deployment name', () => {
expect(buildUpstreamPath('/chat/completions', HOST, '/openai/deployments/my-custom-gpt-4-deployment'))
.toBe('/openai/deployments/my-custom-gpt-4-deployment/chat/completions');
});
});
describe('Anthropic custom target with base path', () => {
it('should prepend /anthropic to messages endpoint', () => {
expect(buildUpstreamPath('/v1/messages', 'proxy.corporate.com', '/anthropic'))
.toBe('/anthropic/v1/messages');
});
it('should preserve Anthropic query params', () => {
expect(buildUpstreamPath('/v1/messages?beta=true', 'proxy.corporate.com', '/anthropic'))
.toBe('/anthropic/v1/messages?beta=true');
});
});
describe('path preservation for real-world API endpoints', () => {
it('should preserve /v1/chat/completions exactly (OpenAI standard path)', () => {
expect(buildUpstreamPath('/v1/chat/completions', 'api.openai.com', ''))
.toBe('/v1/chat/completions');
});
it('should preserve /v1/messages exactly (Anthropic standard path)', () => {
expect(buildUpstreamPath('/v1/messages', 'api.anthropic.com', ''))
.toBe('/v1/messages');
});
it('should handle URL-encoded characters in path', () => {
// %2F is preserved by the URL parser (an encoded slash stays encoded)
expect(buildUpstreamPath('/v1/models/gpt-4%2Fturbo', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/models/gpt-4%2Fturbo');
});
it('should handle hash fragment being ignored (not forwarded in HTTP requests)', () => {
// Hash fragments are never sent to the server; URL parser drops them
expect(buildUpstreamPath('/v1/chat/completions#fragment', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/chat/completions');
});
it('should drop empty query string marker', () => {
expect(buildUpstreamPath('/v1/chat/completions?', HOST, '/serving-endpoints'))
.toBe('/serving-endpoints/v1/chat/completions');
});
});
describe('with normalized API target (gh-aw#25137 regression)', () => {
it('should produce correct path when target was already normalized', () => {
// normalizeApiTarget('https://my-gateway.example.com/some-path')
// returns 'my-gateway.example.com' (hostname only)
const target = 'my-gateway.example.com';
expect(buildUpstreamPath('/v1/messages', target, ''))
.toBe('/v1/messages');
});
it('should produce wrong hostname if scheme is NOT stripped (demonstrating the bug)', () => {
// Without normalizeApiTarget, the scheme-prefixed value causes
// new URL() to parse 'https' as the hostname instead of the real host
const badTarget = 'https://my-gateway.example.com';
const targetUrl = new URL('/v1/messages', `https://${badTarget}`);
// Node parses this as hostname='https', not 'my-gateway.example.com'
expect(targetUrl.hostname).not.toBe('my-gateway.example.com');
});
});
});
// ── Helpers for proxyWebSocket tests ──────────────────────────────────────────
/** Create a minimal mock socket with write/destroy spies. */
function makeMockSocket() {
const s = new EventEmitter();
s.write = jest.fn();
s.destroy = jest.fn();
s.pipe = jest.fn();
s.writable = true;
s.destroyed = false;
return s;
}
/** Create a mock HTTP request for a WebSocket upgrade. */
function makeUpgradeReq(overrides = {}) {
return {
url: '/v1/responses',
headers: {
'upgrade': 'websocket',
'connection': 'Upgrade',
'sec-websocket-key': 'test-ws-key==',
'sec-websocket-version': '13',
'host': '172.30.0.30',
...overrides.headers,
},
...overrides,
};
}
describe('proxyWebSocket', () => {
afterEach(() => {
jest.restoreAllMocks();
});
// ── Request validation ─────────────────────────────────────────────────────
describe('request validation', () => {
it('rejects a non-WebSocket upgrade (e.g. h2c) with 400', () => {
const socket = makeMockSocket();
proxyWebSocket(makeUpgradeReq({ headers: { 'upgrade': 'h2c' } }), socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 400 Bad Request'));
expect(socket.destroy).toHaveBeenCalled();
});
it('rejects an upgrade with no Upgrade header with 400', () => {
const socket = makeMockSocket();
const req = makeUpgradeReq();
delete req.headers['upgrade'];
proxyWebSocket(req, socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 400 Bad Request'));
expect(socket.destroy).toHaveBeenCalled();
});
it('rejects an absolute URL with 400 (SSRF prevention)', () => {
const socket = makeMockSocket();
proxyWebSocket(makeUpgradeReq({ url: 'https://evil.com/v1/responses' }), socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 400 Bad Request'));
expect(socket.destroy).toHaveBeenCalled();
});
it('rejects a null URL with 400', () => {
const socket = makeMockSocket();
proxyWebSocket(makeUpgradeReq({ url: null }), socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 400 Bad Request'));
expect(socket.destroy).toHaveBeenCalled();
});
});
// ── Proxy config errors ────────────────────────────────────────────────────
describe('proxy configuration errors', () => {
it('returns 502 when HTTPS_PROXY is not configured', () => {
// The module was loaded without HTTPS_PROXY; proxyWebSocket should fail-safe.
const socket = makeMockSocket();
proxyWebSocket(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 502 Bad Gateway'));
expect(socket.destroy).toHaveBeenCalled();
});
});
// ── Network tunnel tests (module loaded with HTTPS_PROXY set) ─────────────
describe('CONNECT tunnel and auth injection', () => {
let wsProxy;
beforeAll(() => {
// Re-require server with HTTPS_PROXY so proxyWebSocket uses the proxy URL.
process.env.HTTPS_PROXY = 'http://127.0.0.1:3128';
jest.resetModules();
wsProxy = require('./server').proxyWebSocket;
});
afterAll(() => {
delete process.env.HTTPS_PROXY;
jest.resetModules();
});
it('returns 502 when the CONNECT response is not 200', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
const tunnel = makeMockSocket();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
setImmediate(() => connectReq.emit('connect', { statusCode: 407 }, tunnel));
wsProxy(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', { 'Authorization': 'Bearer key' }, 'openai');
return new Promise(resolve => setImmediate(() => {
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 502 Bad Gateway'));
expect(socket.destroy).toHaveBeenCalled();
expect(tunnel.destroy).toHaveBeenCalled();
resolve();
}));
});
it('returns 502 when the CONNECT request emits an error', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
setImmediate(() => connectReq.emit('error', new Error('connection refused')));
wsProxy(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', { 'Authorization': 'Bearer key' }, 'openai');
return new Promise(resolve => setImmediate(() => {
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 502 Bad Gateway'));
expect(socket.destroy).toHaveBeenCalled();
resolve();
}));
});
it('returns 502 when TLS handshake fails', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
const tunnel = makeMockSocket();
const tlsSocket = new EventEmitter();
tlsSocket.write = jest.fn();
tlsSocket.destroy = jest.fn();
tlsSocket.pipe = jest.fn();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
jest.spyOn(tls, 'connect').mockReturnValue(tlsSocket);
setImmediate(() => {
connectReq.emit('connect', { statusCode: 200 }, tunnel);
setImmediate(() => tlsSocket.emit('error', new Error('certificate unknown')));
});
wsProxy(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', { 'Authorization': 'Bearer key' }, 'openai');
return new Promise(resolve => setTimeout(() => {
expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 502 Bad Gateway'));
expect(socket.destroy).toHaveBeenCalled();
resolve();
}, 30));
});
it('injects Authorization header and fixes Host header in the upgrade request', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
const tunnel = makeMockSocket();
const tlsSocket = new EventEmitter();
tlsSocket.write = jest.fn();
tlsSocket.destroy = jest.fn();
tlsSocket.pipe = jest.fn();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
jest.spyOn(tls, 'connect').mockReturnValue(tlsSocket);
setImmediate(() => {
connectReq.emit('connect', { statusCode: 200 }, tunnel);
setImmediate(() => tlsSocket.emit('secureConnect'));
});
wsProxy(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', { 'Authorization': 'Bearer secret' }, 'openai');
return new Promise(resolve => setTimeout(() => {
// The upgrade request is written as a string to tlsSocket
const upgradeWrite = tlsSocket.write.mock.calls.find(
c => typeof c[0] === 'string' && c[0].startsWith('GET ')
);
expect(upgradeWrite).toBeDefined();
const upgradeReqStr = upgradeWrite[0];
expect(upgradeReqStr).toContain('Authorization: Bearer secret');
expect(upgradeReqStr).toContain('host: api.openai.com');
// Both sides should be piped
expect(tlsSocket.pipe).toHaveBeenCalledWith(socket);
expect(socket.pipe).toHaveBeenCalledWith(tlsSocket);
resolve();
}, 30));
});
it('strips client-supplied auth headers before forwarding', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
const tunnel = makeMockSocket();
const tlsSocket = new EventEmitter();
tlsSocket.write = jest.fn();
tlsSocket.destroy = jest.fn();
tlsSocket.pipe = jest.fn();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
jest.spyOn(tls, 'connect').mockReturnValue(tlsSocket);
setImmediate(() => {
connectReq.emit('connect', { statusCode: 200 }, tunnel);
setImmediate(() => tlsSocket.emit('secureConnect'));
});
const req = makeUpgradeReq({
headers: {
'upgrade': 'websocket',
'authorization': 'Bearer client-supplied', // must be stripped
'x-api-key': 'client-api-key', // must be stripped
'sec-websocket-key': 'ws-key==',
'sec-websocket-version': '13',
},
});
wsProxy(req, socket, Buffer.alloc(0), 'api.openai.com', { 'Authorization': 'Bearer injected' }, 'openai');
return new Promise(resolve => setTimeout(() => {
const upgradeWrite = tlsSocket.write.mock.calls.find(
c => typeof c[0] === 'string' && c[0].startsWith('GET ')
);
expect(upgradeWrite).toBeDefined();
const upgradeReqStr = upgradeWrite[0];
// Client-supplied auth is stripped; injected auth is present
expect(upgradeReqStr).not.toContain('client-supplied');
expect(upgradeReqStr).not.toContain('client-api-key');
expect(upgradeReqStr).toContain('Bearer injected');
resolve();
}, 30));
});
it('forwards the CONNECT request to the configured Squid proxy host/port', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
let capturedOptions;
jest.spyOn(http, 'request').mockImplementation((options) => {
capturedOptions = options;
return connectReq;
});
wsProxy(makeUpgradeReq(), socket, Buffer.alloc(0), 'api.openai.com', {}, 'openai');
expect(capturedOptions).toBeDefined();
expect(capturedOptions.method).toBe('CONNECT');
expect(capturedOptions.path).toBe('api.openai.com:443');
expect(capturedOptions.host).toBe('127.0.0.1');
expect(capturedOptions.port).toBe(3128);
});
it('forwards buffered head bytes to the upstream after upgrade', () => {
const socket = makeMockSocket();
const connectReq = new EventEmitter();
connectReq.end = jest.fn();
const tunnel = makeMockSocket();
const tlsSocket = new EventEmitter();
tlsSocket.write = jest.fn();
tlsSocket.destroy = jest.fn();
tlsSocket.pipe = jest.fn();
jest.spyOn(http, 'request').mockReturnValue(connectReq);
jest.spyOn(tls, 'connect').mockReturnValue(tlsSocket);
setImmediate(() => {
connectReq.emit('connect', { statusCode: 200 }, tunnel);
setImmediate(() => tlsSocket.emit('secureConnect'));
});
const headBytes = Buffer.from([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]); // WS text frame: FIN=1, opcode=1, len=5, payload='Hello'
wsProxy(makeUpgradeReq(), socket, headBytes, 'api.openai.com', { 'Authorization': 'Bearer k' }, 'openai');
return new Promise(resolve => setTimeout(() => {
// The head buffer should have been written to tlsSocket
const bufWrite = tlsSocket.write.mock.calls.find(c => Buffer.isBuffer(c[0]));
expect(bufWrite).toBeDefined();
expect(bufWrite[0]).toEqual(headBytes);
resolve();
}, 30));
});
});
});
describe('resolveCopilotAuthToken', () => {
it('should return COPILOT_GITHUB_TOKEN when only it is set', () => {
expect(resolveCopilotAuthToken({ COPILOT_GITHUB_TOKEN: 'gho_abc123' })).toBe('gho_abc123');
});
it('should return COPILOT_API_KEY when only it is set', () => {
expect(resolveCopilotAuthToken({ COPILOT_API_KEY: 'sk-byok-key' })).toBe('sk-byok-key');
});
it('should prefer COPILOT_GITHUB_TOKEN over COPILOT_API_KEY when both are set', () => {
expect(resolveCopilotAuthToken({
COPILOT_GITHUB_TOKEN: 'gho_abc123',
COPILOT_API_KEY: 'sk-byok-key',
})).toBe('gho_abc123');
});
it('should return undefined when neither is set', () => {
expect(resolveCopilotAuthToken({})).toBeUndefined();
});
it('should return undefined for empty strings', () => {
expect(resolveCopilotAuthToken({ COPILOT_GITHUB_TOKEN: '', COPILOT_API_KEY: '' })).toBeUndefined();
});
it('should return undefined for whitespace-only values', () => {
expect(resolveCopilotAuthToken({ COPILOT_GITHUB_TOKEN: ' ', COPILOT_API_KEY: ' \n' })).toBeUndefined();
});
it('should trim whitespace from token values', () => {
expect(resolveCopilotAuthToken({ COPILOT_API_KEY: ' sk-byok-key ' })).toBe('sk-byok-key');
});
it('should fall back to COPILOT_API_KEY when COPILOT_GITHUB_TOKEN is whitespace-only', () => {
expect(resolveCopilotAuthToken({
COPILOT_GITHUB_TOKEN: ' ',
COPILOT_API_KEY: 'sk-byok-key',
})).toBe('sk-byok-key');
});
});