xrpld
Loading...
Searching...
No Matches
TrustedPublisherServer.h
1#pragma once
2
3#include <test/jtx/envconfig.h>
4
5#include <xrpl/basics/Slice.h>
6#include <xrpl/basics/base64.h>
7#include <xrpl/basics/chrono.h>
8#include <xrpl/basics/random.h>
9#include <xrpl/basics/strHex.h>
10#include <xrpl/protocol/HashPrefix.h>
11#include <xrpl/protocol/KeyType.h>
12#include <xrpl/protocol/PublicKey.h>
13#include <xrpl/protocol/SField.h>
14#include <xrpl/protocol/STObject.h>
15#include <xrpl/protocol/SecretKey.h>
16#include <xrpl/protocol/Serializer.h>
17#include <xrpl/protocol/Sign.h>
18
19#include <boost/asio.hpp>
20#include <boost/asio/ip/tcp.hpp>
21#include <boost/asio/ssl/stream.hpp>
22#include <boost/beast/core/flat_buffer.hpp>
23#include <boost/beast/http.hpp>
24#include <boost/beast/ssl.hpp>
25#include <boost/beast/version.hpp>
26#include <boost/lexical_cast.hpp>
27
28#include <chrono>
29#include <cstddef>
30#include <cstdint>
31#include <cstring>
32#include <exception>
33#include <functional>
34#include <limits>
35#include <memory>
36#include <optional>
37#include <sstream>
38#include <string>
39#include <string_view>
40#include <thread>
41#include <utility>
42#include <vector>
43
44namespace xrpl::test {
45
46class TrustedPublisherServer : public std::enable_shared_from_this<TrustedPublisherServer>
47{
48 using EndpointType = boost::asio::ip::tcp::endpoint;
49 using AddressType = boost::asio::ip::address;
50 using SocketType = boost::asio::ip::tcp::socket;
51
52 using ReqType = boost::beast::http::request<boost::beast::http::string_body>;
53 using RespType = boost::beast::http::response<boost::beast::http::string_body>;
54 using ErrorCode = boost::system::error_code;
55
58 boost::asio::ip::tcp::acceptor acceptor_;
59 // Generates a version 1 validator list, using the int parameter as the
60 // actual version.
62 // Generates a version 2 validator list, using the int parameter as the
63 // actual version.
65
66 // The SSL context is required, and holds certificates
67 bool useSSL_;
68 boost::asio::ssl::context sslCtx_{boost::asio::ssl::context::tlsv12};
69
72
73 // Load a signed certificate into the ssl context, and configure
74 // the context for use with a server.
75 void
77 {
78 sslCtx_.set_password_callback(
79 [](std::size_t, boost::asio::ssl::context_base::password_purpose) { return "test"; });
80
81 sslCtx_.set_options(
82 boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 |
83 boost::asio::ssl::context::single_dh_use);
84
85 sslCtx_.use_certificate_chain(boost::asio::buffer(cert().data(), cert().size()));
86
87 sslCtx_.use_private_key(
88 boost::asio::buffer(key().data(), key().size()),
89 boost::asio::ssl::context::file_format::pem);
90
91 sslCtx_.use_tmp_dh(boost::asio::buffer(dh().data(), dh().size()));
92 }
93
94 struct BlobInfo
95 {
96 BlobInfo(std::string b, std::string s) : blob(std::move(b)), signature(std::move(s))
97 {
98 }
99
100 // base-64 encoded JSON containing the validator list.
102 // hex-encoded signature of the blob using the publisher's signing key
104 };
105
106public:
113
114 static std::string
116 PublicKey const& pk,
117 SecretKey const& sk,
118 PublicKey const& spk,
119 SecretKey const& ssk,
120 int seq)
121 {
123 st[sfSequence] = seq;
124 st[sfPublicKey] = pk;
125 st[sfSigningPubKey] = spk;
126
127 // NOLINTBEGIN(bugprone-unchecked-optional-access) publicKeyType returns value for valid
128 // keys
129 sign(st, HashPrefix::Manifest, *publicKeyType(spk), ssk);
130 sign(st, HashPrefix::Manifest, *publicKeyType(pk), sk, sfMasterSignature);
131 // NOLINTEND(bugprone-unchecked-optional-access)
132
133 Serializer s;
134 st.add(s);
135
136 return base64Encode(std::string(static_cast<char const*>(s.data()), s.size()));
137 }
138
139 static Validator
141 {
142 auto const secret = randomSecretKey();
143 auto const masterPublic = derivePublicKey(KeyType::Ed25519, secret);
144 auto const signingKeys = randomKeyPair(KeyType::Secp256k1);
145 return {
146 .masterPublic = masterPublic,
147 .signingPublic = signingKeys.first,
148 .manifest =
149 makeManifestString(masterPublic, secret, signingKeys.first, signingKeys.second, 1),
150 };
151 }
152
153 // TrustedPublisherServer must be accessed through a shared_ptr.
154 // This constructor is only public so std::make_shared has access.
155 // The function `makeTrustedPublisherServer` should be used to create
156 // instances.
157 // The `futures` member is expected to be structured as
158 // effective / expiration time point pairs for use in version 2 UNLs
160 boost::asio::io_context& ioc,
161 std::vector<Validator> const& validators,
162 NetClock::time_point validUntil,
164 bool useSSL = false,
165 int version = 1,
166 bool immediateStart = true,
167 int sequence = 1)
168 : sock_{ioc}
169 , ep_{boost::asio::ip::make_address(xrpl::test::getEnvLocalhostAddr()),
170 // 0 means let OS pick the port based on what's available
171 0}
172 , acceptor_{ioc}
173 , useSSL_{useSSL}
176 {
177 auto const keys = randomKeyPair(KeyType::Secp256k1);
178 auto const manifest =
179 makeManifestString(publisherPublic_, publisherSecret_, keys.first, keys.second, 1);
180
181 std::vector<BlobInfo> blobInfo;
182 blobInfo.reserve(futures.size() + 1);
183 auto const [data, blob] = [&] -> std::pair<std::string, std::string> {
184 // Builds the validator list, then encodes it into a blob.
185 std::string data = "{\"sequence\":" + std::to_string(sequence) +
186 ",\"expiration\":" + std::to_string(validUntil.time_since_epoch().count()) +
187 ",\"validators\":[";
188
189 for (auto const& val : validators)
190 {
191 data += R"({"validation_public_key":")" + strHex(val.masterPublic) +
192 R"(","manifest":")" + val.manifest + "\"},";
193 }
194 data.pop_back();
195 data += "]}";
196 std::string const blob = base64Encode(data);
197 return std::make_pair(data, blob);
198 }();
199 auto const sig = strHex(sign(keys.first, keys.second, makeSlice(data)));
200 blobInfo.emplace_back(blob, sig);
201 getList_ = [blob = blob, sig, manifest, version](int interval) {
202 // Build the contents of a version 1 format UNL file
204 l << R"({"blob":")" << blob << "\"" << R"(,"signature":")" << sig << "\""
205 << R"(,"manifest":")" << manifest << "\""
206 << ",\"refresh_interval\": " << interval << ",\"version\":" << version << '}';
207 return l.str();
208 };
209 for (auto const& future : futures)
210 {
211 std::string data = "{\"sequence\":" + std::to_string(++sequence) +
212 ",\"effective\":" + std::to_string(future.first.time_since_epoch().count()) +
213 ",\"expiration\":" + std::to_string(future.second.time_since_epoch().count()) +
214 ",\"validators\":[";
215
216 // Use the same set of validators for simplicity
217 for (auto const& val : validators)
218 {
219 data += R"({"validation_public_key":")" + strHex(val.masterPublic) +
220 R"(","manifest":")" + val.manifest + "\"},";
221 }
222 data.pop_back();
223 data += "]}";
224 std::string const blob = base64Encode(data);
225 auto const sig = strHex(sign(keys.first, keys.second, makeSlice(data)));
226 blobInfo.emplace_back(blob, sig);
227 }
228 getList2_ = [blobInfo, manifest, version](int interval) {
229 // Build the contents of a version 2 format UNL file
230 // Use `version + 1` to get 2 for most tests, but have
231 // a "bad" version number for tests that provide an override.
233 for (auto const& info : blobInfo)
234 {
235 l << R"({"blob":")" << info.blob << "\"" << R"(,"signature":")" << info.signature
236 << "\"},";
237 }
238 std::string blobs = l.str();
239 blobs.pop_back();
240 l.str(std::string());
241 l << "{\"blobs_v2\": [ " << blobs << R"(],"manifest":")" << manifest << "\""
242 << ",\"refresh_interval\": " << interval << ",\"version\":" << (version + 1) << '}';
243 return l.str();
244 };
245
246 if (useSSL_)
247 {
248 // This holds the self-signed certificate used by the server
250 }
251 }
252
253 void
255 {
256 ErrorCode ec;
257 acceptor_.open(ep_.protocol());
258 acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true), ec);
259 acceptor_.bind(ep_);
260 acceptor_.listen(boost::asio::socket_base::max_listen_connections);
261 acceptor_.async_accept(
263 if (auto const p = wp.lock())
264 {
265 p->onAccept(ec);
266 }
267 });
268 }
269
270 void
272 {
273 ErrorCode ec;
274 acceptor_.close(ec);
275 // TODO: consider making this join
276 // any running do_peer threads
277 }
278
280 {
281 stop();
282 }
283
286 {
287 return acceptor_.local_endpoint();
288 }
289
290 PublicKey const&
292 {
293 return publisherPublic_;
294 }
295
296 /* CA/self-signed certs :
297 *
298 * The following three methods return certs/keys used by
299 * server and/or client to do the SSL handshake. These strings
300 * were generated using the script below. The server key and cert
301 * are used to configure the server (see loadServerCertificate
302 * above). The ca.crt should be used to configure the client
303 * when ssl verification is enabled.
304 *
305 * note:
306 * cert() ==> server.crt
307 * key() ==> server.key
308 * caCert() ==> ca.crt
309 * dh() ==> dh.pem
310 ```
311 #!/usr/bin/env bash
312
313 mkdir -p /tmp/__certs__
314 pushd /tmp/__certs__
315 rm *.crt *.key *.pem
316
317 # generate CA
318 openssl genrsa -out ca.key 2048
319 openssl req -new -x509 -nodes -days 10000 -key ca.key -out ca.crt \
320 -subj "/C=US/ST=CA/L=Los
321 Angeles/O=xrpld-unit-tests/CN=example.com" # generate private cert
322 openssl genrsa -out server.key 2048
323 # Generate certificate signing request
324 # since our unit tests can run in either ipv4 or ipv6 mode,
325 # we need to use extensions (subjectAltName) so that we can
326 # associate both ipv4 and ipv6 localhost addresses with this cert
327 cat >"extras.cnf" <<EOF
328 [req]
329 req_extensions = v3_req
330 distinguished_name = req_distinguished_name
331
332 [req_distinguished_name]
333
334 [v3_req]
335 subjectAltName = @alt_names
336
337 [alt_names]
338 DNS.1 = localhost
339 IP.1 = ::1
340 EOF
341 openssl req -new -key server.key -out server.csr \
342 -config extras.cnf \
343 -subj "/C=US/ST=California/L=San
344 Francisco/O=xrpld-unit-tests/CN=127.0.0.1" \
345
346 # Create public certificate by signing with our CA
347 openssl x509 -req -days 10000 -in server.csr -CA ca.crt -CAkey ca.key
348 -out server.crt \ -extfile extras.cnf -set_serial 01 -extensions v3_req
349
350 # generate DH params for server
351 openssl dhparam -out dh.pem 2048
352 # verify certs
353 openssl verify -CAfile ca.crt server.crt
354 openssl x509 -in server.crt -text -noout
355 popd
356 ```
357 */
358 static std::string const&
360 {
361 static std::string const kCert{R"cert(
362-----BEGIN CERTIFICATE-----
363MIIDczCCAlugAwIBAgIBATANBgkqhkiG9w0BAQsFADBjMQswCQYDVQQGEwJVUzEL
364MAkGA1UECAwCQ0ExFDASBgNVBAcMC0xvcyBBbmdlbGVzMRswGQYDVQQKDBJyaXBw
365bGVkLXVuaXQtdGVzdHMxFDASBgNVBAMMC2V4YW1wbGUuY29tMB4XDTIyMDIwNTIz
366NDk0M1oXDTQ5MDYyMzIzNDk0M1owazELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNh
367bGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xGzAZBgNVBAoMEnJpcHBs
368ZWQtdW5pdC10ZXN0czESMBAGA1UEAwwJMTI3LjAuMC4xMIIBIjANBgkqhkiG9w0B
369AQEFAAOCAQ8AMIIBCgKCAQEAueZ1hgRxwPgfeVx2AdngUYx7zYcaxcGYXyqi7izJ
370qTuBUcVcTRC/9Ip67RAEhfcgGudRS/a4Sv1ljwiRknSCcD/ZjzOFDLgbqYGSZNEs
371+T/qkwmc/L+Pbzf85HM7RjeGOd6NDQy9+oOBbUtqpTxcSGa4ln+YBFUSeoS1Aa9f
372n9vrxnWX9LgTu5dSWzH5TqFIti+Zs/v0PFjEivBIAOHPslmnzg/wCr99I6z9CAR3
373zVDe7+sxR//ivpeVE7FWjgkGixnUpZAqn69zNkJjMLNXETgOYskZdMIgbVOMr+0q
374S1Uj77mhwxKfpnB6TqUVvWLBvmBDzPjf0m0NcCf9UAjqPwIDAQABoyowKDAmBgNV
375HREEHzAdgglsb2NhbGhvc3SHEAAAAAAAAAAAAAAAAAAAAAEwDQYJKoZIhvcNAQEL
376BQADggEBAJkUFNS0CeEAKvo0ttzooXnCDH3esj2fwmLJQYLUGsAF8DFrFHTqZEcx
377hFRdr0ftEb/VKpV9dVF6xtSoMU56kHOnhbHEWADyqdKUkCDjrGBet5QdWmEwNV2L
378nYrwGQBAybMt/+1XMUV8HeLFJNHnyxfQYcW0fUsrmNGk8W0kzWuuq88qbhfXZAIx
379KiXrzYpLlM0RlpWXRfYQ6mTdSrRrLnEo5MklizVgNB8HYX78lxa06zP08oReQcfT
380GSGO8NEEq8BTVmp69zD1JyfvQcXzsi7WtkAX+/EOFZ7LesnZ6VsyjZ74wECCaQuD
381X1yu/XxHqchM+DOzzVw6wRKaM7Zsk80=
382-----END CERTIFICATE-----
383)cert"};
384 return kCert;
385 }
386
387 static std::string const&
388 key()
390 static std::string const kKey{R"pkey(
391-----BEGIN RSA PRIVATE KEY-----
392MIIEpAIBAAKCAQEAueZ1hgRxwPgfeVx2AdngUYx7zYcaxcGYXyqi7izJqTuBUcVc
393TRC/9Ip67RAEhfcgGudRS/a4Sv1ljwiRknSCcD/ZjzOFDLgbqYGSZNEs+T/qkwmc
394/L+Pbzf85HM7RjeGOd6NDQy9+oOBbUtqpTxcSGa4ln+YBFUSeoS1Aa9fn9vrxnWX
3959LgTu5dSWzH5TqFIti+Zs/v0PFjEivBIAOHPslmnzg/wCr99I6z9CAR3zVDe7+sx
396R//ivpeVE7FWjgkGixnUpZAqn69zNkJjMLNXETgOYskZdMIgbVOMr+0qS1Uj77mh
397wxKfpnB6TqUVvWLBvmBDzPjf0m0NcCf9UAjqPwIDAQABAoIBAEC9MDpOu+quvg8+
398kt4MKSFdIhQuM7WguNaTe5AkSspDrcJzT7SK275mp259QIYCzMxxuA8TSZTb8A1C
399t6dgKbi7k6FaGMCYMRHzzK6NZfMbPi6cj245q9LYlZpdQswuM/FdPpPH1zUxrNYK
400CIaooZ6ZHzlSD/eaRMgkBQEkONHrZZtEinLIvKedwssPCaXkIISmt7MFQTDOlxkf
401K0Mt1mnRREPYbYSfPEEfIyy/KDIiB5AzgGt+uPOn8Oeb1pSqy69jpYcfhSj+bo4S
402UV6qTuTfBd4qkkNI6d/Z7DcDJFFlfloG/vVgGk/beWNnL2e39vzxiebB3w+MQn4F
403Wyx5mCECgYEA22z1/ihqt9LIAWtP42oSS3S/RxlFzpp5d7QfNqFnEoVgeRhQzleP
404pRJIzVXpMYBxexZYqZA/q8xBSggz+2gmRoYnW20VIzl14DsSH378ye3FRwJB0tLy
405dWU8DC7ZB5XQCTvI9UY3voJNToknODw7RCNO1h3V3T1y6JRLdcLskk8CgYEA2OLy
406aE5bvsUaLBSv7W9NFhSuZ0p9Y0pFmRgHI7g8i/AgRZ0BgiE8u8OZSHmPJPMaNs/h
407YIEIrlsgDci1PzwrUYseRp/aiVE1kyev09/ihqRXTPpLQu6h/d63KRe/06W3t5X3
408Dmfj49hH5zGPBI/0y1ECV/n0fwnRhxSv7fNr3RECgYBEuFpOUAAkNApZj29ErNqv
4098Q9ayAp5yx1RpQLFjEUIoub05e2gwgGF1DUiwc43p59iyjvYVwnp1x13fxwwl4yt
410N6Sp2H7vOja1lCp33MB0yVeohodw7InsxFjLA/0KiBvQWH32exhIPOzTNNcooIx7
411KYeuPUfWc0FCn/cGGZcXtwKBgQC1hp1k99CKBuY05suoanOWe5DNGud/ZvaBgD7Z
412gqYKadxY52QPyknOzZNJuZQ5VM8n+S2lW9osNFDLuKUaW/3Vrh6U9c4vCC1TEPB0
4134PnzvzDiWMsNJjWnCfU7C4meVyFBIt84y3NNjAQCWNRe+S3lzdOsVqRwf4NDD+l/
414uzEYQQKBgQCJczIlwobm1Y6O41hbGZhZL/CGMNS6Z0INi2yasV0WDqYlh7XayHMD
415cK55dMILcbHqeIBq/wR6sIhw6IJcaDBfFfrJiKKDilfij2lHxR2FQrEngtTCCRV+
416ZzARzaWhQPvbDqEtLJDWuXZNXfL8/PTIs5NmuKuQ8F4+gQJpkQgwaw==
417-----END RSA PRIVATE KEY-----
418)pkey"};
419 return kKey;
420 }
421
422 static std::string const&
423 caCert()
424 {
425 static std::string const kCert{R"cert(
426-----BEGIN CERTIFICATE-----
427MIIDpzCCAo+gAwIBAgIUWc45WqaaNuaSLoFYTMC/Mjfqw/gwDQYJKoZIhvcNAQEL
428BQAwYzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRQwEgYDVQQHDAtMb3MgQW5n
429ZWxlczEbMBkGA1UECgwScmlwcGxlZC11bml0LXRlc3RzMRQwEgYDVQQDDAtleGFt
430cGxlLmNvbTAeFw0yMjAyMDUyMzQ5MDFaFw00OTA2MjMyMzQ5MDFaMGMxCzAJBgNV
431BAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLTG9zIEFuZ2VsZXMxGzAZBgNV
432BAoMEnJpcHBsZWQtdW5pdC10ZXN0czEUMBIGA1UEAwwLZXhhbXBsZS5jb20wggEi
433MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0f2JBW2XNW2wT5/ajX2qxmUY+
434aNJGfpV6gZ5CmwdQpbHrPPvJoskxwsCyr3GifzT/GtCpmb1fiu59uUAPxQEYCxiq
435V+HchX4g4Vl27xKJ0P+usxuEED9v7TCteKum9u9eMZ8UDF0fspXcnWGs9fXlyoTj
436uTRP1SBQllk44DPc/KzlrtH+QNXmr9XQnP8XvwWCgJXMx87voxEGiFFOVhkSSAOv
437v+OUGgEuq0NPgwv2LHBlYHSdkoU9F5Z/TmkCAFMShbyoUjldIz2gcWXjN2tespGo
438D6qYvasvPIpmcholBBkc0z8QDt+RNq+Wzrults7epJXy/u+txGK9cHCNlLCpAgMB
439AAGjUzBRMB0GA1UdDgQWBBS1oydh+YyqDNOFKYOvOtVMWKqV4zAfBgNVHSMEGDAW
440gBS1oydh+YyqDNOFKYOvOtVMWKqV4zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
441DQEBCwUAA4IBAQCDPyGKQwQ8Lz0yEgvIl/Uo9BtwAzlvjrLM/39qhStLQqDGSs2Q
442xFIbtjzjuLf5vR3q6OJ62CCvzqXgHkJ+hzVN/tAvyliGTdjJrK+xv1M5a+XipO2f
443c9lb4gRbFL/DyoeoWgb1Rkv3gFf0FlCYH+ZUcYb9ZYCRlGtFgOcxJI2g+T7jSLFp
4448+hSzQ6W5Sp9L6b5iJyCww1vjBvBqzNyZMNeB4gXGtd6z9vMDSvKboTdGD7wcFB+
445mRMyNekaRw+Npy4Hjou5sx272cXHHmPCSF5TjwdaibSaGjx1k0Q50mOf7S9KG5b5
4467X1e3FekJlaD02EBEhtkXURIxogOQALdFncj
447-----END CERTIFICATE-----
448)cert"};
449 return kCert;
450 }
451
452 static std::string const&
453 dh()
454 {
455 static std::string const kDH{R"dh(
456-----BEGIN DH PARAMETERS-----
457MIIBCAKCAQEAp2I2fWEUZ3sCNfitSRC/MdAhJE/bS+NO0O2tWdIdlvmIFE6B5qhC
458sGW9ojrQT8DTxBvGAcbjr/jagmlE3BV4oSnxyhP37G2mDvMOJ29J3NvFD/ZFAW0d
459BvZJ1RNvMu29NmVCyt6/jgzcqrqnami9uD93aK+zaVrlPsPEYM8xB19HXwqsEYCL
460ux2B7sqXm9Ts74HPg/EV+pcVon9phxNWxxgHlOvFc2QjZ3hXH++kzmJ4vs7N/XDB
461xbEQ+TUZ5jbJGSeBqNFKFeuOUQGJ46Io0jBSYd4rSmKUXkvElQwR+n7KF3jy1uAt
462/8hzd8tHn9TyW7Q2/CPkOA6dCXzltpOSowIBAg==
463-----END DH PARAMETERS-----
464)dh"};
465 return kDH;
466 }
467
468private:
469 struct Lambda
470 {
471 int id;
474 boost::asio::executor_work_guard<boost::asio::executor> work;
475 bool ssl;
476
478 : id(id), self(self), sock(std::move(sock)), work(this->sock.get_executor()), ssl(ssl)
479 {
480 }
481
482 void
483 operator()()
484 {
485 self.doPeer(id, std::move(sock), ssl);
486 }
487 };
488
489 void
491 {
492 if (ec || !acceptor_.is_open())
493 return;
494
495 static int nextId = 0; // NOLINT(readability-identifier-naming)
496 std::thread{Lambda{++nextId, *this, std::move(sock_), useSSL_}}.detach();
497 acceptor_.async_accept(
498 sock_, [wp = std::weak_ptr<TrustedPublisherServer>{shared_from_this()}](ErrorCode ec) {
499 if (auto const p = wp.lock())
500 {
501 p->onAccept(ec);
502 }
503 });
504 }
505
506 void
507 doPeer(int id, SocketType&& s, bool ssl)
508 {
509 using namespace boost::beast;
510 using namespace boost::asio;
511 SocketType sock(std::move(s));
512 flat_buffer sb;
513 ErrorCode ec;
514 std::optional<ssl_stream<ip::tcp::socket&>> sslStream;
515
516 if (ssl)
517 {
518 // Construct the stream around the socket
519 sslStream.emplace(sock, sslCtx_);
520 // Perform the SSL handshake
521 sslStream->handshake(ssl::stream_base::server, ec);
522 if (ec)
523 return;
524 }
525
526 for (;;)
527 {
528 RespType res;
529 ReqType req;
530 try
531 {
532 if (ssl)
533 {
534 http::read(
535 *sslStream, sb, req, ec); // NOLINT(bugprone-unchecked-optional-access)
536 // ssl_stream emplaced when ssl==true
537 }
538 else
539 {
540 http::read(sock, sb, req, ec);
541 }
542
543 if (ec)
544 break;
545
546 std::string_view const path = req.target();
547 res.insert("Server", "TrustedPublisherServer");
548 res.version(req.version());
549 res.keep_alive(req.keep_alive());
550 bool prepare = true;
551
552 if (path.starts_with("/validators2"))
553 {
554 res.result(http::status::ok);
555 res.insert("Content-Type", "application/json");
556 if (path == "/validators2/bad")
557 {
558 res.body() = "{ 'bad': \"2']";
559 }
560 else if (path == "/validators2/missing")
561 {
562 res.body() = "{\"version\": 2}";
563 }
564 else
565 {
566 int refresh = 5;
567 static constexpr char const* kRefreshPrefix = "/validators2/refresh/";
568 if (path.starts_with(kRefreshPrefix))
569 {
570 refresh = boost::lexical_cast<unsigned int>(
571 path.substr(strlen(kRefreshPrefix)));
572 }
573 res.body() = getList2_(refresh);
574 }
575 }
576 else if (path.starts_with("/validators"))
577 {
578 res.result(http::status::ok);
579 res.insert("Content-Type", "application/json");
580 if (path == "/validators/bad")
581 {
582 res.body() = "{ 'bad': \"1']";
583 }
584 else if (path == "/validators/missing")
585 {
586 res.body() = "{\"version\": 1}";
587 }
588 else
589 {
590 int refresh = 5;
591 static constexpr char const* kRefreshPrefix = "/validators/refresh/";
592 if (path.starts_with(kRefreshPrefix))
593 {
594 refresh = boost::lexical_cast<unsigned int>(
595 path.substr(strlen(kRefreshPrefix)));
596 }
597 res.body() = getList_(refresh);
598 }
599 }
600 else if (path.starts_with("/textfile"))
601 {
602 prepare = false;
603 res.result(http::status::ok);
604 res.insert("Content-Type", "text/example");
605 // if huge was requested, lie about content length
606 std::uint64_t const cl = path.starts_with("/textfile/huge")
608 : 1024;
609 res.content_length(cl);
610 if (req.method() == http::verb::get)
611 {
612 std::stringstream body;
613 for (auto i = 0; i < 1024; ++i)
614 {
615 body << static_cast<char>(randInt<short>(32, 126)),
616 res.body() = body.str();
617 }
618 }
619 }
620 else if (path.starts_with("/sleep/"))
621 {
622 auto const sleepSec = boost::lexical_cast<unsigned int>(path.substr(7));
623 std::this_thread::sleep_for(std::chrono::seconds(sleepSec));
624 }
625 else if (path.starts_with("/redirect"))
626 {
627 if (path.ends_with("/301"))
628 {
629 res.result(http::status::moved_permanently);
630 }
631 else if (path.ends_with("/302"))
632 {
633 res.result(http::status::found);
634 }
635 else if (path.ends_with("/307"))
636 {
637 res.result(http::status::temporary_redirect);
638 }
639 else if (path.ends_with("/308"))
640 {
641 res.result(http::status::permanent_redirect);
642 }
643
644 std::stringstream location;
645 if (path.starts_with("/redirect_to/"))
646 {
647 location << path.substr(13);
648 }
649 else if (!path.starts_with("/redirect_nolo"))
650 {
651 location << (ssl ? "https://" : "http://") << localEndpoint()
652 << (path.starts_with("/redirect_forever/") ? path : "/validators");
653 }
654 if (!location.str().empty())
655 res.insert("Location", location.str());
656 }
657 else
658 {
659 // unknown request
660 res.result(boost::beast::http::status::not_found);
661 res.insert("Content-Type", "text/html");
662 res.body() = "The file '" + std::string(path) +
663 "' was not "
664 "found";
665 }
666
667 if (prepare)
668 res.prepare_payload();
669 }
670 catch (std::exception const& e)
671 {
672 res = {};
673 res.result(boost::beast::http::status::internal_server_error);
674 res.version(req.version());
675 res.insert("Server", "TrustedPublisherServer");
676 res.insert("Content-Type", "text/html");
677 res.body() = std::string{"An internal error occurred"} + e.what();
678 res.prepare_payload();
679 }
680
681 if (ssl)
682 {
683 write(*sslStream, res, ec); // NOLINT(bugprone-unchecked-optional-access)
684 // ssl_stream emplaced when ssl==true
685 }
686 else
687 {
688 write(sock, res, ec);
689 }
690
691 if (ec || req.need_eof())
692 break;
693 }
694
695 // Perform the SSL shutdown
696 if (ssl)
697 sslStream->shutdown(ec); // NOLINT(bugprone-unchecked-optional-access) ssl_stream
698 // emplaced when ssl==true
699 }
700};
701
702inline std::shared_ptr<TrustedPublisherServer>
704 boost::asio::io_context& ioc,
706 NetClock::time_point validUntil,
708 bool useSSL = false,
709 int version = 1,
710 bool immediateStart = true,
711 int sequence = 1)
712{
714 ioc, validators, validUntil, futures, useSSL, version, sequence);
715 if (immediateStart)
716 r->start();
717 return r;
718}
719
720} // namespace xrpl::test
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
A public key.
Definition PublicKey.h:53
void add(Serializer &s) const override
Definition STObject.cpp:123
A secret key.
Definition SecretKey.h:24
std::size_t size() const noexcept
Definition Serializer.h:147
void const * data() const noexcept
Definition Serializer.h:153
static std::string makeManifestString(PublicKey const &pk, SecretKey const &sk, PublicKey const &spk, SecretKey const &ssk, int seq)
boost::beast::http::response< boost::beast::http::string_body > RespType
void doPeer(int id, SocketType &&s, bool ssl)
boost::asio::ip::tcp::acceptor acceptor_
std::function< std::string(int)> getList_
boost::asio::ip::tcp::endpoint EndpointType
TrustedPublisherServer(boost::asio::io_context &ioc, std::vector< Validator > const &validators, NetClock::time_point validUntil, std::vector< std::pair< NetClock::time_point, NetClock::time_point > > const &futures, bool useSSL=false, int version=1, bool immediateStart=true, int sequence=1)
boost::beast::http::request< boost::beast::http::string_body > ReqType
boost::asio::ip::tcp::socket SocketType
std::function< std::string(int)> getList2_
T emplace_back(T... args)
T emplace(T... args)
T ends_with(T... args)
T make_pair(T... args)
T make_shared(T... args)
T max(T... args)
T move(T... args)
STL namespace.
void write(nudb::detail::ostream &os, std::size_t t)
Definition Varint.h:120
void sign(json::Value const &jv, Account const &account, json::Value &sigObject, HashPrefix prefix)
Sign automatically into a specific Json field of the jv object.
Definition utility.cpp:52
std::shared_ptr< TrustedPublisherServer > makeTrustedPublisherServer(boost::asio::io_context &ioc, std::vector< TrustedPublisherServer::Validator > const &validators, NetClock::time_point validUntil, std::vector< std::pair< NetClock::time_point, NetClock::time_point > > const &futures, bool useSSL=false, int version=1, bool immediateStart=true, int sequence=1)
char const * getEnvLocalhostAddr()
Definition envconfig.h:16
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
KeyType
Definition KeyType.h:8
std::pair< PublicKey, SecretKey > randomKeyPair(KeyType type)
Create a key pair using secure random numbers.
PublicKey derivePublicKey(KeyType type, SecretKey const &sk)
Derive the public key from a secret key.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
SField const sfGeneric
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
SecretKey randomSecretKey()
Create a secret key using secure random numbers.
std::string base64Encode(std::uint8_t const *data, std::size_t len)
@ Manifest
Manifest.
Definition HashPrefix.h:84
T pop_back(T... args)
T reserve(T... args)
T sleep_for(T... args)
T starts_with(T... args)
T str(T... args)
T strlen(T... args)
Lambda(int id, TrustedPublisherServer &self, SocketType &&sock, bool ssl)
boost::asio::executor_work_guard< boost::asio::executor > work
T substr(T... args)
T time_since_epoch(T... args)
T to_string(T... args)
T what(T... args)