Skip to main content

jsonrpsee_server/transport/
http.rs

1use crate::{server::handle_rpc_call, BatchRequestConfig, HttpRequest, HttpResponse, LOG_TARGET};
2use http::Method;
3use hyper::body::Bytes;
4use jsonrpsee_core::{
5    http_helpers::{read_body, HttpError},
6    middleware::RpcServiceT,
7    BoxError,
8};
9use std::time::Duration;
10
11/// Returns true if the `content_type` header indicates a valid JSON message.
12///
13/// Only the media type is compared. The parameter list after it may be spaced freely and may quote
14/// its values, so comparing the whole header would reject spellings that mean the same type, such
15/// as `application/json; charset="utf-8"`. The media type is matched as a prefix rather than split
16/// off and trimmed, so rejecting another type never walks the whitespace a client put after it.
17fn is_json(content_type: Option<&hyper::header::HeaderValue>) -> bool {
18    content_type.and_then(|val| val.to_str().ok()).is_some_and(|content| {
19        ["application/json", "application/json-rpc"].into_iter().any(|media_type| {
20            content.split_at_checked(media_type.len()).is_some_and(|(prefix, params)| {
21                prefix.eq_ignore_ascii_case(media_type) &&
22                    matches!(params.trim_ascii_start().as_bytes(), [] | [b';', ..])
23            })
24        })
25    })
26}
27
28/// Make JSON-RPC HTTP call with a service [`RpcServiceT`]
29///
30/// Fails if the HTTP request was a malformed JSON-RPC request.
31pub async fn call_with_service<S, B>(
32    request: HttpRequest<B>,
33    batch_config: BatchRequestConfig,
34    max_request_size: u32,
35    request_body_read_timeout: Option<Duration>,
36    rpc_service: &S,
37) -> HttpResponse
38where
39    B: http_body::Body<Data = Bytes> + Send + 'static,
40    B::Data: Send,
41    B::Error: Into<BoxError>,
42    S: RpcServiceT + Send,
43{
44    // Only the `POST` method is allowed.
45    match *request.method() {
46        Method::POST if is_json(request.headers().get(hyper::header::CONTENT_TYPE)) => {
47            let (parts, body) = request.into_parts();
48
49            // Bound how long reading the request body may take, like the response write and the
50            // compressed-body read.
51            let read = read_body(&parts.headers, body, max_request_size);
52            let read = async {
53                match request_body_read_timeout {
54                    Some(timeout) => tokio::time::timeout(timeout, read).await,
55                    None => Ok(read.await),
56                }
57            };
58            let (body, is_single) = match read.await {
59                Ok(Ok(r)) => r,
60                Ok(Err(HttpError::TooLarge)) => return response::too_large(max_request_size),
61                Ok(Err(HttpError::Malformed)) => return response::malformed(),
62                Ok(Err(HttpError::Stream(e))) => {
63                    tracing::warn!(target: LOG_TARGET, "Internal error reading request body: {}", e);
64                    return response::internal_error();
65                }
66                Err(_elapsed) => return response::request_timeout(parts.version),
67            };
68
69            let mut rp =
70                handle_rpc_call(&body, is_single, batch_config, max_request_size, rpc_service)
71                    .await;
72            // HTTP/1.0 has no chunked encoding, so the client couldn't tell an aborted stream
73            // from a complete response.
74            if parts.version < hyper::Version::HTTP_11 {
75                rp = rp.buffer().await;
76            }
77
78            // If the response is empty it means that it was a notification or empty batch.
79            // For HTTP these are just ACK:ed with a empty body.
80            response::from_method_response(rp)
81        }
82        // Error scenarios:
83        Method::POST => response::unsupported_content_type(),
84        _ => response::method_not_allowed(),
85    }
86}
87
88/// HTTP response helpers.
89pub mod response {
90    use futures_util::StreamExt;
91    use http::Version;
92    use http_body::Frame;
93    use http_body_util::StreamBody;
94    use jsonrpsee_core::server::{MethodResponse, ResponseBody};
95    use jsonrpsee_types::{
96        error::{reject_too_big_request, ErrorCode},
97        ErrorObjectOwned, Id, Response, ResponsePayload,
98    };
99
100    use crate::{HttpBody, HttpResponse};
101
102    const JSON: &str = "application/json; charset=utf-8";
103    const TEXT: &str = "text/plain";
104
105    /// Create a response for json internal error.
106    pub fn internal_error() -> HttpResponse {
107        let err = ResponsePayload::<()>::error(ErrorObjectOwned::from(ErrorCode::InternalError));
108        let rp = Response::new(err, Id::Null);
109        let error = serde_json::to_string(&rp).expect("built from known-good data; qed");
110
111        from_template(hyper::StatusCode::INTERNAL_SERVER_ERROR, error, JSON)
112    }
113
114    /// Create a text/plain response for disallowed method used.
115    pub fn method_not_allowed() -> HttpResponse {
116        from_template(
117            hyper::StatusCode::METHOD_NOT_ALLOWED,
118            "Used HTTP Method is not allowed. POST is required\n",
119            TEXT,
120        )
121    }
122
123    /// Create a json response for oversized requests (413)
124    pub fn too_large(limit: u32) -> HttpResponse {
125        let err = ResponsePayload::<()>::error(reject_too_big_request(limit));
126        let rp = Response::new(err, Id::Null);
127        let error = serde_json::to_string(&rp).expect("JSON serialization infallible; qed");
128
129        from_template(hyper::StatusCode::PAYLOAD_TOO_LARGE, error, JSON)
130    }
131
132    /// Create a 408 response for a request body that did not finish arriving in time.
133    pub fn request_timeout(version: Version) -> HttpResponse {
134        if version == Version::HTTP_2 {
135            // End the stream with the headers so HTTP/2 data flow control cannot hold the permit.
136            let mut response = HttpResponse::new(HttpBody::empty());
137            *response.status_mut() = hyper::StatusCode::REQUEST_TIMEOUT;
138            return response;
139        }
140
141        from_template(
142            hyper::StatusCode::REQUEST_TIMEOUT,
143            "Request body was not received in time\n",
144            TEXT,
145        )
146    }
147
148    /// Create a json response for empty or malformed requests (400)
149    pub fn malformed() -> HttpResponse {
150        let rp = Response::new(ResponsePayload::<()>::error(ErrorCode::ParseError), Id::Null);
151        let error = serde_json::to_string(&rp).expect("JSON serialization infallible; qed");
152
153        from_template(hyper::StatusCode::BAD_REQUEST, error, JSON)
154    }
155
156    /// Create a response body.
157    pub(crate) fn from_template(
158        status: hyper::StatusCode,
159        body: impl Into<HttpBody>,
160        content_type: &'static str,
161    ) -> HttpResponse {
162        HttpResponse::builder()
163            .status(status)
164            .header("content-type", hyper::header::HeaderValue::from_static(content_type))
165            .body(body.into())
166            // Parsing `StatusCode` and `HeaderValue` is infallible but
167            // parsing body content is not.
168            .expect("Unable to parse response body for type conversion")
169    }
170
171    /// Create a response from a method response.
172    ///
173    /// A streamed response is sent in parts as they are produced.
174    /// If it fails after it started, the body ends with an error, so hyper aborts the response
175    /// instead of completing it with truncated JSON.
176    pub fn from_method_response(rp: MethodResponse) -> HttpResponse {
177        let body = match rp.into_body() {
178            ResponseBody::Json(json) => HttpBody::from(json),
179            ResponseBody::Stream(stream) => HttpBody::new(StreamBody::new(stream.map(|part| {
180                part.map(Frame::data).inspect_err(|err| {
181                    // Not `LOG_TARGET`: reth turns `jsonrpsee-server` off by default, and the
182                    // client only sees the connection drop.
183                    tracing::warn!(target: "rpc", code = err.code(), "Aborting streamed response");
184                })
185            }))),
186        };
187        from_template(hyper::StatusCode::OK, body, JSON)
188    }
189
190    /// Create a response for unsupported content type.
191    pub fn unsupported_content_type() -> HttpResponse {
192        from_template(
193            hyper::StatusCode::UNSUPPORTED_MEDIA_TYPE,
194            "Supplied content type is not allowed. Content-Type: application/json is required\n",
195            TEXT,
196        )
197    }
198
199    /// Create a response for when the server is busy and can't accept more requests.
200    pub fn too_many_requests() -> HttpResponse {
201        from_template(
202            hyper::StatusCode::TOO_MANY_REQUESTS,
203            "Too many connections. Please try again later.",
204            TEXT,
205        )
206    }
207
208    /// Create a response for when the server denied the request.
209    pub fn denied() -> HttpResponse {
210        from_template(hyper::StatusCode::FORBIDDEN, HttpBody::default(), TEXT)
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use hyper::header::HeaderValue;
218
219    #[test]
220    fn json_content_types_are_accepted_whatever_their_parameters() {
221        for accepted in [
222            "application/json",
223            "application/json-rpc",
224            "APPLICATION/JSON",
225            "application/json; charset=utf-8",
226            "application/json;charset=utf-8",
227            "application/json;  charset=UTF-8",
228            r#"application/json; charset="utf-8""#,
229            "application/json ; charset=utf-8",
230            "application/json-rpc; charset=utf-8",
231            "application/json;charset=utf-8;foo=bar",
232        ] {
233            assert!(is_json(Some(&HeaderValue::from_str(accepted).unwrap())), "{accepted}");
234        }
235
236        for rejected in [
237            "",
238            "text/plain",
239            "application/jsonx",
240            "application/json x",
241            "application/json-rpcx",
242            "application/octet-stream; charset=utf-8",
243        ] {
244            assert!(!is_json(Some(&HeaderValue::from_str(rejected).unwrap())), "{rejected}");
245        }
246
247        assert!(!is_json(None));
248    }
249}