httpapi_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. // httpapi_test.go — tests de contrato de endpoints (port de tests/auth.test.js
  2. // y tests/users.test.js de Node + quirks de cache-control y SPA).
  3. package httpapi_test
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/gnacho/netpulse/server-go/internal/adapters"
  14. "github.com/gnacho/netpulse/server-go/internal/auth"
  15. "github.com/gnacho/netpulse/server-go/internal/config"
  16. "github.com/gnacho/netpulse/server-go/internal/db"
  17. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  18. "github.com/gnacho/netpulse/server-go/internal/sse"
  19. )
  20. type testServer struct {
  21. *httptest.Server
  22. db *db.DB
  23. secret string
  24. }
  25. // makeTestServer replica tests/helpers.js: app real con adapter demo stub y
  26. // DB temporal, config AUTH_USER=admin AUTH_PASS=test1234 DEMO_MODE=1.
  27. func makeTestServer(t *testing.T) *testServer {
  28. t.Helper()
  29. dataDir := t.TempDir()
  30. cfg, err := config.Load(map[string]string{
  31. "AUTH_USER": "admin", "AUTH_PASS": "test1234",
  32. "DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
  33. }, dataDir)
  34. if err != nil {
  35. t.Fatalf("config: %v", err)
  36. }
  37. d, err := db.Open(dataDir)
  38. if err != nil {
  39. t.Fatalf("db: %v", err)
  40. }
  41. secret, err := auth.EnsureSessionSecret(d, cfg)
  42. if err != nil {
  43. t.Fatalf("secret: %v", err)
  44. }
  45. if err := auth.EnsureUsers(d, cfg); err != nil {
  46. t.Fatalf("users: %v", err)
  47. }
  48. adapter := adapters.NewDemo()
  49. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  50. handler := httpapi.NewHandler(httpapi.Deps{
  51. Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
  52. Started: time.Now(),
  53. })
  54. srv := httptest.NewServer(handler)
  55. ts := &testServer{Server: srv, db: d, secret: secret}
  56. t.Cleanup(func() {
  57. srv.Close()
  58. d.Close()
  59. })
  60. return ts
  61. }
  62. // loginCookie hace login y devuelve status + valor de la cookie (id.hmac) +
  63. // header Set-Cookie completo.
  64. func loginCookie(t *testing.T, base, username, password string, headers ...string) (int, string, string) {
  65. t.Helper()
  66. req, _ := http.NewRequest("POST", base+"/api/auth/login",
  67. strings.NewReader(fmt.Sprintf(`{"username":%q,"password":%q}`, username, password)))
  68. req.Header.Set("Content-Type", "application/json")
  69. for i := 0; i+1 < len(headers); i += 2 {
  70. req.Header.Set(headers[i], headers[i+1])
  71. }
  72. res, err := http.DefaultClient.Do(req)
  73. if err != nil {
  74. t.Fatalf("login: %v", err)
  75. }
  76. defer res.Body.Close()
  77. io.Copy(io.Discard, res.Body)
  78. setCookie := res.Header.Get("Set-Cookie")
  79. cookie := ""
  80. if m := strings.Index(setCookie, "session="); m >= 0 {
  81. rest := setCookie[m+len("session="):]
  82. if end := strings.Index(rest, ";"); end >= 0 {
  83. cookie = rest[:end]
  84. }
  85. }
  86. return res.StatusCode, cookie, setCookie
  87. }
  88. func get(t *testing.T, base, path, cookie string) *http.Response {
  89. t.Helper()
  90. req, _ := http.NewRequest("GET", base+path, nil)
  91. if cookie != "" {
  92. req.Header.Set("Cookie", "session="+cookie)
  93. }
  94. res, err := http.DefaultClient.Do(req)
  95. if err != nil {
  96. t.Fatalf("GET %s: %v", path, err)
  97. }
  98. return res
  99. }
  100. func readJSON(t *testing.T, res *http.Response) map[string]any {
  101. t.Helper()
  102. defer res.Body.Close()
  103. var body map[string]any
  104. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  105. t.Fatalf("json: %v", err)
  106. }
  107. return body
  108. }
  109. // ---------------------------------------------------------------------------
  110. // Port de tests/auth.test.js
  111. // ---------------------------------------------------------------------------
  112. func TestLoginIncorrecto401(t *testing.T) {
  113. srv := makeTestServer(t)
  114. status, cookie, _ := loginCookie(t, srv.URL, "admin", "wrong-pass")
  115. if status != 401 {
  116. t.Fatalf("status: got %d want 401", status)
  117. }
  118. if cookie != "" {
  119. t.Fatal("login incorrecto no debe devolver cookie")
  120. }
  121. }
  122. func TestLoginCorrectoYMe(t *testing.T) {
  123. srv := makeTestServer(t)
  124. status, cookie, setCookie := loginCookie(t, srv.URL, "admin", "test1234")
  125. if status != 204 {
  126. t.Fatalf("status: got %d want 204", status)
  127. }
  128. if cookie == "" {
  129. t.Fatal("debe devolver cookie de sesión")
  130. }
  131. if !strings.Contains(setCookie, "HttpOnly") || !strings.Contains(setCookie, "SameSite=Lax") {
  132. t.Fatalf("Set-Cookie sin HttpOnly/SameSite=Lax: %q", setCookie)
  133. }
  134. res := get(t, srv.URL, "/api/auth/me", cookie)
  135. if res.StatusCode != 200 {
  136. t.Fatalf("me: got %d want 200", res.StatusCode)
  137. }
  138. body := readJSON(t, res)
  139. want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "mode": "demo"}
  140. for k, v := range want {
  141. if body[k] != v {
  142. t.Fatalf("me[%s]: got %v want %v (body=%v)", k, body[k], v, body)
  143. }
  144. }
  145. if len(body) != len(want) {
  146. t.Fatalf("me con claves extra: %v", body)
  147. }
  148. }
  149. func TestOverviewProtegido(t *testing.T) {
  150. srv := makeTestServer(t)
  151. res := get(t, srv.URL, "/api/overview", "")
  152. if res.StatusCode != 401 {
  153. t.Fatalf("sin cookie: got %d want 401", res.StatusCode)
  154. }
  155. body := readJSON(t, res)
  156. if body["error"] != "unauthorized" {
  157. t.Fatalf("error: %v", body)
  158. }
  159. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  160. res2 := get(t, srv.URL, "/api/overview", cookie)
  161. if res2.StatusCode != 200 {
  162. t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
  163. }
  164. ov := readJSON(t, res2)
  165. // Shape del overview (claves del contrato)
  166. for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "ts"} {
  167. if _, ok := ov[k]; !ok {
  168. t.Fatalf("overview sin clave %q", k)
  169. }
  170. }
  171. if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
  172. t.Fatalf("routers: %v", ov["routers"])
  173. }
  174. // ts en SEGUNDOS (no ms)
  175. if ts, ok := ov["ts"].(float64); !ok || ts > 1e11 {
  176. t.Fatalf("ts debe ser epoch en segundos: %v", ov["ts"])
  177. }
  178. }
  179. func TestLogoutRevocaSesion(t *testing.T) {
  180. srv := makeTestServer(t)
  181. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  182. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/logout", nil)
  183. req.Header.Set("Cookie", "session="+cookie)
  184. res, err := http.DefaultClient.Do(req)
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. res.Body.Close()
  189. if res.StatusCode != 204 {
  190. t.Fatalf("logout: got %d want 204", res.StatusCode)
  191. }
  192. if sc := res.Header.Get("Set-Cookie"); sc != "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" {
  193. t.Fatalf("Set-Cookie de borrado literal: %q", sc)
  194. }
  195. res2 := get(t, srv.URL, "/api/overview", cookie)
  196. res2.Body.Close()
  197. if res2.StatusCode != 401 {
  198. t.Fatalf("sesión revocada: got %d want 401", res2.StatusCode)
  199. }
  200. }
  201. func TestRateLimitQuintoFallo(t *testing.T) {
  202. srv := makeTestServer(t)
  203. hdr := []string{"X-Forwarded-For", "10.9.9.9"}
  204. for i := 1; i <= 5; i++ {
  205. status, _, _ := loginCookie(t, srv.URL, "admin", "nope", hdr...)
  206. if status != 401 {
  207. t.Fatalf("fallo %d: got %d want 401", i, status)
  208. }
  209. }
  210. // 6º intento: bloqueado (5 min)
  211. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`{"username":"admin","password":"nope"}`))
  212. req.Header.Set("X-Forwarded-For", "10.9.9.9")
  213. res, _ := http.DefaultClient.Do(req)
  214. if res.StatusCode != 429 {
  215. t.Fatalf("6º intento: got %d want 429", res.StatusCode)
  216. }
  217. body := readJSON(t, res)
  218. if body["error"] != "rate_limited" {
  219. t.Fatalf("error: %v", body)
  220. }
  221. retry, ok := body["retryAfterSec"].(float64)
  222. if !ok || retry <= 0 || retry > 300 {
  223. t.Fatalf("retryAfterSec: %v", body)
  224. }
  225. // Incluso con la password correcta sigue bloqueado.
  226. status, _, _ := loginCookie(t, srv.URL, "admin", "test1234", hdr...)
  227. if status != 429 {
  228. t.Fatalf("bloqueado con password correcta: got %d want 429", status)
  229. }
  230. // Persistencia en SQLite.
  231. var attempts int
  232. var lockedUntil int64
  233. if err := srv.db.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  234. Scan(&attempts, &lockedUntil); err != nil {
  235. t.Fatal(err)
  236. }
  237. if attempts < 5 || lockedUntil <= db.NowMS() {
  238. t.Fatalf("login_attempts: attempts=%d locked_until=%d", attempts, lockedUntil)
  239. }
  240. }
  241. func TestLoginInvalidBody400(t *testing.T) {
  242. srv := makeTestServer(t)
  243. for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
  244. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(payload))
  245. res, _ := http.DefaultClient.Do(req)
  246. body := readJSON(t, res)
  247. if res.StatusCode != 400 || body["error"] != "invalid_body" {
  248. t.Fatalf("payload %s: got %d %v", payload, res.StatusCode, body)
  249. }
  250. if body["message"] != `Se esperaba { "username": string, "password": string }` {
  251. t.Fatalf("message: %v", body["message"])
  252. }
  253. }
  254. }
  255. // ---------------------------------------------------------------------------
  256. // Port de tests/users.test.js
  257. // ---------------------------------------------------------------------------
  258. func TestUsersCRUD(t *testing.T) {
  259. srv := makeTestServer(t)
  260. // 401 sin sesión
  261. res := get(t, srv.URL, "/api/users", "")
  262. res.Body.Close()
  263. if res.StatusCode != 401 {
  264. t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
  265. }
  266. // Admin: lista con 1 usuario
  267. _, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  268. res = get(t, srv.URL, "/api/users", adminCookie)
  269. body := readJSON(t, res)
  270. users := body["users"].([]any)
  271. if len(users) != 1 || users[0].(map[string]any)["username"] != "admin" {
  272. t.Fatalf("users: %v", users)
  273. }
  274. // Alta 201
  275. req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto1"}`))
  276. req.Header.Set("Cookie", "session="+adminCookie)
  277. res, _ = http.DefaultClient.Do(req)
  278. if res.StatusCode != 201 {
  279. b, _ := io.ReadAll(res.Body)
  280. res.Body.Close()
  281. t.Fatalf("alta: got %d want 201 (%s)", res.StatusCode, b)
  282. }
  283. res.Body.Close()
  284. // Duplicado 409
  285. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra1234"}`))
  286. req.Header.Set("Cookie", "session="+adminCookie)
  287. res, _ = http.DefaultClient.Do(req)
  288. body = readJSON(t, res)
  289. if res.StatusCode != 409 || body["error"] != "duplicate_user" {
  290. t.Fatalf("duplicado: got %d %v", res.StatusCode, body)
  291. }
  292. // Username inválido 400
  293. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"mal usuario","password":"xxxxxxxxxx"}`))
  294. req.Header.Set("Cookie", "session="+adminCookie)
  295. res, _ = http.DefaultClient.Do(req)
  296. body = readJSON(t, res)
  297. if res.StatusCode != 400 || body["error"] != "invalid_input" {
  298. t.Fatalf("username inválido: got %d %v", res.StatusCode, body)
  299. }
  300. if body["message"] != "usuario debe ser alfanumérico (.-_ permitidos)" {
  301. t.Fatalf("message: %v", body["message"])
  302. }
  303. // El usuario creado puede loguear
  304. status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto1")
  305. if status != 204 {
  306. t.Fatalf("login ana: got %d", status)
  307. }
  308. // ID de ana
  309. res = get(t, srv.URL, "/api/users", adminCookie)
  310. body = readJSON(t, res)
  311. var anaID, adminID float64
  312. for _, u := range body["users"].([]any) {
  313. m := u.(map[string]any)
  314. if m["username"] == "ana" {
  315. anaID = m["id"].(float64)
  316. }
  317. if m["username"] == "admin" {
  318. adminID = m["id"].(float64)
  319. }
  320. }
  321. // Cambio de password → 204 e invalida la sesión de ana
  322. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/password", srv.URL, anaID), strings.NewReader(`{"password":"nueva-clave-9"}`))
  323. req.Header.Set("Cookie", "session="+adminCookie)
  324. res, _ = http.DefaultClient.Do(req)
  325. res.Body.Close()
  326. if res.StatusCode != 204 {
  327. t.Fatalf("set password: got %d want 204", res.StatusCode)
  328. }
  329. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  330. res.Body.Close()
  331. if res.StatusCode != 401 {
  332. t.Fatalf("sesión vieja de ana: got %d want 401", res.StatusCode)
  333. }
  334. status, anaCookie, _ = loginCookie(t, srv.URL, "ana", "nueva-clave-9")
  335. if status != 204 {
  336. t.Fatalf("re-login ana: got %d", status)
  337. }
  338. // No-admin → 403 en /api/users
  339. res = get(t, srv.URL, "/api/users", anaCookie)
  340. body = readJSON(t, res)
  341. if res.StatusCode != 403 || body["error"] != "forbidden" {
  342. t.Fatalf("no-admin: got %d %v", res.StatusCode, body)
  343. }
  344. // Pero SÍ puede cambiar su idioma (fuera del gate admin)
  345. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"es"}`))
  346. req.Header.Set("Cookie", "session="+anaCookie)
  347. res, _ = http.DefaultClient.Do(req)
  348. res.Body.Close()
  349. if res.StatusCode != 204 {
  350. t.Fatalf("me/language no-admin: got %d want 204", res.StatusCode)
  351. }
  352. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  353. body = readJSON(t, res)
  354. if body["language"] != "es" {
  355. t.Fatalf("language: %v", body)
  356. }
  357. // Idioma inválido → 400 literal
  358. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
  359. req.Header.Set("Cookie", "session="+anaCookie)
  360. res, _ = http.DefaultClient.Do(req)
  361. body = readJSON(t, res)
  362. if res.StatusCode != 400 || body["message"] != "language debe ser auto|es|en" {
  363. t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
  364. }
  365. // Rol via QUERY STRING (quirk): ana pasa a admin
  366. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
  367. req.Header.Set("Cookie", "session="+adminCookie)
  368. res, _ = http.DefaultClient.Do(req)
  369. res.Body.Close()
  370. if res.StatusCode != 204 {
  371. t.Fatalf("set role: got %d want 204", res.StatusCode)
  372. }
  373. // La sesión de ana quedó invalidada por el cambio de rol
  374. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  375. res.Body.Close()
  376. if res.StatusCode != 401 {
  377. t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
  378. }
  379. // Rol inválido → 400
  380. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), nil)
  381. req.Header.Set("Cookie", "session="+adminCookie)
  382. res, _ = http.DefaultClient.Do(req)
  383. body = readJSON(t, res)
  384. if res.StatusCode != 400 || body["message"] != "role debe ser admin|user" {
  385. t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
  386. }
  387. // No puedes cambiar tu propio rol
  388. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
  389. req.Header.Set("Cookie", "session="+adminCookie)
  390. res, _ = http.DefaultClient.Do(req)
  391. body = readJSON(t, res)
  392. if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
  393. t.Fatalf("self role: got %d %v", res.StatusCode, body)
  394. }
  395. // Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
  396. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
  397. req.Header.Set("Cookie", "session="+adminCookie)
  398. res, _ = http.DefaultClient.Do(req)
  399. res.Body.Close()
  400. if res.StatusCode != 204 {
  401. t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
  402. }
  403. // No se puede borrar a sí mismo
  404. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
  405. req.Header.Set("Cookie", "session="+adminCookie)
  406. res, _ = http.DefaultClient.Do(req)
  407. body = readJSON(t, res)
  408. if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
  409. t.Fatalf("self delete: got %d %v", res.StatusCode, body)
  410. }
  411. // Borrado 204 y luego 404
  412. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  413. req.Header.Set("Cookie", "session="+adminCookie)
  414. res, _ = http.DefaultClient.Do(req)
  415. res.Body.Close()
  416. if res.StatusCode != 204 {
  417. t.Fatalf("delete: got %d want 204", res.StatusCode)
  418. }
  419. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  420. req.Header.Set("Cookie", "session="+adminCookie)
  421. res, _ = http.DefaultClient.Do(req)
  422. body = readJSON(t, res)
  423. if res.StatusCode != 404 || body["error"] != "not_found" {
  424. t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
  425. }
  426. }
  427. // ---------------------------------------------------------------------------
  428. // Quirks de cache-control y datos
  429. // ---------------------------------------------------------------------------
  430. func TestCacheControl(t *testing.T) {
  431. srv := makeTestServer(t)
  432. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  433. cases := []struct {
  434. path string
  435. noStore bool
  436. }{
  437. {"/api/health", false},
  438. {"/api/auth/me", false},
  439. {"/api/overview", true},
  440. {"/api/users", true},
  441. {"/api/devices", true},
  442. {"/api/alerts", true},
  443. {"/api/topology", true},
  444. }
  445. for _, c := range cases {
  446. res := get(t, srv.URL, c.path, cookie)
  447. res.Body.Close()
  448. got := res.Header.Get("Cache-Control")
  449. if c.noStore && got != "no-store" {
  450. t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
  451. }
  452. if !c.noStore && got == "no-store" {
  453. t.Errorf("%s: NO debe llevar no-store", c.path)
  454. }
  455. }
  456. }
  457. func TestDevicesPaginacionYFiltros(t *testing.T) {
  458. srv := makeTestServer(t)
  459. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  460. // Paginación: 65 dispositivos del dataset canónico reconciliado
  461. // (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
  462. res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
  463. body := readJSON(t, res)
  464. if body["total"].(float64) != 65 || len(body["items"].([]any)) != 10 {
  465. t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
  466. }
  467. if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
  468. t.Fatalf("page/pageSize: %v", body)
  469. }
  470. res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
  471. body = readJSON(t, res)
  472. if len(body["items"].([]any)) != 5 {
  473. t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
  474. }
  475. // Sin solape con la página anterior
  476. res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
  477. prev := readJSON(t, res)
  478. prevIDs := map[string]bool{}
  479. for _, it := range prev["items"].([]any) {
  480. prevIDs[it.(map[string]any)["id"].(string)] = true
  481. }
  482. for _, it := range body["items"].([]any) {
  483. if prevIDs[it.(map[string]any)["id"].(string)] {
  484. t.Fatalf("solape entre page6 y page7: %v", it)
  485. }
  486. }
  487. // Defaults: pageSize=50
  488. res = get(t, srv.URL, "/api/devices", cookie)
  489. body = readJSON(t, res)
  490. if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
  491. t.Fatalf("defaults: %v", body)
  492. }
  493. // Filtros
  494. res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
  495. body = readJSON(t, res)
  496. if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
  497. t.Fatalf("routerId=living: %v", body["total"])
  498. }
  499. res = get(t, srv.URL, "/api/devices?band=cable", cookie)
  500. body = readJSON(t, res)
  501. for _, it := range body["items"].([]any) {
  502. if it.(map[string]any)["band"] != "cable" {
  503. t.Fatalf("band=cable con item de otra banda: %v", it)
  504. }
  505. }
  506. if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 3 netgear + pve + 10 CTs + 6 tras switch)
  507. t.Fatalf("band=cable: %v", body["total"])
  508. }
  509. res = get(t, srv.URL, "/api/devices?status=offline", cookie)
  510. body = readJSON(t, res)
  511. if body["total"].(float64) != 6 {
  512. t.Fatalf("status=offline: %v", body["total"])
  513. }
  514. res = get(t, srv.URL, "/api/devices?type=movil", cookie)
  515. body = readJSON(t, res)
  516. for _, it := range body["items"].([]any) {
  517. m := it.(map[string]any)
  518. if m["type"] != "movil" && m["group"] != "moviles" {
  519. t.Fatalf("type=movil con item que no casa: %v", m)
  520. }
  521. }
  522. if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
  523. t.Fatalf("type=movil: %v", body["total"])
  524. }
  525. res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
  526. body = readJSON(t, res)
  527. if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
  528. t.Fatalf("q=PIXEL: %v", body["total"])
  529. }
  530. // Inválidos → 400
  531. for _, u := range []string{
  532. "/api/devices?band=wifi6",
  533. "/api/devices?status=weird",
  534. "/api/devices?page=abc",
  535. "/api/devices?pageSize=1001",
  536. } {
  537. res = get(t, srv.URL, u, cookie)
  538. body = readJSON(t, res)
  539. if res.StatusCode != 400 || body["error"] != "invalid_query" {
  540. t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
  541. }
  542. }
  543. // Shape Device (12 claves del contrato)
  544. res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
  545. body = readJSON(t, res)
  546. dev := body["items"].([]any)[0].(map[string]any)
  547. for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
  548. if _, ok := dev[k]; !ok {
  549. t.Fatalf("device sin clave %q: %v", k, dev)
  550. }
  551. }
  552. }
  553. func TestAlertsEndpoint(t *testing.T) {
  554. srv := makeTestServer(t)
  555. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  556. res := get(t, srv.URL, "/api/alerts", cookie)
  557. body := readJSON(t, res)
  558. if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
  559. t.Fatalf("alerts default: %v", body)
  560. }
  561. res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
  562. body = readJSON(t, res)
  563. if body["total"].(float64) != 2 {
  564. t.Fatalf("severity=warn: %v", body["total"])
  565. }
  566. res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
  567. body = readJSON(t, res)
  568. if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
  569. t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
  570. }
  571. }
  572. func TestRoutersYDetalle(t *testing.T) {
  573. srv := makeTestServer(t)
  574. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  575. res := get(t, srv.URL, "/api/routers", cookie)
  576. body := readJSON(t, res)
  577. if len(body["routers"].([]any)) != 4 {
  578. t.Fatalf("routers: %v", body)
  579. }
  580. res = get(t, srv.URL, "/api/routers/flint2", cookie)
  581. if res.StatusCode != 200 {
  582. t.Fatalf("detalle flint2: %d", res.StatusCode)
  583. }
  584. detail := readJSON(t, res)
  585. for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
  586. if _, ok := detail[k]; !ok {
  587. t.Fatalf("detalle sin clave %q", k)
  588. }
  589. }
  590. res = get(t, srv.URL, "/api/routers/no-existe", cookie)
  591. body = readJSON(t, res)
  592. if res.StatusCode != 404 || body["error"] != "not_found" {
  593. t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
  594. }
  595. // DAWN: el stub devuelve null → 503
  596. res = get(t, srv.URL, "/api/dawn", cookie)
  597. body = readJSON(t, res)
  598. if res.StatusCode != 503 || body["error"] != "unavailable" {
  599. t.Fatalf("dawn: %d %v", res.StatusCode, body)
  600. }
  601. // AdGuard clients: stub null → 404 not_configured
  602. res = get(t, srv.URL, "/api/adguard/clients", cookie)
  603. body = readJSON(t, res)
  604. if res.StatusCode != 404 || body["error"] != "not_configured" {
  605. t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
  606. }
  607. }
  608. func TestAPI404JSON(t *testing.T) {
  609. srv := makeTestServer(t)
  610. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  611. for _, path := range []string{"/api/no-existe", "/api/routers/"} {
  612. res := get(t, srv.URL, path, cookie)
  613. body := readJSON(t, res)
  614. if res.StatusCode != 404 || body["error"] != "not_found" {
  615. t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
  616. }
  617. }
  618. // Cualquier método → 404 JSON (no 405)
  619. req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
  620. req.Header.Set("Cookie", "session="+cookie)
  621. res, _ := http.DefaultClient.Do(req)
  622. body := readJSON(t, res)
  623. if res.StatusCode != 404 || body["error"] != "not_found" {
  624. t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
  625. }
  626. }
  627. func TestHealthEndpoints(t *testing.T) {
  628. srv := makeTestServer(t)
  629. res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
  630. body := readJSON(t, res)
  631. if res.StatusCode != 200 {
  632. t.Fatalf("/api/health: %d", res.StatusCode)
  633. }
  634. if body["ok"] != true || body["version"] != "2.0.0" || body["mode"] != "demo" || body["db"] != "ok" {
  635. t.Fatalf("/api/health: %v", body)
  636. }
  637. if _, ok := body["uptimeSec"].(float64); !ok {
  638. t.Fatalf("uptimeSec: %v", body)
  639. }
  640. res = get(t, srv.URL, "/health", "")
  641. body = readJSON(t, res)
  642. if body["status"] != "ok" || body["db"] != "connected" {
  643. t.Fatalf("/health: %v", body)
  644. }
  645. mem := body["memory"].(map[string]any)
  646. if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
  647. t.Fatalf("memory: %v", mem)
  648. }
  649. }
  650. func TestSecurityHeaders(t *testing.T) {
  651. srv := makeTestServer(t)
  652. res := get(t, srv.URL, "/api/health", "")
  653. res.Body.Close()
  654. want := map[string]string{
  655. "X-Content-Type-Options": "nosniff",
  656. "X-Frame-Options": "DENY",
  657. "Referrer-Policy": "strict-origin-when-cross-origin",
  658. "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
  659. "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
  660. "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'",
  661. }
  662. for k, v := range want {
  663. if got := res.Header.Get(k); got != v {
  664. t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
  665. }
  666. }
  667. }
  668. func TestSPAFallback(t *testing.T) {
  669. srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
  670. // Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
  671. // con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
  672. _ = srv
  673. }
  674. // writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
  675. // añade json.Encoder (consistencia con D5 WriteError).
  676. func TestWriteJSONSinSaltoFinal(t *testing.T) {
  677. srv := makeTestServer(t)
  678. res := get(t, srv.URL, "/api/health", "")
  679. defer res.Body.Close()
  680. body, err := io.ReadAll(res.Body)
  681. if err != nil {
  682. t.Fatal(err)
  683. }
  684. if len(body) == 0 {
  685. t.Fatal("body vacío")
  686. }
  687. if body[len(body)-1] == '\n' {
  688. t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
  689. }
  690. if !json.Valid(body) {
  691. t.Fatalf("body no es JSON válido: %q", body)
  692. }
  693. }