fix: match MCP OAuth2 resources at path boundaries and by IP address

An advertised resource with a trailing slash no longer covers the same
path without one, as in the MCP SDKs, and an empty path after an
authority equals "/". Origins compare IP literals by address, so
[::1] matches [0:0:0:0:0:0:0:1]. Resource indicators with an IPv6
zone identifier are rejected, since RFC 3986 IP literals have none.

The docs now say the resource must not contain user information,
which validation already rejects.
This commit is contained in:
Michael Suchacz committed 2026-10-12 16:34:31 +00:00
1 parent 72c019ff5e
commit ef2df2c4e7
4 files changed
+55 -13

No files matched your search

+33 -12
View File
@@ -11,6 +11,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/netip"
"net/url" "net/url"
"slices" "slices"
"strings" "strings"
@@ -1792,9 +1793,12 @@ func parseMCPOAuth2Resource(resource string) (*url.URL, error) {
return nil, xerrors.New("oauth2_resource must be a valid URI") return nil, xerrors.New("oauth2_resource must be a valid URI")
} }
// url.Parse validates an IP literal host, but it also accepts "[" and // url.Parse validates an IP literal host, but it also accepts "[" and
// "]" elsewhere, where RFC 3986 does not allow them. // "]" elsewhere and a zone identifier in an IP literal, neither of
// which RFC 3986 allows.
ipLiteral := strings.HasPrefix(parsed.Host, "[")
if strings.ContainsAny(parsed.Opaque+parsed.EscapedPath()+parsed.RawQuery, "[]") || if strings.ContainsAny(parsed.Opaque+parsed.EscapedPath()+parsed.RawQuery, "[]") ||
(!strings.HasPrefix(parsed.Host, "[") && strings.ContainsAny(parsed.Host, "[]")) { (!ipLiteral && strings.ContainsAny(parsed.Host, "[]")) ||
(ipLiteral && strings.Contains(parsed.Host, "%")) {
return nil, xerrors.New("oauth2_resource must be a valid URI") return nil, xerrors.New("oauth2_resource must be a valid URI")
} }
if !parsed.IsAbs() { if !parsed.IsAbs() {
@@ -1902,13 +1906,14 @@ func mcpOAuth2ResourceBinding(resource string) string {
// an MCP server: the most specific advertised Protected Resource // an MCP server: the most specific advertised Protected Resource
// Metadata resource that covers the server URL, stored verbatim, else // Metadata resource that covers the server URL, stored verbatim, else
// the server URL in canonical form, or "" when that is not a valid // the server URL in canonical form, or "" when that is not a valid
// resource indicator. As in the MCP Python SDK, a resource // resource indicator. As in the MCP SDKs, a resource covers URLs on its
// covers URLs on its origin under its path. Paths and queries compare in // origin at or under its path, so "/mcp" covers "/mcp/" but "/mcp/" does
// RFC 3986 normal form, where "%2F" does not end a segment. Unlike the // not cover "/mcp". Paths and queries compare in RFC 3986 normal form,
// SDK, a resource with a query, even an empty one, covers only URLs with // where "%2F" does not end a segment, and IP addresses compare by value.
// the same query, which can select a tenant. // Unlike the SDKs, a resource with a query, even an empty one, covers
// only URLs with the same query, which can select a tenant.
func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string { func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string {
serverPath := withTrailingSlash(comparableURIPath(serverURL)) serverPath := comparableURIPath(serverURL)
serverQuery, serverHasQuery := comparableURIQuery(serverURL) serverQuery, serverHasQuery := comparableURIQuery(serverURL)
best := "" best := ""
bestPathLen := -1 bestPathLen := -1
@@ -1926,8 +1931,8 @@ func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string
if hasQuery && (!serverHasQuery || query != serverQuery) { if hasQuery && (!serverHasQuery || query != serverQuery) {
continue continue
} }
entryPath := withTrailingSlash(comparableURIPath(parsed)) entryPath := comparableURIPath(parsed)
if !strings.HasPrefix(serverPath, entryPath) { if entryPath != serverPath && !strings.HasPrefix(serverPath, withTrailingSlash(entryPath)) {
continue continue
} }
if len(entryPath) > bestPathLen || (len(entryPath) == bestPathLen && hasQuery && !bestHasQuery) { if len(entryPath) > bestPathLen || (len(entryPath) == bestPathLen && hasQuery && !bestHasQuery) {
@@ -1957,13 +1962,18 @@ func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string
// comparableURIPath returns u's escaped path with percent-encodings // comparableURIPath returns u's escaped path with percent-encodings
// normalized and then dot segments removed, so "%2E%2E" is a dot segment. // normalized and then dot segments removed, so "%2E%2E" is a dot segment.
// An empty path after an authority is "/" (RFC 3986 section 6.2.3).
func comparableURIPath(u *url.URL) string { func comparableURIPath(u *url.URL) string {
normalized := *u normalized := *u
// Normalizing escapes leaves the unescaped Path unchanged, so this // Normalizing escapes leaves the unescaped Path unchanged, so this
// RawPath stays a valid encoding of it. // RawPath stays a valid encoding of it.
normalized.RawPath = normalizePercentEncoding(u.EscapedPath()) normalized.RawPath = normalizePercentEncoding(u.EscapedPath())
// Resolving a URL against itself removes dot segments and keeps escapes. // Resolving a URL against itself removes dot segments and keeps escapes.
return normalized.ResolveReference(&normalized).EscapedPath() path := normalized.ResolveReference(&normalized).EscapedPath()
if path == "" && u.Host != "" {
return "/"
}
return path
} }
// comparableURIQuery returns u's query with percent-encodings normalized // comparableURIQuery returns u's query with percent-encodings normalized
@@ -1977,10 +1987,21 @@ func comparableURIQuery(u *url.URL) (string, bool) {
// port, where an omitted port is the scheme's default. // port, where an omitted port is the scheme's default.
func sameOrigin(a, b *url.URL) bool { func sameOrigin(a, b *url.URL) bool {
return strings.EqualFold(a.Scheme, b.Scheme) && return strings.EqualFold(a.Scheme, b.Scheme) &&
strings.EqualFold(a.Hostname(), b.Hostname()) && sameHost(a.Hostname(), b.Hostname()) &&
portOrDefault(a) == portOrDefault(b) portOrDefault(a) == portOrDefault(b)
} }
// sameHost compares IP addresses by value, so "::1" equals
// "0:0:0:0:0:0:0:1", and other hosts case-insensitively.
func sameHost(a, b string) bool {
addrA, errA := netip.ParseAddr(a)
addrB, errB := netip.ParseAddr(b)
if errA == nil && errB == nil {
return addrA == addrB
}
return strings.EqualFold(a, b)
}
func portOrDefault(u *url.URL) string { func portOrDefault(u *url.URL) string {
if port := u.Port(); port != "" { if port := u.Port(); port != "" {
return port return port
+18
View File
@@ -302,6 +302,18 @@ func TestMCPOAuth2ResourceIndicator(t *testing.T) {
advertised: []string{"https://mcp.example.com/mcp"}, advertised: []string{"https://mcp.example.com/mcp"},
want: "https://mcp.example.com/mcp", want: "https://mcp.example.com/mcp",
}, },
{
name: "TrailingSlashResourceDoesNotCoverBarePath",
serverURL: "https://mcp.example.com/mcp",
advertised: []string{"https://mcp.example.com/mcp/"},
want: "https://mcp.example.com/mcp",
},
{
name: "EmptyPathEqualsSlash",
serverURL: "https://mcp.example.com",
advertised: []string{"https://mcp.example.com/"},
want: "https://mcp.example.com/",
},
{ {
name: "PathPrefixIsNotSegment", name: "PathPrefixIsNotSegment",
serverURL: "https://mcp.example.com/mcp2", serverURL: "https://mcp.example.com/mcp2",
@@ -416,6 +428,12 @@ func TestMCPOAuth2ResourceIndicator(t *testing.T) {
advertised: []string{"https://[::1]:8443/"}, advertised: []string{"https://[::1]:8443/"},
want: "https://[::1]:8443/", want: "https://[::1]:8443/",
}, },
{
name: "EquivalentIPv6Literal",
serverURL: "https://[0:0:0:0:0:0:0:1]/mcp",
advertised: []string{"https://[::1]/mcp"},
want: "https://[::1]/mcp",
},
{ {
name: "NoEntriesFallsBack", name: "NoEntriesFallsBack",
serverURL: "https://mcp.example.com/mcp", serverURL: "https://mcp.example.com/mcp",
+3
View File
@@ -1377,6 +1377,9 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) {
"https://mcp.example.com/mcp?tenant=%zz", "https://mcp.example.com/mcp?tenant=%zz",
"https://mcp.example.com/a[b]", "https://mcp.example.com/a[b]",
"https://a]b.example.com/mcp", "https://a]b.example.com/mcp",
"https://[x]/mcp",
"https://[::1][x]/mcp",
"https://[fe80::1%25en0]/mcp",
"https://user@mcp.example.com/mcp", "https://user@mcp.example.com/mcp",
} { } {
_, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ _, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{
@@ -94,7 +94,7 @@ The revocation endpoint must use HTTPS.
Loopback URLs may use HTTP for local development and tests. Loopback URLs may use HTTP for local development and tests.
When `oauth2_resource` is set, Coder sends it as the RFC 8707 `resource` parameter on authorization, token, and refresh requests. When `oauth2_resource` is set, Coder sends it as the RFC 8707 `resource` parameter on authorization, token, and refresh requests.
The value must be an absolute URI without a fragment. The value must be an absolute URI without a fragment or user information.
A manual configuration sends no `resource` parameter unless you set this field. A manual configuration sends no `resource` parameter unless you set this field.
Leave it empty for providers that reject the parameter, such as Microsoft Entra ID. Leave it empty for providers that reject the parameter, such as Microsoft Entra ID.