config.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. "regexp"
  11. "strconv"
  12. "strings"
  13. "github.com/gnacho/netpulse/server-go/internal/auth"
  14. "github.com/gnacho/netpulse/server-go/internal/discover"
  15. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  16. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  17. )
  18. var (
  19. hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  20. hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
  21. )
  22. // registerConfigRoutes registra las rutas /api/config/* en el mux.
  23. // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
  24. // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
  25. // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
  26. func (s *server) registerConfigRoutes(mux *http.ServeMux) {
  27. mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
  28. mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
  29. mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
  30. mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
  31. mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
  32. mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
  33. mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
  34. mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
  35. mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
  36. }
  37. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  38. func (s *server) syncRouters() {
  39. if s.adapter != nil {
  40. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  41. }
  42. }
  43. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  44. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  45. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  46. if key == nil {
  47. writeError(w, http.StatusInternalServerError, "no_key")
  48. return
  49. }
  50. writeJSON(w, http.StatusOK, key)
  51. }
  52. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  53. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  54. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  55. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  56. // (la UI pide escribir la palabra de confirmación).
  57. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  58. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  59. if err != nil {
  60. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  61. return
  62. }
  63. writeJSON(w, http.StatusOK, map[string]any{
  64. "publicKey": key.PublicKey,
  65. "fingerprint": key.Fingerprint,
  66. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  67. })
  68. }
  69. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  70. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  71. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  72. writeJSON(w, http.StatusOK, result)
  73. }
  74. // GET /api/config/routers — lista configurada (no el estado sondeado).
  75. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  76. writeJSON(w, http.StatusOK, map[string]any{"routers": routerstore.ListRouters(s.db.DB)})
  77. }
  78. type routerInput struct {
  79. Name *string `json:"name"`
  80. Host *string `json:"host"`
  81. Type string `json:"type"`
  82. Gateway bool `json:"gateway"`
  83. AgentOnly bool `json:"agent_only"`
  84. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  85. FirmwareTarget *string `json:"firmware_target"`
  86. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  87. SnmpEnabled *bool `json:"snmp_enabled"`
  88. SnmpCommunity *string `json:"snmp_community"`
  89. SnmpPort *int `json:"snmp_port"`
  90. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  91. }
  92. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  93. // trimmeado o "" + mensaje de error.
  94. func validateHost(host string) (string, string) {
  95. h := strings.TrimSpace(host)
  96. if len(h) < 1 {
  97. return "", "String must contain at least 1 character(s)"
  98. }
  99. if len(h) > 253 {
  100. return "", "String must contain at most 253 character(s)"
  101. }
  102. if !hostRe.MatchString(h) {
  103. return "", "host debe ser una IP o hostname válido"
  104. }
  105. return h, ""
  106. }
  107. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  108. // host, puerto y mensaje de error.
  109. func validateAdGuardHost(host string) (string, int, string) {
  110. h := strings.TrimSpace(host)
  111. if len(h) < 1 {
  112. return "", 0, "String must contain at least 1 character(s)"
  113. }
  114. if len(h) > 253 {
  115. return "", 0, "String must contain at most 253 character(s)"
  116. }
  117. m := hostPortRe.FindStringSubmatch(h)
  118. if m == nil {
  119. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  120. }
  121. addr := m[1]
  122. port := 0
  123. if m[2] != "" {
  124. p, err := strconv.Atoi(m[2][1:])
  125. if err != nil || p < 1 || p > 65535 {
  126. return "", 0, "puerto fuera de rango (1-65535)"
  127. }
  128. port = p
  129. }
  130. return addr, port, ""
  131. }
  132. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  133. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  134. var in routerInput
  135. if st := readJSONBody(w, r, &in); st != 0 {
  136. writeBodyError(w, st, "invalid_json", "")
  137. return
  138. }
  139. // Orden de validación del schema zod: name, host, type
  140. name := ""
  141. if in.Name != nil {
  142. name = strings.TrimSpace(*in.Name)
  143. if len(name) < 1 {
  144. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  145. return
  146. }
  147. if len(name) > 60 {
  148. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  149. return
  150. }
  151. }
  152. if in.Host == nil {
  153. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  154. return
  155. }
  156. host, msg := validateHost(*in.Host)
  157. if msg != "" {
  158. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  159. return
  160. }
  161. typ := in.Type
  162. if typ == "" {
  163. typ = "openwrt"
  164. }
  165. if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
  166. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  167. return
  168. }
  169. var firmwareTarget string
  170. if in.FirmwareTarget != nil {
  171. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  172. }
  173. snmpEnabled := false
  174. if in.SnmpEnabled != nil {
  175. snmpEnabled = *in.SnmpEnabled
  176. }
  177. snmpCommunity := ""
  178. if in.SnmpCommunity != nil {
  179. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  180. }
  181. snmpPort := 0
  182. if in.SnmpPort != nil {
  183. snmpPort = *in.SnmpPort
  184. if snmpPort < 0 || snmpPort > 65535 {
  185. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  186. return
  187. }
  188. }
  189. snmpInterval := 60
  190. if in.SnmpPollInterval != nil {
  191. snmpInterval = *in.SnmpPollInterval
  192. if snmpInterval < 10 || snmpInterval > 3600 {
  193. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  194. return
  195. }
  196. }
  197. for _, rt := range routerstore.ListRouters(s.db.DB) {
  198. if rt.Host == host {
  199. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  200. return
  201. }
  202. }
  203. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  204. Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  205. FirmwareTarget: firmwareTarget,
  206. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  207. })
  208. if err != nil {
  209. writeError(w, http.StatusInternalServerError, "internal_error")
  210. return
  211. }
  212. s.syncRouters()
  213. writeJSON(w, http.StatusCreated, map[string]any{"router": created})
  214. }
  215. // DELETE /api/config/routers/:id — 204 o 404.
  216. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  217. if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
  218. writeError(w, http.StatusNotFound, "not_found")
  219. return
  220. }
  221. s.syncRouters()
  222. w.WriteHeader(http.StatusNoContent)
  223. }
  224. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  225. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  226. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  227. id := r.PathValue("id")
  228. var in routerInput
  229. if st := readJSONBody(w, r, &in); st != 0 {
  230. writeBodyError(w, st, "invalid_json", "")
  231. return
  232. }
  233. var name *string
  234. if in.Name != nil {
  235. n := strings.TrimSpace(*in.Name)
  236. if len(n) < 1 {
  237. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  238. return
  239. }
  240. if len(n) > 60 {
  241. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  242. return
  243. }
  244. name = &n
  245. }
  246. var host *string
  247. if in.Host != nil {
  248. h, msg := validateHost(*in.Host)
  249. if msg != "" {
  250. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  251. return
  252. }
  253. // Duplicado: otro router con ese host (excluyendo el propio id).
  254. for _, rt := range routerstore.ListRouters(s.db.DB) {
  255. if rt.Host == h && rt.ID != id {
  256. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  257. return
  258. }
  259. }
  260. host = &h
  261. }
  262. var typ *string
  263. if in.Type != "" {
  264. t := in.Type
  265. if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
  266. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  267. return
  268. }
  269. typ = &t
  270. }
  271. gw := in.Gateway
  272. ao := in.AgentOnly
  273. var firmwareTarget *string
  274. if in.FirmwareTarget != nil {
  275. v := strings.TrimSpace(*in.FirmwareTarget)
  276. firmwareTarget = &v
  277. }
  278. var snmpPollInterval *int
  279. if in.SnmpPollInterval != nil {
  280. v := *in.SnmpPollInterval
  281. if v < 10 || v > 3600 {
  282. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  283. return
  284. }
  285. snmpPollInterval = &v
  286. }
  287. var snmpPort *int
  288. if in.SnmpPort != nil {
  289. p := *in.SnmpPort
  290. if p < 0 || p > 65535 {
  291. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  292. return
  293. }
  294. snmpPort = &p
  295. }
  296. var snmpCommunity *string
  297. if in.SnmpCommunity != nil {
  298. v := strings.TrimSpace(*in.SnmpCommunity)
  299. snmpCommunity = &v
  300. }
  301. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  302. Name: name, Host: host, Type: typ,
  303. IsGateway: &gw, AgentOnly: &ao,
  304. FirmwareTarget: firmwareTarget,
  305. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  306. })
  307. if !ok {
  308. writeError(w, http.StatusNotFound, "not_found")
  309. return
  310. }
  311. s.syncRouters()
  312. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  313. }
  314. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  315. func kvGet(db *sql.DB, key string) string {
  316. var v string
  317. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  318. return ""
  319. }
  320. return v
  321. }
  322. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  323. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  324. user := kvGet(s.db.DB, "adguard_user")
  325. if user == "" {
  326. user = "root"
  327. }
  328. mode := kvGet(s.db.DB, "adguard_mode")
  329. if mode == "" {
  330. mode = "glinet"
  331. }
  332. portStr := kvGet(s.db.DB, "adguard_port")
  333. port := 0
  334. if p, err := strconv.Atoi(portStr); err == nil {
  335. port = p
  336. }
  337. writeJSON(w, http.StatusOK, map[string]any{
  338. "mode": mode,
  339. "host": kvGet(s.db.DB, "adguard_host"),
  340. "port": port,
  341. "user": user,
  342. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  343. })
  344. }
  345. type adguardInput struct {
  346. Mode string `json:"mode"`
  347. Host *string `json:"host"`
  348. Port int `json:"port"`
  349. User string `json:"user"`
  350. Password string `json:"password"`
  351. }
  352. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  353. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  354. var in adguardInput
  355. if st := readJSONBody(w, r, &in); st != 0 {
  356. writeBodyError(w, st, "invalid_json", "")
  357. return
  358. }
  359. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  360. if mode == "" {
  361. mode = "glinet"
  362. }
  363. if mode != "glinet" && mode != "standard" {
  364. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  365. return
  366. }
  367. if in.Host == nil {
  368. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  369. return
  370. }
  371. host := strings.TrimSpace(*in.Host)
  372. port := 0
  373. if mode == "standard" {
  374. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  375. if msg != "" {
  376. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  377. return
  378. }
  379. host = hostFromVal
  380. if in.Port < 1 || in.Port > 65535 {
  381. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  382. return
  383. }
  384. port = in.Port
  385. if port == 0 {
  386. port = portFromHost
  387. }
  388. if port == 0 {
  389. port = 3000
  390. }
  391. }
  392. user := strings.TrimSpace(in.User)
  393. if user == "" {
  394. user = "root"
  395. }
  396. if len(user) > 64 {
  397. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  398. return
  399. }
  400. if len(in.Password) > 128 {
  401. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  402. return
  403. }
  404. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  405. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  406. writeError(w, http.StatusInternalServerError, "internal_error")
  407. return
  408. }
  409. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  410. writeError(w, http.StatusInternalServerError, "internal_error")
  411. return
  412. }
  413. if mode == "standard" {
  414. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  415. writeError(w, http.StatusInternalServerError, "internal_error")
  416. return
  417. }
  418. } else {
  419. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  420. writeError(w, http.StatusInternalServerError, "internal_error")
  421. return
  422. }
  423. }
  424. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  425. writeError(w, http.StatusInternalServerError, "internal_error")
  426. return
  427. }
  428. if in.Password != "" {
  429. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  430. writeError(w, http.StatusInternalServerError, "internal_error")
  431. return
  432. }
  433. }
  434. w.WriteHeader(http.StatusNoContent)
  435. }