agent_api_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // agent_api_test.go — Fase 6 piloto (SPEC-AGENTE-PILOTO §1): ingesta con
  2. // token válido/inválido, body grande, rate limit, payload inválido (no rompe
  3. // el pipeline), y gestión de tokens (crear/listar/revocar; el token solo se
  4. // muestra una vez y NUNCA sale por GET).
  5. package httpapi_test
  6. import (
  7. "crypto/sha256"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "net/http"
  13. "net/http/httptest"
  14. "strings"
  15. "testing"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. "github.com/gnacho/netpulse/server-go/internal/auth"
  19. "github.com/gnacho/netpulse/server-go/internal/config"
  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/sse"
  23. )
  24. type agentTestServer struct {
  25. *httptest.Server
  26. db *db.DB
  27. agents *adapters.AgentRegistry
  28. cookie string
  29. }
  30. // makeAgentTestServer: app real con registry de agentes + sesión admin.
  31. func makeAgentTestServer(t *testing.T) *agentTestServer {
  32. t.Helper()
  33. dataDir := t.TempDir()
  34. cfg, err := config.Load(map[string]string{
  35. "AUTH_USER": "admin", "AUTH_PASS": "test1234",
  36. "DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
  37. }, dataDir)
  38. if err != nil {
  39. t.Fatalf("config: %v", err)
  40. }
  41. d, err := db.Open(dataDir)
  42. if err != nil {
  43. t.Fatalf("db: %v", err)
  44. }
  45. secret, err := auth.EnsureSessionSecret(d, cfg)
  46. if err != nil {
  47. t.Fatalf("secret: %v", err)
  48. }
  49. if err := auth.EnsureUsers(d, cfg); err != nil {
  50. t.Fatalf("users: %v", err)
  51. }
  52. reg := adapters.NewAgentRegistry(90 * time.Second)
  53. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  54. handler := httpapi.NewHandler(httpapi.Deps{
  55. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  56. Agents: reg, Started: time.Now(),
  57. })
  58. srv := httptest.NewServer(handler)
  59. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  60. if status != 204 {
  61. t.Fatalf("login: %d", status)
  62. }
  63. ts := &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}
  64. t.Cleanup(func() {
  65. srv.Close()
  66. d.Close()
  67. })
  68. return ts
  69. }
  70. // createAgentToken crea el token de un slug vía API (con sesión) y devuelve
  71. // (status, token, install).
  72. func createAgentToken(t *testing.T, ts *agentTestServer, slug string) (int, string, string) {
  73. t.Helper()
  74. req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(fmt.Sprintf(`{"slug":%q}`, slug)))
  75. req.Header.Set("Content-Type", "application/json")
  76. req.Header.Set("Cookie", "session="+ts.cookie)
  77. res, err := http.DefaultClient.Do(req)
  78. if err != nil {
  79. t.Fatalf("POST /api/agents: %v", err)
  80. }
  81. defer res.Body.Close()
  82. var body struct {
  83. Slug string `json:"slug"`
  84. Token string `json:"token"`
  85. Install string `json:"install"`
  86. }
  87. data, _ := io.ReadAll(res.Body)
  88. _ = json.Unmarshal(data, &body)
  89. return res.StatusCode, body.Token, body.Install
  90. }
  91. // ingest hace un push de agente; ip fija la X-Forwarded-For (rate limit).
  92. func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.Response {
  93. t.Helper()
  94. req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
  95. req.Header.Set("Content-Type", "application/json")
  96. req.Header.Set("X-Forwarded-For", ip)
  97. if token != "" {
  98. req.Header.Set("Authorization", "Bearer "+token)
  99. }
  100. res, err := http.DefaultClient.Do(req)
  101. if err != nil {
  102. t.Fatalf("ingest: %v", err)
  103. }
  104. return res
  105. }
  106. const validPayload = `{"router":"patio","ts":1754140000,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`
  107. func TestIngestTokenValidoEInvalido(t *testing.T) {
  108. ts := makeAgentTestServer(t)
  109. status, token, install := createAgentToken(t, ts, "patio")
  110. if status != 201 || token == "" {
  111. t.Fatalf("create: %d token=%q", status, token)
  112. }
  113. if !strings.Contains(install, "install-agent.sh") || !strings.Contains(install, token) || !strings.Contains(install, "--slug patio") {
  114. t.Fatalf("one-liner: %q", install)
  115. }
  116. // kv guarda sha256, NUNCA el token en claro
  117. var stored string
  118. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.token.patio'").Scan(&stored); err != nil {
  119. t.Fatalf("kv: %v", err)
  120. }
  121. sum := sha256.Sum256([]byte(token))
  122. if stored != hex.EncodeToString(sum[:]) || strings.Contains(stored, token) {
  123. t.Fatalf("kv debería guardar sha256: %q", stored)
  124. }
  125. // Ingesta sin sesión (exenta del middleware) + token válido → 202
  126. res := ingest(t, ts, token, "10.0.0.1", validPayload)
  127. res.Body.Close()
  128. if res.StatusCode != 202 {
  129. t.Fatalf("ingest válido: %d", res.StatusCode)
  130. }
  131. if _, version, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
  132. t.Fatalf("registry no actualizado: %v %q", ok, version)
  133. }
  134. // Token inválido → 401; sin token → 401; token de otro slug → 401
  135. for _, tok := range []string{"", "deadbeef", token + "00"} {
  136. res := ingest(t, ts, tok, "10.0.0.2", validPayload)
  137. res.Body.Close()
  138. if res.StatusCode != 401 {
  139. t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
  140. }
  141. }
  142. }
  143. func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
  144. ts := makeAgentTestServer(t)
  145. _, token, _ := createAgentToken(t, ts, "patio")
  146. // 413: body > 2 MB
  147. big := strings.Repeat("x", (2<<20)+100)
  148. res := ingest(t, ts, token, "10.0.1.1", big)
  149. res.Body.Close()
  150. if res.StatusCode != 413 {
  151. t.Fatalf("body grande: %d", res.StatusCode)
  152. }
  153. // 400: JSON roto, slug inválido, ts ausente — y NADA se rompe después
  154. for _, p := range []string{
  155. `{no json`,
  156. `{"router":"PATIO!","ts":1,"data":{}}`,
  157. `{"router":"patio","data":{}}`,
  158. `{"router":"patio","ts":-3,"data":{}}`,
  159. } {
  160. res := ingest(t, ts, token, "10.0.1.2", p)
  161. res.Body.Close()
  162. if res.StatusCode != 400 {
  163. t.Fatalf("payload %q debería dar 400, dio %d", p, res.StatusCode)
  164. }
  165. }
  166. // El pipeline sigue sano tras los 400
  167. res = ingest(t, ts, token, "10.0.1.2", validPayload)
  168. res.Body.Close()
  169. if res.StatusCode != 202 {
  170. t.Fatalf("ingest tras 400s: %d", res.StatusCode)
  171. }
  172. }
  173. func TestIngestRateLimit(t *testing.T) {
  174. ts := makeAgentTestServer(t)
  175. _, token, _ := createAgentToken(t, ts, "patio")
  176. // 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
  177. for i := 0; i < 30; i++ {
  178. res := ingest(t, ts, token, "10.0.2.1", validPayload)
  179. res.Body.Close()
  180. if res.StatusCode != 202 {
  181. t.Fatalf("push %d: %d", i, res.StatusCode)
  182. }
  183. }
  184. res := ingest(t, ts, token, "10.0.2.1", validPayload)
  185. defer res.Body.Close()
  186. if res.StatusCode != 429 {
  187. t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
  188. }
  189. var body map[string]any
  190. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  191. t.Fatalf("429 json: %v", err)
  192. }
  193. if body["error"] != "rate_limited" || res.Header.Get("Retry-After") == "" {
  194. t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
  195. }
  196. // Otra IP no está limitada
  197. res2 := ingest(t, ts, token, "10.0.2.2", validPayload)
  198. res2.Body.Close()
  199. if res2.StatusCode != 202 {
  200. t.Fatalf("otra IP: %d", res2.StatusCode)
  201. }
  202. }
  203. func TestAgentsListYRevocacion(t *testing.T) {
  204. ts := makeAgentTestServer(t)
  205. // GET /api/agents exige sesión
  206. res := get(t, ts.URL, "/api/agents", "")
  207. res.Body.Close()
  208. if res.StatusCode != 401 {
  209. t.Fatalf("GET /api/agents sin sesión: %d", res.StatusCode)
  210. }
  211. _, token, _ := createAgentToken(t, ts, "patio")
  212. if _, token2, _ := createAgentToken(t, ts, "living"); token2 == "" {
  213. t.Fatal("segundo token")
  214. }
  215. // Lista: 2 slugs, lastSeen null (nunca empujaron), SIN token ni hash
  216. res = get(t, ts.URL, "/api/agents", ts.cookie)
  217. body := readJSON(t, res)
  218. agents, _ := body["agents"].([]any)
  219. if len(agents) != 2 {
  220. t.Fatalf("agents: %v", body)
  221. }
  222. raw, _ := json.Marshal(body)
  223. if strings.Contains(string(raw), token) || strings.Contains(string(raw), "token") {
  224. t.Fatalf("GET /api/agents no debería exponer tokens: %s", raw)
  225. }
  226. // Tras un push: lastSeen (unix s) + versión + fresh
  227. res2 := ingest(t, ts, token, "10.0.3.1", validPayload)
  228. res2.Body.Close()
  229. res = get(t, ts.URL, "/api/agents", ts.cookie)
  230. body = readJSON(t, res)
  231. agents, _ = body["agents"].([]any)
  232. var patio map[string]any
  233. for _, a := range agents {
  234. m, _ := a.(map[string]any)
  235. if m["slug"] == "patio" {
  236. patio = m
  237. }
  238. }
  239. if patio == nil || patio["lastSeen"] == nil || patio["version"] != "0.1.0" || patio["fresh"] != true {
  240. t.Fatalf("patio tras push: %v", patio)
  241. }
  242. // Revocar → 204; el push siguiente recibe 401; GET ya no lo lista
  243. req, _ := http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  244. req.Header.Set("Cookie", "session="+ts.cookie)
  245. resDel, err := http.DefaultClient.Do(req)
  246. if err != nil {
  247. t.Fatalf("DELETE: %v", err)
  248. }
  249. resDel.Body.Close()
  250. if resDel.StatusCode != 204 {
  251. t.Fatalf("DELETE: %d", resDel.StatusCode)
  252. }
  253. res3 := ingest(t, ts, token, "10.0.3.2", validPayload)
  254. res3.Body.Close()
  255. if res3.StatusCode != 401 {
  256. t.Fatalf("push tras revocar: %d", res3.StatusCode)
  257. }
  258. res = get(t, ts.URL, "/api/agents", ts.cookie)
  259. body = readJSON(t, res)
  260. agents, _ = body["agents"].([]any)
  261. if len(agents) != 1 {
  262. t.Fatalf("tras revocar: %v", body)
  263. }
  264. // Revocar de nuevo → 404
  265. req, _ = http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  266. req.Header.Set("Cookie", "session="+ts.cookie)
  267. resDel, _ = http.DefaultClient.Do(req)
  268. resDel.Body.Close()
  269. if resDel.StatusCode != 404 {
  270. t.Fatalf("DELETE 2ª vez: %d", resDel.StatusCode)
  271. }
  272. }
  273. func TestAgentsCreateValidaSlug(t *testing.T) {
  274. ts := makeAgentTestServer(t)
  275. for _, slug := range []string{"", "PATIO", "con espacios", "-x", strings.Repeat("a", 65)} {
  276. status, _, _ := createAgentToken(t, ts, slug)
  277. if status != 400 {
  278. t.Fatalf("slug %q debería dar 400, dio %d", slug, status)
  279. }
  280. }
  281. }