httpapi_test.go 27 KB

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