web_backend.cpp 7.0 KB

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