Files
coder/coderd/x/chatd/mcpclient/refresh_test.go
T
Michael Suchacz d6b67e8e31 feat: enforce SSRF protection for MCP config-directed traffic (#28242)
Routes all MCP config-directed traffic from coderd and chatd through a
shared SSRF-protected HTTP client, now that organization admins, not
only deployment admins, control MCP server URLs (#27942 and its stack
below).

## Summary

- Uses the [`coder/safedial`](https://github.com/coder/safedial)
library: it blocks private and special-purpose destinations at dial time
(validating resolved addresses at connection time so DNS rebinding
cannot bypass the check) and rejects cross-origin redirects.
- Covers the complete traffic surface: OAuth2 discovery, dynamic client
registration, code exchange, token refresh, revocation, and runtime MCP
connections from chatd.
- Deployments that intentionally host internal MCP servers opt in via
the new `--mcp-allowed-private-cidrs`
(`CODER_MCP_ALLOWED_PRIVATE_CIDRS`) option.
- Includes the deployment configuration surface, generated docs, CLI
goldens, TypeScript types, and regression coverage for each traffic
path.

## Merge window

This protection originally lived inside #27942 and was split out to keep
that diff reviewable. Until this PR lands, the stack below ships with
only main's existing discovery IP-range guard
(`CODER_MCP_OAUTH2_DISCOVERY_ALLOWED_IP_RANGES`), while org admins can
already point MCP configs at arbitrary URLs. This PR should merge
promptly after the stack below it.

Top of the MCP org-separation stack (CODAGT-711 -> CODAGT-717 audit ->
CODAGT-712 ACLs -> CODAGT-806 token RBAC -> CODAGT-714 org picker ->
this PR).

> Mux (AI agent) authored this PR on Mike's behalf.

<!-- mux-attribution: model=claude-fable-5 thinking=high -->
2026-08-30 13:09:17 +02:00

170 lines
4.8 KiB
Go

package mcpclient_test
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"golang.org/x/xerrors"
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/x/chatd/mcpclient"
)
func TestIsPermanentRefreshError(t *testing.T) {
t.Parallel()
retrieveErr := func(code string, status int) error {
body, err := json.Marshal(map[string]string{"error": code})
require.NoError(t, err)
return &oauth2.RetrieveError{
Response: &http.Response{StatusCode: status},
Body: body,
ErrorCode: code,
}
}
cases := []struct {
name string
err error
permanent bool
}{
{"InvalidGrant", retrieveErr("invalid_grant", http.StatusBadRequest), true},
{"BadRefreshToken", retrieveErr("bad_refresh_token", http.StatusOK), true},
{"WrappedInvalidGrant", xerrors.Errorf("refresh: %w", retrieveErr("invalid_grant", http.StatusBadRequest)), true},
{"InvalidClient", retrieveErr("invalid_client", http.StatusUnauthorized), false},
{"UnauthorizedClient", retrieveErr("unauthorized_client", http.StatusBadRequest), false},
{"ServerError", retrieveErr("", http.StatusInternalServerError), false},
{"RateLimited", retrieveErr("", http.StatusTooManyRequests), false},
{"PlainError", xerrors.New("connection refused"), false},
{"Nil", nil, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tc.permanent, mcpclient.IsPermanentRefreshError(tc.err))
})
}
}
func TestRefreshFailureReason(t *testing.T) {
t.Parallel()
require.Equal(t, "boom", mcpclient.RefreshFailureReason(xerrors.New("boom")))
long := strings.Repeat("x", 1000)
reason := mcpclient.RefreshFailureReason(xerrors.New(long))
require.Len(t, reason, 400)
}
func TestRefreshOAuth2TokenInvalidGrant(t *testing.T) {
t.Parallel()
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid_grant","error_description":"grant revoked"}`))
}))
defer tokenSrv.Close()
cfg := database.MCPServerConfig{
OAuth2ClientID: "cid",
OAuth2TokenURL: tokenSrv.URL,
}
tok := database.MCPServerUserToken{
AccessToken: "expired",
RefreshToken: "refresh",
TokenType: "Bearer",
Expiry: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true},
}
_, err := mcpclient.RefreshOAuth2Token(context.Background(), testMCPHTTPClient(nil), cfg, tok)
require.Error(t, err)
require.True(t, mcpclient.IsPermanentRefreshError(err))
}
func TestRefreshOAuth2TokenRejectsCrossOriginRedirect(t *testing.T) {
t.Parallel()
var targetHits atomic.Int64
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
targetHits.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"stolen","token_type":"Bearer"}`))
}))
defer target.Close()
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
}))
defer tokenSrv.Close()
cfg := database.MCPServerConfig{
OAuth2ClientID: "cid",
OAuth2ClientSecret: "secret",
OAuth2TokenURL: tokenSrv.URL,
}
tok := database.MCPServerUserToken{
AccessToken: "expired",
RefreshToken: "refresh",
TokenType: "Bearer",
Expiry: sql.NullTime{Time: time.Now().Add(-time.Hour), Valid: true},
}
_, err := mcpclient.RefreshOAuth2Token(context.Background(), testMCPHTTPClient(tokenSrv.Client()), cfg, tok)
require.Error(t, err)
require.Zero(t, targetHits.Load())
}
func TestBuildAuthHeadersSkipsFailedToken(t *testing.T) {
t.Parallel()
logger := slogtest.Make(t, nil)
cfg := database.MCPServerConfig{
ID: uuid.New(),
Slug: "revoked",
AuthType: "oauth2",
}
t.Run("FailureReasonSet", func(t *testing.T) {
t.Parallel()
headers := mcpclient.BuildAuthHeadersForTest(
context.Background(), logger, cfg,
map[uuid.UUID]database.MCPServerUserToken{
cfg.ID: {
MCPServerConfigID: cfg.ID,
AccessToken: "leftover",
OauthRefreshFailureReason: "invalid_grant",
},
},
uuid.New(), nil,
)
require.NotContains(t, headers, "Authorization")
})
t.Run("HealthyToken", func(t *testing.T) {
t.Parallel()
headers := mcpclient.BuildAuthHeadersForTest(
context.Background(), logger, cfg,
map[uuid.UUID]database.MCPServerUserToken{
cfg.ID: {
MCPServerConfigID: cfg.ID,
AccessToken: "valid",
TokenType: "Bearer",
},
},
uuid.New(), nil,
)
require.Equal(t, "Bearer valid", headers["Authorization"])
})
}