Share more code between DNS and HTTP auth flows (#552)

<!-- Provide a brief summary of your changes -->

## Motivation and Context

Currently the `dns` and `http` based auth flows share code well in the
publisher tool. However there is a lot of duplication in the auth
endpoint. This on it's own is not a problem but it does make
enhancements to the proof record (the `v=MCPv1; ...` string) harder to
keep in sync.

This PR adds a `common.go` file to share logic between the two.

This supports work I am prototyping for
https://github.com/modelcontextprotocol/registry/issues/482.

## How Has This Been Tested?

Added new test cases for the permissions. Ran them before and after the
refactoring to ensure no behavior change.
Ran existing UTs.
Ran the integration tests.
Manually exercised the flows locally.

## Breaking Changes

None.

## Types of changes
<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [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
- [ ] I have added or updated documentation as needed

## Additional context
<!-- Add any other context, implementation notes, or design decisions
-->
This commit is contained in:
Joel Verhagen 2025-09-29 18:43:27 -04:00 • committed by GitHub
commit df018fc43b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -2,13 +2,9 @@ package auth
import (
"context"
"crypto/ed25519"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"time"
@ -23,11 +19,7 @@ const MaxKeyResponseSize = 4096
// HTTPTokenExchangeInput represents the input for HTTP-based authentication
type HTTPTokenExchangeInput struct {
Body struct {
Domain string `json:"domain" doc:"Domain name" example:"example.com" required:"true"`
Timestamp string `json:"timestamp" doc:"RFC3339 timestamp" example:"2023-01-01T00:00:00Z" required:"true"`
SignedTimestamp string `json:"signed_timestamp" doc:"Hex-encoded Ed25519 signature of timestamp" example:"abcdef1234567890" required:"true"`
}
Body SignatureTokenExchangeInput
}
// HTTPKeyFetcher defines the interface for fetching HTTP keys
@ -98,17 +90,15 @@ func (f *DefaultHTTPKeyFetcher) FetchKey(ctx context.Context, domain string) (st
// HTTPAuthHandler handles HTTP-based authentication
type HTTPAuthHandler struct {
config *config.Config
jwtManager *auth.JWTManager
fetcher HTTPKeyFetcher
CoreAuthHandler
fetcher HTTPKeyFetcher
}
// NewHTTPAuthHandler creates a new HTTP authentication handler
func NewHTTPAuthHandler(cfg *config.Config) *HTTPAuthHandler {
return &HTTPAuthHandler{
config: cfg,
jwtManager: auth.NewJWTManager(cfg),
fetcher: NewDefaultHTTPKeyFetcher(),
CoreAuthHandler: *NewCoreAuthHandler(cfg),
fetcher: NewDefaultHTTPKeyFetcher(),
}
}
@ -143,107 +133,14 @@ func RegisterHTTPEndpoint(api huma.API, cfg *config.Config) {
// ExchangeToken exchanges HTTP signature for a Registry JWT token
func (h *HTTPAuthHandler) ExchangeToken(ctx context.Context, domain, timestamp, signedTimestamp string) (*auth.TokenResponse, error) {
// Validate domain format
if !isValidDomain(domain) {
return nil, fmt.Errorf("invalid domain format")
keyFetcher := func(ctx context.Context, domain string) ([]string, error) {
keyResponse, err := h.fetcher.FetchKey(ctx, domain)
if err != nil {
return nil, fmt.Errorf("failed to fetch public key: %w", err)
}
return []string{keyResponse}, nil
}
// Parse and validate timestamp
ts, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
return nil, fmt.Errorf("invalid timestamp format: %w", err)
}
// Check timestamp is within 15 seconds
now := time.Now()
if ts.Before(now.Add(-15*time.Second)) || ts.After(now.Add(15*time.Second)) {
return nil, fmt.Errorf("timestamp outside valid window (±15 seconds)")
}
// Decode signature
signature, err := hex.DecodeString(signedTimestamp)
if err != nil {
return nil, fmt.Errorf("invalid signature format, must be hex: %w", err)
}
if len(signature) != ed25519.SignatureSize {
return nil, fmt.Errorf("invalid signature length: expected %d, got %d", ed25519.SignatureSize, len(signature))
}
// Fetch public key from HTTP endpoint
keyResponse, err := h.fetcher.FetchKey(ctx, domain)
if err != nil {
return nil, fmt.Errorf("failed to fetch public key: %w", err)
}
// Parse public key from HTTP response
publicKey, err := h.parsePublicKeyFromHTTP(keyResponse)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
// Verify signature
messageBytes := []byte(timestamp)
if !ed25519.Verify(publicKey, messageBytes, signature) {
return nil, fmt.Errorf("signature verification failed")
}
// Build permissions for domain and subdomains
permissions := h.buildPermissions(domain)
// Create JWT claims
jwtClaims := auth.JWTClaims{
AuthMethod: auth.MethodHTTP,
AuthMethodSubject: domain,
Permissions: permissions,
}
// Generate Registry JWT token
tokenResponse, err := h.jwtManager.GenerateTokenResponse(ctx, jwtClaims)
if err != nil {
return nil, fmt.Errorf("failed to generate JWT token: %w", err)
}
return tokenResponse, nil
}
// parsePublicKeyFromHTTP parses Ed25519 public key from HTTP response
func (h *HTTPAuthHandler) parsePublicKeyFromHTTP(response string) (ed25519.PublicKey, error) {
// Expected format: v=MCPv1; k=ed25519; p=<base64-encoded-key>
mcpPattern := regexp.MustCompile(`v=MCPv1;\s*k=ed25519;\s*p=([A-Za-z0-9+/=]+)`)
matches := mcpPattern.FindStringSubmatch(response)
if len(matches) != 2 {
return nil, fmt.Errorf("invalid key format, expected: v=MCPv1; k=ed25519; p=<base64-key>")
}
// Decode base64 public key
publicKeyBytes, err := base64.StdEncoding.DecodeString(matches[1])
if err != nil {
return nil, fmt.Errorf("failed to decode base64 public key: %w", err)
}
if len(publicKeyBytes) != ed25519.PublicKeySize {
return nil, fmt.Errorf("invalid public key length: expected %d, got %d", ed25519.PublicKeySize, len(publicKeyBytes))
}
return ed25519.PublicKey(publicKeyBytes), nil
}
// buildPermissions builds permissions for a domain and its subdomains using reverse DNS notation
func (h *HTTPAuthHandler) buildPermissions(domain string) []auth.Permission {
reverseDomain := reverseString(domain)
permissions := []auth.Permission{
// Grant permissions for the exact domain (e.g., com.example/*)
{
Action: auth.PermissionActionPublish,
ResourcePattern: fmt.Sprintf("%s/*", reverseDomain),
},
// HTTP does not imply a hierarchy of ownership of subdomains, unlike DNS
// Therefore this does not give permissions for subdomains
// This is consistent with similar protocols, e.g. ACME HTTP-01
}
return permissions
allowSubdomains := false
return h.CoreAuthHandler.ExchangeToken(ctx, domain, timestamp, signedTimestamp, keyFetcher, allowSubdomains, auth.MethodHTTP)
}