Skip to content

Commit

Permalink
payload length check for resource upload
Browse files Browse the repository at this point in the history
  • Loading branch information
JieningYu committed Feb 27, 2024
1 parent 042c511 commit f7ec307
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 15 additions & 2 deletions src/handle/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,30 @@ pub async fn upload<Io: IoHandle>(
.await
.map_err(|_| Error::ResourceSaveFailed)?;
let mut stream = http_body_util::BodyStream::new(payload);

const MAX_PAYLOAD_LEN: usize = 50 * 1024 * 1024;

let mut len = 0_usize;
while let Some(chunk) = stream
.try_next()
.await
.map_err(|_| Error::ResourceSaveFailed)?
{
let chunk = chunk.into_data().map_err(|_| Error::ResourceSaveFailed)?;
len += chunk.len();
highway::HighwayHash::append(&mut hasher, &chunk);
tokio::io::AsyncWriteExt::write_all(&mut file, &chunk)
.await
.map_err(|_| Error::ResourceSaveFailed)?;
}
if len > MAX_PAYLOAD_LEN {
drop(file);
let _ = tokio::fs::remove_file(buf_path).await;
return Err(Error::PayloadTooLarge {
max: MAX_PAYLOAD_LEN,
});
}

tokio::io::AsyncWriteExt::flush(&mut file)
.await
.map_err(|_| Error::ResourceSaveFailed)?;
Expand Down Expand Up @@ -222,7 +235,7 @@ pub async fn get_info<Io: IoHandle>(
return Err(Error::PermissionDenied);
}
Ok(Json(Info {
variant: resource.variant().clone(),
variant: resource.variant(),
}))
}

Expand Down Expand Up @@ -259,7 +272,7 @@ pub async fn bulk_get_info<Io: IoHandle>(
infos.insert(
resource.id(),
Info {
variant: resource.variant().clone(),
variant: resource.variant(),
},
);
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ pub enum Error {
ResourceSaveFailed,
#[error("resource {0} not found")]
ResourceNotFound(u64),
#[error("payload too large: max {max} bytes")]
PayloadTooLarge { max: usize },

#[error("notification {0} not found")]
NotificationNotFound(u64),
Expand Down

0 comments on commit f7ec307

Please sign in to comment.