agent_api_test.go 11 KB

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