From 099f77aaf6cc181445ef5a837a26170e9cb4c111 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Tue, 24 Nov 2026 22:10:36 -0600 Subject: [PATCH 1/2] feat(bmc-discovery): Record offered reset types Power admission must refuse an action the server does not offer before anything is sent. Discovery now records the ComputerSystem.Reset types each System advertises, inline or from the System's own ActionInfo, in status.discovery.inventory.systems[].resetTypes. It reads them with GETs and never invokes the action. A reset target or ActionInfo off the System records none. Discover and Inventory share one reset-type reader, so both parse ActionInfo the same way. An ActionInfo that cannot be read records no reset types and keeps the rest of the inventory, so one broken link never costs a Device its discovery. Ported from the power prototype in #175, without its worker client. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 4 + docs/operations/bmc-discovery.md | 20 +++-- internal/api/inventory/v1alpha1/types.go | 4 +- internal/bmcdiscovery/discovery_test.go | 10 ++- internal/bmcdiscovery/status.go | 16 +++- internal/redfish/client.go | 36 +-------- internal/redfish/inventory.go | 20 ++++- internal/redfish/reset.go | 45 +++++++++++ internal/redfish/reset_test.go | 77 +++++++++++++++++++ 9 files changed, 188 insertions(+), 44 deletions(-) create mode 100644 internal/redfish/reset.go create mode 100644 internal/redfish/reset_test.go diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index 3bb23d60..c6534990 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -641,6 +641,10 @@ spec: serialNumber: {type: string, maxLength: 253} sku: {type: string, maxLength: 253} powerState: {type: string, maxLength: 63} + resetTypes: + type: array + maxItems: 16 + items: {type: string, minLength: 1, maxLength: 63} networkInterfaces: type: array maxItems: 32 diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index cb149386..26910aba 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -274,6 +274,7 @@ status: serialNumber: SYNTHETIC-0001 sku: TAG0001 powerState: "On" + resetTypes: ["On", ForceOff, ForceRestart] networkInterfaces: - {id: NIC.1, macAddress: "00:00:5e:00:53:01", linkStatus: LinkUp, speedMbps: 25000} conditions: [...] @@ -325,11 +326,20 @@ is `StaleObservation`. ## 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. +with each one's EthernetInterfaces (up to 32). For each System it records +the `ComputerSystem.Reset` types the BMC advertises, inline or from the +System's own ActionInfo, as `resetTypes`. It reads the action's description +and never invokes it. A reset target or ActionInfo off the System, or an +ActionInfo that cannot be read, records none and keeps the rest of the +inventory. A rejected credential on the ActionInfo, such as a 403, fails the +read like any other rejected credential. Nothing reads `resetTypes` yet: it is +recorded for planned Device power operations, which will refuse an action the +server does not offer. + +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. diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 973e9433..562a23f9 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -256,7 +256,8 @@ type ObservedManager struct { } // ObservedSystem is one Redfish ComputerSystem. PowerState is an observation -// only; discovery never changes power. +// only; discovery never changes power. ResetTypes are the ComputerSystem.Reset +// types the BMC advertises for the System, read but never invoked. type ObservedSystem struct { ID string `json:"id"` UUID string `json:"uuid,omitempty"` @@ -266,6 +267,7 @@ type ObservedSystem struct { SKU string `json:"sku,omitempty"` PowerState string `json:"powerState,omitempty"` NetworkInterfaces []ObservedNetworkInterface `json:"networkInterfaces,omitempty"` + ResetTypes []string `json:"resetTypes,omitempty"` } // ObservedNetworkInterface is one Redfish EthernetInterface. diff --git a/internal/bmcdiscovery/discovery_test.go b/internal/bmcdiscovery/discovery_test.go index e32a4c21..e4f6c361 100644 --- a/internal/bmcdiscovery/discovery_test.go +++ b/internal/bmcdiscovery/discovery_test.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "sync" "sync/atomic" @@ -587,7 +588,9 @@ func TestEndToEndOverTLS(t *testing.T) { "/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"}`, + "/redfish/v1/Systems/1": `{"Id":"1","UUID":"00000000-0000-4000-8000-000000000001","Model":"Example 1U","SerialNumber":"SYNTHETIC-0001","PowerState":"Off", + "Actions":{"#ComputerSystem.Reset":{"target":"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset","@Redfish.ActionInfo":"/redfish/v1/Systems/1/ResetActionInfo"}}}`, + "/redfish/v1/Systems/1/ResetActionInfo": `{"Parameters":[{"Name":"ResetType","Required":"true","DataType":"String","AllowableValues":["On","ForceOff","ForceRestart"]}]}`, } server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, authed := r.BasicAuth() @@ -640,6 +643,11 @@ func TestEndToEndOverTLS(t *testing.T) { if c := condition(t, got.Status, inventory.ConditionIdentityMatched); c.Status != metav1.ConditionTrue { t.Fatalf("IdentityMatched = %+v", c) } + // Offered reset types come from the ActionInfo, read with a GET; the + // action itself is never invoked. + if types := got.Status.Discovery.Inventory.Systems[0].ResetTypes; !slices.Equal(types, []string{"On", "ForceOff", "ForceRestart"}) { + t.Fatalf("resetTypes = %v", types) + } mu.Lock() defer mu.Unlock() for _, l := range log { diff --git a/internal/bmcdiscovery/status.go b/internal/bmcdiscovery/status.go index 47dab77d..954e6e93 100644 --- a/internal/bmcdiscovery/status.go +++ b/internal/bmcdiscovery/status.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "slices" "sort" "strings" "time" @@ -217,7 +218,20 @@ func observedInventory(inv redfish.Inventory, at metav1.Time, endpoint string) * 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)}) + Model: clip(s.Model, 253), SerialNumber: clip(s.SerialNumber, 253), SKU: clip(s.SKU, 253), PowerState: clip(s.PowerState, 63), NetworkInterfaces: nics(s.NetworkInterfaces), + ResetTypes: resetTypes(s.ResetTypes)}) + } + } + return out +} + +// resetTypes keeps up to 16 distinct, nonempty advertised reset types. +func resetTypes(in []string) []string { + var out []string + for _, v := range in { + v = clip(v, 63) + if v != "" && !slices.Contains(out, v) && len(out) < 16 { + out = append(out, v) } } return out diff --git a/internal/redfish/client.go b/internal/redfish/client.go index 38fe62e3..11f6f2b5 100644 --- a/internal/redfish/client.go +++ b/internal/redfish/client.go @@ -365,40 +365,8 @@ func (c *Client) Identify(ctx context.Context, t Target) (System, error) { if err := json.Unmarshal(s.RawData, &raw); err != nil { return System{}, classify(err) } - reset := raw.Actions.Reset - target, err := cleanPath(reset.Target) - if err != nil || !strings.HasPrefix(target, sys.Path+"/") { - return System{}, fmt.Errorf("%w: ComputerSystem.Reset target not on the enrolled System", ErrUnsupported) - } - sys.ResetTarget = target - sys.ResetTypes = reset.Allowed - if len(sys.ResetTypes) == 0 && reset.Info != "" { - info, err := cleanPath(reset.Info) - if err != nil || !strings.HasPrefix(info, sys.Path+"/") { - return System{}, fmt.Errorf("%w: ActionInfo not on the enrolled System", ErrUnsupported) - } - // Not schemas.ActionInfo: its typed decode rejects the whole document - // for one off-schema property, as the DMTF emulator's string - // "Required": "true". Only the ResetType values are read. - resp, err := api.Get(info) - var ai struct { - Parameters []struct { - Name, DataType string - AllowableValues []string - } - } - if err == nil { - err = json.NewDecoder(resp.Body).Decode(&ai) - } - schemas.DeferredCleanupHTTPResponse(resp) - if err != nil { - return System{}, classify(err) - } - for _, p := range ai.Parameters { - if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { - sys.ResetTypes = p.AllowableValues - } - } + if sys.ResetTarget, sys.ResetTypes, err = resetTypes(api, sys.Path, raw); err != nil { + return System{}, err } for _, b := range s.Boot.AllowableBootSourceOverrideTargetValues { sys.BootTargets = append(sys.BootTargets, string(b)) diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index e38a6f1a..7c389b86 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -44,6 +44,9 @@ type InventorySystem struct { PowerState string // NetworkInterfaces are the System's EthernetInterfaces. NetworkInterfaces []NetworkInterface + // ResetTypes are the ComputerSystem.Reset types the System advertises. + // Discovery reads them and never invokes the action. + ResetTypes []string } // NetworkInterface is one Redfish EthernetInterface. @@ -109,6 +112,7 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { SKU string PowerState string EthernetInterfaces link + resetAction } if err := getJSON(api, p, &doc); err != nil { return Inventory{}, err @@ -117,8 +121,20 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { 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}) + system := 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} + if doc.Actions.Reset.Target != "" { + // Reset types are optional. A reset target or ActionInfo off + // the System, or an ActionInfo that cannot be read, records + // none and keeps the rest of the inventory. Only a rejected + // credential, pin or identity fails the read. + if _, types, err := resetTypes(api, p, doc.resetAction); err == nil { + system.ResetTypes = types + } else if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { + return Inventory{}, err + } + } + inv.Systems = append(inv.Systems, system) } } return inv, nil diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go new file mode 100644 index 00000000..33e2ecba --- /dev/null +++ b/internal/redfish/reset.go @@ -0,0 +1,45 @@ +package redfish + +import ( + "fmt" + "strings" + + "github.com/stmcginnis/gofish" +) + +// resetTypes returns the ComputerSystem.Reset types a System advertises, +// inline or through its ActionInfo, and the action target. Both must belong to +// the System at sysPath. It issues at most one GET, of the ActionInfo, and +// never invokes the action. +func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, err error) { + reset := raw.Actions.Reset + target, err = cleanPath(reset.Target) + if err != nil || !strings.HasPrefix(target, sysPath+"/") { + return "", nil, fmt.Errorf("%w: ComputerSystem.Reset target not on the System", ErrUnsupported) + } + if len(reset.Allowed) != 0 || reset.Info == "" { + return target, reset.Allowed, nil + } + info, err := cleanPath(reset.Info) + if err != nil || !strings.HasPrefix(info, sysPath+"/") { + return "", nil, fmt.Errorf("%w: ActionInfo not on the System", ErrUnsupported) + } + // Not schemas.ActionInfo: its typed decode rejects the whole document + // for one off-schema property, as the DMTF emulator's string + // "Required": "true". Only the ResetType values are read. + var ai struct { + Parameters []struct { + Name, DataType string + AllowableValues []string + } + } + if err := getJSON(api, info, &ai); err != nil { + return "", nil, err + } + for _, p := range ai.Parameters { + if p.Name == "ResetType" && (p.DataType == "" || p.DataType == "String") { + types = p.AllowableValues + } + } + return target, types, nil +} diff --git a/internal/redfish/reset_test.go b/internal/redfish/reset_test.go new file mode 100644 index 00000000..7937dc92 --- /dev/null +++ b/internal/redfish/reset_test.go @@ -0,0 +1,77 @@ +package redfish + +import ( + "context" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" +) + +// Discovery reads offered reset types inline or from the System's own +// ActionInfo, with GETs only. A reset target off the System records none. +func TestInventoryRecordsResetTypes(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems"] = map[string]any{"Members": []any{ + map[string]string{"@odata.id": "/redfish/v1/Systems/1"}, + map[string]string{"@odata.id": "/redfish/v1/Systems/2"}, + map[string]string{"@odata.id": "/redfish/v1/Systems/3"}, + }} + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}} + bmc.docs["/redfish/v1/Systems/1/ResetActionInfo"] = map[string]any{"Parameters": []any{map[string]any{ + "Name": "ResetType", "Required": "true", "DataType": "String", "AllowableValues": []string{"On", "ForceOff", "ForceRestart"}}}} + bmc.docs["/redfish/v1/Systems/2"] = map[string]any{"Id": "2", "UUID": "00000000-0000-4000-8000-0000000000b2", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/2/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "PowerCycle"}}}} + bmc.docs["/redfish/v1/Systems/3"] = map[string]any{"Id": "3", "UUID": "00000000-0000-4000-8000-0000000000c3", "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On"}}}} + server := httptest.NewTLSServer(bmc) + t.Cleanup(server.Close) + client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), 5*time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := client.Inventory(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(inv.Systems) != 3 || !slices.Equal(inv.Systems[0].ResetTypes, []string{"On", "ForceOff", "ForceRestart"}) || + !slices.Equal(inv.Systems[1].ResetTypes, []string{"On", "PowerCycle"}) || inv.Systems[2].ResetTypes != nil { + t.Fatalf("systems = %+v", inv.Systems) + } + requests, _ := bmc.seen() + for _, request := range requests { + if !strings.HasPrefix(request, "GET ") || strings.Contains(request, "/Actions/") { + t.Fatalf("discovery issued %s", request) + } + } +} + +// An ActionInfo that cannot be read records no reset types and keeps the +// rest of the inventory. +func TestInventoryKeepsTheSystemWhenActionInfoFails(t *testing.T) { + for name, info := range map[string]any{"missing": nil, "malformed": "not an ActionInfo"} { + t.Run(name, func(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}} + if info != nil { + bmc.docs["/redfish/v1/Systems/1/ResetActionInfo"] = info + } + server := httptest.NewTLSServer(bmc) + t.Cleanup(server.Close) + client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), 5*time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := client.Inventory(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { + t.Fatalf("systems = %+v", inv.Systems) + } + }) + } +} From 75d00b3806b9c4349c55e28e84a054bfd1ae0541 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 13:24:14 -0600 Subject: [PATCH 2/2] fix(bmc-discovery): Keep the System when its actions are malformed The System document decoded its Actions strictly, so one off-schema reset annotation failed the whole inventory read. Actions now decode on their own, and a malformed value records no reset types. An ActionInfo under the System's Actions is no longer read, so discovery never sends a request there. Tests cover the guarded ActionInfo paths, ActionInfo server errors and rejected credentials, and the recorded reset type bounds. Co-Authored-By: Claude Opus 5.5 --- docs/operations/bmc-discovery.md | 10 ++- internal/bmcdiscovery/status_test.go | 21 +++++ internal/redfish/inventory.go | 20 +++-- internal/redfish/reset.go | 6 +- internal/redfish/reset_test.go | 110 +++++++++++++++++++++++++++ 5 files changed, 152 insertions(+), 15 deletions(-) create mode 100644 internal/bmcdiscovery/status_test.go diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index 26910aba..49a45f7f 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -329,10 +329,12 @@ Service root, then every Manager and every ComputerSystem (up to 16 of each), with each one's EthernetInterfaces (up to 32). For each System it records the `ComputerSystem.Reset` types the BMC advertises, inline or from the System's own ActionInfo, as `resetTypes`. It reads the action's description -and never invokes it. A reset target or ActionInfo off the System, or an -ActionInfo that cannot be read, records none and keeps the rest of the -inventory. A rejected credential on the ActionInfo, such as a 403, fails the -read like any other rejected credential. Nothing reads `resetTypes` yet: it is +and never invokes it. It keeps at most 16 distinct values. Malformed actions, +a reset target off the System, an ActionInfo off the System or under its +Actions, or an ActionInfo that cannot be read (missing, malformed, a server +error or a timeout) records none and keeps the rest of the inventory. A +rejected credential (401 or 403), a pin mismatch or an unexpected resource +path on the ActionInfo fails the read. Nothing reads `resetTypes` yet: it is recorded for planned Device power operations, which will refuse an action the server does not offer. diff --git a/internal/bmcdiscovery/status_test.go b/internal/bmcdiscovery/status_test.go new file mode 100644 index 00000000..2893ae01 --- /dev/null +++ b/internal/bmcdiscovery/status_test.go @@ -0,0 +1,21 @@ +package bmcdiscovery + +import ( + "fmt" + "slices" + "strings" + "testing" +) + +// Recorded reset types stay within the Device schema: at most 16 distinct, +// nonempty values of at most 63 characters each. +func TestResetTypesStayWithinTheSchema(t *testing.T) { + in := []string{"On", " On ", "", " ", strings.Repeat("x", 80)} + for i := range 20 { + in = append(in, fmt.Sprintf("Vendor%d", i)) + } + got := resetTypes(in) + if len(got) != 16 || !slices.Equal(got[:2], []string{"On", strings.Repeat("x", 63)}) || got[15] != "Vendor13" { + t.Fatalf("resetTypes = %v", got) + } +} diff --git a/internal/redfish/inventory.go b/internal/redfish/inventory.go index 7c389b86..ecc79294 100644 --- a/internal/redfish/inventory.go +++ b/internal/redfish/inventory.go @@ -62,7 +62,8 @@ type NetworkInterface struct { // 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. +// failed read fails the whole observation; nothing partial is returned. The +// optional reset types are the exception: see below. func (c *Client) Inventory(ctx context.Context) (Inventory, error) { api, err := c.connect(ctx) if err != nil { @@ -112,7 +113,9 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { SKU string PowerState string EthernetInterfaces link - resetAction + // Decoded on its own below, so an off-schema action + // annotation cannot fail the rest of the System. + Actions json.RawMessage } if err := getJSON(api, p, &doc); err != nil { return Inventory{}, err @@ -123,12 +126,13 @@ func (c *Client) Inventory(ctx context.Context) (Inventory, error) { } system := 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} - if doc.Actions.Reset.Target != "" { - // Reset types are optional. A reset target or ActionInfo off - // the System, or an ActionInfo that cannot be read, records - // none and keeps the rest of the inventory. Only a rejected - // credential, pin or identity fails the read. - if _, types, err := resetTypes(api, p, doc.resetAction); err == nil { + // Reset types are optional. Malformed actions, a reset target or + // ActionInfo off the System, or an ActionInfo that cannot be read + // records none and keeps the rest of the inventory. Only a + // rejected credential, pin or identity fails the read. + var raw resetAction + if json.Unmarshal(doc.Actions, &raw.Actions) == nil && raw.Actions.Reset.Target != "" { + if _, types, err := resetTypes(api, p, raw); err == nil { system.ResetTypes = types } else if errors.Is(err, ErrUnauthorized) || errors.Is(err, ErrPinMismatch) || errors.Is(err, ErrIdentity) { return Inventory{}, err diff --git a/internal/redfish/reset.go b/internal/redfish/reset.go index 33e2ecba..f3ff6000 100644 --- a/internal/redfish/reset.go +++ b/internal/redfish/reset.go @@ -9,8 +9,8 @@ import ( // resetTypes returns the ComputerSystem.Reset types a System advertises, // inline or through its ActionInfo, and the action target. Both must belong to -// the System at sysPath. It issues at most one GET, of the ActionInfo, and -// never invokes the action. +// the System at sysPath, and the ActionInfo must not sit under its Actions. It +// issues at most one GET, of the ActionInfo, and never invokes the action. func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target string, types []string, err error) { reset := raw.Actions.Reset target, err = cleanPath(reset.Target) @@ -21,7 +21,7 @@ func resetTypes(api *gofish.APIClient, sysPath string, raw resetAction) (target return target, reset.Allowed, nil } info, err := cleanPath(reset.Info) - if err != nil || !strings.HasPrefix(info, sysPath+"/") { + if err != nil || !strings.HasPrefix(info, sysPath+"/") || strings.Contains(info+"/", "/Actions/") { return "", nil, fmt.Errorf("%w: ActionInfo not on the System", ErrUnsupported) } // Not schemas.ActionInfo: its typed decode rejects the whole document diff --git a/internal/redfish/reset_test.go b/internal/redfish/reset_test.go index 7937dc92..f8a2a63f 100644 --- a/internal/redfish/reset_test.go +++ b/internal/redfish/reset_test.go @@ -2,8 +2,11 @@ package redfish import ( "context" + "errors" + "net/http" "net/http/httptest" "slices" + "strconv" "strings" "testing" "time" @@ -75,3 +78,110 @@ func TestInventoryKeepsTheSystemWhenActionInfoFails(t *testing.T) { }) } } + +// An off-schema Actions document records no reset types and keeps the rest +// of the System, as the lenient decode does for any other property. +func TestInventoryKeepsTheSystemWhenActionsAreMalformed(t *testing.T) { + for name, actions := range map[string]any{ + "actions string": "not actions", + "numeric types": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []int{1, 2}}}, + "action info object": map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": map[string]string{"@odata.id": "/redfish/v1/Systems/1/ResetActionInfo"}}}, + } { + t.Run(name, func(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = actions + inv := inventoryOf(t, bmc) + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || inv.Systems[0].PowerState != "Off" || len(inv.Systems[0].NetworkInterfaces) != 1 { + t.Fatalf("systems = %+v", inv.Systems) + } + }) + } +} + +// An ActionInfo under the System's Actions, off the System, or outside the +// service is never read, so discovery sends no request under /Actions/. +func TestInventoryNeverReadsAGuardedActionInfo(t *testing.T) { + offered := map[string]any{"Parameters": []any{map[string]any{"Name": "ResetType", "AllowableValues": []string{"On"}}}} + for name, info := range map[string]string{ + "reset target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", + "under actions": "/redfish/v1/Systems/1/Actions/ResetActionInfo", + "actions itself": "/redfish/v1/Systems/1/Actions", + "other system": "/redfish/v1/Systems/2/ResetActionInfo", + "dot segments": "/redfish/v1/Systems/1/../2/ResetActionInfo", + "absolute url": "https://bmc.example.invalid/redfish/v1/Systems/1/ResetActionInfo", + } { + t.Run(name, func(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": info}} + for _, p := range []string{"/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "/redfish/v1/Systems/1/Actions/ResetActionInfo", + "/redfish/v1/Systems/1/Actions", "/redfish/v1/Systems/2/ResetActionInfo"} { + bmc.docs[p] = offered + } + inv := inventoryOf(t, bmc) + if len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + t.Fatalf("systems = %+v", inv.Systems) + } + requests, _ := bmc.seen() + for _, request := range requests { + if !strings.HasPrefix(request, "GET ") || strings.Contains(request, "/Actions") || strings.Contains(request, "/Systems/2") { + t.Fatalf("discovery issued %s", request) + } + } + }) + } +} + +// A failed ActionInfo read records none and keeps the inventory, except a +// rejected credential, which fails the read like any other. +func TestInventoryActionInfoStatus(t *testing.T) { + for _, tc := range []struct { + status int + fatal bool + }{{http.StatusInternalServerError, false}, {http.StatusServiceUnavailable, false}, {http.StatusUnauthorized, true}, {http.StatusForbidden, true}} { + t.Run(strconv.Itoa(tc.status), func(t *testing.T) { + bmc := newInventoryBMC() + bmc.docs["/redfish/v1/Systems/1"].(map[string]any)["Actions"] = map[string]any{"#ComputerSystem.Reset": map[string]any{ + "target": "/redfish/v1/Systems/1/Actions/ComputerSystem.Reset", "@Redfish.ActionInfo": "/redfish/v1/Systems/1/ResetActionInfo"}} + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/redfish/v1/Systems/1/ResetActionInfo" { + w.WriteHeader(tc.status) + return + } + bmc.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), 5*time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := client.Inventory(context.Background()) + if tc.fatal { + if !errors.Is(err, ErrUnauthorized) || len(inv.Systems) != 0 { + t.Fatalf("inventory = %+v, err = %v", inv, err) + } + return + } + if err != nil || len(inv.Systems) != 1 || inv.Systems[0].ResetTypes != nil || len(inv.Systems[0].NetworkInterfaces) != 1 { + t.Fatalf("inventory = %+v, err = %v", inv, err) + } + }) + } +} + +func inventoryOf(t *testing.T, bmc *inventoryBMC) Inventory { + t.Helper() + server := httptest.NewTLSServer(bmc) + t.Cleanup(server.Close) + client, err := NewPinnedClient(server.URL, "operator", "synthetic-secret", PublicKeySHA256(server.Certificate()), 5*time.Second) + if err != nil { + t.Fatal(err) + } + inv, err := client.Inventory(context.Background()) + if err != nil { + t.Fatal(err) + } + return inv +}