feat(auth): streamline GitHub token validation and add organization membership check

This commit is contained in:
Avinash Sridhar 2025-04-30 10:03:45 -04:00 • committed by Toby Padilla
commit 089fd3994a
3 changed files with 62 additions and 48 deletions

View file

@ -2,7 +2,6 @@
package auth package auth
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -11,10 +10,6 @@ import (
"regexp" "regexp"
) )
const (
GitHubValidateTokenURL = "https://api.github.com/applications/CLIENT_ID/token"
)
var ( var (
// ErrAuthFailed is returned when authentication fails // ErrAuthFailed is returned when authentication fails
ErrAuthFailed = errors.New("authentication failed") ErrAuthFailed = errors.New("authentication failed")
@ -71,69 +66,65 @@ func NewGitHubDeviceAuth(config GitHubOAuthConfig) *GitHubDeviceAuth {
} }
// ValidateToken checks if a token has write:packages access to the required repository // ValidateToken checks if a token has write:packages access to the required repository
// and verifies that the user matches the owner in the required repository
func (g *GitHubDeviceAuth) ValidateToken(token string, requiredRepo string) (bool, error) { func (g *GitHubDeviceAuth) ValidateToken(token string, requiredRepo string) (bool, error) {
// If no repo is required, we can't validate properly // If no repo is required, we can't validate properly
if requiredRepo == "" { if requiredRepo == "" {
return false, fmt.Errorf("repository reference is required for token validation") return false, fmt.Errorf("repository reference is required for token validation")
} }
// First, check if the token is valid using the app token check endpoint // Get the authenticated user
req, err := http.NewRequest("POST", GitHubValidateTokenURL, bytes.NewBuffer([]byte(`{"access_token": "`+token+`"}`))) userReq, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil { if err != nil {
return false, err return false, err
} }
req.URL.Path = fmt.Sprintf("/applications/%s/token", g.config.ClientID) userReq.Header.Set("Accept", "application/vnd.github+json")
userReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(g.config.ClientID, g.config.ClientSecret)
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) userResp, err := client.Do(userReq)
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer userResp.Body.Close()
body, err := io.ReadAll(resp.Body) if userResp.StatusCode != http.StatusOK {
return false, fmt.Errorf("failed to get user info: status %d", userResp.StatusCode)
}
var userInfo struct {
Login string `json:"login"`
}
userBody, err := io.ReadAll(userResp.Body)
if err != nil { if err != nil {
return false, err return false, err
} }
if resp.StatusCode != http.StatusOK { if err := json.Unmarshal(userBody, &userInfo); err != nil {
return false, fmt.Errorf("token validation failed: %s", body) return false, err
} }
var validationResp TokenValidationResponse // Extract owner from the required repo
err = json.Unmarshal(body, &validationResp) owner, _, err := g.ExtractGitHubRepoFromName(requiredRepo)
if err != nil { if err != nil {
return false, err return false, err
} }
// Now check if the token has permissions to the specific repository // Verify that the authenticated user matches the owner
// Use the GitHub API to check repository-specific permissions if userInfo.Login != owner {
repoCheckURL := fmt.Sprintf("https://api.github.com/repos/%s", requiredRepo) // Check if the user is a member of the organization
repoReq, err := http.NewRequest("GET", repoCheckURL, nil) isMember, err := g.checkOrgMembership(token, userInfo.Login, owner)
if err != nil { if err != nil {
return false, err return false, fmt.Errorf("failed to check org membership: %s", owner)
} }
repoReq.Header.Set("Accept", "application/vnd.github+json") if !isMember {
repoReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) return false, fmt.Errorf("token belongs to user %s, but repository is owned by %s and user is not a member of the organization", userInfo.Login, owner)
repoResp, err := client.Do(repoReq)
if err != nil {
return false, err
} }
defer repoResp.Body.Close()
// Read and check response
if repoResp.StatusCode != http.StatusOK {
return false, fmt.Errorf("token does not have access to repository: %s (status: %d)", requiredRepo, repoResp.StatusCode)
} }
// If we've reached this point, the token has access the repo // If we've reached this point, the token has access the repo and the user matches the owner or is a member of the owner org
return true, nil return true, nil
} }
@ -156,3 +147,32 @@ func (g *GitHubDeviceAuth) ExtractGitHubRepo(repoURL string) (owner, repo string
} }
return matches[1], matches[2], nil return matches[1], matches[2], nil
} }
// checkOrgMembership checks if a user is a member of an organization
func (g *GitHubDeviceAuth) checkOrgMembership(token, username, org string) (bool, error) {
// Create request to check if user is a member of the organization
// GitHub API endpoint: GET /orgs/{org}/members/{username}
// true if status code is 204 No Content
// false if status code is 404 Not Found
url := fmt.Sprint("https://api.github.com/orgs/", org, "/members/", username)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNoContent {
return true, nil
}
return false, fmt.Errorf("failed to check org membership: status %d", resp.StatusCode)
}

View file

@ -52,15 +52,7 @@ func (s *AuthServiceImpl) ValidateAuth(ctx context.Context, auth model.Authentic
switch auth.Method { switch auth.Method {
case model.AuthMethodGitHub: case model.AuthMethodGitHub:
// Extract repo reference from the repository URL if it's not provided // Extract repo reference from the repository URL if it's not provided
owner, repo, err := s.githubAuth.ExtractGitHubRepoFromName(auth.RepoRef) return s.githubAuth.ValidateToken(auth.Token, auth.RepoRef)
if err != nil {
return false, err
}
repoRef := fmt.Sprintf("%s/%s", owner, repo)
if repoRef == "" {
return false, fmt.Errorf("repository reference is required for GitHub authentication")
}
return s.githubAuth.ValidateToken(auth.Token, repoRef)
default: default:
return false, ErrUnsupportedAuthMethod return false, ErrUnsupportedAuthMethod
} }

View file

@ -14,7 +14,9 @@ import (
const ( const (
tokenFilePath = ".mcpregistry_token" tokenFilePath = ".mcpregistry_token"
GithubClientID = "Iv23ctIMuVtIi2bxoi9o"
// TODO: Replace this with the official owned OAuth client ID
GithubClientID = "Ov23ct0x1531TPL3WJ9h"
// GitHub OAuth URLs // GitHub OAuth URLs
GitHubDeviceCodeURL = "https://github.com/login/device/code" GitHubDeviceCodeURL = "https://github.com/login/device/code"
@ -123,7 +125,7 @@ func performDeviceFlowLogin() error {
func requestDeviceCode() (string, string, string, error) { func requestDeviceCode() (string, string, string, error) {
payload := map[string]string{ payload := map[string]string{
"client_id": GithubClientID, "client_id": GithubClientID,
"scope": "write:packages repo", "scope": "read:org read:user",
} }
jsonData, err := json.Marshal(payload) jsonData, err := json.Marshal(payload)