config_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. // config_test.go — port de tests/routers.test.js: CRUD de /api/config/routers
  2. // (lista, alta, duplicado 409, validación 400, borrado 204/404) + sshkey.
  3. package httpapi_test
  4. import (
  5. "io"
  6. "net/http"
  7. "strings"
  8. "testing"
  9. )
  10. func doReq(t *testing.T, method, url, cookie, body string) *http.Response {
  11. t.Helper()
  12. var rdr io.Reader
  13. if body != "" {
  14. rdr = strings.NewReader(body)
  15. }
  16. req, err := http.NewRequest(method, url, rdr)
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. if body != "" {
  21. req.Header.Set("Content-Type", "application/json")
  22. }
  23. if cookie != "" {
  24. req.Header.Set("Cookie", "session="+cookie)
  25. }
  26. res, err := http.DefaultClient.Do(req)
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. return res
  31. }
  32. // TestConfigRoutersCRUD replica routers.test.js.
  33. func TestConfigRoutersCRUD(t *testing.T) {
  34. srv := makeTestServer(t)
  35. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  36. // GET inicial: lista vacía (200)
  37. res := doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
  38. if res.StatusCode != 200 {
  39. t.Fatalf("GET routers: %d", res.StatusCode)
  40. }
  41. body := readJSON(t, res)
  42. if _, ok := body["routers"].([]any); !ok {
  43. t.Fatalf("routers no es lista: %v", body)
  44. }
  45. // POST: crea un router (201, {router})
  46. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  47. `{"name":"Salón","host":"192.168.8.2","type":"openwrt"}`)
  48. if res.StatusCode != 201 {
  49. t.Fatalf("POST router: %d", res.StatusCode)
  50. }
  51. body = readJSON(t, res)
  52. router := body["router"].(map[string]any)
  53. if router["id"] != "salon" || router["name"] != "Salón" || router["is_gateway"] != false {
  54. t.Fatalf("router creado: %v", router)
  55. }
  56. // POST gateway: is_gateway exclusivo
  57. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  58. `{"host":"192.168.8.1","type":"glinet","gateway":true}`)
  59. if res.StatusCode != 201 {
  60. t.Fatalf("POST gateway: %d", res.StatusCode)
  61. }
  62. res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
  63. body = readJSON(t, res)
  64. routers := body["routers"].([]any)
  65. if len(routers) != 2 {
  66. t.Fatalf("routers: %d", len(routers))
  67. }
  68. gwCount := 0
  69. for _, r := range routers {
  70. if r.(map[string]any)["is_gateway"] == true {
  71. gwCount++
  72. }
  73. }
  74. if gwCount != 1 {
  75. t.Fatalf("gateways: %d", gwCount)
  76. }
  77. // POST duplicado → 409 duplicate_host
  78. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  79. `{"host":"192.168.8.2"}`)
  80. if res.StatusCode != 409 {
  81. t.Fatalf("duplicado: %d", res.StatusCode)
  82. }
  83. body = readJSON(t, res)
  84. if body["error"] != "duplicate_host" {
  85. t.Fatalf("error: %v", body)
  86. }
  87. // POST host inválido → 400 invalid_input
  88. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  89. `{"host":"no es un host"}`)
  90. if res.StatusCode != 400 {
  91. t.Fatalf("host inválido: %d", res.StatusCode)
  92. }
  93. // POST type inválido → 400
  94. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  95. `{"host":"192.168.8.9","type":"cisco"}`)
  96. if res.StatusCode != 400 {
  97. t.Fatalf("type inválido: %d", res.StatusCode)
  98. }
  99. // POST JSON inválido → 400 invalid_json
  100. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie, `{`)
  101. if res.StatusCode != 400 {
  102. t.Fatalf("json inválido: %d", res.StatusCode)
  103. }
  104. body = readJSON(t, res)
  105. if body["error"] != "invalid_json" {
  106. t.Fatalf("error: %v", body)
  107. }
  108. // DELETE existente → 204; repetir → 404
  109. res = doReq(t, "DELETE", srv.URL+"/api/config/routers/salon", cookie, "")
  110. if res.StatusCode != 204 {
  111. t.Fatalf("DELETE: %d", res.StatusCode)
  112. }
  113. res = doReq(t, "DELETE", srv.URL+"/api/config/routers/salon", cookie, "")
  114. if res.StatusCode != 404 {
  115. t.Fatalf("DELETE 404: %d", res.StatusCode)
  116. }
  117. // GET sshkey → 200 {publicKey, fingerprint} (la clave se genera al vuelo)
  118. res = doReq(t, "GET", srv.URL+"/api/config/sshkey", cookie, "")
  119. // Sin clave generada en el DATA_DIR de test → 500 no_key; si existe
  120. // ssh-keygen en el sistema la ruta la habría creado el arranque (no en
  121. // tests) — aceptamos ambos y validamos el shape cuando hay clave.
  122. if res.StatusCode == 200 {
  123. body = readJSON(t, res)
  124. if _, ok := body["publicKey"].(string); !ok {
  125. t.Fatalf("sshkey: %v", body)
  126. }
  127. } else if res.StatusCode != 500 {
  128. t.Fatalf("sshkey: %d", res.StatusCode)
  129. }
  130. }
  131. // TestRotateSSHKey cubre POST /api/config/sshkey/rotate (#242):
  132. // - 403 sin admin
  133. // - 200 y la nueva pública difiere de la anterior (cuando había clave)
  134. // - la respuesta incluye publicKey + fingerprint
  135. func TestRotateSSHKey(t *testing.T) {
  136. srv := makeTestServer(t)
  137. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  138. // Sin admin → 403.
  139. res := doReq(t, "POST", srv.URL+"/api/config/sshkey/rotate", "", "")
  140. if res.StatusCode != 403 && res.StatusCode != 401 {
  141. t.Fatalf("rotate sin admin: %d (esperaba 403)", res.StatusCode)
  142. }
  143. // Clave previa (puede no existir en el DATA_DIR de test).
  144. prev := ""
  145. res = doReq(t, "GET", srv.URL+"/api/config/sshkey", cookie, "")
  146. if res.StatusCode == 200 {
  147. prev = readJSON(t, res)["publicKey"].(string)
  148. }
  149. res = doReq(t, "POST", srv.URL+"/api/config/sshkey/rotate", cookie, "")
  150. if res.StatusCode != 200 {
  151. t.Fatalf("rotate: %d", res.StatusCode)
  152. }
  153. body := readJSON(t, res)
  154. pub, ok := body["publicKey"].(string)
  155. if !ok || pub == "" {
  156. t.Fatalf("rotate: sin publicKey: %v", body)
  157. }
  158. if _, ok := body["fingerprint"].(string); !ok {
  159. t.Fatalf("rotate: sin fingerprint: %v", body)
  160. }
  161. if prev != "" && prev == pub {
  162. t.Fatalf("rotate: la clave no cambió (prev==new)")
  163. }
  164. }
  165. // TestConfigRoutersUpdate cubre PUT /api/config/routers/{id}:
  166. // - 404 si no existe
  167. // - editar name (200, campo cambiado)
  168. // - editar host inválido (400)
  169. // - editar host duplicado con otro router (409)
  170. // - promover a gateway (200, solo uno con el flag)
  171. // - marcar agent_only (200, flag cambiado)
  172. // - PUT no-admin → 401/403 (lo cubre admin_gate_test.go)
  173. func TestConfigRoutersUpdate(t *testing.T) {
  174. srv := makeTestServer(t)
  175. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  176. // Setup: dos routers (rt1 no-gateway, gw gateway).
  177. res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  178. `{"name":"rt1","host":"192.168.8.10","type":"openwrt"}`)
  179. if res.StatusCode != 201 {
  180. t.Fatalf("POST rt1: %d", res.StatusCode)
  181. }
  182. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  183. `{"name":"gw","host":"192.168.8.1","type":"glinet","gateway":true}`)
  184. if res.StatusCode != 201 {
  185. t.Fatalf("POST gw: %d", res.StatusCode)
  186. }
  187. // PUT inexistente → 404
  188. res = doReq(t, "PUT", srv.URL+"/api/config/routers/no-existe", cookie,
  189. `{"name":"foo"}`)
  190. if res.StatusCode != 404 {
  191. t.Fatalf("PUT 404: %d", res.StatusCode)
  192. }
  193. // PUT name → 200, name cambiado
  194. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  195. `{"name":"Salón Editado","host":"192.168.8.10","type":"openwrt","gateway":false,"agent_only":false}`)
  196. if res.StatusCode != 200 {
  197. t.Fatalf("PUT name: %d", res.StatusCode)
  198. }
  199. body := readJSON(t, res)
  200. rt := body["router"].(map[string]any)
  201. if rt["name"] != "Salón Editado" {
  202. t.Errorf("name: %v", rt["name"])
  203. }
  204. // PUT host inválido → 400
  205. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  206. `{"host":"no es un host"}`)
  207. if res.StatusCode != 400 {
  208. t.Fatalf("PUT host inválido: %d", res.StatusCode)
  209. }
  210. // PUT host duplicado con gw → 409
  211. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  212. `{"host":"192.168.8.1"}`)
  213. if res.StatusCode != 409 {
  214. t.Fatalf("PUT host duplicado: %d", res.StatusCode)
  215. }
  216. // PUT promover rt1 a gateway → 200, ahora rt1 es el único gateway
  217. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  218. `{"host":"192.168.8.10","gateway":true}`)
  219. if res.StatusCode != 200 {
  220. t.Fatalf("PUT gateway: %d", res.StatusCode)
  221. }
  222. res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
  223. body = readJSON(t, res)
  224. gwCount := 0
  225. rt1Gw := false
  226. for _, r := range body["routers"].([]any) {
  227. rm := r.(map[string]any)
  228. if rm["is_gateway"] == true {
  229. gwCount++
  230. if rm["id"] == "rt1" {
  231. rt1Gw = true
  232. }
  233. }
  234. }
  235. if gwCount != 1 || !rt1Gw {
  236. t.Fatalf("gateway mutado: gwCount=%d rt1Gw=%v", gwCount, rt1Gw)
  237. }
  238. // PUT agent_only=true → 200, agent_only cambiado
  239. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  240. `{"host":"192.168.8.10","agent_only":true}`)
  241. if res.StatusCode != 200 {
  242. t.Fatalf("PUT agent_only: %d", res.StatusCode)
  243. }
  244. body = readJSON(t, res)
  245. rt = body["router"].(map[string]any)
  246. if rt["agent_only"] != true {
  247. t.Errorf("agent_only: %v", rt["agent_only"])
  248. }
  249. }
  250. // TestConfigRoutersFirmwareTarget cubre firmware_target (issue #241):
  251. // alta con target, PUT que lo actualiza y persistencia en la lista.
  252. func TestConfigRoutersFirmwareTarget(t *testing.T) {
  253. srv := makeTestServer(t)
  254. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  255. // POST con firmware_target → 201 y el router devuelto lo lleva.
  256. res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  257. `{"name":"rt1","host":"192.168.8.10","type":"openwrt","firmware_target":"25.12.5"}`)
  258. if res.StatusCode != 201 {
  259. t.Fatalf("POST router: %d", res.StatusCode)
  260. }
  261. body := readJSON(t, res)
  262. router := body["router"].(map[string]any)
  263. if router["firmware_target"] != "25.12.5" {
  264. t.Fatalf("firmware_target tras alta: %v", router)
  265. }
  266. // PUT cambia firmware_target → 200 y el campo cambia.
  267. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  268. `{"host":"192.168.8.10","firmware_target":"24.10.1"}`)
  269. if res.StatusCode != 200 {
  270. t.Fatalf("PUT firmware_target: %d", res.StatusCode)
  271. }
  272. body = readJSON(t, res)
  273. rt := body["router"].(map[string]any)
  274. if rt["firmware_target"] != "24.10.1" {
  275. t.Fatalf("firmware_target tras PUT: %v", rt)
  276. }
  277. // GET persiste el valor en la lista.
  278. res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
  279. if res.StatusCode != 200 {
  280. t.Fatalf("GET routers: %d", res.StatusCode)
  281. }
  282. body = readJSON(t, res)
  283. found := ""
  284. for _, r := range body["routers"].([]any) {
  285. rm := r.(map[string]any)
  286. if rm["id"] == "rt1" {
  287. found, _ = rm["firmware_target"].(string)
  288. }
  289. }
  290. if found != "24.10.1" {
  291. t.Fatalf("firmware_target persistido=%q, esperaba 24.10.1", found)
  292. }
  293. }
  294. // TestConfigRoutersTempThreshold cubre el umbral de temperatura por router
  295. // (issue #716): alta sin umbral (default 65), PUT que lo fija, persistencia en
  296. // la lista, reset a default con 0 y validación de rango.
  297. func TestConfigRoutersTempThreshold(t *testing.T) {
  298. srv := makeTestServer(t)
  299. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  300. // POST sin umbral → 201 y el campo queda ausente (NULL = default 65).
  301. res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  302. `{"name":"rt1","host":"192.168.8.10","type":"openwrt"}`)
  303. if res.StatusCode != 201 {
  304. t.Fatalf("POST router: %d", res.StatusCode)
  305. }
  306. body := readJSON(t, res)
  307. router := body["router"].(map[string]any)
  308. if _, ok := router["temp_threshold"]; ok {
  309. t.Fatalf("temp_threshold tras alta debía estar ausente: %v", router)
  310. }
  311. // PUT fija el umbral → 200 y el campo cambia.
  312. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  313. `{"host":"192.168.8.10","temp_threshold":70}`)
  314. if res.StatusCode != 200 {
  315. t.Fatalf("PUT temp_threshold: %d", res.StatusCode)
  316. }
  317. body = readJSON(t, res)
  318. rt := body["router"].(map[string]any)
  319. if rt["temp_threshold"] != float64(70) {
  320. t.Fatalf("temp_threshold tras PUT: %v", rt)
  321. }
  322. // GET persiste el valor en la lista.
  323. res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
  324. if res.StatusCode != 200 {
  325. t.Fatalf("GET routers: %d", res.StatusCode)
  326. }
  327. body = readJSON(t, res)
  328. var found float64 = -1
  329. for _, r := range body["routers"].([]any) {
  330. rm := r.(map[string]any)
  331. if rm["id"] == "rt1" {
  332. found, _ = rm["temp_threshold"].(float64)
  333. }
  334. }
  335. if found != 70 {
  336. t.Fatalf("temp_threshold persistido=%v, esperaba 70", found)
  337. }
  338. // PUT con 0 resetea a default (NULL) → campo ausente.
  339. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  340. `{"host":"192.168.8.10","temp_threshold":0}`)
  341. if res.StatusCode != 200 {
  342. t.Fatalf("PUT temp_threshold reset: %d", res.StatusCode)
  343. }
  344. body = readJSON(t, res)
  345. rt = body["router"].(map[string]any)
  346. if _, ok := rt["temp_threshold"]; ok {
  347. t.Fatalf("temp_threshold tras reset debía estar ausente: %v", rt)
  348. }
  349. // Fuera de rango → 400 invalid_input.
  350. res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
  351. `{"host":"192.168.8.10","temp_threshold":200}`)
  352. if res.StatusCode != 400 {
  353. t.Fatalf("temp_threshold fuera de rango: esperado 400, got %d", res.StatusCode)
  354. }
  355. }
  356. // TestAdGuardConfigPort cubre PUT /api/config/adguard (#420):
  357. // - guardar un puerto distinto de 3000 en modo standard
  358. // - GET devuelve el puerto guardado, no 3000
  359. // - el puerto explícito tiene prioridad sobre el que pueda venir en host:port
  360. func TestAdGuardConfigPort(t *testing.T) {
  361. srv := makeTestServer(t)
  362. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  363. // PUT modo standard con puerto 80
  364. res := doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
  365. `{"mode":"standard","host":"adguard.example.com","port":80,"user":"root","password":"secret"}`)
  366. if res.StatusCode != 204 {
  367. body := readJSON(t, res)
  368. t.Fatalf("PUT adguard: %d %v", res.StatusCode, body)
  369. }
  370. // GET debe devolver puerto 80
  371. res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
  372. if res.StatusCode != 200 {
  373. t.Fatalf("GET adguard: %d", res.StatusCode)
  374. }
  375. body := readJSON(t, res)
  376. if body["port"].(float64) != 80 {
  377. t.Fatalf("port esperado 80, got %v", body["port"])
  378. }
  379. // Puerto explícito tiene prioridad sobre host:port
  380. res = doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
  381. `{"mode":"standard","host":"adguard.example.com:8080","port":9090,"user":"root","password":"secret"}`)
  382. if res.StatusCode != 204 {
  383. body := readJSON(t, res)
  384. t.Fatalf("PUT adguard con host:port: %d %v", res.StatusCode, body)
  385. }
  386. res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
  387. body = readJSON(t, res)
  388. if body["port"].(float64) != 9090 {
  389. t.Fatalf("port esperado 9090, got %v", body["port"])
  390. }
  391. // Puerto fuera de rango → 400
  392. res = doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
  393. `{"mode":"standard","host":"adguard.example.com","port":70000,"user":"root","password":"secret"}`)
  394. if res.StatusCode != 400 {
  395. t.Fatalf("port fuera de rango: esperado 400, got %d", res.StatusCode)
  396. }
  397. // Modo glinet con host vacío debe seguir permitiéndose (no regresión)
  398. res = doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
  399. `{"mode":"glinet","host":"","port":0,"user":"root","password":"secret"}`)
  400. if res.StatusCode != 204 {
  401. body := readJSON(t, res)
  402. t.Fatalf("PUT glinet host vacío: %d %v", res.StatusCode, body)
  403. }
  404. res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
  405. body = readJSON(t, res)
  406. if body["mode"] != "glinet" || body["host"] != "" || body["port"] != float64(0) {
  407. t.Fatalf("glinet host vacío no se guardó: %+v", body)
  408. }
  409. }
  410. // TestAdGuardConfigDisable cubre DELETE /api/config/adguard (#813): borra la
  411. // config para que AdGuard deje de sondearse y de penalizar la salud.
  412. func TestAdGuardConfigDisable(t *testing.T) {
  413. srv := makeTestServer(t)
  414. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  415. // Configurar AdGuard (modo glinet, como en producción).
  416. res := doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
  417. `{"mode":"glinet","host":"192.168.1.1","port":0,"user":"root","password":"secret"}`)
  418. if res.StatusCode != 204 {
  419. body := readJSON(t, res)
  420. t.Fatalf("PUT adguard: %d %v", res.StatusCode, body)
  421. }
  422. res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
  423. body := readJSON(t, res)
  424. if body["host"] != "192.168.1.1" || body["passSet"] != true {
  425. t.Fatalf("config previa al DELETE: %+v", body)
  426. }
  427. // DELETE limpia la config (host y password fuera).
  428. res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", cookie, "")
  429. if res.StatusCode != 204 {
  430. body := readJSON(t, res)
  431. t.Fatalf("DELETE adguard: %d %v", res.StatusCode, body)
  432. }
  433. res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
  434. body = readJSON(t, res)
  435. if body["host"] != "" || body["passSet"] != false {
  436. t.Fatalf("config tras DELETE: %+v", body)
  437. }
  438. // Idempotente: un segundo DELETE sigue devolviendo 204.
  439. res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", cookie, "")
  440. if res.StatusCode != 204 {
  441. t.Fatalf("DELETE idempotente: got %d", res.StatusCode)
  442. }
  443. // Solo admin: sin sesión no puede desactivar.
  444. res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", "", "")
  445. if res.StatusCode < 400 {
  446. t.Fatalf("DELETE sin sesión debería fallar, got %d", res.StatusCode)
  447. }
  448. }
  449. func TestConfigRoutersSNMP(t *testing.T) {
  450. srv := makeTestServer(t)
  451. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  452. res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  453. `{"name":"sw1","host":"192.168.8.20","type":"managed-switch","snmp_enabled":true,"snmp_community":"public","snmp_port":161}`)
  454. if res.StatusCode != 201 {
  455. t.Fatalf("POST router: %d", res.StatusCode)
  456. }
  457. body := readJSON(t, res)
  458. router := body["router"].(map[string]any)
  459. if router["snmp_enabled"] != true {
  460. t.Fatalf("snmp_enabled tras alta: %v", router)
  461. }
  462. if router["snmp_community"] != "public" {
  463. t.Fatalf("snmp_community tras alta: %v", router)
  464. }
  465. if router["snmp_port"] != float64(161) {
  466. t.Fatalf("snmp_port tras alta: %v", router)
  467. }
  468. res = doReq(t, "PUT", srv.URL+"/api/config/routers/sw1", cookie,
  469. `{"host":"192.168.8.20","snmp_enabled":false,"snmp_community":"secret"}`)
  470. if res.StatusCode != 200 {
  471. t.Fatalf("PUT snmp: %d", res.StatusCode)
  472. }
  473. body = readJSON(t, res)
  474. rt := body["router"].(map[string]any)
  475. if rt["snmp_enabled"] != false {
  476. t.Fatalf("snmp_enabled tras PUT: %v", rt)
  477. }
  478. if rt["snmp_community"] != "secret" {
  479. t.Fatalf("snmp_community tras PUT: %v", rt)
  480. }
  481. res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  482. `{"name":"sw2","host":"192.168.8.21","type":"managed-switch","snmp_port":99999}`)
  483. if res.StatusCode != 400 {
  484. t.Fatalf("POST invalid snmp_port: %d; want 400", res.StatusCode)
  485. }
  486. }
  487. func TestConfigRoutersRouterOS(t *testing.T) {
  488. srv := makeTestServer(t)
  489. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  490. // POST RouterOS con credenciales
  491. res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
  492. `{"name":"mikrotik","host":"192.168.8.1","type":"routeros","routeros_user":"admin","routeros_password":"secretpassword","routeros_insecure":true}`)
  493. if res.StatusCode != 201 {
  494. t.Fatalf("POST router: %d", res.StatusCode)
  495. }
  496. body := readJSON(t, res)
  497. router := body["router"].(map[string]any)
  498. if router["type"] != "routeros" {
  499. t.Fatalf("type: %v", router["type"])
  500. }
  501. if router["routeros_user"] != "admin" {
  502. t.Fatalf("routeros_user: %v", router["routeros_user"])
  503. }
  504. if router["routeros_insecure"] != true {
  505. t.Fatalf("routeros_insecure: %v", router["routeros_insecure"])
  506. }
  507. if _, present := router["routeros_password"]; present {
  508. t.Fatalf("routeros_password no debe devolverse en la API: %v", router)
  509. }
  510. // PUT actualiza usuario e insecure
  511. res = doReq(t, "PUT", srv.URL+"/api/config/routers/mikrotik", cookie,
  512. `{"host":"192.168.8.1","routeros_user":"netpulse","routeros_insecure":false}`)
  513. if res.StatusCode != 200 {
  514. t.Fatalf("PUT router: %d", res.StatusCode)
  515. }
  516. body = readJSON(t, res)
  517. rt := body["router"].(map[string]any)
  518. if rt["routeros_user"] != "netpulse" {
  519. t.Fatalf("routeros_user tras PUT: %v", rt["routeros_user"])
  520. }
  521. if rt["routeros_insecure"] != false {
  522. t.Fatalf("routeros_insecure tras PUT: %v", rt["routeros_insecure"])
  523. }
  524. }
  525. // TestProxmoxConfig (#561): PUT/GET /api/config/proxmox
  526. // - guardar url+token, GET no devuelve el secret (solo tokenSet)
  527. // - url vacía desactiva (limpia kv)
  528. // - url inválida → 400
  529. func TestProxmoxConfig(t *testing.T) {
  530. srv := makeTestServer(t)
  531. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  532. res := doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
  533. `{"url":"https://192.168.1.100:8006","tokenId":"root@pam!netpulse","secret":"uuid-1234"}`)
  534. if res.StatusCode != 204 {
  535. body := readJSON(t, res)
  536. t.Fatalf("PUT proxmox: %d %v", res.StatusCode, body)
  537. }
  538. res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
  539. if res.StatusCode != 200 {
  540. t.Fatalf("GET proxmox: %d", res.StatusCode)
  541. }
  542. body := readJSON(t, res)
  543. if body["url"] != "https://192.168.1.100:8006" || body["tokenId"] != "root@pam!netpulse" {
  544. t.Fatalf("GET proxmox body: %v", body)
  545. }
  546. if _, present := body["secret"]; present {
  547. t.Fatalf("GET proxmox no debe devolver el secret: %v", body)
  548. }
  549. if body["tokenSet"] != true {
  550. t.Fatalf("tokenSet esperado true: %v", body)
  551. }
  552. // #764: el secret jamas viaja, tampoco dentro de instances.
  553. for _, raw := range body["instances"].([]any) {
  554. m, _ := raw.(map[string]any)
  555. for k := range m {
  556. if strings.EqualFold(k, "secret") || strings.EqualFold(k, "Secret") {
  557. t.Fatalf("instance con secret en el GET: %v", m)
  558. }
  559. }
  560. }
  561. // Actualizar solo el secret conserva url/tokenId.
  562. res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
  563. `{"secret":"uuid-9999"}`)
  564. if res.StatusCode != 204 {
  565. body := readJSON(t, res)
  566. t.Fatalf("PUT proxmox secret: %d %v", res.StatusCode, body)
  567. }
  568. res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
  569. body = readJSON(t, res)
  570. if body["url"] != "https://192.168.1.100:8006" || body["tokenId"] != "root@pam!netpulse" {
  571. t.Fatalf("GET tras update secret: %v", body)
  572. }
  573. // URL inválida → 400
  574. res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
  575. `{"url":"no-es-url","tokenId":"a!b","secret":"c"}`)
  576. if res.StatusCode != 400 {
  577. t.Fatalf("url inválida: esperado 400, got %d", res.StatusCode)
  578. }
  579. // Eliminar (#764): DELETE de la instancia; el listado queda vacío.
  580. res = doReq(t, "DELETE", srv.URL+"/api/config/proxmox/default", cookie, "")
  581. if res.StatusCode != 204 {
  582. body := readJSON(t, res)
  583. t.Fatalf("DELETE proxmox: %d %v", res.StatusCode, body)
  584. }
  585. res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
  586. body = readJSON(t, res)
  587. if body["url"] != "" || body["tokenId"] != "" || body["tokenSet"] != false {
  588. t.Fatalf("GET tras eliminar: %v", body)
  589. }
  590. if ins, _ := body["instances"].([]any); len(ins) != 0 {
  591. t.Fatalf("instances tras eliminar: %v", ins)
  592. }
  593. }
  594. // The Proxmox test endpoint: a failure is a result the form can show, not an
  595. // HTTP error, and it needs a session like the rest of the config API.
  596. func TestProxmoxTestEndpoint(t *testing.T) {
  597. srv := makeTestServer(t)
  598. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  599. // Nothing configured and nothing submitted: a plain 400, not a "result".
  600. res := doReq(t, "POST", srv.URL+"/api/config/proxmox/test", cookie, `{}`)
  601. res.Body.Close()
  602. if res.StatusCode != http.StatusBadRequest {
  603. t.Fatalf("sin config: %d", res.StatusCode)
  604. }
  605. // An endpoint that is not there reports ok:false with what happened.
  606. res = doReq(t, "POST", srv.URL+"/api/config/proxmox/test", cookie,
  607. `{"url":"http://127.0.0.1:1","tokenId":"netpulse@pam!t","secret":"s"}`)
  608. if res.StatusCode != http.StatusOK {
  609. res.Body.Close()
  610. t.Fatalf("inalcanzable: %d", res.StatusCode)
  611. }
  612. body := readJSON(t, res)
  613. if body["ok"] != false || body["error"] == "" {
  614. t.Fatalf("resultado: %v", body)
  615. }
  616. // And it is admin-only.
  617. res = doReq(t, "POST", srv.URL+"/api/config/proxmox/test", "", `{}`)
  618. res.Body.Close()
  619. if res.StatusCode == http.StatusOK {
  620. t.Fatalf("sin sesión devolvió %d", res.StatusCode)
  621. }
  622. }