Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 78 additions & 4 deletions rusk/src/lib/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ use crate::VERSION;
pub use self::event::{RuesDispatchEvent, RuesEvent, RUES_LOCATION_PREFIX};
pub use error::Error as HttpError;

use self::event::{check_rusk_version, ResponseData, RuesEventUri, SessionId};
use self::event::{
check_rusk_version, RequestParseError, ResponseData, RuesEventUri,
SessionId,
};
use self::stream::Listener;

pub type HttpResult<T> = std::result::Result<T, HttpError>;
Expand Down Expand Up @@ -577,7 +580,27 @@ async fn handle_request_rues<H: HandleRequest>(
}

let (event, binary_request) =
RuesDispatchEvent::from_request(req).await?;
match RuesDispatchEvent::from_request(req).await {
Ok(data) => data,
Err(RequestParseError::InvalidPath) => {
return response(
StatusCode::NOT_FOUND,
"{\"error\":\"Invalid URL path\"}",
);
}
Err(RequestParseError::InvalidPayload(msg)) => {
return response(
StatusCode::UNPROCESSABLE_ENTITY,
serde_json::json!({ "error": msg }).to_string(),
);
}
Err(RequestParseError::Other(err)) => {
return response(
StatusCode::INTERNAL_SERVER_ERROR,
err.to_string(),
);
}
};
let mut resp_headers = event.x_headers();
let (responder, mut receiver) = mpsc::unbounded_channel();
handle_execution_rues(handler, event, responder).await;
Expand Down Expand Up @@ -1052,11 +1075,12 @@ mod tests {
(stream, sid)
}

async fn assert_bad_request_contains(
async fn assert_status_contains(
response: reqwest::Response,
status: StatusCode,
expected: &str,
) {
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(response.status(), status);
let body = response
.text()
.await
Expand All @@ -1067,6 +1091,14 @@ mod tests {
);
}

async fn assert_bad_request_contains(
response: reqwest::Response,
expected: &str,
) {
assert_status_contains(response, StatusCode::BAD_REQUEST, expected)
.await;
}

#[tokio::test]
async fn http_query() {
let (_server, local_addr, _event_sender) =
Expand Down Expand Up @@ -1161,6 +1193,48 @@ mod tests {
.await;
}

#[tokio::test]
async fn post_rues_invalid_path_returns_not_found() {
let (_server, local_addr, _event_sender) =
bind_test_server(TestHandle).await;

let client = reqwest::Client::new();
let response = client
.post(format!("http://{local_addr}/on"))
.body("hello")
.send()
.await
.expect("Requesting should succeed");

assert_status_contains(
response,
StatusCode::NOT_FOUND,
"Invalid URL path",
)
.await;
}

#[tokio::test]
async fn post_rues_invalid_utf8_payload_returns_unprocessable_entity() {
let (_server, local_addr, _event_sender) =
bind_test_server(TestHandle).await;

let client = reqwest::Client::new();
let response = client
.post(format!("http://{local_addr}/on/test/echo"))
.body(vec![0xff, 0xfe])
.send()
.await
.expect("Requesting should succeed");

assert_status_contains(
response,
StatusCode::UNPROCESSABLE_ENTITY,
"Invalid utf8",
)
.await;
}

#[tokio::test(flavor = "multi_thread")]
async fn get_delete_rues_strict_without_version_returns_bad_request() {
let (_server, local_addr, _event_sender) =
Expand Down
52 changes: 40 additions & 12 deletions rusk/src/lib/http/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,25 @@ pub struct RuesDispatchEvent {
pub data: RequestData,
}

#[derive(Debug)]
pub enum RequestParseError {
InvalidPath,
InvalidPayload(String),
Other(anyhow::Error),
}

impl Display for RequestParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RequestParseError::InvalidPath => write!(f, "Invalid URL path"),
RequestParseError::InvalidPayload(msg) => write!(f, "{msg}"),
RequestParseError::Other(err) => write!(f, "{err}"),
}
}
}

impl std::error::Error for RequestParseError {}

impl RuesDispatchEvent {
pub fn x_headers(&self) -> serde_json::Map<String, serde_json::Value> {
let mut h = self.headers.clone();
Expand Down Expand Up @@ -593,27 +612,38 @@ impl RuesDispatchEvent {
}
pub async fn from_request(
req: Request<Incoming>,
) -> Result<(Self, bool), super::HttpError> {
) -> Result<(Self, bool), RequestParseError> {
let (parts, body) = req.into_parts();

let uri = RuesEventUri::parse_from_path(parts.uri.path())
.ok_or(super::HttpError::invalid_input("Invalid URL path"))?;
.ok_or(RequestParseError::InvalidPath)?;

let headers = parts
.headers
.iter()
.map(|(k, v)| {
let v = if v.is_empty() {
let value = if v.is_empty() {
serde_json::Value::Null
} else {
} else if let Ok(parsed) =
serde_json::from_slice::<serde_json::Value>(v.as_bytes())
.unwrap_or(serde_json::Value::String(
v.to_str().unwrap().to_string(),
{
parsed
} else {
let as_str = v.to_str().map_err(|_| {
RequestParseError::InvalidPayload(format!(
"Invalid header encoding for {}",
k.as_str()
))
})?;
serde_json::Value::String(as_str.to_string())
};
(k.to_string().to_lowercase(), v)

Ok((k.to_string().to_lowercase(), value))
})
.collect();
.collect::<Result<
serde_json::Map<String, serde_json::Value>,
RequestParseError,
>>()?;

// HTTP REQUEST
let content_type = parts
Expand All @@ -635,16 +665,14 @@ impl RuesDispatchEvent {
let bytes = body
.collect()
.await
.map_err(|e| super::HttpError::internal(e.to_string()))?
.map_err(|e| RequestParseError::Other(e.into()))?
.to_bytes()
.to_vec();
let data = match binary_request {
true => bytes.into(),
_ => {
let text = String::from_utf8(bytes).map_err(|_| {
super::HttpError::InvalidEncoding(
"Invalid utf8".to_string(),
)
RequestParseError::InvalidPayload("Invalid utf8".into())
})?;
if let Some(hex) = text.strip_prefix("0x") {
if let Ok(bytes) = hex::decode(hex) {
Expand Down