registry/internal/api/handlers/v0/publish_test.go
Radoslav Dimitrov 8d7e471fd3
Allow for vendor extensions on servers (#298)
<!-- Provide a brief summary of your changes -->
This PR serves as a placeholder and brings together all of the changes
related to supporting vendor extensions passed through the API. The idea
is to have a single place to track and review the work as it comes
together (even if it’s still a bit of a work in progress).

**The changes in this PR cover:**
* Updates on the data model
* Updates on both databases (in-memory and postgresql), added a new
table to PSQL for tracking the extensions leaving the server table only
for the clean server.json properties
* Updates the seed.json file (thus the big line change)
* Adds a seed-migrate tool to help migrating an existing seed file to
the new format
* Updates the seed import mechanism to support this
* Updates the existing tests - unit, integration and validation tests
* Adds the publish handler to the OpenAPI spec (it was missing)
* Fixes linting errors
* Updates on the API side on (publish, list, get) to support the new
format of `ServerResponse` -
```
{
  "server": {},
  "x-io.modelcontextprotocol.registry": {}, /*not available for publish since this gets populated by the registry*/
  "x-publisher": {}
}
```

## Motivation and Context
<!-- Why is this change needed? What problem does it solve? -->
Motivated by the discussions in:
https://github.com/modelcontextprotocol/registry/discussions/284

## How Has This Been Tested?
<!-- Have you tested this in a real application? Which scenarios were
tested? -->
Locally and by running all of the tests

## Breaking Changes
<!-- Will users need to update their code or configurations? -->
Yes, it changes both the API and the format of the seed file
 
## 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)
- [ ] New feature (non-breaking change which adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update

---

Signed-off-by: Radoslav Dimitrov <radoslav@stacklok.com>
Co-authored-by: adam jones <domdomegg+git@gmail.com>
2025-08-23 09:59:03 +01:00

266 lines
7.8 KiB
Go

package v0_test
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"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/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// MockRegistryService is a mock implementation of the RegistryService interface
type MockRegistryService struct {
mock.Mock
}
func (m *MockRegistryService) List(cursor string, limit int) ([]model.ServerResponse, string, error) {
args := m.Called(cursor, limit)
return args.Get(0).([]model.ServerResponse), args.String(1), args.Error(2)
}
func (m *MockRegistryService) GetByID(id string) (*model.ServerResponse, error) {
args := m.Called(id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*model.ServerResponse), args.Error(1)
}
func (m *MockRegistryService) Publish(request model.PublishRequest) (*model.ServerResponse, error) {
args := m.Called(request)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*model.ServerResponse), args.Error(1)
}
// Helper function to generate a valid JWT token for testing
func generateTestJWTToken(cfg *config.Config, claims auth.JWTClaims) (string, error) {
jwtManager := auth.NewJWTManager(cfg)
ctx := context.Background()
tokenResponse, err := jwtManager.GenerateTokenResponse(ctx, claims)
if err != nil {
return "", err
}
return tokenResponse.RegistryToken, nil
}
func TestPublishEndpoint(t *testing.T) {
testSeed := make([]byte, ed25519.SeedSize)
_, err := rand.Read(testSeed)
require.NoError(t, err)
testConfig := &config.Config{
JWTPrivateKey: hex.EncodeToString(testSeed),
}
testCases := []struct {
name string
requestBody interface{}
tokenClaims *auth.JWTClaims
authHeader string
setupMocks func(*MockRegistryService)
expectedStatus int
expectedError string
}{
{
name: "successful publish with GitHub auth",
requestBody: model.PublishRequest{
Server: model.ServerDetail{
Name: "io.github.example/test-server",
Description: "A test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server",
Source: "github",
ID: "example/test-server",
},
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
},
tokenClaims: &auth.JWTClaims{
AuthMethod: model.AuthMethodGitHubAT,
AuthMethodSubject: "example",
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.example/*"},
},
},
setupMocks: func(registry *MockRegistryService) {
registry.On("Publish", mock.AnythingOfType("model.PublishRequest")).Return(&model.ServerResponse{}, nil)
},
expectedStatus: http.StatusOK,
},
{
name: "successful publish with no auth (AuthMethodNone)",
requestBody: model.PublishRequest{
Server: model.ServerDetail{
Name: "example/test-server",
Description: "A test server without auth",
Repository: model.Repository{
URL: "https://example.com/test-server",
Source: "example",
ID: "example/test-server",
},
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
},
tokenClaims: &auth.JWTClaims{
AuthMethod: model.AuthMethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "example/*"},
},
},
setupMocks: func(registry *MockRegistryService) {
registry.On("Publish", mock.AnythingOfType("model.PublishRequest")).Return(&model.ServerResponse{}, nil)
},
expectedStatus: http.StatusOK,
},
{
name: "missing authorization header",
requestBody: model.PublishRequest{},
authHeader: "", // Empty auth header
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity,
expectedError: "required header parameter is missing",
},
{
name: "invalid authorization header format",
requestBody: model.PublishRequest{},
authHeader: "InvalidFormat",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnauthorized,
expectedError: "Invalid Authorization header format",
},
{
name: "invalid token",
requestBody: model.PublishRequest{
Server: model.ServerDetail{
Name: "test-server",
Description: "A test server",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
},
authHeader: "Bearer invalidToken",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnauthorized,
expectedError: "Invalid or expired Registry JWT token",
},
{
name: "permission denied",
requestBody: model.PublishRequest{
Server: model.ServerDetail{
Name: "io.github.other/test-server",
Description: "A test server",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
},
tokenClaims: &auth.JWTClaims{
AuthMethod: model.AuthMethodGitHubAT,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.example/*"},
},
},
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusForbidden,
expectedError: "You do not have permission to publish this server",
},
{
name: "registry service error",
requestBody: model.PublishRequest{
Server: model.ServerDetail{
Name: "example/test-server",
Description: "A test server",
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
},
tokenClaims: &auth.JWTClaims{
AuthMethod: model.AuthMethodNone,
Permissions: []auth.Permission{
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
},
},
setupMocks: func(registry *MockRegistryService) {
registry.On("Publish", mock.AnythingOfType("model.PublishRequest")).Return(nil, errors.New("database error"))
},
expectedStatus: http.StatusInternalServerError,
expectedError: "Failed to publish server",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create mocks
mockRegistry := new(MockRegistryService)
// Setup mocks
tc.setupMocks(mockRegistry)
// Create a new ServeMux and Huma API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the endpoint with test config
v0.RegisterPublishEndpoint(api, mockRegistry, testConfig)
// Prepare request body
var requestBody []byte
if tc.requestBody != nil {
var err error
requestBody, err = json.Marshal(tc.requestBody)
assert.NoError(t, err)
}
// Create request
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/v0/publish", bytes.NewBuffer(requestBody))
assert.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
// Set auth header
if tc.authHeader != "" {
req.Header.Set("Authorization", tc.authHeader)
} else if tc.tokenClaims != nil {
// Generate a valid JWT token
token, err := generateTestJWTToken(testConfig, *tc.tokenClaims)
assert.NoError(t, err)
req.Header.Set("Authorization", "Bearer "+token)
}
// Perform request
rr := httptest.NewRecorder()
mux.ServeHTTP(rr, req)
// Assertions
assert.Equal(t, tc.expectedStatus, rr.Code, "status code mismatch")
if tc.expectedError != "" {
assert.Contains(t, rr.Body.String(), tc.expectedError)
}
// Verify mock expectations
mockRegistry.AssertExpectations(t)
})
}
}