httpapi_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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 y ru son válidos (catálogos en la UI)
  516. for _, lang := range []string{"zh", "ru"} {
  517. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"`+lang+`"}`))
  518. req.Header.Set("Cookie", "session="+anaCookie)
  519. res, _ = http.DefaultClient.Do(req)
  520. res.Body.Close()
  521. if res.StatusCode != 204 {
  522. t.Fatalf("me/language %s: got %d want 204", lang, res.StatusCode)
  523. }
  524. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  525. body = readJSON(t, res)
  526. if body["language"] != lang {
  527. t.Fatalf("language %s: %v", lang, body)
  528. }
  529. }
  530. // Idioma inválido → 400 literal
  531. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
  532. req.Header.Set("Cookie", "session="+anaCookie)
  533. res, _ = http.DefaultClient.Do(req)
  534. body = readJSON(t, res)
  535. if res.StatusCode != 400 || body["message"] != "language must be auto|es|en|zh|ru" {
  536. t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
  537. }
  538. // Rol via QUERY STRING (quirk): ana pasa a admin
  539. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
  540. req.Header.Set("Cookie", "session="+adminCookie)
  541. res, _ = http.DefaultClient.Do(req)
  542. res.Body.Close()
  543. if res.StatusCode != 204 {
  544. t.Fatalf("set role: got %d want 204", res.StatusCode)
  545. }
  546. // La sesión de ana quedó invalidada por el cambio de rol
  547. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  548. res.Body.Close()
  549. if res.StatusCode != 401 {
  550. t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
  551. }
  552. // Rol inválido → 400
  553. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), nil)
  554. req.Header.Set("Cookie", "session="+adminCookie)
  555. res, _ = http.DefaultClient.Do(req)
  556. body = readJSON(t, res)
  557. if res.StatusCode != 400 || body["message"] != "role debe ser admin|user" {
  558. t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
  559. }
  560. // No puedes cambiar tu propio rol
  561. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
  562. req.Header.Set("Cookie", "session="+adminCookie)
  563. res, _ = http.DefaultClient.Do(req)
  564. body = readJSON(t, res)
  565. if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
  566. t.Fatalf("self role: got %d %v", res.StatusCode, body)
  567. }
  568. // Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
  569. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
  570. req.Header.Set("Cookie", "session="+adminCookie)
  571. res, _ = http.DefaultClient.Do(req)
  572. res.Body.Close()
  573. if res.StatusCode != 204 {
  574. t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
  575. }
  576. // No se puede borrar a sí mismo
  577. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
  578. req.Header.Set("Cookie", "session="+adminCookie)
  579. res, _ = http.DefaultClient.Do(req)
  580. body = readJSON(t, res)
  581. if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
  582. t.Fatalf("self delete: got %d %v", res.StatusCode, body)
  583. }
  584. // Borrado 204 y luego 404
  585. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  586. req.Header.Set("Cookie", "session="+adminCookie)
  587. res, _ = http.DefaultClient.Do(req)
  588. res.Body.Close()
  589. if res.StatusCode != 204 {
  590. t.Fatalf("delete: got %d want 204", res.StatusCode)
  591. }
  592. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  593. req.Header.Set("Cookie", "session="+adminCookie)
  594. res, _ = http.DefaultClient.Do(req)
  595. body = readJSON(t, res)
  596. if res.StatusCode != 404 || body["error"] != "not_found" {
  597. t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
  598. }
  599. }
  600. // ---------------------------------------------------------------------------
  601. // Quirks de cache-control y datos
  602. // ---------------------------------------------------------------------------
  603. func TestCacheControl(t *testing.T) {
  604. srv := makeTestServer(t)
  605. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  606. cases := []struct {
  607. path string
  608. noStore bool
  609. }{
  610. {"/api/health", false},
  611. {"/api/auth/me", false},
  612. {"/api/overview", true},
  613. {"/api/users", true},
  614. {"/api/devices", true},
  615. {"/api/alerts", true},
  616. {"/api/topology", true},
  617. }
  618. for _, c := range cases {
  619. res := get(t, srv.URL, c.path, cookie)
  620. res.Body.Close()
  621. got := res.Header.Get("Cache-Control")
  622. if c.noStore && got != "no-store" {
  623. t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
  624. }
  625. if !c.noStore && got == "no-store" {
  626. t.Errorf("%s: NO debe llevar no-store", c.path)
  627. }
  628. }
  629. }
  630. func TestDevicesPaginacionYFiltros(t *testing.T) {
  631. srv := makeTestServer(t)
  632. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  633. // Paginación: 65 dispositivos del dataset canónico reconciliado
  634. // (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
  635. res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
  636. body := readJSON(t, res)
  637. if body["total"].(float64) != 65 || len(body["items"].([]any)) != 10 {
  638. t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
  639. }
  640. if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
  641. t.Fatalf("page/pageSize: %v", body)
  642. }
  643. res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
  644. body = readJSON(t, res)
  645. if len(body["items"].([]any)) != 5 {
  646. t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
  647. }
  648. // Sin solape con la página anterior
  649. res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
  650. prev := readJSON(t, res)
  651. prevIDs := map[string]bool{}
  652. for _, it := range prev["items"].([]any) {
  653. prevIDs[it.(map[string]any)["id"].(string)] = true
  654. }
  655. for _, it := range body["items"].([]any) {
  656. if prevIDs[it.(map[string]any)["id"].(string)] {
  657. t.Fatalf("solape entre page6 y page7: %v", it)
  658. }
  659. }
  660. // Defaults: pageSize=50
  661. res = get(t, srv.URL, "/api/devices", cookie)
  662. body = readJSON(t, res)
  663. if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
  664. t.Fatalf("defaults: %v", body)
  665. }
  666. // typeCounts: inventario agrupado por tipo (conteos suman el total)
  667. if tc, ok := body["typeCounts"].(map[string]any); !ok {
  668. t.Fatalf("typeCounts ausente: %v", body)
  669. } else {
  670. sum := 0
  671. for _, v := range tc {
  672. sum += int(v.(float64))
  673. }
  674. if sum != 65 {
  675. t.Fatalf("typeCounts suma %d, esperaba 65: %v", sum, tc)
  676. }
  677. }
  678. // Filtros
  679. res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
  680. body = readJSON(t, res)
  681. if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
  682. t.Fatalf("routerId=living: %v", body["total"])
  683. }
  684. res = get(t, srv.URL, "/api/devices?band=cable", cookie)
  685. body = readJSON(t, res)
  686. for _, it := range body["items"].([]any) {
  687. if it.(map[string]any)["band"] != "cable" {
  688. t.Fatalf("band=cable con item de otra banda: %v", it)
  689. }
  690. }
  691. if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 3 netgear + pve + 10 CTs + 6 tras switch)
  692. t.Fatalf("band=cable: %v", body["total"])
  693. }
  694. res = get(t, srv.URL, "/api/devices?status=offline", cookie)
  695. body = readJSON(t, res)
  696. if body["total"].(float64) != 6 {
  697. t.Fatalf("status=offline: %v", body["total"])
  698. }
  699. res = get(t, srv.URL, "/api/devices?type=movil", cookie)
  700. body = readJSON(t, res)
  701. for _, it := range body["items"].([]any) {
  702. m := it.(map[string]any)
  703. if m["type"] != "movil" && m["group"] != "moviles" {
  704. t.Fatalf("type=movil con item que no casa: %v", m)
  705. }
  706. }
  707. if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
  708. t.Fatalf("type=movil: %v", body["total"])
  709. }
  710. res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
  711. body = readJSON(t, res)
  712. if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
  713. t.Fatalf("q=PIXEL: %v", body["total"])
  714. }
  715. // Inválidos → 400
  716. for _, u := range []string{
  717. "/api/devices?band=wifi6",
  718. "/api/devices?status=weird",
  719. "/api/devices?page=abc",
  720. "/api/devices?pageSize=1001",
  721. } {
  722. res = get(t, srv.URL, u, cookie)
  723. body = readJSON(t, res)
  724. if res.StatusCode != 400 || body["error"] != "invalid_query" {
  725. t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
  726. }
  727. }
  728. // Shape Device (12 claves del contrato)
  729. res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
  730. body = readJSON(t, res)
  731. dev := body["items"].([]any)[0].(map[string]any)
  732. for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
  733. if _, ok := dev[k]; !ok {
  734. t.Fatalf("device sin clave %q: %v", k, dev)
  735. }
  736. }
  737. }
  738. func TestAlertsEndpoint(t *testing.T) {
  739. srv := makeTestServer(t)
  740. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  741. res := get(t, srv.URL, "/api/alerts", cookie)
  742. body := readJSON(t, res)
  743. if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
  744. t.Fatalf("alerts default: %v", body)
  745. }
  746. res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
  747. body = readJSON(t, res)
  748. if body["total"].(float64) != 2 {
  749. t.Fatalf("severity=warn: %v", body["total"])
  750. }
  751. res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
  752. body = readJSON(t, res)
  753. if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
  754. t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
  755. }
  756. }
  757. func TestRoutersYDetalle(t *testing.T) {
  758. srv := makeTestServer(t)
  759. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  760. res := get(t, srv.URL, "/api/routers", cookie)
  761. body := readJSON(t, res)
  762. if len(body["routers"].([]any)) != 4 {
  763. t.Fatalf("routers: %v", body)
  764. }
  765. res = get(t, srv.URL, "/api/routers/flint2", cookie)
  766. if res.StatusCode != 200 {
  767. t.Fatalf("detalle flint2: %d", res.StatusCode)
  768. }
  769. detail := readJSON(t, res)
  770. for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
  771. if _, ok := detail[k]; !ok {
  772. t.Fatalf("detalle sin clave %q", k)
  773. }
  774. }
  775. res = get(t, srv.URL, "/api/routers/no-existe", cookie)
  776. body = readJSON(t, res)
  777. if res.StatusCode != 404 || body["error"] != "not_found" {
  778. t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
  779. }
  780. // DAWN: el stub devuelve null → 503
  781. res = get(t, srv.URL, "/api/usteer", cookie)
  782. body = readJSON(t, res)
  783. if res.StatusCode != 503 || body["error"] != "unavailable" {
  784. t.Fatalf("dawn: %d %v", res.StatusCode, body)
  785. }
  786. // AdGuard clients: stub null → 404 not_configured
  787. res = get(t, srv.URL, "/api/adguard/clients", cookie)
  788. body = readJSON(t, res)
  789. if res.StatusCode != 404 || body["error"] != "not_configured" {
  790. t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
  791. }
  792. }
  793. func TestAPI404JSON(t *testing.T) {
  794. srv := makeTestServer(t)
  795. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  796. for _, path := range []string{"/api/no-existe", "/api/routers/"} {
  797. res := get(t, srv.URL, path, cookie)
  798. body := readJSON(t, res)
  799. if res.StatusCode != 404 || body["error"] != "not_found" {
  800. t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
  801. }
  802. }
  803. // Cualquier método → 404 JSON (no 405)
  804. req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
  805. req.Header.Set("Cookie", "session="+cookie)
  806. res, _ := http.DefaultClient.Do(req)
  807. body := readJSON(t, res)
  808. if res.StatusCode != 404 || body["error"] != "not_found" {
  809. t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
  810. }
  811. }
  812. func TestHealthEndpoints(t *testing.T) {
  813. srv := makeTestServer(t)
  814. res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
  815. body := readJSON(t, res)
  816. if res.StatusCode != 200 {
  817. t.Fatalf("/api/health: %d", res.StatusCode)
  818. }
  819. if body["ok"] != true || body["version"] != httpapi.Version || body["mode"] != "demo" || body["db"] != "ok" {
  820. t.Fatalf("/api/health: %v", body)
  821. }
  822. if _, ok := body["uptimeSec"].(float64); !ok {
  823. t.Fatalf("uptimeSec: %v", body)
  824. }
  825. // Métricas operativas (Fase 8): los 3 campos presentes; en demo los
  826. // agentes/sse son 0 y devicesTotal viene del overview del poller demo.
  827. for _, k := range []string{"agentsConnected", "sseConnections", "agentSseConnections", "devicesTotal"} {
  828. if _, ok := body[k].(float64); !ok {
  829. t.Fatalf("%s ausente o no numérico: %v", k, body)
  830. }
  831. }
  832. res = get(t, srv.URL, "/health", "")
  833. body = readJSON(t, res)
  834. if body["status"] != "ok" || body["db"] != "connected" {
  835. t.Fatalf("/health: %v", body)
  836. }
  837. mem := body["memory"].(map[string]any)
  838. if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
  839. t.Fatalf("memory: %v", mem)
  840. }
  841. }
  842. func TestSecurityHeaders(t *testing.T) {
  843. srv := makeTestServer(t)
  844. res := get(t, srv.URL, "/api/health", "")
  845. res.Body.Close()
  846. want := map[string]string{
  847. "X-Content-Type-Options": "nosniff",
  848. "X-Frame-Options": "DENY",
  849. "Referrer-Policy": "strict-origin-when-cross-origin",
  850. "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
  851. "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'",
  852. }
  853. for k, v := range want {
  854. if got := res.Header.Get(k); got != v {
  855. t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
  856. }
  857. }
  858. // FORK: HSTS only on secure responses; plain HTTP never carries it.
  859. if got := res.Header.Get("Strict-Transport-Security"); got != "" {
  860. t.Errorf("plain HTTP response carried HSTS %q", got)
  861. }
  862. }
  863. // FORK: behind a TLS-terminating proxy the server trusts (the test server
  864. // sets TRUST_PROXY), a request forwarded as https gets HSTS.
  865. func TestSecurityHeadersHSTSOnSecureRequests(t *testing.T) {
  866. srv := makeTestServer(t)
  867. req, err := http.NewRequest("GET", srv.URL+"/api/health", nil)
  868. if err != nil {
  869. t.Fatal(err)
  870. }
  871. req.Header.Set("X-Forwarded-Proto", "https")
  872. res, err := http.DefaultClient.Do(req)
  873. if err != nil {
  874. t.Fatal(err)
  875. }
  876. res.Body.Close()
  877. if got := res.Header.Get("Strict-Transport-Security"); got != "max-age=31536000" {
  878. t.Errorf("HSTS on a secure request = %q, want max-age=31536000", got)
  879. }
  880. }
  881. func TestSPAFallback(t *testing.T) {
  882. srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
  883. // Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
  884. // con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
  885. _ = srv
  886. }
  887. // writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
  888. // añade json.Encoder (consistencia con D5 WriteError).
  889. func TestWriteJSONSinSaltoFinal(t *testing.T) {
  890. srv := makeTestServer(t)
  891. res := get(t, srv.URL, "/api/health", "")
  892. defer res.Body.Close()
  893. body, err := io.ReadAll(res.Body)
  894. if err != nil {
  895. t.Fatal(err)
  896. }
  897. if len(body) == 0 {
  898. t.Fatal("body vacío")
  899. }
  900. if body[len(body)-1] == '\n' {
  901. t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
  902. }
  903. if !json.Valid(body) {
  904. t.Fatalf("body no es JSON válido: %q", body)
  905. }
  906. }
  907. func TestWebhookDLQEndpoint(t *testing.T) {
  908. srv := makeTestServer(t)
  909. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  910. if status != 204 {
  911. t.Fatalf("login: %d", status)
  912. }
  913. // Sin sesión → 401 (el middleware global exige auth)
  914. req, _ := http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  915. res, _ := http.DefaultClient.Do(req)
  916. res.Body.Close()
  917. if res.StatusCode != 401 {
  918. t.Fatalf("sin sesión debería dar 401, dio %d", res.StatusCode)
  919. }
  920. // Con sesión admin → 200 con items vacío (tabla nueva)
  921. req, _ = http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  922. req.Header.Set("Cookie", "session="+cookie)
  923. res, _ = http.DefaultClient.Do(req)
  924. body := readJSON(t, res)
  925. if res.StatusCode != 200 {
  926. t.Fatalf("con sesión debería dar 200, dio %d", res.StatusCode)
  927. }
  928. if body["total"].(float64) != 0 {
  929. t.Fatalf("DLQ vacío esperado, total=%v", body["total"])
  930. }
  931. }
  932. func TestPortSeriesEndpoint(t *testing.T) {
  933. srv := makeTestServer(t)
  934. defer srv.Close()
  935. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  936. if srv.db.PortSeries == nil {
  937. t.Fatal("PortSeries store not initialized")
  938. }
  939. now := time.Now()
  940. err := srv.db.PortSeries.RecordSample(portseries.PortSample{
  941. RouterID: "rt1", PortID: "lan1", TS: now,
  942. RxBytes: 1000, TxBytes: 2000, RxBps: 500, TxBps: 1000, SpeedMbps: 1000,
  943. })
  944. if err != nil {
  945. t.Fatalf("record sample: %v", err)
  946. }
  947. from := now.Add(-time.Hour).Unix()
  948. to := now.Add(time.Hour).Unix()
  949. req, _ := http.NewRequest("GET",
  950. fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
  951. req.Header.Set("Cookie", "session="+cookie)
  952. res, err := http.DefaultClient.Do(req)
  953. if err != nil {
  954. t.Fatalf("request: %v", err)
  955. }
  956. defer res.Body.Close()
  957. if res.StatusCode != 200 {
  958. t.Fatalf("expected 200, got %d", res.StatusCode)
  959. }
  960. body := readJSON(t, res)
  961. if body["resolution"] != "raw" {
  962. t.Errorf("expected raw resolution, got %v", body["resolution"])
  963. }
  964. points, ok := body["points"].([]any)
  965. if !ok {
  966. t.Fatalf("points is not an array: %T", body["points"])
  967. }
  968. if len(points) == 0 {
  969. t.Error("expected at least 1 point, got 0")
  970. }
  971. }
  972. func TestPortSeriesAutoResolution(t *testing.T) {
  973. srv := makeTestServer(t)
  974. defer srv.Close()
  975. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  976. now := time.Now()
  977. from := now.Add(-60 * 24 * time.Hour).Unix()
  978. to := now.Unix()
  979. req, _ := http.NewRequest("GET",
  980. fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
  981. req.Header.Set("Cookie", "session="+cookie)
  982. res, err := http.DefaultClient.Do(req)
  983. if err != nil {
  984. t.Fatalf("request: %v", err)
  985. }
  986. defer res.Body.Close()
  987. if res.StatusCode != 200 {
  988. t.Fatalf("expected 200, got %d", res.StatusCode)
  989. }
  990. body := readJSON(t, res)
  991. if body["resolution"] != "daily" {
  992. t.Errorf("expected daily resolution for 60d range, got %v", body["resolution"])
  993. }
  994. }
  995. func TestPortSeriesInvalidResolution(t *testing.T) {
  996. srv := makeTestServer(t)
  997. defer srv.Close()
  998. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  999. req, _ := http.NewRequest("GET", srv.URL+"/api/routers/rt1/ports/lan1/series?resolution=invalid", nil)
  1000. req.Header.Set("Cookie", "session="+cookie)
  1001. res, err := http.DefaultClient.Do(req)
  1002. if err != nil {
  1003. t.Fatalf("request: %v", err)
  1004. }
  1005. defer res.Body.Close()
  1006. if res.StatusCode != 400 {
  1007. t.Errorf("expected 400 for invalid resolution, got %d", res.StatusCode)
  1008. }
  1009. }
  1010. func TestDeviceTrafficEndpoint(t *testing.T) {
  1011. srv := makeTestServer(t)
  1012. defer srv.Close()
  1013. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  1014. if srv.db.ClientBW == nil {
  1015. t.Fatal("ClientBW store not initialized")
  1016. }
  1017. now := time.Now()
  1018. err := srv.db.ClientBW.Insert(clientbw.Sample{
  1019. MAC: "aa:bb:cc:dd:ee:01", RouterID: "rt2", TS: now,
  1020. RxBytes: 1000, TxBytes: 2000, RxBps: 8000, TxBps: 16000,
  1021. })
  1022. if err != nil {
  1023. t.Fatalf("insert sample: %v", err)
  1024. }
  1025. from := now.Add(-time.Hour).Unix()
  1026. to := now.Add(time.Hour).Unix()
  1027. req, _ := http.NewRequest("GET",
  1028. fmt.Sprintf("%s/api/devices/aa:bb:cc:dd:ee:01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
  1029. req.Header.Set("Cookie", "session="+cookie)
  1030. res, err := http.DefaultClient.Do(req)
  1031. if err != nil {
  1032. t.Fatalf("request: %v", err)
  1033. }
  1034. defer res.Body.Close()
  1035. if res.StatusCode != 200 {
  1036. t.Fatalf("expected 200, got %d", res.StatusCode)
  1037. }
  1038. body := readJSON(t, res)
  1039. points, ok := body["points"].([]any)
  1040. if !ok || len(points) == 0 {
  1041. t.Fatalf("expected points, got %T %v", body["points"], body["points"])
  1042. }
  1043. // La MAC del path se normaliza: formato con guiones también vale.
  1044. req2, _ := http.NewRequest("GET",
  1045. fmt.Sprintf("%s/api/devices/aa-bb-cc-dd-ee-01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
  1046. req2.Header.Set("Cookie", "session="+cookie)
  1047. res2, err := http.DefaultClient.Do(req2)
  1048. if err != nil {
  1049. t.Fatalf("request guiones: %v", err)
  1050. }
  1051. defer res2.Body.Close()
  1052. if res2.StatusCode != 200 {
  1053. t.Fatalf("guiones expected 200, got %d", res2.StatusCode)
  1054. }
  1055. }
  1056. func TestDeviceTrafficInvalidMAC(t *testing.T) {
  1057. srv := makeTestServer(t)
  1058. defer srv.Close()
  1059. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  1060. req, _ := http.NewRequest("GET", srv.URL+"/api/devices/not-a-mac/traffic", nil)
  1061. req.Header.Set("Cookie", "session="+cookie)
  1062. res, err := http.DefaultClient.Do(req)
  1063. if err != nil {
  1064. t.Fatalf("request: %v", err)
  1065. }
  1066. defer res.Body.Close()
  1067. if res.StatusCode != 400 {
  1068. t.Fatalf("expected 400 for invalid mac, got %d", res.StatusCode)
  1069. }
  1070. }