-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathhttp_helpers_test.go
More file actions
867 lines (783 loc) · 25.7 KB
/
http_helpers_test.go
File metadata and controls
867 lines (783 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
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
package server
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/github/gh-aw-mcpg/internal/config"
"github.com/github/gh-aw-mcpg/internal/guard"
"github.com/github/gh-aw-mcpg/internal/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestSetupSessionCallback tests the setupSessionCallback helper function which
// combines session extraction, logging, and context injection into one call.
func TestSetupSessionCallback(t *testing.T) {
tests := []struct {
name string
authHeader string
backendID string
requestMethod string
requestBody string
expectOK bool
expectedSession string
expectBackendInCtx bool
}{
{
name: "routed mode - valid session with backendID",
authHeader: "my-api-key",
backendID: "github",
requestMethod: "POST",
requestBody: `{"method":"initialize"}`,
expectOK: true,
expectedSession: "my-api-key",
expectBackendInCtx: true,
},
{
name: "unified mode - valid session without backendID",
authHeader: "my-api-key",
backendID: "",
requestMethod: "POST",
requestBody: `{"method":"tools/call"}`,
expectOK: true,
expectedSession: "my-api-key",
expectBackendInCtx: false,
},
{
name: "missing Authorization header - rejected",
authHeader: "",
backendID: "github",
requestMethod: "POST",
requestBody: "",
expectOK: false,
expectedSession: "",
expectBackendInCtx: false,
},
{
name: "Bearer token - valid session",
authHeader: "Bearer session-token-123",
backendID: "slack",
requestMethod: "GET",
requestBody: "",
expectOK: true,
expectedSession: "session-token-123",
expectBackendInCtx: true,
},
{
name: "routed mode - POST with no body",
authHeader: "session-xyz",
backendID: "backend-1",
requestMethod: "POST",
requestBody: "",
expectOK: true,
expectedSession: "session-xyz",
expectBackendInCtx: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var req *http.Request
if tt.requestBody != "" {
req = httptest.NewRequest(tt.requestMethod, "/mcp", bytes.NewBufferString(tt.requestBody))
} else {
req = httptest.NewRequest(tt.requestMethod, "/mcp", nil)
}
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
sessionID, ok := setupSessionCallback(req, tt.backendID)
assert.Equal(t, tt.expectOK, ok, "ok flag should match expected")
assert.Equal(t, tt.expectedSession, sessionID, "returned session ID should match")
if tt.expectOK {
// Verify context was injected into req (pointer mutation via *r = *...)
ctxSessionID := req.Context().Value(SessionIDContextKey)
require.NotNil(t, ctxSessionID, "session ID should be in request context")
assert.Equal(t, tt.expectedSession, ctxSessionID, "context session ID should match")
if tt.expectBackendInCtx {
ctxBackendID := req.Context().Value(mcp.ContextKey("backend-id"))
require.NotNil(t, ctxBackendID, "backend ID should be in context for routed mode")
assert.Equal(t, tt.backendID, ctxBackendID, "context backend ID should match")
} else {
ctxBackendID := req.Context().Value(mcp.ContextKey("backend-id"))
assert.Nil(t, ctxBackendID, "backend ID should not be in context for unified mode")
}
// Verify body is still readable after logging (body restoration)
if tt.requestBody != "" && tt.requestMethod == "POST" {
bodyBytes, err := io.ReadAll(req.Body)
require.NoError(t, err, "body should be readable after setupSessionCallback")
assert.Equal(t, tt.requestBody, string(bodyBytes), "body content should be preserved")
}
}
})
}
}
// TestSetupSessionCallback_MutatesRequest verifies that setupSessionCallback
// mutates the request in-place via pointer dereference (*r = *...).
func TestSetupSessionCallback_MutatesRequest(t *testing.T) {
req := httptest.NewRequest("POST", "/mcp", nil)
req.Header.Set("Authorization", "my-session-id")
// Verify context does not have session ID before call
assert.Nil(t, req.Context().Value(SessionIDContextKey), "context should be empty before call")
sessionID, ok := setupSessionCallback(req, "backend-a")
require.True(t, ok, "call should succeed")
assert.Equal(t, "my-session-id", sessionID, "returned session ID should match")
// After the call, the request should have been mutated in-place
ctxSessionID := req.Context().Value(SessionIDContextKey)
assert.Equal(t, "my-session-id", ctxSessionID, "request context should be mutated in-place")
}
// TestWithResponseLogging tests the withResponseLogging middleware which wraps
// an http.Handler to log response bodies.
func TestWithResponseLogging(t *testing.T) {
tests := []struct {
name string
responseBody string
statusCode int
expectBody string
expectStatus int
}{
{
name: "response with body is passed through",
responseBody: `{"result":"ok"}`,
statusCode: http.StatusOK,
expectBody: `{"result":"ok"}`,
expectStatus: http.StatusOK,
},
{
name: "empty response body",
responseBody: "",
statusCode: http.StatusOK,
expectBody: "",
expectStatus: http.StatusOK,
},
{
name: "error response is passed through",
responseBody: `{"error":"not found"}`,
statusCode: http.StatusNotFound,
expectBody: `{"error":"not found"}`,
expectStatus: http.StatusNotFound,
},
{
name: "large response body is passed through",
responseBody: `{"items":[1,2,3,4,5,6,7,8,9,10]}`,
statusCode: http.StatusOK,
expectBody: `{"items":[1,2,3,4,5,6,7,8,9,10]}`,
expectStatus: http.StatusOK,
},
{
name: "server error response",
responseBody: "Internal Server Error",
statusCode: http.StatusInternalServerError,
expectBody: "Internal Server Error",
expectStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
innerCalled := false
innerHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
innerCalled = true
w.WriteHeader(tt.statusCode)
if tt.responseBody != "" {
w.Write([]byte(tt.responseBody))
}
})
wrappedHandler := withResponseLogging(innerHandler)
req := httptest.NewRequest("GET", "/test", nil)
req.RemoteAddr = "127.0.0.1:12345"
w := httptest.NewRecorder()
wrappedHandler.ServeHTTP(w, req)
assert.True(t, innerCalled, "inner handler should be called")
assert.Equal(t, tt.expectStatus, w.Code, "status code should be passed through")
if tt.expectBody != "" {
assert.Equal(t, tt.expectBody, w.Body.String(), "response body should be passed through")
}
})
}
}
// TestWithResponseLogging_PreservesHeaders verifies that withResponseLogging
// does not interfere with response headers set by the inner handler.
func TestWithResponseLogging_PreservesHeaders(t *testing.T) {
innerHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Custom-Header", "test-value")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"ok":true}`))
})
wrappedHandler := withResponseLogging(innerHandler)
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
wrappedHandler.ServeHTTP(w, req)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"), "Content-Type header should be preserved")
assert.Equal(t, "test-value", w.Header().Get("X-Custom-Header"), "custom header should be preserved")
assert.Equal(t, http.StatusOK, w.Code, "status code should be preserved")
assert.Equal(t, `{"ok":true}`, w.Body.String(), "response body should be preserved")
}
// TestWithResponseLogging_ReturnsHTTPHandler verifies the return type.
func TestWithResponseLogging_ReturnsHTTPHandler(t *testing.T) {
innerHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
wrapped := withResponseLogging(innerHandler)
assert.Implements(t, (*http.Handler)(nil), wrapped, "should return an http.Handler")
}
func TestExtractAndValidateSession(t *testing.T) {
tests := []struct {
name string
authHeader string
expectedID string
shouldBeEmpty bool
}{
{
name: "Valid plain API key",
authHeader: "test-session-123",
expectedID: "test-session-123",
shouldBeEmpty: false,
},
{
name: "Valid Bearer token",
authHeader: "Bearer my-token-456",
expectedID: "my-token-456",
shouldBeEmpty: false,
},
{
name: "Empty Authorization header",
authHeader: "",
expectedID: "",
shouldBeEmpty: true,
},
{
name: "Whitespace only header",
authHeader: " ",
expectedID: " ",
shouldBeEmpty: false,
},
{
name: "Long session ID",
authHeader: "very-long-session-id-with-many-characters-1234567890",
expectedID: "very-long-session-id-with-many-characters-1234567890",
shouldBeEmpty: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "/mcp", nil)
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
sessionID := extractAndValidateSession(req)
if tt.shouldBeEmpty {
assert.Empty(t, sessionID, "Expected empty session ID")
} else {
assert.Equal(t, tt.expectedID, sessionID, "Session ID mismatch")
}
})
}
}
func TestLogHTTPRequestBody(t *testing.T) {
tests := []struct {
name string
method string
body string
sessionID string
backendID string
shouldLog bool
}{
{
name: "POST request with body and backend",
method: "POST",
body: `{"method":"initialize"}`,
sessionID: "session-123",
backendID: "backend-1",
shouldLog: true,
},
{
name: "POST request with body without backend",
method: "POST",
body: `{"method":"tools/call"}`,
sessionID: "session-456",
backendID: "",
shouldLog: true,
},
{
name: "GET request (no body logging)",
method: "GET",
body: "",
sessionID: "session-789",
backendID: "backend-2",
shouldLog: false,
},
{
name: "POST request with empty body",
method: "POST",
body: "",
sessionID: "session-abc",
backendID: "backend-3",
shouldLog: false,
},
{
name: "POST request with nil body",
method: "POST",
body: "",
sessionID: "session-def",
backendID: "",
shouldLog: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var req *http.Request
if tt.body != "" {
req = httptest.NewRequest(tt.method, "/mcp", bytes.NewBufferString(tt.body))
} else if tt.method == "POST" {
req = httptest.NewRequest(tt.method, "/mcp", nil)
} else {
req = httptest.NewRequest(tt.method, "/mcp", nil)
}
// Call the function
logHTTPRequestBody(req, tt.sessionID, tt.backendID)
// Verify body can still be read after logging
if tt.body != "" {
bodyBytes, err := io.ReadAll(req.Body)
require.NoError(t, err, "Should be able to read body after logging")
assert.Equal(t, tt.body, string(bodyBytes), "Body content should be preserved")
}
})
}
}
func TestInjectSessionContext(t *testing.T) {
tests := []struct {
name string
sessionID string
backendID string
expectBackendID bool
}{
{
name: "Inject session and backend ID (routed mode)",
sessionID: "session-123",
backendID: "github",
expectBackendID: true,
},
{
name: "Inject session ID only (unified mode)",
sessionID: "session-456",
backendID: "",
expectBackendID: false,
},
{
name: "Long session ID with backend",
sessionID: "very-long-session-id-1234567890",
backendID: "slack",
expectBackendID: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "/mcp", nil)
// Inject context
modifiedReq := injectSessionContext(req, tt.sessionID, tt.backendID)
// Verify session ID is in context
sessionIDFromCtx := modifiedReq.Context().Value(SessionIDContextKey)
require.NotNil(t, sessionIDFromCtx, "Session ID should be in context")
assert.Equal(t, tt.sessionID, sessionIDFromCtx, "Session ID mismatch")
// Verify DIFC agent ID is synchronized with session ID
agentIDFromCtx := guard.GetAgentIDFromContext(modifiedReq.Context())
assert.Equal(t, tt.sessionID, agentIDFromCtx, "Agent ID should match session ID")
// Verify backend ID if expected
if tt.expectBackendID {
backendIDFromCtx := modifiedReq.Context().Value(mcp.ContextKey("backend-id"))
require.NotNil(t, backendIDFromCtx, "Backend ID should be in context")
assert.Equal(t, tt.backendID, backendIDFromCtx, "Backend ID mismatch")
} else {
backendIDFromCtx := modifiedReq.Context().Value(mcp.ContextKey("backend-id"))
assert.Nil(t, backendIDFromCtx, "Backend ID should not be in context for unified mode")
}
// Verify original request is not modified
originalSessionID := req.Context().Value(SessionIDContextKey)
assert.Nil(t, originalSessionID, "Original request context should not be modified")
})
}
}
// testContextKey is a custom type for context keys to avoid collisions
type testContextKey string
func TestInjectSessionContext_PreservesExistingContext(t *testing.T) {
// Create a request with existing context values
req := httptest.NewRequest("POST", "/mcp", nil)
ctx := context.WithValue(req.Context(), testContextKey("existing-key"), "existing-value")
req = req.WithContext(ctx)
// Inject session context
modifiedReq := injectSessionContext(req, "session-123", "backend-1")
// Verify both values are present
sessionID := modifiedReq.Context().Value(SessionIDContextKey)
assert.Equal(t, "session-123", sessionID, "Session ID should be present")
agentID := guard.GetAgentIDFromContext(modifiedReq.Context())
assert.Equal(t, "session-123", agentID, "Agent ID should match session ID")
backendID := modifiedReq.Context().Value(mcp.ContextKey("backend-id"))
assert.Equal(t, "backend-1", backendID, "Backend ID should be present")
existingValue := modifiedReq.Context().Value(testContextKey("existing-key"))
assert.Equal(t, "existing-value", existingValue, "Existing context value should be preserved")
}
// TestWrapWithMiddleware tests the wrapWithMiddleware helper function
func TestWrapWithMiddleware(t *testing.T) {
tests := []struct {
name string
apiKey string
authHeader string
shutdown bool
expectStatusCode int
expectNextCalled bool
expectErrorMessage string
}{
{
name: "NoAuth_NotShutdown_Success",
apiKey: "",
authHeader: "",
shutdown: false,
expectStatusCode: http.StatusOK,
expectNextCalled: true,
},
{
name: "WithAuth_ValidKey_Success",
apiKey: "test-key",
authHeader: "test-key",
shutdown: false,
expectStatusCode: http.StatusOK,
expectNextCalled: true,
},
{
name: "WithAuth_InvalidKey_Unauthorized",
apiKey: "test-key",
authHeader: "wrong-key",
shutdown: false,
expectStatusCode: http.StatusUnauthorized,
expectNextCalled: false,
expectErrorMessage: "unauthorized",
},
{
name: "WithAuth_MissingKey_Unauthorized",
apiKey: "test-key",
authHeader: "",
shutdown: false,
expectStatusCode: http.StatusUnauthorized,
expectNextCalled: false,
expectErrorMessage: "unauthorized",
},
{
name: "Shutdown_RejectsRequest",
apiKey: "",
authHeader: "",
shutdown: true,
expectStatusCode: http.StatusServiceUnavailable,
expectNextCalled: false,
expectErrorMessage: "Gateway is shutting down",
},
{
name: "Shutdown_WithAuth_StillRejects",
apiKey: "test-key",
authHeader: "test-key",
shutdown: true,
expectStatusCode: http.StatusServiceUnavailable,
expectNextCalled: false,
expectErrorMessage: "Gateway is shutting down",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create minimal unified server
ctx := context.Background()
cfg := &config.Config{
Servers: map[string]*config.ServerConfig{},
}
us, err := NewUnified(ctx, cfg)
require.NoError(t, err)
defer us.Close()
// Set test mode to prevent os.Exit()
us.SetTestMode(true)
// Trigger shutdown if needed
if tt.shutdown {
us.InitiateShutdown()
}
// Track whether the next handler was called
nextCalled := false
mockHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
// Wrap with middleware
finalHandler := wrapWithMiddleware(mockHandler, "test", us, tt.apiKey)
// Create test request
req := httptest.NewRequest("GET", "/test", nil)
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
w := httptest.NewRecorder()
// Execute request
finalHandler(w, req)
// Verify status code
assert.Equal(t, tt.expectStatusCode, w.Code, "Status code should match")
// Verify next handler was called (or not)
assert.Equal(t, tt.expectNextCalled, nextCalled, "Next handler call status should match")
// Verify error message if expected
if tt.expectErrorMessage != "" {
assert.Contains(t, w.Body.String(), tt.expectErrorMessage, "Response should contain expected error message")
}
})
}
}
// TestWrapWithMiddleware_MiddlewareOrder tests that middleware is applied in correct order
func TestWrapWithMiddleware_MiddlewareOrder(t *testing.T) {
// Create minimal unified server
ctx := context.Background()
cfg := &config.Config{
Servers: map[string]*config.ServerConfig{},
}
us, err := NewUnified(ctx, cfg)
require.NoError(t, err)
defer us.Close()
// Set test mode
us.SetTestMode(true)
// Test that shutdown check happens before auth
// This is important per spec 5.1.3
us.InitiateShutdown()
// Create mock handler
mockHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Wrap with middleware that requires auth
finalHandler := wrapWithMiddleware(mockHandler, "test", us, "test-key")
// Create request with valid auth
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("Authorization", "test-key")
w := httptest.NewRecorder()
// Execute request
finalHandler(w, req)
// Should return 503 (shutdown) not 200 (success)
// This proves shutdown check happens before auth
assert.Equal(t, http.StatusServiceUnavailable, w.Code, "Shutdown should take precedence over auth")
assert.Contains(t, w.Body.String(), "Gateway is shutting down", "Should contain shutdown error message")
}
// TestWrapWithMiddleware_LogTagVariations tests different log tag formats
func TestWrapWithMiddleware_LogTagVariations(t *testing.T) {
tests := []struct {
name string
logTag string
}{
{
name: "Unified mode tag",
logTag: "unified",
},
{
name: "Routed mode tag with backend",
logTag: "routed:github",
},
{
name: "Routed mode tag with another backend",
logTag: "routed:slack",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create minimal unified server
ctx := context.Background()
cfg := &config.Config{
Servers: map[string]*config.ServerConfig{},
}
us, err := NewUnified(ctx, cfg)
require.NoError(t, err)
defer us.Close()
// Create mock handler
mockHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Should not panic with any log tag
assert.NotPanics(t, func() {
finalHandler := wrapWithMiddleware(mockHandler, tt.logTag, us, "")
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
finalHandler(w, req)
}, "wrapWithMiddleware should not panic with log tag: %s", tt.logTag)
})
}
}
// TestLogRuntimeError tests the logRuntimeError function.
func TestLogRuntimeError(t *testing.T) {
tests := []struct {
name string
errorType string
detail string
requestID string
serverName *string
path string
method string
}{
{
name: "BasicError",
errorType: "authentication_failed",
detail: "missing_auth_header",
requestID: "req-123",
serverName: nil,
path: "/api/test",
method: "GET",
},
{
name: "ErrorWithServerName",
errorType: "backend_error",
detail: "connection_failed",
requestID: "req-456",
serverName: stringPtr("test-server"),
path: "/mcp/test",
method: "POST",
},
{
name: "ErrorWithoutRequestID",
errorType: "validation_error",
detail: "invalid_input",
requestID: "",
serverName: nil,
path: "/health",
method: "GET",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(tt.method, tt.path, nil)
if tt.requestID != "" {
req.Header.Set("X-Request-ID", tt.requestID)
}
assert.NotPanics(t, func() {
logRuntimeError(tt.errorType, tt.detail, req, tt.serverName)
}, "logRuntimeError should not panic")
})
}
}
// stringPtr returns a pointer to s. Used as a helper in tests.
func stringPtr(s string) *string {
return &s
}
// TestWriteErrorResponse verifies that writeErrorResponse writes a JSON error
// body with "error" and "message" fields and the correct status code and Content-Type.
func TestWriteErrorResponse(t *testing.T) {
tests := []struct {
name string
statusCode int
code string
message string
}{
{
name: "400 bad request",
statusCode: http.StatusBadRequest,
code: "bad_request",
message: "the request body is malformed",
},
{
name: "401 unauthorized",
statusCode: http.StatusUnauthorized,
code: "unauthorized",
message: "invalid API key",
},
{
name: "403 forbidden",
statusCode: http.StatusForbidden,
code: "forbidden",
message: "access denied",
},
{
name: "404 not found",
statusCode: http.StatusNotFound,
code: "not_found",
message: "the requested resource does not exist",
},
{
name: "500 internal server error",
statusCode: http.StatusInternalServerError,
code: "internal_error",
message: "an unexpected error occurred",
},
{
name: "503 service unavailable",
statusCode: http.StatusServiceUnavailable,
code: "service_unavailable",
message: "the gateway is shutting down",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
writeErrorResponse(w, tt.statusCode, tt.code, tt.message)
assert.Equal(t, tt.statusCode, w.Code, "status code should match")
assert.Equal(t, "application/json", w.Header().Get("Content-Type"), "Content-Type should be application/json")
var body map[string]string
err := json.NewDecoder(w.Body).Decode(&body)
require.NoError(t, err, "response body should be valid JSON")
assert.Equal(t, tt.code, body["error"], "response body 'error' field should match code")
assert.Equal(t, tt.message, body["message"], "response body 'message' field should match message")
})
}
}
// TestRejectRequest verifies that rejectRequest writes the correct HTTP error
// response and does not panic for a variety of status codes and messages.
func TestRejectRequest(t *testing.T) {
tests := []struct {
name string
status int
code string
msg string
logCategory string
runtimeErrType string
runtimeDetail string
path string
method string
}{
{
name: "401 missing auth header",
status: http.StatusUnauthorized,
code: "unauthorized",
msg: "missing Authorization header",
logCategory: "auth",
runtimeErrType: "authentication_failed",
runtimeDetail: "missing_auth_header",
path: "/mcp",
method: "GET",
},
{
name: "401 invalid api key",
status: http.StatusUnauthorized,
code: "unauthorized",
msg: "invalid API key",
logCategory: "auth",
runtimeErrType: "authentication_failed",
runtimeDetail: "invalid_api_key",
path: "/mcp/github",
method: "POST",
},
{
name: "503 shutdown",
status: http.StatusServiceUnavailable,
code: "service_unavailable",
msg: "Gateway is shutting down",
logCategory: "gateway",
runtimeErrType: "shutdown",
runtimeDetail: "shutdown_in_progress",
path: "/mcp",
method: "POST",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(tt.method, tt.path, nil)
assert.NotPanics(t, func() {
rejectRequest(w, r, tt.status, tt.code, tt.msg, tt.logCategory, tt.runtimeErrType, tt.runtimeDetail)
})
assert.Equal(t, tt.status, w.Code, "status code should match")
assert.Equal(t, "application/json", w.Header().Get("Content-Type"), "Content-Type should be application/json")
var body map[string]string
err := json.NewDecoder(w.Body).Decode(&body)
require.NoError(t, err, "response body should be valid JSON")
assert.Equal(t, tt.code, body["error"], "response body 'error' field should match code")
assert.Equal(t, tt.msg, body["message"], "response body 'message' field should match msg")
})
}
}