-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Expand file tree
/
Copy pathconnection-test.test.ts
More file actions
4954 lines (4652 loc) · 169 KB
/
Copy pathconnection-test.test.ts
File metadata and controls
4954 lines (4652 loc) · 169 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
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
// Coverage for the /api/test/connection route. Hits status mapping for each
// provider protocol and uses fake CLI bins for deterministic agent outcomes.
import * as http from 'node:http';
import { promises as dnsPromises } from 'node:dns';
import { promises as fsp } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { Socks5ProxyAgent } from 'undici';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import * as platform from '@open-design/platform';
const { resolveSystemProxyEnvMock } = vi.hoisted(() => ({
resolveSystemProxyEnvMock: vi.fn(() => ({})),
}));
vi.mock('@open-design/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('@open-design/platform')>()),
resolveSystemProxyEnv: resolveSystemProxyEnvMock,
}));
import {
createAgentSink,
isSmokeOkReply,
mergeNoProxyWithLoopbackDefaults,
proxyDispatcherRequestInit,
redactSecrets,
resolveOpenAIConnectionTestRunProviderPackage,
resolveConnectionTestTimeoutMs,
testAgentConnection,
testProviderConnection,
validateBaseUrlResolved,
validateUserProviderBaseUrl,
type DnsLookupAddress,
} from '../src/connectionTest.js';
import {
applyAgentLaunchEnv,
getAgentDef,
resolveAgentLaunch,
spawnEnvForAgent,
} from '../src/agents.js';
import { readAppConfig, writeAppConfig } from '../src/app-config.js';
import { listProviderModels } from '../src/integrations/provider-models.js';
import { readVelaCredentialRevision } from '../src/integrations/vela.js';
import { startServer } from '../src/server.js';
import { rememberLiveModels } from '../src/runtimes/models.js';
import { amrModelLoadingCache } from '../src/runtimes/amr-model-cache.js';
import { buildAmrModelCacheKey } from '../src/runtimes/amr-model-probe.js';
type FetchInput = Parameters<typeof fetch>[0];
type FetchInit = Parameters<typeof fetch>[1];
interface StartedServer {
url: string;
server: http.Server;
}
const realFetch = globalThis.fetch;
let baseUrl: string;
let server: http.Server;
const FAKE_VELA_FIXTURE = path.resolve(process.cwd(), 'tests', 'fixtures', 'fake-vela.mjs');
function jsonResponse(body: unknown, init?: ResponseInit): Response {
return new Response(JSON.stringify(body), {
status: init?.status ?? 200,
headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) },
});
}
function textResponse(body: string, init?: ResponseInit): Response {
return new Response(body, {
status: init?.status ?? 200,
headers: { 'content-type': 'text/plain', ...(init?.headers ?? {}) },
});
}
function passThroughOrUpstream(handler: (url: string, init?: FetchInit) => Response | Promise<Response>) {
return vi.fn((input: FetchInput, init?: FetchInit) => {
const url = String(input);
if (url.startsWith(baseUrl)) return realFetch(input, init);
return Promise.resolve(handler(url, init));
});
}
async function withFakeAgent<T>(
binName: string,
script: string,
run: () => Promise<T>,
): Promise<T> {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'od-conn-test-bin-'));
const oldPath = process.env.PATH;
try {
if (process.platform === 'win32') {
const runner = path.join(dir, `${binName}-test-runner.cjs`);
await fsp.writeFile(runner, script);
await fsp.writeFile(
path.join(dir, `${binName}.cmd`),
`@echo off\r\nnode "${runner}" %*\r\n`,
);
} else {
const bin = path.join(dir, binName);
await fsp.writeFile(bin, `#!/usr/bin/env node\n${script}`);
await fsp.chmod(bin, 0o755);
}
process.env.PATH = `${dir}${path.delimiter}${oldPath ?? ''}`;
return await run();
} finally {
process.env.PATH = oldPath;
await fsp.rm(dir, { recursive: true, force: true });
}
}
async function withOnlyFakeAgent<T>(
binName: string,
script: string,
run: () => Promise<T>,
): Promise<T> {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'od-conn-test-bin-'));
const oldPath = process.env.PATH;
const oldAgentHome = process.env.OD_AGENT_HOME;
const oldClaudeBin = process.env.CLAUDE_BIN;
try {
if (process.platform === 'win32') {
const runner = path.join(dir, `${binName}-test-runner.cjs`);
await fsp.writeFile(runner, script);
await fsp.writeFile(
path.join(dir, `${binName}.cmd`),
`@echo off\r\nnode "${runner}" %*\r\n`,
);
} else {
const bin = path.join(dir, binName);
await fsp.writeFile(bin, `#!/usr/bin/env node\n${script}`);
await fsp.chmod(bin, 0o755);
}
process.env.PATH = dir;
process.env.OD_AGENT_HOME = dir;
delete process.env.CLAUDE_BIN;
return await run();
} finally {
process.env.PATH = oldPath;
if (oldAgentHome === undefined) delete process.env.OD_AGENT_HOME;
else process.env.OD_AGENT_HOME = oldAgentHome;
if (oldClaudeBin === undefined) delete process.env.CLAUDE_BIN;
else process.env.CLAUDE_BIN = oldClaudeBin;
await fsp.rm(dir, { recursive: true, force: true });
}
}
async function withFakeCodex<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('codex', script, run);
}
async function withFakeClaude<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('claude', script, run);
}
async function withOnlyFakeOpenClaude<T>(script: string, run: () => Promise<T>): Promise<T> {
return withOnlyFakeAgent('openclaude', script, run);
}
async function withFakeOpenCode<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('opencode', script, run);
}
async function withFakeCursorAgent<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('cursor-agent', script, run);
}
async function withFakeDeepSeek<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('deepseek', script, run);
}
async function withFakeKimi<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('kimi', script, run);
}
async function withFakeAntigravity<T>(script: string, run: () => Promise<T>): Promise<T> {
return withFakeAgent('agy', script, run);
}
async function waitForFile(file: string, timeoutMs = 5_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
await fsp.access(file);
return;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
throw new Error(`Timed out waiting for ${file}`);
}
async function waitForPidToExit(pid: number, timeoutMs = 5_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
process.kill(pid, 0);
} catch {
return;
}
await new Promise((resolve) => setTimeout(resolve, 10));
}
throw new Error(`Timed out waiting for process ${pid} to exit`);
}
beforeAll(async () => {
const started = (await startServer({ port: 0, returnServer: true })) as StartedServer;
baseUrl = started.url;
server = started.server;
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
amrModelLoadingCache.resetForTests();
});
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
describe('POST /api/provider/models', () => {
it('lists OpenAI-compatible models from /models', async () => {
const fetchMock = passThroughOrUpstream((url, init) => {
expect(url).toBe('https://api.openai.com/v1/models');
expect((init?.headers as Record<string, string>).authorization).toBe(
'Bearer sk-openai',
);
return jsonResponse({
data: [
{
id: 'gpt-4o-mini',
object: 'model',
metadata: { cost: 'low', capability: 'standard' },
enabled: false,
},
{
id: 'gpt-4o',
object: 'model',
metadata: { cost: 'medium', capability: 'advanced' },
default: true,
},
{ id: 'gpt-4o', object: 'model' },
{ id: 'wan2-1-14b-t2v-250225', object: 'model' },
{ id: 'text-embedding-3-large', object: 'model' },
{ id: 'dall-e-3', object: 'model' },
],
});
});
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'sk-openai',
}),
});
expect(res.status).toBe(200);
const body = (await res.json()) as {
ok: boolean;
kind: string;
models?: Array<Record<string, unknown>>;
};
expect(body).toMatchObject({
ok: true,
kind: 'success',
models: [
{
id: 'gpt-4o-mini',
label: 'gpt-4o-mini',
metadata: { cost: 'low', capability: 'standard' },
},
{
id: 'gpt-4o',
label: 'gpt-4o',
metadata: { cost: 'medium', capability: 'advanced' },
},
],
});
expect(body.models?.[0]?.enabled).toBeUndefined();
expect(body.models?.[0]?.default).toBeUndefined();
expect(body.models?.[1]?.enabled).toBeUndefined();
expect(body.models?.[1]?.default).toBeUndefined();
});
// Regression for #5367: a gateway's /models catalogue can list embedding
// models alongside real chat models. `BAAI/bge-large-en-v1.5` (reported via
// SiliconFlow) doesn't contain any of the existing exclusion substrings
// (`embedding`, `rerank`, ...), so it was surfacing as a "loaded" chat model
// in the picker and then 404ing the moment a user actually tested it.
it('excludes the BGE embedding family from an OpenAI-compatible /models catalogue', async () => {
const fetchMock = passThroughOrUpstream(() =>
jsonResponse({
data: [
{ id: 'deepseek-ai/DeepSeek-V3', object: 'model' },
{ id: 'BAAI/bge-large-en-v1.5', object: 'model' },
{ id: 'BAAI/bge-reranker-v2-m3', object: 'model' },
],
}),
);
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'https://api.siliconflow.cn/v1',
apiKey: 'sk-siliconflow',
}),
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({
ok: true,
kind: 'success',
models: [{ id: 'deepseek-ai/DeepSeek-V3', label: 'deepseek-ai/DeepSeek-V3' }],
});
});
it('routes provider model discovery through the live proxy dispatcher', async () => {
const proxySpy = vi.spyOn(platform, 'resolveSystemProxyEnv').mockReturnValue({
HTTP_PROXY: 'http://proxy.example.test:8080',
NODE_USE_ENV_PROXY: '1',
NO_PROXY: 'localhost,127.0.0.1,[::1]',
});
const fetchMock = passThroughOrUpstream((_url, init) => {
expect(init?.dispatcher).toBeTruthy();
return jsonResponse({
data: [{ id: 'gpt-4o', object: 'model' }],
});
});
vi.stubGlobal('fetch', fetchMock);
try {
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'sk-openai',
}),
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({
ok: true,
kind: 'success',
models: [{ id: 'gpt-4o', label: 'gpt-4o' }],
});
expect(proxySpy).toHaveBeenCalledWith();
} finally {
proxySpy.mockRestore();
}
});
it('lists Anthropic models with display names and a high page limit', async () => {
const fetchMock = passThroughOrUpstream((url, init) => {
expect(url).toBe('https://api.anthropic.com/v1/models?limit=1000');
expect((init?.headers as Record<string, string>)['x-api-key']).toBe(
'sk-ant',
);
expect((init?.headers as Record<string, string>)['anthropic-version']).toBe(
'2023-06-01',
);
return jsonResponse({
data: [
{
id: 'claude-sonnet-4-5',
display_name: 'Claude Sonnet 4.5',
type: 'model',
},
{
id: 'claude-haiku-4-5',
display_name: 'Claude Haiku 4.5',
type: 'model',
},
],
});
});
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'anthropic',
baseUrl: 'https://api.anthropic.com',
apiKey: 'sk-ant',
}),
});
await expect(res.json()).resolves.toMatchObject({
ok: true,
models: [
{ id: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
{ id: 'claude-haiku-4-5', label: 'Claude Haiku 4.5' },
],
});
});
it('lists only Gemini models that support generateContent', async () => {
const fetchMock = passThroughOrUpstream((url) => {
expect(url).toBe(
'https://generativelanguage.googleapis.com/v1beta/models?key=goog-key',
);
return jsonResponse({
models: [
{
name: 'models/gemini-custom',
displayName: 'Gemini Custom',
supportedGenerationMethods: ['generateContent'],
},
{
name: 'models/text-embedding-004',
displayName: 'Embedding',
supportedGenerationMethods: ['embedContent'],
},
{
name: 'models/gemini-2.0-flash-001',
baseModelId: 'gemini-2.0-flash',
displayName: 'Gemini 2.0 Flash',
supportedGenerationMethods: ['generateContent', 'countTokens'],
},
],
});
});
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'google',
baseUrl: 'https://generativelanguage.googleapis.com',
apiKey: 'goog-key',
}),
});
await expect(res.json()).resolves.toMatchObject({
ok: true,
models: [
{ id: 'gemini-custom', label: 'Gemini Custom' },
{ id: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' },
],
});
});
it('does not double-append v1beta when listing Gemini models', async () => {
const fetchMock = passThroughOrUpstream((url) => {
expect(url).toBe(
'https://generativelanguage.googleapis.com/v1beta/models?key=goog-key',
);
return jsonResponse({
models: [
{
name: 'models/gemini-2.0-flash',
displayName: 'Gemini 2.0 Flash',
supportedGenerationMethods: ['generateContent'],
},
],
});
});
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'google',
baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
apiKey: 'goog-key',
}),
});
await expect(res.json()).resolves.toMatchObject({
ok: true,
models: [{ id: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' }],
});
});
it('lets unsupported contract protocols return a classified provider-models result', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({}));
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'ollama',
baseUrl: 'https://ollama.com',
apiKey: 'ollama-key',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(res.status).toBe(200);
expect(body).toMatchObject({
ok: false,
kind: 'unsupported_protocol',
});
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
});
it('maps upstream listing failures to categorized results and redacts keys', async () => {
for (const [status, kind, response] of [
[
401,
'auth_failed',
(apiKey: string) => jsonResponse(
{ error: { message: `bad key ${apiKey}` } },
{ status: 401 },
),
],
[
429,
'rate_limited',
(apiKey: string) => textResponse(`rate limit for ${apiKey}`, { status: 429 }),
],
[
503,
'upstream_unavailable',
(apiKey: string) => textResponse(
`<html>temporary outage for ${apiKey}</html>`,
{ status: 503, headers: { 'content-type': 'text/html' } },
),
],
] as const) {
const apiKey = `sk-secret-models-${status}`;
vi.stubGlobal(
'fetch',
passThroughOrUpstream(() => response(apiKey)),
);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiKey,
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body).toMatchObject({ ok: false, kind, status });
expect(String(body.detail)).not.toContain(apiKey);
vi.unstubAllGlobals();
}
});
it('rejects private-network base URLs without calling upstream fetch', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({}));
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'http://192.168.1.5:8080/v1',
apiKey: 'sk-good',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body).toMatchObject({ ok: false, kind: 'forbidden' });
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
});
// Regression for the DNS-bypass SSRF gap flagged on PR #1176: the route
// must resolve the hostname and reject when *any* resolved address is in
// a blocked range, not just when the literal hostname is a private IP.
it('rejects hostnames that resolve to a private IP without calling upstream fetch', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({}));
vi.stubGlobal('fetch', fetchMock);
const dnsSpy = vi
.spyOn(dnsPromises, 'lookup')
.mockImplementation((async (hostname: string) => {
if (hostname === 'rebind.example.test') {
return [{ address: '10.0.0.5', family: 4 }];
}
const err: NodeJS.ErrnoException = new Error('ENOTFOUND');
err.code = 'ENOTFOUND';
throw err;
}) as unknown as typeof dnsPromises.lookup);
try {
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'https://rebind.example.test/v1',
apiKey: 'sk-good',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body).toMatchObject({ ok: false, kind: 'forbidden' });
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
} finally {
dnsSpy.mockRestore();
}
});
it('lets an operator-allowlisted internal endpoint reach the upstream model fetch (#3225)', async () => {
// The exact symptom in #3225 — "Could not fetch models: Internal IPs
// blocked". With the host opted in via OD_ALLOWED_INTERNAL_HOSTS, model
// discovery must reach the internal gateway instead of returning forbidden.
vi.stubEnv('OD_ALLOWED_INTERNAL_HOSTS', '10.0.0.5');
const fetchMock = passThroughOrUpstream(() =>
jsonResponse({ data: [{ id: 'gpt-4o-internal' }] }),
);
vi.stubGlobal('fetch', fetchMock);
try {
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'openai',
baseUrl: 'http://10.0.0.5:11434/v1',
apiKey: 'sk-good',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body).not.toMatchObject({ kind: 'forbidden' });
expect(
fetchMock.mock.calls.some(([input]) =>
String(input).includes('10.0.0.5'),
),
).toBe(true);
} finally {
vi.unstubAllEnvs();
}
});
it('lists local Ollama models from /api/tags', async () => {
// Loopback is opted in so the request reaches upstream regardless of the
// daemon's internal-host policy.
vi.stubEnv('OD_ALLOWED_INTERNAL_HOSTS', '127.0.0.1');
const fetchMock = passThroughOrUpstream((url) => {
expect(url).toBe('http://127.0.0.1:11434/api/tags');
return jsonResponse({
models: [
{ name: 'llama3.3:70b', model: 'llama3.3:70b' },
{ name: 'qwen3-coder:480b' },
],
});
});
vi.stubGlobal('fetch', fetchMock);
try {
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'ollama',
baseUrl: 'http://127.0.0.1:11434',
apiKey: '',
}),
});
const body = (await res.json()) as {
ok: boolean;
kind: string;
models?: Array<Record<string, unknown>>;
};
expect(body).toMatchObject({
ok: true,
kind: 'success',
models: [
{ id: 'llama3.3:70b', label: 'llama3.3:70b' },
{ id: 'qwen3-coder:480b', label: 'qwen3-coder:480b' },
],
});
} finally {
vi.unstubAllEnvs();
}
});
it('rejects Ollama Cloud model discovery without calling upstream fetch', async () => {
const dnsSpy = vi
.spyOn(dnsPromises, 'lookup')
.mockImplementation((async (hostname: string) => {
if (hostname === 'ollama.com') {
return [{ address: '104.18.0.1', family: 4 }];
}
const err: NodeJS.ErrnoException = new Error('ENOTFOUND');
err.code = 'ENOTFOUND';
throw err;
}) as unknown as typeof dnsPromises.lookup);
const fetchMock = passThroughOrUpstream(() => jsonResponse({ models: [] }));
vi.stubGlobal('fetch', fetchMock);
try {
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'ollama',
baseUrl: 'https://ollama.com',
apiKey: 'ollama-key',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body).toMatchObject({ ok: false, kind: 'unsupported_protocol' });
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
} finally {
dnsSpy.mockRestore();
}
});
it('reports timeout when model listing is aborted by the probe timer', async () => {
// The DNS-aware validator runs before the probe timer is installed; stub
// the resolver so the test doesn't race against real DNS while fake
// timers are active.
const dnsSpy = vi
.spyOn(dnsPromises, 'lookup')
.mockImplementation((async () => [
{ address: '203.0.113.10', family: 4 },
]) as unknown as typeof dnsPromises.lookup);
vi.useFakeTimers();
vi.stubGlobal(
'fetch',
vi.fn((_input: FetchInput, init?: FetchInit) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('Aborted', 'AbortError'));
});
}),
),
);
try {
const pending = listProviderModels({
protocol: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'sk-timeout',
});
await vi.advanceTimersByTimeAsync(12_000);
await expect(pending).resolves.toMatchObject({
ok: false,
kind: 'timeout',
});
} finally {
dnsSpy.mockRestore();
}
});
});
describe('POST /api/test/connection provider mode', () => {
it('reports success and returns the model sample for an Anthropic 200', async () => {
vi.stubGlobal(
'fetch',
passThroughOrUpstream(() =>
jsonResponse({
content: [{ type: 'text', text: 'ok' }],
}),
),
);
const res = await realFetch(`${baseUrl}/api/test/connection`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
mode: 'provider',
protocol: 'anthropic',
baseUrl: 'https://api.anthropic.com',
apiKey: 'sk-ant-test',
model: 'claude-sonnet-4-5',
}),
});
expect(res.status).toBe(200);
const body = (await res.json()) as Record<string, unknown>;
expect(body.ok).toBe(true);
expect(body.kind).toBe('success');
expect(body.model).toBe('claude-sonnet-4-5');
expect(body.sample).toBe('ok');
});
it('redacts submitted keys from success samples', async () => {
vi.stubGlobal(
'fetch',
passThroughOrUpstream(() =>
jsonResponse({
content: [{ type: 'text', text: 'debug echo sk-success-secret' }],
}),
),
);
const res = await realFetch(`${baseUrl}/api/test/connection`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
mode: 'provider',
protocol: 'anthropic',
baseUrl: 'https://api.anthropic.com',
apiKey: 'sk-success-secret',
model: 'claude-sonnet-4-5',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body.ok).toBe(true);
expect(body.sample).toBe('debug echo [REDACTED]');
expect(body.sample).not.toContain('sk-success-secret');
});
it('maps a 401 to auth_failed', async () => {
vi.stubGlobal(
'fetch',
passThroughOrUpstream(() =>
jsonResponse({ error: { message: 'invalid x-api-key' } }, { status: 401 }),
),
);
const res = await realFetch(`${baseUrl}/api/test/connection`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
mode: 'provider',
protocol: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiKey: 'sk-bad',
model: 'gpt-4o',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body.ok).toBe(false);
expect(body.kind).toBe('auth_failed');
expect(body.status).toBe(401);
});
it('maps NVIDIA DEGRADED errors to actionable upstream detail', async () => {
vi.stubGlobal(
'fetch',
passThroughOrUpstream((url) => {
expect(url).toBe('https://integrate.api.nvidia.com/v1/chat/completions');
return jsonResponse(
{ error: { message: 'DEGRADED function id=abc123' } },
{ status: 400 },
);
}),
);
const res = await realFetch(`${baseUrl}/api/test/connection`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
mode: 'provider',
protocol: 'openai',
baseUrl: 'https://integrate.api.nvidia.com/v1',
apiKey: 'nvapi-test',
model: 'minimaxai/minimax-m3',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body.ok).toBe(false);
expect(body.kind).toBe('upstream_unavailable');
expect(body.status).toBe(400);
expect(body.detail).toContain('selected NVIDIA model instance');
expect(body.detail).toContain('Try a different model');
expect(body.detail).not.toContain('function id');
});
it('does not add a duplicate version segment for versioned OpenAI-compatible subpaths', async () => {
const fetchMock = vi.fn((input: FetchInput, init?: FetchInit) => {
const url = String(input);
if (url.startsWith(baseUrl)) return realFetch(input, init);
if (url.endsWith('/models')) {
return Promise.resolve(jsonResponse({ data: [{ id: 'm' }] }));
}
return Promise.resolve(
jsonResponse({
choices: [{ message: { content: 'ok' } }],
}),
);
});
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/test/connection`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
mode: 'provider',
protocol: 'openai',
baseUrl: 'https://api.deepinfra.com/v1/openai',
apiKey: 'sk-good',
model: 'm',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(body.ok).toBe(true);
expect(fetchMock).toHaveBeenCalledWith(
'https://api.deepinfra.com/v1/openai/chat/completions',
expect.anything(),
);
});
it('returns static AWS Bedrock model seeds without calling upstream fetch', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({ error: 'unexpected upstream call' }, { status: 500 }));
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'bedrock',
baseUrl: 'https://bedrock-runtime.us-east-1.amazonaws.com',
apiKey: '',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(res.status).toBe(200);
expect(body).toMatchObject({
ok: true,
kind: 'success',
});
expect(body.models).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
}),
]),
);
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
});
it('rejects malformed AWS Bedrock model-list URLs before static seeds', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({ error: 'unexpected upstream call' }, { status: 500 }));
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'bedrock',
baseUrl: 'not-a-url',
apiKey: '',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(res.status).toBe(200);
expect(body).toMatchObject({
ok: false,
kind: 'invalid_base_url',
});
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
});
it('rejects forbidden AWS Bedrock model-list URLs before static seeds', async () => {
const fetchMock = passThroughOrUpstream(() => jsonResponse({ error: 'unexpected upstream call' }, { status: 500 }));
vi.stubGlobal('fetch', fetchMock);
const res = await realFetch(`${baseUrl}/api/provider/models`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
protocol: 'bedrock',
baseUrl: 'http://10.0.0.8:8080',
apiKey: '',
}),
});
const body = (await res.json()) as Record<string, unknown>;
expect(res.status).toBe(200);
expect(body).toMatchObject({
ok: false,
kind: 'forbidden',
});
expect(
fetchMock.mock.calls.some(
([input]) => !String(input).startsWith(baseUrl),
),
).toBe(false);
});
it('checks SenseAudio non-chat model availability without probing chat completions', async () => {
const fetchMock = passThroughOrUpstream((url) => {