httpapi_test.go 35 KB

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