Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/dcr_test.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package oauthex
6
7 import (
8 "context"
9 "encoding/json"
10 "io"
11 "net/http"
12 "net/http/httptest"
13 "os"
14 "path/filepath"
15 "strings"
16 "testing"
17 "time"
18
19 "github.com/google/go-cmp/cmp"
20 )
21
22 func TestClientRegistrationMetadataParse(t *testing.T) {
23 // Verify that we can parse a typical client metadata JSON.
24 data, err := os.ReadFile(filepath.FromSlash("testdata/client-auth-meta.json"))
25 if err != nil {
26 t.Fatal(err)
27 }
28 var a ClientRegistrationMetadata
29 if err := json.Unmarshal(data, &a); err != nil {
30 t.Fatal(err)
31 }
32 // Spot check
33 if g, w := a.ClientName, "My Test App"; g != w {
34 t.Errorf("got ClientName %q, want %q", g, w)
35 }
36 if g, w := len(a.RedirectURIs), 2; g != w {
37 t.Errorf("got %d RedirectURIs, want %d", g, w)
38 }
39 }
40
41 func TestRegisterClient(t *testing.T) {
42 testCases := []struct {
43 name string
44 handler http.HandlerFunc
45 clientMeta *ClientRegistrationMetadata
46 wantClientID string
47 wantErr string
48 }{
49 {
50 name: "Success",
51 handler: func(w http.ResponseWriter, r *http.Request) {
52 if r.Method != "POST" {
53 t.Errorf("Expected POST, got %s", r.Method)
54 }
55 body, err := io.ReadAll(r.Body)
56 if err != nil {
57 t.Fatal(err)
58 }
59 var receivedMeta ClientRegistrationMetadata
60 if err := json.Unmarshal(body, &receivedMeta); err != nil {
61 t.Fatalf("Failed to unmarshal request body: %v", err)
62 }
63 if receivedMeta.ClientName != "Test App" {
64 t.Errorf("Expected ClientName 'Test App', got '%s'", receivedMeta.ClientName)
65 }
66 w.Header().Set("Content-Type", "application/json")
67 w.WriteHeader(http.StatusCreated)
68 w.Write([]byte(`{"client_id":"test-client-id","client_secret":"test-client-secret","client_name":"Test App"}`))
69 },
70 clientMeta: &ClientRegistrationMetadata{ClientName: "Test App", RedirectURIs: []string{"http://localhost/cb"}},
71 wantClientID: "test-client-id",
72 },
73 {
74 name: "Success with 200",
75 handler: func(w http.ResponseWriter, r *http.Request) {
76 if r.Method != "POST" {
77 t.Errorf("Expected POST, got %s", r.Method)
78 }
79 body, err := io.ReadAll(r.Body)
80 if err != nil {
81 t.Fatal(err)
82 }
83 var receivedMeta ClientRegistrationMetadata
84 if err := json.Unmarshal(body, &receivedMeta); err != nil {
85 t.Fatalf("Failed to unmarshal request body: %v", err)
86 }
87 if receivedMeta.ClientName != "Test App" {
88 t.Errorf("Expected ClientName 'Test App', got '%s'", receivedMeta.ClientName)
89 }
90 w.Header().Set("Content-Type", "application/json")
91 w.WriteHeader(http.StatusOK)
92 w.Write([]byte(`{"client_id":"test-client-id","client_secret":"test-client-secret","client_name":"Test App"}`))
93 },
94 clientMeta: &ClientRegistrationMetadata{ClientName: "Test App", RedirectURIs: []string{"http://localhost/cb"}},
95 wantClientID: "test-client-id",
96 },
97 {
98 name: "Missing ClientID in Response",
99 handler: func(w http.ResponseWriter, r *http.Request) {
100 w.Header().Set("Content-Type", "application/json")
101 w.WriteHeader(http.StatusCreated)
102 w.Write([]byte(`{"client_secret":"test-client-secret"}`)) // No client_id
103 },
104 clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://localhost/cb"}},
105 wantErr: "registration response is missing required 'client_id' field",
106 },
107 {
108 name: "Standard OAuth Error",
109 handler: func(w http.ResponseWriter, r *http.Request) {
110 w.Header().Set("Content-Type", "application/json")
111 w.WriteHeader(http.StatusBadRequest)
112 w.Write([]byte(`{"error":"invalid_redirect_uri","error_description":"Redirect URI is not valid."}`))
113 },
114 clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://invalid/cb"}},
115 wantErr: "registration failed: invalid_redirect_uri (Redirect URI is not valid.)",
116 },
117 {
118 name: "Non-JSON Server Error",
119 handler: func(w http.ResponseWriter, r *http.Request) {
120 w.WriteHeader(http.StatusInternalServerError)
121 w.Write([]byte("Internal Server Error"))
122 },
123 clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://localhost/cb"}},
124 wantErr: "registration failed with status 500 Internal Server Error",
125 },
126 }
127
128 for _, tc := range testCases {
129 t.Run(tc.name, func(t *testing.T) {
130 server := httptest.NewServer(tc.handler)
131 defer server.Close()
132
133 info, err := RegisterClient(context.Background(), server.URL, tc.clientMeta, server.Client())
134
135 if tc.wantErr != "" {
136 if err == nil {
137 t.Fatalf("Expected an error containing '%s', but got nil", tc.wantErr)
138 }
139 if !strings.Contains(err.Error(), tc.wantErr) {
140 t.Errorf("Expected error to contain '%s', got '%v'", tc.wantErr, err)
141 }
142 return
143 }
144
145 if err != nil {
146 t.Fatalf("Expected no error, but got: %v", err)
147 }
148 if info.ClientID != tc.wantClientID {
149 t.Errorf("Expected client_id '%s', got '%s'", tc.wantClientID, info.ClientID)
150 }
151 })
152 }
153
154 t.Run("No Endpoint", func(t *testing.T) {
155 _, err := RegisterClient(context.Background(), "", &ClientRegistrationMetadata{}, nil)
156 if err == nil {
157 t.Fatal("Expected an error for missing registration endpoint, got nil")
158 }
159 expectedErr := "registration_endpoint is required"
160 if err.Error() != expectedErr {
161 t.Errorf("Expected error '%s', got '%v'", expectedErr, err)
162 }
163 })
164 }
165
166 func TestClientRegistrationResponseJSON(t *testing.T) {
167 testCases := []struct {
168 name string
169 in ClientRegistrationResponse
170 wantJSON string
171 }{
172 {
173 name: "full response",
174 in: ClientRegistrationResponse{
175 ClientID: "test-client-id",
176 ClientSecret: "test-client-secret",
177 ClientIDIssuedAt: time.Unix(1758840047, 0),
178 ClientSecretExpiresAt: time.Unix(1790376047, 0),
179 },
180 wantJSON: `{"client_id":"test-client-id","client_secret":"test-client-secret","client_id_issued_at":1758840047,"client_secret_expires_at":1790376047, "redirect_uris": null}`,
181 },
182 {
183 name: "minimal response with only required fields",
184 in: ClientRegistrationResponse{
185 ClientID: "test-client-id-minimal",
186 },
187 wantJSON: `{"client_id":"test-client-id-minimal", "redirect_uris":null}`,
188 },
189 {
190 name: "response with a secret that does not expire",
191 in: ClientRegistrationResponse{
192 ClientID: "test-client-id-no-expiry",
193 ClientSecret: "test-secret-no-expiry",
194 },
195 wantJSON: `{"client_id":"test-client-id-no-expiry","client_secret":"test-secret-no-expiry", "redirect_uris":null}`,
196 },
197 {
198 name: "unmarshal with zero timestamp",
199 in: ClientRegistrationResponse{ClientID: "client-id-zero"},
200 wantJSON: `{"client_id":"client-id-zero", "redirect_uris":null}`,
201 },
202 }
203
204 for _, tc := range testCases {
205 t.Run(tc.name, func(t *testing.T) {
206 // Test MarshalJSON
207 t.Run("marshal", func(t *testing.T) {
208 b, err := json.Marshal(&tc.in)
209 if err != nil {
210 t.Fatalf("Marshal() error = %v", err)
211 }
212
213 var gotMap, wantMap map[string]any
214 if err := json.Unmarshal(b, &gotMap); err != nil {
215 t.Fatalf("failed to unmarshal actual result: %v", err)
216 }
217 if err := json.Unmarshal([]byte(tc.wantJSON), &wantMap); err != nil {
218 t.Fatalf("failed to unmarshal expected result: %v", err)
219 }
220
221 if diff := cmp.Diff(wantMap, gotMap); diff != "" {
222 t.Errorf("Marshal() mismatch (-want +got):\n%s", diff)
223 }
224 })
225
226 // Test UnmarshalJSON
227 t.Run("unmarshal", func(t *testing.T) {
228 var got ClientRegistrationResponse
229 if err := json.Unmarshal([]byte(tc.wantJSON), &got); err != nil {
230 t.Fatalf("Unmarshal() error = %v", err)
231 }
232
233 if diff := cmp.Diff(tc.in, got); diff != "" {
234 t.Errorf("Unmarshal() mismatch (-want +got):\n%s", diff)
235 }
236 })
237 })
238 }
239 }