Skip to main content

nv_redfish/account/
mod.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! AccountService (Redfish) — high-level wrappers
17//!
18//! Feature: `accounts` (this module is compiled only when the feature is enabled).
19//!
20//! This module provides ergonomic wrappers around the generated Redfish
21//! AccountService model:
22//! - `AccountService`: entry point to manage accounts
23//! - `AccountCollection`: access and create `ManagerAccount` members
24//! - `Account`: operate on an individual `ManagerAccount`
25//!
26//! Vendor compatibility
27//! - Some implementations omit fields marked as `Redfish.Required`.
28//! - This crate can apply read/response patches (see `patch_support`) to keep
29//!   behavior compatible across vendors (for example, defaulting `AccountTypes`).
30//!
31
32/// Collection of accounts.
33mod collection;
34/// Account inside account service.
35mod item;
36
37use crate::patch_support::JsonValue;
38use crate::patch_support::ReadPatchFn;
39use crate::schema::redfish::account_service::AccountService as SchemaAccountService;
40use crate::Error;
41use crate::NvBmc;
42use crate::ServiceRoot;
43use nv_redfish_core::Bmc;
44use std::sync::Arc;
45
46#[doc(inline)]
47pub use crate::schema::redfish::manager_account::AccountTypes;
48#[doc(inline)]
49pub use crate::schema::redfish::manager_account::ManagerAccountCreate;
50#[doc(inline)]
51pub use crate::schema::redfish::manager_account::ManagerAccountUpdate;
52#[doc(inline)]
53pub use item::Account;
54
55#[doc(inline)]
56pub use collection::AccountCollection;
57#[doc(inline)]
58pub(crate) use collection::SlotDefinedConfig;
59#[doc(inline)]
60pub(crate) use item::Config as AccountConfig;
61
62/// Account service. Provides the ability to manage accounts via Redfish.
63pub struct AccountService<B: Bmc> {
64    collection_config: collection::Config,
65    service: Arc<SchemaAccountService>,
66    bmc: NvBmc<B>,
67}
68
69impl<B: Bmc> AccountService<B> {
70    /// Create a new account service. This is always done by
71    /// `ServiceRoot` object.
72    pub(crate) async fn new(
73        bmc: &NvBmc<B>,
74        root: &ServiceRoot<B>,
75    ) -> Result<Option<Self>, Error<B>> {
76        let Some(service_nav) = root.root.account_service.as_ref() else {
77            return Ok(None);
78        };
79        let service = service_nav.get(bmc.as_ref()).await.map_err(Error::Bmc)?;
80
81        let mut patches = Vec::new();
82        if bmc.quirks.bug_no_account_type_in_accounts() {
83            patches.push(append_default_account_type);
84        }
85        let account_read_patch_fn = if patches.is_empty() {
86            None
87        } else {
88            let account_read_patch_fn: ReadPatchFn =
89                Arc::new(move |v| patches.iter().fold(v, |acc, f| f(acc)));
90            Some(account_read_patch_fn)
91        };
92        let slot_defined_user_accounts = bmc.quirks.slot_defined_user_accounts();
93        Ok(Some(Self {
94            collection_config: collection::Config {
95                account: AccountConfig {
96                    read_patch_fn: account_read_patch_fn,
97                    disable_account_on_delete: slot_defined_user_accounts
98                        .as_ref()
99                        .is_some_and(|cfg| cfg.disable_account_on_delete),
100                },
101                slot_defined_user_accounts,
102            },
103            service,
104            bmc: bmc.clone(),
105        }))
106    }
107
108    /// Get the raw schema data for this account service.
109    ///
110    /// Returns an `Arc` to the underlying schema, allowing cheap cloning
111    /// and sharing of the data.
112    #[must_use]
113    pub fn raw(&self) -> Arc<SchemaAccountService> {
114        self.service.clone()
115    }
116
117    /// Get the accounts collection.
118    ///
119    /// Uses `$expand` to retrieve members in a single request when supported.
120    ///
121    /// # Errors
122    ///
123    /// Returns an error if expanding the collection fails.
124    pub async fn accounts(&self) -> Result<Option<AccountCollection<B>>, Error<B>> {
125        if let Some(collection_ref) = self.service.accounts.as_ref() {
126            AccountCollection::new(
127                self.bmc.clone(),
128                collection_ref,
129                self.collection_config.clone(),
130            )
131            .await
132            .map(Some)
133        } else {
134            Ok(None)
135        }
136    }
137}
138
139// `AccountTypes` is marked as `Redfish.Required`, but some systems
140// ignore this requirement. The account service replaces its value with
141// a reasonable default (see below).
142//
143// Note quote from schema: "if this property is not provided by the client, the default value
144// shall be an array that contains the value `Redfish`".
145fn append_default_account_type(v: JsonValue) -> JsonValue {
146    if let JsonValue::Object(mut obj) = v {
147        obj.entry("AccountTypes")
148            .or_insert(JsonValue::Array(vec![JsonValue::String("Redfish".into())]));
149        JsonValue::Object(obj)
150    } else {
151        v
152    }
153}