config.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. // config.go — rutas /api/config/* (paridad src/routes/config.js, SPEC §2.17):
  2. // CRUD de routers (tabla `routers`), clave SSH propia del servidor,
  3. // descubrimiento de la LAN y credenciales AdGuard GL.iNet (kv; la contraseña
  4. // NUNCA se devuelve). Tras cada mutación se sincroniza el adapter
  5. // (SetRouters) sin reiniciar.
  6. package httpapi
  7. import (
  8. "database/sql"
  9. "net/http"
  10. urlpkg "net/url"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "github.com/gnacho/netpulse/server-go/internal/adapters"
  15. "github.com/gnacho/netpulse/server-go/internal/auth"
  16. "github.com/gnacho/netpulse/server-go/internal/discover"
  17. "github.com/gnacho/netpulse/server-go/internal/pve"
  18. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  19. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  20. )
  21. var (
  22. hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  23. hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
  24. )
  25. // registerConfigRoutes registra las rutas /api/config/* en el mux.
  26. // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
  27. // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
  28. // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
  29. func (s *server) registerConfigRoutes(mux *http.ServeMux) {
  30. mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
  31. mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
  32. mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
  33. mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
  34. mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
  35. mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
  36. mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
  37. mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
  38. mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
  39. mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
  40. mux.Handle("POST /api/config/adguard/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectAdguard)))
  41. mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
  42. mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
  43. mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
  44. mux.Handle("POST /api/config/proxmox/test", auth.RequireAdmin(http.HandlerFunc(s.handleTestProxmoxConfig)))
  45. mux.Handle("POST /api/config/proxmox/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectProxmox)))
  46. }
  47. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  48. func (s *server) syncRouters() {
  49. if s.adapter != nil {
  50. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  51. }
  52. }
  53. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  54. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  55. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  56. if key == nil {
  57. writeError(w, http.StatusInternalServerError, "no_key")
  58. return
  59. }
  60. writeJSON(w, http.StatusOK, key)
  61. }
  62. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  63. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  64. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  65. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  66. // (la UI pide escribir la palabra de confirmación).
  67. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  68. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  69. if err != nil {
  70. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  71. return
  72. }
  73. writeJSON(w, http.StatusOK, map[string]any{
  74. "publicKey": key.PublicKey,
  75. "fingerprint": key.Fingerprint,
  76. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  77. })
  78. }
  79. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  80. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  81. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  82. writeJSON(w, http.StatusOK, result)
  83. }
  84. // routerListItem es la vista HTTP de un router. Omite la comunidad SNMP,
  85. // que solo necesita el adapter para sondear, y expone si esta configurada.
  86. type routerListItem struct {
  87. ID string `json:"id"`
  88. Name string `json:"name"`
  89. Host string `json:"host"`
  90. Type string `json:"type"`
  91. IsGateway bool `json:"is_gateway"`
  92. AgentOnly bool `json:"agent_only"`
  93. // InventoryMode (#1917): "auto" | "agent" | "ssh".
  94. InventoryMode string `json:"inventory_mode,omitempty"`
  95. CreatedAt int64 `json:"created_at"`
  96. FirmwareTarget string `json:"firmware_target,omitempty"`
  97. SnmpEnabled bool `json:"snmp_enabled"`
  98. SnmpCommunitySet bool `json:"snmp_community_set"`
  99. SnmpPort int `json:"snmp_port,omitempty"`
  100. SnmpPollInterval int `json:"snmp_poll_interval,omitempty"`
  101. Disabled bool `json:"disabled"`
  102. ConsolePolling bool `json:"console_polling"`
  103. SSHPort int `json:"ssh_port,omitempty"`
  104. TempThreshold *int `json:"temp_threshold,omitempty"`
  105. }
  106. func newRouterListItem(rt adapters.RouterConfig) routerListItem {
  107. return routerListItem{
  108. ID: rt.ID,
  109. Name: rt.Name,
  110. Host: rt.Host,
  111. Type: rt.Type,
  112. IsGateway: rt.IsGateway,
  113. AgentOnly: rt.AgentOnly,
  114. InventoryMode: rt.InventoryMode,
  115. CreatedAt: rt.CreatedAt,
  116. FirmwareTarget: rt.FirmwareTarget,
  117. SnmpEnabled: rt.SnmpEnabled,
  118. SnmpCommunitySet: rt.SnmpCommunity != "",
  119. SnmpPort: rt.SnmpPort,
  120. SnmpPollInterval: rt.SnmpPollInterval,
  121. Disabled: rt.Disabled,
  122. ConsolePolling: rt.ConsolePolling,
  123. SSHPort: rt.SSHPort,
  124. TempThreshold: rt.TempThreshold,
  125. }
  126. }
  127. // GET /api/config/routers — lista configurada (no el estado sondeado).
  128. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  129. routers := routerstore.ListRouters(s.db.DB)
  130. items := make([]routerListItem, 0, len(routers))
  131. for _, rt := range routers {
  132. items = append(items, newRouterListItem(rt))
  133. }
  134. writeJSON(w, http.StatusOK, map[string]any{"routers": items})
  135. }
  136. type routerInput struct {
  137. Name *string `json:"name"`
  138. Host *string `json:"host"`
  139. Type string `json:"type"`
  140. // Gateway y AgentOnly son punteros por el mismo motivo que el resto:
  141. // ausente significa "no lo toques". Con bool a secas, un PUT parcial
  142. // (por ejemplo el que solo cambia inventory_mode) los reiniciaba a
  143. // false y tiraba el gateway o el agent-only de la unidad (#1937).
  144. Gateway *bool `json:"gateway"`
  145. AgentOnly *bool `json:"agent_only"`
  146. // InventoryMode (#1917): "auto" | "agent" | "ssh". Manda sobre agent_only.
  147. InventoryMode *string `json:"inventory_mode"`
  148. // Disabled (issue #1085): pausa la unidad (nil = no tocar).
  149. Disabled *bool `json:"disabled"`
  150. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  151. FirmwareTarget *string `json:"firmware_target"`
  152. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  153. SnmpEnabled *bool `json:"snmp_enabled"`
  154. // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
  155. ConsolePolling *bool `json:"console_polling"`
  156. SnmpCommunity *string `json:"snmp_community"`
  157. SnmpPort *int `json:"snmp_port"`
  158. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  159. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  160. // estándar). Ausente/0 → 22.
  161. SSHPort *int `json:"ssh_port"`
  162. // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
  163. // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
  164. TempThreshold *int `json:"temp_threshold"`
  165. }
  166. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  167. // trimmeado o "" + mensaje de error.
  168. func validateHost(host string) (string, string) {
  169. h := strings.TrimSpace(host)
  170. if len(h) < 1 {
  171. return "", "String must contain at least 1 character(s)"
  172. }
  173. if len(h) > 253 {
  174. return "", "String must contain at most 253 character(s)"
  175. }
  176. if !hostRe.MatchString(h) {
  177. return "", "host debe ser una IP o hostname válido"
  178. }
  179. return h, ""
  180. }
  181. // validateInventoryMode (#1917): "" se acepta y el store lo interpreta como
  182. // "auto" implicito (compatibilidad con clientes que no mandan el campo).
  183. func validateInventoryMode(v *string) (string, string) {
  184. if v == nil {
  185. return "", ""
  186. }
  187. m := strings.TrimSpace(*v)
  188. switch m {
  189. case "", "auto", "agent", "ssh":
  190. return m, ""
  191. }
  192. return "", "Invalid enum value. Expected 'auto' | 'agent' | 'ssh'"
  193. }
  194. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  195. // host, puerto y mensaje de error.
  196. func validateAdGuardHost(host string) (string, int, string) {
  197. h := strings.TrimSpace(host)
  198. if len(h) < 1 {
  199. return "", 0, "String must contain at least 1 character(s)"
  200. }
  201. if len(h) > 253 {
  202. return "", 0, "String must contain at most 253 character(s)"
  203. }
  204. m := hostPortRe.FindStringSubmatch(h)
  205. if m == nil {
  206. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  207. }
  208. addr := m[1]
  209. port := 0
  210. if m[2] != "" {
  211. p, err := strconv.Atoi(m[2][1:])
  212. if err != nil || p < 1 || p > 65535 {
  213. return "", 0, "puerto fuera de rango (1-65535)"
  214. }
  215. port = p
  216. }
  217. return addr, port, ""
  218. }
  219. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  220. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  221. var in routerInput
  222. if st := readJSONBody(w, r, &in); st != 0 {
  223. writeBodyError(w, st, "invalid_json", "")
  224. return
  225. }
  226. // Orden de validación del schema zod: name, host, type
  227. name := ""
  228. if in.Name != nil {
  229. name = strings.TrimSpace(*in.Name)
  230. if len(name) < 1 {
  231. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  232. return
  233. }
  234. if len(name) > 60 {
  235. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  236. return
  237. }
  238. }
  239. if in.Host == nil {
  240. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  241. return
  242. }
  243. host, msg := validateHost(*in.Host)
  244. if msg != "" {
  245. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  246. return
  247. }
  248. typ := in.Type
  249. if typ == "" {
  250. typ = "openwrt"
  251. }
  252. if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
  253. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  254. return
  255. }
  256. var firmwareTarget string
  257. if in.FirmwareTarget != nil {
  258. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  259. }
  260. snmpEnabled := false
  261. if in.SnmpEnabled != nil {
  262. snmpEnabled = *in.SnmpEnabled
  263. }
  264. snmpCommunity := ""
  265. if in.SnmpCommunity != nil {
  266. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  267. }
  268. snmpPort := 0
  269. if in.SnmpPort != nil {
  270. snmpPort = *in.SnmpPort
  271. if snmpPort < 0 || snmpPort > 65535 {
  272. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  273. return
  274. }
  275. }
  276. snmpInterval := 60
  277. if in.SnmpPollInterval != nil {
  278. snmpInterval = *in.SnmpPollInterval
  279. if snmpInterval < 10 || snmpInterval > 3600 {
  280. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  281. return
  282. }
  283. }
  284. for _, rt := range routerstore.ListRouters(s.db.DB) {
  285. if rt.Host == host {
  286. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  287. return
  288. }
  289. }
  290. sshPort := 0
  291. if in.SSHPort != nil {
  292. p := *in.SSHPort
  293. if p < 1 || p > 65535 {
  294. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  295. return
  296. }
  297. sshPort = p
  298. }
  299. invMode, invMsg := validateInventoryMode(in.InventoryMode)
  300. if invMsg != "" {
  301. writeError(w, http.StatusBadRequest, "invalid_input", invMsg)
  302. return
  303. }
  304. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  305. Name: name, Host: host, Type: typ,
  306. IsGateway: in.Gateway != nil && *in.Gateway, AgentOnly: in.AgentOnly != nil && *in.AgentOnly,
  307. InventoryMode: invMode,
  308. FirmwareTarget: firmwareTarget,
  309. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  310. SSHPort: sshPort,
  311. })
  312. if err != nil {
  313. writeError(w, http.StatusInternalServerError, "internal_error")
  314. return
  315. }
  316. s.syncRouters()
  317. writeJSON(w, http.StatusCreated, map[string]any{"router": newRouterListItem(created)})
  318. }
  319. // DELETE /api/config/routers/:id — 204 o 404.
  320. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  321. id := r.PathValue("id")
  322. // #1276: MAC aprendida del último push del agente (bridge MAC), para
  323. // purgar su entrada del registro de clientes tras borrar el router.
  324. var macs []string
  325. if s.agents != nil {
  326. if p, ok := s.agents.StalePayload(id); ok {
  327. if sys := p.Data.System; sys != nil && sys.BridgeMAC != "" {
  328. macs = append(macs, sys.BridgeMAC)
  329. }
  330. }
  331. }
  332. if !routerstore.RemoveRouter(s.db.DB, id) {
  333. writeError(w, http.StatusNotFound, "not_found")
  334. return
  335. }
  336. // #1276: limpieza del stub de Dispositivos/Agentes. Sin esto, el estado
  337. // persistido (agent.state.*) y el registro seguían listando la unidad
  338. // borrada sin forma de quitarla. Se revoca TAMBIÉN el token: si el
  339. // agente sigue instalado en la caja, su siguiente push recibe 401 y
  340. // deja de re-crear la entrada. Re-añadir el router requiere re-emparejar
  341. // el agente (reinstall).
  342. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKeyPrefix+id)
  343. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentStateKeyPrefix+id)
  344. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTransportPrefix+id)
  345. if s.agents != nil {
  346. s.agents.Forget(id)
  347. }
  348. for _, m := range macs {
  349. _, _ = s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?",
  350. strings.ToUpper(m), strings.ToLower(strings.ReplaceAll(m, ":", "-")))
  351. }
  352. s.syncRouters()
  353. w.WriteHeader(http.StatusNoContent)
  354. }
  355. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  356. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  357. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  358. id := r.PathValue("id")
  359. var in routerInput
  360. if st := readJSONBody(w, r, &in); st != 0 {
  361. writeBodyError(w, st, "invalid_json", "")
  362. return
  363. }
  364. var name *string
  365. if in.Name != nil {
  366. n := strings.TrimSpace(*in.Name)
  367. if len(n) < 1 {
  368. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  369. return
  370. }
  371. if len(n) > 60 {
  372. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  373. return
  374. }
  375. name = &n
  376. }
  377. var host *string
  378. if in.Host != nil {
  379. h, msg := validateHost(*in.Host)
  380. if msg != "" {
  381. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  382. return
  383. }
  384. // Duplicado: otro router con ese host (excluyendo el propio id).
  385. for _, rt := range routerstore.ListRouters(s.db.DB) {
  386. if rt.Host == h && rt.ID != id {
  387. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  388. return
  389. }
  390. }
  391. host = &h
  392. }
  393. var typ *string
  394. if in.Type != "" {
  395. t := in.Type
  396. if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
  397. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  398. return
  399. }
  400. typ = &t
  401. }
  402. var invMode *string
  403. if in.InventoryMode != nil {
  404. m, msg := validateInventoryMode(in.InventoryMode)
  405. if msg != "" {
  406. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  407. return
  408. }
  409. invMode = &m
  410. }
  411. var firmwareTarget *string
  412. if in.FirmwareTarget != nil {
  413. v := strings.TrimSpace(*in.FirmwareTarget)
  414. firmwareTarget = &v
  415. }
  416. var snmpPollInterval *int
  417. if in.SnmpPollInterval != nil {
  418. v := *in.SnmpPollInterval
  419. if v < 10 || v > 3600 {
  420. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  421. return
  422. }
  423. snmpPollInterval = &v
  424. }
  425. var snmpPort *int
  426. if in.SnmpPort != nil {
  427. p := *in.SnmpPort
  428. if p < 0 || p > 65535 {
  429. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  430. return
  431. }
  432. snmpPort = &p
  433. }
  434. var snmpCommunity *string
  435. if in.SnmpCommunity != nil {
  436. v := strings.TrimSpace(*in.SnmpCommunity)
  437. snmpCommunity = &v
  438. }
  439. var sshPort *int
  440. if in.SSHPort != nil {
  441. p := *in.SSHPort
  442. if p < 1 || p > 65535 {
  443. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  444. return
  445. }
  446. sshPort = &p
  447. }
  448. var tempThreshold *int
  449. if in.TempThreshold != nil {
  450. v := *in.TempThreshold
  451. if v > 150 {
  452. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  453. return
  454. }
  455. tempThreshold = &v
  456. }
  457. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  458. Name: name, Host: host, Type: typ,
  459. IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  460. InventoryMode: invMode,
  461. Disabled: in.Disabled,
  462. FirmwareTarget: firmwareTarget,
  463. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  464. SSHPort: sshPort,
  465. TempThreshold: tempThreshold,
  466. ConsolePolling: in.ConsolePolling,
  467. })
  468. if !ok {
  469. writeError(w, http.StatusNotFound, "not_found")
  470. return
  471. }
  472. s.syncRouters()
  473. writeJSON(w, http.StatusOK, map[string]any{"router": newRouterListItem(updated)})
  474. }
  475. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  476. func kvGet(db *sql.DB, key string) string {
  477. var v string
  478. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  479. return ""
  480. }
  481. return v
  482. }
  483. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  484. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  485. user := kvGet(s.db.DB, "adguard_user")
  486. if user == "" {
  487. user = "root"
  488. }
  489. mode := kvGet(s.db.DB, "adguard_mode")
  490. if mode == "" {
  491. mode = "glinet"
  492. }
  493. portStr := kvGet(s.db.DB, "adguard_port")
  494. port := 0
  495. if p, err := strconv.Atoi(portStr); err == nil {
  496. port = p
  497. }
  498. writeJSON(w, http.StatusOK, map[string]any{
  499. "mode": mode,
  500. "host": kvGet(s.db.DB, "adguard_host"),
  501. "port": port,
  502. "user": user,
  503. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  504. })
  505. }
  506. type adguardInput struct {
  507. Mode string `json:"mode"`
  508. Host *string `json:"host"`
  509. Port int `json:"port"`
  510. User string `json:"user"`
  511. Password string `json:"password"`
  512. }
  513. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  514. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  515. var in adguardInput
  516. if st := readJSONBody(w, r, &in); st != 0 {
  517. writeBodyError(w, st, "invalid_json", "")
  518. return
  519. }
  520. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  521. if mode == "" {
  522. mode = "glinet"
  523. }
  524. if mode != "glinet" && mode != "standard" {
  525. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  526. return
  527. }
  528. if in.Host == nil {
  529. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  530. return
  531. }
  532. host := strings.TrimSpace(*in.Host)
  533. port := 0
  534. if mode == "standard" {
  535. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  536. if msg != "" {
  537. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  538. return
  539. }
  540. host = hostFromVal
  541. if in.Port < 1 || in.Port > 65535 {
  542. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  543. return
  544. }
  545. port = in.Port
  546. if port == 0 {
  547. port = portFromHost
  548. }
  549. if port == 0 {
  550. port = 3000
  551. }
  552. }
  553. user := strings.TrimSpace(in.User)
  554. if user == "" {
  555. user = "root"
  556. }
  557. if len(user) > 64 {
  558. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  559. return
  560. }
  561. if len(in.Password) > 128 {
  562. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  563. return
  564. }
  565. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  566. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  567. writeError(w, http.StatusInternalServerError, "internal_error")
  568. return
  569. }
  570. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  571. writeError(w, http.StatusInternalServerError, "internal_error")
  572. return
  573. }
  574. if mode == "standard" {
  575. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  576. writeError(w, http.StatusInternalServerError, "internal_error")
  577. return
  578. }
  579. } else {
  580. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  581. writeError(w, http.StatusInternalServerError, "internal_error")
  582. return
  583. }
  584. }
  585. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  586. writeError(w, http.StatusInternalServerError, "internal_error")
  587. return
  588. }
  589. if in.Password != "" {
  590. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  591. writeError(w, http.StatusInternalServerError, "internal_error")
  592. return
  593. }
  594. }
  595. w.WriteHeader(http.StatusNoContent)
  596. }
  597. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  598. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  599. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  600. // Idempotente: 204 aunque no hubiera nada configurado.
  601. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  602. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  603. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  604. writeError(w, http.StatusInternalServerError, "internal_error")
  605. return
  606. }
  607. }
  608. if s.pollNow != nil {
  609. s.pollNow()
  610. }
  611. w.WriteHeader(http.StatusNoContent)
  612. }
  613. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  614. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  615. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  616. // para no romper frontends cacheados.
  617. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  618. instances := pve.LoadInstances(s.db.DB)
  619. // Vista sanitizada: el secret JAMAS sale del server (#764).
  620. view := make([]map[string]any, 0, len(instances))
  621. for _, in := range instances {
  622. view = append(view, map[string]any{
  623. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  624. "caPem": in.CAPEM, "fingerprintSha256": in.FingerprintSHA256, "insecure": in.Insecure,
  625. })
  626. }
  627. out := map[string]any{
  628. "instances": view,
  629. "url": "",
  630. "tokenId": "",
  631. "tokenSet": false,
  632. }
  633. if len(instances) > 0 {
  634. out["url"] = instances[0].URL
  635. out["tokenId"] = instances[0].TokenID
  636. out["tokenSet"] = instances[0].Secret != ""
  637. }
  638. writeJSON(w, http.StatusOK, out)
  639. }
  640. type proxmoxInput struct {
  641. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  642. TokenID string `json:"tokenId"`
  643. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  644. }
  645. type proxmoxInstanceInput struct {
  646. ID string `json:"id"`
  647. Name string `json:"name"`
  648. URL string `json:"url"`
  649. TokenID string `json:"tokenId"`
  650. Secret string `json:"secret"` // vacío en edición = conservar el actual
  651. CAPEM *string `json:"caPem"`
  652. FingerprintSHA256 *string `json:"fingerprintSha256"`
  653. Insecure *bool `json:"insecure"`
  654. }
  655. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  656. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  657. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  658. // migrada "default", creándola si hace falta; url "" desactiva todo).
  659. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  660. var in proxmoxInstanceInput
  661. if st := readJSONBody(w, r, &in); st != 0 {
  662. writeBodyError(w, st, "invalid_json", "")
  663. return
  664. }
  665. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  666. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  667. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  668. tokenID := strings.TrimSpace(in.TokenID)
  669. if len(tokenID) > 128 || len(in.Secret) > 256 {
  670. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  671. return
  672. }
  673. id := strings.TrimSpace(in.ID)
  674. if id == "" {
  675. id = "default" // legacy sin id
  676. }
  677. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  678. if url != "" {
  679. u, err := urlpkg.Parse(url)
  680. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  681. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  682. return
  683. }
  684. }
  685. list := pve.LoadInstances(s.db.DB)
  686. var current *pve.Instance
  687. for i := range list {
  688. if list[i].ID == id {
  689. current = &list[i]
  690. break
  691. }
  692. }
  693. if current != nil {
  694. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" &&
  695. in.CAPEM == nil && in.FingerprintSHA256 == nil && in.Insecure == nil {
  696. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  697. return
  698. }
  699. if url != "" {
  700. current.URL = url
  701. }
  702. if tokenID != "" {
  703. current.TokenID = tokenID
  704. }
  705. if in.Secret != "" {
  706. current.Secret = in.Secret
  707. }
  708. if in.CAPEM != nil {
  709. current.CAPEM = strings.TrimSpace(*in.CAPEM)
  710. }
  711. if in.FingerprintSHA256 != nil {
  712. current.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  713. }
  714. if in.Insecure != nil {
  715. current.Insecure = *in.Insecure
  716. }
  717. if n := strings.TrimSpace(in.Name); n != "" {
  718. current.Name = n
  719. }
  720. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  721. writeError(w, http.StatusInternalServerError, "internal_error")
  722. return
  723. }
  724. w.WriteHeader(http.StatusNoContent)
  725. return
  726. }
  727. // Instancia nueva: completa.
  728. if url == "" || tokenID == "" || in.Secret == "" {
  729. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  730. return
  731. }
  732. name := strings.TrimSpace(in.Name)
  733. if name == "" {
  734. name = id
  735. }
  736. cfg := pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}
  737. if in.CAPEM != nil {
  738. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  739. }
  740. if in.FingerprintSHA256 != nil {
  741. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  742. }
  743. if in.Insecure != nil {
  744. cfg.Insecure = *in.Insecure
  745. }
  746. inst := pve.Instance{ID: id, Name: name, Config: cfg}
  747. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  748. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  749. return
  750. }
  751. w.WriteHeader(http.StatusNoContent)
  752. }
  753. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  754. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  755. id := r.PathValue("id")
  756. if !pve.ValidInstanceID(id) {
  757. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  758. return
  759. }
  760. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  761. writeError(w, http.StatusInternalServerError, "internal_error")
  762. return
  763. }
  764. w.WriteHeader(http.StatusNoContent)
  765. }
  766. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  767. //
  768. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  769. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  770. // rechaza) y la integración se queda muda — indistinguible de un cluster
  771. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  772. //
  773. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  774. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  775. // reutiliza el almacenado, igual que el PUT.
  776. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  777. var in proxmoxInstanceInput
  778. _ = readJSONBody(w, r, &in) // cuerpo opcional
  779. id := strings.TrimSpace(in.ID)
  780. if id == "" {
  781. id = "default"
  782. }
  783. var cfg pve.Config
  784. for _, inst := range pve.LoadInstances(s.db.DB) {
  785. if inst.ID == id {
  786. cfg = inst.Config
  787. break
  788. }
  789. }
  790. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  791. cfg.URL = u
  792. }
  793. if t := strings.TrimSpace(in.TokenID); t != "" {
  794. cfg.TokenID = t
  795. }
  796. if in.Secret != "" {
  797. cfg.Secret = in.Secret
  798. }
  799. if in.CAPEM != nil {
  800. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  801. }
  802. if in.FingerprintSHA256 != nil {
  803. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  804. }
  805. if in.Insecure != nil {
  806. cfg.Insecure = *in.Insecure
  807. }
  808. if !cfg.Enabled() {
  809. writeError(w, http.StatusBadRequest, "invalid_input", "faltan url, tokenId o secret")
  810. return
  811. }
  812. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  813. // poder enseñar lo que contestó Proxmox.
  814. res, err := pve.NewClient(cfg).Test(r.Context())
  815. if err != nil {
  816. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  817. return
  818. }
  819. writeJSON(w, http.StatusOK, map[string]any{
  820. "ok": true, "version": res.Version, "nodes": res.Nodes,
  821. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  822. })
  823. }