From 7725512e7cfbd4b8bcf004212adaf537389513de Mon Sep 17 00:00:00 2001 From: Den <53200638+localden@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:04:38 +0000 Subject: [PATCH 1/4] Set admin accounts in the stack config --- deploy/Pulumi.gcpProd.yaml | 1 + deploy/Pulumi.gcpStaging.yaml | 1 + deploy/README.md | 1 + deploy/pkg/k8s/admin_accounts.go | 37 +++++++++++++++++ deploy/pkg/k8s/admin_accounts_test.go | 42 ++++++++++++++++++++ deploy/pkg/k8s/production_scaling_test.go | 4 ++ deploy/pkg/k8s/registry.go | 7 +++- docs/administration/admin-operations.md | 2 +- docs/administration/maintainer-onboarding.md | 1 + docs/design/tech-architecture.md | 6 +-- 10 files changed, 97 insertions(+), 5 deletions(-) create mode 100644 deploy/pkg/k8s/admin_accounts.go create mode 100644 deploy/pkg/k8s/admin_accounts_test.go diff --git a/deploy/Pulumi.gcpProd.yaml b/deploy/Pulumi.gcpProd.yaml index 16f654cf4..473eabd48 100644 --- a/deploy/Pulumi.gcpProd.yaml +++ b/deploy/Pulumi.gcpProd.yaml @@ -40,6 +40,7 @@ config: # Daily check of listed packages against OSV malware records; see "Malware sweep" in README.md. mcp-registry:malwareSweep: "true" gcp:project: mcp-registry-prod + mcp-registry:adminAccounts: david@modelcontextprotocol.io,den@modelcontextprotocol.io,radoslav@modelcontextprotocol.io mcp-registry:githubClientId: Iv23liUydBbI7Z2Q9bOZ mcp-registry:githubClientSecret: secure: v1:mSVikc0wDjoN8jCF:ytoI2gZ5WRJN3Fd6s5SRd2fnzirqtFBPSdIshIa2RfnF0OdtDpmucfs5KRw3HoJVGfDTbkrG+Sk= diff --git a/deploy/Pulumi.gcpStaging.yaml b/deploy/Pulumi.gcpStaging.yaml index 0174b79e9..db52bb701 100644 --- a/deploy/Pulumi.gcpStaging.yaml +++ b/deploy/Pulumi.gcpStaging.yaml @@ -19,6 +19,7 @@ config: mcp-registry:postgresSharedBuffers: 512MB mcp-registry:postgresCPULimit: "3" gcp:project: mcp-registry-staging + mcp-registry:adminAccounts: david@modelcontextprotocol.io,den@modelcontextprotocol.io,radoslav@modelcontextprotocol.io mcp-registry:githubClientId: Iv23liB2r5oUw6PxiMOC mcp-registry:githubClientSecret: secure: v1:WRAquCFbMSoG7+iD:LCiTHniEP6eCHeE440q+lI/KqyYvK+0gZ4s4NseM1pN9JgWFt31wRttiQ7nWeHQpf0QEkZFALZY= diff --git a/deploy/README.md b/deploy/README.md index 738762b94..a99e9534f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -492,6 +492,7 @@ 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:adminAccounts` | Comma-separated lowercase @modelcontextprotocol.io accounts that can use [admin operations](../docs/administration/admin-operations.md) | Yes (hosted stacks only) | | `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_accounts.go b/deploy/pkg/k8s/admin_accounts.go new file mode 100644 index 000000000..17ccdad63 --- /dev/null +++ b/deploy/pkg/k8s/admin_accounts.go @@ -0,0 +1,37 @@ +package k8s + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" + + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" +) + +const workspaceDomain = "modelcontextprotocol.io" + +// The registry compares addresses exactly, so only lowercase ones are accepted. +var adminAccount = regexp.MustCompile(`^[a-z0-9][a-z0-9._'-]*@` + regexp.QuoteMeta(workspaceDomain) + `$`) + +// adminClaims returns the OIDC claim rules for admin sign-in, using the +// accounts in mcp-registry:adminAccounts. Hosted stacks must set it. +func adminClaims(conf *config.Config, environment string) (string, error) { + rule := map[string]any{"hd": workspaceDomain} + if configured := conf.Get("adminAccounts"); configured != "" { + accounts := strings.Split(configured, ",") + for i, account := range accounts { + accounts[i] = strings.TrimSpace(account) + if !adminAccount.MatchString(accounts[i]) { + return "", fmt.Errorf("mcp-registry:adminAccounts: %q is not a lowercase %s address", accounts[i], workspaceDomain) + } + } + rule["email"] = accounts + rule["email_verified"] = true + } else if environment != "local" { + return "", errors.New("mcp-registry:adminAccounts is required") + } + claims, err := json.Marshal([]map[string]any{rule}) + return string(claims), err +} diff --git a/deploy/pkg/k8s/admin_accounts_test.go b/deploy/pkg/k8s/admin_accounts_test.go new file mode 100644 index 000000000..df564d337 --- /dev/null +++ b/deploy/pkg/k8s/admin_accounts_test.go @@ -0,0 +1,42 @@ +package k8s //nolint:testpackage // Check stack configuration without deploying. + +import ( + "testing" + + "github.com/pulumi/pulumi/sdk/v3/go/pulumi" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" +) + +func TestAdminClaims(t *testing.T) { + for _, tc := range []struct { + name, environment, accounts, want string + wantErr bool + }{ + {"accounts", "prod", "a@modelcontextprotocol.io, b@modelcontextprotocol.io", + `[{"email":["a@modelcontextprotocol.io","b@modelcontextprotocol.io"],"email_verified":true,"hd":"modelcontextprotocol.io"}]`, false}, + {"local default", "local", "", `[{"hd":"modelcontextprotocol.io"}]`, false}, + {"required in prod", "prod", "", "", true}, + {"required in staging", "staging", "", "", true}, + {"other domain", "prod", "a@example.com", "", true}, + {"no account name", "prod", "@modelcontextprotocol.io", "", true}, + {"uppercase", "prod", "A@modelcontextprotocol.io", "", true}, + {"wildcard", "prod", "*@modelcontextprotocol.io", "", true}, + {"inner space", "prod", "a @modelcontextprotocol.io", "", true}, + {"trailing comma", "prod", "a@modelcontextprotocol.io,", "", true}, + } { + t.Run(tc.name, func(t *testing.T) { + err := pulumi.RunErr(func(ctx *pulumi.Context) error { + got, err := adminClaims(config.New(ctx, "mcp-registry"), tc.environment) + if (err != nil) != tc.wantErr || got != tc.want { + t.Errorf("adminClaims() = %q, %v", got, err) + } + return nil + }, pulumi.WithMocks("admin-accounts-test", "staging", ownershipMonitor{t}), func(info *pulumi.RunInfo) { + info.Config = map[string]string{"mcp-registry:adminAccounts": tc.accounts} + }) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/deploy/pkg/k8s/production_scaling_test.go b/deploy/pkg/k8s/production_scaling_test.go index 388d21a65..f1ff02a39 100644 --- a/deploy/pkg/k8s/production_scaling_test.go +++ b/deploy/pkg/k8s/production_scaling_test.go @@ -103,6 +103,9 @@ func (m *productionScalingMonitor) NewResource(a pulumi.MockResourceArgs) (strin env[v["name"].StringValue()] = v["value"].StringValue() } } + if env["MCP_REGISTRY_OIDC_EXTRA_CLAIMS"] != `[{"email":["admin@modelcontextprotocol.io"],"email_verified":true,"hd":"modelcontextprotocol.io"}]` { + m.t.Error("admin accounts missing from the sign-in rules") + } if env["MCP_REGISTRY_DATABASE_MAX_CONNECTIONS"] != expectedPool || env["MCP_REGISTRY_DATABASE_MIN_CONNECTIONS"] != "5" || env["MCP_REGISTRY_PREPARED_LISTING_JSON"] != "true" { m.t.Error("missing bounded pools or changed prepared reads") } @@ -165,6 +168,7 @@ func TestProductionScalingRendersPreparationAndActivation(t *testing.T) { return err }, pulumi.WithMocks("scaling-test", "prod", m), func(info *pulumi.RunInfo) { info.Config = productionScalingConfig(phase) + info.Config["mcp-registry:adminAccounts"] = "admin@modelcontextprotocol.io" if profile.packed { info.Config["mcp-registry:productionPackedPlacement"] = "true" info.Config["mcp-registry:gatewayProductionPhase"] = "standalone" diff --git a/deploy/pkg/k8s/registry.go b/deploy/pkg/k8s/registry.go index 9d7912be4..580ae7022 100644 --- a/deploy/pkg/k8s/registry.go +++ b/deploy/pkg/k8s/registry.go @@ -183,6 +183,11 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }) } + oidcClaims, err := adminClaims(conf, environment) + if err != nil { + return nil, err + } + // Create Deployment _, err = v1.NewDeployment(ctx, "mcp-registry", &v1.DeploymentArgs{ Metadata: &metav1.ObjectMetaArgs{ @@ -283,7 +288,7 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_EXTRA_CLAIMS"), - Value: pulumi.String(`[{"hd":"modelcontextprotocol.io"}]`), + Value: pulumi.String(oidcClaims), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_EDIT_PERMISSIONS"), diff --git a/docs/administration/admin-operations.md b/docs/administration/admin-operations.md index 646a2eb67..cabe150c3 100644 --- a/docs/administration/admin-operations.md +++ b/docs/administration/admin-operations.md @@ -4,7 +4,7 @@ This is a brief guide for admins and moderators managing content on the registry ## Prerequisites -- Admin account with @modelcontextprotocol.io email +- @modelcontextprotocol.io account listed in `mcp-registry:adminAccounts` in the stack files under `deploy/` - If you are a maintainer and would like an account, ask in the Discord - `gcloud` CLI installed and configured - `curl` and `jq` installed diff --git a/docs/administration/maintainer-onboarding.md b/docs/administration/maintainer-onboarding.md index aab0beaa8..4afffc92c 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, add their account to `mcp-registry:adminAccounts` in both hosted stack files in `deploy/` ### 2. MAINTAINERS.md diff --git a/docs/design/tech-architecture.md b/docs/design/tech-architecture.md index f7fab724f..bc83dddbf 100644 --- a/docs/design/tech-architecture.md +++ b/docs/design/tech-architecture.md @@ -186,7 +186,7 @@ sequenceDiagram ### 4. Admin OIDC Authentication Flow -For registry administration, users with @modelcontextprotocol.io Google Cloud Identity accounts can authenticate using OIDC: +For registry administration, the @modelcontextprotocol.io Google accounts in `mcp-registry:adminAccounts` can authenticate using OIDC: ```mermaid sequenceDiagram @@ -197,10 +197,10 @@ sequenceDiagram Admin->>CLI: Request admin token CLI->>GCP: gcloud auth print-identity-token --audiences=mcp-registry - GCP-->>CLI: ID Token (with hd: "modelcontextprotocol.io") + GCP-->>CLI: ID Token (with email and hd claims) 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: Validate claims (issuer, audience, email, hd) API->>API: Grant admin permissions (edit: *, publish: *) API-->>CLI: Registry JWT Token CLI->>API: POST /admin/* (with Registry JWT) From a8c3d9e2a2545828013ba079ccdb5d793abfa9f5 Mon Sep 17 00:00:00 2001 From: Den <53200638+localden@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:54:47 +0000 Subject: [PATCH 2/4] Use the registry-admins group for admin sign-in --- deploy/Pulumi.gcpProd.yaml | 2 +- deploy/Pulumi.gcpStaging.yaml | 2 +- deploy/README.md | 2 +- deploy/pkg/k8s/admin_accounts.go | 37 ----------------- deploy/pkg/k8s/admin_accounts_test.go | 42 -------------------- deploy/pkg/k8s/admin_login.go | 35 ++++++++++++++++ deploy/pkg/k8s/admin_login_test.go | 38 ++++++++++++++++++ deploy/pkg/k8s/production_scaling_test.go | 7 ++-- deploy/pkg/k8s/registry.go | 13 ++---- docs/administration/admin-operations.md | 6 ++- docs/administration/maintainer-onboarding.md | 2 +- docs/design/tech-architecture.md | 14 ++++--- tools/admin/auth.sh | 27 ++++++++++++- 13 files changed, 122 insertions(+), 105 deletions(-) delete mode 100644 deploy/pkg/k8s/admin_accounts.go delete mode 100644 deploy/pkg/k8s/admin_accounts_test.go create mode 100644 deploy/pkg/k8s/admin_login.go create mode 100644 deploy/pkg/k8s/admin_login_test.go diff --git a/deploy/Pulumi.gcpProd.yaml b/deploy/Pulumi.gcpProd.yaml index 473eabd48..ee3a8a481 100644 --- a/deploy/Pulumi.gcpProd.yaml +++ b/deploy/Pulumi.gcpProd.yaml @@ -40,7 +40,7 @@ config: # Daily check of listed packages against OSV malware records; see "Malware sweep" in README.md. mcp-registry:malwareSweep: "true" gcp:project: mcp-registry-prod - mcp-registry:adminAccounts: david@modelcontextprotocol.io,den@modelcontextprotocol.io,radoslav@modelcontextprotocol.io + mcp-registry:adminServiceAccount: registry-admin@mcp-registry-prod.iam.gserviceaccount.com mcp-registry:githubClientId: Iv23liUydBbI7Z2Q9bOZ mcp-registry:githubClientSecret: secure: v1:mSVikc0wDjoN8jCF:ytoI2gZ5WRJN3Fd6s5SRd2fnzirqtFBPSdIshIa2RfnF0OdtDpmucfs5KRw3HoJVGfDTbkrG+Sk= diff --git a/deploy/Pulumi.gcpStaging.yaml b/deploy/Pulumi.gcpStaging.yaml index db52bb701..aae304af2 100644 --- a/deploy/Pulumi.gcpStaging.yaml +++ b/deploy/Pulumi.gcpStaging.yaml @@ -19,7 +19,7 @@ config: mcp-registry:postgresSharedBuffers: 512MB mcp-registry:postgresCPULimit: "3" gcp:project: mcp-registry-staging - mcp-registry:adminAccounts: david@modelcontextprotocol.io,den@modelcontextprotocol.io,radoslav@modelcontextprotocol.io + mcp-registry:adminServiceAccount: registry-admin@mcp-registry-staging.iam.gserviceaccount.com mcp-registry:githubClientId: Iv23liB2r5oUw6PxiMOC mcp-registry:githubClientSecret: secure: v1:WRAquCFbMSoG7+iD:LCiTHniEP6eCHeE440q+lI/KqyYvK+0gZ4s4NseM1pN9JgWFt31wRttiQ7nWeHQpf0QEkZFALZY= diff --git a/deploy/README.md b/deploy/README.md index a99e9534f..a568fac77 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -492,7 +492,7 @@ 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:adminAccounts` | Comma-separated lowercase @modelcontextprotocol.io accounts that can use [admin operations](../docs/administration/admin-operations.md) | Yes (hosted stacks only) | +| `mcp-registry:adminServiceAccount` | Service account used for [admin sign-in](../docs/administration/admin-operations.md#authentication). Enable the IAM Service Account Credentials API, then give the `registry-admins` group `roles/iam.serviceAccountTokenCreator` on this account only. The account needs no project roles or keys | Yes (hosted stacks only) | | `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_accounts.go b/deploy/pkg/k8s/admin_accounts.go deleted file mode 100644 index 17ccdad63..000000000 --- a/deploy/pkg/k8s/admin_accounts.go +++ /dev/null @@ -1,37 +0,0 @@ -package k8s - -import ( - "encoding/json" - "errors" - "fmt" - "regexp" - "strings" - - "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" -) - -const workspaceDomain = "modelcontextprotocol.io" - -// The registry compares addresses exactly, so only lowercase ones are accepted. -var adminAccount = regexp.MustCompile(`^[a-z0-9][a-z0-9._'-]*@` + regexp.QuoteMeta(workspaceDomain) + `$`) - -// adminClaims returns the OIDC claim rules for admin sign-in, using the -// accounts in mcp-registry:adminAccounts. Hosted stacks must set it. -func adminClaims(conf *config.Config, environment string) (string, error) { - rule := map[string]any{"hd": workspaceDomain} - if configured := conf.Get("adminAccounts"); configured != "" { - accounts := strings.Split(configured, ",") - for i, account := range accounts { - accounts[i] = strings.TrimSpace(account) - if !adminAccount.MatchString(accounts[i]) { - return "", fmt.Errorf("mcp-registry:adminAccounts: %q is not a lowercase %s address", accounts[i], workspaceDomain) - } - } - rule["email"] = accounts - rule["email_verified"] = true - } else if environment != "local" { - return "", errors.New("mcp-registry:adminAccounts is required") - } - claims, err := json.Marshal([]map[string]any{rule}) - return string(claims), err -} diff --git a/deploy/pkg/k8s/admin_accounts_test.go b/deploy/pkg/k8s/admin_accounts_test.go deleted file mode 100644 index df564d337..000000000 --- a/deploy/pkg/k8s/admin_accounts_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package k8s //nolint:testpackage // Check stack configuration without deploying. - -import ( - "testing" - - "github.com/pulumi/pulumi/sdk/v3/go/pulumi" - "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" -) - -func TestAdminClaims(t *testing.T) { - for _, tc := range []struct { - name, environment, accounts, want string - wantErr bool - }{ - {"accounts", "prod", "a@modelcontextprotocol.io, b@modelcontextprotocol.io", - `[{"email":["a@modelcontextprotocol.io","b@modelcontextprotocol.io"],"email_verified":true,"hd":"modelcontextprotocol.io"}]`, false}, - {"local default", "local", "", `[{"hd":"modelcontextprotocol.io"}]`, false}, - {"required in prod", "prod", "", "", true}, - {"required in staging", "staging", "", "", true}, - {"other domain", "prod", "a@example.com", "", true}, - {"no account name", "prod", "@modelcontextprotocol.io", "", true}, - {"uppercase", "prod", "A@modelcontextprotocol.io", "", true}, - {"wildcard", "prod", "*@modelcontextprotocol.io", "", true}, - {"inner space", "prod", "a @modelcontextprotocol.io", "", true}, - {"trailing comma", "prod", "a@modelcontextprotocol.io,", "", true}, - } { - t.Run(tc.name, func(t *testing.T) { - err := pulumi.RunErr(func(ctx *pulumi.Context) error { - got, err := adminClaims(config.New(ctx, "mcp-registry"), tc.environment) - if (err != nil) != tc.wantErr || got != tc.want { - t.Errorf("adminClaims() = %q, %v", got, err) - } - return nil - }, pulumi.WithMocks("admin-accounts-test", "staging", ownershipMonitor{t}), func(info *pulumi.RunInfo) { - info.Config = map[string]string{"mcp-registry:adminAccounts": tc.accounts} - }) - if err != nil { - t.Fatal(err) - } - }) - } -} diff --git a/deploy/pkg/k8s/admin_login.go b/deploy/pkg/k8s/admin_login.go new file mode 100644 index 000000000..a96011c6c --- /dev/null +++ b/deploy/pkg/k8s/admin_login.go @@ -0,0 +1,35 @@ +package k8s + +import ( + "encoding/json" + "fmt" + "regexp" + + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" +) + +var serviceAccountEmail = regexp.MustCompile(`^[a-z][a-z0-9-]{4,28}[a-z0-9]@[a-z][a-z0-9-]{4,28}[a-z0-9]\.iam\.gserviceaccount\.com$`) + +// registryURL is the public address of an environment. Tokens exchanged with +// that environment must be issued for it. +func registryURL(environment string) string { + if environment == "prod" { + return "https://registry.modelcontextprotocol.io" + } + return "https://" + environment + ".registry.modelcontextprotocol.io" +} + +// adminLogin returns the audience and claim rules for admin sign-in. Admins +// request a token for mcp-registry:adminServiceAccount, and IAM, including +// inherited grants, decides who can. Hosted stacks must set it. +func adminLogin(conf *config.Config, environment string) (audience, claims string, err error) { + account := conf.Get("adminServiceAccount") + if account == "" && environment == "local" { + return "32555940559.apps.googleusercontent.com", `[{"hd":"modelcontextprotocol.io"}]`, nil + } + if !serviceAccountEmail.MatchString(account) { + return "", "", fmt.Errorf("mcp-registry:adminServiceAccount must be a service account email, got %q", account) + } + rules, err := json.Marshal([]map[string]any{{"email": account, "email_verified": true}}) + return registryURL(environment), string(rules), err +} diff --git a/deploy/pkg/k8s/admin_login_test.go b/deploy/pkg/k8s/admin_login_test.go new file mode 100644 index 000000000..746d2080a --- /dev/null +++ b/deploy/pkg/k8s/admin_login_test.go @@ -0,0 +1,38 @@ +package k8s //nolint:testpackage // Check stack configuration without deploying. + +import ( + "testing" + + "github.com/pulumi/pulumi/sdk/v3/go/pulumi" + "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config" +) + +func TestAdminLogin(t *testing.T) { + const account = "registry-admin@mcp-registry-prod.iam.gserviceaccount.com" + const rules = `[{"email":"` + account + `","email_verified":true}]` + for _, tc := range []struct{ name, environment, account, audience, claims string }{ + {"prod", "prod", account, "https://registry.modelcontextprotocol.io", rules}, + {"staging", "staging", account, "https://staging.registry.modelcontextprotocol.io", rules}, + {"local default", "local", "", "32555940559.apps.googleusercontent.com", `[{"hd":"modelcontextprotocol.io"}]`}, + {"required in prod", "prod", "", "", ""}, + {"required in staging", "staging", "", "", ""}, + {"user account", "prod", "someone@modelcontextprotocol.io", "", ""}, + {"no account name", "prod", "@mcp-registry-prod.iam.gserviceaccount.com", "", ""}, + {"other suffix", "prod", account + ".example.com", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + err := pulumi.RunErr(func(ctx *pulumi.Context) error { + audience, claims, err := adminLogin(config.New(ctx, "mcp-registry"), tc.environment) + if (err != nil) != (tc.audience == "") || audience != tc.audience || claims != tc.claims { + t.Errorf("adminLogin() = %q, %q, %v", audience, claims, err) + } + return nil + }, pulumi.WithMocks("admin-login-test", "staging", ownershipMonitor{t}), func(info *pulumi.RunInfo) { + info.Config = map[string]string{"mcp-registry:adminServiceAccount": tc.account} + }) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/deploy/pkg/k8s/production_scaling_test.go b/deploy/pkg/k8s/production_scaling_test.go index f1ff02a39..d3ee4d38a 100644 --- a/deploy/pkg/k8s/production_scaling_test.go +++ b/deploy/pkg/k8s/production_scaling_test.go @@ -103,8 +103,9 @@ func (m *productionScalingMonitor) NewResource(a pulumi.MockResourceArgs) (strin env[v["name"].StringValue()] = v["value"].StringValue() } } - if env["MCP_REGISTRY_OIDC_EXTRA_CLAIMS"] != `[{"email":["admin@modelcontextprotocol.io"],"email_verified":true,"hd":"modelcontextprotocol.io"}]` { - m.t.Error("admin accounts missing from the sign-in rules") + if env["MCP_REGISTRY_OIDC_CLIENT_ID"] != "https://registry.modelcontextprotocol.io" || + env["MCP_REGISTRY_OIDC_EXTRA_CLAIMS"] != `[{"email":"registry-admin@mcp-registry-prod.iam.gserviceaccount.com","email_verified":true}]` { + m.t.Error("admin service account missing from the sign-in rules") } if env["MCP_REGISTRY_DATABASE_MAX_CONNECTIONS"] != expectedPool || env["MCP_REGISTRY_DATABASE_MIN_CONNECTIONS"] != "5" || env["MCP_REGISTRY_PREPARED_LISTING_JSON"] != "true" { m.t.Error("missing bounded pools or changed prepared reads") @@ -168,7 +169,7 @@ func TestProductionScalingRendersPreparationAndActivation(t *testing.T) { return err }, pulumi.WithMocks("scaling-test", "prod", m), func(info *pulumi.RunInfo) { info.Config = productionScalingConfig(phase) - info.Config["mcp-registry:adminAccounts"] = "admin@modelcontextprotocol.io" + info.Config["mcp-registry:adminServiceAccount"] = "registry-admin@mcp-registry-prod.iam.gserviceaccount.com" if profile.packed { info.Config["mcp-registry:productionPackedPlacement"] = "true" info.Config["mcp-registry:gatewayProductionPhase"] = "standalone" diff --git a/deploy/pkg/k8s/registry.go b/deploy/pkg/k8s/registry.go index 580ae7022..2ea51ef56 100644 --- a/deploy/pkg/k8s/registry.go +++ b/deploy/pkg/k8s/registry.go @@ -183,7 +183,7 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }) } - oidcClaims, err := adminClaims(conf, environment) + oidcAudience, oidcClaims, err := adminLogin(conf, environment) if err != nil { return nil, err } @@ -284,7 +284,7 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_CLIENT_ID"), - Value: pulumi.String("32555940559.apps.googleusercontent.com"), + Value: pulumi.String(oidcAudience), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_EXTRA_CLAIMS"), @@ -299,13 +299,8 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env Value: pulumi.String("*"), }, &corev1.EnvVarArgs{ - Name: pulumi.String("MCP_REGISTRY_GITHUB_OIDC_AUDIENCE"), - Value: pulumi.String(func() string { - if environment == "prod" { - return "https://registry.modelcontextprotocol.io" - } - return "https://" + environment + ".registry.modelcontextprotocol.io" - }()), + Name: pulumi.String("MCP_REGISTRY_GITHUB_OIDC_AUDIENCE"), + Value: pulumi.String(registryURL(environment)), }, }, poolEnv...), // StartupProbe protects the DB-retry budget in cmd/registry/main.go: diff --git a/docs/administration/admin-operations.md b/docs/administration/admin-operations.md index cabe150c3..8c93a1632 100644 --- a/docs/administration/admin-operations.md +++ b/docs/administration/admin-operations.md @@ -4,8 +4,8 @@ This is a brief guide for admins and moderators managing content on the registry ## Prerequisites -- @modelcontextprotocol.io account listed in `mcp-registry:adminAccounts` in the stack files under `deploy/` - - If you are a maintainer and would like an account, ask in the Discord +- Member of the `registry-admins` Google group, managed with the `registry-admins` role in the [access repository](https://github.com/modelcontextprotocol/access) + - If you are a maintainer and need access, ask in the Discord - `gcloud` CLI installed and configured - `curl` and `jq` installed - `kubectl` installed with `gke-gcloud-auth-plugin` (for database access) @@ -19,6 +19,8 @@ A takedown made with global registry edit permission places a hold on the affect ./tools/admin/auth.sh ``` +The script signs you in with a token for the environment's `registry-admin` service account, which the `registry-admins` group can request. New members may need to wait for the group change to reach Google Cloud. The active `gcloud` account must be the one in the group; switch with `gcloud config set account`. Set `REGISTRY_URL` to use staging. For another registry with an admin service account, also set `ADMIN_SERVICE_ACCOUNT`, and `ADMIN_AUDIENCE` if it differs from `REGISTRY_URL`. + ## 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 4afffc92c..28bfa37ae 100644 --- a/docs/administration/maintainer-onboarding.md +++ b/docs/administration/maintainer-onboarding.md @@ -9,7 +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, add their account to `mcp-registry:adminAccounts` in both hosted stack files in `deploy/` +- [ ] 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 bc83dddbf..4f0199f87 100644 --- a/docs/design/tech-architecture.md +++ b/docs/design/tech-architecture.md @@ -186,7 +186,7 @@ sequenceDiagram ### 4. Admin OIDC Authentication Flow -For registry administration, the @modelcontextprotocol.io Google accounts in `mcp-registry:adminAccounts` can authenticate using OIDC: +For registry administration, members of the `registry-admins` Google group authenticate using OIDC, with a token for the service account in `mcp-registry:adminServiceAccount`: ```mermaid sequenceDiagram @@ -196,11 +196,11 @@ sequenceDiagram 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 email and hd claims) + CLI->>GCP: Request service account ID token for the registry URL + GCP-->>CLI: ID Token (with the service account email) CLI->>API: POST /v0.1/auth/oidc {"oidc_token": "eyJ..."} API->>GCP: Verify token signature (JWKS) - API->>API: Validate claims (issuer, audience, email, hd) + API->>API: Validate claims (issuer, audience, email) API->>API: Grant admin permissions (edit: *, publish: *) API-->>CLI: Registry JWT Token CLI->>API: POST /admin/* (with Registry JWT) @@ -210,8 +210,10 @@ sequenceDiagram **Usage:** ```bash -# Get Google Cloud Identity token -ID_TOKEN=$(gcloud auth print-identity-token) +# Get a token for the admin service account +ID_TOKEN=$(gcloud auth print-identity-token \ + --impersonate-service-account="$ADMIN_SERVICE_ACCOUNT" \ + --audiences="$REGISTRY_URL" --include-email) # Exchange for Registry JWT token REGISTRY_TOKEN=$(curl -X POST /v0.1/auth/oidc \ diff --git a/tools/admin/auth.sh b/tools/admin/auth.sh index 8062e4415..d2fb45831 100755 --- a/tools/admin/auth.sh +++ b/tools/admin/auth.sh @@ -4,13 +4,36 @@ set -euo pipefail REGISTRY_URL="${REGISTRY_URL:-https://registry.modelcontextprotocol.io}" +REGISTRY_URL="${REGISTRY_URL%/}" + +ADMIN_SERVICE_ACCOUNT="${ADMIN_SERVICE_ACCOUNT:-}" +ADMIN_AUDIENCE="${ADMIN_AUDIENCE:-}" + +# Keep these accounts in step with mcp-registry:adminServiceAccount in deploy/ +case "$REGISTRY_URL" in + https://registry.modelcontextprotocol.io | https://prod.registry.modelcontextprotocol.io) + : "${ADMIN_SERVICE_ACCOUNT:=registry-admin@mcp-registry-prod.iam.gserviceaccount.com}" + : "${ADMIN_AUDIENCE:=https://registry.modelcontextprotocol.io}" + ;; + https://staging.registry.modelcontextprotocol.io) + : "${ADMIN_SERVICE_ACCOUNT:=registry-admin@mcp-registry-staging.iam.gserviceaccount.com}" + ;; +esac if ! gcloud projects list &> /dev/null; then gcloud auth login >&2 fi -# Get Google Cloud identity token -OIDC_TOKEN=$(gcloud auth print-identity-token) +if [ -n "$ADMIN_SERVICE_ACCOUNT" ]; then + # Get an identity token for the admin service account, valid only for this registry + OIDC_TOKEN=$(gcloud auth print-identity-token \ + --impersonate-service-account="$ADMIN_SERVICE_ACCOUNT" \ + --audiences="${ADMIN_AUDIENCE:-$REGISTRY_URL}" \ + --include-email) +else + # Registries without an admin service account, such as local ones + OIDC_TOKEN=$(gcloud auth print-identity-token) +fi # Exchange for registry token RESPONSE=$(curl -sS -X POST "${REGISTRY_URL}/v0/auth/oidc" \ From 9c047a18920b1070c22aa4ba074ced327477e67c Mon Sep 17 00:00:00 2001 From: Den <53200638+localden@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:17:41 +0000 Subject: [PATCH 3/4] Add GitHub sign-in for registry admins --- .env.example | 10 + deploy/Pulumi.gcpProd.yaml | 1 - deploy/Pulumi.gcpStaging.yaml | 1 - deploy/README.md | 3 +- deploy/pkg/k8s/admin_login.go | 63 +++-- deploy/pkg/k8s/admin_login_test.go | 51 ++-- deploy/pkg/k8s/production_scaling_test.go | 5 - deploy/pkg/k8s/registry.go | 42 ++-- docker-compose.yml | 3 + docs/administration/admin-operations.md | 6 +- docs/design/tech-architecture.md | 44 ++-- docs/reference/api/official-registry-api.md | 3 +- internal/api/handlers/v0/auth/common.go | 2 +- internal/api/handlers/v0/auth/github_admin.go | 221 ++++++++++++++++++ .../api/handlers/v0/auth/github_admin_test.go | 141 +++++++++++ internal/api/handlers/v0/auth/main.go | 3 + internal/auth/types.go | 2 + internal/config/config.go | 24 +- tools/admin/auth.sh | 82 +++++-- 19 files changed, 574 insertions(+), 133 deletions(-) create mode 100644 internal/api/handlers/v0/auth/github_admin.go create mode 100644 internal/api/handlers/v0/auth/github_admin_test.go diff --git a/.env.example b/.env.example index 76c064ac0..31065db2e 100644 --- a/.env.example +++ b/.env.example @@ -57,6 +57,16 @@ 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 device flow, read access +# to organization members, and to be installed on the team's organization. +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/Pulumi.gcpProd.yaml b/deploy/Pulumi.gcpProd.yaml index ee3a8a481..16f654cf4 100644 --- a/deploy/Pulumi.gcpProd.yaml +++ b/deploy/Pulumi.gcpProd.yaml @@ -40,7 +40,6 @@ config: # Daily check of listed packages against OSV malware records; see "Malware sweep" in README.md. mcp-registry:malwareSweep: "true" gcp:project: mcp-registry-prod - mcp-registry:adminServiceAccount: registry-admin@mcp-registry-prod.iam.gserviceaccount.com mcp-registry:githubClientId: Iv23liUydBbI7Z2Q9bOZ mcp-registry:githubClientSecret: secure: v1:mSVikc0wDjoN8jCF:ytoI2gZ5WRJN3Fd6s5SRd2fnzirqtFBPSdIshIa2RfnF0OdtDpmucfs5KRw3HoJVGfDTbkrG+Sk= diff --git a/deploy/Pulumi.gcpStaging.yaml b/deploy/Pulumi.gcpStaging.yaml index aae304af2..0174b79e9 100644 --- a/deploy/Pulumi.gcpStaging.yaml +++ b/deploy/Pulumi.gcpStaging.yaml @@ -19,7 +19,6 @@ config: mcp-registry:postgresSharedBuffers: 512MB mcp-registry:postgresCPULimit: "3" gcp:project: mcp-registry-staging - mcp-registry:adminServiceAccount: registry-admin@mcp-registry-staging.iam.gserviceaccount.com mcp-registry:githubClientId: Iv23liB2r5oUw6PxiMOC mcp-registry:githubClientSecret: secure: v1:WRAquCFbMSoG7+iD:LCiTHniEP6eCHeE440q+lI/KqyYvK+0gZ4s4NseM1pN9JgWFt31wRttiQ7nWeHQpf0QEkZFALZY= diff --git a/deploy/README.md b/deploy/README.md index a568fac77..f4e7b6baf 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -492,7 +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:adminServiceAccount` | Service account used for [admin sign-in](../docs/administration/admin-operations.md#authentication). Enable the IAM Service Account Credentials API, then give the `registry-admins` group `roles/iam.serviceAccountTokenCreator` on this account only. The account needs no project roles or keys | Yes (hosted stacks only) | +| `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 device flow, read access to organization members, and to be installed on the organization | 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 index a96011c6c..9b483d145 100644 --- a/deploy/pkg/k8s/admin_login.go +++ b/deploy/pkg/k8s/admin_login.go @@ -1,35 +1,52 @@ package k8s import ( - "encoding/json" - "fmt" - "regexp" + "errors" + "strconv" + 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" ) -var serviceAccountEmail = regexp.MustCompile(`^[a-z][a-z0-9-]{4,28}[a-z0-9]@[a-z][a-z0-9-]{4,28}[a-z0-9]\.iam\.gserviceaccount\.com$`) +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 +) -// registryURL is the public address of an environment. Tokens exchanged with -// that environment must be issued for it. -func registryURL(environment string) string { - if environment == "prod" { - return "https://registry.modelcontextprotocol.io" +// 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, and returns the settings for the registry container. +func adminLogin(conf *config.Config, environment string, secrets pulumi.StringMap, secretName pulumi.StringPtrInput) (corev1.EnvVarArray, error) { + clientID := conf.Get("githubAdminClientId") + env := corev1.EnvVarArray{&corev1.EnvVarArgs{ + Name: pulumi.String("MCP_REGISTRY_OIDC_ENABLED"), + Value: pulumi.String(strconv.FormatBool(clientID == "")), + }} + if clientID == "" { + return env, nil } - return "https://" + environment + ".registry.modelcontextprotocol.io" -} - -// adminLogin returns the audience and claim rules for admin sign-in. Admins -// request a token for mcp-registry:adminServiceAccount, and IAM, including -// inherited grants, decides who can. Hosted stacks must set it. -func adminLogin(conf *config.Config, environment string) (audience, claims string, err error) { - account := conf.Get("adminServiceAccount") - if account == "" && environment == "local" { - return "32555940559.apps.googleusercontent.com", `[{"hd":"modelcontextprotocol.io"}]`, nil + if clientID == conf.Get("githubClientId") { + return nil, errors.New("githubAdminClientId must not be the GitHub app for publishing") } - if !serviceAccountEmail.MatchString(account) { - return "", "", fmt.Errorf("mcp-registry:adminServiceAccount must be a service account email, got %q", account) + // 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 nil, errors.New("githubAdminClientId requires an imageTag after " + lastGoogleOnlyRelease) } - rules, err := json.Marshal([]map[string]any{{"email": account, "email_verified": true}}) - return registryURL(environment), string(rules), err + secrets[githubAdminSecretKey] = conf.RequireSecret("githubAdminClientSecret") + return append(env, + &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 index 746d2080a..eb27d1f4c 100644 --- a/deploy/pkg/k8s/admin_login_test.go +++ b/deploy/pkg/k8s/admin_login_test.go @@ -3,32 +3,53 @@ 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) { - const account = "registry-admin@mcp-registry-prod.iam.gserviceaccount.com" - const rules = `[{"email":"` + account + `","email_verified":true}]` - for _, tc := range []struct{ name, environment, account, audience, claims string }{ - {"prod", "prod", account, "https://registry.modelcontextprotocol.io", rules}, - {"staging", "staging", account, "https://staging.registry.modelcontextprotocol.io", rules}, - {"local default", "local", "", "32555940559.apps.googleusercontent.com", `[{"hd":"modelcontextprotocol.io"}]`}, - {"required in prod", "prod", "", "", ""}, - {"required in staging", "staging", "", "", ""}, - {"user account", "prod", "someone@modelcontextprotocol.io", "", ""}, - {"no account name", "prod", "@mcp-registry-prod.iam.gserviceaccount.com", "", ""}, - {"other suffix", "prod", account + ".example.com", "", ""}, + 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 { - audience, claims, err := adminLogin(config.New(ctx, "mcp-registry"), tc.environment) - if (err != nil) != (tc.audience == "") || audience != tc.audience || claims != tc.claims { - t.Errorf("adminLogin() = %q, %q, %v", audience, claims, err) + secrets := pulumi.StringMap{} + 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 + } + } + wantOIDC, wantTeam, wantSecrets := any(pulumi.String("true")), any(nil), 0 + if !tc.google { + wantOIDC, wantTeam, wantSecrets = pulumi.String("false"), pulumi.String(githubAdminTeam), 1 + } + if values["MCP_REGISTRY_OIDC_ENABLED"] != wantOIDC || values["MCP_REGISTRY_GITHUB_ADMIN_TEAM"] != wantTeam || len(secrets) != wantSecrets { + t.Errorf("unexpected settings: %v, %d secrets", values, len(secrets)) } return nil }, pulumi.WithMocks("admin-login-test", "staging", ownershipMonitor{t}), func(info *pulumi.RunInfo) { - info.Config = map[string]string{"mcp-registry:adminServiceAccount": tc.account} + 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/production_scaling_test.go b/deploy/pkg/k8s/production_scaling_test.go index d3ee4d38a..388d21a65 100644 --- a/deploy/pkg/k8s/production_scaling_test.go +++ b/deploy/pkg/k8s/production_scaling_test.go @@ -103,10 +103,6 @@ func (m *productionScalingMonitor) NewResource(a pulumi.MockResourceArgs) (strin env[v["name"].StringValue()] = v["value"].StringValue() } } - if env["MCP_REGISTRY_OIDC_CLIENT_ID"] != "https://registry.modelcontextprotocol.io" || - env["MCP_REGISTRY_OIDC_EXTRA_CLAIMS"] != `[{"email":"registry-admin@mcp-registry-prod.iam.gserviceaccount.com","email_verified":true}]` { - m.t.Error("admin service account missing from the sign-in rules") - } if env["MCP_REGISTRY_DATABASE_MAX_CONNECTIONS"] != expectedPool || env["MCP_REGISTRY_DATABASE_MIN_CONNECTIONS"] != "5" || env["MCP_REGISTRY_PREPARED_LISTING_JSON"] != "true" { m.t.Error("missing bounded pools or changed prepared reads") } @@ -169,7 +165,6 @@ func TestProductionScalingRendersPreparationAndActivation(t *testing.T) { return err }, pulumi.WithMocks("scaling-test", "prod", m), func(info *pulumi.RunInfo) { info.Config = productionScalingConfig(phase) - info.Config["mcp-registry:adminServiceAccount"] = "registry-admin@mcp-registry-prod.iam.gserviceaccount.com" if profile.packed { info.Config["mcp-registry:productionPackedPlacement"] = "true" info.Config["mcp-registry:gatewayProductionPhase"] = "standalone" diff --git a/deploy/pkg/k8s/registry.go b/deploy/pkg/k8s/registry.go index 2ea51ef56..9242493da 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"), + } + 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 @@ -183,11 +189,6 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }) } - oidcAudience, oidcClaims, err := adminLogin(conf, environment) - if err != nil { - return nil, err - } - // Create Deployment _, err = v1.NewDeployment(ctx, "mcp-registry", &v1.DeploymentArgs{ Metadata: &metav1.ObjectMetaArgs{ @@ -273,22 +274,18 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }, }, }, - // Google Cloud Identity OIDC for admin access - &corev1.EnvVarArgs{ - Name: pulumi.String("MCP_REGISTRY_OIDC_ENABLED"), - Value: pulumi.String("true"), - }, + // Google Cloud Identity OIDC for admin access, if adminEnv turns it on &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_ISSUER"), Value: pulumi.String("https://accounts.google.com"), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_CLIENT_ID"), - Value: pulumi.String(oidcAudience), + Value: pulumi.String("32555940559.apps.googleusercontent.com"), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_EXTRA_CLAIMS"), - Value: pulumi.String(oidcClaims), + Value: pulumi.String(`[{"hd":"modelcontextprotocol.io"}]`), }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_EDIT_PERMISSIONS"), @@ -299,10 +296,15 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env Value: pulumi.String("*"), }, &corev1.EnvVarArgs{ - Name: pulumi.String("MCP_REGISTRY_GITHUB_OIDC_AUDIENCE"), - Value: pulumi.String(registryURL(environment)), + Name: pulumi.String("MCP_REGISTRY_GITHUB_OIDC_AUDIENCE"), + Value: pulumi.String(func() string { + if environment == "prod" { + return "https://registry.modelcontextprotocol.io" + } + 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 8c93a1632..b100e9642 100644 --- a/docs/administration/admin-operations.md +++ b/docs/administration/admin-operations.md @@ -4,7 +4,7 @@ This is a brief guide for admins and moderators managing content on the registry ## Prerequisites -- Member of the `registry-admins` Google group, managed with the `registry-admins` role in the [access repository](https://github.com/modelcontextprotocol/access) +- `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 @@ -19,7 +19,9 @@ A takedown made with global registry edit permission places a hold on the affect ./tools/admin/auth.sh ``` -The script signs you in with a token for the environment's `registry-admin` service account, which the `registry-admins` group can request. New members may need to wait for the group change to reach Google Cloud. The active `gcloud` account must be the one in the group; switch with `gcloud config set account`. Set `REGISTRY_URL` to use staging. For another registry with an admin service account, also set `ADMIN_SERVICE_ACCOUNT`, and `ADMIN_AUDIENCE` if it differs from `REGISTRY_URL`. +Where the stack file in `deploy/` has a `githubAdminClientId`, the script signs you in with GitHub, 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` too if it uses GitHub admin sign-in. Use that only for a registry you trust, because it receives your token. ## Edit a Specific Server Version diff --git a/docs/design/tech-architecture.md b/docs/design/tech-architecture.md index 4f0199f87..e04e5624b 100644 --- a/docs/design/tech-architecture.md +++ b/docs/design/tech-architecture.md @@ -184,42 +184,24 @@ sequenceDiagram CLI-->>User: Success! ``` -### 4. Admin OIDC Authentication Flow +### 4. Admin Authentication Flow -For registry administration, members of the `registry-admins` Google group authenticate using OIDC, with a token for the service account in `mcp-registry:adminServiceAccount`: +Where GitHub admin sign-in is configured, the registry only accepts a token from its GitHub app for admins, and only if the user is an active member of the configured team or its child teams. Publishing uses a different GitHub app, so a publishing token never grants admin permissions. 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 CLI as auth.sh + participant GH as GitHub participant API as Registry API - + Admin->>CLI: Request admin token - CLI->>GCP: Request service account ID token for the registry URL - GCP-->>CLI: ID Token (with the service account email) - CLI->>API: POST /v0.1/auth/oidc {"oidc_token": "eyJ..."} - API->>GCP: Verify token signature (JWKS) - API->>API: Validate claims (issuer, audience, email) - 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 + CLI->>GH: Start device flow for the GitHub admin app + Admin->>GH: Enter the code and authorize + GH-->>CLI: User access token + CLI->>API: POST /v0/auth/github-admin + API->>GH: Check that the user is in the admin team + API->>GH: Check that the token is from the admin app + API-->>CLI: Registry JWT (5 minutes) + CLI-->>Admin: Export command for the token ``` - -**Usage:** -```bash -# Get a token for the admin service account -ID_TOKEN=$(gcloud auth print-identity-token \ - --impersonate-service-account="$ADMIN_SERVICE_ACCOUNT" \ - --audiences="$REGISTRY_URL" --include-email) - -# 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 diff --git a/docs/reference/api/official-registry-api.md b/docs/reference/api/official-registry-api.md index f674a2431..4f1876737 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 access token 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..8e8342d2b --- /dev/null +++ b/internal/api/handlers/v0/auth/github_admin.go @@ -0,0 +1,221 @@ +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 +) + +var ( + // GitHub allows underscores in team slugs and in managed users' logins. + githubPathName = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) + + errGitHubUnavailable = errors.New("GitHub is unavailable") +) + +// GitHubAdminHandler signs in registry admins: members of a GitHub team. It +// uses its own GitHub app, not the one for publishing. Anyone can point the +// publisher CLI at another registry, which then receives the user's token, so a +// publishing token must never be enough to become an admin. +type GitHubAdminHandler struct { + config *config.Config + jwtManager *auth.JWTManager + client *http.Client + baseURL 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}, + baseURL: "https://api.github.com", + org: org, + team: team, + }, nil +} + +// SetBaseURL sets the base URL for the GitHub API (used for testing) +func (h *GitHubAdminHandler) SetBaseURL(baseURL string) { + h.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 access token for admin Registry JWT", + Description: "Exchange an access token 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 *GitHubTokenExchangeInput) (*v0.Response[auth.TokenResponse], error) { + response, err := handler.ExchangeToken(ctx, input.Body.GitHubToken) + 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 + }) +} + +// ExchangeToken exchanges a GitHub token for an admin Registry JWT. It fails +// unless GitHub confirms the user, their team membership and the token's app. +func (h *GitHubAdminHandler) ExchangeToken(ctx context.Context, githubToken string) (*auth.TokenResponse, error) { + // The first two calls use the caller's token. The app check comes last, so + // that only team members can use up the app's own rate limit. + login, err := h.currentUser(ctx, githubToken) + if err != nil { + return nil, err + } + if err := h.checkTeamMember(ctx, githubToken, login); err != nil { + return nil, err + } + if err := h.checkTokenApp(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 +} + +func (h *GitHubAdminHandler) currentUser(ctx context.Context, githubToken string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.baseURL+"/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 +} + +// checkTokenApp only accepts tokens that the admin app issued to this user, so +// a token that the user gave to any other app can't be used here. +func (h *GitHubAdminHandler) checkTokenApp(ctx context.Context, githubToken, login string) error { + body, err := json.Marshal(map[string]string{"access_token": githubToken}) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + h.baseURL+"/applications/"+url.PathEscape(h.config.GitHubAdminClientID)+"/token", bytes.NewReader(body)) + if err != nil { + return err + } + req.SetBasicAuth(h.config.GitHubAdminClientID, h.config.GitHubAdminClientSecret) + req.Header.Set("Content-Type", "application/json") + + var token struct { + App struct { + ClientID string `json:"client_id"` + } `json:"app"` + User GitHubUserOrOrg `json:"user"` + } + if err := h.do(req, &token); err != nil { + return fmt.Errorf("failed to confirm the app of GitHub user %q's token: %w", login, err) + } + if token.App.ClientID != h.config.GitHubAdminClientID || token.User.Login != login { + return fmt.Errorf("GitHub user %q's token is not from the admin app", login) + } + return 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.baseURL, 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 { + 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..b0e45389f --- /dev/null +++ b/internal/api/handlers/v0/auth/github_admin_test.go @@ -0,0 +1,141 @@ +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 TestGitHubAdminExchangeToken(t *testing.T) { + const user = `{"login":"alice_corp"}` + const active = `{"state":"active","role":"member"}` + const app = `{"app":{"client_id":"admin-app"},"user":{"login":"alice_corp"}}` + type reply struct { + status int + body string + } + for _, tt := range []struct { + name string + user, team, app reply + valid bool + calls string + }{ + {"active member", reply{200, user}, reply{200, active}, reply{200, app}, true, "user team app"}, + {"invalid token", reply{401, `{}`}, reply{200, active}, reply{200, app}, false, "user"}, + {"no user", reply{200, `{}`}, reply{200, active}, reply{200, app}, false, "user"}, + {"unsafe login", reply{200, `{"login":"../x"}`}, reply{200, active}, reply{200, app}, false, "user"}, + {"pending member", reply{200, user}, reply{200, `{"state":"pending"}`}, reply{200, app}, false, "user team"}, + {"not a member", reply{200, user}, reply{404, `{}`}, reply{200, app}, false, "user team"}, + {"app can't read the team", reply{200, user}, reply{403, active}, reply{200, app}, false, "user team"}, + {"team check unavailable", reply{200, user}, reply{503, active}, reply{200, app}, false, "user team"}, + {"empty team response", reply{200, user}, reply{200, `{}`}, reply{200, app}, false, "user team"}, + {"invalid team response", reply{200, user}, reply{200, ``}, reply{200, app}, false, "user team"}, + {"token from the publishing app", reply{200, user}, reply{200, active}, reply{404, `{}`}, false, "user team app"}, + {"another app in the response", reply{200, user}, reply{200, active}, reply{200, `{"app":{"client_id":"publish-app"},"user":{"login":"alice_corp"}}`}, false, "user team app"}, + {"another user in the response", reply{200, user}, reply{200, active}, reply{200, `{"app":{"client_id":"admin-app"},"user":{"login":"bob"}}`}, false, "user team app"}, + {"empty app response", reply{200, user}, reply{200, active}, reply{200, `{}`}, false, "user team app"}, + {"app check unavailable", reply{200, user}, reply{200, active}, reply{503, app}, false, "user team app"}, + } { + t.Run(tt.name, func(t *testing.T) { + var calls []string + respond := func(w http.ResponseWriter, name string, r reply) { + calls = append(calls, name) + w.WriteHeader(r.status) + _, _ = w.Write([]byte(r.body)) + } + mux := http.NewServeMux() + 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("POST /applications/admin-app/token", func(w http.ResponseWriter, r *http.Request) { + id, secret, _ := r.BasicAuth() + assert.Equal(t, "admin-app", id) + assert.Equal(t, "admin-secret", secret) + var body map[string]string + assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, "user-token", body["access_token"]) + respond(w, "app", tt.app) + }) + 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.ExchangeToken(context.Background(), "user-token") + 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..e7870c8c0 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 (access token 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 d2fb45831..04572dafd 100755 --- a/tools/admin/auth.sh +++ b/tools/admin/auth.sh @@ -1,44 +1,80 @@ #!/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%/}" -ADMIN_SERVICE_ACCOUNT="${ADMIN_SERVICE_ACCOUNT:-}" -ADMIN_AUDIENCE="${ADMIN_AUDIENCE:-}" +# For our registries, the GitHub app comes from this checkout and never from +# the server, so another server can't ask for a token that works on ours. +stack_client_id() { + sed -n 's/^ mcp-registry:githubAdminClientId: *\([A-Za-z0-9._-]*\).*$/\1/p' \ + "$(dirname "${BASH_SOURCE[0]}")/../../deploy/Pulumi.$1.yaml" +} -# Keep these accounts in step with mcp-registry:adminServiceAccount in deploy/ case "$REGISTRY_URL" in https://registry.modelcontextprotocol.io | https://prod.registry.modelcontextprotocol.io) - : "${ADMIN_SERVICE_ACCOUNT:=registry-admin@mcp-registry-prod.iam.gserviceaccount.com}" - : "${ADMIN_AUDIENCE:=https://registry.modelcontextprotocol.io}" - ;; + CLIENT_ID=$(stack_client_id gcpProd) ;; https://staging.registry.modelcontextprotocol.io) - : "${ADMIN_SERVICE_ACCOUNT:=registry-admin@mcp-registry-staging.iam.gserviceaccount.com}" - ;; + CLIENT_ID=$(stack_client_id gcpStaging) ;; + *) + CLIENT_ID="${GITHUB_ADMIN_CLIENT_ID:-}" ;; esac -if ! gcloud projects list &> /dev/null; then - gcloud auth login >&2 -fi +# Each step returns on failure, because set -e is off inside $(...) +github_token() { + local device code interval reply token error + device=$(curl -sS -X POST https://github.com/login/device/code \ + -H "Accept: application/json" \ + --data-urlencode "client_id=${CLIENT_ID}") || return 1 + if ! code=$(printf '%s\n' "$device" | jq -er '.device_code' 2>/dev/null); then + echo "Error: GitHub sign-in could not start: $(printf '%s\n' "$device" | jq -r '.error_description // .error // "unexpected response"' 2>/dev/null)" >&2 + return 1 + fi + interval=$(printf '%s\n' "$device" | jq -er '.interval // 5') || return 1 + printf '%s\n' "$device" | jq -er '"Open \(.verification_uri) and enter the code \(.user_code)"' >&2 || return 1 -if [ -n "$ADMIN_SERVICE_ACCOUNT" ]; then - # Get an identity token for the admin service account, valid only for this registry - OIDC_TOKEN=$(gcloud auth print-identity-token \ - --impersonate-service-account="$ADMIN_SERVICE_ACCOUNT" \ - --audiences="${ADMIN_AUDIENCE:-$REGISTRY_URL}" \ - --include-email) + while true; do + sleep "$interval" || return 1 + # The device code goes through stdin to keep it out of process listings + reply=$(printf '%s' "$code" | curl -sS -X POST https://github.com/login/oauth/access_token \ + -H "Accept: application/json" \ + --data-urlencode "client_id=${CLIENT_ID}" \ + --data-urlencode "device_code@-" \ + --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:device_code") || reply="" + token=$(printf '%s\n' "$reply" | jq -r '.access_token // empty' 2>/dev/null) || token="" + if [ -n "$token" ]; then + printf '%s' "$token" + return + fi + # Keep trying after a failed request. GitHub ends the wait when the code expires. + error=$(printf '%s\n' "$reply" | jq -r '.error // empty' 2>/dev/null) || error="" + case "$error" in + "" | authorization_pending) ;; + slow_down) interval=$((interval + 5)) ;; + *) echo "Error: GitHub sign-in failed: ${error}" >&2; return 1 ;; + esac + done +} + +if [ -n "$CLIENT_ID" ]; then + TOKEN=$(github_token) + ENDPOINT=github-admin + FIELD=github_token else - # Registries without an admin service account, such as local ones - OIDC_TOKEN=$(gcloud auth print-identity-token) + if ! gcloud projects list &> /dev/null; then + gcloud auth login >&2 + fi + TOKEN=$(gcloud auth print-identity-token) + ENDPOINT=oidc + FIELD=oidc_token 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' "$TOKEN" | jq -Rs --arg field "$FIELD" '{($field): .}' | \ + 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 From 4f8ba4be966de2835099074ebb526424419eec20 Mon Sep 17 00:00:00 2001 From: Den <53200638+localden@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:33:20 +0000 Subject: [PATCH 4/4] Use browser sign-in with PKCE for registry admins --- .env.example | 6 +- deploy/README.md | 2 +- deploy/pkg/k8s/admin_login.go | 20 +- deploy/pkg/k8s/admin_login_test.go | 10 +- deploy/pkg/k8s/registry.go | 8 +- docs/administration/admin-operations.md | 6 +- docs/design/tech-architecture.md | 18 +- docs/reference/api/official-registry-api.md | 2 +- internal/api/handlers/v0/auth/github_admin.go | 183 +++++++++++++----- .../api/handlers/v0/auth/github_admin_test.go | 79 +++++--- internal/auth/types.go | 2 +- tools/admin/auth.sh | 120 +++++++----- tools/admin/github-login.py | 127 ++++++++++++ 13 files changed, 423 insertions(+), 160 deletions(-) create mode 100755 tools/admin/github-login.py diff --git a/.env.example b/.env.example index 31065db2e..af44384fd 100644 --- a/.env.example +++ b/.env.example @@ -62,8 +62,10 @@ MCP_REGISTRY_JWT_PRIVATE_KEY=bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb # 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 device flow, read access -# to organization members, and to be installed on the team's organization. +# 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= diff --git a/deploy/README.md b/deploy/README.md index f4e7b6baf..c9dab0951 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -492,7 +492,7 @@ 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 device flow, read access to organization members, and to be installed on the organization | No | +| `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) | diff --git a/deploy/pkg/k8s/admin_login.go b/deploy/pkg/k8s/admin_login.go index 9b483d145..7a520a3ee 100644 --- a/deploy/pkg/k8s/admin_login.go +++ b/deploy/pkg/k8s/admin_login.go @@ -2,7 +2,6 @@ package k8s import ( "errors" - "strconv" corev1 "github.com/pulumi/pulumi-kubernetes/sdk/v4/go/kubernetes/core/v1" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" @@ -20,26 +19,23 @@ const ( // 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, and returns the settings for the registry container. -func adminLogin(conf *config.Config, environment string, secrets pulumi.StringMap, secretName pulumi.StringPtrInput) (corev1.EnvVarArray, error) { +// 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") - env := corev1.EnvVarArray{&corev1.EnvVarArgs{ - Name: pulumi.String("MCP_REGISTRY_OIDC_ENABLED"), - Value: pulumi.String(strconv.FormatBool(clientID == "")), - }} if clientID == "" { - return env, nil + return true, nil, nil } if clientID == conf.Get("githubClientId") { - return nil, errors.New("githubAdminClientId must not be the GitHub app for publishing") + 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 nil, errors.New("githubAdminClientId requires an imageTag after " + lastGoogleOnlyRelease) + return false, nil, errors.New("githubAdminClientId requires an imageTag after " + lastGoogleOnlyRelease) } secrets[githubAdminSecretKey] = conf.RequireSecret("githubAdminClientSecret") - return append(env, + 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{ @@ -48,5 +44,5 @@ func adminLogin(conf *config.Config, environment string, secrets pulumi.StringMa Name: secretName, Key: pulumi.String(githubAdminSecretKey), }}, }, - ), nil + }, nil } diff --git a/deploy/pkg/k8s/admin_login_test.go b/deploy/pkg/k8s/admin_login_test.go index eb27d1f4c..2c14da843 100644 --- a/deploy/pkg/k8s/admin_login_test.go +++ b/deploy/pkg/k8s/admin_login_test.go @@ -24,7 +24,7 @@ func TestAdminLogin(t *testing.T) { t.Run(tc.name, func(t *testing.T) { err := pulumi.RunErr(func(ctx *pulumi.Context) error { secrets := pulumi.StringMap{} - env, err := adminLogin(config.New(ctx, "mcp-registry"), tc.environment, secrets, pulumi.String("secrets").ToStringPtrOutput()) + 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) } @@ -37,12 +37,12 @@ func TestAdminLogin(t *testing.T) { values[string(e.Name.(pulumi.String))] = e.Value } } - wantOIDC, wantTeam, wantSecrets := any(pulumi.String("true")), any(nil), 0 + wantTeam, wantEnv, wantSecrets := any(nil), 0, 0 if !tc.google { - wantOIDC, wantTeam, wantSecrets = pulumi.String("false"), pulumi.String(githubAdminTeam), 1 + wantTeam, wantEnv, wantSecrets = pulumi.String(githubAdminTeam), 3, 1 } - if values["MCP_REGISTRY_OIDC_ENABLED"] != wantOIDC || values["MCP_REGISTRY_GITHUB_ADMIN_TEAM"] != wantTeam || len(secrets) != wantSecrets { - t.Errorf("unexpected settings: %v, %d secrets", values, len(secrets)) + 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) { diff --git a/deploy/pkg/k8s/registry.go b/deploy/pkg/k8s/registry.go index 9242493da..588881464 100644 --- a/deploy/pkg/k8s/registry.go +++ b/deploy/pkg/k8s/registry.go @@ -93,7 +93,7 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env "GITHUB_CLIENT_SECRET": conf.RequireSecret("githubClientSecret"), "JWT_PRIVATE_KEY": conf.RequireSecret("jwtPrivateKey"), } - adminEnv, err := adminLogin(conf, environment, secrets, pulumi.String("mcp-registry-secrets")) + googleAdminLogin, adminEnv, err := adminLogin(conf, environment, secrets, pulumi.String("mcp-registry-secrets")) if err != nil { return nil, err } @@ -274,7 +274,11 @@ func DeployMCPRegistry(ctx *pulumi.Context, cluster *providers.ProviderInfo, env }, }, }, - // Google Cloud Identity OIDC for admin access, if adminEnv turns it on + // Google Cloud Identity OIDC for admin access, unless adminEnv turns on GitHub + &corev1.EnvVarArgs{ + Name: pulumi.String("MCP_REGISTRY_OIDC_ENABLED"), + Value: pulumi.String(strconv.FormatBool(googleAdminLogin)), + }, &corev1.EnvVarArgs{ Name: pulumi.String("MCP_REGISTRY_OIDC_ISSUER"), Value: pulumi.String("https://accounts.google.com"), diff --git a/docs/administration/admin-operations.md b/docs/administration/admin-operations.md index b100e9642..056d92949 100644 --- a/docs/administration/admin-operations.md +++ b/docs/administration/admin-operations.md @@ -7,7 +7,7 @@ This is a brief guide for admins and moderators managing content on the registry - `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,9 +19,9 @@ 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, and the registry checks that you are in the `registry-admins` team. Otherwise it uses `gcloud`. Run it from an up-to-date checkout. +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` too if it uses GitHub admin sign-in. Use that only for a registry you trust, because it receives your token. +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 diff --git a/docs/design/tech-architecture.md b/docs/design/tech-architecture.md index e04e5624b..570f3b360 100644 --- a/docs/design/tech-architecture.md +++ b/docs/design/tech-architecture.md @@ -186,22 +186,22 @@ sequenceDiagram ### 4. Admin Authentication Flow -Where GitHub admin sign-in is configured, the registry only accepts a token from its GitHub app for admins, and only if the user is an active member of the configured team or its child teams. Publishing uses a different GitHub app, so a publishing token never grants admin permissions. Hosted registries without an admin app use Google sign-in through `/auth/oidc` instead. +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 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->>GH: Start device flow for the GitHub admin app - Admin->>GH: Enter the code and authorize - GH-->>CLI: User access token - CLI->>API: POST /v0/auth/github-admin + 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: Check that the token is from the admin app + API->>GH: Revoke the user's authorization and token API-->>CLI: Registry JWT (5 minutes) - CLI-->>Admin: Export command for the token ``` diff --git a/docs/reference/api/official-registry-api.md b/docs/reference/api/official-registry-api.md index 4f1876737..6e147e9dd 100644 --- a/docs/reference/api/official-registry-api.md +++ b/docs/reference/api/official-registry-api.md @@ -88,7 +88,7 @@ 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 access token for admin auth token (for admins, where configured) +- 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, where configured) diff --git a/internal/api/handlers/v0/auth/github_admin.go b/internal/api/handlers/v0/auth/github_admin.go index 8e8342d2b..62079107a 100644 --- a/internal/api/handlers/v0/auth/github_admin.go +++ b/internal/api/handlers/v0/auth/github_admin.go @@ -23,24 +23,43 @@ import ( 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 -// uses its own GitHub app, not the one for publishing. Anyone can point the -// publisher CLI at another registry, which then receives the user's token, so a -// publishing token must never be enough to become an admin. +// 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 - baseURL string + apiURL string + webURL string org, team string } @@ -59,16 +78,21 @@ func NewGitHubAdminHandler(cfg *config.Config) (*GitHubAdminHandler, error) { return &GitHubAdminHandler{ config: cfg, jwtManager: auth.NewJWTManager(cfg), - client: &http.Client{Timeout: githubAdminTimeout}, - baseURL: "https://api.github.com", - org: org, - team: team, + 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 the GitHub API (used for testing) +// SetBaseURL sets the base URL for GitHub and its API (used for testing) func (h *GitHubAdminHandler) SetBaseURL(baseURL string) { - h.baseURL = baseURL + h.apiURL, h.webURL = baseURL, baseURL } // RegisterGitHubAdminEndpoint registers admin sign-in if a team is configured. @@ -85,11 +109,11 @@ func RegisterGitHubAdminEndpoint(api huma.API, pathPrefix string, cfg *config.Co OperationID: "exchange-github-admin-token" + strings.ReplaceAll(pathPrefix, "/", "-"), Method: http.MethodPost, Path: pathPrefix + "/auth/github-admin", - Summary: "Exchange GitHub access token for admin Registry JWT", - Description: "Exchange an access token from this registry's GitHub admin app for a short-lived admin Registry JWT. Only for registry admins.", + 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 *GitHubTokenExchangeInput) (*v0.Response[auth.TokenResponse], error) { - response, err := handler.ExchangeToken(ctx, input.Body.GitHubToken) + }, 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) @@ -102,19 +126,33 @@ func RegisterGitHubAdminEndpoint(api huma.API, pathPrefix string, cfg *config.Co }) } -// ExchangeToken exchanges a GitHub token for an admin Registry JWT. It fails -// unless GitHub confirms the user, their team membership and the token's app. -func (h *GitHubAdminHandler) ExchangeToken(ctx context.Context, githubToken string) (*auth.TokenResponse, error) { - // The first two calls use the caller's token. The app check comes last, so - // that only team members can use up the app's own rate limit. - login, err := h.currentUser(ctx, githubToken) +// 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 } - if err := h.checkTeamMember(ctx, githubToken, login); err != nil { + + login, err := h.currentUser(ctx, githubToken) + if err != nil { return nil, err } - if err := h.checkTokenApp(ctx, githubToken, login); err != nil { + if err := h.checkTeamMember(ctx, githubToken, login); err != nil { return nil, err } @@ -133,57 +171,102 @@ func (h *GitHubAdminHandler) ExchangeToken(ctx context.Context, githubToken stri return response, nil } -func (h *GitHubAdminHandler) currentUser(ctx context.Context, githubToken string) (string, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.baseURL+"/user", 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("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) + 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 !githubPathName.MatchString(user.Login) { - return "", errors.New("the GitHub token has no valid user") + if err := h.do(req, &token); err != nil { + return "", fmt.Errorf("failed to exchange the authorization code: %w", err) } - return user.Login, nil + 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) } -// checkTokenApp only accepts tokens that the admin app issued to this user, so -// a token that the user gave to any other app can't be used here. -func (h *GitHubAdminHandler) checkTokenApp(ctx context.Context, githubToken, login string) error { +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.MethodPost, - h.baseURL+"/applications/"+url.PathEscape(h.config.GitHubAdminClientID)+"/token", bytes.NewReader(body)) + 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 +} - var token struct { - App struct { - ClientID string `json:"client_id"` - } `json:"app"` - User GitHubUserOrOrg `json:"user"` +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 } - if err := h.do(req, &token); err != nil { - return fmt.Errorf("failed to confirm the app of GitHub user %q's token: %w", login, 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 token.App.ClientID != h.config.GitHubAdminClientID || token.User.Login != login { - return fmt.Errorf("GitHub user %q's token is not from the admin app", login) + if !githubPathName.MatchString(user.Login) { + return "", errors.New("the GitHub token has no valid user") } - return nil + 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.baseURL, h.org, h.team, login), nil) + fmt.Sprintf("%s/orgs/%s/teams/%s/memberships/%s", h.apiURL, h.org, h.team, login), nil) if err != nil { return err } @@ -202,8 +285,10 @@ func (h *GitHubAdminHandler) checkTeamMember(ctx context.Context, githubToken, l } func (h *GitHubAdminHandler) do(req *http.Request, result any) error { - req.Header.Set("Accept", "application/vnd.github+json") - req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + 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) diff --git a/internal/api/handlers/v0/auth/github_admin_test.go b/internal/api/handlers/v0/auth/github_admin_test.go index b0e45389f..7df6dc57d 100644 --- a/internal/api/handlers/v0/auth/github_admin_test.go +++ b/internal/api/handlers/v0/auth/github_admin_test.go @@ -28,44 +28,71 @@ func githubAdminConfig() *config.Config { } } -func TestGitHubAdminExchangeToken(t *testing.T) { +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"}` - const app = `{"app":{"client_id":"admin-app"},"user":{"login":"alice_corp"}}` + 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 - user, team, app reply - valid bool - calls string + name string + verifier, redirect string + code, user, team reply + revoke int + valid bool + calls string }{ - {"active member", reply{200, user}, reply{200, active}, reply{200, app}, true, "user team app"}, - {"invalid token", reply{401, `{}`}, reply{200, active}, reply{200, app}, false, "user"}, - {"no user", reply{200, `{}`}, reply{200, active}, reply{200, app}, false, "user"}, - {"unsafe login", reply{200, `{"login":"../x"}`}, reply{200, active}, reply{200, app}, false, "user"}, - {"pending member", reply{200, user}, reply{200, `{"state":"pending"}`}, reply{200, app}, false, "user team"}, - {"not a member", reply{200, user}, reply{404, `{}`}, reply{200, app}, false, "user team"}, - {"app can't read the team", reply{200, user}, reply{403, active}, reply{200, app}, false, "user team"}, - {"team check unavailable", reply{200, user}, reply{503, active}, reply{200, app}, false, "user team"}, - {"empty team response", reply{200, user}, reply{200, `{}`}, reply{200, app}, false, "user team"}, - {"invalid team response", reply{200, user}, reply{200, ``}, reply{200, app}, false, "user team"}, - {"token from the publishing app", reply{200, user}, reply{200, active}, reply{404, `{}`}, false, "user team app"}, - {"another app in the response", reply{200, user}, reply{200, active}, reply{200, `{"app":{"client_id":"publish-app"},"user":{"login":"alice_corp"}}`}, false, "user team app"}, - {"another user in the response", reply{200, user}, reply{200, active}, reply{200, `{"app":{"client_id":"admin-app"},"user":{"login":"bob"}}`}, false, "user team app"}, - {"empty app response", reply{200, user}, reply{200, active}, reply{200, `{}`}, false, "user team app"}, - {"app check unavailable", reply{200, user}, reply{200, active}, reply{503, app}, false, "user team app"}, + {"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) @@ -74,14 +101,14 @@ func TestGitHubAdminExchangeToken(t *testing.T) { assert.Equal(t, "Bearer user-token", r.Header.Get("Authorization")) respond(w, "team", tt.team) }) - mux.HandleFunc("POST /applications/admin-app/token", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("DELETE /applications/admin-app/grant", func(w http.ResponseWriter, r *http.Request) { id, secret, _ := r.BasicAuth() - assert.Equal(t, "admin-app", id) - assert.Equal(t, "admin-secret", secret) + 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, "app", tt.app) + respond(w, "revoke", reply{tt.revoke, ""}) }) github := httptest.NewServer(mux) defer github.Close() @@ -91,7 +118,7 @@ func TestGitHubAdminExchangeToken(t *testing.T) { require.NoError(t, err) handler.SetBaseURL(github.URL) - response, err := handler.ExchangeToken(context.Background(), "user-token") + 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) diff --git a/internal/auth/types.go b/internal/auth/types.go index e7870c8c0..9a8a45289 100644 --- a/internal/auth/types.go +++ b/internal/auth/types.go @@ -6,7 +6,7 @@ type Method string const ( // GitHub OAuth authentication (access token) MethodGitHubAT Method = "github-at" - // GitHub authentication for registry admins (access token and team membership) + // GitHub authentication for registry admins (authorization code with PKCE, and team membership) MethodGitHubAdmin Method = "github-admin" // GitHub Actions OIDC authentication MethodGitHubOIDC Method = "github-oidc" diff --git a/tools/admin/auth.sh b/tools/admin/auth.sh index 04572dafd..db1a9dd12 100755 --- a/tools/admin/auth.sh +++ b/tools/admin/auth.sh @@ -6,74 +6,95 @@ set -euo pipefail REGISTRY_URL="${REGISTRY_URL:-https://registry.modelcontextprotocol.io}" REGISTRY_URL="${REGISTRY_URL%/}" +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 token that works on ours. +# the server, so another server can't ask for a code that works on ours. stack_client_id() { - sed -n 's/^ mcp-registry:githubAdminClientId: *\([A-Za-z0-9._-]*\).*$/\1/p' \ - "$(dirname "${BASH_SOURCE[0]}")/../../deploy/Pulumi.$1.yaml" + 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) +GOOGLE=false case "$REGISTRY_URL" in https://registry.modelcontextprotocol.io | https://prod.registry.modelcontextprotocol.io) - CLIENT_ID=$(stack_client_id gcpProd) ;; + CLIENT_ID="$PROD_ID" + GOOGLE=true + ;; https://staging.registry.modelcontextprotocol.io) - CLIENT_ID=$(stack_client_id gcpStaging) ;; + CLIENT_ID="$STAGING_ID" + GOOGLE=true + ;; *) - CLIENT_ID="${GITHUB_ADMIN_CLIENT_ID:-}" ;; -esac - -# Each step returns on failure, because set -e is off inside $(...) -github_token() { - local device code interval reply token error - device=$(curl -sS -X POST https://github.com/login/device/code \ - -H "Accept: application/json" \ - --data-urlencode "client_id=${CLIENT_ID}") || return 1 - if ! code=$(printf '%s\n' "$device" | jq -er '.device_code' 2>/dev/null); then - echo "Error: GitHub sign-in could not start: $(printf '%s\n' "$device" | jq -r '.error_description // .error // "unexpected response"' 2>/dev/null)" >&2 - return 1 - fi - interval=$(printf '%s\n' "$device" | jq -er '.interval // 5') || return 1 - printf '%s\n' "$device" | jq -er '"Open \(.verification_uri) and enter the code \(.user_code)"' >&2 || return 1 - - while true; do - sleep "$interval" || return 1 - # The device code goes through stdin to keep it out of process listings - reply=$(printf '%s' "$code" | curl -sS -X POST https://github.com/login/oauth/access_token \ - -H "Accept: application/json" \ - --data-urlencode "client_id=${CLIENT_ID}" \ - --data-urlencode "device_code@-" \ - --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:device_code") || reply="" - token=$(printf '%s\n' "$reply" | jq -r '.access_token // empty' 2>/dev/null) || token="" - if [ -n "$token" ]; then - printf '%s' "$token" - return + # 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 - # Keep trying after a failed request. GitHub ends the wait when the code expires. - error=$(printf '%s\n' "$reply" | jq -r '.error // empty' 2>/dev/null) || error="" - case "$error" in - "" | authorization_pending) ;; - slow_down) interval=$((interval + 5)) ;; - *) echo "Error: GitHub sign-in failed: ${error}" >&2; return 1 ;; + 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 - done -} + 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 - TOKEN=$(github_token) ENDPOINT=github-admin - FIELD=github_token -else + 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) - ENDPOINT=oidc - FIELD=oidc_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=$(printf '%s' "$TOKEN" | jq -Rs --arg field "$FIELD" '{($field): .}' | \ - curl -sS -X POST "${REGISTRY_URL}/v0/auth/${ENDPOINT}" \ +RESPONSE=$(printf '%s' "$BODY" | curl -sS -X POST "${REGISTRY_URL}/v0/auth/${ENDPOINT}" \ -H "Content-Type: application/json" --data-binary @-) # Check if successful @@ -81,7 +102,8 @@ if ! REGISTRY_TOKEN=$(printf '%s\n' "$RESPONSE" | jq -r '.registry_token // empt 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])