pve.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. // Package pve — cliente read-only de la API de Proxmox VE (issue #561).
  2. //
  3. // Objetivo: obtener el inventario del cluster (VMs/CTs → nodo/host) como
  4. // ground truth para sellar la infraestructura en NetPulse (hypervisor + ct
  5. // con attachTo). La relación CT→host NO es deducible del tráfico L2 (un
  6. // puerto del router mezcla dispositivos); vive en el cluster.
  7. //
  8. // Auth: API token de Proxmox (PVEAPIToken) con privilegios de solo lectura
  9. // (Sys.Audit para cluster/resources; VM.Audit para leer la config de cada
  10. // VM/CT y extraer sus MACs). El token se envía en el header Authorization:
  11. //
  12. // Authorization: PVEAPIToken=USER@REALM!TOKENID=UUID
  13. //
  14. // TLS: el certificado del cluster suele ser self-signed. Por defecto se valida
  15. // contra las raíces del sistema; se puede fijar una CA (caPem) o el SHA-256 del
  16. // certificado hoja (fingerprintSha256). "insecure" desactiva la validación de
  17. // forma explícita. Solo lectura: GET únicamente.
  18. package pve
  19. import (
  20. "context"
  21. "crypto/sha256"
  22. "crypto/subtle"
  23. "crypto/tls"
  24. "crypto/x509"
  25. "encoding/hex"
  26. "encoding/json"
  27. "fmt"
  28. "io"
  29. "net/http"
  30. "net/url"
  31. "sort"
  32. "strconv"
  33. "strings"
  34. "time"
  35. )
  36. // Config: datos de conexión al cluster (persistidos en kv por el server).
  37. type Config struct {
  38. // URL base, p. ej. "https://192.168.1.100:8006" (sin barra final).
  39. URL string `json:"url"`
  40. // TokenID: "USER@REALM!TOKENID" (p. ej. "root@pam!netpulse").
  41. TokenID string `json:"tokenId"`
  42. // Secret: la parte UUID del token (se muestra una sola vez al crearlo).
  43. // NUNCA viaja en respuestas de la API (la config se expone sanitizada).
  44. Secret string `json:"secret,omitempty"`
  45. // CAPEM: CA en PEM para validar el certificado del cluster.
  46. CAPEM string `json:"caPem,omitempty"`
  47. // FingerprintSHA256: SHA-256 en hex del certificado hoja.
  48. FingerprintSHA256 string `json:"fingerprintSha256,omitempty"`
  49. // Insecure: desactiva la validación TLS. Solo para transiciones controladas.
  50. Insecure bool `json:"insecure,omitempty"`
  51. }
  52. // Enabled: true si hay config completa.
  53. func (c Config) Enabled() bool {
  54. return c.URL != "" && c.TokenID != "" && c.Secret != ""
  55. }
  56. const httpTimeout = 5 * time.Second
  57. // Client consulta la API PVE de un cluster.
  58. type Client struct {
  59. cfg Config
  60. hc *http.Client
  61. err error
  62. }
  63. // NewClient crea el cliente (sin red: solo guarda config). Por defecto valida
  64. // el certificado contra las raíces del sistema. CAPEM añade una CA,
  65. // FingerprintSHA256 fija el certificado hoja e Insecure desactiva la validación.
  66. func NewClient(cfg Config) *Client {
  67. transport := http.DefaultTransport.(*http.Transport).Clone()
  68. tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
  69. var clientErr error
  70. switch {
  71. case cfg.Insecure:
  72. tlsCfg.InsecureSkipVerify = true
  73. case cfg.FingerprintSHA256 != "":
  74. want, err := normalizeFingerprint(cfg.FingerprintSHA256)
  75. if err != nil {
  76. clientErr = err
  77. break
  78. }
  79. tlsCfg.InsecureSkipVerify = true
  80. tlsCfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
  81. return verifyFingerprint(rawCerts, want)
  82. }
  83. case cfg.CAPEM != "":
  84. pool := x509.NewCertPool()
  85. if !pool.AppendCertsFromPEM([]byte(cfg.CAPEM)) {
  86. clientErr = fmt.Errorf("PVE: invalid caPem")
  87. break
  88. }
  89. tlsCfg.RootCAs = pool
  90. }
  91. transport.TLSClientConfig = tlsCfg
  92. return &Client{
  93. cfg: cfg,
  94. hc: &http.Client{Timeout: httpTimeout, Transport: transport},
  95. err: clientErr,
  96. }
  97. }
  98. func normalizeFingerprint(v string) (string, error) {
  99. s := strings.ToLower(strings.TrimSpace(v))
  100. s = strings.NewReplacer(":", "", " ", "", "-", "").Replace(s)
  101. if len(s) != 64 {
  102. return "", fmt.Errorf("PVE: fingerprintSha256 must be 64 hex characters")
  103. }
  104. if _, err := hex.DecodeString(s); err != nil {
  105. return "", fmt.Errorf("PVE: invalid fingerprintSha256: %w", err)
  106. }
  107. return s, nil
  108. }
  109. func verifyFingerprint(rawCerts [][]byte, want string) error {
  110. if len(rawCerts) == 0 {
  111. return fmt.Errorf("PVE: no peer certificate")
  112. }
  113. sum := sha256.Sum256(rawCerts[0])
  114. got := hex.EncodeToString(sum[:])
  115. if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
  116. return fmt.Errorf("PVE: certificate fingerprint mismatch")
  117. }
  118. return nil
  119. }
  120. func (c *Client) authHeader() string {
  121. return "PVEAPIToken=" + c.cfg.TokenID + "=" + c.cfg.Secret
  122. }
  123. func (c *Client) get(ctx context.Context, path string, dst any) error {
  124. if c.err != nil {
  125. return c.err
  126. }
  127. req, err := http.NewRequestWithContext(ctx, "GET", c.cfg.URL+path, nil)
  128. if err != nil {
  129. return err
  130. }
  131. req.Header.Set("Authorization", c.authHeader())
  132. req.Header.Set("Accept", "application/json")
  133. res, err := c.hc.Do(req)
  134. if err != nil {
  135. return fmt.Errorf("PVE %s: %w", path, err)
  136. }
  137. defer res.Body.Close()
  138. if res.StatusCode != 200 {
  139. body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
  140. return fmt.Errorf("PVE %s → HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body)))
  141. }
  142. // La API PVE envuelve todo en {"data": ...}.
  143. var wrapper struct {
  144. Data json.RawMessage `json:"data"`
  145. }
  146. if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&wrapper); err != nil {
  147. return err
  148. }
  149. return json.Unmarshal(wrapper.Data, dst)
  150. }
  151. // Resource: un elemento de cluster/resources (VM, CT, storage, node…).
  152. // Verificado contra pve-docs: los campos que NetPulse necesita para el
  153. // sellado de infra son vmid/name/type/node/status.
  154. type Resource struct {
  155. ID string `json:"id"` // "qemu/100" | "lxc/200" | "node/citadel-01"…
  156. VMID int `json:"vmid"` // 0 para nodos/storage
  157. Name string `json:"name"` // hostname del CT/VM, o nombre del nodo
  158. Type string `json:"type"` // "lxc" | "qemu" | "node" | "storage" | …
  159. Node string `json:"node"` // nodo que lo ejecuta ("" para storage)
  160. Status string `json:"status"` // "running" | "stopped" | …
  161. }
  162. // ClusterResources: GET /api2/json/cluster/resources → VMs/CTs de TODO el
  163. // cluster con su nodo (host). Una sola llamada.
  164. func (c *Client) ClusterResources(ctx context.Context) ([]Resource, error) {
  165. var out []Resource
  166. if err := c.get(ctx, "/api2/json/cluster/resources", &out); err != nil {
  167. return nil, err
  168. }
  169. return out, nil
  170. }
  171. // VMConfig: GET /nodes/{node}/lxc|qemu/{vmid}/config. Devuelve el objeto de
  172. // config crudo; NetPulse usa netN → MAC de cada interfaz.
  173. func (c *Client) VMConfig(ctx context.Context, node, typ string, vmid int) (map[string]any, error) {
  174. path := fmt.Sprintf("/api2/json/nodes/%s/%s/%d/config", url.PathEscape(node), typ, vmid)
  175. var out map[string]any
  176. if err := c.get(ctx, path, &out); err != nil {
  177. return nil, err
  178. }
  179. return out, nil
  180. }
  181. // NodeIP: GET /nodes/{node}/network → IP IPv4 del bridge vmbr0 (o el primer
  182. // iface con address IPv4). Identifica al host físico del nodo en la LAN.
  183. func (c *Client) NodeIP(ctx context.Context, node string) (string, error) {
  184. path := fmt.Sprintf("/api2/json/nodes/%s/network", url.PathEscape(node))
  185. var out []struct {
  186. Iface string `json:"iface"`
  187. Type string `json:"type"`
  188. Address string `json:"address"`
  189. }
  190. if err := c.get(ctx, path, &out); err != nil {
  191. return "", err
  192. }
  193. // Preferencia: vmbr0 (bridge principal); si no, cualquier iface con IPv4.
  194. var fallback string
  195. for _, i := range out {
  196. if !strings.Contains(i.Address, ".") {
  197. continue
  198. }
  199. if i.Iface == "vmbr0" {
  200. return i.Address, nil
  201. }
  202. if fallback == "" {
  203. fallback = i.Address
  204. }
  205. }
  206. return fallback, nil
  207. }
  208. // NIC is one NIC declared in a guest config: the MAC it uses, the VLAN tag it
  209. // carries and the bridge it hangs from. Proxmox writes tag=<vid> when the
  210. // guest is not on the native VLAN, and that is the only place the tag exists:
  211. // the guest sits behind the host bridge, so the router never sees it (#1757).
  212. type NIC struct {
  213. MAC string
  214. Tag int
  215. Bridge string
  216. }
  217. // NICsOfConfig returns the NICs of a VM/CT config, in net<N> order so the
  218. // result is stable between polls. Proxmox exposes each NIC as "net0": "…":
  219. //
  220. // LXC: net0: bridge=vmbr0,hwaddr=BC:24:11:XX:XX:XX,ip=dhcp,name=eth0,type=veth
  221. // QEMU: net0: virtio=BC:24:11:XX:XX:XX,bridge=vmbr0 (MAC tras el modelo)
  222. //
  223. // MACs are normalised to upper case with ':'.
  224. func NICsOfConfig(cfg map[string]any) []NIC {
  225. keys := make([]string, 0, len(cfg))
  226. for k := range cfg {
  227. if strings.HasPrefix(k, "net") {
  228. keys = append(keys, k)
  229. }
  230. }
  231. sort.Strings(keys)
  232. var out []NIC
  233. for _, k := range keys {
  234. s, ok := cfg[k].(string)
  235. if !ok {
  236. continue
  237. }
  238. var nic NIC
  239. for _, field := range strings.Split(s, ",") {
  240. switch {
  241. case strings.HasPrefix(field, "hwaddr="):
  242. nic.MAC = normMAC(field[len("hwaddr="):])
  243. case strings.HasPrefix(field, "bridge="):
  244. nic.Bridge = field[len("bridge="):]
  245. case strings.HasPrefix(field, "tag="):
  246. if n, err := strconv.Atoi(field[len("tag="):]); err == nil && n > 0 && n < 4095 {
  247. nic.Tag = n
  248. }
  249. default:
  250. // QEMU: el primer campo es <modelo>=<MAC> (virtio=XX, e1000=XX…)
  251. if eq := strings.Index(field, "="); eq > 0 {
  252. if looksLikeMAC(field[eq+1:]) {
  253. nic.MAC = normMAC(field[eq+1:])
  254. }
  255. }
  256. }
  257. }
  258. if nic.MAC != "" {
  259. out = append(out, nic)
  260. }
  261. }
  262. return out
  263. }
  264. // MACsOfConfig extrae las MACs de una config de VM/CT (ver NICsOfConfig).
  265. func MACsOfConfig(cfg map[string]any) []string {
  266. nics := NICsOfConfig(cfg)
  267. if len(nics) == 0 {
  268. return nil
  269. }
  270. out := make([]string, 0, len(nics))
  271. for _, n := range nics {
  272. out = append(out, n.MAC)
  273. }
  274. return out
  275. }
  276. func looksLikeMAC(s string) bool {
  277. if len(s) != 17 {
  278. return false
  279. }
  280. for i, r := range s {
  281. if i%3 == 2 {
  282. if r != ':' {
  283. return false
  284. }
  285. } else if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) {
  286. return false
  287. }
  288. }
  289. return true
  290. }
  291. func normMAC(s string) string {
  292. var b strings.Builder
  293. for _, r := range strings.ToUpper(s) {
  294. if (r >= '0' && r <= '9') || (r >= 'A' && r <= 'F') {
  295. b.WriteRune(r)
  296. }
  297. }
  298. hex := b.String()
  299. if len(hex) != 12 {
  300. return ""
  301. }
  302. var out strings.Builder
  303. for i := 0; i < 12; i += 2 {
  304. if i > 0 {
  305. out.WriteByte(':')
  306. }
  307. out.WriteString(hex[i : i+2])
  308. }
  309. return out.String()
  310. }
  311. // TestResult is what a connection test can tell the user about an endpoint.
  312. type TestResult struct {
  313. // Version: the PVE release string ("8.4.21").
  314. Version string `json:"version"`
  315. Nodes int `json:"nodes"`
  316. VMs int `json:"vms"`
  317. CTs int `json:"cts"`
  318. // Limited: the token authenticates but Proxmox is filtering the listings
  319. // because the token has no audit rights. This is the failure the test
  320. // exists for: PVE does not reject a list a token may not see, it returns
  321. // it empty with HTTP 200, so an under-privileged token looks exactly
  322. // like a cluster with no guests and the integration goes quiet.
  323. Limited bool `json:"limited"`
  324. }
  325. // Test checks an endpoint the way a user needs it checked: can we reach it,
  326. // does the token authenticate, and can it actually see anything.
  327. func (c *Client) Test(ctx context.Context) (*TestResult, error) {
  328. if !c.cfg.Enabled() {
  329. return nil, fmt.Errorf("missing url, tokenId or secret")
  330. }
  331. var version struct {
  332. Version string `json:"version"`
  333. Release string `json:"release"`
  334. }
  335. // /version needs no privileges: it separates "unreachable or bad token"
  336. // from "authenticated but blind", which are different problems.
  337. if err := c.get(ctx, "/api2/json/version", &version); err != nil {
  338. return nil, err
  339. }
  340. out := &TestResult{Version: version.Version}
  341. if out.Version == "" {
  342. out.Version = version.Release
  343. }
  344. resources, err := c.ClusterResources(ctx)
  345. if err != nil {
  346. return nil, err
  347. }
  348. var firstNode string
  349. for _, r := range resources {
  350. switch r.Type {
  351. case "node":
  352. out.Nodes++
  353. if firstNode == "" {
  354. firstNode = r.Node
  355. }
  356. case "qemu":
  357. out.VMs++
  358. case "lxc":
  359. out.CTs++
  360. }
  361. }
  362. // Nothing to seal: is the cluster empty, or is the token blind? Ask for
  363. // something that needs Sys.Audit and read the answer. A 403 proves the
  364. // token lacks the rights, and the user gets told which ones.
  365. if out.VMs == 0 && out.CTs == 0 && firstNode != "" {
  366. var status map[string]any
  367. if err := c.get(ctx, "/api2/json/nodes/"+url.PathEscape(firstNode)+"/status", &status); err != nil &&
  368. strings.Contains(err.Error(), "HTTP 403") {
  369. out.Limited = true
  370. }
  371. }
  372. return out, nil
  373. }
  374. // ClusterNode is one entry of /cluster/status: the address corosync knows a
  375. // node by, which is the node's real address on the network.
  376. type ClusterNode struct {
  377. Type string `json:"type"` // "node" | "cluster"
  378. Name string `json:"name"`
  379. IP string `json:"ip"`
  380. }
  381. // ClusterStatus: GET /api2/json/cluster/status → node name and IP.
  382. //
  383. // This is where a node's address actually lives. /nodes/{node}/network only
  384. // reports what /etc/network/interfaces declares, so a host whose management
  385. // address is configured outside it -- DHCP on the NIC, systemd-networkd, a
  386. // setup with no bridge in that file -- lists its interfaces with no address
  387. // at all and offers nothing to match the host device by.
  388. //
  389. // Needs Sys.Audit on "/"; a token without it gets a 403 and the caller
  390. // falls back to the interface listing.
  391. func (c *Client) ClusterStatus(ctx context.Context) ([]ClusterNode, error) {
  392. var out []ClusterNode
  393. if err := c.get(ctx, "/api2/json/cluster/status", &out); err != nil {
  394. return nil, err
  395. }
  396. return out, nil
  397. }
  398. // HostOfURL: the host part of the configured endpoint, with no port. For a
  399. // single-node instance that is the node's address, and it is the last
  400. // resort when the API will not say what its own address is.
  401. func (c *Client) HostOfURL() string {
  402. u, err := url.Parse(c.cfg.URL)
  403. if err != nil {
  404. return ""
  405. }
  406. return u.Hostname()
  407. }