diff --git a/.env.example b/.env.example index 76c064ac0..af44384fd 100644 --- a/.env.example +++ b/.env.example @@ -57,6 +57,18 @@ MCP_REGISTRY_GITHUB_CLIENT_SECRET=0e8db54879b02c29adef51795586f3c510a9341d # This should be a 32-byte Ed25519 seed (not the full private key). Generate a new seed with: `openssl rand -hex 32` MCP_REGISTRY_JWT_PRIVATE_KEY=bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c +# GitHub team (org/team) whose members, including those of child teams, can sign +# in as registry admins. Unset turns GitHub admin sign-in off. It doesn't turn +# off OIDC admin sign-in: set MCP_REGISTRY_OIDC_ENABLED=false for that. +MCP_REGISTRY_GITHUB_ADMIN_TEAM= +# GitHub app for admin sign-in only. Don't use the app above: tokens for +# publishing must not work for admin sign-in. It needs the callback URLs +# http://127.0.0.1:47821/callback, :47822 and :47823, read access to +# organization members, and to be installed on the team's organization. Leave +# device flow off. +MCP_REGISTRY_GITHUB_ADMIN_CLIENT_ID= +MCP_REGISTRY_GITHUB_ADMIN_CLIENT_SECRET= + # Anonymous authentication for development/testing only # When enabled, allows anyone to get tokens for publishing to io.modelcontextprotocol.anonymous/* namespace # This should be disabled in prod diff --git a/deploy/README.md b/deploy/README.md index 738762b94..c9dab0951 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -492,6 +492,8 @@ Configuration keys are namespaced. Set them with `pulumi config set [--sec | `mcp-registry:provider` | Kubernetes provider (local/gcp) | No (default: local) | | `mcp-registry:nodeMachineType` | GCP node machine type; changing it rolls nodes | No (default: e2-standard-2) | | `mcp-registry:postgresSharedBuffers` | Registry PostgreSQL shared buffers, e.g. `512MB`; changes restart the singleton | No (PostgreSQL default) | +| `mcp-registry:githubAdminClientId` | Client ID of the GitHub app for [admin sign-in](../docs/administration/admin-operations.md#authentication). Setting it turns on GitHub admin sign-in and turns off Google's. In production it needs an `imageTag` after 1.8.21. Use a different app for each environment, and never the one for publishing. The app needs the callback URLs `http://127.0.0.1:47821/callback`, `http://127.0.0.1:47822/callback` and `http://127.0.0.1:47823/callback`, read access to organization members, and to be installed on the organization. Leave device flow off | No | +| `mcp-registry:githubAdminClientSecret` | Client secret of that app | With `githubAdminClientId` (secret) | | `mcp-registry:githubClientId` | GitHub OAuth Client ID | Yes | | `mcp-registry:githubClientSecret` | GitHub OAuth Client Secret | Yes (secret) | | `mcp-registry:jwtPrivateKey` | Ed25519 seed used to sign registry JWTs | Yes (secret) | diff --git a/deploy/pkg/k8s/admin_login.go b/deploy/pkg/k8s/admin_login.go new file mode 100644 index 000000000..7a520a3ee --- /dev/null +++ b/deploy/pkg/k8s/admin_login.go @@ -0,0 +1,48 @@ +package k8s + +import ( + "errors" + + corev1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/core/v1" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" + "golang.org/x/mod/semver" +) + +const ( + // Managed in github.com/modelcontextprotocol/access + githubAdminTeam = "modelcontextprotocol/registry-admins" + // The last release without GitHub admin sign-in + lastGoogleOnlyRelease = "v1.8.21" + githubAdminSecretKey = "GITHUB_ADMIN_CLIENT_SECRET" //nolint:gosec // G101: the name of a key, not a credential +) + +// adminLogin turns on exactly one kind of admin sign-in: GitHub if +// githubAdminClientId is set, Google otherwise. It adds the GitHub app's secret +// to secrets. It returns whether Google sign-in is on, and the settings for +// GitHub sign-in, which are empty when it is off. +func adminLogin(conf *config.Config, environment string, secrets pulumi.StringMap, secretName pulumi.StringPtrInput) (google bool, env corev1.EnvVarArray, err error) { + clientID := conf.Get("githubAdminClientId") + if clientID == "" { + return true, nil, nil + } + if clientID == conf.Get("githubClientId") { + return false, nil, errors.New("githubAdminClientId must not be the GitHub app for publishing") + } + // Older releases ignore these settings, which would leave no admin sign-in. + if version := "v" + conf.Get("imageTag"); environment == "prod" && + (!semver.IsValid(version) || semver.Compare(version, lastGoogleOnlyRelease) <= 0) { + return false, nil, errors.New("githubAdminClientId requires an imageTag after " + lastGoogleOnlyRelease) + } + secrets[githubAdminSecretKey] = conf.RequireSecret("githubAdminClientSecret") + return false, corev1.EnvVarArray{ + &corev1.EnvVarArgs{Name: pulumi.String("MCP_REGISTRY_GITHUB_ADMIN_TEAM"), Value: pulumi.String(githubAdminTeam)}, + &corev1.EnvVarArgs{Name: pulumi.String("MCP_REGISTRY_GITHUB_ADMIN_CLIENT_ID"), Value: pulumi.String(clientID)}, + &corev1.EnvVarArgs{ + Name: pulumi.String("MCP_REGISTRY_GITHUB_ADMIN_CLIENT_SECRET"), + ValueFrom: &corev1.EnvVarSourceArgs{SecretKeyRef: &corev1.SecretKeySelectorArgs{ + Name: secretName, Key: pulumi.String(githubAdminSecretKey), + }}, + }, + }, nil +} diff --git a/deploy/pkg/k8s/admin_login_test.go b/deploy/pkg/k8s/admin_login_test.go new file mode 100644 index 000000000..2c14da843 --- /dev/null +++ b/deploy/pkg/k8s/admin_login_test.go @@ -0,0 +1,59 @@ +package k8s //nolint:testpackage // Check stack configuration without deploying. + +import ( + "testing" + + corev1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/core/v1" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" +) + +func TestAdminLogin(t *testing.T) { + for _, tc := range []struct { + name, environment, clientID, imageTag string + google, wantErr bool + }{ + {"off in prod", "prod", "", "1.8.21", true, false}, + {"off in staging", "staging", "", "", true, false}, + {"on in staging", "staging", "admin-app", "", false, false}, + {"on in prod", "prod", "admin-app", "1.8.22", false, false}, + {"prod release is too old", "prod", "admin-app", "1.8.21", false, true}, + {"prod release is not a version", "prod", "admin-app", "main", false, true}, + {"app for publishing", "staging", "publish-app", "", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + err := pulumi.RunErr(func(ctx *pulumi.Context) error { + secrets := pulumi.StringMap{} + google, env, err := adminLogin(config.New(ctx, "mcp-registry"), tc.environment, secrets, pulumi.String("secrets").ToStringPtrOutput()) + if (err != nil) != tc.wantErr { + t.Fatalf("unexpected error: %v", err) + } + if tc.wantErr { + return nil + } + values := map[string]any{} + for _, v := range env { + if e := v.(*corev1.EnvVarArgs); e.Value != nil { + values[string(e.Name.(pulumi.String))] = e.Value + } + } + wantTeam, wantEnv, wantSecrets := any(nil), 0, 0 + if !tc.google { + wantTeam, wantEnv, wantSecrets = pulumi.String(githubAdminTeam), 3, 1 + } + if google != tc.google || values["MCP_REGISTRY_GITHUB_ADMIN_TEAM"] != wantTeam || len(env) != wantEnv || len(secrets) != wantSecrets { + t.Errorf("unexpected settings: google %v, %v, %d secrets", google, values, len(secrets)) + } + return nil + }, pulumi.WithMocks("admin-login-test", "staging", ownershipMonitor{t}), func(info *pulumi.RunInfo) { + info.Config = map[string]string{ + "mcp-registry:githubClientId": "publish-app", "mcp-registry:githubAdminClientId": tc.clientID, + "mcp-registry:githubAdminClientSecret": "test", "mcp-registry:imageTag": tc.imageTag, + } + }) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/deploy/pkg/k8s/registry.go b/deploy/pkg/k8s/registry.go index 9d7912be4..588881464 100644 --- a/deploy/pkg/k8s/registry.go +++ b/deploy/pkg/k8s/registry.go @@ -89,6 +89,15 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env registryCPURequest = request } + secrets := pulumi.StringMap{ + "GITHUB_CLIENT_SECRET": conf.RequireSecret("githubClientSecret"), + "JWT_PRIVATE_KEY": conf.RequireSecret("jwtPrivateKey"), + } + googleAdminLogin, adminEnv, err := adminLogin(conf, environment, secrets, pulumi.String("mcp-registry-secrets")) + if err != nil { + return nil, err + } + // Create Secret with sensitive configuration secret, err := corev1.NewSecret(ctx, "mcp-registry-secrets", &corev1.SecretArgs{ Metadata: &metav1.ObjectMetaArgs{ @@ -99,11 +108,8 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env "environment": pulumi.String(environment), }, }, - StringData: pulumi.StringMap{ - "GITHUB_CLIENT_SECRET": conf.RequireSecret("githubClientSecret"), - "JWT_PRIVATE_KEY": conf.RequireSecret("jwtPrivateKey"), - }, - Type: pulumi.String("Opaque"), + StringData: secrets, + Type: pulumi.String("Opaque"), }, pulumi.Provider(cluster.Provider)) if err != nil { return nil, err @@ -268,10 +274,10 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }, }, }, - // Google Cloud Identity OIDC for admin access + // Google Cloud Identity OIDC for admin access, unless adminEnv turns on GitHub &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_ENABLED"), - Value: pulumi.String("true"), + Value: pulumi.String(strconv.FormatBool(googleAdminLogin)), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_ISSUER"), @@ -302,7 +308,7 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env return "https://" + environment + ".registry.modelcontextprotocol.io" }()), }, - }, poolEnv...), + }, append(adminEnv, poolEnv...)...), // StartupProbe protects the DB-retry budget in cmd/registry/main.go: // 30 × 5s = 150s allowed before liveness/readiness take over, which // covers the worst-case retry budget (8 attempts × 10s + ~40s sleep). diff --git a/docker-compose.yml b/docker-compose.yml index 3fff7bca1..e29d54501 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,9 @@ services: - MCP_REGISTRY_DATABASE_URL=${MCP_REGISTRY_DATABASE_URL:-postgres://mcpregistry:mcpregistry@postgres:5432/mcp-registry} - MCP_REGISTRY_GITHUB_CLIENT_ID=${MCP_REGISTRY_GITHUB_CLIENT_ID:-Iv23licy3GSiM9Km5jtd} - MCP_REGISTRY_GITHUB_CLIENT_SECRET=${MCP_REGISTRY_GITHUB_CLIENT_SECRET:-0e8db54879b02c29adef51795586f3c510a9341d} + - MCP_REGISTRY_GITHUB_ADMIN_TEAM=${MCP_REGISTRY_GITHUB_ADMIN_TEAM:-} + - MCP_REGISTRY_GITHUB_ADMIN_CLIENT_ID=${MCP_REGISTRY_GITHUB_ADMIN_CLIENT_ID:-} + - MCP_REGISTRY_GITHUB_ADMIN_CLIENT_SECRET=${MCP_REGISTRY_GITHUB_ADMIN_CLIENT_SECRET:-} - MCP_REGISTRY_JWT_PRIVATE_KEY=${MCP_REGISTRY_JWT_PRIVATE_KEY:-8103179d8ef955f6d3de6d6217224a909ec4060529dfeb1d4ca5a994537658cd} - MCP_REGISTRY_ENABLE_ANONYMOUS_AUTH=${MCP_REGISTRY_ENABLE_ANONYMOUS_AUTH:-true} - MCP_REGISTRY_SEED_FROM=${MCP_REGISTRY_SEED_FROM:-https://registry.modelcontextprotocol.io/v0/servers?search=domdomegg} diff --git a/docs/administration/admin-operations.md b/docs/administration/admin-operations.md index 646a2eb67..056d92949 100644 --- a/docs/administration/admin-operations.md +++ b/docs/administration/admin-operations.md @@ -4,10 +4,10 @@ This is a brief guide for admins and moderators managing content on the registry ## Prerequisites -- Admin account with @modelcontextprotocol.io email - - If you are a maintainer and would like an account, ask in the Discord +- `registry-admins` role in the [access repository](https://github.com/modelcontextprotocol/access#add-or-remove-a-registry-admin), and an @modelcontextprotocol.io account for registries that still use Google sign-in + - If you are a maintainer and need access, ask in the Discord - `gcloud` CLI installed and configured -- `curl` and `jq` installed +- `curl`, `jq` and Python 3 installed - `kubectl` installed with `gke-gcloud-auth-plugin` (for database access) A takedown made with global registry edit permission places a hold on the affected versions. A moderator can also place a hold on a previously withdrawn version by setting its status to `deleted` again. Restoring the version clears the hold. A publisher's bulk status change fails in full if any targeted version is held. New versions are evaluated separately. @@ -19,6 +19,10 @@ A takedown made with global registry edit permission places a hold on the affect ./tools/admin/auth.sh ``` +Where the stack file in `deploy/` has a `githubAdminClientId`, the script signs you in with GitHub in your browser, and the registry checks that you are in the `registry-admins` team. Otherwise it uses `gcloud`. Run it from an up-to-date checkout. + +Set `REGISTRY_URL` to use another registry, such as staging. For one that isn't hosted by us, set `GITHUB_ADMIN_CLIENT_ID` to its own GitHub app, and only do this for a registry you trust, because it receives your sign-in code. Without that setting, the script uses `gcloud`, and only for a registry on this computer. Run the script on the computer where your browser is, and finish one sign-in before you start another. + ## Edit a Specific Server Version Use this when you need to modify details of a specific version (e.g., fix description, update status, modify packages). diff --git a/docs/administration/maintainer-onboarding.md b/docs/administration/maintainer-onboarding.md index aab0beaa8..28bfa37ae 100644 --- a/docs/administration/maintainer-onboarding.md +++ b/docs/administration/maintainer-onboarding.md @@ -9,6 +9,7 @@ When onboarding a new maintainer, complete the following steps: ### 1. Access Repository (GitHub, Google Workspace) - [ ] Open a PR on the [modelcontextprotocol/access](https://github.com/modelcontextprotocol/access) repository +- [ ] For registry admins, include the `registry-admins` role in that PR ### 2. MAINTAINERS.md diff --git a/docs/design/tech-architecture.md b/docs/design/tech-architecture.md index f7fab724f..570f3b360 100644 --- a/docs/design/tech-architecture.md +++ b/docs/design/tech-architecture.md @@ -184,40 +184,24 @@ sequenceDiagram CLI-->>User: Success! ``` -### 4. Admin OIDC Authentication Flow +### 4. Admin Authentication Flow -For registry administration, users with @modelcontextprotocol.io Google Cloud Identity accounts can authenticate using OIDC: +Where GitHub admin sign-in is configured, admins use the authorization code flow with PKCE in their browser. The code returns to `127.0.0.1` on their computer, and the registry exchanges it using its GitHub app for admins. There is no device flow, and the endpoint doesn't accept GitHub tokens, so a publishing token never grants admin permissions. The user must be an active member of the configured team or its child teams. Hosted registries without an admin app use Google sign-in through `/auth/oidc` instead. ```mermaid sequenceDiagram - participant Admin as Admin User - participant CLI as Admin CLI - participant GCP as Google Cloud Identity + participant Admin as Admin's browser + participant CLI as auth.sh + participant GH as GitHub participant API as Registry API - - Admin->>CLI: Request admin token - CLI->>GCP: gcloud auth print-identity-token --audiences=mcp-registry - GCP-->>CLI: ID Token (with hd: "modelcontextprotocol.io") - CLI->>API: POST /v0.1/auth/oidc {"oidc_token": "eyJ..."} - API->>GCP: Verify token signature (JWKS) - API->>API: Validate claims (issuer, audience, hd) - API->>API: Grant admin permissions (edit: *, publish: *) - API-->>CLI: Registry JWT Token - CLI->>API: POST /admin/* (with Registry JWT) - API->>API: Validate JWT + permissions - API-->>CLI: Admin operation success -``` -**Usage:** -```bash -# Get Google Cloud Identity token -ID_TOKEN=$(gcloud auth print-identity-token) - -# Exchange for Registry JWT token -REGISTRY_TOKEN=$(curl -X POST /v0.1/auth/oidc \ - -H "Content-Type: application/json" \ - -d '{"oidc_token": "'$ID_TOKEN'"}' | jq -r .registry_token) - -# Use for admin operations -curl -H "Authorization: Bearer $REGISTRY_TOKEN" /v0.1/... -``` \ No newline at end of file + CLI->>Admin: Open GitHub with state and PKCE challenge + Admin->>GH: Sign in and authorize + GH-->>CLI: Code, through 127.0.0.1 + CLI->>CLI: Check state + CLI->>API: POST /v0/auth/github-admin (code and PKCE verifier) + API->>GH: Exchange the code, with the app's secret + API->>GH: Check that the user is in the admin team + API->>GH: Revoke the user's authorization and token + API-->>CLI: Registry JWT (5 minutes) +``` diff --git a/docs/reference/api/official-registry-api.md b/docs/reference/api/official-registry-api.md index f674a2431..6e147e9dd 100644 --- a/docs/reference/api/official-registry-api.md +++ b/docs/reference/api/official-registry-api.md @@ -88,8 +88,9 @@ The `GET /v0.1/servers/{serverName}/versions` endpoint returns all versions of a - POST `/v0.1/auth/dns` - Exchange signed DNS challenge for auth token - POST `/v0.1/auth/http` - Exchange signed HTTP challenge for auth token - POST `/v0.1/auth/github-at` - Exchange GitHub access token for auth token +- POST `/v0.1/auth/github-admin` - Exchange GitHub authorization code and PKCE verifier for admin auth token (for admins, where configured) - POST `/v0.1/auth/github-oidc` - Exchange GitHub OIDC token for auth token -- POST `/v0.1/auth/oidc` - Exchange Google OIDC token for auth token (for admins) +- POST `/v0.1/auth/oidc` - Exchange Google OIDC token for auth token (for admins, where configured) #### Status endpoints diff --git a/internal/api/handlers/v0/auth/common.go b/internal/api/handlers/v0/auth/common.go index 36bd08514..9ff2a19ce 100644 --- a/internal/api/handlers/v0/auth/common.go +++ b/internal/api/handlers/v0/auth/common.go @@ -287,7 +287,7 @@ func (h *CoreAuthHandler) ExchangeToken( return nil, fmt.Errorf("no MCP public key found in HTTP response") case auth.MethodDNS: return nil, fmt.Errorf("no MCP public key found in DNS TXT records") - case auth.MethodGitHubAT, auth.MethodGitHubOIDC, auth.MethodOIDC, auth.MethodNone: + case auth.MethodGitHubAT, auth.MethodGitHubAdmin, auth.MethodGitHubOIDC, auth.MethodOIDC, auth.MethodNone: default: return nil, fmt.Errorf("no MCP public key found using %s authentication", authMethod) } diff --git a/internal/api/handlers/v0/auth/github_admin.go b/internal/api/handlers/v0/auth/github_admin.go new file mode 100644 index 000000000..62079107a --- /dev/null +++ b/internal/api/handlers/v0/auth/github_admin.go @@ -0,0 +1,306 @@ +package auth + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "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" +) + +const ( + githubAdminTimeout = 10 * time.Second + maxGitHubAdminResponse = 1 << 20 + + githubAdminRevokeAttempts = 3 + githubAdminRevokeDelay = 200 * time.Millisecond +) + +var ( + // GitHub allows underscores in team slugs and in managed users' logins. + githubPathName = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) + + // The sign-in script listens on one of these ports on the admin's own + // computer. GitHub Apps need each callback URL to be registered exactly, so + // these match tools/admin/github-login.py and the app's settings. + githubAdminRedirect = regexp.MustCompile(`^http://127\.0\.0\.1:4782[1-3]/callback$`) + + errGitHubUnavailable = errors.New("GitHub is unavailable") +) + +// GitHubAdminTokenExchangeInput is the result of GitHub's web application flow +// with PKCE. +type GitHubAdminTokenExchangeInput struct { + Body struct { + Code string `json:"code" doc:"Authorization code from GitHub" required:"true" minLength:"1" maxLength:"256"` + CodeVerifier string `json:"code_verifier" doc:"PKCE code verifier" required:"true" minLength:"43" maxLength:"128"` + RedirectURI string `json:"redirect_uri" doc:"Loopback redirect URI that received the code" required:"true" maxLength:"64"` + } +} + +// GitHubAdminHandler signs in registry admins: members of a GitHub team. It +// takes an authorization code for its own GitHub app and exchanges it itself. +// It never accepts a GitHub token, so tokens from publishing, the device flow +// or any other app can't be used to become an admin. +type GitHubAdminHandler struct { + config *config.Config + jwtManager *auth.JWTManager + client *http.Client + apiURL string + webURL string + org, team string +} + +// NewGitHubAdminHandler creates a handler for the team in GitHubAdminTeam. +func NewGitHubAdminHandler(cfg *config.Config) (*GitHubAdminHandler, error) { + org, team, _ := strings.Cut(cfg.GitHubAdminTeam, "/") + if !githubPathName.MatchString(org) || !githubPathName.MatchString(team) { + return nil, fmt.Errorf("GitHub admin team must be in the form org/team, got %q", cfg.GitHubAdminTeam) + } + if cfg.GitHubAdminClientID == "" || cfg.GitHubAdminClientSecret == "" { + return nil, errors.New("GitHub admin sign-in needs its own client ID and secret") + } + if cfg.GitHubAdminClientID == cfg.GithubClientID { + return nil, errors.New("GitHub admin sign-in must not use the GitHub app for publishing") + } + return &GitHubAdminHandler{ + config: cfg, + jwtManager: auth.NewJWTManager(cfg), + client: &http.Client{ + Timeout: githubAdminTimeout, + // A redirect could send the app's secret or the user's token elsewhere. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, + apiURL: "https://api.github.com", + webURL: "https://github.com", + org: org, + team: team, + }, nil +} + +// SetBaseURL sets the base URL for GitHub and its API (used for testing) +func (h *GitHubAdminHandler) SetBaseURL(baseURL string) { + h.apiURL, h.webURL = baseURL, baseURL +} + +// RegisterGitHubAdminEndpoint registers admin sign-in if a team is configured. +func RegisterGitHubAdminEndpoint(api huma.API, pathPrefix string, cfg *config.Config) { + if cfg.GitHubAdminTeam == "" { + return + } + handler, err := NewGitHubAdminHandler(cfg) + if err != nil { + panic(err) + } + + huma.Register(api, huma.Operation{ + OperationID: "exchange-github-admin-token" + strings.ReplaceAll(pathPrefix, "/", "-"), + Method: http.MethodPost, + Path: pathPrefix + "/auth/github-admin", + Summary: "Exchange GitHub authorization code for admin Registry JWT", + Description: "Exchange an authorization code and PKCE verifier from this registry's GitHub admin app for a short-lived admin Registry JWT. Only for registry admins.", + Tags: []string{tagAuth}, + }, func(ctx context.Context, input *GitHubAdminTokenExchangeInput) (*v0.Response[auth.TokenResponse], error) { + response, err := handler.ExchangeCode(ctx, input.Body.Code, input.Body.CodeVerifier, input.Body.RedirectURI) + if err != nil { + // As in tokenExchangeError, the details are only logged. + log.Printf("github-admin token exchange failed: %v", err) + if errors.Is(err, errGitHubUnavailable) { + return nil, huma.Error503ServiceUnavailable("GitHub is unavailable, try again later") + } + return nil, huma.Error401Unauthorized("Token exchange failed") + } + return &v0.Response[auth.TokenResponse]{Body: *response}, nil + }) +} + +// ExchangeCode exchanges an authorization code for an admin Registry JWT. It +// fails unless GitHub accepts the code and confirms the user's team membership. +func (h *GitHubAdminHandler) ExchangeCode(ctx context.Context, code, verifier, redirectURI string) (*auth.TokenResponse, error) { + if !githubAdminRedirect.MatchString(redirectURI) { + return nil, errors.New("the redirect URI is not a loopback callback") + } + if len(verifier) < 43 { + return nil, errors.New("a PKCE code verifier is required") + } + // Once GitHub has accepted the code, finish even if the caller goes away, so + // that any token received is revoked. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*githubAdminTimeout) + defer cancel() + githubToken, err := h.exchangeCode(ctx, code, verifier, redirectURI) + if githubToken != "" { + // The token is only needed for the checks below. + defer h.revoke(ctx, githubToken) + } + if err != nil { + return nil, err + } + + login, err := h.currentUser(ctx, githubToken) + if err != nil { + return nil, err + } + if err := h.checkTeamMember(ctx, githubToken, login); err != nil { + return nil, err + } + + response, err := h.jwtManager.GenerateTokenResponse(ctx, auth.JWTClaims{ + AuthMethod: auth.MethodGitHubAdmin, + AuthMethodSubject: login, + Permissions: []auth.Permission{ + {Action: auth.PermissionActionPublish, ResourcePattern: "*"}, + {Action: auth.PermissionActionEdit, ResourcePattern: "*"}, + }, + }) + if err != nil { + return nil, fmt.Errorf("failed to generate JWT token: %w", err) + } + log.Printf("admin sign-in: issued a token to GitHub user %q", login) + return response, nil +} + +// exchangeCode gets the user's token. GitHub only accepts a code that it issued +// to the admin app. If the sign-in started with a PKCE challenge, as it does in +// github-login.py, GitHub also needs the matching verifier. The result can hold +// a token to revoke even if there is an error. +func (h *GitHubAdminHandler) exchangeCode(ctx context.Context, code, verifier, redirectURI string) (string, error) { + form := url.Values{ + "client_id": {h.config.GitHubAdminClientID}, + "client_secret": {h.config.GitHubAdminClientSecret}, + "code": {code}, + "code_verifier": {verifier}, + "redirect_uri": {redirectURI}, + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, h.webURL+"/login/oauth/access_token", strings.NewReader(form.Encode())) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // Without this, GitHub's reply isn't JSON. + req.Header.Set("Accept", "application/json") + // GitHub reports most errors with status 200 and an error field. + var token struct { + AccessToken string `json:"access_token"` + Error string `json:"error"` + } + if err := h.do(req, &token); err != nil { + return "", fmt.Errorf("failed to exchange the authorization code: %w", err) + } + if token.Error != "" || token.AccessToken == "" { + return token.AccessToken, fmt.Errorf("GitHub refused the authorization code: %q", token.Error) + } + return token.AccessToken, nil +} + +// revoke deletes the user's authorization of the app, with all its tokens, so +// that GitHub asks for consent again at the next sign-in. +func (h *GitHubAdminHandler) revoke(ctx context.Context, githubToken string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), githubAdminTimeout) + defer cancel() + var err error + for attempt := range githubAdminRevokeAttempts { + if attempt > 0 { + time.Sleep(githubAdminRevokeDelay) + } + if err = h.deleteGrant(ctx, githubToken); err == nil { + return + } + } + log.Printf("admin sign-in: failed to revoke the GitHub authorization: %v", err) +} + +func (h *GitHubAdminHandler) deleteGrant(ctx context.Context, githubToken string) error { + body, err := json.Marshal(map[string]string{"access_token": githubToken}) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, + h.apiURL+"/applications/"+url.PathEscape(h.config.GitHubAdminClientID)+"/grant", bytes.NewReader(body)) + if err != nil { + return err + } + req.SetBasicAuth(h.config.GitHubAdminClientID, h.config.GitHubAdminClientSecret) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + resp, err := h.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + return fmt.Errorf("status %d", resp.StatusCode) + } + return nil +} + +func (h *GitHubAdminHandler) currentUser(ctx context.Context, githubToken string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.apiURL+"/user", nil) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+githubToken) + var user GitHubUserOrOrg + if err := h.do(req, &user); err != nil { + return "", fmt.Errorf("failed to get the GitHub user: %w", err) + } + if !githubPathName.MatchString(user.Login) { + return "", errors.New("the GitHub token has no valid user") + } + return user.Login, nil +} + +// checkTeamMember asks GitHub, as the user, whether they are an active member. +// GitHub also counts members of child teams. +func (h *GitHubAdminHandler) checkTeamMember(ctx context.Context, githubToken, login string) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, + fmt.Sprintf("%s/orgs/%s/teams/%s/memberships/%s", h.apiURL, h.org, h.team, login), nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+githubToken) + + var membership struct { + State string `json:"state"` + } + if err := h.do(req, &membership); err != nil { + return fmt.Errorf("failed to confirm that GitHub user %q is in the admin team: %w", login, err) + } + if membership.State != githubMembershipStateActive { + return fmt.Errorf("GitHub user %q is not an active member of the admin team", login) + } + return nil +} + +func (h *GitHubAdminHandler) do(req *http.Request, result any) error { + if req.Header.Get("Accept") == "" { + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + } + resp, err := h.client.Do(req) + if err != nil { + return fmt.Errorf("%w: %w", errGitHubUnavailable, err) + } + defer resp.Body.Close() + if resp.StatusCode >= http.StatusInternalServerError || resp.StatusCode == http.StatusTooManyRequests || + (resp.StatusCode == http.StatusForbidden && (resp.Header.Get("X-RateLimit-Remaining") == "0" || resp.Header.Get("Retry-After") != "")) { + return fmt.Errorf("%w: status %d", errGitHubUnavailable, resp.StatusCode) + } + // The body can describe the token, so only the status is reported. + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("GitHub API status %d", resp.StatusCode) + } + return json.NewDecoder(io.LimitReader(resp.Body, maxGitHubAdminResponse)).Decode(result) +} diff --git a/internal/api/handlers/v0/auth/github_admin_test.go b/internal/api/handlers/v0/auth/github_admin_test.go new file mode 100644 index 000000000..7df6dc57d --- /dev/null +++ b/internal/api/handlers/v0/auth/github_admin_test.go @@ -0,0 +1,168 @@ +package auth_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/danielgtaylor/huma/v2" + "github.com/danielgtaylor/huma/v2/adapters/humago" + v0auth "github.com/modelcontextprotocol/registry/internal/api/handlers/v0/auth" + "github.com/modelcontextprotocol/registry/internal/auth" + "github.com/modelcontextprotocol/registry/internal/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func githubAdminConfig() *config.Config { + return &config.Config{ + GithubClientID: "publish-app", + GithubClientSecret: "publish-secret", + GitHubAdminTeam: "example-org/registry_admins", + GitHubAdminClientID: "admin-app", + GitHubAdminClientSecret: "admin-secret", + JWTPrivateKey: strings.Repeat("ab", 32), + } +} + +func TestGitHubAdminExchangeCode(t *testing.T) { + const redirect = "http://127.0.0.1:47821/callback" + const token = `{"access_token":"user-token","token_type":"bearer"}` + const user = `{"login":"alice_corp"}` + const active = `{"state":"active","role":"member"}` + verifier := strings.Repeat("v", 43) + type reply struct { + status int + body string + } + ok := func(body string) reply { return reply{http.StatusOK, body} } + for _, tt := range []struct { + name string + verifier, redirect string + code, user, team reply + revoke int + valid bool + calls string + }{ + {"active member", verifier, redirect, ok(token), ok(user), ok(active), 204, true, "code user team revoke"}, + {"revoke fails", verifier, redirect, ok(token), ok(user), ok(active), 500, true, "code user team revoke revoke revoke"}, + {"no verifier", "", redirect, ok(token), ok(user), ok(active), 204, false, ""}, + {"remote redirect", verifier, "https://example.com/callback", ok(token), ok(user), ok(active), 204, false, ""}, + {"lookalike redirect", verifier, "http://127.0.0.1:1@example.com/callback", ok(token), ok(user), ok(active), 204, false, ""}, + {"localhost redirect", verifier, "http://localhost:47821/callback", ok(token), ok(user), ok(active), 204, false, ""}, + {"unregistered port", verifier, "http://127.0.0.1:47824/callback", ok(token), ok(user), ok(active), 204, false, ""}, + {"redirect from GitHub", verifier, redirect, reply{307, token}, ok(user), ok(active), 204, false, "code"}, + {"redirected user request", verifier, redirect, ok(token), reply{307, user}, ok(active), 204, false, "code user revoke"}, + {"code or verifier refused", verifier, redirect, ok(`{"error":"bad_verification_code"}`), ok(user), ok(active), 204, false, "code"}, + {"error and token", verifier, redirect, ok(`{"error":"x","access_token":"user-token"}`), ok(user), ok(active), 204, false, "code revoke"}, + {"empty code response", verifier, redirect, ok(`{}`), ok(user), ok(active), 204, false, "code"}, + {"code exchange unavailable", verifier, redirect, reply{503, token}, ok(user), ok(active), 204, false, "code"}, + {"no user", verifier, redirect, ok(token), ok(`{}`), ok(active), 204, false, "code user revoke"}, + {"unsafe login", verifier, redirect, ok(token), ok(`{"login":"../x"}`), ok(active), 204, false, "code user revoke"}, + {"pending member", verifier, redirect, ok(token), ok(user), ok(`{"state":"pending"}`), 204, false, "code user team revoke"}, + {"not a member", verifier, redirect, ok(token), ok(user), reply{404, `{}`}, 204, false, "code user team revoke"}, + {"app can't read the team", verifier, redirect, ok(token), ok(user), reply{403, active}, 204, false, "code user team revoke"}, + {"team check unavailable", verifier, redirect, ok(token), ok(user), reply{503, active}, 204, false, "code user team revoke"}, + {"empty team response", verifier, redirect, ok(token), ok(user), ok(`{}`), 204, false, "code user team revoke"}, + {"invalid team response", verifier, redirect, ok(token), ok(user), ok(``), 204, false, "code user team revoke"}, + } { + t.Run(tt.name, func(t *testing.T) { + var calls []string + respond := func(w http.ResponseWriter, name string, r reply) { + calls = append(calls, name) + if r.status == http.StatusTemporaryRedirect { + w.Header().Set("Location", "/redirected") + } + w.WriteHeader(r.status) + _, _ = w.Write([]byte(r.body)) + } + mux := http.NewServeMux() + mux.HandleFunc("/redirected", func(w http.ResponseWriter, _ *http.Request) { + respond(w, "redirected", ok(token)) + }) + mux.HandleFunc("POST /login/oauth/access_token", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "application/json", r.Header.Get("Accept")) + assert.NoError(t, r.ParseForm()) + assert.Equal(t, "admin-app", r.PostForm.Get("client_id")) + assert.Equal(t, "admin-secret", r.PostForm.Get("client_secret")) + assert.Equal(t, "the-code", r.PostForm.Get("code")) + assert.Equal(t, verifier, r.PostForm.Get("code_verifier")) + assert.Equal(t, redirect, r.PostForm.Get("redirect_uri")) + respond(w, "code", tt.code) + }) + mux.HandleFunc("GET /user", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "Bearer user-token", r.Header.Get("Authorization")) + respond(w, "user", tt.user) + }) + mux.HandleFunc("GET /orgs/example-org/teams/registry_admins/memberships/alice_corp", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "Bearer user-token", r.Header.Get("Authorization")) + respond(w, "team", tt.team) + }) + mux.HandleFunc("DELETE /applications/admin-app/grant", func(w http.ResponseWriter, r *http.Request) { + id, secret, _ := r.BasicAuth() + assert.Equal(t, "admin-app:admin-secret", id+":"+secret) + assert.Equal(t, "application/json", r.Header.Get("Content-Type")) + var body map[string]string + assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, "user-token", body["access_token"]) + respond(w, "revoke", reply{tt.revoke, ""}) + }) + github := httptest.NewServer(mux) + defer github.Close() + + cfg := githubAdminConfig() + handler, err := v0auth.NewGitHubAdminHandler(cfg) + require.NoError(t, err) + handler.SetBaseURL(github.URL) + + response, err := handler.ExchangeCode(context.Background(), "the-code", tt.verifier, tt.redirect) + assert.Equal(t, tt.calls, strings.Join(calls, " ")) + if !tt.valid { + require.Error(t, err) + assert.Nil(t, response) + return + } + require.NoError(t, err) + claims, err := auth.NewJWTManager(cfg).ValidateToken(context.Background(), response.RegistryToken) + require.NoError(t, err) + assert.Equal(t, auth.MethodGitHubAdmin, claims.AuthMethod) + assert.Equal(t, "alice_corp", claims.AuthMethodSubject) + assert.ElementsMatch(t, []auth.Permission{ + {Action: auth.PermissionActionPublish, ResourcePattern: "*"}, + {Action: auth.PermissionActionEdit, ResourcePattern: "*"}, + }, claims.Permissions) + }) + } +} + +func TestGitHubAdminConfig(t *testing.T) { + for _, team := range []string{"", "registry-admins", "/registry-admins", "example-org/", "example-org/a/b", "example-org/../x"} { + cfg := githubAdminConfig() + cfg.GitHubAdminTeam = team + _, err := v0auth.NewGitHubAdminHandler(cfg) + require.Error(t, err, team) + } + for name, change := range map[string]func(*config.Config){ + "no client ID": func(c *config.Config) { c.GitHubAdminClientID = "" }, + "no secret": func(c *config.Config) { c.GitHubAdminClientSecret = "" }, + "app for publishing": func(c *config.Config) { c.GitHubAdminClientID = c.GithubClientID }, + } { + cfg := githubAdminConfig() + change(cfg) + _, err := v0auth.NewGitHubAdminHandler(cfg) + require.Error(t, err, name) + } +} + +func TestGitHubAdminEndpointNeedsTeam(t *testing.T) { + for team, registered := range map[string]bool{"": false, "example-org/registry_admins": true} { + cfg := githubAdminConfig() + cfg.GitHubAdminTeam = team + api := humago.New(http.NewServeMux(), huma.DefaultConfig("Test", "1.0.0")) + v0auth.RegisterGitHubAdminEndpoint(api, "/v0", cfg) + assert.Equal(t, registered, api.OpenAPI().Paths["/v0/auth/github-admin"] != nil) + } +} diff --git a/internal/api/handlers/v0/auth/main.go b/internal/api/handlers/v0/auth/main.go index 62d9883d8..d4d1b5f8e 100644 --- a/internal/api/handlers/v0/auth/main.go +++ b/internal/api/handlers/v0/auth/main.go @@ -13,6 +13,9 @@ func RegisterAuthEndpoints(api huma.API, pathPrefix string, cfg *config.Config) // Register GitHub access token authentication endpoint RegisterGitHubATEndpoint(api, pathPrefix, cfg) + // Register GitHub admin authentication endpoint if a team is configured + RegisterGitHubAdminEndpoint(api, pathPrefix, cfg) + // Register GitHub OIDC authentication endpoint RegisterGitHubOIDCEndpoint(api, pathPrefix, cfg) diff --git a/internal/auth/types.go b/internal/auth/types.go index 38b7959ae..9a8a45289 100644 --- a/internal/auth/types.go +++ b/internal/auth/types.go @@ -6,6 +6,8 @@ type Method string const ( // GitHub OAuth authentication (access token) MethodGitHubAT Method = "github-at" + // GitHub authentication for registry admins (authorization code with PKCE, and team membership) + MethodGitHubAdmin Method = "github-admin" // GitHub Actions OIDC authentication MethodGitHubOIDC Method = "github-oidc" // Generic OIDC authentication diff --git a/internal/config/config.go b/internal/config/config.go index d392a9949..c6b676a81 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -31,15 +31,21 @@ func (c *Config) ValidateMalwareCheckMode() error { // Config holds the application configuration // See .env.example for more documentation type Config struct { - ServerAddress string `env:"SERVER_ADDRESS" envDefault:":8080"` - DatabaseURL string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/mcp-registry?sslmode=disable"` - DatabaseMaxConnections int32 `env:"DATABASE_MAX_CONNECTIONS" envDefault:"60"` - DatabaseMinConnections int32 `env:"DATABASE_MIN_CONNECTIONS" envDefault:"10"` - PreparedListingJSON bool `env:"PREPARED_LISTING_JSON" envDefault:"false"` - SeedFrom string `env:"SEED_FROM" envDefault:""` - Version string `env:"VERSION" envDefault:"dev"` - GithubClientID string `env:"GITHUB_CLIENT_ID" envDefault:""` - GithubClientSecret string `env:"GITHUB_CLIENT_SECRET" envDefault:""` + ServerAddress string `env:"SERVER_ADDRESS" envDefault:":8080"` + DatabaseURL string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/mcp-registry?sslmode=disable"` + DatabaseMaxConnections int32 `env:"DATABASE_MAX_CONNECTIONS" envDefault:"60"` + DatabaseMinConnections int32 `env:"DATABASE_MIN_CONNECTIONS" envDefault:"10"` + PreparedListingJSON bool `env:"PREPARED_LISTING_JSON" envDefault:"false"` + SeedFrom string `env:"SEED_FROM" envDefault:""` + Version string `env:"VERSION" envDefault:"dev"` + GithubClientID string `env:"GITHUB_CLIENT_ID" envDefault:""` + GithubClientSecret string `env:"GITHUB_CLIENT_SECRET" envDefault:""` + // GitHubAdminTeam is the GitHub team, as org/team, whose members can sign + // in as registry admins. Unset turns GitHub admin sign-in off. + // It needs a GitHub app of its own, not the one for publishing. + GitHubAdminTeam string `env:"GITHUB_ADMIN_TEAM" envDefault:""` + GitHubAdminClientID string `env:"GITHUB_ADMIN_CLIENT_ID" envDefault:""` + GitHubAdminClientSecret string `env:"GITHUB_ADMIN_CLIENT_SECRET" envDefault:""` JWTPrivateKey string `env:"JWT_PRIVATE_KEY" envDefault:""` EnableAnonymousAuth bool `env:"ENABLE_ANONYMOUS_AUTH" envDefault:"false"` EnableRegistryValidation bool `env:"ENABLE_REGISTRY_VALIDATION" envDefault:"true"` diff --git a/tools/admin/auth.sh b/tools/admin/auth.sh index 8062e4415..db1a9dd12 100755 --- a/tools/admin/auth.sh +++ b/tools/admin/auth.sh @@ -1,28 +1,109 @@ #!/bin/bash -# Simple OIDC authentication helper using gcloud +# Signs in as a registry admin: with GitHub where it is set up, otherwise with gcloud set -euo pipefail REGISTRY_URL="${REGISTRY_URL:-https://registry.modelcontextprotocol.io}" +REGISTRY_URL="${REGISTRY_URL%/}" -if ! gcloud projects list &> /dev/null; then - gcloud auth login >&2 -fi +TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +lower() { + printf '%s' "$1" | tr '[:upper:]' '[:lower:]' +} + +# For our registries, the GitHub app comes from this checkout and never from +# the server, so another server can't ask for a code that works on ours. +stack_client_id() { + local file="$TOOLS_DIR/../../deploy/Pulumi.$1.yaml" line id + line=$(grep -E '^ *mcp-registry:githubAdminClientId:' "$file") || { [ -r "$file" ] && return 0; return 1; } + # As in the deploy code, an empty value means that GitHub sign-in is off + if printf '%s\n' "$line" | grep -qE ":githubAdminClientId: *(\"\"|'')( +#.*)?\$"; then + return 0 + fi + id=$(printf '%s\n' "$line" | sed -nE "s/^[^:]*:[^:]*: *[\"']?([A-Za-z0-9._-]+)[\"']? *(#.*)?\$/\1/p") + if [ -z "$id" ]; then + echo "Error: can't read githubAdminClientId in ${file}" >&2 + return 1 + fi + printf '%s' "$id" +} +PROD_ID=$(stack_client_id gcpProd) +STAGING_ID=$(stack_client_id gcpStaging) -# Get Google Cloud identity token -OIDC_TOKEN=$(gcloud auth print-identity-token) +GOOGLE=false +case "$REGISTRY_URL" in + https://registry.modelcontextprotocol.io | https://prod.registry.modelcontextprotocol.io) + CLIENT_ID="$PROD_ID" + GOOGLE=true + ;; + https://staging.registry.modelcontextprotocol.io) + CLIENT_ID="$STAGING_ID" + GOOGLE=true + ;; + *) + # Letters, digits, dots and hyphens only, so the host can't be disguised + if ! [[ "$REGISTRY_URL" =~ ^(https?)://([A-Za-z0-9.-]+)(:[0-9]+)?$ ]]; then + echo "Error: REGISTRY_URL must look like https://host or https://host:port" >&2 + exit 1 + fi + HOST=$(lower "${BASH_REMATCH[2]}") + case "$HOST" in + localhost | 127.0.0.1) GOOGLE=true ;; + modelcontextprotocol.io* | *.modelcontextprotocol.io*) + echo "Error: use the registry's exact URL, such as https://registry.modelcontextprotocol.io" >&2 + exit 1 + ;; + *) + if [ "${BASH_REMATCH[1]}" != https ]; then + echo "Error: REGISTRY_URL must use https" >&2 + exit 1 + fi + ;; + esac + CLIENT_ID="${GITHUB_ADMIN_CLIENT_ID:-}" + if [ -n "$CLIENT_ID" ]; then + if ! [[ "$CLIENT_ID" =~ ^[A-Za-z0-9._-]+$ ]]; then + echo "Error: GITHUB_ADMIN_CLIENT_ID is not a client ID" >&2 + exit 1 + fi + # Ignore case, in case GitHub does + LOWER_ID=$(lower "$CLIENT_ID") + if [ "$LOWER_ID" = "$(lower "$PROD_ID")" ] || [ "$LOWER_ID" = "$(lower "$STAGING_ID")" ]; then + echo "Error: GITHUB_ADMIN_CLIENT_ID is for another registry" >&2 + exit 1 + fi + fi + ;; +esac + +if [ -n "$CLIENT_ID" ]; then + ENDPOINT=github-admin + BODY=$(python3 "$TOOLS_DIR/github-login.py" "$CLIENT_ID") +elif [ "$GOOGLE" = true ]; then + ENDPOINT=oidc + if ! gcloud projects list &> /dev/null; then + gcloud auth login >&2 + fi + TOKEN=$(gcloud auth print-identity-token) + BODY=$(printf '%s' "$TOKEN" | jq -Rs '{oidc_token: .}') +else + # Our registries accept gcloud's tokens, so don't give one to another server + echo "Error: set GITHUB_ADMIN_CLIENT_ID for ${REGISTRY_URL}" >&2 + exit 1 +fi # Exchange for registry token -RESPONSE=$(curl -sS -X POST "${REGISTRY_URL}/v0/auth/oidc" \ - -H "Content-Type: application/json" \ - -d "{\"oidc_token\": \"${OIDC_TOKEN}\"}") +RESPONSE=$(printf '%s' "$BODY" | curl -sS -X POST "${REGISTRY_URL}/v0/auth/${ENDPOINT}" \ + -H "Content-Type: application/json" --data-binary @-) # Check if successful if ! REGISTRY_TOKEN=$(printf '%s\n' "$RESPONSE" | jq -r '.registry_token // empty' 2>/dev/null); then REGISTRY_TOKEN="" fi -if [ -z "$REGISTRY_TOKEN" ]; then +# The output is run as a command, so only accept the characters of a JWT +if ! [[ "$REGISTRY_TOKEN" =~ ^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$ ]]; then echo "Error: Authentication failed" >&2 if ! printf '%s\n' "$RESPONSE" | jq '.' >&2 2>/dev/null; then printf '%s\n' "$RESPONSE" >&2 diff --git a/tools/admin/github-login.py b/tools/admin/github-login.py new file mode 100755 index 000000000..94eb314b2 --- /dev/null +++ b/tools/admin/github-login.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Signs in to GitHub in the browser, for auth.sh. + +Uses the authorization code flow with PKCE, and receives the code on a +port of 127.0.0.1. Prints the JSON body for POST /v0/auth/github-admin. The +registry exchanges the code, so this script never gets a GitHub token. + +Usage: github-login.py CLIENT_ID +""" +import base64 +import hashlib +import hmac +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +import queue +import secrets +import sys +import threading +from urllib.parse import parse_qs, urlencode, urlsplit +import webbrowser + +AUTHORIZE_URL = 'https://github.com/login/oauth/authorize' +TIMEOUT = 300 +# GitHub Apps need each callback URL to be registered exactly. The registry only +# accepts these too (internal/api/handlers/v0/auth/github_admin.go). +PORTS = (47821, 47822, 47823) + + +def challenge(verifier): + digest = hashlib.sha256(verifier.encode()).digest() + return base64.urlsafe_b64encode(digest).rstrip(b'=').decode() + + +class Callback(BaseHTTPRequestHandler): + timeout = 5 + + def do_GET(self): + url = urlsplit(self.path) + query = parse_qs(url.query) + state = query.get('state', []) + # Ignore anything that isn't the answer to this sign-in. + if (self.headers.get('Host') != self.server.host or url.path != '/callback' or len(state) != 1 + or not hmac.compare_digest(state[0].encode(), self.server.state.encode())): + self.reply(404, 'Not found') + return + code = query.get('code', []) + if len(code) == 1 and 'error' not in query: + result = code[0] + self.reply(200, 'Go back to the terminal. You can close this tab.') + else: + result = None + self.reply(400, 'GitHub sign-in did not finish. Go back to the terminal.') + try: + self.server.results.put_nowait(result) + except queue.Full: + pass # Only the first answer counts. + + def reply(self, status, text): + body = text.encode() + self.send_response(status) + self.send_header('Content-Type', 'text/plain; charset=utf-8') + self.send_header('Content-Length', str(len(body))) + self.send_header('Cache-Control', 'no-store') + self.send_header('Referrer-Policy', 'no-referrer') + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass # The request line holds the code. + + +class Server(ThreadingHTTPServer): + # Reuse a port right after the last sign-in. On Windows, this option would + # let another program share it. + allow_reuse_address = os.name != 'nt' + allow_reuse_port = False + + +def listen(): + for port in PORTS: + try: + return Server(('127.0.0.1', port), Callback) + except OSError: + continue + sys.exit(f'Error: ports {PORTS[0]} to {PORTS[-1]} are all in use') + + +def main(client_id): + # Browsers inherit stdout, which auth.sh reads. Keep it for the result only. + result = os.fdopen(os.dup(1), 'w') + os.set_inheritable(result.fileno(), False) + os.dup2(2, 1) + + verifier = secrets.token_urlsafe(64) + with listen() as server: + server.host = f'127.0.0.1:{server.server_port}' + server.state = secrets.token_urlsafe(32) + server.results = queue.Queue(maxsize=1) + redirect_uri = f'http://{server.host}/callback' + url = AUTHORIZE_URL + '?' + urlencode({ + 'client_id': client_id, + 'redirect_uri': redirect_uri, + 'state': server.state, + 'code_challenge': challenge(verifier), + 'code_challenge_method': 'S256', + 'prompt': 'select_account', + }) + print(f'Sign in with GitHub in your browser, on this computer. If it does not open, go to:\n{url}', file=sys.stderr) + threading.Thread(target=server.serve_forever, daemon=True).start() + # Some browsers block until they are closed. + threading.Thread(target=webbrowser.open, args=(url,), daemon=True).start() + + try: + code = server.results.get(timeout=TIMEOUT) + except queue.Empty: + sys.exit('Error: GitHub sign-in timed out') + if code is None: + sys.exit('Error: GitHub sign-in was canceled or failed') + print(json.dumps({'code': code, 'code_verifier': verifier, 'redirect_uri': redirect_uri}), file=result, flush=True) + os._exit(0) # Don't wait for the browser. + + +if __name__ == '__main__': + if len(sys.argv) != 2: + sys.exit(__doc__) + main(sys.argv[1])