4
0

config.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. writeJSON(w, http.StatusOK, map[string]any{
  670. "mode": mode,
  671. "host": kvGet(s.db.DB, "adguard_host"),
  672. "port": port,
  673. "user": user,
  674. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  675. })
  676. }
  677. type adguardInput struct {
  678. Mode string `json:"mode"`
  679. Host *string `json:"host"`
  680. Port int `json:"port"`
  681. User string `json:"user"`
  682. Password string `json:"password"`
  683. }
  684. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  685. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  686. var in adguardInput
  687. if st := readJSONBody(w, r, &in); st != 0 {
  688. writeBodyError(w, st, "invalid_json", "")
  689. return
  690. }
  691. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  692. if mode == "" {
  693. mode = "glinet"
  694. }
  695. if mode != "glinet" && mode != "standard" {
  696. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  697. return
  698. }
  699. if in.Host == nil {
  700. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  701. return
  702. }
  703. host := strings.TrimSpace(*in.Host)
  704. port := 0
  705. if mode == "standard" {
  706. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  707. if msg != "" {
  708. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  709. return
  710. }
  711. host = hostFromVal
  712. if in.Port < 1 || in.Port > 65535 {
  713. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  714. return
  715. }
  716. port = in.Port
  717. if port == 0 {
  718. port = portFromHost
  719. }
  720. if port == 0 {
  721. port = 3000
  722. }
  723. }
  724. user := strings.TrimSpace(in.User)
  725. if user == "" {
  726. user = "root"
  727. }
  728. if len(user) > 64 {
  729. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  730. return
  731. }
  732. if len(in.Password) > 128 {
  733. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  734. return
  735. }
  736. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  737. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  738. writeError(w, http.StatusInternalServerError, "internal_error")
  739. return
  740. }
  741. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  742. writeError(w, http.StatusInternalServerError, "internal_error")
  743. return
  744. }
  745. if mode == "standard" {
  746. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  747. writeError(w, http.StatusInternalServerError, "internal_error")
  748. return
  749. }
  750. } else {
  751. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  752. writeError(w, http.StatusInternalServerError, "internal_error")
  753. return
  754. }
  755. }
  756. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  757. writeError(w, http.StatusInternalServerError, "internal_error")
  758. return
  759. }
  760. if in.Password != "" {
  761. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  762. writeError(w, http.StatusInternalServerError, "internal_error")
  763. return
  764. }
  765. }
  766. w.WriteHeader(http.StatusNoContent)
  767. }
  768. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  769. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  770. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  771. // Idempotente: 204 aunque no hubiera nada configurado.
  772. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  773. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  774. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  775. writeError(w, http.StatusInternalServerError, "internal_error")
  776. return
  777. }
  778. }
  779. if s.pollNow != nil {
  780. s.pollNow()
  781. }
  782. w.WriteHeader(http.StatusNoContent)
  783. }
  784. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  785. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  786. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  787. // para no romper frontends cacheados.
  788. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  789. instances := pve.LoadInstances(s.db.DB)
  790. // Vista sanitizada: el secret JAMAS sale del server (#764).
  791. view := make([]map[string]any, 0, len(instances))
  792. for _, in := range instances {
  793. view = append(view, map[string]any{
  794. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  795. "caPem": in.CAPEM, "fingerprintSha256": in.FingerprintSHA256, "insecure": in.Insecure,
  796. })
  797. }
  798. out := map[string]any{
  799. "instances": view,
  800. "url": "",
  801. "tokenId": "",
  802. "tokenSet": false,
  803. }
  804. if len(instances) > 0 {
  805. out["url"] = instances[0].URL
  806. out["tokenId"] = instances[0].TokenID
  807. out["tokenSet"] = instances[0].Secret != ""
  808. }
  809. writeJSON(w, http.StatusOK, out)
  810. }
  811. type proxmoxInput struct {
  812. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  813. TokenID string `json:"tokenId"`
  814. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  815. }
  816. type proxmoxInstanceInput struct {
  817. ID string `json:"id"`
  818. Name string `json:"name"`
  819. URL string `json:"url"`
  820. TokenID string `json:"tokenId"`
  821. Secret string `json:"secret"` // vacío en edición = conservar el actual
  822. CAPEM *string `json:"caPem"`
  823. FingerprintSHA256 *string `json:"fingerprintSha256"`
  824. Insecure *bool `json:"insecure"`
  825. }
  826. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  827. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  828. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  829. // migrada "default", creándola si hace falta; url "" desactiva todo).
  830. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  831. var in proxmoxInstanceInput
  832. if st := readJSONBody(w, r, &in); st != 0 {
  833. writeBodyError(w, st, "invalid_json", "")
  834. return
  835. }
  836. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  837. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  838. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  839. tokenID := strings.TrimSpace(in.TokenID)
  840. if len(tokenID) > 128 || len(in.Secret) > 256 {
  841. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  842. return
  843. }
  844. id := strings.TrimSpace(in.ID)
  845. if id == "" {
  846. id = "default" // legacy sin id
  847. }
  848. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  849. if url != "" {
  850. u, err := urlpkg.Parse(url)
  851. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  852. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  853. return
  854. }
  855. }
  856. list := pve.LoadInstances(s.db.DB)
  857. var current *pve.Instance
  858. for i := range list {
  859. if list[i].ID == id {
  860. current = &list[i]
  861. break
  862. }
  863. }
  864. if current != nil {
  865. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" &&
  866. in.CAPEM == nil && in.FingerprintSHA256 == nil && in.Insecure == nil {
  867. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  868. return
  869. }
  870. if url != "" {
  871. current.URL = url
  872. }
  873. if tokenID != "" {
  874. current.TokenID = tokenID
  875. }
  876. if in.Secret != "" {
  877. current.Secret = in.Secret
  878. }
  879. if in.CAPEM != nil {
  880. current.CAPEM = strings.TrimSpace(*in.CAPEM)
  881. }
  882. if in.FingerprintSHA256 != nil {
  883. current.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  884. }
  885. if in.Insecure != nil {
  886. current.Insecure = *in.Insecure
  887. }
  888. if n := strings.TrimSpace(in.Name); n != "" {
  889. current.Name = n
  890. }
  891. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  892. writeError(w, http.StatusInternalServerError, "internal_error")
  893. return
  894. }
  895. w.WriteHeader(http.StatusNoContent)
  896. return
  897. }
  898. // Instancia nueva: completa.
  899. if url == "" || tokenID == "" || in.Secret == "" {
  900. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  901. return
  902. }
  903. name := strings.TrimSpace(in.Name)
  904. if name == "" {
  905. name = id
  906. }
  907. cfg := pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}
  908. if in.CAPEM != nil {
  909. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  910. }
  911. if in.FingerprintSHA256 != nil {
  912. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  913. }
  914. if in.Insecure != nil {
  915. cfg.Insecure = *in.Insecure
  916. }
  917. inst := pve.Instance{ID: id, Name: name, Config: cfg}
  918. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  919. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  920. return
  921. }
  922. w.WriteHeader(http.StatusNoContent)
  923. }
  924. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  925. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  926. id := r.PathValue("id")
  927. if !pve.ValidInstanceID(id) {
  928. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  929. return
  930. }
  931. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  932. writeError(w, http.StatusInternalServerError, "internal_error")
  933. return
  934. }
  935. w.WriteHeader(http.StatusNoContent)
  936. }
  937. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  938. //
  939. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  940. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  941. // rechaza) y la integración se queda muda — indistinguible de un cluster
  942. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  943. //
  944. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  945. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  946. // reutiliza el almacenado, igual que el PUT.
  947. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  948. var in proxmoxInstanceInput
  949. _ = readJSONBody(w, r, &in) // cuerpo opcional
  950. id := strings.TrimSpace(in.ID)
  951. if id == "" {
  952. id = "default"
  953. }
  954. var cfg pve.Config
  955. for _, inst := range pve.LoadInstances(s.db.DB) {
  956. if inst.ID == id {
  957. cfg = inst.Config
  958. break
  959. }
  960. }
  961. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  962. cfg.URL = u
  963. }
  964. if t := strings.TrimSpace(in.TokenID); t != "" {
  965. cfg.TokenID = t
  966. }
  967. if in.Secret != "" {
  968. cfg.Secret = in.Secret
  969. }
  970. if in.CAPEM != nil {
  971. cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
  972. }
  973. if in.FingerprintSHA256 != nil {
  974. cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
  975. }
  976. if in.Insecure != nil {
  977. cfg.Insecure = *in.Insecure
  978. }
  979. if !cfg.Enabled() {
  980. writeError(w, http.StatusBadRequest, "invalid_input", "missing url, tokenId or secret")
  981. return
  982. }
  983. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  984. // poder enseñar lo que contestó Proxmox.
  985. res, err := pve.NewClient(cfg).Test(r.Context())
  986. if err != nil {
  987. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  988. return
  989. }
  990. writeJSON(w, http.StatusOK, map[string]any{
  991. "ok": true, "version": res.Version, "nodes": res.Nodes,
  992. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  993. })
  994. }