Files
coder/coderd/oauth2provider/metadata_test.go
T
Atif Ali 261269aff0 fix: support path-aware OAuth discovery for remote MCP (#30168)
## 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. 🧑💻
2026-10-09 00:58:39 +05:00

180 lines
6.6 KiB
Go

package oauth2provider_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/oauth2provider"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
func TestOAuth2AuthorizationServerMetadata(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
serverURL := client.URL
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
// Use a plain HTTP client since this endpoint doesn't require authentication.
// Add a short readiness wait to avoid rare races with server startup.
endpoint := serverURL.ResolveReference(&url.URL{Path: "/.well-known/oauth-authorization-server"}).String()
var metadata codersdk.OAuth2AuthorizationServerMetadata
testutil.RequireEventuallyResponseOK(ctx, t, endpoint, &metadata)
// Verify the metadata
require.NotEmpty(t, metadata.Issuer)
require.NotEmpty(t, metadata.AuthorizationEndpoint)
require.NotEmpty(t, metadata.TokenEndpoint)
require.Contains(t, metadata.ResponseTypesSupported, codersdk.OAuth2ProviderResponseTypeCode)
require.Contains(t, metadata.GrantTypesSupported, codersdk.OAuth2ProviderGrantTypeAuthorizationCode)
require.Contains(t, metadata.GrantTypesSupported, codersdk.OAuth2ProviderGrantTypeRefreshToken)
require.Contains(t, metadata.CodeChallengeMethodsSupported, codersdk.OAuth2PKCECodeChallengeMethodS256)
// Pinned to a literal, not to the function the handler itself returns, which
// would hold for whatever that function said. "none" advertises secretless
// registration to public clients (RFC 8414 §2).
require.ElementsMatch(t, []codersdk.OAuth2TokenEndpointAuthMethod{
codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
codersdk.OAuth2TokenEndpointAuthMethodNone,
}, metadata.TokenEndpointAuthMethodsSupported)
// Supported scopes are published from the curated catalog
require.Equal(t, rbac.ExternalScopeNames(), metadata.ScopesSupported)
}
// TestGetAuthorizationServerMetadata_DCREnabled is a focused unit test on
// the discovery handler itself, bypassing the full coderdtest HTTP server.
// It verifies the dynamic-client-registration-enabled gate: registration_endpoint
// is advertised once an admin explicitly enables DCR, omitted when explicitly
// disabled, and omitted by default when the setting has never been
// configured.
func TestGetAuthorizationServerMetadata_DCREnabled(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-metadata-dcr-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
// configureDCR is nil for "never configured".
configureDCR *bool
wantRegistrationEndpoint bool
}{
{
name: "EnabledAdvertisesRegistrationEndpoint",
configureDCR: new(true),
wantRegistrationEndpoint: true,
},
{
name: "DisabledOmitsRegistrationEndpoint",
configureDCR: new(false),
wantRegistrationEndpoint: false,
},
{
name: "NeverConfiguredDefaultsToOmitted",
configureDCR: nil,
wantRegistrationEndpoint: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
if tt.configureDCR != nil {
err := db.UpsertOAuth2DCREnabled(ctx, *tt.configureDCR)
require.NoError(t, err)
}
handler := oauth2provider.GetAuthorizationServerMetadata(db, accessURL)
r := httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil).WithContext(ctx)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusOK, rw.Code)
var metadata codersdk.OAuth2AuthorizationServerMetadata
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &metadata))
if tt.wantRegistrationEndpoint {
require.NotEmpty(t, metadata.RegistrationEndpoint)
} else {
require.Empty(t, metadata.RegistrationEndpoint)
}
})
}
}
func TestOAuth2ProtectedResourceMetadataUnknownPath(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
for _, suffix := range []string{
"/unknown", "/api/v2/users/me", "/api/experimental/mcp/http/unknown",
"/api/experimental/mcp/http-extra", "/../api/experimental/mcp/http",
"/api/experimental/mcp/../mcp/http", "/api//experimental/mcp/http",
"//api/experimental/mcp/http", "/api/experimental/mcp/http//",
"/api/experimental/mcp/%2e%2e/mcp/http", "/%ff",
} {
t.Run(suffix, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
client.URL.String()+"/.well-known/oauth-protected-resource"+suffix, nil)
require.NoError(t, err)
resp, err := client.HTTPClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, http.StatusNotFound, resp.StatusCode)
})
}
}
func TestOAuth2ProtectedResourceMetadata(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
serverURL := client.URL
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
// Use a plain HTTP client since this endpoint doesn't require authentication.
// Add a short readiness wait to avoid rare races with server startup.
endpoint := serverURL.ResolveReference(&url.URL{Path: "/.well-known/oauth-protected-resource"}).String()
var metadata codersdk.OAuth2ProtectedResourceMetadata
testutil.RequireEventuallyResponseOK(ctx, t, endpoint, &metadata)
// Verify the metadata
require.Equal(t, serverURL.String(), metadata.Resource)
require.NotEmpty(t, metadata.AuthorizationServers)
require.Len(t, metadata.AuthorizationServers, 1)
require.Equal(t, metadata.Resource, metadata.AuthorizationServers[0])
for _, suffix := range []string{"/api/experimental/mcp/http", "/api/experimental/mcp/http/"} {
var pathMetadata codersdk.OAuth2ProtectedResourceMetadata
testutil.RequireEventuallyResponseOK(ctx, t, endpoint+suffix, &pathMetadata)
require.Equal(t, serverURL.String()+suffix, pathMetadata.Resource)
require.Equal(t, []string{serverURL.String()}, pathMetadata.AuthorizationServers)
}
// RFC 6750 bearer tokens are now supported as fallback methods
require.Contains(t, metadata.BearerMethodsSupported, "header")
require.Contains(t, metadata.BearerMethodsSupported, "query")
// Supported scopes are published from the curated catalog
require.Equal(t, rbac.ExternalScopeNames(), metadata.ScopesSupported)
}