<!-- Provide a brief summary of your changes --> ## Motivation and Context <!-- Why is this change needed? What problem does it solve? --> The following PR eliminates duplicate struct definitions by migrating the publisher tool to use canonical types from pkg/model, creating a single source of truth across the codebase. The publisher tool previously had its own copies of structs that were duplicated, ie. ServerJSON, Package, Repository, VersionDetail, EnvironmentVariable, RuntimeArgument and a few others which was not optimal **Changes in the PR:** - Refactored the structs to single canonical types located at pkg/model - Refactor the implementation to use/build canonical structures directly - Remove all duplicate definitions (5 structs eliminated) - Publisher now uses model.ServerJSON, model.Package, model.Repository, etc. - Renamed some of the structs to better reflect their use case, i.e. ServerJSON instead of ServerDetail - Fixes an issue where the Remote property was missing from the previous publisher copy of the Server **Benefits:** - Single source of truth - Schema changes in one place - Type safety - Compiler catches mismatches - Enhanced validation - Field constraints and bson tags - Zero breaking changes - Same CLI interface and JSON output - Future-proof - New canonical fields automatically available Supersedes: #217 and #240 ## How Has This Been Tested? <!-- Have you tested this in a real application? Which scenarios were tested? --> Locally ## Breaking Changes <!-- Will users need to update their code or configurations? --> No ## Types of changes <!-- What types of changes does your code introduce? Put an `x` in all the boxes that apply: --> - [x] Bug fix (non-breaking change which fixes an issue) - [ ] 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. --> - [ ] I have read the [MCP Documentation](https://modelcontextprotocol.io) - [ ] My code follows the repository's style guidelines - [ ] New and existing tests pass locally - [ ] 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 --> --------- Signed-off-by: Radoslav Dimitrov <radoslav@stacklok.com>
196 lines
5.8 KiB
Go
196 lines
5.8 KiB
Go
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"
|
|
)
|
|
|
|
// 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, intauth.MethodDNS, 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))
|
|
}
|
|
})
|
|
}
|
|
}
|