registry/internal/api/handlers/v0/publish.go
Radoslav Dimitrov 8759d9d8c0
ci: bump golangci-lint to v2.13.1 to fix panic on Go 1.27 (#1561)
CI is red on `main` and on every open PR (including the Dependabot PRs
#1531, #1552–#1554) with:

```
panic: file requires newer Go version go1.27 (application built with go1.26)
golangci-lint exit with code 2
```

## Cause

`actions/setup-go` with `go-version: 'stable'` started resolving to
**go1.27.0**. The pinned golangci-lint **v2.11.4** release binary is
built with **go1.26**, and its `go/types` refuses to typecheck source
files declaring a newer language version. Nothing in the failing PRs is
at fault.

## Fix

Bump to **golangci-lint v2.13.1**, whose release binaries are built with
go1.27, so linting works under `stable` again.

That bump also pulls in newer linter versions, which surface 57 findings
this tree did not have before. Handled as follows:

| Linter | Count | Resolution |
|---|---|---|
| `goconst` | 50 | 39 were repeated literals in `_test.go` files —
goconst started counting those in v2.12.0 (golangci-lint#6480 exposed
`ignore-tests`). Fixture data like `"1.0.0"` (89 occurrences) is not a
missing constant, so `goconst.ignore-tests: true`. The other 11 were
real duplication in production code (OpenAPI tags, the `bearer` security
scheme name, `$ref`, `http`/`https`) and became named constants. |
| `gosec` G710 | 1 | **True positive, fixed.** See below. |
| `staticcheck` SA1019 | 6 | Go 1.26 deprecated `ecdsa.PublicKey.X/Y`
and `PrivateKey.D`. Annotated with the same targeted `nolint` +
rationale already used for `ScalarBaseMult` in
`cmd/publisher/auth/common.go`. |

### The open redirect is real

`TrailingSlashMiddleware` copied the entire `*url.URL` before rewriting
the path. For an absolute-form request URI — legal for a Go HTTP server
to parse, e.g. `GET http://evil.com/foo/ HTTP/1.1` — `r.URL.Scheme` and
`r.URL.Host` are populated, and they were echoed straight back in the
`Location` header. The redirect target is now built from the cleaned
path and query alone. The existing `path.Clean` hardening for
GHSA-v8vw-gw5j-w7m6 (protocol-relative `//evil.com/`) is unchanged.

### Also

Switched `gomodguard` → `gomodguard_v2`; the former is deprecated as of
v2.12.0 and was emitting a warning on every run.

## Verification

- `golangci-lint v2.13.1` against this tree: **0 issues**, no
deprecation warnings
- `make validate`: all validations passed
- `go build ./...` and tests for every touched package pass (DB-backed
tests need Postgres; left to CI)

## Note on migrating the ecdsa key paths

Moving those six sites to `PublicKey.Bytes` /
`ParseUncompressedPublicKey` / `crypto/ecdh` touches key parsing and
signature verification. It should be its own reviewed PR rather than
riding along on a CI unblock. Happy to open one.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 00:14:13 +03:00

100 lines
4.1 KiB
Go

package v0
import (
"context"
"net/http"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/modelcontextprotocol/registry/internal/auth"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/service"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
)
// PublishServerInput represents the input for publishing a server
type PublishServerInput struct {
Authorization string `header:"Authorization" doc:"Registry JWT token (obtained from /v0/auth/token/github)" required:"true"`
Body apiv0.ServerJSON `body:""`
}
// RegisterPublishEndpoint registers the publish endpoint with a custom path prefix
func RegisterPublishEndpoint(api huma.API, pathPrefix string, registry service.RegistryService, cfg *config.Config) {
// Create JWT manager for token validation
jwtManager := auth.NewJWTManager(cfg)
huma.Register(api, huma.Operation{
OperationID: "publish-server" + strings.ReplaceAll(pathPrefix, "/", "-"),
Method: http.MethodPost,
Path: pathPrefix + "/publish",
Summary: "Publish MCP server",
Description: "Publish a new MCP server to the registry or update an existing one",
Tags: []string{"publish"},
Security: []map[string][]string{
{securitySchemeBearer: {}},
},
}, func(ctx context.Context, input *PublishServerInput) (*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)
}
// Verify that the token has permission to publish the server
if !jwtManager.HasPermission(input.Body.Name, auth.PermissionActionPublish, claims.Permissions) {
return nil, huma.Error403Forbidden(buildPermissionErrorMessage(input.Body.Name, claims.Permissions))
}
// Validate server JSON structure and schema (returns 422 on validation failure)
validationResult := validators.ValidateServerJSON(&input.Body, validators.ValidationSchemaVersionAndSemantic)
if !validationResult.Valid {
return nil, huma.Error422UnprocessableEntity("Failed to publish server, invalid schema: call /validate for details")
}
// Publish the server with extensions
publishedServer, err := registry.CreateServer(ctx, &input.Body)
if err != nil {
return nil, huma.Error400BadRequest("Failed to publish server", err)
}
// Return the published server response with metadata
return &Response[apiv0.ServerResponse]{
Body: *publishedServer,
}, nil
})
}
// buildPermissionErrorMessage creates a detailed error message showing what permissions
// the user has and what they're trying to publish
func buildPermissionErrorMessage(attemptedResource string, permissions []auth.Permission) string {
var permissionStrs []string
for _, perm := range permissions {
if perm.Action == auth.PermissionActionPublish {
permissionStrs = append(permissionStrs, perm.ResourcePattern)
}
}
errorMsg := "You do not have permission to publish this server"
if len(permissionStrs) > 0 {
errorMsg += ". You have permission to publish: " + strings.Join(permissionStrs, ", ")
} else {
errorMsg += ". You do not have any publish permissions"
}
errorMsg += ". Attempting to publish: " + attemptedResource
// Add helpful hint for GitHub organization publishing issues
if strings.HasPrefix(attemptedResource, "io.github.") {
errorMsg += ". If you're trying to publish to a GitHub organization, you may need to make your organization membership public in your GitHub settings: https://docs.github.com/en/account-and-profile/how-tos/organization-membership/publicizing-or-hiding-organization-membership"
}
return errorMsg
}