wireguard_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package orchestr
  2. import (
  3. "errors"
  4. "strings"
  5. "testing"
  6. "time"
  7. "github.com/gnacho/netpulse/agent/executor"
  8. )
  9. // Fixture: túnel wg0 activo con 2 peers (admin + uno gestionado).
  10. // Formato real de `wg show` + `uci show network`.
  11. const wireGuardOut = `===WG_BIN===
  12. yes
  13. ===WG===
  14. interface: wg0
  15. public key: SERVERPUB
  16. listening port: 51820
  17. peer: ADMINPUB
  18. allowed ips: 10.0.0.2/32
  19. peer: PEER2PUB
  20. allowed ips: 10.0.0.3/32
  21. ===NETWORK===
  22. network.lan=interface
  23. network.lan.device='br-lan'
  24. network.wg0=interface
  25. network.wg0.proto='wireguard'
  26. network.wg0.private_key='secret'
  27. network.wg0.addresses='10.0.0.1/24'
  28. network.wgpeer1=wireguard_wg0
  29. network.wgpeer1.public_key='ADMINPUB'
  30. network.wgpeer1.allowed_ips='10.0.0.2/32'
  31. network.wgpeer2=wireguard_wg0
  32. network.wgpeer2.public_key='PEER2PUB'
  33. network.wgpeer2.allowed_ips='10.0.0.3/32'
  34. network.wgpeer2.allowed_ips='10.0.0.9/32'
  35. ===END===`
  36. // fakeWGCommandRunner implementa CommandRunner para tests del probe/healthcheck.
  37. type fakeWGCommandRunner struct {
  38. out string
  39. err error
  40. cmd string
  41. host string
  42. }
  43. func (f *fakeWGCommandRunner) Run(host, cmd string, _ time.Duration) (string, error) {
  44. f.host, f.cmd = host, cmd
  45. return f.out, f.err
  46. }
  47. // TestParseWireGuardDetectaTunelYPeers: wg instalado, túnel activo y peers.
  48. func TestParseWireGuardDetectaTunelYPeers(t *testing.T) {
  49. sc := parseWireGuard(wireGuardOut)
  50. if !sc.WGInstalled {
  51. t.Error("WGInstalled: esperaba true")
  52. }
  53. if !sc.WGActive {
  54. t.Error("WGActive: esperaba true (wg show reporta wg0)")
  55. }
  56. if len(sc.ActiveIfaces) != 1 || sc.ActiveIfaces[0] != "wg0" {
  57. t.Errorf("ActiveIfaces: got %v want [wg0]", sc.ActiveIfaces)
  58. }
  59. if len(sc.WGIfaces) != 1 || sc.WGIfaces[0] != "wg0" {
  60. t.Errorf("WGIfaces: got %v want [wg0]", sc.WGIfaces)
  61. }
  62. if len(sc.Peers) != 2 {
  63. t.Fatalf("Peers: got %d want 2", len(sc.Peers))
  64. }
  65. if sc.Peers[0].Name != "wgpeer1" || sc.Peers[0].PublicKey != "ADMINPUB" {
  66. t.Errorf("peer[0]: got %+v", sc.Peers[0])
  67. }
  68. if sc.Peers[1].AllowedIPs != "10.0.0.3/32,10.0.0.9/32" {
  69. t.Errorf("peer[1] allowed_ips (lista): got %q", sc.Peers[1].AllowedIPs)
  70. }
  71. }
  72. // TestParseWireGuardSinTunel: wg instalado pero sin interfaces ni peers.
  73. func TestParseWireGuardSinTunel(t *testing.T) {
  74. out := `===WG_BIN===
  75. yes
  76. ===WG===
  77. ===NETWORK===
  78. network.lan=interface
  79. ===END===`
  80. sc := parseWireGuard(out)
  81. if !sc.WGInstalled {
  82. t.Error("WGInstalled: esperaba true")
  83. }
  84. if sc.WGActive {
  85. t.Error("WGActive: esperaba false sin interfaces")
  86. }
  87. if len(sc.WGIfaces) != 0 || len(sc.Peers) != 0 {
  88. t.Errorf("no debería haber ifaces/peers: %v %v", sc.WGIfaces, sc.Peers)
  89. }
  90. }
  91. // TestParseWireGuardWgNoInstalado: wg ausente → escenario tolerante (no error).
  92. func TestParseWireGuardWgNoInstalado(t *testing.T) {
  93. out := `===WG_BIN===
  94. no
  95. ===WG===
  96. ===NETWORK===
  97. network.lan=interface
  98. ===END===`
  99. sc := parseWireGuard(out)
  100. if sc.WGInstalled {
  101. t.Error("WGInstalled: esperaba false")
  102. }
  103. if sc.WGActive {
  104. t.Error("WGActive: esperaba false sin wg")
  105. }
  106. }
  107. // TestWireGuardOpsCreaInterfazYPeers: sin interfaz ni túnel, el plan crea
  108. // wg0 + un peer y termina con commit + reload (sin wg_check: no había túnel).
  109. func TestWireGuardOpsCreaInterfazYPeers(t *testing.T) {
  110. sc := parseWireGuard(`===WG_BIN===
  111. no
  112. ===WG===
  113. ===NETWORK===
  114. network.lan=interface
  115. ===END===`)
  116. ops := WireGuardOps(WireGuardDesired{
  117. Interface: "wg0",
  118. Peers: []WireGuardPeer{{Name: "laptop", PublicKey: "PEER1PUB", AllowedIPs: "10.0.0.2/32"}},
  119. }, sc)
  120. if len(ops) == 0 {
  121. t.Fatal("plan generó 0 ops")
  122. }
  123. if err := validateWireGuardOps(ops); err != nil {
  124. t.Fatalf("ops no validan en executor: %v", err)
  125. }
  126. // Crea la interfaz (uci_set_named network.wg0=interface + proto).
  127. if !hasOp(ops, "uci_set_named", "section", "wg0") {
  128. t.Error("plan sin uci_set_named de la interfaz wg0")
  129. }
  130. if !hasOp(ops, "uci_set", "option", "proto") {
  131. t.Error("plan sin uci_set proto=wireguard")
  132. }
  133. // Crea el peer wgpeer1 con su public_key y allowed_ips.
  134. if !hasOp(ops, "uci_set_named", "section", "wgpeer1") {
  135. t.Error("plan sin uci_set_named del peer wgpeer1")
  136. }
  137. if !hasOp(ops, "uci_set", "option", "public_key") {
  138. t.Error("plan sin uci_set public_key del peer")
  139. }
  140. if !hasOp(ops, "uci_add_list", "option", "allowed_ips") {
  141. t.Error("plan sin uci_add_list allowed_ips del peer")
  142. }
  143. if !hasOp(ops, "uci_commit", "config", "network") {
  144. t.Error("plan sin uci_commit network")
  145. }
  146. if !hasOp(ops, "service", "action", "reload") {
  147. t.Error("plan sin service network reload")
  148. }
  149. // Sin túnel activo previo → sin wg_check (nada que proteger).
  150. for _, o := range ops {
  151. if o.Kind == "wg_check" {
  152. t.Error("no debería incluir wg_check sin túnel activo previo")
  153. }
  154. }
  155. }
  156. // TestWireGuardOpsNoBorraPeerAdmin: anti-lockout. El peer del admin está en el
  157. // router pero no en el desired; con AdminPeerPublicKey se conserva. El otro
  158. // peer (en desired) se actualiza, no se borra.
  159. func TestWireGuardOpsNoBorraPeerAdmin(t *testing.T) {
  160. sc := parseWireGuard(wireGuardOut)
  161. ops := WireGuardOps(WireGuardDesired{
  162. Interface: "wg0",
  163. AdminPeerPublicKey: "ADMINPUB",
  164. Peers: []WireGuardPeer{
  165. {Name: "peer2", PublicKey: "PEER2PUB", AllowedIPs: "10.0.0.3/32"},
  166. },
  167. }, sc)
  168. if err := validateWireGuardOps(ops); err != nil {
  169. t.Fatalf("ops no validan: %v", err)
  170. }
  171. // Sin protección, wgpeer1 (admin) sería candidato a borrado. Con
  172. // AdminPeerPublicKey no debe aparecer ningún uci_delete_section.
  173. for _, o := range ops {
  174. if o.Kind == "uci_delete_section" {
  175. t.Errorf("anti-lockout roto: plan borra la sección %q", o.Args["section"])
  176. }
  177. }
  178. }
  179. // TestWireGuardOpsBorraPeersSinDesired: sin anti-lockout configurado, los
  180. // peers que no están en el desired se borran.
  181. func TestWireGuardOpsBorraPeersSinDesired(t *testing.T) {
  182. sc := parseWireGuard(wireGuardOut)
  183. ops := WireGuardOps(WireGuardDesired{Interface: "wg0"}, sc)
  184. delSections := map[string]bool{}
  185. for _, o := range ops {
  186. if o.Kind == "uci_delete_section" {
  187. delSections[o.Args["section"]] = true
  188. }
  189. }
  190. if !delSections["wgpeer1"] || !delSections["wgpeer2"] {
  191. t.Errorf("desired sin peers debe borrar ambos: %v", delSections)
  192. }
  193. }
  194. // TestWireGuardOpsHealthcheckSoloSiTunelActivo: wg_check solo si el túnel
  195. // estaba arriba antes del apply (proteger el túnel existente).
  196. func TestWireGuardOpsHealthcheckSoloSiTunelActivo(t *testing.T) {
  197. sc := parseWireGuard(wireGuardOut)
  198. ops := WireGuardOps(WireGuardDesired{Interface: "wg0", Peers: []WireGuardPeer{{Name: "p", PublicKey: "PEER2PUB", AllowedIPs: "10.0.0.3/32"}}}, sc)
  199. found := false
  200. for _, o := range ops {
  201. if o.Kind == "wg_check" {
  202. found = true
  203. if o.Args["interface"] != "wg0" {
  204. t.Errorf("wg_check interface: got %q want wg0", o.Args["interface"])
  205. }
  206. }
  207. }
  208. if !found {
  209. t.Error("con túnel activo previo el plan debe incluir wg_check")
  210. }
  211. }
  212. // TestWireGuardOpsActualizaAllowedIPs: un peer existente con allowed_ips
  213. // distinto se resetea (delete + add_list) sin recrear la sección.
  214. func TestWireGuardOpsActualizaAllowedIPs(t *testing.T) {
  215. sc := parseWireGuard(wireGuardOut)
  216. ops := WireGuardOps(WireGuardDesired{
  217. Interface: "wg0",
  218. Peers: []WireGuardPeer{{Name: "peer2", PublicKey: "PEER2PUB", AllowedIPs: "10.0.0.3/32,10.0.0.42/32"}},
  219. }, sc)
  220. if err := validateWireGuardOps(ops); err != nil {
  221. t.Fatalf("ops no validan: %v", err)
  222. }
  223. if !hasOp(ops, "uci_delete", "section", "wgpeer2") {
  224. t.Error("debe resetear allowed_ips del peer existente (uci_delete)")
  225. }
  226. count := 0
  227. for _, o := range ops {
  228. if o.Kind == "uci_add_list" && o.Args["section"] == "wgpeer2" {
  229. count++
  230. }
  231. }
  232. if count != 2 {
  233. t.Errorf("esperaba 2 add_list en wgpeer2, got %d", count)
  234. }
  235. }
  236. // TestWireGuardOpsSinCambios: desired == scenario → sin ops (idempotente).
  237. func TestWireGuardOpsSinCambios(t *testing.T) {
  238. sc := parseWireGuard(wireGuardOut)
  239. ops := WireGuardOps(WireGuardDesired{
  240. Interface: "wg0",
  241. Peers: []WireGuardPeer{
  242. {Name: "admin", PublicKey: "ADMINPUB", AllowedIPs: "10.0.0.2/32"},
  243. {Name: "peer2", PublicKey: "PEER2PUB", AllowedIPs: "10.0.0.3/32,10.0.0.9/32"},
  244. },
  245. }, sc)
  246. if len(ops) != 0 {
  247. t.Errorf("sin diferencias debería generar 0 ops, got %d:\n%+v", len(ops), ops)
  248. }
  249. }
  250. // TestWireGuardHealthcheck: `wg show wg0` arriba → nil; fallo → error.
  251. func TestWireGuardHealthcheck(t *testing.T) {
  252. run := &fakeWGCommandRunner{out: "interface: wg0\n public key: X\n"}
  253. if err := WireGuardHealthcheck(run, "192.168.1.1", "wg0"); err != nil {
  254. t.Fatalf("túnel arriba: esperaba nil, got %v", err)
  255. }
  256. if !strings.Contains(run.cmd, "wg show wg0") {
  257. t.Errorf("comando: got %q, esperaba contener 'wg show wg0'", run.cmd)
  258. }
  259. run.err = errors.New("wg show exit 1")
  260. if err := WireGuardHealthcheck(run, "192.168.1.1", "wg0"); err == nil {
  261. t.Error("túnel caído: esperaba error")
  262. }
  263. }
  264. // hasOp busca una op por kind + (arg, value).
  265. func hasOp(ops []executor.Op, kind, arg, value string) bool {
  266. for _, o := range ops {
  267. if o.Kind != kind {
  268. continue
  269. }
  270. if v, ok := o.Args[arg]; ok && v == value {
  271. return true
  272. }
  273. }
  274. return false
  275. }