registry/internal/validators/registries/mcpb.go
Radoslav Dimitrov 1201cbd82b
security: fix open redirect and add small hardening (#1227)
## What this does

Fixes an open redirect plus a handful of small, mostly-invisible
hardening changes around it.

## What's in it

- **The fix**: trailing-slash redirects no longer let `//evil.com/`
redirect off-host.
- **SSRF block** on the DNS/HTTP namespace verification — refuses to
dial loopback, RFC1918, link-local, multicast, CGNAT, or
IP-literal/single-label \"domains\".
- **Slow-client guard**: `ReadTimeout` and `IdleTimeout` on the HTTP
server (no `WriteTimeout` — would risk cutting off legitimate
multi-package publishes).
- **Defence-in-depth headers** on the UI (`/`) and 404 responses.
- **5xx responses** stop leaking raw DB error text to clients (logged
server-side instead).
- **Search filter** stops treating `%` and `_` as wildcards.
- **Validators**: PyPI/NuGet identifiers URL-escaped before fetching;
MCPB no longer follows redirects.
- **Misc**: `Version` field bounded to 255 chars; logs quote user input;
`BlockedNamespaces` denylist now catches subdomain claimants.

Each change is its own commit so they can be reviewed (or reverted)
independently.

## Test plan

- [ ] CI green
- [ ] Synthetic publish in staging for each package type (npm, pypi,
nuget, oci, mcpb) — confirms validator changes don't regress
- [ ] Quick browser check of `/` after deploy to confirm UI still loads
with the new CSP
- [ ] `curl https://<host>//evil.com/` — confirm the open redirect is
closed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 19:14:00 -04:00

176 lines
6 KiB
Go

package registries
import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/modelcontextprotocol/registry/pkg/model"
)
var (
ErrMissingIdentifierForMCPB = fmt.Errorf("package identifier is required for MCPB packages")
ErrMissingFileSHA256ForMCPB = fmt.Errorf("must include a fileSha256 hash for integrity verification")
)
func ValidateMCPB(ctx context.Context, pkg model.Package, _ string) error {
// MCPB packages must include a file hash for integrity verification
if pkg.FileSHA256 == "" {
return ErrMissingFileSHA256ForMCPB
}
if pkg.Identifier == "" {
return ErrMissingIdentifierForMCPB
}
// Validate that registryBaseUrl is not present
// MCPB packages use full download URLs in identifier
if pkg.RegistryBaseURL != "" {
return fmt.Errorf("MCPB packages must not have 'registryBaseUrl' field - use the full download URL in 'identifier' instead")
}
// Note: version field is optional for MCPB packages
// It can be included for clarity or omitted if the version is embedded in the download URL
err := validateMCPBUrl(pkg.Identifier)
if err != nil {
return err
}
// Parse the URL to validate format
url, err := url.Parse(pkg.Identifier)
if err != nil {
return fmt.Errorf("invalid MCPB package URL: %w", err)
}
if url.Scheme != "https" {
return fmt.Errorf("invalid MCPB package URL, must use HTTPS: %s", pkg.Identifier)
}
// Check that the URL contains 'mcp' somewhere (case-insensitive)
if !strings.Contains(strings.ToLower(pkg.Identifier), "mcp") {
return fmt.Errorf("MCPB package URL must contain 'mcp': %s", pkg.Identifier)
}
// Verify the file exists and is publicly accessible. Refuse to follow
// redirects: the URL allowlist (github.com / gitlab.com) only constrains
// the FIRST hop, and a 30x bouncing through CDN/release-asset hosts
// could otherwise be steered toward attacker infrastructure or
// internal-only endpoints reached via DNS quirks.
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequestWithContext(ctx, http.MethodHead, pkg.Identifier, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to verify MCPB package accessibility: %w", err)
}
defer resp.Body.Close()
// GitHub serves release assets via a 302 to a signed S3 URL; a HEAD that
// returns 200 directly OR a 302 with a Location header is acceptable.
// Any other 3xx without a usable Location is treated as inaccessible.
switch {
case resp.StatusCode == http.StatusOK:
// fine
case resp.StatusCode >= 300 && resp.StatusCode < 400 && resp.Header.Get("Location") != "":
// fine — first-hop allowlist + we don't actually need the body
default:
return fmt.Errorf("MCPB package '%s' is not publicly accessible (status: %d)", pkg.Identifier, resp.StatusCode)
}
return nil
}
func validateMCPBUrl(fullURL string) error {
parsedURL, err := url.Parse(fullURL)
if err != nil {
return fmt.Errorf("invalid MCPB package URL: %w", err)
}
host := strings.ToLower(parsedURL.Host)
allowedHosts := []string{
"github.com",
"www.github.com",
"gitlab.com",
"www.gitlab.com",
}
isAllowed := false
for _, allowed := range allowedHosts {
if host == allowed {
isAllowed = true
break
}
}
if !isAllowed {
return fmt.Errorf("MCPB packages must be hosted on allowlisted providers (GitHub or GitLab). Host '%s' is not allowed", host)
}
// Validate URL path is a proper release URL with strict structure validation
path := parsedURL.Path
switch host {
case "github.com", "www.github.com":
// GitHub release URLs must match: /owner/repo/releases/download/tag/filename
if !isValidGitHubReleaseURL(path) {
return fmt.Errorf("GitHub MCPB packages must be release assets following the pattern '/owner/repo/releases/download/tag/filename'")
}
case "gitlab.com", "www.gitlab.com":
// GitLab release URLs must match specific patterns
if !isValidGitLabReleaseURL(path) {
return fmt.Errorf("GitLab MCPB packages must be release assets following patterns '/owner/repo/-/releases/tag/downloads/filename' or '/owner/repo/-/package_files/id/download'")
}
}
return nil
}
// isValidGitHubReleaseURL validates that a path follows the GitHub release asset pattern
// Pattern: /owner/repo/releases/download/tag/filename
func isValidGitHubReleaseURL(path string) bool {
// GitHub release URL pattern: /owner/repo/releases/download/tag/filename
// - owner: username or organization (1-39 chars, alphanumeric + hyphens, no consecutive hyphens)
// - repo: repository name (similar rules to owner)
// - tag: release tag (can contain various characters but not empty)
// - filename: asset filename (not empty)
pattern := `^/([a-zA-Z0-9]([a-zA-Z0-9\-]{0,37}[a-zA-Z0-9])?)/([a-zA-Z0-9._\-]+)/releases/download/([^/]+)/([^/]+)$`
matched, _ := regexp.MatchString(pattern, path)
return matched
}
// isValidGitLabReleaseURL validates that a path follows GitLab release asset patterns
func isValidGitLabReleaseURL(path string) bool {
// GitLab release URL patterns:
// 1. /owner/repo/-/releases/tag/downloads/filename
// 2. /owner/repo/-/package_files/id/download
// 3. /group/subgroup/repo/-/releases/tag/downloads/filename (nested groups)
// The key insight is that GitLab URLs have "/-/" as a delimiter that separates the
// project path from the GitLab-specific routes. Everything before "/-/" is the project path.
// Pattern 1: Release downloads with /-/releases/tag/downloads/filename
releasePattern := `^/([a-zA-Z0-9._\-]+(?:/[a-zA-Z0-9._\-]+)*)/-/releases/([^/]+)/downloads/([^/]+)$`
if matched, _ := regexp.MatchString(releasePattern, path); matched {
return true
}
// Pattern 2: Package files with /-/package_files/id/download
packagePattern := `^/([a-zA-Z0-9._\-]+(?:/[a-zA-Z0-9._\-]+)*)/-/package_files/([0-9]+)/download$`
if matched, _ := regexp.MatchString(packagePattern, path); matched {
return true
}
return false
}