httpapi_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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 TestMutationsCrossOriginRejected(t *testing.T) {
  248. // Issue #213: una mutación con Origin cruzado → 403 cross_origin antes
  249. // incluso de la autenticación; el login legítimo con Origin propio pasa.
  250. srv := makeTestServer(t)
  251. req, _ := http.NewRequest("POST", srv.URL+"/api/refresh", strings.NewReader(`{}`))
  252. req.Header.Set("Origin", "https://evil.example")
  253. res, _ := http.DefaultClient.Do(req)
  254. if res.StatusCode != http.StatusForbidden {
  255. t.Fatalf("POST cross-origin: got %d want 403", res.StatusCode)
  256. }
  257. body := readJSON(t, res)
  258. if body["error"] != "cross_origin" {
  259. t.Fatalf("error: %v", body)
  260. }
  261. u, _ := url.Parse(srv.URL)
  262. req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login",
  263. strings.NewReader(`{"username":"admin","password":"test123456"}`))
  264. req2.Header.Set("Origin", u.Scheme+"://"+u.Host)
  265. res2, _ := http.DefaultClient.Do(req2)
  266. if res2.StatusCode != http.StatusNoContent {
  267. t.Fatalf("login con Origin propio: got %d want 204", res2.StatusCode)
  268. }
  269. }
  270. func TestRateLimitQuintoFallo(t *testing.T) {
  271. srv := makeTestServer(t)
  272. hdr := []string{"X-Forwarded-For", "10.9.9.9"}
  273. for i := 1; i <= 5; i++ {
  274. status, _, _ := loginCookie(t, srv.URL, "admin", "nope", hdr...)
  275. if status != 401 {
  276. t.Fatalf("fallo %d: got %d want 401", i, status)
  277. }
  278. }
  279. // 6º intento: bloqueado (5 min)
  280. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`{"username":"admin","password":"nope"}`))
  281. req.Header.Set("X-Forwarded-For", "10.9.9.9")
  282. res, _ := http.DefaultClient.Do(req)
  283. if res.StatusCode != 429 {
  284. t.Fatalf("6º intento: got %d want 429", res.StatusCode)
  285. }
  286. body := readJSON(t, res)
  287. if body["error"] != "rate_limited" {
  288. t.Fatalf("error: %v", body)
  289. }
  290. retry, ok := body["retryAfterSec"].(float64)
  291. if !ok || retry <= 0 || retry > 300 {
  292. t.Fatalf("retryAfterSec: %v", body)
  293. }
  294. // Incluso con la password correcta sigue bloqueado.
  295. status, _, _ := loginCookie(t, srv.URL, "admin", "test123456", hdr...)
  296. if status != 429 {
  297. t.Fatalf("bloqueado con password correcta: got %d want 429", status)
  298. }
  299. // Persistencia en SQLite.
  300. var attempts int
  301. var lockedUntil int64
  302. if err := srv.db.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  303. Scan(&attempts, &lockedUntil); err != nil {
  304. t.Fatal(err)
  305. }
  306. if attempts < 5 || lockedUntil <= db.NowMS() {
  307. t.Fatalf("login_attempts: attempts=%d locked_until=%d", attempts, lockedUntil)
  308. }
  309. }
  310. func TestOversizedBodyReturns413(t *testing.T) {
  311. // Issue #215: un body mayor que maxBodyBytes responde 413 payload_too_large
  312. // (no 400 invalid_body) con el writer real en MaxBytesReader.
  313. srv := makeTestServer(t)
  314. big := `{"username":"admin","password":"` + strings.Repeat("a", (64<<10)+100) + `"}`
  315. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(big))
  316. res, _ := http.DefaultClient.Do(req)
  317. if res.StatusCode != http.StatusRequestEntityTooLarge {
  318. t.Fatalf("body > maxBodyBytes: got %d want 413", res.StatusCode)
  319. }
  320. body := readJSON(t, res)
  321. if body["error"] != "payload_too_large" {
  322. t.Fatalf("error: %v", body)
  323. }
  324. // Un JSON mal formado pero pequeño sigue siendo 400 invalid_body.
  325. req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`not-json`))
  326. res2, _ := http.DefaultClient.Do(req2)
  327. if res2.StatusCode != http.StatusBadRequest || readJSON(t, res2)["error"] != "invalid_body" {
  328. t.Fatalf("JSON inválido: got %d want 400 invalid_body", res2.StatusCode)
  329. }
  330. }
  331. func TestLoginInvalidBody400(t *testing.T) {
  332. srv := makeTestServer(t)
  333. for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
  334. req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(payload))
  335. res, _ := http.DefaultClient.Do(req)
  336. body := readJSON(t, res)
  337. if res.StatusCode != 400 || body["error"] != "invalid_body" {
  338. t.Fatalf("payload %s: got %d %v", payload, res.StatusCode, body)
  339. }
  340. if body["message"] != `Se esperaba { "username": string, "password": string }` {
  341. t.Fatalf("message: %v", body["message"])
  342. }
  343. }
  344. }
  345. // ---------------------------------------------------------------------------
  346. // Port de tests/users.test.js
  347. // ---------------------------------------------------------------------------
  348. func TestUsersCRUD(t *testing.T) {
  349. srv := makeTestServer(t)
  350. // 401 sin sesión
  351. res := get(t, srv.URL, "/api/users", "")
  352. res.Body.Close()
  353. if res.StatusCode != 401 {
  354. t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
  355. }
  356. // Admin: lista con 1 usuario
  357. _, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  358. res = get(t, srv.URL, "/api/users", adminCookie)
  359. body := readJSON(t, res)
  360. users := body["users"].([]any)
  361. if len(users) != 1 || users[0].(map[string]any)["username"] != "admin" {
  362. t.Fatalf("users: %v", users)
  363. }
  364. // Alta 201
  365. req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto12345"}`))
  366. req.Header.Set("Cookie", "session="+adminCookie)
  367. res, _ = http.DefaultClient.Do(req)
  368. if res.StatusCode != 201 {
  369. b, _ := io.ReadAll(res.Body)
  370. res.Body.Close()
  371. t.Fatalf("alta: got %d want 201 (%s)", res.StatusCode, b)
  372. }
  373. res.Body.Close()
  374. // Duplicado 409
  375. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra123456"}`))
  376. req.Header.Set("Cookie", "session="+adminCookie)
  377. res, _ = http.DefaultClient.Do(req)
  378. body = readJSON(t, res)
  379. if res.StatusCode != 409 || body["error"] != "duplicate_user" {
  380. t.Fatalf("duplicado: got %d %v", res.StatusCode, body)
  381. }
  382. // Username inválido 400
  383. req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"mal usuario","password":"xxxxxxxxxx"}`))
  384. req.Header.Set("Cookie", "session="+adminCookie)
  385. res, _ = http.DefaultClient.Do(req)
  386. body = readJSON(t, res)
  387. if res.StatusCode != 400 || body["error"] != "invalid_input" {
  388. t.Fatalf("username inválido: got %d %v", res.StatusCode, body)
  389. }
  390. if body["message"] != "usuario debe ser alfanumérico (.-_ permitidos)" {
  391. t.Fatalf("message: %v", body["message"])
  392. }
  393. // El usuario creado puede loguear
  394. status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto12345")
  395. if status != 204 {
  396. t.Fatalf("login ana: got %d", status)
  397. }
  398. // ID de ana
  399. res = get(t, srv.URL, "/api/users", adminCookie)
  400. body = readJSON(t, res)
  401. var anaID, adminID float64
  402. for _, u := range body["users"].([]any) {
  403. m := u.(map[string]any)
  404. if m["username"] == "ana" {
  405. anaID = m["id"].(float64)
  406. }
  407. if m["username"] == "admin" {
  408. adminID = m["id"].(float64)
  409. }
  410. }
  411. // Cambio de password → 204 e invalida la sesión de ana
  412. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/password", srv.URL, anaID), strings.NewReader(`{"password":"nueva-clave-9"}`))
  413. req.Header.Set("Cookie", "session="+adminCookie)
  414. res, _ = http.DefaultClient.Do(req)
  415. res.Body.Close()
  416. if res.StatusCode != 204 {
  417. t.Fatalf("set password: got %d want 204", res.StatusCode)
  418. }
  419. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  420. res.Body.Close()
  421. if res.StatusCode != 401 {
  422. t.Fatalf("sesión vieja de ana: got %d want 401", res.StatusCode)
  423. }
  424. status, anaCookie, _ = loginCookie(t, srv.URL, "ana", "nueva-clave-9")
  425. if status != 204 {
  426. t.Fatalf("re-login ana: got %d", status)
  427. }
  428. // No-admin → 403 en /api/users
  429. res = get(t, srv.URL, "/api/users", anaCookie)
  430. body = readJSON(t, res)
  431. if res.StatusCode != 403 || body["error"] != "forbidden" {
  432. t.Fatalf("no-admin: got %d %v", res.StatusCode, body)
  433. }
  434. // Pero SÍ puede cambiar su idioma (fuera del gate admin)
  435. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"es"}`))
  436. req.Header.Set("Cookie", "session="+anaCookie)
  437. res, _ = http.DefaultClient.Do(req)
  438. res.Body.Close()
  439. if res.StatusCode != 204 {
  440. t.Fatalf("me/language no-admin: got %d want 204", res.StatusCode)
  441. }
  442. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  443. body = readJSON(t, res)
  444. if body["language"] != "es" {
  445. t.Fatalf("language: %v", body)
  446. }
  447. // Idioma inválido → 400 literal
  448. req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
  449. req.Header.Set("Cookie", "session="+anaCookie)
  450. res, _ = http.DefaultClient.Do(req)
  451. body = readJSON(t, res)
  452. if res.StatusCode != 400 || body["message"] != "language debe ser auto|es|en" {
  453. t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
  454. }
  455. // Rol via QUERY STRING (quirk): ana pasa a admin
  456. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
  457. req.Header.Set("Cookie", "session="+adminCookie)
  458. res, _ = http.DefaultClient.Do(req)
  459. res.Body.Close()
  460. if res.StatusCode != 204 {
  461. t.Fatalf("set role: got %d want 204", res.StatusCode)
  462. }
  463. // La sesión de ana quedó invalidada por el cambio de rol
  464. res = get(t, srv.URL, "/api/auth/me", anaCookie)
  465. res.Body.Close()
  466. if res.StatusCode != 401 {
  467. t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
  468. }
  469. // Rol inválido → 400
  470. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), 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["message"] != "role debe ser admin|user" {
  475. t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
  476. }
  477. // No puedes cambiar tu propio rol
  478. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
  479. req.Header.Set("Cookie", "session="+adminCookie)
  480. res, _ = http.DefaultClient.Do(req)
  481. body = readJSON(t, res)
  482. if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
  483. t.Fatalf("self role: got %d %v", res.StatusCode, body)
  484. }
  485. // Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
  486. req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
  487. req.Header.Set("Cookie", "session="+adminCookie)
  488. res, _ = http.DefaultClient.Do(req)
  489. res.Body.Close()
  490. if res.StatusCode != 204 {
  491. t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
  492. }
  493. // No se puede borrar a sí mismo
  494. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
  495. req.Header.Set("Cookie", "session="+adminCookie)
  496. res, _ = http.DefaultClient.Do(req)
  497. body = readJSON(t, res)
  498. if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
  499. t.Fatalf("self delete: got %d %v", res.StatusCode, body)
  500. }
  501. // Borrado 204 y luego 404
  502. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  503. req.Header.Set("Cookie", "session="+adminCookie)
  504. res, _ = http.DefaultClient.Do(req)
  505. res.Body.Close()
  506. if res.StatusCode != 204 {
  507. t.Fatalf("delete: got %d want 204", res.StatusCode)
  508. }
  509. req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
  510. req.Header.Set("Cookie", "session="+adminCookie)
  511. res, _ = http.DefaultClient.Do(req)
  512. body = readJSON(t, res)
  513. if res.StatusCode != 404 || body["error"] != "not_found" {
  514. t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
  515. }
  516. }
  517. // ---------------------------------------------------------------------------
  518. // Quirks de cache-control y datos
  519. // ---------------------------------------------------------------------------
  520. func TestCacheControl(t *testing.T) {
  521. srv := makeTestServer(t)
  522. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  523. cases := []struct {
  524. path string
  525. noStore bool
  526. }{
  527. {"/api/health", false},
  528. {"/api/auth/me", false},
  529. {"/api/overview", true},
  530. {"/api/users", true},
  531. {"/api/devices", true},
  532. {"/api/alerts", true},
  533. {"/api/topology", true},
  534. }
  535. for _, c := range cases {
  536. res := get(t, srv.URL, c.path, cookie)
  537. res.Body.Close()
  538. got := res.Header.Get("Cache-Control")
  539. if c.noStore && got != "no-store" {
  540. t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
  541. }
  542. if !c.noStore && got == "no-store" {
  543. t.Errorf("%s: NO debe llevar no-store", c.path)
  544. }
  545. }
  546. }
  547. func TestDevicesPaginacionYFiltros(t *testing.T) {
  548. srv := makeTestServer(t)
  549. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  550. // Paginación: 65 dispositivos del dataset canónico reconciliado
  551. // (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
  552. res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
  553. body := readJSON(t, res)
  554. if body["total"].(float64) != 65 || len(body["items"].([]any)) != 10 {
  555. t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
  556. }
  557. if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
  558. t.Fatalf("page/pageSize: %v", body)
  559. }
  560. res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
  561. body = readJSON(t, res)
  562. if len(body["items"].([]any)) != 5 {
  563. t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
  564. }
  565. // Sin solape con la página anterior
  566. res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
  567. prev := readJSON(t, res)
  568. prevIDs := map[string]bool{}
  569. for _, it := range prev["items"].([]any) {
  570. prevIDs[it.(map[string]any)["id"].(string)] = true
  571. }
  572. for _, it := range body["items"].([]any) {
  573. if prevIDs[it.(map[string]any)["id"].(string)] {
  574. t.Fatalf("solape entre page6 y page7: %v", it)
  575. }
  576. }
  577. // Defaults: pageSize=50
  578. res = get(t, srv.URL, "/api/devices", cookie)
  579. body = readJSON(t, res)
  580. if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
  581. t.Fatalf("defaults: %v", body)
  582. }
  583. // typeCounts: inventario agrupado por tipo (conteos suman el total)
  584. if tc, ok := body["typeCounts"].(map[string]any); !ok {
  585. t.Fatalf("typeCounts ausente: %v", body)
  586. } else {
  587. sum := 0
  588. for _, v := range tc {
  589. sum += int(v.(float64))
  590. }
  591. if sum != 65 {
  592. t.Fatalf("typeCounts suma %d, esperaba 65: %v", sum, tc)
  593. }
  594. }
  595. // Filtros
  596. res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
  597. body = readJSON(t, res)
  598. if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
  599. t.Fatalf("routerId=living: %v", body["total"])
  600. }
  601. res = get(t, srv.URL, "/api/devices?band=cable", cookie)
  602. body = readJSON(t, res)
  603. for _, it := range body["items"].([]any) {
  604. if it.(map[string]any)["band"] != "cable" {
  605. t.Fatalf("band=cable con item de otra banda: %v", it)
  606. }
  607. }
  608. if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 3 netgear + pve + 10 CTs + 6 tras switch)
  609. t.Fatalf("band=cable: %v", body["total"])
  610. }
  611. res = get(t, srv.URL, "/api/devices?status=offline", cookie)
  612. body = readJSON(t, res)
  613. if body["total"].(float64) != 6 {
  614. t.Fatalf("status=offline: %v", body["total"])
  615. }
  616. res = get(t, srv.URL, "/api/devices?type=movil", cookie)
  617. body = readJSON(t, res)
  618. for _, it := range body["items"].([]any) {
  619. m := it.(map[string]any)
  620. if m["type"] != "movil" && m["group"] != "moviles" {
  621. t.Fatalf("type=movil con item que no casa: %v", m)
  622. }
  623. }
  624. if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
  625. t.Fatalf("type=movil: %v", body["total"])
  626. }
  627. res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
  628. body = readJSON(t, res)
  629. if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
  630. t.Fatalf("q=PIXEL: %v", body["total"])
  631. }
  632. // Inválidos → 400
  633. for _, u := range []string{
  634. "/api/devices?band=wifi6",
  635. "/api/devices?status=weird",
  636. "/api/devices?page=abc",
  637. "/api/devices?pageSize=1001",
  638. } {
  639. res = get(t, srv.URL, u, cookie)
  640. body = readJSON(t, res)
  641. if res.StatusCode != 400 || body["error"] != "invalid_query" {
  642. t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
  643. }
  644. }
  645. // Shape Device (12 claves del contrato)
  646. res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
  647. body = readJSON(t, res)
  648. dev := body["items"].([]any)[0].(map[string]any)
  649. for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
  650. if _, ok := dev[k]; !ok {
  651. t.Fatalf("device sin clave %q: %v", k, dev)
  652. }
  653. }
  654. }
  655. func TestAlertsEndpoint(t *testing.T) {
  656. srv := makeTestServer(t)
  657. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  658. res := get(t, srv.URL, "/api/alerts", cookie)
  659. body := readJSON(t, res)
  660. if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
  661. t.Fatalf("alerts default: %v", body)
  662. }
  663. res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
  664. body = readJSON(t, res)
  665. if body["total"].(float64) != 2 {
  666. t.Fatalf("severity=warn: %v", body["total"])
  667. }
  668. res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
  669. body = readJSON(t, res)
  670. if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
  671. t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
  672. }
  673. }
  674. func TestRoutersYDetalle(t *testing.T) {
  675. srv := makeTestServer(t)
  676. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  677. res := get(t, srv.URL, "/api/routers", cookie)
  678. body := readJSON(t, res)
  679. if len(body["routers"].([]any)) != 4 {
  680. t.Fatalf("routers: %v", body)
  681. }
  682. res = get(t, srv.URL, "/api/routers/flint2", cookie)
  683. if res.StatusCode != 200 {
  684. t.Fatalf("detalle flint2: %d", res.StatusCode)
  685. }
  686. detail := readJSON(t, res)
  687. for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
  688. if _, ok := detail[k]; !ok {
  689. t.Fatalf("detalle sin clave %q", k)
  690. }
  691. }
  692. res = get(t, srv.URL, "/api/routers/no-existe", cookie)
  693. body = readJSON(t, res)
  694. if res.StatusCode != 404 || body["error"] != "not_found" {
  695. t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
  696. }
  697. // DAWN: el stub devuelve null → 503
  698. res = get(t, srv.URL, "/api/usteer", cookie)
  699. body = readJSON(t, res)
  700. if res.StatusCode != 503 || body["error"] != "unavailable" {
  701. t.Fatalf("dawn: %d %v", res.StatusCode, body)
  702. }
  703. // AdGuard clients: stub null → 404 not_configured
  704. res = get(t, srv.URL, "/api/adguard/clients", cookie)
  705. body = readJSON(t, res)
  706. if res.StatusCode != 404 || body["error"] != "not_configured" {
  707. t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
  708. }
  709. }
  710. func TestAPI404JSON(t *testing.T) {
  711. srv := makeTestServer(t)
  712. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  713. for _, path := range []string{"/api/no-existe", "/api/routers/"} {
  714. res := get(t, srv.URL, path, cookie)
  715. body := readJSON(t, res)
  716. if res.StatusCode != 404 || body["error"] != "not_found" {
  717. t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
  718. }
  719. }
  720. // Cualquier método → 404 JSON (no 405)
  721. req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
  722. req.Header.Set("Cookie", "session="+cookie)
  723. res, _ := http.DefaultClient.Do(req)
  724. body := readJSON(t, res)
  725. if res.StatusCode != 404 || body["error"] != "not_found" {
  726. t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
  727. }
  728. }
  729. func TestHealthEndpoints(t *testing.T) {
  730. srv := makeTestServer(t)
  731. res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
  732. body := readJSON(t, res)
  733. if res.StatusCode != 200 {
  734. t.Fatalf("/api/health: %d", res.StatusCode)
  735. }
  736. if body["ok"] != true || body["version"] != httpapi.Version || body["mode"] != "demo" || body["db"] != "ok" {
  737. t.Fatalf("/api/health: %v", body)
  738. }
  739. if _, ok := body["uptimeSec"].(float64); !ok {
  740. t.Fatalf("uptimeSec: %v", body)
  741. }
  742. // Métricas operativas (Fase 8): los 3 campos presentes; en demo los
  743. // agentes/sse son 0 y devicesTotal viene del overview del poller demo.
  744. for _, k := range []string{"agentsConnected", "sseConnections", "devicesTotal"} {
  745. if _, ok := body[k].(float64); !ok {
  746. t.Fatalf("%s ausente o no numérico: %v", k, body)
  747. }
  748. }
  749. res = get(t, srv.URL, "/health", "")
  750. body = readJSON(t, res)
  751. if body["status"] != "ok" || body["db"] != "connected" {
  752. t.Fatalf("/health: %v", body)
  753. }
  754. mem := body["memory"].(map[string]any)
  755. if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
  756. t.Fatalf("memory: %v", mem)
  757. }
  758. }
  759. func TestSecurityHeaders(t *testing.T) {
  760. srv := makeTestServer(t)
  761. res := get(t, srv.URL, "/api/health", "")
  762. res.Body.Close()
  763. want := map[string]string{
  764. "X-Content-Type-Options": "nosniff",
  765. "X-Frame-Options": "DENY",
  766. "Referrer-Policy": "strict-origin-when-cross-origin",
  767. "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
  768. "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
  769. "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'",
  770. }
  771. for k, v := range want {
  772. if got := res.Header.Get(k); got != v {
  773. t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
  774. }
  775. }
  776. }
  777. func TestSPAFallback(t *testing.T) {
  778. srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
  779. // Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
  780. // con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
  781. _ = srv
  782. }
  783. // writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
  784. // añade json.Encoder (consistencia con D5 WriteError).
  785. func TestWriteJSONSinSaltoFinal(t *testing.T) {
  786. srv := makeTestServer(t)
  787. res := get(t, srv.URL, "/api/health", "")
  788. defer res.Body.Close()
  789. body, err := io.ReadAll(res.Body)
  790. if err != nil {
  791. t.Fatal(err)
  792. }
  793. if len(body) == 0 {
  794. t.Fatal("body vacío")
  795. }
  796. if body[len(body)-1] == '\n' {
  797. t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
  798. }
  799. if !json.Valid(body) {
  800. t.Fatalf("body no es JSON válido: %q", body)
  801. }
  802. }
  803. func TestWebhookDLQEndpoint(t *testing.T) {
  804. srv := makeTestServer(t)
  805. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  806. if status != 204 {
  807. t.Fatalf("login: %d", status)
  808. }
  809. // Sin sesión → 401 (el middleware global exige auth)
  810. req, _ := http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  811. res, _ := http.DefaultClient.Do(req)
  812. res.Body.Close()
  813. if res.StatusCode != 401 {
  814. t.Fatalf("sin sesión debería dar 401, dio %d", res.StatusCode)
  815. }
  816. // Con sesión admin → 200 con items vacío (tabla nueva)
  817. req, _ = http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
  818. req.Header.Set("Cookie", "session="+cookie)
  819. res, _ = http.DefaultClient.Do(req)
  820. body := readJSON(t, res)
  821. if res.StatusCode != 200 {
  822. t.Fatalf("con sesión debería dar 200, dio %d", res.StatusCode)
  823. }
  824. if body["total"].(float64) != 0 {
  825. t.Fatalf("DLQ vacío esperado, total=%v", body["total"])
  826. }
  827. }
  828. func TestPortSeriesEndpoint(t *testing.T) {
  829. srv := makeTestServer(t)
  830. defer srv.Close()
  831. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  832. if srv.db.PortSeries == nil {
  833. t.Fatal("PortSeries store not initialized")
  834. }
  835. now := time.Now()
  836. err := srv.db.PortSeries.RecordSample(portseries.PortSample{
  837. RouterID: "rt1", PortID: "lan1", TS: now,
  838. RxBytes: 1000, TxBytes: 2000, RxBps: 500, TxBps: 1000, SpeedMbps: 1000,
  839. })
  840. if err != nil {
  841. t.Fatalf("record sample: %v", err)
  842. }
  843. from := now.Add(-time.Hour).Unix()
  844. to := now.Add(time.Hour).Unix()
  845. req, _ := http.NewRequest("GET",
  846. fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
  847. req.Header.Set("Cookie", "session="+cookie)
  848. res, err := http.DefaultClient.Do(req)
  849. if err != nil {
  850. t.Fatalf("request: %v", err)
  851. }
  852. defer res.Body.Close()
  853. if res.StatusCode != 200 {
  854. t.Fatalf("expected 200, got %d", res.StatusCode)
  855. }
  856. body := readJSON(t, res)
  857. if body["resolution"] != "raw" {
  858. t.Errorf("expected raw resolution, got %v", body["resolution"])
  859. }
  860. points, ok := body["points"].([]any)
  861. if !ok {
  862. t.Fatalf("points is not an array: %T", body["points"])
  863. }
  864. if len(points) == 0 {
  865. t.Error("expected at least 1 point, got 0")
  866. }
  867. }
  868. func TestPortSeriesAutoResolution(t *testing.T) {
  869. srv := makeTestServer(t)
  870. defer srv.Close()
  871. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  872. now := time.Now()
  873. from := now.Add(-60 * 24 * time.Hour).Unix()
  874. to := now.Unix()
  875. req, _ := http.NewRequest("GET",
  876. fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
  877. req.Header.Set("Cookie", "session="+cookie)
  878. res, err := http.DefaultClient.Do(req)
  879. if err != nil {
  880. t.Fatalf("request: %v", err)
  881. }
  882. defer res.Body.Close()
  883. if res.StatusCode != 200 {
  884. t.Fatalf("expected 200, got %d", res.StatusCode)
  885. }
  886. body := readJSON(t, res)
  887. if body["resolution"] != "daily" {
  888. t.Errorf("expected daily resolution for 60d range, got %v", body["resolution"])
  889. }
  890. }
  891. func TestPortSeriesInvalidResolution(t *testing.T) {
  892. srv := makeTestServer(t)
  893. defer srv.Close()
  894. _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  895. req, _ := http.NewRequest("GET", srv.URL+"/api/routers/rt1/ports/lan1/series?resolution=invalid", nil)
  896. req.Header.Set("Cookie", "session="+cookie)
  897. res, err := http.DefaultClient.Do(req)
  898. if err != nil {
  899. t.Fatalf("request: %v", err)
  900. }
  901. defer res.Body.Close()
  902. if res.StatusCode != 400 {
  903. t.Errorf("expected 400 for invalid resolution, got %d", res.StatusCode)
  904. }
  905. }