-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity_test.go
More file actions
1002 lines (892 loc) · 33.5 KB
/
Copy pathsecurity_test.go
File metadata and controls
1002 lines (892 loc) · 33.5 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
package llm_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/bds421/rho-llm"
"github.com/bds421/rho-llm/provider/anthropic"
"github.com/bds421/rho-llm/provider/gemini"
"github.com/bds421/rho-llm/provider/openaicompat"
)
// =============================================================================
// SECURITY TESTS
// =============================================================================
// TestGeminiAPIKeyNotInURL verifies that the Gemini adapter sends the API key
// via the x-goog-api-key header, NOT as a URL query parameter. API keys in
// URLs leak into server logs, proxy logs, referer headers, and browser history.
func TestGeminiAPIKeyNotInURL(t *testing.T) {
const testKey = "test-secret-key-12345"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FAIL if the key appears anywhere in the URL
if strings.Contains(r.URL.String(), testKey) {
t.Errorf("API key leaked into URL: %s", r.URL.String())
}
if r.URL.Query().Get("key") != "" {
t.Errorf("API key sent as query parameter 'key=%s'", r.URL.Query().Get("key"))
}
// PASS if the key is in the header
got := r.Header.Get("x-goog-api-key")
if got != testKey {
t.Errorf("x-goog-api-key header = %q, want %q", got, testKey)
}
// Return a minimal valid Gemini response
w.Header().Set("Content-Type", "application/json")
resp := map[string]interface{}{
"candidates": []map[string]interface{}{
{
"content": map[string]interface{}{
"parts": []map[string]string{{"text": "Hello"}},
"role": "model",
},
"finishReason": "STOP",
},
},
"usageMetadata": map[string]int{
"promptTokenCount": 5,
"candidatesTokenCount": 1,
"totalTokenCount": 6,
},
}
if err := json.NewEncoder(w).Encode(resp); err != nil {
t.Fatalf("failed to encode response: %v", err)
}
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: testKey,
BaseURL: srv.URL,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("gemini.New() error: %v", err)
}
resp, err := client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err != nil {
t.Fatalf("Complete() error: %v", err)
}
if resp.Content != "Hello" {
t.Errorf("unexpected content: %q", resp.Content)
}
}
// TestGeminiStreamAPIKeyNotInURL verifies the streaming path also uses headers.
func TestGeminiStreamAPIKeyNotInURL(t *testing.T) {
const testKey = "stream-secret-key-67890"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.String(), testKey) {
t.Errorf("API key leaked into URL: %s", r.URL.String())
}
if r.URL.Query().Get("key") != "" {
t.Errorf("API key sent as query parameter")
}
got := r.Header.Get("x-goog-api-key")
if got != testKey {
t.Errorf("x-goog-api-key header = %q, want %q", got, testKey)
}
// Return minimal SSE stream
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Hi\"}],\"role\":\"model\"},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":5,\"candidatesTokenCount\":1}}\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: testKey,
BaseURL: srv.URL,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("gemini.New() error: %v", err)
}
for event, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
t.Fatalf("Stream error: %v", err)
}
_ = event
}
}
// TestErrorBodyTruncation verifies that enormous error response bodies are
// truncated before being stored in APIError.Message. Without truncation,
// a malicious endpoint could return a multi-GB error body causing OOM.
func TestErrorBodyTruncation(t *testing.T) {
// 2MB body — well over the expected cap
bigBody := strings.Repeat("x", 2*1024*1024)
apiErr := llm.NewAPIErrorFromStatus("test", 500, bigBody)
// Message should be capped (we expect 4KB max)
const maxExpected = 4096 + 100 // allow small overhead for truncation marker
if len(apiErr.Message) > maxExpected {
t.Errorf("APIError.Message length = %d, want <= %d", len(apiErr.Message), maxExpected)
}
}
// TestErrorBodyReadBounded verifies that io.ReadAll on error responses is
// bounded. We test this via the Gemini adapter with a server that streams
// an enormous error body.
func TestErrorBodyReadBounded(t *testing.T) {
// Server that returns a 500 with a never-ending body
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
// Write 2MB of error data
chunk := strings.Repeat("E", 64*1024)
for i := 0; i < 32; i++ {
if _, err := io.WriteString(w, chunk); err != nil {
return
}
}
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: "test-key",
BaseURL: srv.URL,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("gemini.New() error: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err == nil {
t.Fatal("expected error from 500 response")
}
// The error message should be bounded, not the full 2MB
var apiErr *llm.APIError
if ok := errors.As(err, &apiErr); !ok {
t.Fatalf("expected *llm.APIError, got %T", err)
}
const maxExpected = 1024*1024 + 4096 // 1MB read limit + truncation overhead
if len(apiErr.Message) > maxExpected {
t.Errorf("error body length = %d, want <= %d (unbounded read)", len(apiErr.Message), maxExpected)
}
}
// TestRedirectDoesNotLeakAuthHeaders verifies that HTTP redirects to a
// different host strip sensitive authentication headers. Without this,
// a MITM or malicious redirect could steal API keys.
func TestRedirectDoesNotLeakAuthHeaders(t *testing.T) {
var capturedHeaders http.Header
// Attacker server that captures headers
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedHeaders = r.Header.Clone()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"candidates":[{"content":{"parts":[{"text":"pwned"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1}}`)
}))
defer attacker.Close()
// Legitimate-looking server that redirects to attacker
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, attacker.URL+r.URL.Path, http.StatusTemporaryRedirect)
}))
defer redirector.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: "secret-key-do-not-leak",
BaseURL: redirector.URL,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("gemini.New() error: %v", err)
}
// The request may succeed or fail depending on redirect policy —
// what matters is that the attacker didn't get our auth headers.
_, _ = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if capturedHeaders != nil {
if got := capturedHeaders.Get("x-goog-api-key"); got != "" {
t.Errorf("x-goog-api-key header leaked to redirect target: %q", got)
}
if got := capturedHeaders.Get("Authorization"); got != "" {
t.Errorf("Authorization header leaked to redirect target: %q", got)
}
if got := capturedHeaders.Get("x-api-key"); got != "" {
t.Errorf("x-api-key header leaked to redirect target: %q", got)
}
}
}
// TestRedirectDoesNotLeakAnthropicKey tests redirect stripping for Anthropic's x-api-key.
func TestRedirectDoesNotLeakAnthropicKey(t *testing.T) {
var capturedHeaders http.Header
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedHeaders = r.Header.Clone()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"pwned"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}))
defer attacker.Close()
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, attacker.URL+r.URL.Path, http.StatusTemporaryRedirect)
}))
defer redirector.Close()
cfg := llm.Config{
Provider: "anthropic",
Model: "claude-sonnet-4-6",
APIKey: "sk-secret-anthropic-key",
BaseURL: redirector.URL,
}
client, err := llm.NewClient(cfg)
if err != nil {
t.Fatalf("NewClient() error: %v", err)
}
defer client.Close()
_, _ = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if capturedHeaders != nil {
if got := capturedHeaders.Get("x-api-key"); got != "" {
t.Errorf("x-api-key header leaked to redirect target: %q", got)
}
if got := capturedHeaders.Get("Authorization"); got != "" {
t.Errorf("Authorization header leaked to redirect target: %q", got)
}
}
}
// TestRedirectDoesNotLeakOpenAIKey tests redirect stripping for OpenAI Bearer tokens.
func TestRedirectDoesNotLeakOpenAIKey(t *testing.T) {
var capturedHeaders http.Header
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedHeaders = r.Header.Clone()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"id":"chatcmpl-test","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"pwned"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
}))
defer attacker.Close()
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, attacker.URL+r.URL.Path, http.StatusTemporaryRedirect)
}))
defer redirector.Close()
cfg := llm.Config{
Provider: "openai",
Model: "gpt-4",
APIKey: "sk-openai-secret-key",
BaseURL: redirector.URL,
}
client, err := llm.NewClient(cfg)
if err != nil {
t.Fatalf("NewClient() error: %v", err)
}
defer client.Close()
_, _ = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if capturedHeaders != nil {
if got := capturedHeaders.Get("Authorization"); got != "" {
t.Errorf("Authorization header leaked to redirect target: %q", got)
}
}
}
// =============================================================================
// ROUND 2: Unbounded success body decode, inputBuffer accumulation, SSE errors
// =============================================================================
// TestSuccessResponseBodyBounded verifies that JSON decoding of success
// response bodies is bounded. Without a limit, a malicious endpoint returning
// a multi-GB JSON response causes OOM via json.Decoder.
func TestSuccessResponseBodyBounded(t *testing.T) {
t.Run("gemini", func(t *testing.T) {
// Server returns a 200 with a huge JSON body (> MaxResponseBodyBytes)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Write valid JSON prefix, then a huge text field
fmt.Fprint(w, `{"candidates":[{"content":{"parts":[{"text":"`)
// Write 40MB of 'A' — well over any sane response limit
chunk := strings.Repeat("A", 64*1024)
for i := 0; i < 640; i++ {
if _, err := io.WriteString(w, chunk); err != nil {
return
}
}
fmt.Fprint(w, `"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1}}`)
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
// Should get a decode error because the reader was truncated, not OOM
if err == nil {
t.Fatal("expected error from oversized response body, got nil")
}
// Verify we got an error (not a panic/OOM)
t.Logf("got expected error: %v", err)
})
t.Run("anthropic", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"msg_test","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"`)
chunk := strings.Repeat("A", 64*1024)
for i := 0; i < 640; i++ {
if _, err := io.WriteString(w, chunk); err != nil {
return
}
}
fmt.Fprint(w, `"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}))
defer srv.Close()
cfg := llm.Config{
Provider: "anthropic",
Model: "claude-sonnet-4-6",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := anthropic.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err == nil {
t.Fatal("expected error from oversized response body, got nil")
}
t.Logf("got expected error: %v", err)
})
t.Run("openai", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"chatcmpl-test","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"`)
chunk := strings.Repeat("A", 64*1024)
for i := 0; i < 640; i++ {
if _, err := io.WriteString(w, chunk); err != nil {
return
}
}
fmt.Fprint(w, `"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
}))
defer srv.Close()
cfg := llm.Config{
Provider: "openai",
Model: "gpt-4",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := openaicompat.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err == nil {
t.Fatal("expected error from oversized response body, got nil")
}
t.Logf("got expected error: %v", err)
})
}
// TestStreamInputBufferBounded verifies that tool input accumulation during
// streaming is bounded. Without a cap, a malicious endpoint sending thousands
// of input_json_delta events can exhaust memory.
func TestStreamInputBufferBounded(t *testing.T) {
t.Run("anthropic", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
// Start a tool call
fmt.Fprint(w, "data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"call_1\",\"name\":\"big_tool\"}}\n\n")
// Send 2000 input_json_delta events, each ~1KB → total ~2MB
for i := 0; i < 2000; i++ {
chunk := strings.Repeat("x", 1024)
fmt.Fprintf(w, "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"%s\"}}\n\n", chunk)
}
// End the tool call
fmt.Fprint(w, "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n")
fmt.Fprint(w, "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\"},\"usage\":{\"output_tokens\":100}}\n\n")
fmt.Fprint(w, "data: {\"type\":\"message_stop\"}\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "anthropic",
Model: "claude-sonnet-4-6",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := anthropic.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
var gotError bool
for _, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
gotError = true
t.Logf("got expected error from oversized tool input: %v", err)
break
}
}
if !gotError {
t.Error("expected error from oversized tool input buffer, stream completed without error")
}
})
t.Run("openai", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
// Start a tool call
fmt.Fprint(w, "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"big_tool\",\"arguments\":\"\"}}]}}]}\n\n")
// Send 2000 argument chunks, each ~1KB → total ~2MB
for i := 0; i < 2000; i++ {
chunk := strings.Repeat("y", 1024)
fmt.Fprintf(w, "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"%s\"}}]}}]}\n\n", chunk)
}
fmt.Fprint(w, "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"finish_reason\":\"tool_calls\"}]}\n\n")
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "openai",
Model: "gpt-4",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := openaicompat.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
var gotError bool
for _, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
gotError = true
t.Logf("got expected error from oversized tool input: %v", err)
break
}
}
if !gotError {
t.Error("expected error from oversized tool input buffer, stream completed without error")
}
})
}
// TestMalformedSSEEventYieldsError verifies that malformed SSE events are
// reported as errors to the caller, not silently dropped. Silent drops cause
// data loss without the caller's knowledge.
func TestMalformedSSEEventYieldsError(t *testing.T) {
t.Run("gemini", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
// Valid event, then malformed, then valid done
fmt.Fprint(w, "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Hello\"}],\"role\":\"model\"}}]}\n\n")
fmt.Fprint(w, "data: {this is not valid json}\n\n")
fmt.Fprint(w, "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\" world\"}],\"role\":\"model\"},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":1,\"candidatesTokenCount\":1}}\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
var gotError bool
for _, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
gotError = true
break
}
}
if !gotError {
t.Error("expected error from malformed SSE event, stream completed silently")
}
})
t.Run("anthropic", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10}}}\n\n")
fmt.Fprint(w, "data: {not valid json at all}\n\n")
fmt.Fprint(w, "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5}}\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "anthropic",
Model: "claude-sonnet-4-6",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := anthropic.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
var gotError bool
for _, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
gotError = true
break
}
}
if !gotError {
t.Error("expected error from malformed SSE event, stream completed silently")
}
})
t.Run("openai", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}]}\n\n")
fmt.Fprint(w, "data: {broken json\n\n")
fmt.Fprint(w, "data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"finish_reason\":\"stop\"}]}\n\n")
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer srv.Close()
cfg := llm.Config{
Provider: "openai",
Model: "gpt-4",
APIKey: "test-key",
BaseURL: srv.URL,
Timeout: 10 * time.Second,
}
client, err := openaicompat.New(cfg)
if err != nil {
t.Fatalf("New() error: %v", err)
}
var gotError bool
for _, err := range client.Stream(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
}) {
if err != nil {
gotError = true
break
}
}
if !gotError {
t.Error("expected error from malformed SSE event, stream completed silently")
}
})
}
// =============================================================================
// ROUND 3: JSON Redaction & Scheme Validation
// =============================================================================
// TestConfigMarshalJSONRedactsAPIKey verifies that Config.MarshalJSON replaces
// the APIKey with "REDACTED" so secrets don't leak into logs or debug output.
func TestConfigMarshalJSONRedactsAPIKey(t *testing.T) {
tests := []struct {
name string
apiKey string
wantKey string
}{
{"non-empty key is redacted", "sk-secret-12345", "REDACTED"},
{"empty key stays empty", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := llm.DefaultConfig()
cfg.APIKey = tt.apiKey
data, err := json.Marshal(cfg)
if err != nil {
t.Fatalf("Marshal error: %v", err)
}
var decoded map[string]interface{}
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
got, _ := decoded["api_key"].(string)
if got != tt.wantKey {
t.Errorf("api_key = %q, want %q", got, tt.wantKey)
}
// The raw JSON must never contain the original secret
if tt.apiKey != "" && strings.Contains(string(data), tt.apiKey) {
t.Errorf("serialized JSON contains the raw API key")
}
})
}
}
// TestAuthProfileMarshalJSONRedactsAPIKey verifies that AuthProfile.MarshalJSON
// replaces the APIKey with "REDACTED".
func TestAuthProfileMarshalJSONRedactsAPIKey(t *testing.T) {
tests := []struct {
name string
apiKey string
wantKey string
}{
{"non-empty key is redacted", "sk-auth-profile-secret", "REDACTED"},
{"empty key stays empty", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
profile := llm.AuthProfile{
Name: "test-profile",
APIKey: tt.apiKey,
IsHealthy: true,
}
data, err := json.Marshal(profile)
if err != nil {
t.Fatalf("Marshal error: %v", err)
}
var decoded map[string]interface{}
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
got, _ := decoded["api_key"].(string)
if got != tt.wantKey {
t.Errorf("api_key = %q, want %q", got, tt.wantKey)
}
if tt.apiKey != "" && strings.Contains(string(data), tt.apiKey) {
t.Errorf("serialized JSON contains the raw API key")
}
})
}
}
// TestBaseURLSchemeValidation documents that non-HTTP(S) BaseURL schemes
// (file://, javascript:, ftp://, data:) fail at request time. NOTE: this library
// does NOT validate the scheme itself — Go's net/http rejects unsupported schemes
// when the request is made. This test pins that incidental behavior; it is not
// evidence of an allowlist. For actual SSRF hardening of BaseURL, see
// Config.BlockPrivateBaseURL / llm.CheckBaseURL (TestBlockPrivateBaseURL).
//
// Uses the openaicompat adapter directly (not llm.NewClient) to avoid the
// PooledClient retry loop, which would add ~30s per subtest in cooldown waits.
// TestAdapterCloseClosesIdleConnections verifies that calling Close() on
// each provider adapter drains idle HTTP connections. Without this, rotated
// clients leak transport-level connection pools.
func TestAdapterCloseClosesIdleConnections(t *testing.T) {
// The test strategy: create a client pointing at a test server, make one
// request to establish a connection pool entry, then Close() the client.
// After Close, the server should not see any lingering connections.
// We can verify this indirectly: calling Close should not panic and should
// invoke CloseIdleConnections (we can verify by checking the HTTP transport
// state). In practice, the simplest effective test is to verify Close()
// returns nil and the method actually calls httpClient.CloseIdleConnections.
//
// A practical approach: make a request, then Close. If Close merely
// returns nil without draining, connections stay open. We verify via a
// second request after Close — if connections were drained, the transport
// needs to re-dial.
t.Run("anthropic", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}))
defer srv.Close()
client, err := anthropic.New(llm.Config{
Provider: "anthropic", Model: "claude-sonnet-4-6",
APIKey: "test", BaseURL: srv.URL, Timeout: 5 * time.Second,
})
if err != nil {
t.Fatalf("New: %v", err)
}
// Establish a connection
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err != nil {
t.Fatalf("Complete: %v", err)
}
// Close should drain idle connections (not panic, return nil)
if err := client.Close(); err != nil {
t.Errorf("Close() = %v, want nil", err)
}
})
t.Run("gemini", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"candidates":[{"content":{"parts":[{"text":"ok"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1}}`)
}))
defer srv.Close()
client, err := gemini.New(llm.Config{
Provider: "gemini", Model: "gemini-2.5-flash",
APIKey: "test", BaseURL: srv.URL, Timeout: 5 * time.Second,
})
if err != nil {
t.Fatalf("New: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err != nil {
t.Fatalf("Complete: %v", err)
}
if err := client.Close(); err != nil {
t.Errorf("Close() = %v, want nil", err)
}
})
t.Run("openaicompat", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"id":"chatcmpl-1","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
}))
defer srv.Close()
client, err := openaicompat.New(llm.Config{
Provider: "openai", Model: "gpt-4",
APIKey: "test", BaseURL: srv.URL, Timeout: 5 * time.Second,
})
if err != nil {
t.Fatalf("New: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err != nil {
t.Fatalf("Complete: %v", err)
}
if err := client.Close(); err != nil {
t.Errorf("Close() = %v, want nil", err)
}
})
}
func TestBaseURLSchemeValidation(t *testing.T) {
tests := []struct {
name string
baseURL string
wantError bool
}{
{"https scheme works", "https://api.example.com", false},
{"http scheme works", "http://localhost:8080", false},
{"file scheme rejected", "file:///etc/passwd", true},
{"javascript scheme rejected", "javascript:alert(1)", true},
{"ftp scheme rejected", "ftp://example.com", true},
{"data scheme rejected", "data:text/html,<h1>hi</h1>", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := llm.Config{
Provider: "openai",
Model: "gpt-4",
APIKey: "test-key",
BaseURL: tt.baseURL,
MaxTokens: 100,
Timeout: 2 * time.Second,
}
client, err := openaicompat.New(cfg)
if err != nil {
// Construction error is fine for invalid schemes
if tt.wantError {
return
}
t.Fatalf("New() unexpected error: %v", err)
}
// Try a request — invalid schemes should fail at request creation
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if tt.wantError && err == nil {
t.Error("expected error for invalid URL scheme, got nil")
}
if !tt.wantError && err != nil {
// Connection errors are expected (no real server) — that's fine.
// We only care that http/https don't produce *scheme* errors.
errStr := err.Error()
if strings.Contains(errStr, "unsupported protocol") ||
strings.Contains(errStr, "invalid scheme") {
t.Errorf("unexpected scheme error for valid URL: %v", err)
}
}
})
}
}
// TestPerConfigErrorMessageLimit proves that Config.MaxErrorMessageLen is actually
// honored by the adapters. Regression test for the "dead config" bug where adapters
// ignored every per-Config safety limit and used package globals/constants instead.
// A server returns a 5000-byte error body; with MaxErrorMessageLen=100 the stored
// message must be far shorter than the 4096-byte default would have allowed.
func TestPerConfigErrorMessageLimit(t *testing.T) {
const bodyLen = 5000
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
if _, err := io.WriteString(w, strings.Repeat("E", bodyLen)); err != nil {
return
}
}))
defer srv.Close()
cfg := llm.Config{
Provider: "gemini",
Model: "gemini-2.5-flash",
APIKey: "test-key",
BaseURL: srv.URL,
MaxErrorMessageLen: 100, // far below DefaultMaxErrorMessageLen (4096)
}
client, err := gemini.New(cfg)
if err != nil {
t.Fatalf("gemini.New() error: %v", err)
}
_, err = client.Complete(context.Background(), llm.Request{
Messages: []llm.Message{llm.NewTextMessage(llm.RoleUser, "hi")},
})
if err == nil {
t.Fatal("expected error from 500 response")
}
var apiErr *llm.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("expected *llm.APIError, got %T", err)
}
// 100 chars + "... [truncated]" marker. If the per-Config limit were ignored,
// the default (4096) would yield a message ~40x longer than this.
const wantMax = 100 + len("... [truncated]")
if len(apiErr.Message) > wantMax {
t.Errorf("APIError.Message length = %d, want <= %d (per-Config MaxErrorMessageLen was ignored)", len(apiErr.Message), wantMax)
}
if len(apiErr.Message) < 100 {
t.Errorf("APIError.Message length = %d, want >= 100 (truncated too aggressively)", len(apiErr.Message))
}
}
// TestBlockPrivateBaseURL verifies the opt-in SSRF guard (F2): with
// BlockPrivateBaseURL set, construction rejects loopback/private/link-local hosts
// (incl. the cloud metadata IP) — while the default (opt-out) still allows them,
// so local providers keep working.
func TestBlockPrivateBaseURL(t *testing.T) {
cases := []struct {
name string
baseURL string
block bool
wantErr bool
}{
{"metadata IP blocked", "http://169.254.169.254/latest", true, true},
{"loopback blocked", "http://127.0.0.1:8080/v1", true, true},
{"localhost blocked", "http://localhost:11434/v1", true, true},
{"private 10.x blocked", "http://10.0.0.5/v1", true, true},
{"public host allowed", "https://api.example.com/v1", true, false},
{"default: metadata IP allowed (opt-out)", "http://169.254.169.254/latest", false, false},
{"empty base URL ok", "", true, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := llm.CheckBaseURL(llm.Config{BaseURL: tc.baseURL, BlockPrivateBaseURL: tc.block})
if tc.wantErr && err == nil {
t.Errorf("CheckBaseURL(%q, block=%v) = nil, want error", tc.baseURL, tc.block)
}
if !tc.wantErr && err != nil {
t.Errorf("CheckBaseURL(%q, block=%v) = %v, want nil", tc.baseURL, tc.block, err)
}
})
}
// Integration: NewClient must refuse a private BaseURL when blocking is on.
_, err := llm.NewClient(llm.Config{
Provider: "openai", Model: "gpt-4", APIKey: "k",
BaseURL: "http://169.254.169.254/v1", BlockPrivateBaseURL: true,
MaxTokens: 10,
})
if err == nil {
t.Error("NewClient with private BaseURL + BlockPrivateBaseURL should error")