agent_api_test.go 14 KB

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