|
3 | 3 | package oauth |
4 | 4 |
|
5 | 5 | import ( |
| 6 | + "encoding/json" |
6 | 7 | "fmt" |
7 | 8 | "net/http" |
8 | | - "net/url" |
9 | 9 | "strings" |
10 | 10 |
|
11 | 11 | "github.com/github/github-mcp-server/pkg/http/headers" |
12 | 12 | "github.com/go-chi/chi/v5" |
13 | | - "github.com/modelcontextprotocol/go-sdk/auth" |
14 | 13 | "github.com/modelcontextprotocol/go-sdk/oauthex" |
15 | 14 | ) |
16 | 15 |
|
@@ -48,17 +47,12 @@ type Config struct { |
48 | 47 | // Defaults to GitHub's OAuth server if not specified. |
49 | 48 | AuthorizationServer string |
50 | 49 |
|
51 | | - // ResourcePath is the resource path suffix (e.g., "/mcp"). |
52 | | - // If empty, defaults to "/" |
| 50 | + // ResourcePath is the externally visible base path for the MCP server (e.g., "/mcp"). |
| 51 | + // This is used to restore the original path when a proxy strips a base path before forwarding. |
| 52 | + // If empty, requests are treated as already using the external path. |
53 | 53 | ResourcePath string |
54 | 54 | } |
55 | 55 |
|
56 | | -// ProtectedResourceData contains the data needed to build an OAuth protected resource response. |
57 | | -type ProtectedResourceData struct { |
58 | | - ResourceURL string |
59 | | - AuthorizationServer string |
60 | | -} |
61 | | - |
62 | 56 | // AuthHandler handles OAuth-related HTTP endpoints. |
63 | 57 | type AuthHandler struct { |
64 | 58 | cfg *Config |
@@ -94,119 +88,165 @@ func (h *AuthHandler) RegisterRoutes(r chi.Router) { |
94 | 88 | for _, pattern := range routePatterns { |
95 | 89 | for _, route := range h.routesForPattern(pattern) { |
96 | 90 | path := OAuthProtectedResourcePrefix + route |
97 | | - |
98 | | - // Build metadata for this specific resource path |
99 | | - metadata := h.buildMetadata(route) |
100 | | - r.Handle(path, auth.ProtectedResourceMetadataHandler(metadata)) |
| 91 | + r.Handle(path, h.metadataHandler()) |
101 | 92 | } |
102 | 93 | } |
103 | 94 | } |
104 | 95 |
|
105 | | -func (h *AuthHandler) buildMetadata(resourcePath string) *oauthex.ProtectedResourceMetadata { |
106 | | - baseURL := strings.TrimSuffix(h.cfg.BaseURL, "/") |
107 | | - resourceURL := baseURL |
108 | | - if resourcePath != "" && resourcePath != "/" { |
109 | | - resourceURL = baseURL + resourcePath |
110 | | - } |
| 96 | +func (h *AuthHandler) metadataHandler() http.Handler { |
| 97 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 98 | + // CORS headers for browser-based clients |
| 99 | + w.Header().Set("Access-Control-Allow-Origin", "*") |
| 100 | + w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") |
| 101 | + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") |
111 | 102 |
|
112 | | - return &oauthex.ProtectedResourceMetadata{ |
113 | | - Resource: resourceURL, |
114 | | - AuthorizationServers: []string{h.cfg.AuthorizationServer}, |
115 | | - ResourceName: "GitHub MCP Server", |
116 | | - ScopesSupported: SupportedScopes, |
117 | | - BearerMethodsSupported: []string{"header"}, |
118 | | - } |
| 103 | + if r.Method == http.MethodOptions { |
| 104 | + w.WriteHeader(http.StatusNoContent) |
| 105 | + return |
| 106 | + } |
| 107 | + if r.Method != http.MethodGet { |
| 108 | + w.WriteHeader(http.StatusMethodNotAllowed) |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + resourcePath := resolveResourcePath( |
| 113 | + strings.TrimPrefix(r.URL.Path, OAuthProtectedResourcePrefix), |
| 114 | + h.cfg.ResourcePath, |
| 115 | + ) |
| 116 | + resourceURL := h.buildResourceURL(r, resourcePath) |
| 117 | + |
| 118 | + w.Header().Set("Content-Type", "application/json") |
| 119 | + _ = json.NewEncoder(w).Encode(&oauthex.ProtectedResourceMetadata{ |
| 120 | + Resource: resourceURL, |
| 121 | + AuthorizationServers: []string{h.cfg.AuthorizationServer}, |
| 122 | + ResourceName: "GitHub MCP Server", |
| 123 | + ScopesSupported: SupportedScopes, |
| 124 | + BearerMethodsSupported: []string{"header"}, |
| 125 | + }) |
| 126 | + }) |
119 | 127 | } |
120 | 128 |
|
121 | 129 | // routesForPattern generates route variants for a given pattern. |
122 | 130 | // GitHub strips the /mcp prefix before forwarding, so we register both variants: |
123 | 131 | // - With /mcp prefix: for direct access or when GitHub doesn't strip |
124 | 132 | // - Without /mcp prefix: for when GitHub has stripped the prefix |
125 | 133 | func (h *AuthHandler) routesForPattern(pattern string) []string { |
126 | | - return []string{ |
127 | | - pattern, |
128 | | - "/mcp" + pattern, |
129 | | - pattern + "/", |
130 | | - "/mcp" + pattern + "/", |
| 134 | + basePaths := []string{""} |
| 135 | + if basePath := normalizeBasePath(h.cfg.ResourcePath); basePath != "" { |
| 136 | + basePaths = append(basePaths, basePath) |
| 137 | + } else { |
| 138 | + basePaths = append(basePaths, "/mcp") |
131 | 139 | } |
| 140 | + |
| 141 | + routes := make([]string, 0, len(basePaths)*2) |
| 142 | + for _, basePath := range basePaths { |
| 143 | + routes = append(routes, joinRoute(basePath, pattern)) |
| 144 | + routes = append(routes, joinRoute(basePath, pattern)+"/") |
| 145 | + } |
| 146 | + |
| 147 | + return routes |
| 148 | +} |
| 149 | + |
| 150 | +// resolveResourcePath returns the externally visible resource path, |
| 151 | +// restoring the configured base path when proxies strip it before forwarding. |
| 152 | +func resolveResourcePath(path, basePath string) string { |
| 153 | + if path == "" { |
| 154 | + path = "/" |
| 155 | + } |
| 156 | + base := normalizeBasePath(basePath) |
| 157 | + if base == "" { |
| 158 | + return path |
| 159 | + } |
| 160 | + if path == "/" { |
| 161 | + return base |
| 162 | + } |
| 163 | + if path == base || strings.HasPrefix(path, base+"/") { |
| 164 | + return path |
| 165 | + } |
| 166 | + return base + path |
132 | 167 | } |
133 | 168 |
|
134 | | -// GetEffectiveResourcePath returns the resource path for OAuth protected resource URLs. |
135 | | -// Since proxies may strip the /mcp prefix before forwarding requests, this function |
136 | | -// restores the prefix for the external-facing URL. |
137 | | -func GetEffectiveResourcePath(r *http.Request) string { |
138 | | - if r.URL.Path == "/" { |
139 | | - return "/mcp" |
| 169 | +// ResolveResourcePath returns the externally visible resource path for a request. |
| 170 | +// Exported for use by middleware. |
| 171 | +func ResolveResourcePath(r *http.Request, cfg *Config) string { |
| 172 | + basePath := "" |
| 173 | + if cfg != nil { |
| 174 | + basePath = cfg.ResourcePath |
140 | 175 | } |
141 | | - return "/mcp" + r.URL.Path |
| 176 | + return resolveResourcePath(r.URL.Path, basePath) |
142 | 177 | } |
143 | 178 |
|
144 | | -// GetProtectedResourceData builds the OAuth protected resource data for a request. |
145 | | -func (h *AuthHandler) GetProtectedResourceData(r *http.Request, resourcePath string) (*ProtectedResourceData, error) { |
| 179 | +// buildResourceURL constructs the full resource URL for OAuth metadata. |
| 180 | +func (h *AuthHandler) buildResourceURL(r *http.Request, resourcePath string) string { |
146 | 181 | host, scheme := GetEffectiveHostAndScheme(r, h.cfg) |
147 | | - |
148 | | - // Build the base URL |
149 | 182 | baseURL := fmt.Sprintf("%s://%s", scheme, host) |
150 | 183 | if h.cfg.BaseURL != "" { |
151 | 184 | baseURL = strings.TrimSuffix(h.cfg.BaseURL, "/") |
152 | 185 | } |
153 | | - |
154 | | - // Build the resource URL using url.JoinPath for proper path handling |
155 | | - var resourceURL string |
156 | | - var err error |
157 | | - if resourcePath == "/" { |
158 | | - resourceURL = baseURL + "/" |
159 | | - } else { |
160 | | - resourceURL, err = url.JoinPath(baseURL, resourcePath) |
161 | | - if err != nil { |
162 | | - return nil, fmt.Errorf("failed to build resource URL: %w", err) |
163 | | - } |
| 186 | + if resourcePath == "" { |
| 187 | + resourcePath = "/" |
164 | 188 | } |
165 | | - |
166 | | - return &ProtectedResourceData{ |
167 | | - ResourceURL: resourceURL, |
168 | | - AuthorizationServer: h.cfg.AuthorizationServer, |
169 | | - }, nil |
| 189 | + if !strings.HasPrefix(resourcePath, "/") { |
| 190 | + resourcePath = "/" + resourcePath |
| 191 | + } |
| 192 | + return baseURL + resourcePath |
170 | 193 | } |
171 | 194 |
|
172 | 195 | // GetEffectiveHostAndScheme returns the effective host and scheme for a request. |
173 | | -// It checks X-Forwarded-Host and X-Forwarded-Proto headers first (set by proxies), |
174 | | -// then falls back to the request's Host and TLS state. |
175 | | -func GetEffectiveHostAndScheme(r *http.Request, cfg *Config) (host, scheme string) { //nolint:revive // parameters are required by http.oauth.BuildResourceMetadataURL signature |
176 | | - // Check for forwarded headers first (typically set by reverse proxies) |
177 | | - if forwardedHost := r.Header.Get(headers.ForwardedHostHeader); forwardedHost != "" { |
178 | | - host = forwardedHost |
| 196 | +func GetEffectiveHostAndScheme(r *http.Request, cfg *Config) (host, scheme string) { //nolint:revive |
| 197 | + if fh := r.Header.Get(headers.ForwardedHostHeader); fh != "" { |
| 198 | + host = fh |
179 | 199 | } else { |
180 | 200 | host = r.Host |
181 | 201 | } |
182 | | - |
183 | | - // Determine scheme |
184 | | - switch { |
185 | | - case r.Header.Get(headers.ForwardedProtoHeader) != "": |
186 | | - scheme = strings.ToLower(r.Header.Get(headers.ForwardedProtoHeader)) |
187 | | - case r.TLS != nil: |
188 | | - scheme = "https" |
189 | | - default: |
190 | | - // Default to HTTPS in production scenarios |
191 | | - scheme = "https" |
| 202 | + if host == "" { |
| 203 | + host = "localhost" |
192 | 204 | } |
193 | | - |
194 | | - return host, scheme |
| 205 | + if fp := r.Header.Get(headers.ForwardedProtoHeader); fp != "" { |
| 206 | + scheme = strings.ToLower(fp) |
| 207 | + } else { |
| 208 | + scheme = "https" // Default to HTTPS |
| 209 | + } |
| 210 | + return |
195 | 211 | } |
196 | 212 |
|
197 | 213 | // BuildResourceMetadataURL constructs the full URL to the OAuth protected resource metadata endpoint. |
198 | 214 | func BuildResourceMetadataURL(r *http.Request, cfg *Config, resourcePath string) string { |
199 | 215 | host, scheme := GetEffectiveHostAndScheme(r, cfg) |
200 | | - |
| 216 | + suffix := "" |
| 217 | + if resourcePath != "" && resourcePath != "/" { |
| 218 | + if !strings.HasPrefix(resourcePath, "/") { |
| 219 | + suffix = "/" + resourcePath |
| 220 | + } else { |
| 221 | + suffix = resourcePath |
| 222 | + } |
| 223 | + } |
201 | 224 | if cfg != nil && cfg.BaseURL != "" { |
202 | | - baseURL := strings.TrimSuffix(cfg.BaseURL, "/") |
203 | | - return baseURL + OAuthProtectedResourcePrefix + "/" + strings.TrimPrefix(resourcePath, "/") |
| 225 | + return strings.TrimSuffix(cfg.BaseURL, "/") + OAuthProtectedResourcePrefix + suffix |
204 | 226 | } |
| 227 | + return fmt.Sprintf("%s://%s%s%s", scheme, host, OAuthProtectedResourcePrefix, suffix) |
| 228 | +} |
205 | 229 |
|
206 | | - path := OAuthProtectedResourcePrefix |
207 | | - if resourcePath != "" && resourcePath != "/" { |
208 | | - path = path + "/" + strings.TrimPrefix(resourcePath, "/") |
| 230 | +func normalizeBasePath(path string) string { |
| 231 | + trimmed := strings.TrimSpace(path) |
| 232 | + if trimmed == "" || trimmed == "/" { |
| 233 | + return "" |
209 | 234 | } |
| 235 | + if !strings.HasPrefix(trimmed, "/") { |
| 236 | + trimmed = "/" + trimmed |
| 237 | + } |
| 238 | + return strings.TrimSuffix(trimmed, "/") |
| 239 | +} |
210 | 240 |
|
211 | | - return fmt.Sprintf("%s://%s%s", scheme, host, path) |
| 241 | +func joinRoute(basePath, pattern string) string { |
| 242 | + if basePath == "" { |
| 243 | + return pattern |
| 244 | + } |
| 245 | + if pattern == "" { |
| 246 | + return basePath |
| 247 | + } |
| 248 | + if strings.HasSuffix(basePath, "/") { |
| 249 | + return strings.TrimSuffix(basePath, "/") + pattern |
| 250 | + } |
| 251 | + return basePath + pattern |
212 | 252 | } |
0 commit comments