Publisher-managed "deleted" support (#893)
(Updated auto-generated PR description from @tadasant / Claude on Feb 22, 2026) ## Motivation and Context Fixes #637 Server lifecycle management (deprecation and yanking) is a standard requirement for package registries. Use cases like rebranding, security vulnerabilities, and end-of-life servers demand the ability to mark servers as deprecated or deleted, with optional messaging to guide consumers toward alternatives. ## Changes ### New API endpoints - **`PATCH /v0/servers/{serverName}/versions/{version}/status`** — Update the lifecycle status of a single server version - **`PATCH /v0/servers/{serverName}/status`** — Update the lifecycle status of all versions of a server in a single transaction Both endpoints accept: ```json { "status": "active|deprecated|deleted", "statusMessage": "Optional message (max 500 chars) explaining the change" } ``` ### New CLI command - **`mcp-publisher status <serverName> [version]`** — Update server lifecycle status from the command line - `--status` (required): `active`, `deprecated`, or `deleted` - `--message`: Optional status message - `--all-versions`: Apply to all versions of the server (replaces the `<version>` argument) ### API response changes `RegistryExtensions` now includes two new fields: - `statusChangedAt` — Timestamp of the last status change - `statusMessage` — Optional free-form message (e.g., deprecation reason, migration guidance) ### List endpoint changes - New `include_deleted` query parameter on `GET /v0/servers` — defaults to `false`, hiding deleted servers from listings - When `updated_since` is provided, `include_deleted` is automatically set to `true` for incremental sync ### Database - Migration `013_add_status_fields.sql`: Adds `status_changed_at` (NOT NULL, initialized from `published_at`) and `status_message` columns to the `servers` table ### Design decisions (from review discussion) - **Dedicated status endpoints** rather than overloading the existing edit endpoint - **Bidirectional status transitions** — all transitions between `active`, `deprecated`, and `deleted` are allowed - **`statusMessage` as free-form text** — no structured `nextName` or `alternativeUrl` fields (per maintainer feedback, to avoid complexity around chaining, trust transfer, etc.) - **Publish permission** grants status change access (not limited to admin/edit) - **Status message auto-cleared** when transitioning back to `active` Good, now I have the full picture. Here's the addendum: ### Consumer-facing API changes The new status fields live inside `_meta["io.modelcontextprotocol.registry/official"]` on every `ServerResponse`. This is the existing `RegistryExtensions` object — two new fields are added alongside the existing ones: **Before:** ```json { "server": { "name": "com.example/my-server", "...": "..." }, "_meta": { "io.modelcontextprotocol.registry/official": { "status": "active", "publishedAt": "2025-06-01T00:00:00Z", "updatedAt": "2025-06-15T00:00:00Z", "isLatest": true } } } ``` **After:** ```json { "server": { "name": "com.example/my-server", "...": "..." }, "_meta": { "io.modelcontextprotocol.registry/official": { "status": "deprecated", "statusChangedAt": "2026-02-01T12:00:00Z", "statusMessage": "Deprecated in favor of com.example/my-server-v2", "publishedAt": "2025-06-01T00:00:00Z", "updatedAt": "2026-02-01T12:00:00Z", "isLatest": true } } } ``` | New field | Type | Present when | |-----------|------|-------------| | `statusChangedAt` | `string` (RFC3339) | Always — initialized to `publishedAt` for existing records | | `statusMessage` | `string` (max 500 chars) | Only when set — `null`/omitted for active servers (auto-cleared on transition to active) | These fields appear on **every endpoint that returns a `ServerResponse`**: `GET /v0/servers`, `GET /v0/servers/{name}`, `GET /v0/servers/{name}/versions/{version}`, and the new PATCH status endpoints. ### List endpoint filtering `GET /v0/servers` gains an `include_deleted` query parameter: | Scenario | Behavior | |----------|----------| | No `include_deleted` param | Deleted servers hidden (default `false`) | | `include_deleted=true` | Deleted servers included in results | | `updated_since` provided | `include_deleted` forced to `true` for incremental sync | ## How Has This Been Tested? - Unit tests for status handler (`status_test.go`) covering status transitions, permission checks, validation errors, and the all-versions endpoint - Unit tests for the CLI command (`status_test.go`) - Integration with existing server/edit handler tests - Database layer tests for the new status update and query methods - Tested locally with `make dev-compose` ## Types of changes - [x] New feature (non-breaking change which adds functionality) ## Checklist - [x] I have read the [MCP Documentation](https://modelcontextprotocol.io) - [x] My code follows the repository's style guidelines - [x] New and existing tests pass locally - [x] I have added appropriate error handling - [x] I have added or updated documentation as needed ## Open items from review - [ ] `include_deleted` silent override: When `updated_since` is provided and `include_deleted=false` is explicitly passed, should return a 400 error rather than silently overriding ([thread](https://github.com/modelcontextprotocol/registry/pull/893#discussion_r2100879360)) — agreed upon but may not yet be implemented
This commit is contained in:
parent
01e4e2b09e
commit
bb84ea69e8
6 changed files with 4153 additions and 474 deletions
|
|
@ -8,13 +8,13 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"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"
|
||||
)
|
||||
|
||||
// EditServerInput represents the input for editing a server
|
||||
|
|
@ -22,7 +22,6 @@ type EditServerInput struct {
|
|||
Authorization string `header:"Authorization" doc:"Registry JWT token with edit permissions" required:"true"`
|
||||
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:""`
|
||||
}
|
||||
|
||||
|
|
@ -36,8 +35,8 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
Method: http.MethodPut,
|
||||
Path: pathPrefix + "/servers/{serverName}/versions/{version}",
|
||||
Summary: "Edit MCP server",
|
||||
Description: "Update a specific version of an existing MCP server (admin only).",
|
||||
Tags: []string{"admin"},
|
||||
Description: "Update the configuration of a specific version of an existing MCP server. Requires edit permission for the server. Use PATCH /servers/{serverName}/versions/{version}/status to update status metadata.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
|
|
@ -69,7 +68,8 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
// Deleted servers return 404 - restore via status endpoint first
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version, false)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -98,28 +98,7 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
return nil, huma.Error422UnprocessableEntity("Failed to edit server, invalid schema: call /validate for details")
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
updatedServer, err := registry.UpdateServer(ctx, serverName, version, &input.Body, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
|
|||
|
|
@ -71,25 +71,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Create a deleted server for undelete testing
|
||||
deletedServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
|
|
@ -112,7 +93,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody apiv0.ServerJSON
|
||||
statusParam string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
|
|
@ -148,31 +128,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
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{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
|
|
@ -310,27 +265,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
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{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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",
|
||||
|
|
@ -381,9 +315,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
encodedVersion := url.PathEscape(tc.version)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/versions/" + encodedVersion
|
||||
if tc.statusParam != "" {
|
||||
requestURL += "?status=" + tc.statusParam
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
|
@ -404,6 +335,9 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
|
|
@ -437,12 +371,10 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
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},
|
||||
{"com.example/active-server", "1.0.0"},
|
||||
{"com.example/multi-version-server", "1.0.0"},
|
||||
{"com.example/multi-version-server", "2.0.0"},
|
||||
}
|
||||
|
||||
for _, server := range testServers {
|
||||
|
|
@ -453,17 +385,6 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
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{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
}, stringPtr(string(server.status)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create API
|
||||
|
|
@ -471,95 +392,6 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterEditEndpoints(api, "/v0", 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{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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"
|
||||
|
|
@ -651,13 +483,70 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
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")
|
||||
otherVersion, err := registryService.GetServerByNameAndVersion(context.Background(), "com.example/multi-version-server", "2.0.0", false)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, "Updated v1.0.0 specifically", otherVersion.Server.Description)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
t.Run("edit preserves status metadata", func(t *testing.T) {
|
||||
// Create a server and set it to deprecated using the service directly
|
||||
deprecatedServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deprecated-for-edit-test",
|
||||
Description: "Server to test edit preserves status",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
_, err := registryService.CreateServer(context.Background(), deprecatedServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set to deprecated status using UpdateServerStatus
|
||||
statusMsg := "This server is deprecated"
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), deprecatedServer.Name, deprecatedServer.Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeprecated,
|
||||
StatusMessage: &statusMsg,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Now edit the server description
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deprecated-for-edit-test",
|
||||
Description: "Updated description but status should remain deprecated",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape("com.example/deprecated-for-edit-test")
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
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 description but status should remain deprecated", response.Server.Description)
|
||||
// Status should still be deprecated
|
||||
assert.Equal(t, model.StatusDeprecated, response.Meta.Official.Status)
|
||||
// Status message should be preserved
|
||||
assert.NotNil(t, response.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "This server is deprecated", *response.Meta.Official.StatusMessage)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -16,13 +17,49 @@ import (
|
|||
|
||||
const errRecordNotFound = "record not found"
|
||||
|
||||
// OptionalBool tracks whether a bool query parameter was explicitly set
|
||||
type OptionalBool struct {
|
||||
Value bool
|
||||
IsSet bool
|
||||
}
|
||||
|
||||
// Schema implements huma.SchemaProvider - returns schema for the wrapped type
|
||||
func (o OptionalBool) Schema(r huma.Registry) *huma.Schema {
|
||||
return huma.SchemaFromType(r, reflect.TypeOf(o.Value))
|
||||
}
|
||||
|
||||
// Receiver implements huma.ParamWrapper - exposes wrapped value to receive parsed value
|
||||
func (o *OptionalBool) Receiver() reflect.Value {
|
||||
return reflect.ValueOf(o).Elem().Field(0)
|
||||
}
|
||||
|
||||
// OnParamSet implements huma.ParamReactor - tracks whether parameter was set in request
|
||||
func (o *OptionalBool) OnParamSet(isSet bool, _ any) {
|
||||
o.IsSet = isSet
|
||||
}
|
||||
|
||||
// resolveIncludeDeleted handles the include_deleted parameter logic for list endpoints
|
||||
// Returns the resolved value and an error if include_deleted=false conflicts with updated_since
|
||||
func resolveIncludeDeleted(includeDeleted OptionalBool, hasUpdatedSince bool) (bool, error) {
|
||||
if hasUpdatedSince {
|
||||
// When updated_since is provided, include_deleted must be true for incremental sync
|
||||
if includeDeleted.IsSet && !includeDeleted.Value {
|
||||
return false, huma.Error400BadRequest("Cannot set include_deleted=false when using updated_since (incremental sync requires deleted servers)")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
// Use provided value, defaults to false if not set
|
||||
return includeDeleted.Value, nil
|
||||
}
|
||||
|
||||
// ListServersInput represents the input for listing servers
|
||||
type ListServersInput struct {
|
||||
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"`
|
||||
Version string `query:"version" doc:"Filter by version ('latest' for latest version, or an exact version like '1.2.3')" required:"false" example:"latest"`
|
||||
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"`
|
||||
Version string `query:"version" doc:"Filter by version ('latest' for latest version, or an exact version like '1.2.3')" required:"false" example:"latest"`
|
||||
IncludeDeleted OptionalBool `query:"include_deleted" doc:"Include deleted servers in results (default: false, but always true when updated_since is provided)" required:"false"`
|
||||
}
|
||||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
|
|
@ -32,13 +69,15 @@ type ServerDetailInput struct {
|
|||
|
||||
// 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"`
|
||||
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"`
|
||||
IncludeDeleted bool `query:"include_deleted" doc:"Include deleted servers in results (default: false)" required:"false" default:"false"`
|
||||
}
|
||||
|
||||
// ServerVersionsInput represents the input for listing all versions of a server
|
||||
type ServerVersionsInput struct {
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
IncludeDeleted bool `query:"include_deleted" doc:"Include deleted servers in results (default: false)" required:"false" default:"false"`
|
||||
}
|
||||
|
||||
// RegisterServersEndpoints registers all server-related endpoints with a custom path prefix
|
||||
|
|
@ -82,6 +121,13 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
}
|
||||
}
|
||||
|
||||
// Handle include_deleted parameter
|
||||
includeDeleted, err := resolveIncludeDeleted(input.IncludeDeleted, filter.UpdatedSince != nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.IncludeDeleted = &includeDeleted
|
||||
|
||||
// Get paginated results with filtering
|
||||
servers, nextCursor, err := registry.ListServers(ctx, filter, input.Cursor, input.Limit)
|
||||
if err != nil {
|
||||
|
|
@ -129,9 +175,9 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
var serverResponse *apiv0.ServerResponse
|
||||
// Handle "latest" as a special version
|
||||
if version == "latest" {
|
||||
serverResponse, err = registry.GetServerByName(ctx, serverName)
|
||||
serverResponse, err = registry.GetServerByName(ctx, serverName, input.IncludeDeleted)
|
||||
} else {
|
||||
serverResponse, err = registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
serverResponse, err = registry.GetServerByNameAndVersion(ctx, serverName, version, input.IncludeDeleted)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
|
@ -162,7 +208,7 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
}
|
||||
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName)
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName, input.IncludeDeleted)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
|
|||
|
|
@ -392,6 +392,122 @@ func TestGetAllVersionsEndpoint(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestListServersDeletedFiltering(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
// Setup test data: 2 active servers and 1 deleted server
|
||||
_, err := registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/active-server-1",
|
||||
Description: "Active server 1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/active-server-2",
|
||||
Description: "Active server 2",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deleted-server",
|
||||
Description: "Deleted server",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete the third server
|
||||
_, err = registryService.UpdateServerStatus(ctx, "com.example/deleted-server", "1.0.0", &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterServersEndpoints(api, "/v0", registryService)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
expectedCount int
|
||||
checkDeleted bool // whether deleted server should be in results
|
||||
}{
|
||||
{
|
||||
name: "default excludes deleted servers",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
checkDeleted: false,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=false excludes deleted servers",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
checkDeleted: false,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=true includes deleted servers",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 3,
|
||||
checkDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "updated_since always includes deleted servers",
|
||||
queryParams: "?updated_since=1990-01-01T00:00:00Z",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 3,
|
||||
checkDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "updated_since with include_deleted=false returns error",
|
||||
queryParams: "?updated_since=1990-01-01T00:00:00Z&include_deleted=false",
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedCount: 0,
|
||||
checkDeleted: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers"+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
// Skip response body checks for error responses
|
||||
if tt.expectedStatus != http.StatusOK {
|
||||
return
|
||||
}
|
||||
|
||||
var resp apiv0.ServerListResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, resp.Servers, tt.expectedCount)
|
||||
|
||||
// Check if deleted server is in results
|
||||
hasDeleted := false
|
||||
for _, server := range resp.Servers {
|
||||
if server.Server.Name == "com.example/deleted-server" {
|
||||
hasDeleted = true
|
||||
assert.Equal(t, model.StatusDeleted, server.Meta.Official.Status)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, tt.checkDeleted, hasDeleted, "Deleted server presence mismatch")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServersEndpointEdgeCases(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
|
@ -518,3 +634,137 @@ func TestServersEndpointEdgeCases(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestIncludeDeletedOnDetailEndpoints(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
serverName := "com.example/deleted-detail-test"
|
||||
|
||||
// Create server with multiple versions
|
||||
_, err := registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: serverName,
|
||||
Description: "Test server v1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: serverName,
|
||||
Description: "Test server v2",
|
||||
Version: "2.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete version 1.0.0
|
||||
_, err = registryService.UpdateServerStatus(ctx, serverName, "1.0.0", &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterServersEndpoints(api, "/v0", registryService)
|
||||
|
||||
encodedName := url.PathEscape(serverName)
|
||||
|
||||
t.Run("detail endpoint", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
version string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
}{
|
||||
{
|
||||
name: "deleted version without include_deleted returns 404",
|
||||
version: "1.0.0",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "deleted version with include_deleted=false returns 404",
|
||||
version: "1.0.0",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "deleted version with include_deleted=true returns 200",
|
||||
version: "1.0.0",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "active version without include_deleted returns 200",
|
||||
version: "2.0.0",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
encodedVersion := url.PathEscape(tt.version)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers/"+encodedName+"/versions/"+encodedVersion+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
if tt.expectedStatus == http.StatusOK {
|
||||
var resp apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.version, resp.Server.Version)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("version history endpoint", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
expectedCount int
|
||||
}{
|
||||
{
|
||||
name: "without include_deleted excludes deleted versions",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=false excludes deleted versions",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=true includes deleted versions",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers/"+encodedName+"/versions"+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
var resp apiv0.ServerListResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, resp.Servers, tt.expectedCount)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
299
internal/api/handlers/v0/status.go
Normal file
299
internal/api/handlers/v0/status.go
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
package v0
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// UpdateServerStatusBody represents the request body for updating server status
|
||||
type UpdateServerStatusBody struct {
|
||||
Status string `json:"status" required:"true" enum:"active,deprecated,deleted" doc:"New server lifecycle status"`
|
||||
StatusMessage *string `json:"statusMessage,omitempty" maxLength:"500" doc:"Optional message explaining the status change (e.g., reason for deprecation)"`
|
||||
}
|
||||
|
||||
// UpdateServerStatusInput represents the input for updating server status
|
||||
type UpdateServerStatusInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with publish or edit permissions" required:"true"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded version to update" example:"1.0.0"`
|
||||
Body UpdateServerStatusBody `body:""`
|
||||
}
|
||||
|
||||
// validateStatusTransition validates if the status transition is allowed
|
||||
// Returns nil if status or message differs from current (something to update)
|
||||
// Returns error if nothing changes (no-op) or if status transition is invalid
|
||||
func validateStatusTransition(currentServer *apiv0.ServerResponse, newStatus model.Status, body UpdateServerStatusBody) error {
|
||||
// Validate newStatus is a valid value
|
||||
validStatuses := map[model.Status]bool{
|
||||
model.StatusActive: true,
|
||||
model.StatusDeprecated: true,
|
||||
model.StatusDeleted: true,
|
||||
}
|
||||
if !validStatuses[newStatus] {
|
||||
return huma.Error400BadRequest(fmt.Sprintf("Invalid status: %s. Must be one of: active, deprecated, deleted", newStatus))
|
||||
}
|
||||
|
||||
// Reject status_message when setting status to active
|
||||
if newStatus == model.StatusActive && body.StatusMessage != nil {
|
||||
return huma.Error400BadRequest("status_message cannot be provided when setting status to active")
|
||||
}
|
||||
|
||||
if currentServer.Meta.Official == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
currentStatus := currentServer.Meta.Official.Status
|
||||
currentMessage := currentServer.Meta.Official.StatusMessage
|
||||
newMessage := body.StatusMessage
|
||||
|
||||
statusChanges := currentStatus != newStatus
|
||||
messageChanges := (currentMessage == nil) != (newMessage == nil) ||
|
||||
(currentMessage != nil && newMessage != nil && *currentMessage != *newMessage)
|
||||
|
||||
// Valid if either status or message changes
|
||||
if statusChanges || messageChanges {
|
||||
return nil
|
||||
}
|
||||
|
||||
return huma.Error400BadRequest("No changes to apply: status and message are already set to the provided values")
|
||||
}
|
||||
|
||||
// RegisterStatusEndpoints registers the status update endpoint with a custom path prefix
|
||||
func RegisterStatusEndpoints(api huma.API, pathPrefix string, registry service.RegistryService, cfg *config.Config) {
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
|
||||
// Update server status endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "update-server-status" + strings.ReplaceAll(pathPrefix, "/", "-"),
|
||||
Method: http.MethodPatch,
|
||||
Path: pathPrefix + "/servers/{serverName}/versions/{version}/status",
|
||||
Summary: "Update MCP server status",
|
||||
Description: "Update the status metadata of a specific version of an MCP server. Requires publish or edit permission for the server. This endpoint allows changing status and status message without requiring the full server configuration.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *UpdateServerStatusInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
if len(authHeader) < len(bearerPrefix) || !strings.EqualFold(authHeader[:len(bearerPrefix)], bearerPrefix) {
|
||||
return nil, huma.Error401Unauthorized("Invalid Authorization header format. Expected 'Bearer <token>'")
|
||||
}
|
||||
token := authHeader[len(bearerPrefix):]
|
||||
|
||||
// Validate Registry JWT token
|
||||
claims, err := jwtManager.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
newStatus := model.Status(input.Body.Status)
|
||||
|
||||
// Get the server and verify it exists
|
||||
// Include deleted servers since we need to be able to restore them
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version, true)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server version not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server", err)
|
||||
}
|
||||
|
||||
// Verify publish or edit permissions for this server
|
||||
hasPublish := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionPublish, claims.Permissions)
|
||||
hasEdit := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions)
|
||||
if !hasPublish && !hasEdit {
|
||||
return nil, huma.Error403Forbidden("You do not have publish or edit permissions for this server")
|
||||
}
|
||||
|
||||
// Validate status transition is allowed
|
||||
if err := validateStatusTransition(currentServer, newStatus, input.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build status change request
|
||||
statusChange := buildStatusChangeRequestFromBody(input.Body)
|
||||
|
||||
// Update the server status using the service
|
||||
updatedServer, err := registry.UpdateServerStatus(ctx, serverName, version, statusChange)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error400BadRequest("Failed to update server status", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *updatedServer,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// buildStatusChangeRequestFromBody constructs a StatusChangeRequest from the request body
|
||||
func buildStatusChangeRequestFromBody(body UpdateServerStatusBody) *service.StatusChangeRequest {
|
||||
var statusMessage *string
|
||||
|
||||
newStatus := model.Status(body.Status)
|
||||
|
||||
// When transitioning to active status, clear status_message
|
||||
if newStatus != model.StatusActive {
|
||||
statusMessage = body.StatusMessage
|
||||
}
|
||||
|
||||
return &service.StatusChangeRequest{
|
||||
NewStatus: newStatus,
|
||||
StatusMessage: statusMessage,
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateAllVersionsStatusInput represents the input for updating all versions' status
|
||||
type UpdateAllVersionsStatusInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with publish or edit permissions" required:"true"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Body UpdateServerStatusBody `body:""`
|
||||
}
|
||||
|
||||
// UpdateAllVersionsStatusResponse represents the response for updating all versions' status
|
||||
type UpdateAllVersionsStatusResponse struct {
|
||||
UpdatedCount int `json:"updatedCount" doc:"Number of versions updated"`
|
||||
Servers []apiv0.ServerResponse `json:"servers" doc:"List of all updated server versions"`
|
||||
}
|
||||
|
||||
// RegisterAllVersionsStatusEndpoints registers the all-versions status update endpoint
|
||||
func RegisterAllVersionsStatusEndpoints(api huma.API, pathPrefix string, registry service.RegistryService, cfg *config.Config) {
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
|
||||
// Update all versions status endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "update-server-all-versions-status" + strings.ReplaceAll(pathPrefix, "/", "-"),
|
||||
Method: http.MethodPatch,
|
||||
Path: pathPrefix + "/servers/{serverName}/status",
|
||||
Summary: "Update status for all versions of an MCP server",
|
||||
Description: "Update the status metadata of all versions of an MCP server in a single transaction. Requires publish or edit permission for the server. Either all versions are updated or none on failure.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *UpdateAllVersionsStatusInput) (*Response[UpdateAllVersionsStatusResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
if len(authHeader) < len(bearerPrefix) || !strings.EqualFold(authHeader[:len(bearerPrefix)], bearerPrefix) {
|
||||
return nil, huma.Error401Unauthorized("Invalid Authorization header format. Expected 'Bearer <token>'")
|
||||
}
|
||||
token := authHeader[len(bearerPrefix):]
|
||||
|
||||
// Validate Registry JWT token
|
||||
claims, err := jwtManager.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get any version to verify server exists and check permissions
|
||||
// Include deleted servers since we need to be able to restore them
|
||||
currentServer, err := registry.GetServerByName(ctx, serverName, true)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server", err)
|
||||
}
|
||||
|
||||
// Verify publish or edit permissions for this server
|
||||
hasPublish := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionPublish, claims.Permissions)
|
||||
hasEdit := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions)
|
||||
if !hasPublish && !hasEdit {
|
||||
return nil, huma.Error403Forbidden("You do not have publish or edit permissions for this server")
|
||||
}
|
||||
|
||||
newStatus := model.Status(input.Body.Status)
|
||||
|
||||
// Fetch all versions to validate the bulk status transition
|
||||
allVersions, err := registry.GetAllVersionsByServerName(ctx, serverName, true)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
|
||||
}
|
||||
|
||||
// Validate bulk status transition - reject if no changes would occur
|
||||
if err := validateBulkStatusTransition(allVersions, newStatus, input.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build status change request
|
||||
statusChange := buildStatusChangeRequestFromBody(input.Body)
|
||||
|
||||
// Update all versions' status using the service
|
||||
updatedServers, err := registry.UpdateAllVersionsStatus(ctx, serverName, statusChange)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error400BadRequest("Failed to update server status", err)
|
||||
}
|
||||
|
||||
// Convert to response format
|
||||
servers := make([]apiv0.ServerResponse, len(updatedServers))
|
||||
for i, s := range updatedServers {
|
||||
servers[i] = *s
|
||||
}
|
||||
|
||||
return &Response[UpdateAllVersionsStatusResponse]{
|
||||
Body: UpdateAllVersionsStatusResponse{
|
||||
UpdatedCount: len(servers),
|
||||
Servers: servers,
|
||||
},
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// validateBulkStatusTransition validates if a bulk status transition would result in any changes
|
||||
// Returns an error if no changes would occur (all versions already have target status and message)
|
||||
func validateBulkStatusTransition(versions []*apiv0.ServerResponse, newStatus model.Status, body UpdateServerStatusBody) error {
|
||||
if len(versions) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check if any version would have changes applied
|
||||
for _, version := range versions {
|
||||
err := validateStatusTransition(version, newStatus, body)
|
||||
if err == nil {
|
||||
// This version has changes, so the bulk operation is valid
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// No versions would have any changes
|
||||
return huma.Error400BadRequest("No changes to apply: all versions already have the requested status and message")
|
||||
}
|
||||
885
internal/api/handlers/v0/status_test.go
Normal file
885
internal/api/handlers/v0/status_test.go
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
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"
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestUpdateServerStatusEndpoint(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 and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create test servers for different scenarios
|
||||
testServers := map[string]*apiv0.ServerJSON{
|
||||
"active": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/active-server",
|
||||
Description: "Server in active status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/active-server",
|
||||
Source: "github",
|
||||
ID: "testuser/active-server",
|
||||
},
|
||||
},
|
||||
"deprecated": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deprecated-server",
|
||||
Description: "Server in deprecated status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/deprecated-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deprecated-server",
|
||||
},
|
||||
},
|
||||
"deleted": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Server in deleted status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/deleted-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deleted-server",
|
||||
},
|
||||
},
|
||||
"other": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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",
|
||||
},
|
||||
},
|
||||
"multi-version": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions for testing",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create the test servers
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), server)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Set deprecated server to deprecated status
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), testServers["deprecated"].Name, testServers["deprecated"].Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeprecated,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set deleted server to deleted status
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), testServers["deleted"].Name, testServers["deleted"].Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add a second version to multi-version server
|
||||
multiVersionV2 := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions for testing",
|
||||
Version: "2.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionV2)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody v0.UpdateServerStatusBody
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful status change from active to deprecated",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with message",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deleted",
|
||||
StatusMessage: strPtr("Security vulnerability discovered"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeleted, resp.Meta.Official.Status)
|
||||
assert.NotNil(t, resp.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Security vulnerability discovered", *resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful restore from deleted to active",
|
||||
serverName: "io.github.testuser/deleted-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
// Status message should be cleared when transitioning to active
|
||||
assert.Nil(t, resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful undeprecate from deprecated to active",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "",
|
||||
requestBody: v0.UpdateServerStatusBody{Status: "deprecated"},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid or expired Registry JWT token",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no publish or edit permissions",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: "read", ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
name: "successful status change with edit permission only",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with both publish and edit permissions",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
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.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
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.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server version not found",
|
||||
},
|
||||
{
|
||||
name: "same status transition allowed when updating statusMessage",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("Updated deprecation message"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
assert.NotNil(t, resp.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Updated deprecation message", *resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status_message rejected when setting status to active",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
StatusMessage: strPtr("This message should not be allowed"),
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "status_message cannot be provided when setting status to active",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register status endpoints
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
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 + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, 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 and execute request
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
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 TestUpdateServerStatusEndpointSameStatusTransition(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)
|
||||
|
||||
// Create an active server
|
||||
activeServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/same-status-test",
|
||||
Description: "Server for same status transition test",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), activeServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Try to transition from active to active (should fail)
|
||||
requestBody := v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
}
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(activeServer.Name)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, 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.PermissionActionPublish, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
assert.Contains(t, w.Body.String(), "No changes to apply: status and message are already set to the provided values")
|
||||
}
|
||||
|
||||
func TestUpdateServerStatusEndpointURLEncoding(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)
|
||||
|
||||
// Create a server with build metadata version
|
||||
buildMetadataServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Server with build metadata version",
|
||||
Version: "1.0.0+20130313144700",
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), buildMetadataServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Update status with URL-encoded version
|
||||
requestBody := v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("Testing URL encoding"),
|
||||
}
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(buildMetadataServer.Name)
|
||||
encodedVersion := url.PathEscape(buildMetadataServer.Version)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/" + encodedVersion + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, 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.PermissionActionPublish, 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, model.StatusDeprecated, response.Meta.Official.Status)
|
||||
assert.Equal(t, "1.0.0+20130313144700", response.Server.Version)
|
||||
}
|
||||
|
||||
func TestUpdateAllVersionsStatusEndpoint(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 and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create a server with multiple versions
|
||||
multiVersionServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add more versions
|
||||
multiVersionServer.Version = "1.1.0"
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
multiVersionServer.Version = "2.0.0"
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create other user's server
|
||||
otherServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
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",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), otherServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
serverName string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody v0.UpdateServerStatusBody
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *v0.UpdateAllVersionsStatusResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful deprecation of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("This server is deprecated"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
assert.Len(t, resp.Servers, 3)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeprecated, server.Meta.Official.Status)
|
||||
assert.NotNil(t, server.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "This server is deprecated", *server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful delete of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deleted",
|
||||
StatusMessage: strPtr("Security issue discovered"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeleted, server.Meta.Official.Status)
|
||||
assert.NotNil(t, server.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Security issue discovered", *server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful reactivation of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusActive, server.Meta.Official.Status)
|
||||
// Status message should be cleared when transitioning to active
|
||||
assert.Nil(t, server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authHeader: "",
|
||||
requestBody: v0.UpdateServerStatusBody{Status: "deprecated"},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no publish or edit permissions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: "read", ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
name: "successful status change with edit permission only",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeprecated, server.Meta.Official.Status)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with both publish and edit permissions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusActive, server.Meta.Official.Status)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bulk no-op when all versions already have target status and message",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "No changes to apply: all versions already have the requested status and message",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverName: "io.github.testuser/non-existent",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server not found",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register all-versions status endpoints
|
||||
v0.RegisterAllVersionsStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
requestBody, err := json.Marshal(tc.requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create request URL with proper encoding
|
||||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, 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 and execute request
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
if tc.expectedStatus == http.StatusOK && tc.checkResult != nil {
|
||||
var response v0.UpdateAllVersionsStatusResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
tc.checkResult(t, &response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// strPtr is a helper function to create a pointer to a string
|
||||
func strPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
Loading…
Reference in a new issue