config.go 37 KB

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