web_backend.cpp 8.0 KB

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