summaryrefslogtreecommitdiffstats
path: root/src/web_service/web_backend.cpp
blob: 58b0c2f10f4aee1f16ed1b5af78f015dd2ca11fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <array>
#include <mutex>
#include <string>

#include <fmt/format.h>

#ifdef __GNUC__
#pragma GCC diagnostic push
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
#endif
#include <httplib.h>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

#include "common/logging/log.h"
#include "web_service/web_backend.h"
#include "web_service/web_result.h"

namespace WebService {

constexpr std::array<const char, 1> API_VERSION{'1'};

constexpr std::size_t TIMEOUT_SECONDS = 30;

struct Client::Impl {
    Impl(std::string host, std::string username, std::string token)
        : host{std::move(host)}, username{std::move(username)}, token{std::move(token)} {
        std::scoped_lock lock{jwt_cache.mutex};
        if (this->username == jwt_cache.username && this->token == jwt_cache.token) {
            jwt = jwt_cache.jwt;
        }
    }

    /// A generic function handles POST, GET and DELETE request together
    WebResult GenericRequest(const std::string& method, const std::string& path,
                             const std::string& data, bool allow_anonymous,
                             const std::string& accept) {
        if (jwt.empty()) {
            UpdateJWT();
        }

        if (jwt.empty() && !allow_anonymous) {
            LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
            return WebResult{WebResult::Code::CredentialsMissing, "Credentials needed", ""};
        }

        auto result = GenericRequest(method, path, data, accept, jwt);
        if (result.result_string == "401") {
            // Try again with new JWT
            UpdateJWT();
            result = GenericRequest(method, path, data, accept, jwt);
        }

        return result;
    }

    /**
     * A generic function with explicit authentication method specified
     * JWT is used if the jwt parameter is not empty
     * username + token is used if jwt is empty but username and token are
     * not empty anonymous if all of jwt, username and token are empty
     */
    WebResult GenericRequest(const std::string& method, const std::string& path,
                             const std::string& data, const std::string& accept,
                             const std::string& jwt = "", const std::string& username = "",
                             const std::string& token = "") {
        if (cli == nullptr) {
            cli = std::make_unique<httplib::Client>(host.c_str());
        }

        if (!cli->is_valid()) {
            LOG_ERROR(WebService, "Client is invalid, skipping request!");
            return {};
        }

        cli->set_connection_timeout(TIMEOUT_SECONDS);
        cli->set_read_timeout(TIMEOUT_SECONDS);
        cli->set_write_timeout(TIMEOUT_SECONDS);

        httplib::Headers params;
        if (!jwt.empty()) {
            params = {
                {std::string("Authorization"), fmt::format("Bearer {}", jwt)},
            };
        } else if (!username.empty()) {
            params = {
                {std::string("x-username"), username},
                {std::string("x-token"), token},
            };
        }

        params.emplace(std::string("api-version"),
                       std::string(API_VERSION.begin(), API_VERSION.end()));
        if (method != "GET") {
            params.emplace(std::string("Content-Type"), std::string("application/json"));
        }

        httplib::Request request;
        request.method = method;
        request.path = path;
        request.headers = params;
        request.body = data;

        httplib::Response response;
        httplib::Error error;

        if (!cli->send(request, response, error)) {
            LOG_ERROR(WebService, "{} to {} returned null", method, host + path);
            return WebResult{WebResult::Code::LibError, "Null response", ""};
        }

        if (response.status >= 400) {
            LOG_ERROR(WebService, "{} to {} returned error status code: {}", method, host + path,
                      response.status);
            return WebResult{WebResult::Code::HttpError, std::to_string(response.status), ""};
        }

        auto content_type = response.headers.find("content-type");

        if (content_type == response.headers.end()) {
            LOG_ERROR(WebService, "{} to {} returned no content", method, host + path);
            return WebResult{WebResult::Code::WrongContent, "", ""};
        }

        if (content_type->second.find(accept) == std::string::npos) {
            LOG_ERROR(WebService, "{} to {} returned wrong content: {}", method, host + path,
                      content_type->second);
            return WebResult{WebResult::Code::WrongContent, "Wrong content", ""};
        }
        return WebResult{WebResult::Code::Success, "", response.body};
    }

    // Retrieve a new JWT from given username and token
    void UpdateJWT() {
        if (username.empty() || token.empty()) {
            return;
        }

        auto result = GenericRequest("POST", "/jwt/internal", "", "text/html", "", username, token);
        if (result.result_code != WebResult::Code::Success) {
            LOG_ERROR(WebService, "UpdateJWT failed");
        } else {
            std::scoped_lock lock{jwt_cache.mutex};
            jwt_cache.username = username;
            jwt_cache.token = token;
            jwt_cache.jwt = jwt = result.returned_data;
        }
    }

    std::string host;
    std::string username;
    std::string token;
    std::string jwt;
    std::unique_ptr<httplib::Client> cli;

    struct JWTCache {
        std::mutex mutex;
        std::string username;
        std::string token;
        std::string jwt;
    };
    static inline JWTCache jwt_cache;
};

Client::Client(std::string host, std::string username, std::string token)
    : impl{std::make_unique<Impl>(std::move(host), std::move(username), std::move(token))} {}

Client::~Client() = default;

WebResult Client::PostJson(const std::string& path, const std::string& data, bool allow_anonymous) {
    return impl->GenericRequest("POST", path, data, allow_anonymous, "application/json");
}

WebResult Client::GetJson(const std::string& path, bool allow_anonymous) {
    return impl->GenericRequest("GET", path, "", allow_anonymous, "application/json");
}

WebResult Client::DeleteJson(const std::string& path, const std::string& data,
                             bool allow_anonymous) {
    return impl->GenericRequest("DELETE", path, data, allow_anonymous, "application/json");
}

WebResult Client::GetPlain(const std::string& path, bool allow_anonymous) {
    return impl->GenericRequest("GET", path, "", allow_anonymous, "text/plain");
}

WebResult Client::GetImage(const std::string& path, bool allow_anonymous) {
    return impl->GenericRequest("GET", path, "", allow_anonymous, "image/png");
}

WebResult Client::GetExternalJWT(const std::string& audience) {
    return impl->GenericRequest("POST", fmt::format("/jwt/external/{}", audience), "", false,
                                "text/html");
}

} // namespace WebService