httpapi_test.go 32 KB

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