agent_hot_token_test.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package httpapi_test
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. "strings"
  7. "testing"
  8. "time"
  9. "github.com/gnacho/netpulse/agent/probe"
  10. )
  11. // postAgentCreateHot publica POST /api/agents con body dado y devuelve la
  12. // respuesta decodificada.
  13. func postAgentCreateHot(t *testing.T, base, cookie, body string) (int, map[string]any) {
  14. t.Helper()
  15. req, _ := http.NewRequest("POST", base+"/api/agents", strings.NewReader(body))
  16. req.Header.Set("Content-Type", "application/json")
  17. req.Header.Set("Cookie", "session="+cookie)
  18. res, err := http.DefaultClient.Do(req)
  19. if err != nil {
  20. t.Fatalf("POST /api/agents: %v", err)
  21. }
  22. defer res.Body.Close()
  23. raw, _ := io.ReadAll(res.Body)
  24. var m map[string]any
  25. _ = json.Unmarshal(raw, &m)
  26. return res.StatusCode, m
  27. }
  28. // TestRotateTokenHot: con hot:true y un router OpenWrt accesible por SSH,
  29. // el token se aplica en caliente (método hot + 1 comando SSH de push).
  30. func TestRotateTokenHot(t *testing.T) {
  31. ssh := &fakeSSH{}
  32. ts := makeRearmTestServer(t, ssh, 1500*time.Millisecond)
  33. status, body := postAgentCreateHot(t, ts.URL, ts.cookie, `{"slug":"patio","hot":true}`)
  34. if status != 201 {
  35. t.Fatalf("create: %d", status)
  36. }
  37. if body["method"] != "hot" {
  38. t.Fatalf("quiero method=hot, tuve %v", body["method"])
  39. }
  40. if _, ok := body["manualReason"]; ok {
  41. t.Fatalf("hot no debe traer manualReason, tuve %v", body["manualReason"])
  42. }
  43. if body["token"] == "" {
  44. t.Fatal("sin token")
  45. }
  46. if ssh.count() != 1 {
  47. t.Fatalf("quiero 1 comando SSH de push, tuve %d", ssh.count())
  48. }
  49. if !strings.Contains(ssh.cmds[0], "NETPULSE_TOKEN=") || !strings.Contains(ssh.cmds[0], `"$INIT" restart`) {
  50. t.Fatalf("el comando SSH no reescribe el token/restart: %q", ssh.cmds[0])
  51. }
  52. }
  53. // TestRotateTokenManual: sin router en la tabla (o hot=false) no hay push
  54. // SSH: método manual y el token se conserva en kv con el one-liner.
  55. func TestRotateTokenManual(t *testing.T) {
  56. ssh := &fakeSSH{}
  57. ts := makeRearmTestServer(t, ssh, 1500*time.Millisecond)
  58. // Slug sin router asociado → manual, sin SSH.
  59. status, body := postAgentCreateHot(t, ts.URL, ts.cookie, `{"slug":"solitario","hot":true}`)
  60. if status != 201 {
  61. t.Fatalf("create: %d", status)
  62. }
  63. if body["method"] != "manual" {
  64. t.Fatalf("quiero method=manual, tuve %v", body["method"])
  65. }
  66. if body["manualReason"] != "no_router" {
  67. t.Fatalf("sin router quiero manualReason=no_router, tuve %v", body["manualReason"])
  68. }
  69. if ssh.count() != 0 {
  70. t.Fatalf("no debe ejecutarse SSH con router desconocido, tuve %d", ssh.count())
  71. }
  72. if body["install"] == "" {
  73. t.Fatal("manual debe incluir el one-liner de instalación")
  74. }
  75. // hot=false → manual aunque el router exista (comportamiento previo).
  76. status, body = postAgentCreateHot(t, ts.URL, ts.cookie, `{"slug":"patio"}`)
  77. if status != 201 {
  78. t.Fatalf("create: %d", status)
  79. }
  80. if body["method"] != "manual" {
  81. t.Fatalf("sin hot=true quiero method=manual, tuve %v", body["method"])
  82. }
  83. if ssh.count() != 0 {
  84. t.Fatalf("sin hot=true no debe ejecutarse SSH, tuve %d", ssh.count())
  85. }
  86. }
  87. // TestRotateTokenHotSSHFail: si el push SSH falla, no se rompe el flujo y el
  88. // método cae a manual (el token ya rotado se entrega vía Install).
  89. func TestRotateTokenHotSSHFail(t *testing.T) {
  90. ssh := &fakeSSH{fail: true}
  91. ts := makeRearmTestServer(t, ssh, 1500*time.Millisecond)
  92. status, body := postAgentCreateHot(t, ts.URL, ts.cookie, `{"slug":"patio","hot":true}`)
  93. if status != 201 {
  94. t.Fatalf("create: %d", status)
  95. }
  96. if body["method"] != "manual" {
  97. t.Fatalf("SSH caído quiero method=manual, tuve %v", body["method"])
  98. }
  99. if body["manualReason"] != "ssh_failed" {
  100. t.Fatalf("SSH caído quiero manualReason=ssh_failed, tuve %v", body["manualReason"])
  101. }
  102. if body["install"] == "" {
  103. t.Fatal("debe incluir el one-liner para recuperar manualmente")
  104. }
  105. }
  106. // TestRotateTokenNetgrip (#719): con un agente kind=netgrip, hot:true no
  107. // toca SSH y devuelve manual con motivo netgrip.
  108. func TestRotateTokenNetgrip(t *testing.T) {
  109. ssh := &fakeSSH{}
  110. ts := makeRearmTestServer(t, ssh, 1500*time.Millisecond)
  111. ts.agents.Ingest(&probe.Payload{Router: "patio", Ts: time.Now().Unix(), Version: "0.23.0", Kind: "netgrip"})
  112. status, body := postAgentCreateHot(t, ts.URL, ts.cookie, `{"slug":"patio","hot":true}`)
  113. if status != 201 {
  114. t.Fatalf("create: %d", status)
  115. }
  116. if body["method"] != "manual" {
  117. t.Fatalf("netgrip quiero method=manual, tuve %v", body["method"])
  118. }
  119. if body["manualReason"] != "netgrip" {
  120. t.Fatalf("netgrip quiero manualReason=netgrip, tuve %v", body["manualReason"])
  121. }
  122. if ssh.count() != 0 {
  123. t.Fatalf("netgrip no debe ejecutarse SSH, tuve %d", ssh.count())
  124. }
  125. }