-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathoauth_test.go
More file actions
1308 lines (1096 loc) · 41.7 KB
/
Copy pathoauth_test.go
File metadata and controls
1308 lines (1096 loc) · 41.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
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 integration
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"os/exec"
"regexp"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// TestBasicOAuthFlow tests the basic OAuth server functionality
func TestBasicOAuthFlow(t *testing.T) {
// Start mcp-front with OAuth config
startMCPFront(t, "config/config.oauth-test.json",
"JWT_SECRET=test-jwt-secret-32-bytes-exactly!",
"ENCRYPTION_KEY=test-encryption-key-32-bytes-ok!",
"GOOGLE_CLIENT_ID=test-client-id-for-oauth",
"GOOGLE_CLIENT_SECRET=test-client-secret-for-oauth",
"MCP_FRONT_ENV=development",
"GOOGLE_OAUTH_AUTH_URL=http://localhost:9090/auth",
"GOOGLE_OAUTH_TOKEN_URL=http://localhost:9090/token",
"GOOGLE_USERINFO_URL=http://localhost:9090/userinfo",
)
// Wait for startup
waitForMCPFront(t)
// Test OAuth discovery
resp, err := http.Get("http://localhost:8080/.well-known/oauth-authorization-server")
require.NoError(t, err, "Failed to get OAuth discovery")
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode, "OAuth discovery failed")
var discovery map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&discovery)
require.NoError(t, err, "Failed to decode discovery")
// Verify required endpoints
requiredEndpoints := []string{
"issuer",
"authorization_endpoint",
"token_endpoint",
"registration_endpoint",
}
for _, endpoint := range requiredEndpoints {
_, ok := discovery[endpoint]
assert.True(t, ok, "Missing required endpoint: %s", endpoint)
}
// Verify client_secret_post is advertised
authMethods, ok := discovery["token_endpoint_auth_methods_supported"].([]interface{})
assert.True(t, ok, "token_endpoint_auth_methods_supported should be present")
var hasNone, hasClientSecretPost bool
for _, method := range authMethods {
if method == "none" {
hasNone = true
}
if method == "client_secret_post" {
hasClientSecretPost = true
}
}
assert.True(t, hasNone, "Should support 'none' auth method for public clients")
assert.True(t, hasClientSecretPost, "Should support 'client_secret_post' auth method for confidential clients")
}
// TestJWTSecretValidation tests JWT secret length requirements
func TestJWTSecretValidation(t *testing.T) {
tests := []struct {
name string
secret string
shouldFail bool
}{
{"Short 3-byte secret", "123", true},
{"Short 16-byte secret", "sixteen-byte-key", true},
{"Valid 32-byte secret", "demo-jwt-secret-32-bytes-exactly!", false},
{"Long 64-byte secret", "demo-jwt-secret-32-bytes-exactly!demo-jwt-secret-32-bytes-exactly!", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Start mcp-front with specific JWT secret
mcpCmd := exec.Command("../cmd/mcp-front/mcp-front", "-config", "config/config.oauth-test.json")
mcpCmd.Env = []string{
"PATH=" + os.Getenv("PATH"),
"JWT_SECRET=" + tt.secret,
"ENCRYPTION_KEY=test-encryption-key-32-bytes-ok!",
"GOOGLE_CLIENT_ID=test-client-id",
"GOOGLE_CLIENT_SECRET=test-client-secret",
"MCP_FRONT_ENV=development",
}
// Capture stderr
stderrPipe, _ := mcpCmd.StderrPipe()
scanner := bufio.NewScanner(stderrPipe)
if err := mcpCmd.Start(); err != nil {
t.Fatalf("Failed to start mcp-front: %v", err)
}
// Read stderr to check for errors
errorFound := false
go func() {
for scanner.Scan() {
line := scanner.Text()
if contains(line, "JWT secret must be at least") {
errorFound = true
}
}
}()
// Give it time to start or fail
time.Sleep(2 * time.Second)
// Check if it's running
healthy := checkHealth()
// Clean up
if mcpCmd.Process != nil {
_ = mcpCmd.Process.Kill()
_ = mcpCmd.Wait()
}
if tt.shouldFail {
assert.False(t, healthy && !errorFound, "Expected failure with short JWT secret but server started successfully")
} else {
assert.True(t, healthy, "Expected success with valid JWT secret but server failed to start")
}
})
}
}
// TestClientRegistration tests dynamic client registration (RFC 7591)
func TestClientRegistration(t *testing.T) {
// Start OAuth server
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": "development",
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 30) {
t.Fatal("OAuth server failed to start")
}
t.Run("PublicClientRegistration", func(t *testing.T) {
// Register a public client (no secret)
clientReq := map[string]interface{}{
"redirect_uris": []string{"http://127.0.0.1:6274/oauth/callback/debug"},
"scope": "read write",
}
body, _ := json.Marshal(clientReq)
resp, err := http.Post(
"http://localhost:8080/register",
"application/json",
bytes.NewBuffer(body),
)
if err != nil {
t.Fatalf("Failed to register client: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("Client registration failed with status %d: %s", resp.StatusCode, string(body))
}
var clientResp map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&clientResp); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Verify response
if clientResp["client_id"] == "" {
t.Error("Client ID should not be empty")
}
if clientResp["client_secret"] != nil {
t.Error("Public client should not have a secret")
}
if scope, ok := clientResp["scope"].(string); !ok || scope != "read write" {
t.Errorf("Expected scope 'read write' as string, got: %v", clientResp["scope"])
}
})
t.Run("MultipleRegistrations", func(t *testing.T) {
// Register multiple clients and verify they get different IDs
var clientIDs []string
for i := 0; i < 3; i++ {
clientReq := map[string]interface{}{
"redirect_uris": []string{fmt.Sprintf("http://example.com/callback%d", i)},
"scope": "read",
}
body, _ := json.Marshal(clientReq)
resp, err := http.Post(
"http://localhost:8080/register",
"application/json",
bytes.NewBuffer(body),
)
if err != nil {
t.Fatalf("Failed to register client %d: %v", i, err)
}
defer resp.Body.Close()
var clientResp map[string]interface{}
_ = json.NewDecoder(resp.Body).Decode(&clientResp)
clientIDs = append(clientIDs, clientResp["client_id"].(string))
}
// Verify all IDs are unique
for i := 0; i < len(clientIDs); i++ {
for j := i + 1; j < len(clientIDs); j++ {
if clientIDs[i] == clientIDs[j] {
t.Errorf("Client IDs should be unique, but got duplicate: %s", clientIDs[i])
}
}
}
})
t.Run("ConfidentialClientRegistration", func(t *testing.T) {
// Register a confidential client with client_secret_post
clientReq := map[string]interface{}{
"redirect_uris": []string{"https://example.com/callback"},
"scope": "read write",
"token_endpoint_auth_method": "client_secret_post",
}
body, _ := json.Marshal(clientReq)
resp, err := http.Post(
"http://localhost:8080/register",
"application/json",
bytes.NewBuffer(body),
)
if err != nil {
t.Fatalf("Failed to register confidential client: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("Confidential client registration failed with status %d: %s", resp.StatusCode, string(body))
}
var clientResp map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&clientResp); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Verify response includes client_secret
if clientResp["client_id"] == "" {
t.Error("Client ID should not be empty")
}
clientSecret, ok := clientResp["client_secret"].(string)
if !ok || clientSecret == "" {
t.Error("Confidential client should receive a client_secret")
}
// Verify secret has reasonable length (base64 of 32 bytes)
if len(clientSecret) < 40 {
t.Errorf("Client secret seems too short: %d chars", len(clientSecret))
}
tokenAuthMethod, ok := clientResp["token_endpoint_auth_method"].(string)
if !ok || tokenAuthMethod != "client_secret_post" {
t.Errorf("Expected token_endpoint_auth_method 'client_secret_post', got: %v", clientResp["token_endpoint_auth_method"])
}
// Verify scope is returned as string
if scope, ok := clientResp["scope"].(string); !ok || scope != "read write" {
t.Errorf("Expected scope 'read write' as string, got: %v", clientResp["scope"])
}
})
t.Run("PublicVsConfidentialClients", func(t *testing.T) {
// Test that public clients don't get secrets and confidential ones do
// First, create a public client
publicReq := map[string]interface{}{
"redirect_uris": []string{"https://public.example.com/callback"},
"scope": "read",
// No token_endpoint_auth_method specified - defaults to "none"
}
body, _ := json.Marshal(publicReq)
resp, err := http.Post(
"http://localhost:8080/register",
"application/json",
bytes.NewBuffer(body),
)
require.NoError(t, err)
defer resp.Body.Close()
var publicResp map[string]interface{}
_ = json.NewDecoder(resp.Body).Decode(&publicResp)
// Verify public client has no secret
if _, hasSecret := publicResp["client_secret"]; hasSecret {
t.Error("Public client should not have a secret")
}
if authMethod := publicResp["token_endpoint_auth_method"]; authMethod != "none" {
t.Errorf("Public client should have auth method 'none', got: %v", authMethod)
}
// Now create a confidential client
confidentialReq := map[string]interface{}{
"redirect_uris": []string{"https://confidential.example.com/callback"},
"scope": "read write",
"token_endpoint_auth_method": "client_secret_post",
}
body, _ = json.Marshal(confidentialReq)
resp, err = http.Post(
"http://localhost:8080/register",
"application/json",
bytes.NewBuffer(body),
)
require.NoError(t, err)
defer resp.Body.Close()
var confResp map[string]interface{}
_ = json.NewDecoder(resp.Body).Decode(&confResp)
// Verify confidential client has a secret
if secret, ok := confResp["client_secret"].(string); !ok || secret == "" {
t.Error("Confidential client should have a secret")
}
if authMethod := confResp["token_endpoint_auth_method"]; authMethod != "client_secret_post" {
t.Errorf("Confidential client should have auth method 'client_secret_post', got: %v", authMethod)
}
})
}
// TestUserTokenFlow tests the user token management functionality with browser-based SSO
// This test expects the /my/* routes to work with Google SSO (session-based auth),
// not Bearer token auth.
func TestUserTokenFlow(t *testing.T) {
// Start OAuth server with user token configuration
mcpCmd := startOAuthServerWithTokenConfig(t)
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 30) {
t.Fatal("Server failed to start")
}
// Create a client with cookie jar to simulate browser behavior
jar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// Allow up to 10 redirects
if len(via) >= 10 {
return fmt.Errorf("too many redirects")
}
return nil
},
}
t.Run("UnauthenticatedRedirectsToSSO", func(t *testing.T) {
// Create a client that doesn't follow redirects to test the initial redirect
noRedirectClient := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
// Try to access /my/tokens without authentication
resp, err := noRedirectClient.Get("http://localhost:8080/my/tokens")
require.NoError(t, err)
defer resp.Body.Close()
// Should get a redirect response
assert.Equal(t, http.StatusFound, resp.StatusCode, "Should get redirect status")
// Check the redirect location
location := resp.Header.Get("Location")
assert.Contains(t, location, "localhost:9090/auth", "Should redirect to Google OAuth")
assert.Contains(t, location, "client_id=", "Should include client_id")
assert.Contains(t, location, "redirect_uri=", "Should include redirect_uri")
// The state should be URL-encoded and include signed CSRF: "browser:nonce:signature:/my/tokens"
// Extract and validate the state parameter
parsedURL, err := url.Parse(location)
require.NoError(t, err)
stateParam := parsedURL.Query().Get("state")
require.NotEmpty(t, stateParam, "State parameter should be present")
// State format should be "browser:nonce:signature:returnURL"
assert.True(t, strings.HasPrefix(stateParam, "browser:"), "State should start with browser:")
parts := strings.SplitN(stateParam, ":", 4)
require.Len(t, parts, 4, "State should have 4 parts: browser:nonce:signature:url")
assert.Equal(t, "browser", parts[0], "First part should be 'browser'")
assert.NotEmpty(t, parts[1], "Nonce should not be empty")
assert.NotEmpty(t, parts[2], "Signature should not be empty")
assert.Equal(t, "/my/tokens", parts[3], "Return URL should be /my/tokens")
})
t.Run("AuthenticatedUserCanAccessTokens", func(t *testing.T) {
// The client with cookie jar will automatically follow the full SSO flow:
// 1. GET /my/tokens -> redirect to Google OAuth
// 2. Google OAuth redirects to /oauth/callback with code
// 3. Callback sets session cookie and redirects to /my/tokens
// 4. Client follows redirect with cookie and gets the page
resp, err := client.Get("http://localhost:8080/my/tokens")
require.NoError(t, err)
defer resp.Body.Close()
// After following all redirects, we should be at /my/tokens with 200 OK
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should access /my/tokens after SSO")
finalURL := resp.Request.URL.String()
assert.Contains(t, finalURL, "/my/tokens", "Should end up at /my/tokens after SSO")
// Read response body
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
bodyStr := string(body)
// Should show both services without tokens
assert.Contains(t, bodyStr, "Notion", "Expected Notion service in response")
assert.Contains(t, bodyStr, "GitHub", "Expected GitHub service in response")
})
t.Run("SetTokenWithValidation", func(t *testing.T) {
// Assume we're already authenticated from previous test
// Get CSRF token first
resp, err := client.Get("http://localhost:8080/my/tokens")
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
// Extract CSRF token from response
csrfToken := extractCSRFToken(t, string(body))
// Try to set invalid Notion token
form := url.Values{
"service": {"notion"},
"token": {"invalid-token"},
"csrf_token": {csrfToken},
}
req, _ := http.NewRequest("POST", "http://localhost:8080/my/tokens/set", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Use custom client that doesn't follow redirects for this test
noRedirectClient := &http.Client{
Jar: jar, // Use same cookie jar
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err = noRedirectClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
// Should redirect with error
assert.Equal(t, http.StatusSeeOther, resp.StatusCode, "Expected redirect")
location := resp.Header.Get("Location")
assert.Contains(t, location, "error", "Expected error in redirect")
// Get new CSRF token
resp, err = client.Get("http://localhost:8080/my/tokens")
require.NoError(t, err)
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
csrfToken = extractCSRFToken(t, string(body))
// Set valid Notion token (regex expects exactly 43 chars after "secret_")
form = url.Values{
"service": {"notion"},
"token": {"secret_1234567890123456789012345678901234567890123"},
"csrf_token": {csrfToken},
}
req, _ = http.NewRequest("POST", "http://localhost:8080/my/tokens/set", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err = noRedirectClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
// Should redirect with success
assert.Equal(t, http.StatusSeeOther, resp.StatusCode, "Expected redirect")
location = resp.Header.Get("Location")
assert.Contains(t, location, "success", "Expected success in redirect")
})
}
// TestStateParameterHandling tests OAuth state parameter requirements
func TestStateParameterHandling(t *testing.T) {
tests := []struct {
name string
environment string
state string
expectError bool
}{
{"Production without state", "production", "", true},
{"Production with state", "production", "secure-random-state", false},
{"Development without state", "development", "", false}, // Should auto-generate
{"Development with state", "development", "test-state", false},
}
for _, tt := range tests {
tt := tt // capture range variable
t.Run(tt.name, func(t *testing.T) {
// Start server with specific environment
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": tt.environment,
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 10) {
t.Fatal("Server failed to start")
}
// Register a client first
clientID := registerTestClient(t)
// Create authorization request
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {"http://127.0.0.1:6274/oauth/callback"},
"code_challenge": {"test-challenge"},
"code_challenge_method": {"S256"},
"scope": {"read write"},
}
if tt.state != "" {
params.Set("state", tt.state)
}
authURL := fmt.Sprintf("http://localhost:8080/authorize?%s", params.Encode())
// Use a client that doesn't follow redirects
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(authURL)
if err != nil {
t.Fatalf("Authorization request failed: %v", err)
}
defer resp.Body.Close()
if tt.expectError {
// OAuth errors are returned as redirects with error parameters
if resp.StatusCode == 302 || resp.StatusCode == 303 {
location := resp.Header.Get("Location")
if strings.Contains(location, "error=") {
} else {
t.Errorf("Expected error redirect for %s, got redirect without error", tt.name)
}
} else if resp.StatusCode >= 400 {
} else {
t.Errorf("Expected error for %s, got status %d", tt.name, resp.StatusCode)
}
} else {
if resp.StatusCode == 302 || resp.StatusCode == 303 {
location := resp.Header.Get("Location")
if strings.Contains(location, "error=") {
t.Errorf("Unexpected error redirect for %s: %s", tt.name, location)
}
} else if resp.StatusCode < 400 {
} else {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Expected success for %s, got status %d: %s", tt.name, resp.StatusCode, string(body))
}
}
})
}
}
// TestEnvironmentModes tests development vs production mode differences
func TestEnvironmentModes(t *testing.T) {
t.Run("DevelopmentMode", func(t *testing.T) {
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": "development",
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 30) {
t.Fatal("Server failed to start")
}
// In development mode, missing state should be auto-generated
clientID := registerTestClient(t)
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {"http://127.0.0.1:6274/oauth/callback"},
"code_challenge": {"test-challenge"},
"code_challenge_method": {"S256"},
"scope": {"read"},
// Intentionally omitting state parameter
}
// Use a client that doesn't follow redirects
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get("http://localhost:8080/authorize?" + params.Encode())
if err != nil {
t.Fatalf("Failed to make auth request: %v", err)
}
defer resp.Body.Close()
// Should redirect (302) not error
if resp.StatusCode >= 400 && resp.StatusCode != 302 {
t.Errorf("Development mode should handle missing state, got status %d", resp.StatusCode)
}
})
t.Run("ProductionMode", func(t *testing.T) {
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": "production",
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 30) {
t.Fatal("Server failed to start")
}
// In production mode, state should be required
clientID := registerTestClient(t)
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {"http://127.0.0.1:6274/oauth/callback"},
"code_challenge": {"test-challenge"},
"code_challenge_method": {"S256"},
"scope": {"read"},
// Intentionally omitting state parameter
}
// Use a client that doesn't follow redirects
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get("http://localhost:8080/authorize?" + params.Encode())
if err != nil {
t.Fatalf("Failed to make auth request: %v", err)
}
defer resp.Body.Close()
// Should error - OAuth errors are returned as redirects
if resp.StatusCode == 302 || resp.StatusCode == 303 {
location := resp.Header.Get("Location")
if strings.Contains(location, "error=") {
} else {
t.Errorf("Expected error redirect in production mode, got redirect without error")
}
} else if resp.StatusCode >= 400 {
} else {
t.Errorf("Production mode should require state parameter, got status %d", resp.StatusCode)
}
})
}
// TestOAuthEndpoints tests all OAuth endpoints comprehensively
func TestOAuthEndpoints(t *testing.T) {
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": "development",
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 10) {
t.Fatal("Server failed to start")
}
t.Run("Discovery", func(t *testing.T) {
resp, err := http.Get("http://localhost:8080/.well-known/oauth-authorization-server")
if err != nil {
t.Fatalf("Discovery request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("Discovery failed with status %d", resp.StatusCode)
}
var discovery map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&discovery); err != nil {
t.Fatalf("Failed to decode discovery response: %v", err)
}
// Verify all required fields
required := []string{
"issuer",
"authorization_endpoint",
"token_endpoint",
"registration_endpoint",
"response_types_supported",
"grant_types_supported",
"code_challenge_methods_supported",
}
for _, field := range required {
if _, ok := discovery[field]; !ok {
t.Errorf("Missing required discovery field: %s", field)
}
}
})
t.Run("HealthCheck", func(t *testing.T) {
resp, err := http.Get("http://localhost:8080/health")
if err != nil {
t.Fatalf("Health check failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("Health check should return 200, got %d", resp.StatusCode)
}
var health map[string]string
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
t.Fatalf("Failed to decode health response: %v", err)
}
if health["status"] != "ok" {
t.Errorf("Expected status 'ok', got '%s'", health["status"])
}
})
}
// TestCORSHeaders tests CORS headers for Claude.ai compatibility
func TestCORSHeaders(t *testing.T) {
mcpCmd := startOAuthServer(t, map[string]string{
"MCP_FRONT_ENV": "development",
})
defer stopServer(mcpCmd)
if !waitForHealthCheck(t, 10) {
t.Fatal("Server failed to start")
}
// Test preflight request
req, _ := http.NewRequest("OPTIONS", "http://localhost:8080/register", nil)
req.Header.Set("Origin", "https://claude.ai")
req.Header.Set("Access-Control-Request-Method", "POST")
req.Header.Set("Access-Control-Request-Headers", "content-type")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("Preflight request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("Preflight should return 200, got %d", resp.StatusCode)
}
// Check CORS headers
expectedHeaders := map[string]string{
"Access-Control-Allow-Origin": "https://claude.ai",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, Cache-Control, mcp-protocol-version",
}
for header, expected := range expectedHeaders {
actual := resp.Header.Get(header)
if actual != expected {
t.Errorf("Expected %s: '%s', got '%s'", header, expected, actual)
}
}
}
// TestToolAdvertisementWithUserTokens tests that tools are advertised even without user tokens
// but fail gracefully when invoked without the required token, and succeed with the token
func TestToolAdvertisementWithUserTokens(t *testing.T) {
// Start OAuth server with user token configuration
startMCPFront(t, "config/config.oauth-usertoken-tools-test.json",
"JWT_SECRET=demo-jwt-secret-32-bytes-exactly!",
"ENCRYPTION_KEY=test-encryption-key-32-bytes-ok!",
"GOOGLE_CLIENT_ID=test-client-id-oauth",
"GOOGLE_CLIENT_SECRET=test-client-secret-oauth",
"GOOGLE_OAUTH_AUTH_URL=http://localhost:9090/auth",
"GOOGLE_OAUTH_TOKEN_URL=http://localhost:9090/token",
"GOOGLE_USERINFO_URL=http://localhost:9090/userinfo",
"MCP_FRONT_ENV=development",
"LOG_LEVEL=debug",
)
if !waitForHealthCheck(t, 30) {
t.Fatal("Server failed to start")
}
// Complete OAuth flow to get a valid access token
accessToken := getOAuthAccessToken(t)
t.Run("ToolsAdvertisedWithoutToken", func(t *testing.T) {
// Create MCP client with OAuth token
mcpClient := NewMCPSSEClient("http://localhost:8080")
mcpClient.SetAuthToken(accessToken)
// Connect to postgres SSE endpoint
err := mcpClient.Connect()
require.NoError(t, err, "Should connect to postgres SSE endpoint without user token")
defer mcpClient.Close()
// Request tools list
toolsResp, err := mcpClient.SendMCPRequest("tools/list", map[string]interface{}{})
require.NoError(t, err, "Should list tools without user token")
// Verify we got tools
resultMap, ok := toolsResp["result"].(map[string]interface{})
require.True(t, ok, "Expected result in tools response")
tools, ok := resultMap["tools"].([]interface{})
require.True(t, ok, "Expected tools array in result")
assert.NotEmpty(t, tools, "Should have tools advertised")
// Check for common postgres tools
var toolNames []string
for _, tool := range tools {
if toolMap, ok := tool.(map[string]interface{}); ok {
if name, ok := toolMap["name"].(string); ok {
toolNames = append(toolNames, name)
}
}
}
assert.Contains(t, toolNames, "query", "Should have query tool")
t.Logf("Successfully advertised tools without user token: %v", toolNames)
})
t.Run("ToolInvocationFailsWithoutToken", func(t *testing.T) {
// Create MCP client with OAuth token
mcpClient := NewMCPSSEClient("http://localhost:8080")
mcpClient.SetAuthToken(accessToken)
// Connect to postgres SSE endpoint
err := mcpClient.Connect()
require.NoError(t, err)
defer mcpClient.Close()
// Try to invoke a tool without user token
queryParams := map[string]interface{}{
"name": "query",
"arguments": map[string]interface{}{
"sql": "SELECT 1",
},
}
result, err := mcpClient.SendMCPRequest("tools/call", queryParams)
require.NoError(t, err, "Should get response even without token")
// MCP protocol returns errors as successful responses with error content
require.NotNil(t, result["result"], "Should have result in response")
resultMap := result["result"].(map[string]interface{})
content := resultMap["content"].([]interface{})
require.NotEmpty(t, content, "Should have content in result")
contentItem := content[0].(map[string]interface{})
errorJSON := contentItem["text"].(string)
// Parse the error JSON
var errorData map[string]interface{}
err = json.Unmarshal([]byte(errorJSON), &errorData)
require.NoError(t, err, "Error should be valid JSON")
// Verify error structure
errorInfo := errorData["error"].(map[string]interface{})
assert.Equal(t, "token_required", errorInfo["code"], "Error code should be token_required")
errorMessage := errorInfo["message"].(string)
assert.Contains(t, errorMessage, "token required", "Error should mention token required")
assert.Contains(t, errorMessage, "/my/tokens", "Error should mention token setup URL")
assert.Contains(t, errorMessage, "Test Service", "Error should mention service name")
// Verify error data
errData := errorInfo["data"].(map[string]interface{})
assert.Equal(t, "postgres", errData["service"], "Should identify the service")
assert.Contains(t, errData["tokenSetupUrl"].(string), "/my/tokens", "Should include token setup URL")
// Verify instructions
instructions := errData["instructions"].(map[string]interface{})
assert.Contains(t, instructions["ai"].(string), "CRITICAL", "Should have AI instructions")
assert.Contains(t, instructions["human"].(string), "token required", "Should have human instructions")
})
t.Run("ToolInvocationSucceedsWithUserToken", func(t *testing.T) {
// Step 1: GET /my/tokens to extract CSRF token
jar, err := cookiejar.New(nil)
require.NoError(t, err)
client := &http.Client{
Jar: jar, // Need cookie jar for CSRF
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // Don't follow redirects
},
}
req, err := http.NewRequest("GET", "http://localhost:8080/my/tokens", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
// Check if we got the page or a redirect
if resp.StatusCode == 302 || resp.StatusCode == 303 {
// Follow the redirect
location := resp.Header.Get("Location")
t.Logf("Got redirect to: %s", location)
// Allow redirects for this request
client = &http.Client{
Jar: jar,
}
req, err = http.NewRequest("GET", "http://localhost:8080/my/tokens", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err = client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
}
require.Equal(t, 200, resp.StatusCode, "Should be able to access token page")
// Extract CSRF token from HTML
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
// Look for the CSRF token in the form
csrfRegex := regexp.MustCompile(`name="csrf_token" value="([^"]+)"`)
matches := csrfRegex.FindSubmatch(body)
require.Len(t, matches, 2, "Should find CSRF token in form")
csrfToken := string(matches[1])
// Step 2: POST to /my/tokens/set with test token
formData := url.Values{
"service": {"postgres"},
"token": {"test-user-token-12345"},
"csrf_token": {csrfToken},
}
req, err = http.NewRequest("POST", "http://localhost:8080/my/tokens/set", strings.NewReader(formData.Encode()))
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err = client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
// Check the response - it might be 200 if following redirects
if resp.StatusCode == 200 {
// That's fine, it means the token was set and we got the page back
t.Log("Token set successfully, got page response")
} else if resp.StatusCode == 302 || resp.StatusCode == 303 {
// Also fine, redirect means success
t.Log("Token set successfully, got redirect")
} else {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("Unexpected response setting token: status=%d, body=%s", resp.StatusCode, string(body))
}
// Step 3: Now test tool invocation with the token
mcpClient := NewMCPSSEClient("http://localhost:8080")
mcpClient.SetAuthToken(accessToken)
err = mcpClient.Connect()
require.NoError(t, err, "Should connect to postgres SSE endpoint")
defer mcpClient.Close()