httpapi_test.go 38 KB

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