mqtt_settings.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // mqtt_settings.go - ajustes del publisher MQTT (#838): GET (sin password),
  2. // PUT (password vacío = conservar), test de conexión y propagación a los
  3. // routers NetGrip de la flota.
  4. package httpapi
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "log"
  9. "net/http"
  10. "strconv"
  11. "time"
  12. "github.com/gnacho/netpulse/agent/executor"
  13. "github.com/gnacho/netpulse/server-go/internal/auth"
  14. "github.com/gnacho/netpulse/server-go/internal/mqttpub"
  15. "github.com/gnacho/netpulse/server-go/internal/orchestr"
  16. "github.com/gnacho/netpulse/server-go/internal/sse"
  17. )
  18. // mqttRedactedPass sustituye la contraseña del broker en la copia del plan que
  19. // se persiste: el secreto viaja al agente por el canal autenticado (SSE), pero
  20. // no se duplica en orchestr_plans ni en el historial de auditoría.
  21. const mqttRedactedPass = "<redacted>"
  22. type mqttConfigResponse struct {
  23. Enabled bool `json:"enabled"`
  24. Host string `json:"host"`
  25. Port int `json:"port"`
  26. User string `json:"user"`
  27. PassSet bool `json:"passSet"`
  28. Instance string `json:"instance"`
  29. IntervalSec int `json:"intervalSec"`
  30. Running bool `json:"running"`
  31. }
  32. func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager, orchMgr *orchestr.Manager) {
  33. adapter := &dbKVAdapter{db: s.db.DB}
  34. mux.Handle("GET /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  35. if mgr == nil {
  36. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  37. return
  38. }
  39. cfg := mgr.Config()
  40. writeJSON(w, http.StatusOK, mqttConfigResponse{
  41. Enabled: cfg.Enabled, Host: cfg.Host, Port: cfg.Port, User: cfg.User,
  42. PassSet: cfg.Pass != "", Instance: cfg.Instance,
  43. IntervalSec: int(cfg.Interval.Seconds()), Running: mgr.Running(),
  44. })
  45. })))
  46. mux.Handle("PUT /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  47. if mgr == nil {
  48. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  49. return
  50. }
  51. var body struct {
  52. // Enabled es puntero (#968): un PUT parcial que solo toca otro
  53. // campo (p.ej. host) NO debe apagar el publisher por accidente.
  54. Enabled *bool `json:"enabled"`
  55. Host string `json:"host"`
  56. Port int `json:"port"`
  57. User string `json:"user"`
  58. Pass string `json:"pass"`
  59. Instance string `json:"instance"`
  60. IntervalSec int `json:"intervalSec"`
  61. }
  62. if st := readJSONBody(w, r, &body); st != 0 {
  63. return
  64. }
  65. cfg := mgr.Config()
  66. if body.Enabled != nil {
  67. cfg.Enabled = *body.Enabled
  68. }
  69. if body.Host != "" {
  70. cfg.Host = body.Host
  71. }
  72. if body.Port > 0 {
  73. cfg.Port = body.Port
  74. }
  75. if body.User != "" {
  76. cfg.User = body.User
  77. }
  78. if body.Pass != "" {
  79. cfg.Pass = body.Pass
  80. }
  81. if body.Instance != "" {
  82. cfg.Instance = body.Instance
  83. }
  84. if body.IntervalSec > 0 {
  85. cfg.Interval = time.Duration(body.IntervalSec) * time.Second
  86. }
  87. if err := mqttpub.SaveConfig(adapter, cfg); err != nil {
  88. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  89. return
  90. }
  91. mgr.Apply(cfg)
  92. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  93. })))
  94. mux.Handle("POST /api/settings/mqtt/test", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  95. if mgr == nil {
  96. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  97. return
  98. }
  99. var body struct {
  100. Host string `json:"host"`
  101. Port int `json:"port"`
  102. User string `json:"user"`
  103. Pass string `json:"pass"`
  104. }
  105. if st := readJSONBody(w, r, &body); st != 0 {
  106. return
  107. }
  108. cfg := mgr.Config()
  109. if body.Host != "" {
  110. cfg.Host = body.Host
  111. }
  112. if body.Port > 0 {
  113. cfg.Port = body.Port
  114. }
  115. if body.User != "" {
  116. cfg.User = body.User
  117. }
  118. if body.Pass != "" {
  119. cfg.Pass = body.Pass
  120. }
  121. if err := mqttpub.Probe(r.Context(), cfg); err != nil {
  122. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  123. return
  124. }
  125. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  126. })))
  127. // propagate envía la configuración del broker a cada router NetGrip de la
  128. // flota (op mqtt.configure) por SSE, al agente embebido en su NetGrip.
  129. //
  130. // Cada router recibe un plan REAL (fila en orchestr_plans, marcado
  131. // applying antes del envío) y se identifica en la respuesta con su planId.
  132. // La respuesta solo afirma que el comando quedó ENCOLADO en el agente: el
  133. // resultado real llega después por POST /api/agents/{slug}/apply-result.
  134. mux.Handle("POST /api/settings/mqtt/propagate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. if mgr == nil {
  136. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  137. return
  138. }
  139. if orchMgr == nil {
  140. writeError(w, http.StatusServiceUnavailable, "orchestr_unavailable")
  141. return
  142. }
  143. cfg := mgr.Config()
  144. if !cfg.Enabled {
  145. writeError(w, http.StatusBadRequest, "mqtt_disabled", "MQTT está desactivado en este servidor")
  146. return
  147. }
  148. ov := s.lastOv()
  149. if ov == nil {
  150. writeError(w, http.StatusServiceUnavailable, "no_overview")
  151. return
  152. }
  153. if s.agentHub == nil {
  154. writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
  155. return
  156. }
  157. actor := ""
  158. if user := auth.UserFromContext(r.Context()); user != nil {
  159. actor = user.Username
  160. }
  161. intervalSec := int(cfg.Interval.Seconds())
  162. op := executor.Op{
  163. Kind: "mqtt.configure",
  164. Args: map[string]string{
  165. "enabled": "true",
  166. "host": cfg.Host,
  167. "port": strconv.Itoa(cfg.Port),
  168. "user": cfg.User,
  169. "pass": cfg.Pass,
  170. "interval": strconv.Itoa(intervalSec),
  171. },
  172. Desc: "MQTT: aplicar el broker de NetPulse",
  173. }
  174. // Copia persistida del op: el secreto se redacta (el agente recibe el
  175. // valor real por el stream autenticado).
  176. opPersisted := op
  177. opPersisted.Args = map[string]string{}
  178. for k, v := range op.Args {
  179. opPersisted.Args[k] = v
  180. }
  181. if cfg.Pass != "" {
  182. opPersisted.Args["pass"] = mqttRedactedPass
  183. }
  184. // Estado deseado persistido: la configuración del broker sin secreto.
  185. desiredJSON, _ := json.Marshal(map[string]any{
  186. "enabled": true,
  187. "host": cfg.Host,
  188. "port": cfg.Port,
  189. "user": cfg.User,
  190. "instance": cfg.Instance,
  191. "intervalSec": intervalSec,
  192. "passSet": cfg.Pass != "",
  193. })
  194. results := []map[string]any{}
  195. for _, rt := range ov.Routers {
  196. if s.agentKindOf(rt.ID) != "netgrip" {
  197. continue
  198. }
  199. res := map[string]any{
  200. "id": rt.ID, "name": rt.Name,
  201. "queued": false, "delegated": false, "status": "not_queued",
  202. }
  203. plan, err := orchMgr.CreatePlan(rt.ID, "mqtt", desiredJSON, []executor.Op{opPersisted}, actor)
  204. if err != nil {
  205. log.Printf("[netpulse] mqtt propagate: no se pudo crear el plan de %s: %v", rt.ID, err)
  206. res["error"] = "plan_error"
  207. results = append(results, res)
  208. continue
  209. }
  210. res["planId"] = plan.ID
  211. // El estado se fija ANTES de enviar: si el agente responde al
  212. // instante, su resultado encuentra el plan en applying.
  213. if err := orchMgr.SetApplying(plan.ID, actor); err != nil {
  214. log.Printf("[netpulse] mqtt propagate: no se pudo marcar applying el plan %s: %v", plan.ID, err)
  215. res["error"] = "plan_error"
  216. results = append(results, res)
  217. continue
  218. }
  219. data, _ := json.Marshal(map[string]any{"plan_id": plan.ID, "ops": []executor.Op{op}})
  220. if err := s.agentHub.SendPrivileged(rt.ID, "apply", json.RawMessage(data)); err != nil {
  221. // No se entregó: el plan vuelve a pending (no se simula éxito).
  222. s.restorePlan(orchMgr, plan.ID, "applying", "pending", actor, "sse delivery failed")
  223. if errors.Is(err, sse.ErrInsecureAgentTransport) {
  224. res["error"] = "insecure_agent_transport"
  225. } else {
  226. res["error"] = "agent_not_connected"
  227. }
  228. results = append(results, res)
  229. continue
  230. }
  231. res["queued"] = true
  232. // delegated: alias histórico de queued (compatibilidad de campo).
  233. res["delegated"] = true
  234. res["status"] = "queued"
  235. results = append(results, res)
  236. }
  237. writeJSON(w, http.StatusOK, map[string]any{"results": results})
  238. })))
  239. }