xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision 092a33f195800301a7a6e1437e38515a02e10011)
140e9b92eSEd Tanous // SPDX-License-Identifier: Apache-2.0
240e9b92eSEd Tanous // SPDX-FileCopyrightText: Copyright OpenBMC Authors
340e9b92eSEd Tanous // SPDX-FileCopyrightText: Copyright 2018 Intel Corporation
488d16c9aSLewanczyk, Dawid #pragma once
588d16c9aSLewanczyk, Dawid 
6d7857201SEd Tanous #include "bmcweb_config.h"
7d7857201SEd Tanous 
83ccb3adbSEd Tanous #include "app.hpp"
9d7857201SEd Tanous #include "async_resp.hpp"
10a0735a4eSGunnar Mills #include "boost_formatters.hpp"
111aa375b8SEd Tanous #include "certificate_service.hpp"
123ccb3adbSEd Tanous #include "dbus_utility.hpp"
133ccb3adbSEd Tanous #include "error_messages.hpp"
140ec8b83dSEd Tanous #include "generated/enums/account_service.hpp"
15d7857201SEd Tanous #include "http_request.hpp"
16d7857201SEd Tanous #include "http_response.hpp"
17d7857201SEd Tanous #include "logging.hpp"
18d7857201SEd Tanous #include "pam_authenticate.hpp"
193ccb3adbSEd Tanous #include "persistent_data.hpp"
20d7857201SEd Tanous #include "privileges.hpp"
213ccb3adbSEd Tanous #include "query.hpp"
220ec8b83dSEd Tanous #include "registries/privilege_registry.hpp"
233281bcf1SEd Tanous #include "sessions.hpp"
241aa375b8SEd Tanous #include "utils/collection.hpp"
253ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
263ccb3adbSEd Tanous #include "utils/json_utils.hpp"
270ec8b83dSEd Tanous 
28d7857201SEd Tanous #include <security/_pam_types.h>
29d7857201SEd Tanous #include <systemd/sd-bus.h>
30d7857201SEd Tanous 
31d7857201SEd Tanous #include <boost/beast/http/field.hpp>
32d7857201SEd Tanous #include <boost/beast/http/status.hpp>
33d7857201SEd Tanous #include <boost/beast/http/verb.hpp>
341aa375b8SEd Tanous #include <boost/url/format.hpp>
351aa375b8SEd Tanous #include <boost/url/url.hpp>
36d7857201SEd Tanous #include <nlohmann/json.hpp>
37d7857201SEd Tanous #include <sdbusplus/message.hpp>
38d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
391214b7e7SGunnar Mills 
40d7857201SEd Tanous #include <algorithm>
412b73119cSGeorge Liu #include <array>
42d7857201SEd Tanous #include <cstddef>
43d7857201SEd Tanous #include <cstdint>
44d7857201SEd Tanous #include <cstring>
45d7857201SEd Tanous #include <format>
46d7857201SEd Tanous #include <functional>
471aa375b8SEd Tanous #include <memory>
48c7229815SAbhishek Patel #include <optional>
493544d2a7SEd Tanous #include <ranges>
50c7229815SAbhishek Patel #include <string>
512b73119cSGeorge Liu #include <string_view>
5220fa6a2cSEd Tanous #include <utility>
53d7857201SEd Tanous #include <variant>
54c7229815SAbhishek Patel #include <vector>
55c7229815SAbhishek Patel 
561abe55efSEd Tanous namespace redfish
571abe55efSEd Tanous {
5888d16c9aSLewanczyk, Dawid 
5923a21a1cSEd Tanous constexpr const char* ldapConfigObjectName =
606973a582SRatan Gupta     "/xyz/openbmc_project/user/ldap/openldap";
612c70f800SEd Tanous constexpr const char* adConfigObject =
62ab828d7cSRatan Gupta     "/xyz/openbmc_project/user/ldap/active_directory";
63ab828d7cSRatan Gupta 
64b477fd44SP Dheeraj Srujan Kumar constexpr const char* rootUserDbusPath = "/xyz/openbmc_project/user/";
656973a582SRatan Gupta constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
666973a582SRatan Gupta constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
676973a582SRatan Gupta constexpr const char* ldapConfigInterface =
686973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Config";
696973a582SRatan Gupta constexpr const char* ldapCreateInterface =
706973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Create";
716973a582SRatan Gupta constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
7206785244SRatan Gupta constexpr const char* ldapPrivMapperInterface =
7306785244SRatan Gupta     "xyz.openbmc_project.User.PrivilegeMapper";
746973a582SRatan Gupta 
7554fc587aSNagaraju Goruganti struct LDAPRoleMapData
7654fc587aSNagaraju Goruganti {
7754fc587aSNagaraju Goruganti     std::string groupName;
7854fc587aSNagaraju Goruganti     std::string privilege;
7954fc587aSNagaraju Goruganti };
8054fc587aSNagaraju Goruganti 
816973a582SRatan Gupta struct LDAPConfigData
826973a582SRatan Gupta {
8347f2934cSEd Tanous     std::string uri;
8447f2934cSEd Tanous     std::string bindDN;
8547f2934cSEd Tanous     std::string baseDN;
8647f2934cSEd Tanous     std::string searchScope;
8747f2934cSEd Tanous     std::string serverType;
886973a582SRatan Gupta     bool serviceEnabled = false;
8947f2934cSEd Tanous     std::string userNameAttribute;
9047f2934cSEd Tanous     std::string groupAttribute;
9154fc587aSNagaraju Goruganti     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
926973a582SRatan Gupta };
936973a582SRatan Gupta 
9454fc587aSNagaraju Goruganti inline std::string getRoleIdFromPrivilege(std::string_view role)
9584e12cb7SAppaRao Puli {
9684e12cb7SAppaRao Puli     if (role == "priv-admin")
9784e12cb7SAppaRao Puli     {
9884e12cb7SAppaRao Puli         return "Administrator";
9984e12cb7SAppaRao Puli     }
1003174e4dfSEd Tanous     if (role == "priv-user")
10184e12cb7SAppaRao Puli     {
102c80fee55SAppaRao Puli         return "ReadOnly";
10384e12cb7SAppaRao Puli     }
1043174e4dfSEd Tanous     if (role == "priv-operator")
10584e12cb7SAppaRao Puli     {
10684e12cb7SAppaRao Puli         return "Operator";
10784e12cb7SAppaRao Puli     }
10884e12cb7SAppaRao Puli     return "";
10984e12cb7SAppaRao Puli }
11054fc587aSNagaraju Goruganti inline std::string getPrivilegeFromRoleId(std::string_view role)
11184e12cb7SAppaRao Puli {
11284e12cb7SAppaRao Puli     if (role == "Administrator")
11384e12cb7SAppaRao Puli     {
11484e12cb7SAppaRao Puli         return "priv-admin";
11584e12cb7SAppaRao Puli     }
1163174e4dfSEd Tanous     if (role == "ReadOnly")
11784e12cb7SAppaRao Puli     {
11884e12cb7SAppaRao Puli         return "priv-user";
11984e12cb7SAppaRao Puli     }
1203174e4dfSEd Tanous     if (role == "Operator")
12184e12cb7SAppaRao Puli     {
12284e12cb7SAppaRao Puli         return "priv-operator";
12384e12cb7SAppaRao Puli     }
12484e12cb7SAppaRao Puli     return "";
12584e12cb7SAppaRao Puli }
126b9b2e0b2SEd Tanous 
127c7229815SAbhishek Patel /**
128c7229815SAbhishek Patel  * @brief Maps user group names retrieved from D-Bus object to
129c7229815SAbhishek Patel  * Account Types.
130c7229815SAbhishek Patel  *
131c7229815SAbhishek Patel  * @param[in] userGroups List of User groups
132c7229815SAbhishek Patel  * @param[out] res AccountTypes populated
133c7229815SAbhishek Patel  *
134c7229815SAbhishek Patel  * @return true in case of success, false if UserGroups contains
135c7229815SAbhishek Patel  * invalid group name(s).
136c7229815SAbhishek Patel  */
137c7229815SAbhishek Patel inline bool translateUserGroup(const std::vector<std::string>& userGroups,
138c7229815SAbhishek Patel                                crow::Response& res)
139c7229815SAbhishek Patel {
140c7229815SAbhishek Patel     std::vector<std::string> accountTypes;
141c7229815SAbhishek Patel     for (const auto& userGroup : userGroups)
142c7229815SAbhishek Patel     {
143c7229815SAbhishek Patel         if (userGroup == "redfish")
144c7229815SAbhishek Patel         {
145c7229815SAbhishek Patel             accountTypes.emplace_back("Redfish");
146c7229815SAbhishek Patel             accountTypes.emplace_back("WebUI");
147c7229815SAbhishek Patel         }
148c7229815SAbhishek Patel         else if (userGroup == "ipmi")
149c7229815SAbhishek Patel         {
150c7229815SAbhishek Patel             accountTypes.emplace_back("IPMI");
151c7229815SAbhishek Patel         }
152c7229815SAbhishek Patel         else if (userGroup == "ssh")
153c7229815SAbhishek Patel         {
154c7229815SAbhishek Patel             accountTypes.emplace_back("ManagerConsole");
155c7229815SAbhishek Patel         }
1563e72c202SNinad Palsule         else if (userGroup == "hostconsole")
1573e72c202SNinad Palsule         {
1583e72c202SNinad Palsule             // The hostconsole group controls who can access the host console
1593e72c202SNinad Palsule             // port via ssh and websocket.
1603e72c202SNinad Palsule             accountTypes.emplace_back("HostConsole");
1613e72c202SNinad Palsule         }
162c7229815SAbhishek Patel         else if (userGroup == "web")
163c7229815SAbhishek Patel         {
164c7229815SAbhishek Patel             // 'web' is one of the valid groups in the UserGroups property of
165c7229815SAbhishek Patel             // the user account in the D-Bus object. This group is currently not
166c7229815SAbhishek Patel             // doing anything, and is considered to be equivalent to 'redfish'.
167c7229815SAbhishek Patel             // 'redfish' user group is mapped to 'Redfish'and 'WebUI'
168c7229815SAbhishek Patel             // AccountTypes, so do nothing here...
169c7229815SAbhishek Patel         }
170c7229815SAbhishek Patel         else
171c7229815SAbhishek Patel         {
1728ece0e45SEd Tanous             // Invalid user group name. Caller throws an exception.
173c7229815SAbhishek Patel             return false;
174c7229815SAbhishek Patel         }
175c7229815SAbhishek Patel     }
176c7229815SAbhishek Patel 
177c7229815SAbhishek Patel     res.jsonValue["AccountTypes"] = std::move(accountTypes);
178c7229815SAbhishek Patel     return true;
179c7229815SAbhishek Patel }
180c7229815SAbhishek Patel 
18158345856SAbhishek Patel /**
18258345856SAbhishek Patel  * @brief Builds User Groups from the Account Types
18358345856SAbhishek Patel  *
18458345856SAbhishek Patel  * @param[in] asyncResp Async Response
18558345856SAbhishek Patel  * @param[in] accountTypes List of Account Types
18658345856SAbhishek Patel  * @param[out] userGroups List of User Groups mapped from Account Types
18758345856SAbhishek Patel  *
18858345856SAbhishek Patel  * @return true if Account Types mapped to User Groups, false otherwise.
18958345856SAbhishek Patel  */
190bd79bce8SPatrick Williams inline bool getUserGroupFromAccountType(
191bd79bce8SPatrick Williams     crow::Response& res, const std::vector<std::string>& accountTypes,
19258345856SAbhishek Patel     std::vector<std::string>& userGroups)
19358345856SAbhishek Patel {
19458345856SAbhishek Patel     // Need both Redfish and WebUI Account Types to map to 'redfish' User Group
19558345856SAbhishek Patel     bool redfishType = false;
19658345856SAbhishek Patel     bool webUIType = false;
19758345856SAbhishek Patel 
19858345856SAbhishek Patel     for (const auto& accountType : accountTypes)
19958345856SAbhishek Patel     {
20058345856SAbhishek Patel         if (accountType == "Redfish")
20158345856SAbhishek Patel         {
20258345856SAbhishek Patel             redfishType = true;
20358345856SAbhishek Patel         }
20458345856SAbhishek Patel         else if (accountType == "WebUI")
20558345856SAbhishek Patel         {
20658345856SAbhishek Patel             webUIType = true;
20758345856SAbhishek Patel         }
20858345856SAbhishek Patel         else if (accountType == "IPMI")
20958345856SAbhishek Patel         {
21058345856SAbhishek Patel             userGroups.emplace_back("ipmi");
21158345856SAbhishek Patel         }
21258345856SAbhishek Patel         else if (accountType == "HostConsole")
21358345856SAbhishek Patel         {
21458345856SAbhishek Patel             userGroups.emplace_back("hostconsole");
21558345856SAbhishek Patel         }
21658345856SAbhishek Patel         else if (accountType == "ManagerConsole")
21758345856SAbhishek Patel         {
21858345856SAbhishek Patel             userGroups.emplace_back("ssh");
21958345856SAbhishek Patel         }
22058345856SAbhishek Patel         else
22158345856SAbhishek Patel         {
22258345856SAbhishek Patel             // Invalid Account Type
22358345856SAbhishek Patel             messages::propertyValueNotInList(res, "AccountTypes", accountType);
22458345856SAbhishek Patel             return false;
22558345856SAbhishek Patel         }
22658345856SAbhishek Patel     }
22758345856SAbhishek Patel 
22858345856SAbhishek Patel     // Both  Redfish and WebUI Account Types are needed to PATCH
22958345856SAbhishek Patel     if (redfishType ^ webUIType)
23058345856SAbhishek Patel     {
23162598e31SEd Tanous         BMCWEB_LOG_ERROR(
23262598e31SEd Tanous             "Missing Redfish or WebUI Account Type to set redfish User Group");
23358345856SAbhishek Patel         messages::strictAccountTypes(res, "AccountTypes");
23458345856SAbhishek Patel         return false;
23558345856SAbhishek Patel     }
23658345856SAbhishek Patel 
23758345856SAbhishek Patel     if (redfishType && webUIType)
23858345856SAbhishek Patel     {
23958345856SAbhishek Patel         userGroups.emplace_back("redfish");
24058345856SAbhishek Patel     }
24158345856SAbhishek Patel 
24258345856SAbhishek Patel     return true;
24358345856SAbhishek Patel }
24458345856SAbhishek Patel 
24558345856SAbhishek Patel /**
24658345856SAbhishek Patel  * @brief Sets UserGroups property of the user based on the Account Types
24758345856SAbhishek Patel  *
24858345856SAbhishek Patel  * @param[in] accountTypes List of User Account Types
24958345856SAbhishek Patel  * @param[in] asyncResp Async Response
25058345856SAbhishek Patel  * @param[in] dbusObjectPath D-Bus Object Path
25158345856SAbhishek Patel  * @param[in] userSelf true if User is updating OWN Account Types
25258345856SAbhishek Patel  */
253504af5a0SPatrick Williams inline void patchAccountTypes(
254504af5a0SPatrick Williams     const std::vector<std::string>& accountTypes,
25558345856SAbhishek Patel     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
25658345856SAbhishek Patel     const std::string& dbusObjectPath, bool userSelf)
25758345856SAbhishek Patel {
25858345856SAbhishek Patel     // Check if User is disabling own Redfish Account Type
25958345856SAbhishek Patel     if (userSelf &&
26058345856SAbhishek Patel         (accountTypes.cend() ==
26158345856SAbhishek Patel          std::find(accountTypes.cbegin(), accountTypes.cend(), "Redfish")))
26258345856SAbhishek Patel     {
26362598e31SEd Tanous         BMCWEB_LOG_ERROR(
26462598e31SEd Tanous             "User disabling OWN Redfish Account Type is not allowed");
26558345856SAbhishek Patel         messages::strictAccountTypes(asyncResp->res, "AccountTypes");
26658345856SAbhishek Patel         return;
26758345856SAbhishek Patel     }
26858345856SAbhishek Patel 
26958345856SAbhishek Patel     std::vector<std::string> updatedUserGroups;
27058345856SAbhishek Patel     if (!getUserGroupFromAccountType(asyncResp->res, accountTypes,
27158345856SAbhishek Patel                                      updatedUserGroups))
27258345856SAbhishek Patel     {
27358345856SAbhishek Patel         // Problem in mapping Account Types to User Groups, Error already
27458345856SAbhishek Patel         // logged.
27558345856SAbhishek Patel         return;
27658345856SAbhishek Patel     }
277e93abac6SGinu George     setDbusProperty(asyncResp, "AccountTypes",
278e93abac6SGinu George                     "xyz.openbmc_project.User.Manager", dbusObjectPath,
279e93abac6SGinu George                     "xyz.openbmc_project.User.Attributes", "UserGroups",
280e93abac6SGinu George                     updatedUserGroups);
28158345856SAbhishek Patel }
28258345856SAbhishek Patel 
2838d1b46d7Szhanghch05 inline void userErrorMessageHandler(
2848d1b46d7Szhanghch05     const sd_bus_error* e, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2858d1b46d7Szhanghch05     const std::string& newUser, const std::string& username)
28666b5ca76Sjayaprakash Mutyala {
28766b5ca76Sjayaprakash Mutyala     if (e == nullptr)
28866b5ca76Sjayaprakash Mutyala     {
28966b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
29066b5ca76Sjayaprakash Mutyala         return;
29166b5ca76Sjayaprakash Mutyala     }
29266b5ca76Sjayaprakash Mutyala 
293055806b3SManojkiran Eda     const char* errorMessage = e->name;
29466b5ca76Sjayaprakash Mutyala     if (strcmp(errorMessage,
29566b5ca76Sjayaprakash Mutyala                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
29666b5ca76Sjayaprakash Mutyala     {
297d8a5d5d8SJiaqing Zhao         messages::resourceAlreadyExists(asyncResp->res, "ManagerAccount",
29866b5ca76Sjayaprakash Mutyala                                         "UserName", newUser);
29966b5ca76Sjayaprakash Mutyala     }
30066b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
30166b5ca76Sjayaprakash Mutyala                                   "UserNameDoesNotExist") == 0)
30266b5ca76Sjayaprakash Mutyala     {
303d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
30466b5ca76Sjayaprakash Mutyala     }
305d4d25793SEd Tanous     else if ((strcmp(errorMessage,
306d4d25793SEd Tanous                      "xyz.openbmc_project.Common.Error.InvalidArgument") ==
307d4d25793SEd Tanous               0) ||
3080fda0f12SGeorge Liu              (strcmp(
3090fda0f12SGeorge Liu                   errorMessage,
3100fda0f12SGeorge Liu                   "xyz.openbmc_project.User.Common.Error.UserNameGroupFail") ==
3110fda0f12SGeorge Liu               0))
31266b5ca76Sjayaprakash Mutyala     {
31366b5ca76Sjayaprakash Mutyala         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
31466b5ca76Sjayaprakash Mutyala     }
31566b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage,
31666b5ca76Sjayaprakash Mutyala                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
31766b5ca76Sjayaprakash Mutyala     {
31866b5ca76Sjayaprakash Mutyala         messages::createLimitReachedForResource(asyncResp->res);
31966b5ca76Sjayaprakash Mutyala     }
32066b5ca76Sjayaprakash Mutyala     else
32166b5ca76Sjayaprakash Mutyala     {
322b8ad583fSGunnar Mills         BMCWEB_LOG_ERROR("DBUS response error {}", errorMessage);
32366b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
32466b5ca76Sjayaprakash Mutyala     }
32566b5ca76Sjayaprakash Mutyala }
32666b5ca76Sjayaprakash Mutyala 
32781ce609eSEd Tanous inline void parseLDAPConfigData(nlohmann::json& jsonResponse,
328ab828d7cSRatan Gupta                                 const LDAPConfigData& confData,
329ab828d7cSRatan Gupta                                 const std::string& ldapType)
3306973a582SRatan Gupta {
33149cc263fSEd Tanous     nlohmann::json::object_t ldap;
3321476687dSEd Tanous     ldap["ServiceEnabled"] = confData.serviceEnabled;
33349cc263fSEd Tanous     nlohmann::json::array_t serviceAddresses;
334*092a33f1SEd Tanous     if (!confData.uri.empty())
335*092a33f1SEd Tanous     {
33649cc263fSEd Tanous         serviceAddresses.emplace_back(confData.uri);
337*092a33f1SEd Tanous     }
33849cc263fSEd Tanous     ldap["ServiceAddresses"] = std::move(serviceAddresses);
33949cc263fSEd Tanous 
34049cc263fSEd Tanous     nlohmann::json::object_t authentication;
34149cc263fSEd Tanous     authentication["AuthenticationType"] =
3420ec8b83dSEd Tanous         account_service::AuthenticationTypes::UsernameAndPassword;
34349cc263fSEd Tanous     authentication["Username"] = confData.bindDN;
34449cc263fSEd Tanous     authentication["Password"] = nullptr;
34549cc263fSEd Tanous     ldap["Authentication"] = std::move(authentication);
3461476687dSEd Tanous 
34749cc263fSEd Tanous     nlohmann::json::object_t ldapService;
34849cc263fSEd Tanous     nlohmann::json::object_t searchSettings;
34949cc263fSEd Tanous     nlohmann::json::array_t baseDistinguishedNames;
350*092a33f1SEd Tanous     if (!confData.baseDN.empty())
351*092a33f1SEd Tanous     {
35249cc263fSEd Tanous         baseDistinguishedNames.emplace_back(confData.baseDN);
353*092a33f1SEd Tanous     }
3541476687dSEd Tanous 
35549cc263fSEd Tanous     searchSettings["BaseDistinguishedNames"] =
35649cc263fSEd Tanous         std::move(baseDistinguishedNames);
35749cc263fSEd Tanous     searchSettings["UsernameAttribute"] = confData.userNameAttribute;
35849cc263fSEd Tanous     searchSettings["GroupsAttribute"] = confData.groupAttribute;
35949cc263fSEd Tanous     ldapService["SearchSettings"] = std::move(searchSettings);
36049cc263fSEd Tanous     ldap["LDAPService"] = std::move(ldapService);
36149cc263fSEd Tanous 
36249cc263fSEd Tanous     nlohmann::json::array_t roleMapArray;
3639eb808c1SEd Tanous     for (const auto& obj : confData.groupRoleList)
36454fc587aSNagaraju Goruganti     {
36562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Pushing the data groupName={}", obj.second.groupName);
366613dabeaSEd Tanous 
367613dabeaSEd Tanous         nlohmann::json::object_t remoteGroup;
368613dabeaSEd Tanous         remoteGroup["RemoteGroup"] = obj.second.groupName;
369329f0348SJorge Cisneros         remoteGroup["LocalRole"] = getRoleIdFromPrivilege(obj.second.privilege);
370329f0348SJorge Cisneros         roleMapArray.emplace_back(std::move(remoteGroup));
37154fc587aSNagaraju Goruganti     }
37249cc263fSEd Tanous 
37349cc263fSEd Tanous     ldap["RemoteRoleMapping"] = std::move(roleMapArray);
37449cc263fSEd Tanous 
37549cc263fSEd Tanous     jsonResponse[ldapType].update(ldap);
3766973a582SRatan Gupta }
3776973a582SRatan Gupta 
3786973a582SRatan Gupta /**
37906785244SRatan Gupta  *  @brief validates given JSON input and then calls appropriate method to
38006785244SRatan Gupta  * create, to delete or to set Rolemapping object based on the given input.
38106785244SRatan Gupta  *
38206785244SRatan Gupta  */
38323a21a1cSEd Tanous inline void handleRoleMapPatch(
3848d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
38506785244SRatan Gupta     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
386c1019828SEd Tanous     const std::string& serverType,
387c1019828SEd Tanous     std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input)
38806785244SRatan Gupta {
38906785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
39006785244SRatan Gupta     {
391c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
392c1019828SEd Tanous             input[index];
393c1019828SEd Tanous         nlohmann::json::object_t* obj =
394c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
395c1019828SEd Tanous         if (obj == nullptr)
39606785244SRatan Gupta         {
39706785244SRatan Gupta             // delete the existing object
39806785244SRatan Gupta             if (index < roleMapObjData.size())
39906785244SRatan Gupta             {
400177612aaSEd Tanous                 dbus::utility::async_method_call(
401177612aaSEd Tanous                     asyncResp,
40206785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
4035e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
40406785244SRatan Gupta                         if (ec)
40506785244SRatan Gupta                         {
40662598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
40706785244SRatan Gupta                             messages::internalError(asyncResp->res);
40806785244SRatan Gupta                             return;
40906785244SRatan Gupta                         }
410bd79bce8SPatrick Williams                         asyncResp->res
411bd79bce8SPatrick Williams                             .jsonValue[serverType]["RemoteRoleMapping"][index] =
412bd79bce8SPatrick Williams                             nullptr;
41306785244SRatan Gupta                     },
41406785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
41506785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
41606785244SRatan Gupta             }
41706785244SRatan Gupta             else
41806785244SRatan Gupta             {
41962598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
420bd79bce8SPatrick Williams                 messages::propertyValueTypeError(
421bd79bce8SPatrick Williams                     asyncResp->res, "null",
422bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index));
42306785244SRatan Gupta                 return;
42406785244SRatan Gupta             }
42506785244SRatan Gupta         }
426c1019828SEd Tanous         else if (obj->empty())
42706785244SRatan Gupta         {
42806785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
42906785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
43006785244SRatan Gupta         }
43106785244SRatan Gupta         else
43206785244SRatan Gupta         {
43306785244SRatan Gupta             // update/create the object
43406785244SRatan Gupta             std::optional<std::string> remoteGroup;
43506785244SRatan Gupta             std::optional<std::string> localRole;
43606785244SRatan Gupta 
437afc474aeSMyung Bae             if (!json_util::readJsonObject(    //
438afc474aeSMyung Bae                     *obj, asyncResp->res,      //
439afc474aeSMyung Bae                     "LocalRole", localRole,    //
440afc474aeSMyung Bae                     "RemoteGroup", remoteGroup //
441afc474aeSMyung Bae                     ))
44206785244SRatan Gupta             {
44306785244SRatan Gupta                 continue;
44406785244SRatan Gupta             }
44506785244SRatan Gupta 
44606785244SRatan Gupta             // Update existing RoleMapping Object
44706785244SRatan Gupta             if (index < roleMapObjData.size())
44806785244SRatan Gupta             {
44962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
45006785244SRatan Gupta                 // If "RemoteGroup" info is provided
45106785244SRatan Gupta                 if (remoteGroup)
45206785244SRatan Gupta                 {
453d02aad39SEd Tanous                     setDbusProperty(
454e93abac6SGinu George                         asyncResp,
455d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
456e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
457e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
458e93abac6SGinu George                         "GroupName", *remoteGroup);
45906785244SRatan Gupta                 }
46006785244SRatan Gupta 
46106785244SRatan Gupta                 // If "LocalRole" info is provided
46206785244SRatan Gupta                 if (localRole)
46306785244SRatan Gupta                 {
4646d0b80beSRavi Teja                     std::string priv = getPrivilegeFromRoleId(*localRole);
4656d0b80beSRavi Teja                     if (priv.empty())
4666d0b80beSRavi Teja                     {
4676d0b80beSRavi Teja                         messages::propertyValueNotInList(
4686d0b80beSRavi Teja                             asyncResp->res, *localRole,
4696d0b80beSRavi Teja                             std::format("RemoteRoleMapping/{}/LocalRole",
4706d0b80beSRavi Teja                                         index));
4716d0b80beSRavi Teja                         return;
4726d0b80beSRavi Teja                     }
473d02aad39SEd Tanous                     setDbusProperty(
474e93abac6SGinu George                         asyncResp,
475d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
476e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
477e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
4786d0b80beSRavi Teja                         "Privilege", priv);
47906785244SRatan Gupta                 }
48006785244SRatan Gupta             }
48106785244SRatan Gupta             // Create a new RoleMapping Object.
48206785244SRatan Gupta             else
48306785244SRatan Gupta             {
48462598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
48562598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
486bd79bce8SPatrick Williams                 std::string pathString =
487bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index);
48806785244SRatan Gupta 
48906785244SRatan Gupta                 if (!localRole)
49006785244SRatan Gupta                 {
49106785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
49206785244SRatan Gupta                                               pathString + "/LocalRole");
49306785244SRatan Gupta                     continue;
49406785244SRatan Gupta                 }
49506785244SRatan Gupta                 if (!remoteGroup)
49606785244SRatan Gupta                 {
49706785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
49806785244SRatan Gupta                                               pathString + "/RemoteGroup");
49906785244SRatan Gupta                     continue;
50006785244SRatan Gupta                 }
50106785244SRatan Gupta 
50206785244SRatan Gupta                 std::string dbusObjectPath;
50306785244SRatan Gupta                 if (serverType == "ActiveDirectory")
50406785244SRatan Gupta                 {
5052c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
50606785244SRatan Gupta                 }
50706785244SRatan Gupta                 else if (serverType == "LDAP")
50806785244SRatan Gupta                 {
50923a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
51006785244SRatan Gupta                 }
51106785244SRatan Gupta 
51262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
51362598e31SEd Tanous                                  *localRole);
51406785244SRatan Gupta 
515177612aaSEd Tanous                 dbus::utility::async_method_call(
516177612aaSEd Tanous                     asyncResp,
517271584abSEd Tanous                     [asyncResp, serverType, localRole,
5185e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
51906785244SRatan Gupta                         if (ec)
52006785244SRatan Gupta                         {
52162598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
52206785244SRatan Gupta                             messages::internalError(asyncResp->res);
52306785244SRatan Gupta                             return;
52406785244SRatan Gupta                         }
52506785244SRatan Gupta                         nlohmann::json& remoteRoleJson =
52606785244SRatan Gupta                             asyncResp->res
52706785244SRatan Gupta                                 .jsonValue[serverType]["RemoteRoleMapping"];
5281476687dSEd Tanous                         nlohmann::json::object_t roleMapEntry;
5291476687dSEd Tanous                         roleMapEntry["LocalRole"] = *localRole;
5301476687dSEd Tanous                         roleMapEntry["RemoteGroup"] = *remoteGroup;
531b2ba3072SPatrick Williams                         remoteRoleJson.emplace_back(std::move(roleMapEntry));
53206785244SRatan Gupta                     },
53306785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
5343174e4dfSEd Tanous                     "Create", *remoteGroup,
53506785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
53606785244SRatan Gupta             }
53706785244SRatan Gupta         }
53806785244SRatan Gupta     }
53906785244SRatan Gupta }
54006785244SRatan Gupta 
54106785244SRatan Gupta /**
5426973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5436973a582SRatan Gupta  * into JSON
5446973a582SRatan Gupta  */
5456973a582SRatan Gupta template <typename CallbackFunc>
546504af5a0SPatrick Williams inline void getLDAPConfigData(const std::string& ldapType,
547504af5a0SPatrick Williams                               CallbackFunc&& callback)
5486973a582SRatan Gupta {
5492b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5502b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
55154fc587aSNagaraju Goruganti 
5522b73119cSGeorge Liu     dbus::utility::getDbusObject(
5532b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5548cb2c024SEd Tanous         [callback = std::forward<CallbackFunc>(callback),
555c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
556c1019828SEd Tanous                    const dbus::utility::MapperGetObject& resp) mutable {
55754fc587aSNagaraju Goruganti             if (ec || resp.empty())
55854fc587aSNagaraju Goruganti             {
559bf2ddedeSCarson Labrado                 BMCWEB_LOG_WARNING(
560bd79bce8SPatrick Williams                     "DBUS response error during getting of service name: {}",
561bd79bce8SPatrick Williams                     ec);
56223a21a1cSEd Tanous                 LDAPConfigData empty{};
56323a21a1cSEd Tanous                 callback(false, empty, ldapType);
56454fc587aSNagaraju Goruganti                 return;
56554fc587aSNagaraju Goruganti             }
56654fc587aSNagaraju Goruganti             std::string service = resp.begin()->first;
5675eb468daSGeorge Liu             sdbusplus::message::object_path path(ldapRootObject);
5685eb468daSGeorge Liu             dbus::utility::getManagedObjects(
5695eb468daSGeorge Liu                 service, path,
570bd79bce8SPatrick Williams                 [callback, ldapType](const boost::system::error_code& ec2,
571bd79bce8SPatrick Williams                                      const dbus::utility::ManagedObjectType&
572bd79bce8SPatrick Williams                                          ldapObjects) mutable {
5736973a582SRatan Gupta                     LDAPConfigData confData{};
5748b24275dSEd Tanous                     if (ec2)
5756973a582SRatan Gupta                     {
576ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
577bf2ddedeSCarson Labrado                         BMCWEB_LOG_WARNING("D-Bus responses error: {}", ec2);
5786973a582SRatan Gupta                         return;
5796973a582SRatan Gupta                     }
580ab828d7cSRatan Gupta 
581ab828d7cSRatan Gupta                     std::string ldapDbusType;
58254fc587aSNagaraju Goruganti                     std::string searchString;
58354fc587aSNagaraju Goruganti 
584ab828d7cSRatan Gupta                     if (ldapType == "LDAP")
585ab828d7cSRatan Gupta                     {
5860fda0f12SGeorge Liu                         ldapDbusType =
5870fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.OpenLdap";
58854fc587aSNagaraju Goruganti                         searchString = "openldap";
589ab828d7cSRatan Gupta                     }
590ab828d7cSRatan Gupta                     else if (ldapType == "ActiveDirectory")
591ab828d7cSRatan Gupta                     {
59254fc587aSNagaraju Goruganti                         ldapDbusType =
5930fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.ActiveDirectory";
59454fc587aSNagaraju Goruganti                         searchString = "active_directory";
595ab828d7cSRatan Gupta                     }
596ab828d7cSRatan Gupta                     else
597ab828d7cSRatan Gupta                     {
598bd79bce8SPatrick Williams                         BMCWEB_LOG_ERROR(
599bd79bce8SPatrick Williams                             "Can't get the DbusType for the given type={}",
60062598e31SEd Tanous                             ldapType);
601ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
602ab828d7cSRatan Gupta                         return;
603ab828d7cSRatan Gupta                     }
604ab828d7cSRatan Gupta 
605ab828d7cSRatan Gupta                     std::string ldapEnableInterfaceStr = ldapEnableInterface;
606ab828d7cSRatan Gupta                     std::string ldapConfigInterfaceStr = ldapConfigInterface;
607ab828d7cSRatan Gupta 
6086973a582SRatan Gupta                     for (const auto& object : ldapObjects)
6096973a582SRatan Gupta                     {
61054fc587aSNagaraju Goruganti                         // let's find the object whose ldap type is equal to the
61154fc587aSNagaraju Goruganti                         // given type
612bd79bce8SPatrick Williams                         if (object.first.str.find(searchString) ==
613bd79bce8SPatrick Williams                             std::string::npos)
6146973a582SRatan Gupta                         {
615ab828d7cSRatan Gupta                             continue;
616ab828d7cSRatan Gupta                         }
617ab828d7cSRatan Gupta 
6186973a582SRatan Gupta                         for (const auto& interface : object.second)
6196973a582SRatan Gupta                         {
6206973a582SRatan Gupta                             if (interface.first == ldapEnableInterfaceStr)
6216973a582SRatan Gupta                             {
6226973a582SRatan Gupta                                 // rest of the properties are string.
6236973a582SRatan Gupta                                 for (const auto& property : interface.second)
6246973a582SRatan Gupta                                 {
6256973a582SRatan Gupta                                     if (property.first == "Enabled")
6266973a582SRatan Gupta                                     {
6276973a582SRatan Gupta                                         const bool* value =
6286973a582SRatan Gupta                                             std::get_if<bool>(&property.second);
6296973a582SRatan Gupta                                         if (value == nullptr)
6306973a582SRatan Gupta                                         {
6316973a582SRatan Gupta                                             continue;
6326973a582SRatan Gupta                                         }
6336973a582SRatan Gupta                                         confData.serviceEnabled = *value;
6346973a582SRatan Gupta                                         break;
6356973a582SRatan Gupta                                     }
6366973a582SRatan Gupta                                 }
6376973a582SRatan Gupta                             }
6386973a582SRatan Gupta                             else if (interface.first == ldapConfigInterfaceStr)
6396973a582SRatan Gupta                             {
6406973a582SRatan Gupta                                 for (const auto& property : interface.second)
6416973a582SRatan Gupta                                 {
642271584abSEd Tanous                                     const std::string* strValue =
643bd79bce8SPatrick Williams                                         std::get_if<std::string>(
644bd79bce8SPatrick Williams                                             &property.second);
645271584abSEd Tanous                                     if (strValue == nullptr)
6466973a582SRatan Gupta                                     {
6476973a582SRatan Gupta                                         continue;
6486973a582SRatan Gupta                                     }
6496973a582SRatan Gupta                                     if (property.first == "LDAPServerURI")
6506973a582SRatan Gupta                                     {
651271584abSEd Tanous                                         confData.uri = *strValue;
6526973a582SRatan Gupta                                     }
6536973a582SRatan Gupta                                     else if (property.first == "LDAPBindDN")
6546973a582SRatan Gupta                                     {
655271584abSEd Tanous                                         confData.bindDN = *strValue;
6566973a582SRatan Gupta                                     }
6576973a582SRatan Gupta                                     else if (property.first == "LDAPBaseDN")
6586973a582SRatan Gupta                                     {
659271584abSEd Tanous                                         confData.baseDN = *strValue;
6606973a582SRatan Gupta                                     }
661bd79bce8SPatrick Williams                                     else if (property.first ==
662bd79bce8SPatrick Williams                                              "LDAPSearchScope")
6636973a582SRatan Gupta                                     {
664271584abSEd Tanous                                         confData.searchScope = *strValue;
6656973a582SRatan Gupta                                     }
666bd79bce8SPatrick Williams                                     else if (property.first ==
667bd79bce8SPatrick Williams                                              "GroupNameAttribute")
6686973a582SRatan Gupta                                     {
669271584abSEd Tanous                                         confData.groupAttribute = *strValue;
6706973a582SRatan Gupta                                     }
671bd79bce8SPatrick Williams                                     else if (property.first ==
672bd79bce8SPatrick Williams                                              "UserNameAttribute")
6736973a582SRatan Gupta                                     {
674271584abSEd Tanous                                         confData.userNameAttribute = *strValue;
6756973a582SRatan Gupta                                     }
67654fc587aSNagaraju Goruganti                                     else if (property.first == "LDAPType")
677ab828d7cSRatan Gupta                                     {
678271584abSEd Tanous                                         confData.serverType = *strValue;
67954fc587aSNagaraju Goruganti                                     }
68054fc587aSNagaraju Goruganti                                 }
68154fc587aSNagaraju Goruganti                             }
682bd79bce8SPatrick Williams                             else if (
683bd79bce8SPatrick Williams                                 interface.first ==
6840fda0f12SGeorge Liu                                 "xyz.openbmc_project.User.PrivilegeMapperEntry")
68554fc587aSNagaraju Goruganti                             {
68654fc587aSNagaraju Goruganti                                 LDAPRoleMapData roleMapData{};
68754fc587aSNagaraju Goruganti                                 for (const auto& property : interface.second)
68854fc587aSNagaraju Goruganti                                 {
689271584abSEd Tanous                                     const std::string* strValue =
690bd79bce8SPatrick Williams                                         std::get_if<std::string>(
691bd79bce8SPatrick Williams                                             &property.second);
69254fc587aSNagaraju Goruganti 
693271584abSEd Tanous                                     if (strValue == nullptr)
69454fc587aSNagaraju Goruganti                                     {
69554fc587aSNagaraju Goruganti                                         continue;
69654fc587aSNagaraju Goruganti                                     }
69754fc587aSNagaraju Goruganti 
69854fc587aSNagaraju Goruganti                                     if (property.first == "GroupName")
69954fc587aSNagaraju Goruganti                                     {
700271584abSEd Tanous                                         roleMapData.groupName = *strValue;
70154fc587aSNagaraju Goruganti                                     }
70254fc587aSNagaraju Goruganti                                     else if (property.first == "Privilege")
70354fc587aSNagaraju Goruganti                                     {
704271584abSEd Tanous                                         roleMapData.privilege = *strValue;
70554fc587aSNagaraju Goruganti                                     }
70654fc587aSNagaraju Goruganti                                 }
70754fc587aSNagaraju Goruganti 
708bd79bce8SPatrick Williams                                 confData.groupRoleList.emplace_back(
709bd79bce8SPatrick Williams                                     object.first.str, roleMapData);
71054fc587aSNagaraju Goruganti                             }
71154fc587aSNagaraju Goruganti                         }
71254fc587aSNagaraju Goruganti                     }
713ab828d7cSRatan Gupta                     callback(true, confData, ldapType);
7145eb468daSGeorge Liu                 });
7152b73119cSGeorge Liu         });
7166973a582SRatan Gupta }
7176973a582SRatan Gupta 
7188a07d286SRatan Gupta /**
7198a07d286SRatan Gupta  * @brief updates the LDAP server address and updates the
7208a07d286SRatan Gupta           json response with the new value.
7218a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
7228a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7238a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7248a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7258a07d286SRatan Gupta  */
7268a07d286SRatan Gupta 
7274f48d5f6SEd Tanous inline void handleServiceAddressPatch(
7288a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
7298d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7308a07d286SRatan Gupta     const std::string& ldapServerElementName,
7318a07d286SRatan Gupta     const std::string& ldapConfigObject)
7328a07d286SRatan Gupta {
733e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceAddress",
734e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
735e93abac6SGinu George                     "LDAPServerURI", serviceAddressList.front());
7368a07d286SRatan Gupta }
7378a07d286SRatan Gupta /**
7388a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
7398a07d286SRatan Gupta           json response with the new value.
7408a07d286SRatan Gupta  * @param username name of the user which needs to be updated.
7418a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7428a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7438a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7448a07d286SRatan Gupta  */
7458a07d286SRatan Gupta 
746504af5a0SPatrick Williams inline void handleUserNamePatch(
747504af5a0SPatrick Williams     const std::string& username,
7488d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7498a07d286SRatan Gupta     const std::string& ldapServerElementName,
7508a07d286SRatan Gupta     const std::string& ldapConfigObject)
7518a07d286SRatan Gupta {
752e93abac6SGinu George     setDbusProperty(asyncResp,
753d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Username",
754e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
755e93abac6SGinu George                     "LDAPBindDN", username);
7568a07d286SRatan Gupta }
7578a07d286SRatan Gupta 
7588a07d286SRatan Gupta /**
7598a07d286SRatan Gupta  * @brief updates the LDAP password
7608a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7618a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7628a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7638a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7648a07d286SRatan Gupta  */
7658a07d286SRatan Gupta 
766504af5a0SPatrick Williams inline void handlePasswordPatch(
767504af5a0SPatrick Williams     const std::string& password,
7688d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7698a07d286SRatan Gupta     const std::string& ldapServerElementName,
7708a07d286SRatan Gupta     const std::string& ldapConfigObject)
7718a07d286SRatan Gupta {
772e93abac6SGinu George     setDbusProperty(asyncResp,
773d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
774e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
775e93abac6SGinu George                     "LDAPBindDNPassword", password);
7768a07d286SRatan Gupta }
7778a07d286SRatan Gupta 
7788a07d286SRatan Gupta /**
7798a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7808a07d286SRatan Gupta           json response with the new value.
7818a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
7828a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7838a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7848a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7858a07d286SRatan Gupta  */
7868a07d286SRatan Gupta 
787504af5a0SPatrick Williams inline void handleBaseDNPatch(
788504af5a0SPatrick Williams     const std::vector<std::string>& baseDNList,
7898d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7908a07d286SRatan Gupta     const std::string& ldapServerElementName,
7918a07d286SRatan Gupta     const std::string& ldapConfigObject)
7928a07d286SRatan Gupta {
793e93abac6SGinu George     setDbusProperty(asyncResp,
794d02aad39SEd Tanous                     ldapServerElementName +
795d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
796e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
797e93abac6SGinu George                     "LDAPBaseDN", baseDNList.front());
7988a07d286SRatan Gupta }
7998a07d286SRatan Gupta /**
8008a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
8018a07d286SRatan Gupta           json response with the new value.
8028a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
8038a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8048a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8058a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8068a07d286SRatan Gupta  */
8078a07d286SRatan Gupta 
808bd79bce8SPatrick Williams inline void handleUserNameAttrPatch(
809bd79bce8SPatrick Williams     const std::string& userNameAttribute,
8108d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8118a07d286SRatan Gupta     const std::string& ldapServerElementName,
8128a07d286SRatan Gupta     const std::string& ldapConfigObject)
8138a07d286SRatan Gupta {
814bd79bce8SPatrick Williams     setDbusProperty(
815bd79bce8SPatrick Williams         asyncResp,
816bd79bce8SPatrick Williams         ldapServerElementName + "LDAPService/SearchSettings/UsernameAttribute",
817e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
818e93abac6SGinu George         "UserNameAttribute", userNameAttribute);
8198a07d286SRatan Gupta }
8208a07d286SRatan Gupta /**
8218a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
8228a07d286SRatan Gupta           json response with the new value.
8238a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
8248a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8258a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8268a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8278a07d286SRatan Gupta  */
8288a07d286SRatan Gupta 
8294f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
8308d1b46d7Szhanghch05     const std::string& groupsAttribute,
8318d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8328a07d286SRatan Gupta     const std::string& ldapServerElementName,
8338a07d286SRatan Gupta     const std::string& ldapConfigObject)
8348a07d286SRatan Gupta {
835bd79bce8SPatrick Williams     setDbusProperty(
836bd79bce8SPatrick Williams         asyncResp,
837bd79bce8SPatrick Williams         ldapServerElementName + "/LDAPService/SearchSettings/GroupsAttribute",
838e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
839e93abac6SGinu George         "GroupNameAttribute", groupsAttribute);
8408a07d286SRatan Gupta }
8418a07d286SRatan Gupta /**
8428a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
8438a07d286SRatan Gupta           json response with the new value.
8448a07d286SRatan Gupta  * @param input JSON data.
8458a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8468a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8478a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8488a07d286SRatan Gupta  */
8498a07d286SRatan Gupta 
8504f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8516c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8528a07d286SRatan Gupta     const std::string& ldapServerElementName,
8538a07d286SRatan Gupta     const std::string& ldapConfigObject)
8548a07d286SRatan Gupta {
855e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceEnabled",
856e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapEnableInterface,
857e93abac6SGinu George                     "Enabled", serviceEnabled);
8588a07d286SRatan Gupta }
8598a07d286SRatan Gupta 
860c1019828SEd Tanous struct AuthMethods
86178158631SZbigniew Kurzynski {
86278158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
86378158631SZbigniew Kurzynski     std::optional<bool> cookie;
86478158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
86578158631SZbigniew Kurzynski     std::optional<bool> xToken;
866501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
867c1019828SEd Tanous };
86878158631SZbigniew Kurzynski 
869504af5a0SPatrick Williams inline void handleAuthMethodsPatch(
870504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
871c1019828SEd Tanous     const AuthMethods& auth)
87278158631SZbigniew Kurzynski {
873c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
87452cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
87578158631SZbigniew Kurzynski 
876c1019828SEd Tanous     if (auth.basicAuth)
87778158631SZbigniew Kurzynski     {
87825b54dbaSEd Tanous         if constexpr (!BMCWEB_BASIC_AUTH)
87925b54dbaSEd Tanous         {
880f16f6263SAlan Kuo             messages::actionNotSupported(
8810fda0f12SGeorge Liu                 asyncResp->res,
8820fda0f12SGeorge Liu                 "Setting BasicAuth when basic-auth feature is disabled");
883f16f6263SAlan Kuo             return;
88425b54dbaSEd Tanous         }
88525b54dbaSEd Tanous 
886c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
88778158631SZbigniew Kurzynski     }
88878158631SZbigniew Kurzynski 
889c1019828SEd Tanous     if (auth.cookie)
89078158631SZbigniew Kurzynski     {
89125b54dbaSEd Tanous         if constexpr (!BMCWEB_COOKIE_AUTH)
89225b54dbaSEd Tanous         {
8930fda0f12SGeorge Liu             messages::actionNotSupported(
8940fda0f12SGeorge Liu                 asyncResp->res,
8950fda0f12SGeorge Liu                 "Setting Cookie when cookie-auth feature is disabled");
896f16f6263SAlan Kuo             return;
89725b54dbaSEd Tanous         }
898c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
89978158631SZbigniew Kurzynski     }
90078158631SZbigniew Kurzynski 
901c1019828SEd Tanous     if (auth.sessionToken)
90278158631SZbigniew Kurzynski     {
90325b54dbaSEd Tanous         if constexpr (!BMCWEB_SESSION_AUTH)
90425b54dbaSEd Tanous         {
905f16f6263SAlan Kuo             messages::actionNotSupported(
9060fda0f12SGeorge Liu                 asyncResp->res,
9070fda0f12SGeorge Liu                 "Setting SessionToken when session-auth feature is disabled");
908f16f6263SAlan Kuo             return;
90925b54dbaSEd Tanous         }
910c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
91178158631SZbigniew Kurzynski     }
91278158631SZbigniew Kurzynski 
913c1019828SEd Tanous     if (auth.xToken)
91478158631SZbigniew Kurzynski     {
91525b54dbaSEd Tanous         if constexpr (!BMCWEB_XTOKEN_AUTH)
91625b54dbaSEd Tanous         {
9170fda0f12SGeorge Liu             messages::actionNotSupported(
9180fda0f12SGeorge Liu                 asyncResp->res,
9190fda0f12SGeorge Liu                 "Setting XToken when xtoken-auth feature is disabled");
920f16f6263SAlan Kuo             return;
92125b54dbaSEd Tanous         }
922c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
92378158631SZbigniew Kurzynski     }
92478158631SZbigniew Kurzynski 
925c1019828SEd Tanous     if (auth.tls)
926501f1e58SZbigniew Kurzynski     {
92725b54dbaSEd Tanous         if constexpr (!BMCWEB_MUTUAL_TLS_AUTH)
92825b54dbaSEd Tanous         {
9290fda0f12SGeorge Liu             messages::actionNotSupported(
9300fda0f12SGeorge Liu                 asyncResp->res,
9310fda0f12SGeorge Liu                 "Setting TLS when mutual-tls-auth feature is disabled");
932f16f6263SAlan Kuo             return;
93325b54dbaSEd Tanous         }
934c1019828SEd Tanous         authMethodsConfig.tls = *auth.tls;
935501f1e58SZbigniew Kurzynski     }
936501f1e58SZbigniew Kurzynski 
93778158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
938501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
939501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
94078158631SZbigniew Kurzynski     {
94178158631SZbigniew Kurzynski         // Do not allow user to disable everything
94278158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
94378158631SZbigniew Kurzynski                                      "of disabling all available methods");
94478158631SZbigniew Kurzynski         return;
94578158631SZbigniew Kurzynski     }
94678158631SZbigniew Kurzynski 
94752cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
94852cc112dSEd Tanous         authMethodsConfig);
94978158631SZbigniew Kurzynski     // Save configuration immediately
95052cc112dSEd Tanous     persistent_data::getConfig().writeData();
95178158631SZbigniew Kurzynski 
95278158631SZbigniew Kurzynski     messages::success(asyncResp->res);
95378158631SZbigniew Kurzynski }
95478158631SZbigniew Kurzynski 
9558a07d286SRatan Gupta /**
9568a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9578a07d286SRatan Gupta  *        value and create the LDAP config object.
9588a07d286SRatan Gupta  * @param input JSON data
9598a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9608a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9618a07d286SRatan Gupta  */
9628a07d286SRatan Gupta 
96310cb44f3SEd Tanous struct LdapPatchParams
96410cb44f3SEd Tanous {
96510cb44f3SEd Tanous     std::optional<std::string> authType;
96610cb44f3SEd Tanous     std::optional<std::vector<std::string>> serviceAddressList;
96710cb44f3SEd Tanous     std::optional<bool> serviceEnabled;
96810cb44f3SEd Tanous     std::optional<std::vector<std::string>> baseDNList;
96910cb44f3SEd Tanous     std::optional<std::string> userNameAttribute;
97010cb44f3SEd Tanous     std::optional<std::string> groupsAttribute;
97110cb44f3SEd Tanous     std::optional<std::string> userName;
97210cb44f3SEd Tanous     std::optional<std::string> password;
97310cb44f3SEd Tanous     std::optional<
97410cb44f3SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
97510cb44f3SEd Tanous         remoteRoleMapData;
97610cb44f3SEd Tanous };
97710cb44f3SEd Tanous 
97810cb44f3SEd Tanous inline void handleLDAPPatch(LdapPatchParams&& input,
9798d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9808a07d286SRatan Gupta                             const std::string& serverType)
9818a07d286SRatan Gupta {
982eb2bbe56SRatan Gupta     std::string dbusObjectPath;
983eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
984eb2bbe56SRatan Gupta     {
9852c70f800SEd Tanous         dbusObjectPath = adConfigObject;
986eb2bbe56SRatan Gupta     }
987eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
988eb2bbe56SRatan Gupta     {
98923a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
990eb2bbe56SRatan Gupta     }
991cb13a392SEd Tanous     else
992cb13a392SEd Tanous     {
99310cb44f3SEd Tanous         BMCWEB_LOG_ERROR("serverType wasn't AD or LDAP but was {}????",
99410cb44f3SEd Tanous                          serverType);
995cb13a392SEd Tanous         return;
996cb13a392SEd Tanous     }
997eb2bbe56SRatan Gupta 
99810cb44f3SEd Tanous     if (input.authType && *input.authType != "UsernameAndPassword")
9998a07d286SRatan Gupta     {
100010cb44f3SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *input.authType,
1001c1019828SEd Tanous                                          "AuthenticationType");
1002c1019828SEd Tanous         return;
10038a07d286SRatan Gupta     }
1004c1019828SEd Tanous 
100510cb44f3SEd Tanous     if (input.serviceAddressList)
10068a07d286SRatan Gupta     {
100710cb44f3SEd Tanous         if (input.serviceAddressList->empty())
10088a07d286SRatan Gupta         {
1009e2616cc5SEd Tanous             messages::propertyValueNotInList(
101010cb44f3SEd Tanous                 asyncResp->res, *input.serviceAddressList, "ServiceAddress");
10118a07d286SRatan Gupta             return;
10128a07d286SRatan Gupta         }
10138a07d286SRatan Gupta     }
101410cb44f3SEd Tanous     if (input.baseDNList)
10158a07d286SRatan Gupta     {
101610cb44f3SEd Tanous         if (input.baseDNList->empty())
10178a07d286SRatan Gupta         {
101810cb44f3SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *input.baseDNList,
10198a07d286SRatan Gupta                                              "BaseDistinguishedNames");
10208a07d286SRatan Gupta             return;
10218a07d286SRatan Gupta         }
10228a07d286SRatan Gupta     }
10238a07d286SRatan Gupta 
10248a07d286SRatan Gupta     // nothing to update, then return
102510cb44f3SEd Tanous     if (!input.userName && !input.password && !input.serviceAddressList &&
102610cb44f3SEd Tanous         !input.baseDNList && !input.userNameAttribute &&
102710cb44f3SEd Tanous         !input.groupsAttribute && !input.serviceEnabled &&
102810cb44f3SEd Tanous         !input.remoteRoleMapData)
10298a07d286SRatan Gupta     {
10308a07d286SRatan Gupta         return;
10318a07d286SRatan Gupta     }
10328a07d286SRatan Gupta 
10338a07d286SRatan Gupta     // Get the existing resource first then keep modifying
10348a07d286SRatan Gupta     // whenever any property gets updated.
1035bd79bce8SPatrick Williams     getLDAPConfigData(serverType, [asyncResp, input = std::move(input),
103610cb44f3SEd Tanous                                    dbusObjectPath = std::move(dbusObjectPath)](
1037bd79bce8SPatrick Williams                                       bool success,
1038bd79bce8SPatrick Williams                                       const LDAPConfigData& confData,
1039c1019828SEd Tanous                                       const std::string& serverT) mutable {
10408a07d286SRatan Gupta         if (!success)
10418a07d286SRatan Gupta         {
10428a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10438a07d286SRatan Gupta             return;
10448a07d286SRatan Gupta         }
10456c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10468a07d286SRatan Gupta         if (confData.serviceEnabled)
10478a07d286SRatan Gupta         {
10488a07d286SRatan Gupta             // Disable the service first and update the rest of
10498a07d286SRatan Gupta             // the properties.
10506c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10518a07d286SRatan Gupta         }
10528a07d286SRatan Gupta 
105310cb44f3SEd Tanous         if (input.serviceAddressList)
10548a07d286SRatan Gupta         {
105510cb44f3SEd Tanous             handleServiceAddressPatch(*input.serviceAddressList, asyncResp,
105610cb44f3SEd Tanous                                       serverT, dbusObjectPath);
105710cb44f3SEd Tanous         }
105810cb44f3SEd Tanous         if (input.userName)
105910cb44f3SEd Tanous         {
106010cb44f3SEd Tanous             handleUserNamePatch(*input.userName, asyncResp, serverT,
10616c51eab1SEd Tanous                                 dbusObjectPath);
10628a07d286SRatan Gupta         }
106310cb44f3SEd Tanous         if (input.password)
10648a07d286SRatan Gupta         {
106510cb44f3SEd Tanous             handlePasswordPatch(*input.password, asyncResp, serverT,
106610cb44f3SEd Tanous                                 dbusObjectPath);
10678a07d286SRatan Gupta         }
10688a07d286SRatan Gupta 
106910cb44f3SEd Tanous         if (input.baseDNList)
10708a07d286SRatan Gupta         {
107110cb44f3SEd Tanous             handleBaseDNPatch(*input.baseDNList, asyncResp, serverT,
10726c51eab1SEd Tanous                               dbusObjectPath);
10738a07d286SRatan Gupta         }
107410cb44f3SEd Tanous         if (input.userNameAttribute)
10758a07d286SRatan Gupta         {
107610cb44f3SEd Tanous             handleUserNameAttrPatch(*input.userNameAttribute, asyncResp,
107710cb44f3SEd Tanous                                     serverT, dbusObjectPath);
107810cb44f3SEd Tanous         }
107910cb44f3SEd Tanous         if (input.groupsAttribute)
108010cb44f3SEd Tanous         {
108110cb44f3SEd Tanous             handleGroupNameAttrPatch(*input.groupsAttribute, asyncResp, serverT,
10826c51eab1SEd Tanous                                      dbusObjectPath);
10838a07d286SRatan Gupta         }
108410cb44f3SEd Tanous         if (input.serviceEnabled)
10858a07d286SRatan Gupta         {
10868a07d286SRatan Gupta             // if user has given the value as true then enable
10878a07d286SRatan Gupta             // the service. if user has given false then no-op
10888a07d286SRatan Gupta             // as service is already stopped.
108910cb44f3SEd Tanous             if (*input.serviceEnabled)
10908a07d286SRatan Gupta             {
109110cb44f3SEd Tanous                 handleServiceEnablePatch(*input.serviceEnabled, asyncResp,
109210cb44f3SEd Tanous                                          serverT, dbusObjectPath);
10938a07d286SRatan Gupta             }
10948a07d286SRatan Gupta         }
10958a07d286SRatan Gupta         else
10968a07d286SRatan Gupta         {
10978a07d286SRatan Gupta             // if user has not given the service enabled value
10988a07d286SRatan Gupta             // then revert it to the same state as it was
10998a07d286SRatan Gupta             // before.
11008a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
110123a21a1cSEd Tanous                                      serverT, dbusObjectPath);
11028a07d286SRatan Gupta         }
110306785244SRatan Gupta 
110410cb44f3SEd Tanous         if (input.remoteRoleMapData)
110506785244SRatan Gupta         {
11066c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
110710cb44f3SEd Tanous                                *input.remoteRoleMapData);
110806785244SRatan Gupta         }
11098a07d286SRatan Gupta     });
11108a07d286SRatan Gupta }
1111d4b5443fSEd Tanous 
1112492ec93aSEd Tanous struct UserUpdateParams
11131abe55efSEd Tanous {
1114492ec93aSEd Tanous     std::string username;
1115492ec93aSEd Tanous     std::optional<std::string> password;
1116492ec93aSEd Tanous     std::optional<bool> enabled;
1117492ec93aSEd Tanous     std::optional<std::string> roleId;
1118492ec93aSEd Tanous     std::optional<bool> locked;
1119492ec93aSEd Tanous     std::optional<std::vector<std::string>> accountTypes;
1120492ec93aSEd Tanous     bool userSelf;
1121492ec93aSEd Tanous     std::shared_ptr<persistent_data::UserSession> session;
1122492ec93aSEd Tanous     std::string dbusObjectPath;
1123492ec93aSEd Tanous };
11246c51eab1SEd Tanous 
1125504af5a0SPatrick Williams inline void afterVerifyUserExists(
1126504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1127492ec93aSEd Tanous     const UserUpdateParams& params, int rc)
1128492ec93aSEd Tanous {
1129e662eae8SEd Tanous     if (rc <= 0)
11306c51eab1SEd Tanous     {
1131d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1132492ec93aSEd Tanous                                    params.username);
11336c51eab1SEd Tanous         return;
11346c51eab1SEd Tanous     }
11356c51eab1SEd Tanous 
1136492ec93aSEd Tanous     if (params.password)
11376c51eab1SEd Tanous     {
1138492ec93aSEd Tanous         int retval = pamUpdatePassword(params.username, *params.password);
11396c51eab1SEd Tanous 
11406c51eab1SEd Tanous         if (retval == PAM_USER_UNKNOWN)
11416c51eab1SEd Tanous         {
1142d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1143492ec93aSEd Tanous                                        params.username);
11446c51eab1SEd Tanous         }
11456c51eab1SEd Tanous         else if (retval == PAM_AUTHTOK_ERR)
11466c51eab1SEd Tanous         {
11476c51eab1SEd Tanous             // If password is invalid
11489bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
11499bd80831SJason M. Bills                                                "Password");
115062598e31SEd Tanous             BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11516c51eab1SEd Tanous         }
11526c51eab1SEd Tanous         else if (retval != PAM_SUCCESS)
11536c51eab1SEd Tanous         {
11546c51eab1SEd Tanous             messages::internalError(asyncResp->res);
11556c51eab1SEd Tanous             return;
11566c51eab1SEd Tanous         }
1157e7b1b62bSEd Tanous         else
1158e7b1b62bSEd Tanous         {
1159bd79bce8SPatrick Williams             // Remove existing sessions of the user when password
1160bd79bce8SPatrick Williams             // changed
1161e518ef32SRavi Teja             persistent_data::SessionStore::getInstance()
1162492ec93aSEd Tanous                 .removeSessionsByUsernameExceptSession(params.username,
1163492ec93aSEd Tanous                                                        params.session);
1164e7b1b62bSEd Tanous             messages::success(asyncResp->res);
1165e7b1b62bSEd Tanous         }
11666c51eab1SEd Tanous     }
11676c51eab1SEd Tanous 
1168492ec93aSEd Tanous     if (params.enabled)
11696c51eab1SEd Tanous     {
1170bd79bce8SPatrick Williams         setDbusProperty(
1171bd79bce8SPatrick Williams             asyncResp, "Enabled", "xyz.openbmc_project.User.Manager",
1172492ec93aSEd Tanous             params.dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1173492ec93aSEd Tanous             "UserEnabled", *params.enabled);
11746c51eab1SEd Tanous     }
11756c51eab1SEd Tanous 
1176492ec93aSEd Tanous     if (params.roleId)
11776c51eab1SEd Tanous     {
1178492ec93aSEd Tanous         std::string priv = getPrivilegeFromRoleId(*params.roleId);
11796c51eab1SEd Tanous         if (priv.empty())
11806c51eab1SEd Tanous         {
1181492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, true, "Locked");
11826c51eab1SEd Tanous             return;
11836c51eab1SEd Tanous         }
1184492ec93aSEd Tanous         setDbusProperty(asyncResp, "RoleId", "xyz.openbmc_project.User.Manager",
1185492ec93aSEd Tanous                         params.dbusObjectPath,
1186492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes", "UserPrivilege",
1187492ec93aSEd Tanous                         priv);
11886c51eab1SEd Tanous     }
11896c51eab1SEd Tanous 
1190492ec93aSEd Tanous     if (params.locked)
11916c51eab1SEd Tanous     {
11926c51eab1SEd Tanous         // admin can unlock the account which is locked by
11936c51eab1SEd Tanous         // successive authentication failures but admin should
11946c51eab1SEd Tanous         // not be allowed to lock an account.
1195492ec93aSEd Tanous         if (*params.locked)
11966c51eab1SEd Tanous         {
1197492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, "true", "Locked");
11986c51eab1SEd Tanous             return;
11996c51eab1SEd Tanous         }
1200492ec93aSEd Tanous         setDbusProperty(asyncResp, "Locked", "xyz.openbmc_project.User.Manager",
1201492ec93aSEd Tanous                         params.dbusObjectPath,
1202492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes",
1203492ec93aSEd Tanous                         "UserLockedForFailedAttempt", *params.locked);
12046c51eab1SEd Tanous     }
120558345856SAbhishek Patel 
1206492ec93aSEd Tanous     if (params.accountTypes)
120758345856SAbhishek Patel     {
1208492ec93aSEd Tanous         patchAccountTypes(*params.accountTypes, asyncResp,
1209492ec93aSEd Tanous                           params.dbusObjectPath, params.userSelf);
121058345856SAbhishek Patel     }
1211492ec93aSEd Tanous }
1212492ec93aSEd Tanous 
1213492ec93aSEd Tanous inline void updateUserProperties(
1214492ec93aSEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1215492ec93aSEd Tanous     const std::string& username, const std::optional<std::string>& password,
1216492ec93aSEd Tanous     const std::optional<bool>& enabled,
1217492ec93aSEd Tanous     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
1218492ec93aSEd Tanous     const std::optional<std::vector<std::string>>& accountTypes, bool userSelf,
1219492ec93aSEd Tanous     const std::shared_ptr<persistent_data::UserSession>& session)
1220492ec93aSEd Tanous {
1221492ec93aSEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1222492ec93aSEd Tanous     tempObjPath /= username;
1223492ec93aSEd Tanous     std::string dbusObjectPath(tempObjPath);
1224492ec93aSEd Tanous 
1225492ec93aSEd Tanous     UserUpdateParams params{username, password, enabled,
1226492ec93aSEd Tanous                             roleId,   locked,   accountTypes,
1227492ec93aSEd Tanous                             userSelf, session,  dbusObjectPath};
1228492ec93aSEd Tanous 
1229492ec93aSEd Tanous     dbus::utility::checkDbusPathExists(
1230492ec93aSEd Tanous         dbusObjectPath,
1231492ec93aSEd Tanous         std::bind_front(afterVerifyUserExists, asyncResp, std::move(params)));
12326c51eab1SEd Tanous }
12336c51eab1SEd Tanous 
12344c7d4d33SEd Tanous inline void handleAccountServiceHead(
12354c7d4d33SEd Tanous     App& app, const crow::Request& req,
12361ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12376c51eab1SEd Tanous {
12383ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
123945ca1b86SEd Tanous     {
124045ca1b86SEd Tanous         return;
124145ca1b86SEd Tanous     }
12424c7d4d33SEd Tanous     asyncResp->res.addHeader(
12434c7d4d33SEd Tanous         boost::beast::http::field::link,
12444c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
12454c7d4d33SEd Tanous }
12464c7d4d33SEd Tanous 
1247504af5a0SPatrick Williams inline void getClientCertificates(
1248504af5a0SPatrick Williams     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12491aa375b8SEd Tanous     const nlohmann::json::json_pointer& keyLocation)
12501aa375b8SEd Tanous {
12511aa375b8SEd Tanous     boost::urls::url url(
12521aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates");
12531aa375b8SEd Tanous     std::array<std::string_view, 1> interfaces = {
12541aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Certificate"};
12551aa375b8SEd Tanous     std::string path = "/xyz/openbmc_project/certs/authority/truststore";
12561aa375b8SEd Tanous 
12571aa375b8SEd Tanous     collection_util::getCollectionToKey(asyncResp, url, interfaces, path,
12581aa375b8SEd Tanous                                         keyLocation);
12591aa375b8SEd Tanous }
12601aa375b8SEd Tanous 
12611aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceHead(
12621aa375b8SEd Tanous     App& app, const crow::Request& req,
12631aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12641aa375b8SEd Tanous     const std::string& /*id*/)
12651aa375b8SEd Tanous {
12661aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12671aa375b8SEd Tanous     {
12681aa375b8SEd Tanous         return;
12691aa375b8SEd Tanous     }
12701aa375b8SEd Tanous 
12711aa375b8SEd Tanous     asyncResp->res.addHeader(
12721aa375b8SEd Tanous         boost::beast::http::field::link,
12731aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/Certificate/Certificate.json>; rel=describedby");
12741aa375b8SEd Tanous }
12751aa375b8SEd Tanous 
12761aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceGet(
12771aa375b8SEd Tanous     App& app, const crow::Request& req,
12781aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id)
12791aa375b8SEd Tanous {
12801aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12811aa375b8SEd Tanous     {
12821aa375b8SEd Tanous         return;
12831aa375b8SEd Tanous     }
12841aa375b8SEd Tanous     BMCWEB_LOG_DEBUG("ClientCertificate Certificate ID={}", id);
12851aa375b8SEd Tanous     const boost::urls::url certURL = boost::urls::format(
12861aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/{}",
12871aa375b8SEd Tanous         id);
12881aa375b8SEd Tanous     std::string objPath =
12891aa375b8SEd Tanous         sdbusplus::message::object_path(certs::authorityObjectPath) / id;
12901aa375b8SEd Tanous     getCertificateProperties(
12911aa375b8SEd Tanous         asyncResp, objPath,
12921aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Manager.Authority.Truststore", id, certURL,
12931aa375b8SEd Tanous         "Client Certificate");
12941aa375b8SEd Tanous }
12951aa375b8SEd Tanous 
12961aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesHead(
12971aa375b8SEd Tanous     App& app, const crow::Request& req,
12981aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12991aa375b8SEd Tanous {
13001aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
13011aa375b8SEd Tanous     {
13021aa375b8SEd Tanous         return;
13031aa375b8SEd Tanous     }
13041aa375b8SEd Tanous 
13051aa375b8SEd Tanous     asyncResp->res.addHeader(
13061aa375b8SEd Tanous         boost::beast::http::field::link,
13071aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/CertificateCollection/CertificateCollection.json>; rel=describedby");
13081aa375b8SEd Tanous }
13091aa375b8SEd Tanous 
13101aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesGet(
13111aa375b8SEd Tanous     App& app, const crow::Request& req,
13121aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13131aa375b8SEd Tanous {
13141aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
13151aa375b8SEd Tanous     {
13161aa375b8SEd Tanous         return;
13171aa375b8SEd Tanous     }
13180f09ed32SMyung Bae 
13190f09ed32SMyung Bae     nlohmann::json& json = asyncResp->res.jsonValue;
13200f09ed32SMyung Bae     json["@odata.id"] =
13210f09ed32SMyung Bae         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
13220f09ed32SMyung Bae     json["@odata.type"] = "#CertificateCollection.CertificateCollection";
13230f09ed32SMyung Bae     json["Name"] = "Certificates Collection";
13240f09ed32SMyung Bae     json["Description"] = "Multi-factor Authentication Client Certificates";
13251aa375b8SEd Tanous     getClientCertificates(asyncResp, "/Members"_json_pointer);
13261aa375b8SEd Tanous }
13271aa375b8SEd Tanous 
13283ce3688aSEd Tanous using account_service::CertificateMappingAttribute;
13293ce3688aSEd Tanous using persistent_data::MTLSCommonNameParseMode;
1330504af5a0SPatrick Williams inline CertificateMappingAttribute getCertificateMapping(
1331504af5a0SPatrick Williams     MTLSCommonNameParseMode parse)
13323ce3688aSEd Tanous {
13333ce3688aSEd Tanous     switch (parse)
13343ce3688aSEd Tanous     {
13353ce3688aSEd Tanous         case MTLSCommonNameParseMode::CommonName:
13363ce3688aSEd Tanous         {
13373ce3688aSEd Tanous             return CertificateMappingAttribute::CommonName;
13383ce3688aSEd Tanous         }
13393ce3688aSEd Tanous         break;
13403ce3688aSEd Tanous         case MTLSCommonNameParseMode::Whole:
13413ce3688aSEd Tanous         {
13423ce3688aSEd Tanous             return CertificateMappingAttribute::Whole;
13433ce3688aSEd Tanous         }
13443ce3688aSEd Tanous         break;
13453ce3688aSEd Tanous         case MTLSCommonNameParseMode::UserPrincipalName:
13463ce3688aSEd Tanous         {
13473ce3688aSEd Tanous             return CertificateMappingAttribute::UserPrincipalName;
13483ce3688aSEd Tanous         }
13493ce3688aSEd Tanous         break;
13503ce3688aSEd Tanous         default:
13513ce3688aSEd Tanous         {
13523ce3688aSEd Tanous             return CertificateMappingAttribute::Invalid;
13533ce3688aSEd Tanous         }
13543ce3688aSEd Tanous         break;
13553ce3688aSEd Tanous     }
13563ce3688aSEd Tanous }
13573ce3688aSEd Tanous 
1358504af5a0SPatrick Williams inline void handleAccountServiceGet(
1359504af5a0SPatrick Williams     App& app, const crow::Request& req,
13604c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13614c7d4d33SEd Tanous {
1362afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1363afd369c6SJiaqing Zhao     {
1364afd369c6SJiaqing Zhao         return;
1365afd369c6SJiaqing Zhao     }
13663e72c202SNinad Palsule 
13673e72c202SNinad Palsule     if (req.session == nullptr)
13683e72c202SNinad Palsule     {
13693e72c202SNinad Palsule         messages::internalError(asyncResp->res);
13703e72c202SNinad Palsule         return;
13713e72c202SNinad Palsule     }
13723e72c202SNinad Palsule 
1373c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1374c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1375c1019828SEd Tanous 
1376afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1377afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1378afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1379afd369c6SJiaqing Zhao 
13801476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
13811476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
1382482a69e7SRavi Teja     json["@odata.type"] = "#AccountService.v1_15_0.AccountService";
13831476687dSEd Tanous     json["Id"] = "AccountService";
13841476687dSEd Tanous     json["Name"] = "Account Service";
13851476687dSEd Tanous     json["Description"] = "Account Service";
13861476687dSEd Tanous     json["ServiceEnabled"] = true;
13871476687dSEd Tanous     json["MaxPasswordLength"] = 20;
13881ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
13891476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
1390482a69e7SRavi Teja     json["HTTPBasicAuth"] = authMethodsConfig.basic
1391482a69e7SRavi Teja                                 ? account_service::BasicAuthState::Enabled
1392482a69e7SRavi Teja                                 : account_service::BasicAuthState::Disabled;
1393482a69e7SRavi Teja 
1394482a69e7SRavi Teja     nlohmann::json::array_t allowed;
1395482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Enabled);
1396482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Disabled);
1397482a69e7SRavi Teja     json["HTTPBasicAuth@AllowableValues"] = std::move(allowed);
1398482a69e7SRavi Teja 
13991aa375b8SEd Tanous     nlohmann::json::object_t clientCertificate;
14001aa375b8SEd Tanous     clientCertificate["Enabled"] = authMethodsConfig.tls;
14013281bcf1SEd Tanous     clientCertificate["RespondToUnauthenticatedClients"] =
14023281bcf1SEd Tanous         !authMethodsConfig.tlsStrict;
14033ce3688aSEd Tanous 
14043ce3688aSEd Tanous     using account_service::CertificateMappingAttribute;
14053ce3688aSEd Tanous 
14063ce3688aSEd Tanous     CertificateMappingAttribute mapping =
14073ce3688aSEd Tanous         getCertificateMapping(authMethodsConfig.mTLSCommonNameParsingMode);
14083ce3688aSEd Tanous     if (mapping == CertificateMappingAttribute::Invalid)
14093ce3688aSEd Tanous     {
14103ce3688aSEd Tanous         messages::internalError(asyncResp->res);
14113ce3688aSEd Tanous     }
14123ce3688aSEd Tanous     else
14133ce3688aSEd Tanous     {
14143ce3688aSEd Tanous         clientCertificate["CertificateMappingAttribute"] = mapping;
14153ce3688aSEd Tanous     }
14161aa375b8SEd Tanous     nlohmann::json::object_t certificates;
14171aa375b8SEd Tanous     certificates["@odata.id"] =
14181aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
14191aa375b8SEd Tanous     certificates["@odata.type"] =
14201aa375b8SEd Tanous         "#CertificateCollection.CertificateCollection";
14211aa375b8SEd Tanous     clientCertificate["Certificates"] = std::move(certificates);
14221aa375b8SEd Tanous     json["MultiFactorAuth"]["ClientCertificate"] = std::move(clientCertificate);
14231aa375b8SEd Tanous 
14241aa375b8SEd Tanous     getClientCertificates(
14251aa375b8SEd Tanous         asyncResp,
14261aa375b8SEd Tanous         "/MultiFactorAuth/ClientCertificate/Certificates/Members"_json_pointer);
14271aa375b8SEd Tanous 
14281476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
14295b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
14301476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
14311476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
14321476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
14331476687dSEd Tanous         authMethodsConfig.basic;
14341476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
14351476687dSEd Tanous         authMethodsConfig.sessionToken;
14361ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
14371ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
14381ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
14391476687dSEd Tanous 
14401ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
14411ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
14421ef4c342SEd Tanous     // permissions ConfigureManager
144372048780SAbhishek Patel     Privileges effectiveUserPrivileges =
14443e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
144572048780SAbhishek Patel 
144672048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
144772048780SAbhishek Patel                                          effectiveUserPrivileges))
144872048780SAbhishek Patel     {
14491ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
14501476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
145172048780SAbhishek Patel     }
1452deae6a78SEd Tanous     dbus::utility::getAllProperties(
1453deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1454deae6a78SEd Tanous         "xyz.openbmc_project.User.AccountPolicy",
14555e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
14561ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
14573d958bbcSAppaRao Puli             if (ec)
14583d958bbcSAppaRao Puli             {
14593d958bbcSAppaRao Puli                 messages::internalError(asyncResp->res);
14603d958bbcSAppaRao Puli                 return;
14613d958bbcSAppaRao Puli             }
1462d1bde9e5SKrzysztof Grobelny 
146362598e31SEd Tanous             BMCWEB_LOG_DEBUG("Got {} properties for AccountService",
146462598e31SEd Tanous                              propertiesList.size());
1465d1bde9e5SKrzysztof Grobelny 
1466d1bde9e5SKrzysztof Grobelny             const uint8_t* minPasswordLength = nullptr;
1467d1bde9e5SKrzysztof Grobelny             const uint32_t* accountUnlockTimeout = nullptr;
1468d1bde9e5SKrzysztof Grobelny             const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1469d1bde9e5SKrzysztof Grobelny 
1470d1bde9e5SKrzysztof Grobelny             const bool success = sdbusplus::unpackPropertiesNoThrow(
1471d1bde9e5SKrzysztof Grobelny                 dbus_utils::UnpackErrorPrinter(), propertiesList,
1472d1bde9e5SKrzysztof Grobelny                 "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1473d1bde9e5SKrzysztof Grobelny                 accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1474d1bde9e5SKrzysztof Grobelny                 maxLoginAttemptBeforeLockout);
1475d1bde9e5SKrzysztof Grobelny 
1476d1bde9e5SKrzysztof Grobelny             if (!success)
14773d958bbcSAppaRao Puli             {
1478d1bde9e5SKrzysztof Grobelny                 messages::internalError(asyncResp->res);
1479d1bde9e5SKrzysztof Grobelny                 return;
14803d958bbcSAppaRao Puli             }
1481d1bde9e5SKrzysztof Grobelny 
1482d1bde9e5SKrzysztof Grobelny             if (minPasswordLength != nullptr)
14833d958bbcSAppaRao Puli             {
1484bd79bce8SPatrick Williams                 asyncResp->res.jsonValue["MinPasswordLength"] =
1485bd79bce8SPatrick Williams                     *minPasswordLength;
14863d958bbcSAppaRao Puli             }
1487d1bde9e5SKrzysztof Grobelny 
1488d1bde9e5SKrzysztof Grobelny             if (accountUnlockTimeout != nullptr)
14893d958bbcSAppaRao Puli             {
1490d1bde9e5SKrzysztof Grobelny                 asyncResp->res.jsonValue["AccountLockoutDuration"] =
1491d1bde9e5SKrzysztof Grobelny                     *accountUnlockTimeout;
1492d1bde9e5SKrzysztof Grobelny             }
1493d1bde9e5SKrzysztof Grobelny 
1494d1bde9e5SKrzysztof Grobelny             if (maxLoginAttemptBeforeLockout != nullptr)
14953d958bbcSAppaRao Puli             {
1496002d39b4SEd Tanous                 asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1497d1bde9e5SKrzysztof Grobelny                     *maxLoginAttemptBeforeLockout;
14983d958bbcSAppaRao Puli             }
1499d1bde9e5SKrzysztof Grobelny         });
15006973a582SRatan Gupta 
150102cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1502ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1503cb13a392SEd Tanous         if (!success)
1504cb13a392SEd Tanous         {
1505cb13a392SEd Tanous             return;
1506cb13a392SEd Tanous         }
1507002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1508ab828d7cSRatan Gupta     };
1509ab828d7cSRatan Gupta 
1510ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1511ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
15121ef4c342SEd Tanous }
15136973a582SRatan Gupta 
1514bd79bce8SPatrick Williams inline void handleCertificateMappingAttributePatch(
1515bd79bce8SPatrick Williams     crow::Response& res, const std::string& certMapAttribute)
15163ce3688aSEd Tanous {
15173ce3688aSEd Tanous     MTLSCommonNameParseMode parseMode =
15183ce3688aSEd Tanous         persistent_data::getMTLSCommonNameParseMode(certMapAttribute);
15193ce3688aSEd Tanous     if (parseMode == MTLSCommonNameParseMode::Invalid)
15203ce3688aSEd Tanous     {
15213ce3688aSEd Tanous         messages::propertyValueNotInList(res, "CertificateMappingAttribute",
15223ce3688aSEd Tanous                                          certMapAttribute);
15233ce3688aSEd Tanous         return;
15243ce3688aSEd Tanous     }
15253ce3688aSEd Tanous 
15263ce3688aSEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15273ce3688aSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15283ce3688aSEd Tanous     authMethodsConfig.mTLSCommonNameParsingMode = parseMode;
15293ce3688aSEd Tanous }
15303ce3688aSEd Tanous 
15313281bcf1SEd Tanous inline void handleRespondToUnauthenticatedClientsPatch(
15323281bcf1SEd Tanous     App& app, const crow::Request& req, crow::Response& res,
15333281bcf1SEd Tanous     bool respondToUnauthenticatedClients)
15343281bcf1SEd Tanous {
15353281bcf1SEd Tanous     if (req.session != nullptr)
15363281bcf1SEd Tanous     {
15373281bcf1SEd Tanous         // Sanity check.  If the user isn't currently authenticated with mutual
15383281bcf1SEd Tanous         // TLS, they very likely are about to permanently lock themselves out.
15393281bcf1SEd Tanous         // Make sure they're using mutual TLS before allowing locking.
15403281bcf1SEd Tanous         if (req.session->sessionType != persistent_data::SessionType::MutualTLS)
15413281bcf1SEd Tanous         {
15423281bcf1SEd Tanous             messages::propertyValueExternalConflict(
15433281bcf1SEd Tanous                 res,
15443281bcf1SEd Tanous                 "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
15453281bcf1SEd Tanous                 respondToUnauthenticatedClients);
15463281bcf1SEd Tanous             return;
15473281bcf1SEd Tanous         }
15483281bcf1SEd Tanous     }
15493281bcf1SEd Tanous 
15503281bcf1SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15513281bcf1SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15523281bcf1SEd Tanous 
15533281bcf1SEd Tanous     // Change the settings
15543281bcf1SEd Tanous     authMethodsConfig.tlsStrict = !respondToUnauthenticatedClients;
15553281bcf1SEd Tanous 
15563281bcf1SEd Tanous     // Write settings to disk
15573281bcf1SEd Tanous     persistent_data::getConfig().writeData();
15583281bcf1SEd Tanous 
15593281bcf1SEd Tanous     // Trigger a reload, to apply the new settings to new connections
15603281bcf1SEd Tanous     app.loadCertificate();
15613281bcf1SEd Tanous }
15623281bcf1SEd Tanous 
15631ef4c342SEd Tanous inline void handleAccountServicePatch(
15641ef4c342SEd Tanous     App& app, const crow::Request& req,
15651ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
15661ef4c342SEd Tanous {
15673ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
156845ca1b86SEd Tanous     {
156945ca1b86SEd Tanous         return;
157045ca1b86SEd Tanous     }
1571f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1572f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1573ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1574f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
157510cb44f3SEd Tanous     LdapPatchParams ldapObject;
15763ce3688aSEd Tanous     std::optional<std::string> certificateMappingAttribute;
15773281bcf1SEd Tanous     std::optional<bool> respondToUnauthenticatedClients;
157810cb44f3SEd Tanous     LdapPatchParams activeDirectoryObject;
1579c1019828SEd Tanous     AuthMethods auth;
1580482a69e7SRavi Teja     std::optional<std::string> httpBasicAuth;
15813ce3688aSEd Tanous 
1582afc474aeSMyung Bae     if (!json_util::readJsonPatch(                                         //
1583afc474aeSMyung Bae             req, asyncResp->res,                                           //
1584afc474aeSMyung Bae             "AccountLockoutDuration", unlockTimeout,                       //
1585afc474aeSMyung Bae             "AccountLockoutThreshold", lockoutThreshold,                   //
1586afc474aeSMyung Bae             "ActiveDirectory/Authentication/AuthenticationType",
1587afc474aeSMyung Bae             activeDirectoryObject.authType,                                //
1588afc474aeSMyung Bae             "ActiveDirectory/Authentication/Password",
1589afc474aeSMyung Bae             activeDirectoryObject.password,                                //
1590afc474aeSMyung Bae             "ActiveDirectory/Authentication/Username",
1591afc474aeSMyung Bae             activeDirectoryObject.userName,                                //
1592afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/BaseDistinguishedNames",
1593afc474aeSMyung Bae             activeDirectoryObject.baseDNList,                              //
1594afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/GroupsAttribute",
1595afc474aeSMyung Bae             activeDirectoryObject.groupsAttribute,                         //
1596afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/UsernameAttribute",
1597afc474aeSMyung Bae             activeDirectoryObject.userNameAttribute,                       //
1598afc474aeSMyung Bae             "ActiveDirectory/RemoteRoleMapping",
1599afc474aeSMyung Bae             activeDirectoryObject.remoteRoleMapData,                       //
1600afc474aeSMyung Bae             "ActiveDirectory/ServiceAddresses",
1601afc474aeSMyung Bae             activeDirectoryObject.serviceAddressList,                      //
1602afc474aeSMyung Bae             "ActiveDirectory/ServiceEnabled",
1603afc474aeSMyung Bae             activeDirectoryObject.serviceEnabled,                          //
1604afc474aeSMyung Bae             "HTTPBasicAuth", httpBasicAuth,                                //
1605afc474aeSMyung Bae             "LDAP/Authentication/AuthenticationType", ldapObject.authType, //
1606afc474aeSMyung Bae             "LDAP/Authentication/Password", ldapObject.password,           //
1607afc474aeSMyung Bae             "LDAP/Authentication/Username", ldapObject.userName,           //
1608afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/BaseDistinguishedNames",
1609afc474aeSMyung Bae             ldapObject.baseDNList,                                         //
1610afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/GroupsAttribute",
1611afc474aeSMyung Bae             ldapObject.groupsAttribute,                                    //
1612afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/UsernameAttribute",
1613afc474aeSMyung Bae             ldapObject.userNameAttribute,                                  //
1614afc474aeSMyung Bae             "LDAP/RemoteRoleMapping", ldapObject.remoteRoleMapData,        //
1615afc474aeSMyung Bae             "LDAP/ServiceAddresses", ldapObject.serviceAddressList,        //
1616afc474aeSMyung Bae             "LDAP/ServiceEnabled", ldapObject.serviceEnabled,              //
1617afc474aeSMyung Bae             "MaxPasswordLength", maxPasswordLength,                        //
1618afc474aeSMyung Bae             "MinPasswordLength", minPasswordLength,                        //
1619afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/CertificateMappingAttribute",
1620afc474aeSMyung Bae             certificateMappingAttribute,                                   //
1621afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
1622afc474aeSMyung Bae             respondToUnauthenticatedClients,                               //
1623afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth,           //
1624afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie,                 //
1625afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken,     //
1626afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/TLS", auth.tls,                       //
1627afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken                  //
1628afc474aeSMyung Bae             ))
1629f5ffd806SEd Tanous     {
1630f5ffd806SEd Tanous         return;
1631f5ffd806SEd Tanous     }
1632f5ffd806SEd Tanous 
1633482a69e7SRavi Teja     if (httpBasicAuth)
1634482a69e7SRavi Teja     {
1635482a69e7SRavi Teja         if (*httpBasicAuth == "Enabled")
1636482a69e7SRavi Teja         {
1637482a69e7SRavi Teja             auth.basicAuth = true;
1638482a69e7SRavi Teja         }
1639482a69e7SRavi Teja         else if (*httpBasicAuth == "Disabled")
1640482a69e7SRavi Teja         {
1641482a69e7SRavi Teja             auth.basicAuth = false;
1642482a69e7SRavi Teja         }
1643482a69e7SRavi Teja         else
1644482a69e7SRavi Teja         {
1645482a69e7SRavi Teja             messages::propertyValueNotInList(asyncResp->res, "HttpBasicAuth",
1646482a69e7SRavi Teja                                              *httpBasicAuth);
1647482a69e7SRavi Teja         }
1648482a69e7SRavi Teja     }
1649482a69e7SRavi Teja 
16503281bcf1SEd Tanous     if (respondToUnauthenticatedClients)
16513281bcf1SEd Tanous     {
16523281bcf1SEd Tanous         handleRespondToUnauthenticatedClientsPatch(
16533281bcf1SEd Tanous             app, req, asyncResp->res, *respondToUnauthenticatedClients);
16543281bcf1SEd Tanous     }
16553281bcf1SEd Tanous 
16563ce3688aSEd Tanous     if (certificateMappingAttribute)
16573ce3688aSEd Tanous     {
16583ce3688aSEd Tanous         handleCertificateMappingAttributePatch(asyncResp->res,
16593ce3688aSEd Tanous                                                *certificateMappingAttribute);
16603ce3688aSEd Tanous     }
16613ce3688aSEd Tanous 
1662f5ffd806SEd Tanous     if (minPasswordLength)
1663f5ffd806SEd Tanous     {
1664d02aad39SEd Tanous         setDbusProperty(
1665e93abac6SGinu George             asyncResp, "MinPasswordLength", "xyz.openbmc_project.User.Manager",
1666d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16679ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1668e93abac6SGinu George             *minPasswordLength);
1669f5ffd806SEd Tanous     }
1670f5ffd806SEd Tanous 
1671f5ffd806SEd Tanous     if (maxPasswordLength)
1672f5ffd806SEd Tanous     {
16731ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1674f5ffd806SEd Tanous     }
1675f5ffd806SEd Tanous 
167610cb44f3SEd Tanous     handleLDAPPatch(std::move(activeDirectoryObject), asyncResp,
167710cb44f3SEd Tanous                     "ActiveDirectory");
167810cb44f3SEd Tanous     handleLDAPPatch(std::move(ldapObject), asyncResp, "LDAP");
1679f5ffd806SEd Tanous 
1680c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1681f5ffd806SEd Tanous 
1682f5ffd806SEd Tanous     if (unlockTimeout)
1683f5ffd806SEd Tanous     {
1684d02aad39SEd Tanous         setDbusProperty(
1685e93abac6SGinu George             asyncResp, "AccountLockoutDuration",
1686e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1687d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16889ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1689e93abac6SGinu George             *unlockTimeout);
1690f5ffd806SEd Tanous     }
1691f5ffd806SEd Tanous     if (lockoutThreshold)
1692f5ffd806SEd Tanous     {
1693d02aad39SEd Tanous         setDbusProperty(
1694e93abac6SGinu George             asyncResp, "AccountLockoutThreshold",
1695e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1696d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16979ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1698e93abac6SGinu George             "MaxLoginAttemptBeforeLockout", *lockoutThreshold);
1699f5ffd806SEd Tanous     }
17001ef4c342SEd Tanous }
1701f5ffd806SEd Tanous 
17024c7d4d33SEd Tanous inline void handleAccountCollectionHead(
17031ef4c342SEd Tanous     App& app, const crow::Request& req,
17041ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
17051ef4c342SEd Tanous {
17063ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
170745ca1b86SEd Tanous     {
170845ca1b86SEd Tanous         return;
170945ca1b86SEd Tanous     }
17104c7d4d33SEd Tanous     asyncResp->res.addHeader(
17114c7d4d33SEd Tanous         boost::beast::http::field::link,
17124c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17134c7d4d33SEd Tanous }
17144c7d4d33SEd Tanous 
17154c7d4d33SEd Tanous inline void handleAccountCollectionGet(
17164c7d4d33SEd Tanous     App& app, const crow::Request& req,
17174c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
17184c7d4d33SEd Tanous {
1719afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1720afd369c6SJiaqing Zhao     {
1721afd369c6SJiaqing Zhao         return;
1722afd369c6SJiaqing Zhao     }
17233e72c202SNinad Palsule 
17243e72c202SNinad Palsule     if (req.session == nullptr)
17253e72c202SNinad Palsule     {
17263e72c202SNinad Palsule         messages::internalError(asyncResp->res);
17273e72c202SNinad Palsule         return;
17283e72c202SNinad Palsule     }
17293e72c202SNinad Palsule 
1730afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1731afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1732afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17331476687dSEd Tanous 
17341476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
17351476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
17361ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
17371476687dSEd Tanous                                               "ManagerAccountCollection";
17381476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
17391476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
17400f74e643SEd Tanous 
17416c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
17423e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
17436c51eab1SEd Tanous 
1744f5e29f33SJunLin Chen     std::string thisUser;
1745f5e29f33SJunLin Chen     if (req.session)
1746f5e29f33SJunLin Chen     {
1747f5e29f33SJunLin Chen         thisUser = req.session->username;
1748f5e29f33SJunLin Chen     }
17495eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17505eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17515eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1752cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
17535e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1754711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1755b9b2e0b2SEd Tanous             if (ec)
1756b9b2e0b2SEd Tanous             {
1757f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
1758b9b2e0b2SEd Tanous                 return;
1759b9b2e0b2SEd Tanous             }
1760b9b2e0b2SEd Tanous 
1761cef1ddfbSEd Tanous             bool userCanSeeAllAccounts =
1762002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1763cef1ddfbSEd Tanous 
1764cef1ddfbSEd Tanous             bool userCanSeeSelf =
1765002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1766cef1ddfbSEd Tanous 
1767002d39b4SEd Tanous             nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1768b9b2e0b2SEd Tanous             memberArray = nlohmann::json::array();
1769b9b2e0b2SEd Tanous 
17709eb808c1SEd Tanous             for (const auto& userpath : users)
1771b9b2e0b2SEd Tanous             {
17722dfd18efSEd Tanous                 std::string user = userpath.first.filename();
17732dfd18efSEd Tanous                 if (user.empty())
1774b9b2e0b2SEd Tanous                 {
17752dfd18efSEd Tanous                     messages::internalError(asyncResp->res);
177662598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid firmware ID");
17772dfd18efSEd Tanous 
17782dfd18efSEd Tanous                     return;
1779b9b2e0b2SEd Tanous                 }
1780f365910cSGunnar Mills 
1781f365910cSGunnar Mills                 // As clarified by Redfish here:
1782f365910cSGunnar Mills                 // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
17836c51eab1SEd Tanous                 // Users without ConfigureUsers, only see their own
17846c51eab1SEd Tanous                 // account. Users with ConfigureUsers, see all
17856c51eab1SEd Tanous                 // accounts.
1786bd79bce8SPatrick Williams                 if (userCanSeeAllAccounts ||
1787bd79bce8SPatrick Williams                     (thisUser == user && userCanSeeSelf))
1788f365910cSGunnar Mills                 {
17891476687dSEd Tanous                     nlohmann::json::object_t member;
17903b32780dSEd Tanous                     member["@odata.id"] = boost::urls::format(
17913b32780dSEd Tanous                         "/redfish/v1/AccountService/Accounts/{}", user);
1792b2ba3072SPatrick Williams                     memberArray.emplace_back(std::move(member));
1793b9b2e0b2SEd Tanous                 }
1794f365910cSGunnar Mills             }
1795bd79bce8SPatrick Williams             asyncResp->res.jsonValue["Members@odata.count"] =
1796bd79bce8SPatrick Williams                 memberArray.size();
17975eb468daSGeorge Liu         });
17981ef4c342SEd Tanous }
17996c51eab1SEd Tanous 
180097e90da3SNinad Palsule inline void processAfterCreateUser(
180197e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
180297e90da3SNinad Palsule     const std::string& username, const std::string& password,
180397e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
180497e90da3SNinad Palsule {
180597e90da3SNinad Palsule     if (ec)
180697e90da3SNinad Palsule     {
180797e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
180897e90da3SNinad Palsule         return;
180997e90da3SNinad Palsule     }
181097e90da3SNinad Palsule 
181197e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
181297e90da3SNinad Palsule     {
181397e90da3SNinad Palsule         // At this point we have a user that's been
181497e90da3SNinad Palsule         // created, but the password set
181597e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
181697e90da3SNinad Palsule         // that we've already created
181797e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
181897e90da3SNinad Palsule         tempObjPath /= username;
181997e90da3SNinad Palsule         const std::string userPath(tempObjPath);
182097e90da3SNinad Palsule 
1821177612aaSEd Tanous         dbus::utility::async_method_call(
1822177612aaSEd Tanous             asyncResp,
182397e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
182497e90da3SNinad Palsule                 if (ec3)
182597e90da3SNinad Palsule                 {
182697e90da3SNinad Palsule                     messages::internalError(asyncResp->res);
182797e90da3SNinad Palsule                     return;
182897e90da3SNinad Palsule                 }
182997e90da3SNinad Palsule 
183097e90da3SNinad Palsule                 // If password is invalid
18319bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
183297e90da3SNinad Palsule                                                    "Password");
183397e90da3SNinad Palsule             },
183497e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
183597e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
183697e90da3SNinad Palsule 
183762598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
183897e90da3SNinad Palsule         return;
183997e90da3SNinad Palsule     }
184097e90da3SNinad Palsule 
184197e90da3SNinad Palsule     messages::created(asyncResp->res);
184297e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
184397e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
184497e90da3SNinad Palsule }
184597e90da3SNinad Palsule 
184697e90da3SNinad Palsule inline void processAfterGetAllGroups(
184797e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
184897e90da3SNinad Palsule     const std::string& username, const std::string& password,
1849e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
18509ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
185197e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
185297e90da3SNinad Palsule {
18533e72c202SNinad Palsule     std::vector<std::string> userGroups;
18549ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
18559ba73934SNinad Palsule 
18569ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
18579ba73934SNinad Palsule     if (accountTypes)
18589ba73934SNinad Palsule     {
18599ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
18609ba73934SNinad Palsule                                          accountTypeUserGroups))
18619ba73934SNinad Palsule         {
18629ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
18639ba73934SNinad Palsule             // logged.
18649ba73934SNinad Palsule             return;
18659ba73934SNinad Palsule         }
18669ba73934SNinad Palsule     }
18679ba73934SNinad Palsule 
18683e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
18693e72c202SNinad Palsule     {
18709ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
18719ba73934SNinad Palsule         // in the account types group list.
18729ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
18739ba73934SNinad Palsule         {
18749ba73934SNinad Palsule             bool found = false;
18759ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
18769ba73934SNinad Palsule             {
18779ba73934SNinad Palsule                 if (grp == grp1)
18789ba73934SNinad Palsule                 {
18799ba73934SNinad Palsule                     found = true;
18809ba73934SNinad Palsule                     break;
18819ba73934SNinad Palsule                 }
18829ba73934SNinad Palsule             }
18839ba73934SNinad Palsule             if (!found)
18849ba73934SNinad Palsule             {
18859ba73934SNinad Palsule                 continue;
18869ba73934SNinad Palsule             }
18879ba73934SNinad Palsule         }
18889ba73934SNinad Palsule 
18893e72c202SNinad Palsule         // Console access is provided to the user who is a member of
18903e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
18913e72c202SNinad Palsule         // hostconsole group only for the administrator.
18929ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
18933e72c202SNinad Palsule         {
18949ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
18959ba73934SNinad Palsule             {
189662598e31SEd Tanous                 BMCWEB_LOG_ERROR(
189762598e31SEd Tanous                     "Only administrator can get HostConsole access");
18989ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
18999ba73934SNinad Palsule                 return;
19009ba73934SNinad Palsule             }
19019ba73934SNinad Palsule             continue;
19029ba73934SNinad Palsule         }
19033e72c202SNinad Palsule         userGroups.emplace_back(grp);
19043e72c202SNinad Palsule     }
19059ba73934SNinad Palsule 
19069ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
19079ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
19089ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
19099ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
19109ba73934SNinad Palsule     {
19119ba73934SNinad Palsule         messages::internalError(asyncResp->res);
19129ba73934SNinad Palsule         return;
19133e72c202SNinad Palsule     }
1914177612aaSEd Tanous     dbus::utility::async_method_call(
1915177612aaSEd Tanous         asyncResp,
191697e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
191797e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
191897e90da3SNinad Palsule             processAfterCreateUser(asyncResp, username, password, ec2, m);
191997e90da3SNinad Palsule         },
192097e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
19213e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1922e01d0c36SEd Tanous         roleId, enabled);
192397e90da3SNinad Palsule }
192497e90da3SNinad Palsule 
19251ef4c342SEd Tanous inline void handleAccountCollectionPost(
19261ef4c342SEd Tanous     App& app, const crow::Request& req,
19271ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
19281ef4c342SEd Tanous {
19293ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
193045ca1b86SEd Tanous     {
193145ca1b86SEd Tanous         return;
193245ca1b86SEd Tanous     }
19339712f8acSEd Tanous     std::string username;
19349712f8acSEd Tanous     std::string password;
1935e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1936e01d0c36SEd Tanous     std::optional<bool> enabledJson;
19379ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1938afc474aeSMyung Bae     if (!json_util::readJsonPatch(        //
1939afc474aeSMyung Bae             req, asyncResp->res,          //
1940afc474aeSMyung Bae             "AccountTypes", accountTypes, //
1941afc474aeSMyung Bae             "Enabled", enabledJson,       //
1942afc474aeSMyung Bae             "Password", password,         //
1943afc474aeSMyung Bae             "RoleId", roleIdJson,         //
1944afc474aeSMyung Bae             "UserName", username          //
1945afc474aeSMyung Bae             ))
194604ae99ecSEd Tanous     {
194704ae99ecSEd Tanous         return;
194804ae99ecSEd Tanous     }
194904ae99ecSEd Tanous 
1950e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1951e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
195284e12cb7SAppaRao Puli     if (priv.empty())
195304ae99ecSEd Tanous     {
1954e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
195504ae99ecSEd Tanous         return;
195604ae99ecSEd Tanous     }
19579712f8acSEd Tanous     roleId = priv;
195804ae99ecSEd Tanous 
1959e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1960e01d0c36SEd Tanous 
1961599c71d8SAyushi Smriti     // Reading AllGroups property
1962deae6a78SEd Tanous     dbus::utility::getProperty<std::vector<std::string>>(
1963deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1964deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "AllGroups",
19659ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
19669ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
19671e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1968599c71d8SAyushi Smriti             if (ec)
1969599c71d8SAyushi Smriti             {
1970a0735a4eSGunnar Mills                 BMCWEB_LOG_ERROR("D-Bus response error {}", ec);
1971599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1972599c71d8SAyushi Smriti                 return;
1973599c71d8SAyushi Smriti             }
1974599c71d8SAyushi Smriti 
19751e1e598dSJonathan Doman             if (allGroupsList.empty())
1976599c71d8SAyushi Smriti             {
1977599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1978599c71d8SAyushi Smriti                 return;
1979599c71d8SAyushi Smriti             }
1980599c71d8SAyushi Smriti 
1981bd79bce8SPatrick Williams             processAfterGetAllGroups(asyncResp, username, password, roleId,
1982bd79bce8SPatrick Williams                                      enabled, accountTypes, allGroupsList);
19831e1e598dSJonathan Doman         });
19841ef4c342SEd Tanous }
1985b9b2e0b2SEd Tanous 
1986504af5a0SPatrick Williams inline void handleAccountHead(
1987504af5a0SPatrick Williams     App& app, const crow::Request& req,
19886c51eab1SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19894c7d4d33SEd Tanous     const std::string& /*accountName*/)
19901ef4c342SEd Tanous {
19913ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
199245ca1b86SEd Tanous     {
199345ca1b86SEd Tanous         return;
199445ca1b86SEd Tanous     }
19954c7d4d33SEd Tanous     asyncResp->res.addHeader(
19964c7d4d33SEd Tanous         boost::beast::http::field::link,
19974c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
19984c7d4d33SEd Tanous }
1999afd369c6SJiaqing Zhao 
2000504af5a0SPatrick Williams inline void handleAccountGet(
2001504af5a0SPatrick Williams     App& app, const crow::Request& req,
20024c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
20034c7d4d33SEd Tanous     const std::string& accountName)
20044c7d4d33SEd Tanous {
2005afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2006afd369c6SJiaqing Zhao     {
2007afd369c6SJiaqing Zhao         return;
2008afd369c6SJiaqing Zhao     }
2009afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
2010afd369c6SJiaqing Zhao         boost::beast::http::field::link,
2011afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
2012afd369c6SJiaqing Zhao 
201325b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
201425b54dbaSEd Tanous     {
2015031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
201625b54dbaSEd Tanous         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
201725b54dbaSEd Tanous                                    accountName);
2018031514fbSJunLin Chen         return;
201925b54dbaSEd Tanous     }
2020afd369c6SJiaqing Zhao 
2021031514fbSJunLin Chen     if (req.session == nullptr)
2022031514fbSJunLin Chen     {
2023031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2024031514fbSJunLin Chen         return;
2025031514fbSJunLin Chen     }
20266c51eab1SEd Tanous     if (req.session->username != accountName)
2027b9b2e0b2SEd Tanous     {
20286c51eab1SEd Tanous         // At this point we've determined that the user is trying to
20291ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
20301ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
20311ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
20326c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
20333e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
20341ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
20351ef4c342SEd Tanous                                                          "ConfigureManager"};
20366c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
20376c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
2038900f9497SJoseph Reynolds         {
203962598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
2040900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2041900f9497SJoseph Reynolds             return;
2042900f9497SJoseph Reynolds         }
2043900f9497SJoseph Reynolds     }
2044900f9497SJoseph Reynolds 
20455eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
20465eb468daSGeorge Liu     dbus::utility::getManagedObjects(
20475eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
20481ef4c342SEd Tanous         [asyncResp,
20495e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
2050711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
2051b9b2e0b2SEd Tanous             if (ec)
2052b9b2e0b2SEd Tanous             {
2053f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
2054b9b2e0b2SEd Tanous                 return;
2055b9b2e0b2SEd Tanous             }
20563544d2a7SEd Tanous             const auto userIt = std::ranges::find_if(
205780f79a40SMichael Shen                 users,
205880f79a40SMichael Shen                 [accountName](
2059b477fd44SP Dheeraj Srujan Kumar                     const std::pair<sdbusplus::message::object_path,
206080f79a40SMichael Shen                                     dbus::utility::DBusInterfacesMap>& user) {
206155f79e6fSEd Tanous                     return accountName == user.first.filename();
2062b477fd44SP Dheeraj Srujan Kumar                 });
2063b9b2e0b2SEd Tanous 
206484e12cb7SAppaRao Puli             if (userIt == users.end())
2065b9b2e0b2SEd Tanous             {
2066002d39b4SEd Tanous                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
2067002d39b4SEd Tanous                                            accountName);
206884e12cb7SAppaRao Puli                 return;
206984e12cb7SAppaRao Puli             }
20704e68c45bSAyushi Smriti 
20711476687dSEd Tanous             asyncResp->res.jsonValue["@odata.type"] =
207258345856SAbhishek Patel                 "#ManagerAccount.v1_7_0.ManagerAccount";
20731476687dSEd Tanous             asyncResp->res.jsonValue["Name"] = "User Account";
20741476687dSEd Tanous             asyncResp->res.jsonValue["Description"] = "User Account";
20751476687dSEd Tanous             asyncResp->res.jsonValue["Password"] = nullptr;
207658345856SAbhishek Patel             asyncResp->res.jsonValue["StrictAccountTypes"] = true;
20774e68c45bSAyushi Smriti 
207884e12cb7SAppaRao Puli             for (const auto& interface : userIt->second)
207965b0dc32SEd Tanous             {
2080002d39b4SEd Tanous                 if (interface.first == "xyz.openbmc_project.User.Attributes")
208165b0dc32SEd Tanous                 {
2082b437a535SAsmitha Karunanithi                     const bool* userEnabled = nullptr;
2083b437a535SAsmitha Karunanithi                     const bool* userLocked = nullptr;
2084b437a535SAsmitha Karunanithi                     const std::string* userPrivPtr = nullptr;
2085b437a535SAsmitha Karunanithi                     const bool* userPasswordExpired = nullptr;
2086b437a535SAsmitha Karunanithi                     const std::vector<std::string>* userGroups = nullptr;
2087b437a535SAsmitha Karunanithi 
2088b437a535SAsmitha Karunanithi                     const bool success = sdbusplus::unpackPropertiesNoThrow(
2089b437a535SAsmitha Karunanithi                         dbus_utils::UnpackErrorPrinter(), interface.second,
2090b437a535SAsmitha Karunanithi                         "UserEnabled", userEnabled,
2091b437a535SAsmitha Karunanithi                         "UserLockedForFailedAttempt", userLocked,
2092b437a535SAsmitha Karunanithi                         "UserPrivilege", userPrivPtr, "UserPasswordExpired",
2093b437a535SAsmitha Karunanithi                         userPasswordExpired, "UserGroups", userGroups);
2094b437a535SAsmitha Karunanithi                     if (!success)
209565b0dc32SEd Tanous                     {
2096b437a535SAsmitha Karunanithi                         messages::internalError(asyncResp->res);
2097b437a535SAsmitha Karunanithi                         return;
2098b437a535SAsmitha Karunanithi                     }
209965b0dc32SEd Tanous                     if (userEnabled == nullptr)
210065b0dc32SEd Tanous                     {
210162598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
210284e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
210384e12cb7SAppaRao Puli                         return;
210465b0dc32SEd Tanous                     }
2105002d39b4SEd Tanous                     asyncResp->res.jsonValue["Enabled"] = *userEnabled;
2106b437a535SAsmitha Karunanithi 
210765b0dc32SEd Tanous                     if (userLocked == nullptr)
210865b0dc32SEd Tanous                     {
210962598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserLockedForF"
211084e12cb7SAppaRao Puli                                          "ailedAttempt "
211162598e31SEd Tanous                                          "wasn't a bool");
211284e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
211384e12cb7SAppaRao Puli                         return;
211465b0dc32SEd Tanous                     }
2115002d39b4SEd Tanous                     asyncResp->res.jsonValue["Locked"] = *userLocked;
211620fa6a2cSEd Tanous                     nlohmann::json::array_t allowed;
211720fa6a2cSEd Tanous                     // can only unlock accounts
211820fa6a2cSEd Tanous                     allowed.emplace_back("false");
2119b437a535SAsmitha Karunanithi                     asyncResp->res.jsonValue["Locked@Redfish.AllowableValues"] =
212020fa6a2cSEd Tanous                         std::move(allowed);
2121b437a535SAsmitha Karunanithi 
212254fc587aSNagaraju Goruganti                     if (userPrivPtr == nullptr)
212384e12cb7SAppaRao Puli                     {
212462598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
212562598e31SEd Tanous                                          "string");
212684e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
212784e12cb7SAppaRao Puli                         return;
212884e12cb7SAppaRao Puli                     }
2129b437a535SAsmitha Karunanithi                     std::string role = getRoleIdFromPrivilege(*userPrivPtr);
213054fc587aSNagaraju Goruganti                     if (role.empty())
213184e12cb7SAppaRao Puli                     {
213262598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid user role");
213384e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
213484e12cb7SAppaRao Puli                         return;
213584e12cb7SAppaRao Puli                     }
213654fc587aSNagaraju Goruganti                     asyncResp->res.jsonValue["RoleId"] = role;
213784e12cb7SAppaRao Puli 
21381476687dSEd Tanous                     nlohmann::json& roleEntry =
2139002d39b4SEd Tanous                         asyncResp->res.jsonValue["Links"]["Role"];
21403b32780dSEd Tanous                     roleEntry["@odata.id"] = boost::urls::format(
21413b32780dSEd Tanous                         "/redfish/v1/AccountService/Roles/{}", role);
2142b437a535SAsmitha Karunanithi 
21433bf4e632SJoseph Reynolds                     if (userPasswordExpired == nullptr)
21443bf4e632SJoseph Reynolds                     {
2145b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("UserPasswordExpired wasn't a bool");
21463bf4e632SJoseph Reynolds                         messages::internalError(asyncResp->res);
21473bf4e632SJoseph Reynolds                         return;
21483bf4e632SJoseph Reynolds                     }
2149002d39b4SEd Tanous                     asyncResp->res.jsonValue["PasswordChangeRequired"] =
21503bf4e632SJoseph Reynolds                         *userPasswordExpired;
2151b437a535SAsmitha Karunanithi 
2152c7229815SAbhishek Patel                     if (userGroups == nullptr)
2153c7229815SAbhishek Patel                     {
2154b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("userGroups wasn't a string vector");
2155c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2156c7229815SAbhishek Patel                         return;
2157c7229815SAbhishek Patel                     }
2158b437a535SAsmitha Karunanithi                     if (!translateUserGroup(*userGroups, asyncResp->res))
2159c7229815SAbhishek Patel                     {
216062598e31SEd Tanous                         BMCWEB_LOG_ERROR("userGroups mapping failed");
2161c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2162c7229815SAbhishek Patel                         return;
2163c7229815SAbhishek Patel                     }
2164c7229815SAbhishek Patel                 }
216565b0dc32SEd Tanous             }
216665b0dc32SEd Tanous 
21673b32780dSEd Tanous             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
21683b32780dSEd Tanous                 "/redfish/v1/AccountService/Accounts/{}", accountName);
2169b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["Id"] = accountName;
2170b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["UserName"] = accountName;
21715eb468daSGeorge Liu         });
21721ef4c342SEd Tanous }
2173a840879dSEd Tanous 
2174504af5a0SPatrick Williams inline void handleAccountDelete(
2175504af5a0SPatrick Williams     App& app, const crow::Request& req,
21766c51eab1SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
21771ef4c342SEd Tanous     const std::string& username)
21781ef4c342SEd Tanous {
21793ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
218045ca1b86SEd Tanous     {
218145ca1b86SEd Tanous         return;
218245ca1b86SEd Tanous     }
21831ef4c342SEd Tanous 
218425b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
218525b54dbaSEd Tanous     {
2186031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
2187d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
2188031514fbSJunLin Chen         return;
218925b54dbaSEd Tanous     }
21901ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
21911ef4c342SEd Tanous     tempObjPath /= username;
21921ef4c342SEd Tanous     const std::string userPath(tempObjPath);
21931ef4c342SEd Tanous 
2194177612aaSEd Tanous     dbus::utility::async_method_call(
2195177612aaSEd Tanous         asyncResp,
21965e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
21971ef4c342SEd Tanous             if (ec)
21981ef4c342SEd Tanous             {
2199d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
22001ef4c342SEd Tanous                                            username);
22011ef4c342SEd Tanous                 return;
22021ef4c342SEd Tanous             }
22031ef4c342SEd Tanous 
22041ef4c342SEd Tanous             messages::accountRemoved(asyncResp->res);
22051ef4c342SEd Tanous         },
22061ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
22071ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
22081ef4c342SEd Tanous }
22091ef4c342SEd Tanous 
2210504af5a0SPatrick Williams inline void handleAccountPatch(
2211504af5a0SPatrick Williams     App& app, const crow::Request& req,
22121ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
22131ef4c342SEd Tanous     const std::string& username)
22141ef4c342SEd Tanous {
22151ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
22161ef4c342SEd Tanous     {
22171ef4c342SEd Tanous         return;
22181ef4c342SEd Tanous     }
221925b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
222025b54dbaSEd Tanous     {
22211ef4c342SEd Tanous         // If authentication is disabled, there are no user accounts
2222d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
22231ef4c342SEd Tanous         return;
222425b54dbaSEd Tanous     }
2225a24526dcSEd Tanous     std::optional<std::string> newUserName;
2226a24526dcSEd Tanous     std::optional<std::string> password;
2227a24526dcSEd Tanous     std::optional<bool> enabled;
2228a24526dcSEd Tanous     std::optional<std::string> roleId;
222924c8542dSRatan Gupta     std::optional<bool> locked;
223058345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
223158345856SAbhishek Patel 
2232031514fbSJunLin Chen     if (req.session == nullptr)
2233031514fbSJunLin Chen     {
2234031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2235031514fbSJunLin Chen         return;
2236031514fbSJunLin Chen     }
2237031514fbSJunLin Chen 
22382b9c1dfeSEd Tanous     bool userSelf = (username == req.session->username);
22392b9c1dfeSEd Tanous 
2240e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
22413e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
2242e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
2243e9cc5172SEd Tanous     bool userHasConfigureUsers =
2244e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
2245e9cc5172SEd Tanous     if (userHasConfigureUsers)
2246e9cc5172SEd Tanous     {
2247e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
2248afc474aeSMyung Bae         if (!json_util::readJsonPatch(        //
2249afc474aeSMyung Bae                 req, asyncResp->res,          //
2250afc474aeSMyung Bae                 "AccountTypes", accountTypes, //
2251afc474aeSMyung Bae                 "Enabled", enabled,           //
2252afc474aeSMyung Bae                 "Locked", locked,             //
2253afc474aeSMyung Bae                 "Password", password,         //
2254afc474aeSMyung Bae                 "RoleId", roleId,             //
2255afc474aeSMyung Bae                 "UserName", newUserName       //
2256afc474aeSMyung Bae                 ))
2257a840879dSEd Tanous         {
2258a840879dSEd Tanous             return;
2259a840879dSEd Tanous         }
2260e9cc5172SEd Tanous     }
2261e9cc5172SEd Tanous     else
2262900f9497SJoseph Reynolds     {
2263e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
226458345856SAbhishek Patel         if (!userSelf)
2265900f9497SJoseph Reynolds         {
2266900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2267900f9497SJoseph Reynolds             return;
2268900f9497SJoseph Reynolds         }
2269031514fbSJunLin Chen 
2270e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
22711ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
22721ef4c342SEd Tanous                                       password))
2273e9cc5172SEd Tanous         {
2274e9cc5172SEd Tanous             return;
2275e9cc5172SEd Tanous         }
2276900f9497SJoseph Reynolds     }
2277900f9497SJoseph Reynolds 
227866b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
22796c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
22806c51eab1SEd Tanous     // updating user properties other then username. If username
22816c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
22826c51eab1SEd Tanous     // user rename request.
228366b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
2284a840879dSEd Tanous     {
22851ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
2286e518ef32SRavi Teja                              locked, accountTypes, userSelf, req.session);
228784e12cb7SAppaRao Puli         return;
228884e12cb7SAppaRao Puli     }
2289177612aaSEd Tanous     dbus::utility::async_method_call(
2290177612aaSEd Tanous         asyncResp,
22916c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
22921ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
2293608ad2ccSEd Tanous          locked, userSelf, session = req.session,
2294608ad2ccSEd Tanous          accountTypes(std::move(accountTypes))](
2295e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
229684e12cb7SAppaRao Puli             if (ec)
229784e12cb7SAppaRao Puli             {
2298002d39b4SEd Tanous                 userErrorMessageHandler(m.get_error(), asyncResp, newUser,
2299002d39b4SEd Tanous                                         username);
2300a840879dSEd Tanous                 return;
2301a840879dSEd Tanous             }
2302a840879dSEd Tanous 
2303002d39b4SEd Tanous             updateUserProperties(asyncResp, newUser, password, enabled, roleId,
2304608ad2ccSEd Tanous                                  locked, accountTypes, userSelf, session);
230584e12cb7SAppaRao Puli         },
23061ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
230784e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
230884e12cb7SAppaRao Puli         *newUserName);
23091ef4c342SEd Tanous }
23101ef4c342SEd Tanous 
23111ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
23121ef4c342SEd Tanous {
23131ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23144c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
23154c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23164c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
23174c7d4d33SEd Tanous 
23184c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23191ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
23201ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23211ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
23221ef4c342SEd Tanous 
23231ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23241ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
23251ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23261ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
23271ef4c342SEd Tanous 
23281aa375b8SEd Tanous     BMCWEB_ROUTE(
23291aa375b8SEd Tanous         app,
2330e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23311aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificateCollection)
23321aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23331aa375b8SEd Tanous             handleAccountServiceClientCertificatesHead, std::ref(app)));
23341aa375b8SEd Tanous 
23351aa375b8SEd Tanous     BMCWEB_ROUTE(
23361aa375b8SEd Tanous         app,
2337e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23381aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificateCollection)
23391aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23401aa375b8SEd Tanous             handleAccountServiceClientCertificatesGet, std::ref(app)));
23411aa375b8SEd Tanous 
23421aa375b8SEd Tanous     BMCWEB_ROUTE(
23431aa375b8SEd Tanous         app,
2344e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23451aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificate)
23461aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23471aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceHead, std::ref(app)));
23481aa375b8SEd Tanous 
23491aa375b8SEd Tanous     BMCWEB_ROUTE(
23501aa375b8SEd Tanous         app,
23511aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23521aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificate)
23531aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23541aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceGet, std::ref(app)));
23551aa375b8SEd Tanous 
23561ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23574c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
23584c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23594c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
23604c7d4d33SEd Tanous 
23614c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23621ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
23631ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23641ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
23651ef4c342SEd Tanous 
23661ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23671ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
23681ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
23691ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
23701ef4c342SEd Tanous 
23711ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23724c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
23734c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23744c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
23754c7d4d33SEd Tanous 
23764c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23771ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
23781ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23791ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
23801ef4c342SEd Tanous 
23811ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23821ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
23831ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
23841ef4c342SEd Tanous         // yet
23851ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
23861ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23871ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
238884e12cb7SAppaRao Puli 
23896c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2390ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
23916c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
239220fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
239306e086d9SEd Tanous }
239488d16c9aSLewanczyk, Dawid 
239588d16c9aSLewanczyk, Dawid } // namespace redfish
2396