1use std::{fmt, future::Future, pin::Pin};
6
7use futures::{future, FutureExt};
8use http_body_util::{BodyExt, Limited};
9use hyper::header;
10use jsonrpsee::{
11 core::BoxError,
12 server::{HttpBody, HttpRequest, HttpResponse},
13};
14use jsonrpsee_types::ErrorObject;
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17use subtle::ConstantTimeEq;
18use tower::Service;
19
20use super::cookie::Cookie;
21
22use base64::{engine::general_purpose::STANDARD, Engine as _};
23
24#[derive(Clone, Debug)]
58pub struct HttpRequestMiddleware<S> {
59 service: S,
60 auth: Option<RpcAuth>,
61 max_request_body_size: usize,
62}
63
64#[derive(Clone)]
65pub(super) enum RpcAuth {
66 Cookie(Cookie),
67 Static([u8; 32]),
68}
69
70impl fmt::Debug for RpcAuth {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(match self {
73 Self::Cookie(_) => "Cookie(..)",
74 Self::Static(_) => "Static(..)",
75 })
76 }
77}
78
79impl RpcAuth {
80 pub(super) fn static_credentials(user: &str, password: &str) -> Self {
81 Self::Static(
83 Sha256::new()
84 .chain_update(user)
85 .chain_update(b":")
86 .chain_update(password)
87 .finalize()
88 .into(),
89 )
90 }
91
92 fn authenticate(&self, authorization: &str) -> bool {
93 let encoded = match self {
94 Self::Cookie(_) => authorization.split_whitespace().nth(1),
96 Self::Static(_) => authorization
97 .split_once(' ')
98 .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Basic"))
99 .map(|(_, value)| value.trim_start_matches(' ')),
100 };
101 let Some(credentials) = encoded.and_then(|value| STANDARD.decode(value).ok()) else {
102 return false;
103 };
104 match self {
105 Self::Cookie(cookie) => std::str::from_utf8(&credentials)
106 .ok()
107 .and_then(|pair| pair.split_once(':'))
108 .is_some_and(|(_, password)| cookie.authenticate(password.to_owned())),
109 Self::Static(expected) => expected.ct_eq(&Sha256::digest(credentials)).into(),
110 }
111 }
112}
113
114impl<S> HttpRequestMiddleware<S> {
115 pub fn new(service: S, cookie: Option<Cookie>, max_request_body_size: usize) -> Self {
117 Self::with_auth(service, cookie.map(RpcAuth::Cookie), max_request_body_size)
118 }
119
120 fn with_auth(service: S, auth: Option<RpcAuth>, max_request_body_size: usize) -> Self {
122 Self {
123 service,
124 auth,
125 max_request_body_size,
126 }
127 }
128
129 pub fn check_credentials(&self, headers: &header::HeaderMap) -> bool {
131 self.auth.as_ref().is_none_or(|auth| {
132 headers
133 .get(header::AUTHORIZATION)
134 .and_then(|auth_header| auth_header.to_str().ok())
135 .is_some_and(|authorization| auth.authenticate(authorization))
136 })
137 }
138
139 fn unauthenticated_response() -> HttpResponse<HttpBody> {
144 let error = ErrorObject::borrowed(401, "unauthenticated method", None);
145 let body = serde_json::json!({
146 "jsonrpc": "2.0",
147 "error": error,
148 "id": null,
149 });
150
151 let mut response = HttpResponse::new(HttpBody::from(body.to_string()));
152 *response.status_mut() = hyper::StatusCode::UNAUTHORIZED;
153 response.headers_mut().insert(
154 header::CONTENT_TYPE,
155 header::HeaderValue::from_static("application/json"),
156 );
157 response.headers_mut().insert(
158 header::WWW_AUTHENTICATE,
159 header::HeaderValue::from_static("Basic realm=\"jsonrpc\""),
160 );
161 response
162 }
163
164 pub fn insert_or_replace_content_type_header(headers: &mut header::HeaderMap) {
186 if !headers.contains_key(header::CONTENT_TYPE)
187 || headers
188 .get(header::CONTENT_TYPE)
189 .filter(|value| {
190 value
191 .to_str()
192 .ok()
193 .unwrap_or_default()
194 .starts_with("text/plain")
195 })
196 .is_some()
197 {
198 headers.insert(
199 header::CONTENT_TYPE,
200 header::HeaderValue::from_static("application/json"),
201 );
202 }
203 }
204
205 async fn request_to_json_rpc_2(
207 request: HttpRequest<HttpBody>,
208 max_request_body_size: usize,
209 ) -> Result<(JsonRpcVersion, HttpRequest<HttpBody>), BoxError> {
210 let (parts, body) = request.into_parts();
211 let bytes = Limited::new(body, max_request_body_size)
212 .collect()
213 .await?
214 .to_bytes();
215 let (version, bytes) =
216 if let Ok(request) = serde_json::from_slice::<'_, JsonRpcRequest>(bytes.as_ref()) {
217 let version = request.version();
218 if matches!(version, JsonRpcVersion::Unknown) {
219 (version, bytes)
220 } else {
221 (
222 version,
223 serde_json::to_vec(&request.into_2()).expect("valid").into(),
224 )
225 }
226 } else {
227 (JsonRpcVersion::Unknown, bytes)
228 };
229 Ok((
230 version,
231 HttpRequest::from_parts(parts, HttpBody::from(Vec::from(bytes))),
233 ))
234 }
235 async fn response_from_json_rpc_2(
237 version: JsonRpcVersion,
238 response: HttpResponse<HttpBody>,
239 ) -> Result<HttpResponse<HttpBody>, BoxError> {
240 let (parts, body) = response.into_parts();
241 let bytes = body.collect().await?.to_bytes();
242 let bytes =
243 if let Ok(response) = serde_json::from_slice::<'_, JsonRpcResponse>(bytes.as_ref()) {
244 serde_json::to_vec(&response.into_version(version))
245 .expect("valid")
246 .into()
247 } else {
248 bytes
249 };
250 Ok(HttpResponse::from_parts(
251 parts,
252 HttpBody::from(bytes.as_ref().to_vec()),
253 ))
254 }
255}
256
257#[derive(Clone)]
259pub struct HttpRequestMiddlewareLayer {
260 auth: Option<RpcAuth>,
261 max_request_body_size: usize,
262}
263
264impl HttpRequestMiddlewareLayer {
265 pub fn new(cookie: Option<Cookie>, max_request_body_size: usize) -> Self {
267 Self::with_auth(cookie.map(RpcAuth::Cookie), max_request_body_size)
268 }
269
270 pub(super) fn with_auth(auth: Option<RpcAuth>, max_request_body_size: usize) -> Self {
272 Self {
273 auth,
274 max_request_body_size,
275 }
276 }
277}
278
279impl<S> tower::Layer<S> for HttpRequestMiddlewareLayer {
280 type Service = HttpRequestMiddleware<S>;
281
282 fn layer(&self, service: S) -> Self::Service {
283 HttpRequestMiddleware::with_auth(service, self.auth.clone(), self.max_request_body_size)
284 }
285}
286
287impl<S> Service<HttpRequest<HttpBody>> for HttpRequestMiddleware<S>
288where
289 S: Service<HttpRequest, Response = HttpResponse> + std::clone::Clone + Send + 'static,
290 S::Error: Into<BoxError> + 'static,
291 S::Future: Send + 'static,
292{
293 type Response = S::Response;
294 type Error = BoxError;
295 type Future =
296 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
297
298 fn poll_ready(
299 &mut self,
300 cx: &mut std::task::Context<'_>,
301 ) -> std::task::Poll<Result<(), Self::Error>> {
302 self.service.poll_ready(cx).map_err(Into::into)
303 }
304
305 fn call(&mut self, mut request: HttpRequest<HttpBody>) -> Self::Future {
306 if !self.check_credentials(request.headers_mut()) {
308 return future::ok(Self::unauthenticated_response()).boxed();
309 }
310
311 Self::insert_or_replace_content_type_header(request.headers_mut());
313
314 let mut service = self.service.clone();
315 let max_request_body_size = self.max_request_body_size;
316
317 async move {
318 let (version, request) =
319 Self::request_to_json_rpc_2(request, max_request_body_size).await?;
320 let response = service.call(request).await.map_err(Into::into)?;
321 Self::response_from_json_rpc_2(version, response).await
322 }
323 .boxed()
324 }
325}
326
327#[derive(Clone, Copy, Debug)]
328enum JsonRpcVersion {
329 Bitcoind,
331 Lightwalletd,
334 TwoPointZero,
336 Unknown,
338}
339
340#[derive(Debug, Deserialize, Serialize)]
342pub(super) struct JsonRpcRequest {
343 #[serde(skip_serializing_if = "Option::is_none")]
344 jsonrpc: Option<String>,
345 method: String,
346 #[serde(skip_serializing_if = "Option::is_none")]
347 params: Option<serde_json::Value>,
348 #[serde(
349 default,
350 deserialize_with = "deserialize_present_id",
351 skip_serializing_if = "Option::is_none"
352 )]
353 id: Option<serde_json::Value>,
354}
355
356fn deserialize_present_id<'de, D: serde::Deserializer<'de>>(
357 deserializer: D,
358) -> Result<Option<serde_json::Value>, D::Error> {
359 serde_json::Value::deserialize(deserializer).map(Some)
360}
361
362impl JsonRpcRequest {
363 fn version(&self) -> JsonRpcVersion {
364 match (self.jsonrpc.as_deref(), &self.params, &self.id) {
365 (
366 Some("2.0"),
367 _,
368 None
369 | Some(
370 serde_json::Value::Null
371 | serde_json::Value::String(_)
372 | serde_json::Value::Number(_),
373 ),
374 ) => JsonRpcVersion::TwoPointZero,
375 (Some("1.0"), Some(_), Some(_)) => JsonRpcVersion::Lightwalletd,
376 (None, Some(_), Some(_)) => JsonRpcVersion::Bitcoind,
377 _ => JsonRpcVersion::Unknown,
378 }
379 }
380
381 pub(super) fn into_2(mut self) -> Self {
382 self.jsonrpc = Some("2.0".into());
383 self
384 }
385}
386#[derive(Debug, Deserialize, Serialize)]
388struct JsonRpcResponse {
389 #[serde(skip_serializing_if = "Option::is_none")]
390 jsonrpc: Option<String>,
391 id: serde_json::Value,
392 #[serde(skip_serializing_if = "Option::is_none")]
393 result: Option<Box<serde_json::value::RawValue>>,
394 #[serde(skip_serializing_if = "Option::is_none")]
395 error: Option<serde_json::Value>,
396}
397
398impl JsonRpcResponse {
399 fn into_version(mut self, version: JsonRpcVersion) -> Self {
400 match version {
401 JsonRpcVersion::Bitcoind => {
402 self.jsonrpc = None;
403 self.result = self
404 .result
405 .or_else(|| serde_json::value::to_raw_value(&()).ok());
406 self.error = self.error.or(Some(serde_json::Value::Null));
407 }
408 JsonRpcVersion::Lightwalletd => {
409 self.jsonrpc = Some("1.0".into());
410 self.result = self
411 .result
412 .or_else(|| serde_json::value::to_raw_value(&()).ok());
413 self.error = self.error.or(Some(serde_json::Value::Null));
414 }
415 JsonRpcVersion::TwoPointZero => {
416 assert_eq!(self.jsonrpc.as_deref(), Some("2.0"));
420 if self.error.is_none() {
421 self.result = self
422 .result
423 .or_else(|| serde_json::value::to_raw_value(&()).ok());
424 } else {
425 assert!(self.result.is_none());
426 }
427 }
428 JsonRpcVersion::Unknown => (),
429 }
430 self
431 }
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437
438 use tower::{service_fn, ServiceExt};
439
440 use crate::server::cookie;
441
442 const INNER_BODY: &str = "inner service reached";
443
444 async fn call_with_auth(cookie: Cookie, auth: Option<String>) -> HttpResponse<HttpBody> {
447 let inner = service_fn(|_request: HttpRequest| async {
448 Ok::<_, BoxError>(HttpResponse::new(HttpBody::from(INNER_BODY)))
449 });
450 let mut middleware = HttpRequestMiddleware::new(inner, Some(cookie), 1024);
451
452 let mut request = HttpRequest::new(HttpBody::from(
453 r#"{"jsonrpc":"2.0","method":"getinfo","params":[],"id":1}"#,
454 ));
455 if let Some(auth) = auth {
456 request.headers_mut().insert(
457 header::AUTHORIZATION,
458 header::HeaderValue::from_str(&format!("Basic {}", STANDARD.encode(auth))).unwrap(),
459 );
460 }
461
462 middleware
463 .ready()
464 .await
465 .expect("the middleware is always ready")
466 .call(request)
467 .await
468 .expect("the middleware returns an HTTP response, not a transport error")
469 }
470
471 fn cookie_credentials(cookie: &Cookie) -> String {
473 let dir = tempfile::tempdir().unwrap();
474 cookie::write_to_disk(cookie, dir.path()).unwrap();
475 std::fs::read_to_string(dir.path().join(".cookie")).unwrap()
476 }
477
478 async fn assert_unauthenticated(response: HttpResponse<HttpBody>) {
479 assert_eq!(response.status(), hyper::StatusCode::UNAUTHORIZED);
480 assert_eq!(
481 response.headers().get(header::CONTENT_TYPE),
482 Some(&header::HeaderValue::from_static("application/json"))
483 );
484 assert_eq!(
485 response.headers().get(header::WWW_AUTHENTICATE),
486 Some(&header::HeaderValue::from_static("Basic realm=\"jsonrpc\""))
487 );
488
489 let body = response.into_body().collect().await.unwrap().to_bytes();
490 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
491 assert_eq!(body["error"]["code"], 401);
492 assert_eq!(body["error"]["message"], "unauthenticated method");
493 }
494
495 #[test]
496 fn static_auth_requires_the_whole_basic_credential() {
497 let auth = RpcAuth::static_credentials("node", "one:two");
498 let middleware = HttpRequestMiddleware::with_auth((), Some(auth), 1024);
499 for (scheme, pair, allowed) in [
500 ("bAsIc", "node:one:two", true),
501 ("Basic", "node:one", false),
502 ("Basic", "peer:one:two", false),
503 ("Bearer", "node:one:two", false),
504 ] {
505 let mut headers = header::HeaderMap::new();
506 let value = format!("{scheme} {}", STANDARD.encode(pair));
507 headers.insert(header::AUTHORIZATION, value.parse().unwrap());
508 assert_eq!(middleware.check_credentials(&headers), allowed);
509 }
510 }
511
512 #[tokio::test]
513 async fn request_without_credentials_gets_a_401_response() {
514 assert_unauthenticated(call_with_auth(Cookie::default(), None).await).await;
515 }
516
517 #[tokio::test]
518 async fn request_with_wrong_password_gets_a_401_response() {
519 let cookie = Cookie::default();
520 let wrong = cookie_credentials(&Cookie::default());
521
522 assert_unauthenticated(call_with_auth(cookie, Some(wrong)).await).await;
523 }
524
525 #[tokio::test]
526 async fn request_with_valid_credentials_reaches_inner_service() {
527 let cookie = Cookie::default();
528 let credentials = cookie_credentials(&cookie);
529
530 let response = call_with_auth(cookie, Some(credentials)).await;
531
532 assert_eq!(response.status(), hyper::StatusCode::OK);
533 let body = response.into_body().collect().await.unwrap().to_bytes();
534 assert_eq!(body.as_ref(), INNER_BODY.as_bytes());
535 }
536}