| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143 |
- // httpapi_test.go — tests de contrato de endpoints (port de tests/auth.test.js
- // y tests/users.test.js de Node + quirks de cache-control y SPA).
- package httpapi_test
- import (
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/url"
- "strings"
- "testing"
- "time"
- "github.com/gnacho/netpulse/server-go/internal/adapters"
- "github.com/gnacho/netpulse/server-go/internal/apitoken"
- "github.com/gnacho/netpulse/server-go/internal/auth"
- "github.com/gnacho/netpulse/server-go/internal/channelplan"
- "github.com/gnacho/netpulse/server-go/internal/clientbw"
- "github.com/gnacho/netpulse/server-go/internal/config"
- "github.com/gnacho/netpulse/server-go/internal/configbackup"
- "github.com/gnacho/netpulse/server-go/internal/db"
- "github.com/gnacho/netpulse/server-go/internal/httpapi"
- "github.com/gnacho/netpulse/server-go/internal/orchestr"
- "github.com/gnacho/netpulse/server-go/internal/portseries"
- "github.com/gnacho/netpulse/server-go/internal/sse"
- )
- type testServer struct {
- *httptest.Server
- db *db.DB
- secret string
- }
- // makeTestServer replica tests/helpers.js: app real con adapter demo stub y
- // DB temporal. DEMO_MODE=0 → la API permite mutaciones (tests de CRUD de
- // users/routers/agents). Para probar el modo demo read-only (issue #118) usar
- // makeDemoTestServer. El adapter sigue siendo NewDemo: /api/health y /api/auth/me
- // reportan mode:"demo" como esperan algunos tests de contrato.
- func makeTestServer(t *testing.T) *testServer {
- t.Helper()
- return makeTestServerWithMode(t, false)
- }
- // makeDemoTestServer: igual que makeTestServer pero con DEMO_MODE=1 (issue
- // #118) — las mutaciones fuera de la allowlist se rechazan con 409.
- func makeDemoTestServer(t *testing.T) *testServer {
- t.Helper()
- return makeTestServerWithMode(t, true)
- }
- func makeTestServerWithMode(t *testing.T, demoMode bool) *testServer {
- t.Helper()
- // Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
- // limit); por defecto en producción NO se confía en XFF (auditoría #1).
- auth.SetTrustProxy(true)
- t.Cleanup(func() { auth.SetTrustProxy(false) })
- dataDir := t.TempDir()
- demo := "0"
- if demoMode {
- demo = "1"
- }
- cfg, err := config.Load(map[string]string{
- "AUTH_USER": "admin", "AUTH_PASS": "test123456",
- "DEMO_MODE": demo, "DATA_DIR": dataDir, "NODE_ENV": "test",
- }, dataDir)
- if err != nil {
- t.Fatalf("config: %v", err)
- }
- d, err := db.Open(dataDir)
- if err != nil {
- t.Fatalf("db: %v", err)
- }
- secret, err := auth.EnsureSessionSecret(d, cfg)
- if err != nil {
- t.Fatalf("secret: %v", err)
- }
- if err := auth.EnsureUsers(d, cfg); err != nil {
- t.Fatalf("users: %v", err)
- }
- if err := apitoken.EnsureSchema(d); err != nil {
- t.Fatalf("api_tokens schema: %v", err)
- }
- tokenStore := apitoken.NewStore(d, secret)
- configBackup, err := configbackup.NewStore(d)
- if err != nil {
- t.Fatalf("config backup store: %v", err)
- }
- orchestrMgr := orchestr.New(d)
- adapter := adapters.NewDemo()
- agents := adapters.NewAgentRegistry(0)
- hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
- chPlan := channelplan.NewStore(d.DB)
- handler := httpapi.NewHandler(httpapi.Deps{
- Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
- Started: time.Now(),
- TokenStore: tokenStore,
- ConfigBackup: configBackup,
- Orchestr: orchestrMgr,
- Agents: agents,
- ChannelPlan: chPlan,
- })
- srv := httptest.NewServer(handler)
- ts := &testServer{Server: srv, db: d, secret: secret}
- t.Cleanup(func() {
- srv.Close()
- d.Close()
- })
- return ts
- }
- // loginCookie hace login y devuelve status + valor de la cookie (id.hmac) +
- // header Set-Cookie completo.
- func loginCookie(t *testing.T, base, username, password string, headers ...string) (int, string, string) {
- t.Helper()
- req, _ := http.NewRequest("POST", base+"/api/auth/login",
- strings.NewReader(fmt.Sprintf(`{"username":%q,"password":%q}`, username, password)))
- req.Header.Set("Content-Type", "application/json")
- for i := 0; i+1 < len(headers); i += 2 {
- req.Header.Set(headers[i], headers[i+1])
- }
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("login: %v", err)
- }
- defer res.Body.Close()
- io.Copy(io.Discard, res.Body)
- setCookie := res.Header.Get("Set-Cookie")
- cookie := ""
- if m := strings.Index(setCookie, "session="); m >= 0 {
- rest := setCookie[m+len("session="):]
- if end := strings.Index(rest, ";"); end >= 0 {
- cookie = rest[:end]
- }
- }
- return res.StatusCode, cookie, setCookie
- }
- func get(t *testing.T, base, path, cookie string) *http.Response {
- t.Helper()
- req, _ := http.NewRequest("GET", base+path, nil)
- if cookie != "" {
- req.Header.Set("Cookie", "session="+cookie)
- }
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("GET %s: %v", path, err)
- }
- return res
- }
- func readJSON(t *testing.T, res *http.Response) map[string]any {
- t.Helper()
- defer res.Body.Close()
- var body map[string]any
- if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
- t.Fatalf("json: %v", err)
- }
- return body
- }
- // ---------------------------------------------------------------------------
- // Port de tests/auth.test.js
- // ---------------------------------------------------------------------------
- func TestLoginIncorrecto401(t *testing.T) {
- srv := makeTestServer(t)
- status, cookie, _ := loginCookie(t, srv.URL, "admin", "wrong-pass")
- if status != 401 {
- t.Fatalf("status: got %d want 401", status)
- }
- if cookie != "" {
- t.Fatal("login incorrecto no debe devolver cookie")
- }
- }
- func TestLoginCorrectoYMe(t *testing.T) {
- srv := makeTestServer(t)
- status, cookie, setCookie := loginCookie(t, srv.URL, "admin", "test123456")
- if status != 204 {
- t.Fatalf("status: got %d want 204", status)
- }
- if cookie == "" {
- t.Fatal("debe devolver cookie de sesión")
- }
- if !strings.Contains(setCookie, "HttpOnly") || !strings.Contains(setCookie, "SameSite=Lax") {
- t.Fatalf("Set-Cookie sin HttpOnly/SameSite=Lax: %q", setCookie)
- }
- res := get(t, srv.URL, "/api/auth/me", cookie)
- if res.StatusCode != 200 {
- t.Fatalf("me: got %d want 200", res.StatusCode)
- }
- body := readJSON(t, res)
- want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "displayName": "", "mode": "demo"}
- for k, v := range want {
- if body[k] != v {
- t.Fatalf("me[%s]: got %v want %v (body=%v)", k, body[k], v, body)
- }
- }
- if len(body) != len(want) {
- t.Fatalf("me con claves extra: %v", body)
- }
- }
- func TestOverviewProtegido(t *testing.T) {
- srv := makeTestServer(t)
- res := get(t, srv.URL, "/api/overview", "")
- if res.StatusCode != 401 {
- t.Fatalf("sin cookie: got %d want 401", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["error"] != "unauthorized" {
- t.Fatalf("error: %v", body)
- }
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- res2 := get(t, srv.URL, "/api/overview", cookie)
- if res2.StatusCode != 200 {
- t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
- }
- ov := readJSON(t, res2)
- // Shape del overview (claves del contrato; vm SIEMPRE, SPEC-65 D65-4)
- for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "vm", "ts"} {
- if _, ok := ov[k]; !ok {
- t.Fatalf("overview sin clave %q", k)
- }
- }
- if ov["vm"] != float64(1) {
- t.Fatalf("vm debe ser 1 (ViewModelVersion): %v", ov["vm"])
- }
- if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
- t.Fatalf("routers: %v", ov["routers"])
- }
- // ts en SEGUNDOS (no ms)
- if ts, ok := ov["ts"].(float64); !ok || ts > 1e11 {
- t.Fatalf("ts debe ser epoch en segundos: %v", ov["ts"])
- }
- }
- func TestLogoutRevocaSesion(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- req, _ := http.NewRequest("POST", srv.URL+"/api/auth/logout", nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- }
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("logout: got %d want 204", res.StatusCode)
- }
- if sc := res.Header.Get("Set-Cookie"); sc != "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" {
- t.Fatalf("Set-Cookie de borrado literal: %q", sc)
- }
- res2 := get(t, srv.URL, "/api/overview", cookie)
- res2.Body.Close()
- if res2.StatusCode != 401 {
- t.Fatalf("sesión revocada: got %d want 401", res2.StatusCode)
- }
- }
- func TestMyPasswordChange(t *testing.T) {
- srv := makeTestServer(t)
- _, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- // Alta de ana (rol user)
- req, _ := http.NewRequest("POST", srv.URL+"/api/users",
- strings.NewReader(`{"username":"ana","password":"secreto12345","role":"user"}`))
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ := http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 201 {
- t.Fatalf("create ana: got %d want 201", res.StatusCode)
- }
- // Dos sesiones de ana: la que pide el cambio y otra que debe morir.
- _, c1, _ := loginCookie(t, srv.URL, "ana", "secreto12345")
- _, c2, _ := loginCookie(t, srv.URL, "ana", "secreto12345")
- put := func(cookie, jsonBody string) *http.Response {
- t.Helper()
- r, _ := http.NewRequest("PUT", srv.URL+"/api/auth/password", strings.NewReader(jsonBody))
- r.Header.Set("Cookie", "session="+cookie)
- rq, err := http.DefaultClient.Do(r)
- if err != nil {
- t.Fatal(err)
- }
- return rq
- }
- // Current incorrecto → 401 y la sesión no se toca
- res = put(c1, `{"current":"no-es-la-clave","password":"nueva-clave-99"}`)
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("current malo: got %d want 401", res.StatusCode)
- }
- res = get(t, srv.URL, "/api/auth/me", c1)
- res.Body.Close()
- if res.StatusCode != 200 {
- t.Fatalf("sesión tras 401: got %d want 200", res.StatusCode)
- }
- // Password corto → 400
- res = put(c1, `{"current":"secreto12345","password":"corta"}`)
- res.Body.Close()
- if res.StatusCode != 400 {
- t.Fatalf("password corto: got %d want 400", res.StatusCode)
- }
- // Cambio correcto → 204
- res = put(c1, `{"current":"secreto12345","password":"nueva-clave-99"}`)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("cambio: got %d want 204", res.StatusCode)
- }
- // La sesión que pidió el cambio sigue viva; la otra muere.
- res = get(t, srv.URL, "/api/auth/me", c1)
- res.Body.Close()
- if res.StatusCode != 200 {
- t.Fatalf("sesión actual: got %d want 200", res.StatusCode)
- }
- res = get(t, srv.URL, "/api/auth/me", c2)
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("sesión hermana: got %d want 401", res.StatusCode)
- }
- // Login con la clave nueva OK; con la vieja, 401.
- if st, _, _ := loginCookie(t, srv.URL, "ana", "nueva-clave-99"); st != 204 {
- t.Fatalf("login clave nueva: got %d want 204", st)
- }
- if st, _, _ := loginCookie(t, srv.URL, "ana", "secreto12345"); st != 401 {
- t.Fatalf("login clave vieja: got %d want 401", st)
- }
- }
- func TestMutationsCrossOriginRejected(t *testing.T) {
- // Issue #213: una mutación con Origin cruzado → 403 cross_origin antes
- // incluso de la autenticación; el login legítimo con Origin propio pasa.
- srv := makeTestServer(t)
- req, _ := http.NewRequest("POST", srv.URL+"/api/refresh", strings.NewReader(`{}`))
- req.Header.Set("Origin", "https://evil.example")
- res, _ := http.DefaultClient.Do(req)
- if res.StatusCode != http.StatusForbidden {
- t.Fatalf("POST cross-origin: got %d want 403", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["error"] != "cross_origin" {
- t.Fatalf("error: %v", body)
- }
- u, _ := url.Parse(srv.URL)
- req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login",
- strings.NewReader(`{"username":"admin","password":"test123456"}`))
- req2.Header.Set("Origin", u.Scheme+"://"+u.Host)
- res2, _ := http.DefaultClient.Do(req2)
- if res2.StatusCode != http.StatusNoContent {
- t.Fatalf("login con Origin propio: got %d want 204", res2.StatusCode)
- }
- }
- func TestRateLimitQuintoFallo(t *testing.T) {
- srv := makeTestServer(t)
- hdr := []string{"X-Forwarded-For", "10.9.9.9"}
- for i := 1; i <= 5; i++ {
- status, _, _ := loginCookie(t, srv.URL, "admin", "nope", hdr...)
- if status != 401 {
- t.Fatalf("fallo %d: got %d want 401", i, status)
- }
- }
- // 6º intento: bloqueado (5 min)
- req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`{"username":"admin","password":"nope"}`))
- req.Header.Set("X-Forwarded-For", "10.9.9.9")
- res, _ := http.DefaultClient.Do(req)
- if res.StatusCode != 429 {
- t.Fatalf("6º intento: got %d want 429", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["error"] != "rate_limited" {
- t.Fatalf("error: %v", body)
- }
- retry, ok := body["retryAfterSec"].(float64)
- if !ok || retry <= 0 || retry > 300 {
- t.Fatalf("retryAfterSec: %v", body)
- }
- // Incluso con la password correcta sigue bloqueado.
- status, _, _ := loginCookie(t, srv.URL, "admin", "test123456", hdr...)
- if status != 429 {
- t.Fatalf("bloqueado con password correcta: got %d want 429", status)
- }
- // Persistencia en SQLite.
- var attempts int
- var lockedUntil int64
- if err := srv.db.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
- Scan(&attempts, &lockedUntil); err != nil {
- t.Fatal(err)
- }
- if attempts < 5 || lockedUntil <= db.NowMS() {
- t.Fatalf("login_attempts: attempts=%d locked_until=%d", attempts, lockedUntil)
- }
- }
- func TestOversizedBodyReturns413(t *testing.T) {
- // Issue #215: un body mayor que maxBodyBytes responde 413 payload_too_large
- // (no 400 invalid_body) con el writer real en MaxBytesReader.
- srv := makeTestServer(t)
- big := `{"username":"admin","password":"` + strings.Repeat("a", (64<<10)+100) + `"}`
- req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(big))
- res, _ := http.DefaultClient.Do(req)
- if res.StatusCode != http.StatusRequestEntityTooLarge {
- t.Fatalf("body > maxBodyBytes: got %d want 413", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["error"] != "payload_too_large" {
- t.Fatalf("error: %v", body)
- }
- // Un JSON mal formado pero pequeño sigue siendo 400 invalid_body.
- req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`not-json`))
- res2, _ := http.DefaultClient.Do(req2)
- if res2.StatusCode != http.StatusBadRequest || readJSON(t, res2)["error"] != "invalid_body" {
- t.Fatalf("JSON inválido: got %d want 400 invalid_body", res2.StatusCode)
- }
- }
- func TestLoginInvalidBody400(t *testing.T) {
- srv := makeTestServer(t)
- for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
- req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(payload))
- res, _ := http.DefaultClient.Do(req)
- body := readJSON(t, res)
- if res.StatusCode != 400 || body["error"] != "invalid_body" {
- t.Fatalf("payload %s: got %d %v", payload, res.StatusCode, body)
- }
- if body["message"] != `Se esperaba { "username": string, "password": string }` {
- t.Fatalf("message: %v", body["message"])
- }
- }
- }
- // ---------------------------------------------------------------------------
- // Port de tests/users.test.js
- // ---------------------------------------------------------------------------
- func TestUsersCRUD(t *testing.T) {
- srv := makeTestServer(t)
- // 401 sin sesión
- res := get(t, srv.URL, "/api/users", "")
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
- }
- // Admin: lista con 1 usuario
- _, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- res = get(t, srv.URL, "/api/users", adminCookie)
- body := readJSON(t, res)
- users := body["users"].([]any)
- if len(users) != 1 || users[0].(map[string]any)["username"] != "admin" {
- t.Fatalf("users: %v", users)
- }
- // Alta 201
- req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto12345"}`))
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- if res.StatusCode != 201 {
- b, _ := io.ReadAll(res.Body)
- res.Body.Close()
- t.Fatalf("alta: got %d want 201 (%s)", res.StatusCode, b)
- }
- res.Body.Close()
- // Duplicado 409
- req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra123456"}`))
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 409 || body["error"] != "duplicate_user" {
- t.Fatalf("duplicado: got %d %v", res.StatusCode, body)
- }
- // Username inválido 400
- req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"mal usuario","password":"xxxxxxxxxx"}`))
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["error"] != "invalid_input" {
- t.Fatalf("username inválido: got %d %v", res.StatusCode, body)
- }
- if body["message"] != "usuario debe ser alfanumérico (.-_ permitidos)" {
- t.Fatalf("message: %v", body["message"])
- }
- // El usuario creado puede loguear
- status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto12345")
- if status != 204 {
- t.Fatalf("login ana: got %d", status)
- }
- // ID de ana
- res = get(t, srv.URL, "/api/users", adminCookie)
- body = readJSON(t, res)
- var anaID, adminID float64
- for _, u := range body["users"].([]any) {
- m := u.(map[string]any)
- if m["username"] == "ana" {
- anaID = m["id"].(float64)
- }
- if m["username"] == "admin" {
- adminID = m["id"].(float64)
- }
- }
- // Cambio de password → 204 e invalida la sesión de ana
- req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/password", srv.URL, anaID), strings.NewReader(`{"password":"nueva-clave-9"}`))
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("set password: got %d want 204", res.StatusCode)
- }
- res = get(t, srv.URL, "/api/auth/me", anaCookie)
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("sesión vieja de ana: got %d want 401", res.StatusCode)
- }
- status, anaCookie, _ = loginCookie(t, srv.URL, "ana", "nueva-clave-9")
- if status != 204 {
- t.Fatalf("re-login ana: got %d", status)
- }
- // No-admin → 403 en /api/users
- res = get(t, srv.URL, "/api/users", anaCookie)
- body = readJSON(t, res)
- if res.StatusCode != 403 || body["error"] != "forbidden" {
- t.Fatalf("no-admin: got %d %v", res.StatusCode, body)
- }
- // Pero SÍ puede cambiar su idioma (fuera del gate admin)
- req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"es"}`))
- req.Header.Set("Cookie", "session="+anaCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("me/language no-admin: got %d want 204", res.StatusCode)
- }
- res = get(t, srv.URL, "/api/auth/me", anaCookie)
- body = readJSON(t, res)
- if body["language"] != "es" {
- t.Fatalf("language: %v", body)
- }
- // zh y ru son válidos (catálogos en la UI)
- for _, lang := range []string{"zh", "ru"} {
- req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"`+lang+`"}`))
- req.Header.Set("Cookie", "session="+anaCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("me/language %s: got %d want 204", lang, res.StatusCode)
- }
- res = get(t, srv.URL, "/api/auth/me", anaCookie)
- body = readJSON(t, res)
- if body["language"] != lang {
- t.Fatalf("language %s: %v", lang, body)
- }
- }
- // Idioma inválido → 400 literal
- req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
- req.Header.Set("Cookie", "session="+anaCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["message"] != "language must be auto|es|en|zh|ru" {
- t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
- }
- // Rol via QUERY STRING (quirk): ana pasa a admin
- req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("set role: got %d want 204", res.StatusCode)
- }
- // La sesión de ana quedó invalidada por el cambio de rol
- res = get(t, srv.URL, "/api/auth/me", anaCookie)
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
- }
- // Rol inválido → 400
- req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["message"] != "role debe ser admin|user" {
- t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
- }
- // No puedes cambiar tu propio rol
- req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
- t.Fatalf("self role: got %d %v", res.StatusCode, body)
- }
- // Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
- req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
- }
- // No se puede borrar a sí mismo
- req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
- t.Fatalf("self delete: got %d %v", res.StatusCode, body)
- }
- // Borrado 204 y luego 404
- req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 204 {
- t.Fatalf("delete: got %d want 204", res.StatusCode)
- }
- req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
- req.Header.Set("Cookie", "session="+adminCookie)
- res, _ = http.DefaultClient.Do(req)
- body = readJSON(t, res)
- if res.StatusCode != 404 || body["error"] != "not_found" {
- t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
- }
- }
- // ---------------------------------------------------------------------------
- // Quirks de cache-control y datos
- // ---------------------------------------------------------------------------
- func TestCacheControl(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- cases := []struct {
- path string
- noStore bool
- }{
- {"/api/health", false},
- {"/api/auth/me", false},
- {"/api/overview", true},
- {"/api/users", true},
- {"/api/devices", true},
- {"/api/alerts", true},
- {"/api/topology", true},
- }
- for _, c := range cases {
- res := get(t, srv.URL, c.path, cookie)
- res.Body.Close()
- got := res.Header.Get("Cache-Control")
- if c.noStore && got != "no-store" {
- t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
- }
- if !c.noStore && got == "no-store" {
- t.Errorf("%s: NO debe llevar no-store", c.path)
- }
- }
- }
- func TestDevicesPaginacionYFiltros(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- // Paginación: 65 dispositivos del dataset canónico reconciliado
- // (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
- res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
- body := readJSON(t, res)
- if body["total"].(float64) != 65 || len(body["items"].([]any)) != 10 {
- t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
- }
- if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
- t.Fatalf("page/pageSize: %v", body)
- }
- res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
- body = readJSON(t, res)
- if len(body["items"].([]any)) != 5 {
- t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
- }
- // Sin solape con la página anterior
- res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
- prev := readJSON(t, res)
- prevIDs := map[string]bool{}
- for _, it := range prev["items"].([]any) {
- prevIDs[it.(map[string]any)["id"].(string)] = true
- }
- for _, it := range body["items"].([]any) {
- if prevIDs[it.(map[string]any)["id"].(string)] {
- t.Fatalf("solape entre page6 y page7: %v", it)
- }
- }
- // Defaults: pageSize=50
- res = get(t, srv.URL, "/api/devices", cookie)
- body = readJSON(t, res)
- if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
- t.Fatalf("defaults: %v", body)
- }
- // typeCounts: inventario agrupado por tipo (conteos suman el total)
- if tc, ok := body["typeCounts"].(map[string]any); !ok {
- t.Fatalf("typeCounts ausente: %v", body)
- } else {
- sum := 0
- for _, v := range tc {
- sum += int(v.(float64))
- }
- if sum != 65 {
- t.Fatalf("typeCounts suma %d, esperaba 65: %v", sum, tc)
- }
- }
- // Filtros
- res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
- body = readJSON(t, res)
- if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
- t.Fatalf("routerId=living: %v", body["total"])
- }
- res = get(t, srv.URL, "/api/devices?band=cable", cookie)
- body = readJSON(t, res)
- for _, it := range body["items"].([]any) {
- if it.(map[string]any)["band"] != "cable" {
- t.Fatalf("band=cable con item de otra banda: %v", it)
- }
- }
- if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 3 netgear + pve + 10 CTs + 6 tras switch)
- t.Fatalf("band=cable: %v", body["total"])
- }
- res = get(t, srv.URL, "/api/devices?status=offline", cookie)
- body = readJSON(t, res)
- if body["total"].(float64) != 6 {
- t.Fatalf("status=offline: %v", body["total"])
- }
- res = get(t, srv.URL, "/api/devices?type=movil", cookie)
- body = readJSON(t, res)
- for _, it := range body["items"].([]any) {
- m := it.(map[string]any)
- if m["type"] != "movil" && m["group"] != "moviles" {
- t.Fatalf("type=movil con item que no casa: %v", m)
- }
- }
- if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
- t.Fatalf("type=movil: %v", body["total"])
- }
- res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
- body = readJSON(t, res)
- if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
- t.Fatalf("q=PIXEL: %v", body["total"])
- }
- // Inválidos → 400
- for _, u := range []string{
- "/api/devices?band=wifi6",
- "/api/devices?status=weird",
- "/api/devices?page=abc",
- "/api/devices?pageSize=1001",
- } {
- res = get(t, srv.URL, u, cookie)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["error"] != "invalid_query" {
- t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
- }
- }
- // Shape Device (12 claves del contrato)
- res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
- body = readJSON(t, res)
- dev := body["items"].([]any)[0].(map[string]any)
- for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
- if _, ok := dev[k]; !ok {
- t.Fatalf("device sin clave %q: %v", k, dev)
- }
- }
- }
- func TestAlertsEndpoint(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- res := get(t, srv.URL, "/api/alerts", cookie)
- body := readJSON(t, res)
- if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
- t.Fatalf("alerts default: %v", body)
- }
- res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
- body = readJSON(t, res)
- if body["total"].(float64) != 2 {
- t.Fatalf("severity=warn: %v", body["total"])
- }
- res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
- body = readJSON(t, res)
- if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
- t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
- }
- }
- func TestRoutersYDetalle(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- res := get(t, srv.URL, "/api/routers", cookie)
- body := readJSON(t, res)
- if len(body["routers"].([]any)) != 4 {
- t.Fatalf("routers: %v", body)
- }
- res = get(t, srv.URL, "/api/routers/flint2", cookie)
- if res.StatusCode != 200 {
- t.Fatalf("detalle flint2: %d", res.StatusCode)
- }
- detail := readJSON(t, res)
- for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
- if _, ok := detail[k]; !ok {
- t.Fatalf("detalle sin clave %q", k)
- }
- }
- res = get(t, srv.URL, "/api/routers/no-existe", cookie)
- body = readJSON(t, res)
- if res.StatusCode != 404 || body["error"] != "not_found" {
- t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
- }
- // DAWN: el stub devuelve null → 503
- res = get(t, srv.URL, "/api/usteer", cookie)
- body = readJSON(t, res)
- if res.StatusCode != 503 || body["error"] != "unavailable" {
- t.Fatalf("dawn: %d %v", res.StatusCode, body)
- }
- // AdGuard clients: stub null → 404 not_configured
- res = get(t, srv.URL, "/api/adguard/clients", cookie)
- body = readJSON(t, res)
- if res.StatusCode != 404 || body["error"] != "not_configured" {
- t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
- }
- }
- func TestAPI404JSON(t *testing.T) {
- srv := makeTestServer(t)
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- for _, path := range []string{"/api/no-existe", "/api/routers/"} {
- res := get(t, srv.URL, path, cookie)
- body := readJSON(t, res)
- if res.StatusCode != 404 || body["error"] != "not_found" {
- t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
- }
- }
- // Cualquier método → 404 JSON (no 405)
- req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, _ := http.DefaultClient.Do(req)
- body := readJSON(t, res)
- if res.StatusCode != 404 || body["error"] != "not_found" {
- t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
- }
- }
- func TestHealthEndpoints(t *testing.T) {
- srv := makeTestServer(t)
- res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
- body := readJSON(t, res)
- if res.StatusCode != 200 {
- t.Fatalf("/api/health: %d", res.StatusCode)
- }
- if body["ok"] != true || body["version"] != httpapi.Version || body["mode"] != "demo" || body["db"] != "ok" {
- t.Fatalf("/api/health: %v", body)
- }
- if _, ok := body["uptimeSec"].(float64); !ok {
- t.Fatalf("uptimeSec: %v", body)
- }
- // Métricas operativas (Fase 8): los 3 campos presentes; en demo los
- // agentes/sse son 0 y devicesTotal viene del overview del poller demo.
- for _, k := range []string{"agentsConnected", "sseConnections", "agentSseConnections", "devicesTotal"} {
- if _, ok := body[k].(float64); !ok {
- t.Fatalf("%s ausente o no numérico: %v", k, body)
- }
- }
- res = get(t, srv.URL, "/health", "")
- body = readJSON(t, res)
- if body["status"] != "ok" || body["db"] != "connected" {
- t.Fatalf("/health: %v", body)
- }
- mem := body["memory"].(map[string]any)
- if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
- t.Fatalf("memory: %v", mem)
- }
- }
- func TestSecurityHeaders(t *testing.T) {
- srv := makeTestServer(t)
- res := get(t, srv.URL, "/api/health", "")
- res.Body.Close()
- want := map[string]string{
- "X-Content-Type-Options": "nosniff",
- "X-Frame-Options": "DENY",
- "Referrer-Policy": "strict-origin-when-cross-origin",
- "Permissions-Policy": "geolocation=(), microphone=(), camera=()",
- "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'",
- }
- for k, v := range want {
- if got := res.Header.Get(k); got != v {
- t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
- }
- }
- // FORK: HSTS only on secure responses; plain HTTP never carries it.
- if got := res.Header.Get("Strict-Transport-Security"); got != "" {
- t.Errorf("plain HTTP response carried HSTS %q", got)
- }
- }
- // FORK: behind a TLS-terminating proxy the server trusts (the test server
- // sets TRUST_PROXY), a request forwarded as https gets HSTS.
- func TestSecurityHeadersHSTSOnSecureRequests(t *testing.T) {
- srv := makeTestServer(t)
- req, err := http.NewRequest("GET", srv.URL+"/api/health", nil)
- if err != nil {
- t.Fatal(err)
- }
- req.Header.Set("X-Forwarded-Proto", "https")
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- }
- res.Body.Close()
- if got := res.Header.Get("Strict-Transport-Security"); got != "max-age=31536000" {
- t.Errorf("HSTS on a secure request = %q, want max-age=31536000", got)
- }
- }
- func TestSPAFallback(t *testing.T) {
- srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
- // Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
- // con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
- _ = srv
- }
- // writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
- // añade json.Encoder (consistencia con D5 WriteError).
- func TestWriteJSONSinSaltoFinal(t *testing.T) {
- srv := makeTestServer(t)
- res := get(t, srv.URL, "/api/health", "")
- defer res.Body.Close()
- body, err := io.ReadAll(res.Body)
- if err != nil {
- t.Fatal(err)
- }
- if len(body) == 0 {
- t.Fatal("body vacío")
- }
- if body[len(body)-1] == '\n' {
- t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
- }
- if !json.Valid(body) {
- t.Fatalf("body no es JSON válido: %q", body)
- }
- }
- func TestWebhookDLQEndpoint(t *testing.T) {
- srv := makeTestServer(t)
- status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- if status != 204 {
- t.Fatalf("login: %d", status)
- }
- // Sin sesión → 401 (el middleware global exige auth)
- req, _ := http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
- res, _ := http.DefaultClient.Do(req)
- res.Body.Close()
- if res.StatusCode != 401 {
- t.Fatalf("sin sesión debería dar 401, dio %d", res.StatusCode)
- }
- // Con sesión admin → 200 con items vacío (tabla nueva)
- req, _ = http.NewRequest("GET", srv.URL+"/api/webhook/dlq", nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, _ = http.DefaultClient.Do(req)
- body := readJSON(t, res)
- if res.StatusCode != 200 {
- t.Fatalf("con sesión debería dar 200, dio %d", res.StatusCode)
- }
- if body["total"].(float64) != 0 {
- t.Fatalf("DLQ vacío esperado, total=%v", body["total"])
- }
- }
- func TestPortSeriesEndpoint(t *testing.T) {
- srv := makeTestServer(t)
- defer srv.Close()
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- if srv.db.PortSeries == nil {
- t.Fatal("PortSeries store not initialized")
- }
- now := time.Now()
- err := srv.db.PortSeries.RecordSample(portseries.PortSample{
- RouterID: "rt1", PortID: "lan1", TS: now,
- RxBytes: 1000, TxBytes: 2000, RxBps: 500, TxBps: 1000, SpeedMbps: 1000,
- })
- if err != nil {
- t.Fatalf("record sample: %v", err)
- }
- from := now.Add(-time.Hour).Unix()
- to := now.Add(time.Hour).Unix()
- req, _ := http.NewRequest("GET",
- fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("request: %v", err)
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- t.Fatalf("expected 200, got %d", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["resolution"] != "raw" {
- t.Errorf("expected raw resolution, got %v", body["resolution"])
- }
- points, ok := body["points"].([]any)
- if !ok {
- t.Fatalf("points is not an array: %T", body["points"])
- }
- if len(points) == 0 {
- t.Error("expected at least 1 point, got 0")
- }
- }
- func TestPortSeriesAutoResolution(t *testing.T) {
- srv := makeTestServer(t)
- defer srv.Close()
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- now := time.Now()
- from := now.Add(-60 * 24 * time.Hour).Unix()
- to := now.Unix()
- req, _ := http.NewRequest("GET",
- fmt.Sprintf("%s/api/routers/rt1/ports/lan1/series?from=%d&to=%d", srv.URL, from, to), nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("request: %v", err)
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- t.Fatalf("expected 200, got %d", res.StatusCode)
- }
- body := readJSON(t, res)
- if body["resolution"] != "daily" {
- t.Errorf("expected daily resolution for 60d range, got %v", body["resolution"])
- }
- }
- func TestPortSeriesInvalidResolution(t *testing.T) {
- srv := makeTestServer(t)
- defer srv.Close()
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- req, _ := http.NewRequest("GET", srv.URL+"/api/routers/rt1/ports/lan1/series?resolution=invalid", nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("request: %v", err)
- }
- defer res.Body.Close()
- if res.StatusCode != 400 {
- t.Errorf("expected 400 for invalid resolution, got %d", res.StatusCode)
- }
- }
- func TestDeviceTrafficEndpoint(t *testing.T) {
- srv := makeTestServer(t)
- defer srv.Close()
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- if srv.db.ClientBW == nil {
- t.Fatal("ClientBW store not initialized")
- }
- now := time.Now()
- err := srv.db.ClientBW.Insert(clientbw.Sample{
- MAC: "aa:bb:cc:dd:ee:01", RouterID: "rt2", TS: now,
- RxBytes: 1000, TxBytes: 2000, RxBps: 8000, TxBps: 16000,
- })
- if err != nil {
- t.Fatalf("insert sample: %v", err)
- }
- from := now.Add(-time.Hour).Unix()
- to := now.Add(time.Hour).Unix()
- req, _ := http.NewRequest("GET",
- fmt.Sprintf("%s/api/devices/aa:bb:cc:dd:ee:01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("request: %v", err)
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- t.Fatalf("expected 200, got %d", res.StatusCode)
- }
- body := readJSON(t, res)
- points, ok := body["points"].([]any)
- if !ok || len(points) == 0 {
- t.Fatalf("expected points, got %T %v", body["points"], body["points"])
- }
- // La MAC del path se normaliza: formato con guiones también vale.
- req2, _ := http.NewRequest("GET",
- fmt.Sprintf("%s/api/devices/aa-bb-cc-dd-ee-01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
- req2.Header.Set("Cookie", "session="+cookie)
- res2, err := http.DefaultClient.Do(req2)
- if err != nil {
- t.Fatalf("request guiones: %v", err)
- }
- defer res2.Body.Close()
- if res2.StatusCode != 200 {
- t.Fatalf("guiones expected 200, got %d", res2.StatusCode)
- }
- }
- func TestDeviceTrafficInvalidMAC(t *testing.T) {
- srv := makeTestServer(t)
- defer srv.Close()
- _, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- req, _ := http.NewRequest("GET", srv.URL+"/api/devices/not-a-mac/traffic", nil)
- req.Header.Set("Cookie", "session="+cookie)
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("request: %v", err)
- }
- defer res.Body.Close()
- if res.StatusCode != 400 {
- t.Fatalf("expected 400 for invalid mac, got %d", res.StatusCode)
- }
- }
|