config.go 12 KB

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