config.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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. "unicode"
  15. "github.com/gnacho/netpulse/server-go/internal/adapters"
  16. "github.com/gnacho/netpulse/server-go/internal/auth"
  17. "github.com/gnacho/netpulse/server-go/internal/discover"
  18. "github.com/gnacho/netpulse/server-go/internal/pve"
  19. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  20. "github.com/gnacho/netpulse/server-go/internal/snmp"
  21. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  22. )
  23. var (
  24. hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  25. hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
  26. )
  27. // registerConfigRoutes registra las rutas /api/config/* en el mux.
  28. // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
  29. // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
  30. // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
  31. func (s *server) registerConfigRoutes(mux *http.ServeMux) {
  32. mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
  33. mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
  34. mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
  35. mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
  36. mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
  37. mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
  38. mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
  39. mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
  40. mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
  41. mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
  42. mux.Handle("POST /api/config/adguard/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectAdguard)))
  43. mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
  44. mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
  45. mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
  46. mux.Handle("POST /api/config/proxmox/test", auth.RequireAdmin(http.HandlerFunc(s.handleTestProxmoxConfig)))
  47. mux.Handle("POST /api/config/proxmox/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectProxmox)))
  48. }
  49. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  50. func (s *server) syncRouters() {
  51. if s.adapter != nil {
  52. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  53. }
  54. }
  55. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  56. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  57. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  58. if key == nil {
  59. writeError(w, http.StatusInternalServerError, "no_key")
  60. return
  61. }
  62. writeJSON(w, http.StatusOK, key)
  63. }
  64. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  65. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  66. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  67. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  68. // (la UI pide escribir la palabra de confirmación).
  69. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  70. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  71. if err != nil {
  72. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  73. return
  74. }
  75. writeJSON(w, http.StatusOK, map[string]any{
  76. "publicKey": key.PublicKey,
  77. "fingerprint": key.Fingerprint,
  78. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  79. })
  80. }
  81. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  82. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  83. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  84. writeJSON(w, http.StatusOK, result)
  85. }
  86. // routerListItem es la vista HTTP de un router. Omite la comunidad SNMP,
  87. // que solo necesita el adapter para sondear, y expone si esta configurada.
  88. type routerListItem struct {
  89. ID string `json:"id"`
  90. Name string `json:"name"`
  91. Host string `json:"host"`
  92. Type string `json:"type"`
  93. IsGateway bool `json:"is_gateway"`
  94. AgentOnly bool `json:"agent_only"`
  95. // InventoryMode (#1917): "auto" | "agent" | "ssh".
  96. InventoryMode string `json:"inventory_mode,omitempty"`
  97. DiscoveryOverrides adapters.DiscoveryOverrides `json:"discovery_overrides,omitzero"`
  98. CreatedAt int64 `json:"created_at"`
  99. FirmwareTarget string `json:"firmware_target,omitempty"`
  100. SnmpEnabled bool `json:"snmp_enabled"`
  101. SnmpCommunitySet bool `json:"snmp_community_set"`
  102. SnmpPort int `json:"snmp_port,omitempty"`
  103. SnmpPollInterval int `json:"snmp_poll_interval,omitempty"`
  104. // SNMPv3 (#2042). Las passphrases nunca salen: solo si están guardadas.
  105. SnmpVersion string `json:"snmp_version"`
  106. SnmpV3User string `json:"snmp_v3_user,omitempty"`
  107. SnmpV3SecurityLevel string `json:"snmp_v3_security_level,omitempty"`
  108. SnmpV3AuthProto string `json:"snmp_v3_auth_proto,omitempty"`
  109. SnmpV3AuthPassSet bool `json:"snmp_v3_auth_pass_set"`
  110. SnmpV3PrivProto string `json:"snmp_v3_priv_proto,omitempty"`
  111. SnmpV3PrivPassSet bool `json:"snmp_v3_priv_pass_set"`
  112. Disabled bool `json:"disabled"`
  113. ConsolePolling bool `json:"console_polling"`
  114. SSHPort int `json:"ssh_port,omitempty"`
  115. TempThreshold *int `json:"temp_threshold,omitempty"`
  116. }
  117. func newRouterListItem(rt adapters.RouterConfig) routerListItem {
  118. return routerListItem{
  119. ID: rt.ID,
  120. Name: rt.Name,
  121. Host: rt.Host,
  122. Type: rt.Type,
  123. IsGateway: rt.IsGateway,
  124. AgentOnly: rt.AgentOnly,
  125. InventoryMode: rt.InventoryMode,
  126. DiscoveryOverrides: rt.DiscoveryOverrides,
  127. CreatedAt: rt.CreatedAt,
  128. FirmwareTarget: rt.FirmwareTarget,
  129. SnmpEnabled: rt.SnmpEnabled,
  130. SnmpCommunitySet: rt.SnmpCommunity != "",
  131. SnmpPort: rt.SnmpPort,
  132. SnmpPollInterval: rt.SnmpPollInterval,
  133. SnmpVersion: normalizeSnmpVersion(rt.SnmpVersion),
  134. SnmpV3User: rt.SnmpV3User,
  135. // Los protocolos y el nivel se devuelven porque no son secretos: la UI
  136. // los necesita para pintar el formulario al editar.
  137. SnmpV3SecurityLevel: defaultIfEmpty(rt.SnmpV3SecurityLevel, "authPriv"),
  138. SnmpV3AuthProto: defaultIfEmpty(rt.SnmpV3AuthProto, "SHA"),
  139. SnmpV3AuthPassSet: rt.SnmpV3AuthPass != "",
  140. SnmpV3PrivProto: defaultIfEmpty(rt.SnmpV3PrivProto, "AES"),
  141. SnmpV3PrivPassSet: rt.SnmpV3PrivPass != "",
  142. Disabled: rt.Disabled,
  143. ConsolePolling: rt.ConsolePolling,
  144. SSHPort: rt.SSHPort,
  145. TempThreshold: rt.TempThreshold,
  146. }
  147. }
  148. // normalizeSnmpVersion deja la versión en uno de los tres valores que habla
  149. // el poller. Cualquier otra cosa (filas viejas con NULL/"" incluidas) es v2c.
  150. func normalizeSnmpVersion(v string) string {
  151. if v == "1" || v == "3" {
  152. return v
  153. }
  154. return "2c"
  155. }
  156. // defaultIfEmpty evita que la UI reciba "" en los selects de SNMPv3 cuando la
  157. // fila es anterior a la migración.
  158. func defaultIfEmpty(v, fallback string) string {
  159. if v == "" {
  160. return fallback
  161. }
  162. return v
  163. }
  164. // derefStr lee un *string opcional quedándose con "" cuando no viene.
  165. func derefStr(p *string) string {
  166. if p == nil {
  167. return ""
  168. }
  169. return *p
  170. }
  171. // GET /api/config/routers — lista configurada (no el estado sondeado).
  172. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  173. routers := routerstore.ListRouters(s.db.DB)
  174. items := make([]routerListItem, 0, len(routers))
  175. for _, rt := range routers {
  176. items = append(items, newRouterListItem(rt))
  177. }
  178. writeJSON(w, http.StatusOK, map[string]any{"routers": items})
  179. }
  180. type routerInput struct {
  181. Name *string `json:"name"`
  182. Host *string `json:"host"`
  183. Type string `json:"type"`
  184. // Gateway y AgentOnly son punteros por el mismo motivo que el resto:
  185. // ausente significa "no lo toques". Con bool a secas, un PUT parcial
  186. // (por ejemplo el que solo cambia inventory_mode) los reiniciaba a
  187. // false y tiraba el gateway o el agent-only de la unidad (#1937).
  188. Gateway *bool `json:"gateway"`
  189. AgentOnly *bool `json:"agent_only"`
  190. // InventoryMode (#1917): "auto" | "agent" | "ssh". Manda sobre agent_only.
  191. InventoryMode *string `json:"inventory_mode"`
  192. // DiscoveryOverrides: overrides por red lógica y por dispositivo Linux
  193. // ("on"|"off"|"auto"). nil = no tocar; un objeto reemplaza todo el ajuste
  194. // ("auto" y mapas vacíos se descartan antes de guardar).
  195. DiscoveryOverrides *adapters.DiscoveryOverrides `json:"discovery_overrides"`
  196. // Disabled (issue #1085): pausa la unidad (nil = no tocar).
  197. Disabled *bool `json:"disabled"`
  198. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  199. FirmwareTarget *string `json:"firmware_target"`
  200. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  201. SnmpEnabled *bool `json:"snmp_enabled"`
  202. // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
  203. ConsolePolling *bool `json:"console_polling"`
  204. SnmpCommunity *string `json:"snmp_community"`
  205. SnmpPort *int `json:"snmp_port"`
  206. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  207. // SNMPv3 (#2042). "1" | "2c" | "3". Con v3 manda el bloque USM y la
  208. // comunidad se ignora. Las passphrases son secretos: nil = no tocar y ""
  209. // = borrar (mismo contrato que snmp_community).
  210. SnmpVersion *string `json:"snmp_version"`
  211. SnmpV3User *string `json:"snmp_v3_user"`
  212. SnmpV3SecurityLevel *string `json:"snmp_v3_security_level"`
  213. SnmpV3AuthProto *string `json:"snmp_v3_auth_proto"`
  214. SnmpV3AuthPass *string `json:"snmp_v3_auth_pass"`
  215. SnmpV3PrivProto *string `json:"snmp_v3_priv_proto"`
  216. SnmpV3PrivPass *string `json:"snmp_v3_priv_pass"`
  217. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  218. // estándar). Ausente/0 → 22.
  219. SSHPort *int `json:"ssh_port"`
  220. // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
  221. // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
  222. TempThreshold *int `json:"temp_threshold"`
  223. }
  224. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  225. // trimmeado o "" + mensaje de error.
  226. func validateHost(host string) (string, string) {
  227. h := strings.TrimSpace(host)
  228. if len(h) < 1 {
  229. return "", "String must contain at least 1 character(s)"
  230. }
  231. if len(h) > 253 {
  232. return "", "String must contain at most 253 character(s)"
  233. }
  234. if !hostRe.MatchString(h) {
  235. return "", "host debe ser una IP o hostname válido"
  236. }
  237. return h, ""
  238. }
  239. // validateInventoryMode (#1917): "" se acepta y el store lo interpreta como
  240. // "auto" implicito (compatibilidad con clientes que no mandan el campo).
  241. func validateInventoryMode(v *string) (string, string) {
  242. if v == nil {
  243. return "", ""
  244. }
  245. m := strings.TrimSpace(*v)
  246. switch m {
  247. case "", "auto", "agent", "ssh":
  248. return m, ""
  249. }
  250. return "", "Invalid enum value. Expected 'auto' | 'agent' | 'ssh'"
  251. }
  252. // isValidNetworkKey comprueba que el nombre de una red lógica de OpenWrt
  253. // tenga entre 1 y 32 bytes de [A-Za-z0-9_].
  254. func isValidNetworkKey(k string) bool {
  255. if len(k) < 1 || len(k) > 32 {
  256. return false
  257. }
  258. for i := 0; i < len(k); i++ {
  259. b := k[i]
  260. ok := (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_'
  261. if !ok {
  262. return false
  263. }
  264. }
  265. return true
  266. }
  267. // isValidDeviceKey comprueba que el nombre de un dispositivo Linux tenga entre
  268. // 1 y 15 bytes sin espacios, caracteres de control ni '/'.
  269. func isValidDeviceKey(k string) bool {
  270. if k == "" || len(k) > 15 {
  271. return false
  272. }
  273. for _, r := range k {
  274. if unicode.IsSpace(r) || unicode.IsControl(r) || r == '/' {
  275. return false
  276. }
  277. }
  278. return true
  279. }
  280. // validateOverrideMap valida un mapa de overrides (redes o dispositivos):
  281. // descarta "auto" (comportamiento por defecto) y rechaza claves o modos fuera
  282. // de regla. Devuelve nil si no queda ningún override explícito.
  283. func validateOverrideMap(m map[string]adapters.DiscoveryMode, validKey func(string) bool, keyErr string) (map[string]adapters.DiscoveryMode, string) {
  284. if len(m) == 0 {
  285. return nil, ""
  286. }
  287. if len(m) > 64 {
  288. return nil, "discovery_overrides must contain at most 64 entries per map"
  289. }
  290. out := make(map[string]adapters.DiscoveryMode, len(m))
  291. for k, mode := range m {
  292. if !validKey(k) {
  293. return nil, keyErr
  294. }
  295. switch mode {
  296. case adapters.DiscoveryOn, adapters.DiscoveryOff:
  297. out[k] = mode
  298. case adapters.DiscoveryAuto:
  299. // "auto" es el comportamiento por defecto: no se persiste.
  300. default:
  301. return nil, "Invalid enum value. Expected 'auto' | 'on' | 'off'"
  302. }
  303. }
  304. if len(out) == 0 {
  305. return nil, ""
  306. }
  307. return out, ""
  308. }
  309. // validateDiscoveryOverrides valida los overrides de descubrimiento por red
  310. // lógica y por dispositivo Linux: como mucho 64 entradas por mapa, nombres de
  311. // red de 1..32 bytes en [A-Za-z0-9_], nombres de dispositivo de 1..15 bytes
  312. // sin espacios, caracteres de control ni '/', y valores "on", "off" o "auto"
  313. // ("auto" y mapas vacíos se descartan antes de guardar).
  314. func validateDiscoveryOverrides(v *adapters.DiscoveryOverrides) (*adapters.DiscoveryOverrides, string) {
  315. if v == nil {
  316. return nil, ""
  317. }
  318. nets, msg := validateOverrideMap(v.Networks, isValidNetworkKey, "invalid network name in discovery_overrides")
  319. if msg != "" {
  320. return nil, msg
  321. }
  322. devs, msg := validateOverrideMap(v.Devices, isValidDeviceKey, "invalid interface name in discovery_overrides")
  323. if msg != "" {
  324. return nil, msg
  325. }
  326. return &adapters.DiscoveryOverrides{Networks: nets, Devices: devs}, ""
  327. }
  328. // snmpV3Input es el bloque SNMPv3 (#2042) ya normalizado y validado. Los
  329. // punteros nil significan "no tocar" y se propagan tal cual al store; los
  330. // valores "" son borrados explícitos (passphrases) o defaults (protocolos).
  331. type snmpV3Input struct {
  332. Version *string
  333. User *string
  334. SecurityLevel *string
  335. AuthProto *string
  336. AuthPass *string
  337. PrivProto *string
  338. PrivPass *string
  339. }
  340. // validateSnmpV3 valida el bloque USM de una alta o una edición. Devuelve el
  341. // input normalizado y un mensaje de error ("" = ok).
  342. func validateSnmpV3(in routerInput) (snmpV3Input, string) {
  343. out := snmpV3Input{}
  344. if in.SnmpVersion != nil {
  345. v := strings.TrimSpace(*in.SnmpVersion)
  346. if v == "" {
  347. v = "2c"
  348. }
  349. if v != "1" && v != "2c" && v != "3" {
  350. return out, "Invalid enum value. Expected '1' | '2c' | '3'"
  351. }
  352. out.Version = &v
  353. }
  354. if in.SnmpV3User != nil {
  355. u := strings.TrimSpace(*in.SnmpV3User)
  356. if len(u) > 32 {
  357. return out, "snmp_v3_user must contain at most 32 characters"
  358. }
  359. out.User = &u
  360. }
  361. if in.SnmpV3SecurityLevel != nil {
  362. l := strings.TrimSpace(*in.SnmpV3SecurityLevel)
  363. if l != "" && !snmp.ValidV3SecurityLevel(l) {
  364. return out, "Invalid enum value. Expected 'noAuthNoPriv' | 'authNoPriv' | 'authPriv'"
  365. }
  366. out.SecurityLevel = &l
  367. }
  368. if in.SnmpV3AuthProto != nil {
  369. p := strings.TrimSpace(*in.SnmpV3AuthProto)
  370. if p != "" && !snmp.ValidV3AuthProtocol(p) {
  371. return out, "Invalid enum value. Expected 'MD5' | 'SHA' | 'SHA224' | 'SHA256' | 'SHA384' | 'SHA512'"
  372. }
  373. out.AuthProto = &p
  374. }
  375. if in.SnmpV3PrivProto != nil {
  376. p := strings.TrimSpace(*in.SnmpV3PrivProto)
  377. if p != "" && !snmp.ValidV3PrivProtocol(p) {
  378. return out, "Invalid enum value. Expected 'DES' | 'AES' | 'AES192' | 'AES256' | 'AES192C' | 'AES256C'"
  379. }
  380. out.PrivProto = &p
  381. }
  382. for _, f := range []struct {
  383. name string
  384. val *string
  385. dst **string
  386. }{
  387. {"snmp_v3_auth_pass", in.SnmpV3AuthPass, &out.AuthPass},
  388. {"snmp_v3_priv_pass", in.SnmpV3PrivPass, &out.PrivPass},
  389. } {
  390. if f.val == nil {
  391. continue
  392. }
  393. v := *f.val
  394. // La passphrase no se trimea: los espacios pueden ser parte del
  395. // secreto que el dispositivo espera.
  396. if v != "" && len(v) < snmp.MinV3Passphrase {
  397. return out, f.name + " must contain at least 8 characters"
  398. }
  399. if len(v) > 255 {
  400. return out, f.name + " must contain at most 255 characters"
  401. }
  402. *f.dst = &v
  403. }
  404. return out, ""
  405. }
  406. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  407. // host, puerto y mensaje de error.
  408. func validateAdGuardHost(host string) (string, int, string) {
  409. h := strings.TrimSpace(host)
  410. if len(h) < 1 {
  411. return "", 0, "String must contain at least 1 character(s)"
  412. }
  413. if len(h) > 253 {
  414. return "", 0, "String must contain at most 253 character(s)"
  415. }
  416. m := hostPortRe.FindStringSubmatch(h)
  417. if m == nil {
  418. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  419. }
  420. addr := m[1]
  421. port := 0
  422. if m[2] != "" {
  423. p, err := strconv.Atoi(m[2][1:])
  424. if err != nil || p < 1 || p > 65535 {
  425. return "", 0, "puerto fuera de rango (1-65535)"
  426. }
  427. port = p
  428. }
  429. return addr, port, ""
  430. }
  431. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  432. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  433. var in routerInput
  434. if st := readJSONBody(w, r, &in); st != 0 {
  435. writeBodyError(w, st, "invalid_json", "")
  436. return
  437. }
  438. // Orden de validación del schema zod: name, host, type
  439. name := ""
  440. if in.Name != nil {
  441. name = strings.TrimSpace(*in.Name)
  442. if len(name) < 1 {
  443. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  444. return
  445. }
  446. if len(name) > 60 {
  447. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  448. return
  449. }
  450. }
  451. if in.Host == nil {
  452. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  453. return
  454. }
  455. host, msg := validateHost(*in.Host)
  456. if msg != "" {
  457. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  458. return
  459. }
  460. typ := in.Type
  461. if typ == "" {
  462. typ = "openwrt"
  463. }
  464. if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
  465. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  466. return
  467. }
  468. var firmwareTarget string
  469. if in.FirmwareTarget != nil {
  470. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  471. }
  472. snmpEnabled := false
  473. if in.SnmpEnabled != nil {
  474. snmpEnabled = *in.SnmpEnabled
  475. }
  476. snmpCommunity := ""
  477. if in.SnmpCommunity != nil {
  478. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  479. }
  480. snmpPort := 0
  481. if in.SnmpPort != nil {
  482. snmpPort = *in.SnmpPort
  483. if snmpPort < 0 || snmpPort > 65535 {
  484. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  485. return
  486. }
  487. }
  488. snmpInterval := 60
  489. if in.SnmpPollInterval != nil {
  490. snmpInterval = *in.SnmpPollInterval
  491. if snmpInterval < 10 || snmpInterval > 3600 {
  492. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  493. return
  494. }
  495. }
  496. for _, rt := range routerstore.ListRouters(s.db.DB) {
  497. if rt.Host == host {
  498. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  499. return
  500. }
  501. }
  502. v3, v3Msg := validateSnmpV3(in)
  503. if v3Msg != "" {
  504. writeError(w, http.StatusBadRequest, "invalid_input", v3Msg)
  505. return
  506. }
  507. snmpVersion := derefStr(v3.Version)
  508. snmpV3User := derefStr(v3.User)
  509. snmpSecLevel := defaultIfEmpty(derefStr(v3.SecurityLevel), "authPriv")
  510. snmpAuthProto := defaultIfEmpty(derefStr(v3.AuthProto), "SHA")
  511. snmpAuthPass := derefStr(v3.AuthPass)
  512. snmpPrivProto := defaultIfEmpty(derefStr(v3.PrivProto), "AES")
  513. snmpPrivPass := derefStr(v3.PrivPass)
  514. if snmpVersion == "3" {
  515. if snmpV3User == "" {
  516. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_user is required for SNMPv3")
  517. return
  518. }
  519. if (snmpSecLevel == "authNoPriv" || snmpSecLevel == "authPriv") && snmpAuthPass == "" {
  520. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_auth_pass is required for "+snmpSecLevel)
  521. return
  522. }
  523. if snmpSecLevel == "authPriv" && snmpPrivPass == "" {
  524. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_priv_pass is required for authPriv")
  525. return
  526. }
  527. }
  528. sshPort := 0
  529. if in.SSHPort != nil {
  530. p := *in.SSHPort
  531. if p < 1 || p > 65535 {
  532. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  533. return
  534. }
  535. sshPort = p
  536. }
  537. invMode, invMsg := validateInventoryMode(in.InventoryMode)
  538. if invMsg != "" {
  539. writeError(w, http.StatusBadRequest, "invalid_input", invMsg)
  540. return
  541. }
  542. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  543. Name: name, Host: host, Type: typ,
  544. IsGateway: in.Gateway != nil && *in.Gateway, AgentOnly: in.AgentOnly != nil && *in.AgentOnly,
  545. InventoryMode: invMode,
  546. FirmwareTarget: firmwareTarget,
  547. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  548. SnmpVersion: snmpVersion, SnmpV3User: snmpV3User, SnmpV3SecurityLevel: snmpSecLevel,
  549. SnmpV3AuthProto: snmpAuthProto, SnmpV3AuthPass: snmpAuthPass,
  550. SnmpV3PrivProto: snmpPrivProto, SnmpV3PrivPass: snmpPrivPass,
  551. SSHPort: sshPort,
  552. })
  553. if err != nil {
  554. writeError(w, http.StatusInternalServerError, "internal_error")
  555. return
  556. }
  557. s.syncRouters()
  558. writeJSON(w, http.StatusCreated, map[string]any{"router": newRouterListItem(created)})
  559. }
  560. // DELETE /api/config/routers/:id — 204 o 404.
  561. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  562. id := r.PathValue("id")
  563. // #1276: MAC aprendida del último push del agente (bridge MAC), para
  564. // purgar su entrada del registro de clientes tras borrar el router.
  565. var macs []string
  566. if s.agents != nil {
  567. if p, ok := s.agents.StalePayload(id); ok {
  568. if sys := p.Data.System; sys != nil && sys.BridgeMAC != "" {
  569. macs = append(macs, sys.BridgeMAC)
  570. }
  571. }
  572. }
  573. if !routerstore.RemoveRouter(s.db.DB, id) {
  574. writeError(w, http.StatusNotFound, "not_found")
  575. return
  576. }
  577. // #1276: limpieza del stub de Dispositivos/Agentes. Sin esto, el estado
  578. // persistido (agent.state.*) y el registro seguían listando la unidad
  579. // borrada sin forma de quitarla. Se revoca TAMBIÉN el token: si el
  580. // agente sigue instalado en la caja, su siguiente push recibe 401 y
  581. // deja de re-crear la entrada. Re-añadir el router requiere re-emparejar
  582. // el agente (reinstall).
  583. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKeyPrefix+id)
  584. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentStateKeyPrefix+id)
  585. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTransportPrefix+id)
  586. if s.agents != nil {
  587. s.agents.Forget(id)
  588. }
  589. for _, m := range macs {
  590. _, _ = s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?",
  591. strings.ToUpper(m), strings.ToLower(strings.ReplaceAll(m, ":", "-")))
  592. }
  593. s.syncRouters()
  594. w.WriteHeader(http.StatusNoContent)
  595. }
  596. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  597. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  598. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  599. id := r.PathValue("id")
  600. var in routerInput
  601. if st := readJSONBody(w, r, &in); st != 0 {
  602. writeBodyError(w, st, "invalid_json", "")
  603. return
  604. }
  605. var name *string
  606. if in.Name != nil {
  607. n := strings.TrimSpace(*in.Name)
  608. if len(n) < 1 {
  609. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  610. return
  611. }
  612. if len(n) > 60 {
  613. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  614. return
  615. }
  616. name = &n
  617. }
  618. var host *string
  619. if in.Host != nil {
  620. h, msg := validateHost(*in.Host)
  621. if msg != "" {
  622. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  623. return
  624. }
  625. // Duplicado: otro router con ese host (excluyendo el propio id).
  626. for _, rt := range routerstore.ListRouters(s.db.DB) {
  627. if rt.Host == h && rt.ID != id {
  628. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  629. return
  630. }
  631. }
  632. host = &h
  633. }
  634. var typ *string
  635. if in.Type != "" {
  636. t := in.Type
  637. if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
  638. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  639. return
  640. }
  641. typ = &t
  642. }
  643. var invMode *string
  644. if in.InventoryMode != nil {
  645. m, msg := validateInventoryMode(in.InventoryMode)
  646. if msg != "" {
  647. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  648. return
  649. }
  650. invMode = &m
  651. }
  652. discOverrides, discMsg := validateDiscoveryOverrides(in.DiscoveryOverrides)
  653. if discMsg != "" {
  654. writeError(w, http.StatusBadRequest, "invalid_input", discMsg)
  655. return
  656. }
  657. var firmwareTarget *string
  658. if in.FirmwareTarget != nil {
  659. v := strings.TrimSpace(*in.FirmwareTarget)
  660. firmwareTarget = &v
  661. }
  662. var snmpPollInterval *int
  663. if in.SnmpPollInterval != nil {
  664. v := *in.SnmpPollInterval
  665. if v < 10 || v > 3600 {
  666. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  667. return
  668. }
  669. snmpPollInterval = &v
  670. }
  671. var snmpPort *int
  672. if in.SnmpPort != nil {
  673. p := *in.SnmpPort
  674. if p < 0 || p > 65535 {
  675. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  676. return
  677. }
  678. snmpPort = &p
  679. }
  680. var snmpCommunity *string
  681. if in.SnmpCommunity != nil {
  682. v := strings.TrimSpace(*in.SnmpCommunity)
  683. snmpCommunity = &v
  684. }
  685. // SNMPv3 (#2042). Los punteros nil siguen significando "no tocar".
  686. v3, v3Msg := validateSnmpV3(in)
  687. if v3Msg != "" {
  688. writeError(w, http.StatusBadRequest, "invalid_input", v3Msg)
  689. return
  690. }
  691. if v3.Version != nil && *v3.Version == "3" && v3.User != nil && *v3.User == "" {
  692. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_user is required for SNMPv3")
  693. return
  694. }
  695. var sshPort *int
  696. if in.SSHPort != nil {
  697. p := *in.SSHPort
  698. if p < 1 || p > 65535 {
  699. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  700. return
  701. }
  702. sshPort = &p
  703. }
  704. var tempThreshold *int
  705. if in.TempThreshold != nil {
  706. v := *in.TempThreshold
  707. if v > 150 {
  708. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  709. return
  710. }
  711. tempThreshold = &v
  712. }
  713. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  714. Name: name, Host: host, Type: typ,
  715. IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  716. InventoryMode: invMode,
  717. DiscoveryOverrides: discOverrides,
  718. Disabled: in.Disabled,
  719. FirmwareTarget: firmwareTarget,
  720. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  721. SnmpVersion: v3.Version, SnmpV3User: v3.User, SnmpV3SecurityLevel: v3.SecurityLevel,
  722. SnmpV3AuthProto: v3.AuthProto, SnmpV3AuthPass: v3.AuthPass,
  723. SnmpV3PrivProto: v3.PrivProto, SnmpV3PrivPass: v3.PrivPass,
  724. SSHPort: sshPort,
  725. TempThreshold: tempThreshold,
  726. ConsolePolling: in.ConsolePolling,
  727. })
  728. if !ok {
  729. writeError(w, http.StatusNotFound, "not_found")
  730. return
  731. }
  732. s.syncRouters()
  733. writeJSON(w, http.StatusOK, map[string]any{"router": newRouterListItem(updated)})
  734. }
  735. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  736. func kvGet(db *sql.DB, key string) string {
  737. var v string
  738. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  739. return ""
  740. }
  741. return v
  742. }
  743. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  744. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  745. user := kvGet(s.db.DB, "adguard_user")
  746. if user == "" {
  747. user = "root"
  748. }
  749. mode := kvGet(s.db.DB, "adguard_mode")
  750. if mode == "" {
  751. mode = "glinet"
  752. }
  753. portStr := kvGet(s.db.DB, "adguard_port")
  754. port := 0
  755. if p, err := strconv.Atoi(portStr); err == nil {
  756. port = p
  757. }
  758. scheme := kvGet(s.db.DB, "adguard_scheme")
  759. if scheme == "" {
  760. scheme = "http"
  761. }
  762. writeJSON(w, http.StatusOK, map[string]any{
  763. "mode": mode,
  764. "scheme": scheme,
  765. "host": kvGet(s.db.DB, "adguard_host"),
  766. "port": port,
  767. "user": user,
  768. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  769. "insecure": kvGet(s.db.DB, "adguard_insecure") == "1",
  770. })
  771. }
  772. type adguardInput struct {
  773. Mode string `json:"mode"`
  774. Scheme *string `json:"scheme"`
  775. Host *string `json:"host"`
  776. Port int `json:"port"`
  777. User string `json:"user"`
  778. Password string `json:"password"`
  779. Insecure *bool `json:"insecure"`
  780. }
  781. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  782. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  783. var in adguardInput
  784. if st := readJSONBody(w, r, &in); st != 0 {
  785. writeBodyError(w, st, "invalid_json", "")
  786. return
  787. }
  788. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  789. if mode == "" {
  790. mode = "glinet"
  791. }
  792. if mode != "glinet" && mode != "standard" {
  793. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  794. return
  795. }
  796. if in.Host == nil {
  797. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  798. return
  799. }
  800. host := strings.TrimSpace(*in.Host)
  801. port := 0
  802. scheme := "http"
  803. insecure := false
  804. if mode == "standard" {
  805. scheme = kvGet(s.db.DB, "adguard_scheme")
  806. if in.Scheme != nil {
  807. scheme = strings.ToLower(strings.TrimSpace(*in.Scheme))
  808. }
  809. if scheme == "" {
  810. scheme = "http"
  811. }
  812. if scheme != "http" && scheme != "https" {
  813. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'http' | 'https'")
  814. return
  815. }
  816. insecure = kvGet(s.db.DB, "adguard_insecure") == "1"
  817. if in.Insecure != nil {
  818. insecure = *in.Insecure
  819. }
  820. if scheme != "https" {
  821. insecure = false
  822. }
  823. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  824. if msg != "" {
  825. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  826. return
  827. }
  828. host = hostFromVal
  829. if in.Port < 1 || in.Port > 65535 {
  830. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  831. return
  832. }
  833. port = in.Port
  834. if port == 0 {
  835. port = portFromHost
  836. }
  837. if port == 0 {
  838. port = 3000
  839. }
  840. }
  841. user := strings.TrimSpace(in.User)
  842. if user == "" {
  843. user = "root"
  844. }
  845. if len(user) > 64 {
  846. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  847. return
  848. }
  849. if len(in.Password) > 128 {
  850. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  851. return
  852. }
  853. tx, err := s.db.DB.BeginTx(r.Context(), nil)
  854. if err != nil {
  855. writeError(w, http.StatusInternalServerError, "internal_error")
  856. return
  857. }
  858. defer tx.Rollback()
  859. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  860. if _, err := tx.Exec(upsert, "adguard_mode", mode); err != nil {
  861. writeError(w, http.StatusInternalServerError, "internal_error")
  862. return
  863. }
  864. if _, err := tx.Exec(upsert, "adguard_host", host); err != nil {
  865. writeError(w, http.StatusInternalServerError, "internal_error")
  866. return
  867. }
  868. if mode == "standard" {
  869. if _, err := tx.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  870. writeError(w, http.StatusInternalServerError, "internal_error")
  871. return
  872. }
  873. if _, err := tx.Exec(upsert, "adguard_scheme", scheme); err != nil {
  874. writeError(w, http.StatusInternalServerError, "internal_error")
  875. return
  876. }
  877. insecureValue := "0"
  878. if insecure {
  879. insecureValue = "1"
  880. }
  881. if _, err := tx.Exec(upsert, "adguard_insecure", insecureValue); err != nil {
  882. writeError(w, http.StatusInternalServerError, "internal_error")
  883. return
  884. }
  885. } else {
  886. for _, key := range []string{"adguard_port", "adguard_scheme", "adguard_insecure"} {
  887. if _, err := tx.Exec("DELETE FROM kv WHERE key = ?", key); err != nil {
  888. writeError(w, http.StatusInternalServerError, "internal_error")
  889. return
  890. }
  891. }
  892. }
  893. if _, err := tx.Exec(upsert, "adguard_user", user); err != nil {
  894. writeError(w, http.StatusInternalServerError, "internal_error")
  895. return
  896. }
  897. if in.Password != "" {
  898. if _, err := tx.Exec(upsert, "adguard_pass", in.Password); err != nil {
  899. writeError(w, http.StatusInternalServerError, "internal_error")
  900. return
  901. }
  902. }
  903. if err := tx.Commit(); err != nil {
  904. writeError(w, http.StatusInternalServerError, "internal_error")
  905. return
  906. }
  907. w.WriteHeader(http.StatusNoContent)
  908. }
  909. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  910. // (mode/host/user/pass/port/scheme/insecure) para que deje de sondearse y de
  911. // penalizar la salud. Idempotente: 204 aunque no hubiera nada configurado.
  912. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  913. tx, err := s.db.DB.BeginTx(r.Context(), nil)
  914. if err != nil {
  915. writeError(w, http.StatusInternalServerError, "internal_error")
  916. return
  917. }
  918. defer tx.Rollback()
  919. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port", "adguard_scheme", "adguard_insecure"} {
  920. if _, err := tx.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  921. writeError(w, http.StatusInternalServerError, "internal_error")
  922. return
  923. }
  924. }
  925. if err := tx.Commit(); err != nil {
  926. writeError(w, http.StatusInternalServerError, "internal_error")
  927. return
  928. }
  929. if s.pollNow != nil {
  930. s.pollNow()
  931. }
  932. w.WriteHeader(http.StatusNoContent)
  933. }
  934. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  935. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  936. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  937. // para no romper frontends cacheados.
  938. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  939. instances := pve.LoadInstances(s.db.DB)
  940. // Vista sanitizada: el secret JAMAS sale del server (#764).
  941. view := make([]map[string]any, 0, len(instances))
  942. for _, in := range instances {
  943. view = append(view, map[string]any{
  944. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  945. "caPem": in.CAPEM, "fingerprintSha256": in.FingerprintSHA256, "insecure": in.Insecure,
  946. })
  947. }
  948. out := map[string]any{
  949. "instances": view,
  950. "url": "",
  951. "tokenId": "",
  952. "tokenSet": false,
  953. }
  954. if len(instances) > 0 {
  955. out["url"] = instances[0].URL
  956. out["tokenId"] = instances[0].TokenID
  957. out["tokenSet"] = instances[0].Secret != ""
  958. }
  959. writeJSON(w, http.StatusOK, out)
  960. }
  961. type proxmoxInput struct {
  962. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  963. TokenID string `json:"tokenId"`
  964. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  965. }
  966. type proxmoxInstanceInput struct {
  967. ID string `json:"id"`
  968. Name string `json:"name"`
  969. URL string `json:"url"`
  970. TokenID string `json:"tokenId"`
  971. Secret string `json:"secret"` // vacío en edición = conservar el actual
  972. CAPEM *string `json:"caPem"`
  973. FingerprintSHA256 *string `json:"fingerprintSha256"`
  974. Insecure *bool `json:"insecure"`
  975. }
  976. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  977. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  978. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  979. // migrada "default", creándola si hace falta; url "" desactiva todo).
  980. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  981. var in proxmoxInstanceInput
  982. if st := readJSONBody(w, r, &in); st != 0 {
  983. writeBodyError(w, st, "invalid_json", "")
  984. return
  985. }
  986. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  987. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  988. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  989. tokenID := strings.TrimSpace(in.TokenID)
  990. if len(tokenID) > 128 || len(in.Secret) > 256 {
  991. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  992. return
  993. }
  994. id := strings.TrimSpace(in.ID)
  995. if id == "" {
  996. id = "default" // legacy sin id
  997. }
  998. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  999. if url != "" {
  1000. u, err := urlpkg.Parse(url)
  1001. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  1002. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  1003. return
  1004. }
  1005. }
  1006. list := pve.LoadInstances(s.db.DB)
  1007. var current *pve.Instance
  1008. for i := range list {
  1009. if list[i].ID == id {
  1010. current = &list[i]
  1011. break
  1012. }
  1013. }
  1014. if current != nil {
  1015. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" &&
  1016. in.CAPEM == nil && in.FingerprintSHA256 == nil && in.Insecure == nil {
  1017. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  1018. return
  1019. }
  1020. if url != "" {
  1021. current.URL = url
  1022. }
  1023. if tokenID != "" {
  1024. current.TokenID = tokenID
  1025. }
  1026. if in.Secret != "" {
  1027. current.Secret = in.Secret
  1028. }
  1029. if in.CAPEM != nil {
  1030. current.CAPEM = strings.TrimSpace(*in.CAPEM)
  1031. }
  1032. if in.FingerprintSHA256 != nil {
  1033. current.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  1034. }
  1035. if in.Insecure != nil {
  1036. current.Insecure = *in.Insecure
  1037. }
  1038. if n := strings.TrimSpace(in.Name); n != "" {
  1039. current.Name = n
  1040. }
  1041. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  1042. writeError(w, http.StatusInternalServerError, "internal_error")
  1043. return
  1044. }
  1045. w.WriteHeader(http.StatusNoContent)
  1046. return
  1047. }
  1048. // Instancia nueva: completa.
  1049. if url == "" || tokenID == "" || in.Secret == "" {
  1050. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  1051. return
  1052. }
  1053. name := strings.TrimSpace(in.Name)
  1054. if name == "" {
  1055. name = id
  1056. }
  1057. cfg := pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}
  1058. if in.CAPEM != nil {
  1059. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  1060. }
  1061. if in.FingerprintSHA256 != nil {
  1062. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  1063. }
  1064. if in.Insecure != nil {
  1065. cfg.Insecure = *in.Insecure
  1066. }
  1067. inst := pve.Instance{ID: id, Name: name, Config: cfg}
  1068. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  1069. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  1070. return
  1071. }
  1072. w.WriteHeader(http.StatusNoContent)
  1073. }
  1074. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  1075. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  1076. id := r.PathValue("id")
  1077. if !pve.ValidInstanceID(id) {
  1078. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  1079. return
  1080. }
  1081. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  1082. writeError(w, http.StatusInternalServerError, "internal_error")
  1083. return
  1084. }
  1085. w.WriteHeader(http.StatusNoContent)
  1086. }
  1087. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  1088. //
  1089. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  1090. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  1091. // rechaza) y la integración se queda muda — indistinguible de un cluster
  1092. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  1093. //
  1094. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  1095. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  1096. // reutiliza el almacenado, igual que el PUT.
  1097. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  1098. var in proxmoxInstanceInput
  1099. _ = readJSONBody(w, r, &in) // cuerpo opcional
  1100. id := strings.TrimSpace(in.ID)
  1101. if id == "" {
  1102. id = "default"
  1103. }
  1104. var cfg pve.Config
  1105. for _, inst := range pve.LoadInstances(s.db.DB) {
  1106. if inst.ID == id {
  1107. cfg = inst.Config
  1108. break
  1109. }
  1110. }
  1111. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  1112. cfg.URL = u
  1113. }
  1114. if t := strings.TrimSpace(in.TokenID); t != "" {
  1115. cfg.TokenID = t
  1116. }
  1117. if in.Secret != "" {
  1118. cfg.Secret = in.Secret
  1119. }
  1120. if in.CAPEM != nil {
  1121. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  1122. }
  1123. if in.FingerprintSHA256 != nil {
  1124. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  1125. }
  1126. if in.Insecure != nil {
  1127. cfg.Insecure = *in.Insecure
  1128. }
  1129. if !cfg.Enabled() {
  1130. writeError(w, http.StatusBadRequest, "invalid_input", "missing url, tokenId or secret")
  1131. return
  1132. }
  1133. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  1134. // poder enseñar lo que contestó Proxmox.
  1135. res, err := pve.NewClient(cfg).Test(r.Context())
  1136. if err != nil {
  1137. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  1138. return
  1139. }
  1140. writeJSON(w, http.StatusOK, map[string]any{
  1141. "ok": true, "version": res.Version, "nodes": res.Nodes,
  1142. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  1143. })
  1144. }