agent_api_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // agent_api_test.go — Fase 3 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/hmac"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "net/http/httptest"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/adapters"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/config"
  21. "github.com/gnacho/netpulse/server-go/internal/db"
  22. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  23. "github.com/gnacho/netpulse/server-go/internal/sse"
  24. )
  25. type agentTestServer struct {
  26. *httptest.Server
  27. db *db.DB
  28. agents *adapters.AgentRegistry
  29. cookie string
  30. }
  31. // makeAgentTestServer: app real con registry de agentes + sesión admin.
  32. func makeAgentTestServer(t *testing.T) *agentTestServer {
  33. t.Helper()
  34. // Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
  35. // limit); el comportamiento por defecto en producción es NO confiar en
  36. // XFF (auditoría #1), así que aquí se activa explícitamente.
  37. auth.SetTrustProxy(true)
  38. t.Cleanup(func() { auth.SetTrustProxy(false) })
  39. dataDir := t.TempDir()
  40. cfg, err := config.Load(map[string]string{
  41. "AUTH_USER": "admin", "AUTH_PASS": "test1234",
  42. "DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
  43. }, dataDir)
  44. if err != nil {
  45. t.Fatalf("config: %v", err)
  46. }
  47. d, err := db.Open(dataDir)
  48. if err != nil {
  49. t.Fatalf("db: %v", err)
  50. }
  51. secret, err := auth.EnsureSessionSecret(d, cfg)
  52. if err != nil {
  53. t.Fatalf("secret: %v", err)
  54. }
  55. if err := auth.EnsureUsers(d, cfg); err != nil {
  56. t.Fatalf("users: %v", err)
  57. }
  58. reg := adapters.NewAgentRegistry(90 * time.Second)
  59. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  60. handler := httpapi.NewHandler(httpapi.Deps{
  61. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  62. Agents: reg, Started: time.Now(),
  63. })
  64. srv := httptest.NewServer(handler)
  65. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
  66. if status != 204 {
  67. t.Fatalf("login: %d", status)
  68. }
  69. ts := &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}
  70. t.Cleanup(func() {
  71. srv.Close()
  72. d.Close()
  73. })
  74. return ts
  75. }
  76. // createAgentToken crea el token de un slug vía API (con sesión) y devuelve
  77. // (status, token, install).
  78. func createAgentToken(t *testing.T, ts *agentTestServer, slug string) (int, string, string) {
  79. t.Helper()
  80. req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(fmt.Sprintf(`{"slug":%q}`, slug)))
  81. req.Header.Set("Content-Type", "application/json")
  82. req.Header.Set("Cookie", "session="+ts.cookie)
  83. res, err := http.DefaultClient.Do(req)
  84. if err != nil {
  85. t.Fatalf("POST /api/agents: %v", err)
  86. }
  87. defer res.Body.Close()
  88. var body struct {
  89. Slug string `json:"slug"`
  90. Token string `json:"token"`
  91. Install string `json:"install"`
  92. }
  93. data, _ := io.ReadAll(res.Body)
  94. _ = json.Unmarshal(data, &body)
  95. return res.StatusCode, body.Token, body.Install
  96. }
  97. // ingest hace un push de agente; ip fija la X-Forwarded-For (rate limit).
  98. func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.Response {
  99. t.Helper()
  100. req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
  101. req.Header.Set("Content-Type", "application/json")
  102. req.Header.Set("X-Forwarded-For", ip)
  103. if token != "" {
  104. req.Header.Set("Authorization", "Bearer "+token)
  105. mac := hmac.New(sha256.New, []byte(token))
  106. mac.Write([]byte(payload))
  107. req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
  108. }
  109. res, err := http.DefaultClient.Do(req)
  110. if err != nil {
  111. t.Fatalf("ingest: %v", err)
  112. }
  113. return res
  114. }
  115. // validPayload construye un payload de agente válido con ts ACTUAL (el
  116. // anti-replay de la auditoría #2 rechaza ts antiguos, así que el payload de
  117. // test no puede llevar un ts fijo del pasado).
  118. func validPayload(ts ...int64) string {
  119. t := time.Now().Unix()
  120. if len(ts) > 0 {
  121. t = ts[0]
  122. }
  123. return fmt.Sprintf(`{"router":"patio","ts":%d,"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":{}}}}`, t)
  124. }
  125. func TestIngestTokenValidoEInvalido(t *testing.T) {
  126. ts := makeAgentTestServer(t)
  127. status, token, install := createAgentToken(t, ts, "patio")
  128. if status != 201 || token == "" {
  129. t.Fatalf("create: %d token=%q", status, token)
  130. }
  131. if !strings.Contains(install, "install-agent.sh") || !strings.Contains(install, token) || !strings.Contains(install, "--slug patio") {
  132. t.Fatalf("one-liner: %q", install)
  133. }
  134. // kv guarda sha256, NUNCA el token en claro
  135. var stored string
  136. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.token.patio'").Scan(&stored); err != nil {
  137. t.Fatalf("kv: %v", err)
  138. }
  139. sum := sha256.Sum256([]byte(token))
  140. if stored != hex.EncodeToString(sum[:]) || strings.Contains(stored, token) {
  141. t.Fatalf("kv debería guardar sha256: %q", stored)
  142. }
  143. // Ingesta sin sesión (exenta del middleware) + token válido → 202
  144. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  145. res.Body.Close()
  146. if res.StatusCode != 202 {
  147. t.Fatalf("ingest válido: %d", res.StatusCode)
  148. }
  149. if _, version, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
  150. t.Fatalf("registry no actualizado: %v %q", ok, version)
  151. }
  152. // Token inválido → 401; sin token → 401; token de otro slug → 401
  153. for _, tok := range []string{"", "deadbeef", token + "00"} {
  154. res := ingest(t, ts, tok, "10.0.0.2", validPayload())
  155. res.Body.Close()
  156. if res.StatusCode != 401 {
  157. t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
  158. }
  159. }
  160. }
  161. func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
  162. ts := makeAgentTestServer(t)
  163. _, token, _ := createAgentToken(t, ts, "patio")
  164. // 413: body > 2 MB
  165. big := strings.Repeat("x", (2<<20)+100)
  166. res := ingest(t, ts, token, "10.0.1.1", big)
  167. res.Body.Close()
  168. if res.StatusCode != 413 {
  169. t.Fatalf("body grande: %d", res.StatusCode)
  170. }
  171. // 400: JSON roto, slug inválido, ts ausente — y NADA se rompe después
  172. for _, p := range []string{
  173. `{no json`,
  174. `{"router":"PATIO!","ts":1,"data":{}}`,
  175. `{"router":"patio","data":{}}`,
  176. `{"router":"patio","ts":-3,"data":{}}`,
  177. } {
  178. res := ingest(t, ts, token, "10.0.1.2", p)
  179. res.Body.Close()
  180. if res.StatusCode != 400 {
  181. t.Fatalf("payload %q debería dar 400, dio %d", p, res.StatusCode)
  182. }
  183. }
  184. // El pipeline sigue sano tras los 400
  185. res = ingest(t, ts, token, "10.0.1.2", validPayload())
  186. res.Body.Close()
  187. if res.StatusCode != 202 {
  188. t.Fatalf("ingest tras 400s: %d", res.StatusCode)
  189. }
  190. }
  191. func TestIngestRateLimit(t *testing.T) {
  192. ts := makeAgentTestServer(t)
  193. _, token, _ := createAgentToken(t, ts, "patio")
  194. // 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
  195. for i := 0; i < 30; i++ {
  196. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  197. res.Body.Close()
  198. if res.StatusCode != 202 {
  199. t.Fatalf("push %d: %d", i, res.StatusCode)
  200. }
  201. }
  202. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  203. defer res.Body.Close()
  204. if res.StatusCode != 429 {
  205. t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
  206. }
  207. var body map[string]any
  208. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  209. t.Fatalf("429 json: %v", err)
  210. }
  211. if body["error"] != "rate_limited" || res.Header.Get("Retry-After") == "" {
  212. t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
  213. }
  214. // Otra IP no está limitada
  215. res2 := ingest(t, ts, token, "10.0.2.2", validPayload())
  216. res2.Body.Close()
  217. if res2.StatusCode != 202 {
  218. t.Fatalf("otra IP: %d", res2.StatusCode)
  219. }
  220. }
  221. func TestAgentsListYRevocacion(t *testing.T) {
  222. ts := makeAgentTestServer(t)
  223. // GET /api/agents exige sesión
  224. res := get(t, ts.URL, "/api/agents", "")
  225. res.Body.Close()
  226. if res.StatusCode != 401 {
  227. t.Fatalf("GET /api/agents sin sesión: %d", res.StatusCode)
  228. }
  229. _, token, _ := createAgentToken(t, ts, "patio")
  230. if _, token2, _ := createAgentToken(t, ts, "living"); token2 == "" {
  231. t.Fatal("segundo token")
  232. }
  233. // Lista: 2 slugs, lastSeen null (nunca empujaron), SIN token ni hash
  234. res = get(t, ts.URL, "/api/agents", ts.cookie)
  235. body := readJSON(t, res)
  236. agents, _ := body["agents"].([]any)
  237. if len(agents) != 2 {
  238. t.Fatalf("agents: %v", body)
  239. }
  240. raw, _ := json.Marshal(body)
  241. if strings.Contains(string(raw), token) || strings.Contains(string(raw), "token") {
  242. t.Fatalf("GET /api/agents no debería exponer tokens: %s", raw)
  243. }
  244. // Tras un push: lastSeen (unix s) + versión + fresh
  245. res2 := ingest(t, ts, token, "10.0.3.1", validPayload())
  246. res2.Body.Close()
  247. res = get(t, ts.URL, "/api/agents", ts.cookie)
  248. body = readJSON(t, res)
  249. agents, _ = body["agents"].([]any)
  250. var patio map[string]any
  251. for _, a := range agents {
  252. m, _ := a.(map[string]any)
  253. if m["slug"] == "patio" {
  254. patio = m
  255. }
  256. }
  257. if patio == nil || patio["lastSeen"] == nil || patio["version"] != "0.1.0" || patio["fresh"] != true {
  258. t.Fatalf("patio tras push: %v", patio)
  259. }
  260. // Revocar → 204; el push siguiente recibe 401; GET ya no lo lista
  261. req, _ := http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  262. req.Header.Set("Cookie", "session="+ts.cookie)
  263. resDel, err := http.DefaultClient.Do(req)
  264. if err != nil {
  265. t.Fatalf("DELETE: %v", err)
  266. }
  267. resDel.Body.Close()
  268. if resDel.StatusCode != 204 {
  269. t.Fatalf("DELETE: %d", resDel.StatusCode)
  270. }
  271. res3 := ingest(t, ts, token, "10.0.3.2", validPayload())
  272. res3.Body.Close()
  273. if res3.StatusCode != 401 {
  274. t.Fatalf("push tras revocar: %d", res3.StatusCode)
  275. }
  276. res = get(t, ts.URL, "/api/agents", ts.cookie)
  277. body = readJSON(t, res)
  278. agents, _ = body["agents"].([]any)
  279. if len(agents) != 1 {
  280. t.Fatalf("tras revocar: %v", body)
  281. }
  282. // Revocar de nuevo → 404
  283. req, _ = http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  284. req.Header.Set("Cookie", "session="+ts.cookie)
  285. resDel, _ = http.DefaultClient.Do(req)
  286. resDel.Body.Close()
  287. if resDel.StatusCode != 404 {
  288. t.Fatalf("DELETE 2ª vez: %d", resDel.StatusCode)
  289. }
  290. }
  291. func TestAgentsCreateValidaSlug(t *testing.T) {
  292. ts := makeAgentTestServer(t)
  293. for _, slug := range []string{"", "PATIO", "con espacios", "-x", strings.Repeat("a", 65)} {
  294. status, _, _ := createAgentToken(t, ts, slug)
  295. if status != 400 {
  296. t.Fatalf("slug %q debería dar 400, dio %d", slug, status)
  297. }
  298. }
  299. }
  300. // TestAgentStatePersistenciaYRestauracion (Fase 8.2, R8): tras una ingesta,
  301. // el último push queda en kv (agent.state.<slug>); un registry nuevo que
  302. // restaura desde kv recupera lastSeen/versión/payload (simula reinicio).
  303. func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
  304. ts := makeAgentTestServer(t)
  305. _, token, _ := createAgentToken(t, ts, "patio")
  306. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  307. res.Body.Close()
  308. if res.StatusCode != 202 {
  309. t.Fatalf("ingest: %d", res.StatusCode)
  310. }
  311. // El estado debe estar en kv tras la ingesta
  312. var raw string
  313. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.state.patio'").Scan(&raw); err != nil {
  314. t.Fatalf("kv agent.state: %v", err)
  315. }
  316. // Simular reinicio: registry nuevo + restaurador desde la misma BD
  317. reg2 := adapters.NewAgentRegistry(90 * time.Second)
  318. httpapi.NewStateRestorer(ts.db)(reg2)
  319. _, version, ok := reg2.Info("patio")
  320. if !ok {
  321. t.Fatal("estado no restaurado tras reinicio")
  322. }
  323. if version != "0.1.0" {
  324. t.Fatalf("versión restaurada: %q", version)
  325. }
  326. payload, fresh := reg2.Fresh("patio")
  327. if !fresh || payload == nil || payload.Router != "patio" {
  328. t.Fatalf("payload no fresco tras restauración: fresh=%v", fresh)
  329. }
  330. }
  331. // TestIngestAntiReplay (auditoría #2): un payload con ts fuera de la ventana
  332. // de frescura (pasado o futuro) se rechaza con 401 stale_payload, aunque el
  333. // token y el HMAC sean correctos — evita reinyectar pushes viejos capturados.
  334. func TestIngestAntiReplay(t *testing.T) {
  335. ts := makeAgentTestServer(t)
  336. _, token, _ := createAgentToken(t, ts, "patio")
  337. stale := validPayload(time.Now().Add(-10 * time.Minute).Unix())
  338. res := ingest(t, ts, token, "10.0.4.1", stale)
  339. res.Body.Close()
  340. if res.StatusCode != 401 {
  341. t.Fatalf("ts pasado debería dar 401, dio %d", res.StatusCode)
  342. }
  343. future := validPayload(time.Now().Add(10 * time.Minute).Unix())
  344. res = ingest(t, ts, token, "10.0.4.2", future)
  345. res.Body.Close()
  346. if res.StatusCode != 401 {
  347. t.Fatalf("ts futuro debería dar 401, dio %d", res.StatusCode)
  348. }
  349. // ts justo dentro de la ventana → 202
  350. res = ingest(t, ts, token, "10.0.4.3", validPayload(time.Now().Add(-2*time.Minute).Unix()))
  351. res.Body.Close()
  352. if res.StatusCode != 202 {
  353. t.Fatalf("ts en ventana debería dar 202, dio %d", res.StatusCode)
  354. }
  355. }