mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 20:34:19 +00:00
fix(mcp): refuse cross-origin browser requests to mcp serve --http
The Streamable HTTP handler had no cross-origin check, so a web page could call a loopback server that runs without a token. It now uses the SDK's CrossOriginProtection, which refuses cross-site browser requests and leaves non-browser clients alone.
This commit is contained in:
@@ -100,9 +100,13 @@ func NewServer(b *Builder, opts Options) (*mcp.Server, error) {
|
||||
}
|
||||
|
||||
// HTTPHandler serves srv over Streamable HTTP. A non-empty token must be sent
|
||||
// as a bearer token on every request.
|
||||
// as a bearer token on every request. Cross-origin browser requests are
|
||||
// refused, so a web page cannot reach a loopback server that has no token.
|
||||
func HTTPHandler(srv *mcp.Server, token string) http.Handler {
|
||||
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{Stateless: true})
|
||||
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{
|
||||
Stateless: true,
|
||||
CrossOriginProtection: http.NewCrossOriginProtection(),
|
||||
})
|
||||
if token == "" {
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -141,6 +141,22 @@ func TestHTTPHandler_RequiresBearerToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A web page in the browser must not reach a loopback server that has no token.
|
||||
func TestHTTPHandler_RejectsCrossOriginBrowserRequests(t *testing.T) {
|
||||
srv, err := NewServer(&Builder{Source: t.TempDir()}, Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8765/", strings.NewReader(`{}`))
|
||||
req.Header.Set("Origin", "https://evil.example")
|
||||
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
rec := httptest.NewRecorder()
|
||||
HTTPHandler(srv, "").ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("cross-origin request: status %d, want 403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServer_SeesNewSkillWithoutRestart(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
cs := connect(t, src)
|
||||
|
||||
Reference in New Issue
Block a user