Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/resource_meta.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 Protected Resource Metadata.
6 // See https://www.rfc-editor.org/rfc/rfc9728.html.
7
8 package oauthex
9
10 import (
11 "context"
12 "errors"
13 "fmt"
14 "net/http"
15 "strings"
16 "unicode"
17
18 "github.com/modelcontextprotocol/go-sdk/internal/util"
19 )
20
21 // ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource,
22 // as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html.
23 //
24 // The following features are not supported:
25 // - additional keys (§2, last sentence)
26 // - human-readable metadata (§2.1)
27 // - signed metadata (§2.2)
28 type ProtectedResourceMetadata struct {
29 // Resource (resource) is the protected resource's resource identifier.
30 // Required.
31 Resource string `json:"resource"`
32
33 // AuthorizationServers (authorization_servers) is an optional slice containing a list of
34 // OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be
35 // used with this protected resource.
36 AuthorizationServers []string `json:"authorization_servers,omitempty"`
37
38 // JWKSURI (jwks_uri) is an optional URL of the protected resource's JSON Web Key (JWK) Set
39 // document. This contains public keys belonging to the protected resource, such as
40 // signing key(s) that the resource server uses to sign resource responses.
41 JWKSURI string `json:"jwks_uri,omitempty"`
42
43 // ScopesSupported (scopes_supported) is a recommended slice containing a list of scope
44 // values (as defined in RFC 6749) used in authorization requests to request access
45 // to this protected resource.
46 ScopesSupported []string `json:"scopes_supported,omitempty"`
47
48 // BearerMethodsSupported (bearer_methods_supported) is an optional slice containing
49 // a list of the supported methods of sending an OAuth 2.0 bearer token to the
50 // protected resource. Defined values are "header", "body", and "query".
51 BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
52
53 // ResourceSigningAlgValuesSupported (resource_signing_alg_values_supported) is an optional
54 // slice of JWS signing algorithms (alg values) supported by the protected
55 // resource for signing resource responses.
56 ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
57
58 // ResourceName (resource_name) is a human-readable name of the protected resource
59 // intended for display to the end user. It is RECOMMENDED that this field be included.
60 // This value may be internationalized.
61 ResourceName string `json:"resource_name,omitempty"`
62
63 // ResourceDocumentation (resource_documentation) is an optional URL of a page containing
64 // human-readable information for developers using the protected resource.
65 // This value may be internationalized.
66 ResourceDocumentation string `json:"resource_documentation,omitempty"`
67
68 // ResourcePolicyURI (resource_policy_uri) is an optional URL of a page containing
69 // human-readable policy information on how a client can use the data provided.
70 // This value may be internationalized.
71 ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
72
73 // ResourceTOSURI (resource_tos_uri) is an optional URL of a page containing the protected
74 // resource's human-readable terms of service. This value may be internationalized.
75 ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
76
77 // TLSClientCertificateBoundAccessTokens (tls_client_certificate_bound_access_tokens) is an
78 // optional boolean indicating support for mutual-TLS client certificate-bound
79 // access tokens (RFC 8705). Defaults to false if omitted.
80 TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
81
82 // AuthorizationDetailsTypesSupported (authorization_details_types_supported) is an optional
83 // slice of 'type' values supported by the resource server for the
84 // 'authorization_details' parameter (RFC 9396).
85 AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
86
87 // DPOPSigningAlgValuesSupported (dpop_signing_alg_values_supported) is an optional
88 // slice of JWS signing algorithms supported by the resource server for validating
89 // DPoP proof JWTs (RFC 9449).
90 DPOPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
91
92 // DPOPBoundAccessTokensRequired (dpop_bound_access_tokens_required) is an optional boolean
93 // specifying whether the protected resource always requires the use of DPoP-bound
94 // access tokens (RFC 9449). Defaults to false if omitted.
95 DPOPBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
96
97 // SignedMetadata (signed_metadata) is an optional JWT containing metadata parameters
98 // about the protected resource as claims. If present, these values take precedence
99 // over values conveyed in plain JSON.
100 // TODO:implement.
101 // Note that §2.2 says it's okay to ignore this.
102 // SignedMetadata string `json:"signed_metadata,omitempty"`
103 }
104
105 // Challenge represents a single authentication challenge from a WWW-Authenticate header.
106 // As per RFC 9110, Section 11.6.1, a challenge consists of a scheme and optional parameters.
107 type Challenge struct {
108 // Scheme is the authentication scheme (e.g., "Bearer", "Basic").
109 // It is case-insensitive. A parsed value will always be lower-case.
110 Scheme string
111 // Params is a map of authentication parameters.
112 // Keys are case-insensitive. Parsed keys are always lower-case.
113 Params map[string]string
114 }
115
116 // GetProtectedResourceMetadata issues a GET request to retrieve protected resource
117 // metadata from a resource server.
118 // The metadataURL is typically a URL with a host:port and possibly a path.
119 // The resourceURL is the resource URI the metadataURL is for.
120 // The following checks are performed:
121 // - The metadataURL must use HTTPS or be a local address.
122 // - The resource field of the resulting metadata must match the resourceURL.
123 // - The authorization_servers field of the resulting metadata is checked for dangerous URL schemes.
124 func GetProtectedResourceMetadata(ctx context.Context, metadataURL, resourceURL string, c *http.Client) (_ *ProtectedResourceMetadata, err error) {
125 defer util.Wrapf(&err, "GetProtectedResourceMetadata(%q)", metadataURL)
126 // Only allow HTTP for local addresses (testing or development purposes).
127 if err := checkHTTPSOrLoopback(metadataURL); err != nil {
128 return nil, fmt.Errorf("metadataURL: %v", err)
129 }
130 prm, err := getJSON[ProtectedResourceMetadata](ctx, c, metadataURL, 1<<20)
131 if err != nil {
132 return nil, err
133 }
134 // Validate the Resource field (see RFC 9728, section 3.3).
135 if prm.Resource != resourceURL {
136 return nil, fmt.Errorf("got metadata resource %q, want %q", prm.Resource, resourceURL)
137 }
138 // Validate the authorization server URLs to prevent XSS attacks (see #526).
139 for i, u := range prm.AuthorizationServers {
140 if err := checkURLScheme(u); err != nil {
141 return nil, fmt.Errorf("authorization_servers[%d]: %v", i, err)
142 }
143 if err := checkHTTPSOrLoopback(u); err != nil {
144 return nil, fmt.Errorf("authorization_servers[%d]: %v", i, err)
145 }
146 }
147 return prm, nil
148 }
149
150 // ParseWWWAuthenticate parses a WWW-Authenticate header string.
151 // The header format is defined in RFC 9110, Section 11.6.1, and can contain
152 // one or more challenges, separated by commas.
153 // It returns a slice of challenges or an error if one of the headers is malformed.
154 func ParseWWWAuthenticate(headers []string) ([]Challenge, error) {
155 var challenges []Challenge
156 for _, h := range headers {
157 challengeStrings, err := splitChallenges(h)
158 if err != nil {
159 return nil, err
160 }
161 for _, cs := range challengeStrings {
162 if strings.TrimSpace(cs) == "" {
163 continue
164 }
165 challenge, err := parseSingleChallenge(cs)
166 if err != nil {
167 return nil, fmt.Errorf("failed to parse challenge %q: %w", cs, err)
168 }
169 challenges = append(challenges, challenge)
170 }
171 }
172 return challenges, nil
173 }
174
175 // splitChallenges splits a header value containing one or more challenges.
176 // It correctly handles commas within quoted strings and distinguishes between
177 // commas separating auth-params and commas separating challenges.
178 func splitChallenges(header string) ([]string, error) {
179 var challenges []string
180 inQuotes := false
181 start := 0
182 for i, r := range header {
183 if r == '"' {
184 if i > 0 && header[i-1] != '\\' {
185 inQuotes = !inQuotes
186 } else if i == 0 {
187 // A challenge begins with an auth-scheme, which is a token, which cannot contain
188 // a quote.
189 return nil, errors.New(`challenge begins with '"'`)
190 }
191 } else if r == ',' && !inQuotes {
192 // This is a potential challenge separator.
193 // A new challenge does not start with `key=value`.
194 // We check if the part after the comma looks like a parameter.
195 lookahead := strings.TrimSpace(header[i+1:])
196 eqPos := strings.Index(lookahead, "=")
197
198 isParam := false
199 if eqPos > 0 {
200 // Check if the part before '=' is a single token (no spaces).
201 token := lookahead[:eqPos]
202 if strings.IndexFunc(token, unicode.IsSpace) == -1 {
203 isParam = true
204 }
205 }
206
207 if !isParam {
208 // The part after the comma does not look like a parameter,
209 // so this comma separates challenges.
210 challenges = append(challenges, header[start:i])
211 start = i + 1
212 }
213 }
214 }
215 // Add the last (or only) challenge to the list.
216 challenges = append(challenges, header[start:])
217 return challenges, nil
218 }
219
220 // parseSingleChallenge parses a string containing exactly one challenge.
221 // challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ]
222 func parseSingleChallenge(s string) (Challenge, error) {
223 s = strings.TrimSpace(s)
224 if s == "" {
225 return Challenge{}, errors.New("empty challenge string")
226 }
227
228 scheme, paramsStr, found := strings.Cut(s, " ")
229 c := Challenge{Scheme: strings.ToLower(scheme)}
230 if !found {
231 return c, nil
232 }
233
234 params := make(map[string]string)
235
236 // Parse the key-value parameters.
237 for paramsStr != "" {
238 // Find the end of the parameter key.
239 keyEnd := strings.Index(paramsStr, "=")
240 if keyEnd <= 0 {
241 return Challenge{}, fmt.Errorf("malformed auth parameter: expected key=value, but got %q", paramsStr)
242 }
243 key := strings.TrimSpace(paramsStr[:keyEnd])
244
245 // Move the string past the key and the '='.
246 paramsStr = strings.TrimSpace(paramsStr[keyEnd+1:])
247
248 var value string
249 if strings.HasPrefix(paramsStr, "\"") {
250 // The value is a quoted string.
251 paramsStr = paramsStr[1:] // Consume the opening quote.
252 var valBuilder strings.Builder
253 i := 0
254 for ; i < len(paramsStr); i++ {
255 // Handle escaped characters.
256 if paramsStr[i] == '\\' && i+1 < len(paramsStr) {
257 valBuilder.WriteByte(paramsStr[i+1])
258 i++ // We've consumed two characters.
259 } else if paramsStr[i] == '"' {
260 // End of the quoted string.
261 break
262 } else {
263 valBuilder.WriteByte(paramsStr[i])
264 }
265 }
266
267 // A quoted string must be terminated.
268 if i == len(paramsStr) {
269 return Challenge{}, fmt.Errorf("unterminated quoted string in auth parameter")
270 }
271
272 value = valBuilder.String()
273 // Move the string past the value and the closing quote.
274 paramsStr = strings.TrimSpace(paramsStr[i+1:])
275 } else {
276 // The value is a token. It ends at the next comma or the end of the string.
277 commaPos := strings.Index(paramsStr, ",")
278 if commaPos == -1 {
279 value = paramsStr
280 paramsStr = ""
281 } else {
282 value = strings.TrimSpace(paramsStr[:commaPos])
283 paramsStr = strings.TrimSpace(paramsStr[commaPos:]) // Keep comma for next check
284 }
285 }
286 if value == "" {
287 return Challenge{}, fmt.Errorf("no value for auth param %q", key)
288 }
289
290 // Per RFC 9110, parameter keys are case-insensitive.
291 params[strings.ToLower(key)] = value
292
293 // If there is a comma, consume it and continue to the next parameter.
294 if strings.HasPrefix(paramsStr, ",") {
295 paramsStr = strings.TrimSpace(paramsStr[1:])
296 } else if paramsStr != "" {
297 // If there's content but it's not a new parameter, the format is wrong.
298 return Challenge{}, fmt.Errorf("malformed auth parameter: expected comma after value, but got %q", paramsStr)
299 }
300 }
301
302 // Per RFC 9110, the scheme is case-insensitive.
303 return Challenge{Scheme: strings.ToLower(scheme), Params: params}, nil
304 }