web_backend.cpp 6.8 KB

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