auth: Add DNS auth (#279)
Fixes #270 Closes #233 Adds support for DNS-based authentication for proving ownership of a particular domain. E.g. if you can add a TXT record to `anthropic.com`, you can publish anything at `com.anthropic/*` or `com.anthropic.*`. Notes: - Uses Ed25519 signatures with 15-second timestamp windows to prevent replay attacks - Supports multiple public keys in DNS TXT records for key rotation scenarios - Publisher CLI supports DNS auth via --dns-domain and --dns-private-key flags - Includes key generation commands in publisher README for easy setup ## Motivation and Context This implements DNS-based public/private key authentication to allow people to actually publish at their own domains. Currently, authentication requires GitHub accounts which limits publishing to the io.github.* namespace. DNS-based auth enables: - Publishing under your actual domain (e.g., com.anthropic/* for anthropic.com) - Independence from GitHub or other external auth providers - Organizations managing their own keys and access to publishing ## How Has This Been Tested? - Unit tests cover signature verification, DNS TXT parsing, timestamp validation, and error cases - Tested locally by editing my own DNS records - All existing auth methods covered by passing tests ## 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 - [x] I have added or updated documentation as needed ## Additional context Will be adding HTTP challenge auth in a similar way as a separate PR, e.g. for verifying you own `github.com` by hosting a `github.com/.well-known/mcp-server-challenge` or similar. Just mentioning this as we discussed HTTP challenges as closely related to DNS challenges elsewhere, and want to reassure reviewer that this hasn't been forgotten with this approach. :) Update: tracking the HTTP auth in https://github.com/modelcontextprotocol/registry/issues/280
This commit is contained in:
parent
6dad0e340a
commit
316cbb08ee
3 changed files with 604 additions and 4 deletions
228
internal/api/handlers/v0/auth/dns.go
Normal file
228
internal/api/handlers/v0/auth/dns.go
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
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/model"
|
||||
)
|
||||
|
||||
// DNSTokenExchangeInput represents the input for DNS-based authentication
|
||||
type DNSTokenExchangeInput 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"`
|
||||
}
|
||||
}
|
||||
|
||||
// DNSResolver defines the interface for DNS resolution
|
||||
type DNSResolver interface {
|
||||
LookupTXT(ctx context.Context, name string) ([]string, error)
|
||||
}
|
||||
|
||||
// DefaultDNSResolver uses Go's standard DNS resolution
|
||||
type DefaultDNSResolver struct{}
|
||||
|
||||
// LookupTXT performs DNS TXT record lookup
|
||||
func (r *DefaultDNSResolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
|
||||
return (&net.Resolver{}).LookupTXT(ctx, name)
|
||||
}
|
||||
|
||||
// DNSAuthHandler handles DNS-based authentication
|
||||
type DNSAuthHandler struct {
|
||||
config *config.Config
|
||||
jwtManager *auth.JWTManager
|
||||
resolver DNSResolver
|
||||
}
|
||||
|
||||
// NewDNSAuthHandler creates a new DNS authentication handler
|
||||
func NewDNSAuthHandler(cfg *config.Config) *DNSAuthHandler {
|
||||
return &DNSAuthHandler{
|
||||
config: cfg,
|
||||
jwtManager: auth.NewJWTManager(cfg),
|
||||
resolver: &DefaultDNSResolver{},
|
||||
}
|
||||
}
|
||||
|
||||
// SetResolver sets a custom DNS resolver (used for testing)
|
||||
func (h *DNSAuthHandler) SetResolver(resolver DNSResolver) {
|
||||
h.resolver = resolver
|
||||
}
|
||||
|
||||
// RegisterDNSEndpoint registers the DNS authentication endpoint
|
||||
func RegisterDNSEndpoint(api huma.API, cfg *config.Config) {
|
||||
handler := NewDNSAuthHandler(cfg)
|
||||
|
||||
// DNS authentication endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "exchange-dns-token",
|
||||
Method: http.MethodPost,
|
||||
Path: "/v0/auth/dns",
|
||||
Summary: "Exchange DNS signature for Registry JWT",
|
||||
Description: "Authenticate using DNS TXT record public key and signed timestamp",
|
||||
Tags: []string{"auth"},
|
||||
}, func(ctx context.Context, input *DNSTokenExchangeInput) (*v0.Response[auth.TokenResponse], error) {
|
||||
response, err := handler.ExchangeToken(ctx, input.Body.Domain, input.Body.Timestamp, input.Body.SignedTimestamp)
|
||||
if err != nil {
|
||||
return nil, huma.Error401Unauthorized("DNS authentication failed", err)
|
||||
}
|
||||
|
||||
return &v0.Response[auth.TokenResponse]{
|
||||
Body: *response,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExchangeToken exchanges DNS signature for a Registry JWT token
|
||||
func (h *DNSAuthHandler) ExchangeToken(ctx context.Context, domain, timestamp, signedTimestamp string) (*auth.TokenResponse, error) {
|
||||
// Validate domain format
|
||||
if !isValidDomain(domain) {
|
||||
return nil, fmt.Errorf("invalid domain format")
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
// Lookup DNS TXT records
|
||||
txtRecords, err := h.resolver.LookupTXT(ctx, domain)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to lookup DNS TXT records: %w", err)
|
||||
}
|
||||
|
||||
// Parse public keys from TXT records
|
||||
publicKeys := h.parsePublicKeysFromTXT(txtRecords)
|
||||
|
||||
if len(publicKeys) == 0 {
|
||||
return nil, fmt.Errorf("no valid MCP public keys found in DNS TXT records")
|
||||
}
|
||||
|
||||
// Verify signature with any of the public keys
|
||||
messageBytes := []byte(timestamp)
|
||||
signatureValid := false
|
||||
for _, publicKey := range publicKeys {
|
||||
if ed25519.Verify(publicKey, messageBytes, signature) {
|
||||
signatureValid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !signatureValid {
|
||||
return nil, fmt.Errorf("signature verification failed")
|
||||
}
|
||||
|
||||
// Build permissions for domain and subdomains
|
||||
permissions := h.buildPermissions(domain)
|
||||
|
||||
// Create JWT claims
|
||||
jwtClaims := auth.JWTClaims{
|
||||
AuthMethod: model.AuthMethodDNS,
|
||||
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
|
||||
}
|
||||
|
||||
// parsePublicKeysFromTXT parses Ed25519 public keys from DNS TXT records
|
||||
func (h *DNSAuthHandler) parsePublicKeysFromTXT(txtRecords []string) []ed25519.PublicKey {
|
||||
var publicKeys []ed25519.PublicKey
|
||||
mcpPattern := regexp.MustCompile(`v=MCPv1;\s*k=ed25519;\s*p=([A-Za-z0-9+/=]+)`)
|
||||
|
||||
for _, record := range txtRecords {
|
||||
matches := mcpPattern.FindStringSubmatch(record)
|
||||
if len(matches) == 2 {
|
||||
// Decode base64 public key
|
||||
publicKeyBytes, err := base64.StdEncoding.DecodeString(matches[1])
|
||||
if err != nil {
|
||||
continue // Skip invalid keys
|
||||
}
|
||||
|
||||
if len(publicKeyBytes) != ed25519.PublicKeySize {
|
||||
continue // Skip invalid key sizes
|
||||
}
|
||||
|
||||
publicKeys = append(publicKeys, ed25519.PublicKey(publicKeyBytes))
|
||||
}
|
||||
}
|
||||
|
||||
return publicKeys
|
||||
}
|
||||
|
||||
// buildPermissions builds permissions for a domain and its subdomains using reverse DNS notation
|
||||
func (h *DNSAuthHandler) 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),
|
||||
},
|
||||
// DNS implies a hierarchy where subdomains are treated as part of the parent domain,
|
||||
// therefore we grant permissions for all subdomains (e.g., com.example.*)
|
||||
// This is in line with other DNS-based authentication methods e.g. ACME DNS-01 challenges
|
||||
{
|
||||
Action: auth.PermissionActionPublish,
|
||||
ResourcePattern: fmt.Sprintf("%s.*", reverseDomain),
|
||||
},
|
||||
}
|
||||
|
||||
return permissions
|
||||
}
|
||||
|
||||
// reverseString reverses a domain string (example.com -> com.example)
|
||||
func reverseString(domain string) string {
|
||||
parts := strings.Split(domain, ".")
|
||||
for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
|
||||
parts[i], parts[j] = parts[j], parts[i]
|
||||
}
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func isValidDomain(domain string) bool {
|
||||
if len(domain) == 0 || len(domain) > 253 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for valid characters and structure
|
||||
domainPattern := regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$`)
|
||||
return domainPattern.MatchString(domain)
|
||||
}
|
||||
197
internal/api/handlers/v0/auth/dns_test.go
Normal file
197
internal/api/handlers/v0/auth/dns_test.go
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/api/handlers/v0/auth"
|
||||
intauth "github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/model"
|
||||
)
|
||||
|
||||
// MockDNSResolver for testing
|
||||
type MockDNSResolver struct {
|
||||
txtRecords map[string][]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *MockDNSResolver) LookupTXT(_ context.Context, name string) ([]string, error) {
|
||||
if m.err != nil {
|
||||
return nil, m.err
|
||||
}
|
||||
return m.txtRecords[name], nil
|
||||
}
|
||||
|
||||
func TestDNSAuthHandler_ExchangeToken(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
}
|
||||
handler := auth.NewDNSAuthHandler(cfg)
|
||||
|
||||
// Generate a test key pair
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create mock DNS resolver
|
||||
publicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)
|
||||
mockResolver := &MockDNSResolver{
|
||||
txtRecords: map[string][]string{
|
||||
"example.com": {
|
||||
fmt.Sprintf("v=MCPv1; k=ed25519; p=%s", publicKeyB64),
|
||||
},
|
||||
},
|
||||
}
|
||||
handler.SetResolver(mockResolver)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
domain string
|
||||
timestamp string
|
||||
signedTimestamp string
|
||||
setupMock func(*MockDNSResolver)
|
||||
expectError bool
|
||||
errorContains string
|
||||
}{
|
||||
{
|
||||
name: "successful authentication",
|
||||
domain: "example.com",
|
||||
timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
setupMock: func(_ *MockDNSResolver) {
|
||||
// Mock is already set up with valid key
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "multiple keys",
|
||||
domain: "example.com",
|
||||
timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
setupMock: func(m *MockDNSResolver) {
|
||||
publicKey, _, err := ed25519.GenerateKey(nil)
|
||||
require.NoError(t, err)
|
||||
otherPublicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)
|
||||
|
||||
m.txtRecords["example.com"] = []string{
|
||||
fmt.Sprintf("v=MCPv1; k=ed25519; p=%s", "someNonsense"),
|
||||
fmt.Sprintf("v=MCPv1; k=ed25519; p=%s", publicKeyB64),
|
||||
fmt.Sprintf("v=MCPv1; k=ed25519; p=%s", otherPublicKeyB64),
|
||||
}
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "invalid domain format",
|
||||
domain: "invalid..domain",
|
||||
timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
expectError: true,
|
||||
errorContains: "invalid domain format",
|
||||
},
|
||||
{
|
||||
name: "timestamp too old",
|
||||
domain: "example.com",
|
||||
timestamp: time.Now().Add(-30 * time.Second).UTC().Format(time.RFC3339),
|
||||
expectError: true,
|
||||
errorContains: "timestamp outside valid window",
|
||||
},
|
||||
{
|
||||
name: "timestamp too far in the future",
|
||||
domain: "example.com",
|
||||
timestamp: time.Now().Add(30 * time.Second).UTC().Format(time.RFC3339),
|
||||
expectError: true,
|
||||
errorContains: "timestamp outside valid window",
|
||||
},
|
||||
{
|
||||
name: "DNS lookup failure",
|
||||
domain: "nonexistent.com",
|
||||
timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
setupMock: func(m *MockDNSResolver) {
|
||||
m.err = fmt.Errorf("DNS lookup failed")
|
||||
},
|
||||
expectError: true,
|
||||
errorContains: "failed to lookup DNS TXT records",
|
||||
},
|
||||
{
|
||||
name: "no MCP TXT records",
|
||||
domain: "nokeys.com",
|
||||
timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
setupMock: func(m *MockDNSResolver) {
|
||||
m.txtRecords["nokeys.com"] = []string{"v=spf1 include:_spf.google.com ~all"}
|
||||
m.err = nil
|
||||
},
|
||||
expectError: true,
|
||||
errorContains: "no valid MCP public keys found",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset mock resolver
|
||||
mockResolver.err = nil
|
||||
if tt.setupMock != nil {
|
||||
tt.setupMock(mockResolver)
|
||||
}
|
||||
|
||||
// Generate signature if not provided
|
||||
signedTimestamp := tt.signedTimestamp
|
||||
if signedTimestamp == "" && !tt.expectError {
|
||||
signature := ed25519.Sign(privateKey, []byte(tt.timestamp))
|
||||
signedTimestamp = hex.EncodeToString(signature)
|
||||
} else if signedTimestamp == "" {
|
||||
// For error cases, generate a valid signature unless we're testing signature format
|
||||
if !strings.Contains(tt.errorContains, "signature") {
|
||||
signature := ed25519.Sign(privateKey, []byte(tt.timestamp))
|
||||
signedTimestamp = hex.EncodeToString(signature)
|
||||
} else {
|
||||
signedTimestamp = "invalid"
|
||||
}
|
||||
}
|
||||
|
||||
// Call the handler
|
||||
result, err := handler.ExchangeToken(context.Background(), tt.domain, tt.timestamp, signedTimestamp)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorContains != "" {
|
||||
assert.Contains(t, err.Error(), tt.errorContains)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.NotEmpty(t, result.RegistryToken)
|
||||
|
||||
// Verify the token contains expected claims
|
||||
jwtManager := intauth.NewJWTManager(cfg)
|
||||
claims, err := jwtManager.ValidateToken(context.Background(), result.RegistryToken)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, model.AuthMethodDNS, claims.AuthMethod)
|
||||
assert.Equal(t, tt.domain, claims.AuthMethodSubject)
|
||||
assert.Len(t, claims.Permissions, 2) // domain and subdomain permissions
|
||||
|
||||
// Check permissions use reverse DNS patterns
|
||||
patterns := make([]string, len(claims.Permissions))
|
||||
for i, perm := range claims.Permissions {
|
||||
patterns[i] = perm.ResourcePattern
|
||||
}
|
||||
// Convert domain to reverse DNS for expected patterns
|
||||
parts := strings.Split(tt.domain, ".")
|
||||
for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
|
||||
parts[i], parts[j] = parts[j], parts[i]
|
||||
}
|
||||
reverseDomain := strings.Join(parts, ".")
|
||||
assert.Contains(t, patterns, fmt.Sprintf("%s/*", reverseDomain))
|
||||
assert.Contains(t, patterns, fmt.Sprintf("%s.*", reverseDomain))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -13,6 +13,9 @@ func RegisterAuthEndpoints(api huma.API, cfg *config.Config) {
|
|||
// Register GitHub OIDC authentication endpoint
|
||||
RegisterGitHubOIDCEndpoint(api, cfg)
|
||||
|
||||
// Register DNS-based authentication endpoint
|
||||
RegisterDNSEndpoint(api, cfg)
|
||||
|
||||
// Register anonymous authentication endpoint
|
||||
RegisterNoneEndpoint(api, cfg)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue