pve_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package pve
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/pem"
  7. "net/http"
  8. "net/http/httptest"
  9. "reflect"
  10. "sort"
  11. "strings"
  12. "testing"
  13. )
  14. // Fixtures del formato REAL de las configs de Proxmox (verificado en
  15. // pve-docs chapter-pct/chapter-qm).
  16. func TestMACsOfConfigLXC(t *testing.T) {
  17. cfg := map[string]any{
  18. "hostname": "webs",
  19. "net0": "bridge=vmbr0,hwaddr=BC:24:11:A4:9E:BB,ip=dhcp,name=eth0,type=veth",
  20. "net1": "bridge=vmbr0,hwaddr=bc:24:11:00:00:01,ip=dhcp,name=eth1,type=veth",
  21. "memory": float64(2048),
  22. }
  23. macs := MACsOfConfig(cfg)
  24. sort.Strings(macs)
  25. want := []string{"BC:24:11:00:00:01", "BC:24:11:A4:9E:BB"}
  26. sort.Strings(want)
  27. if !reflect.DeepEqual(macs, want) {
  28. t.Fatalf("macs lxc: %v (want %v)", macs, want)
  29. }
  30. }
  31. func TestMACsOfConfigQEMU(t *testing.T) {
  32. cfg := map[string]any{
  33. "name": "pbs-vm",
  34. "net0": "e1000=EE:D2:28:5F:B6:3E,bridge=vmbr0",
  35. "net1": "virtio=52:54:00:12:34:56,bridge=vmbr0",
  36. }
  37. macs := MACsOfConfig(cfg)
  38. sort.Strings(macs)
  39. want := []string{"52:54:00:12:34:56", "EE:D2:28:5F:B6:3E"}
  40. sort.Strings(want)
  41. if !reflect.DeepEqual(macs, want) {
  42. t.Fatalf("macs qemu: %v (want %v)", macs, want)
  43. }
  44. }
  45. func TestMACsOfConfigIgnoraCampos(t *testing.T) {
  46. // net0 sin MAC (ip estática sin hwaddr explícita), otros campos, basura.
  47. cfg := map[string]any{
  48. "net0": "name=eth0,bridge=vmbr0,ip=192.168.1.10/24",
  49. "net1": "bridge=vmbr0,hwaddr=00:11:22:33:44:55,ip=dhcp,name=eth1",
  50. "memory": "2048", // no es net*, se ignora
  51. "netx": "no es una NIC real", // prefijo net pero sin MAC
  52. }
  53. macs := MACsOfConfig(cfg)
  54. want := []string{"00:11:22:33:44:55"}
  55. if !reflect.DeepEqual(macs, want) {
  56. t.Fatalf("macs: %v (want %v)", macs, want)
  57. }
  58. }
  59. // TestClientClusterResources: el cliente parsea {"data":[...]} de la API PVE
  60. // y manda el header de token.
  61. func TestClientClusterResources(t *testing.T) {
  62. var gotAuth string
  63. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  64. gotAuth = r.Header.Get("Authorization")
  65. if r.URL.Path != "/api2/json/cluster/resources" {
  66. t.Errorf("path: %s", r.URL.Path)
  67. }
  68. w.Header().Set("Content-Type", "application/json")
  69. w.Write([]byte(`{"data":[
  70. {"id":"node/citadel-01","node":"citadel-01","type":"node","status":"online","name":"citadel-01"},
  71. {"id":"lxc/100","vmid":100,"node":"citadel-01","type":"lxc","status":"running","name":"webs"},
  72. {"id":"qemu/200","vmid":200,"node":"citadel-02","type":"qemu","status":"running","name":"pbs"},
  73. {"id":"lxc/101","vmid":101,"node":"citadel-01","type":"lxc","status":"stopped","name":"apagado"}
  74. ]}`))
  75. }))
  76. defer srv.Close()
  77. c := NewClient(Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "uuid-secret"})
  78. res, err := c.ClusterResources(context.Background())
  79. if err != nil {
  80. t.Fatalf("cluster: %v", err)
  81. }
  82. if len(res) != 4 {
  83. t.Fatalf("resources: %d", len(res))
  84. }
  85. if res[1].VMID != 100 || res[1].Type != "lxc" || res[1].Node != "citadel-01" || res[1].Name != "webs" || res[1].Status != "running" {
  86. t.Fatalf("lxc webs: %+v", res[1])
  87. }
  88. if res[2].VMID != 200 || res[2].Type != "qemu" || res[2].Node != "citadel-02" {
  89. t.Fatalf("qemu pbs: %+v", res[2])
  90. }
  91. if res[0].VMID != 0 || res[0].Type != "node" {
  92. t.Fatalf("node: %+v", res[0])
  93. }
  94. if want := "PVEAPIToken=root@pam!netpulse=uuid-secret"; gotAuth != want {
  95. t.Fatalf("auth: %q (want %q)", gotAuth, want)
  96. }
  97. }
  98. func TestClientErrors(t *testing.T) {
  99. // 401 sin token válido
  100. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  101. w.WriteHeader(http.StatusUnauthorized)
  102. w.Write([]byte(`{"errors":{"root@pam!netpulse":"no such token"}}`))
  103. }))
  104. defer srv.Close()
  105. c := NewClient(Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "mal"})
  106. if _, err := c.ClusterResources(context.Background()); err == nil {
  107. t.Fatal("401 debería dar error")
  108. }
  109. }
  110. func TestConfigEnabled(t *testing.T) {
  111. if (Config{}).Enabled() {
  112. t.Fatal("config vacía no enabled")
  113. }
  114. if !(Config{URL: "https://x:8006", TokenID: "a!b", Secret: "c"}).Enabled() {
  115. t.Fatal("config completa debería ser enabled")
  116. }
  117. }
  118. func TestNodeIP(t *testing.T) {
  119. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  120. w.Header().Set("Content-Type", "application/json")
  121. w.Write([]byte(`{"data":[
  122. {"iface":"eno1","type":"eth","address":""},
  123. {"iface":"vmbr0","type":"bridge","address":"192.168.1.101"},
  124. {"iface":"vmbr0","type":"bridge","address":"fe80::1"}
  125. ]}`))
  126. }))
  127. defer srv.Close()
  128. c := NewClient(Config{URL: srv.URL, TokenID: "a!b", Secret: "c"})
  129. ip, err := c.NodeIP(context.Background(), "citadel-02")
  130. if err != nil {
  131. t.Fatalf("nodeip: %v", err)
  132. }
  133. if ip != "192.168.1.101" {
  134. t.Fatalf("ip: %q", ip)
  135. }
  136. }
  137. // pveTestServer: an endpoint that answers /version and /cluster/resources
  138. // with what it is given, and /nodes/{n}/status with the audit verdict.
  139. func pveTestServer(t *testing.T, resources string, nodeStatus int) *httptest.Server {
  140. t.Helper()
  141. return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  142. w.Header().Set("Content-Type", "application/json")
  143. switch {
  144. case r.URL.Path == "/api2/json/version":
  145. w.Write([]byte(`{"data":{"release":"8.4","version":"8.4.21"}}`))
  146. case r.URL.Path == "/api2/json/cluster/resources":
  147. w.Write([]byte(`{"data":[` + resources + `]}`))
  148. case strings.HasSuffix(r.URL.Path, "/status"):
  149. w.WriteHeader(nodeStatus)
  150. if nodeStatus == 403 {
  151. w.Write([]byte(`{"message":"Permission check failed (/nodes/pve1, Sys.Audit)\n","data":null}`))
  152. return
  153. }
  154. w.Write([]byte(`{"data":{"uptime":1}}`))
  155. default:
  156. t.Errorf("unexpected path %q", r.URL.Path)
  157. w.WriteHeader(404)
  158. }
  159. }))
  160. }
  161. func TestTestCountsWhatItSees(t *testing.T) {
  162. srv := pveTestServer(t, `
  163. {"id":"node/pve1","node":"pve1","type":"node","status":"online"},
  164. {"id":"lxc/100","vmid":100,"node":"pve1","type":"lxc","status":"running"},
  165. {"id":"qemu/200","vmid":200,"node":"pve1","type":"qemu","status":"running"},
  166. {"id":"qemu/201","vmid":201,"node":"pve1","type":"qemu","status":"stopped"},
  167. {"id":"storage/local","node":"pve1","type":"storage"}`, 200)
  168. defer srv.Close()
  169. res, err := NewClient(Config{URL: srv.URL, TokenID: "netpulse@pam!t", Secret: "s"}).Test(context.Background())
  170. if err != nil {
  171. t.Fatal(err)
  172. }
  173. if res.Version != "8.4.21" || res.Nodes != 1 || res.VMs != 2 || res.CTs != 1 {
  174. t.Fatalf("result: %+v", res)
  175. }
  176. // With guests in sight there is nothing to warn about.
  177. if res.Limited {
  178. t.Fatalf("limited should be false: %+v", res)
  179. }
  180. }
  181. // The failure the endpoint exists for: the token authenticates, PVE answers
  182. // 200 with empty lists because it filters what the token may not see, and
  183. // the integration goes quiet with nothing to show for it.
  184. func TestTestDetectsATokenWithoutAuditRights(t *testing.T) {
  185. srv := pveTestServer(t, `{"id":"node/pve1","node":"pve1","type":"node","status":"online"}`, 403)
  186. defer srv.Close()
  187. res, err := NewClient(Config{URL: srv.URL, TokenID: "netpulse@pam!t", Secret: "s"}).Test(context.Background())
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. if !res.Limited {
  192. t.Fatalf("a 403 on the node status means the token is blind: %+v", res)
  193. }
  194. if res.Nodes != 1 || res.VMs != 0 || res.CTs != 0 {
  195. t.Fatalf("result: %+v", res)
  196. }
  197. }
  198. // A cluster that really is empty is not reported as a permissions problem.
  199. func TestTestDoesNotCryWolfOnAnEmptyCluster(t *testing.T) {
  200. srv := pveTestServer(t, `{"id":"node/pve1","node":"pve1","type":"node","status":"online"}`, 200)
  201. defer srv.Close()
  202. res, err := NewClient(Config{URL: srv.URL, TokenID: "netpulse@pam!t", Secret: "s"}).Test(context.Background())
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. if res.Limited {
  207. t.Fatalf("no guests but full rights: %+v", res)
  208. }
  209. }
  210. func TestTestReportsUnreachableAndUnconfigured(t *testing.T) {
  211. if _, err := NewClient(Config{URL: "http://127.0.0.1:1", TokenID: "a!b", Secret: "s"}).
  212. Test(context.Background()); err == nil {
  213. t.Fatal("expected a connection error")
  214. }
  215. if _, err := NewClient(Config{URL: "http://x"}).Test(context.Background()); err == nil {
  216. t.Fatal("expected an error for an incomplete config")
  217. }
  218. }
  219. // cluster/status is where a node's address really is: /nodes/{n}/network
  220. // only knows what /etc/network/interfaces declares, and a host configured
  221. // outside it lists its NICs with no address at all.
  222. func TestClusterStatusAndHostOfURL(t *testing.T) {
  223. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  224. w.Header().Set("Content-Type", "application/json")
  225. w.Write([]byte(`{"data":[
  226. {"type":"cluster","name":"home","id":"cluster"},
  227. {"type":"node","name":"pve1","ip":"192.0.2.2","online":1,"id":"node/pve1"},
  228. {"type":"node","name":"pve2","ip":"192.0.2.3","online":1,"id":"node/pve2"}
  229. ]}`))
  230. }))
  231. defer srv.Close()
  232. c := NewClient(Config{URL: srv.URL + "/", TokenID: "netpulse@pam!t", Secret: "s"})
  233. nodes, err := c.ClusterStatus(context.Background())
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. if len(nodes) != 3 {
  238. t.Fatalf("nodes: %+v", nodes)
  239. }
  240. got := map[string]string{}
  241. for _, n := range nodes {
  242. if n.Type == "node" {
  243. got[n.Name] = n.IP
  244. }
  245. }
  246. if got["pve1"] != "192.0.2.2" || got["pve2"] != "192.0.2.3" {
  247. t.Fatalf("addresses: %v", got)
  248. }
  249. // The endpoint's own host, with the port stripped.
  250. if h := (&Client{cfg: Config{URL: "https://192.0.2.9:8006"}}).HostOfURL(); h != "192.0.2.9" {
  251. t.Fatalf("HostOfURL: %q", h)
  252. }
  253. }
  254. // A node whose interfaces declare no address at all: NodeIP has nothing to
  255. // return, and saying so is what makes the caller fall back.
  256. func TestNodeIPWithoutAnyAddress(t *testing.T) {
  257. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  258. w.Header().Set("Content-Type", "application/json")
  259. w.Write([]byte(`{"data":[
  260. {"iface":"enp2s0","type":"eth","method":"manual"},
  261. {"iface":"enp3s0","type":"eth","method":"manual"}
  262. ]}`))
  263. }))
  264. defer srv.Close()
  265. ip, err := NewClient(Config{URL: srv.URL, TokenID: "a!b", Secret: "s"}).
  266. NodeIP(context.Background(), "pve1")
  267. if err != nil || ip != "" {
  268. t.Fatalf("ip=%q err=%v", ip, err)
  269. }
  270. }
  271. func TestClientTLSVerification(t *testing.T) {
  272. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  273. w.Header().Set("Content-Type", "application/json")
  274. w.Write([]byte(`{"data":[]}`))
  275. }))
  276. defer srv.Close()
  277. cert := srv.Certificate()
  278. caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
  279. sum := sha256.Sum256(cert.Raw)
  280. fingerprint := hex.EncodeToString(sum[:])
  281. base := Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "uuid-secret"}
  282. tests := []struct {
  283. name string
  284. mutate func(*Config)
  285. wantErr bool
  286. }{
  287. {name: "default rejects self-signed", wantErr: true},
  288. {name: "configured CA", mutate: func(c *Config) { c.CAPEM = string(caPEM) }},
  289. {name: "pinned fingerprint", mutate: func(c *Config) { c.FingerprintSHA256 = fingerprint }},
  290. {name: "wrong fingerprint", mutate: func(c *Config) { c.FingerprintSHA256 = strings.Repeat("0", 64) }, wantErr: true},
  291. {name: "explicit insecure", mutate: func(c *Config) { c.Insecure = true }},
  292. }
  293. for _, tt := range tests {
  294. t.Run(tt.name, func(t *testing.T) {
  295. cfg := base
  296. if tt.mutate != nil {
  297. tt.mutate(&cfg)
  298. }
  299. if _, err := NewClient(cfg).ClusterResources(context.Background()); (err != nil) != tt.wantErr {
  300. t.Fatalf("error: got %v wantErr %v", err, tt.wantErr)
  301. }
  302. })
  303. }
  304. }
  305. // TestNICsOfConfigReadsTag: la VLAN del invitado solo existe en la config de
  306. // Proxmox (tag=<vid>), así que el parser tiene que sacarla junto a la MAC
  307. // (#1757). Un invitado sin tag está en la VLAN nativa del bridge.
  308. func TestNICsOfConfigReadsTag(t *testing.T) {
  309. cfg := map[string]any{
  310. "net0": "bridge=vmbr0,hwaddr=BC:24:11:00:00:01,tag=999,ip=dhcp,name=eth0,type=veth",
  311. "net1": "virtio=BC:24:11:00:00:02,bridge=vmbr1,tag=42",
  312. "net2": "bridge=vmbr0,hwaddr=BC:24:11:00:00:03,ip=dhcp,name=eth2,type=veth",
  313. "net3": "bridge=vmbr0,hwaddr=BC:24:11:00:00:04,tag=0",
  314. }
  315. nics := NICsOfConfig(cfg)
  316. if len(nics) != 4 {
  317. t.Fatalf("nics: %+v (want 4)", nics)
  318. }
  319. // net<N> en orden, no el orden aleatorio del map.
  320. want := []NIC{
  321. {MAC: "BC:24:11:00:00:01", Tag: 999, Bridge: "vmbr0"},
  322. {MAC: "BC:24:11:00:00:02", Tag: 42, Bridge: "vmbr1"},
  323. {MAC: "BC:24:11:00:00:03", Bridge: "vmbr0"},
  324. {MAC: "BC:24:11:00:00:04", Bridge: "vmbr0"},
  325. }
  326. if !reflect.DeepEqual(nics, want) {
  327. t.Fatalf("nics: %+v (want %+v)", nics, want)
  328. }
  329. // MACsOfConfig sigue devolviendo solo las MACs, en el mismo orden.
  330. macs := MACsOfConfig(cfg)
  331. wantMACs := []string{"BC:24:11:00:00:01", "BC:24:11:00:00:02", "BC:24:11:00:00:03", "BC:24:11:00:00:04"}
  332. if !reflect.DeepEqual(macs, wantMACs) {
  333. t.Fatalf("macs: %v (want %v)", macs, wantMACs)
  334. }
  335. }