From 73a7ca0eb97bb21dfb093fbd9f74acc79af8258a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 19:59:36 -0600 Subject: [PATCH 1/3] feat(redfish): Add BMC key pinning and inventory read Add PinnedTLSConfig and NewPinnedClient, which verify a BMC by the SHA-256 of its leaf SubjectPublicKeyInfo instead of the system trust store, through the existing transport guard. Add Probe, an anonymous handshake and service root GET that records the presented key, and Client.Inventory, a GET-only lenient read of Managers, Systems and their EthernetInterfaces. The executor's behavior is unchanged. Co-Authored-By: Claude Opus 5.5 --- internal/redfish/client.go | 12 ++ internal/redfish/inventory.go | 255 ++++++++++++++++++++++++++++++++++ internal/redfish/pin.go | 172 +++++++++++++++++++++++ internal/redfish/pin_test.go | 189 +++++++++++++++++++++++++ 4 files changed, 628 insertions(+) create mode 100644 internal/redfish/inventory.go create mode 100644 internal/redfish/pin.go create mode 100644 internal/redfish/pin_test.go diff --git a/internal/redfish/client.go b/internal/redfish/client.go index 3109d62f..d3e6576a 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -16,6 +16,7 @@ package redfish import ( "context" + "crypto/tls" "encoding/json" "errors" "fmt" @@ -77,6 +78,12 @@ func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, if err != nil { return nil, err } + return newClient(endpoint, user, password, timeout, nil) +} + +// newClient builds the guarded client for a canonical endpoint. A nil +// tlsConfig keeps the system trust store. +func newClient(endpoint, user, password string, timeout time.Duration, tlsConfig *tls.Config) (*Client, error) { u, _ := url.Parse(endpoint) if user == "" || password == "" || strings.ContainsAny(user, ":\r\n") || strings.ContainsAny(password, "\r\n") { return nil, errors.New("redfish credential must be a nonempty single-line username and password") @@ -86,6 +93,9 @@ func NewClient(endpoint, user, password string, timeout time.Duration) (*Client, } transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil + if tlsConfig != nil { + transport.TLSClientConfig = tlsConfig + } return &Client{config: gofish.ClientConfig{ Endpoint: u.Scheme + "://" + u.Host, Username: user, Password: password, // Basic authentication: creating a session would itself be a BMC @@ -169,6 +179,8 @@ func classify(err error) error { switch { case err == nil: return nil + case errors.Is(err, ErrPinMismatch): + return ErrPinMismatch case errors.Is(err, ErrIdentity): return fmt.Errorf("%w: unexpected resource path", ErrIdentity) case errors.As(err, &rf) && (rf.HTTPReturnedStatusCode == http.StatusUnauthorized || rf.HTTPReturnedStatusCode == http.StatusForbidden): diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go new file mode 100644 index 00000000..ac95f211 --- /dev/null +++ b/internal/redfish/inventory.go @@ -0,0 +1,255 @@ +package redfish + +import ( + "context" + "encoding/json" + "errors" + "net" + "strings" + + "github.com/stmcginnis/gofish" + "github.com/stmcginnis/gofish/schemas" +) + +// Inventory bounds. A BMC that reports more is read only up to these limits. +const ( + maxInventoryMembers = 16 + maxInventoryInterfaces = 32 + maxCollectionPages = 8 +) + +// Inventory is a read-only observation of what a BMC reports about itself and +// the Systems it manages. +type Inventory struct { + Managers []Manager + Systems []InventorySystem +} + +// Manager is one Redfish Manager: the BMC itself. +type Manager struct { + ID string + Model string + FirmwareVersion string + NetworkInterfaces []NetworkInterface +} + +// InventorySystem is one ComputerSystem's identity and observed power state. +type InventorySystem struct { + ID string + UUID string + Manufacturer string + Model string + SerialNumber string + SKU string + PowerState string + // NetworkInterfaces are the System's EthernetInterfaces. + NetworkInterfaces []NetworkInterface +} + +// NetworkInterface is one Redfish EthernetInterface. +type NetworkInterface struct { + ID string + MACAddress string + LinkStatus string + SpeedMbps int64 +} + +// Inventory reads the service root, every Manager and every ComputerSystem +// with their EthernetInterfaces. It issues GETs only and never follows an +// action, so it cannot change power, boot or any setting. Documents are +// decoded leniently: only the named properties are read, and a vendor +// property with an off-schema type elsewhere in a document is ignored. Any +// failed read fails the whole observation; nothing partial is returned. +func (c *Client) Inventory(ctx context.Context) (Inventory, error) { + api, err := c.connect(ctx) + if err != nil { + return Inventory{}, err + } + var root struct { + Systems, Managers link + } + if err := getJSON(api, schemas.DefaultServiceRoot, &root); err != nil { + return Inventory{}, err + } + var inv Inventory + if root.Managers.ID != "" { + paths, err := members(api, root.Managers.ID, maxInventoryMembers) + if err != nil { + return Inventory{}, err + } + for _, p := range paths { + var doc struct { + ID string `json:"Id"` + Model string + FirmwareVersion string + EthernetInterfaces link + } + if err := getJSON(api, p, &doc); err != nil { + return Inventory{}, err + } + nics, err := interfaces(api, p, doc.EthernetInterfaces.ID) + if err != nil { + return Inventory{}, err + } + inv.Managers = append(inv.Managers, Manager{ID: doc.ID, Model: doc.Model, FirmwareVersion: doc.FirmwareVersion, NetworkInterfaces: nics}) + } + } + if root.Systems.ID != "" { + paths, err := members(api, root.Systems.ID, maxInventoryMembers) + if err != nil { + return Inventory{}, err + } + for _, p := range paths { + var doc struct { + ID string `json:"Id"` + UUID string + Manufacturer string + Model string + SerialNumber string + SKU string + PowerState string + EthernetInterfaces link + } + if err := getJSON(api, p, &doc); err != nil { + return Inventory{}, err + } + nics, err := interfaces(api, p, doc.EthernetInterfaces.ID) + if err != nil { + return Inventory{}, err + } + inv.Systems = append(inv.Systems, InventorySystem{ID: doc.ID, UUID: canonicalUUID(doc.UUID), Manufacturer: doc.Manufacturer, + Model: doc.Model, SerialNumber: doc.SerialNumber, SKU: doc.SKU, PowerState: doc.PowerState, NetworkInterfaces: nics}) + } + } + return inv, nil +} + +type link struct { + ID string `json:"@odata.id"` +} + +func getJSON(api *gofish.APIClient, path string, out any) error { + if _, err := cleanPath(path); err != nil { + return err + } + resp, err := api.Get(path) + if err == nil { + err = json.NewDecoder(resp.Body).Decode(out) + } + schemas.DeferredCleanupHTTPResponse(resp) + return classify(err) +} + +// members returns up to limit member paths of a collection, following +// Members@odata.nextLink pages. Every member must sit under the collection. +func members(api *gofish.APIClient, collection string, limit int) ([]string, error) { + base, err := cleanPath(collection) + if err != nil { + return nil, err + } + var out []string + next := base + for page := 0; next != "" && page < maxCollectionPages && len(out) < limit; page++ { + var doc struct { + Members []link + NextLink string `json:"Members@odata.nextLink"` + } + path, query, _ := strings.Cut(next, "?") + if _, err := cleanPath(path); err != nil || (path != base && !strings.HasPrefix(path, base+"/")) { + return nil, errors.New("redfish: collection page outside the collection") + } + if query != "" { + path += "?" + query + } + resp, err := api.Get(path) + if err == nil { + err = json.NewDecoder(resp.Body).Decode(&doc) + } + schemas.DeferredCleanupHTTPResponse(resp) + if err != nil { + return nil, classify(err) + } + for _, m := range doc.Members { + p, err := cleanPath(m.ID) + if err != nil || !strings.HasPrefix(p, base+"/") { + return nil, errors.New("redfish: collection member outside the collection") + } + if len(out) < limit { + out = append(out, p) + } + } + next = doc.NextLink + } + return out, nil +} + +// interfaces reads an EthernetInterfaces collection that must belong to owner. +func interfaces(api *gofish.APIClient, owner, collection string) ([]NetworkInterface, error) { + if collection == "" { + return nil, nil + } + if p, err := cleanPath(collection); err != nil || !strings.HasPrefix(p, owner+"/") { + return nil, errors.New("redfish: EthernetInterfaces outside its owner") + } + paths, err := members(api, collection, maxInventoryInterfaces) + if err != nil { + return nil, err + } + var out []NetworkInterface + for _, p := range paths { + var doc struct { + ID string `json:"Id"` + MACAddress string + PermanentMACAddress string + LinkStatus string + SpeedMbps *json.Number + InterfaceEnabledFlag *bool `json:"InterfaceEnabled"` + } + if err := getJSON(api, p, &doc); err != nil { + return nil, err + } + mac := canonicalMAC(doc.PermanentMACAddress) + if mac == "" { + mac = canonicalMAC(doc.MACAddress) + } + nic := NetworkInterface{ID: doc.ID, MACAddress: mac, LinkStatus: doc.LinkStatus} + if doc.SpeedMbps != nil { + if v, err := doc.SpeedMbps.Int64(); err == nil && v >= 0 { + nic.SpeedMbps = v + } + } + out = append(out, nic) + } + return out, nil +} + +// canonicalMAC returns a 48-bit MAC in lowercase colon form, or "" when the +// value is not one (including the all-zero placeholder some BMCs report). +func canonicalMAC(s string) string { + hw, err := net.ParseMAC(strings.TrimSpace(s)) + if err != nil || len(hw) != 6 || hw.String() == "00:00:00:00:00:00" { + return "" + } + return hw.String() +} + +// canonicalUUID returns the SMBIOS UUID in lowercase canonical form, or "". +func canonicalUUID(s string) string { + s = strings.ToLower(strings.TrimSpace(s)) + if len(s) != 36 { + return "" + } + for i, r := range s { + switch i { + case 8, 13, 18, 23: + if r != '-' { + return "" + } + default: + if !strings.ContainsRune("0123456789abcdef", r) { + return "" + } + } + } + return s +} diff --git a/internal/redfish/pin.go b/internal/redfish/pin.go new file mode 100644 index 00000000..3f074347 --- /dev/null +++ b/internal/redfish/pin.go @@ -0,0 +1,172 @@ +package redfish + +import ( + "bytes" + "context" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// ErrPinMismatch means the BMC presented a TLS public key other than the +// approved pin. The handshake is aborted before any request, so no credential +// is sent. +var ErrPinMismatch = errors.New("redfish: BMC TLS public key does not match the approved pin") + +// PublicKeySHA256 returns the lowercase hex SHA-256 of the certificate's DER +// SubjectPublicKeyInfo. It is the same value as +// +// openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | sha256sum +// +// and stays the same when a BMC reissues its certificate for the same key. +func PublicKeySHA256(cert *x509.Certificate) string { + sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +// ParsePin accepts 64 hex digits, optionally colon-separated and in either +// case, and returns the lowercase form PublicKeySHA256 produces. +func ParsePin(pin string) (string, error) { + pin = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(pin), ":", "")) + if b, err := hex.DecodeString(pin); err != nil || len(b) != sha256.Size { + return "", errors.New("redfish: TLS pin must be a SHA-256 of the public key in hex") + } + return pin, nil +} + +// PinnedTLSConfig verifies the peer by its leaf public key alone. BMC +// certificates are commonly self-signed and share a subject across a fleet, so +// chain and hostname verification are replaced, not added to: the handshake +// succeeds only when the leaf SubjectPublicKeyInfo hashes to pin. +func PinnedTLSConfig(pin string) (*tls.Config, error) { + pin, err := ParsePin(pin) + if err != nil { + return nil, err + } + return &tls.Config{ + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: true, // replaced by the pin check in VerifyConnection + VerifyConnection: func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) == 0 || PublicKeySHA256(cs.PeerCertificates[0]) != pin { + return ErrPinMismatch + } + return nil + }, + }, nil +} + +// NewPinnedClient is NewClient over https with the peer verified by +// PinnedTLSConfig instead of the system trust store. Every request opens a new +// connection, so every request re-checks the pin before it is written. +func NewPinnedClient(endpoint, user, password, pin string, timeout time.Duration) (*Client, error) { + canonical, err := ParseEndpoint(endpoint) + if err != nil { + return nil, err + } + if !strings.HasPrefix(canonical, "https://") { + return nil, errors.New("redfish: a pinned client requires an https endpoint") + } + config, err := PinnedTLSConfig(pin) + if err != nil { + return nil, err + } + return newClient(canonical, user, password, timeout, config) +} + +// Certificate is what a BMC's TLS handshake revealed about its leaf +// certificate. +type Certificate struct { + PublicKeySHA256 string + NotAfter time.Time + SelfSigned bool +} + +// ServiceRoot holds the anonymous service root facts a probe reads. +type ServiceRoot struct { + RedfishVersion string + UUID string + Vendor string + Product string +} + +// ErrNoHandshake means a probe did not complete a TLS handshake. +var ErrNoHandshake = errors.New("redfish: TLS handshake not completed") + +// Probe completes a TLS handshake with any certificate, records it, and issues +// one anonymous GET of the service root through the same guard as every other +// request. It holds no credential, so it cannot send one, which is what makes +// accepting an unverified certificate here safe. The certificate is returned +// whenever the handshake completed, even if the GET failed; otherwise the +// error is ErrNoHandshake. +func Probe(ctx context.Context, endpoint string, timeout time.Duration) (Certificate, ServiceRoot, error) { + canonical, err := ParseEndpoint(endpoint) + if err != nil { + return Certificate{}, ServiceRoot{}, err + } + if !strings.HasPrefix(canonical, "https://") || timeout <= 0 { + return Certificate{}, ServiceRoot{}, errors.New("redfish: a probe requires an https endpoint and a positive timeout") + } + u, _ := url.Parse(canonical) + var ( + mu sync.Mutex + leaf *x509.Certificate + ) + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + transport.DisableKeepAlives = true + transport.TLSClientConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: true, // observed, not trusted: no credential is held + VerifyConnection: func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) == 0 { + return ErrNoHandshake + } + mu.Lock() + leaf = cs.PeerCertificates[0] + mu.Unlock() + return nil + }, + } + httpClient := &http.Client{Timeout: timeout, Transport: guard{scheme: u.Scheme, host: u.Host, next: transport}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, canonical+"/redfish/v1/", nil) + if err != nil { + return Certificate{}, ServiceRoot{}, err + } + req.Header.Set("Accept", "application/json") + resp, getErr := httpClient.Do(req) + var root struct { + RedfishVersion, UUID, Vendor, Product string + } + if getErr == nil { + if resp.StatusCode/100 != 2 { + getErr = Status{resp.StatusCode} + } else if err := json.NewDecoder(resp.Body).Decode(&root); err != nil { + getErr = errors.New("redfish: transport failure or unreadable response") + } + resp.Body.Close() + } + mu.Lock() + defer mu.Unlock() + if leaf == nil { + return Certificate{}, ServiceRoot{}, ErrNoHandshake + } + cert := Certificate{PublicKeySHA256: PublicKeySHA256(leaf), NotAfter: leaf.NotAfter.UTC(), + SelfSigned: bytes.Equal(leaf.RawIssuer, leaf.RawSubject) && leaf.CheckSignature(leaf.SignatureAlgorithm, leaf.RawTBSCertificate, leaf.Signature) == nil} + if getErr != nil { + var status Status + if !errors.As(getErr, &status) { + getErr = errors.New("redfish: transport failure or unreadable response") + } + return cert, ServiceRoot{}, getErr + } + return cert, ServiceRoot{RedfishVersion: root.RedfishVersion, UUID: strings.ToLower(root.UUID), Vendor: root.Vendor, Product: root.Product}, nil +} diff --git a/internal/redfish/pin_test.go b/internal/redfish/pin_test.go new file mode 100644 index 00000000..02d0e836 --- /dev/null +++ b/internal/redfish/pin_test.go @@ -0,0 +1,189 @@ +package redfish + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// inventoryBMC is a TLS Redfish service that records every request and +// whether it carried a credential. +type inventoryBMC struct { + mu sync.Mutex + requests []string + authed []bool + docs map[string]any +} + +func newInventoryBMC() *inventoryBMC { + nic := func(owner, id, mac string) map[string]any { + return map[string]any{"@odata.id": owner + "/EthernetInterfaces/" + id, "Id": id, "MACAddress": mac, "LinkStatus": "LinkUp", "SpeedMbps": 25000, + // An off-schema vendor property must not fail the lenient decode. + "Oem": map[string]any{"Vendor": map[string]any{"Speed": "fast"}}} + } + return &inventoryBMC{docs: map[string]any{ + "/redfish/v1/": map[string]any{"@odata.id": "/redfish/v1", "RedfishVersion": "1.15.0", "UUID": "00000000-0000-4000-8000-0000000000AA", "Vendor": "Example", + "Systems": map[string]string{"@odata.id": "/redfish/v1/Systems"}, "Managers": map[string]string{"@odata.id": "/redfish/v1/Managers"}}, + "/redfish/v1/Managers": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Managers/BMC"}}}, + "/redfish/v1/Managers/BMC": map[string]any{"Id": "BMC", "Model": "Example BMC", "FirmwareVersion": "1.2.3", + "EthernetInterfaces": map[string]string{"@odata.id": "/redfish/v1/Managers/BMC/EthernetInterfaces"}}, + "/redfish/v1/Managers/BMC/EthernetInterfaces": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Managers/BMC/EthernetInterfaces/1"}}}, + "/redfish/v1/Managers/BMC/EthernetInterfaces/1": nic("/redfish/v1/Managers/BMC", "1", "00-00-5E-00-53-10"), + "/redfish/v1/Systems": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/1"}}}, + "/redfish/v1/Systems/1": map[string]any{"Id": "1", "UUID": "00000000-0000-4000-8000-00000000000A", "Manufacturer": "Example Vendor", + "Model": "Example 1U", "SerialNumber": "SYNTHETIC-0001", "SKU": "TAG0001", "PowerState": "Off", "Boot": map[string]any{"BootSourceOverrideTarget": 7}, + "EthernetInterfaces": map[string]string{"@odata.id": "/redfish/v1/Systems/1/EthernetInterfaces"}}, + "/redfish/v1/Systems/1/EthernetInterfaces": map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Systems/1/EthernetInterfaces/NIC.1"}}}, + "/redfish/v1/Systems/1/EthernetInterfaces/NIC.1": nic("/redfish/v1/Systems/1", "NIC.1", "00:00:5E:00:53:01"), + }} +} + +func (b *inventoryBMC) ServeHTTP(w http.ResponseWriter, r *http.Request) { + _, _, authed := r.BasicAuth() + b.mu.Lock() + b.requests = append(b.requests, r.Method+" "+r.URL.Path) + b.authed = append(b.authed, authed) + doc, ok := b.docs[r.URL.Path] + b.mu.Unlock() + if user, pass, _ := r.BasicAuth(); r.URL.Path != "/redfish/v1/" && (user != "operator" || pass != "synthetic-secret") { + w.WriteHeader(http.StatusUnauthorized) + return + } + if !ok || r.Method != http.MethodGet { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(doc) +} + +func (b *inventoryBMC) seen() ([]string, []bool) { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.requests...), append([]bool(nil), b.authed...) +} + +func tlsBMC(t *testing.T) (*inventoryBMC, *httptest.Server, string) { + t.Helper() + bmc := newInventoryBMC() + server := httptest.NewTLSServer(bmc) + t.Cleanup(server.Close) + return bmc, server, PublicKeySHA256(server.Certificate()) +} + +func TestParsePin(t *testing.T) { + pin := strings.Repeat("Ab", 32) + for _, in := range []string{pin, " " + pin + "\n", strings.ToUpper(pin)} { + if got, err := ParsePin(in); err != nil || got != strings.ToLower(pin) { + t.Fatalf("ParsePin(%q) = %q, %v", in, got, err) + } + } + colons := strings.TrimSuffix(strings.Repeat("ab:", 32), ":") + if got, err := ParsePin(colons); err != nil || got != strings.Repeat("ab", 32) { + t.Fatalf("colon form = %q, %v", got, err) + } + for _, bad := range []string{"", "ab", strings.Repeat("zz", 32), strings.Repeat("ab", 31)} { + if _, err := ParsePin(bad); err == nil { + t.Fatalf("ParsePin(%q) accepted", bad) + } + } +} + +func TestProbeRecordsTheKeyAnonymously(t *testing.T) { + bmc, server, pin := tlsBMC(t) + cert, root, err := Probe(context.Background(), server.URL, 5*time.Second) + if err != nil { + t.Fatal(err) + } + if cert.PublicKeySHA256 != pin || !cert.NotAfter.Equal(server.Certificate().NotAfter) || !cert.SelfSigned { + t.Fatalf("certificate = %+v, want pin %s", cert, pin) + } + if root.RedfishVersion != "1.15.0" || root.UUID != "00000000-0000-4000-8000-0000000000aa" || root.Vendor != "Example" { + t.Fatalf("service root = %+v", root) + } + requests, authed := bmc.seen() + if len(requests) != 1 || requests[0] != "GET /redfish/v1/" || authed[0] { + t.Fatalf("probe sent %v (credential %v), want one anonymous GET of the service root", requests, authed) + } +} + +func TestProbeWithoutHandshake(t *testing.T) { + server := httptest.NewServer(http.NotFoundHandler()) // plain HTTP: no TLS handshake + defer server.Close() + endpoint := "https://" + strings.TrimPrefix(server.URL, "http://") + if _, _, err := Probe(context.Background(), endpoint, 2*time.Second); !errors.Is(err, ErrNoHandshake) { + t.Fatalf("err = %v, want ErrNoHandshake", err) + } + if _, _, err := Probe(context.Background(), server.URL, 2*time.Second); err == nil { + t.Fatal("probe accepted a plain http endpoint") + } +} + +func TestPinnedClientReadsInventoryWithTheApprovedPin(t *testing.T) { + bmc, server, pin := tlsBMC(t) + c, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", strings.ToUpper(pin), 5*time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := c.Inventory(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(inv.Managers) != 1 || inv.Managers[0].FirmwareVersion != "1.2.3" || inv.Managers[0].NetworkInterfaces[0].MACAddress != "00:00:5e:00:53:10" { + t.Fatalf("managers = %+v", inv.Managers) + } + s := inv.Systems + if len(s) != 1 || s[0].UUID != "00000000-0000-4000-8000-00000000000a" || s[0].SerialNumber != "SYNTHETIC-0001" || s[0].SKU != "TAG0001" || + s[0].PowerState != "Off" || len(s[0].NetworkInterfaces) != 1 || s[0].NetworkInterfaces[0].MACAddress != "00:00:5e:00:53:01" || s[0].NetworkInterfaces[0].SpeedMbps != 25000 { + t.Fatalf("systems = %+v", s) + } + requests, _ := bmc.seen() + for _, r := range requests { + if !strings.HasPrefix(r, "GET ") { + t.Fatalf("inventory issued %s; discovery is GET only", r) + } + } +} + +func TestPinMismatchSendsNoRequest(t *testing.T) { + bmc, server, pin := tlsBMC(t) + other := strings.Repeat("0", 64) + if other == pin { + t.Fatal("synthetic pin collided") + } + c, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", other, 5*time.Second) + if err != nil { + t.Fatal(err) + } + if _, err := c.Inventory(context.Background()); !errors.Is(err, ErrPinMismatch) { + t.Fatalf("err = %v, want ErrPinMismatch", err) + } + // The handshake fails before any request is written, so the server never + // sees one, let alone a credential. + if requests, _ := bmc.seen(); len(requests) != 0 { + t.Fatalf("server received %v with a mismatched pin", requests) + } +} + +func TestPinnedClientRequiresHTTPSAndAPin(t *testing.T) { + if _, err := NewPinnedClient("http://192.0.2.10:80", "operator", "synthetic-secret", strings.Repeat("ab", 32), time.Second); err == nil { + t.Fatal("pinned client accepted http") + } + if _, err := NewPinnedClient("https://192.0.2.10:443", "operator", "synthetic-secret", "", time.Second); err == nil { + t.Fatal("pinned client accepted an empty pin") + } +} + +func TestInventoryRejectsForeignLinks(t *testing.T) { + bmc, server, pin := tlsBMC(t) + bmc.docs["/redfish/v1/Systems"] = map[string]any{"Members": []any{map[string]string{"@odata.id": "/redfish/v1/Managers/BMC"}}} + c, _ := NewPinnedClient(server.URL, "operator", "synthetic-secret", pin, 5*time.Second) + if _, err := c.Inventory(context.Background()); err == nil { + t.Fatal("a System member outside the Systems collection was accepted") + } +} From a5fce8f967cdc1de1ae11d5d654de9c0b40325e8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 19:59:36 -0600 Subject: [PATCH 2/3] feat(inventory): Add Device discovery status Device status now holds retained BMC observations (TLS key, service root, inventory) and Reachable, Authenticated, Discovered, IdentityMatched and PublicKeyUnique conditions. Spec identity stays authoritative and immutable. The Device ProtectedResource declares updateStatus and the status subresource, and the new inventory-discoverer role grants Device reads and status writes only. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 105 +++++++++++++++++ .../inventory/protected-resources/device.yaml | 8 +- .../inventory/roles/discoverer.yaml | 17 +++ .../inventory/roles/kustomization.yaml | 1 + internal/api/inventory/v1alpha1/crd_test.go | 59 ++++++++-- internal/api/inventory/v1alpha1/iam_test.go | 49 +++++++- internal/api/inventory/v1alpha1/types.go | 108 ++++++++++++++++-- 7 files changed, 326 insertions(+), 21 deletions(-) create mode 100644 config/components/inventory/roles/discoverer.yaml diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 49936808..0118a920 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -230,6 +230,14 @@ spec: type: boolean priority: 1 jsonPath: .spec.identity.unidentified + - name: Discovered + type: string + priority: 1 + jsonPath: .status.conditions[?(@.type=="Discovered")].status + - name: Identity + type: string + priority: 1 + jsonPath: .status.conditions[?(@.type=="IdentityMatched")].reason - name: Age type: date jsonPath: .metadata.creationTimestamp @@ -625,6 +633,103 @@ spec: - Half status: type: object + description: Written only by read-only BMC discovery through the status subresource. Observations are evidence; spec stays authoritative. + properties: + observedGeneration: + type: integer + format: int64 + minimum: 0 + discovery: + type: object + properties: + lastAttemptAt: {type: string, format: date-time} + lastAttemptEndpoint: {type: string, maxLength: 2048} + tls: + type: object + required: [observedAt, endpoint, publicKeySHA256] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + publicKeySHA256: {type: string, pattern: '^[0-9a-f]{64}$'} + notAfter: {type: string, format: date-time} + selfSigned: {type: boolean} + serviceRoot: + type: object + required: [observedAt, endpoint] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + redfishVersion: {type: string, maxLength: 63} + uuid: {type: string, maxLength: 36} + vendor: {type: string, maxLength: 253} + product: {type: string, maxLength: 253} + inventory: + type: object + required: [observedAt, endpoint] + properties: + observedAt: {type: string, format: date-time} + endpoint: {type: string, maxLength: 2048} + managers: + type: array + maxItems: 16 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + model: {type: string, maxLength: 253} + firmwareVersion: {type: string, maxLength: 253} + networkInterfaces: + type: array + maxItems: 32 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + linkStatus: {type: string, maxLength: 63} + speedMbps: {type: integer, minimum: 0, maximum: 100000000} + systems: + type: array + maxItems: 16 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + uuid: {type: string, pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'} + manufacturer: {type: string, maxLength: 253} + model: {type: string, maxLength: 253} + serialNumber: {type: string, maxLength: 253} + sku: {type: string, maxLength: 253} + powerState: {type: string, maxLength: 63} + networkInterfaces: + type: array + maxItems: 32 + items: + type: object + required: [id] + properties: + id: {type: string, minLength: 1, maxLength: 253} + macAddress: {type: string, maxLength: 17, pattern: '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'} + linkStatus: {type: string, maxLength: 63} + speedMbps: {type: integer, minimum: 0, maximum: 100000000} + conditions: + type: array + maxItems: 8 + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [type] + items: + type: object + required: [type, status, lastTransitionTime, reason, message] + properties: + type: {type: string, minLength: 1, maxLength: 316, pattern: '^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$'} + status: {type: string, enum: ['True', 'False', 'Unknown']} + observedGeneration: {type: integer, format: int64, minimum: 0} + lastTransitionTime: {type: string, format: date-time} + reason: {type: string, minLength: 1, maxLength: 1024, pattern: '^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$'} + message: {type: string, maxLength: 32768} --- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition diff --git a/config/components/inventory/protected-resources/device.yaml b/config/components/inventory/protected-resources/device.yaml index 78bdacfa..8ca7e516 100644 --- a/config/components/inventory/protected-resources/device.yaml +++ b/config/components/inventory/protected-resources/device.yaml @@ -8,7 +8,13 @@ spec: kind: Device plural: devices singular: device - permissions: [list, get, watch, create, update, patch, delete] + # updateStatus is held only by the discoverer role. With subresource + # authorization enabled, status writes use devices/status.update and + # devices/status.patch instead. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] parentResources: - apiGroup: resourcemanager.miloapis.com kind: Project diff --git a/config/components/inventory/roles/discoverer.yaml b/config/components/inventory/roles/discoverer.yaml new file mode 100644 index 00000000..0eec5bf9 --- /dev/null +++ b/config/components/inventory/roles/discoverer.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-inventory-discoverer + annotations: + kubernetes.io/display-name: Fleet Inventory Discoverer + kubernetes.io/description: Read Devices and write only what their BMCs report into Device status +spec: + launchStage: Alpha + # Deliberately not the viewer role: discovery reads Devices only. + includedPermissions: + - fleet.datumapis.com/devices.get + - fleet.datumapis.com/devices.list + - fleet.datumapis.com/devices.watch + - fleet.datumapis.com/devices.updateStatus + - fleet.datumapis.com/devices/status.update + - fleet.datumapis.com/devices/status.patch diff --git a/config/components/inventory/roles/kustomization.yaml b/config/components/inventory/roles/kustomization.yaml index 81e649bf..66a0d1f3 100644 --- a/config/components/inventory/roles/kustomization.yaml +++ b/config/components/inventory/roles/kustomization.yaml @@ -5,3 +5,4 @@ resources: - editor.yaml - manager.yaml - importer.yaml + - discoverer.yaml diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go index 41303ce0..c5ede2f8 100644 --- a/internal/api/inventory/v1alpha1/crd_test.go +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -71,9 +71,13 @@ func TestInventoryCRDContract(t *testing.T) { if version.Subresources == nil || version.Subresources.Status == nil { t.Fatalf("%s must reserve status as a separate subresource", kind) } - if status := version.Schema.OpenAPIV3Schema.Properties["status"]; len(status.Properties) != 0 || status.XPreserveUnknownFields != nil { + status := version.Schema.OpenAPIV3Schema.Properties["status"] + if status.XPreserveUnknownFields != nil || (kind != "Device" && len(status.Properties) != 0) { t.Fatalf("%s status must stay empty until a collector or verifier owns it", kind) } + if kind == "Device" && (len(status.Properties) != 3 || status.Properties["discovery"].Type != "object" || status.Properties["conditions"].Type != "array") { + t.Fatalf("Device status must hold exactly observedGeneration, discovery and conditions") + } if crd.Annotations["discovery.miloapis.com/parent-contexts"] != "Project" { t.Fatalf("%s must be served in Milo project control planes", kind) } @@ -396,12 +400,48 @@ func TestReplacementBindsANewDeviceToTheSameClaim(t *testing.T) { } } -func TestStatusAcceptsNoFieldsYet(t *testing.T) { - device := object(t, syntheticDevice()) - device["status"] = map[string]any{"identity": map[string]any{"serial": "SYNTHETIC-0009"}} - if errs := admit(t, "Device", device, nil); len(errs) > 0 { - t.Fatal(errs) +func discoveredDevice() Device { + device := syntheticDevice() + at := metav1.NewTime(baseTime) + nic := []ObservedNetworkInterface{{ID: "1", MACAddress: "00:00:5e:00:53:01", LinkStatus: "LinkUp", SpeedMbps: 25000}} + device.Status = DeviceStatus{ + ObservedGeneration: 1, + Discovery: &DeviceDiscovery{ + LastAttemptAt: &at, LastAttemptEndpoint: "https://192.0.2.100:443", + TLS: &ObservedTLS{ObservedAt: at, Endpoint: "https://192.0.2.100:443", PublicKeySHA256: strings.Repeat("ab", 32), NotAfter: &at, SelfSigned: true}, + ServiceRoot: &ObservedServiceRoot{ObservedAt: at, Endpoint: "https://192.0.2.100:443", RedfishVersion: "1.15.0"}, + Inventory: &ObservedInventory{ObservedAt: at, Endpoint: "https://192.0.2.100:443", + Managers: []ObservedManager{{ID: "BMC", Model: "Example BMC", FirmwareVersion: "1.0", NetworkInterfaces: nic}}, + Systems: []ObservedSystem{{ID: "1", UUID: "00000000-0000-4000-8000-000000000001", Model: "Example 1U", SerialNumber: "SYNTHETIC-0001", + PowerState: "On", NetworkInterfaces: nic}}}, + }, + Conditions: []metav1.Condition{{Type: ConditionDiscovered, Status: metav1.ConditionTrue, Reason: "InventoryRead", Message: "read", LastTransitionTime: at}}, + } + return device +} + +func TestDeviceStatusSchema(t *testing.T) { + if errs := admit(t, "Device", object(t, discoveredDevice()), nil); len(errs) > 0 { + t.Fatalf("discovered status rejected: %v", errs) } + for name, mutate := range map[string]func(*Device){ + "pin not a sha256": func(d *Device) { d.Status.Discovery.TLS.PublicKeySHA256 = "AB" }, + "uppercase uuid": func(d *Device) { d.Status.Discovery.Inventory.Systems[0].UUID = "00000000-0000-4000-8000-00000000000A" }, + "mac not canonical": func(d *Device) { + d.Status.Discovery.Inventory.Systems[0].NetworkInterfaces[0].MACAddress = "00-00-5E-00-53-01" + }, + "condition reason": func(d *Device) { d.Status.Conditions[0].Reason = "" }, + "duplicate conditions": func(d *Device) { d.Status.Conditions = append(d.Status.Conditions, d.Status.Conditions[0]) }, + } { + t.Run(name, func(t *testing.T) { + device := discoveredDevice() + mutate(&device) + if errs := admit(t, "Device", object(t, device), nil); len(errs) == 0 { + t.Fatal("accepted") + } + }) + } + // Status cannot carry identity: an unknown status field is pruned. var schema apiextensions.JSONSchemaProps if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(loadCRDs(t)["Device"].Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { t.Fatal(err) @@ -410,8 +450,11 @@ func TestStatusAcceptsNoFieldsYet(t *testing.T) { if err != nil { t.Fatal(err) } - if structural.Properties["status"].Properties != nil { - t.Fatal("status declares fields") + device := object(t, discoveredDevice()) + device["status"].(map[string]any)["identity"] = map[string]any{"serial": "SYNTHETIC-0009"} + pruning.Prune(device, structural, true) + if _, ok := device["status"].(map[string]any)["identity"]; ok { + t.Fatal("status identity was not pruned") } } diff --git a/internal/api/inventory/v1alpha1/iam_test.go b/internal/api/inventory/v1alpha1/iam_test.go index f43023da..ae1254bd 100644 --- a/internal/api/inventory/v1alpha1/iam_test.go +++ b/internal/api/inventory/v1alpha1/iam_test.go @@ -20,7 +20,11 @@ type protectedResource struct { Plural string `json:"plural"` Singular string `json:"singular"` Permissions []string `json:"permissions"` - Parents []struct { + Subresource []struct { + Name string `json:"name"` + Permissions []string `json:"permissions"` + } `json:"subresources"` + Parents []struct { APIGroup string `json:"apiGroup"` Kind string `json:"kind"` } `json:"parentResources"` @@ -86,8 +90,15 @@ func TestProtectedResourcesMatchTheCRDs(t *testing.T) { if len(resource.Spec.Parents) != 1 || resource.Spec.Parents[0].APIGroup != "resourcemanager.miloapis.com" || resource.Spec.Parents[0].Kind != "Project" { t.Fatalf("%s must be project-scoped", resource.Metadata.Name) } - if slices.Contains(resource.Spec.Permissions, "updateStatus") { - t.Fatalf("%s grants status writes; status has no writer yet", resource.Metadata.Name) + // Device status has one writer, BMC discovery; every other kind's + // status is reserved. + statusWritable := slices.Contains(resource.Spec.Permissions, "updateStatus") || len(resource.Spec.Subresource) != 0 + if resource.Spec.Kind != "Device" && statusWritable { + t.Fatalf("%s grants status writes; its status has no writer", resource.Metadata.Name) + } + if resource.Spec.Kind == "Device" && (!slices.Contains(resource.Spec.Permissions, "updateStatus") || len(resource.Spec.Subresource) != 1 || + resource.Spec.Subresource[0].Name != "status" || !slices.Equal(resource.Spec.Subresource[0].Permissions, []string{"update", "patch"})) { + t.Fatalf("%s must declare updateStatus and the status subresource's update and patch", resource.Metadata.Name) } } } @@ -98,6 +109,11 @@ func TestInventoryRolesSplitReadFromWrite(t *testing.T) { for _, verb := range resource.Spec.Permissions { declared[GroupVersion.Group+"/"+resource.Spec.Plural+"."+verb] = true } + for _, sub := range resource.Spec.Subresource { + for _, verb := range sub.Permissions { + declared[GroupVersion.Group+"/"+resource.Spec.Plural+"/"+sub.Name+"."+verb] = true + } + } } roles := map[string]role{} for _, r := range decodeDir[role](t, filepath.Join(inventoryRoot, "roles")) { @@ -109,9 +125,32 @@ func TestInventoryRolesSplitReadFromWrite(t *testing.T) { "fleet.datumapis.com-inventory-manager": {"create", "update", "patch"}, "fleet.datumapis.com-inventory-importer": {"create", "patch"}, } - if len(roles) != len(wantVerbs) { - t.Fatalf("want exactly viewer, editor, manager and importer roles, got %v", roles) + if len(roles) != len(wantVerbs)+1 { + t.Fatalf("want exactly viewer, editor, manager, importer and discoverer roles, got %v", roles) } + t.Run("fleet.datumapis.com-inventory-discoverer", func(t *testing.T) { + current, ok := roles["fleet.datumapis.com-inventory-discoverer"] + if !ok { + t.Fatal("missing discoverer role") + } + // Reads Devices and writes only their status: no spec verb, no other + // kind, and no inherited role that could add one. + expected := []string{"devices.get", "devices.list", "devices.watch", "devices.updateStatus", "devices/status.update", "devices/status.patch"} + for i := range expected { + expected[i] = GroupVersion.Group + "/" + expected[i] + } + actual := slices.Clone(current.Spec.Included) + slices.Sort(expected) + slices.Sort(actual) + if !slices.Equal(actual, expected) || len(current.Spec.Inherited) != 0 { + t.Fatalf("discoverer permissions = %v inherited %v, want exactly %v", actual, current.Spec.Inherited, expected) + } + for _, permission := range actual { + if !declared[permission] { + t.Fatalf("role permission %s has no ProtectedResource", permission) + } + } + }) for name, verbs := range wantVerbs { t.Run(name, func(t *testing.T) { current, ok := roles[name] diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index cd8cd62c..771a64e5 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -2,10 +2,10 @@ // fleet.datumapis.com. Legacy slot claims retain their historical bindings; // new typed claims describe individual installations without accepting them. // -// All are operator-written records. None has a controller. Registering a -// Device authorizes no hardware effect and creates or changes no -// MachineCapacity. Status is reserved for future collectors and verifiers and -// has no writer. +// All are operator-written records. Registering a Device authorizes no +// hardware effect and creates or changes no MachineCapacity. Device status has +// one writer, read-only BMC discovery (internal/bmcdiscovery); every other +// kind's status is reserved and has no writer. package v1alpha1 import ( @@ -189,9 +189,103 @@ type Interface struct { Peer *PortPeer `json:"peer,omitempty"` } -// DeviceStatus is reserved for collectors and verifiers to report drift and -// mismatch. It never carries identity. Nothing writes it yet. -type DeviceStatus struct{} +// DeviceStatus is what read-only BMC discovery observed, and how it compares +// with spec. BMC discovery is its only writer, through the status subresource; +// it never writes spec. Observed identity here is evidence only: spec.identity +// stays the authoritative, immutable record, and a mismatch is reported as a +// condition, never corrected. +type DeviceStatus struct { + // ObservedGeneration is the spec generation the conditions were computed + // against. + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + // Discovery holds the latest observations. A failed attempt never clears + // them: each keeps its own time and endpoint. + Discovery *DeviceDiscovery `json:"discovery,omitempty"` + // Conditions are Reachable, Authenticated, Discovered, IdentityMatched and + // PublicKeyUnique. + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// Device status condition types and reasons. +const ( + ConditionReachable = "Reachable" + ConditionAuthenticated = "Authenticated" + ConditionDiscovered = "Discovered" + ConditionIdentityMatched = "IdentityMatched" + ConditionPublicKeyUnique = "PublicKeyUnique" +) + +// DeviceDiscovery is the retained BMC observation of a Device. +type DeviceDiscovery struct { + // LastAttemptAt is when discovery last contacted the BMC. + LastAttemptAt *metav1.Time `json:"lastAttemptAt,omitempty"` + // LastAttemptEndpoint is the spec.bmc.endpoint of that attempt. + LastAttemptEndpoint string `json:"lastAttemptEndpoint,omitempty"` + // TLS is the certificate the BMC last presented in an unauthenticated + // handshake. + TLS *ObservedTLS `json:"tls,omitempty"` + // ServiceRoot is the last anonymous read of /redfish/v1. + ServiceRoot *ObservedServiceRoot `json:"serviceRoot,omitempty"` + // Inventory is the last complete authenticated read. + Inventory *ObservedInventory `json:"inventory,omitempty"` +} + +// ObservedTLS identifies the BMC's TLS key. PublicKeySHA256 is the value an +// operator verifies out of band and approves in the credential Secret. +type ObservedTLS struct { + ObservedAt metav1.Time `json:"observedAt"` + Endpoint string `json:"endpoint"` + PublicKeySHA256 string `json:"publicKeySHA256"` + NotAfter *metav1.Time `json:"notAfter,omitempty"` + SelfSigned bool `json:"selfSigned,omitempty"` +} + +// ObservedServiceRoot is the unauthenticated Redfish service root. +type ObservedServiceRoot struct { + ObservedAt metav1.Time `json:"observedAt"` + Endpoint string `json:"endpoint"` + RedfishVersion string `json:"redfishVersion,omitempty"` + UUID string `json:"uuid,omitempty"` + Vendor string `json:"vendor,omitempty"` + Product string `json:"product,omitempty"` +} + +// ObservedInventory is one complete, authenticated, read-only inventory. +type ObservedInventory struct { + ObservedAt metav1.Time `json:"observedAt"` + Endpoint string `json:"endpoint"` + Managers []ObservedManager `json:"managers,omitempty"` + Systems []ObservedSystem `json:"systems,omitempty"` +} + +// ObservedManager is one Redfish Manager, the BMC itself. +type ObservedManager struct { + ID string `json:"id"` + Model string `json:"model,omitempty"` + FirmwareVersion string `json:"firmwareVersion,omitempty"` + NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` +} + +// ObservedSystem is one Redfish ComputerSystem. PowerState is an observation +// only; discovery never changes power. +type ObservedSystem struct { + ID string `json:"id"` + UUID string `json:"uuid,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model,omitempty"` + SerialNumber string `json:"serialNumber,omitempty"` + SKU string `json:"sku,omitempty"` + PowerState string `json:"powerState,omitempty"` + NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` +} + +// ObservedNetworkInterface is one Redfish EthernetInterface. +type ObservedNetworkInterface struct { + ID string `json:"id"` + MACAddress string `json:"macAddress,omitempty"` + LinkStatus string `json:"linkStatus,omitempty"` + SpeedMbps int64 `json:"speedMbps,omitempty"` +} type DeviceClaimList struct { metav1.TypeMeta `json:",inline"` From f96c790b959f81d403c2a0c10ae4ce35c20b6785 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Mon, 23 Nov 2026 19:59:36 -0600 Subject: [PATCH 3/3] feat(bmc-discovery): Discover BMCs into Device status Add fleet-bmc-discovery, a single-replica controller that reads Devices from one Milo project and credential Secrets from its own namespace, probes each BMC anonymously, sends the credential only when the observed key equals the approved pin, and writes only Device status. It retains earlier observations on failure, backs off per Device, spaces contacts per endpoint, reports shared TLS keys, and has a --once mode that prints the statuses without writing. Ship config/base/bmc-discovery, a synthetic credential Secret and sidecar snippet, the binary in the fleet image, the base in the published bundle, and docs/operations/bmc-discovery.md. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 1 + build/manager.Dockerfile | 4 +- cmd/fleet-bmc-discovery/main.go | 79 +++ config/README.md | 9 +- config/base/bmc-discovery/config.yaml | 11 + config/base/bmc-discovery/deployment.yaml | 71 ++ .../examples/credential-secret.yaml | 20 + .../examples/sidecar-container.yaml | 40 ++ config/base/bmc-discovery/kustomization.yaml | 14 + config/base/bmc-discovery/rbac.yaml | 28 + docs/operations/README.md | 1 + docs/operations/bmc-discovery.md | 346 ++++++++++ docs/operations/physical-inventory.md | 12 +- docs/operations/redfish-lab.md | 14 +- internal/bmcdiscovery/config.go | 101 +++ internal/bmcdiscovery/credentials.go | 86 +++ internal/bmcdiscovery/discovery_test.go | 650 ++++++++++++++++++ internal/bmcdiscovery/manifest_test.go | 49 ++ internal/bmcdiscovery/reconciler.go | 172 +++++ internal/bmcdiscovery/runtime.go | 223 ++++++ internal/bmcdiscovery/status.go | 354 ++++++++++ 21 files changed, 2273 insertions(+), 12 deletions(-) create mode 100644 cmd/fleet-bmc-discovery/main.go create mode 100644 config/base/bmc-discovery/config.yaml create mode 100644 config/base/bmc-discovery/deployment.yaml create mode 100644 config/base/bmc-discovery/examples/credential-secret.yaml create mode 100644 config/base/bmc-discovery/examples/sidecar-container.yaml create mode 100644 config/base/bmc-discovery/kustomization.yaml create mode 100644 config/base/bmc-discovery/rbac.yaml create mode 100644 docs/operations/bmc-discovery.md create mode 100644 internal/bmcdiscovery/config.go create mode 100644 internal/bmcdiscovery/credentials.go create mode 100644 internal/bmcdiscovery/discovery_test.go create mode 100644 internal/bmcdiscovery/manifest_test.go create mode 100644 internal/bmcdiscovery/reconciler.go create mode 100644 internal/bmcdiscovery/runtime.go create mode 100644 internal/bmcdiscovery/status.go diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 53cd39c7..5e99dee5 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -64,6 +64,7 @@ jobs: images: | - { path: config/base/manager, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/base/registration, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } + - { path: config/base/bmc-discovery, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/overlays/synthetic-staging, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/components/consumer-ui-plugin, name: ghcr.io/datum-cloud/fleet-consumer-ui-plugin, tag: "${{ needs.publish-consumer-ui-plugin-image.outputs.tag }}" } - { path: config/components/provider-ui-plugin, name: ghcr.io/datum-cloud/fleet-provider-ui-plugin, tag: "${{ needs.publish-provider-ui-plugin-image.outputs.tag }}" } diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 4d0d2328..d6af25cd 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -8,11 +8,13 @@ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-registration ./cmd/fleet-registration \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ - && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager COPY --from=build /out/fleet-registration /fleet-registration COPY --from=build /out/fleet-simulator /fleet-simulator COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync +COPY --from=build /out/fleet-bmc-discovery /fleet-bmc-discovery ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-bmc-discovery/main.go b/cmd/fleet-bmc-discovery/main.go new file mode 100644 index 00000000..100d58dd --- /dev/null +++ b/cmd/fleet-bmc-discovery/main.go @@ -0,0 +1,79 @@ +// fleet-bmc-discovery reads what each Device's BMC reports over read-only +// Redfish GETs and writes it into Device status in one Milo project. It runs +// where the BMC network is reachable, as one replica without leader election. +// With --once it contacts each BMC once and prints the statuses it would +// write, writing nothing to Milo. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + "go.datum.net/fleet/internal/bmcdiscovery" +) + +func main() { + var configPath string + var once bool + flag.StringVar(&configPath, "config", "/etc/fleet/bmc-discovery/config.yaml", "discovery configuration file") + flag.BoolVar(&once, "once", false, "contact each BMC once, print the statuses that would be written, and write nothing to Milo") + zapOptions := zap.Options{Development: false} + zapOptions.BindFlags(flag.CommandLine) + flag.Parse() + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zapOptions))) + if err := run(ctrl.SetupSignalHandler(), configPath, once); err != nil && !errors.Is(err, context.Canceled) { + fmt.Fprintln(os.Stderr, "fleet-bmc-discovery:", err) + os.Exit(1) + } +} + +func run(ctx context.Context, configPath string, once bool) error { + config, err := bmcdiscovery.LoadConfig(configPath) + if err != nil { + return err + } + milo, err := clientcmd.BuildConfigFromFlags("", config.MiloKubeconfig) + if err != nil { + return fmt.Errorf("Milo project kubeconfig: %w", err) + } + var local *rest.Config + if config.LocalKubeconfig != "" { + local, err = clientcmd.BuildConfigFromFlags("", config.LocalKubeconfig) + } else { + local, err = rest.InClusterConfig() + } + if err != nil { + return fmt.Errorf("local cluster config: %w", err) + } + scheme, err := bmcdiscovery.NewScheme() + if err != nil { + return err + } + bmc := bmcdiscovery.RedfishBMC{Timeout: config.RequestTimeout.Duration} + if once { + devices, err := client.New(milo, client.Options{Scheme: scheme}) + if err != nil { + return err + } + secrets, err := client.New(local, client.Options{Scheme: scheme}) + if err != nil { + return err + } + // Reads only: RunOnce takes readers, so no write can reach Milo. + return bmcdiscovery.RunOnce(ctx, config, client.Reader(devices), client.Reader(secrets), bmc, os.Stdout) + } + mgr, err := bmcdiscovery.NewManager(config, milo, local, scheme, bmc) + if err != nil { + return err + } + return mgr.Start(ctx) +} diff --git a/config/README.md b/config/README.md index 3c6187d1..f28af822 100644 --- a/config/README.md +++ b/config/README.md @@ -55,12 +55,19 @@ A price change is a new `-v2` pricing, since a ServicePricing can't be changed. `config/components/inventory` registers the operator-written `DeviceClaim` and `Device` kinds of `fleet.datumapis.com` in Milo: their CRDs, ProtectedResources, -and inventory viewer and editor roles. The production `config/milo` and isolated +and inventory viewer, editor, manager, importer and discoverer roles. The production `config/milo` and isolated non-production `config/milo-synthetic` roots include it; records live in the provider project. `config/inventory` renders the CRDs alone for a legacy management-cluster install and will be removed. See [Planning and registering physical devices](../docs/operations/physical-inventory.md). +`config/base/bmc-discovery` runs read-only BMC discovery for one Milo project +in a cluster that can reach the BMC network: one replica, no leader election, +unprivileged. It is in no root here; the deploying repository applies it with +its namespace, image digest, Milo kubeconfig Secret and configuration. +`examples/` holds a synthetic credential Secret and a sidecar container +snippet. See [BMC discovery](../docs/operations/bmc-discovery.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/base/bmc-discovery/config.yaml b/config/base/bmc-discovery/config.yaml new file mode 100644 index 00000000..106e77ee --- /dev/null +++ b/config/base/bmc-discovery/config.yaml @@ -0,0 +1,11 @@ +# Synthetic values; the deploying repository replaces them. +project: example-provider-project +miloKubeconfig: /var/run/fleet/milo/kubeconfig +deviceNamespaces: [default] +# credentialNamespace defaults to the pod's namespace ($POD_NAMESPACE). +interval: 1h +retryBase: 30s +minContactInterval: 1m +requestTimeout: 20s +concurrency: 4 +healthProbeAddress: ":8081" diff --git a/config/base/bmc-discovery/deployment.yaml b/config/base/bmc-discovery/deployment.yaml new file mode 100644 index 00000000..a7fabe40 --- /dev/null +++ b/config/base/bmc-discovery/deployment.yaml @@ -0,0 +1,71 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-bmc-discovery +spec: + # Exactly one replica and no leader election: two replicas would each + # contact every BMC and race on status. Recreate keeps a rollout from + # briefly running two. + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: fleet-bmc-discovery + template: + metadata: + labels: + app.kubernetes.io/name: fleet-bmc-discovery + spec: + serviceAccountName: fleet-bmc-discovery + # The token is needed to read credential Secrets in this namespace. Set + # localKubeconfig in the config and turn this off to use a mounted + # kubeconfig instead. + automountServiceAccountToken: true + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: bmc-discovery + image: ghcr.io/datum-cloud/fleet:latest + command: [/fleet-bmc-discovery] + args: + - --config=/etc/fleet/bmc-discovery/config.yaml + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + ports: + - name: probes + containerPort: 8081 + livenessProbe: + httpGet: {path: /healthz, port: probes} + readinessProbe: + httpGet: {path: /readyz, port: probes} + resources: + requests: {cpu: 20m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - {name: config, mountPath: /etc/fleet/bmc-discovery, readOnly: true} + - {name: milo, mountPath: /var/run/fleet/milo, readOnly: true} + volumes: + - name: config + configMap: + name: fleet-bmc-discovery-config + # A kubeconfig for the one Milo project, bound to the + # fleet.datumapis.com-inventory-discoverer role. Environment-owned. + - name: milo + secret: + secretName: fleet-bmc-discovery-milo-kubeconfig + defaultMode: 0440 + items: [{key: kubeconfig, path: kubeconfig}] diff --git a/config/base/bmc-discovery/examples/credential-secret.yaml b/config/base/bmc-discovery/examples/credential-secret.yaml new file mode 100644 index 00000000..c832d9dd --- /dev/null +++ b/config/base/bmc-discovery/examples/credential-secret.yaml @@ -0,0 +1,20 @@ +# Synthetic example of one BMC credential Secret. Not part of the base: create +# one per Device, in the namespace where discovery runs, outside Git. +apiVersion: v1 +kind: Secret +metadata: + name: bmc-example-device-01 + labels: + fleet.datumapis.com/bmc-credential: "true" + annotations: + fleet.datumapis.com/device-project: example-provider-project + fleet.datumapis.com/device-namespace: default + fleet.datumapis.com/device-name: example-device-01 +type: Opaque +stringData: + username: example-operator + password: example-password + # Leave unset for first contact. Discovery then records the observed key in + # the Device's status.discovery.tls.publicKeySHA256 and sends nothing. Set + # it only after verifying that value out of band. + # tlsPublicKeySHA256: 0000000000000000000000000000000000000000000000000000000000000000 diff --git a/config/base/bmc-discovery/examples/sidecar-container.yaml b/config/base/bmc-discovery/examples/sidecar-container.yaml new file mode 100644 index 00000000..6c058910 --- /dev/null +++ b/config/base/bmc-discovery/examples/sidecar-container.yaml @@ -0,0 +1,40 @@ +# Synthetic snippet: discovery as one extra container in a pod that already +# reaches the BMC network (for example a VPN gateway pod). Merge it into that +# pod's spec.template.spec. It shares only the network namespace; it needs no +# privilege, capability or other container. The pod's service account needs +# the Role in ../rbac.yaml bound to it, or set localKubeconfig in the config +# and mount a kubeconfig instead. +containers: + - name: bmc-discovery + image: ghcr.io/datum-cloud/fleet@sha256: + command: [/fleet-bmc-discovery] + args: [--config=/etc/fleet/bmc-discovery/config.yaml] + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + resources: + requests: {cpu: 20m, memory: 64Mi} + limits: {memory: 256Mi} + securityContext: + runAsNonRoot: true + runAsUser: 65532 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + seccompProfile: + type: RuntimeDefault + volumeMounts: + - {name: bmc-discovery-config, mountPath: /etc/fleet/bmc-discovery, readOnly: true} + - {name: bmc-discovery-milo, mountPath: /var/run/fleet/milo, readOnly: true} +volumes: + - name: bmc-discovery-config + configMap: + name: fleet-bmc-discovery-config + - name: bmc-discovery-milo + secret: + secretName: fleet-bmc-discovery-milo-kubeconfig + defaultMode: 0440 + items: [{key: kubeconfig, path: kubeconfig}] diff --git a/config/base/bmc-discovery/kustomization.yaml b/config/base/bmc-discovery/kustomization.yaml new file mode 100644 index 00000000..c7c667d9 --- /dev/null +++ b/config/base/bmc-discovery/kustomization.yaml @@ -0,0 +1,14 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +# Read-only BMC discovery for one Milo project. Apply it to a cluster from +# which the BMC network is reachable, in the namespace that holds the +# credential Secrets; the deploying repository sets that namespace, the +# image digest, the Milo kubeconfig Secret and the config values. +# See docs/operations/bmc-discovery.md. +resources: + - rbac.yaml + - deployment.yaml +configMapGenerator: + - name: fleet-bmc-discovery-config + files: + - config.yaml diff --git a/config/base/bmc-discovery/rbac.yaml b/config/base/bmc-discovery/rbac.yaml new file mode 100644 index 00000000..ca8fed6b --- /dev/null +++ b/config/base/bmc-discovery/rbac.yaml @@ -0,0 +1,28 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-bmc-discovery +--- +# Reads credential Secrets in its own namespace only. Kubernetes RBAC cannot +# narrow this to the labelled Secrets, so keep discovery in a namespace that +# holds nothing else it should not read. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-bmc-discovery-credentials +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-bmc-discovery-credentials +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-bmc-discovery-credentials +subjects: + - kind: ServiceAccount + name: fleet-bmc-discovery diff --git a/docs/operations/README.md b/docs/operations/README.md index f0bad0b3..0a6f9ac6 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -18,6 +18,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | +| Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Run the manager across consuming projects | [Project discovery](../../config/README.md#project-discovery) | Discovery, per-project isolation, departure, role bindings, and readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md new file mode 100644 index 00000000..e4a84f1b --- /dev/null +++ b/docs/operations/bmc-discovery.md @@ -0,0 +1,346 @@ +# BMC discovery + +[Operations guide](README.md) · [Physical devices](physical-inventory.md) · +[Redfish client](redfish-lab.md#bmc-client-library) + +`fleet-bmc-discovery` reads what each Device's BMC reports and writes it into +the Device's `status`. It is read-only towards the hardware: it issues Redfish +`GET` requests only, never changes power, boot or any BMC setting, and never +writes a Device's `spec`. + +## Implementation status + +| Aspect | State | +| --- | --- | +| Code | `cmd/fleet-bmc-discovery`, `internal/bmcdiscovery`, pinning and the read-only inventory in `internal/redfish` (`pin.go`, `inventory.go`). | +| API | `Device.status` schema in `config/components/inventory/crds`, Go types in `internal/api/inventory/v1alpha1`. | +| IAM | `fleet.datumapis.com-inventory-discoverer` role; `updateStatus` and the `status` subresource on the Device ProtectedResource. | +| Packaging | `config/base/bmc-discovery`, published in the `fleet-kustomize` bundle. The binary is in the `fleet` image. | +| Tests | Unit tests and an end-to-end test against an `httptest` TLS Redfish service (see [Tests](#tests)). | +| Hardware qualification | **None.** Not run against a vendor BMC. See [Not yet qualified](#not-yet-qualified). | + +## Who writes what + +| Surface | Writer | Content | +| --- | --- | --- | +| `Device.spec` | The inventory source (an operator or an importer) | Expected facts: identity, components, `bmc.endpoint`. | +| `Device.status` | BMC discovery only, through the status subresource | What the BMC reported, and how it compares with spec. | + +Observed values in status are evidence. `spec.identity` stays the +authoritative, immutable record. A mismatch is reported as a condition and is +never corrected in either direction. Discovery does not fill in MACs or a +system UUID that spec lacks; an importer that wants them reads status and +decides for itself. + +## Deployment + +Discovery runs where the BMC network is reachable, as **one replica with no +leader election**. Two replicas would contact every BMC twice and race on +status. The base uses `replicas: 1` and the `Recreate` strategy, so a rollout +never runs two. + +It needs: + +- a kubeconfig for **one Milo project**, mounted from a Secret; +- read access to credential Secrets in the namespace where it runs; +- network reachability to each `spec.bmc.endpoint`. It needs no privilege, + capability or host networking of its own. + +### Standalone Deployment + +`config/base/bmc-discovery` contains a ServiceAccount, a namespaced Role and +RoleBinding for Secrets, a ConfigMap generated from `config.yaml`, and the +Deployment. The container runs as UID 65532, non-root, with a read-only root +filesystem, no privilege escalation, all capabilities dropped and the +`RuntimeDefault` seccomp profile. The deploying repository supplies: + +| Input | Where | +| --- | --- | +| Namespace | Kustomize `namespace:`. Credential Secrets live here. | +| Image digest | Kustomize `images:`, for `ghcr.io/datum-cloud/fleet`. | +| Milo kubeconfig | Secret `fleet-bmc-discovery-milo-kubeconfig`, key `kubeconfig`. | +| Configuration | A patch of `config.yaml` or the generated ConfigMap. | + +The ServiceAccount token is mounted because discovery reads Secrets through +the Kubernetes API. Kubernetes RBAC cannot narrow a Role to labelled Secrets, +so run discovery in a namespace that holds nothing else it should not read. +To avoid the token, set `localKubeconfig` and mount a kubeconfig instead. + +### Sidecar in another pod + +When only one pod can reach the BMC network, for example a VPN gateway pod +that owns the tunnel device, run discovery as an extra container in that pod. +It shares the pod's network namespace and depends on no other container. +`config/base/bmc-discovery/examples/sidecar-container.yaml` is the container +and volume snippet to merge into that pod's template. In that case: + +- create the ConfigMap and Milo kubeconfig Secret yourself; the snippet uses + fixed names; +- bind the Role in `rbac.yaml` to that pod's ServiceAccount, or set + `localKubeconfig`; +- set `healthProbeAddress: ""` if port 8081 is already in use in the pod. + The snippet defines no probes. + +### Configuration + +`config.yaml`, read with strict decoding: + +| Field | Default | Meaning | +| --- | --- | --- | +| `project` | required | The Milo project the kubeconfig addresses. Secrets must name it. | +| `miloKubeconfig` | required | Path of the Milo project kubeconfig. | +| `deviceNamespaces` | required | Project namespaces whose Devices are read. | +| `credentialNamespace` | `$POD_NAMESPACE` | Local namespace of the credential Secrets. | +| `localKubeconfig` | in-cluster | Kubeconfig for the local cluster. | +| `interval` | `1h` | Re-discovery period after a completed attempt. At least `1m`. | +| `retryBase` | `30s` | First retry after an uncertain attempt; doubles up to `interval`. | +| `minContactInterval` | `1m` | Least time between two attempts on one BMC endpoint. | +| `requestTimeout` | `20s` | Timeout of each HTTP request to a BMC. | +| `concurrency` | `4` | BMCs contacted at once (1–64). | +| `healthProbeAddress` | off | Serves `/healthz` and `/readyz`; the base sets `:8081`. | + +### Milo access + +Bind the kubeconfig's identity to `fleet.datumapis.com-inventory-discoverer` +in the project. It grants exactly: + +| Permission | Used for | +| --- | --- | +| `fleet.datumapis.com/devices.get`, `.list`, `.watch` | Reading Devices. | +| `fleet.datumapis.com/devices.updateStatus` | Status writes when the authorizer maps status to this verb, as Fleet's metal roles assume. | +| `fleet.datumapis.com/devices/status.update`, `/status.patch` | Status writes when Milo's subresource authorization is enabled. | + +It grants no `devices.update`, `devices.patch` or any other kind, and inherits +no role. Discovery writes with a JSON merge patch on `devices/status` and an +optimistic lock. If an authorizer were to check `devices.patch` for a status +patch, the write would be denied, so a misconfiguration fails closed. + +### First run with `--once` + +`--once` contacts each eligible BMC once, prints the statuses it would write +as JSON on stdout, and exits. It reads Devices and Secrets and writes nothing +to Milo. Against the running Deployment: + +```sh +kubectl -n exec deploy/fleet-bmc-discovery -- \ + /fleet-bmc-discovery --config=/etc/fleet/bmc-discovery/config.yaml --once +``` + +## Credential Secrets + +One Secret per Device, in the credential namespace, never in Git, Milo or the +Device. `examples/credential-secret.yaml` is a synthetic example. + +| Field | Value | +| --- | --- | +| Label `fleet.datumapis.com/bmc-credential` | `"true"`; only labelled Secrets are cached or read. | +| Annotation `fleet.datumapis.com/device-project` | Must equal `project` in the config. | +| Annotation `fleet.datumapis.com/device-namespace` | The Device's namespace in the project. | +| Annotation `fleet.datumapis.com/device-name` | The Device's name. | +| `data.username`, `data.password` | Single-line BMC credential. | +| `data.tlsPublicKeySHA256` | Optional. The approved pin, 64 hex digits, colons and case ignored. | + +A Device is discovered only when it has `spec.bmc` and exactly one Secret +names it. A Device with neither is skipped and its status is not written. Two +Secrets naming one Device report `CredentialConflict` and send nothing. + +## TLS pinning + +BMC certificates are commonly self-signed and share one subject across a +fleet, so chain and hostname verification cannot identify a BMC. Discovery +identifies it by the SHA-256 of its leaf certificate's SubjectPublicKeyInfo +instead. TLS 1.2 or later is required. + +Each attempt runs in this order: + +1. **Anonymous probe.** A TLS handshake that accepts any certificate, then one + `GET /redfish/v1/` without a credential. The certificate's key hash, + `notAfter` and whether it is self-signed are recorded in + `status.discovery.tls`. The probe client holds no credential, so it cannot + send one. +2. **Pin check.** Discovery stops here without sending the credential when no + pin is approved (`PinNotApproved`) or the observed key differs from the + approved pin (`PinMismatch`). It never accepts a new key by itself. +3. **Authenticated read.** Only when the observed key equals the approved pin. + This client's handshake fails unless the key matches the pin, and it opens + a new connection for every request. A BMC that changes keys after the probe + gets no request at all and is reported as `PinMismatch`. + +All requests go through the shared Redfish transport guard: the enrolled +`https://IPv4:port` only, paths under `/redfish/v1`, no redirects, no +environment proxy, and a 1 MiB bound on each response. +`redfish.NewPinnedClient` and `redfish.PinnedTLSConfig` are available to the +provisioning executor too; its behavior is unchanged. + +### Approving a pin + +1. Create the credential Secret without `tlsPublicKeySHA256`. +2. Read the observed key: + + ```sh + kubectl get device -n \ + -o jsonpath='{.status.discovery.tls.publicKeySHA256}' + ``` + +3. Verify it out of band, from a host you trust on the BMC network or from + the BMC's own console or certificate page: + + ```sh + openssl s_client -connect :443 /dev/null \ + | openssl x509 -pubkey -noout \ + | openssl pkey -pubin -outform der | sha256sum + ``` + +4. Check that `PublicKeyUnique` is `True`. If it is `False`, see + [Shared keys](#shared-keys) before approving. +5. Set `tlsPublicKeySHA256` in the Secret. The Secret change triggers a new + attempt at once, still subject to `minContactInterval`. + +A BMC that regenerates its key, for example after a firmware reset, reports +`PinMismatch` until an operator verifies and approves the new key. + +### Shared keys + +Some firmware ships one default key on every unit. Then the pin cannot tell +those BMCs apart. Discovery compares the observed key of every Device it sees +and sets `PublicKeyUnique=False` with reason `SharedPublicKey` on each Device +that shares it, naming up to three of the others. This does not block the +credential: identity comparison still runs after the read. Replace the key +on those BMCs where the firmware allows it. + +## Status + +```yaml +status: + observedGeneration: 3 + discovery: + lastAttemptAt: "2026-01-02T03:04:05Z" + lastAttemptEndpoint: https://192.0.2.10:443 + tls: + observedAt: "2026-01-02T03:04:05Z" + endpoint: https://192.0.2.10:443 + publicKeySHA256: <64 hex digits> + notAfter: "2036-01-01T00:00:00Z" + selfSigned: true + serviceRoot: + observedAt: "2026-01-02T03:04:05Z" + endpoint: https://192.0.2.10:443 + redfishVersion: 1.15.0 + uuid: + vendor: Example + product: Example BMC + inventory: + observedAt: "2026-01-02T03:04:05Z" + endpoint: https://192.0.2.10:443 + managers: + - id: BMC + model: Example BMC + firmwareVersion: 1.2.3 + networkInterfaces: + - {id: "1", macAddress: "00:00:5e:00:53:10", linkStatus: LinkUp, speedMbps: 1000} + systems: + - id: "1" + uuid: 00000000-0000-4000-8000-000000000001 + manufacturer: Example Vendor + model: Example 1U + serialNumber: SYNTHETIC-0001 + sku: TAG0001 + powerState: "On" + networkInterfaces: + - {id: NIC.1, macAddress: "00:00:5e:00:53:01", linkStatus: LinkUp, speedMbps: 25000} + conditions: [...] +``` + +Each observation (`tls`, `serviceRoot`, `inventory`) carries its own time and +endpoint and is replaced only by a newer observation of the same kind. A +failed or refused attempt updates `lastAttemptAt` and the conditions and +keeps every earlier observation. Inventory is all or nothing: a partially read +BMC keeps the previous inventory. MACs are lowercase colon form and UUIDs +lowercase canonical. Power state is an observation; discovery never changes it. + +### Conditions + +| Type | Reasons | +| --- | --- | +| `Reachable` | `ServiceRootRead`; `ServiceRootUnreadable` (handshake completed, anonymous read failed); False `ConnectFailed`, `EndpointInvalid` | +| `Authenticated` | `CredentialAccepted`; False `PinNotApproved`, `PinMismatch`, `CredentialRejected`, `CredentialConflict`, `CredentialInvalid`; Unknown `NotAttempted`, `ReadFailed` | +| `Discovered` | `InventoryRead`; False for a definite refusal (the reason above); Unknown `Unreachable`, `ReadFailed` | +| `IdentityMatched` | `Matched`; False `SystemUUIDMismatch`, `SerialMismatch`, `ModelMismatch`; Unknown `NotObserved`, `StaleObservation`, `AmbiguousSystem` | +| `PublicKeyUnique` | `Unique`; False `SharedPublicKey`; Unknown `NotObserved` | + +Messages never carry a URL, credential, header or response body. + +Identity comparison selects the System by `spec.identity.systemUUID` when set, +else by serial, else the only System. The serial matches the System's +`SerialNumber` or `SKU`, because some vendors report the service tag as the +SKU. The model matches when the normalized values are equal or one ends with +the other as whole words, so `Example 1U` matches `Family Example 1U`. +Manufacturer is recorded but not compared, since vendor names vary in form. +An inventory read from an endpoint other than the current `spec.bmc.endpoint` +is `StaleObservation`. + +### Scheduling + +- A completed attempt, including a definite refusal, is repeated after + `interval`. A rejected credential is not retried sooner, so discovery cannot + lock out the BMC account. +- An uncertain attempt (no handshake, an interrupted read) is retried after + `retryBase`, doubling to `interval`. +- A Secret change or an endpoint change triggers an attempt at once. +- No endpoint is contacted twice within `minContactInterval`, whatever the + trigger. +- Other events, such as another Device's key changing, re-derive conditions + from retained status without contacting the BMC. +- The schedule is in memory. A restart contacts each BMC once, within the + `concurrency` bound. + +## What is read + +Service root, then every Manager and every ComputerSystem (up to 16 of each), +with each one's EthernetInterfaces (up to 32). Collections follow +`Members@odata.nextLink` for up to 8 pages. Every member must sit under its +collection. Documents are decoded leniently: only the named properties are +read, so an off-schema vendor property elsewhere in a document does not fail +the read. + +Not read: `Chassis`, `NetworkAdapters` and their ports, firmware inventory, +sessions. Basic authentication is used; no Redfish session is created. + +## Tests + +`go test -race ./internal/redfish/ ./internal/bmcdiscovery/ +./internal/api/inventory/...` covers: + +- pinning at the HTTP layer: the probe is one anonymous `GET`; a matching pin + reads the inventory with `GET`s only; a mismatched pin fails the handshake + and the server receives no request; +- the decision table: no credential is sent without an approved pin, on a + mismatch, or with a conflicting or malformed Secret; +- that a failed attempt keeps earlier observations and reports Unknown; +- identity comparison, including SKU, model prefixes, UUID selection and + stale endpoints, and that it never changes spec; +- that the reconciler writes only `devices/status` and never spec, skips + Devices without `spec.bmc` or a Secret, honors the interval, backoff and + per-endpoint gap, and contacts at once after a pin is approved; +- shared-key detection on both Devices, without a second contact; +- `--once` writing nothing and bounding concurrency; +- end to end against an `httptest` TLS service: first contact records the pin + with no credential sent, then approval yields inventory and + `IdentityMatched=True`; +- the Device status schema, the discoverer role, and the shipped Deployment's + single unprivileged replica. + +## Not yet qualified + +- **Vendor BMCs.** Not run against any vendor Redfish service. Check + property names and types, the service tag in `SerialNumber` or `SKU`, + EthernetInterfaces under Managers, and rate limits. +- **Milo status authorization.** Which permission Milo checks for a + `devices/status` patch has not been observed; the role carries both forms. +- **Anonymous service root.** Some BMCs may require authentication on + `/redfish/v1/`. That is reported as `ServiceRootUnreadable` and does not + block the pinned read. +- **Key rotation.** There is no workflow beyond re-approving a new pin. +- **NetworkAdapters.** MACs from `Chassis/NetworkAdapters` are not read. +- **Credential lifecycle.** Secrets are long-lived; rotation and a broker are + out of scope. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 96b1908b..5b725b54 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -40,8 +40,8 @@ where facts came from on its own labels and annotations. | Home | Milo. `config/milo` registers six CRDs, six ProtectedResources and three IAM roles. Management and synthetic-staging overlays install none of them. | | Staff portal | Six-kind hardware directory in the Bare Metal provider plugin (`ui/provider`), with permission-aware browsing and limited authorized Facility/Rack creation and portal-owned name edits. See [implementation scope](../development/staff-inventory-ui.md). | | Tests | Unit tests run API-server schema, list-type and CEL validation offline for the six kinds, including pruning of retired fields. IAM tests check ProtectedResource and role shape and that no metal role grants inventory access. Plugin tests cover browse/detail, partial placement, reconciliation, restricted, pagination and empty states. | -| Controllers | None for inventory. Staff browsing is read-only; no reconciler accepts plans, verifies hardware, discovers or synchronizes external inventory, or publishes eligibility. Flux applies only operator-reviewed Git records. | -| Hardware qualification | None. Records hold operator-entered facts, not verified hardware state. | +| Controllers | [BMC discovery](bmc-discovery.md) writes Device `status` only, from read-only Redfish reads. Nothing else reconciles inventory: staff browsing is read-only, and no reconciler accepts plans, synchronizes external inventory, or publishes eligibility. Flux applies only operator-reviewed Git records. | +| Hardware qualification | None. Spec holds operator-entered facts. Device status holds what a BMC reported, compared with spec; BMC discovery is not qualified on vendor hardware. | ## What registration does and does not do @@ -77,12 +77,14 @@ project control plane serves the kinds. Access is what keeps consumers out: | `fleet.datumapis.com-inventory-editor` | The viewer role plus `create`, `update`, `patch`, `delete` | | `fleet.datumapis.com-inventory-manager` | The viewer role plus `create`, `update`, `patch`; no deletion or status writes | | `fleet.datumapis.com-inventory-importer` | The viewer role plus `create` and `patch`, for server-side apply; no `update`, deletion or status writes | +| `fleet.datumapis.com-inventory-discoverer` | `get`, `list`, `watch` on Devices and Device status writes only; no spec write and no other kind. For [BMC discovery](bmc-discovery.md). | No `metal.datumapis.com` role includes or inherits any inventory role. The consumer, claimant, and viewer roles that reach customer projects therefore grant no inventory access, and the provider role does not either. Bind the inventory -roles explicitly, scoped to the provider project. No role grants status -writes, because status has no writer yet. +roles explicitly, scoped to the provider project. Only the discoverer role +grants status writes, and only for Devices; every other kind's status has no +writer. The manager is a separate least-privilege role for explicitly authorized inventory staff; it does not change the existing editor or give staff viewers write access. @@ -144,7 +146,7 @@ in the provider project. The plugin never writes. | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | | `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Only an Active Device can be registered as capacity. See [Device lifecycle](../development/inventory-capacity-registration.md#device-lifecycle). | -| `status` is a separate subresource that declares no fields | All six | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | +| `status` is a separate subresource | All six | Device status holds BMC discovery's observations and conditions; see [BMC discovery](bmc-discovery.md#status). Observed identity there is evidence; `spec.identity` stays authoritative. Every other kind's status declares no fields and has no writer. | The CRDs cannot check that `claimRef` names an existing DeviceClaim, because CEL cannot read other objects. Until a registrar enforces it, the operator diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 2fff15d7..a96498ff 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -226,8 +226,10 @@ sequencing, recovery and results, and calls the same `Discover`, `Observe`, query on a mutation, `OData-Version: 4.0`, and a 1 MiB response bound. A link returned by the BMC cannot send the credential elsewhere. Redirects are never followed. The environment proxy is not used, so the credential goes - only to the enrolled endpoint. TLS uses the system trust store; there is no - certificate pinning or private CA yet. The endpoint must still be a literal + only to the enrolled endpoint. The executor's TLS uses the system trust + store. `NewPinnedClient` verifies a BMC by the SHA-256 of its leaf public key + instead, through the same guard; [BMC discovery](bmc-discovery.md) uses it, + and the executor does not yet. The endpoint must still be a literal `http(s)://IPv4:port`. - **Identity and capability checks.** These are unchanged: one UUID match across all members with the enrolled Id, a reset target and ActionInfo on @@ -600,7 +602,8 @@ MVP. They are listed as an explicit qualification checklist: order persistence. 3. **Receipts.** Replace the read-only console capture with serial-over-LAN or an authenticated installer callback, and decide its trust model. -4. **Credentials and transport.** TLS with pinned CA or certificate, per-BMC +4. **Credentials and transport.** Public-key pinning exists + (`NewPinnedClient`) but the executor does not use it. Per-BMC accounts, a credential broker so workers never hold a long-lived password, and rotation and revocation. 5. **Provisioning network.** Synchronized DHCP reservations with served and @@ -620,8 +623,9 @@ MVP. They are listed as an explicit qualification checklist: designed. Never reset the journal of a retained target ([known limitations](multiplane.md#known-limitations-of-the-local-mvp)). 9. **Enrollment.** The asset-to-System mapping is a static source value. - Enrollment trust, BMC discovery and attestation of the System identity - (beyond Id and UUID) are open. + Enrollment trust and attestation of the System identity (beyond Id and + UUID) are open. Read-only [BMC discovery](bmc-discovery.md) reports + observed identity into Device status but does not enroll. 10. **Operator recovery.** Unknown operations, for example a power-off without a receipt or an exhausted `On` budget, have no automated resolution. The only recovery is to discard the disposable topology after inspection. diff --git a/internal/bmcdiscovery/config.go b/internal/bmcdiscovery/config.go new file mode 100644 index 00000000..80d0a06c --- /dev/null +++ b/internal/bmcdiscovery/config.go @@ -0,0 +1,101 @@ +// Package bmcdiscovery reads what each Device's BMC reports, over Redfish GETs +// only, and writes it into Device status. It never writes spec, never changes +// power or boot, and sends a credential only to a BMC whose TLS public key +// matches the operator-approved pin. See docs/operations/bmc-discovery.md. +package bmcdiscovery + +import ( + "errors" + "fmt" + "os" + "strings" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/yaml" +) + +// Config is the discovery configuration file, usually a mounted ConfigMap. +type Config struct { + // Project is the Milo project the kubeconfig addresses. Credential Secrets + // must name it, so Secrets for another project are never used. + Project string `json:"project"` + // MiloKubeconfig is the path of a kubeconfig for that one project. + MiloKubeconfig string `json:"miloKubeconfig"` + // DeviceNamespaces are the project namespaces whose Devices are read. + DeviceNamespaces []string `json:"deviceNamespaces"` + // CredentialNamespace holds the credential Secrets in the cluster where + // discovery runs. It defaults to $POD_NAMESPACE. + CredentialNamespace string `json:"credentialNamespace,omitempty"` + // LocalKubeconfig reaches that cluster. Empty uses the in-cluster + // service account. + LocalKubeconfig string `json:"localKubeconfig,omitempty"` + // Interval is the re-discovery period after a completed attempt. + Interval metav1.Duration `json:"interval,omitempty"` + // RetryBase is the first backoff after an uncertain attempt; it doubles + // per consecutive failure up to Interval. + RetryBase metav1.Duration `json:"retryBase,omitempty"` + // MinContactInterval is the least time between two attempts against one + // BMC endpoint, whatever triggers them. + MinContactInterval metav1.Duration `json:"minContactInterval,omitempty"` + // RequestTimeout bounds each HTTP request to a BMC. + RequestTimeout metav1.Duration `json:"requestTimeout,omitempty"` + // Concurrency is the number of BMCs contacted at once. + Concurrency int `json:"concurrency,omitempty"` + // HealthProbeAddress serves /healthz and /readyz; empty disables them. + HealthProbeAddress string `json:"healthProbeAddress,omitempty"` +} + +// LoadConfig reads, defaults and validates a configuration file. +func LoadConfig(path string) (Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return Config{}, fmt.Errorf("read discovery config: %w", err) + } + var c Config + if err := yaml.UnmarshalStrict(data, &c); err != nil { + return Config{}, fmt.Errorf("parse discovery config: %w", err) + } + c.Default() + return c, c.Validate() +} + +// Default fills unset values. +func (c *Config) Default() { + set := func(d *metav1.Duration, v time.Duration) { + if d.Duration == 0 { + d.Duration = v + } + } + set(&c.Interval, time.Hour) + set(&c.RetryBase, 30*time.Second) + set(&c.MinContactInterval, time.Minute) + set(&c.RequestTimeout, 20*time.Second) + if c.Concurrency == 0 { + c.Concurrency = 4 + } + if c.CredentialNamespace == "" { + c.CredentialNamespace = os.Getenv("POD_NAMESPACE") + } +} + +// Validate rejects an incomplete or out-of-range configuration. +func (c Config) Validate() error { + var errs []error + if c.Project == "" || c.MiloKubeconfig == "" || c.CredentialNamespace == "" || len(c.DeviceNamespaces) == 0 { + errs = append(errs, errors.New("project, miloKubeconfig, deviceNamespaces and credentialNamespace (or $POD_NAMESPACE) are required")) + } + for _, ns := range c.DeviceNamespaces { + if strings.TrimSpace(ns) == "" { + errs = append(errs, errors.New("deviceNamespaces must not contain an empty name")) + } + } + if c.Interval.Duration < time.Minute || c.RetryBase.Duration <= 0 || c.RetryBase.Duration > c.Interval.Duration || + c.MinContactInterval.Duration < 0 || c.MinContactInterval.Duration > c.Interval.Duration || c.RequestTimeout.Duration <= 0 { + errs = append(errs, errors.New("need interval >= 1m, 0 < retryBase <= interval, 0 <= minContactInterval <= interval and requestTimeout > 0")) + } + if c.Concurrency < 1 || c.Concurrency > 64 { + errs = append(errs, errors.New("concurrency must be between 1 and 64")) + } + return errors.Join(errs...) +} diff --git a/internal/bmcdiscovery/credentials.go b/internal/bmcdiscovery/credentials.go new file mode 100644 index 00000000..7ef7e77f --- /dev/null +++ b/internal/bmcdiscovery/credentials.go @@ -0,0 +1,86 @@ +package bmcdiscovery + +import ( + "errors" + "sort" + "strings" + + corev1 "k8s.io/api/core/v1" + + "go.datum.net/fleet/internal/redfish" +) + +// Credential Secret contract. Secrets live in the cluster where discovery +// runs, never in Milo or on the Device. +const ( + // CredentialLabel selects credential Secrets; its value must be "true". + CredentialLabel = "fleet.datumapis.com/bmc-credential" + // The annotations name the one Device a Secret is for. + ProjectAnnotation = "fleet.datumapis.com/device-project" + NamespaceAnnotation = "fleet.datumapis.com/device-namespace" + NameAnnotation = "fleet.datumapis.com/device-name" + + UsernameKey = "username" + PasswordKey = "password" + // PinKey holds the operator-approved SHA-256 of the BMC's TLS public key. + // Until it is set discovery records the observed key and sends nothing. + PinKey = "tlsPublicKeySHA256" +) + +// Credential is a parsed credential Secret. +type Credential struct { + Username, Password string + // Pin is empty until an operator approves the BMC's key. + Pin string + // Version changes whenever the Secret does, so an approval triggers a new + // attempt at once. + Version string +} + +var ( + errCredentialConflict = errors.New("more than one credential Secret names this Device") + errCredentialInvalid = errors.New("credential Secret is malformed") +) + +// deviceKey is the Device a credential Secret names, or "" when the Secret +// does not name one in project. +func deviceKey(secret *corev1.Secret, project string) string { + if secret.Labels[CredentialLabel] != "true" || secret.Annotations[ProjectAnnotation] != project { + return "" + } + ns, name := secret.Annotations[NamespaceAnnotation], secret.Annotations[NameAnnotation] + if ns == "" || name == "" { + return "" + } + return ns + "/" + name +} + +// selectCredential picks the one Secret for a Device. It returns found=false +// when none names it. A conflict or malformed Secret is an error with a +// Version, so the condition is reported and the attempt still records the +// anonymous TLS observation. +func selectCredential(secrets []corev1.Secret) (cred Credential, found bool, err error) { + if len(secrets) == 0 { + return Credential{}, false, nil + } + versions := make([]string, 0, len(secrets)) + for _, s := range secrets { + versions = append(versions, string(s.UID)+"@"+s.ResourceVersion) + } + sort.Strings(versions) + version := strings.Join(versions, ",") + if len(secrets) > 1 { + return Credential{Version: version}, true, errCredentialConflict + } + data := secrets[0].Data + cred = Credential{Username: strings.TrimSpace(string(data[UsernameKey])), Password: strings.TrimSpace(string(data[PasswordKey])), Version: version} + if cred.Username == "" || cred.Password == "" || strings.ContainsAny(cred.Username, ":\r\n") || strings.ContainsAny(cred.Password, "\r\n") { + return Credential{Version: version}, true, errCredentialInvalid + } + if pin := strings.TrimSpace(string(data[PinKey])); pin != "" { + if cred.Pin, err = redfish.ParsePin(pin); err != nil { + return Credential{Version: version}, true, errCredentialInvalid + } + } + return cred, true, nil +} diff --git a/internal/bmcdiscovery/discovery_test.go b/internal/bmcdiscovery/discovery_test.go new file mode 100644 index 00000000..e32a4c21 --- /dev/null +++ b/internal/bmcdiscovery/discovery_test.go @@ -0,0 +1,650 @@ +package bmcdiscovery + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/redfish" +) + +const ( + project = "example-provider-project" + credNS = "bmc-discovery" + deviceNS = "default" +) + +var ( + pinA = strings.Repeat("a", 64) + pinB = strings.Repeat("b", 64) + t0 = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) +) + +// fakeBMC answers per endpoint and records every call. +type fakeBMC struct { + mu sync.Mutex + pins map[string]string + probeErr error + rootErr error // returned with the certificate, as for a failed anonymous service-root read + invErr error + inv redfish.Inventory + probes []string + inventories []string // "endpoint pin" + active, max atomic.Int32 + hold time.Duration +} + +func (f *fakeBMC) Probe(_ context.Context, endpoint string) (redfish.Certificate, redfish.ServiceRoot, error) { + n := f.active.Add(1) + defer f.active.Add(-1) + for { + m := f.max.Load() + if n <= m || f.max.CompareAndSwap(m, n) { + break + } + } + time.Sleep(f.hold) + f.mu.Lock() + defer f.mu.Unlock() + f.probes = append(f.probes, endpoint) + if f.probeErr != nil { + return redfish.Certificate{}, redfish.ServiceRoot{}, f.probeErr + } + cert := redfish.Certificate{PublicKeySHA256: f.pins[endpoint], NotAfter: t0.Add(24 * time.Hour), SelfSigned: true} + if f.rootErr != nil { + return cert, redfish.ServiceRoot{}, f.rootErr + } + return cert, redfish.ServiceRoot{RedfishVersion: "1.15.0"}, nil +} + +func (f *fakeBMC) Inventory(_ context.Context, endpoint, user, password, pin string) (redfish.Inventory, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.inventories = append(f.inventories, endpoint+" "+pin) + if f.invErr != nil { + return redfish.Inventory{}, f.invErr + } + if user != "operator" || password != "synthetic-secret" { + return redfish.Inventory{}, redfish.ErrUnauthorized + } + return f.inv, nil +} + +func (f *fakeBMC) calls() (int, int) { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.probes), len(f.inventories) +} + +func system() redfish.InventorySystem { + return redfish.InventorySystem{ID: "1", UUID: "00000000-0000-4000-8000-000000000001", Manufacturer: "Example Vendor", Model: "Example Family Example 1U", + SerialNumber: "SYNTHETIC-0001", PowerState: "On", NetworkInterfaces: []redfish.NetworkInterface{{ID: "NIC.1", MACAddress: "00:00:5e:00:53:01"}}} +} + +func newFakeBMC() *fakeBMC { + return &fakeBMC{pins: map[string]string{"https://192.0.2.10:443": pinA, "https://192.0.2.11:443": pinB}, + inv: redfish.Inventory{Managers: []redfish.Manager{{ID: "BMC", FirmwareVersion: "1.0"}}, Systems: []redfish.InventorySystem{system()}}} +} + +func device(name, endpoint string) *inventory.Device { + return &inventory.Device{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: deviceNS, Generation: 1}, + Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "claim-" + name}, + Identity: inventory.DeviceIdentity{Manufacturer: "Example", Model: "Example 1U", Serial: "SYNTHETIC-0001"}, + BMC: &inventory.BMC{Endpoint: endpoint}}, + } +} + +func secret(deviceName, pin string) *corev1.Secret { + s := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "bmc-" + deviceName, Namespace: credNS, UID: types.UID("uid-" + deviceName), ResourceVersion: "1", + Labels: map[string]string{CredentialLabel: "true"}, + Annotations: map[string]string{ProjectAnnotation: project, NamespaceAnnotation: deviceNS, NameAnnotation: deviceName}}, + Data: map[string][]byte{UsernameKey: []byte("operator"), PasswordKey: []byte("synthetic-secret")}} + if pin != "" { + s.Data[PinKey] = []byte(pin) + } + return s +} + +func condition(t *testing.T, status inventory.DeviceStatus, kind string) metav1.Condition { + t.Helper() + c := meta.FindStatusCondition(status.Conditions, kind) + if c == nil { + t.Fatalf("no %s condition in %+v", kind, status.Conditions) + } + return *c +} + +func TestContactSendsCredentialOnlyForTheApprovedPin(t *testing.T) { + for name, tc := range map[string]struct { + pin string + credErr error + reason string + inventory bool + }{ + "no pin approved": {reason: ReasonPinNotApproved}, + "pin mismatch": {pin: pinB, reason: ReasonPinMismatch}, + "secret conflict": {pin: pinA, credErr: errCredentialConflict, reason: ReasonCredentialConflict}, + "secret malformed": {credErr: errCredentialInvalid, reason: ReasonCredentialInvalid}, + "pin approved": {pin: pinA, reason: ReasonCredentialAccepted, inventory: true}, + } { + t.Run(name, func(t *testing.T) { + bmc := newFakeBMC() + a := contact(context.Background(), bmc, "https://192.0.2.10:443", Credential{Username: "operator", Password: "synthetic-secret", Pin: tc.pin}, tc.credErr, t0) + var status inventory.DeviceStatus + apply(&status, a, 1) + if got := condition(t, status, inventory.ConditionAuthenticated); got.Reason != tc.reason { + t.Fatalf("Authenticated = %+v, want %s", got, tc.reason) + } + // The observed pin is recorded whatever happens next. + if status.Discovery.TLS == nil || status.Discovery.TLS.PublicKeySHA256 != pinA || !status.Discovery.TLS.SelfSigned || status.Discovery.TLS.NotAfter == nil { + t.Fatalf("TLS observation = %+v", status.Discovery.TLS) + } + if probes, invs := bmc.calls(); probes != 1 || (invs == 1) != tc.inventory { + t.Fatalf("probes %d, credentialed reads %d, want credential sent = %v", probes, invs, tc.inventory) + } + if (status.Discovery.Inventory != nil) != tc.inventory { + t.Fatalf("inventory = %+v", status.Discovery.Inventory) + } + }) + } +} + +func TestContactOutcomes(t *testing.T) { + cred := Credential{Username: "operator", Password: "synthetic-secret", Pin: pinA} + for name, tc := range map[string]struct { + endpoint string + probeErr, invErr error + reachable, discovered metav1.ConditionStatus + reason string + uncertain bool + }{ + "endpoint not https": {endpoint: "http://192.0.2.10:80", reachable: metav1.ConditionFalse, discovered: metav1.ConditionFalse, reason: ReasonEndpointInvalid}, + "no handshake": {probeErr: redfish.ErrNoHandshake, reachable: metav1.ConditionFalse, discovered: metav1.ConditionUnknown, reason: ReasonUnreachable, uncertain: true}, + "rejected": {invErr: redfish.ErrUnauthorized, reachable: metav1.ConditionTrue, discovered: metav1.ConditionFalse, reason: ReasonCredentialRejected}, + "key changed": {invErr: redfish.ErrPinMismatch, reachable: metav1.ConditionTrue, discovered: metav1.ConditionFalse, reason: ReasonPinMismatch}, + "read failed": {invErr: errors.New("synthetic-secret leaked in error"), reachable: metav1.ConditionTrue, discovered: metav1.ConditionUnknown, reason: ReasonReadFailed, uncertain: true}, + } { + t.Run(name, func(t *testing.T) { + bmc := newFakeBMC() + bmc.probeErr, bmc.invErr = tc.probeErr, tc.invErr + endpoint := tc.endpoint + if endpoint == "" { + endpoint = "https://192.0.2.10:443" + } + a := contact(context.Background(), bmc, endpoint, cred, nil, t0) + var status inventory.DeviceStatus + apply(&status, a, 1) + if r := condition(t, status, inventory.ConditionReachable); r.Status != tc.reachable { + t.Fatalf("Reachable = %+v", r) + } + d := condition(t, status, inventory.ConditionDiscovered) + if d.Status != tc.discovered || d.Reason != tc.reason || a.uncertain != tc.uncertain { + t.Fatalf("Discovered = %+v, uncertain %v", d, a.uncertain) + } + for _, c := range status.Conditions { + if strings.Contains(c.Message, "synthetic-secret") || strings.Contains(c.Message, "192.0.2") { + t.Fatalf("condition message leaks a credential or URL: %q", c.Message) + } + } + }) + } +} + +func TestUnreadableServiceRootBacksOffWhateverTheCredential(t *testing.T) { + for name, cred := range map[string]Credential{ + "pin not approved": {Username: "operator", Password: "synthetic-secret"}, + "pin refused": {Username: "operator", Password: "synthetic-secret", Pin: pinB}, + } { + t.Run(name, func(t *testing.T) { + bmc := newFakeBMC() + bmc.rootErr = errors.New("service root returned 503") + a := contact(context.Background(), bmc, "https://192.0.2.10:443", cred, nil, t0) + if !a.uncertain { + t.Fatal("an unreadable service root must be retried with backoff") + } + var status inventory.DeviceStatus + apply(&status, a, 1) + if r := condition(t, status, inventory.ConditionReachable); r.Reason != ReasonServiceRootUnreadable { + t.Fatalf("Reachable = %+v", r) + } + if _, inv := bmc.calls(); inv != 0 { + t.Fatalf("credential was sent %d times without an approved pin", inv) + } + }) + } +} + +func TestFailedAttemptRetainsEarlierObservations(t *testing.T) { + bmc := newFakeBMC() + cred := Credential{Username: "operator", Password: "synthetic-secret", Pin: pinA} + var status inventory.DeviceStatus + apply(&status, contact(context.Background(), bmc, "https://192.0.2.10:443", cred, nil, t0), 1) + before := *status.Discovery.Inventory + tlsBefore := *status.Discovery.TLS + bmc.probeErr = redfish.ErrNoHandshake + later := t0.Add(time.Hour) + apply(&status, contact(context.Background(), bmc, "https://192.0.2.10:443", cred, nil, later), 1) + if status.Discovery.Inventory == nil || !status.Discovery.Inventory.ObservedAt.Equal(&before.ObservedAt) || len(status.Discovery.Inventory.Systems) != 1 { + t.Fatalf("inventory not retained: %+v", status.Discovery.Inventory) + } + if status.Discovery.TLS == nil || status.Discovery.TLS.PublicKeySHA256 != tlsBefore.PublicKeySHA256 || !status.Discovery.TLS.ObservedAt.Equal(&tlsBefore.ObservedAt) { + t.Fatalf("TLS observation not retained: %+v", status.Discovery.TLS) + } + if !status.Discovery.LastAttemptAt.Time.Equal(later) { + t.Fatalf("last attempt = %v", status.Discovery.LastAttemptAt) + } + if d := condition(t, status, inventory.ConditionDiscovered); d.Status != metav1.ConditionUnknown { + t.Fatalf("Discovered after a transient failure = %+v, want Unknown", d) + } +} + +func TestIdentityComparison(t *testing.T) { + endpoint := "https://192.0.2.10:443" + observe := func(systems ...inventory.ObservedSystem) *inventory.DeviceStatus { + return &inventory.DeviceStatus{Discovery: &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{Endpoint: endpoint, Systems: systems}}} + } + base := inventory.ObservedSystem{ID: "1", UUID: "00000000-0000-4000-8000-000000000001", Model: "PowerFamily Example 1U", SerialNumber: "SYNTHETIC-0001"} + other := base + other.ID, other.UUID, other.SerialNumber = "2", "00000000-0000-4000-8000-000000000002", "SYNTHETIC-0002" + with := func(mutate func(*inventory.ObservedSystem)) inventory.ObservedSystem { s := base; mutate(&s); return s } + for name, tc := range map[string]struct { + status *inventory.DeviceStatus + identity inventory.DeviceIdentity + want metav1.ConditionStatus + reason string + }{ + "not observed": {status: &inventory.DeviceStatus{}, want: metav1.ConditionUnknown, reason: ReasonNotObserved}, + "serial and model": {status: observe(base), want: metav1.ConditionTrue, reason: ReasonMatched}, + "service tag as SKU": {status: observe(with(func(s *inventory.ObservedSystem) { s.SerialNumber, s.SKU = "CHASSIS-9", "synthetic-0001" })), want: metav1.ConditionTrue, reason: ReasonMatched}, + "serial differs": {status: observe(with(func(s *inventory.ObservedSystem) { s.SerialNumber = "SYNTHETIC-0009" })), want: metav1.ConditionFalse, reason: ReasonSerialMismatch}, + "model differs": {status: observe(with(func(s *inventory.ObservedSystem) { s.Model = "Example 2U" })), want: metav1.ConditionFalse, reason: ReasonModelMismatch}, + "model is not a word": {status: observe(with(func(s *inventory.ObservedSystem) { s.Model = "Example 1UX" })), want: metav1.ConditionFalse, reason: ReasonModelMismatch}, + "picks by serial": {status: observe(other, base), want: metav1.ConditionTrue, reason: ReasonMatched}, + "uuid differs": {status: observe(other), identity: inventory.DeviceIdentity{Model: "Example 1U", SystemUUID: base.UUID}, want: metav1.ConditionFalse, reason: ReasonSystemUUIDMismatch}, + "uuid then serial": {status: observe(with(func(s *inventory.ObservedSystem) { s.SerialNumber = "X" })), identity: inventory.DeviceIdentity{Model: "Example 1U", Serial: "SYNTHETIC-0001", SystemUUID: base.UUID}, want: metav1.ConditionFalse, reason: ReasonSerialMismatch}, + "model only, ambiguous": {status: observe(base, other), identity: inventory.DeviceIdentity{Model: "Example 1U", Unidentified: true}, want: metav1.ConditionUnknown, reason: ReasonAmbiguousSystem}, + "stale endpoint": {status: &inventory.DeviceStatus{Discovery: &inventory.DeviceDiscovery{Inventory: &inventory.ObservedInventory{Endpoint: "https://192.0.2.99:443", Systems: []inventory.ObservedSystem{base}}}}, want: metav1.ConditionUnknown, reason: ReasonStaleObservation}, + } { + t.Run(name, func(t *testing.T) { + d := device("example-device-01", endpoint) + if tc.identity.Model != "" { + d.Spec.Identity = tc.identity + } + specBefore, _ := json.Marshal(d.Spec) + got := identityCondition(tc.status, d) + if got.Status != tc.want || got.Reason != tc.reason { + t.Fatalf("IdentityMatched = %+v, want %s %s", got, tc.want, tc.reason) + } + if specAfter, _ := json.Marshal(d.Spec); !bytes.Equal(specBefore, specAfter) { + t.Fatal("comparison changed spec") + } + }) + } +} + +// harness is a reconciler over a fake Milo client that records every write. +type harness struct { + r *Reconciler + c client.Client + bmc *fakeBMC + now time.Time + writes []string +} + +func newHarness(t *testing.T, objects ...client.Object) *harness { + t.Helper() + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + h := &harness{bmc: newFakeBMC(), now: t0} + var devices []client.Object + var secrets []client.Object + for _, o := range objects { + if _, ok := o.(*corev1.Secret); ok { + secrets = append(secrets, o) + } else { + devices = append(devices, o) + } + } + record := func(kind string) { h.writes = append(h.writes, kind) } + h.c = fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&inventory.Device{}).WithObjects(devices...).WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, o client.Object, opts ...client.CreateOption) error { + record("create") + return c.Create(ctx, o, opts...) + }, + Update: func(ctx context.Context, c client.WithWatch, o client.Object, opts ...client.UpdateOption) error { + record("update") + return c.Update(ctx, o, opts...) + }, + Patch: func(ctx context.Context, c client.WithWatch, o client.Object, p client.Patch, opts ...client.PatchOption) error { + record("patch") + return c.Patch(ctx, o, p, opts...) + }, + Delete: func(ctx context.Context, c client.WithWatch, o client.Object, opts ...client.DeleteOption) error { + record("delete") + return c.Delete(ctx, o, opts...) + }, + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, o client.Object, opts ...client.SubResourceUpdateOption) error { + record(sub + " update") + return c.SubResource(sub).Update(ctx, o, opts...) + }, + SubResourcePatch: func(ctx context.Context, c client.Client, sub string, o client.Object, p client.Patch, opts ...client.SubResourcePatchOption) error { + record(sub + " patch") + return c.SubResource(sub).Patch(ctx, o, p, opts...) + }, + }).Build() + secretClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(secrets...).Build() + h.r = &Reconciler{Devices: h.c, Secrets: secretClient, Namespace: credNS, Project: project, BMC: h.bmc, + Interval: time.Hour, RetryBase: 30 * time.Second, MinContact: time.Minute, Now: func() time.Time { return h.now }} + return h +} + +func (h *harness) reconcile(t *testing.T, name string) reconcile.Result { + t.Helper() + res, err := h.r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: deviceNS, Name: name}}) + if err != nil { + t.Fatal(err) + } + return res +} + +func (h *harness) get(t *testing.T, name string) *inventory.Device { + t.Helper() + var d inventory.Device + if err := h.c.Get(context.Background(), types.NamespacedName{Namespace: deviceNS, Name: name}, &d); err != nil { + t.Fatal(err) + } + return &d +} + +func TestReconcileWritesOnlyStatus(t *testing.T) { + d := device("example-device-01", "https://192.0.2.10:443") + h := newHarness(t, d, secret("example-device-01", pinA)) + specBefore, _ := json.Marshal(h.get(t, "example-device-01").Spec) + res := h.reconcile(t, "example-device-01") + got := h.get(t, "example-device-01") + if specAfter, _ := json.Marshal(got.Spec); !bytes.Equal(specBefore, specAfter) { + t.Fatalf("spec changed:\n%s\n%s", specBefore, specAfter) + } + for _, w := range h.writes { + if w != "status patch" { + t.Fatalf("writes = %v, want status patches only", h.writes) + } + } + if len(h.writes) != 1 || res.RequeueAfter != time.Hour { + t.Fatalf("writes %v, requeue %v", h.writes, res.RequeueAfter) + } + for kind, reason := range map[string]string{inventory.ConditionReachable: ReasonServiceRootRead, inventory.ConditionAuthenticated: ReasonCredentialAccepted, + inventory.ConditionDiscovered: ReasonInventoryRead, inventory.ConditionIdentityMatched: ReasonMatched, inventory.ConditionPublicKeyUnique: ReasonUnique} { + if c := condition(t, got.Status, kind); c.Reason != reason || c.ObservedGeneration != 1 { + t.Fatalf("%s = %+v, want %s", kind, c, reason) + } + } + if got.Status.Discovery.Inventory.Systems[0].PowerState != "On" { + t.Fatalf("inventory = %+v", got.Status.Discovery.Inventory) + } +} + +func TestReconcileSkipsDevicesWithoutBMCOrCredential(t *testing.T) { + noBMC := device("no-bmc", "") + noBMC.Spec.BMC = nil + otherProject := secret("other-project", pinA) + otherProject.Annotations[ProjectAnnotation] = "another-project" + h := newHarness(t, noBMC, secret("no-bmc", pinA), device("no-secret", "https://192.0.2.10:443"), device("other-project", "https://192.0.2.11:443"), otherProject) + for _, name := range []string{"no-bmc", "no-secret", "other-project", "missing"} { + h.reconcile(t, name) + } + if probes, _ := h.bmc.calls(); probes != 0 || len(h.writes) != 0 { + t.Fatalf("probes %d, writes %v; want none", probes, h.writes) + } +} + +func TestReconcileSchedulesContacts(t *testing.T) { + h := newHarness(t, device("example-device-01", "https://192.0.2.10:443"), secret("example-device-01", "")) + h.reconcile(t, "example-device-01") + if got := condition(t, h.get(t, "example-device-01").Status, inventory.ConditionAuthenticated); got.Reason != ReasonPinNotApproved { + t.Fatalf("Authenticated = %+v", got) + } + // An event before the interval re-derives without contacting the BMC. + h.now = h.now.Add(10 * time.Minute) + res := h.reconcile(t, "example-device-01") + if probes, _ := h.bmc.calls(); probes != 1 || res.RequeueAfter != 50*time.Minute { + t.Fatalf("probes %d requeue %v", probes, res.RequeueAfter) + } + // Approving the pin is a Secret change: discovery contacts at once and + // sends the credential. + var s corev1.Secret + secrets := h.r.Secrets.(client.Client) + if err := secrets.Get(context.Background(), types.NamespacedName{Namespace: credNS, Name: "bmc-example-device-01"}, &s); err != nil { + t.Fatal(err) + } + s.Data[PinKey] = []byte(strings.ToUpper(pinA)) + if err := secrets.Update(context.Background(), &s); err != nil { + t.Fatal(err) + } + h.reconcile(t, "example-device-01") + if probes, invs := h.bmc.calls(); probes != 2 || invs != 1 { + t.Fatalf("probes %d, credentialed reads %d after approval", probes, invs) + } + if got := condition(t, h.get(t, "example-device-01").Status, inventory.ConditionDiscovered); got.Status != metav1.ConditionTrue { + t.Fatalf("Discovered = %+v", got) + } +} + +func TestReconcileBacksOffAndRespectsTheEndpointGap(t *testing.T) { + h := newHarness(t, device("example-device-01", "https://192.0.2.10:443"), secret("example-device-01", pinA), + device("example-device-02", "https://192.0.2.10:443"), secret("example-device-02", pinA)) + h.bmc.probeErr = redfish.ErrNoHandshake + if res := h.reconcile(t, "example-device-01"); res.RequeueAfter != 30*time.Second { + t.Fatalf("first retry after %v, want 30s", res.RequeueAfter) + } + // A second Device on the same endpoint waits for the per-endpoint gap. + if res := h.reconcile(t, "example-device-02"); res.RequeueAfter != time.Minute { + t.Fatalf("same-endpoint Device requeued after %v, want the 1m gap", res.RequeueAfter) + } + if probes, _ := h.bmc.calls(); probes != 1 { + t.Fatalf("probes = %d, want the endpoint contacted once", probes) + } + for i, want := range []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute} { + h.now = h.now.Add(time.Hour) + if res := h.reconcile(t, "example-device-01"); res.RequeueAfter != want { + t.Fatalf("retry %d after %v, want %v", i+2, res.RequeueAfter, want) + } + } +} + +func TestSharedPublicKeyIsReportedOnEveryHolder(t *testing.T) { + h := newHarness(t, device("example-device-01", "https://192.0.2.10:443"), secret("example-device-01", ""), + device("example-device-02", "https://192.0.2.12:443"), secret("example-device-02", "")) + h.bmc.pins["https://192.0.2.12:443"] = pinA // the same default key on two BMCs + h.reconcile(t, "example-device-01") + if got := condition(t, h.get(t, "example-device-01").Status, inventory.ConditionPublicKeyUnique); got.Status != metav1.ConditionTrue { + t.Fatalf("before the second BMC is seen: %+v", got) + } + h.reconcile(t, "example-device-02") + // The watch re-derives the first Device from retained status; no new + // contact is needed. + h.reconcile(t, "example-device-01") + for _, name := range []string{"example-device-01", "example-device-02"} { + got := condition(t, h.get(t, name).Status, inventory.ConditionPublicKeyUnique) + if got.Status != metav1.ConditionFalse || got.Reason != ReasonSharedPublicKey { + t.Fatalf("%s PublicKeyUnique = %+v", name, got) + } + } + if probes, invs := h.bmc.calls(); probes != 2 || invs != 0 { + t.Fatalf("probes %d, credentialed reads %d; first contact sends no credential", probes, invs) + } +} + +func TestRunOnceWritesNothingAndBoundsConcurrency(t *testing.T) { + var objects []client.Object + bmc := newFakeBMC() + bmc.hold = 20 * time.Millisecond + for i := range 12 { + name := fmt.Sprintf("example-device-%02d", i) + endpoint := fmt.Sprintf("https://192.0.2.%d:443", 20+i) + bmc.pins[endpoint] = pinA + objects = append(objects, device(name, endpoint), secret(name, "")) + } + h := newHarness(t, objects...) + var out bytes.Buffer + c := Config{Project: project, DeviceNamespaces: []string{deviceNS}, CredentialNamespace: credNS, Concurrency: 3} + if err := RunOnce(context.Background(), c, h.c, h.r.Secrets, bmc, &out); err != nil { + t.Fatal(err) + } + if len(h.writes) != 0 { + t.Fatalf("--once wrote %v", h.writes) + } + if m := bmc.max.Load(); m > 3 || m < 2 { + t.Fatalf("max concurrent probes = %d, want at most 3", m) + } + var results []OnceResult + if err := json.Unmarshal(out.Bytes(), &results); err != nil || len(results) != 12 { + t.Fatalf("results %d: %v\n%s", len(results), err, out.String()) + } + for _, r := range results { + if r.Status.Discovery.TLS.PublicKeySHA256 != pinA || condition(t, r.Status, inventory.ConditionPublicKeyUnique).Reason != ReasonSharedPublicKey || + condition(t, r.Status, inventory.ConditionAuthenticated).Reason != ReasonPinNotApproved { + t.Fatalf("result %+v", r) + } + } +} + +func TestSelectCredential(t *testing.T) { + if _, found, _ := selectCredential(nil); found { + t.Fatal("found a credential in no Secrets") + } + good := secret("example-device-01", strings.ToUpper(pinA)) + cred, found, err := selectCredential([]corev1.Secret{*good}) + if !found || err != nil || cred.Pin != pinA || cred.Username != "operator" || cred.Version == "" { + t.Fatalf("cred = %+v %v %v", cred, found, err) + } + badPin := secret("example-device-01", "not-a-pin") + if _, _, err := selectCredential([]corev1.Secret{*badPin}); !errors.Is(err, errCredentialInvalid) { + t.Fatalf("bad pin err = %v", err) + } + noPassword := secret("example-device-01", "") + delete(noPassword.Data, PasswordKey) + if _, _, err := selectCredential([]corev1.Secret{*noPassword}); !errors.Is(err, errCredentialInvalid) { + t.Fatalf("missing password err = %v", err) + } + second := secret("example-device-01", "") + second.Name, second.UID = "duplicate", "uid-duplicate" + if cred, _, err := selectCredential([]corev1.Secret{*good, *second}); !errors.Is(err, errCredentialConflict) || cred.Password != "" { + t.Fatalf("conflict = %+v %v", cred, err) + } +} + +func TestConfigValidation(t *testing.T) { + c := Config{Project: project, MiloKubeconfig: "/k", DeviceNamespaces: []string{deviceNS}, CredentialNamespace: credNS} + c.Default() + if err := c.Validate(); err != nil || c.Interval.Duration != time.Hour || c.Concurrency != 4 { + t.Fatalf("defaults %+v: %v", c, err) + } + for name, mutate := range map[string]func(*Config){ + "no project": func(c *Config) { c.Project = "" }, + "no namespaces": func(c *Config) { c.DeviceNamespaces = nil }, + "short interval": func(c *Config) { c.Interval.Duration = time.Second }, + "zero concurrency": func(c *Config) { c.Concurrency = -1 }, + } { + bad := c + mutate(&bad) + if bad.Validate() == nil { + t.Fatalf("%s accepted", name) + } + } +} + +// TestEndToEndOverTLS drives the real Redfish client against a TLS service: +// first contact records the pin without sending a credential; approval of +// that pin sends it and reads the inventory. +func TestEndToEndOverTLS(t *testing.T) { + var mu sync.Mutex + var log []string + docs := map[string]string{ + "/redfish/v1/": `{"RedfishVersion":"1.15.0","Systems":{"@odata.id":"/redfish/v1/Systems"},"Managers":{"@odata.id":"/redfish/v1/Managers"}}`, + "/redfish/v1/Managers": `{"Members":[{"@odata.id":"/redfish/v1/Managers/BMC"}]}`, + "/redfish/v1/Managers/BMC": `{"Id":"BMC","Model":"Example BMC","FirmwareVersion":"1.2.3"}`, + "/redfish/v1/Systems": `{"Members":[{"@odata.id":"/redfish/v1/Systems/1"}]}`, + "/redfish/v1/Systems/1": `{"Id":"1","UUID":"00000000-0000-4000-8000-000000000001","Model":"Example 1U","SerialNumber":"SYNTHETIC-0001","PowerState":"Off"}`, + } + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, authed := r.BasicAuth() + mu.Lock() + log = append(log, r.Method+" "+r.URL.Path+map[bool]string{true: " authed", false: ""}[authed]) + mu.Unlock() + if r.URL.Path != "/redfish/v1/" && (user != "operator" || pass != "synthetic-secret") { + w.WriteHeader(http.StatusUnauthorized) + return + } + doc, ok := docs[r.URL.Path] + if !ok || r.Method != http.MethodGet { + w.WriteHeader(http.StatusNotFound) + return + } + w.Write([]byte(doc)) + })) + defer server.Close() + pin := redfish.PublicKeySHA256(server.Certificate()) + h := newHarness(t, device("example-device-01", server.URL), secret("example-device-01", "")) + h.r.BMC = RedfishBMC{Timeout: 5 * time.Second} + h.reconcile(t, "example-device-01") + got := h.get(t, "example-device-01") + if got.Status.Discovery.TLS.PublicKeySHA256 != pin || condition(t, got.Status, inventory.ConditionAuthenticated).Reason != ReasonPinNotApproved { + t.Fatalf("first contact status = %+v", got.Status) + } + mu.Lock() + for _, l := range log { + if strings.HasSuffix(l, "authed") { + t.Fatalf("credential sent before the pin was approved: %v", log) + } + } + mu.Unlock() + var s corev1.Secret + secrets := h.r.Secrets.(client.Client) + _ = secrets.Get(context.Background(), types.NamespacedName{Namespace: credNS, Name: "bmc-example-device-01"}, &s) + s.Data[PinKey] = []byte(pin) + if err := secrets.Update(context.Background(), &s); err != nil { + t.Fatal(err) + } + h.now = h.now.Add(2 * time.Minute) + h.reconcile(t, "example-device-01") + got = h.get(t, "example-device-01") + if c := condition(t, got.Status, inventory.ConditionDiscovered); c.Status != metav1.ConditionTrue { + t.Fatalf("Discovered = %+v", c) + } + if inv := got.Status.Discovery.Inventory; inv == nil || inv.Managers[0].FirmwareVersion != "1.2.3" || inv.Systems[0].PowerState != "Off" { + t.Fatalf("inventory = %+v", inv) + } + if c := condition(t, got.Status, inventory.ConditionIdentityMatched); c.Status != metav1.ConditionTrue { + t.Fatalf("IdentityMatched = %+v", c) + } + mu.Lock() + defer mu.Unlock() + for _, l := range log { + if !strings.HasPrefix(l, "GET ") { + t.Fatalf("discovery issued %s", l) + } + } +} diff --git a/internal/bmcdiscovery/manifest_test.go b/internal/bmcdiscovery/manifest_test.go new file mode 100644 index 00000000..8ceba6ba --- /dev/null +++ b/internal/bmcdiscovery/manifest_test.go @@ -0,0 +1,49 @@ +package bmcdiscovery + +import ( + "os" + "path/filepath" + "testing" + + appsv1 "k8s.io/api/apps/v1" + "sigs.k8s.io/yaml" +) + +var baseDir = filepath.Join("..", "..", "config", "base", "bmc-discovery") + +func TestShippedConfigLoads(t *testing.T) { + t.Setenv("POD_NAMESPACE", "bmc-discovery") + c, err := LoadConfig(filepath.Join(baseDir, "config.yaml")) + if err != nil { + t.Fatal(err) + } + if c.CredentialNamespace != "bmc-discovery" || c.Interval.Duration.Hours() != 1 { + t.Fatalf("config = %+v", c) + } +} + +func TestDeploymentIsSingleUnprivilegedReplica(t *testing.T) { + data, err := os.ReadFile(filepath.Join(baseDir, "deployment.yaml")) + if err != nil { + t.Fatal(err) + } + var d appsv1.Deployment + if err := yaml.UnmarshalStrict(data, &d); err != nil { + t.Fatal(err) + } + if d.Spec.Replicas == nil || *d.Spec.Replicas != 1 || d.Spec.Strategy.Type != appsv1.RecreateDeploymentStrategyType { + t.Fatal("discovery has no leader election: it must be one replica with Recreate") + } + pod := d.Spec.Template.Spec + if pod.SecurityContext == nil || pod.SecurityContext.RunAsNonRoot == nil || !*pod.SecurityContext.RunAsNonRoot || pod.HostNetwork { + t.Fatal("pod must run as non-root without host networking") + } + if len(pod.Containers) != 1 { + t.Fatal("discovery is one container") + } + sc := pod.Containers[0].SecurityContext + if sc == nil || sc.ReadOnlyRootFilesystem == nil || !*sc.ReadOnlyRootFilesystem || sc.AllowPrivilegeEscalation == nil || *sc.AllowPrivilegeEscalation || + sc.Privileged != nil || sc.Capabilities == nil || len(sc.Capabilities.Add) != 0 || len(sc.Capabilities.Drop) != 1 || sc.Capabilities.Drop[0] != "ALL" { + t.Fatalf("container security context = %+v", sc) + } +} diff --git a/internal/bmcdiscovery/reconciler.go b/internal/bmcdiscovery/reconciler.go new file mode 100644 index 00000000..5b3e447c --- /dev/null +++ b/internal/bmcdiscovery/reconciler.go @@ -0,0 +1,172 @@ +package bmcdiscovery + +import ( + "context" + "encoding/json" + "sync" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +// Reconciler discovers one Device per reconcile. Devices without spec.bmc or +// without a credential Secret are skipped and their status is not written. +type Reconciler struct { + // Devices reads Devices and writes only their status subresource. + Devices client.Client + // Secrets reads credential Secrets in Namespace of the local cluster. + Secrets client.Reader + Namespace string + Project string + BMC BMC + // Interval, RetryBase and MinContact are Config's durations. + Interval, RetryBase, MinContact time.Duration + Now func() time.Time + + mu sync.Mutex + targets map[types.NamespacedName]*target + // contacts is the last attempt per endpoint, across Devices. + contacts map[string]time.Time +} + +// target is the in-memory attempt schedule of one Device. It is rebuilt +// after a restart, which therefore contacts each BMC once more. +type target struct { + next time.Time + failures int + version string + endpoint string +} + +func (r *Reconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} + +// credentialsFor lists the credential Secrets naming the Device. +func (r *Reconciler) credentialsFor(ctx context.Context, key types.NamespacedName) ([]corev1.Secret, error) { + var list corev1.SecretList + if err := r.Secrets.List(ctx, &list, client.InNamespace(r.Namespace), client.MatchingLabels{CredentialLabel: "true"}); err != nil { + return nil, err + } + var out []corev1.Secret + for _, s := range list.Items { + if deviceKey(&s, r.Project) == key.String() { + out = append(out, s) + } + } + return out, nil +} + +// due reports whether the Device's BMC should be contacted now, or else how +// long until it should be. +func (r *Reconciler) due(key types.NamespacedName, endpoint, version string, now time.Time) (bool, time.Duration) { + r.mu.Lock() + defer r.mu.Unlock() + t := r.targets[key] + if t != nil && t.version == version && t.endpoint == endpoint && now.Before(t.next) { + return false, t.next.Sub(now) + } + if last, ok := r.contacts[endpoint]; ok && now.Before(last.Add(r.MinContact)) { + return false, last.Add(r.MinContact).Sub(now) + } + return true, 0 +} + +// record schedules the next attempt after one finished. +func (r *Reconciler) record(key types.NamespacedName, endpoint, version string, uncertain bool, now time.Time) time.Duration { + r.mu.Lock() + defer r.mu.Unlock() + if r.targets == nil { + r.targets, r.contacts = map[types.NamespacedName]*target{}, map[string]time.Time{} + } + r.contacts[endpoint] = now + t := r.targets[key] + if t == nil || t.version != version || t.endpoint != endpoint { + t = &target{version: version, endpoint: endpoint} + r.targets[key] = t + } + wait := r.Interval + if uncertain { + t.failures++ + wait = r.RetryBase << min(t.failures-1, 20) + if wait <= 0 || wait > r.Interval { + wait = r.Interval + } + } else { + t.failures = 0 + } + t.next = now.Add(wait) + return wait +} + +func (r *Reconciler) forget(key types.NamespacedName) { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.targets, key) +} + +func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { + var device inventory.Device + if err := r.Devices.Get(ctx, req.NamespacedName, &device); err != nil { + if apierrors.IsNotFound(err) { + r.forget(req.NamespacedName) + return reconcile.Result{}, nil + } + return reconcile.Result{}, err + } + if device.Spec.BMC == nil || !device.DeletionTimestamp.IsZero() { + r.forget(req.NamespacedName) + return reconcile.Result{}, nil + } + secrets, err := r.credentialsFor(ctx, req.NamespacedName) + if err != nil { + return reconcile.Result{}, err + } + cred, found, credErr := selectCredential(secrets) + if !found { + r.forget(req.NamespacedName) + return reconcile.Result{}, nil + } + now := r.now() + endpoint := device.Spec.BMC.Endpoint + status := &device.DeepCopyObject().(*inventory.Device).Status + contactNow, wait := r.due(req.NamespacedName, endpoint, cred.Version, now) + if contactNow { + a := contact(ctx, r.BMC, endpoint, cred, credErr, now) + wait = r.record(req.NamespacedName, endpoint, cred.Version, a.uncertain, now) + apply(status, a, device.Generation) + } + var all inventory.DeviceList + if err := r.Devices.List(ctx, &all); err != nil { + return reconcile.Result{}, err + } + derive(status, &device, sharingKey(&device, status, all.Items), metav1.NewTime(now.UTC().Truncate(time.Second))) + status.ObservedGeneration = device.Generation + if !sameStatus(&device.Status, status) { + patch := client.MergeFromWithOptions(device.DeepCopyObject().(*inventory.Device), client.MergeFromWithOptimisticLock{}) + device.Status = *status + if err := r.Devices.Status().Patch(ctx, &device, patch); err != nil { + // The observation is not retained; contact again, still subject + // to the per-endpoint gap. + r.forget(req.NamespacedName) + return reconcile.Result{}, err + } + } + return reconcile.Result{RequeueAfter: wait}, nil +} + +func sameStatus(a, b *inventory.DeviceStatus) bool { + x, _ := json.Marshal(a) + y, _ := json.Marshal(b) + return string(x) == string(y) +} diff --git a/internal/bmcdiscovery/runtime.go b/internal/bmcdiscovery/runtime.go new file mode 100644 index 00000000..71366e6c --- /dev/null +++ b/internal/bmcdiscovery/runtime.go @@ -0,0 +1,223 @@ +package bmcdiscovery + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strings" + "sync" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "k8s.io/client-go/util/workqueue" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/manager" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +const pinIndex = "status.discovery.tls.publicKeySHA256" + +// NewScheme registers the kinds discovery reads. +func NewScheme() (*runtime.Scheme, error) { + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + return nil, err + } + return scheme, inventory.AddToScheme(scheme) +} + +// NewManager builds the discovery controller. The manager's cluster is the +// Milo project; a second cluster reads only labelled Secrets in the credential +// namespace. There is no leader election: run exactly one replica. +func NewManager(c Config, milo, local *rest.Config, scheme *runtime.Scheme, bmc BMC) (manager.Manager, error) { + namespaces := map[string]cache.Config{} + for _, ns := range c.DeviceNamespaces { + namespaces[ns] = cache.Config{} + } + probe := c.HealthProbeAddress + if probe == "" { + probe = "0" + } + mgr, err := manager.New(milo, manager.Options{ + Scheme: scheme, + Cache: cache.Options{DefaultNamespaces: namespaces, DefaultTransform: cache.TransformStripManagedFields()}, + Metrics: metricsserver.Options{BindAddress: "0"}, + HealthProbeBindAddress: probe, + LeaderElection: false, + }) + if err != nil { + return nil, fmt.Errorf("build Milo project manager: %w", err) + } + selector := labels.SelectorFromSet(labels.Set{CredentialLabel: "true"}) + secrets, err := cluster.New(local, func(o *cluster.Options) { + o.Scheme = scheme + o.Cache = cache.Options{DefaultNamespaces: map[string]cache.Config{c.CredentialNamespace: {}}, + ByObject: map[client.Object]cache.ByObject{&corev1.Secret{}: {Label: selector}}, DefaultTransform: cache.TransformStripManagedFields()} + }) + if err != nil { + return nil, fmt.Errorf("build credential Secret cache: %w", err) + } + if err := mgr.Add(secrets); err != nil { + return nil, err + } + if err := mgr.GetFieldIndexer().IndexField(context.Background(), &inventory.Device{}, pinIndex, func(o client.Object) []string { + if d := o.(*inventory.Device).Status.Discovery; d != nil && d.TLS != nil { + return []string{d.TLS.PublicKeySHA256} + } + return nil + }); err != nil { + return nil, err + } + r := &Reconciler{Devices: mgr.GetClient(), Secrets: secrets.GetCache(), Namespace: c.CredentialNamespace, Project: c.Project, BMC: bmc, + Interval: c.Interval.Duration, RetryBase: c.RetryBase.Duration, MinContact: c.MinContactInterval.Duration} + // A Device whose observed key changes re-derives every Device holding the + // old or the new key; that pass reads only retained status. + peers := func(ctx context.Context, q workqueue.TypedRateLimitingInterface[reconcile.Request], self client.Object, pins ...string) { + for _, pin := range pins { + if pin == "" { + continue + } + var list inventory.DeviceList + if err := mgr.GetClient().List(ctx, &list, client.MatchingFields{pinIndex: pin}); err != nil { + continue + } + for _, d := range list.Items { + if d.Namespace != self.GetNamespace() || d.Name != self.GetName() { + q.Add(reconcile.Request{NamespacedName: types.NamespacedName{Namespace: d.Namespace, Name: d.Name}}) + } + } + } + } + pinOf := func(o client.Object) string { + if d := o.(*inventory.Device).Status.Discovery; d != nil && d.TLS != nil { + return d.TLS.PublicKeySHA256 + } + return "" + } + sharedKey := handler.Funcs{ + CreateFunc: func(ctx context.Context, e event.CreateEvent, q workqueue.TypedRateLimitingInterface[reconcile.Request]) { + peers(ctx, q, e.Object, pinOf(e.Object)) + }, + UpdateFunc: func(ctx context.Context, e event.UpdateEvent, q workqueue.TypedRateLimitingInterface[reconcile.Request]) { + if old, cur := pinOf(e.ObjectOld), pinOf(e.ObjectNew); old != cur { + peers(ctx, q, e.ObjectNew, old, cur) + } + }, + DeleteFunc: func(ctx context.Context, e event.DeleteEvent, q workqueue.TypedRateLimitingInterface[reconcile.Request]) { + peers(ctx, q, e.Object, pinOf(e.Object)) + }, + } + credential := handler.EnqueueRequestsFromMapFunc(func(_ context.Context, o client.Object) []reconcile.Request { + key := deviceKey(o.(*corev1.Secret), c.Project) + ns, name, ok := strings.Cut(key, "/") + if !ok { + return nil + } + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: ns, Name: name}}} + }) + err = builder.ControllerManagedBy(mgr). + Named("bmc-discovery"). + For(&inventory.Device{}). + Watches(&inventory.Device{}, sharedKey). + WatchesRawSource(source.Kind(secrets.GetCache(), client.Object(&corev1.Secret{}), credential)). + WithOptions(controller.Options{MaxConcurrentReconciles: c.Concurrency}). + Complete(r) + if err != nil { + return nil, err + } + if c.HealthProbeAddress != "" { + if err := mgr.AddHealthzCheck("ping", healthz.Ping); err != nil { + return nil, err + } + if err := mgr.AddReadyzCheck("ping", healthz.Ping); err != nil { + return nil, err + } + } + return mgr, nil +} + +// OnceResult is what --once would write for one Device. +type OnceResult struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + Status inventory.DeviceStatus `json:"status"` +} + +// RunOnce contacts every eligible Device's BMC once, concurrently up to +// Config.Concurrency, and writes the statuses it would have written to out as +// JSON. It writes nothing to Milo: the Device client is used for reads only. +func RunOnce(ctx context.Context, c Config, devices, secrets client.Reader, bmc BMC, out io.Writer) error { + var all []inventory.Device + for _, ns := range c.DeviceNamespaces { + var list inventory.DeviceList + if err := devices.List(ctx, &list, client.InNamespace(ns)); err != nil { + return fmt.Errorf("list Devices in %s: %w", ns, err) + } + all = append(all, list.Items...) + } + var secretList corev1.SecretList + if err := secrets.List(ctx, &secretList, client.InNamespace(c.CredentialNamespace), client.MatchingLabels{CredentialLabel: "true"}); err != nil { + return fmt.Errorf("list credential Secrets: %w", err) + } + byDevice := map[string][]corev1.Secret{} + for _, s := range secretList.Items { + if key := deviceKey(&s, c.Project); key != "" { + byDevice[key] = append(byDevice[key], s) + } + } + results := make([]*OnceResult, len(all)) + sem := make(chan struct{}, c.Concurrency) + var wg sync.WaitGroup + for i := range all { + device := &all[i] + cred, found, credErr := selectCredential(byDevice[device.Namespace+"/"+device.Name]) + if device.Spec.BMC == nil || !found { + continue + } + wg.Add(1) + go func() { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + status := device.DeepCopyObject().(*inventory.Device).Status + apply(&status, contact(ctx, bmc, device.Spec.BMC.Endpoint, cred, credErr, time.Now().UTC().Truncate(time.Second)), device.Generation) + results[i] = &OnceResult{Namespace: device.Namespace, Name: device.Name, Status: status} + }() + } + wg.Wait() + // Shared keys are judged against this run's observations. + for i, r := range results { + if r != nil { + all[i].Status = r.Status + } + } + var printed []OnceResult + for i, r := range results { + if r == nil { + continue + } + derive(&r.Status, &all[i], sharingKey(&all[i], &r.Status, all), metav1.NewTime(time.Now().UTC().Truncate(time.Second))) + r.Status.ObservedGeneration = all[i].Generation + printed = append(printed, *r) + } + enc := json.NewEncoder(out) + enc.SetIndent("", " ") + return enc.Encode(printed) +} diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go new file mode 100644 index 00000000..47dab77d --- /dev/null +++ b/internal/bmcdiscovery/status.go @@ -0,0 +1,354 @@ +package bmcdiscovery + +import ( + "context" + "errors" + "fmt" + "sort" + "strings" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/redfish" +) + +// BMC is the read-only Redfish surface discovery uses. +type BMC interface { + // Probe completes an unauthenticated TLS handshake and one anonymous GET + // of the service root. It never holds a credential. + Probe(ctx context.Context, endpoint string) (redfish.Certificate, redfish.ServiceRoot, error) + // Inventory reads the BMC with the credential, over a connection whose + // handshake fails unless the leaf public key matches pin. + Inventory(ctx context.Context, endpoint, user, password, pin string) (redfish.Inventory, error) +} + +// RedfishBMC is the BMC over internal/redfish. +type RedfishBMC struct{ Timeout time.Duration } + +func (b RedfishBMC) Probe(ctx context.Context, endpoint string) (redfish.Certificate, redfish.ServiceRoot, error) { + return redfish.Probe(ctx, endpoint, b.Timeout) +} + +func (b RedfishBMC) Inventory(ctx context.Context, endpoint, user, password, pin string) (redfish.Inventory, error) { + c, err := redfish.NewPinnedClient(endpoint, user, password, pin, b.Timeout) + if err != nil { + return redfish.Inventory{}, err + } + return c.Inventory(ctx) +} + +// Condition reasons. +const ( + ReasonEndpointInvalid = "EndpointInvalid" + ReasonConnectFailed = "ConnectFailed" + ReasonServiceRootRead = "ServiceRootRead" + ReasonServiceRootUnreadable = "ServiceRootUnreadable" + ReasonNotAttempted = "NotAttempted" + ReasonCredentialConflict = "CredentialConflict" + ReasonCredentialInvalid = "CredentialInvalid" + ReasonPinNotApproved = "PinNotApproved" + ReasonPinMismatch = "PinMismatch" + ReasonCredentialRejected = "CredentialRejected" + ReasonCredentialAccepted = "CredentialAccepted" + ReasonReadFailed = "ReadFailed" + ReasonUnreachable = "Unreachable" + ReasonInventoryRead = "InventoryRead" + ReasonNotObserved = "NotObserved" + ReasonStaleObservation = "StaleObservation" + ReasonAmbiguousSystem = "AmbiguousSystem" + ReasonMatched = "Matched" + ReasonSystemUUIDMismatch = "SystemUUIDMismatch" + ReasonSerialMismatch = "SerialMismatch" + ReasonModelMismatch = "ModelMismatch" + ReasonUnique = "Unique" + ReasonSharedPublicKey = "SharedPublicKey" +) + +// attempt is the outcome of contacting one BMC once. +type attempt struct { + at metav1.Time + endpoint string + cert *redfish.Certificate + root *redfish.ServiceRoot + inv *redfish.Inventory + // conditions set by the attempt: Reachable, Authenticated, Discovered. + conditions []metav1.Condition + // uncertain attempts are retried with backoff; definite refusals wait for + // the interval or a credential change. A rejected credential is never + // retried quickly, so discovery cannot lock out the BMC account. + uncertain bool +} + +func cond(kind string, status metav1.ConditionStatus, reason, message string) metav1.Condition { + return metav1.Condition{Type: kind, Status: status, Reason: reason, Message: message} +} + +// contact runs one attempt. A credential is passed to the BMC only after the +// anonymous probe observed exactly the approved pin, and the authenticated +// connection re-checks that pin in its own handshake before any request. +func contact(ctx context.Context, bmc BMC, endpoint string, cred Credential, credErr error, now time.Time) attempt { + a := attempt{at: metav1.NewTime(now.UTC().Truncate(time.Second)), endpoint: endpoint} + set := func(reachable, authenticated, discovered metav1.Condition) attempt { + a.conditions = []metav1.Condition{reachable, authenticated, discovered} + return a + } + notAttempted := cond(inventory.ConditionAuthenticated, metav1.ConditionUnknown, ReasonNotAttempted, "no credential was sent") + canonical, err := redfish.ParseEndpoint(endpoint) + if err != nil || !strings.HasPrefix(canonical, "https://") { + msg := "spec.bmc.endpoint must be https://IPv4:port" + return set(cond(inventory.ConditionReachable, metav1.ConditionFalse, ReasonEndpointInvalid, msg), notAttempted, + cond(inventory.ConditionDiscovered, metav1.ConditionFalse, ReasonEndpointInvalid, msg)) + } + cert, root, err := bmc.Probe(ctx, canonical) + if errors.Is(err, redfish.ErrNoHandshake) || (err != nil && cert.PublicKeySHA256 == "") { + a.uncertain = true + return set(cond(inventory.ConditionReachable, metav1.ConditionFalse, ReasonConnectFailed, "no TLS handshake completed with the BMC endpoint"), notAttempted, + cond(inventory.ConditionDiscovered, metav1.ConditionUnknown, ReasonUnreachable, "the BMC was not reached; earlier observations are retained")) + } + a.cert = &cert + reachable := cond(inventory.ConditionReachable, metav1.ConditionTrue, ReasonServiceRootRead, "TLS handshake completed and the anonymous service root was read") + if err != nil { + // The service root may be briefly unavailable (for example a 503 + // while the BMC boots), so retry with backoff whatever the credential + // state turns out to be. + a.uncertain = true + reachable = cond(inventory.ConditionReachable, metav1.ConditionTrue, ReasonServiceRootUnreadable, "TLS handshake completed; the anonymous service root read failed: "+safe(err)) + } else { + a.root = &root + } + refuse := func(reason, msg string) attempt { + return set(reachable, cond(inventory.ConditionAuthenticated, metav1.ConditionFalse, reason, msg+"; no credential was sent"), + cond(inventory.ConditionDiscovered, metav1.ConditionFalse, reason, msg)) + } + switch { + case errors.Is(credErr, errCredentialConflict): + return refuse(ReasonCredentialConflict, "more than one credential Secret names this Device") + case credErr != nil: + return refuse(ReasonCredentialInvalid, "the credential Secret needs a single-line username and password and, if set, a hex SHA-256 tlsPublicKeySHA256") + case cred.Pin == "": + return refuse(ReasonPinNotApproved, "the observed public key is in status.discovery.tls; verify it out of band and approve it as tlsPublicKeySHA256 in the credential Secret") + case cred.Pin != cert.PublicKeySHA256: + return refuse(ReasonPinMismatch, "the BMC presented a public key other than the approved pin") + } + inv, err := bmc.Inventory(ctx, canonical, cred.Username, cred.Password, cred.Pin) + switch { + case errors.Is(err, redfish.ErrPinMismatch): + return refuse(ReasonPinMismatch, "the BMC presented a public key other than the approved pin") + case errors.Is(err, redfish.ErrUnauthorized): + return set(reachable, cond(inventory.ConditionAuthenticated, metav1.ConditionFalse, ReasonCredentialRejected, "the BMC rejected the credential; it is retried only after the interval or a Secret change"), + cond(inventory.ConditionDiscovered, metav1.ConditionFalse, ReasonCredentialRejected, "the BMC rejected the credential")) + case err != nil: + a.uncertain = true + return set(reachable, cond(inventory.ConditionAuthenticated, metav1.ConditionUnknown, ReasonReadFailed, "the authenticated read did not complete: "+safe(err)), + cond(inventory.ConditionDiscovered, metav1.ConditionUnknown, ReasonReadFailed, "the inventory read did not complete; earlier observations are retained: "+safe(err))) + } + a.inv = &inv + return set(reachable, cond(inventory.ConditionAuthenticated, metav1.ConditionTrue, ReasonCredentialAccepted, "the BMC accepted the credential over the pinned connection"), + cond(inventory.ConditionDiscovered, metav1.ConditionTrue, ReasonInventoryRead, "managers, systems and their Ethernet interfaces were read")) +} + +// safe keeps only redfish's own outcome classes, which never carry a URL, +// header or response body. +func safe(err error) string { + var status redfish.Status + switch { + case errors.As(err, &status): + return status.Error() + case errors.Is(err, redfish.ErrIdentity): + return "the BMC returned a link outside the Redfish service" + default: + return "transport failure or unreadable response" + } +} + +// apply records an attempt into status. Each observation replaces only its +// own retained section, so a failed read keeps the previous one. +func apply(status *inventory.DeviceStatus, a attempt, generation int64) { + if status.Discovery == nil { + status.Discovery = &inventory.DeviceDiscovery{} + } + d := status.Discovery + d.LastAttemptAt, d.LastAttemptEndpoint = &a.at, a.endpoint + if a.cert != nil { + t := &inventory.ObservedTLS{ObservedAt: a.at, Endpoint: a.endpoint, PublicKeySHA256: a.cert.PublicKeySHA256, SelfSigned: a.cert.SelfSigned} + if !a.cert.NotAfter.IsZero() { + notAfter := metav1.NewTime(a.cert.NotAfter) + t.NotAfter = ¬After + } + d.TLS = t + } + if a.root != nil { + d.ServiceRoot = &inventory.ObservedServiceRoot{ObservedAt: a.at, Endpoint: a.endpoint, RedfishVersion: clip(a.root.RedfishVersion, 63), + UUID: canonicalUUIDOrEmpty(a.root.UUID), Vendor: clip(a.root.Vendor, 253), Product: clip(a.root.Product, 253)} + } + if a.inv != nil { + d.Inventory = observedInventory(*a.inv, a.at, a.endpoint) + } + for _, c := range a.conditions { + setCondition(status, c, generation, a.at) + } +} + +func setCondition(status *inventory.DeviceStatus, c metav1.Condition, generation int64, now metav1.Time) { + c.ObservedGeneration, c.LastTransitionTime = generation, now + meta.SetStatusCondition(&status.Conditions, c) +} + +func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) *inventory.ObservedInventory { + nics := func(in []redfish.NetworkInterface) []inventory.ObservedNetworkInterface { + var out []inventory.ObservedNetworkInterface + for _, n := range in { + if n.ID == "" || len(out) == 32 { + continue + } + out = append(out, inventory.ObservedNetworkInterface{ID: clip(n.ID, 253), MACAddress: n.MACAddress, LinkStatus: clip(n.LinkStatus, 63), SpeedMbps: min(n.SpeedMbps, 100000000)}) + } + return out + } + out := &inventory.ObservedInventory{ObservedAt: at, Endpoint: endpoint} + for _, m := range inv.Managers { + if m.ID != "" && len(out.Managers) < 16 { + out.Managers = append(out.Managers, inventory.ObservedManager{ID: clip(m.ID, 253), Model: clip(m.Model, 253), FirmwareVersion: clip(m.FirmwareVersion, 253), NetworkInterfaces: nics(m.NetworkInterfaces)}) + } + } + for _, s := range inv.Systems { + if s.ID != "" && len(out.Systems) < 16 { + out.Systems = append(out.Systems, inventory.ObservedSystem{ID: clip(s.ID, 253), UUID: canonicalUUIDOrEmpty(s.UUID), Manufacturer: clip(s.Manufacturer, 253), + Model: clip(s.Model, 253), SerialNumber: clip(s.SerialNumber, 253), SKU: clip(s.SKU, 253), PowerState: clip(s.PowerState, 63), NetworkInterfaces: nics(s.NetworkInterfaces)}) + } + } + return out +} + +func clip(s string, n int) string { + s = strings.TrimSpace(s) + if len(s) > n { + return s[:n] + } + return s +} + +func canonicalUUIDOrEmpty(s string) string { + s = strings.ToLower(strings.TrimSpace(s)) + if len(s) != 36 || strings.Count(s, "-") != 4 || s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' || strings.Trim(s, "0123456789abcdef-") != "" { + return "" + } + return s +} + +// derive recomputes the conditions that compare observations with spec and +// with other Devices. It never changes an observation. +func derive(status *inventory.DeviceStatus, device *inventory.Device, sharing []string, now metav1.Time) { + setCondition(status, identityCondition(status, device), device.Generation, now) + setCondition(status, uniqueCondition(status, sharing), device.Generation, now) +} + +func normalize(s string) string { return strings.Join(strings.Fields(strings.ToLower(s)), " ") } + +// modelMatches allows a vendor family prefix on either side ("PowerEdge X1" +// against "X1"): one normalized model must equal the other or end with it as +// whole words. +func modelMatches(expected, observed string) bool { + e, o := normalize(expected), normalize(observed) + return e == o || (e != "" && strings.HasSuffix(o, " "+e)) || (o != "" && strings.HasSuffix(e, " "+o)) +} + +// serialMatches compares the spec serial with the System serial and SKU: +// some vendors report the chassis service tag as the SKU. +func serialMatches(expected string, s inventory.ObservedSystem) bool { + e := normalize(expected) + return e != "" && (e == normalize(s.SerialNumber) || e == normalize(s.SKU)) +} + +func identityCondition(status *inventory.DeviceStatus, device *inventory.Device) metav1.Condition { + kind := inventory.ConditionIdentityMatched + if status.Discovery == nil || status.Discovery.Inventory == nil { + return cond(kind, metav1.ConditionUnknown, ReasonNotObserved, "no inventory has been read") + } + inv := status.Discovery.Inventory + if device.Spec.BMC == nil || inv.Endpoint != device.Spec.BMC.Endpoint { + return cond(kind, metav1.ConditionUnknown, ReasonStaleObservation, "the retained inventory was read from another endpoint") + } + want := device.Spec.Identity + var candidates []inventory.ObservedSystem + switch { + case want.SystemUUID != "": + for _, s := range inv.Systems { + if s.UUID == want.SystemUUID { + candidates = append(candidates, s) + } + } + if len(candidates) == 0 { + return cond(kind, metav1.ConditionFalse, ReasonSystemUUIDMismatch, "no System reports spec.identity.systemUUID; spec is not changed") + } + case want.Serial != "": + for _, s := range inv.Systems { + if serialMatches(want.Serial, s) { + candidates = append(candidates, s) + } + } + if len(candidates) == 0 { + return cond(kind, metav1.ConditionFalse, ReasonSerialMismatch, "no System reports spec.identity.serial as its serial number or SKU; spec is not changed") + } + default: + candidates = inv.Systems + } + if len(candidates) != 1 { + return cond(kind, metav1.ConditionUnknown, ReasonAmbiguousSystem, fmt.Sprintf("%d Systems could be this Device", len(candidates))) + } + s := candidates[0] + var compared []string + switch { + case want.SystemUUID != "" && want.Serial != "" && !serialMatches(want.Serial, s): + return cond(kind, metav1.ConditionFalse, ReasonSerialMismatch, "the System with spec.identity.systemUUID reports another serial; spec is not changed") + case !modelMatches(want.Model, s.Model): + return cond(kind, metav1.ConditionFalse, ReasonModelMismatch, "the System reports a model other than spec.identity.model; spec is not changed") + } + if want.SystemUUID != "" { + compared = append(compared, "systemUUID") + } + if want.Serial != "" { + compared = append(compared, "serial") + } + compared = append(compared, "model") + return cond(kind, metav1.ConditionTrue, ReasonMatched, "System "+s.ID+" matches spec.identity ("+strings.Join(compared, ", ")+")") +} + +func uniqueCondition(status *inventory.DeviceStatus, sharing []string) metav1.Condition { + kind := inventory.ConditionPublicKeyUnique + if status.Discovery == nil || status.Discovery.TLS == nil { + return cond(kind, metav1.ConditionUnknown, ReasonNotObserved, "no TLS public key has been observed") + } + if len(sharing) == 0 { + return cond(kind, metav1.ConditionTrue, ReasonUnique, "no other discovered Device presents this TLS public key") + } + sort.Strings(sharing) + names := sharing + if len(names) > 3 { + names = names[:3] + } + return cond(kind, metav1.ConditionFalse, ReasonSharedPublicKey, fmt.Sprintf("%d other Devices present this TLS public key (%s); the pin cannot tell these BMCs apart", + len(sharing), strings.Join(names, ", "))) +} + +// sharingKey lists the other Devices whose retained TLS observation has the +// same public key as device. +func sharingKey(device *inventory.Device, status *inventory.DeviceStatus, all []inventory.Device) []string { + if status.Discovery == nil || status.Discovery.TLS == nil { + return nil + } + var out []string + for i := range all { + other := &all[i] + if other.Namespace == device.Namespace && other.Name == device.Name { + continue + } + if d := other.Status.Discovery; d != nil && d.TLS != nil && d.TLS.PublicKeySHA256 == status.Discovery.TLS.PublicKeySHA256 { + out = append(out, other.Namespace+"/"+other.Name) + } + } + return out +}