Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/oauth2.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 implements extensions to OAuth2.
6
7 package oauthex
8
9 import (
10 "context"
11 "fmt"
12 "io"
13 "mime"
14 "net/http"
15 "net/url"
16 "strings"
17
18 "github.com/modelcontextprotocol/go-sdk/internal/json"
19 "github.com/modelcontextprotocol/go-sdk/internal/util"
20 )
21
22 type httpStatusError struct {
23 StatusCode int
24 }
25
26 func (e *httpStatusError) Error() string {
27 return fmt.Sprintf("bad status %d", e.StatusCode)
28 }
29
30 // getJSON retrieves JSON and unmarshals JSON from the URL, as specified in both
31 // RFC 9728 and RFC 8414.
32 // It will not read more than limit bytes from the body.
33 func getJSON[T any](ctx context.Context, c *http.Client, url string, limit int64) (*T, error) {
34 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
35 if err != nil {
36 return nil, err
37 }
38 if c == nil {
39 c = http.DefaultClient
40 }
41 res, err := c.Do(req)
42 if err != nil {
43 return nil, err
44 }
45 defer res.Body.Close()
46
47 if res.StatusCode != http.StatusOK {
48 return nil, &httpStatusError{StatusCode: res.StatusCode}
49 }
50 ct := res.Header.Get("Content-Type")
51 mediaType, _, err := mime.ParseMediaType(ct)
52 if err != nil || mediaType != "application/json" {
53 return nil, fmt.Errorf("bad content type %q", ct)
54 }
55
56 var t T
57 dec := json.NewDecoder(io.LimitReader(res.Body, limit))
58 if err := dec.Decode(&t); err != nil {
59 return nil, err
60 }
61 return &t, nil
62 }
63
64 // checkURLScheme ensures that its argument is a valid URL with a scheme
65 // that prevents XSS attacks.
66 // See #526.
67 // Note: a copy of this function exists in auth/extauth/oidc_login.go; keep these in sync.
68 func checkURLScheme(u string) error {
69 if u == "" {
70 return nil
71 }
72 uu, err := url.Parse(u)
73 if err != nil {
74 return err
75 }
76 scheme := strings.ToLower(uu.Scheme)
77 if scheme == "javascript" || scheme == "data" || scheme == "vbscript" {
78 return fmt.Errorf("URL has disallowed scheme %q", scheme)
79 }
80 return nil
81 }
82
83 func checkHTTPSOrLoopback(addr string) error {
84 if addr == "" {
85 return nil
86 }
87 u, err := url.Parse(addr)
88 if err != nil {
89 return err
90 }
91 if !util.IsLoopback(u.Host) && u.Scheme != "https" {
92 return fmt.Errorf("URL %q does not use HTTPS or is not a loopback address", addr)
93 }
94 return nil
95 }