Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/dcr.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 // This file implements Authorization Server Metadata.
6 // See https://www.rfc-editor.org/rfc/rfc8414.html.
7
8 package oauthex
9
10 import (
11 "bytes"
12 "context"
13 "encoding/json"
14 "fmt"
15 "io"
16 "net/http"
17 "time"
18
19 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
20 )
21
22 // ClientRegistrationMetadata represents the client metadata fields for the DCR POST request (RFC 7591).
23 //
24 // Note: URL fields in this struct are validated by validateClientRegistrationURLs
25 // to prevent XSS attacks. If you add a new URL field, you must also add it to
26 // that function.
27 type ClientRegistrationMetadata struct {
28 // RedirectURIs is a REQUIRED JSON array of redirection URI strings for use in
29 // redirect-based flows (such as the authorization code grant).
30 RedirectURIs []string `json:"redirect_uris"`
31
32 // TokenEndpointAuthMethod is an OPTIONAL string indicator of the requested
33 // authentication method for the token endpoint.
34 // If omitted, the default is "client_secret_basic".
35 TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
36
37 // GrantTypes is an OPTIONAL JSON array of OAuth 2.0 grant type strings
38 // that the client will restrict itself to using.
39 // If omitted, the default is ["authorization_code"].
40 GrantTypes []string `json:"grant_types,omitempty"`
41
42 // ResponseTypes is an OPTIONAL JSON array of OAuth 2.0 response type strings
43 // that the client will restrict itself to using.
44 // If omitted, the default is ["code"].
45 ResponseTypes []string `json:"response_types,omitempty"`
46
47 // ClientName is a RECOMMENDED human-readable name of the client to be presented
48 // to the end-user.
49 ClientName string `json:"client_name,omitempty"`
50
51 // ClientURI is a RECOMMENDED URL of a web page providing information about the client.
52 ClientURI string `json:"client_uri,omitempty"`
53
54 // LogoURI is an OPTIONAL URL of a logo for the client, which may be displayed
55 // to the end-user.
56 LogoURI string `json:"logo_uri,omitempty"`
57
58 // Scope is an OPTIONAL string containing a space-separated list of scope values
59 // that the client will restrict itself to using.
60 Scope string `json:"scope,omitempty"`
61
62 // Contacts is an OPTIONAL JSON array of strings representing ways to contact
63 // people responsible for this client (e.g., email addresses).
64 Contacts []string `json:"contacts,omitempty"`
65
66 // TOSURI is an OPTIONAL URL that the client provides to the end-user
67 // to read about the client's terms of service.
68 TOSURI string `json:"tos_uri,omitempty"`
69
70 // PolicyURI is an OPTIONAL URL that the client provides to the end-user
71 // to read about the client's privacy policy.
72 PolicyURI string `json:"policy_uri,omitempty"`
73
74 // JWKSURI is an OPTIONAL URL for the client's JSON Web Key Set [JWK] document.
75 // This is preferred over the 'jwks' parameter.
76 JWKSURI string `json:"jwks_uri,omitempty"`
77
78 // JWKS is an OPTIONAL client's JSON Web Key Set [JWK] document, passed by value.
79 // This is an alternative to providing a JWKSURI.
80 JWKS string `json:"jwks,omitempty"`
81
82 // SoftwareID is an OPTIONAL unique identifier string for the client software,
83 // constant across all instances and versions.
84 SoftwareID string `json:"software_id,omitempty"`
85
86 // SoftwareVersion is an OPTIONAL version identifier string for the client software.
87 SoftwareVersion string `json:"software_version,omitempty"`
88
89 // SoftwareStatement is an OPTIONAL JWT that asserts client metadata values.
90 // Values in the software statement take precedence over other metadata values.
91 SoftwareStatement string `json:"software_statement,omitempty"`
92
93 // ApplicationType is an OPTIONAL string that indicates the type of application.
94 // Valid values are "native" and "web".
95 // If omitted, OIDC-compliant authorization servers default to "web".
96 ApplicationType string `json:"application_type,omitempty"`
97 }
98
99 // ClientRegistrationResponse represents the fields returned by the Authorization Server
100 // (RFC 7591, Section 3.2.1 and 3.2.2).
101 type ClientRegistrationResponse struct {
102 // ClientRegistrationMetadata contains all registered client metadata, returned by the
103 // server on success, potentially with modified or defaulted values.
104 ClientRegistrationMetadata
105
106 // ClientID is the REQUIRED newly issued OAuth 2.0 client identifier.
107 ClientID string `json:"client_id"`
108
109 // ClientSecret is an OPTIONAL client secret string.
110 ClientSecret string `json:"client_secret,omitempty"`
111
112 // ClientIDIssuedAt is an OPTIONAL Unix timestamp when the ClientID was issued.
113 ClientIDIssuedAt time.Time `json:"client_id_issued_at,omitempty"`
114
115 // ClientSecretExpiresAt is the REQUIRED (if client_secret is issued) Unix
116 // timestamp when the secret expires, or 0 if it never expires.
117 ClientSecretExpiresAt time.Time `json:"client_secret_expires_at,omitempty"`
118 }
119
120 func (r *ClientRegistrationResponse) MarshalJSON() ([]byte, error) {
121 type alias ClientRegistrationResponse
122 var clientIDIssuedAt int64
123 var clientSecretExpiresAt int64
124
125 if !r.ClientIDIssuedAt.IsZero() {
126 clientIDIssuedAt = r.ClientIDIssuedAt.Unix()
127 }
128 if !r.ClientSecretExpiresAt.IsZero() {
129 clientSecretExpiresAt = r.ClientSecretExpiresAt.Unix()
130 }
131
132 return json.Marshal(&struct {
133 ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
134 ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
135 *alias
136 }{
137 ClientIDIssuedAt: clientIDIssuedAt,
138 ClientSecretExpiresAt: clientSecretExpiresAt,
139 alias: (*alias)(r),
140 })
141 }
142
143 func (r *ClientRegistrationResponse) UnmarshalJSON(data []byte) error {
144 type alias ClientRegistrationResponse
145 aux := &struct {
146 ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
147 ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
148 *alias
149 }{
150 alias: (*alias)(r),
151 }
152 if err := internaljson.Unmarshal(data, &aux); err != nil {
153 return err
154 }
155 if aux.ClientIDIssuedAt != 0 {
156 r.ClientIDIssuedAt = time.Unix(aux.ClientIDIssuedAt, 0)
157 }
158 if aux.ClientSecretExpiresAt != 0 {
159 r.ClientSecretExpiresAt = time.Unix(aux.ClientSecretExpiresAt, 0)
160 }
161 return nil
162 }
163
164 // ClientRegistrationError is the error response from the Authorization Server
165 // for a failed registration attempt (RFC 7591, Section 3.2.2).
166 type ClientRegistrationError struct {
167 // ErrorCode is the REQUIRED error code if registration failed (RFC 7591, 3.2.2).
168 ErrorCode string `json:"error"`
169
170 // ErrorDescription is an OPTIONAL human-readable error message.
171 ErrorDescription string `json:"error_description,omitempty"`
172 }
173
174 func (e *ClientRegistrationError) Error() string {
175 return fmt.Sprintf("registration failed: %s (%s)", e.ErrorCode, e.ErrorDescription)
176 }
177
178 // RegisterClient performs Dynamic Client Registration according to RFC 7591.
179 func RegisterClient(ctx context.Context, registrationEndpoint string, clientMeta *ClientRegistrationMetadata, c *http.Client) (*ClientRegistrationResponse, error) {
180 if registrationEndpoint == "" {
181 return nil, fmt.Errorf("registration_endpoint is required")
182 }
183
184 if c == nil {
185 c = http.DefaultClient
186 }
187
188 payload, err := json.Marshal(clientMeta)
189 if err != nil {
190 return nil, fmt.Errorf("failed to marshal client metadata: %w", err)
191 }
192
193 req, err := http.NewRequestWithContext(ctx, "POST", registrationEndpoint, bytes.NewBuffer(payload))
194 if err != nil {
195 return nil, fmt.Errorf("failed to create registration request: %w", err)
196 }
197
198 req.Header.Set("Content-Type", "application/json")
199 req.Header.Set("Accept", "application/json")
200
201 resp, err := c.Do(req)
202 if err != nil {
203 return nil, fmt.Errorf("registration request failed: %w", err)
204 }
205 defer resp.Body.Close()
206
207 body, err := io.ReadAll(resp.Body)
208 if err != nil {
209 return nil, fmt.Errorf("failed to read registration response body: %w", err)
210 }
211
212 if resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusOK {
213 var regResponse ClientRegistrationResponse
214 if err := internaljson.Unmarshal(body, &regResponse); err != nil {
215 return nil, fmt.Errorf("failed to decode successful registration response: %w (%s)", err, string(body))
216 }
217 if regResponse.ClientID == "" {
218 return nil, fmt.Errorf("registration response is missing required 'client_id' field")
219 }
220 // Validate URL fields to prevent XSS attacks (see #526).
221 if err := validateClientRegistrationURLs(&regResponse.ClientRegistrationMetadata); err != nil {
222 return nil, err
223 }
224 return &regResponse, nil
225 }
226
227 if resp.StatusCode == http.StatusBadRequest {
228 var regError ClientRegistrationError
229 if err := internaljson.Unmarshal(body, &regError); err != nil {
230 return nil, fmt.Errorf("failed to decode registration error response: %w (%s)", err, string(body))
231 }
232 return nil, &regError
233 }
234
235 return nil, fmt.Errorf("registration failed with status %s: %s", resp.Status, string(body))
236 }
237
238 // validateClientRegistrationURLs validates all URL fields in ClientRegistrationMetadata
239 // to ensure they don't use dangerous schemes that could enable XSS attacks.
240 func validateClientRegistrationURLs(meta *ClientRegistrationMetadata) error {
241 // Validate redirect URIs
242 for i, uri := range meta.RedirectURIs {
243 if err := checkURLScheme(uri); err != nil {
244 return fmt.Errorf("redirect_uris[%d]: %w", i, err)
245 }
246 }
247
248 // Validate other URL fields
249 urls := []struct {
250 name string
251 value string
252 }{
253 {"client_uri", meta.ClientURI},
254 {"logo_uri", meta.LogoURI},
255 {"tos_uri", meta.TOSURI},
256 {"policy_uri", meta.PolicyURI},
257 {"jwks_uri", meta.JWKSURI},
258 }
259
260 for _, u := range urls {
261 if err := checkURLScheme(u.value); err != nil {
262 return fmt.Errorf("%s: %w", u.name, err)
263 }
264 }
265 return nil
266 }