httpapi_test.go 32 KB

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