auth: Add GitHub OIDC auth (#278)
Adds support for auth'ing to the registry via [GitHub Actions OIDC](https://docs.github.com/en/actions/concepts/security/openid-connect). Fixes #271 ## Motivation and Context People will probably want to publish to the registry from CI environments. DNS auth can work here fine (https://github.com/modelcontextprotocol/registry/issues/270). But for people who haven't set up DNS, the standard GitHub device flow won't really work here. We could make this nice by supporting GitHub Actions OIDC. ## How Has This Been Tested? Tested locally with a real GitHub OIDC token from a personal repo. ## 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
This commit is contained in:
parent
e9fe6f9ab8
commit
12ab632d32
6 changed files with 802 additions and 193 deletions
|
|
@ -23,11 +23,14 @@ The tool supports two main commands:
|
|||
### Publishing a server
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
./bin/mcp-publisher publish -registry-url <REGISTRY_URL> -mcp-file <PATH_TO_MCP_FILE>
|
||||
# Basic usage with GitHub OAuth (interactive authentication)
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE>
|
||||
|
||||
# Use GitHub Actions OIDC (for CI/CD pipelines)
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE> --auth-method github-oidc
|
||||
|
||||
# Force a new login even if a token exists
|
||||
./bin/mcp-publisher publish -registry-url <REGISTRY_URL> -mcp-file <PATH_TO_MCP_FILE> -login
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE> --login
|
||||
```
|
||||
|
||||
### Creating a server.json file
|
||||
|
|
@ -39,10 +42,13 @@ The tool supports two main commands:
|
|||
|
||||
### Command-line Arguments
|
||||
|
||||
- `-registry-url`: URL of the MCP registry (required)
|
||||
- `-mcp-file`: Path to the MCP configuration file (required)
|
||||
- `-login`: Force a new GitHub authentication even if a token already exists (overwrites existing token file)
|
||||
- `-auth-method`: Authentication method to use (default: github)
|
||||
- `--registry-url`: URL of the MCP registry (required)
|
||||
- `--mcp-file`: Path to the MCP configuration file (required)
|
||||
- `--login`: Force a new GitHub authentication even if a token already exists (overwrites existing token file)
|
||||
- `--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)
|
||||
- `none`: No authentication (for registry contributors testing locally)
|
||||
|
||||
## Creating a server.json file
|
||||
|
||||
|
|
@ -127,28 +133,59 @@ After creation, you may need to manually edit the file to:
|
|||
|
||||
## Authentication
|
||||
|
||||
The tool has been simplified to use **GitHub OAuth device flow authentication exclusively**. Previous versions supported multiple authentication methods, but this version focuses solely on GitHub OAuth for better security and user experience.
|
||||
The tool supports multiple authentication methods to accommodate different use cases:
|
||||
|
||||
### GitHub OAuth Device Flow (`github-at`) - Default
|
||||
|
||||
For interactive use:
|
||||
|
||||
1. **Automatic Setup**: The tool automatically retrieves the GitHub Client ID from the registry's health endpoint
|
||||
2. **First Run Authentication**: When first run (or with the `--login` flag), the tool initiates the GitHub device flow
|
||||
3. **User Authorization**: You'll be provided with a URL and a verification code to enter on GitHub
|
||||
4. **Token Storage**: After successful authentication, the tool saves the access token locally in `.mcpregistry_github_token` for future use
|
||||
5. **Token Exchange**: The GitHub token is exchanged for a short-lived registry token, which is saved locally in `.mcpregistry_registry_token`.
|
||||
5. **Secure Communication**: The registry token is sent in the HTTP Authorization header with the Bearer scheme for all registry API calls
|
||||
|
||||
**Note**: Authentication is performed via GitHub OAuth App, which you must authorize for the respective resources (e.g., organization access if publishing organization repositories).
|
||||
|
||||
## Publishing Example
|
||||
|
||||
To publish an existing server.json file to the registry:
|
||||
|
||||
1. Prepare your `server.json` file with your server details. See an example in [server.json](./server.json)
|
||||
2. Run the publisher tool:
|
||||
5. **Token Exchange**: The GitHub token is exchanged for a short-lived registry token, which is saved locally in `.mcpregistry_registry_token`
|
||||
6. **Secure Communication**: The registry token is sent in the HTTP Authorization header with the Bearer scheme for all registry API calls
|
||||
|
||||
```bash
|
||||
./bin/mcp-publisher publish --registry-url "https://mcp-registry.example.com" --mcp-file "./server.json"
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE> --auth-method github-at
|
||||
```
|
||||
|
||||
3. Follow the authentication instructions in the terminal if prompted.
|
||||
### GitHub Actions OIDC (`github-oidc`)
|
||||
|
||||
4. Upon successful publication, you'll see a confirmation message.
|
||||
For CI/CD pipelines using GitHub Actions:
|
||||
|
||||
1. **Prerequisites**: Your GitHub Actions workflow must have `id-token: write` permissions
|
||||
2. **Token Exchange**: The OIDC token is exchanged directly for a registry token via `/v0/auth/github-oidc`
|
||||
3. **No Storage**: No local token files are created; authentication is ephemeral per workflow run
|
||||
|
||||
**Example GitHub Actions workflow:**
|
||||
|
||||
```yaml
|
||||
name: Publish MCP Server
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write # Required for OIDC token generation
|
||||
contents: read # E.g. To read the server.json file from your Git repo
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Publish to MCP Registry
|
||||
run: |
|
||||
./bin/mcp-publisher publish \
|
||||
--registry-url "https://registry.modelcontextprotocol.org" \
|
||||
--mcp-file "./server.json" \
|
||||
--auth-method github-oidc
|
||||
```
|
||||
|
||||
### No Authentication (`none`)
|
||||
|
||||
Mainly for registry contributors, for testing locally:
|
||||
|
||||
```bash
|
||||
./bin/mcp-publisher publish --registry-url <REGISTRY_URL> --mcp-file <PATH_TO_MCP_FILE> --auth-method none
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1,104 +0,0 @@
|
|||
# Authentication System
|
||||
|
||||
The publisher tool now uses an interface-based authentication system that allows for multiple authentication mechanisms.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Provider Interface
|
||||
|
||||
The `Provider` interface is defined in `auth/interface.go` and provides the following methods:
|
||||
|
||||
- `GetToken(ctx context.Context) (string, error)` - Retrieves or generates an authentication token
|
||||
- `NeedsLogin() bool` - Checks if a new login flow is required
|
||||
- `Login(ctx context.Context) error` - Performs the authentication flow
|
||||
- `Name() string` - Returns the name of the authentication provider
|
||||
|
||||
### Available Authentication Providers
|
||||
|
||||
#### 1. GitHub OAuth Provider
|
||||
- **Location**: `auth/github/oauth.go`
|
||||
- **Usage**: Uses GitHub's device flow for authentication
|
||||
- **Example**: `github.NewOAuthProvider(forceLogin, registryURL)`
|
||||
|
||||
|
||||
## How to Add New Authentication Providers
|
||||
|
||||
1. Create a new package under `auth/` directory (e.g., `auth/custom/`)
|
||||
2. Implement the `Provider` interface
|
||||
3. Add any necessary configuration or initialization functions
|
||||
4. Update the main application to use the new provider
|
||||
|
||||
### Example Implementation
|
||||
|
||||
```go
|
||||
package custom
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type CustomProvider struct {
|
||||
// your custom fields
|
||||
}
|
||||
|
||||
func NewCustomProvider(config string) *CustomProvider {
|
||||
return &CustomProvider{
|
||||
// initialize your provider
|
||||
}
|
||||
}
|
||||
|
||||
func (cp *CustomProvider) GetToken(ctx context.Context) (string, error) {
|
||||
// implement token retrieval logic
|
||||
return "custom-token", nil
|
||||
}
|
||||
|
||||
func (cp *CustomProvider) NeedsLogin() bool {
|
||||
// implement login check logic
|
||||
return false
|
||||
}
|
||||
|
||||
func (cp *CustomProvider) Login(ctx context.Context) error {
|
||||
// implement authentication flow
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cp *CustomProvider) Name() string {
|
||||
return "custom-auth"
|
||||
}
|
||||
```
|
||||
|
||||
## Usage in Main Application
|
||||
|
||||
The main application automatically selects the appropriate authentication provider:
|
||||
|
||||
1. Uses `GitHub OAuth Provider` by default
|
||||
2. Future providers can be added by extending the provider selection logic
|
||||
|
||||
```go
|
||||
// Create the appropriate auth provider based on configuration
|
||||
var authProvider auth.Provider
|
||||
switch authMethod {
|
||||
case "github":
|
||||
log.Println("Using GitHub OAuth for authentication")
|
||||
authProvider = github.NewOAuthProvider(forceLogin, registryURL)
|
||||
default:
|
||||
log.Printf("Unsupported authentication method: %s\n", authMethod)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if login is needed and perform authentication
|
||||
ctx := context.Background()
|
||||
if authProvider.NeedsLogin() {
|
||||
err := authProvider.Login(ctx)
|
||||
if err != nil {
|
||||
log.Printf("Failed to authenticate with %s: %s\n", authProvider.Name(), err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get the token
|
||||
token, err := authProvider.GetToken(ctx)
|
||||
```
|
||||
|
||||
This design allows for easy extension and testing of different authentication mechanisms while maintaining a clean separation of concerns.
|
||||
432
tools/publisher/auth/github-at.go
Normal file
432
tools/publisher/auth/github-at.go
Normal file
|
|
@ -0,0 +1,432 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
gitHubTokenFilePath = ".mcpregistry_github_token" // #nosec:G101
|
||||
registryTokenFilePath = ".mcpregistry_registry_token" // #nosec:G101
|
||||
// GitHub OAuth URLs
|
||||
GitHubDeviceCodeURL = "https://github.com/login/device/code" // #nosec:G101
|
||||
GitHubAccessTokenURL = "https://github.com/login/oauth/access_token" // #nosec:G101
|
||||
)
|
||||
|
||||
// DeviceCodeResponse represents the response from GitHub's device code endpoint
|
||||
type DeviceCodeResponse struct {
|
||||
DeviceCode string `json:"device_code"`
|
||||
UserCode string `json:"user_code"`
|
||||
VerificationURI string `json:"verification_uri"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Interval int `json:"interval"`
|
||||
}
|
||||
|
||||
// AccessTokenResponse represents the response from GitHub's access token endpoint
|
||||
type AccessTokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Scope string `json:"scope"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// RegistryTokenResponse represents the response from registry's token exchange endpoint
|
||||
type RegistryTokenResponse struct {
|
||||
RegistryToken string `json:"registry_token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
// StoredRegistryToken represents the registry token with expiration stored locally
|
||||
type StoredRegistryToken struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
// GitHubATProvider implements the Provider interface using GitHub's device flow
|
||||
type GitHubATProvider struct {
|
||||
clientID string
|
||||
forceLogin bool
|
||||
registryURL string
|
||||
}
|
||||
|
||||
// ServerHealthResponse represents the response from the health endpoint
|
||||
type ServerHealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
GitHubClientID string `json:"github_client_id"`
|
||||
}
|
||||
|
||||
// NewGitHubATProvider creates a new GitHub OAuth provider
|
||||
func NewGitHubATProvider(forceLogin bool, registryURL string) Provider { //nolint:ireturn
|
||||
return &GitHubATProvider{
|
||||
forceLogin: forceLogin,
|
||||
registryURL: registryURL,
|
||||
}
|
||||
}
|
||||
|
||||
// GetToken retrieves the registry JWT token (exchanges GitHub token if needed)
|
||||
func (g *GitHubATProvider) GetToken(ctx context.Context) (string, error) {
|
||||
// Check if we have a valid registry token
|
||||
registryToken, err := readRegistryToken()
|
||||
if err == nil && registryToken != "" {
|
||||
return registryToken, nil
|
||||
}
|
||||
|
||||
// If no valid registry token, exchange GitHub token for registry token
|
||||
githubToken, err := readToken()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read GitHub token: %w", err)
|
||||
}
|
||||
|
||||
// Exchange GitHub token for registry token
|
||||
registryToken, expiresAt, err := g.exchangeTokenForRegistry(ctx, githubToken)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to exchange token: %w", err)
|
||||
}
|
||||
|
||||
// Store the registry token
|
||||
err = saveRegistryToken(registryToken, expiresAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to save registry token: %w", err)
|
||||
}
|
||||
|
||||
return registryToken, nil
|
||||
}
|
||||
|
||||
// NeedsLogin checks if a new login is required
|
||||
func (g *GitHubATProvider) NeedsLogin() bool {
|
||||
if g.forceLogin {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if GitHub token exists
|
||||
_, statErr := os.Stat(gitHubTokenFilePath)
|
||||
if os.IsNotExist(statErr) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if valid registry token exists
|
||||
_, err := readRegistryToken()
|
||||
if err != nil {
|
||||
// No valid registry token, but we have GitHub token
|
||||
// We don't need to login, just exchange tokens
|
||||
return false
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Login performs the GitHub device flow authentication
|
||||
func (g *GitHubATProvider) Login(ctx context.Context) error {
|
||||
// If clientID is not set, try to retrieve it from the server's health endpoint
|
||||
if g.clientID == "" {
|
||||
clientID, err := getClientID(ctx, g.registryURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting GitHub Client ID: %w", err)
|
||||
}
|
||||
g.clientID = clientID
|
||||
}
|
||||
|
||||
// Device flow login logic using GitHub's device flow
|
||||
// First, request a device code
|
||||
deviceCode, userCode, verificationURI, err := g.requestDeviceCode(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error requesting device code: %w", err)
|
||||
}
|
||||
|
||||
// Display instructions to the user
|
||||
log.Println("\nTo authenticate, please:")
|
||||
log.Println("1. Go to:", verificationURI)
|
||||
log.Println("2. Enter code:", userCode)
|
||||
log.Println("3. Authorize this application")
|
||||
|
||||
// Poll for the token
|
||||
log.Println("Waiting for authorization...")
|
||||
token, err := g.pollForToken(ctx, deviceCode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error polling for token: %w", err)
|
||||
}
|
||||
|
||||
// Store the token locally
|
||||
err = saveToken(token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error saving token: %w", err)
|
||||
}
|
||||
|
||||
log.Println("Successfully authenticated!")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Name returns the name of this auth provider
|
||||
func (g *GitHubATProvider) Name() string {
|
||||
return "github"
|
||||
}
|
||||
|
||||
// requestDeviceCode initiates the device authorization flow
|
||||
func (g *GitHubATProvider) requestDeviceCode(ctx context.Context) (string, string, string, error) {
|
||||
if g.clientID == "" {
|
||||
return "", "", "", fmt.Errorf("GitHub Client ID is required for device flow login")
|
||||
}
|
||||
|
||||
payload := map[string]string{
|
||||
"client_id": g.clientID,
|
||||
"scope": "read:org read:user",
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GitHubDeviceCodeURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return "", "", "", 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 "", "", "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", "", fmt.Errorf("request device code failed: %s", body)
|
||||
}
|
||||
|
||||
var deviceCodeResp DeviceCodeResponse
|
||||
err = json.Unmarshal(body, &deviceCodeResp)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
return deviceCodeResp.DeviceCode, deviceCodeResp.UserCode, deviceCodeResp.VerificationURI, nil
|
||||
}
|
||||
|
||||
// pollForToken polls for access token after user completes authorization
|
||||
func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string) (string, error) {
|
||||
if g.clientID == "" {
|
||||
return "", fmt.Errorf("GitHub Client ID is required for device flow login")
|
||||
}
|
||||
|
||||
payload := map[string]string{
|
||||
"client_id": g.clientID,
|
||||
"device_code": deviceCode,
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Default polling interval and expiration time
|
||||
interval := 5 // seconds
|
||||
expiresIn := 900 // 15 minutes
|
||||
deadline := time.Now().Add(time.Duration(expiresIn) * time.Second)
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GitHubAccessTokenURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return "", 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 "", err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var tokenResp AccessTokenResponse
|
||||
err = json.Unmarshal(body, &tokenResp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if tokenResp.Error == "authorization_pending" {
|
||||
// User hasn't authorized yet, wait and retry
|
||||
time.Sleep(time.Duration(interval) * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
if tokenResp.Error != "" {
|
||||
return "", fmt.Errorf("token request failed: %s", tokenResp.Error)
|
||||
}
|
||||
|
||||
if tokenResp.AccessToken != "" {
|
||||
return tokenResp.AccessToken, nil
|
||||
}
|
||||
|
||||
// If we reach here, something unexpected happened
|
||||
return "", fmt.Errorf("failed to obtain access token")
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("device code authorization timed out")
|
||||
}
|
||||
|
||||
// saveToken saves the GitHub access token to a local file
|
||||
func saveToken(token string) error {
|
||||
return os.WriteFile(gitHubTokenFilePath, []byte(token), 0600)
|
||||
}
|
||||
|
||||
// readToken reads the GitHub access token from a local file
|
||||
func readToken() (string, error) {
|
||||
tokenData, err := os.ReadFile(gitHubTokenFilePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(tokenData), nil
|
||||
}
|
||||
|
||||
func getClientID(ctx context.Context, registryURL string) (string, error) {
|
||||
// This function should retrieve the GitHub Client ID from the registry URL
|
||||
// For now, we will return a placeholder value
|
||||
// In a real implementation, this would likely involve querying the registry or configuration
|
||||
if registryURL == "" {
|
||||
return "", fmt.Errorf("registry URL is required to get GitHub Client ID")
|
||||
}
|
||||
// get the clientID from the server's health endpoint
|
||||
healthURL := registryURL + "/v0/health"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, healthURL, nil)
|
||||
if err != nil {
|
||||
log.Printf("Error creating request: %s\n", err.Error())
|
||||
return "", err
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("Error fetching health endpoint: %s\n", err.Error())
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
log.Printf("Health endpoint returned status %d: %s\n", resp.StatusCode, body)
|
||||
return "", fmt.Errorf("health endpoint returned status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var healthResponse ServerHealthResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&healthResponse)
|
||||
if err != nil {
|
||||
log.Printf("Error decoding health response: %s\n", err.Error())
|
||||
return "", err
|
||||
}
|
||||
if healthResponse.GitHubClientID == "" {
|
||||
log.Println("GitHub Client ID is not set in the server's health response.")
|
||||
return "", fmt.Errorf("GitHub Client ID is not set in the server's health response")
|
||||
}
|
||||
|
||||
githubClientID := healthResponse.GitHubClientID
|
||||
|
||||
return githubClientID, nil
|
||||
}
|
||||
|
||||
// exchangeTokenForRegistry exchanges a GitHub token for a registry JWT token
|
||||
func (g *GitHubATProvider) exchangeTokenForRegistry(ctx context.Context, githubToken string) (string, int64, error) {
|
||||
if g.registryURL == "" {
|
||||
return "", 0, fmt.Errorf("registry URL is required for token exchange")
|
||||
}
|
||||
|
||||
// Prepare the request body
|
||||
payload := map[string]string{
|
||||
"github_token": githubToken,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
// Make the token exchange request
|
||||
exchangeURL := g.registryURL + "/v0/auth/github-at"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, exchangeURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return "", 0, 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 "", 0, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", 0, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var tokenResp RegistryTokenResponse
|
||||
err = json.Unmarshal(body, &tokenResp)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("failed to unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
return tokenResp.RegistryToken, tokenResp.ExpiresAt, nil
|
||||
}
|
||||
|
||||
// saveRegistryToken saves the registry JWT token to a local file with expiration
|
||||
func saveRegistryToken(token string, expiresAt int64) error {
|
||||
storedToken := StoredRegistryToken{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(storedToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal token: %w", err)
|
||||
}
|
||||
|
||||
return os.WriteFile(registryTokenFilePath, data, 0600)
|
||||
}
|
||||
|
||||
// readRegistryToken reads the registry JWT token from a local file
|
||||
func readRegistryToken() (string, error) {
|
||||
data, err := os.ReadFile(registryTokenFilePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var storedToken StoredRegistryToken
|
||||
err = json.Unmarshal(data, &storedToken)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to unmarshal token: %w", err)
|
||||
}
|
||||
|
||||
// Check if token has expired
|
||||
if time.Now().Unix() >= storedToken.ExpiresAt {
|
||||
// Token has expired, remove the file
|
||||
os.Remove(registryTokenFilePath)
|
||||
return "", fmt.Errorf("registry token has expired")
|
||||
}
|
||||
|
||||
return storedToken.Token, nil
|
||||
}
|
||||
165
tools/publisher/auth/github-oidc.go
Normal file
165
tools/publisher/auth/github-oidc.go
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
type GitHubOIDCProvider struct {
|
||||
registryURL string
|
||||
}
|
||||
|
||||
func NewGitHubOIDCProvider(registryURL string) Provider { //nolint:ireturn
|
||||
return &GitHubOIDCProvider{
|
||||
registryURL: registryURL,
|
||||
}
|
||||
}
|
||||
|
||||
// GetToken retrieves the registry JWT token using GitHub Actions OIDC token
|
||||
func (o *GitHubOIDCProvider) GetToken(ctx context.Context) (string, error) {
|
||||
// Get OIDC token from GitHub Actions endpoint
|
||||
oidcToken, err := o.getOIDCTokenFromGitHub(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get OIDC token from GitHub: %w", err)
|
||||
}
|
||||
|
||||
// Exchange OIDC token for registry token
|
||||
registryToken, err := o.exchangeOIDCTokenForRegistry(ctx, oidcToken)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to exchange OIDC token: %w", err)
|
||||
}
|
||||
|
||||
return registryToken, nil
|
||||
}
|
||||
|
||||
// NeedsLogin always returns false for OIDC since the token is provided by GitHub Actions
|
||||
func (o *GitHubOIDCProvider) NeedsLogin() bool {
|
||||
// OIDC tokens are provided by GitHub Actions runtime, no interactive login needed
|
||||
return false
|
||||
}
|
||||
|
||||
// Login is not needed for OIDC since tokens are provided by GitHub Actions
|
||||
func (o *GitHubOIDCProvider) Login(_ context.Context) error {
|
||||
// No interactive login needed for OIDC
|
||||
return nil
|
||||
}
|
||||
|
||||
// Name returns the name of this auth provider
|
||||
func (o *GitHubOIDCProvider) Name() string {
|
||||
return "github-oidc"
|
||||
}
|
||||
|
||||
// exchangeOIDCTokenForRegistry exchanges a GitHub OIDC token for a registry JWT token
|
||||
func (o *GitHubOIDCProvider) exchangeOIDCTokenForRegistry(ctx context.Context, oidcToken string) (string, error) {
|
||||
if o.registryURL == "" {
|
||||
return "", fmt.Errorf("registry URL is required for token exchange")
|
||||
}
|
||||
|
||||
// Prepare the request body
|
||||
payload := map[string]string{
|
||||
"oidc_token": oidcToken,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
// Make the token exchange request
|
||||
exchangeURL := o.registryURL + "/v0/auth/github-oidc"
|
||||
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
|
||||
}
|
||||
|
||||
// getOIDCTokenFromGitHub fetches the OIDC token from GitHub Actions endpoint
|
||||
func (o *GitHubOIDCProvider) getOIDCTokenFromGitHub(ctx context.Context) (string, error) {
|
||||
// Check for required environment variables
|
||||
requestToken := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
|
||||
if requestToken == "" {
|
||||
return "", fmt.Errorf("ACTIONS_ID_TOKEN_REQUEST_TOKEN environment variable not found - are you running in GitHub Actions with id-token: write permissions?")
|
||||
}
|
||||
|
||||
requestURL := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL")
|
||||
if requestURL == "" {
|
||||
return "", fmt.Errorf("ACTIONS_ID_TOKEN_REQUEST_URL environment variable not found - are you running in GitHub Actions with id-token: write permissions?")
|
||||
}
|
||||
|
||||
// Build the full URL with audience parameter
|
||||
fullURL := requestURL + "&audience=mcp-registry"
|
||||
|
||||
// Create the request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Set the authorization header
|
||||
req.Header.Set("Authorization", "Bearer "+requestToken)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
// Make the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read the response
|
||||
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("GitHub OIDC token request failed with status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// Parse the response to extract the token value
|
||||
var tokenResp struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
err = json.Unmarshal(body, &tokenResp)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to unmarshal OIDC token response: %w", err)
|
||||
}
|
||||
|
||||
if tokenResp.Value == "" {
|
||||
return "", fmt.Errorf("OIDC token value is empty in response")
|
||||
}
|
||||
|
||||
return tokenResp.Value, nil
|
||||
}
|
||||
76
tools/publisher/auth/none.go
Normal file
76
tools/publisher/auth/none.go
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type NoneProvider struct {
|
||||
registryURL string
|
||||
token string
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
RegistryToken string `json:"registry_token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
func NewNoneProvider(registryURL string) Provider { //nolint:ireturn
|
||||
return &NoneProvider{
|
||||
registryURL: registryURL,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *NoneProvider) GetToken(ctx context.Context) (string, error) {
|
||||
if p.token != "" {
|
||||
return p.token, nil
|
||||
}
|
||||
|
||||
// Get anonymous token from registry
|
||||
if !strings.HasSuffix(p.registryURL, "/") {
|
||||
p.registryURL += "/"
|
||||
}
|
||||
tokenURL := p.registryURL + "v0/auth/none"
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error getting anonymous token: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("failed to get anonymous token (status %d): %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var tokenResp TokenResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
|
||||
return "", fmt.Errorf("error decoding token response: %w", err)
|
||||
}
|
||||
|
||||
p.token = tokenResp.RegistryToken
|
||||
return p.token, nil
|
||||
}
|
||||
|
||||
func (p *NoneProvider) NeedsLogin() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *NoneProvider) Login(_ context.Context) error {
|
||||
// No login needed for anonymous auth
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *NoneProvider) Name() string {
|
||||
return "none"
|
||||
}
|
||||
|
|
@ -14,8 +14,6 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/tools/publisher/auth"
|
||||
"github.com/modelcontextprotocol/registry/tools/publisher/auth/github"
|
||||
"github.com/modelcontextprotocol/registry/tools/publisher/auth/none"
|
||||
)
|
||||
|
||||
// Server structure types for JSON generation
|
||||
|
|
@ -104,8 +102,7 @@ func publishCommand() error {
|
|||
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",
|
||||
"authentication method (github for authenticated, none for anonymous) (default: github)")
|
||||
publishFlags.StringVar(&authMethod, "auth-method", "github-at", "authentication method (default: github-at)")
|
||||
|
||||
// Set custom usage function
|
||||
publishFlags.Usage = func() {
|
||||
|
|
@ -117,7 +114,7 @@ func publishCommand() error {
|
|||
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 (github for authenticated, none for anonymous) (default: github)\n")
|
||||
fmt.Fprint(os.Stdout, " --auth-method string authentication method (default: github-at)\n")
|
||||
}
|
||||
|
||||
if err := publishFlags.Parse(os.Args[2:]); err != nil {
|
||||
|
|
@ -137,12 +134,15 @@ func publishCommand() error {
|
|||
|
||||
var authProvider auth.Provider // Determine the authentication method
|
||||
switch authMethod {
|
||||
case "github":
|
||||
log.Println("Using GitHub OAuth for authentication")
|
||||
authProvider = github.NewOAuthProvider(forceLogin, registryURL)
|
||||
case "github-at":
|
||||
log.Println("Using GitHub Access Token for authentication")
|
||||
authProvider = auth.NewGitHubATProvider(forceLogin, registryURL)
|
||||
case "github-oidc":
|
||||
log.Println("Using GitHub Actions OIDC for authentication")
|
||||
authProvider = auth.NewGitHubOIDCProvider(registryURL)
|
||||
case "none":
|
||||
log.Println("Using anonymous authentication")
|
||||
authProvider = none.NewProvider(registryURL)
|
||||
authProvider = auth.NewNoneProvider(registryURL)
|
||||
default:
|
||||
return fmt.Errorf("unsupported authentication method: %s", authMethod)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue