Add registry validators (#350)
Fixes #96 ## Motivation and Context See #96 ## How Has This Been Tested? Has some unit and integration tests, still needs proper testing of the different registry types ## Breaking Changes Yes, new package uploads will need extra verification ## Types of changes <!-- What types of changes does your code introduce? Put an `x` in all the boxes that apply: --> - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [x] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update
This commit is contained in:
parent
6ea3828e3c
commit
694a4d8879
15 changed files with 1859 additions and 728 deletions
|
|
@ -14,14 +14,13 @@ var (
|
|||
ErrInvalidRemoteURL = errors.New("invalid remote URL")
|
||||
|
||||
// Registry validation errors
|
||||
ErrUnsupportedRegistryType = errors.New("unsupported registry type")
|
||||
ErrUnsupportedRegistryBaseURL = errors.New("unsupported registry base URL")
|
||||
ErrMismatchedRegistryTypeAndURL = errors.New("registry type and base URL do not match")
|
||||
|
||||
// Argument validation errors
|
||||
ErrNamedArgumentNameRequired = errors.New("named argument name is required")
|
||||
ErrInvalidNamedArgumentName = errors.New("invalid named argument name format")
|
||||
ErrArgumentValueStartsWithName = errors.New("argument value cannot start with the argument name")
|
||||
ErrNamedArgumentNameRequired = errors.New("named argument name is required")
|
||||
ErrInvalidNamedArgumentName = errors.New("invalid named argument name format")
|
||||
ErrArgumentValueStartsWithName = errors.New("argument value cannot start with the argument name")
|
||||
ErrArgumentDefaultStartsWithName = errors.New("argument default cannot start with the argument name")
|
||||
)
|
||||
|
||||
|
|
|
|||
29
internal/validators/package.go
Normal file
29
internal/validators/package.go
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package validators
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// ValidatePackage validates that the package referenced in the server configuration is:
|
||||
// 1. allowed on the official registry (based on registry base url); and
|
||||
// 2. owned by the publisher, by checking for a matching server name in the package metadata
|
||||
func ValidatePackage(ctx context.Context, pkg model.Package, serverName string) error {
|
||||
switch pkg.RegistryType {
|
||||
case model.RegistryTypeNPM:
|
||||
return registries.ValidateNPM(ctx, pkg, serverName)
|
||||
case model.RegistryTypePyPI:
|
||||
return registries.ValidatePyPI(ctx, pkg, serverName)
|
||||
case model.RegistryTypeNuGet:
|
||||
return registries.ValidateNuGet(ctx, pkg, serverName)
|
||||
case model.RegistryTypeOCI:
|
||||
return registries.ValidateOCI(ctx, pkg, serverName)
|
||||
case model.RegistryTypeMCPB:
|
||||
return registries.ValidateMCPB(ctx, pkg, serverName)
|
||||
default:
|
||||
return fmt.Errorf("unsupported registry type: %s", pkg.RegistryType)
|
||||
}
|
||||
}
|
||||
167
internal/validators/registries/mcpb.go
Normal file
167
internal/validators/registries/mcpb.go
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
package registries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
func ValidateMCPB(ctx context.Context, pkg model.Package, _ string) error {
|
||||
err := validateMCPBUrl(pkg.Identifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
inferredBaseURL, err := inferMCPBRegistryBaseURL(pkg.Identifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
pkg.RegistryBaseURL = inferredBaseURL
|
||||
} else if pkg.RegistryBaseURL != inferredBaseURL {
|
||||
return fmt.Errorf("MCPB package '%s' has inconsistent registry base URL: %s (expected: %s)",
|
||||
pkg.Identifier, pkg.RegistryBaseURL, inferredBaseURL)
|
||||
}
|
||||
|
||||
// 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
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
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()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
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
|
||||
}
|
||||
|
||||
// inferMCPBRegistryBaseURL infers the registry base URL from an MCPB identifier
|
||||
func inferMCPBRegistryBaseURL(identifier string) (string, error) {
|
||||
parsedURL, err := url.Parse(identifier)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
host := strings.ToLower(parsedURL.Host)
|
||||
switch host {
|
||||
case "github.com", "www.github.com":
|
||||
return model.RegistryURLGitHub, nil
|
||||
case "gitlab.com", "www.gitlab.com":
|
||||
return model.RegistryURLGitLab, nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid host for MCPB package: %s, expected github or gitlab", host)
|
||||
}
|
||||
}
|
||||
81
internal/validators/registries/mcpb_test.go
Normal file
81
internal/validators/registries/mcpb_test.go
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateMCPB(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
packageName string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
name: "valid MCPB package should pass",
|
||||
packageName: "https://github.com/domdomegg/airtable-mcp-server/releases/download/v1.7.2/airtable-mcp-server.mcpb",
|
||||
serverName: "io.github.domdomegg/airtable-mcp-server",
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "valid MCPB package should pass",
|
||||
packageName: "https://github.com/microsoft/playwright-mcp/releases/download/v0.0.36/playwright-mcp-extension-v0.0.36.zip",
|
||||
serverName: "com.microsoft/playwright-mcp",
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "valid MCPB package with .mcpb extension should fail accessibility check",
|
||||
packageName: "https://github.com/example/server/releases/download/v1.0.0/server.mcpb",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "not publicly accessible",
|
||||
},
|
||||
{
|
||||
name: "invalid URL without mcp anywhere should fail",
|
||||
packageName: "https://github.com/example/server/releases/download/v1.0.0/server.tar.gz",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "URL must contain 'mcp'",
|
||||
},
|
||||
{
|
||||
name: "invalid URL format should fail",
|
||||
packageName: "not://a valid url for mcpb!",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "invalid MCPB package URL",
|
||||
},
|
||||
{
|
||||
name: "non-existent file should fail accessibility check",
|
||||
packageName: "https://github.com/nonexistent/repo/releases/download/v1.0.0/mcp-server.tar.gz",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "not publicly accessible",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pkg := model.Package{
|
||||
RegistryType: model.RegistryTypeMCPB,
|
||||
Identifier: tt.packageName,
|
||||
}
|
||||
|
||||
err := registries.ValidateMCPB(ctx, pkg, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.errorMessage)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
66
internal/validators/registries/npm.go
Normal file
66
internal/validators/registries/npm.go
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
package registries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// NPMPackageResponse represents the structure returned by the NPM registry API
|
||||
type NPMPackageResponse struct {
|
||||
MCPName string `json:"mcpName"`
|
||||
}
|
||||
|
||||
// ValidateNPM validates that an NPM package contains the correct MCP server name
|
||||
func ValidateNPM(ctx context.Context, pkg model.Package, serverName string) error {
|
||||
// Set default registry base URL if empty
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
pkg.RegistryBaseURL = model.RegistryURLNPM
|
||||
}
|
||||
|
||||
// Validate that the registry base URL matches NPM exactly
|
||||
if pkg.RegistryBaseURL != model.RegistryURLNPM {
|
||||
return fmt.Errorf("registry type and base URL do not match: '%s' is not valid for registry type '%s'. Expected: %s",
|
||||
pkg.RegistryBaseURL, model.RegistryTypeNPM, model.RegistryURLNPM)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
url := pkg.RegistryBaseURL + "/" + pkg.Identifier + "/" + pkg.Version
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch package metadata from NPM: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("NPM package '%s' not found (status: %d)", pkg.Identifier, resp.StatusCode)
|
||||
}
|
||||
|
||||
var npmResp NPMPackageResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&npmResp); err != nil {
|
||||
return fmt.Errorf("failed to parse NPM package metadata: %w", err)
|
||||
}
|
||||
|
||||
if npmResp.MCPName == "" {
|
||||
return fmt.Errorf("NPM package '%s' is missing required 'mcpName' field. Add this to your package.json: \"mcpName\": \"%s\"", pkg.Identifier, serverName)
|
||||
}
|
||||
|
||||
if npmResp.MCPName != serverName {
|
||||
return fmt.Errorf("NPM package ownership validation failed. Expected mcpName '%s', got '%s'", serverName, npmResp.MCPName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
90
internal/validators/registries/npm_test.go
Normal file
90
internal/validators/registries/npm_test.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateNPM_RealPackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
packageName string
|
||||
version string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
name: "non-existent package should fail",
|
||||
packageName: generateRandomPackageName(),
|
||||
version: "1.0.0",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "not found",
|
||||
},
|
||||
{
|
||||
name: "real package without mcpName should fail",
|
||||
packageName: "express", // Popular package without mcpName field
|
||||
version: "4.18.2",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "missing required 'mcpName' field",
|
||||
},
|
||||
{
|
||||
name: "real package without mcpName should fail",
|
||||
packageName: "lodash", // Another popular package
|
||||
version: "4.17.21",
|
||||
serverName: "com.example/completely-different-name",
|
||||
expectError: true,
|
||||
errorMessage: "missing required 'mcpName' field",
|
||||
},
|
||||
{
|
||||
name: "real package without mcpName should fail",
|
||||
packageName: "airtable-mcp-server",
|
||||
version: "1.5.0",
|
||||
serverName: "io.github.domdomegg/airtable-mcp-server",
|
||||
expectError: true,
|
||||
errorMessage: "missing required 'mcpName' field",
|
||||
},
|
||||
{
|
||||
name: "real package with incorrect mcpName should fail",
|
||||
packageName: "airtable-mcp-server",
|
||||
version: "1.7.2",
|
||||
serverName: "io.github.not-domdomegg/airtable-mcp-server",
|
||||
expectError: true,
|
||||
errorMessage: "Expected mcpName 'io.github.not-domdomegg/airtable-mcp-server', got 'io.github.domdomegg/airtable-mcp-server'",
|
||||
},
|
||||
{
|
||||
name: "real package with correct mcpName should pass",
|
||||
packageName: "airtable-mcp-server",
|
||||
version: "1.7.2",
|
||||
serverName: "io.github.domdomegg/airtable-mcp-server",
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pkg := model.Package{
|
||||
RegistryType: model.RegistryTypeNPM,
|
||||
Identifier: tt.packageName,
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
err := registries.ValidateNPM(ctx, pkg, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.errorMessage)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
67
internal/validators/registries/nuget.go
Normal file
67
internal/validators/registries/nuget.go
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
package registries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// ValidateNuGet validates that a NuGet package contains the correct MCP server name
|
||||
func ValidateNuGet(ctx context.Context, pkg model.Package, serverName string) error {
|
||||
// Set default registry base URL if empty
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
pkg.RegistryBaseURL = model.RegistryURLNuGet
|
||||
}
|
||||
|
||||
// Validate that the registry base URL matches NuGet exactly
|
||||
if pkg.RegistryBaseURL != model.RegistryURLNuGet {
|
||||
return fmt.Errorf("registry type and base URL do not match: '%s' is not valid for registry type '%s'. Expected: %s",
|
||||
pkg.RegistryBaseURL, model.RegistryTypeNuGet, model.RegistryURLNuGet)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
lowerID := strings.ToLower(pkg.Identifier)
|
||||
lowerVersion := strings.ToLower(pkg.Version)
|
||||
if lowerVersion == "" {
|
||||
return fmt.Errorf("NuGet package validation requires a specific version, but none was provided")
|
||||
}
|
||||
|
||||
// Try to get README from the package
|
||||
readmeURL := fmt.Sprintf("%s/v3-flatcontainer/%s/%s/readme", pkg.RegistryBaseURL, lowerID, lowerVersion)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, readmeURL, 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 fetch README from NuGet: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
// Check README content
|
||||
readmeBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read README content: %w", err)
|
||||
}
|
||||
|
||||
readmeContent := string(readmeBytes)
|
||||
|
||||
// Check for mcp-name: format (more specific)
|
||||
mcpNamePattern := "mcp-name: " + serverName
|
||||
if strings.Contains(readmeContent, mcpNamePattern) {
|
||||
return nil // Found as mcp-name: format
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("NuGet package '%s' ownership validation failed. The server name '%s' must appear as 'mcp-name: %s' in the package README. Add it to your package README", pkg.Identifier, serverName, serverName)
|
||||
}
|
||||
90
internal/validators/registries/nuget_test.go
Normal file
90
internal/validators/registries/nuget_test.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateNuGet_RealPackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
packageName string
|
||||
version string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
name: "non-existent package should fail",
|
||||
packageName: generateRandomNuGetPackageName(),
|
||||
version: "1.0.0",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed",
|
||||
},
|
||||
{
|
||||
name: "real package without version should fail",
|
||||
packageName: "Newtonsoft.Json",
|
||||
version: "", // No version provided
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "requires a specific version",
|
||||
},
|
||||
{
|
||||
name: "real package with non-existent version should fail",
|
||||
packageName: "Newtonsoft.Json",
|
||||
version: "999.999.999", // Version that doesn't exist
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed",
|
||||
},
|
||||
{
|
||||
name: "real package without server name in README should fail",
|
||||
packageName: "Newtonsoft.Json",
|
||||
version: "13.0.3", // Popular version
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed",
|
||||
},
|
||||
{
|
||||
name: "real package without server name in README should fail",
|
||||
packageName: "TimeMcpServer",
|
||||
version: "1.0.0",
|
||||
serverName: "io.github.domdomegg/time-mcp-server",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed",
|
||||
},
|
||||
{
|
||||
name: "real package with server name in README should pass",
|
||||
packageName: "TimeMcpServer",
|
||||
version: "1.0.2",
|
||||
serverName: "io.github.domdomegg/time-mcp-server",
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pkg := model.Package{
|
||||
RegistryType: model.RegistryTypeNuGet,
|
||||
Identifier: tt.packageName,
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
err := registries.ValidateNuGet(ctx, pkg, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.errorMessage)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
260
internal/validators/registries/oci.go
Normal file
260
internal/validators/registries/oci.go
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
package registries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
const (
|
||||
dockerIoAPIBaseURL = "https://registry-1.docker.io"
|
||||
)
|
||||
|
||||
// OCIAuthResponse represents the Docker Hub authentication response
|
||||
type OCIAuthResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// OCIManifest represents an OCI image manifest
|
||||
type OCIManifest struct {
|
||||
Manifests []struct {
|
||||
Digest string `json:"digest"`
|
||||
} `json:"manifests,omitempty"`
|
||||
Config struct {
|
||||
Digest string `json:"digest"`
|
||||
} `json:"config,omitempty"`
|
||||
}
|
||||
|
||||
// OCIImageConfig represents an OCI image configuration
|
||||
type OCIImageConfig struct {
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"config"`
|
||||
}
|
||||
|
||||
// ValidateOCI validates that an OCI image contains the correct MCP server name annotation
|
||||
func ValidateOCI(ctx context.Context, pkg model.Package, serverName string) error {
|
||||
// Set default registry base URL if empty
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
pkg.RegistryBaseURL = model.RegistryURLDocker
|
||||
}
|
||||
|
||||
// Validate that the registry base URL matches OCI/Docker exactly
|
||||
if pkg.RegistryBaseURL != model.RegistryURLDocker {
|
||||
return fmt.Errorf("registry type and base URL do not match: '%s' is not valid for registry type '%s'. Expected: %s",
|
||||
pkg.RegistryBaseURL, model.RegistryTypeOCI, model.RegistryURLDocker)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// Parse image reference (namespace/repo or repo)
|
||||
namespace, repo, err := parseImageReference(pkg.Identifier)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid OCI image reference: %w", err)
|
||||
}
|
||||
|
||||
apiBaseURL := pkg.RegistryBaseURL
|
||||
if pkg.RegistryBaseURL == model.RegistryURLDocker {
|
||||
// docker.io is an exceptional registry that was created before standardisation, so needs a custom API base url
|
||||
// https://github.com/containers/image/blob/5e4845dddd57598eb7afeaa6e0f4c76531bd3c91/docker/docker_client.go#L225-L229
|
||||
apiBaseURL = dockerIoAPIBaseURL
|
||||
}
|
||||
|
||||
tag := pkg.Version
|
||||
manifestURL := fmt.Sprintf("%s/v2/%s/%s/manifests/%s", apiBaseURL, namespace, repo, tag)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create manifest request: %w", err)
|
||||
}
|
||||
|
||||
// Get auth token for docker.io
|
||||
// We only support auth for docker.io, other registries must allow unauthed requests
|
||||
if apiBaseURL == dockerIoAPIBaseURL {
|
||||
token, err := getDockerIoAuthToken(ctx, client, namespace, repo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to authenticate with Docker registry: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.manifest.v1+json")
|
||||
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch OCI manifest: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusUnauthorized {
|
||||
return fmt.Errorf("OCI image '%s/%s:%s' not found (status: %d)", namespace, repo, tag, resp.StatusCode)
|
||||
}
|
||||
if resp.StatusCode == http.StatusTooManyRequests {
|
||||
// Rate limited, skip validation for now
|
||||
log.Printf("Warning: Rate limited when accessing OCI image '%s/%s:%s'. Skipping validation.", namespace, repo, tag)
|
||||
return nil
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to fetch OCI manifest (status: %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
var manifest OCIManifest
|
||||
if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {
|
||||
return fmt.Errorf("failed to parse OCI manifest: %w", err)
|
||||
}
|
||||
|
||||
// Handle multi-arch images by using first manifest
|
||||
var configDigest string
|
||||
if len(manifest.Manifests) > 0 {
|
||||
// This is a multi-arch image, get the specific manifest
|
||||
specificManifest, err := getSpecificManifest(ctx, client, apiBaseURL, namespace, repo, manifest.Manifests[0].Digest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get specific manifest: %w", err)
|
||||
}
|
||||
configDigest = specificManifest.Config.Digest
|
||||
} else {
|
||||
configDigest = manifest.Config.Digest
|
||||
}
|
||||
|
||||
if configDigest == "" {
|
||||
return fmt.Errorf("unable to determine image config digest for '%s/%s:%s'", namespace, repo, tag)
|
||||
}
|
||||
|
||||
// Get image config (contains labels)
|
||||
config, err := getImageConfig(ctx, client, apiBaseURL, namespace, repo, configDigest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get image config: %w", err)
|
||||
}
|
||||
|
||||
mcpName, exists := config.Config.Labels["io.modelcontextprotocol.server.name"]
|
||||
if !exists {
|
||||
return fmt.Errorf("OCI image '%s/%s:%s' is missing required annotation. Add this to your Dockerfile: LABEL io.modelcontextprotocol.server.name=\"%s\"", namespace, repo, tag, serverName)
|
||||
}
|
||||
|
||||
if mcpName != serverName {
|
||||
return fmt.Errorf("OCI image ownership validation failed. Expected annotation 'io.modelcontextprotocol.server.name' = '%s', got '%s'", serverName, mcpName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseImageReference(identifier string) (string, string, error) {
|
||||
parts := strings.Split(identifier, "/")
|
||||
switch len(parts) {
|
||||
case 2:
|
||||
return parts[0], parts[1], nil
|
||||
case 1:
|
||||
return "library", parts[0], nil
|
||||
default:
|
||||
return "", "", fmt.Errorf("invalid image reference: %s", identifier)
|
||||
}
|
||||
}
|
||||
|
||||
// getDockerIoAuthToken retrieves an authentication token from Docker Hub
|
||||
func getDockerIoAuthToken(ctx context.Context, client *http.Client, namespace, repo string) (string, error) {
|
||||
authURL := fmt.Sprintf("https://auth.docker.io/token?service=registry.docker.io&scope=repository:%s/%s:pull", namespace, repo)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, authURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create auth request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to request auth token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("auth request failed with status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var authResp OCIAuthResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
|
||||
return "", fmt.Errorf("failed to parse auth response: %w", err)
|
||||
}
|
||||
|
||||
return authResp.Token, nil
|
||||
}
|
||||
|
||||
// getSpecificManifest retrieves a specific manifest for multi-arch images
|
||||
func getSpecificManifest(ctx context.Context, client *http.Client, apiBaseURL, namespace, repo, digest string) (*OCIManifest, error) {
|
||||
manifestURL := fmt.Sprintf("%s/v2/%s/%s/manifests/%s", apiBaseURL, namespace, repo, digest)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create specific manifest request: %w", err)
|
||||
}
|
||||
|
||||
// Get auth token for docker.io
|
||||
if apiBaseURL == dockerIoAPIBaseURL {
|
||||
token, err := getDockerIoAuthToken(ctx, client, namespace, repo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to authenticate with Docker registry: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/vnd.oci.image.manifest.v1+json")
|
||||
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch specific manifest: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("specific manifest not found (status: %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
var manifest OCIManifest
|
||||
if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse specific manifest: %w", err)
|
||||
}
|
||||
|
||||
return &manifest, nil
|
||||
}
|
||||
|
||||
// getImageConfig retrieves the image configuration containing labels
|
||||
func getImageConfig(ctx context.Context, client *http.Client, apiBaseURL, namespace, repo, configDigest string) (*OCIImageConfig, error) {
|
||||
configURL := fmt.Sprintf("%s/v2/%s/%s/blobs/%s", apiBaseURL, namespace, repo, configDigest)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, configURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create config request: %w", err)
|
||||
}
|
||||
|
||||
// Get auth token for docker.io
|
||||
if apiBaseURL == dockerIoAPIBaseURL {
|
||||
token, err := getDockerIoAuthToken(ctx, client, namespace, repo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to authenticate with Docker registry: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json")
|
||||
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch image config: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("image config not found (status: %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
var config OCIImageConfig
|
||||
if err := json.NewDecoder(resp.Body).Decode(&config); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse image config: %w", err)
|
||||
}
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
84
internal/validators/registries/oci_test.go
Normal file
84
internal/validators/registries/oci_test.go
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateOCI_RealPackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
packageName string
|
||||
version string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
name: "non-existent image should fail",
|
||||
packageName: generateRandomImageName(),
|
||||
version: "latest",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "not found",
|
||||
},
|
||||
{
|
||||
name: "real image without MCP annotation should fail",
|
||||
packageName: "nginx", // Popular image without MCP annotation
|
||||
version: "latest",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "missing required annotation",
|
||||
},
|
||||
{
|
||||
name: "real image with specific tag without MCP annotation should fail",
|
||||
packageName: "redis",
|
||||
version: "7-alpine", // Specific tag
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "missing required annotation",
|
||||
},
|
||||
{
|
||||
name: "namespaced image without MCP annotation should fail",
|
||||
packageName: "hello-world", // Simple image for testing
|
||||
version: "latest",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "missing required annotation",
|
||||
},
|
||||
{
|
||||
name: "real image with correct MCP annotation should pass",
|
||||
packageName: "domdomegg/airtable-mcp-server",
|
||||
version: "1.7.2",
|
||||
serverName: "io.github.domdomegg/airtable-mcp-server", // This should match the annotation
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Skip("Skipping OCI registry tests because we keep hitting DockerHub rate limits")
|
||||
|
||||
pkg := model.Package{
|
||||
RegistryType: model.RegistryTypeOCI,
|
||||
Identifier: tt.packageName,
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
err := registries.ValidateOCI(ctx, pkg, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.errorMessage)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
70
internal/validators/registries/pypi.go
Normal file
70
internal/validators/registries/pypi.go
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
package registries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// PyPIPackageResponse represents the structure returned by the PyPI JSON API
|
||||
type PyPIPackageResponse struct {
|
||||
Info struct {
|
||||
Description string `json:"description"`
|
||||
} `json:"info"`
|
||||
}
|
||||
|
||||
// ValidatePyPI validates that a PyPI package contains the correct MCP server name
|
||||
func ValidatePyPI(ctx context.Context, pkg model.Package, serverName string) error {
|
||||
// Set default registry base URL if empty
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
pkg.RegistryBaseURL = model.RegistryURLPyPI
|
||||
}
|
||||
|
||||
// Validate that the registry base URL matches PyPI exactly
|
||||
if pkg.RegistryBaseURL != model.RegistryURLPyPI {
|
||||
return fmt.Errorf("registry type and base URL do not match: '%s' is not valid for registry type '%s'. Expected: %s",
|
||||
pkg.RegistryBaseURL, model.RegistryTypePyPI, model.RegistryURLPyPI)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
url := fmt.Sprintf("%s/pypi/%s/json", pkg.RegistryBaseURL, pkg.Identifier)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch package metadata from PyPI: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("PyPI package '%s' not found (status: %d)", pkg.Identifier, resp.StatusCode)
|
||||
}
|
||||
|
||||
var pypiResp PyPIPackageResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&pypiResp); err != nil {
|
||||
return fmt.Errorf("failed to parse PyPI package metadata: %w", err)
|
||||
}
|
||||
|
||||
// Check description (README) content
|
||||
description := pypiResp.Info.Description
|
||||
|
||||
// Check for mcp-name: format (more specific)
|
||||
mcpNamePattern := "mcp-name: " + serverName
|
||||
if strings.Contains(description, mcpNamePattern) {
|
||||
return nil // Found as mcp-name: format
|
||||
}
|
||||
|
||||
return fmt.Errorf("PyPI package '%s' ownership validation failed. The server name '%s' must appear as 'mcp-name: %s' in the package README", pkg.Identifier, serverName, serverName)
|
||||
}
|
||||
74
internal/validators/registries/pypi_test.go
Normal file
74
internal/validators/registries/pypi_test.go
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators/registries"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidatePyPI_RealPackages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
packageName string
|
||||
version string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
name: "non-existent package should fail",
|
||||
packageName: generateRandomPackageName(),
|
||||
version: "1.0.0",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "not found",
|
||||
},
|
||||
{
|
||||
name: "real package without MCP server name should fail",
|
||||
packageName: "requests", // Popular package without MCP server name in keywords/description/URLs
|
||||
version: "2.31.0",
|
||||
serverName: "com.example/test",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed",
|
||||
},
|
||||
{
|
||||
name: "real package with different server name should fail",
|
||||
packageName: "numpy", // Another popular package
|
||||
version: "1.25.2",
|
||||
serverName: "com.example/completely-different-name",
|
||||
expectError: true,
|
||||
errorMessage: "ownership validation failed", // Will fail because numpy doesn't have this server name
|
||||
},
|
||||
{
|
||||
name: "real package with server name in README should pass",
|
||||
packageName: "time-mcp-pypi",
|
||||
version: "1.0.0",
|
||||
serverName: "io.github.domdomegg/time-mcp-pypi",
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pkg := model.Package{
|
||||
RegistryType: model.RegistryTypePyPI,
|
||||
Identifier: tt.packageName,
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
err := registries.ValidatePyPI(ctx, pkg, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.errorMessage)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
32
internal/validators/registries/testutils_test.go
Normal file
32
internal/validators/registries/testutils_test.go
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
package registries_test
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func generateRandomPackageName() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
// Fallback to a static name if crypto/rand fails
|
||||
return "nonexistent-pkg-fallback"
|
||||
}
|
||||
return fmt.Sprintf("nonexistent-pkg-%s", hex.EncodeToString(bytes))
|
||||
}
|
||||
|
||||
func generateRandomNuGetPackageName() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "NonExistent.Package.Fallback"
|
||||
}
|
||||
return fmt.Sprintf("NonExistent.Package.%s", hex.EncodeToString(bytes)[:16])
|
||||
}
|
||||
|
||||
func generateRandomImageName() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "nonexistent-image-fallback"
|
||||
}
|
||||
return fmt.Sprintf("nonexistent-image-%s", hex.EncodeToString(bytes)[:16])
|
||||
}
|
||||
|
|
@ -1,13 +1,14 @@
|
|||
package validators
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
|
@ -24,19 +25,13 @@ func ValidateServerJSON(serverJSON *apiv0.ServerJSON) error {
|
|||
}
|
||||
|
||||
// Validate all packages (basic field validation)
|
||||
// Detailed package validation (including registry checks) is done during publish
|
||||
for _, pkg := range serverJSON.Packages {
|
||||
if err := validatePackageField(&pkg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all packages (URL and registry type validation)
|
||||
for _, pkg := range serverJSON.Packages {
|
||||
if err := validatePackage(&pkg); err != nil {
|
||||
return fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate all remotes
|
||||
for _, remote := range serverJSON.Remotes {
|
||||
if err := validateRemote(&remote); err != nil {
|
||||
|
|
@ -142,230 +137,8 @@ func validateRemote(obj *model.Remote) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validateMCPBPackage(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
|
||||
}
|
||||
|
||||
// getDefaultRegistryBaseURL returns the default registry base URL for a given registry type
|
||||
func getDefaultRegistryBaseURL(registryType string) string {
|
||||
defaultURLs := map[string]string{
|
||||
model.RegistryTypeNPM: model.RegistryURLNPM,
|
||||
model.RegistryTypePyPI: model.RegistryURLPyPI,
|
||||
model.RegistryTypeOCI: model.RegistryURLDocker,
|
||||
model.RegistryTypeNuGet: model.RegistryURLNuGet,
|
||||
}
|
||||
|
||||
return defaultURLs[registryType]
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// inferMCPBRegistryBaseURL infers the registry base URL from an MCPB identifier
|
||||
func inferMCPBRegistryBaseURL(identifier string) string {
|
||||
parsedURL, err := url.Parse(identifier)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
host := strings.ToLower(parsedURL.Host)
|
||||
switch host {
|
||||
case "github.com", "www.github.com":
|
||||
return model.RegistryURLGitHub
|
||||
case "gitlab.com", "www.gitlab.com":
|
||||
return model.RegistryURLGitLab
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// validateRegistryType checks if the registry type is supported
|
||||
func validateRegistryType(registryType string) error {
|
||||
// Registry type is required
|
||||
if registryType == "" {
|
||||
return fmt.Errorf("%w: registry type is required", ErrUnsupportedRegistryType)
|
||||
}
|
||||
|
||||
supportedTypes := []string{
|
||||
model.RegistryTypeNPM,
|
||||
model.RegistryTypePyPI,
|
||||
model.RegistryTypeOCI,
|
||||
model.RegistryTypeNuGet,
|
||||
model.RegistryTypeMCPB,
|
||||
}
|
||||
|
||||
for _, supported := range supportedTypes {
|
||||
if registryType == supported {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: '%s'. Supported types: %v", ErrUnsupportedRegistryType, registryType, supportedTypes)
|
||||
}
|
||||
|
||||
// validateRegistryBaseURL checks if the registry base URL is valid for the given registry type
|
||||
func validateRegistryBaseURL(registryType, baseURL string) error {
|
||||
// Base URL is required for all registry types except MCPB (which uses direct URLs)
|
||||
if baseURL == "" {
|
||||
if registryType == model.RegistryTypeMCPB {
|
||||
return nil // MCPB packages use direct URLs in the identifier
|
||||
}
|
||||
return fmt.Errorf("%w: registry base URL is required for registry type '%s'", ErrUnsupportedRegistryBaseURL, registryType)
|
||||
}
|
||||
|
||||
// Define expected base URLs for each registry type
|
||||
expectedURLs := map[string][]string{
|
||||
model.RegistryTypeNPM: {model.RegistryURLNPM},
|
||||
model.RegistryTypePyPI: {model.RegistryURLPyPI},
|
||||
model.RegistryTypeOCI: {model.RegistryURLDocker},
|
||||
model.RegistryTypeNuGet: {model.RegistryURLNuGet},
|
||||
model.RegistryTypeMCPB: {model.RegistryURLGitHub, model.RegistryURLGitLab},
|
||||
}
|
||||
|
||||
// Check if the base URL is valid for the registry type
|
||||
if expectedURLsForType, exists := expectedURLs[registryType]; exists {
|
||||
for _, expected := range expectedURLsForType {
|
||||
if baseURL == expected {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w: '%s' is not valid for registry type '%s'. Expected: %v",
|
||||
ErrMismatchedRegistryTypeAndURL, baseURL, registryType, expectedURLsForType)
|
||||
}
|
||||
|
||||
// If registry type is not in our expected URLs map but base URL is provided,
|
||||
// it's likely an unsupported base URL
|
||||
return fmt.Errorf("%w: '%s'", ErrUnsupportedRegistryBaseURL, baseURL)
|
||||
}
|
||||
|
||||
func validatePackage(pkg *model.Package) error {
|
||||
registryType := strings.ToLower(pkg.RegistryType)
|
||||
|
||||
// Only validate if package has an identifier (i.e., it's a real package reference)
|
||||
if pkg.Identifier != "" {
|
||||
// Validate registry type is supported
|
||||
if err := validateRegistryType(registryType); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Apply defaults for registry base URL if empty
|
||||
if pkg.RegistryBaseURL == "" {
|
||||
if registryType == model.RegistryTypeMCPB {
|
||||
// For MCPB, infer from identifier
|
||||
pkg.RegistryBaseURL = inferMCPBRegistryBaseURL(pkg.Identifier)
|
||||
} else {
|
||||
// For other types, use default
|
||||
pkg.RegistryBaseURL = getDefaultRegistryBaseURL(registryType)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate registry base URL matches the registry type
|
||||
if err := validateRegistryBaseURL(registryType, pkg.RegistryBaseURL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// For direct download packages (mcpb or direct URLs)
|
||||
if registryType == model.RegistryTypeMCPB ||
|
||||
strings.HasPrefix(pkg.Identifier, "http://") || strings.HasPrefix(pkg.Identifier, "https://") {
|
||||
parsedURL, err := url.Parse(pkg.Identifier)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid package URL: %w", err)
|
||||
}
|
||||
|
||||
// For MCPB packages, validate they're from allowed hosts and are release URLs
|
||||
if registryType == model.RegistryTypeMCPB {
|
||||
return validateMCPBPackage(pkg.Identifier)
|
||||
}
|
||||
|
||||
// For other URL-based packages, just ensure it's valid
|
||||
if parsedURL.Scheme == "" || parsedURL.Host == "" {
|
||||
return fmt.Errorf("package URL must be a valid absolute URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// For other registry-based packages, no special validation needed
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidatePublishRequest validates a complete publish request including extensions
|
||||
func ValidatePublishRequest(req apiv0.ServerJSON) error {
|
||||
func ValidatePublishRequest(req apiv0.ServerJSON, cfg *config.Config) error {
|
||||
// Validate publisher extensions in _meta
|
||||
if err := validatePublisherExtensions(req); err != nil {
|
||||
return err
|
||||
|
|
@ -376,6 +149,16 @@ func ValidatePublishRequest(req apiv0.ServerJSON) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Validate registry ownership for all packages if validation is enabled and server is not deleted
|
||||
if cfg.EnableRegistryValidation && req.Status != model.StatusDeleted {
|
||||
ctx := context.Background()
|
||||
for i, pkg := range req.Packages {
|
||||
if err := ValidatePackage(ctx, pkg, req.Name); err != nil {
|
||||
return fmt.Errorf("registry validation failed for package %d (%s): %w", i, pkg.Identifier, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@ package validators_test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
|
|
@ -649,38 +649,47 @@ func TestValidateArgument_ValidValueFields(t *testing.T) {
|
|||
}
|
||||
|
||||
// Helper function to create a valid server with a specific argument for testing
|
||||
func TestValidate_RegistryTypes(t *testing.T) {
|
||||
func TestValidate_RegistryTypesAndUrls(t *testing.T) {
|
||||
testCases := []struct {
|
||||
tcName string
|
||||
name string
|
||||
registryType string
|
||||
baseURL string
|
||||
identifier string
|
||||
version string
|
||||
expectError bool
|
||||
}{
|
||||
// Valid registry types (should pass)
|
||||
{"valid_npm", model.RegistryTypeNPM, model.RegistryURLNPM, "test-package", false},
|
||||
{"valid_pypi", model.RegistryTypePyPI, model.RegistryURLPyPI, "test-package", false},
|
||||
{"valid_oci", model.RegistryTypeOCI, model.RegistryURLDocker, "test-package", false},
|
||||
{"valid_nuget", model.RegistryTypeNuGet, model.RegistryURLNuGet, "test-package", false},
|
||||
{"valid_mcpb_github", model.RegistryTypeMCPB, model.RegistryURLGitHub, "https://github.com/owner/repo/releases/download/v1.0.0/package.mcpb", false},
|
||||
{"valid_mcpb_gitlab", model.RegistryTypeMCPB, model.RegistryURLGitLab, "https://gitlab.com/owner/repo/-/releases/v1.0.0/downloads/package.mcpb", false},
|
||||
{"valid_npm", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeNPM, model.RegistryURLNPM, "airtable-mcp-server", "1.7.2", false},
|
||||
{"valid_npm", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeNPM, "", "airtable-mcp-server", "1.7.2", false},
|
||||
{"valid_pypi", "io.github.domdomegg/time-mcp-pypi", model.RegistryTypePyPI, model.RegistryURLPyPI, "time-mcp-pypi", "1.0.1", false},
|
||||
{"valid_pypi", "io.github.domdomegg/time-mcp-pypi", model.RegistryTypePyPI, "", "time-mcp-pypi", "1.0.1", false},
|
||||
{"valid_oci", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeOCI, model.RegistryURLDocker, "domdomegg/airtable-mcp-server", "1.7.2", false},
|
||||
{"valid_nuget", "io.github.domdomegg/time-mcp-server", model.RegistryTypeNuGet, model.RegistryURLNuGet, "TimeMcpServer", "1.0.2", false},
|
||||
{"valid_nuget", "io.github.domdomegg/time-mcp-server", model.RegistryTypeNuGet, "", "TimeMcpServer", "1.0.2", false},
|
||||
{"valid_mcpb_github", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeMCPB, model.RegistryURLGitHub, "https://github.com/domdomegg/airtable-mcp-server/releases/download/v1.7.2/airtable-mcp-server.mcpb", "1.7.2", false},
|
||||
{"valid_mcpb_github", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeMCPB, "", "https://github.com/domdomegg/airtable-mcp-server/releases/download/v1.7.2/airtable-mcp-server.mcpb", "1.7.2", false},
|
||||
{"valid_mcpb_gitlab", "io.gitlab.fforster/gitlab-mcp", model.RegistryTypeMCPB, model.RegistryURLGitLab, "https://gitlab.com/fforster/gitlab-mcp/-/releases/v1.31.0/downloads/gitlab-mcp_1.31.0_Linux_x86_64.tar.gz", "1.31.0", false}, // this is not actually a valid mcpb, but it's the closest I can get for testing for now
|
||||
{"valid_mcpb_gitlab", "io.gitlab.fforster/gitlab-mcp", model.RegistryTypeMCPB, "", "https://gitlab.com/fforster/gitlab-mcp/-/releases/v1.31.0/downloads/gitlab-mcp_1.31.0_Linux_x86_64.tar.gz", "1.31.0", false}, // this is not actually a valid mcpb, but it's the closest I can get for testing for now
|
||||
|
||||
// Invalid registry types (should fail)
|
||||
{"invalid_maven", "maven", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_cargo", "cargo", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_gem", "gem", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_invalid", "invalid", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_unknown", "UNKNOWN", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_custom", "custom-registry", "https://example.com/registry", "test-package", true},
|
||||
{"invalid_github", "github", "https://example.com/registry", "test-package", true}, // This is a source, not a registry type
|
||||
{"invalid_docker", "docker", "https://example.com/registry", "test-package", true}, // Should be "oci"
|
||||
{"invalid_empty", "", "https://example.com/registry", "test-package", true}, // Empty registry type
|
||||
{"invalid_maven", "io.github.domdomegg/airtable-mcp-server", "maven", model.RegistryURLNPM, "airtable-mcp-server", "1.7.2", true},
|
||||
{"invalid_cargo", "io.github.domdomegg/time-mcp-pypi", "cargo", model.RegistryURLPyPI, "time-mcp-pypi", "1.0.1", true},
|
||||
{"invalid_gem", "io.github.domdomegg/airtable-mcp-server", "gem", model.RegistryURLDocker, "domdomegg/airtable-mcp-server", "1.7.2", true},
|
||||
{"invalid_unknown", "io.github.domdomegg/time-mcp-server", "unknown", model.RegistryURLNuGet, "TimeMcpServer", "1.0.2", true},
|
||||
{"invalid_blank", "io.github.domdomegg/time-mcp-server", "", model.RegistryURLNuGet, "TimeMcpServer", "1.0.2", true},
|
||||
{"invalid_docker", "io.github.domdomegg/airtable-mcp-server", "docker", model.RegistryURLDocker, "domdomegg/airtable-mcp-server", "1.7.2", true}, // should be oci
|
||||
{"invalid_github", "io.github.domdomegg/airtable-mcp-server", "github", model.RegistryURLGitHub, "https://github.com/domdomegg/airtable-mcp-server/releases/download/v1.7.2/airtable-mcp-server.mcpb", "1.7.2", true}, // should be mcpb
|
||||
|
||||
{"invalid_mix_1", "io.github.domdomegg/time-mcp-server", model.RegistryTypeNuGet, model.RegistryURLNPM, "TimeMcpServer", "1.0.2", true},
|
||||
{"invalid_mix_2", "io.github.domdomegg/airtable-mcp-server", model.RegistryTypeOCI, model.RegistryURLNPM, "domdomegg/airtable-mcp-server", "1.7.2", true},
|
||||
{"invalid_mix_3", "io.github.domdomegg/airtable-mcp-server", model.RegistryURLNPM, model.RegistryURLNPM, "airtable-mcp-server", "1.7.2", true},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
serverDetail := apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
t.Run(tc.tcName, func(t *testing.T) {
|
||||
serverJSON := apiv0.ServerJSON{
|
||||
Name: tc.name,
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/owner/repo",
|
||||
|
|
@ -695,19 +704,16 @@ func TestValidate_RegistryTypes(t *testing.T) {
|
|||
Identifier: tc.identifier,
|
||||
RegistryType: tc.registryType,
|
||||
RegistryBaseURL: tc.baseURL,
|
||||
},
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
Version: tc.version,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := validators.ValidateServerJSON(&serverDetail)
|
||||
err := validators.ValidatePublishRequest(serverJSON, &config.Config{
|
||||
EnableRegistryValidation: true,
|
||||
})
|
||||
if tc.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), validators.ErrUnsupportedRegistryType.Error())
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
|
@ -715,119 +721,6 @@ func TestValidate_RegistryTypes(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestValidate_RegistryBaseURLs(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
registryType string
|
||||
baseURL string
|
||||
identifier string
|
||||
expectError bool
|
||||
}{
|
||||
// Invalid base URLs for specific registry types
|
||||
{"npm_wrong_url", model.RegistryTypeNPM, "https://pypi.org", "test-package", true},
|
||||
{"pypi_wrong_url", model.RegistryTypePyPI, "https://registry.npmjs.org", "test-package", true},
|
||||
{"oci_wrong_url", model.RegistryTypeOCI, "https://registry.npmjs.org", "test-package", true},
|
||||
{"nuget_wrong_url", model.RegistryTypeNuGet, "https://docker.io", "test-package", true},
|
||||
{"mcpb_wrong_url", model.RegistryTypeMCPB, "https://evil.com", "https://github.com/owner/repo", true},
|
||||
{"mismatched_base_url_1", model.RegistryTypeNPM, model.RegistryURLDocker, "test-package", true},
|
||||
{"mismatched_base_url_2", model.RegistryTypeOCI, model.RegistryTypeNuGet, "test-package", true},
|
||||
|
||||
// Localhost URLs should be rejected - no development exceptions
|
||||
{"localhost_npm", model.RegistryTypeNPM, "http://localhost:3000", "test-package", true},
|
||||
{"localhost_ip", model.RegistryTypePyPI, "http://127.0.0.1:8080", "test-package", true},
|
||||
|
||||
// Valid combinations (should pass)
|
||||
{"valid_npm", model.RegistryTypeNPM, model.RegistryURLNPM, "test-package", false},
|
||||
{"valid_pypi", model.RegistryTypePyPI, model.RegistryURLPyPI, "test-package", false},
|
||||
{"valid_oci", model.RegistryTypeOCI, model.RegistryURLDocker, "test-package", false},
|
||||
{"valid_nuget", model.RegistryTypeNuGet, model.RegistryURLNuGet, "test-package", false},
|
||||
{"valid_mcpb_github", model.RegistryTypeMCPB, model.RegistryURLGitHub, "https://github.com/owner/repo/releases/download/v1.0.0/package.mcpb", false},
|
||||
{"valid_mcpb_gitlab", model.RegistryTypeMCPB, model.RegistryURLGitLab, "https://gitlab.com/owner/repo/-/releases/v1.0.0/downloads/package.mcpb", false},
|
||||
{"empty_base_url_npm", model.RegistryTypeNPM, "", "test-package", false}, // should be inferred
|
||||
{"empty_base_url_nuget", model.RegistryTypeNuGet, "", "test-package", false}, // should be inferred
|
||||
{"empty_base_url_mcpb", model.RegistryTypeMCPB, "", "https://github.com/owner/repo/releases/download/v1.0.0/package.mcpb", false},
|
||||
|
||||
// Trailing slash URLs should be rejected - strict exact match only
|
||||
{"npm_trailing_slash", model.RegistryTypeNPM, "https://registry.npmjs.org/", "test-package", true},
|
||||
{"pypi_trailing_slash", model.RegistryTypePyPI, "https://pypi.org/", "test-package", true},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
serverDetail := apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/owner/repo",
|
||||
Source: "github",
|
||||
ID: "owner/repo",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Packages: []model.Package{
|
||||
{
|
||||
Identifier: tc.identifier,
|
||||
RegistryType: tc.registryType,
|
||||
RegistryBaseURL: tc.baseURL,
|
||||
},
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := validators.ValidateServerJSON(&serverDetail)
|
||||
if tc.expectError {
|
||||
assert.Error(t, err)
|
||||
// Check that the error is related to registry validation
|
||||
errStr := err.Error()
|
||||
assert.True(t,
|
||||
strings.Contains(errStr, validators.ErrUnsupportedRegistryBaseURL.Error()) ||
|
||||
strings.Contains(errStr, validators.ErrMismatchedRegistryTypeAndURL.Error()),
|
||||
"Expected registry validation error, got: %s", errStr)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate_EmptyRegistryType(t *testing.T) {
|
||||
// Test that empty registry type is rejected
|
||||
serverDetail := apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/owner/repo",
|
||||
Source: "github",
|
||||
ID: "owner/repo",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Packages: []model.Package{
|
||||
{
|
||||
Identifier: "test-package",
|
||||
RegistryType: "", // Empty registry type
|
||||
RegistryBaseURL: "",
|
||||
},
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := validators.ValidateServerJSON(&serverDetail)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), validators.ErrUnsupportedRegistryType.Error())
|
||||
assert.Contains(t, err.Error(), "registry type is required")
|
||||
}
|
||||
|
||||
func createValidServerWithArgument(arg model.Argument) apiv0.ServerJSON {
|
||||
return apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
|
|
@ -855,72 +748,3 @@ func createValidServerWithArgument(arg model.Argument) apiv0.ServerJSON {
|
|||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate_MCPBReleaseURLs(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
identifier string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
// Valid GitHub release URLs
|
||||
{"valid_github_release", "https://github.com/owner/repo/releases/download/v1.0.0/package.mcpb", false, ""},
|
||||
{"valid_github_release_with_path", "https://github.com/org/project/releases/download/v2.1.0/my-server.mcpb", false, ""},
|
||||
{"valid_github_complex_tag", "https://github.com/owner/repo/releases/download/v1.0.0-alpha.1+build.123/package.mcpb", false, ""},
|
||||
{"valid_github_single_char_owner", "https://github.com/a/b/releases/download/v1.0.0/package.mcpb", false, ""},
|
||||
|
||||
// Valid GitLab release URLs
|
||||
{"valid_gitlab_releases", "https://gitlab.com/owner/repo/-/releases/v1.0.0/downloads/package.mcpb", false, ""},
|
||||
{"valid_gitlab_package_files", "https://gitlab.com/owner/repo/-/package_files/123/download", false, ""},
|
||||
{"valid_gitlab_nested_group", "https://gitlab.com/group/subgroup/repo/-/releases/v1.0.0/downloads/package.mcpb", false, ""},
|
||||
{"valid_gitlab_deep_nested", "https://gitlab.com/org/team/project/repo/-/releases/v2.0.0/downloads/server.mcpb", false, ""},
|
||||
|
||||
// Invalid GitHub URLs (not release URLs)
|
||||
{"invalid_github_root", "https://github.com/owner/repo", true, "GitHub MCPB packages must be release assets"},
|
||||
{"invalid_github_tree", "https://github.com/owner/repo/tree/main", true, "GitHub MCPB packages must be release assets"},
|
||||
{"invalid_github_blob", "https://github.com/owner/repo/blob/main/file.mcpb", true, "GitHub MCPB packages must be release assets"},
|
||||
{"invalid_github_fake_release_path", "https://github.com/owner/repo/fake/releases/download/v1.0.0/file.mcpb", true, "GitHub MCPB packages must be release assets"},
|
||||
{"invalid_github_missing_tag", "https://github.com/owner/repo/releases/download//file.mcpb", true, "GitHub MCPB packages must be release assets"},
|
||||
{"invalid_github_missing_filename", "https://github.com/owner/repo/releases/download/v1.0.0/", true, "GitHub MCPB packages must be release assets"},
|
||||
|
||||
// Invalid GitLab URLs (not release URLs)
|
||||
{"invalid_gitlab_root", "https://gitlab.com/owner/repo", true, "GitLab MCPB packages must be release assets"},
|
||||
{"invalid_gitlab_tree", "https://gitlab.com/owner/repo/-/tree/main", true, "GitLab MCPB packages must be release assets"},
|
||||
{"invalid_gitlab_blob", "https://gitlab.com/owner/repo/-/blob/main/file.mcpb", true, "GitLab MCPB packages must be release assets"},
|
||||
{"invalid_gitlab_missing_dash_prefix", "https://gitlab.com/owner/repo/releases/v1.0.0/downloads/file.mcpb", true, "GitLab MCPB packages must be release assets"},
|
||||
{"invalid_gitlab_missing_downloads", "https://gitlab.com/owner/repo/-/releases/v1.0.0/file.mcpb", true, "GitLab MCPB packages must be release assets"},
|
||||
{"invalid_gitlab_invalid_package_files", "https://gitlab.com/owner/repo/-/package_files/abc/download", true, "GitLab MCPB packages must be release assets"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: model.RegistryTypeMCPB,
|
||||
RegistryBaseURL: model.RegistryURLGitHub,
|
||||
Identifier: tc.identifier,
|
||||
},
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := validators.ValidateServerJSON(&server)
|
||||
if tc.expectError {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tc.errorMsg)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue