1use axum::{
2 http::{
3 HeaderName, HeaderValue, StatusCode,
4 header::{ALLOW, CONTENT_TYPE},
5 },
6 response::{IntoResponse, Response},
7};
8
9use crate::s3::types::RequestId;
10
11#[derive(Clone, Debug)]
18pub struct S3Error {
19 status: StatusCode,
20 code: &'static str,
21 message: String,
22 resource: Option<String>,
23 headers: Vec<(HeaderName, HeaderValue)>,
24}
25
26impl S3Error {
27 pub fn status(&self) -> StatusCode {
29 self.status
30 }
31
32 pub fn code(&self) -> &'static str {
34 self.code
35 }
36
37 pub fn message(&self) -> &str {
39 &self.message
40 }
41
42 pub fn resource(&self) -> Option<&str> {
44 self.resource.as_deref()
45 }
46
47 pub fn invalid_request(message: impl Into<String>) -> Self {
49 Self::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
50 }
51
52 pub fn invalid_argument(message: impl Into<String>) -> Self {
54 Self::new(StatusCode::BAD_REQUEST, "InvalidArgument", message)
55 }
56
57 pub fn malformed_xml(message: impl Into<String>) -> Self {
59 Self::new(StatusCode::BAD_REQUEST, "MalformedXML", message)
60 }
61
62 pub fn no_such_bucket(bucket: impl Into<String>) -> Self {
64 Self::new(
65 StatusCode::NOT_FOUND,
66 "NoSuchBucket",
67 format!("The specified bucket does not exist: {}", bucket.into()),
68 )
69 }
70
71 pub fn no_such_key() -> Self {
73 Self::new(
74 StatusCode::NOT_FOUND,
75 "NoSuchKey",
76 "The specified key does not exist.",
77 )
78 }
79
80 pub fn access_denied(message: impl Into<String>) -> Self {
82 Self::new(StatusCode::FORBIDDEN, "AccessDenied", message)
83 }
84
85 pub fn authorization_header_malformed(message: impl Into<String>) -> Self {
87 Self::new(
88 StatusCode::BAD_REQUEST,
89 "AuthorizationHeaderMalformed",
90 message,
91 )
92 }
93
94 pub fn signature_does_not_match() -> Self {
96 Self::new(
97 StatusCode::FORBIDDEN,
98 "SignatureDoesNotMatch",
99 "The request signature we calculated does not match the signature you provided.",
100 )
101 }
102
103 pub fn request_time_too_skewed() -> Self {
105 Self::new(
106 StatusCode::FORBIDDEN,
107 "RequestTimeTooSkewed",
108 "The difference between the request time and the server's time is too large.",
109 )
110 }
111
112 pub fn missing_content_length() -> Self {
114 Self::new(
115 StatusCode::LENGTH_REQUIRED,
116 "MissingContentLength",
117 "You must provide the Content-Length HTTP header.",
118 )
119 }
120
121 pub fn bad_digest(message: impl Into<String>) -> Self {
123 Self::new(StatusCode::BAD_REQUEST, "BadDigest", message)
124 }
125
126 pub fn no_such_upload() -> Self {
128 Self::new(
129 StatusCode::NOT_FOUND,
130 "NoSuchUpload",
131 "The specified multipart upload does not exist.",
132 )
133 }
134
135 pub fn invalid_part(message: impl Into<String>) -> Self {
137 Self::new(StatusCode::BAD_REQUEST, "InvalidPart", message)
138 }
139
140 pub fn entity_too_small(message: impl Into<String>) -> Self {
142 Self::new(StatusCode::BAD_REQUEST, "EntityTooSmall", message)
143 }
144
145 pub fn entity_too_large(message: impl Into<String>) -> Self {
147 Self::new(StatusCode::PAYLOAD_TOO_LARGE, "EntityTooLarge", message)
148 }
149
150 pub fn slow_down(message: impl Into<String>) -> Self {
152 Self::new(StatusCode::SERVICE_UNAVAILABLE, "SlowDown", message)
153 }
154
155 pub fn invalid_range(message: impl Into<String>) -> Self {
157 Self::new(StatusCode::RANGE_NOT_SATISFIABLE, "InvalidRange", message)
158 }
159
160 pub fn precondition_failed(message: impl Into<String>) -> Self {
162 Self::new(
163 StatusCode::PRECONDITION_FAILED,
164 "PreconditionFailed",
165 message,
166 )
167 }
168
169 pub fn method_not_allowed() -> Self {
171 Self::new(
172 StatusCode::METHOD_NOT_ALLOWED,
173 "MethodNotAllowed",
174 "The specified method is not allowed against this resource.",
175 )
176 .with_header(
177 ALLOW,
178 HeaderValue::from_static("DELETE, GET, HEAD, POST, PUT"),
179 )
180 }
181
182 pub fn not_implemented(message: impl Into<String>) -> Self {
184 Self::new(StatusCode::NOT_IMPLEMENTED, "NotImplemented", message)
185 }
186
187 pub fn internal(message: impl Into<String>) -> Self {
189 Self::new(StatusCode::INTERNAL_SERVER_ERROR, "InternalError", message)
190 }
191
192 pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
194 self.resource = Some(resource.into());
195 self
196 }
197
198 pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
200 self.headers.push((name, value));
201 self
202 }
203
204 pub fn into_response_with_request_id(self, request_id: &RequestId) -> Response {
206 let mut response = (self.status, self.to_xml(request_id)).into_response();
207 response.headers_mut().insert(
208 CONTENT_TYPE,
209 HeaderValue::from_static("application/xml; charset=utf-8"),
210 );
211 for (name, value) in self.headers {
212 response.headers_mut().insert(name, value);
213 }
214 if let Ok(value) = HeaderValue::from_str(request_id.as_str()) {
215 response.headers_mut().insert("x-amz-request-id", value);
216 }
217 response
218 }
219
220 fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
221 Self {
222 status,
223 code,
224 message: message.into(),
225 resource: None,
226 headers: Vec::new(),
227 }
228 }
229
230 fn to_xml(&self, request_id: &RequestId) -> String {
231 let resource = self
232 .resource
233 .as_ref()
234 .map(|resource| format!(" <Resource>{}</Resource>\n", escape_xml(resource)))
235 .unwrap_or_default();
236
237 format!(
238 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
239 <Error>\n\
240 \x20 <Code>{}</Code>\n\
241 \x20 <Message>{}</Message>\n\
242 {}\
243 \x20 <RequestId>{}</RequestId>\n\
244 </Error>\n",
245 self.code,
246 escape_xml(&self.message),
247 resource,
248 request_id.as_str()
249 )
250 }
251}
252
253impl IntoResponse for S3Error {
254 fn into_response(self) -> Response {
255 let request_id = RequestId::new();
256 self.into_response_with_request_id(&request_id)
257 }
258}
259
260fn escape_xml(value: &str) -> String {
261 value
262 .replace('&', "&")
263 .replace('<', "<")
264 .replace('>', ">")
265 .replace('"', """)
266 .replace('\'', "'")
267}