httpapi_test.go 39 KB

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