registry/internal/auth/jwt.go
Preeti Dewani bb84ea69e8
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
2026-02-27 09:00:07 -08:00

166 lines
4.6 KiB
Go

package auth
import (
"context"
"crypto/ed25519"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/modelcontextprotocol/registry/internal/config"
)
// PermissionAction represents the type of action that can be performed
type PermissionAction string
const (
PermissionActionPublish PermissionAction = "publish"
// PermissionActionEdit allows editing server configuration.
PermissionActionEdit PermissionAction = "edit"
)
type Permission struct {
Action PermissionAction `json:"action"` // The action type (publish or edit)
ResourcePattern string `json:"resource"` // e.g., "io.github.username/*"
}
// JWTClaims represents the claims for the Registry JWT token
type JWTClaims struct {
jwt.RegisteredClaims
// Authentication method used to obtain this token
AuthMethod Method `json:"auth_method"`
AuthMethodSubject string `json:"auth_method_sub"`
Permissions []Permission `json:"permissions"`
}
type TokenResponse struct {
RegistryToken string `json:"registry_token"`
ExpiresAt int `json:"expires_at"`
}
// JWTManager handles JWT token operations
type JWTManager struct {
privateKey ed25519.PrivateKey
publicKey ed25519.PublicKey
tokenDuration time.Duration
}
func NewJWTManager(cfg *config.Config) *JWTManager {
seed, err := hex.DecodeString(cfg.JWTPrivateKey)
if err != nil {
panic(fmt.Sprintf("JWTPrivateKey must be a valid hex-encoded string: %v", err))
}
// Require a valid Ed25519 seed (32 bytes)
if len(seed) != ed25519.SeedSize {
panic(fmt.Sprintf("JWTPrivateKey seed must be exactly %d bytes for Ed25519, got %d bytes", ed25519.SeedSize, len(seed)))
}
// Generate the full Ed25519 key pair from the seed
privateKey := ed25519.NewKeyFromSeed(seed)
publicKey := privateKey.Public().(ed25519.PublicKey)
return &JWTManager{
privateKey: privateKey,
publicKey: publicKey,
tokenDuration: 5 * time.Minute, // 5-minute tokens as per requirements
}
}
// GenerateToken generates a new Registry JWT token
func (j *JWTManager) GenerateTokenResponse(_ context.Context, claims JWTClaims) (*TokenResponse, error) {
// Check whether they have global permissions (used by admins)
hasGlobalPermissions := false
for _, perm := range claims.Permissions {
if perm.ResourcePattern == "*" {
hasGlobalPermissions = true
break
}
}
// Check permissions against denylist, provided they are not an admin
if !hasGlobalPermissions {
for _, blockedNamespace := range BlockedNamespaces {
if j.HasPermission(blockedNamespace+"/test", PermissionActionPublish, claims.Permissions) {
return nil, fmt.Errorf("your namespace is blocked. raise an issue at https://github.com/modelcontextprotocol/registry/ if you think this is a mistake")
}
}
}
if claims.IssuedAt == nil {
claims.IssuedAt = jwt.NewNumericDate(time.Now())
}
if claims.ExpiresAt == nil {
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(j.tokenDuration))
}
if claims.NotBefore == nil {
claims.NotBefore = jwt.NewNumericDate(time.Now())
}
if claims.Issuer == "" {
claims.Issuer = "mcp-registry"
}
// Create token with claims
token := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, claims)
// Sign token with Ed25519 private key
tokenString, err := token.SignedString(j.privateKey)
if err != nil {
return nil, fmt.Errorf("failed to sign token: %w", err)
}
return &TokenResponse{
RegistryToken: tokenString,
ExpiresAt: int(claims.ExpiresAt.Unix()),
}, nil
}
// ValidateToken validates a Registry JWT token and returns the claims
func (j *JWTManager) ValidateToken(_ context.Context, tokenString string) (*JWTClaims, error) {
// Parse token
// This also validates expiry
token, err := jwt.ParseWithClaims(
tokenString,
&JWTClaims{},
func(_ *jwt.Token) (interface{}, error) { return j.publicKey, nil },
jwt.WithValidMethods([]string{"EdDSA"}),
jwt.WithExpirationRequired(),
)
// Validate token
if err != nil {
return nil, fmt.Errorf("failed to parse token: %w", err)
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
// Extract claims
claims, ok := token.Claims.(*JWTClaims)
if !ok {
return nil, fmt.Errorf("invalid token claims")
}
return claims, nil
}
func (j *JWTManager) HasPermission(resource string, action PermissionAction, permissions []Permission) bool {
for _, perm := range permissions {
if perm.Action == action && isResourceMatch(resource, perm.ResourcePattern) {
return true
}
}
return false
}
func isResourceMatch(resource, pattern string) bool {
if pattern == "*" {
return true
}
if strings.HasSuffix(pattern, "*") {
return strings.HasPrefix(resource, strings.TrimSuffix(pattern, "*"))
}
return resource == pattern
}