Skip to main content

s3_endpoint/
error.rs

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/// S3 XML error response.
12///
13/// `S3Error` keeps the HTTP status, S3 error code, user-facing message,
14/// optional resource, and extra response headers together until the HTTP
15/// boundary converts it to an XML response. Constructors are named after the
16/// S3 error code or behavior they represent.
17#[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    /// Returns the HTTP status that will be used for the error response.
28    pub fn status(&self) -> StatusCode {
29        self.status
30    }
31
32    /// Returns the S3 error code.
33    pub fn code(&self) -> &'static str {
34        self.code
35    }
36
37    /// Returns the user-facing S3 error message.
38    pub fn message(&self) -> &str {
39        &self.message
40    }
41
42    /// Returns the optional S3 resource path included in the XML body.
43    pub fn resource(&self) -> Option<&str> {
44        self.resource.as_deref()
45    }
46
47    /// Returns a `400 InvalidRequest` error.
48    pub fn invalid_request(message: impl Into<String>) -> Self {
49        Self::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
50    }
51
52    /// Returns a `400 InvalidArgument` error.
53    pub fn invalid_argument(message: impl Into<String>) -> Self {
54        Self::new(StatusCode::BAD_REQUEST, "InvalidArgument", message)
55    }
56
57    /// Returns a `400 MalformedXML` error.
58    pub fn malformed_xml(message: impl Into<String>) -> Self {
59        Self::new(StatusCode::BAD_REQUEST, "MalformedXML", message)
60    }
61
62    /// Returns a `404 NoSuchBucket` error for a bucket name.
63    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    /// Returns a `404 NoSuchKey` error.
72    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    /// Returns a `403 AccessDenied` error.
81    pub fn access_denied(message: impl Into<String>) -> Self {
82        Self::new(StatusCode::FORBIDDEN, "AccessDenied", message)
83    }
84
85    /// Returns a `400 AuthorizationHeaderMalformed` error.
86    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    /// Returns a `403 SignatureDoesNotMatch` error.
95    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    /// Returns a `403 RequestTimeTooSkewed` error.
104    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    /// Returns a `411 MissingContentLength` error.
113    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    /// Returns a `400 BadDigest` error.
122    pub fn bad_digest(message: impl Into<String>) -> Self {
123        Self::new(StatusCode::BAD_REQUEST, "BadDigest", message)
124    }
125
126    /// Returns a `404 NoSuchUpload` error.
127    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    /// Returns a `400 InvalidPart` error.
136    pub fn invalid_part(message: impl Into<String>) -> Self {
137        Self::new(StatusCode::BAD_REQUEST, "InvalidPart", message)
138    }
139
140    /// Returns a `400 EntityTooSmall` error.
141    pub fn entity_too_small(message: impl Into<String>) -> Self {
142        Self::new(StatusCode::BAD_REQUEST, "EntityTooSmall", message)
143    }
144
145    /// Returns a `413 EntityTooLarge` error.
146    pub fn entity_too_large(message: impl Into<String>) -> Self {
147        Self::new(StatusCode::PAYLOAD_TOO_LARGE, "EntityTooLarge", message)
148    }
149
150    /// Returns a `503 SlowDown` error.
151    pub fn slow_down(message: impl Into<String>) -> Self {
152        Self::new(StatusCode::SERVICE_UNAVAILABLE, "SlowDown", message)
153    }
154
155    /// Returns a `416 InvalidRange` error.
156    pub fn invalid_range(message: impl Into<String>) -> Self {
157        Self::new(StatusCode::RANGE_NOT_SATISFIABLE, "InvalidRange", message)
158    }
159
160    /// Returns a `412 PreconditionFailed` error.
161    pub fn precondition_failed(message: impl Into<String>) -> Self {
162        Self::new(
163            StatusCode::PRECONDITION_FAILED,
164            "PreconditionFailed",
165            message,
166        )
167    }
168
169    /// Returns a `405 MethodNotAllowed` error with the endpoint's `Allow` header.
170    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    /// Returns a `501 NotImplemented` error.
183    pub fn not_implemented(message: impl Into<String>) -> Self {
184        Self::new(StatusCode::NOT_IMPLEMENTED, "NotImplemented", message)
185    }
186
187    /// Returns a `500 InternalError` error.
188    pub fn internal(message: impl Into<String>) -> Self {
189        Self::new(StatusCode::INTERNAL_SERVER_ERROR, "InternalError", message)
190    }
191
192    /// Attaches the S3 resource path included in the XML error body.
193    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
194        self.resource = Some(resource.into());
195        self
196    }
197
198    /// Attaches an HTTP response header to the eventual error response.
199    pub fn with_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
200        self.headers.push((name, value));
201        self
202    }
203
204    /// Converts the error into an S3 XML response using a known request ID.
205    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('&', "&amp;")
263        .replace('<', "&lt;")
264        .replace('>', "&gt;")
265        .replace('"', "&quot;")
266        .replace('\'', "&apos;")
267}