## Problem VS Code discovers Coder's MCP endpoint as a path-qualified OAuth resource, but Coder advertises the deployment root. Accepting MCP-bound tokens also requires keeping REST-backed tool calls within the originating MCP resource rather than granting those tokens direct REST access. ## Fix - Publish path-aware protected resource metadata and authentication challenges; keep authorization-server metadata at the root. - Validate the MCP audience and delegate tool requests through a private in-process transport that retains identity, scopes, expiry, revocation, and streaming cancellation. - Reject unsupported MCP path aliases and validate SDK path components before URL resolution. - Add discovery, audience, authorization, endpoint-isolation, and transport lifecycle regression tests and update integration docs. ## Validation VS Code completed OAuth and returned the authenticated user through a real MCP tool. Official MCP SDK 1.30.1 completed discovery, registration, PKCE, tool execution, and refresh. These live checks preceded the final path hardening; the hardened paths are covered by automated regressions. Affected Go package tests, targeted race tests, backend/SDK lint, and targeted documentation checks passed during self-review. The exact PR commit was also checked separately from the uncommitted consent-scope fix. > [!NOTE] > Tokens are MCP-audience-bound, but grants still include `coder:all`; least-privilege scopes remain a separate requirement ([PLAT-639](https://linear.app/codercom/issue/PLAT-639)). Preview: https://coder.com/docs/@fix/mcp-internal-delegation/ai-coder/mcp-server <details> <summary>Implementation decisions and review context</summary> 1. Treat `/api/experimental/mcp/http` and its single-trailing-slash form as supported MCP resource paths; reject other aliases and descendants before route authentication. 2. Preserve deployment-root discovery and authorization-server metadata for existing REST integrations. 3. Bind private delegation to the authenticated API-key ID. Revalidate the original credential and enforce normal RBAC/scopes on every internal REST request; do not derive delegation from HTTP headers. 4. Keep internal HTTP, streaming, and WebSocket traffic in-process with no network fallback. Close the transport on outer-request cancellation and normal completion. 5. Validate workspace owner/name path segments before SDK URL construction, including tool-level tests that malformed arguments cannot select a different REST endpoint. 6. Keep compatibility and delegated tool execution together: discovery-only changes would allow authentication while leaving real MCP tool calls broken. </details> > 🤖 This PR was created with the help of Coder Agents, and needs a human review. 🧑💻
77 lines
3.3 KiB
Go
77 lines
3.3 KiB
Go
package oauth2provider
|
|
|
|
import (
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/httpapi"
|
|
"github.com/coder/coder/v2/coderd/rbac"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// GetAuthorizationServerMetadata returns an http.HandlerFunc that handles GET /.well-known/oauth-authorization-server
|
|
func GetAuthorizationServerMetadata(db database.Store, accessURL *url.URL) http.HandlerFunc {
|
|
return func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
|
|
// This is queried on every request rather than cached, for the
|
|
// same reason as the registration endpoint: discovery is not
|
|
// expected to be a hot path, and a flood of requests should be
|
|
// mitigated with rate limiting or firewalling, not a cache.
|
|
//nolint:gocritic // Public discovery endpoint, no authenticated actor to authorize against.
|
|
dcrEnabled, err := db.GetOAuth2DCREnabled(dbauthz.AsSystemOAuth2(ctx))
|
|
if err != nil {
|
|
httpapi.InternalServerError(rw, err)
|
|
return
|
|
}
|
|
|
|
metadata := codersdk.OAuth2AuthorizationServerMetadata{
|
|
Issuer: accessURL.String(),
|
|
AuthorizationEndpoint: accessURL.JoinPath("/oauth2/authorize").String(),
|
|
TokenEndpoint: accessURL.JoinPath("/oauth2/tokens").String(),
|
|
RevocationEndpoint: accessURL.JoinPath("/oauth2/revoke").String(), // RFC 7009
|
|
ResponseTypesSupported: []codersdk.OAuth2ProviderResponseType{codersdk.OAuth2ProviderResponseTypeCode},
|
|
GrantTypesSupported: []codersdk.OAuth2ProviderGrantType{codersdk.OAuth2ProviderGrantTypeAuthorizationCode, codersdk.OAuth2ProviderGrantTypeRefreshToken},
|
|
CodeChallengeMethodsSupported: []codersdk.OAuth2PKCECodeChallengeMethod{codersdk.OAuth2PKCECodeChallengeMethodS256},
|
|
ScopesSupported: rbac.ExternalScopeNames(),
|
|
// Not gated on dcrEnabled: existing clients still need to
|
|
// exchange tokens when new registrations are turned off.
|
|
TokenEndpointAuthMethodsSupported: codersdk.AdvertisedOAuth2TokenEndpointAuthMethods(),
|
|
}
|
|
if dcrEnabled {
|
|
metadata.RegistrationEndpoint = accessURL.JoinPath("/oauth2/register").String() // RFC 7591
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusOK, metadata)
|
|
}
|
|
}
|
|
|
|
// GetProtectedResourceMetadata returns an http.HandlerFunc that handles GET /.well-known/oauth-protected-resource
|
|
func GetProtectedResourceMetadata(accessURL *url.URL) http.HandlerFunc {
|
|
return func(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
resource := accessURL.String()
|
|
suffix := strings.TrimPrefix(r.URL.Path, "/.well-known/oauth-protected-resource")
|
|
switch suffix {
|
|
case "", "/":
|
|
case codersdk.MCPEndpoint, codersdk.MCPEndpoint + "/":
|
|
resource = accessURL.JoinPath(suffix).String()
|
|
default:
|
|
// Match before joining paths so malformed or unknown resources
|
|
// cannot be normalized into a supported resource (RFC 9728 §3.1).
|
|
httpapi.RouteNotFound(rw)
|
|
return
|
|
}
|
|
metadata := codersdk.OAuth2ProtectedResourceMetadata{
|
|
Resource: resource,
|
|
AuthorizationServers: []string{accessURL.String()},
|
|
ScopesSupported: rbac.ExternalScopeNames(),
|
|
// RFC 6750 Bearer Token methods supported as fallback methods in api key middleware
|
|
BearerMethodsSupported: []string{"header", "query"},
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusOK, metadata)
|
|
}
|
|
}
|