httpapi_test.go 32 KB

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