httpapi_test.go 32 KB

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