| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 |
- // Package pve — cliente read-only de la API de Proxmox VE (issue #561).
- //
- // Objetivo: obtener el inventario del cluster (VMs/CTs → nodo/host) como
- // ground truth para sellar la infraestructura en NetPulse (hypervisor + ct
- // con attachTo). La relación CT→host NO es deducible del tráfico L2 (un
- // puerto del router mezcla dispositivos); vive en el cluster.
- //
- // Auth: API token de Proxmox (PVEAPIToken) con privilegios de solo lectura
- // (Sys.Audit para cluster/resources; VM.Audit para leer la config de cada
- // VM/CT y extraer sus MACs). El token se envía en el header Authorization:
- //
- // Authorization: PVEAPIToken=USER@REALM!TOKENID=UUID
- //
- // TLS: el certificado del cluster suele ser self-signed. Por defecto se valida
- // contra las raíces del sistema; se puede fijar una CA (caPem) o el SHA-256 del
- // certificado hoja (fingerprintSha256). "insecure" desactiva la validación de
- // forma explícita. Solo lectura: GET únicamente.
- package pve
- import (
- "context"
- "crypto/sha256"
- "crypto/subtle"
- "crypto/tls"
- "crypto/x509"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "sort"
- "strconv"
- "strings"
- "time"
- "github.com/gnacho/netpulse/agent/macaddr"
- )
- // Config: datos de conexión al cluster (persistidos en kv por el server).
- type Config struct {
- // URL base, p. ej. "https://192.168.1.100:8006" (sin barra final).
- URL string `json:"url"`
- // TokenID: "USER@REALM!TOKENID" (p. ej. "root@pam!netpulse").
- TokenID string `json:"tokenId"`
- // Secret: la parte UUID del token (se muestra una sola vez al crearlo).
- // NUNCA viaja en respuestas de la API (la config se expone sanitizada).
- Secret string `json:"secret,omitempty"`
- // CAPEM: CA en PEM para validar el certificado del cluster.
- CAPEM string `json:"caPem,omitempty"`
- // FingerprintSHA256: SHA-256 en hex del certificado hoja.
- FingerprintSHA256 string `json:"fingerprintSha256,omitempty"`
- // Insecure: desactiva la validación TLS. Solo para transiciones controladas.
- Insecure bool `json:"insecure,omitempty"`
- }
- // Enabled: true si hay config completa.
- func (c Config) Enabled() bool {
- return c.URL != "" && c.TokenID != "" && c.Secret != ""
- }
- const httpTimeout = 5 * time.Second
- // Client consulta la API PVE de un cluster.
- type Client struct {
- cfg Config
- hc *http.Client
- err error
- }
- // NewClient crea el cliente (sin red: solo guarda config). Por defecto valida
- // el certificado contra las raíces del sistema. CAPEM añade una CA,
- // FingerprintSHA256 fija el certificado hoja e Insecure desactiva la validación.
- func NewClient(cfg Config) *Client {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
- var clientErr error
- switch {
- case cfg.Insecure:
- tlsCfg.InsecureSkipVerify = true
- case cfg.FingerprintSHA256 != "":
- want, err := normalizeFingerprint(cfg.FingerprintSHA256)
- if err != nil {
- clientErr = err
- break
- }
- tlsCfg.InsecureSkipVerify = true
- tlsCfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
- return verifyFingerprint(rawCerts, want)
- }
- case cfg.CAPEM != "":
- pool := x509.NewCertPool()
- if !pool.AppendCertsFromPEM([]byte(cfg.CAPEM)) {
- clientErr = fmt.Errorf("PVE: invalid caPem")
- break
- }
- tlsCfg.RootCAs = pool
- }
- transport.TLSClientConfig = tlsCfg
- return &Client{
- cfg: cfg,
- hc: &http.Client{Timeout: httpTimeout, Transport: transport},
- err: clientErr,
- }
- }
- func normalizeFingerprint(v string) (string, error) {
- s := strings.ToLower(strings.TrimSpace(v))
- s = strings.NewReplacer(":", "", " ", "", "-", "").Replace(s)
- if len(s) != 64 {
- return "", fmt.Errorf("PVE: fingerprintSha256 must be 64 hex characters")
- }
- if _, err := hex.DecodeString(s); err != nil {
- return "", fmt.Errorf("PVE: invalid fingerprintSha256: %w", err)
- }
- return s, nil
- }
- func verifyFingerprint(rawCerts [][]byte, want string) error {
- if len(rawCerts) == 0 {
- return fmt.Errorf("PVE: no peer certificate")
- }
- sum := sha256.Sum256(rawCerts[0])
- got := hex.EncodeToString(sum[:])
- if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
- return fmt.Errorf("PVE: certificate fingerprint mismatch")
- }
- return nil
- }
- func (c *Client) authHeader() string {
- return "PVEAPIToken=" + c.cfg.TokenID + "=" + c.cfg.Secret
- }
- func (c *Client) get(ctx context.Context, path string, dst any) error {
- if c.err != nil {
- return c.err
- }
- req, err := http.NewRequestWithContext(ctx, "GET", c.cfg.URL+path, nil)
- if err != nil {
- return err
- }
- req.Header.Set("Authorization", c.authHeader())
- req.Header.Set("Accept", "application/json")
- res, err := c.hc.Do(req)
- if err != nil {
- return fmt.Errorf("PVE %s: %w", path, err)
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
- return fmt.Errorf("PVE %s → HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body)))
- }
- // La API PVE envuelve todo en {"data": ...}.
- var wrapper struct {
- Data json.RawMessage `json:"data"`
- }
- if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&wrapper); err != nil {
- return err
- }
- return json.Unmarshal(wrapper.Data, dst)
- }
- // Resource: un elemento de cluster/resources (VM, CT, storage, node…).
- // Verificado contra pve-docs: los campos que NetPulse necesita para el
- // sellado de infra son vmid/name/type/node/status.
- type Resource struct {
- ID string `json:"id"` // "qemu/100" | "lxc/200" | "node/citadel-01"…
- VMID int `json:"vmid"` // 0 para nodos/storage
- Name string `json:"name"` // hostname del CT/VM, o nombre del nodo
- Type string `json:"type"` // "lxc" | "qemu" | "node" | "storage" | …
- Node string `json:"node"` // nodo que lo ejecuta ("" para storage)
- Status string `json:"status"` // "running" | "stopped" | …
- }
- // ClusterResources: GET /api2/json/cluster/resources → VMs/CTs de TODO el
- // cluster con su nodo (host). Una sola llamada.
- func (c *Client) ClusterResources(ctx context.Context) ([]Resource, error) {
- var out []Resource
- if err := c.get(ctx, "/api2/json/cluster/resources", &out); err != nil {
- return nil, err
- }
- return out, nil
- }
- // VMConfig: GET /nodes/{node}/lxc|qemu/{vmid}/config. Devuelve el objeto de
- // config crudo; NetPulse usa netN → MAC de cada interfaz.
- func (c *Client) VMConfig(ctx context.Context, node, typ string, vmid int) (map[string]any, error) {
- path := fmt.Sprintf("/api2/json/nodes/%s/%s/%d/config", url.PathEscape(node), typ, vmid)
- var out map[string]any
- if err := c.get(ctx, path, &out); err != nil {
- return nil, err
- }
- return out, nil
- }
- // NodeIP: GET /nodes/{node}/network → IP IPv4 del bridge vmbr0 (o el primer
- // iface con address IPv4). Identifica al host físico del nodo en la LAN.
- func (c *Client) NodeIP(ctx context.Context, node string) (string, error) {
- path := fmt.Sprintf("/api2/json/nodes/%s/network", url.PathEscape(node))
- var out []struct {
- Iface string `json:"iface"`
- Type string `json:"type"`
- Address string `json:"address"`
- }
- if err := c.get(ctx, path, &out); err != nil {
- return "", err
- }
- // Preferencia: vmbr0 (bridge principal); si no, cualquier iface con IPv4.
- var fallback string
- for _, i := range out {
- if !strings.Contains(i.Address, ".") {
- continue
- }
- if i.Iface == "vmbr0" {
- return i.Address, nil
- }
- if fallback == "" {
- fallback = i.Address
- }
- }
- return fallback, nil
- }
- // NIC is one NIC declared in a guest config: the MAC it uses, the VLAN tag it
- // carries and the bridge it hangs from. Proxmox writes tag=<vid> when the
- // guest is not on the native VLAN, and that is the only place the tag exists:
- // the guest sits behind the host bridge, so the router never sees it (#1757).
- type NIC struct {
- MAC string
- Tag int
- Bridge string
- }
- // NICsOfConfig returns the NICs of a VM/CT config, in net<N> order so the
- // result is stable between polls. Proxmox exposes each NIC as "net0": "…":
- //
- // LXC: net0: bridge=vmbr0,hwaddr=BC:24:11:XX:XX:XX,ip=dhcp,name=eth0,type=veth
- // QEMU: net0: virtio=BC:24:11:XX:XX:XX,bridge=vmbr0 (MAC tras el modelo)
- //
- // MACs are normalised to upper case with ':'.
- func NICsOfConfig(cfg map[string]any) []NIC {
- keys := make([]string, 0, len(cfg))
- for k := range cfg {
- if strings.HasPrefix(k, "net") {
- keys = append(keys, k)
- }
- }
- sort.Strings(keys)
- var out []NIC
- for _, k := range keys {
- s, ok := cfg[k].(string)
- if !ok {
- continue
- }
- var nic NIC
- for _, field := range strings.Split(s, ",") {
- switch {
- case strings.HasPrefix(field, "hwaddr="):
- nic.MAC = normMAC(field[len("hwaddr="):])
- case strings.HasPrefix(field, "bridge="):
- nic.Bridge = field[len("bridge="):]
- case strings.HasPrefix(field, "tag="):
- if n, err := strconv.Atoi(field[len("tag="):]); err == nil && n > 0 && n < 4095 {
- nic.Tag = n
- }
- default:
- // QEMU: el primer campo es <modelo>=<MAC> (virtio=XX, e1000=XX…)
- if eq := strings.Index(field, "="); eq > 0 {
- if looksLikeMAC(field[eq+1:]) {
- nic.MAC = normMAC(field[eq+1:])
- }
- }
- }
- }
- if nic.MAC != "" {
- out = append(out, nic)
- }
- }
- return out
- }
- // MACsOfConfig extrae las MACs de una config de VM/CT (ver NICsOfConfig).
- func MACsOfConfig(cfg map[string]any) []string {
- nics := NICsOfConfig(cfg)
- if len(nics) == 0 {
- return nil
- }
- out := make([]string, 0, len(nics))
- for _, n := range nics {
- out = append(out, n.MAC)
- }
- return out
- }
- // looksLikeMAC comprueba si el valor de un campo key=value de netN es una MAC
- // con separadores (17 caracteres) para distinguirlo de otras opciones de NIC.
- func looksLikeMAC(s string) bool {
- return macaddr.NormalizeSeparated(s) != ""
- }
- func normMAC(s string) string {
- return macaddr.Normalize(s)
- }
- // TestResult is what a connection test can tell the user about an endpoint.
- type TestResult struct {
- // Version: the PVE release string ("8.4.21").
- Version string `json:"version"`
- Nodes int `json:"nodes"`
- VMs int `json:"vms"`
- CTs int `json:"cts"`
- // Limited: the token authenticates but Proxmox is filtering the listings
- // because the token has no audit rights. This is the failure the test
- // exists for: PVE does not reject a list a token may not see, it returns
- // it empty with HTTP 200, so an under-privileged token looks exactly
- // like a cluster with no guests and the integration goes quiet.
- Limited bool `json:"limited"`
- }
- // Test checks an endpoint the way a user needs it checked: can we reach it,
- // does the token authenticate, and can it actually see anything.
- func (c *Client) Test(ctx context.Context) (*TestResult, error) {
- if !c.cfg.Enabled() {
- return nil, fmt.Errorf("missing url, tokenId or secret")
- }
- var version struct {
- Version string `json:"version"`
- Release string `json:"release"`
- }
- // /version needs no privileges: it separates "unreachable or bad token"
- // from "authenticated but blind", which are different problems.
- if err := c.get(ctx, "/api2/json/version", &version); err != nil {
- return nil, err
- }
- out := &TestResult{Version: version.Version}
- if out.Version == "" {
- out.Version = version.Release
- }
- resources, err := c.ClusterResources(ctx)
- if err != nil {
- return nil, err
- }
- var firstNode string
- for _, r := range resources {
- switch r.Type {
- case "node":
- out.Nodes++
- if firstNode == "" {
- firstNode = r.Node
- }
- case "qemu":
- out.VMs++
- case "lxc":
- out.CTs++
- }
- }
- // Nothing to seal: is the cluster empty, or is the token blind? Ask for
- // something that needs Sys.Audit and read the answer. A 403 proves the
- // token lacks the rights, and the user gets told which ones.
- if out.VMs == 0 && out.CTs == 0 && firstNode != "" {
- var status map[string]any
- if err := c.get(ctx, "/api2/json/nodes/"+url.PathEscape(firstNode)+"/status", &status); err != nil &&
- strings.Contains(err.Error(), "HTTP 403") {
- out.Limited = true
- }
- }
- return out, nil
- }
- // ClusterNode is one entry of /cluster/status: the address corosync knows a
- // node by, which is the node's real address on the network.
- type ClusterNode struct {
- Type string `json:"type"` // "node" | "cluster"
- Name string `json:"name"`
- IP string `json:"ip"`
- }
- // ClusterStatus: GET /api2/json/cluster/status → node name and IP.
- //
- // This is where a node's address actually lives. /nodes/{node}/network only
- // reports what /etc/network/interfaces declares, so a host whose management
- // address is configured outside it -- DHCP on the NIC, systemd-networkd, a
- // setup with no bridge in that file -- lists its interfaces with no address
- // at all and offers nothing to match the host device by.
- //
- // Needs Sys.Audit on "/"; a token without it gets a 403 and the caller
- // falls back to the interface listing.
- func (c *Client) ClusterStatus(ctx context.Context) ([]ClusterNode, error) {
- var out []ClusterNode
- if err := c.get(ctx, "/api2/json/cluster/status", &out); err != nil {
- return nil, err
- }
- return out, nil
- }
- // HostOfURL: the host part of the configured endpoint, with no port. For a
- // single-node instance that is the node's address, and it is the last
- // resort when the API will not say what its own address is.
- func (c *Client) HostOfURL() string {
- u, err := url.Parse(c.cfg.URL)
- if err != nil {
- return ""
- }
- return u.Hostname()
- }
|