fix(coderd): tighten MCP OAuth2 resource matching and validation

Resource origins now compare with an omitted port treated as the
scheme's default, and paths compare in escaped form so "%2F" does not
end a segment. Resource values must contain only RFC 3986 characters
and valid percent escapes, because url.Parse accepts spaces and invalid
escapes in the query.
This commit is contained in:
Michael Suchacz committed 2026-10-12 15:02:47 +00:00
1 parent bf0879560c
commit 16a1d783fa
3 files changed
+80 -8

No files matched your search

+55 -6
View File
@@ -1784,6 +1784,9 @@ func parseMCPOAuth2Resource(resource string) (*url.URL, error) {
if strings.Contains(resource, "#") {
return nil, xerrors.New("oauth2_resource must not contain a fragment")
}
if !isURIText(resource) {
return nil, xerrors.New("oauth2_resource must be a valid URI")
}
parsed, err := url.Parse(resource)
if err != nil {
return nil, xerrors.New("oauth2_resource must be a valid URI")
@@ -1794,6 +1797,30 @@ func parseMCPOAuth2Resource(resource string) (*url.URL, error) {
return parsed, nil
}
// isURIText reports whether s contains only characters RFC 3986 allows
// in a URI, with every "%" starting a percent-encoded octet. url.Parse
// alone accepts spaces and other characters a URI cannot contain.
func isURIText(s string) bool {
for i := 0; i < len(s); i++ {
switch c := s[i]; {
case c == '%':
if i+2 >= len(s) || !isHexDigit(s[i+1]) || !isHexDigit(s[i+2]) {
return false
}
i += 2
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9':
case strings.IndexByte("-._~:/?#[]@!$&'()*+,;=", c) >= 0:
default:
return false
}
}
return true
}
func isHexDigit(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
// validateMCPOAuth2ResourceRequest writes a 400 response and returns
// false when a non-empty oauth2_resource is invalid. An empty value is
// valid because it means no resource parameter is sent.
@@ -1828,11 +1855,11 @@ func mcpOAuth2ResourceBinding(resource string) string {
// an MCP server: the most specific advertised Protected Resource
// Metadata resource that covers the server URL, stored verbatim, else
// the server URL in canonical form. As in the MCP Python SDK, a resource
// covers URLs on its origin under its path. Unlike the SDK, a resource
// with a query covers only URLs with the same query, which can select a
// tenant.
// covers URLs on its origin under its escaped path, so "%2F" does not
// end a segment. Unlike the SDK, a resource with a query covers only
// URLs with the same query, which can select a tenant.
func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string {
serverPath := withTrailingSlash(serverURL.Path)
serverPath := withTrailingSlash(serverURL.EscapedPath())
best := ""
bestPathLen := -1
bestHasQuery := false
@@ -1842,14 +1869,14 @@ func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string
if err != nil {
continue
}
if !strings.EqualFold(parsed.Scheme, serverURL.Scheme) || !strings.EqualFold(parsed.Host, serverURL.Host) {
if !sameOrigin(parsed, serverURL) {
continue
}
hasQuery := parsed.RawQuery != ""
if hasQuery && parsed.RawQuery != serverURL.RawQuery {
continue
}
entryPath := withTrailingSlash(parsed.Path)
entryPath := withTrailingSlash(parsed.EscapedPath())
if !strings.HasPrefix(serverPath, entryPath) {
continue
}
@@ -1872,6 +1899,28 @@ func mcpOAuth2ResourceIndicator(serverURL *url.URL, advertised []string) string
return canonical.String()
}
// sameOrigin reports whether two URLs have the same scheme, host, and
// port, where an omitted port is the scheme's default.
func sameOrigin(a, b *url.URL) bool {
return strings.EqualFold(a.Scheme, b.Scheme) &&
strings.EqualFold(a.Hostname(), b.Hostname()) &&
portOrDefault(a) == portOrDefault(b)
}
func portOrDefault(u *url.URL) string {
if port := u.Port(); port != "" {
return port
}
switch strings.ToLower(u.Scheme) {
case "http":
return "80"
case "https":
return "443"
default:
return ""
}
}
func withTrailingSlash(path string) string {
if strings.HasSuffix(path, "/") {
return path
+18
View File
@@ -345,6 +345,24 @@ func TestMCPOAuth2ResourceIndicator(t *testing.T) {
advertised: []string{"https://mcp.example.com/mcp"},
want: "https://mcp.example.com/mcp",
},
{
name: "ExplicitDefaultPortOnServer",
serverURL: "https://mcp.example.com:443/mcp",
advertised: []string{"https://mcp.example.com/mcp"},
want: "https://mcp.example.com/mcp",
},
{
name: "ExplicitDefaultPortOnResource",
serverURL: "http://mcp.example.com/mcp",
advertised: []string{"http://mcp.example.com:80/mcp"},
want: "http://mcp.example.com:80/mcp",
},
{
name: "EscapedSlashIsNotSegmentBoundary",
serverURL: "https://mcp.example.com/mcp%2Ftenant",
advertised: []string{"https://mcp.example.com/mcp"},
want: "https://mcp.example.com/mcp%2Ftenant",
},
{
name: "NoEntriesFallsBack",
serverURL: "https://mcp.example.com/mcp",
+7 -2
View File
@@ -1361,7 +1361,7 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) {
require.NoError(t, err)
require.Equal(t, newRevocationURL, updated.OAuth2RevocationURL)
// RFC 8707 resource indicators must be absolute URIs without a
// RFC 8707 resource indicators must be valid absolute URIs without a
// fragment, on both create and update. Create rejects them before
// auto-discovery so an invalid value causes no client registration.
var discoveryRequests atomic.Int64
@@ -1370,7 +1370,12 @@ func TestMCPServerConfigsUserOIDCClearsFields(t *testing.T) {
http.NotFound(w, r)
}))
t.Cleanup(discoveryProbe.Close)
for _, invalidResource := range []string{"https://mcp.example.com/v1#frag", "/v1/mcp"} {
for _, invalidResource := range []string{
"https://mcp.example.com/v1#frag",
"/v1/mcp",
"https://mcp.example.com/a b",
"https://mcp.example.com/mcp?tenant=%zz",
} {
_, err = client.UpdateMCPServerConfig(ctx, created.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{
OAuth2Resource: &invalidResource,
})