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
7 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)
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ const (
|
|||
AuthMethodGitHubAT AuthMethod = "github-at"
|
||||
// GitHub Actions OIDC authentication
|
||||
AuthMethodGitHubOIDC AuthMethod = "github-oidc"
|
||||
// DNS-based public/private key authentication
|
||||
AuthMethodDNS AuthMethod = "dns"
|
||||
// No authentication - should only be used for local development and testing
|
||||
AuthMethodNone AuthMethod = "none"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -48,7 +48,10 @@ The tool supports two main commands:
|
|||
- `--auth-method`: Authentication method to use (default: github-at)
|
||||
- `github-at`: Interactive GitHub OAuth device flow authentication
|
||||
- `github-oidc`: GitHub Actions OIDC authentication (for CI/CD)
|
||||
- `dns`: DNS-based public/private key authentication
|
||||
- `none`: No authentication (for registry contributors testing locally)
|
||||
- `--dns-domain`: Domain name for DNS authentication (required for dns auth method)
|
||||
- `--dns-private-key`: 64-character hex seed for DNS authentication (required for dns auth method)
|
||||
|
||||
## Creating a server.json file
|
||||
|
||||
|
|
@ -182,6 +185,31 @@ jobs:
|
|||
--auth-method github-oidc
|
||||
```
|
||||
|
||||
### DNS Authentication (`dns`)
|
||||
|
||||
For domain-based authentication using public/private key cryptography:
|
||||
|
||||
1. **Generate Ed25519 keypair**:
|
||||
```bash
|
||||
openssl genpkey -algorithm Ed25519 -out /tmp/key.pem && \
|
||||
echo "\n\nDNS record to add to your domain:" && \
|
||||
echo " Type: TXT" && \
|
||||
echo " Value: v=MCPv1; k=ed25519; p=$(openssl pkey -in /tmp/key.pem -pubout -outform DER | tail -c 32 | base64)" && \
|
||||
echo "" && \
|
||||
echo "Private key for --dns-private-key flag:" && \
|
||||
echo " $(openssl pkey -in /tmp/key.pem -noout -text | grep -A3 "priv:" | tail -n +2 | tr -d ' :\n')\n" && \
|
||||
rm /tmp/key.pem
|
||||
```
|
||||
2. **Add DNS TXT record**: Add a TXT record to your domain with format: `v=MCPv1; k=ed25519; p=<base64-public-key>`
|
||||
3. **Use CLI arguments**: Provide domain and private key via command line flags
|
||||
|
||||
```bash
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE> \
|
||||
--auth-method dns --dns-domain example.com --dns-private-key abc123...
|
||||
```
|
||||
|
||||
This grants publishing permissions for both `example.com/*` and `*.example.com/*` namespaces.
|
||||
|
||||
### No Authentication (`none`)
|
||||
|
||||
Mainly for registry contributors, for testing locally:
|
||||
|
|
|
|||
133
tools/publisher/auth/dns.go
Normal file
133
tools/publisher/auth/dns.go
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DNSProvider struct {
|
||||
registryURL string
|
||||
domain string
|
||||
hexSeed string
|
||||
}
|
||||
|
||||
//nolint:ireturn
|
||||
func NewDNSProvider(registryURL, domain, hexSeed string) Provider {
|
||||
return &DNSProvider{
|
||||
registryURL: registryURL,
|
||||
domain: domain,
|
||||
hexSeed: hexSeed,
|
||||
}
|
||||
}
|
||||
|
||||
// GetToken retrieves the registry JWT token using DNS authentication
|
||||
func (d *DNSProvider) GetToken(ctx context.Context) (string, error) {
|
||||
if d.domain == "" {
|
||||
return "", fmt.Errorf("DNS domain is required")
|
||||
}
|
||||
|
||||
if d.hexSeed == "" {
|
||||
return "", fmt.Errorf("DNS private key (hex seed) is required")
|
||||
}
|
||||
|
||||
// Decode hex seed to private key
|
||||
seedBytes, err := hex.DecodeString(d.hexSeed)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid hex seed format: %w", err)
|
||||
}
|
||||
|
||||
if len(seedBytes) != ed25519.SeedSize {
|
||||
return "", fmt.Errorf("invalid seed length: expected %d bytes, got %d", ed25519.SeedSize, len(seedBytes))
|
||||
}
|
||||
|
||||
privateKey := ed25519.NewKeyFromSeed(seedBytes)
|
||||
|
||||
// Generate current timestamp
|
||||
timestamp := time.Now().UTC().Format(time.RFC3339)
|
||||
|
||||
// Sign the timestamp
|
||||
signature := ed25519.Sign(privateKey, []byte(timestamp))
|
||||
signedTimestamp := hex.EncodeToString(signature)
|
||||
|
||||
// Exchange signature for registry token
|
||||
registryToken, err := d.exchangeDNSTokenForRegistry(ctx, d.domain, timestamp, signedTimestamp)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to exchange DNS signature: %w", err)
|
||||
}
|
||||
|
||||
return registryToken, nil
|
||||
}
|
||||
|
||||
// NeedsLogin always returns false for DNS since no interactive login is needed
|
||||
func (d *DNSProvider) NeedsLogin() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Login is not needed for DNS since authentication is cryptographic
|
||||
func (d *DNSProvider) Login(_ context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Name returns the name of this auth provider
|
||||
func (d *DNSProvider) Name() string {
|
||||
return "dns"
|
||||
}
|
||||
|
||||
// exchangeDNSTokenForRegistry exchanges DNS signature for a registry JWT token
|
||||
func (d *DNSProvider) exchangeDNSTokenForRegistry(ctx context.Context, domain, timestamp, signedTimestamp string) (string, error) {
|
||||
if d.registryURL == "" {
|
||||
return "", fmt.Errorf("registry URL is required for token exchange")
|
||||
}
|
||||
|
||||
// Prepare the request body
|
||||
payload := map[string]string{
|
||||
"domain": domain,
|
||||
"timestamp": timestamp,
|
||||
"signed_timestamp": signedTimestamp,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
// Make the token exchange request
|
||||
exchangeURL := d.registryURL + "/v0/auth/dns"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, exchangeURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var tokenResp RegistryTokenResponse
|
||||
err = json.Unmarshal(body, &tokenResp)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
return tokenResp.RegistryToken, nil
|
||||
}
|
||||
|
|
@ -97,12 +97,16 @@ func publishCommand() error {
|
|||
var mcpFilePath string
|
||||
var forceLogin bool
|
||||
var authMethod string
|
||||
var dnsDomain string
|
||||
var dnsPrivateKey string
|
||||
|
||||
// Command-line flags for configuration
|
||||
publishFlags.StringVar(®istryURL, "registry-url", "", "URL of the registry (required)")
|
||||
publishFlags.StringVar(&mcpFilePath, "mcp-file", "", "path to the MCP file (required)")
|
||||
publishFlags.BoolVar(&forceLogin, "login", false, "force a new login even if a token exists")
|
||||
publishFlags.StringVar(&authMethod, "auth-method", "github-at", "authentication method (default: github-at)")
|
||||
publishFlags.StringVar(&dnsDomain, "dns-domain", "", "domain name for DNS authentication (required for dns auth method)")
|
||||
publishFlags.StringVar(&dnsPrivateKey, "dns-private-key", "", "64-character hex seed for DNS authentication (required for dns auth method)")
|
||||
|
||||
// Set custom usage function
|
||||
publishFlags.Usage = func() {
|
||||
|
|
@ -111,10 +115,12 @@ func publishCommand() error {
|
|||
fmt.Fprint(os.Stdout, "Publish a server.json file to the registry\n")
|
||||
fmt.Fprint(os.Stdout, "\n")
|
||||
fmt.Fprint(os.Stdout, "Flags:\n")
|
||||
fmt.Fprint(os.Stdout, " --registry-url string URL of the registry (required)\n")
|
||||
fmt.Fprint(os.Stdout, " --mcp-file string path to the MCP file (required)\n")
|
||||
fmt.Fprint(os.Stdout, " --login force a new login even if a token exists\n")
|
||||
fmt.Fprint(os.Stdout, " --auth-method string authentication method (default: github-at)\n")
|
||||
fmt.Fprint(os.Stdout, " --registry-url string URL of the registry (required)\n")
|
||||
fmt.Fprint(os.Stdout, " --mcp-file string path to the MCP file (required)\n")
|
||||
fmt.Fprint(os.Stdout, " --login force a new login even if a token exists\n")
|
||||
fmt.Fprint(os.Stdout, " --auth-method string authentication method (default: github-at)\n")
|
||||
fmt.Fprint(os.Stdout, " --dns-domain string domain name for DNS authentication\n")
|
||||
fmt.Fprint(os.Stdout, " --dns-private-key string 64-character hex seed for DNS authentication\n")
|
||||
}
|
||||
|
||||
if err := publishFlags.Parse(os.Args[2:]); err != nil {
|
||||
|
|
@ -140,6 +146,9 @@ func publishCommand() error {
|
|||
case "github-oidc":
|
||||
log.Println("Using GitHub Actions OIDC for authentication")
|
||||
authProvider = auth.NewGitHubOIDCProvider(registryURL)
|
||||
case "dns":
|
||||
log.Println("Using DNS-based authentication")
|
||||
authProvider = auth.NewDNSProvider(registryURL, dnsDomain, dnsPrivateKey)
|
||||
case "none":
|
||||
log.Println("Using anonymous authentication")
|
||||
authProvider = auth.NewNoneProvider(registryURL)
|
||||
|
|
|
|||
Loading…
Reference in a new issue