httpapi_test.go 29 KB

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