Repository navigation
Expand file tree
/
Copy pathAPI.cpp
More file actions
348 lines (264 loc) · 11 KB
/
Copy pathAPI.cpp
File metadata and controls
348 lines (264 loc) · 11 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#include <Server/ACME/API.h>
#if USE_SSL
#include <Common/Base64.h>
#include <Common/HTTPConnectionPool.h>
#include <Common/JSONWebKey.h>
#include <Common/OpenSSLHelpers.h>
#include <Common/ProfileEvents.h>
#include <Common/config_version.h>
#include <Disks/IO/ReadBufferFromWebServer.h>
#include <IO/HTTPCommon.h>
#include <IO/ReadHelpers.h>
#include <Interpreters/Context.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/StreamCopier.h>
namespace ProfileEvents
{
extern const Event ACMECertificateOrders;
extern const Event ACMEAPIRequests;
}
namespace DB
{
namespace ErrorCodes
{
extern const int ACME_ERROR;
extern const int LOGICAL_ERROR;
}
namespace ACME
{
Directory Directory::parse(const std::string & json_data)
{
Poco::JSON::Parser parser;
auto json = parser.parse(json_data).extract<Poco::JSON::Object::Ptr>();
auto dir = Directory{
.new_account = Poco::URI(json->getValue<std::string>(Directory::new_account_key)),
.new_order = Poco::URI(json->getValue<std::string>(Directory::new_order_key)),
.new_nonce = Poco::URI(json->getValue<std::string>(Directory::new_nonce_key)),
};
chassert(!dir.new_account.empty());
chassert(!dir.new_order.empty());
chassert(!dir.new_nonce.empty());
LOG_TEST(
&Poco::Logger::get("ACME::Directory"),
"Directory: newAccount: {}, newOrder: {}, newNonce: {}",
dir.new_account.toString(),
dir.new_order.toString(),
dir.new_nonce.toString()
);
return dir;
}
namespace
{
std::string readURLUntilEOF(const Poco::URI & url)
{
auto * log = &Poco::Logger::get("ACME::API");
LOG_TEST(log, "Requesting URL: {}", url.toString());
std::string result;
ReadSettings read_settings;
auto reader = std::make_unique<ReadBufferFromWebServer>(
url.toString(),
Context::getGlobalContextInstance(),
DBMS_DEFAULT_BUFFER_SIZE,
read_settings,
/* use_external_buffer */ true,
/* read_until_position */ 0);
readStringUntilEOF(result, *reader);
LOG_TEST(log, "Response from URL {}: {}", url.toString(), result);
return result;
}
}
API::API(Configuration _configuration): configuration(_configuration)
{
connection_timeout_settings = ConnectionTimeouts();
proxy_configuration = ProxyConfiguration();
directory = getDirectory();
authenticate();
LOG_TRACE(&Poco::Logger::get("ACME::API"), "ACME API initialized");
}
DirectoryPtr API::getDirectory() const
{
LOG_TRACE(log, "Requesting ACME directory from {}", configuration.directory_url.toString());
auto response = readURLUntilEOF(configuration.directory_url);
return std::make_shared<Directory>(Directory::parse(response));
}
std::string API::requestNonce() const
{
if (!directory)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Directory is not initialized");
LOG_TEST(log, "Requesting nonce from {}", directory->new_nonce.toString());
auto uri = Poco::URI(directory->new_nonce);
auto r = Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_HEAD, uri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
r.set("User-Agent", fmt::format("ClickHouse/{}", VERSION_STRING));
auto session = makeHTTPSession(HTTPConnectionGroupType::HTTP, uri, connection_timeout_settings, proxy_configuration);
session->setKeepAlive(false);
session->sendRequest(r);
auto response = Poco::Net::HTTPResponse();
receiveResponse(*session, r, response, /* allow_redirects */ false);
return response.get(NONCE_HEADER_NAME);
}
std::string API::formatJWSRequestData(const Poco::URI & url, const std::string & payload, const std::string & nonce) const
{
chassert(configuration.private_key);
std::string protected_data;
if (!key_id.empty())
protected_data = fmt::format(R"({{"alg":"RS256","kid":"{}","nonce":"{}","url":"{}"}})", key_id, nonce, url.toString());
else
{
auto jwk = JSONWebKey::fromRSAKey(*configuration.private_key).toString();
protected_data = fmt::format(R"({{"alg":"RS256","jwk":{},"nonce":"{}","url":"{}"}})", jwk, nonce, url.toString());
}
std::string protected_enc = base64Encode(protected_data, /*url_encoding*/ true, /*no_padding*/ true);
auto payload_enc = base64Encode(payload, /*url_encoding*/ true, /*no_padding*/ true);
EVP_PKEY * pkey = static_cast<EVP_PKEY*>(*configuration.private_key);
std::string to_sign = fmt::format("{}.{}", protected_enc, payload_enc);
std::string signature = rsaSHA256Sign(pkey, to_sign);
std::string encoded_signature = base64Encode(signature, /*url_encoding*/ true, /*no_padding*/ true);
return
R"({"protected":")" + protected_enc
+ R"(","payload":")" + payload_enc
+ R"(","signature":")" + encoded_signature
+ R"("})";
}
std::string API::doJWSRequest(
const Poco::URI & url,
const std::string & payload,
std::shared_ptr<Poco::Net::HTTPResponse> response) const
{
LOG_TEST(log, "Making JWS request to URL: {} with payload {}", url.toString(), payload);
std::string nonce = requestNonce();
std::string request_data = formatJWSRequestData(url, payload, nonce);
auto r = Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_POST, url.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
r.set("User-Agent", fmt::format("ClickHouse/{}", VERSION_STRING));
r.set("Content-Type", APPLICATION_JOSE_JSON);
r.set("Content-Length", std::to_string(request_data.size()));
auto session = makeHTTPSession(HTTPConnectionGroupType::HTTP, url, connection_timeout_settings, proxy_configuration);
session->setKeepAlive(false);
ProfileEvents::increment(ProfileEvents::ACMEAPIRequests);
auto & ostream = session->sendRequest(r);
ostream << request_data;
if (!response)
response = std::make_shared<Poco::Net::HTTPResponse>();
auto * rstream = receiveResponse(*session, r, *response, /* allow_redirects */ false);
std::string response_data;
Poco::StreamCopier::copyToString(*rstream, response_data);
return response_data;
}
Poco::JSON::Object::Ptr API::doJWSRequestExpectingJSON(
const Poco::URI & url,
const std::string & payload,
std::shared_ptr<Poco::Net::HTTPResponse> response) const
{
auto response_data = doJWSRequest(url, payload, response);
Poco::JSON::Parser parser;
return parser.parse(response_data).extract<Poco::JSON::Object::Ptr>();
}
std::string API::doJWSRequestWithEmptyPayload(const Poco::URI & url) const
{
auto http_response = std::make_shared<Poco::Net::HTTPResponse>();
return doJWSRequest(url, /*payload=*/ "", http_response);
}
std::string API::authenticate()
{
if (!key_id.empty())
return key_id;
std::string payload;
if (!configuration.contact_email.empty())
payload = fmt::format(
R"({{"contact":["mailto:{}"],"termsOfServiceAgreed":{}}})",
configuration.contact_email,
configuration.terms_of_service_agreed ? "true" : "false");
else
payload = fmt::format(R"({{"termsOfServiceAgreed":{}}})", configuration.terms_of_service_agreed);
auto http_response = std::make_shared<Poco::Net::HTTPResponse>();
auto json = doJWSRequestExpectingJSON(directory->new_account, payload, http_response);
if (!json->has("status") || json->getValue<std::string>("status") != "valid")
throw Exception(ErrorCodes::ACME_ERROR, "Account creation failed");
key_id = (*http_response).get("Location");
return key_id;
}
std::string API::order(const Domains & domains, OrderCallback callback) const
{
std::string payload_from_domains;
{
Poco::JSON::Object payload_json_object;
auto payload_identifiers = Poco::JSON::Array();
for (const auto & domain : domains)
{
Poco::JSON::Object identifier;
identifier.set("type", "dns");
identifier.set("value", domain);
payload_identifiers.add(identifier);
}
payload_json_object.set("identifiers", payload_identifiers);
std::ostringstream payload; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
payload.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(payload_json_object, payload);
payload_from_domains = payload.str();
}
auto http_response = std::make_shared<Poco::Net::HTTPResponse>();
auto json = doJWSRequestExpectingJSON(directory->new_order, payload_from_domains, http_response);
ProfileEvents::increment(ProfileEvents::ACMECertificateOrders);
auto status = json->getValue<std::string>("status");
auto expires = json->getValue<std::string>("expires");
auto authorizations = json->getArray("authorizations");
auto finalize = json->getValue<std::string>("finalize");
LOG_TEST(log, "Status: {}, Expires: {}, Finalize: {}", status, expires, finalize);
auto order_url = http_response->get("Location");
for (const auto & auth : *authorizations)
processAuthorization(Poco::URI(auth.toString()), callback);
return order_url;
}
Order API::describeOrder(const Poco::URI & order_url) const
{
auto http_response = std::make_shared<Poco::Net::HTTPResponse>();
auto json = doJWSRequestExpectingJSON(order_url, "", http_response);
auto status = json->getValue<std::string>("status");
auto finalize = json->getValue<std::string>("finalize");
std::string certificate;
if (json->has("certificate"))
certificate = json->getValue<std::string>("certificate");
return Order{
.status = status,
.order_url = order_url,
.finalize_url = Poco::URI(finalize),
.certificate_url = Poco::URI(certificate),
};
}
std::string API::pullCertificate(const Poco::URI & certificate_url) const
{
return doJWSRequestWithEmptyPayload(certificate_url);
}
bool API::finalizeOrder(const Poco::URI & finalize_url, const Domains & domains, const KeyPair & pkey) const
{
EVP_PKEY * key = static_cast<EVP_PKEY *>(pkey);
std::string csr = generateCSR(domains, key);
auto payload = R"({"csr":")" + csr + R"("})";
doJWSRequest(finalize_url, payload, nullptr);
return true;
}
void API::processAuthorization(const Poco::URI & auth_url, OrderCallback callback) const
{
auto http_response = std::make_shared<Poco::Net::HTTPResponse>();
auto json = doJWSRequestExpectingJSON(auth_url, "", http_response);
for (const auto & challenge : *json->getArray("challenges"))
{
const auto & ch = challenge.extract<Poco::JSON::Object::Ptr>();
if (ch->has("validated"))
continue;
auto type = ch->getValue<std::string>("type");
auto url = ch->getValue<std::string>("url");
auto status = ch->getValue<std::string>("status");
auto token = ch->getValue<std::string>("token");
LOG_TEST(log, "Challenge: type: {}, url: {}, status: {}, token: {}", type, url, status, token);
if (type == HTTP_01_CHALLENGE_TYPE)
{
if (status == "valid")
continue;
callback(token);
doJWSRequest(Poco::URI(url), "{}", nullptr);
}
}
}
}
}
#endif