2022-02-21 22:02:30 +00:00
|
|
|
use std::collections::HashMap;
|
2024-02-05 17:49:54 +00:00
|
|
|
use std::convert::{Infallible, TryInto};
|
2022-02-21 22:02:30 +00:00
|
|
|
use std::ops::RangeInclusive;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use std::task::{Context, Poll};
|
|
|
|
|
2023-01-23 19:14:07 +00:00
|
|
|
use base64::prelude::*;
|
2022-02-21 22:02:30 +00:00
|
|
|
use bytes::Bytes;
|
|
|
|
use chrono::{DateTime, Duration, Utc};
|
2024-02-07 14:25:49 +00:00
|
|
|
use futures::{Stream, StreamExt};
|
2022-02-21 22:02:30 +00:00
|
|
|
use hyper::header::{self, HeaderMap, HeaderName, HeaderValue};
|
2024-02-05 17:49:54 +00:00
|
|
|
use hyper::{body::Incoming as IncomingBody, Request, Response, StatusCode};
|
2022-02-21 22:02:30 +00:00
|
|
|
use multer::{Constraints, Multipart, SizeLimit};
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
|
|
|
use garage_model::garage::Garage;
|
|
|
|
|
2024-02-05 17:49:54 +00:00
|
|
|
use crate::helpers::*;
|
|
|
|
use crate::s3::api_server::ResBody;
|
2023-10-20 08:29:03 +00:00
|
|
|
use crate::s3::cors::*;
|
2024-02-23 15:49:50 +00:00
|
|
|
use crate::s3::encryption::EncryptionParams;
|
2022-05-24 10:16:39 +00:00
|
|
|
use crate::s3::error::*;
|
2022-05-10 11:16:57 +00:00
|
|
|
use crate::s3::put::{get_headers, save_stream};
|
|
|
|
use crate::s3::xml as s3_xml;
|
2024-02-27 16:56:57 +00:00
|
|
|
use crate::signature::payload::{verify_v4, Authorization};
|
2022-02-21 22:02:30 +00:00
|
|
|
|
|
|
|
pub async fn handle_post_object(
|
|
|
|
garage: Arc<Garage>,
|
2024-02-05 17:49:54 +00:00
|
|
|
req: Request<IncomingBody>,
|
2022-06-15 18:20:28 +00:00
|
|
|
bucket_name: String,
|
2024-02-05 17:49:54 +00:00
|
|
|
) -> Result<Response<ResBody>, Error> {
|
2022-02-21 22:02:30 +00:00
|
|
|
let boundary = req
|
|
|
|
.headers()
|
|
|
|
.get(header::CONTENT_TYPE)
|
|
|
|
.and_then(|ct| ct.to_str().ok())
|
|
|
|
.and_then(|ct| multer::parse_boundary(ct).ok())
|
2023-08-01 14:17:53 +00:00
|
|
|
.ok_or_bad_request("Could not get multipart boundary")?;
|
2022-02-21 22:02:30 +00:00
|
|
|
|
|
|
|
// 16k seems plenty for a header. 5G is the max size of a single part, so it seems reasonable
|
|
|
|
// for a PostObject
|
|
|
|
let constraints = Constraints::new().size_limit(
|
|
|
|
SizeLimit::new()
|
|
|
|
.per_field(16 * 1024)
|
|
|
|
.for_field("file", 5 * 1024 * 1024 * 1024),
|
|
|
|
);
|
|
|
|
|
|
|
|
let (head, body) = req.into_parts();
|
2024-02-07 14:25:49 +00:00
|
|
|
let stream = body_stream::<_, Error>(body);
|
|
|
|
let mut multipart = Multipart::with_constraints(stream, boundary, constraints);
|
2022-02-21 22:02:30 +00:00
|
|
|
|
|
|
|
let mut params = HeaderMap::new();
|
2024-02-23 15:49:50 +00:00
|
|
|
let file_field = loop {
|
2022-02-21 22:02:30 +00:00
|
|
|
let field = if let Some(field) = multipart.next_field().await? {
|
|
|
|
field
|
|
|
|
} else {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request("Request did not contain a file"));
|
2022-02-21 22:02:30 +00:00
|
|
|
};
|
2024-02-23 15:49:50 +00:00
|
|
|
let name: HeaderName = if let Some(Ok(name)) = field
|
|
|
|
.name()
|
|
|
|
.map(str::to_ascii_lowercase)
|
|
|
|
.map(TryInto::try_into)
|
|
|
|
{
|
2022-02-21 22:02:30 +00:00
|
|
|
name
|
|
|
|
} else {
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
if name == "file" {
|
|
|
|
break field;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Ok(content) = HeaderValue::from_str(&field.text().await?) {
|
|
|
|
match name.as_str() {
|
|
|
|
"tag" => (/* tag need to be reencoded, but we don't support them yet anyway */),
|
|
|
|
"acl" => {
|
|
|
|
if params.insert("x-amz-acl", content).is_some() {
|
2023-08-01 14:17:53 +00:00
|
|
|
return Err(Error::bad_request("Field 'acl' provided more than once"));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
if params.insert(&name, content).is_some() {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request(format!(
|
2023-08-01 14:17:53 +00:00
|
|
|
"Field '{}' provided more than once",
|
2022-02-21 22:02:30 +00:00
|
|
|
name
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Current part is file. Do some checks before handling to PutObject code
|
|
|
|
let key = params
|
|
|
|
.get("key")
|
|
|
|
.ok_or_bad_request("No key was provided")?
|
|
|
|
.to_str()?;
|
|
|
|
let policy = params
|
|
|
|
.get("policy")
|
|
|
|
.ok_or_bad_request("No policy was provided")?
|
|
|
|
.to_str()?;
|
2024-02-27 16:56:57 +00:00
|
|
|
let authorization = Authorization::parse_form(¶ms)?;
|
2024-02-23 15:49:50 +00:00
|
|
|
let content_md5 = params
|
|
|
|
.get("content-md5")
|
|
|
|
.map(HeaderValue::to_str)
|
|
|
|
.transpose()?;
|
2022-02-21 22:02:30 +00:00
|
|
|
|
|
|
|
let key = if key.contains("${filename}") {
|
|
|
|
// if no filename is provided, don't replace. This matches the behavior of AWS.
|
2024-02-23 15:49:50 +00:00
|
|
|
if let Some(filename) = file_field.file_name() {
|
2022-02-21 22:02:30 +00:00
|
|
|
key.replace("${filename}", filename)
|
|
|
|
} else {
|
|
|
|
key.to_owned()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
key.to_owned()
|
|
|
|
};
|
|
|
|
|
2024-02-27 16:56:57 +00:00
|
|
|
let api_key = verify_v4(&garage, "s3", &authorization, policy.as_bytes()).await?;
|
2022-02-21 22:02:30 +00:00
|
|
|
|
2022-05-24 10:16:39 +00:00
|
|
|
let bucket_id = garage
|
|
|
|
.bucket_helper()
|
2022-06-15 18:20:28 +00:00
|
|
|
.resolve_bucket(&bucket_name, &api_key)
|
2022-05-24 10:16:39 +00:00
|
|
|
.await?;
|
2022-02-21 22:02:30 +00:00
|
|
|
|
|
|
|
if !api_key.allow_write(&bucket_id) {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::forbidden("Operation is not allowed for this key."));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
|
2022-06-15 18:20:28 +00:00
|
|
|
let bucket = garage
|
|
|
|
.bucket_helper()
|
|
|
|
.get_existing_bucket(bucket_id)
|
|
|
|
.await?;
|
2024-03-03 13:56:52 +00:00
|
|
|
let bucket_params = bucket.state.into_option().unwrap();
|
|
|
|
let matching_cors_rule = find_matching_cors_rule(
|
|
|
|
&bucket_params,
|
|
|
|
&Request::from_parts(head.clone(), empty_body::<Infallible>()),
|
|
|
|
)?
|
|
|
|
.cloned();
|
2022-06-15 18:20:28 +00:00
|
|
|
|
2023-01-23 19:14:07 +00:00
|
|
|
let decoded_policy = BASE64_STANDARD
|
2023-01-26 16:26:32 +00:00
|
|
|
.decode(policy)
|
2023-01-23 19:14:07 +00:00
|
|
|
.ok_or_bad_request("Invalid policy")?;
|
2022-02-21 22:02:30 +00:00
|
|
|
let decoded_policy: Policy =
|
|
|
|
serde_json::from_slice(&decoded_policy).ok_or_bad_request("Invalid policy")?;
|
|
|
|
|
|
|
|
let expiration: DateTime<Utc> = DateTime::parse_from_rfc3339(&decoded_policy.expiration)
|
|
|
|
.ok_or_bad_request("Invalid expiration date")?
|
|
|
|
.into();
|
|
|
|
if Utc::now() - expiration > Duration::zero() {
|
2023-08-01 14:17:53 +00:00
|
|
|
return Err(Error::bad_request("Expiration date is in the past"));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut conditions = decoded_policy.into_conditions()?;
|
|
|
|
|
|
|
|
for (param_key, value) in params.iter() {
|
2024-02-23 15:49:50 +00:00
|
|
|
let param_key = param_key.as_str();
|
|
|
|
match param_key {
|
2022-02-21 22:02:30 +00:00
|
|
|
"policy" | "x-amz-signature" => (), // this is always accepted, as it's required to validate other fields
|
|
|
|
"content-type" => {
|
|
|
|
let conds = conditions.params.remove("content-type").ok_or_else(|| {
|
2022-05-24 10:16:39 +00:00
|
|
|
Error::bad_request(format!("Key '{}' is not allowed in policy", param_key))
|
2022-02-21 22:02:30 +00:00
|
|
|
})?;
|
|
|
|
for cond in conds {
|
|
|
|
let ok = match cond {
|
|
|
|
Operation::Equal(s) => s.as_str() == value,
|
|
|
|
Operation::StartsWith(s) => {
|
|
|
|
value.to_str()?.split(',').all(|v| v.starts_with(&s))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if !ok {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request(format!(
|
2022-02-21 22:02:30 +00:00
|
|
|
"Key '{}' has value not allowed in policy",
|
|
|
|
param_key
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"key" => {
|
|
|
|
let conds = conditions.params.remove("key").ok_or_else(|| {
|
2022-05-24 10:16:39 +00:00
|
|
|
Error::bad_request(format!("Key '{}' is not allowed in policy", param_key))
|
2022-02-21 22:02:30 +00:00
|
|
|
})?;
|
|
|
|
for cond in conds {
|
|
|
|
let ok = match cond {
|
|
|
|
Operation::Equal(s) => s == key,
|
|
|
|
Operation::StartsWith(s) => key.starts_with(&s),
|
|
|
|
};
|
|
|
|
if !ok {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request(format!(
|
2022-02-21 22:02:30 +00:00
|
|
|
"Key '{}' has value not allowed in policy",
|
|
|
|
param_key
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
if param_key.starts_with("x-ignore-") {
|
|
|
|
// if a x-ignore is provided in policy, it's not removed here, so it will be
|
|
|
|
// rejected as provided in policy but not in the request. As odd as it is, it's
|
|
|
|
// how aws seems to behave.
|
|
|
|
continue;
|
|
|
|
}
|
2024-02-23 15:49:50 +00:00
|
|
|
let conds = conditions.params.remove(param_key).ok_or_else(|| {
|
2022-05-24 10:16:39 +00:00
|
|
|
Error::bad_request(format!("Key '{}' is not allowed in policy", param_key))
|
2022-02-21 22:02:30 +00:00
|
|
|
})?;
|
|
|
|
for cond in conds {
|
|
|
|
let ok = match cond {
|
|
|
|
Operation::Equal(s) => s.as_str() == value,
|
|
|
|
Operation::StartsWith(s) => value.to_str()?.starts_with(s.as_str()),
|
|
|
|
};
|
|
|
|
if !ok {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request(format!(
|
2022-02-21 22:02:30 +00:00
|
|
|
"Key '{}' has value not allowed in policy",
|
|
|
|
param_key
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some((param_key, _)) = conditions.params.iter().next() {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request(format!(
|
2022-02-21 22:02:30 +00:00
|
|
|
"Key '{}' is required in policy, but no value was provided",
|
|
|
|
param_key
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
|
|
|
|
let headers = get_headers(¶ms)?;
|
|
|
|
|
2024-02-23 15:49:50 +00:00
|
|
|
let encryption = EncryptionParams::new_from_headers(&garage, ¶ms)?;
|
2024-03-03 13:56:52 +00:00
|
|
|
|
2024-02-23 15:49:50 +00:00
|
|
|
let stream = file_field.map(|r| r.map_err(Into::into));
|
2024-03-03 13:56:52 +00:00
|
|
|
let ctx = ReqCtx {
|
2022-02-21 22:02:30 +00:00
|
|
|
garage,
|
2024-03-03 13:56:52 +00:00
|
|
|
bucket_id,
|
|
|
|
bucket_name,
|
|
|
|
bucket_params,
|
|
|
|
api_key,
|
|
|
|
};
|
|
|
|
|
2024-02-23 15:49:50 +00:00
|
|
|
let res = save_stream(
|
2024-03-03 13:56:52 +00:00
|
|
|
&ctx,
|
2022-02-21 22:02:30 +00:00
|
|
|
headers,
|
2024-02-23 15:49:50 +00:00
|
|
|
encryption,
|
2022-02-21 22:02:30 +00:00
|
|
|
StreamLimiter::new(stream, conditions.content_length),
|
|
|
|
&key,
|
2024-02-23 15:49:50 +00:00
|
|
|
content_md5.map(str::to_string),
|
2022-02-21 22:02:30 +00:00
|
|
|
None,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
2024-02-23 15:49:50 +00:00
|
|
|
let etag = format!("\"{}\"", res.etag);
|
2022-02-21 22:02:30 +00:00
|
|
|
|
2023-10-20 08:29:03 +00:00
|
|
|
let mut resp = if let Some(mut target) = params
|
2022-02-21 22:02:30 +00:00
|
|
|
.get("success_action_redirect")
|
|
|
|
.and_then(|h| h.to_str().ok())
|
|
|
|
.and_then(|u| url::Url::parse(u).ok())
|
|
|
|
.filter(|u| u.scheme() == "https" || u.scheme() == "http")
|
|
|
|
{
|
|
|
|
target
|
|
|
|
.query_pairs_mut()
|
2024-03-03 13:56:52 +00:00
|
|
|
.append_pair("bucket", &ctx.bucket_name)
|
2022-02-21 22:02:30 +00:00
|
|
|
.append_pair("key", &key)
|
|
|
|
.append_pair("etag", &etag);
|
|
|
|
let target = target.to_string();
|
2024-02-23 15:49:50 +00:00
|
|
|
let mut resp = Response::builder()
|
2022-02-21 22:02:30 +00:00
|
|
|
.status(StatusCode::SEE_OTHER)
|
|
|
|
.header(header::LOCATION, target.clone())
|
2024-02-23 15:49:50 +00:00
|
|
|
.header(header::ETAG, etag);
|
|
|
|
encryption.add_response_headers(&mut resp);
|
|
|
|
resp.body(string_body(target))?
|
2022-02-21 22:02:30 +00:00
|
|
|
} else {
|
|
|
|
let path = head
|
|
|
|
.uri
|
2023-10-20 08:29:03 +00:00
|
|
|
.path_and_query()
|
2022-02-21 22:02:30 +00:00
|
|
|
.map(|paq| paq.path().to_string())
|
|
|
|
.unwrap_or_else(|| "/".to_string());
|
|
|
|
let authority = head
|
|
|
|
.headers
|
|
|
|
.get(header::HOST)
|
|
|
|
.and_then(|h| h.to_str().ok())
|
|
|
|
.unwrap_or_default();
|
|
|
|
let proto = if !authority.is_empty() {
|
|
|
|
"https://"
|
|
|
|
} else {
|
|
|
|
""
|
|
|
|
};
|
|
|
|
|
|
|
|
let url_key: String = form_urlencoded::byte_serialize(key.as_bytes())
|
|
|
|
.flat_map(str::chars)
|
|
|
|
.collect();
|
|
|
|
let location = format!("{}{}{}{}", proto, authority, path, url_key);
|
|
|
|
|
|
|
|
let action = params
|
|
|
|
.get("success_action_status")
|
|
|
|
.and_then(|h| h.to_str().ok())
|
|
|
|
.unwrap_or("204");
|
2024-02-23 15:49:50 +00:00
|
|
|
let mut builder = Response::builder()
|
2022-02-21 22:02:30 +00:00
|
|
|
.header(header::LOCATION, location.clone())
|
|
|
|
.header(header::ETAG, etag.clone());
|
2024-02-23 15:49:50 +00:00
|
|
|
encryption.add_response_headers(&mut builder);
|
2022-02-21 22:02:30 +00:00
|
|
|
match action {
|
2024-02-05 17:49:54 +00:00
|
|
|
"200" => builder.status(StatusCode::OK).body(empty_body())?,
|
2022-02-21 22:02:30 +00:00
|
|
|
"201" => {
|
|
|
|
let xml = s3_xml::PostObject {
|
|
|
|
xmlns: (),
|
|
|
|
location: s3_xml::Value(location),
|
2024-03-03 13:56:52 +00:00
|
|
|
bucket: s3_xml::Value(ctx.bucket_name),
|
2022-02-21 22:02:30 +00:00
|
|
|
key: s3_xml::Value(key),
|
|
|
|
etag: s3_xml::Value(etag),
|
|
|
|
};
|
|
|
|
let body = s3_xml::to_xml_with_header(&xml)?;
|
|
|
|
builder
|
|
|
|
.status(StatusCode::CREATED)
|
2024-02-05 17:49:54 +00:00
|
|
|
.body(string_body(body))?
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
2024-02-05 17:49:54 +00:00
|
|
|
_ => builder.status(StatusCode::NO_CONTENT).body(empty_body())?,
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-10-20 08:29:03 +00:00
|
|
|
if let Some(rule) = matching_cors_rule {
|
2024-03-03 13:56:52 +00:00
|
|
|
add_cors_headers(&mut resp, &rule)
|
2023-10-20 08:29:03 +00:00
|
|
|
.ok_or_internal_error("Invalid bucket CORS configuration")?;
|
|
|
|
}
|
|
|
|
|
2022-02-21 22:02:30 +00:00
|
|
|
Ok(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Policy {
|
|
|
|
expiration: String,
|
|
|
|
conditions: Vec<PolicyCondition>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Policy {
|
|
|
|
fn into_conditions(self) -> Result<Conditions, Error> {
|
|
|
|
let mut params = HashMap::<_, Vec<_>>::new();
|
|
|
|
|
|
|
|
let mut length = (0, u64::MAX);
|
|
|
|
for condition in self.conditions {
|
|
|
|
match condition {
|
|
|
|
PolicyCondition::Equal(map) => {
|
|
|
|
if map.len() != 1 {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request("Invalid policy item"));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
2023-08-01 14:17:53 +00:00
|
|
|
let (mut k, v) = map.into_iter().next().expect("Size could not be verified");
|
2022-02-21 22:02:30 +00:00
|
|
|
k.make_ascii_lowercase();
|
|
|
|
params.entry(k).or_default().push(Operation::Equal(v));
|
|
|
|
}
|
|
|
|
PolicyCondition::OtherOp([cond, mut key, value]) => {
|
|
|
|
if key.remove(0) != '$' {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request("Invalid policy item"));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
key.make_ascii_lowercase();
|
|
|
|
match cond.as_str() {
|
|
|
|
"eq" => {
|
|
|
|
params.entry(key).or_default().push(Operation::Equal(value));
|
|
|
|
}
|
|
|
|
"starts-with" => {
|
|
|
|
params
|
|
|
|
.entry(key)
|
|
|
|
.or_default()
|
|
|
|
.push(Operation::StartsWith(value));
|
|
|
|
}
|
2022-05-24 10:16:39 +00:00
|
|
|
_ => return Err(Error::bad_request("Invalid policy item")),
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
PolicyCondition::SizeRange(key, min, max) => {
|
|
|
|
if key == "content-length-range" {
|
|
|
|
length.0 = length.0.max(min);
|
|
|
|
length.1 = length.1.min(max);
|
|
|
|
} else {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Err(Error::bad_request("Invalid policy item"));
|
2022-02-21 22:02:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(Conditions {
|
|
|
|
params,
|
|
|
|
content_length: RangeInclusive::new(length.0, length.1),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A single condition from a policy
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
enum PolicyCondition {
|
|
|
|
// will contain a single key-value pair
|
|
|
|
Equal(HashMap<String, String>),
|
|
|
|
OtherOp([String; 3]),
|
|
|
|
SizeRange(String, u64, u64),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Conditions {
|
|
|
|
params: HashMap<String, Vec<Operation>>,
|
|
|
|
content_length: RangeInclusive<u64>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
|
|
enum Operation {
|
|
|
|
Equal(String),
|
|
|
|
StartsWith(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
struct StreamLimiter<T> {
|
|
|
|
inner: T,
|
|
|
|
length: RangeInclusive<u64>,
|
|
|
|
read: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> StreamLimiter<T> {
|
|
|
|
fn new(stream: T, length: RangeInclusive<u64>) -> Self {
|
|
|
|
StreamLimiter {
|
|
|
|
inner: stream,
|
|
|
|
length,
|
|
|
|
read: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Stream for StreamLimiter<T>
|
|
|
|
where
|
|
|
|
T: Stream<Item = Result<Bytes, Error>> + Unpin,
|
|
|
|
{
|
|
|
|
type Item = Result<Bytes, Error>;
|
|
|
|
fn poll_next(
|
|
|
|
mut self: std::pin::Pin<&mut Self>,
|
|
|
|
ctx: &mut Context<'_>,
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
|
|
|
let res = std::pin::Pin::new(&mut self.inner).poll_next(ctx);
|
|
|
|
match &res {
|
|
|
|
Poll::Ready(Some(Ok(bytes))) => {
|
|
|
|
self.read += bytes.len() as u64;
|
|
|
|
// optimization to fail early when we know before the end it's too long
|
|
|
|
if self.length.end() < &self.read {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Poll::Ready(Some(Err(Error::bad_request(
|
|
|
|
"File size does not match policy",
|
2022-02-21 22:02:30 +00:00
|
|
|
))));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Poll::Ready(None) => {
|
|
|
|
if !self.length.contains(&self.read) {
|
2022-05-24 10:16:39 +00:00
|
|
|
return Poll::Ready(Some(Err(Error::bad_request(
|
|
|
|
"File size does not match policy",
|
2022-02-21 22:02:30 +00:00
|
|
|
))));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
res
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_policy_1() {
|
|
|
|
let policy_json = br#"
|
|
|
|
{ "expiration": "2007-12-01T12:00:00.000Z",
|
|
|
|
"conditions": [
|
|
|
|
{"acl": "public-read" },
|
|
|
|
{"bucket": "johnsmith" },
|
|
|
|
["starts-with", "$key", "user/eric/"]
|
|
|
|
]
|
|
|
|
}
|
|
|
|
"#;
|
|
|
|
let policy_2: Policy = serde_json::from_slice(&policy_json[..]).unwrap();
|
|
|
|
let mut conditions = policy_2.into_conditions().unwrap();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
conditions.params.remove(&"acl".to_string()),
|
|
|
|
Some(vec![Operation::Equal("public-read".into())])
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
conditions.params.remove(&"bucket".to_string()),
|
|
|
|
Some(vec![Operation::Equal("johnsmith".into())])
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
conditions.params.remove(&"key".to_string()),
|
|
|
|
Some(vec![Operation::StartsWith("user/eric/".into())])
|
|
|
|
);
|
|
|
|
assert!(conditions.params.is_empty());
|
|
|
|
assert_eq!(conditions.content_length, 0..=u64::MAX);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_policy_2() {
|
|
|
|
let policy_json = br#"
|
|
|
|
{ "expiration": "2007-12-01T12:00:00.000Z",
|
|
|
|
"conditions": [
|
|
|
|
[ "eq", "$acl", "public-read" ],
|
|
|
|
["starts-with", "$Content-Type", "image/"],
|
|
|
|
["starts-with", "$success_action_redirect", ""],
|
|
|
|
["content-length-range", 1048576, 10485760]
|
|
|
|
]
|
|
|
|
}
|
|
|
|
"#;
|
|
|
|
let policy_2: Policy = serde_json::from_slice(&policy_json[..]).unwrap();
|
|
|
|
let mut conditions = policy_2.into_conditions().unwrap();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
conditions.params.remove(&"acl".to_string()),
|
|
|
|
Some(vec![Operation::Equal("public-read".into())])
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
conditions.params.remove("content-type").unwrap(),
|
|
|
|
vec![Operation::StartsWith("image/".into())]
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
conditions
|
|
|
|
.params
|
|
|
|
.remove(&"success_action_redirect".to_string()),
|
|
|
|
Some(vec![Operation::StartsWith("".into())])
|
|
|
|
);
|
|
|
|
assert!(conditions.params.is_empty());
|
|
|
|
assert_eq!(conditions.content_length, 1048576..=10485760);
|
|
|
|
}
|
|
|
|
}
|