Clio develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
WebHandlers.hpp
1//------------------------------------------------------------------------------
2/*
3 This file is part of clio: https://github.com/XRPLF/clio
4 Copyright (c) 2024, the clio developers.
5
6 Permission to use, copy, modify, and distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19
20#pragma once
21
22#include "rpc/Errors.hpp"
23#include "util/log/Logger.hpp"
24#include "web/AdminVerificationStrategy.hpp"
25#include "web/SubscriptionContextInterface.hpp"
26#include "web/dosguard/DOSGuardInterface.hpp"
27#include "web/ng/Connection.hpp"
28#include "web/ng/Request.hpp"
29#include "web/ng/Response.hpp"
30
31#include <boost/asio/spawn.hpp>
32#include <boost/beast/http/status.hpp>
33#include <boost/json/array.hpp>
34#include <boost/json/parse.hpp>
35
36#include <exception>
37#include <functional>
38#include <memory>
39#include <utility>
40
41namespace app {
42
47 std::reference_wrapper<web::dosguard::DOSGuardInterface> dosguard_;
48
49public:
56
63 std::expected<void, web::ng::Response>
64 operator()(web::ng::Connection const& connection);
65};
66
71 std::reference_wrapper<web::dosguard::DOSGuardInterface> dosguard_;
72
73public:
80
86 void
87 operator()(web::ng::Connection const& connection);
88};
89
94 std::shared_ptr<web::AdminVerificationStrategy> adminVerifier_;
95
96public:
102 MetricsHandler(std::shared_ptr<web::AdminVerificationStrategy> adminVerifier);
103
113 web::ng::Request const& request,
114 web::ng::ConnectionMetadata& connectionMetadata,
116 boost::asio::yield_context
117 );
118};
119
124public:
133 web::ng::Request const& request,
136 boost::asio::yield_context
137 );
138};
139
145template <typename RpcHandlerType>
147 util::Logger webServerLog_{"WebServer"};
148 std::shared_ptr<web::AdminVerificationStrategy> adminVerifier_;
149 std::reference_wrapper<RpcHandlerType> rpcHandler_;
150 std::reference_wrapper<web::dosguard::DOSGuardInterface> dosguard_;
151
152public:
161 std::shared_ptr<web::AdminVerificationStrategy> adminVerifier,
162 RpcHandlerType& rpcHandler,
164 )
165 : adminVerifier_(std::move(adminVerifier)), rpcHandler_(rpcHandler), dosguard_(dosguard)
166 {
167 }
168
180 web::ng::Request const& request,
181 web::ng::ConnectionMetadata& connectionMetadata,
182 web::SubscriptionContextPtr subscriptionContext,
183 boost::asio::yield_context yield
184 )
185 {
186 if (not dosguard_.get().request(connectionMetadata.ip())) {
187 auto error = rpc::makeError(rpc::RippledError::rpcSLOW_DOWN);
188
189 if (not request.isHttp()) {
190 try {
191 auto requestJson = boost::json::parse(request.message());
192 if (requestJson.is_object() && requestJson.as_object().contains("id"))
193 error["id"] = requestJson.as_object().at("id");
194 error["request"] = request.message();
195 } catch (std::exception const&) {
196 error["request"] = request.message();
197 }
198 }
199 return web::ng::Response{boost::beast::http::status::service_unavailable, error, request};
200 }
201 LOG(webServerLog_.info()) << connectionMetadata.tag()
202 << "Received request from ip = " << connectionMetadata.ip()
203 << " - posting to WorkQueue";
204
205 connectionMetadata.setIsAdmin([this, &request, &connectionMetadata]() {
206 return adminVerifier_->isAdmin(request.httpHeaders(), connectionMetadata.ip());
207 });
208
209 try {
210 auto response = rpcHandler_(request, connectionMetadata, std::move(subscriptionContext), yield);
211
212 if (not dosguard_.get().add(connectionMetadata.ip(), response.message().size())) {
213 auto jsonResponse = boost::json::parse(response.message()).as_object();
214 jsonResponse["warning"] = "load";
215 if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) {
216 jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::WarnRpcRateLimit));
217 } else {
218 jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)};
219 }
220 response.setMessage(jsonResponse);
221 }
222
223 return response;
224 } catch (std::exception const&) {
225 return web::ng::Response{
226 boost::beast::http::status::internal_server_error,
227 rpc::makeError(rpc::RippledError::rpcINTERNAL),
228 request
229 };
230 }
231 }
232};
233
234} // namespace app
A function object to be called when a connection is disconnected.
Definition WebHandlers.hpp:70
DisconnectHook(web::dosguard::DOSGuardInterface &dosguard)
Construct a new DisconnectHook object.
Definition WebHandlers.cpp:57
void operator()(web::ng::Connection const &connection)
The call of the function object.
Definition WebHandlers.cpp:62
A function object that handles the health check endpoint.
Definition WebHandlers.hpp:123
web::ng::Response operator()(web::ng::Request const &request, web::ng::ConnectionMetadata &, web::SubscriptionContextPtr, boost::asio::yield_context)
The call of the function object.
Definition WebHandlers.cpp:93
A function object that handles the metrics endpoint.
Definition WebHandlers.hpp:93
MetricsHandler(std::shared_ptr< web::AdminVerificationStrategy > adminVerifier)
Construct a new MetricsHandler object.
Definition WebHandlers.cpp:67
web::ng::Response operator()(web::ng::Request const &request, web::ng::ConnectionMetadata &connectionMetadata, web::SubscriptionContextPtr, boost::asio::yield_context)
The call of the function object.
Definition WebHandlers.cpp:73
A function object that checks if the connection is allowed to proceed.
Definition WebHandlers.hpp:46
OnConnectCheck(web::dosguard::DOSGuardInterface &dosguard)
Construct a new OnConnectCheck object.
Definition WebHandlers.cpp:40
std::expected< void, web::ng::Response > operator()(web::ng::Connection const &connection)
Check if the connection is allowed to proceed.
Definition WebHandlers.cpp:45
A function object that handles the websocket endpoint.
Definition WebHandlers.hpp:146
RequestHandler(std::shared_ptr< web::AdminVerificationStrategy > adminVerifier, RpcHandlerType &rpcHandler, web::dosguard::DOSGuardInterface &dosguard)
Construct a new RequestHandler object.
Definition WebHandlers.hpp:160
web::ng::Response operator()(web::ng::Request const &request, web::ng::ConnectionMetadata &connectionMetadata, web::SubscriptionContextPtr subscriptionContext, boost::asio::yield_context yield)
The call of the function object.
Definition WebHandlers.hpp:179
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:110
Pump info(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:205
BaseTagDecorator const & tag() const
Getter for tag decorator.
Definition Taggable.hpp:267
The interface of a denial of service guard.
Definition DOSGuardInterface.hpp:44
An interface for a connection metadata class.
Definition Connection.hpp:43
std::string const & ip() const
Get the ip of the client.
Definition Connection.cpp:37
void setIsAdmin(T &&setter)
Set the isAdmin field.
Definition Connection.hpp:90
A class representing a connection to a client.
Definition Connection.hpp:100
Represents an HTTP or WebSocket request.
Definition Request.hpp:37
HttpHeaders const & httpHeaders() const
Get the headers of the request.
Definition Request.cpp:110
std::string_view message() const
Get the body (in case of an HTTP request) or the message (in case of a WebSocket request).
Definition Request.cpp:93
bool isHttp() const
Check if the request is an HTTP request.
Definition Request.cpp:78
Represents an HTTP or Websocket response.
Definition Response.hpp:40
boost::json::object makeError(RippledError err, std::optional< std::string_view > customError, std::optional< std::string_view > customMessage)
Generate JSON from a rpc::RippledError.
Definition Errors.cpp:120
boost::json::object makeWarning(WarningCode code)
Generate JSON from a rpc::WarningCode.
Definition Errors.cpp:65
std::shared_ptr< SubscriptionContextInterface > SubscriptionContextPtr
An alias for shared pointer to a SubscriptionContextInterface.
Definition SubscriptionContextInterface.hpp:86