xref: /openbmc/bmcweb/features/redfish/include/utils/query_param.hpp (revision 102a4cdacb0a6d8c8c3c97e10bedbb66000ac5dc)
1f4c99e70SEd Tanous #pragma once
2d5c80ad9SNan Zhou #include "bmcweb_config.h"
3d5c80ad9SNan Zhou 
4f4c99e70SEd Tanous #include "app.hpp"
5f4c99e70SEd Tanous #include "async_resp.hpp"
6f4c99e70SEd Tanous #include "error_messages.hpp"
7f4c99e70SEd Tanous #include "http_request.hpp"
802cad96eSEd Tanous #include "http_response.hpp"
995c6307aSEd Tanous #include "json_formatters.hpp"
10d5c80ad9SNan Zhou #include "logging.hpp"
1150ebd4afSEd Tanous #include "str_utility.hpp"
12f4c99e70SEd Tanous 
13d5c80ad9SNan Zhou #include <sys/types.h>
14d5c80ad9SNan Zhou 
15d5c80ad9SNan Zhou #include <boost/beast/http/message.hpp> // IWYU pragma: keep
16d5c80ad9SNan Zhou #include <boost/beast/http/status.hpp>
17d5c80ad9SNan Zhou #include <boost/beast/http/verb.hpp>
18d5c80ad9SNan Zhou #include <boost/url/params_view.hpp>
19d5c80ad9SNan Zhou #include <nlohmann/json.hpp>
20d5c80ad9SNan Zhou 
21d5c80ad9SNan Zhou #include <algorithm>
22e155ab54SNan Zhou #include <array>
23e155ab54SNan Zhou #include <cctype>
247cf436c9SEd Tanous #include <charconv>
25827c4902SNan Zhou #include <compare>
26d5c80ad9SNan Zhou #include <cstdint>
27d5c80ad9SNan Zhou #include <functional>
28e155ab54SNan Zhou #include <iterator>
29d5c80ad9SNan Zhou #include <limits>
30d5c80ad9SNan Zhou #include <map>
31d5c80ad9SNan Zhou #include <memory>
32d5c80ad9SNan Zhou #include <optional>
333544d2a7SEd Tanous #include <ranges>
34f4c99e70SEd Tanous #include <string>
35f4c99e70SEd Tanous #include <string_view>
36d5c80ad9SNan Zhou #include <system_error>
377cf436c9SEd Tanous #include <utility>
38f4c99e70SEd Tanous #include <vector>
39f4c99e70SEd Tanous 
40d5c80ad9SNan Zhou // IWYU pragma: no_include <boost/url/impl/params_view.hpp>
41d5c80ad9SNan Zhou // IWYU pragma: no_include <boost/beast/http/impl/message.hpp>
42d5c80ad9SNan Zhou // IWYU pragma: no_include <boost/intrusive/detail/list_iterator.hpp>
43e155ab54SNan Zhou // IWYU pragma: no_include <boost/algorithm/string/detail/classification.hpp>
44e155ab54SNan Zhou // IWYU pragma: no_include <boost/iterator/iterator_facade.hpp>
45e155ab54SNan Zhou // IWYU pragma: no_include <boost/type_index/type_index_facade.hpp>
46d5c80ad9SNan Zhou // IWYU pragma: no_include <stdint.h>
47d5c80ad9SNan Zhou 
48f4c99e70SEd Tanous namespace redfish
49f4c99e70SEd Tanous {
50f4c99e70SEd Tanous namespace query_param
51f4c99e70SEd Tanous {
52f4c99e70SEd Tanous 
537cf436c9SEd Tanous enum class ExpandType : uint8_t
547cf436c9SEd Tanous {
557cf436c9SEd Tanous     None,
567cf436c9SEd Tanous     Links,
577cf436c9SEd Tanous     NotLinks,
587cf436c9SEd Tanous     Both,
597cf436c9SEd Tanous };
607cf436c9SEd Tanous 
61827c4902SNan Zhou // A simple implementation of Trie to help |recursiveSelect|.
62827c4902SNan Zhou class SelectTrieNode
63827c4902SNan Zhou {
64827c4902SNan Zhou   public:
65827c4902SNan Zhou     SelectTrieNode() = default;
66827c4902SNan Zhou 
67827c4902SNan Zhou     const SelectTrieNode* find(const std::string& jsonKey) const
68827c4902SNan Zhou     {
69827c4902SNan Zhou         auto it = children.find(jsonKey);
70827c4902SNan Zhou         if (it == children.end())
71827c4902SNan Zhou         {
72827c4902SNan Zhou             return nullptr;
73827c4902SNan Zhou         }
74827c4902SNan Zhou         return &it->second;
75827c4902SNan Zhou     }
76827c4902SNan Zhou 
77827c4902SNan Zhou     // Creates a new node if the key doesn't exist, returns the reference to the
78827c4902SNan Zhou     // newly created node; otherwise, return the reference to the existing node
79827c4902SNan Zhou     SelectTrieNode* emplace(std::string_view jsonKey)
80827c4902SNan Zhou     {
81827c4902SNan Zhou         auto [it, _] = children.emplace(jsonKey, SelectTrieNode{});
82827c4902SNan Zhou         return &it->second;
83827c4902SNan Zhou     }
84827c4902SNan Zhou 
85827c4902SNan Zhou     bool empty() const
86827c4902SNan Zhou     {
87827c4902SNan Zhou         return children.empty();
88827c4902SNan Zhou     }
89827c4902SNan Zhou 
90827c4902SNan Zhou     void clear()
91827c4902SNan Zhou     {
92827c4902SNan Zhou         children.clear();
93827c4902SNan Zhou     }
94827c4902SNan Zhou 
95827c4902SNan Zhou     void setToSelected()
96827c4902SNan Zhou     {
97827c4902SNan Zhou         selected = true;
98827c4902SNan Zhou     }
99827c4902SNan Zhou 
100827c4902SNan Zhou     bool isSelected() const
101827c4902SNan Zhou     {
102827c4902SNan Zhou         return selected;
103827c4902SNan Zhou     }
104827c4902SNan Zhou 
105827c4902SNan Zhou   private:
106827c4902SNan Zhou     std::map<std::string, SelectTrieNode, std::less<>> children;
107827c4902SNan Zhou     bool selected = false;
108827c4902SNan Zhou };
109827c4902SNan Zhou 
110827c4902SNan Zhou // Validates the property in the $select parameter. Every character is among
111827c4902SNan Zhou // [a-zA-Z0-9#@_.] (taken from Redfish spec, section 9.6 Properties)
112827c4902SNan Zhou inline bool isSelectedPropertyAllowed(std::string_view property)
113827c4902SNan Zhou {
114827c4902SNan Zhou     // These a magic number, but with it it's less likely that this code
115827c4902SNan Zhou     // introduces CVE; e.g., too large properties crash the service.
116827c4902SNan Zhou     constexpr int maxPropertyLength = 60;
117827c4902SNan Zhou     if (property.empty() || property.size() > maxPropertyLength)
118827c4902SNan Zhou     {
119827c4902SNan Zhou         return false;
120827c4902SNan Zhou     }
121827c4902SNan Zhou     for (char ch : property)
122827c4902SNan Zhou     {
123827c4902SNan Zhou         if (std::isalnum(static_cast<unsigned char>(ch)) == 0 && ch != '#' &&
124827c4902SNan Zhou             ch != '@' && ch != '.')
125827c4902SNan Zhou         {
126827c4902SNan Zhou             return false;
127827c4902SNan Zhou         }
128827c4902SNan Zhou     }
129827c4902SNan Zhou     return true;
130827c4902SNan Zhou }
131827c4902SNan Zhou 
132827c4902SNan Zhou struct SelectTrie
133827c4902SNan Zhou {
134827c4902SNan Zhou     SelectTrie() = default;
135827c4902SNan Zhou 
136827c4902SNan Zhou     // Inserts a $select value; returns false if the nestedProperty is illegal.
137827c4902SNan Zhou     bool insertNode(std::string_view nestedProperty)
138827c4902SNan Zhou     {
139827c4902SNan Zhou         if (nestedProperty.empty())
140827c4902SNan Zhou         {
141827c4902SNan Zhou             return false;
142827c4902SNan Zhou         }
143827c4902SNan Zhou         SelectTrieNode* currNode = &root;
144827c4902SNan Zhou         size_t index = nestedProperty.find_first_of('/');
145827c4902SNan Zhou         while (!nestedProperty.empty())
146827c4902SNan Zhou         {
147827c4902SNan Zhou             std::string_view property = nestedProperty.substr(0, index);
148827c4902SNan Zhou             if (!isSelectedPropertyAllowed(property))
149827c4902SNan Zhou             {
150827c4902SNan Zhou                 return false;
151827c4902SNan Zhou             }
152827c4902SNan Zhou             currNode = currNode->emplace(property);
153827c4902SNan Zhou             if (index == std::string::npos)
154827c4902SNan Zhou             {
155827c4902SNan Zhou                 break;
156827c4902SNan Zhou             }
157827c4902SNan Zhou             nestedProperty.remove_prefix(index + 1);
158827c4902SNan Zhou             index = nestedProperty.find_first_of('/');
159827c4902SNan Zhou         }
160827c4902SNan Zhou         currNode->setToSelected();
161827c4902SNan Zhou         return true;
162827c4902SNan Zhou     }
163827c4902SNan Zhou 
164827c4902SNan Zhou     SelectTrieNode root;
165827c4902SNan Zhou };
166827c4902SNan Zhou 
167a6b9125fSNan Zhou // The struct stores the parsed query parameters of the default Redfish route.
168f4c99e70SEd Tanous struct Query
169f4c99e70SEd Tanous {
170a6b9125fSNan Zhou     // Only
171f4c99e70SEd Tanous     bool isOnly = false;
172a6b9125fSNan Zhou     // Expand
173a6b9125fSNan Zhou     uint8_t expandLevel = 0;
1747cf436c9SEd Tanous     ExpandType expandType = ExpandType::None;
175c937d2bfSEd Tanous 
176c937d2bfSEd Tanous     // Skip
1773648c8beSEd Tanous     std::optional<size_t> skip = std::nullopt;
178c937d2bfSEd Tanous 
179c937d2bfSEd Tanous     // Top
1805143f7a5SJiaqing Zhao     static constexpr size_t maxTop = 1000; // Max entries a response contain
1813648c8beSEd Tanous     std::optional<size_t> top = std::nullopt;
182e155ab54SNan Zhou 
183e155ab54SNan Zhou     // Select
18447f2934cSEd Tanous     // Unclear how to make this use structured initialization without this.
18547f2934cSEd Tanous     // Might be a tidy bug?  Ignore for now
18647f2934cSEd Tanous     // NOLINTNEXTLINE(readability-redundant-member-init)
18747f2934cSEd Tanous     SelectTrie selectTrie{};
188f4c99e70SEd Tanous };
189f4c99e70SEd Tanous 
190a6b9125fSNan Zhou // The struct defines how resource handlers in redfish-core/lib/ can handle
191a6b9125fSNan Zhou // query parameters themselves, so that the default Redfish route will delegate
192a6b9125fSNan Zhou // the processing.
193a6b9125fSNan Zhou struct QueryCapabilities
194a6b9125fSNan Zhou {
195a6b9125fSNan Zhou     bool canDelegateOnly = false;
196c937d2bfSEd Tanous     bool canDelegateTop = false;
197c937d2bfSEd Tanous     bool canDelegateSkip = false;
198a6b9125fSNan Zhou     uint8_t canDelegateExpandLevel = 0;
199e155ab54SNan Zhou     bool canDelegateSelect = false;
200a6b9125fSNan Zhou };
201a6b9125fSNan Zhou 
202a6b9125fSNan Zhou // Delegates query parameters according to the given |queryCapabilities|
203a6b9125fSNan Zhou // This function doesn't check query parameter conflicts since the parse
204a6b9125fSNan Zhou // function will take care of it.
205a6b9125fSNan Zhou // Returns a delegated query object which can be used by individual resource
206a6b9125fSNan Zhou // handlers so that handlers don't need to query again.
207a6b9125fSNan Zhou inline Query delegate(const QueryCapabilities& queryCapabilities, Query& query)
208a6b9125fSNan Zhou {
209f1a1e3dcSEd Tanous     Query delegated{};
210a6b9125fSNan Zhou     // delegate only
211a6b9125fSNan Zhou     if (query.isOnly && queryCapabilities.canDelegateOnly)
212a6b9125fSNan Zhou     {
213a6b9125fSNan Zhou         delegated.isOnly = true;
214a6b9125fSNan Zhou         query.isOnly = false;
215a6b9125fSNan Zhou     }
216a6b9125fSNan Zhou     // delegate expand as much as we can
217a6b9125fSNan Zhou     if (query.expandType != ExpandType::None)
218a6b9125fSNan Zhou     {
219a6b9125fSNan Zhou         delegated.expandType = query.expandType;
220a6b9125fSNan Zhou         if (query.expandLevel <= queryCapabilities.canDelegateExpandLevel)
221a6b9125fSNan Zhou         {
222a6b9125fSNan Zhou             query.expandType = ExpandType::None;
223a6b9125fSNan Zhou             delegated.expandLevel = query.expandLevel;
224a6b9125fSNan Zhou             query.expandLevel = 0;
225a6b9125fSNan Zhou         }
226a6b9125fSNan Zhou         else
227a6b9125fSNan Zhou         {
228a6b9125fSNan Zhou             delegated.expandLevel = queryCapabilities.canDelegateExpandLevel;
229a6b9125fSNan Zhou         }
230a6b9125fSNan Zhou     }
231c937d2bfSEd Tanous 
232c937d2bfSEd Tanous     // delegate top
2333648c8beSEd Tanous     if (query.top && queryCapabilities.canDelegateTop)
234c937d2bfSEd Tanous     {
235c937d2bfSEd Tanous         delegated.top = query.top;
2363648c8beSEd Tanous         query.top = std::nullopt;
237c937d2bfSEd Tanous     }
238c937d2bfSEd Tanous 
239c937d2bfSEd Tanous     // delegate skip
2403648c8beSEd Tanous     if (query.skip && queryCapabilities.canDelegateSkip)
241c937d2bfSEd Tanous     {
242c937d2bfSEd Tanous         delegated.skip = query.skip;
243c937d2bfSEd Tanous         query.skip = 0;
244c937d2bfSEd Tanous     }
245e155ab54SNan Zhou 
246e155ab54SNan Zhou     // delegate select
247827c4902SNan Zhou     if (!query.selectTrie.root.empty() && queryCapabilities.canDelegateSelect)
248e155ab54SNan Zhou     {
249827c4902SNan Zhou         delegated.selectTrie = std::move(query.selectTrie);
250827c4902SNan Zhou         query.selectTrie.root.clear();
251e155ab54SNan Zhou     }
252a6b9125fSNan Zhou     return delegated;
253a6b9125fSNan Zhou }
254a6b9125fSNan Zhou 
2557cf436c9SEd Tanous inline bool getExpandType(std::string_view value, Query& query)
2567cf436c9SEd Tanous {
2577cf436c9SEd Tanous     if (value.empty())
2587cf436c9SEd Tanous     {
2597cf436c9SEd Tanous         return false;
2607cf436c9SEd Tanous     }
2617cf436c9SEd Tanous     switch (value[0])
2627cf436c9SEd Tanous     {
2637cf436c9SEd Tanous         case '*':
2647cf436c9SEd Tanous             query.expandType = ExpandType::Both;
2657cf436c9SEd Tanous             break;
2667cf436c9SEd Tanous         case '.':
2677cf436c9SEd Tanous             query.expandType = ExpandType::NotLinks;
2687cf436c9SEd Tanous             break;
2697cf436c9SEd Tanous         case '~':
2707cf436c9SEd Tanous             query.expandType = ExpandType::Links;
2717cf436c9SEd Tanous             break;
2727cf436c9SEd Tanous         default:
2737cf436c9SEd Tanous             return false;
2747cf436c9SEd Tanous     }
2757cf436c9SEd Tanous     value.remove_prefix(1);
2767cf436c9SEd Tanous     if (value.empty())
2777cf436c9SEd Tanous     {
2787cf436c9SEd Tanous         query.expandLevel = 1;
2797cf436c9SEd Tanous         return true;
2807cf436c9SEd Tanous     }
2817cf436c9SEd Tanous     constexpr std::string_view levels = "($levels=";
2827cf436c9SEd Tanous     if (!value.starts_with(levels))
2837cf436c9SEd Tanous     {
2847cf436c9SEd Tanous         return false;
2857cf436c9SEd Tanous     }
2867cf436c9SEd Tanous     value.remove_prefix(levels.size());
2877cf436c9SEd Tanous 
2882bd4ab43SPatrick Williams     auto it = std::from_chars(value.begin(), value.end(), query.expandLevel);
2897cf436c9SEd Tanous     if (it.ec != std::errc())
2907cf436c9SEd Tanous     {
2917cf436c9SEd Tanous         return false;
2927cf436c9SEd Tanous     }
2932bd4ab43SPatrick Williams     value.remove_prefix(
2942bd4ab43SPatrick Williams         static_cast<size_t>(std::distance(value.begin(), it.ptr)));
2957cf436c9SEd Tanous     return value == ")";
2967cf436c9SEd Tanous }
2977cf436c9SEd Tanous 
298c937d2bfSEd Tanous enum class QueryError
299c937d2bfSEd Tanous {
300c937d2bfSEd Tanous     Ok,
301c937d2bfSEd Tanous     OutOfRange,
302c937d2bfSEd Tanous     ValueFormat,
303c937d2bfSEd Tanous };
304c937d2bfSEd Tanous 
305c937d2bfSEd Tanous inline QueryError getNumericParam(std::string_view value, size_t& param)
306c937d2bfSEd Tanous {
3072bd4ab43SPatrick Williams     std::from_chars_result r = std::from_chars(value.begin(), value.end(),
3082bd4ab43SPatrick Williams                                                param);
309c937d2bfSEd Tanous 
310c937d2bfSEd Tanous     // If the number wasn't representable in the type, it's out of range
311c937d2bfSEd Tanous     if (r.ec == std::errc::result_out_of_range)
312c937d2bfSEd Tanous     {
313c937d2bfSEd Tanous         return QueryError::OutOfRange;
314c937d2bfSEd Tanous     }
315c937d2bfSEd Tanous     // All other errors are value format
316c937d2bfSEd Tanous     if (r.ec != std::errc())
317c937d2bfSEd Tanous     {
318c937d2bfSEd Tanous         return QueryError::ValueFormat;
319c937d2bfSEd Tanous     }
320c937d2bfSEd Tanous     return QueryError::Ok;
321c937d2bfSEd Tanous }
322c937d2bfSEd Tanous 
323c937d2bfSEd Tanous inline QueryError getSkipParam(std::string_view value, Query& query)
324c937d2bfSEd Tanous {
3253648c8beSEd Tanous     return getNumericParam(value, query.skip.emplace());
326c937d2bfSEd Tanous }
327c937d2bfSEd Tanous 
328c937d2bfSEd Tanous inline QueryError getTopParam(std::string_view value, Query& query)
329c937d2bfSEd Tanous {
3303648c8beSEd Tanous     QueryError ret = getNumericParam(value, query.top.emplace());
331c937d2bfSEd Tanous     if (ret != QueryError::Ok)
332c937d2bfSEd Tanous     {
333c937d2bfSEd Tanous         return ret;
334c937d2bfSEd Tanous     }
335c937d2bfSEd Tanous 
336c937d2bfSEd Tanous     // Range check for sanity.
3375143f7a5SJiaqing Zhao     if (query.top > Query::maxTop)
338c937d2bfSEd Tanous     {
339c937d2bfSEd Tanous         return QueryError::OutOfRange;
340c937d2bfSEd Tanous     }
341c937d2bfSEd Tanous 
342c937d2bfSEd Tanous     return QueryError::Ok;
343c937d2bfSEd Tanous }
344c937d2bfSEd Tanous 
345e155ab54SNan Zhou // Parses and validates the $select parameter.
346e155ab54SNan Zhou // As per OData URL Conventions and Redfish Spec, the $select values shall be
347e155ab54SNan Zhou // comma separated Resource Path
348e155ab54SNan Zhou // Ref:
349e155ab54SNan Zhou // 1. https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
350e155ab54SNan Zhou // 2.
351e155ab54SNan Zhou // https://docs.oasis-open.org/odata/odata/v4.01/os/abnf/odata-abnf-construction-rules.txt
352e155ab54SNan Zhou inline bool getSelectParam(std::string_view value, Query& query)
353e155ab54SNan Zhou {
354e155ab54SNan Zhou     std::vector<std::string> properties;
35550ebd4afSEd Tanous     bmcweb::split(properties, value, ',');
356e155ab54SNan Zhou     if (properties.empty())
357e155ab54SNan Zhou     {
358e155ab54SNan Zhou         return false;
359e155ab54SNan Zhou     }
360e155ab54SNan Zhou     // These a magic number, but with it it's less likely that this code
361e155ab54SNan Zhou     // introduces CVE; e.g., too large properties crash the service.
362e155ab54SNan Zhou     constexpr int maxNumProperties = 10;
363e155ab54SNan Zhou     if (properties.size() > maxNumProperties)
364e155ab54SNan Zhou     {
365e155ab54SNan Zhou         return false;
366e155ab54SNan Zhou     }
367827c4902SNan Zhou     for (const auto& property : properties)
368e155ab54SNan Zhou     {
369827c4902SNan Zhou         if (!query.selectTrie.insertNode(property))
370e155ab54SNan Zhou         {
371e155ab54SNan Zhou             return false;
372e155ab54SNan Zhou         }
373e155ab54SNan Zhou     }
374e155ab54SNan Zhou     return true;
375e155ab54SNan Zhou }
376e155ab54SNan Zhou 
377079360aeSEd Tanous inline std::optional<Query> parseParameters(boost::urls::params_view urlParams,
378f4c99e70SEd Tanous                                             crow::Response& res)
379f4c99e70SEd Tanous {
380f1a1e3dcSEd Tanous     Query ret{};
381f4c99e70SEd Tanous     for (const boost::urls::params_view::value_type& it : urlParams)
382f4c99e70SEd Tanous     {
383079360aeSEd Tanous         if (it.key == "only")
384f4c99e70SEd Tanous         {
385f4c99e70SEd Tanous             if (!it.value.empty())
386f4c99e70SEd Tanous             {
387079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
388f4c99e70SEd Tanous                 return std::nullopt;
389f4c99e70SEd Tanous             }
390f4c99e70SEd Tanous             ret.isOnly = true;
391f4c99e70SEd Tanous         }
39225b54dbaSEd Tanous         else if (it.key == "$expand" && BMCWEB_INSECURE_ENABLE_REDFISH_QUERY)
3937cf436c9SEd Tanous         {
394079360aeSEd Tanous             if (!getExpandType(it.value, ret))
3957cf436c9SEd Tanous             {
396079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
3977cf436c9SEd Tanous                 return std::nullopt;
398f4c99e70SEd Tanous             }
3997cf436c9SEd Tanous         }
400079360aeSEd Tanous         else if (it.key == "$top")
401c937d2bfSEd Tanous         {
402079360aeSEd Tanous             QueryError topRet = getTopParam(it.value, ret);
403c937d2bfSEd Tanous             if (topRet == QueryError::ValueFormat)
404c937d2bfSEd Tanous             {
405079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
406c937d2bfSEd Tanous                 return std::nullopt;
407c937d2bfSEd Tanous             }
408c937d2bfSEd Tanous             if (topRet == QueryError::OutOfRange)
409c937d2bfSEd Tanous             {
410c937d2bfSEd Tanous                 messages::queryParameterOutOfRange(
411079360aeSEd Tanous                     res, it.value, "$top",
412079360aeSEd Tanous                     "0-" + std::to_string(Query::maxTop));
413c937d2bfSEd Tanous                 return std::nullopt;
414c937d2bfSEd Tanous             }
415c937d2bfSEd Tanous         }
416079360aeSEd Tanous         else if (it.key == "$skip")
417c937d2bfSEd Tanous         {
418079360aeSEd Tanous             QueryError topRet = getSkipParam(it.value, ret);
419c937d2bfSEd Tanous             if (topRet == QueryError::ValueFormat)
420c937d2bfSEd Tanous             {
421079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
422c937d2bfSEd Tanous                 return std::nullopt;
423c937d2bfSEd Tanous             }
424c937d2bfSEd Tanous             if (topRet == QueryError::OutOfRange)
425c937d2bfSEd Tanous             {
426c937d2bfSEd Tanous                 messages::queryParameterOutOfRange(
427079360aeSEd Tanous                     res, it.value, it.key,
428a926c53eSJiaqing Zhao                     "0-" + std::to_string(std::numeric_limits<size_t>::max()));
429c937d2bfSEd Tanous                 return std::nullopt;
430c937d2bfSEd Tanous             }
431c937d2bfSEd Tanous         }
432079360aeSEd Tanous         else if (it.key == "$select")
433e155ab54SNan Zhou         {
434079360aeSEd Tanous             if (!getSelectParam(it.value, ret))
435e155ab54SNan Zhou             {
436079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
437e155ab54SNan Zhou                 return std::nullopt;
438e155ab54SNan Zhou             }
439e155ab54SNan Zhou         }
4407cf436c9SEd Tanous         else
4417cf436c9SEd Tanous         {
4427cf436c9SEd Tanous             // Intentionally ignore other errors Redfish spec, 7.3.1
443079360aeSEd Tanous             if (it.key.starts_with("$"))
4447cf436c9SEd Tanous             {
4457cf436c9SEd Tanous                 // Services shall return... The HTTP 501 Not Implemented
4467cf436c9SEd Tanous                 // status code for any unsupported query parameters that
4477cf436c9SEd Tanous                 // start with $ .
448079360aeSEd Tanous                 messages::queryParameterValueFormatError(res, it.value, it.key);
4497cf436c9SEd Tanous                 res.result(boost::beast::http::status::not_implemented);
4507cf436c9SEd Tanous                 return std::nullopt;
4517cf436c9SEd Tanous             }
4527cf436c9SEd Tanous             // "Shall ignore unknown or unsupported query parameters that do
4537cf436c9SEd Tanous             // not begin with $ ."
4547cf436c9SEd Tanous         }
4557cf436c9SEd Tanous     }
4567cf436c9SEd Tanous 
457827c4902SNan Zhou     if (ret.expandType != ExpandType::None && !ret.selectTrie.root.empty())
458e155ab54SNan Zhou     {
459e155ab54SNan Zhou         messages::queryCombinationInvalid(res);
460e155ab54SNan Zhou         return std::nullopt;
461e155ab54SNan Zhou     }
462e155ab54SNan Zhou 
463f4c99e70SEd Tanous     return ret;
464f4c99e70SEd Tanous }
465f4c99e70SEd Tanous 
466f4c99e70SEd Tanous inline bool processOnly(crow::App& app, crow::Response& res,
467f4c99e70SEd Tanous                         std::function<void(crow::Response&)>& completionHandler)
468f4c99e70SEd Tanous {
46962598e31SEd Tanous     BMCWEB_LOG_DEBUG("Processing only query param");
470f4c99e70SEd Tanous     auto itMembers = res.jsonValue.find("Members");
471f4c99e70SEd Tanous     if (itMembers == res.jsonValue.end())
472f4c99e70SEd Tanous     {
473f4c99e70SEd Tanous         messages::queryNotSupportedOnResource(res);
474f4c99e70SEd Tanous         completionHandler(res);
475f4c99e70SEd Tanous         return false;
476f4c99e70SEd Tanous     }
477f4c99e70SEd Tanous     auto itMemBegin = itMembers->begin();
478f4c99e70SEd Tanous     if (itMemBegin == itMembers->end() || itMembers->size() != 1)
479f4c99e70SEd Tanous     {
48062598e31SEd Tanous         BMCWEB_LOG_DEBUG(
48162598e31SEd Tanous             "Members contains {} element, returning full collection.",
48262598e31SEd Tanous             itMembers->size());
483f4c99e70SEd Tanous         completionHandler(res);
484f4c99e70SEd Tanous         return false;
485f4c99e70SEd Tanous     }
486f4c99e70SEd Tanous 
487f4c99e70SEd Tanous     auto itUrl = itMemBegin->find("@odata.id");
488f4c99e70SEd Tanous     if (itUrl == itMemBegin->end())
489f4c99e70SEd Tanous     {
49062598e31SEd Tanous         BMCWEB_LOG_DEBUG("No found odata.id");
491f4c99e70SEd Tanous         messages::internalError(res);
492f4c99e70SEd Tanous         completionHandler(res);
493f4c99e70SEd Tanous         return false;
494f4c99e70SEd Tanous     }
495f4c99e70SEd Tanous     const std::string* url = itUrl->get_ptr<const std::string*>();
496f4c99e70SEd Tanous     if (url == nullptr)
497f4c99e70SEd Tanous     {
49862598e31SEd Tanous         BMCWEB_LOG_DEBUG("@odata.id wasn't a string????");
499f4c99e70SEd Tanous         messages::internalError(res);
500f4c99e70SEd Tanous         completionHandler(res);
501f4c99e70SEd Tanous         return false;
502f4c99e70SEd Tanous     }
503f4c99e70SEd Tanous     // TODO(Ed) copy request headers?
504f4c99e70SEd Tanous     // newReq.session = req.session;
505f4c99e70SEd Tanous     std::error_code ec;
506*102a4cdaSJonathan Doman     auto newReq = std::make_shared<crow::Request>(
507*102a4cdaSJonathan Doman         crow::Request::Body{boost::beast::http::verb::get, *url, 11}, ec);
508f4c99e70SEd Tanous     if (ec)
509f4c99e70SEd Tanous     {
510f4c99e70SEd Tanous         messages::internalError(res);
511f4c99e70SEd Tanous         completionHandler(res);
512f4c99e70SEd Tanous         return false;
513f4c99e70SEd Tanous     }
514f4c99e70SEd Tanous 
515f4c99e70SEd Tanous     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
51662598e31SEd Tanous     BMCWEB_LOG_DEBUG("setting completion handler on {}",
51762598e31SEd Tanous                      logPtr(&asyncResp->res));
518f4c99e70SEd Tanous     asyncResp->res.setCompleteRequestHandler(std::move(completionHandler));
519f4c99e70SEd Tanous     app.handle(newReq, asyncResp);
520f4c99e70SEd Tanous     return true;
521f4c99e70SEd Tanous }
522f4c99e70SEd Tanous 
5237cf436c9SEd Tanous struct ExpandNode
5247cf436c9SEd Tanous {
5257cf436c9SEd Tanous     nlohmann::json::json_pointer location;
5267cf436c9SEd Tanous     std::string uri;
5277cf436c9SEd Tanous 
5289de65b34SEd Tanous     bool operator==(const ExpandNode& other) const
5297cf436c9SEd Tanous     {
5307cf436c9SEd Tanous         return location == other.location && uri == other.uri;
5317cf436c9SEd Tanous     }
5327cf436c9SEd Tanous };
5337cf436c9SEd Tanous 
53487788abfSEd Tanous inline void findNavigationReferencesInArrayRecursive(
535c59e338cSEd Tanous     ExpandType eType, nlohmann::json::array_t& array,
53637b1f7beSEd Tanous     const nlohmann::json::json_pointer& jsonPtr, int depth, int skipDepth,
53787788abfSEd Tanous     bool inLinks, std::vector<ExpandNode>& out);
53887788abfSEd Tanous 
53987788abfSEd Tanous inline void findNavigationReferencesInObjectRecursive(
540c59e338cSEd Tanous     ExpandType eType, nlohmann::json::object_t& obj,
54137b1f7beSEd Tanous     const nlohmann::json::json_pointer& jsonPtr, int depth, int skipDepth,
54287788abfSEd Tanous     bool inLinks, std::vector<ExpandNode>& out);
54387788abfSEd Tanous 
5447cf436c9SEd Tanous // Walks a json object looking for Redfish NavigationReference entries that
5457cf436c9SEd Tanous // might need resolved.  It recursively walks the jsonResponse object, looking
5467cf436c9SEd Tanous // for links at every level, and returns a list (out) of locations within the
5477cf436c9SEd Tanous // tree that need to be expanded.  The current json pointer location p is passed
5487cf436c9SEd Tanous // in to reference the current node that's being expanded, so it can be combined
5497cf436c9SEd Tanous // with the keys from the jsonResponse object
5507cf436c9SEd Tanous inline void findNavigationReferencesRecursive(
5517cf436c9SEd Tanous     ExpandType eType, nlohmann::json& jsonResponse,
55237b1f7beSEd Tanous     const nlohmann::json::json_pointer& jsonPtr, int depth, int skipDepth,
55332cdb4a7SWilly Tu     bool inLinks, std::vector<ExpandNode>& out)
5547cf436c9SEd Tanous {
5557cf436c9SEd Tanous     // If no expand is needed, return early
5567cf436c9SEd Tanous     if (eType == ExpandType::None)
5577cf436c9SEd Tanous     {
5587cf436c9SEd Tanous         return;
5597cf436c9SEd Tanous     }
560ad595fa6SEd Tanous 
5617cf436c9SEd Tanous     nlohmann::json::array_t* array =
5627cf436c9SEd Tanous         jsonResponse.get_ptr<nlohmann::json::array_t*>();
5637cf436c9SEd Tanous     if (array != nullptr)
5647cf436c9SEd Tanous     {
56537b1f7beSEd Tanous         findNavigationReferencesInArrayRecursive(eType, *array, jsonPtr, depth,
56687788abfSEd Tanous                                                  skipDepth, inLinks, out);
56787788abfSEd Tanous     }
56887788abfSEd Tanous     nlohmann::json::object_t* obj =
56987788abfSEd Tanous         jsonResponse.get_ptr<nlohmann::json::object_t*>();
57087788abfSEd Tanous     if (obj == nullptr)
57187788abfSEd Tanous     {
57287788abfSEd Tanous         return;
57387788abfSEd Tanous     }
57437b1f7beSEd Tanous     findNavigationReferencesInObjectRecursive(eType, *obj, jsonPtr, depth,
57537b1f7beSEd Tanous                                               skipDepth, inLinks, out);
57687788abfSEd Tanous }
57787788abfSEd Tanous 
57887788abfSEd Tanous inline void findNavigationReferencesInArrayRecursive(
579c59e338cSEd Tanous     ExpandType eType, nlohmann::json::array_t& array,
58037b1f7beSEd Tanous     const nlohmann::json::json_pointer& jsonPtr, int depth, int skipDepth,
58187788abfSEd Tanous     bool inLinks, std::vector<ExpandNode>& out)
58287788abfSEd Tanous {
5837cf436c9SEd Tanous     size_t index = 0;
5847cf436c9SEd Tanous     // For arrays, walk every element in the array
585c59e338cSEd Tanous     for (auto& element : array)
5867cf436c9SEd Tanous     {
58737b1f7beSEd Tanous         nlohmann::json::json_pointer newPtr = jsonPtr / index;
58862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Traversing response at {}", newPtr.to_string());
589ad595fa6SEd Tanous         findNavigationReferencesRecursive(eType, element, newPtr, depth,
59032cdb4a7SWilly Tu                                           skipDepth, inLinks, out);
5917cf436c9SEd Tanous         index++;
5927cf436c9SEd Tanous     }
5937cf436c9SEd Tanous }
59487788abfSEd Tanous 
59587788abfSEd Tanous inline void findNavigationReferencesInObjectRecursive(
596c59e338cSEd Tanous     ExpandType eType, nlohmann::json::object_t& obj,
59737b1f7beSEd Tanous     const nlohmann::json::json_pointer& jsonPtr, int depth, int skipDepth,
59887788abfSEd Tanous     bool inLinks, std::vector<ExpandNode>& out)
5997cf436c9SEd Tanous {
6007cf436c9SEd Tanous     // Navigation References only ever have a single element
601c59e338cSEd Tanous     if (obj.size() == 1)
6027cf436c9SEd Tanous     {
603c59e338cSEd Tanous         if (obj.begin()->first == "@odata.id")
6047cf436c9SEd Tanous         {
6057cf436c9SEd Tanous             const std::string* uri =
606c59e338cSEd Tanous                 obj.begin()->second.get_ptr<const std::string*>();
6077cf436c9SEd Tanous             if (uri != nullptr)
6087cf436c9SEd Tanous             {
60962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Found {} at {}", *uri, jsonPtr.to_string());
61032cdb4a7SWilly Tu                 if (skipDepth == 0)
61132cdb4a7SWilly Tu                 {
61237b1f7beSEd Tanous                     out.push_back({jsonPtr, *uri});
61332cdb4a7SWilly Tu                 }
614ad595fa6SEd Tanous                 return;
6157cf436c9SEd Tanous             }
6167cf436c9SEd Tanous         }
6177cf436c9SEd Tanous     }
618ad595fa6SEd Tanous 
619ad595fa6SEd Tanous     int newDepth = depth;
620c59e338cSEd Tanous     auto odataId = obj.find("@odata.id");
621c59e338cSEd Tanous     if (odataId != obj.end())
622ad595fa6SEd Tanous     {
623ad595fa6SEd Tanous         // The Redfish spec requires all resources to include the resource
624ad595fa6SEd Tanous         // identifier.  If the object has multiple elements and one of them is
625ad595fa6SEd Tanous         // "@odata.id" then that means we have entered a new level / expanded
626ad595fa6SEd Tanous         // resource.  We need to stop traversing if we're already at the desired
627ad595fa6SEd Tanous         // depth
628c59e338cSEd Tanous         if (obj.size() > 1)
62932cdb4a7SWilly Tu         {
63032cdb4a7SWilly Tu             if (depth == 0)
631ad595fa6SEd Tanous             {
632ad595fa6SEd Tanous                 return;
633ad595fa6SEd Tanous             }
63432cdb4a7SWilly Tu             if (skipDepth > 0)
63532cdb4a7SWilly Tu             {
63632cdb4a7SWilly Tu                 skipDepth--;
63732cdb4a7SWilly Tu             }
63832cdb4a7SWilly Tu         }
63932cdb4a7SWilly Tu 
64032cdb4a7SWilly Tu         if (skipDepth == 0)
64132cdb4a7SWilly Tu         {
642ad595fa6SEd Tanous             newDepth--;
643ad595fa6SEd Tanous         }
64432cdb4a7SWilly Tu     }
645ad595fa6SEd Tanous 
6467cf436c9SEd Tanous     // Loop the object and look for links
647c59e338cSEd Tanous     for (auto& element : obj)
6487cf436c9SEd Tanous     {
649e479ad58SNan Zhou         bool localInLinks = inLinks;
650e479ad58SNan Zhou         if (!localInLinks)
6517cf436c9SEd Tanous         {
6527cf436c9SEd Tanous             // Check if this is a links node
653e479ad58SNan Zhou             localInLinks = element.first == "Links";
6547cf436c9SEd Tanous         }
6557cf436c9SEd Tanous         // Only traverse the parts of the tree the user asked for
6567cf436c9SEd Tanous         // Per section 7.3 of the redfish specification
657e479ad58SNan Zhou         if (localInLinks && eType == ExpandType::NotLinks)
6587cf436c9SEd Tanous         {
6597cf436c9SEd Tanous             continue;
6607cf436c9SEd Tanous         }
661e479ad58SNan Zhou         if (!localInLinks && eType == ExpandType::Links)
6627cf436c9SEd Tanous         {
6637cf436c9SEd Tanous             continue;
6647cf436c9SEd Tanous         }
66537b1f7beSEd Tanous         nlohmann::json::json_pointer newPtr = jsonPtr / element.first;
66662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Traversing response at {}", newPtr);
6677cf436c9SEd Tanous 
6687cf436c9SEd Tanous         findNavigationReferencesRecursive(eType, element.second, newPtr,
66932cdb4a7SWilly Tu                                           newDepth, skipDepth, localInLinks,
67032cdb4a7SWilly Tu                                           out);
6717cf436c9SEd Tanous     }
6727cf436c9SEd Tanous }
6737cf436c9SEd Tanous 
674ad595fa6SEd Tanous // TODO: When aggregation is enabled and we receive a partially expanded
675ad595fa6SEd Tanous // response we may need need additional handling when the original URI was
676ad595fa6SEd Tanous // up tree from a top level collection.
677ad595fa6SEd Tanous // Isn't a concern until https://gerrit.openbmc.org/c/openbmc/bmcweb/+/60556
678ad595fa6SEd Tanous // lands.  May want to avoid forwarding query params when request is uptree from
679ad595fa6SEd Tanous // a top level collection.
6807cf436c9SEd Tanous inline std::vector<ExpandNode>
68132cdb4a7SWilly Tu     findNavigationReferences(ExpandType eType, int depth, int skipDepth,
682ad595fa6SEd Tanous                              nlohmann::json& jsonResponse)
6837cf436c9SEd Tanous {
6847cf436c9SEd Tanous     std::vector<ExpandNode> ret;
68572c3ae33SNan Zhou     const nlohmann::json::json_pointer root = nlohmann::json::json_pointer("");
68632cdb4a7SWilly Tu     // SkipDepth +1 since we are skipping the root by default.
68732cdb4a7SWilly Tu     findNavigationReferencesRecursive(eType, jsonResponse, root, depth,
68832cdb4a7SWilly Tu                                       skipDepth + 1, false, ret);
6897cf436c9SEd Tanous     return ret;
6907cf436c9SEd Tanous }
6917cf436c9SEd Tanous 
69272c3ae33SNan Zhou // Formats a query parameter string for the sub-query.
693b66cf2a2SNan Zhou // Returns std::nullopt on failures.
69472c3ae33SNan Zhou // This function shall handle $select when it is added.
6958ece0e45SEd Tanous // There is no need to handle parameters that's not compatible with $expand,
69672c3ae33SNan Zhou // e.g., $only, since this function will only be called in side $expand handlers
697b66cf2a2SNan Zhou inline std::optional<std::string> formatQueryForExpand(const Query& query)
69872c3ae33SNan Zhou {
69972c3ae33SNan Zhou     // query.expandLevel<=1: no need to do subqueries
70072c3ae33SNan Zhou     if (query.expandLevel <= 1)
70172c3ae33SNan Zhou     {
702b66cf2a2SNan Zhou         return "";
70372c3ae33SNan Zhou     }
70472c3ae33SNan Zhou     std::string str = "?$expand=";
70572c3ae33SNan Zhou     switch (query.expandType)
70672c3ae33SNan Zhou     {
70772c3ae33SNan Zhou         case ExpandType::Links:
70872c3ae33SNan Zhou             str += '~';
70972c3ae33SNan Zhou             break;
71072c3ae33SNan Zhou         case ExpandType::NotLinks:
71172c3ae33SNan Zhou             str += '.';
71272c3ae33SNan Zhou             break;
71372c3ae33SNan Zhou         case ExpandType::Both:
71472c3ae33SNan Zhou             str += '*';
71572c3ae33SNan Zhou             break;
716f1a1e3dcSEd Tanous         case ExpandType::None:
717f1a1e3dcSEd Tanous             return "";
7184da0490bSEd Tanous         default:
7194da0490bSEd Tanous             return std::nullopt;
720b66cf2a2SNan Zhou     }
72172c3ae33SNan Zhou     str += "($levels=";
72272c3ae33SNan Zhou     str += std::to_string(query.expandLevel - 1);
72372c3ae33SNan Zhou     str += ')';
72472c3ae33SNan Zhou     return str;
72572c3ae33SNan Zhou }
72672c3ae33SNan Zhou 
7278ece0e45SEd Tanous // Propagates the worst error code to the final response.
7283590bd1dSNan Zhou // The order of error code is (from high to low)
7293590bd1dSNan Zhou // 500 Internal Server Error
7303590bd1dSNan Zhou // 511 Network Authentication Required
7313590bd1dSNan Zhou // 510 Not Extended
7323590bd1dSNan Zhou // 508 Loop Detected
7333590bd1dSNan Zhou // 507 Insufficient Storage
7343590bd1dSNan Zhou // 506 Variant Also Negotiates
7353590bd1dSNan Zhou // 505 HTTP Version Not Supported
7363590bd1dSNan Zhou // 504 Gateway Timeout
7373590bd1dSNan Zhou // 503 Service Unavailable
7383590bd1dSNan Zhou // 502 Bad Gateway
7393590bd1dSNan Zhou // 501 Not Implemented
7403590bd1dSNan Zhou // 401 Unauthorized
7418ece0e45SEd Tanous // 451 - 409 Error codes (not listed explicitly)
7423590bd1dSNan Zhou // 408 Request Timeout
7433590bd1dSNan Zhou // 407 Proxy Authentication Required
7443590bd1dSNan Zhou // 406 Not Acceptable
7453590bd1dSNan Zhou // 405 Method Not Allowed
7463590bd1dSNan Zhou // 404 Not Found
7473590bd1dSNan Zhou // 403 Forbidden
7483590bd1dSNan Zhou // 402 Payment Required
7493590bd1dSNan Zhou // 400 Bad Request
7503590bd1dSNan Zhou inline unsigned propogateErrorCode(unsigned finalCode, unsigned subResponseCode)
7513590bd1dSNan Zhou {
7523590bd1dSNan Zhou     // We keep a explicit list for error codes that this project often uses
7538ece0e45SEd Tanous     // Higher priority codes are in lower indexes
7543590bd1dSNan Zhou     constexpr std::array<unsigned, 13> orderedCodes = {
7553590bd1dSNan Zhou         500, 507, 503, 502, 501, 401, 412, 409, 406, 405, 404, 403, 400};
7563590bd1dSNan Zhou     size_t finalCodeIndex = std::numeric_limits<size_t>::max();
7573590bd1dSNan Zhou     size_t subResponseCodeIndex = std::numeric_limits<size_t>::max();
7583590bd1dSNan Zhou     for (size_t i = 0; i < orderedCodes.size(); ++i)
7593590bd1dSNan Zhou     {
7603590bd1dSNan Zhou         if (orderedCodes[i] == finalCode)
7613590bd1dSNan Zhou         {
7623590bd1dSNan Zhou             finalCodeIndex = i;
7633590bd1dSNan Zhou         }
7643590bd1dSNan Zhou         if (orderedCodes[i] == subResponseCode)
7653590bd1dSNan Zhou         {
7663590bd1dSNan Zhou             subResponseCodeIndex = i;
7673590bd1dSNan Zhou         }
7683590bd1dSNan Zhou     }
7693590bd1dSNan Zhou     if (finalCodeIndex != std::numeric_limits<size_t>::max() &&
7703590bd1dSNan Zhou         subResponseCodeIndex != std::numeric_limits<size_t>::max())
7713590bd1dSNan Zhou     {
7723590bd1dSNan Zhou         return finalCodeIndex <= subResponseCodeIndex ? finalCode
7733590bd1dSNan Zhou                                                       : subResponseCode;
7743590bd1dSNan Zhou     }
7753590bd1dSNan Zhou     if (subResponseCode == 500 || finalCode == 500)
7763590bd1dSNan Zhou     {
7773590bd1dSNan Zhou         return 500;
7783590bd1dSNan Zhou     }
7793590bd1dSNan Zhou     if (subResponseCode > 500 || finalCode > 500)
7803590bd1dSNan Zhou     {
7813590bd1dSNan Zhou         return std::max(finalCode, subResponseCode);
7823590bd1dSNan Zhou     }
7833590bd1dSNan Zhou     if (subResponseCode == 401)
7843590bd1dSNan Zhou     {
7853590bd1dSNan Zhou         return subResponseCode;
7863590bd1dSNan Zhou     }
7873590bd1dSNan Zhou     return std::max(finalCode, subResponseCode);
7883590bd1dSNan Zhou }
7893590bd1dSNan Zhou 
7908ece0e45SEd Tanous // Propagates all error messages into |finalResponse|
7913590bd1dSNan Zhou inline void propogateError(crow::Response& finalResponse,
7923590bd1dSNan Zhou                            crow::Response& subResponse)
7933590bd1dSNan Zhou {
7943590bd1dSNan Zhou     // no errors
7953590bd1dSNan Zhou     if (subResponse.resultInt() >= 200 && subResponse.resultInt() < 400)
7963590bd1dSNan Zhou     {
7973590bd1dSNan Zhou         return;
7983590bd1dSNan Zhou     }
7993590bd1dSNan Zhou     messages::moveErrorsToErrorJson(finalResponse.jsonValue,
8003590bd1dSNan Zhou                                     subResponse.jsonValue);
8013590bd1dSNan Zhou     finalResponse.result(
8023590bd1dSNan Zhou         propogateErrorCode(finalResponse.resultInt(), subResponse.resultInt()));
8033590bd1dSNan Zhou }
8043590bd1dSNan Zhou 
8057cf436c9SEd Tanous class MultiAsyncResp : public std::enable_shared_from_this<MultiAsyncResp>
8067cf436c9SEd Tanous {
8077cf436c9SEd Tanous   public:
8087cf436c9SEd Tanous     // This object takes a single asyncResp object as the "final" one, then
8097cf436c9SEd Tanous     // allows callers to attach sub-responses within the json tree that need
8107cf436c9SEd Tanous     // to be executed and filled into their appropriate locations.  This
8117cf436c9SEd Tanous     // class manages the final "merge" of the json resources.
8128a592810SEd Tanous     MultiAsyncResp(crow::App& appIn,
8137cf436c9SEd Tanous                    std::shared_ptr<bmcweb::AsyncResp> finalResIn) :
8148a592810SEd Tanous         app(appIn),
8157cf436c9SEd Tanous         finalRes(std::move(finalResIn))
8167cf436c9SEd Tanous     {}
8177cf436c9SEd Tanous 
8187cf436c9SEd Tanous     void addAwaitingResponse(
81902cad96eSEd Tanous         const std::shared_ptr<bmcweb::AsyncResp>& res,
8207cf436c9SEd Tanous         const nlohmann::json::json_pointer& finalExpandLocation)
8217cf436c9SEd Tanous     {
8227cf436c9SEd Tanous         res->res.setCompleteRequestHandler(std::bind_front(
82372c3ae33SNan Zhou             placeResultStatic, shared_from_this(), finalExpandLocation));
8247cf436c9SEd Tanous     }
8257cf436c9SEd Tanous 
82672c3ae33SNan Zhou     void placeResult(const nlohmann::json::json_pointer& locationToPlace,
8277cf436c9SEd Tanous                      crow::Response& res)
8287cf436c9SEd Tanous     {
82962598e31SEd Tanous         BMCWEB_LOG_DEBUG("placeResult for {}", locationToPlace);
8303590bd1dSNan Zhou         propogateError(finalRes->res, res);
8313590bd1dSNan Zhou         if (!res.jsonValue.is_object() || res.jsonValue.empty())
8323590bd1dSNan Zhou         {
8333590bd1dSNan Zhou             return;
8343590bd1dSNan Zhou         }
8357cf436c9SEd Tanous         nlohmann::json& finalObj = finalRes->res.jsonValue[locationToPlace];
8367cf436c9SEd Tanous         finalObj = std::move(res.jsonValue);
8377cf436c9SEd Tanous     }
8387cf436c9SEd Tanous 
83972c3ae33SNan Zhou     // Handles the very first level of Expand, and starts a chain of sub-queries
84072c3ae33SNan Zhou     // for deeper levels.
84132cdb4a7SWilly Tu     void startQuery(const Query& query, const Query& delegated)
84272c3ae33SNan Zhou     {
843ad595fa6SEd Tanous         std::vector<ExpandNode> nodes = findNavigationReferences(
84432cdb4a7SWilly Tu             query.expandType, query.expandLevel, delegated.expandLevel,
84532cdb4a7SWilly Tu             finalRes->res.jsonValue);
84662598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} nodes to traverse", nodes.size());
847b66cf2a2SNan Zhou         const std::optional<std::string> queryStr = formatQueryForExpand(query);
848b66cf2a2SNan Zhou         if (!queryStr)
849b66cf2a2SNan Zhou         {
850b66cf2a2SNan Zhou             messages::internalError(finalRes->res);
851b66cf2a2SNan Zhou             return;
852b66cf2a2SNan Zhou         }
8537cf436c9SEd Tanous         for (const ExpandNode& node : nodes)
8547cf436c9SEd Tanous         {
855b66cf2a2SNan Zhou             const std::string subQuery = node.uri + *queryStr;
85662598e31SEd Tanous             BMCWEB_LOG_DEBUG("URL of subquery:  {}", subQuery);
8577cf436c9SEd Tanous             std::error_code ec;
858*102a4cdaSJonathan Doman             auto newReq = std::make_shared<crow::Request>(
859*102a4cdaSJonathan Doman                 crow::Request::Body{boost::beast::http::verb::get, subQuery,
860*102a4cdaSJonathan Doman                                     11},
8617cf436c9SEd Tanous                 ec);
8627cf436c9SEd Tanous             if (ec)
8637cf436c9SEd Tanous             {
86472c3ae33SNan Zhou                 messages::internalError(finalRes->res);
8657cf436c9SEd Tanous                 return;
8667cf436c9SEd Tanous             }
8677cf436c9SEd Tanous 
8687cf436c9SEd Tanous             auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
86962598e31SEd Tanous             BMCWEB_LOG_DEBUG("setting completion handler on {}",
87062598e31SEd Tanous                              logPtr(&asyncResp->res));
87172c3ae33SNan Zhou 
87272c3ae33SNan Zhou             addAwaitingResponse(asyncResp, node.location);
8737cf436c9SEd Tanous             app.handle(newReq, asyncResp);
8747cf436c9SEd Tanous         }
8757cf436c9SEd Tanous     }
8767cf436c9SEd Tanous 
8777cf436c9SEd Tanous   private:
87872c3ae33SNan Zhou     static void
87972c3ae33SNan Zhou         placeResultStatic(const std::shared_ptr<MultiAsyncResp>& multi,
8807cf436c9SEd Tanous                           const nlohmann::json::json_pointer& locationToPlace,
8817cf436c9SEd Tanous                           crow::Response& res)
8827cf436c9SEd Tanous     {
88372c3ae33SNan Zhou         multi->placeResult(locationToPlace, res);
8847cf436c9SEd Tanous     }
8857cf436c9SEd Tanous 
8867cf436c9SEd Tanous     crow::App& app;
8877cf436c9SEd Tanous     std::shared_ptr<bmcweb::AsyncResp> finalRes;
8887cf436c9SEd Tanous };
8897cf436c9SEd Tanous 
8902a68dc80SEd Tanous inline void processTopAndSkip(const Query& query, crow::Response& res)
8912a68dc80SEd Tanous {
8923648c8beSEd Tanous     if (!query.skip && !query.top)
8933648c8beSEd Tanous     {
8943648c8beSEd Tanous         // No work to do.
8953648c8beSEd Tanous         return;
8963648c8beSEd Tanous     }
8972a68dc80SEd Tanous     nlohmann::json::object_t* obj =
8982a68dc80SEd Tanous         res.jsonValue.get_ptr<nlohmann::json::object_t*>();
8992a68dc80SEd Tanous     if (obj == nullptr)
9002a68dc80SEd Tanous     {
9012a68dc80SEd Tanous         // Shouldn't be possible.  All responses should be objects.
9022a68dc80SEd Tanous         messages::internalError(res);
9032a68dc80SEd Tanous         return;
9042a68dc80SEd Tanous     }
9052a68dc80SEd Tanous 
90662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Handling top/skip");
9072a68dc80SEd Tanous     nlohmann::json::object_t::iterator members = obj->find("Members");
9082a68dc80SEd Tanous     if (members == obj->end())
9092a68dc80SEd Tanous     {
9102a68dc80SEd Tanous         // From the Redfish specification 7.3.1
9112a68dc80SEd Tanous         // ... the HTTP 400 Bad Request status code with the
9122a68dc80SEd Tanous         // QueryNotSupportedOnResource message from the Base Message Registry
9132a68dc80SEd Tanous         // for any supported query parameters that apply only to resource
9142a68dc80SEd Tanous         // collections but are used on singular resources.
9152a68dc80SEd Tanous         messages::queryNotSupportedOnResource(res);
9162a68dc80SEd Tanous         return;
9172a68dc80SEd Tanous     }
9182a68dc80SEd Tanous 
9192a68dc80SEd Tanous     nlohmann::json::array_t* arr =
9202a68dc80SEd Tanous         members->second.get_ptr<nlohmann::json::array_t*>();
9212a68dc80SEd Tanous     if (arr == nullptr)
9222a68dc80SEd Tanous     {
9232a68dc80SEd Tanous         messages::internalError(res);
9242a68dc80SEd Tanous         return;
9252a68dc80SEd Tanous     }
9262a68dc80SEd Tanous 
9273648c8beSEd Tanous     if (query.skip)
9283648c8beSEd Tanous     {
9293648c8beSEd Tanous         // Per section 7.3.1 of the Redfish specification, $skip is run before
9303648c8beSEd Tanous         // $top Can only skip as many values as we have
9313648c8beSEd Tanous         size_t skip = std::min(arr->size(), *query.skip);
9322a68dc80SEd Tanous         arr->erase(arr->begin(), arr->begin() + static_cast<ssize_t>(skip));
9333648c8beSEd Tanous     }
9343648c8beSEd Tanous     if (query.top)
9353648c8beSEd Tanous     {
9363648c8beSEd Tanous         size_t top = std::min(arr->size(), *query.top);
9372a68dc80SEd Tanous         arr->erase(arr->begin() + static_cast<ssize_t>(top), arr->end());
9382a68dc80SEd Tanous     }
9393648c8beSEd Tanous }
9402a68dc80SEd Tanous 
941827c4902SNan Zhou // Given a JSON subtree |currRoot|, this function erases leaves whose keys are
942827c4902SNan Zhou // not in the |currNode| Trie node.
943827c4902SNan Zhou inline void recursiveSelect(nlohmann::json& currRoot,
944827c4902SNan Zhou                             const SelectTrieNode& currNode)
945e155ab54SNan Zhou {
946e155ab54SNan Zhou     nlohmann::json::object_t* object =
947e155ab54SNan Zhou         currRoot.get_ptr<nlohmann::json::object_t*>();
948e155ab54SNan Zhou     if (object != nullptr)
949e155ab54SNan Zhou     {
95062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Current JSON is an object");
951e155ab54SNan Zhou         auto it = currRoot.begin();
952e155ab54SNan Zhou         while (it != currRoot.end())
953e155ab54SNan Zhou         {
954e155ab54SNan Zhou             auto nextIt = std::next(it);
95562598e31SEd Tanous             BMCWEB_LOG_DEBUG("key={}", it.key());
956827c4902SNan Zhou             const SelectTrieNode* nextNode = currNode.find(it.key());
9575c9fb2d6SNan Zhou             // Per the Redfish spec section 7.3.3, the service shall select
9585c9fb2d6SNan Zhou             // certain properties as if $select was omitted. This applies to
9595c9fb2d6SNan Zhou             // every TrieNode that contains leaves and the root.
9605c9fb2d6SNan Zhou             constexpr std::array<std::string_view, 5> reservedProperties = {
9615c9fb2d6SNan Zhou                 "@odata.id", "@odata.type", "@odata.context", "@odata.etag",
9625c9fb2d6SNan Zhou                 "error"};
9633544d2a7SEd Tanous             bool reserved = std::ranges::find(reservedProperties, it.key()) !=
9643544d2a7SEd Tanous                             reservedProperties.end();
9655c9fb2d6SNan Zhou             if (reserved || (nextNode != nullptr && nextNode->isSelected()))
966e155ab54SNan Zhou             {
967e155ab54SNan Zhou                 it = nextIt;
968e155ab54SNan Zhou                 continue;
969e155ab54SNan Zhou             }
970827c4902SNan Zhou             if (nextNode != nullptr)
971e155ab54SNan Zhou             {
97262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Recursively select: {}", it.key());
973827c4902SNan Zhou                 recursiveSelect(*it, *nextNode);
974e155ab54SNan Zhou                 it = nextIt;
975e155ab54SNan Zhou                 continue;
976e155ab54SNan Zhou             }
97762598e31SEd Tanous             BMCWEB_LOG_DEBUG("{} is getting removed!", it.key());
978e155ab54SNan Zhou             it = currRoot.erase(it);
979e155ab54SNan Zhou         }
980e155ab54SNan Zhou     }
9815c9fb2d6SNan Zhou     nlohmann::json::array_t* array =
9825c9fb2d6SNan Zhou         currRoot.get_ptr<nlohmann::json::array_t*>();
9835c9fb2d6SNan Zhou     if (array != nullptr)
9845c9fb2d6SNan Zhou     {
98562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Current JSON is an array");
9865c9fb2d6SNan Zhou         // Array index is omitted, so reuse the same Trie node
9875c9fb2d6SNan Zhou         for (nlohmann::json& nextRoot : *array)
9885c9fb2d6SNan Zhou         {
9895c9fb2d6SNan Zhou             recursiveSelect(nextRoot, currNode);
9905c9fb2d6SNan Zhou         }
9915c9fb2d6SNan Zhou     }
992e155ab54SNan Zhou }
993e155ab54SNan Zhou 
994e155ab54SNan Zhou // The current implementation of $select still has the following TODOs due to
995e155ab54SNan Zhou //  ambiguity and/or complexity.
9965c9fb2d6SNan Zhou // 1. combined with $expand; https://github.com/DMTF/Redfish/issues/5058 was
997e155ab54SNan Zhou // created for clarification.
9985c9fb2d6SNan Zhou // 2. respect the full odata spec; e.g., deduplication, namespace, star (*),
999e155ab54SNan Zhou // etc.
1000e155ab54SNan Zhou inline void processSelect(crow::Response& intermediateResponse,
1001827c4902SNan Zhou                           const SelectTrieNode& trieRoot)
1002e155ab54SNan Zhou {
100362598e31SEd Tanous     BMCWEB_LOG_DEBUG("Process $select quary parameter");
1004827c4902SNan Zhou     recursiveSelect(intermediateResponse.jsonValue, trieRoot);
1005e155ab54SNan Zhou }
1006e155ab54SNan Zhou 
10077cf436c9SEd Tanous inline void
100832cdb4a7SWilly Tu     processAllParams(crow::App& app, const Query& query, const Query& delegated,
10097cf436c9SEd Tanous                      std::function<void(crow::Response&)>& completionHandler,
10107cf436c9SEd Tanous                      crow::Response& intermediateResponse)
1011f4c99e70SEd Tanous {
1012f4c99e70SEd Tanous     if (!completionHandler)
1013f4c99e70SEd Tanous     {
101462598e31SEd Tanous         BMCWEB_LOG_DEBUG("Function was invalid?");
1015f4c99e70SEd Tanous         return;
1016f4c99e70SEd Tanous     }
1017f4c99e70SEd Tanous 
101862598e31SEd Tanous     BMCWEB_LOG_DEBUG("Processing query params");
1019f4c99e70SEd Tanous     // If the request failed, there's no reason to even try to run query
1020f4c99e70SEd Tanous     // params.
1021f4c99e70SEd Tanous     if (intermediateResponse.resultInt() < 200 ||
1022f4c99e70SEd Tanous         intermediateResponse.resultInt() >= 400)
1023f4c99e70SEd Tanous     {
1024f4c99e70SEd Tanous         completionHandler(intermediateResponse);
1025f4c99e70SEd Tanous         return;
1026f4c99e70SEd Tanous     }
1027f4c99e70SEd Tanous     if (query.isOnly)
1028f4c99e70SEd Tanous     {
1029f4c99e70SEd Tanous         processOnly(app, intermediateResponse, completionHandler);
1030f4c99e70SEd Tanous         return;
1031f4c99e70SEd Tanous     }
10322a68dc80SEd Tanous 
10333648c8beSEd Tanous     if (query.top || query.skip)
10342a68dc80SEd Tanous     {
10352a68dc80SEd Tanous         processTopAndSkip(query, intermediateResponse);
10362a68dc80SEd Tanous     }
10372a68dc80SEd Tanous 
10387cf436c9SEd Tanous     if (query.expandType != ExpandType::None)
10397cf436c9SEd Tanous     {
104062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Executing expand query");
104113548d85SEd Tanous         auto asyncResp = std::make_shared<bmcweb::AsyncResp>(
104213548d85SEd Tanous             std::move(intermediateResponse));
10437cf436c9SEd Tanous 
104413548d85SEd Tanous         asyncResp->res.setCompleteRequestHandler(std::move(completionHandler));
104513548d85SEd Tanous         auto multi = std::make_shared<MultiAsyncResp>(app, asyncResp);
104632cdb4a7SWilly Tu         multi->startQuery(query, delegated);
10477cf436c9SEd Tanous         return;
10487cf436c9SEd Tanous     }
1049e155ab54SNan Zhou 
1050e155ab54SNan Zhou     // According to Redfish Spec Section 7.3.1, $select is the last parameter to
1051e155ab54SNan Zhou     // to process
1052827c4902SNan Zhou     if (!query.selectTrie.root.empty())
1053e155ab54SNan Zhou     {
1054827c4902SNan Zhou         processSelect(intermediateResponse, query.selectTrie.root);
1055e155ab54SNan Zhou     }
1056e155ab54SNan Zhou 
1057f4c99e70SEd Tanous     completionHandler(intermediateResponse);
1058f4c99e70SEd Tanous }
1059f4c99e70SEd Tanous 
1060f4c99e70SEd Tanous } // namespace query_param
1061f4c99e70SEd Tanous } // namespace redfish
1062