diff --git a/Makefile b/Makefile index dd32cf6..8bd09fc 100644 --- a/Makefile +++ b/Makefile @@ -54,12 +54,16 @@ chart-test: # cluster, named every time so a release can't land on whichever is current. # The fourth argument is the pull secret, for a cluster whose nodes can't read # the registry; it has to exist in the namespace first. +# MCP_HOST_OPENAI_DOMAIN_CHALLENGE: OpenAI's domain verification token, once +# issued. Pass it on every release after that: a release without it removes the +# challenge path. define mcp_host_install @test -n "$(KUBE_CONTEXT)" || { echo "KUBE_CONTEXT is required: the kube context of this environment's cluster"; exit 1; } @test -n "$(MCP_HOST_TAG)" || { echo "MCP_HOST_TAG is required, e.g. v1.11.0"; exit 1; } @test -n "$$SHIPYARD_MCP_CLIENT_SECRET" || { echo "SHIPYARD_MCP_CLIENT_SECRET is required"; exit 1; } @# A pattern, not grep: grep passes a value with a newline if any one line matches. @case "$$SHIPYARD_MCP_CLIENT_SECRET" in *[!A-Za-z0-9._~+/=-]*) echo "SHIPYARD_MCP_CLIENT_SECRET must be one token: letters, digits and ._~+/=-"; exit 1 ;; esac + @case "$(MCP_HOST_OPENAI_DOMAIN_CHALLENGE)" in *[!A-Za-z0-9._~+/=:-]*) echo "MCP_HOST_OPENAI_DOMAIN_CHALLENGE must be one token: letters, digits and ._~+/=:-"; exit 1 ;; esac @# Deployed by digest, looked up now: a tag pushed again later can't change what runs. @digest=$$(docker buildx imagetools inspect "$(MCP_HOST_IMAGE):$(MCP_HOST_TAG)" --format '{{.Manifest.Digest}}') \ && case "$$digest" in sha256:*) ;; *) echo "Couldn't look up the digest of $(MCP_HOST_IMAGE):$(MCP_HOST_TAG)"; exit 1 ;; esac \ @@ -71,6 +75,7 @@ define mcp_host_install --set-string mcp.resourceUrl=$(2) \ --set-string mcp.siteUrl=$(3) \ $(if $(4),--set-string 'imagePullSecrets[0].name=$(4)') \ + $(if $(MCP_HOST_OPENAI_DOMAIN_CHALLENGE),--set-string mcp.openaiDomainChallenge=$(MCP_HOST_OPENAI_DOMAIN_CHALLENGE)) \ -f - mcp-host $(MCP_HOST_CHART) endef diff --git a/commands/mcp_host.go b/commands/mcp_host.go index 2a47077..9f45eba 100644 --- a/commands/mcp_host.go +++ b/commands/mcp_host.go @@ -37,7 +37,10 @@ It is configured from the environment only, so the client secret never lands in SHIPYARD_MCP_CLIENT_ID this server's OAuth client id (default shipyard-mcp-host) SHIPYARD_MCP_CLIENT_SECRET this server's OAuth client secret (required) SHIPYARD_MCP_BEHIND_PROXY true behind a proxy that appends the client's address to - X-Forwarded-For, such as an ingress (default false)`, + X-Forwarded-For, such as an ingress (default false) + SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE + the domain verification token from OpenAI's plugin directory, + served at /.well-known/openai-apps-challenge (default unset)`, Args: cobra.NoArgs, // It never reads the CLI's config file, nor creates one: the image may // run on a read-only filesystem. @@ -72,10 +75,11 @@ func runHost(ctx context.Context, listen string, cfg hosted.Config, func hostConfigFromEnv() (hosted.Config, error) { cfg := hosted.Config{ - ResourceURL: os.Getenv("SHIPYARD_MCP_RESOURCE_URL"), - SiteURL: os.Getenv("SHIPYARD_MCP_SITE_URL"), - ClientID: os.Getenv("SHIPYARD_MCP_CLIENT_ID"), - ClientSecret: os.Getenv("SHIPYARD_MCP_CLIENT_SECRET"), + ResourceURL: os.Getenv("SHIPYARD_MCP_RESOURCE_URL"), + SiteURL: os.Getenv("SHIPYARD_MCP_SITE_URL"), + ClientID: os.Getenv("SHIPYARD_MCP_CLIENT_ID"), + ClientSecret: os.Getenv("SHIPYARD_MCP_CLIENT_SECRET"), + OpenAIDomainChallenge: os.Getenv("SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE"), } if cfg.SiteURL == "" { cfg.SiteURL = "https://shipyard.build" diff --git a/commands/mcp_host_test.go b/commands/mcp_host_test.go index 80721d9..e58e953 100644 --- a/commands/mcp_host_test.go +++ b/commands/mcp_host_test.go @@ -53,6 +53,24 @@ func TestHostConfigFromEnvDefaults(t *testing.T) { } } +func TestHostConfigFromEnvOpenAIDomainChallenge(t *testing.T) { + t.Setenv("SHIPYARD_MCP_RESOURCE_URL", "https://mcp.example.test/mcp") + t.Setenv("SHIPYARD_MCP_CLIENT_SECRET", "host-secret") + t.Setenv("SHIPYARD_MCP_BEHIND_PROXY", "") + t.Setenv("SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE", "") + cfg, err := hostConfigFromEnv() + if err != nil { + t.Fatal(err) + } + if cfg.OpenAIDomainChallenge != "" { + t.Errorf("OpenAIDomainChallenge = %q by default", cfg.OpenAIDomainChallenge) + } + t.Setenv("SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE", "oai-challenge-1234") + if cfg, err = hostConfigFromEnv(); err != nil || cfg.OpenAIDomainChallenge != "oai-challenge-1234" { + t.Errorf("cfg = %+v, err = %v", cfg, err) + } +} + // The hosted server is configured from the environment only. It must start on // a read-only filesystem, and must not load an operator's CLI config. func TestMCPHostDoesNotCreateAConfigFile(t *testing.T) { diff --git a/docs/mcp.md b/docs/mcp.md index cd83b06..fa03079 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -891,7 +891,18 @@ connection, so clients have to sign in again. looked up with `docker buildx imagetools inspect`, so a tag pushed again later can't change what runs. `--atomic` rolls back a release whose pods don't become ready. -6. **Check it** from outside the cluster. A request without a token gets a 401 +6. **OpenAI domain verification**, only once the server is connected in + OpenAI's plugin directory: OpenAI issues a token and fetches it from + `/.well-known/openai-apps-challenge`. Pass it to the release, and on every + release after that, since a release without it removes the path: + + ```bash + make mcp-host.install.production MCP_HOST_TAG=v1.11.0 KUBE_CONTEXT= \ + MCP_HOST_OPENAI_DOMAIN_CHALLENGE= + ``` + + Then click **Verify Domain** in OpenAI's portal. The token isn't a secret. +7. **Check it** from outside the cluster. A request without a token gets a 401 pointing at the metadata, and the metadata names core: ```bash diff --git a/helm/charts/mcp-host/templates/deployment.yaml b/helm/charts/mcp-host/templates/deployment.yaml index 7a6f662..09cb1da 100644 --- a/helm/charts/mcp-host/templates/deployment.yaml +++ b/helm/charts/mcp-host/templates/deployment.yaml @@ -52,6 +52,10 @@ spec: secretKeyRef: name: {{ include "mcp-host.secretName" . }} key: {{ include "mcp-host.secretKey" . }} + {{- with .Values.mcp.openaiDomainChallenge }} + - name: SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE + value: {{ . | quote }} + {{- end }} {{- if .Values.ingress.enabled }} # The ingress appends each client's address to X-Forwarded-For: the # server limits refused tokens per address. diff --git a/helm/charts/mcp-host/values.yaml b/helm/charts/mcp-host/values.yaml index c0f630f..c794ddb 100644 --- a/helm/charts/mcp-host/values.yaml +++ b/helm/charts/mcp-host/values.yaml @@ -30,6 +30,10 @@ mcp: existingSecret: "" existingSecretKey: SHIPYARD_MCP_CLIENT_SECRET clientSecret: "" + # The domain verification token from OpenAI's plugin directory, served as + # plain text at /.well-known/openai-apps-challenge. Not a secret: OpenAI reads + # it from that public URL. Empty, the path is a 404. + openaiDomainChallenge: "" # Logs tools' requests, which carry users' parameters. Leave off in production: # without it, each tool call still logs its name, outcome, duration and org. verbose: false diff --git a/pkg/mcp/hosted/host.go b/pkg/mcp/hosted/host.go index 7ce7f93..436189e 100644 --- a/pkg/mcp/hosted/host.go +++ b/pkg/mcp/hosted/host.go @@ -22,6 +22,7 @@ import ( "strings" "sync/atomic" "time" + "unicode" "github.com/modelcontextprotocol/go-sdk/auth" "github.com/modelcontextprotocol/go-sdk/mcp" @@ -50,6 +51,9 @@ var Logger = log.New(os.Stderr, "", log.LstdFlags|log.LUTC) const ( protectedResourcePath = "/.well-known/oauth-protected-resource" + // openAIChallengePath is where OpenAI's plugin directory looks for the + // domain verification token of a remote MCP server. + openAIChallengePath = "/.well-known/openai-apps-challenge" // Keys in auth.TokenInfo.Extra. extraCoreToken = "core_token" @@ -77,6 +81,11 @@ type Config struct { // X-Forwarded-For, which the proxy in front (the ingress) appends. Set it // only behind one: without it a client could name any address it likes. BehindProxy bool + // OpenAIDomainChallenge is the token OpenAI's plugin directory issues to + // verify this server's domain. Set, the server answers it as plain text at + // /.well-known/openai-apps-challenge; unset, that path is a 404. It isn't + // a secret: OpenAI reads it from the public URL. + OpenAIDomainChallenge string } func (c Config) validate() error { @@ -91,11 +100,17 @@ func (c Config) validate() error { if c.ClientID == "" || c.ClientSecret == "" { return errors.New("the client id and secret are required") } + // OpenAI compares the body with its token exactly, so a pasted space or + // line break would fail verification without saying why. + if strings.IndexFunc(c.OpenAIDomainChallenge, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 { + return errors.New("the OpenAI domain challenge token has a space, line break or control character") + } return nil } // Handler serves the MCP endpoint at the resource URL's path, its protected -// resource metadata (RFC 9728), /healthz and /readyz. +// resource metadata (RFC 9728), /healthz and /readyz, and OpenAI's domain +// challenge when one is set. func Handler(cfg Config) (http.Handler, error) { if err := cfg.validate(); err != nil { return nil, err @@ -154,6 +169,12 @@ func Handler(cfg Config) (http.Handler, error) { } _, _ = w.Write([]byte("ok\n")) }) + if token := cfg.OpenAIDomainChallenge; token != "" { + mux.HandleFunc("GET "+openAIChallengePath, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = w.Write([]byte(token)) + }) + } mux.Handle(mcpPath, auth.RequireBearerToken(h.verify, &auth.RequireBearerTokenOptions{ ResourceMetadataURL: metadataURL, })(h.withServer(streamable))) diff --git a/pkg/mcp/hosted/host_test.go b/pkg/mcp/hosted/host_test.go index 1e18b41..ad200db 100644 --- a/pkg/mcp/hosted/host_test.go +++ b/pkg/mcp/hosted/host_test.go @@ -1306,3 +1306,65 @@ func TestAThrottledAddressStillRefreshesATokenNearExpiry(t *testing.T) { t.Errorf("exchanges = %d, want a refresh after %d", core.exchanges, asked) } } + +// OpenAI's plugin directory verifies a remote MCP server's domain by fetching +// a token from it (SHIP-745). The body must be the token and nothing else. +func TestOpenAIDomainChallenge(t *testing.T) { + core := newFakeCore(t) + cfg := Config{ + ResourceURL: "https://mcp.example.test/mcp", + SiteURL: core.server.URL, + ClientID: "host", + ClientSecret: secret, + } + + t.Run("unset, the path is not found", func(t *testing.T) { + if status := get(t, newHost(t, core), openAIChallengePath); status != http.StatusNotFound { + t.Errorf("%s = %d without a token", openAIChallengePath, status) + } + }) + + t.Run("set, the body is exactly the token, without a bearer token", func(t *testing.T) { + withToken := cfg + withToken.OpenAIDomainChallenge = "oai-challenge-1234" + handler, err := Handler(withToken) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + resp, err := http.Get(srv.URL + openAIChallengePath) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK || string(body) != "oai-challenge-1234" { + t.Errorf("got %d %q", resp.StatusCode, body) + } + if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") { + t.Errorf("Content-Type = %q, want plain text", ct) + } + // Only GET: the challenge path never accepts a write. + post, err := http.Post(srv.URL+openAIChallengePath, "text/plain", strings.NewReader("x")) + if err != nil { + t.Fatal(err) + } + _ = post.Body.Close() + if post.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("POST %s = %d", openAIChallengePath, post.StatusCode) + } + // The MCP endpoint still needs a token. + if status := get(t, srv, "/mcp"); status != http.StatusUnauthorized { + t.Errorf("/mcp = %d", status) + } + }) + + for _, bad := range []string{"oai challenge", "oai-challenge\n", "\toai", "oai\x00"} { + withToken := cfg + withToken.OpenAIDomainChallenge = bad + if _, err := Handler(withToken); err == nil { + t.Errorf("token %q was accepted: OpenAI would never match it", bad) + } + } +} diff --git a/scripts/chart-test.sh b/scripts/chart-test.sh index 886da55..7f0511c 100755 --- a/scripts/chart-test.sh +++ b/scripts/chart-test.sh @@ -82,6 +82,12 @@ if render "${ok[@]}" | grep -A1 'name: SHIPYARD_MCP_BEHIND_PROXY' | grep -qF 'va else fail "SHIPYARD_MCP_BEHIND_PROXY isn't true with the ingress on" fi +if render "${ok[@]}" --set-string mcp.openaiDomainChallenge=oai-challenge-1234 \ + | grep -A1 'name: SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE' | grep -qF 'value: "oai-challenge-1234"'; then + pass "the OpenAI domain challenge reaches the server" +else + fail "the OpenAI domain challenge doesn't reach the server" +fi expect_contains "the garbage collector knows the memory limit" "name: GOMEMLIMIT" "${ok[@]}" digest="sha256:$(printf '0123456789abcdef%.0s' 1 2 3 4)" expect_contains "the image runs by digest when given one" \ @@ -111,6 +117,7 @@ expect_absent() { # A PDB with one replica would block every drain. expect_absent "no PDB with one replica" "kind: PodDisruptionBudget" "${ok[@]}" --set replicaCount=1 expect_absent "no X-Forwarded-For without the ingress" "SHIPYARD_MCP_BEHIND_PROXY" "${ok[@]}" --set ingress.enabled=false +expect_absent "no OpenAI domain challenge by default" "SHIPYARD_MCP_OPENAI_DOMAIN_CHALLENGE" "${ok[@]}" expect_absent "no NetworkPolicy when it's turned off" "kind: NetworkPolicy" "${ok[@]}" --set networkPolicy.enabled=false expect_absent "no chart Secret with an existing one" "kind: Secret" \ --set image.tag=v1.0.0 --set mcp.resourceUrl=https://mcp.example.test/mcp \