xref: /openbmc/bmcweb/features/redfish/lib/account_service.hpp (revision d78572018fc2022091ff8b8eb5a7fef2172ba3d6)
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 
6*d7857201SEd Tanous #include "bmcweb_config.h"
7*d7857201SEd Tanous 
83ccb3adbSEd Tanous #include "app.hpp"
9*d7857201SEd Tanous #include "async_resp.hpp"
10a0735a4eSGunnar Mills #include "boost_formatters.hpp"
111aa375b8SEd Tanous #include "certificate_service.hpp"
12*d7857201SEd Tanous #include "dbus_singleton.hpp"
133ccb3adbSEd Tanous #include "dbus_utility.hpp"
143ccb3adbSEd Tanous #include "error_messages.hpp"
150ec8b83dSEd Tanous #include "generated/enums/account_service.hpp"
16*d7857201SEd Tanous #include "http_request.hpp"
17*d7857201SEd Tanous #include "http_response.hpp"
18*d7857201SEd Tanous #include "logging.hpp"
19*d7857201SEd Tanous #include "pam_authenticate.hpp"
203ccb3adbSEd Tanous #include "persistent_data.hpp"
21*d7857201SEd Tanous #include "privileges.hpp"
223ccb3adbSEd Tanous #include "query.hpp"
230ec8b83dSEd Tanous #include "registries/privilege_registry.hpp"
243281bcf1SEd Tanous #include "sessions.hpp"
251aa375b8SEd Tanous #include "utils/collection.hpp"
263ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
273ccb3adbSEd Tanous #include "utils/json_utils.hpp"
280ec8b83dSEd Tanous 
29*d7857201SEd Tanous #include <security/_pam_types.h>
30*d7857201SEd Tanous #include <systemd/sd-bus.h>
31*d7857201SEd Tanous 
32*d7857201SEd Tanous #include <boost/beast/http/field.hpp>
33*d7857201SEd Tanous #include <boost/beast/http/status.hpp>
34*d7857201SEd Tanous #include <boost/beast/http/verb.hpp>
351aa375b8SEd Tanous #include <boost/url/format.hpp>
361aa375b8SEd Tanous #include <boost/url/url.hpp>
37*d7857201SEd Tanous #include <nlohmann/json.hpp>
38*d7857201SEd Tanous #include <sdbusplus/message.hpp>
39d1bde9e5SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
401214b7e7SGunnar Mills 
41*d7857201SEd Tanous #include <algorithm>
422b73119cSGeorge Liu #include <array>
43*d7857201SEd Tanous #include <cstddef>
44*d7857201SEd Tanous #include <cstdint>
45*d7857201SEd Tanous #include <cstring>
46*d7857201SEd Tanous #include <format>
47*d7857201SEd Tanous #include <functional>
481aa375b8SEd Tanous #include <memory>
49c7229815SAbhishek Patel #include <optional>
503544d2a7SEd Tanous #include <ranges>
51c7229815SAbhishek Patel #include <string>
522b73119cSGeorge Liu #include <string_view>
5320fa6a2cSEd Tanous #include <utility>
54*d7857201SEd Tanous #include <variant>
55c7229815SAbhishek Patel #include <vector>
56c7229815SAbhishek Patel 
571abe55efSEd Tanous namespace redfish
581abe55efSEd Tanous {
5988d16c9aSLewanczyk, Dawid 
6023a21a1cSEd Tanous constexpr const char* ldapConfigObjectName =
616973a582SRatan Gupta     "/xyz/openbmc_project/user/ldap/openldap";
622c70f800SEd Tanous constexpr const char* adConfigObject =
63ab828d7cSRatan Gupta     "/xyz/openbmc_project/user/ldap/active_directory";
64ab828d7cSRatan Gupta 
65b477fd44SP Dheeraj Srujan Kumar constexpr const char* rootUserDbusPath = "/xyz/openbmc_project/user/";
666973a582SRatan Gupta constexpr const char* ldapRootObject = "/xyz/openbmc_project/user/ldap";
676973a582SRatan Gupta constexpr const char* ldapDbusService = "xyz.openbmc_project.Ldap.Config";
686973a582SRatan Gupta constexpr const char* ldapConfigInterface =
696973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Config";
706973a582SRatan Gupta constexpr const char* ldapCreateInterface =
716973a582SRatan Gupta     "xyz.openbmc_project.User.Ldap.Create";
726973a582SRatan Gupta constexpr const char* ldapEnableInterface = "xyz.openbmc_project.Object.Enable";
7306785244SRatan Gupta constexpr const char* ldapPrivMapperInterface =
7406785244SRatan Gupta     "xyz.openbmc_project.User.PrivilegeMapper";
756973a582SRatan Gupta 
7654fc587aSNagaraju Goruganti struct LDAPRoleMapData
7754fc587aSNagaraju Goruganti {
7854fc587aSNagaraju Goruganti     std::string groupName;
7954fc587aSNagaraju Goruganti     std::string privilege;
8054fc587aSNagaraju Goruganti };
8154fc587aSNagaraju Goruganti 
826973a582SRatan Gupta struct LDAPConfigData
836973a582SRatan Gupta {
8447f2934cSEd Tanous     std::string uri;
8547f2934cSEd Tanous     std::string bindDN;
8647f2934cSEd Tanous     std::string baseDN;
8747f2934cSEd Tanous     std::string searchScope;
8847f2934cSEd Tanous     std::string serverType;
896973a582SRatan Gupta     bool serviceEnabled = false;
9047f2934cSEd Tanous     std::string userNameAttribute;
9147f2934cSEd Tanous     std::string groupAttribute;
9254fc587aSNagaraju Goruganti     std::vector<std::pair<std::string, LDAPRoleMapData>> groupRoleList;
936973a582SRatan Gupta };
946973a582SRatan Gupta 
9554fc587aSNagaraju Goruganti inline std::string getRoleIdFromPrivilege(std::string_view role)
9684e12cb7SAppaRao Puli {
9784e12cb7SAppaRao Puli     if (role == "priv-admin")
9884e12cb7SAppaRao Puli     {
9984e12cb7SAppaRao Puli         return "Administrator";
10084e12cb7SAppaRao Puli     }
1013174e4dfSEd Tanous     if (role == "priv-user")
10284e12cb7SAppaRao Puli     {
103c80fee55SAppaRao Puli         return "ReadOnly";
10484e12cb7SAppaRao Puli     }
1053174e4dfSEd Tanous     if (role == "priv-operator")
10684e12cb7SAppaRao Puli     {
10784e12cb7SAppaRao Puli         return "Operator";
10884e12cb7SAppaRao Puli     }
10984e12cb7SAppaRao Puli     return "";
11084e12cb7SAppaRao Puli }
11154fc587aSNagaraju Goruganti inline std::string getPrivilegeFromRoleId(std::string_view role)
11284e12cb7SAppaRao Puli {
11384e12cb7SAppaRao Puli     if (role == "Administrator")
11484e12cb7SAppaRao Puli     {
11584e12cb7SAppaRao Puli         return "priv-admin";
11684e12cb7SAppaRao Puli     }
1173174e4dfSEd Tanous     if (role == "ReadOnly")
11884e12cb7SAppaRao Puli     {
11984e12cb7SAppaRao Puli         return "priv-user";
12084e12cb7SAppaRao Puli     }
1213174e4dfSEd Tanous     if (role == "Operator")
12284e12cb7SAppaRao Puli     {
12384e12cb7SAppaRao Puli         return "priv-operator";
12484e12cb7SAppaRao Puli     }
12584e12cb7SAppaRao Puli     return "";
12684e12cb7SAppaRao Puli }
127b9b2e0b2SEd Tanous 
128c7229815SAbhishek Patel /**
129c7229815SAbhishek Patel  * @brief Maps user group names retrieved from D-Bus object to
130c7229815SAbhishek Patel  * Account Types.
131c7229815SAbhishek Patel  *
132c7229815SAbhishek Patel  * @param[in] userGroups List of User groups
133c7229815SAbhishek Patel  * @param[out] res AccountTypes populated
134c7229815SAbhishek Patel  *
135c7229815SAbhishek Patel  * @return true in case of success, false if UserGroups contains
136c7229815SAbhishek Patel  * invalid group name(s).
137c7229815SAbhishek Patel  */
138c7229815SAbhishek Patel inline bool translateUserGroup(const std::vector<std::string>& userGroups,
139c7229815SAbhishek Patel                                crow::Response& res)
140c7229815SAbhishek Patel {
141c7229815SAbhishek Patel     std::vector<std::string> accountTypes;
142c7229815SAbhishek Patel     for (const auto& userGroup : userGroups)
143c7229815SAbhishek Patel     {
144c7229815SAbhishek Patel         if (userGroup == "redfish")
145c7229815SAbhishek Patel         {
146c7229815SAbhishek Patel             accountTypes.emplace_back("Redfish");
147c7229815SAbhishek Patel             accountTypes.emplace_back("WebUI");
148c7229815SAbhishek Patel         }
149c7229815SAbhishek Patel         else if (userGroup == "ipmi")
150c7229815SAbhishek Patel         {
151c7229815SAbhishek Patel             accountTypes.emplace_back("IPMI");
152c7229815SAbhishek Patel         }
153c7229815SAbhishek Patel         else if (userGroup == "ssh")
154c7229815SAbhishek Patel         {
155c7229815SAbhishek Patel             accountTypes.emplace_back("ManagerConsole");
156c7229815SAbhishek Patel         }
1573e72c202SNinad Palsule         else if (userGroup == "hostconsole")
1583e72c202SNinad Palsule         {
1593e72c202SNinad Palsule             // The hostconsole group controls who can access the host console
1603e72c202SNinad Palsule             // port via ssh and websocket.
1613e72c202SNinad Palsule             accountTypes.emplace_back("HostConsole");
1623e72c202SNinad Palsule         }
163c7229815SAbhishek Patel         else if (userGroup == "web")
164c7229815SAbhishek Patel         {
165c7229815SAbhishek Patel             // 'web' is one of the valid groups in the UserGroups property of
166c7229815SAbhishek Patel             // the user account in the D-Bus object. This group is currently not
167c7229815SAbhishek Patel             // doing anything, and is considered to be equivalent to 'redfish'.
168c7229815SAbhishek Patel             // 'redfish' user group is mapped to 'Redfish'and 'WebUI'
169c7229815SAbhishek Patel             // AccountTypes, so do nothing here...
170c7229815SAbhishek Patel         }
171c7229815SAbhishek Patel         else
172c7229815SAbhishek Patel         {
1738ece0e45SEd Tanous             // Invalid user group name. Caller throws an exception.
174c7229815SAbhishek Patel             return false;
175c7229815SAbhishek Patel         }
176c7229815SAbhishek Patel     }
177c7229815SAbhishek Patel 
178c7229815SAbhishek Patel     res.jsonValue["AccountTypes"] = std::move(accountTypes);
179c7229815SAbhishek Patel     return true;
180c7229815SAbhishek Patel }
181c7229815SAbhishek Patel 
18258345856SAbhishek Patel /**
18358345856SAbhishek Patel  * @brief Builds User Groups from the Account Types
18458345856SAbhishek Patel  *
18558345856SAbhishek Patel  * @param[in] asyncResp Async Response
18658345856SAbhishek Patel  * @param[in] accountTypes List of Account Types
18758345856SAbhishek Patel  * @param[out] userGroups List of User Groups mapped from Account Types
18858345856SAbhishek Patel  *
18958345856SAbhishek Patel  * @return true if Account Types mapped to User Groups, false otherwise.
19058345856SAbhishek Patel  */
191bd79bce8SPatrick Williams inline bool getUserGroupFromAccountType(
192bd79bce8SPatrick Williams     crow::Response& res, const std::vector<std::string>& accountTypes,
19358345856SAbhishek Patel     std::vector<std::string>& userGroups)
19458345856SAbhishek Patel {
19558345856SAbhishek Patel     // Need both Redfish and WebUI Account Types to map to 'redfish' User Group
19658345856SAbhishek Patel     bool redfishType = false;
19758345856SAbhishek Patel     bool webUIType = false;
19858345856SAbhishek Patel 
19958345856SAbhishek Patel     for (const auto& accountType : accountTypes)
20058345856SAbhishek Patel     {
20158345856SAbhishek Patel         if (accountType == "Redfish")
20258345856SAbhishek Patel         {
20358345856SAbhishek Patel             redfishType = true;
20458345856SAbhishek Patel         }
20558345856SAbhishek Patel         else if (accountType == "WebUI")
20658345856SAbhishek Patel         {
20758345856SAbhishek Patel             webUIType = true;
20858345856SAbhishek Patel         }
20958345856SAbhishek Patel         else if (accountType == "IPMI")
21058345856SAbhishek Patel         {
21158345856SAbhishek Patel             userGroups.emplace_back("ipmi");
21258345856SAbhishek Patel         }
21358345856SAbhishek Patel         else if (accountType == "HostConsole")
21458345856SAbhishek Patel         {
21558345856SAbhishek Patel             userGroups.emplace_back("hostconsole");
21658345856SAbhishek Patel         }
21758345856SAbhishek Patel         else if (accountType == "ManagerConsole")
21858345856SAbhishek Patel         {
21958345856SAbhishek Patel             userGroups.emplace_back("ssh");
22058345856SAbhishek Patel         }
22158345856SAbhishek Patel         else
22258345856SAbhishek Patel         {
22358345856SAbhishek Patel             // Invalid Account Type
22458345856SAbhishek Patel             messages::propertyValueNotInList(res, "AccountTypes", accountType);
22558345856SAbhishek Patel             return false;
22658345856SAbhishek Patel         }
22758345856SAbhishek Patel     }
22858345856SAbhishek Patel 
22958345856SAbhishek Patel     // Both  Redfish and WebUI Account Types are needed to PATCH
23058345856SAbhishek Patel     if (redfishType ^ webUIType)
23158345856SAbhishek Patel     {
23262598e31SEd Tanous         BMCWEB_LOG_ERROR(
23362598e31SEd Tanous             "Missing Redfish or WebUI Account Type to set redfish User Group");
23458345856SAbhishek Patel         messages::strictAccountTypes(res, "AccountTypes");
23558345856SAbhishek Patel         return false;
23658345856SAbhishek Patel     }
23758345856SAbhishek Patel 
23858345856SAbhishek Patel     if (redfishType && webUIType)
23958345856SAbhishek Patel     {
24058345856SAbhishek Patel         userGroups.emplace_back("redfish");
24158345856SAbhishek Patel     }
24258345856SAbhishek Patel 
24358345856SAbhishek Patel     return true;
24458345856SAbhishek Patel }
24558345856SAbhishek Patel 
24658345856SAbhishek Patel /**
24758345856SAbhishek Patel  * @brief Sets UserGroups property of the user based on the Account Types
24858345856SAbhishek Patel  *
24958345856SAbhishek Patel  * @param[in] accountTypes List of User Account Types
25058345856SAbhishek Patel  * @param[in] asyncResp Async Response
25158345856SAbhishek Patel  * @param[in] dbusObjectPath D-Bus Object Path
25258345856SAbhishek Patel  * @param[in] userSelf true if User is updating OWN Account Types
25358345856SAbhishek Patel  */
25458345856SAbhishek Patel inline void
25558345856SAbhishek Patel     patchAccountTypes(const std::vector<std::string>& accountTypes,
25658345856SAbhishek Patel                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
25758345856SAbhishek Patel                       const std::string& dbusObjectPath, bool userSelf)
25858345856SAbhishek Patel {
25958345856SAbhishek Patel     // Check if User is disabling own Redfish Account Type
26058345856SAbhishek Patel     if (userSelf &&
26158345856SAbhishek Patel         (accountTypes.cend() ==
26258345856SAbhishek Patel          std::find(accountTypes.cbegin(), accountTypes.cend(), "Redfish")))
26358345856SAbhishek Patel     {
26462598e31SEd Tanous         BMCWEB_LOG_ERROR(
26562598e31SEd Tanous             "User disabling OWN Redfish Account Type is not allowed");
26658345856SAbhishek Patel         messages::strictAccountTypes(asyncResp->res, "AccountTypes");
26758345856SAbhishek Patel         return;
26858345856SAbhishek Patel     }
26958345856SAbhishek Patel 
27058345856SAbhishek Patel     std::vector<std::string> updatedUserGroups;
27158345856SAbhishek Patel     if (!getUserGroupFromAccountType(asyncResp->res, accountTypes,
27258345856SAbhishek Patel                                      updatedUserGroups))
27358345856SAbhishek Patel     {
27458345856SAbhishek Patel         // Problem in mapping Account Types to User Groups, Error already
27558345856SAbhishek Patel         // logged.
27658345856SAbhishek Patel         return;
27758345856SAbhishek Patel     }
278e93abac6SGinu George     setDbusProperty(asyncResp, "AccountTypes",
279e93abac6SGinu George                     "xyz.openbmc_project.User.Manager", dbusObjectPath,
280e93abac6SGinu George                     "xyz.openbmc_project.User.Attributes", "UserGroups",
281e93abac6SGinu George                     updatedUserGroups);
28258345856SAbhishek Patel }
28358345856SAbhishek Patel 
2848d1b46d7Szhanghch05 inline void userErrorMessageHandler(
2858d1b46d7Szhanghch05     const sd_bus_error* e, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2868d1b46d7Szhanghch05     const std::string& newUser, const std::string& username)
28766b5ca76Sjayaprakash Mutyala {
28866b5ca76Sjayaprakash Mutyala     if (e == nullptr)
28966b5ca76Sjayaprakash Mutyala     {
29066b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
29166b5ca76Sjayaprakash Mutyala         return;
29266b5ca76Sjayaprakash Mutyala     }
29366b5ca76Sjayaprakash Mutyala 
294055806b3SManojkiran Eda     const char* errorMessage = e->name;
29566b5ca76Sjayaprakash Mutyala     if (strcmp(errorMessage,
29666b5ca76Sjayaprakash Mutyala                "xyz.openbmc_project.User.Common.Error.UserNameExists") == 0)
29766b5ca76Sjayaprakash Mutyala     {
298d8a5d5d8SJiaqing Zhao         messages::resourceAlreadyExists(asyncResp->res, "ManagerAccount",
29966b5ca76Sjayaprakash Mutyala                                         "UserName", newUser);
30066b5ca76Sjayaprakash Mutyala     }
30166b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage, "xyz.openbmc_project.User.Common.Error."
30266b5ca76Sjayaprakash Mutyala                                   "UserNameDoesNotExist") == 0)
30366b5ca76Sjayaprakash Mutyala     {
304d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
30566b5ca76Sjayaprakash Mutyala     }
306d4d25793SEd Tanous     else if ((strcmp(errorMessage,
307d4d25793SEd Tanous                      "xyz.openbmc_project.Common.Error.InvalidArgument") ==
308d4d25793SEd Tanous               0) ||
3090fda0f12SGeorge Liu              (strcmp(
3100fda0f12SGeorge Liu                   errorMessage,
3110fda0f12SGeorge Liu                   "xyz.openbmc_project.User.Common.Error.UserNameGroupFail") ==
3120fda0f12SGeorge Liu               0))
31366b5ca76Sjayaprakash Mutyala     {
31466b5ca76Sjayaprakash Mutyala         messages::propertyValueFormatError(asyncResp->res, newUser, "UserName");
31566b5ca76Sjayaprakash Mutyala     }
31666b5ca76Sjayaprakash Mutyala     else if (strcmp(errorMessage,
31766b5ca76Sjayaprakash Mutyala                     "xyz.openbmc_project.User.Common.Error.NoResource") == 0)
31866b5ca76Sjayaprakash Mutyala     {
31966b5ca76Sjayaprakash Mutyala         messages::createLimitReachedForResource(asyncResp->res);
32066b5ca76Sjayaprakash Mutyala     }
32166b5ca76Sjayaprakash Mutyala     else
32266b5ca76Sjayaprakash Mutyala     {
323b8ad583fSGunnar Mills         BMCWEB_LOG_ERROR("DBUS response error {}", errorMessage);
32466b5ca76Sjayaprakash Mutyala         messages::internalError(asyncResp->res);
32566b5ca76Sjayaprakash Mutyala     }
32666b5ca76Sjayaprakash Mutyala }
32766b5ca76Sjayaprakash Mutyala 
32881ce609eSEd Tanous inline void parseLDAPConfigData(nlohmann::json& jsonResponse,
329ab828d7cSRatan Gupta                                 const LDAPConfigData& confData,
330ab828d7cSRatan Gupta                                 const std::string& ldapType)
3316973a582SRatan Gupta {
33249cc263fSEd Tanous     nlohmann::json::object_t ldap;
3331476687dSEd Tanous     ldap["ServiceEnabled"] = confData.serviceEnabled;
33449cc263fSEd Tanous     nlohmann::json::array_t serviceAddresses;
33549cc263fSEd Tanous     serviceAddresses.emplace_back(confData.uri);
33649cc263fSEd Tanous     ldap["ServiceAddresses"] = std::move(serviceAddresses);
33749cc263fSEd Tanous 
33849cc263fSEd Tanous     nlohmann::json::object_t authentication;
33949cc263fSEd Tanous     authentication["AuthenticationType"] =
3400ec8b83dSEd Tanous         account_service::AuthenticationTypes::UsernameAndPassword;
34149cc263fSEd Tanous     authentication["Username"] = confData.bindDN;
34249cc263fSEd Tanous     authentication["Password"] = nullptr;
34349cc263fSEd Tanous     ldap["Authentication"] = std::move(authentication);
3441476687dSEd Tanous 
34549cc263fSEd Tanous     nlohmann::json::object_t ldapService;
34649cc263fSEd Tanous     nlohmann::json::object_t searchSettings;
34749cc263fSEd Tanous     nlohmann::json::array_t baseDistinguishedNames;
34849cc263fSEd Tanous     baseDistinguishedNames.emplace_back(confData.baseDN);
3491476687dSEd Tanous 
35049cc263fSEd Tanous     searchSettings["BaseDistinguishedNames"] =
35149cc263fSEd Tanous         std::move(baseDistinguishedNames);
35249cc263fSEd Tanous     searchSettings["UsernameAttribute"] = confData.userNameAttribute;
35349cc263fSEd Tanous     searchSettings["GroupsAttribute"] = confData.groupAttribute;
35449cc263fSEd Tanous     ldapService["SearchSettings"] = std::move(searchSettings);
35549cc263fSEd Tanous     ldap["LDAPService"] = std::move(ldapService);
35649cc263fSEd Tanous 
35749cc263fSEd Tanous     nlohmann::json::array_t roleMapArray;
3589eb808c1SEd Tanous     for (const auto& obj : confData.groupRoleList)
35954fc587aSNagaraju Goruganti     {
36062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Pushing the data groupName={}", obj.second.groupName);
361613dabeaSEd Tanous 
362613dabeaSEd Tanous         nlohmann::json::object_t remoteGroup;
363613dabeaSEd Tanous         remoteGroup["RemoteGroup"] = obj.second.groupName;
364329f0348SJorge Cisneros         remoteGroup["LocalRole"] = getRoleIdFromPrivilege(obj.second.privilege);
365329f0348SJorge Cisneros         roleMapArray.emplace_back(std::move(remoteGroup));
36654fc587aSNagaraju Goruganti     }
36749cc263fSEd Tanous 
36849cc263fSEd Tanous     ldap["RemoteRoleMapping"] = std::move(roleMapArray);
36949cc263fSEd Tanous 
37049cc263fSEd Tanous     jsonResponse[ldapType].update(ldap);
3716973a582SRatan Gupta }
3726973a582SRatan Gupta 
3736973a582SRatan Gupta /**
37406785244SRatan Gupta  *  @brief validates given JSON input and then calls appropriate method to
37506785244SRatan Gupta  * create, to delete or to set Rolemapping object based on the given input.
37606785244SRatan Gupta  *
37706785244SRatan Gupta  */
37823a21a1cSEd Tanous inline void handleRoleMapPatch(
3798d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
38006785244SRatan Gupta     const std::vector<std::pair<std::string, LDAPRoleMapData>>& roleMapObjData,
381c1019828SEd Tanous     const std::string& serverType,
382c1019828SEd Tanous     std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>& input)
38306785244SRatan Gupta {
38406785244SRatan Gupta     for (size_t index = 0; index < input.size(); index++)
38506785244SRatan Gupta     {
386c1019828SEd Tanous         std::variant<nlohmann::json::object_t, std::nullptr_t>& thisJson =
387c1019828SEd Tanous             input[index];
388c1019828SEd Tanous         nlohmann::json::object_t* obj =
389c1019828SEd Tanous             std::get_if<nlohmann::json::object_t>(&thisJson);
390c1019828SEd Tanous         if (obj == nullptr)
39106785244SRatan Gupta         {
39206785244SRatan Gupta             // delete the existing object
39306785244SRatan Gupta             if (index < roleMapObjData.size())
39406785244SRatan Gupta             {
39506785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
39606785244SRatan Gupta                     [asyncResp, roleMapObjData, serverType,
3975e7e2dc5SEd Tanous                      index](const boost::system::error_code& ec) {
39806785244SRatan Gupta                         if (ec)
39906785244SRatan Gupta                         {
40062598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
40106785244SRatan Gupta                             messages::internalError(asyncResp->res);
40206785244SRatan Gupta                             return;
40306785244SRatan Gupta                         }
404bd79bce8SPatrick Williams                         asyncResp->res
405bd79bce8SPatrick Williams                             .jsonValue[serverType]["RemoteRoleMapping"][index] =
406bd79bce8SPatrick Williams                             nullptr;
40706785244SRatan Gupta                     },
40806785244SRatan Gupta                     ldapDbusService, roleMapObjData[index].first,
40906785244SRatan Gupta                     "xyz.openbmc_project.Object.Delete", "Delete");
41006785244SRatan Gupta             }
41106785244SRatan Gupta             else
41206785244SRatan Gupta             {
41362598e31SEd Tanous                 BMCWEB_LOG_ERROR("Can't delete the object");
414bd79bce8SPatrick Williams                 messages::propertyValueTypeError(
415bd79bce8SPatrick Williams                     asyncResp->res, "null",
416bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index));
41706785244SRatan Gupta                 return;
41806785244SRatan Gupta             }
41906785244SRatan Gupta         }
420c1019828SEd Tanous         else if (obj->empty())
42106785244SRatan Gupta         {
42206785244SRatan Gupta             // Don't do anything for the empty objects,parse next json
42306785244SRatan Gupta             // eg {"RemoteRoleMapping",[{}]}
42406785244SRatan Gupta         }
42506785244SRatan Gupta         else
42606785244SRatan Gupta         {
42706785244SRatan Gupta             // update/create the object
42806785244SRatan Gupta             std::optional<std::string> remoteGroup;
42906785244SRatan Gupta             std::optional<std::string> localRole;
43006785244SRatan Gupta 
431afc474aeSMyung Bae             if (!json_util::readJsonObject( //
432afc474aeSMyung Bae                     *obj, asyncResp->res, //
433afc474aeSMyung Bae                     "LocalRole", localRole, //
434afc474aeSMyung Bae                     "RemoteGroup", remoteGroup //
435afc474aeSMyung Bae                     ))
43606785244SRatan Gupta             {
43706785244SRatan Gupta                 continue;
43806785244SRatan Gupta             }
43906785244SRatan Gupta 
44006785244SRatan Gupta             // Update existing RoleMapping Object
44106785244SRatan Gupta             if (index < roleMapObjData.size())
44206785244SRatan Gupta             {
44362598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Update Role Map Object");
44406785244SRatan Gupta                 // If "RemoteGroup" info is provided
44506785244SRatan Gupta                 if (remoteGroup)
44606785244SRatan Gupta                 {
447d02aad39SEd Tanous                     setDbusProperty(
448e93abac6SGinu George                         asyncResp,
449d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/RemoteGroup", index),
450e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
451e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
452e93abac6SGinu George                         "GroupName", *remoteGroup);
45306785244SRatan Gupta                 }
45406785244SRatan Gupta 
45506785244SRatan Gupta                 // If "LocalRole" info is provided
45606785244SRatan Gupta                 if (localRole)
45706785244SRatan Gupta                 {
4586d0b80beSRavi Teja                     std::string priv = getPrivilegeFromRoleId(*localRole);
4596d0b80beSRavi Teja                     if (priv.empty())
4606d0b80beSRavi Teja                     {
4616d0b80beSRavi Teja                         messages::propertyValueNotInList(
4626d0b80beSRavi Teja                             asyncResp->res, *localRole,
4636d0b80beSRavi Teja                             std::format("RemoteRoleMapping/{}/LocalRole",
4646d0b80beSRavi Teja                                         index));
4656d0b80beSRavi Teja                         return;
4666d0b80beSRavi Teja                     }
467d02aad39SEd Tanous                     setDbusProperty(
468e93abac6SGinu George                         asyncResp,
469d02aad39SEd Tanous                         std::format("RemoteRoleMapping/{}/LocalRole", index),
470e93abac6SGinu George                         ldapDbusService, roleMapObjData[index].first,
471e93abac6SGinu George                         "xyz.openbmc_project.User.PrivilegeMapperEntry",
4726d0b80beSRavi Teja                         "Privilege", priv);
47306785244SRatan Gupta                 }
47406785244SRatan Gupta             }
47506785244SRatan Gupta             // Create a new RoleMapping Object.
47606785244SRatan Gupta             else
47706785244SRatan Gupta             {
47862598e31SEd Tanous                 BMCWEB_LOG_DEBUG(
47962598e31SEd Tanous                     "setRoleMappingProperties: Creating new Object");
480bd79bce8SPatrick Williams                 std::string pathString =
481bd79bce8SPatrick Williams                     "RemoteRoleMapping/" + std::to_string(index);
48206785244SRatan Gupta 
48306785244SRatan Gupta                 if (!localRole)
48406785244SRatan Gupta                 {
48506785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
48606785244SRatan Gupta                                               pathString + "/LocalRole");
48706785244SRatan Gupta                     continue;
48806785244SRatan Gupta                 }
48906785244SRatan Gupta                 if (!remoteGroup)
49006785244SRatan Gupta                 {
49106785244SRatan Gupta                     messages::propertyMissing(asyncResp->res,
49206785244SRatan Gupta                                               pathString + "/RemoteGroup");
49306785244SRatan Gupta                     continue;
49406785244SRatan Gupta                 }
49506785244SRatan Gupta 
49606785244SRatan Gupta                 std::string dbusObjectPath;
49706785244SRatan Gupta                 if (serverType == "ActiveDirectory")
49806785244SRatan Gupta                 {
4992c70f800SEd Tanous                     dbusObjectPath = adConfigObject;
50006785244SRatan Gupta                 }
50106785244SRatan Gupta                 else if (serverType == "LDAP")
50206785244SRatan Gupta                 {
50323a21a1cSEd Tanous                     dbusObjectPath = ldapConfigObjectName;
50406785244SRatan Gupta                 }
50506785244SRatan Gupta 
50662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Remote Group={},LocalRole={}", *remoteGroup,
50762598e31SEd Tanous                                  *localRole);
50806785244SRatan Gupta 
50906785244SRatan Gupta                 crow::connections::systemBus->async_method_call(
510271584abSEd Tanous                     [asyncResp, serverType, localRole,
5115e7e2dc5SEd Tanous                      remoteGroup](const boost::system::error_code& ec) {
51206785244SRatan Gupta                         if (ec)
51306785244SRatan Gupta                         {
51462598e31SEd Tanous                             BMCWEB_LOG_ERROR("DBUS response error: {}", ec);
51506785244SRatan Gupta                             messages::internalError(asyncResp->res);
51606785244SRatan Gupta                             return;
51706785244SRatan Gupta                         }
51806785244SRatan Gupta                         nlohmann::json& remoteRoleJson =
51906785244SRatan Gupta                             asyncResp->res
52006785244SRatan Gupta                                 .jsonValue[serverType]["RemoteRoleMapping"];
5211476687dSEd Tanous                         nlohmann::json::object_t roleMapEntry;
5221476687dSEd Tanous                         roleMapEntry["LocalRole"] = *localRole;
5231476687dSEd Tanous                         roleMapEntry["RemoteGroup"] = *remoteGroup;
524b2ba3072SPatrick Williams                         remoteRoleJson.emplace_back(std::move(roleMapEntry));
52506785244SRatan Gupta                     },
52606785244SRatan Gupta                     ldapDbusService, dbusObjectPath, ldapPrivMapperInterface,
5273174e4dfSEd Tanous                     "Create", *remoteGroup,
52806785244SRatan Gupta                     getPrivilegeFromRoleId(std::move(*localRole)));
52906785244SRatan Gupta             }
53006785244SRatan Gupta         }
53106785244SRatan Gupta     }
53206785244SRatan Gupta }
53306785244SRatan Gupta 
53406785244SRatan Gupta /**
5356973a582SRatan Gupta  * Function that retrieves all properties for LDAP config object
5366973a582SRatan Gupta  * into JSON
5376973a582SRatan Gupta  */
5386973a582SRatan Gupta template <typename CallbackFunc>
539bd79bce8SPatrick Williams inline void
540bd79bce8SPatrick Williams     getLDAPConfigData(const std::string& ldapType, CallbackFunc&& callback)
5416973a582SRatan Gupta {
5422b73119cSGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
5432b73119cSGeorge Liu         ldapEnableInterface, ldapConfigInterface};
54454fc587aSNagaraju Goruganti 
5452b73119cSGeorge Liu     dbus::utility::getDbusObject(
5462b73119cSGeorge Liu         ldapConfigObjectName, interfaces,
5478cb2c024SEd Tanous         [callback = std::forward<CallbackFunc>(callback),
548c1019828SEd Tanous          ldapType](const boost::system::error_code& ec,
549c1019828SEd Tanous                    const dbus::utility::MapperGetObject& resp) mutable {
55054fc587aSNagaraju Goruganti             if (ec || resp.empty())
55154fc587aSNagaraju Goruganti             {
552bf2ddedeSCarson Labrado                 BMCWEB_LOG_WARNING(
553bd79bce8SPatrick Williams                     "DBUS response error during getting of service name: {}",
554bd79bce8SPatrick Williams                     ec);
55523a21a1cSEd Tanous                 LDAPConfigData empty{};
55623a21a1cSEd Tanous                 callback(false, empty, ldapType);
55754fc587aSNagaraju Goruganti                 return;
55854fc587aSNagaraju Goruganti             }
55954fc587aSNagaraju Goruganti             std::string service = resp.begin()->first;
5605eb468daSGeorge Liu             sdbusplus::message::object_path path(ldapRootObject);
5615eb468daSGeorge Liu             dbus::utility::getManagedObjects(
5625eb468daSGeorge Liu                 service, path,
563bd79bce8SPatrick Williams                 [callback, ldapType](const boost::system::error_code& ec2,
564bd79bce8SPatrick Williams                                      const dbus::utility::ManagedObjectType&
565bd79bce8SPatrick Williams                                          ldapObjects) mutable {
5666973a582SRatan Gupta                     LDAPConfigData confData{};
5678b24275dSEd Tanous                     if (ec2)
5686973a582SRatan Gupta                     {
569ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
570bf2ddedeSCarson Labrado                         BMCWEB_LOG_WARNING("D-Bus responses error: {}", ec2);
5716973a582SRatan Gupta                         return;
5726973a582SRatan Gupta                     }
573ab828d7cSRatan Gupta 
574ab828d7cSRatan Gupta                     std::string ldapDbusType;
57554fc587aSNagaraju Goruganti                     std::string searchString;
57654fc587aSNagaraju Goruganti 
577ab828d7cSRatan Gupta                     if (ldapType == "LDAP")
578ab828d7cSRatan Gupta                     {
5790fda0f12SGeorge Liu                         ldapDbusType =
5800fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.OpenLdap";
58154fc587aSNagaraju Goruganti                         searchString = "openldap";
582ab828d7cSRatan Gupta                     }
583ab828d7cSRatan Gupta                     else if (ldapType == "ActiveDirectory")
584ab828d7cSRatan Gupta                     {
58554fc587aSNagaraju Goruganti                         ldapDbusType =
5860fda0f12SGeorge Liu                             "xyz.openbmc_project.User.Ldap.Config.Type.ActiveDirectory";
58754fc587aSNagaraju Goruganti                         searchString = "active_directory";
588ab828d7cSRatan Gupta                     }
589ab828d7cSRatan Gupta                     else
590ab828d7cSRatan Gupta                     {
591bd79bce8SPatrick Williams                         BMCWEB_LOG_ERROR(
592bd79bce8SPatrick Williams                             "Can't get the DbusType for the given type={}",
59362598e31SEd Tanous                             ldapType);
594ab828d7cSRatan Gupta                         callback(false, confData, ldapType);
595ab828d7cSRatan Gupta                         return;
596ab828d7cSRatan Gupta                     }
597ab828d7cSRatan Gupta 
598ab828d7cSRatan Gupta                     std::string ldapEnableInterfaceStr = ldapEnableInterface;
599ab828d7cSRatan Gupta                     std::string ldapConfigInterfaceStr = ldapConfigInterface;
600ab828d7cSRatan Gupta 
6016973a582SRatan Gupta                     for (const auto& object : ldapObjects)
6026973a582SRatan Gupta                     {
60354fc587aSNagaraju Goruganti                         // let's find the object whose ldap type is equal to the
60454fc587aSNagaraju Goruganti                         // given type
605bd79bce8SPatrick Williams                         if (object.first.str.find(searchString) ==
606bd79bce8SPatrick Williams                             std::string::npos)
6076973a582SRatan Gupta                         {
608ab828d7cSRatan Gupta                             continue;
609ab828d7cSRatan Gupta                         }
610ab828d7cSRatan Gupta 
6116973a582SRatan Gupta                         for (const auto& interface : object.second)
6126973a582SRatan Gupta                         {
6136973a582SRatan Gupta                             if (interface.first == ldapEnableInterfaceStr)
6146973a582SRatan Gupta                             {
6156973a582SRatan Gupta                                 // rest of the properties are string.
6166973a582SRatan Gupta                                 for (const auto& property : interface.second)
6176973a582SRatan Gupta                                 {
6186973a582SRatan Gupta                                     if (property.first == "Enabled")
6196973a582SRatan Gupta                                     {
6206973a582SRatan Gupta                                         const bool* value =
6216973a582SRatan Gupta                                             std::get_if<bool>(&property.second);
6226973a582SRatan Gupta                                         if (value == nullptr)
6236973a582SRatan Gupta                                         {
6246973a582SRatan Gupta                                             continue;
6256973a582SRatan Gupta                                         }
6266973a582SRatan Gupta                                         confData.serviceEnabled = *value;
6276973a582SRatan Gupta                                         break;
6286973a582SRatan Gupta                                     }
6296973a582SRatan Gupta                                 }
6306973a582SRatan Gupta                             }
6316973a582SRatan Gupta                             else if (interface.first == ldapConfigInterfaceStr)
6326973a582SRatan Gupta                             {
6336973a582SRatan Gupta                                 for (const auto& property : interface.second)
6346973a582SRatan Gupta                                 {
635271584abSEd Tanous                                     const std::string* strValue =
636bd79bce8SPatrick Williams                                         std::get_if<std::string>(
637bd79bce8SPatrick Williams                                             &property.second);
638271584abSEd Tanous                                     if (strValue == nullptr)
6396973a582SRatan Gupta                                     {
6406973a582SRatan Gupta                                         continue;
6416973a582SRatan Gupta                                     }
6426973a582SRatan Gupta                                     if (property.first == "LDAPServerURI")
6436973a582SRatan Gupta                                     {
644271584abSEd Tanous                                         confData.uri = *strValue;
6456973a582SRatan Gupta                                     }
6466973a582SRatan Gupta                                     else if (property.first == "LDAPBindDN")
6476973a582SRatan Gupta                                     {
648271584abSEd Tanous                                         confData.bindDN = *strValue;
6496973a582SRatan Gupta                                     }
6506973a582SRatan Gupta                                     else if (property.first == "LDAPBaseDN")
6516973a582SRatan Gupta                                     {
652271584abSEd Tanous                                         confData.baseDN = *strValue;
6536973a582SRatan Gupta                                     }
654bd79bce8SPatrick Williams                                     else if (property.first ==
655bd79bce8SPatrick Williams                                              "LDAPSearchScope")
6566973a582SRatan Gupta                                     {
657271584abSEd Tanous                                         confData.searchScope = *strValue;
6586973a582SRatan Gupta                                     }
659bd79bce8SPatrick Williams                                     else if (property.first ==
660bd79bce8SPatrick Williams                                              "GroupNameAttribute")
6616973a582SRatan Gupta                                     {
662271584abSEd Tanous                                         confData.groupAttribute = *strValue;
6636973a582SRatan Gupta                                     }
664bd79bce8SPatrick Williams                                     else if (property.first ==
665bd79bce8SPatrick Williams                                              "UserNameAttribute")
6666973a582SRatan Gupta                                     {
667271584abSEd Tanous                                         confData.userNameAttribute = *strValue;
6686973a582SRatan Gupta                                     }
66954fc587aSNagaraju Goruganti                                     else if (property.first == "LDAPType")
670ab828d7cSRatan Gupta                                     {
671271584abSEd Tanous                                         confData.serverType = *strValue;
67254fc587aSNagaraju Goruganti                                     }
67354fc587aSNagaraju Goruganti                                 }
67454fc587aSNagaraju Goruganti                             }
675bd79bce8SPatrick Williams                             else if (
676bd79bce8SPatrick Williams                                 interface.first ==
6770fda0f12SGeorge Liu                                 "xyz.openbmc_project.User.PrivilegeMapperEntry")
67854fc587aSNagaraju Goruganti                             {
67954fc587aSNagaraju Goruganti                                 LDAPRoleMapData roleMapData{};
68054fc587aSNagaraju Goruganti                                 for (const auto& property : interface.second)
68154fc587aSNagaraju Goruganti                                 {
682271584abSEd Tanous                                     const std::string* strValue =
683bd79bce8SPatrick Williams                                         std::get_if<std::string>(
684bd79bce8SPatrick Williams                                             &property.second);
68554fc587aSNagaraju Goruganti 
686271584abSEd Tanous                                     if (strValue == nullptr)
68754fc587aSNagaraju Goruganti                                     {
68854fc587aSNagaraju Goruganti                                         continue;
68954fc587aSNagaraju Goruganti                                     }
69054fc587aSNagaraju Goruganti 
69154fc587aSNagaraju Goruganti                                     if (property.first == "GroupName")
69254fc587aSNagaraju Goruganti                                     {
693271584abSEd Tanous                                         roleMapData.groupName = *strValue;
69454fc587aSNagaraju Goruganti                                     }
69554fc587aSNagaraju Goruganti                                     else if (property.first == "Privilege")
69654fc587aSNagaraju Goruganti                                     {
697271584abSEd Tanous                                         roleMapData.privilege = *strValue;
69854fc587aSNagaraju Goruganti                                     }
69954fc587aSNagaraju Goruganti                                 }
70054fc587aSNagaraju Goruganti 
701bd79bce8SPatrick Williams                                 confData.groupRoleList.emplace_back(
702bd79bce8SPatrick Williams                                     object.first.str, roleMapData);
70354fc587aSNagaraju Goruganti                             }
70454fc587aSNagaraju Goruganti                         }
70554fc587aSNagaraju Goruganti                     }
706ab828d7cSRatan Gupta                     callback(true, confData, ldapType);
7075eb468daSGeorge Liu                 });
7082b73119cSGeorge Liu         });
7096973a582SRatan Gupta }
7106973a582SRatan Gupta 
7118a07d286SRatan Gupta /**
7128a07d286SRatan Gupta  * @brief updates the LDAP server address and updates the
7138a07d286SRatan Gupta           json response with the new value.
7148a07d286SRatan Gupta  * @param serviceAddressList address to be updated.
7158a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7168a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7178a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7188a07d286SRatan Gupta  */
7198a07d286SRatan Gupta 
7204f48d5f6SEd Tanous inline void handleServiceAddressPatch(
7218a07d286SRatan Gupta     const std::vector<std::string>& serviceAddressList,
7228d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7238a07d286SRatan Gupta     const std::string& ldapServerElementName,
7248a07d286SRatan Gupta     const std::string& ldapConfigObject)
7258a07d286SRatan Gupta {
726e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceAddress",
727e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
728e93abac6SGinu George                     "LDAPServerURI", serviceAddressList.front());
7298a07d286SRatan Gupta }
7308a07d286SRatan Gupta /**
7318a07d286SRatan Gupta  * @brief updates the LDAP Bind DN and updates the
7328a07d286SRatan Gupta           json response with the new value.
7338a07d286SRatan Gupta  * @param username name of the user which needs to be updated.
7348a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7358a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7368a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7378a07d286SRatan Gupta  */
7388a07d286SRatan Gupta 
7394f48d5f6SEd Tanous inline void
7404f48d5f6SEd Tanous     handleUserNamePatch(const std::string& username,
7418d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7428a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7438a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7448a07d286SRatan Gupta {
745e93abac6SGinu George     setDbusProperty(asyncResp,
746d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Username",
747e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
748e93abac6SGinu George                     "LDAPBindDN", username);
7498a07d286SRatan Gupta }
7508a07d286SRatan Gupta 
7518a07d286SRatan Gupta /**
7528a07d286SRatan Gupta  * @brief updates the LDAP password
7538a07d286SRatan Gupta  * @param password : ldap password which needs to be updated.
7548a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7558a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7568a07d286SRatan Gupta  *        server(openLDAP/ActiveDirectory)
7578a07d286SRatan Gupta  */
7588a07d286SRatan Gupta 
7594f48d5f6SEd Tanous inline void
7604f48d5f6SEd Tanous     handlePasswordPatch(const std::string& password,
7618d1b46d7Szhanghch05                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7628a07d286SRatan Gupta                         const std::string& ldapServerElementName,
7638a07d286SRatan Gupta                         const std::string& ldapConfigObject)
7648a07d286SRatan Gupta {
765e93abac6SGinu George     setDbusProperty(asyncResp,
766d02aad39SEd Tanous                     ldapServerElementName + "/Authentication/Password",
767e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
768e93abac6SGinu George                     "LDAPBindDNPassword", password);
7698a07d286SRatan Gupta }
7708a07d286SRatan Gupta 
7718a07d286SRatan Gupta /**
7728a07d286SRatan Gupta  * @brief updates the LDAP BaseDN and updates the
7738a07d286SRatan Gupta           json response with the new value.
7748a07d286SRatan Gupta  * @param baseDNList baseDN list which needs to be updated.
7758a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7768a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7778a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7788a07d286SRatan Gupta  */
7798a07d286SRatan Gupta 
7804f48d5f6SEd Tanous inline void
7814f48d5f6SEd Tanous     handleBaseDNPatch(const std::vector<std::string>& baseDNList,
7828d1b46d7Szhanghch05                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
7838a07d286SRatan Gupta                       const std::string& ldapServerElementName,
7848a07d286SRatan Gupta                       const std::string& ldapConfigObject)
7858a07d286SRatan Gupta {
786e93abac6SGinu George     setDbusProperty(asyncResp,
787d02aad39SEd Tanous                     ldapServerElementName +
788d02aad39SEd Tanous                         "/LDAPService/SearchSettings/BaseDistinguishedNames",
789e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapConfigInterface,
790e93abac6SGinu George                     "LDAPBaseDN", baseDNList.front());
7918a07d286SRatan Gupta }
7928a07d286SRatan Gupta /**
7938a07d286SRatan Gupta  * @brief updates the LDAP user name attribute and updates the
7948a07d286SRatan Gupta           json response with the new value.
7958a07d286SRatan Gupta  * @param userNameAttribute attribute to be updated.
7968a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
7978a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
7988a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
7998a07d286SRatan Gupta  */
8008a07d286SRatan Gupta 
801bd79bce8SPatrick Williams inline void handleUserNameAttrPatch(
802bd79bce8SPatrick Williams     const std::string& userNameAttribute,
8038d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8048a07d286SRatan Gupta     const std::string& ldapServerElementName,
8058a07d286SRatan Gupta     const std::string& ldapConfigObject)
8068a07d286SRatan Gupta {
807bd79bce8SPatrick Williams     setDbusProperty(
808bd79bce8SPatrick Williams         asyncResp,
809bd79bce8SPatrick Williams         ldapServerElementName + "LDAPService/SearchSettings/UsernameAttribute",
810e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
811e93abac6SGinu George         "UserNameAttribute", userNameAttribute);
8128a07d286SRatan Gupta }
8138a07d286SRatan Gupta /**
8148a07d286SRatan Gupta  * @brief updates the LDAP group attribute and updates the
8158a07d286SRatan Gupta           json response with the new value.
8168a07d286SRatan Gupta  * @param groupsAttribute attribute to be updated.
8178a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8188a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8198a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8208a07d286SRatan Gupta  */
8218a07d286SRatan Gupta 
8224f48d5f6SEd Tanous inline void handleGroupNameAttrPatch(
8238d1b46d7Szhanghch05     const std::string& groupsAttribute,
8248d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8258a07d286SRatan Gupta     const std::string& ldapServerElementName,
8268a07d286SRatan Gupta     const std::string& ldapConfigObject)
8278a07d286SRatan Gupta {
828bd79bce8SPatrick Williams     setDbusProperty(
829bd79bce8SPatrick Williams         asyncResp,
830bd79bce8SPatrick Williams         ldapServerElementName + "/LDAPService/SearchSettings/GroupsAttribute",
831e93abac6SGinu George         ldapDbusService, ldapConfigObject, ldapConfigInterface,
832e93abac6SGinu George         "GroupNameAttribute", groupsAttribute);
8338a07d286SRatan Gupta }
8348a07d286SRatan Gupta /**
8358a07d286SRatan Gupta  * @brief updates the LDAP service enable and updates the
8368a07d286SRatan Gupta           json response with the new value.
8378a07d286SRatan Gupta  * @param input JSON data.
8388a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
8398a07d286SRatan Gupta  * @param ldapServerElementName Type of LDAP
8408a07d286SRatan Gupta  server(openLDAP/ActiveDirectory)
8418a07d286SRatan Gupta  */
8428a07d286SRatan Gupta 
8434f48d5f6SEd Tanous inline void handleServiceEnablePatch(
8446c51eab1SEd Tanous     bool serviceEnabled, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
8458a07d286SRatan Gupta     const std::string& ldapServerElementName,
8468a07d286SRatan Gupta     const std::string& ldapConfigObject)
8478a07d286SRatan Gupta {
848e93abac6SGinu George     setDbusProperty(asyncResp, ldapServerElementName + "/ServiceEnabled",
849e93abac6SGinu George                     ldapDbusService, ldapConfigObject, ldapEnableInterface,
850e93abac6SGinu George                     "Enabled", serviceEnabled);
8518a07d286SRatan Gupta }
8528a07d286SRatan Gupta 
853c1019828SEd Tanous struct AuthMethods
85478158631SZbigniew Kurzynski {
85578158631SZbigniew Kurzynski     std::optional<bool> basicAuth;
85678158631SZbigniew Kurzynski     std::optional<bool> cookie;
85778158631SZbigniew Kurzynski     std::optional<bool> sessionToken;
85878158631SZbigniew Kurzynski     std::optional<bool> xToken;
859501f1e58SZbigniew Kurzynski     std::optional<bool> tls;
860c1019828SEd Tanous };
86178158631SZbigniew Kurzynski 
862c1019828SEd Tanous inline void
863c1019828SEd Tanous     handleAuthMethodsPatch(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
864c1019828SEd Tanous                            const AuthMethods& auth)
86578158631SZbigniew Kurzynski {
866c1019828SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
86752cc112dSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
86878158631SZbigniew Kurzynski 
869c1019828SEd Tanous     if (auth.basicAuth)
87078158631SZbigniew Kurzynski     {
87125b54dbaSEd Tanous         if constexpr (!BMCWEB_BASIC_AUTH)
87225b54dbaSEd Tanous         {
873f16f6263SAlan Kuo             messages::actionNotSupported(
8740fda0f12SGeorge Liu                 asyncResp->res,
8750fda0f12SGeorge Liu                 "Setting BasicAuth when basic-auth feature is disabled");
876f16f6263SAlan Kuo             return;
87725b54dbaSEd Tanous         }
87825b54dbaSEd Tanous 
879c1019828SEd Tanous         authMethodsConfig.basic = *auth.basicAuth;
88078158631SZbigniew Kurzynski     }
88178158631SZbigniew Kurzynski 
882c1019828SEd Tanous     if (auth.cookie)
88378158631SZbigniew Kurzynski     {
88425b54dbaSEd Tanous         if constexpr (!BMCWEB_COOKIE_AUTH)
88525b54dbaSEd Tanous         {
8860fda0f12SGeorge Liu             messages::actionNotSupported(
8870fda0f12SGeorge Liu                 asyncResp->res,
8880fda0f12SGeorge Liu                 "Setting Cookie when cookie-auth feature is disabled");
889f16f6263SAlan Kuo             return;
89025b54dbaSEd Tanous         }
891c1019828SEd Tanous         authMethodsConfig.cookie = *auth.cookie;
89278158631SZbigniew Kurzynski     }
89378158631SZbigniew Kurzynski 
894c1019828SEd Tanous     if (auth.sessionToken)
89578158631SZbigniew Kurzynski     {
89625b54dbaSEd Tanous         if constexpr (!BMCWEB_SESSION_AUTH)
89725b54dbaSEd Tanous         {
898f16f6263SAlan Kuo             messages::actionNotSupported(
8990fda0f12SGeorge Liu                 asyncResp->res,
9000fda0f12SGeorge Liu                 "Setting SessionToken when session-auth feature is disabled");
901f16f6263SAlan Kuo             return;
90225b54dbaSEd Tanous         }
903c1019828SEd Tanous         authMethodsConfig.sessionToken = *auth.sessionToken;
90478158631SZbigniew Kurzynski     }
90578158631SZbigniew Kurzynski 
906c1019828SEd Tanous     if (auth.xToken)
90778158631SZbigniew Kurzynski     {
90825b54dbaSEd Tanous         if constexpr (!BMCWEB_XTOKEN_AUTH)
90925b54dbaSEd Tanous         {
9100fda0f12SGeorge Liu             messages::actionNotSupported(
9110fda0f12SGeorge Liu                 asyncResp->res,
9120fda0f12SGeorge Liu                 "Setting XToken when xtoken-auth feature is disabled");
913f16f6263SAlan Kuo             return;
91425b54dbaSEd Tanous         }
915c1019828SEd Tanous         authMethodsConfig.xtoken = *auth.xToken;
91678158631SZbigniew Kurzynski     }
91778158631SZbigniew Kurzynski 
918c1019828SEd Tanous     if (auth.tls)
919501f1e58SZbigniew Kurzynski     {
92025b54dbaSEd Tanous         if constexpr (!BMCWEB_MUTUAL_TLS_AUTH)
92125b54dbaSEd Tanous         {
9220fda0f12SGeorge Liu             messages::actionNotSupported(
9230fda0f12SGeorge Liu                 asyncResp->res,
9240fda0f12SGeorge Liu                 "Setting TLS when mutual-tls-auth feature is disabled");
925f16f6263SAlan Kuo             return;
92625b54dbaSEd Tanous         }
927c1019828SEd Tanous         authMethodsConfig.tls = *auth.tls;
928501f1e58SZbigniew Kurzynski     }
929501f1e58SZbigniew Kurzynski 
93078158631SZbigniew Kurzynski     if (!authMethodsConfig.basic && !authMethodsConfig.cookie &&
931501f1e58SZbigniew Kurzynski         !authMethodsConfig.sessionToken && !authMethodsConfig.xtoken &&
932501f1e58SZbigniew Kurzynski         !authMethodsConfig.tls)
93378158631SZbigniew Kurzynski     {
93478158631SZbigniew Kurzynski         // Do not allow user to disable everything
93578158631SZbigniew Kurzynski         messages::actionNotSupported(asyncResp->res,
93678158631SZbigniew Kurzynski                                      "of disabling all available methods");
93778158631SZbigniew Kurzynski         return;
93878158631SZbigniew Kurzynski     }
93978158631SZbigniew Kurzynski 
94052cc112dSEd Tanous     persistent_data::SessionStore::getInstance().updateAuthMethodsConfig(
94152cc112dSEd Tanous         authMethodsConfig);
94278158631SZbigniew Kurzynski     // Save configuration immediately
94352cc112dSEd Tanous     persistent_data::getConfig().writeData();
94478158631SZbigniew Kurzynski 
94578158631SZbigniew Kurzynski     messages::success(asyncResp->res);
94678158631SZbigniew Kurzynski }
94778158631SZbigniew Kurzynski 
9488a07d286SRatan Gupta /**
9498a07d286SRatan Gupta  * @brief Get the required values from the given JSON, validates the
9508a07d286SRatan Gupta  *        value and create the LDAP config object.
9518a07d286SRatan Gupta  * @param input JSON data
9528a07d286SRatan Gupta  * @param asyncResp pointer to the JSON response
9538a07d286SRatan Gupta  * @param serverType Type of LDAP server(openLDAP/ActiveDirectory)
9548a07d286SRatan Gupta  */
9558a07d286SRatan Gupta 
95610cb44f3SEd Tanous struct LdapPatchParams
95710cb44f3SEd Tanous {
95810cb44f3SEd Tanous     std::optional<std::string> authType;
95910cb44f3SEd Tanous     std::optional<std::vector<std::string>> serviceAddressList;
96010cb44f3SEd Tanous     std::optional<bool> serviceEnabled;
96110cb44f3SEd Tanous     std::optional<std::vector<std::string>> baseDNList;
96210cb44f3SEd Tanous     std::optional<std::string> userNameAttribute;
96310cb44f3SEd Tanous     std::optional<std::string> groupsAttribute;
96410cb44f3SEd Tanous     std::optional<std::string> userName;
96510cb44f3SEd Tanous     std::optional<std::string> password;
96610cb44f3SEd Tanous     std::optional<
96710cb44f3SEd Tanous         std::vector<std::variant<nlohmann::json::object_t, std::nullptr_t>>>
96810cb44f3SEd Tanous         remoteRoleMapData;
96910cb44f3SEd Tanous };
97010cb44f3SEd Tanous 
97110cb44f3SEd Tanous inline void handleLDAPPatch(LdapPatchParams&& input,
9728d1b46d7Szhanghch05                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
9738a07d286SRatan Gupta                             const std::string& serverType)
9748a07d286SRatan Gupta {
975eb2bbe56SRatan Gupta     std::string dbusObjectPath;
976eb2bbe56SRatan Gupta     if (serverType == "ActiveDirectory")
977eb2bbe56SRatan Gupta     {
9782c70f800SEd Tanous         dbusObjectPath = adConfigObject;
979eb2bbe56SRatan Gupta     }
980eb2bbe56SRatan Gupta     else if (serverType == "LDAP")
981eb2bbe56SRatan Gupta     {
98223a21a1cSEd Tanous         dbusObjectPath = ldapConfigObjectName;
983eb2bbe56SRatan Gupta     }
984cb13a392SEd Tanous     else
985cb13a392SEd Tanous     {
98610cb44f3SEd Tanous         BMCWEB_LOG_ERROR("serverType wasn't AD or LDAP but was {}????",
98710cb44f3SEd Tanous                          serverType);
988cb13a392SEd Tanous         return;
989cb13a392SEd Tanous     }
990eb2bbe56SRatan Gupta 
99110cb44f3SEd Tanous     if (input.authType && *input.authType != "UsernameAndPassword")
9928a07d286SRatan Gupta     {
99310cb44f3SEd Tanous         messages::propertyValueNotInList(asyncResp->res, *input.authType,
994c1019828SEd Tanous                                          "AuthenticationType");
995c1019828SEd Tanous         return;
9968a07d286SRatan Gupta     }
997c1019828SEd Tanous 
99810cb44f3SEd Tanous     if (input.serviceAddressList)
9998a07d286SRatan Gupta     {
100010cb44f3SEd Tanous         if (input.serviceAddressList->empty())
10018a07d286SRatan Gupta         {
1002e2616cc5SEd Tanous             messages::propertyValueNotInList(
100310cb44f3SEd Tanous                 asyncResp->res, *input.serviceAddressList, "ServiceAddress");
10048a07d286SRatan Gupta             return;
10058a07d286SRatan Gupta         }
10068a07d286SRatan Gupta     }
100710cb44f3SEd Tanous     if (input.baseDNList)
10088a07d286SRatan Gupta     {
100910cb44f3SEd Tanous         if (input.baseDNList->empty())
10108a07d286SRatan Gupta         {
101110cb44f3SEd Tanous             messages::propertyValueNotInList(asyncResp->res, *input.baseDNList,
10128a07d286SRatan Gupta                                              "BaseDistinguishedNames");
10138a07d286SRatan Gupta             return;
10148a07d286SRatan Gupta         }
10158a07d286SRatan Gupta     }
10168a07d286SRatan Gupta 
10178a07d286SRatan Gupta     // nothing to update, then return
101810cb44f3SEd Tanous     if (!input.userName && !input.password && !input.serviceAddressList &&
101910cb44f3SEd Tanous         !input.baseDNList && !input.userNameAttribute &&
102010cb44f3SEd Tanous         !input.groupsAttribute && !input.serviceEnabled &&
102110cb44f3SEd Tanous         !input.remoteRoleMapData)
10228a07d286SRatan Gupta     {
10238a07d286SRatan Gupta         return;
10248a07d286SRatan Gupta     }
10258a07d286SRatan Gupta 
10268a07d286SRatan Gupta     // Get the existing resource first then keep modifying
10278a07d286SRatan Gupta     // whenever any property gets updated.
1028bd79bce8SPatrick Williams     getLDAPConfigData(serverType, [asyncResp, input = std::move(input),
102910cb44f3SEd Tanous                                    dbusObjectPath = std::move(dbusObjectPath)](
1030bd79bce8SPatrick Williams                                       bool success,
1031bd79bce8SPatrick Williams                                       const LDAPConfigData& confData,
1032c1019828SEd Tanous                                       const std::string& serverT) mutable {
10338a07d286SRatan Gupta         if (!success)
10348a07d286SRatan Gupta         {
10358a07d286SRatan Gupta             messages::internalError(asyncResp->res);
10368a07d286SRatan Gupta             return;
10378a07d286SRatan Gupta         }
10386c51eab1SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, serverT);
10398a07d286SRatan Gupta         if (confData.serviceEnabled)
10408a07d286SRatan Gupta         {
10418a07d286SRatan Gupta             // Disable the service first and update the rest of
10428a07d286SRatan Gupta             // the properties.
10436c51eab1SEd Tanous             handleServiceEnablePatch(false, asyncResp, serverT, dbusObjectPath);
10448a07d286SRatan Gupta         }
10458a07d286SRatan Gupta 
104610cb44f3SEd Tanous         if (input.serviceAddressList)
10478a07d286SRatan Gupta         {
104810cb44f3SEd Tanous             handleServiceAddressPatch(*input.serviceAddressList, asyncResp,
104910cb44f3SEd Tanous                                       serverT, dbusObjectPath);
105010cb44f3SEd Tanous         }
105110cb44f3SEd Tanous         if (input.userName)
105210cb44f3SEd Tanous         {
105310cb44f3SEd Tanous             handleUserNamePatch(*input.userName, asyncResp, serverT,
10546c51eab1SEd Tanous                                 dbusObjectPath);
10558a07d286SRatan Gupta         }
105610cb44f3SEd Tanous         if (input.password)
10578a07d286SRatan Gupta         {
105810cb44f3SEd Tanous             handlePasswordPatch(*input.password, asyncResp, serverT,
105910cb44f3SEd Tanous                                 dbusObjectPath);
10608a07d286SRatan Gupta         }
10618a07d286SRatan Gupta 
106210cb44f3SEd Tanous         if (input.baseDNList)
10638a07d286SRatan Gupta         {
106410cb44f3SEd Tanous             handleBaseDNPatch(*input.baseDNList, asyncResp, serverT,
10656c51eab1SEd Tanous                               dbusObjectPath);
10668a07d286SRatan Gupta         }
106710cb44f3SEd Tanous         if (input.userNameAttribute)
10688a07d286SRatan Gupta         {
106910cb44f3SEd Tanous             handleUserNameAttrPatch(*input.userNameAttribute, asyncResp,
107010cb44f3SEd Tanous                                     serverT, dbusObjectPath);
107110cb44f3SEd Tanous         }
107210cb44f3SEd Tanous         if (input.groupsAttribute)
107310cb44f3SEd Tanous         {
107410cb44f3SEd Tanous             handleGroupNameAttrPatch(*input.groupsAttribute, asyncResp, serverT,
10756c51eab1SEd Tanous                                      dbusObjectPath);
10768a07d286SRatan Gupta         }
107710cb44f3SEd Tanous         if (input.serviceEnabled)
10788a07d286SRatan Gupta         {
10798a07d286SRatan Gupta             // if user has given the value as true then enable
10808a07d286SRatan Gupta             // the service. if user has given false then no-op
10818a07d286SRatan Gupta             // as service is already stopped.
108210cb44f3SEd Tanous             if (*input.serviceEnabled)
10838a07d286SRatan Gupta             {
108410cb44f3SEd Tanous                 handleServiceEnablePatch(*input.serviceEnabled, asyncResp,
108510cb44f3SEd Tanous                                          serverT, dbusObjectPath);
10868a07d286SRatan Gupta             }
10878a07d286SRatan Gupta         }
10888a07d286SRatan Gupta         else
10898a07d286SRatan Gupta         {
10908a07d286SRatan Gupta             // if user has not given the service enabled value
10918a07d286SRatan Gupta             // then revert it to the same state as it was
10928a07d286SRatan Gupta             // before.
10938a07d286SRatan Gupta             handleServiceEnablePatch(confData.serviceEnabled, asyncResp,
109423a21a1cSEd Tanous                                      serverT, dbusObjectPath);
10958a07d286SRatan Gupta         }
109606785244SRatan Gupta 
109710cb44f3SEd Tanous         if (input.remoteRoleMapData)
109806785244SRatan Gupta         {
10996c51eab1SEd Tanous             handleRoleMapPatch(asyncResp, confData.groupRoleList, serverT,
110010cb44f3SEd Tanous                                *input.remoteRoleMapData);
110106785244SRatan Gupta         }
11028a07d286SRatan Gupta     });
11038a07d286SRatan Gupta }
1104d4b5443fSEd Tanous 
1105492ec93aSEd Tanous struct UserUpdateParams
11061abe55efSEd Tanous {
1107492ec93aSEd Tanous     std::string username;
1108492ec93aSEd Tanous     std::optional<std::string> password;
1109492ec93aSEd Tanous     std::optional<bool> enabled;
1110492ec93aSEd Tanous     std::optional<std::string> roleId;
1111492ec93aSEd Tanous     std::optional<bool> locked;
1112492ec93aSEd Tanous     std::optional<std::vector<std::string>> accountTypes;
1113492ec93aSEd Tanous     bool userSelf;
1114492ec93aSEd Tanous     std::shared_ptr<persistent_data::UserSession> session;
1115492ec93aSEd Tanous     std::string dbusObjectPath;
1116492ec93aSEd Tanous };
11176c51eab1SEd Tanous 
1118492ec93aSEd Tanous inline void
1119492ec93aSEd Tanous     afterVerifyUserExists(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1120492ec93aSEd Tanous                           const UserUpdateParams& params, int rc)
1121492ec93aSEd Tanous {
1122e662eae8SEd Tanous     if (rc <= 0)
11236c51eab1SEd Tanous     {
1124d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1125492ec93aSEd Tanous                                    params.username);
11266c51eab1SEd Tanous         return;
11276c51eab1SEd Tanous     }
11286c51eab1SEd Tanous 
1129492ec93aSEd Tanous     if (params.password)
11306c51eab1SEd Tanous     {
1131492ec93aSEd Tanous         int retval = pamUpdatePassword(params.username, *params.password);
11326c51eab1SEd Tanous 
11336c51eab1SEd Tanous         if (retval == PAM_USER_UNKNOWN)
11346c51eab1SEd Tanous         {
1135d8a5d5d8SJiaqing Zhao             messages::resourceNotFound(asyncResp->res, "ManagerAccount",
1136492ec93aSEd Tanous                                        params.username);
11376c51eab1SEd Tanous         }
11386c51eab1SEd Tanous         else if (retval == PAM_AUTHTOK_ERR)
11396c51eab1SEd Tanous         {
11406c51eab1SEd Tanous             // If password is invalid
11419bd80831SJason M. Bills             messages::propertyValueFormatError(asyncResp->res, nullptr,
11429bd80831SJason M. Bills                                                "Password");
114362598e31SEd Tanous             BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
11446c51eab1SEd Tanous         }
11456c51eab1SEd Tanous         else if (retval != PAM_SUCCESS)
11466c51eab1SEd Tanous         {
11476c51eab1SEd Tanous             messages::internalError(asyncResp->res);
11486c51eab1SEd Tanous             return;
11496c51eab1SEd Tanous         }
1150e7b1b62bSEd Tanous         else
1151e7b1b62bSEd Tanous         {
1152bd79bce8SPatrick Williams             // Remove existing sessions of the user when password
1153bd79bce8SPatrick Williams             // changed
1154e518ef32SRavi Teja             persistent_data::SessionStore::getInstance()
1155492ec93aSEd Tanous                 .removeSessionsByUsernameExceptSession(params.username,
1156492ec93aSEd Tanous                                                        params.session);
1157e7b1b62bSEd Tanous             messages::success(asyncResp->res);
1158e7b1b62bSEd Tanous         }
11596c51eab1SEd Tanous     }
11606c51eab1SEd Tanous 
1161492ec93aSEd Tanous     if (params.enabled)
11626c51eab1SEd Tanous     {
1163bd79bce8SPatrick Williams         setDbusProperty(
1164bd79bce8SPatrick Williams             asyncResp, "Enabled", "xyz.openbmc_project.User.Manager",
1165492ec93aSEd Tanous             params.dbusObjectPath, "xyz.openbmc_project.User.Attributes",
1166492ec93aSEd Tanous             "UserEnabled", *params.enabled);
11676c51eab1SEd Tanous     }
11686c51eab1SEd Tanous 
1169492ec93aSEd Tanous     if (params.roleId)
11706c51eab1SEd Tanous     {
1171492ec93aSEd Tanous         std::string priv = getPrivilegeFromRoleId(*params.roleId);
11726c51eab1SEd Tanous         if (priv.empty())
11736c51eab1SEd Tanous         {
1174492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, true, "Locked");
11756c51eab1SEd Tanous             return;
11766c51eab1SEd Tanous         }
1177492ec93aSEd Tanous         setDbusProperty(asyncResp, "RoleId", "xyz.openbmc_project.User.Manager",
1178492ec93aSEd Tanous                         params.dbusObjectPath,
1179492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes", "UserPrivilege",
1180492ec93aSEd Tanous                         priv);
11816c51eab1SEd Tanous     }
11826c51eab1SEd Tanous 
1183492ec93aSEd Tanous     if (params.locked)
11846c51eab1SEd Tanous     {
11856c51eab1SEd Tanous         // admin can unlock the account which is locked by
11866c51eab1SEd Tanous         // successive authentication failures but admin should
11876c51eab1SEd Tanous         // not be allowed to lock an account.
1188492ec93aSEd Tanous         if (*params.locked)
11896c51eab1SEd Tanous         {
1190492ec93aSEd Tanous             messages::propertyValueNotInList(asyncResp->res, "true", "Locked");
11916c51eab1SEd Tanous             return;
11926c51eab1SEd Tanous         }
1193492ec93aSEd Tanous         setDbusProperty(asyncResp, "Locked", "xyz.openbmc_project.User.Manager",
1194492ec93aSEd Tanous                         params.dbusObjectPath,
1195492ec93aSEd Tanous                         "xyz.openbmc_project.User.Attributes",
1196492ec93aSEd Tanous                         "UserLockedForFailedAttempt", *params.locked);
11976c51eab1SEd Tanous     }
119858345856SAbhishek Patel 
1199492ec93aSEd Tanous     if (params.accountTypes)
120058345856SAbhishek Patel     {
1201492ec93aSEd Tanous         patchAccountTypes(*params.accountTypes, asyncResp,
1202492ec93aSEd Tanous                           params.dbusObjectPath, params.userSelf);
120358345856SAbhishek Patel     }
1204492ec93aSEd Tanous }
1205492ec93aSEd Tanous 
1206492ec93aSEd Tanous inline void updateUserProperties(
1207492ec93aSEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1208492ec93aSEd Tanous     const std::string& username, const std::optional<std::string>& password,
1209492ec93aSEd Tanous     const std::optional<bool>& enabled,
1210492ec93aSEd Tanous     const std::optional<std::string>& roleId, const std::optional<bool>& locked,
1211492ec93aSEd Tanous     const std::optional<std::vector<std::string>>& accountTypes, bool userSelf,
1212492ec93aSEd Tanous     const std::shared_ptr<persistent_data::UserSession>& session)
1213492ec93aSEd Tanous {
1214492ec93aSEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
1215492ec93aSEd Tanous     tempObjPath /= username;
1216492ec93aSEd Tanous     std::string dbusObjectPath(tempObjPath);
1217492ec93aSEd Tanous 
1218492ec93aSEd Tanous     UserUpdateParams params{username, password, enabled,
1219492ec93aSEd Tanous                             roleId,   locked,   accountTypes,
1220492ec93aSEd Tanous                             userSelf, session,  dbusObjectPath};
1221492ec93aSEd Tanous 
1222492ec93aSEd Tanous     dbus::utility::checkDbusPathExists(
1223492ec93aSEd Tanous         dbusObjectPath,
1224492ec93aSEd Tanous         std::bind_front(afterVerifyUserExists, asyncResp, std::move(params)));
12256c51eab1SEd Tanous }
12266c51eab1SEd Tanous 
12274c7d4d33SEd Tanous inline void handleAccountServiceHead(
12284c7d4d33SEd Tanous     App& app, const crow::Request& req,
12291ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12306c51eab1SEd Tanous {
12313ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
123245ca1b86SEd Tanous     {
123345ca1b86SEd Tanous         return;
123445ca1b86SEd Tanous     }
12354c7d4d33SEd Tanous     asyncResp->res.addHeader(
12364c7d4d33SEd Tanous         boost::beast::http::field::link,
12374c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
12384c7d4d33SEd Tanous }
12394c7d4d33SEd Tanous 
12404c7d4d33SEd Tanous inline void
12411aa375b8SEd Tanous     getClientCertificates(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12421aa375b8SEd Tanous                           const nlohmann::json::json_pointer& keyLocation)
12431aa375b8SEd Tanous {
12441aa375b8SEd Tanous     boost::urls::url url(
12451aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates");
12461aa375b8SEd Tanous     std::array<std::string_view, 1> interfaces = {
12471aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Certificate"};
12481aa375b8SEd Tanous     std::string path = "/xyz/openbmc_project/certs/authority/truststore";
12491aa375b8SEd Tanous 
12501aa375b8SEd Tanous     collection_util::getCollectionToKey(asyncResp, url, interfaces, path,
12511aa375b8SEd Tanous                                         keyLocation);
12521aa375b8SEd Tanous }
12531aa375b8SEd Tanous 
12541aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceHead(
12551aa375b8SEd Tanous     App& app, const crow::Request& req,
12561aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
12571aa375b8SEd Tanous     const std::string& /*id*/)
12581aa375b8SEd Tanous {
12591aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12601aa375b8SEd Tanous     {
12611aa375b8SEd Tanous         return;
12621aa375b8SEd Tanous     }
12631aa375b8SEd Tanous 
12641aa375b8SEd Tanous     asyncResp->res.addHeader(
12651aa375b8SEd Tanous         boost::beast::http::field::link,
12661aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/Certificate/Certificate.json>; rel=describedby");
12671aa375b8SEd Tanous }
12681aa375b8SEd Tanous 
12691aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesInstanceGet(
12701aa375b8SEd Tanous     App& app, const crow::Request& req,
12711aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id)
12721aa375b8SEd Tanous {
12731aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12741aa375b8SEd Tanous     {
12751aa375b8SEd Tanous         return;
12761aa375b8SEd Tanous     }
12771aa375b8SEd Tanous     BMCWEB_LOG_DEBUG("ClientCertificate Certificate ID={}", id);
12781aa375b8SEd Tanous     const boost::urls::url certURL = boost::urls::format(
12791aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/{}",
12801aa375b8SEd Tanous         id);
12811aa375b8SEd Tanous     std::string objPath =
12821aa375b8SEd Tanous         sdbusplus::message::object_path(certs::authorityObjectPath) / id;
12831aa375b8SEd Tanous     getCertificateProperties(
12841aa375b8SEd Tanous         asyncResp, objPath,
12851aa375b8SEd Tanous         "xyz.openbmc_project.Certs.Manager.Authority.Truststore", id, certURL,
12861aa375b8SEd Tanous         "Client Certificate");
12871aa375b8SEd Tanous }
12881aa375b8SEd Tanous 
12891aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesHead(
12901aa375b8SEd Tanous     App& app, const crow::Request& req,
12911aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
12921aa375b8SEd Tanous {
12931aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
12941aa375b8SEd Tanous     {
12951aa375b8SEd Tanous         return;
12961aa375b8SEd Tanous     }
12971aa375b8SEd Tanous 
12981aa375b8SEd Tanous     asyncResp->res.addHeader(
12991aa375b8SEd Tanous         boost::beast::http::field::link,
13001aa375b8SEd Tanous         "</redfish/v1/JsonSchemas/CertificateCollection/CertificateCollection.json>; rel=describedby");
13011aa375b8SEd Tanous }
13021aa375b8SEd Tanous 
13031aa375b8SEd Tanous inline void handleAccountServiceClientCertificatesGet(
13041aa375b8SEd Tanous     App& app, const crow::Request& req,
13051aa375b8SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13061aa375b8SEd Tanous {
13071aa375b8SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
13081aa375b8SEd Tanous     {
13091aa375b8SEd Tanous         return;
13101aa375b8SEd Tanous     }
13111aa375b8SEd Tanous     getClientCertificates(asyncResp, "/Members"_json_pointer);
13121aa375b8SEd Tanous }
13131aa375b8SEd Tanous 
13143ce3688aSEd Tanous using account_service::CertificateMappingAttribute;
13153ce3688aSEd Tanous using persistent_data::MTLSCommonNameParseMode;
13163ce3688aSEd Tanous inline CertificateMappingAttribute
13173ce3688aSEd Tanous     getCertificateMapping(MTLSCommonNameParseMode parse)
13183ce3688aSEd Tanous {
13193ce3688aSEd Tanous     switch (parse)
13203ce3688aSEd Tanous     {
13213ce3688aSEd Tanous         case MTLSCommonNameParseMode::CommonName:
13223ce3688aSEd Tanous         {
13233ce3688aSEd Tanous             return CertificateMappingAttribute::CommonName;
13243ce3688aSEd Tanous         }
13253ce3688aSEd Tanous         break;
13263ce3688aSEd Tanous         case MTLSCommonNameParseMode::Whole:
13273ce3688aSEd Tanous         {
13283ce3688aSEd Tanous             return CertificateMappingAttribute::Whole;
13293ce3688aSEd Tanous         }
13303ce3688aSEd Tanous         break;
13313ce3688aSEd Tanous         case MTLSCommonNameParseMode::UserPrincipalName:
13323ce3688aSEd Tanous         {
13333ce3688aSEd Tanous             return CertificateMappingAttribute::UserPrincipalName;
13343ce3688aSEd Tanous         }
13353ce3688aSEd Tanous         break;
13363ce3688aSEd Tanous 
13373ce3688aSEd Tanous         case MTLSCommonNameParseMode::Meta:
13383ce3688aSEd Tanous         {
13393ce3688aSEd Tanous             if constexpr (BMCWEB_META_TLS_COMMON_NAME_PARSING)
13403ce3688aSEd Tanous             {
13413ce3688aSEd Tanous                 return CertificateMappingAttribute::CommonName;
13423ce3688aSEd Tanous             }
13433ce3688aSEd Tanous         }
13443ce3688aSEd Tanous         break;
13453ce3688aSEd Tanous         default:
13463ce3688aSEd Tanous         {
13473ce3688aSEd Tanous             return CertificateMappingAttribute::Invalid;
13483ce3688aSEd Tanous         }
13493ce3688aSEd Tanous         break;
13503ce3688aSEd Tanous     }
13513ce3688aSEd Tanous }
13523ce3688aSEd Tanous 
13531aa375b8SEd Tanous inline void
13544c7d4d33SEd Tanous     handleAccountServiceGet(App& app, const crow::Request& req,
13554c7d4d33SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
13564c7d4d33SEd Tanous {
1357afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1358afd369c6SJiaqing Zhao     {
1359afd369c6SJiaqing Zhao         return;
1360afd369c6SJiaqing Zhao     }
13613e72c202SNinad Palsule 
13623e72c202SNinad Palsule     if (req.session == nullptr)
13633e72c202SNinad Palsule     {
13643e72c202SNinad Palsule         messages::internalError(asyncResp->res);
13653e72c202SNinad Palsule         return;
13663e72c202SNinad Palsule     }
13673e72c202SNinad Palsule 
1368c1019828SEd Tanous     const persistent_data::AuthConfigMethods& authMethodsConfig =
1369c1019828SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
1370c1019828SEd Tanous 
1371afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1372afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1373afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/AccountService/AccountService.json>; rel=describedby");
1374afd369c6SJiaqing Zhao 
13751476687dSEd Tanous     nlohmann::json& json = asyncResp->res.jsonValue;
13761476687dSEd Tanous     json["@odata.id"] = "/redfish/v1/AccountService";
1377482a69e7SRavi Teja     json["@odata.type"] = "#AccountService.v1_15_0.AccountService";
13781476687dSEd Tanous     json["Id"] = "AccountService";
13791476687dSEd Tanous     json["Name"] = "Account Service";
13801476687dSEd Tanous     json["Description"] = "Account Service";
13811476687dSEd Tanous     json["ServiceEnabled"] = true;
13821476687dSEd Tanous     json["MaxPasswordLength"] = 20;
13831ef4c342SEd Tanous     json["Accounts"]["@odata.id"] = "/redfish/v1/AccountService/Accounts";
13841476687dSEd Tanous     json["Roles"]["@odata.id"] = "/redfish/v1/AccountService/Roles";
1385482a69e7SRavi Teja     json["HTTPBasicAuth"] = authMethodsConfig.basic
1386482a69e7SRavi Teja                                 ? account_service::BasicAuthState::Enabled
1387482a69e7SRavi Teja                                 : account_service::BasicAuthState::Disabled;
1388482a69e7SRavi Teja 
1389482a69e7SRavi Teja     nlohmann::json::array_t allowed;
1390482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Enabled);
1391482a69e7SRavi Teja     allowed.emplace_back(account_service::BasicAuthState::Disabled);
1392482a69e7SRavi Teja     json["HTTPBasicAuth@AllowableValues"] = std::move(allowed);
1393482a69e7SRavi Teja 
13941aa375b8SEd Tanous     nlohmann::json::object_t clientCertificate;
13951aa375b8SEd Tanous     clientCertificate["Enabled"] = authMethodsConfig.tls;
13963281bcf1SEd Tanous     clientCertificate["RespondToUnauthenticatedClients"] =
13973281bcf1SEd Tanous         !authMethodsConfig.tlsStrict;
13983ce3688aSEd Tanous 
13993ce3688aSEd Tanous     using account_service::CertificateMappingAttribute;
14003ce3688aSEd Tanous 
14013ce3688aSEd Tanous     CertificateMappingAttribute mapping =
14023ce3688aSEd Tanous         getCertificateMapping(authMethodsConfig.mTLSCommonNameParsingMode);
14033ce3688aSEd Tanous     if (mapping == CertificateMappingAttribute::Invalid)
14043ce3688aSEd Tanous     {
14053ce3688aSEd Tanous         messages::internalError(asyncResp->res);
14063ce3688aSEd Tanous     }
14073ce3688aSEd Tanous     else
14083ce3688aSEd Tanous     {
14093ce3688aSEd Tanous         clientCertificate["CertificateMappingAttribute"] = mapping;
14103ce3688aSEd Tanous     }
14111aa375b8SEd Tanous     nlohmann::json::object_t certificates;
14121aa375b8SEd Tanous     certificates["@odata.id"] =
14131aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates";
14141aa375b8SEd Tanous     certificates["@odata.type"] =
14151aa375b8SEd Tanous         "#CertificateCollection.CertificateCollection";
14161aa375b8SEd Tanous     clientCertificate["Certificates"] = std::move(certificates);
14171aa375b8SEd Tanous     json["MultiFactorAuth"]["ClientCertificate"] = std::move(clientCertificate);
14181aa375b8SEd Tanous 
14191aa375b8SEd Tanous     getClientCertificates(
14201aa375b8SEd Tanous         asyncResp,
14211aa375b8SEd Tanous         "/MultiFactorAuth/ClientCertificate/Certificates/Members"_json_pointer);
14221aa375b8SEd Tanous 
14231476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.type"] =
14245b5574acSEd Tanous         "#OpenBMCAccountService.v1_0_0.AccountService";
14251476687dSEd Tanous     json["Oem"]["OpenBMC"]["@odata.id"] =
14261476687dSEd Tanous         "/redfish/v1/AccountService#/Oem/OpenBMC";
14271476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["BasicAuth"] =
14281476687dSEd Tanous         authMethodsConfig.basic;
14291476687dSEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["SessionToken"] =
14301476687dSEd Tanous         authMethodsConfig.sessionToken;
14311ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["XToken"] = authMethodsConfig.xtoken;
14321ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["Cookie"] = authMethodsConfig.cookie;
14331ef4c342SEd Tanous     json["Oem"]["OpenBMC"]["AuthMethods"]["TLS"] = authMethodsConfig.tls;
14341476687dSEd Tanous 
14351ef4c342SEd Tanous     // /redfish/v1/AccountService/LDAP/Certificates is something only
14361ef4c342SEd Tanous     // ConfigureManager can access then only display when the user has
14371ef4c342SEd Tanous     // permissions ConfigureManager
143872048780SAbhishek Patel     Privileges effectiveUserPrivileges =
14393e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
144072048780SAbhishek Patel 
144172048780SAbhishek Patel     if (isOperationAllowedWithPrivileges({{"ConfigureManager"}},
144272048780SAbhishek Patel                                          effectiveUserPrivileges))
144372048780SAbhishek Patel     {
14441ef4c342SEd Tanous         asyncResp->res.jsonValue["LDAP"]["Certificates"]["@odata.id"] =
14451476687dSEd Tanous             "/redfish/v1/AccountService/LDAP/Certificates";
144672048780SAbhishek Patel     }
1447deae6a78SEd Tanous     dbus::utility::getAllProperties(
1448deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1449deae6a78SEd Tanous         "xyz.openbmc_project.User.AccountPolicy",
14505e7e2dc5SEd Tanous         [asyncResp](const boost::system::error_code& ec,
14511ef4c342SEd Tanous                     const dbus::utility::DBusPropertiesMap& propertiesList) {
14523d958bbcSAppaRao Puli             if (ec)
14533d958bbcSAppaRao Puli             {
14543d958bbcSAppaRao Puli                 messages::internalError(asyncResp->res);
14553d958bbcSAppaRao Puli                 return;
14563d958bbcSAppaRao Puli             }
1457d1bde9e5SKrzysztof Grobelny 
145862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Got {} properties for AccountService",
145962598e31SEd Tanous                              propertiesList.size());
1460d1bde9e5SKrzysztof Grobelny 
1461d1bde9e5SKrzysztof Grobelny             const uint8_t* minPasswordLength = nullptr;
1462d1bde9e5SKrzysztof Grobelny             const uint32_t* accountUnlockTimeout = nullptr;
1463d1bde9e5SKrzysztof Grobelny             const uint16_t* maxLoginAttemptBeforeLockout = nullptr;
1464d1bde9e5SKrzysztof Grobelny 
1465d1bde9e5SKrzysztof Grobelny             const bool success = sdbusplus::unpackPropertiesNoThrow(
1466d1bde9e5SKrzysztof Grobelny                 dbus_utils::UnpackErrorPrinter(), propertiesList,
1467d1bde9e5SKrzysztof Grobelny                 "MinPasswordLength", minPasswordLength, "AccountUnlockTimeout",
1468d1bde9e5SKrzysztof Grobelny                 accountUnlockTimeout, "MaxLoginAttemptBeforeLockout",
1469d1bde9e5SKrzysztof Grobelny                 maxLoginAttemptBeforeLockout);
1470d1bde9e5SKrzysztof Grobelny 
1471d1bde9e5SKrzysztof Grobelny             if (!success)
14723d958bbcSAppaRao Puli             {
1473d1bde9e5SKrzysztof Grobelny                 messages::internalError(asyncResp->res);
1474d1bde9e5SKrzysztof Grobelny                 return;
14753d958bbcSAppaRao Puli             }
1476d1bde9e5SKrzysztof Grobelny 
1477d1bde9e5SKrzysztof Grobelny             if (minPasswordLength != nullptr)
14783d958bbcSAppaRao Puli             {
1479bd79bce8SPatrick Williams                 asyncResp->res.jsonValue["MinPasswordLength"] =
1480bd79bce8SPatrick Williams                     *minPasswordLength;
14813d958bbcSAppaRao Puli             }
1482d1bde9e5SKrzysztof Grobelny 
1483d1bde9e5SKrzysztof Grobelny             if (accountUnlockTimeout != nullptr)
14843d958bbcSAppaRao Puli             {
1485d1bde9e5SKrzysztof Grobelny                 asyncResp->res.jsonValue["AccountLockoutDuration"] =
1486d1bde9e5SKrzysztof Grobelny                     *accountUnlockTimeout;
1487d1bde9e5SKrzysztof Grobelny             }
1488d1bde9e5SKrzysztof Grobelny 
1489d1bde9e5SKrzysztof Grobelny             if (maxLoginAttemptBeforeLockout != nullptr)
14903d958bbcSAppaRao Puli             {
1491002d39b4SEd Tanous                 asyncResp->res.jsonValue["AccountLockoutThreshold"] =
1492d1bde9e5SKrzysztof Grobelny                     *maxLoginAttemptBeforeLockout;
14933d958bbcSAppaRao Puli             }
1494d1bde9e5SKrzysztof Grobelny         });
14956973a582SRatan Gupta 
149602cad96eSEd Tanous     auto callback = [asyncResp](bool success, const LDAPConfigData& confData,
1497ab828d7cSRatan Gupta                                 const std::string& ldapType) {
1498cb13a392SEd Tanous         if (!success)
1499cb13a392SEd Tanous         {
1500cb13a392SEd Tanous             return;
1501cb13a392SEd Tanous         }
1502002d39b4SEd Tanous         parseLDAPConfigData(asyncResp->res.jsonValue, confData, ldapType);
1503ab828d7cSRatan Gupta     };
1504ab828d7cSRatan Gupta 
1505ab828d7cSRatan Gupta     getLDAPConfigData("LDAP", callback);
1506ab828d7cSRatan Gupta     getLDAPConfigData("ActiveDirectory", callback);
15071ef4c342SEd Tanous }
15086973a582SRatan Gupta 
1509bd79bce8SPatrick Williams inline void handleCertificateMappingAttributePatch(
1510bd79bce8SPatrick Williams     crow::Response& res, const std::string& certMapAttribute)
15113ce3688aSEd Tanous {
15123ce3688aSEd Tanous     MTLSCommonNameParseMode parseMode =
15133ce3688aSEd Tanous         persistent_data::getMTLSCommonNameParseMode(certMapAttribute);
15143ce3688aSEd Tanous     if (parseMode == MTLSCommonNameParseMode::Invalid)
15153ce3688aSEd Tanous     {
15163ce3688aSEd Tanous         messages::propertyValueNotInList(res, "CertificateMappingAttribute",
15173ce3688aSEd Tanous                                          certMapAttribute);
15183ce3688aSEd Tanous         return;
15193ce3688aSEd Tanous     }
15203ce3688aSEd Tanous 
15213ce3688aSEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15223ce3688aSEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15233ce3688aSEd Tanous     authMethodsConfig.mTLSCommonNameParsingMode = parseMode;
15243ce3688aSEd Tanous }
15253ce3688aSEd Tanous 
15263281bcf1SEd Tanous inline void handleRespondToUnauthenticatedClientsPatch(
15273281bcf1SEd Tanous     App& app, const crow::Request& req, crow::Response& res,
15283281bcf1SEd Tanous     bool respondToUnauthenticatedClients)
15293281bcf1SEd Tanous {
15303281bcf1SEd Tanous     if (req.session != nullptr)
15313281bcf1SEd Tanous     {
15323281bcf1SEd Tanous         // Sanity check.  If the user isn't currently authenticated with mutual
15333281bcf1SEd Tanous         // TLS, they very likely are about to permanently lock themselves out.
15343281bcf1SEd Tanous         // Make sure they're using mutual TLS before allowing locking.
15353281bcf1SEd Tanous         if (req.session->sessionType != persistent_data::SessionType::MutualTLS)
15363281bcf1SEd Tanous         {
15373281bcf1SEd Tanous             messages::propertyValueExternalConflict(
15383281bcf1SEd Tanous                 res,
15393281bcf1SEd Tanous                 "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
15403281bcf1SEd Tanous                 respondToUnauthenticatedClients);
15413281bcf1SEd Tanous             return;
15423281bcf1SEd Tanous         }
15433281bcf1SEd Tanous     }
15443281bcf1SEd Tanous 
15453281bcf1SEd Tanous     persistent_data::AuthConfigMethods& authMethodsConfig =
15463281bcf1SEd Tanous         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
15473281bcf1SEd Tanous 
15483281bcf1SEd Tanous     // Change the settings
15493281bcf1SEd Tanous     authMethodsConfig.tlsStrict = !respondToUnauthenticatedClients;
15503281bcf1SEd Tanous 
15513281bcf1SEd Tanous     // Write settings to disk
15523281bcf1SEd Tanous     persistent_data::getConfig().writeData();
15533281bcf1SEd Tanous 
15543281bcf1SEd Tanous     // Trigger a reload, to apply the new settings to new connections
15553281bcf1SEd Tanous     app.loadCertificate();
15563281bcf1SEd Tanous }
15573281bcf1SEd Tanous 
15581ef4c342SEd Tanous inline void handleAccountServicePatch(
15591ef4c342SEd Tanous     App& app, const crow::Request& req,
15601ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
15611ef4c342SEd Tanous {
15623ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
156345ca1b86SEd Tanous     {
156445ca1b86SEd Tanous         return;
156545ca1b86SEd Tanous     }
1566f5ffd806SEd Tanous     std::optional<uint32_t> unlockTimeout;
1567f5ffd806SEd Tanous     std::optional<uint16_t> lockoutThreshold;
1568ef73ad0dSPaul Fertser     std::optional<uint8_t> minPasswordLength;
1569f5ffd806SEd Tanous     std::optional<uint16_t> maxPasswordLength;
157010cb44f3SEd Tanous     LdapPatchParams ldapObject;
15713ce3688aSEd Tanous     std::optional<std::string> certificateMappingAttribute;
15723281bcf1SEd Tanous     std::optional<bool> respondToUnauthenticatedClients;
157310cb44f3SEd Tanous     LdapPatchParams activeDirectoryObject;
1574c1019828SEd Tanous     AuthMethods auth;
1575482a69e7SRavi Teja     std::optional<std::string> httpBasicAuth;
15763ce3688aSEd Tanous 
1577afc474aeSMyung Bae     if (!json_util::readJsonPatch( //
1578afc474aeSMyung Bae             req, asyncResp->res, //
1579afc474aeSMyung Bae             "AccountLockoutDuration", unlockTimeout, //
1580afc474aeSMyung Bae             "AccountLockoutThreshold", lockoutThreshold, //
1581afc474aeSMyung Bae             "ActiveDirectory/Authentication/AuthenticationType",
1582afc474aeSMyung Bae             activeDirectoryObject.authType, //
1583afc474aeSMyung Bae             "ActiveDirectory/Authentication/Password",
1584afc474aeSMyung Bae             activeDirectoryObject.password, //
1585afc474aeSMyung Bae             "ActiveDirectory/Authentication/Username",
1586afc474aeSMyung Bae             activeDirectoryObject.userName, //
1587afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/BaseDistinguishedNames",
1588afc474aeSMyung Bae             activeDirectoryObject.baseDNList, //
1589afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/GroupsAttribute",
1590afc474aeSMyung Bae             activeDirectoryObject.groupsAttribute, //
1591afc474aeSMyung Bae             "ActiveDirectory/LDAPService/SearchSettings/UsernameAttribute",
1592afc474aeSMyung Bae             activeDirectoryObject.userNameAttribute, //
1593afc474aeSMyung Bae             "ActiveDirectory/RemoteRoleMapping",
1594afc474aeSMyung Bae             activeDirectoryObject.remoteRoleMapData, //
1595afc474aeSMyung Bae             "ActiveDirectory/ServiceAddresses",
1596afc474aeSMyung Bae             activeDirectoryObject.serviceAddressList, //
1597afc474aeSMyung Bae             "ActiveDirectory/ServiceEnabled",
1598afc474aeSMyung Bae             activeDirectoryObject.serviceEnabled, //
1599afc474aeSMyung Bae             "HTTPBasicAuth", httpBasicAuth, //
1600afc474aeSMyung Bae             "LDAP/Authentication/AuthenticationType", ldapObject.authType, //
1601afc474aeSMyung Bae             "LDAP/Authentication/Password", ldapObject.password, //
1602afc474aeSMyung Bae             "LDAP/Authentication/Username", ldapObject.userName, //
1603afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/BaseDistinguishedNames",
1604afc474aeSMyung Bae             ldapObject.baseDNList, //
1605afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/GroupsAttribute",
1606afc474aeSMyung Bae             ldapObject.groupsAttribute, //
1607afc474aeSMyung Bae             "LDAP/LDAPService/SearchSettings/UsernameAttribute",
1608afc474aeSMyung Bae             ldapObject.userNameAttribute, //
1609afc474aeSMyung Bae             "LDAP/RemoteRoleMapping", ldapObject.remoteRoleMapData, //
1610afc474aeSMyung Bae             "LDAP/ServiceAddresses", ldapObject.serviceAddressList, //
1611afc474aeSMyung Bae             "LDAP/ServiceEnabled", ldapObject.serviceEnabled, //
1612afc474aeSMyung Bae             "MaxPasswordLength", maxPasswordLength, //
1613afc474aeSMyung Bae             "MinPasswordLength", minPasswordLength, //
1614afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/CertificateMappingAttribute",
1615afc474aeSMyung Bae             certificateMappingAttribute, //
1616afc474aeSMyung Bae             "MultiFactorAuth/ClientCertificate/RespondToUnauthenticatedClients",
1617afc474aeSMyung Bae             respondToUnauthenticatedClients, //
1618afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/BasicAuth", auth.basicAuth, //
1619afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/Cookie", auth.cookie, //
1620afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/SessionToken", auth.sessionToken, //
1621afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/TLS", auth.tls, //
1622afc474aeSMyung Bae             "Oem/OpenBMC/AuthMethods/XToken", auth.xToken //
1623afc474aeSMyung Bae             ))
1624f5ffd806SEd Tanous     {
1625f5ffd806SEd Tanous         return;
1626f5ffd806SEd Tanous     }
1627f5ffd806SEd Tanous 
1628482a69e7SRavi Teja     if (httpBasicAuth)
1629482a69e7SRavi Teja     {
1630482a69e7SRavi Teja         if (*httpBasicAuth == "Enabled")
1631482a69e7SRavi Teja         {
1632482a69e7SRavi Teja             auth.basicAuth = true;
1633482a69e7SRavi Teja         }
1634482a69e7SRavi Teja         else if (*httpBasicAuth == "Disabled")
1635482a69e7SRavi Teja         {
1636482a69e7SRavi Teja             auth.basicAuth = false;
1637482a69e7SRavi Teja         }
1638482a69e7SRavi Teja         else
1639482a69e7SRavi Teja         {
1640482a69e7SRavi Teja             messages::propertyValueNotInList(asyncResp->res, "HttpBasicAuth",
1641482a69e7SRavi Teja                                              *httpBasicAuth);
1642482a69e7SRavi Teja         }
1643482a69e7SRavi Teja     }
1644482a69e7SRavi Teja 
16453281bcf1SEd Tanous     if (respondToUnauthenticatedClients)
16463281bcf1SEd Tanous     {
16473281bcf1SEd Tanous         handleRespondToUnauthenticatedClientsPatch(
16483281bcf1SEd Tanous             app, req, asyncResp->res, *respondToUnauthenticatedClients);
16493281bcf1SEd Tanous     }
16503281bcf1SEd Tanous 
16513ce3688aSEd Tanous     if (certificateMappingAttribute)
16523ce3688aSEd Tanous     {
16533ce3688aSEd Tanous         handleCertificateMappingAttributePatch(asyncResp->res,
16543ce3688aSEd Tanous                                                *certificateMappingAttribute);
16553ce3688aSEd Tanous     }
16563ce3688aSEd Tanous 
1657f5ffd806SEd Tanous     if (minPasswordLength)
1658f5ffd806SEd Tanous     {
1659d02aad39SEd Tanous         setDbusProperty(
1660e93abac6SGinu George             asyncResp, "MinPasswordLength", "xyz.openbmc_project.User.Manager",
1661d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16629ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "MinPasswordLength",
1663e93abac6SGinu George             *minPasswordLength);
1664f5ffd806SEd Tanous     }
1665f5ffd806SEd Tanous 
1666f5ffd806SEd Tanous     if (maxPasswordLength)
1667f5ffd806SEd Tanous     {
16681ef4c342SEd Tanous         messages::propertyNotWritable(asyncResp->res, "MaxPasswordLength");
1669f5ffd806SEd Tanous     }
1670f5ffd806SEd Tanous 
167110cb44f3SEd Tanous     handleLDAPPatch(std::move(activeDirectoryObject), asyncResp,
167210cb44f3SEd Tanous                     "ActiveDirectory");
167310cb44f3SEd Tanous     handleLDAPPatch(std::move(ldapObject), asyncResp, "LDAP");
1674f5ffd806SEd Tanous 
1675c1019828SEd Tanous     handleAuthMethodsPatch(asyncResp, auth);
1676f5ffd806SEd Tanous 
1677f5ffd806SEd Tanous     if (unlockTimeout)
1678f5ffd806SEd Tanous     {
1679d02aad39SEd Tanous         setDbusProperty(
1680e93abac6SGinu George             asyncResp, "AccountLockoutDuration",
1681e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1682d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16839ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy", "AccountUnlockTimeout",
1684e93abac6SGinu George             *unlockTimeout);
1685f5ffd806SEd Tanous     }
1686f5ffd806SEd Tanous     if (lockoutThreshold)
1687f5ffd806SEd Tanous     {
1688d02aad39SEd Tanous         setDbusProperty(
1689e93abac6SGinu George             asyncResp, "AccountLockoutThreshold",
1690e93abac6SGinu George             "xyz.openbmc_project.User.Manager",
1691d02aad39SEd Tanous             sdbusplus::message::object_path("/xyz/openbmc_project/user"),
16929ae226faSGeorge Liu             "xyz.openbmc_project.User.AccountPolicy",
1693e93abac6SGinu George             "MaxLoginAttemptBeforeLockout", *lockoutThreshold);
1694f5ffd806SEd Tanous     }
16951ef4c342SEd Tanous }
1696f5ffd806SEd Tanous 
16974c7d4d33SEd Tanous inline void handleAccountCollectionHead(
16981ef4c342SEd Tanous     App& app, const crow::Request& req,
16991ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
17001ef4c342SEd Tanous {
17013ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
170245ca1b86SEd Tanous     {
170345ca1b86SEd Tanous         return;
170445ca1b86SEd Tanous     }
17054c7d4d33SEd Tanous     asyncResp->res.addHeader(
17064c7d4d33SEd Tanous         boost::beast::http::field::link,
17074c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17084c7d4d33SEd Tanous }
17094c7d4d33SEd Tanous 
17104c7d4d33SEd Tanous inline void handleAccountCollectionGet(
17114c7d4d33SEd Tanous     App& app, const crow::Request& req,
17124c7d4d33SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
17134c7d4d33SEd Tanous {
1714afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1715afd369c6SJiaqing Zhao     {
1716afd369c6SJiaqing Zhao         return;
1717afd369c6SJiaqing Zhao     }
17183e72c202SNinad Palsule 
17193e72c202SNinad Palsule     if (req.session == nullptr)
17203e72c202SNinad Palsule     {
17213e72c202SNinad Palsule         messages::internalError(asyncResp->res);
17223e72c202SNinad Palsule         return;
17233e72c202SNinad Palsule     }
17243e72c202SNinad Palsule 
1725afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
1726afd369c6SJiaqing Zhao         boost::beast::http::field::link,
1727afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccountCollection.json>; rel=describedby");
17281476687dSEd Tanous 
17291476687dSEd Tanous     asyncResp->res.jsonValue["@odata.id"] =
17301476687dSEd Tanous         "/redfish/v1/AccountService/Accounts";
17311ef4c342SEd Tanous     asyncResp->res.jsonValue["@odata.type"] = "#ManagerAccountCollection."
17321476687dSEd Tanous                                               "ManagerAccountCollection";
17331476687dSEd Tanous     asyncResp->res.jsonValue["Name"] = "Accounts Collection";
17341476687dSEd Tanous     asyncResp->res.jsonValue["Description"] = "BMC User Accounts";
17350f74e643SEd Tanous 
17366c51eab1SEd Tanous     Privileges effectiveUserPrivileges =
17373e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
17386c51eab1SEd Tanous 
1739f5e29f33SJunLin Chen     std::string thisUser;
1740f5e29f33SJunLin Chen     if (req.session)
1741f5e29f33SJunLin Chen     {
1742f5e29f33SJunLin Chen         thisUser = req.session->username;
1743f5e29f33SJunLin Chen     }
17445eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
17455eb468daSGeorge Liu     dbus::utility::getManagedObjects(
17465eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
1747cef1ddfbSEd Tanous         [asyncResp, thisUser, effectiveUserPrivileges](
17485e7e2dc5SEd Tanous             const boost::system::error_code& ec,
1749711ac7a9SEd Tanous             const dbus::utility::ManagedObjectType& users) {
1750b9b2e0b2SEd Tanous             if (ec)
1751b9b2e0b2SEd Tanous             {
1752f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
1753b9b2e0b2SEd Tanous                 return;
1754b9b2e0b2SEd Tanous             }
1755b9b2e0b2SEd Tanous 
1756cef1ddfbSEd Tanous             bool userCanSeeAllAccounts =
1757002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureUsers"});
1758cef1ddfbSEd Tanous 
1759cef1ddfbSEd Tanous             bool userCanSeeSelf =
1760002d39b4SEd Tanous                 effectiveUserPrivileges.isSupersetOf({"ConfigureSelf"});
1761cef1ddfbSEd Tanous 
1762002d39b4SEd Tanous             nlohmann::json& memberArray = asyncResp->res.jsonValue["Members"];
1763b9b2e0b2SEd Tanous             memberArray = nlohmann::json::array();
1764b9b2e0b2SEd Tanous 
17659eb808c1SEd Tanous             for (const auto& userpath : users)
1766b9b2e0b2SEd Tanous             {
17672dfd18efSEd Tanous                 std::string user = userpath.first.filename();
17682dfd18efSEd Tanous                 if (user.empty())
1769b9b2e0b2SEd Tanous                 {
17702dfd18efSEd Tanous                     messages::internalError(asyncResp->res);
177162598e31SEd Tanous                     BMCWEB_LOG_ERROR("Invalid firmware ID");
17722dfd18efSEd Tanous 
17732dfd18efSEd Tanous                     return;
1774b9b2e0b2SEd Tanous                 }
1775f365910cSGunnar Mills 
1776f365910cSGunnar Mills                 // As clarified by Redfish here:
1777f365910cSGunnar Mills                 // https://redfishforum.com/thread/281/manageraccountcollection-change-allows-account-enumeration
17786c51eab1SEd Tanous                 // Users without ConfigureUsers, only see their own
17796c51eab1SEd Tanous                 // account. Users with ConfigureUsers, see all
17806c51eab1SEd Tanous                 // accounts.
1781bd79bce8SPatrick Williams                 if (userCanSeeAllAccounts ||
1782bd79bce8SPatrick Williams                     (thisUser == user && userCanSeeSelf))
1783f365910cSGunnar Mills                 {
17841476687dSEd Tanous                     nlohmann::json::object_t member;
17853b32780dSEd Tanous                     member["@odata.id"] = boost::urls::format(
17863b32780dSEd Tanous                         "/redfish/v1/AccountService/Accounts/{}", user);
1787b2ba3072SPatrick Williams                     memberArray.emplace_back(std::move(member));
1788b9b2e0b2SEd Tanous                 }
1789f365910cSGunnar Mills             }
1790bd79bce8SPatrick Williams             asyncResp->res.jsonValue["Members@odata.count"] =
1791bd79bce8SPatrick Williams                 memberArray.size();
17925eb468daSGeorge Liu         });
17931ef4c342SEd Tanous }
17946c51eab1SEd Tanous 
179597e90da3SNinad Palsule inline void processAfterCreateUser(
179697e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
179797e90da3SNinad Palsule     const std::string& username, const std::string& password,
179897e90da3SNinad Palsule     const boost::system::error_code& ec, sdbusplus::message_t& m)
179997e90da3SNinad Palsule {
180097e90da3SNinad Palsule     if (ec)
180197e90da3SNinad Palsule     {
180297e90da3SNinad Palsule         userErrorMessageHandler(m.get_error(), asyncResp, username, "");
180397e90da3SNinad Palsule         return;
180497e90da3SNinad Palsule     }
180597e90da3SNinad Palsule 
180697e90da3SNinad Palsule     if (pamUpdatePassword(username, password) != PAM_SUCCESS)
180797e90da3SNinad Palsule     {
180897e90da3SNinad Palsule         // At this point we have a user that's been
180997e90da3SNinad Palsule         // created, but the password set
181097e90da3SNinad Palsule         // failed.Something is wrong, so delete the user
181197e90da3SNinad Palsule         // that we've already created
181297e90da3SNinad Palsule         sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
181397e90da3SNinad Palsule         tempObjPath /= username;
181497e90da3SNinad Palsule         const std::string userPath(tempObjPath);
181597e90da3SNinad Palsule 
181697e90da3SNinad Palsule         crow::connections::systemBus->async_method_call(
181797e90da3SNinad Palsule             [asyncResp, password](const boost::system::error_code& ec3) {
181897e90da3SNinad Palsule                 if (ec3)
181997e90da3SNinad Palsule                 {
182097e90da3SNinad Palsule                     messages::internalError(asyncResp->res);
182197e90da3SNinad Palsule                     return;
182297e90da3SNinad Palsule                 }
182397e90da3SNinad Palsule 
182497e90da3SNinad Palsule                 // If password is invalid
18259bd80831SJason M. Bills                 messages::propertyValueFormatError(asyncResp->res, nullptr,
182697e90da3SNinad Palsule                                                    "Password");
182797e90da3SNinad Palsule             },
182897e90da3SNinad Palsule             "xyz.openbmc_project.User.Manager", userPath,
182997e90da3SNinad Palsule             "xyz.openbmc_project.Object.Delete", "Delete");
183097e90da3SNinad Palsule 
183162598e31SEd Tanous         BMCWEB_LOG_ERROR("pamUpdatePassword Failed");
183297e90da3SNinad Palsule         return;
183397e90da3SNinad Palsule     }
183497e90da3SNinad Palsule 
183597e90da3SNinad Palsule     messages::created(asyncResp->res);
183697e90da3SNinad Palsule     asyncResp->res.addHeader("Location",
183797e90da3SNinad Palsule                              "/redfish/v1/AccountService/Accounts/" + username);
183897e90da3SNinad Palsule }
183997e90da3SNinad Palsule 
184097e90da3SNinad Palsule inline void processAfterGetAllGroups(
184197e90da3SNinad Palsule     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
184297e90da3SNinad Palsule     const std::string& username, const std::string& password,
1843e01d0c36SEd Tanous     const std::string& roleId, bool enabled,
18449ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes,
184597e90da3SNinad Palsule     const std::vector<std::string>& allGroupsList)
184697e90da3SNinad Palsule {
18473e72c202SNinad Palsule     std::vector<std::string> userGroups;
18489ba73934SNinad Palsule     std::vector<std::string> accountTypeUserGroups;
18499ba73934SNinad Palsule 
18509ba73934SNinad Palsule     // If user specified account types then convert them to unix user groups
18519ba73934SNinad Palsule     if (accountTypes)
18529ba73934SNinad Palsule     {
18539ba73934SNinad Palsule         if (!getUserGroupFromAccountType(asyncResp->res, *accountTypes,
18549ba73934SNinad Palsule                                          accountTypeUserGroups))
18559ba73934SNinad Palsule         {
18569ba73934SNinad Palsule             // Problem in mapping Account Types to User Groups, Error already
18579ba73934SNinad Palsule             // logged.
18589ba73934SNinad Palsule             return;
18599ba73934SNinad Palsule         }
18609ba73934SNinad Palsule     }
18619ba73934SNinad Palsule 
18623e72c202SNinad Palsule     for (const auto& grp : allGroupsList)
18633e72c202SNinad Palsule     {
18649ba73934SNinad Palsule         // If user specified the account type then only accept groups which are
18659ba73934SNinad Palsule         // in the account types group list.
18669ba73934SNinad Palsule         if (!accountTypeUserGroups.empty())
18679ba73934SNinad Palsule         {
18689ba73934SNinad Palsule             bool found = false;
18699ba73934SNinad Palsule             for (const auto& grp1 : accountTypeUserGroups)
18709ba73934SNinad Palsule             {
18719ba73934SNinad Palsule                 if (grp == grp1)
18729ba73934SNinad Palsule                 {
18739ba73934SNinad Palsule                     found = true;
18749ba73934SNinad Palsule                     break;
18759ba73934SNinad Palsule                 }
18769ba73934SNinad Palsule             }
18779ba73934SNinad Palsule             if (!found)
18789ba73934SNinad Palsule             {
18799ba73934SNinad Palsule                 continue;
18809ba73934SNinad Palsule             }
18819ba73934SNinad Palsule         }
18829ba73934SNinad Palsule 
18833e72c202SNinad Palsule         // Console access is provided to the user who is a member of
18843e72c202SNinad Palsule         // hostconsole group and has a administrator role. So, set
18853e72c202SNinad Palsule         // hostconsole group only for the administrator.
18869ba73934SNinad Palsule         if ((grp == "hostconsole") && (roleId != "priv-admin"))
18873e72c202SNinad Palsule         {
18889ba73934SNinad Palsule             if (!accountTypeUserGroups.empty())
18899ba73934SNinad Palsule             {
189062598e31SEd Tanous                 BMCWEB_LOG_ERROR(
189162598e31SEd Tanous                     "Only administrator can get HostConsole access");
18929ba73934SNinad Palsule                 asyncResp->res.result(boost::beast::http::status::bad_request);
18939ba73934SNinad Palsule                 return;
18949ba73934SNinad Palsule             }
18959ba73934SNinad Palsule             continue;
18969ba73934SNinad Palsule         }
18973e72c202SNinad Palsule         userGroups.emplace_back(grp);
18983e72c202SNinad Palsule     }
18999ba73934SNinad Palsule 
19009ba73934SNinad Palsule     // Make sure user specified groups are valid. This is internal error because
19019ba73934SNinad Palsule     // it some inconsistencies between user manager and bmcweb.
19029ba73934SNinad Palsule     if (!accountTypeUserGroups.empty() &&
19039ba73934SNinad Palsule         accountTypeUserGroups.size() != userGroups.size())
19049ba73934SNinad Palsule     {
19059ba73934SNinad Palsule         messages::internalError(asyncResp->res);
19069ba73934SNinad Palsule         return;
19073e72c202SNinad Palsule     }
190897e90da3SNinad Palsule     crow::connections::systemBus->async_method_call(
190997e90da3SNinad Palsule         [asyncResp, username, password](const boost::system::error_code& ec2,
191097e90da3SNinad Palsule                                         sdbusplus::message_t& m) {
191197e90da3SNinad Palsule             processAfterCreateUser(asyncResp, username, password, ec2, m);
191297e90da3SNinad Palsule         },
191397e90da3SNinad Palsule         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
19143e72c202SNinad Palsule         "xyz.openbmc_project.User.Manager", "CreateUser", username, userGroups,
1915e01d0c36SEd Tanous         roleId, enabled);
191697e90da3SNinad Palsule }
191797e90da3SNinad Palsule 
19181ef4c342SEd Tanous inline void handleAccountCollectionPost(
19191ef4c342SEd Tanous     App& app, const crow::Request& req,
19201ef4c342SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
19211ef4c342SEd Tanous {
19223ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
192345ca1b86SEd Tanous     {
192445ca1b86SEd Tanous         return;
192545ca1b86SEd Tanous     }
19269712f8acSEd Tanous     std::string username;
19279712f8acSEd Tanous     std::string password;
1928e01d0c36SEd Tanous     std::optional<std::string> roleIdJson;
1929e01d0c36SEd Tanous     std::optional<bool> enabledJson;
19309ba73934SNinad Palsule     std::optional<std::vector<std::string>> accountTypes;
1931afc474aeSMyung Bae     if (!json_util::readJsonPatch( //
1932afc474aeSMyung Bae             req, asyncResp->res, //
1933afc474aeSMyung Bae             "AccountTypes", accountTypes, //
1934afc474aeSMyung Bae             "Enabled", enabledJson, //
1935afc474aeSMyung Bae             "Password", password, //
1936afc474aeSMyung Bae             "RoleId", roleIdJson, //
1937afc474aeSMyung Bae             "UserName", username //
1938afc474aeSMyung Bae             ))
193904ae99ecSEd Tanous     {
194004ae99ecSEd Tanous         return;
194104ae99ecSEd Tanous     }
194204ae99ecSEd Tanous 
1943e01d0c36SEd Tanous     std::string roleId = roleIdJson.value_or("User");
1944e01d0c36SEd Tanous     std::string priv = getPrivilegeFromRoleId(roleId);
194584e12cb7SAppaRao Puli     if (priv.empty())
194604ae99ecSEd Tanous     {
1947e01d0c36SEd Tanous         messages::propertyValueNotInList(asyncResp->res, roleId, "RoleId");
194804ae99ecSEd Tanous         return;
194904ae99ecSEd Tanous     }
19509712f8acSEd Tanous     roleId = priv;
195104ae99ecSEd Tanous 
1952e01d0c36SEd Tanous     bool enabled = enabledJson.value_or(true);
1953e01d0c36SEd Tanous 
1954599c71d8SAyushi Smriti     // Reading AllGroups property
1955deae6a78SEd Tanous     dbus::utility::getProperty<std::vector<std::string>>(
1956deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
1957deae6a78SEd Tanous         "xyz.openbmc_project.User.Manager", "AllGroups",
19589ba73934SNinad Palsule         [asyncResp, username, password{std::move(password)}, roleId, enabled,
19599ba73934SNinad Palsule          accountTypes](const boost::system::error_code& ec,
19601e1e598dSJonathan Doman                        const std::vector<std::string>& allGroupsList) {
1961599c71d8SAyushi Smriti             if (ec)
1962599c71d8SAyushi Smriti             {
1963a0735a4eSGunnar Mills                 BMCWEB_LOG_ERROR("D-Bus response error {}", ec);
1964599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1965599c71d8SAyushi Smriti                 return;
1966599c71d8SAyushi Smriti             }
1967599c71d8SAyushi Smriti 
19681e1e598dSJonathan Doman             if (allGroupsList.empty())
1969599c71d8SAyushi Smriti             {
1970599c71d8SAyushi Smriti                 messages::internalError(asyncResp->res);
1971599c71d8SAyushi Smriti                 return;
1972599c71d8SAyushi Smriti             }
1973599c71d8SAyushi Smriti 
1974bd79bce8SPatrick Williams             processAfterGetAllGroups(asyncResp, username, password, roleId,
1975bd79bce8SPatrick Williams                                      enabled, accountTypes, allGroupsList);
19761e1e598dSJonathan Doman         });
19771ef4c342SEd Tanous }
1978b9b2e0b2SEd Tanous 
19791ef4c342SEd Tanous inline void
19804c7d4d33SEd Tanous     handleAccountHead(App& app, const crow::Request& req,
19816c51eab1SEd Tanous                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19824c7d4d33SEd Tanous                       const std::string& /*accountName*/)
19831ef4c342SEd Tanous {
19843ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
198545ca1b86SEd Tanous     {
198645ca1b86SEd Tanous         return;
198745ca1b86SEd Tanous     }
19884c7d4d33SEd Tanous     asyncResp->res.addHeader(
19894c7d4d33SEd Tanous         boost::beast::http::field::link,
19904c7d4d33SEd Tanous         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
19914c7d4d33SEd Tanous }
1992afd369c6SJiaqing Zhao 
19934c7d4d33SEd Tanous inline void
19944c7d4d33SEd Tanous     handleAccountGet(App& app, const crow::Request& req,
19954c7d4d33SEd Tanous                      const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
19964c7d4d33SEd Tanous                      const std::string& accountName)
19974c7d4d33SEd Tanous {
1998afd369c6SJiaqing Zhao     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1999afd369c6SJiaqing Zhao     {
2000afd369c6SJiaqing Zhao         return;
2001afd369c6SJiaqing Zhao     }
2002afd369c6SJiaqing Zhao     asyncResp->res.addHeader(
2003afd369c6SJiaqing Zhao         boost::beast::http::field::link,
2004afd369c6SJiaqing Zhao         "</redfish/v1/JsonSchemas/ManagerAccount/ManagerAccount.json>; rel=describedby");
2005afd369c6SJiaqing Zhao 
200625b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
200725b54dbaSEd Tanous     {
2008031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
200925b54dbaSEd Tanous         messages::resourceNotFound(asyncResp->res, "ManagerAccount",
201025b54dbaSEd Tanous                                    accountName);
2011031514fbSJunLin Chen         return;
201225b54dbaSEd Tanous     }
2013afd369c6SJiaqing Zhao 
2014031514fbSJunLin Chen     if (req.session == nullptr)
2015031514fbSJunLin Chen     {
2016031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2017031514fbSJunLin Chen         return;
2018031514fbSJunLin Chen     }
20196c51eab1SEd Tanous     if (req.session->username != accountName)
2020b9b2e0b2SEd Tanous     {
20216c51eab1SEd Tanous         // At this point we've determined that the user is trying to
20221ef4c342SEd Tanous         // modify a user that isn't them.  We need to verify that they
20231ef4c342SEd Tanous         // have permissions to modify other users, so re-run the auth
20241ef4c342SEd Tanous         // check with the same permissions, minus ConfigureSelf.
20256c51eab1SEd Tanous         Privileges effectiveUserPrivileges =
20263e72c202SNinad Palsule             redfish::getUserPrivileges(*req.session);
20271ef4c342SEd Tanous         Privileges requiredPermissionsToChangeNonSelf = {"ConfigureUsers",
20281ef4c342SEd Tanous                                                          "ConfigureManager"};
20296c51eab1SEd Tanous         if (!effectiveUserPrivileges.isSupersetOf(
20306c51eab1SEd Tanous                 requiredPermissionsToChangeNonSelf))
2031900f9497SJoseph Reynolds         {
203262598e31SEd Tanous             BMCWEB_LOG_DEBUG("GET Account denied access");
2033900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2034900f9497SJoseph Reynolds             return;
2035900f9497SJoseph Reynolds         }
2036900f9497SJoseph Reynolds     }
2037900f9497SJoseph Reynolds 
20385eb468daSGeorge Liu     sdbusplus::message::object_path path("/xyz/openbmc_project/user");
20395eb468daSGeorge Liu     dbus::utility::getManagedObjects(
20405eb468daSGeorge Liu         "xyz.openbmc_project.User.Manager", path,
20411ef4c342SEd Tanous         [asyncResp,
20425e7e2dc5SEd Tanous          accountName](const boost::system::error_code& ec,
2043711ac7a9SEd Tanous                       const dbus::utility::ManagedObjectType& users) {
2044b9b2e0b2SEd Tanous             if (ec)
2045b9b2e0b2SEd Tanous             {
2046f12894f8SJason M. Bills                 messages::internalError(asyncResp->res);
2047b9b2e0b2SEd Tanous                 return;
2048b9b2e0b2SEd Tanous             }
20493544d2a7SEd Tanous             const auto userIt = std::ranges::find_if(
205080f79a40SMichael Shen                 users,
205180f79a40SMichael Shen                 [accountName](
2052b477fd44SP Dheeraj Srujan Kumar                     const std::pair<sdbusplus::message::object_path,
205380f79a40SMichael Shen                                     dbus::utility::DBusInterfacesMap>& user) {
205455f79e6fSEd Tanous                     return accountName == user.first.filename();
2055b477fd44SP Dheeraj Srujan Kumar                 });
2056b9b2e0b2SEd Tanous 
205784e12cb7SAppaRao Puli             if (userIt == users.end())
2058b9b2e0b2SEd Tanous             {
2059002d39b4SEd Tanous                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
2060002d39b4SEd Tanous                                            accountName);
206184e12cb7SAppaRao Puli                 return;
206284e12cb7SAppaRao Puli             }
20634e68c45bSAyushi Smriti 
20641476687dSEd Tanous             asyncResp->res.jsonValue["@odata.type"] =
206558345856SAbhishek Patel                 "#ManagerAccount.v1_7_0.ManagerAccount";
20661476687dSEd Tanous             asyncResp->res.jsonValue["Name"] = "User Account";
20671476687dSEd Tanous             asyncResp->res.jsonValue["Description"] = "User Account";
20681476687dSEd Tanous             asyncResp->res.jsonValue["Password"] = nullptr;
206958345856SAbhishek Patel             asyncResp->res.jsonValue["StrictAccountTypes"] = true;
20704e68c45bSAyushi Smriti 
207184e12cb7SAppaRao Puli             for (const auto& interface : userIt->second)
207265b0dc32SEd Tanous             {
2073002d39b4SEd Tanous                 if (interface.first == "xyz.openbmc_project.User.Attributes")
207465b0dc32SEd Tanous                 {
2075b437a535SAsmitha Karunanithi                     const bool* userEnabled = nullptr;
2076b437a535SAsmitha Karunanithi                     const bool* userLocked = nullptr;
2077b437a535SAsmitha Karunanithi                     const std::string* userPrivPtr = nullptr;
2078b437a535SAsmitha Karunanithi                     const bool* userPasswordExpired = nullptr;
2079b437a535SAsmitha Karunanithi                     const std::vector<std::string>* userGroups = nullptr;
2080b437a535SAsmitha Karunanithi 
2081b437a535SAsmitha Karunanithi                     const bool success = sdbusplus::unpackPropertiesNoThrow(
2082b437a535SAsmitha Karunanithi                         dbus_utils::UnpackErrorPrinter(), interface.second,
2083b437a535SAsmitha Karunanithi                         "UserEnabled", userEnabled,
2084b437a535SAsmitha Karunanithi                         "UserLockedForFailedAttempt", userLocked,
2085b437a535SAsmitha Karunanithi                         "UserPrivilege", userPrivPtr, "UserPasswordExpired",
2086b437a535SAsmitha Karunanithi                         userPasswordExpired, "UserGroups", userGroups);
2087b437a535SAsmitha Karunanithi                     if (!success)
208865b0dc32SEd Tanous                     {
2089b437a535SAsmitha Karunanithi                         messages::internalError(asyncResp->res);
2090b437a535SAsmitha Karunanithi                         return;
2091b437a535SAsmitha Karunanithi                     }
209265b0dc32SEd Tanous                     if (userEnabled == nullptr)
209365b0dc32SEd Tanous                     {
209462598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserEnabled wasn't a bool");
209584e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
209684e12cb7SAppaRao Puli                         return;
209765b0dc32SEd Tanous                     }
2098002d39b4SEd Tanous                     asyncResp->res.jsonValue["Enabled"] = *userEnabled;
2099b437a535SAsmitha Karunanithi 
210065b0dc32SEd Tanous                     if (userLocked == nullptr)
210165b0dc32SEd Tanous                     {
210262598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserLockedForF"
210384e12cb7SAppaRao Puli                                          "ailedAttempt "
210462598e31SEd Tanous                                          "wasn't a bool");
210584e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
210684e12cb7SAppaRao Puli                         return;
210765b0dc32SEd Tanous                     }
2108002d39b4SEd Tanous                     asyncResp->res.jsonValue["Locked"] = *userLocked;
210920fa6a2cSEd Tanous                     nlohmann::json::array_t allowed;
211020fa6a2cSEd Tanous                     // can only unlock accounts
211120fa6a2cSEd Tanous                     allowed.emplace_back("false");
2112b437a535SAsmitha Karunanithi                     asyncResp->res.jsonValue["Locked@Redfish.AllowableValues"] =
211320fa6a2cSEd Tanous                         std::move(allowed);
2114b437a535SAsmitha Karunanithi 
211554fc587aSNagaraju Goruganti                     if (userPrivPtr == nullptr)
211684e12cb7SAppaRao Puli                     {
211762598e31SEd Tanous                         BMCWEB_LOG_ERROR("UserPrivilege wasn't a "
211862598e31SEd Tanous                                          "string");
211984e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
212084e12cb7SAppaRao Puli                         return;
212184e12cb7SAppaRao Puli                     }
2122b437a535SAsmitha Karunanithi                     std::string role = getRoleIdFromPrivilege(*userPrivPtr);
212354fc587aSNagaraju Goruganti                     if (role.empty())
212484e12cb7SAppaRao Puli                     {
212562598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid user role");
212684e12cb7SAppaRao Puli                         messages::internalError(asyncResp->res);
212784e12cb7SAppaRao Puli                         return;
212884e12cb7SAppaRao Puli                     }
212954fc587aSNagaraju Goruganti                     asyncResp->res.jsonValue["RoleId"] = role;
213084e12cb7SAppaRao Puli 
21311476687dSEd Tanous                     nlohmann::json& roleEntry =
2132002d39b4SEd Tanous                         asyncResp->res.jsonValue["Links"]["Role"];
21333b32780dSEd Tanous                     roleEntry["@odata.id"] = boost::urls::format(
21343b32780dSEd Tanous                         "/redfish/v1/AccountService/Roles/{}", role);
2135b437a535SAsmitha Karunanithi 
21363bf4e632SJoseph Reynolds                     if (userPasswordExpired == nullptr)
21373bf4e632SJoseph Reynolds                     {
2138b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("UserPasswordExpired wasn't a bool");
21393bf4e632SJoseph Reynolds                         messages::internalError(asyncResp->res);
21403bf4e632SJoseph Reynolds                         return;
21413bf4e632SJoseph Reynolds                     }
2142002d39b4SEd Tanous                     asyncResp->res.jsonValue["PasswordChangeRequired"] =
21433bf4e632SJoseph Reynolds                         *userPasswordExpired;
2144b437a535SAsmitha Karunanithi 
2145c7229815SAbhishek Patel                     if (userGroups == nullptr)
2146c7229815SAbhishek Patel                     {
2147b437a535SAsmitha Karunanithi                         BMCWEB_LOG_ERROR("userGroups wasn't a string vector");
2148c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2149c7229815SAbhishek Patel                         return;
2150c7229815SAbhishek Patel                     }
2151b437a535SAsmitha Karunanithi                     if (!translateUserGroup(*userGroups, asyncResp->res))
2152c7229815SAbhishek Patel                     {
215362598e31SEd Tanous                         BMCWEB_LOG_ERROR("userGroups mapping failed");
2154c7229815SAbhishek Patel                         messages::internalError(asyncResp->res);
2155c7229815SAbhishek Patel                         return;
2156c7229815SAbhishek Patel                     }
2157c7229815SAbhishek Patel                 }
215865b0dc32SEd Tanous             }
215965b0dc32SEd Tanous 
21603b32780dSEd Tanous             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
21613b32780dSEd Tanous                 "/redfish/v1/AccountService/Accounts/{}", accountName);
2162b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["Id"] = accountName;
2163b9b2e0b2SEd Tanous             asyncResp->res.jsonValue["UserName"] = accountName;
21645eb468daSGeorge Liu         });
21651ef4c342SEd Tanous }
2166a840879dSEd Tanous 
21671ef4c342SEd Tanous inline void
216820fc307fSGunnar Mills     handleAccountDelete(App& app, const crow::Request& req,
21696c51eab1SEd Tanous                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
21701ef4c342SEd Tanous                         const std::string& username)
21711ef4c342SEd Tanous {
21723ba00073SCarson Labrado     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
217345ca1b86SEd Tanous     {
217445ca1b86SEd Tanous         return;
217545ca1b86SEd Tanous     }
21761ef4c342SEd Tanous 
217725b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
217825b54dbaSEd Tanous     {
2179031514fbSJunLin Chen         // If authentication is disabled, there are no user accounts
2180d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
2181031514fbSJunLin Chen         return;
218225b54dbaSEd Tanous     }
21831ef4c342SEd Tanous     sdbusplus::message::object_path tempObjPath(rootUserDbusPath);
21841ef4c342SEd Tanous     tempObjPath /= username;
21851ef4c342SEd Tanous     const std::string userPath(tempObjPath);
21861ef4c342SEd Tanous 
21871ef4c342SEd Tanous     crow::connections::systemBus->async_method_call(
21885e7e2dc5SEd Tanous         [asyncResp, username](const boost::system::error_code& ec) {
21891ef4c342SEd Tanous             if (ec)
21901ef4c342SEd Tanous             {
2191d8a5d5d8SJiaqing Zhao                 messages::resourceNotFound(asyncResp->res, "ManagerAccount",
21921ef4c342SEd Tanous                                            username);
21931ef4c342SEd Tanous                 return;
21941ef4c342SEd Tanous             }
21951ef4c342SEd Tanous 
21961ef4c342SEd Tanous             messages::accountRemoved(asyncResp->res);
21971ef4c342SEd Tanous         },
21981ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", userPath,
21991ef4c342SEd Tanous         "xyz.openbmc_project.Object.Delete", "Delete");
22001ef4c342SEd Tanous }
22011ef4c342SEd Tanous 
22021ef4c342SEd Tanous inline void
22031ef4c342SEd Tanous     handleAccountPatch(App& app, const crow::Request& req,
22041ef4c342SEd Tanous                        const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
22051ef4c342SEd Tanous                        const std::string& username)
22061ef4c342SEd Tanous {
22071ef4c342SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
22081ef4c342SEd Tanous     {
22091ef4c342SEd Tanous         return;
22101ef4c342SEd Tanous     }
221125b54dbaSEd Tanous     if constexpr (BMCWEB_INSECURE_DISABLE_AUTH)
221225b54dbaSEd Tanous     {
22131ef4c342SEd Tanous         // If authentication is disabled, there are no user accounts
2214d8a5d5d8SJiaqing Zhao         messages::resourceNotFound(asyncResp->res, "ManagerAccount", username);
22151ef4c342SEd Tanous         return;
221625b54dbaSEd Tanous     }
2217a24526dcSEd Tanous     std::optional<std::string> newUserName;
2218a24526dcSEd Tanous     std::optional<std::string> password;
2219a24526dcSEd Tanous     std::optional<bool> enabled;
2220a24526dcSEd Tanous     std::optional<std::string> roleId;
222124c8542dSRatan Gupta     std::optional<bool> locked;
222258345856SAbhishek Patel     std::optional<std::vector<std::string>> accountTypes;
222358345856SAbhishek Patel 
2224031514fbSJunLin Chen     if (req.session == nullptr)
2225031514fbSJunLin Chen     {
2226031514fbSJunLin Chen         messages::internalError(asyncResp->res);
2227031514fbSJunLin Chen         return;
2228031514fbSJunLin Chen     }
2229031514fbSJunLin Chen 
22302b9c1dfeSEd Tanous     bool userSelf = (username == req.session->username);
22312b9c1dfeSEd Tanous 
2232e9cc5172SEd Tanous     Privileges effectiveUserPrivileges =
22333e72c202SNinad Palsule         redfish::getUserPrivileges(*req.session);
2234e9cc5172SEd Tanous     Privileges configureUsers = {"ConfigureUsers"};
2235e9cc5172SEd Tanous     bool userHasConfigureUsers =
2236e9cc5172SEd Tanous         effectiveUserPrivileges.isSupersetOf(configureUsers);
2237e9cc5172SEd Tanous     if (userHasConfigureUsers)
2238e9cc5172SEd Tanous     {
2239e9cc5172SEd Tanous         // Users with ConfigureUsers can modify for all users
2240afc474aeSMyung Bae         if (!json_util::readJsonPatch( //
2241afc474aeSMyung Bae                 req, asyncResp->res, //
2242afc474aeSMyung Bae                 "AccountTypes", accountTypes, //
2243afc474aeSMyung Bae                 "Enabled", enabled, //
2244afc474aeSMyung Bae                 "Locked", locked, //
2245afc474aeSMyung Bae                 "Password", password, //
2246afc474aeSMyung Bae                 "RoleId", roleId, //
2247afc474aeSMyung Bae                 "UserName", newUserName //
2248afc474aeSMyung Bae                 ))
2249a840879dSEd Tanous         {
2250a840879dSEd Tanous             return;
2251a840879dSEd Tanous         }
2252e9cc5172SEd Tanous     }
2253e9cc5172SEd Tanous     else
2254900f9497SJoseph Reynolds     {
2255e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their own account
225658345856SAbhishek Patel         if (!userSelf)
2257900f9497SJoseph Reynolds         {
2258900f9497SJoseph Reynolds             messages::insufficientPrivilege(asyncResp->res);
2259900f9497SJoseph Reynolds             return;
2260900f9497SJoseph Reynolds         }
2261031514fbSJunLin Chen 
2262e9cc5172SEd Tanous         // ConfigureSelf accounts can only modify their password
22631ef4c342SEd Tanous         if (!json_util::readJsonPatch(req, asyncResp->res, "Password",
22641ef4c342SEd Tanous                                       password))
2265e9cc5172SEd Tanous         {
2266e9cc5172SEd Tanous             return;
2267e9cc5172SEd Tanous         }
2268900f9497SJoseph Reynolds     }
2269900f9497SJoseph Reynolds 
227066b5ca76Sjayaprakash Mutyala     // if user name is not provided in the patch method or if it
22716c51eab1SEd Tanous     // matches the user name in the URI, then we are treating it as
22726c51eab1SEd Tanous     // updating user properties other then username. If username
22736c51eab1SEd Tanous     // provided doesn't match the URI, then we are treating this as
22746c51eab1SEd Tanous     // user rename request.
227566b5ca76Sjayaprakash Mutyala     if (!newUserName || (newUserName.value() == username))
2276a840879dSEd Tanous     {
22771ef4c342SEd Tanous         updateUserProperties(asyncResp, username, password, enabled, roleId,
2278e518ef32SRavi Teja                              locked, accountTypes, userSelf, req.session);
227984e12cb7SAppaRao Puli         return;
228084e12cb7SAppaRao Puli     }
228184e12cb7SAppaRao Puli     crow::connections::systemBus->async_method_call(
22826c51eab1SEd Tanous         [asyncResp, username, password(std::move(password)),
22831ef4c342SEd Tanous          roleId(std::move(roleId)), enabled, newUser{std::string(*newUserName)},
2284e518ef32SRavi Teja          locked, userSelf, req, accountTypes(std::move(accountTypes))](
2285e81de512SEd Tanous             const boost::system::error_code& ec, sdbusplus::message_t& m) {
228684e12cb7SAppaRao Puli             if (ec)
228784e12cb7SAppaRao Puli             {
2288002d39b4SEd Tanous                 userErrorMessageHandler(m.get_error(), asyncResp, newUser,
2289002d39b4SEd Tanous                                         username);
2290a840879dSEd Tanous                 return;
2291a840879dSEd Tanous             }
2292a840879dSEd Tanous 
2293002d39b4SEd Tanous             updateUserProperties(asyncResp, newUser, password, enabled, roleId,
2294e518ef32SRavi Teja                                  locked, accountTypes, userSelf, req.session);
229584e12cb7SAppaRao Puli         },
22961ef4c342SEd Tanous         "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
229784e12cb7SAppaRao Puli         "xyz.openbmc_project.User.Manager", "RenameUser", username,
229884e12cb7SAppaRao Puli         *newUserName);
22991ef4c342SEd Tanous }
23001ef4c342SEd Tanous 
23011ef4c342SEd Tanous inline void requestAccountServiceRoutes(App& app)
23021ef4c342SEd Tanous {
23031ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23044c7d4d33SEd Tanous         .privileges(redfish::privileges::headAccountService)
23054c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23064c7d4d33SEd Tanous             std::bind_front(handleAccountServiceHead, std::ref(app)));
23074c7d4d33SEd Tanous 
23084c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23091ef4c342SEd Tanous         .privileges(redfish::privileges::getAccountService)
23101ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23111ef4c342SEd Tanous             std::bind_front(handleAccountServiceGet, std::ref(app)));
23121ef4c342SEd Tanous 
23131ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/")
23141ef4c342SEd Tanous         .privileges(redfish::privileges::patchAccountService)
23151ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23161ef4c342SEd Tanous             std::bind_front(handleAccountServicePatch, std::ref(app)));
23171ef4c342SEd Tanous 
23181aa375b8SEd Tanous     BMCWEB_ROUTE(
23191aa375b8SEd Tanous         app,
2320e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23211aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificateCollection)
23221aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23231aa375b8SEd Tanous             handleAccountServiceClientCertificatesHead, std::ref(app)));
23241aa375b8SEd Tanous 
23251aa375b8SEd Tanous     BMCWEB_ROUTE(
23261aa375b8SEd Tanous         app,
2327e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/")
23281aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificateCollection)
23291aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23301aa375b8SEd Tanous             handleAccountServiceClientCertificatesGet, std::ref(app)));
23311aa375b8SEd Tanous 
23321aa375b8SEd Tanous     BMCWEB_ROUTE(
23331aa375b8SEd Tanous         app,
2334e9f12014SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23351aa375b8SEd Tanous         .privileges(redfish::privileges::headCertificate)
23361aa375b8SEd Tanous         .methods(boost::beast::http::verb::head)(std::bind_front(
23371aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceHead, std::ref(app)));
23381aa375b8SEd Tanous 
23391aa375b8SEd Tanous     BMCWEB_ROUTE(
23401aa375b8SEd Tanous         app,
23411aa375b8SEd Tanous         "/redfish/v1/AccountService/MultiFactorAuth/ClientCertificate/Certificates/<str>/")
23421aa375b8SEd Tanous         .privileges(redfish::privileges::getCertificate)
23431aa375b8SEd Tanous         .methods(boost::beast::http::verb::get)(std::bind_front(
23441aa375b8SEd Tanous             handleAccountServiceClientCertificatesInstanceGet, std::ref(app)));
23451aa375b8SEd Tanous 
23461ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23474c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccountCollection)
23484c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23494c7d4d33SEd Tanous             std::bind_front(handleAccountCollectionHead, std::ref(app)));
23504c7d4d33SEd Tanous 
23514c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23521ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccountCollection)
23531ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23541ef4c342SEd Tanous             std::bind_front(handleAccountCollectionGet, std::ref(app)));
23551ef4c342SEd Tanous 
23561ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
23571ef4c342SEd Tanous         .privileges(redfish::privileges::postManagerAccountCollection)
23581ef4c342SEd Tanous         .methods(boost::beast::http::verb::post)(
23591ef4c342SEd Tanous             std::bind_front(handleAccountCollectionPost, std::ref(app)));
23601ef4c342SEd Tanous 
23611ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23624c7d4d33SEd Tanous         .privileges(redfish::privileges::headManagerAccount)
23634c7d4d33SEd Tanous         .methods(boost::beast::http::verb::head)(
23644c7d4d33SEd Tanous             std::bind_front(handleAccountHead, std::ref(app)));
23654c7d4d33SEd Tanous 
23664c7d4d33SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23671ef4c342SEd Tanous         .privileges(redfish::privileges::getManagerAccount)
23681ef4c342SEd Tanous         .methods(boost::beast::http::verb::get)(
23691ef4c342SEd Tanous             std::bind_front(handleAccountGet, std::ref(app)));
23701ef4c342SEd Tanous 
23711ef4c342SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
23721ef4c342SEd Tanous         // TODO this privilege should be using the generated endpoints, but
23731ef4c342SEd Tanous         // because of the special handling of ConfigureSelf, it's not able to
23741ef4c342SEd Tanous         // yet
23751ef4c342SEd Tanous         .privileges({{"ConfigureUsers"}, {"ConfigureSelf"}})
23761ef4c342SEd Tanous         .methods(boost::beast::http::verb::patch)(
23771ef4c342SEd Tanous             std::bind_front(handleAccountPatch, std::ref(app)));
237884e12cb7SAppaRao Puli 
23796c51eab1SEd Tanous     BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
2380ed398213SEd Tanous         .privileges(redfish::privileges::deleteManagerAccount)
23816c51eab1SEd Tanous         .methods(boost::beast::http::verb::delete_)(
238220fc307fSGunnar Mills             std::bind_front(handleAccountDelete, std::ref(app)));
238306e086d9SEd Tanous }
238488d16c9aSLewanczyk, Dawid 
238588d16c9aSLewanczyk, Dawid } // namespace redfish
2386