From f86fd520b5472d32aee4f89731995dc9504acc6a Mon Sep 17 00:00:00 2001 From: benthecarman Date: Tue, 9 Dec 2025 17:32:31 -0600 Subject: [PATCH] Limit request body size to 10MB Limit the request body to prevent abuse and too much memory allocation --- ldk-server/src/service.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/ldk-server/src/service.rs b/ldk-server/src/service.rs index 6eb02c5..50b7cb3 100644 --- a/ldk-server/src/service.rs +++ b/ldk-server/src/service.rs @@ -1,6 +1,6 @@ use ldk_node::Node; -use http_body_util::{BodyExt, Full}; +use http_body_util::{BodyExt, Full, Limited}; use hyper::body::{Bytes, Incoming}; use hyper::service::Service; use hyper::{Request, Response, StatusCode}; @@ -39,6 +39,10 @@ use std::future::Future; use std::pin::Pin; use std::sync::Arc; +// Maximum request body size: 10 MB +// This prevents memory exhaustion from large requests +const MAX_BODY_SIZE: usize = 10 * 1024 * 1024; + #[derive(Clone)] pub struct NodeService { node: Arc, @@ -127,8 +131,23 @@ async fn handle_request< >( context: Context, request: Request, handler: F, ) -> Result<>>::Response, hyper::Error> { - // TODO: we should bound the amount of data we read to avoid allocating too much memory. - let bytes = request.into_body().collect().await?.to_bytes(); + // Limit the size of the request body to prevent abuse + let limited_body = Limited::new(request.into_body(), MAX_BODY_SIZE); + let bytes = match limited_body.collect().await { + Ok(collected) => collected.to_bytes(), + Err(_) => { + let (error_response, status_code) = to_error_response(LdkServerError::new( + InvalidRequestError, + "Request body too large or failed to read.", + )); + return Ok(Response::builder() + .status(status_code) + .body(Full::new(Bytes::from(error_response.encode_to_vec()))) + // unwrap safety: body only errors when previous chained calls failed. + .unwrap()); + }, + }; + match T::decode(bytes) { Ok(request) => match handler(context, request) { Ok(response) => Ok(Response::builder()