mcp_gate_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // mcp_gate_test.go - /mcp como integración (#1114): el toggle
  2. // settings.integrations.mcp (default activo cuando el endpoint está montado
  3. // vía NETPULSE_MCP_ENABLED=1) apaga el endpoint con 404 sin reiniciar.
  4. package httpapi_test
  5. import (
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/gnacho/netpulse/server-go/internal/adapters"
  13. "github.com/gnacho/netpulse/server-go/internal/apitoken"
  14. "github.com/gnacho/netpulse/server-go/internal/auth"
  15. "github.com/gnacho/netpulse/server-go/internal/channelplan"
  16. "github.com/gnacho/netpulse/server-go/internal/config"
  17. "github.com/gnacho/netpulse/server-go/internal/configbackup"
  18. "github.com/gnacho/netpulse/server-go/internal/db"
  19. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  20. "github.com/gnacho/netpulse/server-go/internal/mcp"
  21. "github.com/gnacho/netpulse/server-go/internal/orchestr"
  22. "github.com/gnacho/netpulse/server-go/internal/sse"
  23. )
  24. // makeMCPTestServer levanta la app real con NETPULSE_MCP_ENABLED=1 y el
  25. // servidor MCP montado (poller sin snapshot: los tools dan isError, el gate
  26. // no depende de ello).
  27. func makeMCPTestServer(t *testing.T) *testServer {
  28. t.Helper()
  29. dataDir := t.TempDir()
  30. cfg, err := config.Load(map[string]string{
  31. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  32. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  33. "NETPULSE_MCP_ENABLED": "1",
  34. }, dataDir)
  35. if err != nil {
  36. t.Fatalf("config: %v", err)
  37. }
  38. d, err := db.Open(dataDir)
  39. if err != nil {
  40. t.Fatalf("db: %v", err)
  41. }
  42. secret, err := auth.EnsureSessionSecret(d, cfg)
  43. if err != nil {
  44. t.Fatalf("secret: %v", err)
  45. }
  46. if err := auth.EnsureUsers(d, cfg); err != nil {
  47. t.Fatalf("users: %v", err)
  48. }
  49. if err := apitoken.EnsureSchema(d); err != nil {
  50. t.Fatalf("api_tokens schema: %v", err)
  51. }
  52. tokenStore := apitoken.NewStore(d, secret)
  53. configBackup, err := configbackup.NewStore(d)
  54. if err != nil {
  55. t.Fatalf("config backup store: %v", err)
  56. }
  57. mcpSrv := mcp.New(mcp.Deps{LastOverview: func() *adapters.Overview { return nil }, Version: "test"})
  58. handler := httpapi.NewHandler(httpapi.Deps{
  59. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
  60. Secret: secret, Started: time.Now(), TokenStore: tokenStore,
  61. ConfigBackup: configBackup, Orchestr: orchestr.New(d), Agents: adapters.NewAgentRegistry(0),
  62. ChannelPlan: channelplan.NewStore(d.DB), MCP: mcpSrv,
  63. })
  64. srv := httptest.NewServer(handler)
  65. t.Cleanup(func() { srv.Close(); d.Close() })
  66. return &testServer{Server: srv, db: d, secret: secret}
  67. }
  68. func mcpPost(t *testing.T, url, cookie, body string) (int, string) {
  69. t.Helper()
  70. req, err := http.NewRequest("POST", url+"/mcp", strings.NewReader(body))
  71. if err != nil {
  72. t.Fatalf("NewRequest: %v", err)
  73. }
  74. req.Header.Set("Content-Type", "application/json")
  75. req.Header.Set("Accept", "application/json")
  76. if cookie != "" {
  77. req.Header.Set("Cookie", cookie)
  78. }
  79. res, err := http.DefaultClient.Do(req)
  80. if err != nil {
  81. t.Fatalf("Do: %v", err)
  82. }
  83. defer res.Body.Close()
  84. buf := new(strings.Builder)
  85. _, _ = io.Copy(buf, res.Body)
  86. return res.StatusCode, buf.String()
  87. }
  88. func TestMCPGateDefaultOn(t *testing.T) {
  89. srv := makeMCPTestServer(t)
  90. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  91. // View: mcp activo (montado + default on) y no bloqueado.
  92. res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
  93. if res.StatusCode != http.StatusOK {
  94. t.Fatalf("GET integrations: status %d", res.StatusCode)
  95. }
  96. if body["mcp"] != true || body["mcpLocked"] != false {
  97. t.Fatalf("view mcp: %v / locked %v, esperado true/false", body["mcp"], body["mcpLocked"])
  98. }
  99. // /mcp responde (401 sin token Bearer: la auth propia sigue aplicando).
  100. status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
  101. if status != http.StatusUnauthorized {
  102. t.Fatalf("/mcp sin token: status %d, esperado 401 (endpoint vivo)", status)
  103. }
  104. }
  105. func TestMCPGateToggleOffHidesEndpoint(t *testing.T) {
  106. srv := makeMCPTestServer(t)
  107. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  108. // Apagar la integración: sin reinicio el endpoint desaparece (404).
  109. res, body := wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"mcp":false}`)
  110. if res.StatusCode != http.StatusOK {
  111. t.Fatalf("PUT mcp=false: status %d (%v)", res.StatusCode, body)
  112. }
  113. if body["mcp"] != false {
  114. t.Fatalf("echo mcp: %v, esperado false", body["mcp"])
  115. }
  116. status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
  117. if status != http.StatusNotFound {
  118. t.Fatalf("/mcp con integración off: status %d, esperado 404", status)
  119. }
  120. // Reactivar: vuelve a responder (401) sin reiniciar.
  121. res, body = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"mcp":true}`)
  122. if res.StatusCode != http.StatusOK || body["mcp"] != true {
  123. t.Fatalf("PUT mcp=true: status %d (%v)", res.StatusCode, body)
  124. }
  125. status, _ = mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
  126. if status != http.StatusUnauthorized {
  127. t.Fatalf("/mcp reactivado: status %d, esperado 401", status)
  128. }
  129. }
  130. func TestMCPLockedWithoutEnv(t *testing.T) {
  131. // Sin NETPULSE_MCP_ENABLED el endpoint no se monta: la view lo reporta
  132. // bloqueado y /mcp es 404 aunque el toggle kv diga otra cosa.
  133. srv := makeTestServer(t)
  134. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  135. res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
  136. if res.StatusCode != http.StatusOK {
  137. t.Fatalf("GET integrations: status %d", res.StatusCode)
  138. }
  139. if body["mcp"] != false || body["mcpLocked"] != true {
  140. t.Fatalf("view sin env: mcp %v / locked %v, esperado false/true", body["mcp"], body["mcpLocked"])
  141. }
  142. status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
  143. if status != http.StatusNotFound {
  144. t.Fatalf("/mcp sin env: status %d, esperado 404 (no montado)", status)
  145. }
  146. }