-
Notifications
You must be signed in to change notification settings - Fork 648
Share more code between DNS and HTTP auth flows #552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
domdomegg
merged 7 commits into
modelcontextprotocol:main
from
joelverhagen:joelverhagen/refactor
Sep 29, 2025
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
20b8392
Refactor
joelverhagen ecfb4c1
Polish
joelverhagen 910fa32
Improve tests
joelverhagen 130d510
Fix lint issue
joelverhagen cfb4717
Merge remote-tracking branch 'origin/main' into joelverhagen/refactor
joelverhagen d66b79b
Address comments
joelverhagen 3e83cc8
Fix lint issue
joelverhagen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/ed25519" | ||
| "encoding/base64" | ||
| "encoding/hex" | ||
| "fmt" | ||
| "regexp" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/modelcontextprotocol/registry/internal/auth" | ||
| "github.com/modelcontextprotocol/registry/internal/config" | ||
| ) | ||
|
|
||
| // CoreTokenExchangeInput represents the common input structure for token exchange | ||
| type CoreTokenExchangeInput 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"` | ||
| } | ||
|
|
||
| // CoreAuthHandler represents the common handler structure | ||
| type CoreAuthHandler struct { | ||
| config *config.Config | ||
| jwtManager *auth.JWTManager | ||
| } | ||
|
|
||
| // NewCoreAuthHandler creates a new core authentication handler | ||
| func NewCoreAuthHandler(cfg *config.Config) *CoreAuthHandler { | ||
| return &CoreAuthHandler{ | ||
| config: cfg, | ||
| jwtManager: auth.NewJWTManager(cfg), | ||
| } | ||
| } | ||
|
|
||
| // ValidateDomainAndTimestamp validates the domain format and timestamp | ||
| func ValidateDomainAndTimestamp(domain, timestamp string) (*time.Time, error) { | ||
| if !IsValidDomain(domain) { | ||
| return nil, fmt.Errorf("invalid domain format") | ||
| } | ||
|
|
||
| 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, to allow for clock skew | ||
| 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)") | ||
| } | ||
|
|
||
| return &ts, nil | ||
| } | ||
|
|
||
| func DecodeAndValidateSignature(signedTimestamp string) ([]byte, error) { | ||
| 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)) | ||
| } | ||
|
|
||
| return signature, nil | ||
| } | ||
|
|
||
| func VerifySignatureWithKeys(publicKeys []ed25519.PublicKey, messageBytes []byte, signature []byte) bool { | ||
| for _, publicKey := range publicKeys { | ||
| if ed25519.Verify(publicKey, messageBytes, signature) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // BuildPermissions builds permissions for a domain with optional subdomain support | ||
| func BuildPermissions(domain string, includeSubdomains bool) []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), | ||
| }, | ||
| } | ||
|
|
||
| if includeSubdomains { | ||
| // 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 | ||
| permissions = append(permissions, auth.Permission{ | ||
| Action: auth.PermissionActionPublish, | ||
| ResourcePattern: fmt.Sprintf("%s.*", reverseDomain), | ||
| }) | ||
| } | ||
|
|
||
| return permissions | ||
| } | ||
|
|
||
| // CreateJWTClaimsAndToken creates JWT claims and generates a token response | ||
| func (h *CoreAuthHandler) CreateJWTClaimsAndToken(ctx context.Context, authMethod auth.Method, domain string, permissions []auth.Permission) (*auth.TokenResponse, error) { | ||
| // Create JWT claims | ||
| jwtClaims := auth.JWTClaims{ | ||
| AuthMethod: authMethod, | ||
| 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 | ||
| } | ||
|
|
||
| func ParseMCPKeysFromStrings(inputs []string) []ed25519.PublicKey { | ||
| var publicKeys []ed25519.PublicKey | ||
| mcpPattern := regexp.MustCompile(`v=MCPv1;\s*k=ed25519;\s*p=([A-Za-z0-9+/=]+)`) | ||
|
|
||
| for _, input := range inputs { | ||
| matches := mcpPattern.FindStringSubmatch(input) | ||
| 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 | ||
| } | ||
|
|
||
| // 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) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.