mqtt_settings.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. "github.com/gnacho/netpulse/server-go/internal/vercmp"
  18. )
  19. // mqttRedactedPass sustituye la contraseña del broker en la copia del plan que
  20. // se persiste: el secreto viaja al agente por el canal autenticado (SSE), pero
  21. // no se duplica en orchestr_plans ni en el historial de auditoría.
  22. const mqttRedactedPass = "<redacted>"
  23. // netgripMQTTTLSMinVersion is the first NetGrip release that reads the tls and
  24. // tlsInsecure arguments of mqtt.configure. Older agents keep only the original
  25. // seven args, so a TLS config is not propagated to them at all.
  26. const netgripMQTTTLSMinVersion = "0.78.0"
  27. // agentSupportsMQTTTLS reports whether an agent version understands the TLS
  28. // arguments. An empty or unparsable version is treated as unsupported: better
  29. // to ask for an update than to silently configure the router without TLS.
  30. func agentSupportsMQTTTLS(version string) bool {
  31. if _, ok := vercmp.Parse3(version); !ok {
  32. return false
  33. }
  34. return vercmp.Cmp(version, netgripMQTTTLSMinVersion) >= 0
  35. }
  36. type mqttConfigResponse struct {
  37. Enabled bool `json:"enabled"`
  38. Host string `json:"host"`
  39. Port int `json:"port"`
  40. User string `json:"user"`
  41. PassSet bool `json:"passSet"`
  42. Instance string `json:"instance"`
  43. IntervalSec int `json:"intervalSec"`
  44. TLS bool `json:"tls"`
  45. TLSInsecure bool `json:"tlsInsecure"`
  46. Running bool `json:"running"`
  47. }
  48. func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager, orchMgr *orchestr.Manager) {
  49. adapter := &dbKVAdapter{db: s.db.DB}
  50. mux.Handle("GET /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  51. if mgr == nil {
  52. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  53. return
  54. }
  55. cfg := mgr.Config()
  56. writeJSON(w, http.StatusOK, mqttConfigResponse{
  57. Enabled: cfg.Enabled, Host: cfg.Host, Port: cfg.Port, User: cfg.User,
  58. PassSet: cfg.Pass != "", Instance: cfg.Instance,
  59. IntervalSec: int(cfg.Interval.Seconds()), TLS: cfg.TLS, TLSInsecure: cfg.TLSInsecure,
  60. Running: mgr.Running(),
  61. })
  62. })))
  63. mux.Handle("PUT /api/settings/mqtt", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  64. if mgr == nil {
  65. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  66. return
  67. }
  68. var body struct {
  69. // Enabled es puntero (#968): un PUT parcial que solo toca otro
  70. // campo (p.ej. host) NO debe apagar el publisher por accidente.
  71. Enabled *bool `json:"enabled"`
  72. Host string `json:"host"`
  73. Port int `json:"port"`
  74. User string `json:"user"`
  75. Pass string `json:"pass"`
  76. Instance string `json:"instance"`
  77. IntervalSec int `json:"intervalSec"`
  78. TLS *bool `json:"tls"`
  79. TLSInsecure *bool `json:"tlsInsecure"`
  80. }
  81. if st := readJSONBody(w, r, &body); st != 0 {
  82. return
  83. }
  84. cfg := mgr.Config()
  85. if body.Enabled != nil {
  86. cfg.Enabled = *body.Enabled
  87. }
  88. if body.Host != "" {
  89. cfg.Host = body.Host
  90. }
  91. if body.Port > 0 {
  92. cfg.Port = body.Port
  93. }
  94. if body.User != "" {
  95. cfg.User = body.User
  96. }
  97. if body.Pass != "" {
  98. cfg.Pass = body.Pass
  99. }
  100. if body.Instance != "" {
  101. cfg.Instance = body.Instance
  102. }
  103. if body.IntervalSec > 0 {
  104. cfg.Interval = time.Duration(body.IntervalSec) * time.Second
  105. }
  106. if body.TLS != nil {
  107. cfg.TLS = *body.TLS
  108. }
  109. if body.TLSInsecure != nil {
  110. cfg.TLSInsecure = *body.TLSInsecure
  111. }
  112. if !cfg.TLS {
  113. cfg.TLSInsecure = false
  114. }
  115. if err := mqttpub.SaveConfig(adapter, cfg); err != nil {
  116. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  117. return
  118. }
  119. mgr.Apply(cfg)
  120. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  121. })))
  122. mux.Handle("POST /api/settings/mqtt/test", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. if mgr == nil {
  124. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  125. return
  126. }
  127. var body struct {
  128. Host string `json:"host"`
  129. Port int `json:"port"`
  130. User string `json:"user"`
  131. Pass string `json:"pass"`
  132. TLS *bool `json:"tls"`
  133. TLSInsecure *bool `json:"tlsInsecure"`
  134. }
  135. if st := readJSONBody(w, r, &body); st != 0 {
  136. return
  137. }
  138. cfg := mgr.Config()
  139. if body.Host != "" {
  140. cfg.Host = body.Host
  141. }
  142. if body.Port > 0 {
  143. cfg.Port = body.Port
  144. }
  145. if body.User != "" {
  146. cfg.User = body.User
  147. }
  148. if body.Pass != "" {
  149. cfg.Pass = body.Pass
  150. }
  151. if body.TLS != nil {
  152. cfg.TLS = *body.TLS
  153. }
  154. if body.TLSInsecure != nil {
  155. cfg.TLSInsecure = *body.TLSInsecure
  156. }
  157. if !cfg.TLS {
  158. cfg.TLSInsecure = false
  159. }
  160. if err := mqttpub.Probe(r.Context(), cfg); err != nil {
  161. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  162. return
  163. }
  164. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  165. })))
  166. // propagate envía la configuración del broker a cada router NetGrip de la
  167. // flota (op mqtt.configure) por SSE, al agente embebido en su NetGrip.
  168. //
  169. // Cada router recibe un plan REAL (fila en orchestr_plans, marcado
  170. // applying antes del envío) y se identifica en la respuesta con su planId.
  171. // La respuesta solo afirma que el comando quedó ENCOLADO en el agente: el
  172. // resultado real llega después por POST /api/agents/{slug}/apply-result.
  173. mux.Handle("POST /api/settings/mqtt/propagate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  174. if mgr == nil {
  175. writeError(w, http.StatusServiceUnavailable, "mqtt_unavailable")
  176. return
  177. }
  178. if orchMgr == nil {
  179. writeError(w, http.StatusServiceUnavailable, "orchestr_unavailable")
  180. return
  181. }
  182. cfg := mgr.Config()
  183. if !cfg.Enabled {
  184. writeError(w, http.StatusBadRequest, "mqtt_disabled", "MQTT está desactivado en este servidor")
  185. return
  186. }
  187. ov := s.lastOv()
  188. if ov == nil {
  189. writeError(w, http.StatusServiceUnavailable, "no_overview")
  190. return
  191. }
  192. if s.agentHub == nil {
  193. writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
  194. return
  195. }
  196. actor := ""
  197. if user := auth.UserFromContext(r.Context()); user != nil {
  198. actor = user.Username
  199. }
  200. intervalSec := int(cfg.Interval.Seconds())
  201. op := executor.Op{
  202. Kind: "mqtt.configure",
  203. Args: map[string]string{
  204. "enabled": "true",
  205. "host": cfg.Host,
  206. "port": strconv.Itoa(cfg.Port),
  207. "user": cfg.User,
  208. "pass": cfg.Pass,
  209. "interval": strconv.Itoa(intervalSec),
  210. },
  211. Desc: "MQTT: aplicar el broker de NetPulse",
  212. }
  213. if cfg.TLS {
  214. // Added last on purpose: an old NetGrip decodes only the original
  215. // seven keys and would drop TLS without saying so, so propagation
  216. // is refused below unless the agent reports a version that knows
  217. // them.
  218. op.Args["tls"] = "1"
  219. op.Args["tlsInsecure"] = strconv.FormatBool(cfg.TLSInsecure)
  220. }
  221. // Copia persistida del op: el secreto se redacta (el agente recibe el
  222. // valor real por el stream autenticado).
  223. opPersisted := op
  224. opPersisted.Args = map[string]string{}
  225. for k, v := range op.Args {
  226. opPersisted.Args[k] = v
  227. }
  228. if cfg.Pass != "" {
  229. opPersisted.Args["pass"] = mqttRedactedPass
  230. }
  231. // Estado deseado persistido: la configuración del broker sin secreto.
  232. desiredJSON, _ := json.Marshal(map[string]any{
  233. "enabled": true,
  234. "host": cfg.Host,
  235. "port": cfg.Port,
  236. "user": cfg.User,
  237. "instance": cfg.Instance,
  238. "intervalSec": intervalSec,
  239. "tls": cfg.TLS,
  240. "tlsInsecure": cfg.TLSInsecure,
  241. "passSet": cfg.Pass != "",
  242. })
  243. results := []map[string]any{}
  244. for _, rt := range ov.Routers {
  245. if s.agentKindOf(rt.ID) != "netgrip" {
  246. continue
  247. }
  248. res := map[string]any{
  249. "id": rt.ID, "name": rt.Name,
  250. "queued": false, "delegated": false, "status": "not_queued",
  251. }
  252. if cfg.TLS {
  253. _, ver, _, _, _ := s.agents.Info(rt.ID)
  254. if !agentSupportsMQTTTLS(ver) {
  255. res["error"] = "netgrip_update_required"
  256. results = append(results, res)
  257. continue
  258. }
  259. }
  260. plan, err := orchMgr.CreatePlan(rt.ID, "mqtt", desiredJSON, []executor.Op{opPersisted}, actor)
  261. if err != nil {
  262. log.Printf("[netpulse] mqtt propagate: no se pudo crear el plan de %s: %v", rt.ID, err)
  263. res["error"] = "plan_error"
  264. results = append(results, res)
  265. continue
  266. }
  267. res["planId"] = plan.ID
  268. // El estado se fija ANTES de enviar: si el agente responde al
  269. // instante, su resultado encuentra el plan en applying.
  270. if err := orchMgr.SetApplying(plan.ID, actor); err != nil {
  271. log.Printf("[netpulse] mqtt propagate: no se pudo marcar applying el plan %s: %v", plan.ID, err)
  272. res["error"] = "plan_error"
  273. results = append(results, res)
  274. continue
  275. }
  276. data, _ := json.Marshal(map[string]any{"plan_id": plan.ID, "ops": []executor.Op{op}})
  277. if err := s.agentHub.SendPrivileged(rt.ID, "apply", json.RawMessage(data)); err != nil {
  278. // No se entregó: el plan vuelve a pending (no se simula éxito).
  279. s.restorePlan(orchMgr, plan.ID, "applying", "pending", actor, "sse delivery failed")
  280. if errors.Is(err, sse.ErrInsecureAgentTransport) {
  281. res["error"] = "insecure_agent_transport"
  282. } else {
  283. res["error"] = "agent_not_connected"
  284. }
  285. results = append(results, res)
  286. continue
  287. }
  288. res["queued"] = true
  289. // delegated: alias histórico de queued (compatibilidad de campo).
  290. res["delegated"] = true
  291. res["status"] = "queued"
  292. results = append(results, res)
  293. }
  294. writeJSON(w, http.StatusOK, map[string]any{"results": results})
  295. })))
  296. }