web_backend.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // SPDX-FileCopyrightText: 2017 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <mutex>
  5. #include <string>
  6. #include <fmt/format.h>
  7. #ifdef __GNUC__
  8. #pragma GCC diagnostic push
  9. #ifndef __clang__
  10. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  11. #endif
  12. #endif
  13. #include <httplib.h>
  14. #ifdef __GNUC__
  15. #pragma GCC diagnostic pop
  16. #endif
  17. #include "common/logging/log.h"
  18. #include "web_service/web_backend.h"
  19. #include "web_service/web_result.h"
  20. namespace WebService {
  21. constexpr std::array<const char, 1> API_VERSION{'1'};
  22. constexpr std::size_t TIMEOUT_SECONDS = 30;
  23. struct Client::Impl {
  24. Impl(std::string host_, std::string username_, std::string token_)
  25. : host{std::move(host_)}, username{std::move(username_)}, token{std::move(token_)} {
  26. std::scoped_lock lock{jwt_cache.mutex};
  27. if (username == jwt_cache.username && token == jwt_cache.token) {
  28. jwt = jwt_cache.jwt;
  29. }
  30. }
  31. /// A generic function handles POST, GET and DELETE request together
  32. WebResult GenericRequest(const std::string& method, const std::string& path,
  33. const std::string& data, bool allow_anonymous,
  34. const std::string& accept) {
  35. if (jwt.empty()) {
  36. UpdateJWT();
  37. }
  38. if (jwt.empty() && !allow_anonymous) {
  39. LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
  40. return WebResult{WebResult::Code::CredentialsMissing, "Credentials needed", ""};
  41. }
  42. auto result = GenericRequest(method, path, data, accept, jwt);
  43. if (result.result_string == "401") {
  44. // Try again with new JWT
  45. UpdateJWT();
  46. result = GenericRequest(method, path, data, accept, jwt);
  47. }
  48. return result;
  49. }
  50. /**
  51. * A generic function with explicit authentication method specified
  52. * JWT is used if the jwt parameter is not empty
  53. * username + token is used if jwt is empty but username and token are
  54. * not empty anonymous if all of jwt, username and token are empty
  55. */
  56. WebResult GenericRequest(const std::string& method, const std::string& path,
  57. const std::string& data, const std::string& accept,
  58. const std::string& jwt_ = "", const std::string& username_ = "",
  59. const std::string& token_ = "") {
  60. if (cli == nullptr) {
  61. cli = std::make_unique<httplib::Client>(host);
  62. }
  63. if (!cli->is_valid()) {
  64. LOG_ERROR(WebService, "Client is invalid, skipping request!");
  65. return {};
  66. }
  67. cli->set_connection_timeout(TIMEOUT_SECONDS);
  68. cli->set_read_timeout(TIMEOUT_SECONDS);
  69. cli->set_write_timeout(TIMEOUT_SECONDS);
  70. httplib::Headers params;
  71. if (!jwt_.empty()) {
  72. params = {
  73. {std::string("Authorization"), fmt::format("Bearer {}", jwt_)},
  74. };
  75. } else if (!username_.empty()) {
  76. params = {
  77. {std::string("x-username"), username_},
  78. {std::string("x-token"), token_},
  79. };
  80. }
  81. params.emplace(std::string("api-version"),
  82. std::string(API_VERSION.begin(), API_VERSION.end()));
  83. if (method != "GET") {
  84. params.emplace(std::string("Content-Type"), std::string("application/json"));
  85. }
  86. httplib::Request request;
  87. request.method = method;
  88. request.path = path;
  89. request.headers = params;
  90. request.body = data;
  91. httplib::Response response;
  92. httplib::Error error;
  93. if (!cli->send(request, response, error)) {
  94. LOG_ERROR(WebService, "{} to {} returned null (httplib Error: {})", method, host + path,
  95. httplib::to_string(error));
  96. return WebResult{WebResult::Code::LibError, "Null response", ""};
  97. }
  98. if (response.status >= 400) {
  99. LOG_ERROR(WebService, "{} to {} returned error status code: {}", method, host + path,
  100. response.status);
  101. return WebResult{WebResult::Code::HttpError, std::to_string(response.status), ""};
  102. }
  103. auto content_type = response.headers.find("content-type");
  104. if (content_type == response.headers.end()) {
  105. LOG_ERROR(WebService, "{} to {} returned no content", method, host + path);
  106. return WebResult{WebResult::Code::WrongContent, "", ""};
  107. }
  108. if (content_type->second.find(accept) == std::string::npos) {
  109. LOG_ERROR(WebService, "{} to {} returned wrong content: {}", method, host + path,
  110. content_type->second);
  111. return WebResult{WebResult::Code::WrongContent, "Wrong content", ""};
  112. }
  113. return WebResult{WebResult::Code::Success, "", response.body};
  114. }
  115. // Retrieve a new JWT from given username and token
  116. void UpdateJWT() {
  117. if (username.empty() || token.empty()) {
  118. return;
  119. }
  120. auto result = GenericRequest("POST", "/jwt/internal", "", "text/html", "", username, token);
  121. if (result.result_code != WebResult::Code::Success) {
  122. LOG_ERROR(WebService, "UpdateJWT failed");
  123. } else {
  124. std::scoped_lock lock{jwt_cache.mutex};
  125. jwt_cache.username = username;
  126. jwt_cache.token = token;
  127. jwt_cache.jwt = jwt = result.returned_data;
  128. }
  129. }
  130. std::string host;
  131. std::string username;
  132. std::string token;
  133. std::string jwt;
  134. std::unique_ptr<httplib::Client> cli;
  135. struct JWTCache {
  136. std::mutex mutex;
  137. std::string username;
  138. std::string token;
  139. std::string jwt;
  140. };
  141. static inline JWTCache jwt_cache;
  142. };
  143. Client::Client(std::string host, std::string username, std::string token)
  144. : impl{std::make_unique<Impl>(std::move(host), std::move(username), std::move(token))} {}
  145. Client::~Client() = default;
  146. WebResult Client::PostJson(const std::string& path, const std::string& data, bool allow_anonymous) {
  147. return impl->GenericRequest("POST", path, data, allow_anonymous, "application/json");
  148. }
  149. WebResult Client::GetJson(const std::string& path, bool allow_anonymous) {
  150. return impl->GenericRequest("GET", path, "", allow_anonymous, "application/json");
  151. }
  152. WebResult Client::DeleteJson(const std::string& path, const std::string& data,
  153. bool allow_anonymous) {
  154. return impl->GenericRequest("DELETE", path, data, allow_anonymous, "application/json");
  155. }
  156. WebResult Client::GetPlain(const std::string& path, bool allow_anonymous) {
  157. return impl->GenericRequest("GET", path, "", allow_anonymous, "text/plain");
  158. }
  159. WebResult Client::GetImage(const std::string& path, bool allow_anonymous) {
  160. return impl->GenericRequest("GET", path, "", allow_anonymous, "image/png");
  161. }
  162. WebResult Client::GetExternalJWT(const std::string& audience) {
  163. return impl->GenericRequest("POST", fmt::format("/jwt/external/{}", audience), "", false,
  164. "text/html");
  165. }
  166. } // namespace WebService