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:
adam jones 2025-09-04 22:45:59 +01:00 • committed by GitHub
commit 694a4d8879
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 1859 additions and 728 deletions

View file

@ -11,7 +11,6 @@ import (
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/service"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
)
@ -67,11 +66,6 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
return nil, huma.Error403Forbidden("You do not have edit permissions for this server")
}
// Perform all schema validation
if err := validators.ValidatePublishRequest(input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
// Prevent renaming servers
if currentServer.Name != input.Body.Name {
return nil, huma.Error400BadRequest("Cannot rename server")

View file

@ -22,8 +22,8 @@ import (
func TestEditServerEndpoint(t *testing.T) {
// Create registry service and insert a common test server
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
// Publish a test server that will be used across test cases
testServer := apiv0.ServerJSON{
Name: "io.github.domdomegg/test-server",
@ -43,9 +43,9 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, published)
assert.NotNil(t, published.Meta)
assert.NotNil(t, published.Meta.IOModelContextProtocolRegistry)
testServerID := published.Meta.IOModelContextProtocolRegistry.ID
// Publish a second server for permission testing
otherServer := apiv0.ServerJSON{
Name: "io.github.other/test-server",
@ -65,9 +65,9 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, otherPublished)
assert.NotNil(t, otherPublished.Meta)
assert.NotNil(t, otherPublished.Meta.IOModelContextProtocolRegistry)
otherServerID := otherPublished.Meta.IOModelContextProtocolRegistry.ID
// Publish a deleted server for undelete testing
deletedServer := apiv0.ServerJSON{
Name: "io.github.domdomegg/deleted-server",
@ -87,7 +87,7 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, deletedPublished)
assert.NotNil(t, deletedPublished.Meta)
assert.NotNil(t, deletedPublished.Meta.IOModelContextProtocolRegistry)
deletedServerID := deletedPublished.Meta.IOModelContextProtocolRegistry.ID
testCases := []struct {
@ -143,9 +143,9 @@ func TestEditServerEndpoint(t *testing.T) {
Description: "Test server",
VersionDetail: model.VersionDetail{Version: "1.0.0"},
},
serverID: testServerID,
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
serverID: testServerID,
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
},
{
name: "invalid token",
@ -155,12 +155,12 @@ func TestEditServerEndpoint(t *testing.T) {
Description: "Test server",
VersionDetail: model.VersionDetail{Version: "1.0.0"},
},
serverID: testServerID,
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
serverID: testServerID,
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
},
{
name: "permission denied - no edit permissions",
name: "permission denied - no edit permissions",
authHeader: func() string {
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
@ -182,7 +182,7 @@ func TestEditServerEndpoint(t *testing.T) {
expectedError: "Forbidden",
},
{
name: "permission denied - wrong resource",
name: "permission denied - wrong resource",
authHeader: func() string {
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
@ -204,7 +204,7 @@ func TestEditServerEndpoint(t *testing.T) {
expectedError: "Forbidden",
},
{
name: "server not found",
name: "server not found",
authHeader: func() string {
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
@ -226,7 +226,7 @@ func TestEditServerEndpoint(t *testing.T) {
expectedError: "Not Found",
},
{
name: "validation error - invalid server name",
name: "validation error - invalid server name",
authHeader: func() string {
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
@ -248,7 +248,7 @@ func TestEditServerEndpoint(t *testing.T) {
expectedError: "Bad Request",
},
{
name: "cannot undelete server",
name: "cannot undelete server",
authHeader: func() string {
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{

View file

@ -9,7 +9,6 @@ import (
"github.com/modelcontextprotocol/registry/internal/auth"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/service"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
)
@ -49,11 +48,6 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
}
// Perform all schema validation
if err := validators.ValidatePublishRequest(input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
// Verify that the token has permission to publish the server
if !jwtManager.HasPermission(input.Body.Name, auth.PermissionActionPublish, claims.Permissions) {
return nil, huma.Error403Forbidden("You do not have permission to publish this server")

View file

@ -36,17 +36,18 @@ func generateIntegrationTestJWTToken(cfg *config.Config, claims auth.JWTClaims)
}
func TestPublishIntegration(t *testing.T) {
// Setup fake service
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
// Create test config with a valid Ed25519 seed
// Create test config with a valid Ed25519 seed and validation disabled for testing
testSeed := make([]byte, ed25519.SeedSize)
_, err := rand.Read(testSeed)
require.NoError(t, err)
testConfig := &config.Config{
JWTPrivateKey: hex.EncodeToString(testSeed),
JWTPrivateKey: hex.EncodeToString(testSeed),
EnableRegistryValidation: false, // Disable for integration tests
}
// Setup fake service
registryService := service.NewRegistryService(database.NewMemoryDB(), testConfig)
// Create a new ServeMux and Huma API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
@ -219,4 +220,53 @@ func TestPublishIntegration(t *testing.T) {
assert.Equal(t, http.StatusForbidden, rr.Code)
assert.Contains(t, rr.Body.String(), "You do not have permission to publish this server")
})
t.Run("publish succeeds with MCPB package", func(t *testing.T) {
publishReq := apiv0.ServerJSON{
Name: "io.github.domdomegg/airtable-mcp-server",
Description: "A test server with MCPB package",
VersionDetail: model.VersionDetail{
Version: "1.7.2",
},
Status: model.StatusActive,
Packages: []model.Package{
{
RegistryType: model.RegistryTypeMCPB,
Identifier: "github.com/domdomegg/airtable-mcp-server/releases/download/v1.7.2/airtable-mcp-server.mcpb",
Version: "1.7.2",
},
},
}
// Generate valid JWT token with wildcard permission
claims := auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
}
token, err := generateIntegrationTestJWTToken(testConfig, claims)
require.NoError(t, err)
body, err := json.Marshal(publishReq)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/v0/publish", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
var response apiv0.ServerJSON
err = json.Unmarshal(rr.Body.Bytes(), &response)
require.NoError(t, err)
assert.Equal(t, publishReq.Name, response.Name)
assert.Equal(t, publishReq.VersionDetail.Version, response.VersionDetail.Version)
assert.Len(t, response.Packages, 1)
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
})
}

View file

@ -0,0 +1,225 @@
package v0_test
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
"github.com/modelcontextprotocol/registry/internal/auth"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/service"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPublishRegistryValidation(t *testing.T) {
// Create test config with validation ENABLED
testSeed := make([]byte, ed25519.SeedSize)
_, err := rand.Read(testSeed)
require.NoError(t, err)
testConfig := &config.Config{
JWTPrivateKey: hex.EncodeToString(testSeed),
EnableRegistryValidation: true, // Enable validation for this test
}
// Setup fake service
registryService := service.NewRegistryService(database.NewMemoryDB(), testConfig)
// Create a new ServeMux and Huma API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the endpoint
v0.RegisterPublishEndpoint(api, registryService, testConfig)
t.Run("publish fails with npm registry validation error", func(t *testing.T) {
publishReq := apiv0.ServerJSON{
Name: "com.example/test-server-with-npm",
Description: "A test server with invalid npm package reference",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
Packages: []model.Package{
{
RegistryType: model.RegistryTypeNPM,
Identifier: "nonexistent-npm-package-xyz123",
Version: "1.0.0",
},
},
}
// Generate valid JWT token with wildcard permission
claims := auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
}
token, err := generateTestJWTToken(testConfig, claims)
require.NoError(t, err)
body, err := json.Marshal(publishReq)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/v0/publish", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.Contains(t, rr.Body.String(), "registry validation failed")
})
t.Run("publish succeeds with MCPB package (registry validation enabled)", func(t *testing.T) {
publishReq := apiv0.ServerJSON{
Name: "com.example/test-server-mcpb-validation",
Description: "A test server with MCPB package and registry validation enabled",
VersionDetail: model.VersionDetail{
Version: "0.0.36",
},
Packages: []model.Package{
{
RegistryType: model.RegistryTypeMCPB,
Identifier: "https://github.com/microsoft/playwright-mcp/releases/download/v0.0.36/playwright-mcp-extension-v0.0.36.zip",
Version: "0.0.36",
},
},
}
// Generate valid JWT token with wildcard permission
claims := auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
}
token, err := generateTestJWTToken(testConfig, claims)
require.NoError(t, err)
body, err := json.Marshal(publishReq)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/v0/publish", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
var response apiv0.ServerJSON
err = json.Unmarshal(rr.Body.Bytes(), &response)
require.NoError(t, err)
assert.Equal(t, publishReq.Name, response.Name)
assert.Equal(t, publishReq.VersionDetail.Version, response.VersionDetail.Version)
assert.Len(t, response.Packages, 1)
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
})
t.Run("publish fails when second package fails npm validation", func(t *testing.T) {
publishReq := apiv0.ServerJSON{
Name: "com.example/test-server-multiple-packages",
Description: "A test server with multiple packages where second fails",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
Packages: []model.Package{
{
RegistryType: model.RegistryTypeMCPB,
Identifier: "https://github.com/microsoft/playwright-mcp/releases/download/v0.0.36/playwright-mcp-extension-v0.0.36.zip",
Version: "1.0.0",
},
{
RegistryType: model.RegistryTypeNPM,
Identifier: "nonexistent-second-package-abc123",
Version: "1.0.0",
},
},
}
// Generate valid JWT token with wildcard permission
claims := auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
}
token, err := generateTestJWTToken(testConfig, claims)
require.NoError(t, err)
body, err := json.Marshal(publishReq)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/v0/publish", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.Contains(t, rr.Body.String(), "registry validation failed for package 1")
assert.Contains(t, rr.Body.String(), "nonexistent-second-package-abc123")
})
t.Run("publish fails when first package fails validation", func(t *testing.T) {
publishReq := apiv0.ServerJSON{
Name: "com.example/test-server-first-package-fails",
Description: "A test server where first package fails",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
Packages: []model.Package{
{
RegistryType: model.RegistryTypeNPM,
Identifier: "nonexistent-first-package-xyz789",
Version: "1.0.0",
},
{
RegistryType: model.RegistryTypeMCPB,
Identifier: "https://github.com/microsoft/playwright-mcp/releases/download/v0.0.36/playwright-mcp-extension-v0.0.36.zip",
Version: "1.0.0",
},
},
}
// Generate valid JWT token with wildcard permission
claims := auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
}
token, err := generateTestJWTToken(testConfig, claims)
require.NoError(t, err)
body, err := json.Marshal(publishReq)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/v0/publish", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.Contains(t, rr.Body.String(), "registry validation failed for package 0")
assert.Contains(t, rr.Body.String(), "nonexistent-first-package-xyz789")
})
}

View file

@ -24,7 +24,6 @@ import (
"github.com/stretchr/testify/require"
)
// Helper function to generate a valid JWT token for testing
func generateTestJWTToken(cfg *config.Config, claims auth.JWTClaims) (string, error) {
jwtManager := auth.NewJWTManager(cfg)
@ -41,17 +40,18 @@ func TestPublishEndpoint(t *testing.T) {
_, err := rand.Read(testSeed)
require.NoError(t, err)
testConfig := &config.Config{
JWTPrivateKey: hex.EncodeToString(testSeed),
JWTPrivateKey: hex.EncodeToString(testSeed),
EnableRegistryValidation: false, // Disable for unit tests
}
testCases := []struct {
name string
requestBody interface{}
tokenClaims *auth.JWTClaims
authHeader string
name string
requestBody interface{}
tokenClaims *auth.JWTClaims
authHeader string
setupRegistryService func(service.RegistryService)
expectedStatus int
expectedError string
expectedStatus int
expectedError string
}{
{
name: "successful publish with GitHub auth",
@ -105,9 +105,9 @@ func TestPublishEndpoint(t *testing.T) {
expectedStatus: http.StatusOK,
},
{
name: "missing authorization header",
requestBody: apiv0.ServerJSON{},
authHeader: "", // Empty auth header
name: "missing authorization header",
requestBody: apiv0.ServerJSON{},
authHeader: "", // Empty auth header
setupRegistryService: func(_ service.RegistryService) {
// Empty registry - no setup needed
},
@ -121,7 +121,7 @@ func TestPublishEndpoint(t *testing.T) {
Description: "Test server",
VersionDetail: model.VersionDetail{Version: "1.0.0"},
},
authHeader: "InvalidFormat",
authHeader: "InvalidFormat",
setupRegistryService: func(_ service.RegistryService) {
// Empty registry - no setup needed
},
@ -137,7 +137,7 @@ func TestPublishEndpoint(t *testing.T) {
Version: "1.0.0",
},
},
authHeader: "Bearer invalidToken",
authHeader: "Bearer invalidToken",
setupRegistryService: func(_ service.RegistryService) {
// Empty registry - no setup needed
},
@ -209,13 +209,38 @@ func TestPublishEndpoint(t *testing.T) {
expectedStatus: http.StatusBadRequest,
expectedError: "invalid version: cannot publish duplicate version",
},
{
name: "package validation success - MCPB package",
requestBody: apiv0.ServerJSON{
Name: "com.example/test-server-mcpb",
Description: "A test server with MCPB package",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
Packages: []model.Package{
{
RegistryType: model.RegistryTypeMCPB,
Identifier: "https://github.com/example/server/releases/download/v1.0.0/server.tar.gz",
Version: "1.0.0",
},
},
},
tokenClaims: &auth.JWTClaims{
AuthMethod: auth.MethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
},
setupRegistryService: func(_ service.RegistryService) {},
expectedStatus: http.StatusOK,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create registry service
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), testConfig)
// Setup registry service
tc.setupRegistryService(registryService)

View file

@ -11,6 +11,7 @@ import (
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/google/uuid"
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/service"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
@ -131,7 +132,7 @@ func TestServersListEndpoint(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create mock registry service
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
tc.setupRegistryService(registryService)
// Create a new test API
@ -202,7 +203,7 @@ func TestServersListEndpoint(t *testing.T) {
func TestServersDetailEndpoint(t *testing.T) {
// Create mock registry service
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
testServer, err := registryService.Publish(apiv0.ServerJSON{
Name: "com.example/test-server",
@ -284,7 +285,7 @@ func TestServersDetailEndpoint(t *testing.T) {
// TestServersEndpointsIntegration tests the servers endpoints with actual HTTP requests
func TestServersEndpointsIntegration(t *testing.T) {
// Create mock registry service
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
// Test data - publish a server and get its actual ID
testServer := apiv0.ServerJSON{

View file

@ -21,7 +21,7 @@ import (
)
func TestPrometheusHandler(t *testing.T) {
registryService := service.NewRegistryServiceWithDB(database.NewMemoryDB())
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
server, err := registryService.Publish(apiv0.ServerJSON{
Name: "io.github.example/test-server",
Description: "Test server detail",

View file

@ -14,15 +14,16 @@ const (
// Config holds the application configuration
// See .env.example for more documentation
type Config struct {
ServerAddress string `env:"SERVER_ADDRESS" envDefault:":8080"`
DatabaseType DatabaseType `env:"DATABASE_TYPE" envDefault:"postgresql"`
DatabaseURL string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/mcp-registry?sslmode=disable"`
SeedFrom string `env:"SEED_FROM" envDefault:""`
Version string `env:"VERSION" envDefault:"dev"`
GithubClientID string `env:"GITHUB_CLIENT_ID" envDefault:""`
GithubClientSecret string `env:"GITHUB_CLIENT_SECRET" envDefault:""`
JWTPrivateKey string `env:"JWT_PRIVATE_KEY" envDefault:""`
EnableAnonymousAuth bool `env:"ENABLE_ANONYMOUS_AUTH" envDefault:"false"`
ServerAddress string `env:"SERVER_ADDRESS" envDefault:":8080"`
DatabaseType DatabaseType `env:"DATABASE_TYPE" envDefault:"postgresql"`
DatabaseURL string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/mcp-registry?sslmode=disable"`
SeedFrom string `env:"SEED_FROM" envDefault:""`
Version string `env:"VERSION" envDefault:"dev"`
GithubClientID string `env:"GITHUB_CLIENT_ID" envDefault:""`
GithubClientSecret string `env:"GITHUB_CLIENT_SECRET" envDefault:""`
JWTPrivateKey string `env:"JWT_PRIVATE_KEY" envDefault:""`
EnableAnonymousAuth bool `env:"ENABLE_ANONYMOUS_AUTH" envDefault:"false"`
EnableRegistryValidation bool `env:"ENABLE_REGISTRY_VALIDATION" envDefault:"true"`
// OIDC Configuration
OIDCEnabled bool `env:"OIDC_ENABLED" envDefault:"false"`

View file

@ -7,6 +7,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
@ -16,13 +17,15 @@ const maxServerVersionsPerServer = 10000
// registryServiceImpl implements the RegistryService interface using our Database
type registryServiceImpl struct {
db database.Database
db database.Database
cfg *config.Config
}
// NewRegistryServiceWithDB creates a new registry service with the provided database
func NewRegistryServiceWithDB(db database.Database) RegistryService {
// NewRegistryService creates a new registry service with the provided database
func NewRegistryService(db database.Database, cfg *config.Config) RegistryService {
return &registryServiceImpl{
db: db,
db: db,
cfg: cfg,
}
}
@ -74,7 +77,7 @@ func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON,
defer cancel()
// Validate the request
if err := validators.ValidatePublishRequest(req); err != nil {
if err := validators.ValidatePublishRequest(req, s.cfg); err != nil {
return nil, err
}
@ -204,7 +207,7 @@ func (s *registryServiceImpl) EditServer(id string, req apiv0.ServerJSON) (*apiv
defer cancel()
// Validate the request
if err := validators.ValidatePublishRequest(req); err != nil {
if err := validators.ValidatePublishRequest(req, s.cfg); err != nil {
return nil, err
}

View file

@ -5,6 +5,7 @@ import (
"context"
"testing"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
@ -38,7 +39,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
}
memDB := database.NewMemoryDB()
service := NewRegistryServiceWithDB(memDB)
service := NewRegistryService(memDB, &config.Config{EnableRegistryValidation: false})
for _, server := range existingServers {
_, err := service.Publish(*server)

View file

@ -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")
)

View 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)
}
}

View 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)
}
}

View 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)
}
})
}
}

View 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
}

View 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)
}
})
}
}

View 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)
}

View 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)
}
})
}
}

View 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
}

Some files were not shown because too many files have changed in this diff Show more