Changes on the server.json format and the API (#562)
This commit is contained in:
parent
4962609697
commit
b21c6f564d
11 changed files with 4056 additions and 5608 deletions
|
|
@ -26,6 +26,8 @@ func NewNoneHandler(cfg *config.Config) *NoneHandler {
|
|||
}
|
||||
|
||||
// RegisterNoneEndpoint registers the anonymous authentication endpoint
|
||||
// WARNING: This endpoint is intended for local development and automated tests only.
|
||||
// It should NOT be enabled in production environments as it bypasses normal authentication.
|
||||
func RegisterNoneEndpoint(api huma.API, cfg *config.Config) {
|
||||
if !cfg.EnableAnonymousAuth {
|
||||
return
|
||||
|
|
@ -33,13 +35,13 @@ func RegisterNoneEndpoint(api huma.API, cfg *config.Config) {
|
|||
|
||||
handler := NewNoneHandler(cfg)
|
||||
|
||||
// Anonymous token endpoint
|
||||
// Anonymous token endpoint for development/testing only
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-anonymous-token",
|
||||
Method: http.MethodPost,
|
||||
Path: "/v0/auth/none",
|
||||
Summary: "Get anonymous Registry JWT",
|
||||
Description: "Get a short-lived Registry JWT token for publishing to io.modelcontextprotocol.anonymous/* namespace",
|
||||
Summary: "Get anonymous Registry JWT (Development/Testing Only)",
|
||||
Description: "Get a short-lived Registry JWT token for publishing and editing servers in the io.modelcontextprotocol.anonymous/* namespace. This endpoint is intended for local development and automated testing only.",
|
||||
Tags: []string{"auth"},
|
||||
}, func(ctx context.Context, _ *struct{}) (*v0.Response[auth.TokenResponse], error) {
|
||||
response, err := handler.GetAnonymousToken(ctx)
|
||||
|
|
@ -61,6 +63,10 @@ func (h *NoneHandler) GetAnonymousToken(ctx context.Context) (*auth.TokenRespons
|
|||
Action: auth.PermissionActionPublish,
|
||||
ResourcePattern: "io.modelcontextprotocol.anonymous/*",
|
||||
},
|
||||
{
|
||||
Action: auth.PermissionActionEdit,
|
||||
ResourcePattern: "io.modelcontextprotocol.anonymous/*",
|
||||
},
|
||||
}
|
||||
|
||||
// Create JWT claims for anonymous user
|
||||
|
|
|
|||
|
|
@ -43,8 +43,14 @@ func TestNoneHandler_GetAnonymousToken(t *testing.T) {
|
|||
assert.Equal(t, auth.MethodNone, claims.AuthMethod)
|
||||
assert.Equal(t, "anonymous", claims.AuthMethodSubject)
|
||||
|
||||
// Check permissions
|
||||
require.Len(t, claims.Permissions, 1)
|
||||
// Check permissions - should have both publish and edit permissions
|
||||
require.Len(t, claims.Permissions, 2)
|
||||
|
||||
// Check publish permission
|
||||
assert.Equal(t, auth.PermissionActionPublish, claims.Permissions[0].Action)
|
||||
assert.Equal(t, "io.modelcontextprotocol.anonymous/*", claims.Permissions[0].ResourcePattern)
|
||||
|
||||
// Check edit permission
|
||||
assert.Equal(t, auth.PermissionActionEdit, claims.Permissions[1].Action)
|
||||
assert.Equal(t, "io.modelcontextprotocol.anonymous/*", claims.Permissions[1].ResourcePattern)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
|
@ -18,8 +19,9 @@ import (
|
|||
// EditServerInput represents the input for editing a server
|
||||
type EditServerInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with edit permissions" required:"true"`
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Version string `query:"version" doc:"Version to edit (e.g., '1.0.0')" required:"true" example:"1.0.0"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded version to edit" example:"1.0.0"`
|
||||
Status string `query:"status" doc:"New status for the server (active, deprecated, deleted)" required:"false" enum:"active,deprecated,deleted"`
|
||||
Body apiv0.ServerJSON `body:""`
|
||||
}
|
||||
|
||||
|
|
@ -31,14 +33,14 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
huma.Register(api, huma.Operation{
|
||||
OperationID: "edit-server",
|
||||
Method: http.MethodPut,
|
||||
Path: "/v0/servers/{server_id}",
|
||||
Path: "/v0/servers/{serverName}/versions/{version}",
|
||||
Summary: "Edit MCP server",
|
||||
Description: "Update an existing MCP server (admin only). Requires version query parameter to specify which version to edit.",
|
||||
Description: "Update a specific version of an existing MCP server (admin only).",
|
||||
Tags: []string{"admin"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -53,9 +55,20 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetByServerIDAndVersion(input.ServerID, input.Version)
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// URL-decode the version
|
||||
version, err := url.PathUnescape(input.Version)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid version encoding", err)
|
||||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -64,27 +77,42 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
}
|
||||
|
||||
// Verify edit permissions for this server using the existing server name
|
||||
if !jwtManager.HasPermission(currentServer.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
if !jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
return nil, huma.Error403Forbidden("You do not have edit permissions for this server")
|
||||
}
|
||||
|
||||
// Prevent renaming servers
|
||||
if currentServer.Name != input.Body.Name {
|
||||
if currentServer.Server.Name != input.Body.Name {
|
||||
return nil, huma.Error400BadRequest("Cannot rename server")
|
||||
}
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Status == model.StatusDeleted && input.Body.Status != model.StatusDeleted {
|
||||
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
|
||||
// Validate that the version in the body matches the URL parameter
|
||||
if input.Body.Version != version {
|
||||
return nil, huma.Error400BadRequest("Version in request body must match URL path parameter")
|
||||
}
|
||||
|
||||
// Edit the server using the version_id from the current server
|
||||
versionID := currentServer.GetVersionID()
|
||||
if versionID == "" {
|
||||
return nil, huma.Error500InternalServerError("Server version ID not found in metadata", nil)
|
||||
// Handle status changes with proper permission validation
|
||||
if input.Status != "" {
|
||||
newStatus := model.Status(input.Status)
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Meta.Official != nil &&
|
||||
currentServer.Meta.Official.Status == model.StatusDeleted &&
|
||||
newStatus != model.StatusDeleted {
|
||||
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
|
||||
}
|
||||
|
||||
// For now, only allow status changes for admins
|
||||
// Future: Implement logic to allow server authors to change active <-> deprecated
|
||||
// but only admins can set to deleted
|
||||
}
|
||||
|
||||
updatedServer, err := registry.EditServer(versionID, input.Body)
|
||||
// Update the server using the service
|
||||
var statusPtr *string
|
||||
if input.Status != "" {
|
||||
statusPtr = &input.Status
|
||||
}
|
||||
updatedServer, err := registry.UpdateServer(ctx, serverName, version, &input.Body, statusPtr)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -92,7 +120,7 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
return nil, huma.Error400BadRequest("Failed to edit server", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *updatedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,14 +2,20 @@ package v0_test
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
|
|
@ -21,313 +27,616 @@ import (
|
|||
)
|
||||
|
||||
func TestEditServerEndpoint(t *testing.T) {
|
||||
// Create registry service and insert a common test server
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
// Publish a test server that will be used across test cases
|
||||
testServer := apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original test server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/test-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/test-server",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
published, err := registryService.Publish(testServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, published)
|
||||
assert.NotNil(t, published.Meta)
|
||||
assert.NotNil(t, published.Meta.Official)
|
||||
|
||||
testServerID := published.Meta.Official.ServerID
|
||||
// Create registry service and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Publish a second server for permission testing
|
||||
otherServer := apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Other test server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/other/test-server",
|
||||
Source: "github",
|
||||
ID: "other/test-server",
|
||||
// Create test servers for different scenarios
|
||||
testServers := map[string]*apiv0.ServerJSON{
|
||||
"editable": {
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Server that can be edited",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/editable-server",
|
||||
Source: "github",
|
||||
ID: "testuser/editable-server",
|
||||
},
|
||||
},
|
||||
Version: "1.0.0",
|
||||
}
|
||||
otherPublished, err := registryService.Publish(otherServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, otherPublished)
|
||||
assert.NotNil(t, otherPublished.Meta)
|
||||
assert.NotNil(t, otherPublished.Meta.Official)
|
||||
|
||||
otherServerID := otherPublished.Meta.Official.ServerID
|
||||
|
||||
// Publish a deleted server for undelete testing
|
||||
deletedServer := apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/deleted-server",
|
||||
Description: "Deleted test server",
|
||||
Status: model.StatusDeleted,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/deleted-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/deleted-server",
|
||||
"other": {
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Server owned by another user",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/otheruser/other-server",
|
||||
Source: "github",
|
||||
ID: "otheruser/other-server",
|
||||
},
|
||||
},
|
||||
Version: "1.0.0",
|
||||
}
|
||||
deletedPublished, err := registryService.Publish(deletedServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, deletedPublished)
|
||||
assert.NotNil(t, deletedPublished.Meta)
|
||||
assert.NotNil(t, deletedPublished.Meta.Official)
|
||||
|
||||
deletedServerID := deletedPublished.Meta.Official.ServerID
|
||||
// Create the test servers
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), server)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Create a deleted server for undelete testing
|
||||
deletedServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Server that was deleted",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/deleted-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deleted-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), deletedServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set the server to deleted status
|
||||
_, err = registryService.UpdateServer(context.Background(), deletedServer.Name, deletedServer.Version, deletedServer, stringPtr(string(model.StatusDeleted)))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create a server with build metadata for URL encoding test
|
||||
buildMetadataServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Server with build metadata version",
|
||||
Version: "1.0.0+20130313144700",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/build-metadata-server",
|
||||
Source: "github",
|
||||
ID: "testuser/build-metadata-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), buildMetadataServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
authHeader string
|
||||
requestBody interface{}
|
||||
serverID string
|
||||
serverName string
|
||||
version string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody apiv0.ServerJSON
|
||||
statusParam string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful edit with valid token and permissions",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Status: model.StatusDeprecated,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/test-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/test-server",
|
||||
name: "successful edit with valid permissions",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Updated server description",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/editable-server",
|
||||
Source: "github",
|
||||
ID: "testuser/editable-server",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated server description", resp.Server.Description)
|
||||
assert.Equal(t, "io.github.testuser/editable-server", resp.Server.Name)
|
||||
assert.Equal(t, "1.0.0", resp.Server.Version)
|
||||
assert.NotNil(t, resp.Meta.Official)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful edit with status change",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Server with status change",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Server with status change", resp.Server.Description)
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
authHeader: "",
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
serverID: testServerID,
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
expectedStatus: 422,
|
||||
authHeader: "", // No auth header
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Unauthorized",
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Unauthorized",
|
||||
expectedError: "Invalid or expired Registry JWT token",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no edit permissions",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "Forbidden",
|
||||
},
|
||||
{
|
||||
name: "permission denied - wrong resource",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: otherServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "Forbidden",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/nonexistent-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440999", // Non-existent ID
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Not Found",
|
||||
},
|
||||
{
|
||||
name: "validation error - invalid server name",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "invalid-name-format", // Missing namespace/name format
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Bad Request",
|
||||
},
|
||||
{
|
||||
name: "cannot undelete server",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/deleted-server",
|
||||
Description: "Trying to undelete server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/deleted-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/deleted-server",
|
||||
name: "permission denied - no edit permissions",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"}, // Only publish, not edit
|
||||
},
|
||||
Version: "1.0.1",
|
||||
},
|
||||
serverID: deletedServerID,
|
||||
version: "1.0.0",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have edit permissions",
|
||||
},
|
||||
{
|
||||
name: "permission denied - wrong namespace",
|
||||
serverName: "io.github.otheruser/other-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"}, // Wrong namespace
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have edit permissions",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverName: "io.github.testuser/non-existent",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/non-existent",
|
||||
Description: "Non-existent server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server not found",
|
||||
},
|
||||
{
|
||||
name: "attempt to rename server should fail",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/renamed-server", // Different name
|
||||
Description: "Trying to rename server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Cannot rename server",
|
||||
},
|
||||
{
|
||||
name: "version in body must match URL parameter",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Version mismatch test",
|
||||
Version: "2.0.0", // Different version from URL
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Version in request body must match URL path parameter",
|
||||
},
|
||||
{
|
||||
name: "attempt to undelete server should fail",
|
||||
serverName: "io.github.testuser/deleted-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Trying to undelete server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "active", // Trying to change from deleted to active
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Cannot change status of deleted server",
|
||||
},
|
||||
{
|
||||
name: "successful edit of version with build metadata (URL encoded)",
|
||||
serverName: "io.github.testuser/build-metadata-server",
|
||||
version: "1.0.0+20130313144700",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Updated server with build metadata",
|
||||
Version: "1.0.0+20130313144700",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/build-metadata-server",
|
||||
Source: "github",
|
||||
ID: "testuser/build-metadata-server",
|
||||
},
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated server with build metadata", resp.Server.Description)
|
||||
assert.Equal(t, "io.github.testuser/build-metadata-server", resp.Server.Name)
|
||||
assert.Equal(t, "1.0.0+20130313144700", resp.Server.Version)
|
||||
assert.NotNil(t, resp.Meta.Official)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
humaConfig := huma.DefaultConfig("Test API", "1.0.0")
|
||||
api := humago.New(mux, humaConfig)
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register edit endpoints
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c",
|
||||
}
|
||||
v0.RegisterEditEndpoints(api, registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
var requestBody []byte
|
||||
var err error
|
||||
if str, ok := tc.requestBody.(string); ok {
|
||||
requestBody = []byte(str)
|
||||
} else {
|
||||
requestBody, err = json.Marshal(tc.requestBody)
|
||||
assert.NoError(t, err)
|
||||
requestBody, err := json.Marshal(tc.requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create request URL with proper encoding
|
||||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
encodedVersion := url.PathEscape(tc.version)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/versions/" + encodedVersion
|
||||
if tc.statusParam != "" {
|
||||
requestURL += "?status=" + tc.statusParam
|
||||
}
|
||||
|
||||
// Create request
|
||||
url := "/v0/servers/" + tc.serverID
|
||||
if tc.version != "" {
|
||||
url += "?version=" + tc.version
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPut, url, bytes.NewReader(requestBody))
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Set authorization header
|
||||
if tc.authHeader != "" {
|
||||
req.Header.Set("Authorization", tc.authHeader)
|
||||
} else if tc.authClaims != nil {
|
||||
// Generate valid JWT token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), *tc.authClaims)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
}
|
||||
|
||||
// Create response recorder
|
||||
// Create response recorder and execute request
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// Call the endpoint
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check status code
|
||||
// Check response
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
// Check error message if expected
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
// No mock assertions needed with real service
|
||||
if tc.expectedStatus == http.StatusOK && tc.checkResult != nil {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
tc.checkResult(t, &response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditServerEndpointEdgeCases(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Setup test servers with different characteristics
|
||||
testServers := []struct {
|
||||
name string
|
||||
version string
|
||||
status model.Status
|
||||
}{
|
||||
{"com.example/active-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/deprecated-server", "1.0.0", model.StatusDeprecated},
|
||||
{"com.example/multi-version-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/multi-version-server", "2.0.0", model.StatusActive},
|
||||
}
|
||||
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set specific status if not active
|
||||
if server.status != model.StatusActive {
|
||||
_, err = registryService.UpdateServer(context.Background(), server.name, server.version, &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
}, stringPtr(string(server.status)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterEditEndpoints(api, registryService, cfg)
|
||||
|
||||
t.Run("status transitions", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
fromStatus string
|
||||
toStatus string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "active to deprecated",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "deprecated to active",
|
||||
serverName: "com.example/deprecated-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "active",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "active to deleted",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deleted",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "invalid status",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "invalid_status",
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "validation failed",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: tt.serverName,
|
||||
Description: "Status transition test",
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(tt.serverName)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/" + tt.version + "?status=" + tt.toStatus
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
if tt.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tt.expectedError)
|
||||
}
|
||||
|
||||
if tt.expectedStatus == http.StatusOK {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.Status(tt.toStatus), response.Meta.Official.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("URL encoding edge cases", func(t *testing.T) {
|
||||
// Create server with special characters
|
||||
specialServerName := "io.dots.and-dashes/server_with_underscores"
|
||||
_, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: specialServerName,
|
||||
Description: "Server with special characters",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: specialServerName,
|
||||
Description: "Updated server with special chars",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(specialServerName)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, specialServerName, response.Server.Name)
|
||||
assert.Equal(t, "Updated server with special chars", response.Server.Description)
|
||||
})
|
||||
|
||||
t.Run("version-specific editing", func(t *testing.T) {
|
||||
// Test editing a specific version of a multi-version server
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: "com.example/multi-version-server",
|
||||
Description: "Updated v1.0.0 specifically",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape("com.example/multi-version-server")
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Updated v1.0.0 specifically", response.Server.Description)
|
||||
assert.Equal(t, "1.0.0", response.Server.Version)
|
||||
|
||||
// Verify the other version wasn't affected
|
||||
otherVersion, err := registryService.GetServerByNameAndVersion(context.Background(), "com.example/multi-version-server", "2.0.0")
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, "Updated v1.0.0 specifically", otherVersion.Server.Description)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -54,13 +54,13 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
}
|
||||
|
||||
// Publish the server with extensions
|
||||
publishedServer, err := registry.Publish(input.Body)
|
||||
publishedServer, err := registry.CreateServer(ctx, &input.Body)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Failed to publish server", err)
|
||||
}
|
||||
|
||||
// Return the published server in flattened format
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
// Return the published server response with metadata
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *publishedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -90,12 +90,13 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
})
|
||||
|
||||
t.Run("successful publish with none auth (no prefix)", func(t *testing.T) {
|
||||
|
|
@ -132,11 +133,12 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
})
|
||||
|
||||
t.Run("publish fails with missing authorization header", func(t *testing.T) {
|
||||
|
|
@ -220,7 +222,6 @@ func TestPublishIntegration(t *testing.T) {
|
|||
Name: "io.github.domdomegg/airtable-mcp-server",
|
||||
Description: "A test server with MCPB package",
|
||||
Version: "1.7.2",
|
||||
Status: model.StatusActive,
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: model.RegistryTypeMCPB,
|
||||
|
|
@ -256,13 +257,14 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Len(t, response.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
assert.Len(t, response.Server.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Server.Packages[0].RegistryType)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,14 +124,14 @@ func TestPublishRegistryValidation(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Len(t, response.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.Len(t, response.Server.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Server.Packages[0].RegistryType)
|
||||
})
|
||||
|
||||
t.Run("publish fails when second package fails npm validation", func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -192,7 +192,7 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
ID: "example/test-server-existing",
|
||||
},
|
||||
}
|
||||
_, _ = registry.Publish(existingServer)
|
||||
_, _ = registry.CreateServer(context.Background(), &existingServer)
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "invalid version: cannot publish duplicate version",
|
||||
|
|
|
|||
|
|
@ -4,18 +4,20 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
)
|
||||
|
||||
const errRecordNotFound = "record not found"
|
||||
|
||||
// ListServersInput represents the input for listing servers
|
||||
type ListServersInput struct {
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor (UUID)" format:"uuid" required:"false" example:"550e8400-e29b-41d4-a716-446655440000"`
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor" required:"false" example:"server-cursor-123"`
|
||||
Limit int `query:"limit" doc:"Number of items per page" default:"30" minimum:"1" maximum:"100" example:"50"`
|
||||
UpdatedSince string `query:"updated_since" doc:"Filter servers updated since timestamp (RFC3339 datetime)" required:"false" example:"2025-08-07T13:15:04.280Z"`
|
||||
Search string `query:"search" doc:"Search servers by name (substring match)" required:"false" example:"filesystem"`
|
||||
|
|
@ -24,16 +26,22 @@ type ListServersInput struct {
|
|||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
type ServerDetailInput struct {
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Version string `query:"version" doc:"Specific version to retrieve (e.g., '1.0.0'). If not specified, returns latest version." required:"false" example:"1.0.0"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
}
|
||||
|
||||
// ServerVersionDetailInput represents the input for getting a specific version
|
||||
type ServerVersionDetailInput struct {
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded server version" example:"1.0.0"`
|
||||
}
|
||||
|
||||
// ServerVersionsInput represents the input for listing all versions of a server
|
||||
type ServerVersionsInput struct {
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
}
|
||||
|
||||
// RegisterServersEndpoints registers all server-related endpoints
|
||||
//nolint:cyclop // Multiple endpoint registrations are inherently complex
|
||||
func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
||||
// List servers endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
|
|
@ -43,15 +51,7 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
Summary: "List MCP servers",
|
||||
Description: "Get a paginated list of MCP servers from the registry",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ListServersInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Validate cursor if provided
|
||||
if input.Cursor != "" {
|
||||
_, err := uuid.Parse(input.Cursor)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid cursor parameter")
|
||||
}
|
||||
}
|
||||
|
||||
}, func(ctx context.Context, input *ListServersInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Build filter from input parameters
|
||||
filter := &database.ServerFilter{}
|
||||
|
||||
|
|
@ -83,14 +83,20 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
}
|
||||
|
||||
// Get paginated results with filtering
|
||||
servers, nextCursor, err := registry.List(filter, input.Cursor, input.Limit)
|
||||
servers, nextCursor, err := registry.ListServers(ctx, filter, input.Cursor, input.Limit)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("Failed to get registry list", err)
|
||||
}
|
||||
|
||||
// Convert []*ServerResponse to []ServerResponse
|
||||
serverValues := make([]apiv0.ServerResponse, len(servers))
|
||||
for i, server := range servers {
|
||||
serverValues[i] = *server
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerListResponse]{
|
||||
Body: apiv0.ServerListResponse{
|
||||
Servers: servers,
|
||||
Servers: serverValues,
|
||||
Metadata: apiv0.Metadata{
|
||||
NextCursor: nextCursor,
|
||||
Count: len(servers),
|
||||
|
|
@ -99,36 +105,67 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
}, nil
|
||||
})
|
||||
|
||||
// Get server details endpoint
|
||||
// Get server details endpoint (latest version)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{server_id}",
|
||||
Path: "/v0/servers/{serverName}",
|
||||
Summary: "Get MCP server details",
|
||||
Description: "Get detailed information about a specific MCP server. Returns the latest version by default, or a specific version if the 'version' query parameter is provided.",
|
||||
Description: "Get detailed information about the latest version of a specific MCP server.",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerDetailInput) (*Response[apiv0.ServerJSON], error) {
|
||||
// Get the server details from the registry service
|
||||
var serverDetail *apiv0.ServerJSON
|
||||
var err error
|
||||
|
||||
if input.Version != "" {
|
||||
// Get specific version by server_id and version
|
||||
serverDetail, err = registry.GetByServerIDAndVersion(input.ServerID, input.Version)
|
||||
} else {
|
||||
// Get latest version by server_id
|
||||
serverDetail, err = registry.GetByServerID(input.ServerID)
|
||||
}, func(ctx context.Context, input *ServerDetailInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get latest version by server name
|
||||
serverResponse, err := registry.GetServerByName(ctx, serverName)
|
||||
if err != nil {
|
||||
if err.Error() == "record not found" || errors.Is(err, database.ErrNotFound) {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
Body: *serverDetail,
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *serverResponse,
|
||||
}, nil
|
||||
})
|
||||
|
||||
// Get specific server version endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server-version",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{serverName}/versions/{version}",
|
||||
Summary: "Get specific MCP server version",
|
||||
Description: "Get detailed information about a specific version of an MCP server.",
|
||||
Tags: []string{"servers"},
|
||||
}, func(ctx context.Context, input *ServerVersionDetailInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// URL-decode the version
|
||||
version, err := url.PathUnescape(input.Version)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid version encoding", err)
|
||||
}
|
||||
|
||||
// Get specific version by server name and version
|
||||
serverResponse, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *serverResponse,
|
||||
}, nil
|
||||
})
|
||||
|
||||
|
|
@ -136,23 +173,35 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server-versions",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{server_id}/versions",
|
||||
Path: "/v0/servers/{serverName}/versions",
|
||||
Summary: "Get all versions of an MCP server",
|
||||
Description: "Get all available versions for a specific MCP server",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerID(input.ServerID)
|
||||
}, func(ctx context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
if err.Error() == "record not found" {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
|
||||
}
|
||||
|
||||
// Convert []*ServerResponse to []ServerResponse
|
||||
serverValues := make([]apiv0.ServerResponse, len(servers))
|
||||
for i, server := range servers {
|
||||
serverValues[i] = *server
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerListResponse]{
|
||||
Body: apiv0.ServerListResponse{
|
||||
Servers: servers,
|
||||
Servers: serverValues,
|
||||
Metadata: apiv0.Metadata{
|
||||
Count: len(servers),
|
||||
},
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
|
@ -22,7 +23,7 @@ import (
|
|||
|
||||
func TestPrometheusHandler(t *testing.T) {
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
server, err := registryService.Publish(apiv0.ServerJSON{
|
||||
server, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: "io.github.example/test-server",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -50,8 +51,8 @@ func TestPrometheusHandler(t *testing.T) {
|
|||
// Add /metrics for Prometheus metrics using promhttp
|
||||
mux.Handle("/metrics", metrics.PrometheusHandler())
|
||||
|
||||
// Create request
|
||||
url := "/v0/servers/" + server.Meta.Official.ServerID
|
||||
// Create request - using new name-based API
|
||||
url := "/v0/servers/" + url.PathEscape(server.Server.Name)
|
||||
req := httptest.NewRequest(http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
|
@ -76,5 +77,5 @@ func TestPrometheusHandler(t *testing.T) {
|
|||
// Check if the response body contains expected metrics
|
||||
assert.Contains(t, body, "mcp_registry_http_request_duration_bucket")
|
||||
assert.Contains(t, body, "mcp_registry_http_requests_total")
|
||||
assert.Contains(t, body, "path=\"/v0/servers/{server_id}\"")
|
||||
assert.Contains(t, body, "path=\"/v0/servers/{serverName}\"")
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue