use axum::{
http::{
HeaderName, HeaderValue, StatusCode,
header::{ALLOW, CONTENT_TYPE},
},
response::{IntoResponse, Response},
};
use crate::s3::types::RequestId;
#[derive(Clone, Debug)]
pub struct S3Error {
status: StatusCode,
code: &'static str,
message: String,
resource: Option<String>,
headers: Vec<(HeaderName, HeaderValue)>,
}
impl S3Error {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn code(&self) -> &'static str {
self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn resource(&self) -> Option<&str> {
self.resource.as_deref()
}
pub fn invalid_request(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}
pub fn invalid_argument(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "InvalidArgument", message)
}
pub fn malformed_xml(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "MalformedXML", message)
}
pub fn no_such_bucket(bucket: impl Into<String>) -> Self {
Self::new(
StatusCode::NOT_FOUND,
"NoSuchBucket",
format!("The specified bucket does not exist: {}", bucket.into()),
)
}
pub fn no_such_key() -> Self {
Self::new(
StatusCode::NOT_FOUND,
"NoSuchKey",
"The specified key does not exist.",
)
}
pub fn access_denied(message: impl Into<String>) -> Self {
Self::new(StatusCode::FORBIDDEN, "AccessDenied", message)
}
pub fn authorization_header_malformed(message: impl Into<String>) -> Self {
Self::new(
StatusCode::BAD_REQUEST,
"AuthorizationHeaderMalformed",
message,
)
}
pub fn signature_does_not_match() -> Self {
Self::new(
StatusCode::FORBIDDEN,
"SignatureDoesNotMatch",
"The request signature we calculated does not match the signature you provided.",
)
}
pub fn request_time_too_skewed() -> Self {
Self::new(
StatusCode::FORBIDDEN,
"RequestTimeTooSkewed",
"The difference between the request time and the server's time is too large.",
)
}
pub fn missing_content_length() -> Self {
Self::new(
StatusCode::LENGTH_REQUIRED,
"MissingContentLength",
"You must provide the Content-Length HTTP header.",
)
}
pub fn bad_digest(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "BadDigest", message)
}
pub fn no_such_upload() -> Self {
Self::new(
StatusCode::NOT_FOUND,
"NoSuchUpload",
"The specified multipart upload does not exist.",
)
}
pub fn invalid_part(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "InvalidPart", message)
}
pub fn entity_too_small(message: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "EntityTooSmall", message)
}
pub fn entity_too_large(message: impl Into<String>) -> Self {
Self::new(StatusCode::PAYLOAD_TOO_LARGE, "EntityTooLarge", message)
}
pub fn slow_down(message: impl Into<String>) -> Self {
Self::new(StatusCode::SERVICE_UNAVAILABLE, "SlowDown", message)
}
pub fn invalid_range(message: impl Into<String>) -> Self {
Self::new(StatusCode::RANGE_NOT_SATISFIABLE, "InvalidRange", message)
}
pub fn precondition_failed(message: impl Into<String>) -> Self {
Self::new(
StatusCode::PRECONDITION_FAILED,
"PreconditionFailed",
message,
)
}
pub fn method_not_allowed() -> Self {
Self::new(
StatusCode::METHOD_NOT_ALLOWED,
"MethodNotAllowed",
"The specified method is not allowed against this resource.",
)
.with_header(
ALLOW,
HeaderValue::from_static("DELETE, GET, HEAD, POST, PUT"),
)
}
pub fn not_implemented(message: impl Into<String>) -> Self {
Self::new(StatusCode::NOT_IMPLEMENTED, "NotImplemented", message)
}
pub fn internal(message: impl Into<String>) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "InternalError", message)
}
pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
self.resource = Some(resource.into());
self
}
pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.headers.push((name, value));
self
}
pub fn into_response_with_request_id(self, request_id: &RequestId) -> Response {
let mut response = (self.status, self.to_xml(request_id)).into_response();
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/xml; charset=utf-8"),
);
for (name, value) in self.headers {
response.headers_mut().insert(name, value);
}
if let Ok(value) = HeaderValue::from_str(request_id.as_str()) {
response.headers_mut().insert("x-amz-request-id", value);
}
response
}
fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
Self {
status,
code,
message: message.into(),
resource: None,
headers: Vec::new(),
}
}
fn to_xml(&self, request_id: &RequestId) -> String {
let resource = self
.resource
.as_ref()
.map(|resource| format!(" <Resource>{}</Resource>\n", escape_xml(resource)))
.unwrap_or_default();
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<Error>\n\
\x20 <Code>{}</Code>\n\
\x20 <Message>{}</Message>\n\
{}\
\x20 <RequestId>{}</RequestId>\n\
</Error>\n",
self.code,
escape_xml(&self.message),
resource,
request_id.as_str()
)
}
}
impl IntoResponse for S3Error {
fn into_response(self) -> Response {
let request_id = RequestId::new();
self.into_response_with_request_id(&request_id)
}
}
fn escape_xml(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}