agent_api_test.go 15 KB

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