httpapi_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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", "displayName": "", "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; vm SIEMPRE, SPEC-65 D65-4)
  166. for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "vm", "ts"} {
  167. if _, ok := ov[k]; !ok {
  168. t.Fatalf("overview sin clave %q", k)
  169. }
  170. }
  171. if ov["vm"] != float64(1) {
  172. t.Fatalf("vm debe ser 1 (ViewModelVersion): %v", ov["vm"])
  173. }
  174. if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
  175. t.Fatalf("routers: %v", ov["routers"])
  176. }
  177. // ts en SEGUNDOS (no ms)
  178. if ts, ok := ov["ts"].(float64); !ok || ts > 1e11 {
  179. t.Fatalf("ts debe ser epoch en segundos: %v", ov["ts"])
  180. }
  181. }
  182. func TestLogoutRevocaSesion(t *testing.T) {
  183. srv := makeTestServer(t)
  184. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  185. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/logout", nil)
  186. req.Header.Set("Cookie", "session="+cookie)
  187. res, err := http.DefaultClient.Do(req)
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. res.Body.Close()
  192. if res.StatusCode != 204 {
  193. t.Fatalf("logout: got %d want 204", res.StatusCode)
  194. }
  195. if sc := res.Header.Get("Set-Cookie"); sc != "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" {
  196. t.Fatalf("Set-Cookie de borrado literal: %q", sc)
  197. }
  198. res2 := get(t, srv.URL, "/api/overview", cookie)
  199. res2.Body.Close()
  200. if res2.StatusCode != 401 {
  201. t.Fatalf("sesión revocada: got %d want 401", res2.StatusCode)
  202. }
  203. }
  204. func TestRateLimitQuintoFallo(t *testing.T) {
  205. srv := makeTestServer(t)
  206. hdr := []string{"X-Forwarded-For", "10.9.9.9"}
  207. for i := 1; i <= 5; i++ {
  208. status, _, _ := loginCookie(t, srv.URL, "admin", "nope", hdr...)
  209. if status != 401 {
  210. t.Fatalf("fallo %d: got %d want 401", i, status)
  211. }
  212. }
  213. // 6º intento: bloqueado (5 min)
  214. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`{"username":"admin","password":"nope"}`))
  215. req.Header.Set("X-Forwarded-For", "10.9.9.9")
  216. res, _ := http.DefaultClient.Do(req)
  217. if res.StatusCode != 429 {
  218. t.Fatalf("6º intento: got %d want 429", res.StatusCode)
  219. }
  220. body := readJSON(t, res)
  221. if body["error"] != "rate_limited" {
  222. t.Fatalf("error: %v", body)
  223. }
  224. retry, ok := body["retryAfterSec"].(float64)
  225. if !ok || retry <= 0 || retry > 300 {
  226. t.Fatalf("retryAfterSec: %v", body)
  227. }
  228. // Incluso con la password correcta sigue bloqueado.
  229. status, _, _ := loginCookie(t, srv.URL, "admin", "test1234", hdr...)
  230. if status != 429 {
  231. t.Fatalf("bloqueado con password correcta: got %d want 429", status)
  232. }
  233. // Persistencia en SQLite.
  234. var attempts int
  235. var lockedUntil int64
  236. if err := srv.db.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  237. Scan(&attempts, &lockedUntil); err != nil {
  238. t.Fatal(err)
  239. }
  240. if attempts < 5 || lockedUntil <= db.NowMS() {
  241. t.Fatalf("login_attempts: attempts=%d locked_until=%d", attempts, lockedUntil)
  242. }
  243. }
  244. func TestLoginInvalidBody400(t *testing.T) {
  245. srv := makeTestServer(t)
  246. for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
  247. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(payload))
  248. res, _ := http.DefaultClient.Do(req)
  249. body := readJSON(t, res)
  250. if res.StatusCode != 400 || body["error"] != "invalid_body" {
  251. t.Fatalf("payload %s: got %d %v", payload, res.StatusCode, body)
  252. }
  253. if body["message"] != `Se esperaba { "username": string, "password": string }` {
  254. t.Fatalf("message: %v", body["message"])
  255. }
  256. }
  257. }
  258. // ---------------------------------------------------------------------------
  259. // Port de tests/users.test.js
  260. // ---------------------------------------------------------------------------
  261. func TestUsersCRUD(t *testing.T) {
  262. srv := makeTestServer(t)
  263. // 401 sin sesión
  264. res := get(t, srv.URL, "/api/users", "")
  265. res.Body.Close()
  266. if res.StatusCode != 401 {
  267. t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
  268. }
  269. // Admin: lista con 1 usuario
  270. _, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  271. res = get(t, srv.URL, "/api/users", adminCookie)
  272. body := readJSON(t, res)
  273. users := body["users"].([]any)
  274. if len(users) != 1 || users[0].(map[string]any)["username"] != "admin" {
  275. t.Fatalf("users: %v", users)
  276. }
  277. // Alta 201
  278. req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto1"}`))
  279. req.Header.Set("Cookie", "session="+adminCookie)
  280. res, _ = http.DefaultClient.Do(req)
  281. if res.StatusCode != 201 {
  282. b, _ := io.ReadAll(res.Body)
  283. res.Body.Close()
  284. t.Fatalf("alta: got %d want 201 (%s)", res.StatusCode, b)
  285. }
  286. res.Body.Close()
  287. // Duplicado 409
  288. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra1234"}`))
  289. req.Header.Set("Cookie", "session="+adminCookie)
  290. res, _ = http.DefaultClient.Do(req)
  291. body = readJSON(t, res)
  292. if res.StatusCode != 409 || body["error"] != "duplicate_user" {
  293. t.Fatalf("duplicado: got %d %v", res.StatusCode, body)
  294. }
  295. // Username inválido 400
  296. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"mal usuario","password":"xxxxxxxxxx"}`))
  297. req.Header.Set("Cookie", "session="+adminCookie)
  298. res, _ = http.DefaultClient.Do(req)
  299. body = readJSON(t, res)
  300. if res.StatusCode != 400 || body["error"] != "invalid_input" {
  301. t.Fatalf("username inválido: got %d %v", res.StatusCode, body)
  302. }
  303. if body["message"] != "usuario debe ser alfanumérico (.-_ permitidos)" {
  304. t.Fatalf("message: %v", body["message"])
  305. }
  306. // El usuario creado puede loguear
  307. status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto1")
  308. if status != 204 {
  309. t.Fatalf("login ana: got %d", status)
  310. }
  311. // ID de ana
  312. res = get(t, srv.URL, "/api/users", adminCookie)
  313. body = readJSON(t, res)
  314. var anaID, adminID float64
  315. for _, u := range body["users"].([]any) {
  316. m := u.(map[string]any)
  317. if m["username"] == "ana" {
  318. anaID = m["id"].(float64)
  319. }
  320. if m["username"] == "admin" {
  321. adminID = m["id"].(float64)
  322. }
  323. }
  324. // Cambio de password → 204 e invalida la sesión de ana
  325. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/password", srv.URL, anaID), strings.NewReader(`{"password":"nueva-clave-9"}`))
  326. req.Header.Set("Cookie", "session="+adminCookie)
  327. res, _ = http.DefaultClient.Do(req)
  328. res.Body.Close()
  329. if res.StatusCode != 204 {
  330. t.Fatalf("set password: got %d want 204", res.StatusCode)
  331. }
  332. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  333. res.Body.Close()
  334. if res.StatusCode != 401 {
  335. t.Fatalf("sesión vieja de ana: got %d want 401", res.StatusCode)
  336. }
  337. status, anaCookie, _ = loginCookie(t, srv.URL, "ana", "nueva-clave-9")
  338. if status != 204 {
  339. t.Fatalf("re-login ana: got %d", status)
  340. }
  341. // No-admin → 403 en /api/users
  342. res = get(t, srv.URL, "/api/users", anaCookie)
  343. body = readJSON(t, res)
  344. if res.StatusCode != 403 || body["error"] != "forbidden" {
  345. t.Fatalf("no-admin: got %d %v", res.StatusCode, body)
  346. }
  347. // Pero SÍ puede cambiar su idioma (fuera del gate admin)
  348. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"es"}`))
  349. req.Header.Set("Cookie", "session="+anaCookie)
  350. res, _ = http.DefaultClient.Do(req)
  351. res.Body.Close()
  352. if res.StatusCode != 204 {
  353. t.Fatalf("me/language no-admin: got %d want 204", res.StatusCode)
  354. }
  355. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  356. body = readJSON(t, res)
  357. if body["language"] != "es" {
  358. t.Fatalf("language: %v", body)
  359. }
  360. // Idioma inválido → 400 literal
  361. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
  362. req.Header.Set("Cookie", "session="+anaCookie)
  363. res, _ = http.DefaultClient.Do(req)
  364. body = readJSON(t, res)
  365. if res.StatusCode != 400 || body["message"] != "language debe ser auto|es|en" {
  366. t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
  367. }
  368. // Rol via QUERY STRING (quirk): ana pasa a admin
  369. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
  370. req.Header.Set("Cookie", "session="+adminCookie)
  371. res, _ = http.DefaultClient.Do(req)
  372. res.Body.Close()
  373. if res.StatusCode != 204 {
  374. t.Fatalf("set role: got %d want 204", res.StatusCode)
  375. }
  376. // La sesión de ana quedó invalidada por el cambio de rol
  377. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  378. res.Body.Close()
  379. if res.StatusCode != 401 {
  380. t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
  381. }
  382. // Rol inválido → 400
  383. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), nil)
  384. req.Header.Set("Cookie", "session="+adminCookie)
  385. res, _ = http.DefaultClient.Do(req)
  386. body = readJSON(t, res)
  387. if res.StatusCode != 400 || body["message"] != "role debe ser admin|user" {
  388. t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
  389. }
  390. // No puedes cambiar tu propio rol
  391. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
  392. req.Header.Set("Cookie", "session="+adminCookie)
  393. res, _ = http.DefaultClient.Do(req)
  394. body = readJSON(t, res)
  395. if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
  396. t.Fatalf("self role: got %d %v", res.StatusCode, body)
  397. }
  398. // Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
  399. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
  400. req.Header.Set("Cookie", "session="+adminCookie)
  401. res, _ = http.DefaultClient.Do(req)
  402. res.Body.Close()
  403. if res.StatusCode != 204 {
  404. t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
  405. }
  406. // No se puede borrar a sí mismo
  407. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
  408. req.Header.Set("Cookie", "session="+adminCookie)
  409. res, _ = http.DefaultClient.Do(req)
  410. body = readJSON(t, res)
  411. if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
  412. t.Fatalf("self delete: got %d %v", res.StatusCode, body)
  413. }
  414. // Borrado 204 y luego 404
  415. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  416. req.Header.Set("Cookie", "session="+adminCookie)
  417. res, _ = http.DefaultClient.Do(req)
  418. res.Body.Close()
  419. if res.StatusCode != 204 {
  420. t.Fatalf("delete: got %d want 204", res.StatusCode)
  421. }
  422. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  423. req.Header.Set("Cookie", "session="+adminCookie)
  424. res, _ = http.DefaultClient.Do(req)
  425. body = readJSON(t, res)
  426. if res.StatusCode != 404 || body["error"] != "not_found" {
  427. t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
  428. }
  429. }
  430. // ---------------------------------------------------------------------------
  431. // Quirks de cache-control y datos
  432. // ---------------------------------------------------------------------------
  433. func TestCacheControl(t *testing.T) {
  434. srv := makeTestServer(t)
  435. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  436. cases := []struct {
  437. path string
  438. noStore bool
  439. }{
  440. {"/api/health", false},
  441. {"/api/auth/me", false},
  442. {"/api/overview", true},
  443. {"/api/users", true},
  444. {"/api/devices", true},
  445. {"/api/alerts", true},
  446. {"/api/topology", true},
  447. }
  448. for _, c := range cases {
  449. res := get(t, srv.URL, c.path, cookie)
  450. res.Body.Close()
  451. got := res.Header.Get("Cache-Control")
  452. if c.noStore && got != "no-store" {
  453. t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
  454. }
  455. if !c.noStore && got == "no-store" {
  456. t.Errorf("%s: NO debe llevar no-store", c.path)
  457. }
  458. }
  459. }
  460. func TestDevicesPaginacionYFiltros(t *testing.T) {
  461. srv := makeTestServer(t)
  462. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  463. // Paginación: 65 dispositivos del dataset canónico reconciliado
  464. // (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
  465. res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
  466. body := readJSON(t, res)
  467. if body["total"].(float64) != 65 || len(body["items"].([]any)) != 10 {
  468. t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
  469. }
  470. if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
  471. t.Fatalf("page/pageSize: %v", body)
  472. }
  473. res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
  474. body = readJSON(t, res)
  475. if len(body["items"].([]any)) != 5 {
  476. t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
  477. }
  478. // Sin solape con la página anterior
  479. res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
  480. prev := readJSON(t, res)
  481. prevIDs := map[string]bool{}
  482. for _, it := range prev["items"].([]any) {
  483. prevIDs[it.(map[string]any)["id"].(string)] = true
  484. }
  485. for _, it := range body["items"].([]any) {
  486. if prevIDs[it.(map[string]any)["id"].(string)] {
  487. t.Fatalf("solape entre page6 y page7: %v", it)
  488. }
  489. }
  490. // Defaults: pageSize=50
  491. res = get(t, srv.URL, "/api/devices", cookie)
  492. body = readJSON(t, res)
  493. if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
  494. t.Fatalf("defaults: %v", body)
  495. }
  496. // Filtros
  497. res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
  498. body = readJSON(t, res)
  499. if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
  500. t.Fatalf("routerId=living: %v", body["total"])
  501. }
  502. res = get(t, srv.URL, "/api/devices?band=cable", cookie)
  503. body = readJSON(t, res)
  504. for _, it := range body["items"].([]any) {
  505. if it.(map[string]any)["band"] != "cable" {
  506. t.Fatalf("band=cable con item de otra banda: %v", it)
  507. }
  508. }
  509. if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 3 netgear + pve + 10 CTs + 6 tras switch)
  510. t.Fatalf("band=cable: %v", body["total"])
  511. }
  512. res = get(t, srv.URL, "/api/devices?status=offline", cookie)
  513. body = readJSON(t, res)
  514. if body["total"].(float64) != 6 {
  515. t.Fatalf("status=offline: %v", body["total"])
  516. }
  517. res = get(t, srv.URL, "/api/devices?type=movil", cookie)
  518. body = readJSON(t, res)
  519. for _, it := range body["items"].([]any) {
  520. m := it.(map[string]any)
  521. if m["type"] != "movil" && m["group"] != "moviles" {
  522. t.Fatalf("type=movil con item que no casa: %v", m)
  523. }
  524. }
  525. if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
  526. t.Fatalf("type=movil: %v", body["total"])
  527. }
  528. res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
  529. body = readJSON(t, res)
  530. if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
  531. t.Fatalf("q=PIXEL: %v", body["total"])
  532. }
  533. // Inválidos → 400
  534. for _, u := range []string{
  535. "/api/devices?band=wifi6",
  536. "/api/devices?status=weird",
  537. "/api/devices?page=abc",
  538. "/api/devices?pageSize=1001",
  539. } {
  540. res = get(t, srv.URL, u, cookie)
  541. body = readJSON(t, res)
  542. if res.StatusCode != 400 || body["error"] != "invalid_query" {
  543. t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
  544. }
  545. }
  546. // Shape Device (12 claves del contrato)
  547. res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
  548. body = readJSON(t, res)
  549. dev := body["items"].([]any)[0].(map[string]any)
  550. for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
  551. if _, ok := dev[k]; !ok {
  552. t.Fatalf("device sin clave %q: %v", k, dev)
  553. }
  554. }
  555. }
  556. func TestAlertsEndpoint(t *testing.T) {
  557. srv := makeTestServer(t)
  558. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  559. res := get(t, srv.URL, "/api/alerts", cookie)
  560. body := readJSON(t, res)
  561. if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
  562. t.Fatalf("alerts default: %v", body)
  563. }
  564. res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
  565. body = readJSON(t, res)
  566. if body["total"].(float64) != 2 {
  567. t.Fatalf("severity=warn: %v", body["total"])
  568. }
  569. res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
  570. body = readJSON(t, res)
  571. if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
  572. t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
  573. }
  574. }
  575. func TestRoutersYDetalle(t *testing.T) {
  576. srv := makeTestServer(t)
  577. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  578. res := get(t, srv.URL, "/api/routers", cookie)
  579. body := readJSON(t, res)
  580. if len(body["routers"].([]any)) != 4 {
  581. t.Fatalf("routers: %v", body)
  582. }
  583. res = get(t, srv.URL, "/api/routers/flint2", cookie)
  584. if res.StatusCode != 200 {
  585. t.Fatalf("detalle flint2: %d", res.StatusCode)
  586. }
  587. detail := readJSON(t, res)
  588. for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
  589. if _, ok := detail[k]; !ok {
  590. t.Fatalf("detalle sin clave %q", k)
  591. }
  592. }
  593. res = get(t, srv.URL, "/api/routers/no-existe", cookie)
  594. body = readJSON(t, res)
  595. if res.StatusCode != 404 || body["error"] != "not_found" {
  596. t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
  597. }
  598. // DAWN: el stub devuelve null → 503
  599. res = get(t, srv.URL, "/api/dawn", cookie)
  600. body = readJSON(t, res)
  601. if res.StatusCode != 503 || body["error"] != "unavailable" {
  602. t.Fatalf("dawn: %d %v", res.StatusCode, body)
  603. }
  604. // AdGuard clients: stub null → 404 not_configured
  605. res = get(t, srv.URL, "/api/adguard/clients", cookie)
  606. body = readJSON(t, res)
  607. if res.StatusCode != 404 || body["error"] != "not_configured" {
  608. t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
  609. }
  610. }
  611. func TestAPI404JSON(t *testing.T) {
  612. srv := makeTestServer(t)
  613. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  614. for _, path := range []string{"/api/no-existe", "/api/routers/"} {
  615. res := get(t, srv.URL, path, cookie)
  616. body := readJSON(t, res)
  617. if res.StatusCode != 404 || body["error"] != "not_found" {
  618. t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
  619. }
  620. }
  621. // Cualquier método → 404 JSON (no 405)
  622. req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
  623. req.Header.Set("Cookie", "session="+cookie)
  624. res, _ := http.DefaultClient.Do(req)
  625. body := readJSON(t, res)
  626. if res.StatusCode != 404 || body["error"] != "not_found" {
  627. t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
  628. }
  629. }
  630. func TestHealthEndpoints(t *testing.T) {
  631. srv := makeTestServer(t)
  632. res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
  633. body := readJSON(t, res)
  634. if res.StatusCode != 200 {
  635. t.Fatalf("/api/health: %d", res.StatusCode)
  636. }
  637. if body["ok"] != true || body["version"] != httpapi.Version || body["mode"] != "demo" || body["db"] != "ok" {
  638. t.Fatalf("/api/health: %v", body)
  639. }
  640. if _, ok := body["uptimeSec"].(float64); !ok {
  641. t.Fatalf("uptimeSec: %v", body)
  642. }
  643. // Métricas operativas (Fase 8): los 3 campos presentes; en demo los
  644. // agentes/sse son 0 y devicesTotal viene del overview del poller demo.
  645. for _, k := range []string{"agentsConnected", "sseConnections", "devicesTotal"} {
  646. if _, ok := body[k].(float64); !ok {
  647. t.Fatalf("%s ausente o no numérico: %v", k, body)
  648. }
  649. }
  650. res = get(t, srv.URL, "/health", "")
  651. body = readJSON(t, res)
  652. if body["status"] != "ok" || body["db"] != "connected" {
  653. t.Fatalf("/health: %v", body)
  654. }
  655. mem := body["memory"].(map[string]any)
  656. if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
  657. t.Fatalf("memory: %v", mem)
  658. }
  659. }
  660. func TestSecurityHeaders(t *testing.T) {
  661. srv := makeTestServer(t)
  662. res := get(t, srv.URL, "/api/health", "")
  663. res.Body.Close()
  664. want := map[string]string{
  665. "X-Content-Type-Options": "nosniff",
  666. "X-Frame-Options": "DENY",
  667. "Referrer-Policy": "strict-origin-when-cross-origin",
  668. "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
  669. "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
  670. "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'",
  671. }
  672. for k, v := range want {
  673. if got := res.Header.Get(k); got != v {
  674. t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
  675. }
  676. }
  677. }
  678. func TestSPAFallback(t *testing.T) {
  679. srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
  680. // Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
  681. // con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
  682. _ = srv
  683. }
  684. // writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
  685. // añade json.Encoder (consistencia con D5 WriteError).
  686. func TestWriteJSONSinSaltoFinal(t *testing.T) {
  687. srv := makeTestServer(t)
  688. res := get(t, srv.URL, "/api/health", "")
  689. defer res.Body.Close()
  690. body, err := io.ReadAll(res.Body)
  691. if err != nil {
  692. t.Fatal(err)
  693. }
  694. if len(body) == 0 {
  695. t.Fatal("body vacío")
  696. }
  697. if body[len(body)-1] == '\n' {
  698. t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
  699. }
  700. if !json.Valid(body) {
  701. t.Fatalf("body no es JSON válido: %q", body)
  702. }
  703. }
  704. func TestWebhookDLQEndpoint(t *testing.T) {
  705. srv := makeTestServer(t)
  706. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  707. if status != 204 {
  708. t.Fatalf("login: %d", status)
  709. }
  710. // Sin sesión → 401 (el middleware global exige auth)
  711. req, _ := http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  712. res, _ := http.DefaultClient.Do(req)
  713. res.Body.Close()
  714. if res.StatusCode != 401 {
  715. t.Fatalf("sin sesión debería dar 401, dio %d", res.StatusCode)
  716. }
  717. // Con sesión admin → 200 con items vacío (tabla nueva)
  718. req, _ = http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  719. req.Header.Set("Cookie", "session="+cookie)
  720. res, _ = http.DefaultClient.Do(req)
  721. body := readJSON(t, res)
  722. if res.StatusCode != 200 {
  723. t.Fatalf("con sesión debería dar 200, dio %d", res.StatusCode)
  724. }
  725. if body["total"].(float64) != 0 {
  726. t.Fatalf("DLQ vacío esperado, total=%v", body["total"])
  727. }
  728. }