1use std::error::Error;
4use std::fmt;
5use std::io;
6use std::iter;
7use std::sync::Arc;
8
9use tracing::{error, warn};
10
11use crate::SmbError;
12
13pub(crate) type BoxError = Box<dyn Error + Send + Sync>;
14
15const MAX_FIELD_LEN: usize = 128;
17
18#[derive(Debug, Clone)]
24#[non_exhaustive]
25pub enum S3Error {
26 #[non_exhaustive]
29 Status {
30 status: u16,
32 code: Option<String>,
34 request_id: Option<String>,
36 },
37 Transport(Arc<dyn Error + Send + Sync>),
40 TimedOut,
42 DeadlineExceeded,
44 #[doc(hidden)]
46 Stopped,
47 #[doc(hidden)]
50 SourceChanged,
51 SourceRead(Arc<io::Error>),
53 InvalidResponse(&'static str),
55 InvalidArgument(&'static str),
57 Cache(Arc<io::Error>),
59}
60
61impl S3Error {
62 pub(crate) fn status(status: u16, code: Option<&str>, request_id: Option<&str>) -> Self {
66 S3Error::Status {
67 status,
68 code: code.and_then(identifier),
69 request_id: request_id.and_then(identifier),
70 }
71 }
72
73 pub(crate) fn http_status(&self) -> Option<u16> {
75 match self {
76 S3Error::Status { status, .. } => Some(*status),
77 _ => None,
78 }
79 }
80
81 pub(crate) fn code(&self) -> Option<&str> {
83 match self {
84 S3Error::Status { code, .. } => code.as_deref(),
85 _ => None,
86 }
87 }
88
89 pub(crate) fn request_id(&self) -> Option<&str> {
91 match self {
92 S3Error::Status { request_id, .. } => request_id.as_deref(),
93 _ => None,
94 }
95 }
96
97 pub(crate) fn is_no_such_key(&self) -> bool {
101 matches!(
102 (self.http_status(), self.code()),
103 (Some(404), None | Some("NoSuchKey")) | (Some(200), Some("NoSuchKey"))
104 )
105 }
106
107 pub(crate) fn is_precondition_failed(&self) -> bool {
110 self.http_status() == Some(412)
111 }
112
113 pub(crate) fn is_source_changed(&self) -> bool {
117 matches!(self, S3Error::SourceChanged)
118 || matches!(self.code(), Some("XAmzContentSHA256Mismatch" | "BadDigest"))
119 }
120
121 pub(crate) fn is_stopped(&self) -> bool {
123 matches!(self, S3Error::Stopped)
124 }
125
126 pub(crate) fn is_clock_skew(&self) -> bool {
128 self.http_status() == Some(403) && self.code() == Some("RequestTimeTooSkewed")
129 }
130
131 pub(crate) fn is_transient(&self) -> bool {
140 match self {
141 S3Error::Transport(_) | S3Error::TimedOut => true,
142 S3Error::Status { status, code, .. } => {
143 matches!(status, 408 | 429 | 500 | 502 | 503 | 504)
144 || matches!(
145 code.as_deref(),
146 Some(
147 "SlowDown"
148 | "InternalError"
149 | "ServiceUnavailable"
150 | "OperationAborted"
151 )
152 )
153 || (*status == 400 && code.as_deref() == Some("RequestTimeout"))
154 }
155 S3Error::DeadlineExceeded
156 | S3Error::Stopped
157 | S3Error::SourceChanged
158 | S3Error::SourceRead(_)
159 | S3Error::InvalidResponse(_)
160 | S3Error::InvalidArgument(_)
161 | S3Error::Cache(_) => false,
162 }
163 }
164
165 pub(crate) fn transport(source: impl Into<BoxError>) -> Self {
166 S3Error::Transport(Arc::from(source.into()))
167 }
168
169 pub(crate) fn cache(error: SmbError) -> Self {
173 let cause = match error {
174 SmbError::Io(cause) => cause,
175 SmbError::DiskFull => io::Error::new(io::ErrorKind::StorageFull, error),
176 SmbError::QuotaExceeded => io::Error::new(io::ErrorKind::QuotaExceeded, error),
177 other => io::Error::other(other),
178 };
179 S3Error::Cache(Arc::new(cause))
180 }
181
182 pub(crate) fn causes(&self) -> Option<String> {
186 let S3Error::Transport(source) = self else {
187 return None;
188 };
189 let first: &(dyn Error + 'static) = source.as_ref();
190 let chain: Vec<String> = iter::successors(Some(first), |error| (*error).source())
191 .map(ToString::to_string)
192 .collect();
193 Some(chain.join(": "))
194 }
195
196 pub(crate) fn into_smb_error(self) -> SmbError {
203 let (status, code) = (self.http_status(), self.code());
204 match (status, code) {
205 (_, Some("RequestTimeTooSkewed")) => {
206 error!(
207 code = "RequestTimeTooSkewed",
208 request_id = self.request_id(),
209 "the store rejects the request time; check the system clock"
210 );
211 SmbError::Io(io::Error::other(self))
212 }
213 (_, Some("AccessDenied" | "InvalidAccessKeyId" | "SignatureDoesNotMatch"))
214 | (Some(403), _) => {
215 warn!(code, "the store denied access");
216 SmbError::AccessDenied
217 }
218 _ if self.is_no_such_key() => SmbError::NotFound,
219 (_, Some("ObjectParentIsFile")) => SmbError::PathNotFound,
220 (_, Some("ExistingObjectIsDirectory")) => SmbError::Exists,
221 (_, Some("KeyTooLongError")) => SmbError::NameInvalid,
222 (_, Some("EntityTooLarge")) => SmbError::DiskFull,
223 _ => {
224 warn!(
225 status,
226 code,
227 request_id = self.request_id(),
228 cause = self.causes(),
229 "the store request failed"
230 );
231 SmbError::Io(io::Error::other(self))
232 }
233 }
234 }
235}
236
237fn identifier(text: &str) -> Option<String> {
239 let text = text.trim();
240 let plausible = !text.is_empty()
241 && text.len() <= MAX_FIELD_LEN
242 && text.bytes().all(|b| {
243 b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':' | b'/' | b'+' | b'=')
244 });
245 plausible.then(|| text.to_owned())
246}
247
248impl fmt::Display for S3Error {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 match self {
251 S3Error::Status {
252 status,
253 code,
254 request_id,
255 } => {
256 write!(f, "the store answered status {status}")?;
257 if let Some(code) = code {
258 write!(f, " with code {code}")?;
259 }
260 if let Some(id) = request_id {
261 write!(f, " (request id {id})")?;
262 }
263 Ok(())
264 }
265 S3Error::Transport(_) => f.write_str("the request failed in transit"),
266 S3Error::TimedOut => f.write_str("no data moved for 60 seconds"),
267 S3Error::DeadlineExceeded => f.write_str("the deadline passed"),
268 S3Error::Stopped => f.write_str("the call was stopped"),
269 S3Error::SourceChanged => f.write_str("the data to upload changed after it was hashed"),
270 S3Error::SourceRead(_) => f.write_str("the data to upload could not be read"),
271 S3Error::InvalidResponse(what) => write!(f, "invalid response: {what}"),
272 S3Error::InvalidArgument(what) => write!(f, "invalid argument: {what}"),
273 S3Error::Cache(_) => f.write_str("the cache directory could not be used"),
274 }
275 }
276}
277
278impl Error for S3Error {
279 fn source(&self) -> Option<&(dyn Error + 'static)> {
280 match self {
281 S3Error::Transport(source) => Some(source.as_ref()),
282 S3Error::SourceRead(source) | S3Error::Cache(source) => Some(source.as_ref()),
283 _ => None,
284 }
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 fn status(status: u16, code: &str) -> S3Error {
293 S3Error::status(status, Some(code), Some("REQ123"))
294 }
295
296 #[test]
297 fn displays_status_code_and_request_id() {
298 assert_eq!(
299 status(503, "SlowDown").to_string(),
300 "the store answered status 503 with code SlowDown (request id REQ123)"
301 );
302 assert_eq!(
303 S3Error::status(404, None, None).to_string(),
304 "the store answered status 404"
305 );
306 }
307
308 #[test]
309 fn text_from_a_response_body_never_reaches_a_message() {
310 let body =
311 "<Error>AWSAccessKeyId=AKIA... StringToSign=AWS4-HMAC-SHA256 Signature=abc</Error>";
312 let error = S3Error::status(403, Some(body), Some(body));
313 assert_eq!(error.code(), None);
314 assert_eq!(error.request_id(), None);
315 for shown in [error.to_string(), format!("{error:?}")] {
316 assert!(!shown.contains("AKIA"), "{shown}");
317 assert!(!shown.contains("StringToSign"), "{shown}");
318 assert!(!shown.contains("Signature"), "{shown}");
319 }
320 }
321
322 #[test]
323 fn keeps_codes_and_request_ids_that_are_identifiers() {
324 let error = S3Error::status(
325 500,
326 Some(" InternalError "),
327 Some("tx00000000000000000001-0065c4b0f9-1234-default"),
328 );
329 assert_eq!(error.code(), Some("InternalError"));
330 assert_eq!(
331 error.request_id(),
332 Some("tx00000000000000000001-0065c4b0f9-1234-default")
333 );
334 assert_eq!(S3Error::status(500, Some(""), Some(" ")).code(), None);
335 let long = "a".repeat(MAX_FIELD_LEN + 1);
336 assert_eq!(S3Error::status(500, Some(&long), None).code(), None);
337 assert_eq!(
338 S3Error::status(500, Some(&long[1..]), None)
339 .code()
340 .map(str::len),
341 Some(MAX_FIELD_LEN)
342 );
343 }
344
345 #[test]
346 fn the_message_of_a_transport_error_hides_its_source() {
347 let error = S3Error::transport("connection refused by 192.0.2.1");
348 assert_eq!(error.to_string(), "the request failed in transit");
349 assert_eq!(
350 error.source().map(ToString::to_string).as_deref(),
351 Some("connection refused by 192.0.2.1")
352 );
353 }
354
355 #[test]
356 fn a_status_error_is_read_through_accessors_and_predicates() {
357 let error = status(409, "ObjectParentIsFile");
358 assert_eq!(error.http_status(), Some(409));
359 assert_eq!(error.code(), Some("ObjectParentIsFile"));
360 assert_eq!(error.request_id(), Some("REQ123"));
361 assert!(!error.is_no_such_key());
362 assert!(status(404, "NoSuchKey").is_no_such_key());
363 assert!(S3Error::status(404, None, None).is_no_such_key());
364 assert!(!status(404, "NoSuchBucket").is_no_such_key());
365 assert!(!status(404, "NoSuchUpload").is_no_such_key());
366 assert!(!status(403, "NoSuchKey").is_no_such_key());
367 assert!(status(412, "PreconditionFailed").is_precondition_failed());
368 assert!(S3Error::status(412, None, None).is_precondition_failed());
369 assert!(!status(400, "PreconditionFailed").is_precondition_failed());
370 assert_eq!(S3Error::TimedOut.http_status(), None);
371 assert_eq!(S3Error::InvalidResponse("x").code(), None);
372 }
373
374 #[test]
375 fn classifies_transient_errors() {
376 for transient in [
377 S3Error::TimedOut,
378 S3Error::transport("reset"),
379 S3Error::status(408, None, None),
380 S3Error::status(429, None, None),
381 S3Error::status(500, None, None),
382 S3Error::status(502, None, None),
383 S3Error::status(503, None, None),
384 S3Error::status(504, None, None),
385 status(400, "SlowDown"),
386 status(400, "RequestTimeout"),
387 status(200, "InternalError"),
388 status(200, "SlowDown"),
389 status(200, "ServiceUnavailable"),
390 status(409, "OperationAborted"),
391 ] {
392 assert!(transient.is_transient(), "{transient:?}");
393 }
394 for permanent in [
395 S3Error::status(400, None, None),
396 S3Error::status(403, None, None),
397 S3Error::status(404, None, None),
398 S3Error::status(409, None, None),
399 S3Error::status(412, None, None),
400 S3Error::status(416, None, None),
401 S3Error::status(501, None, None),
402 status(200, "AccessDenied"),
403 status(403, "RequestTimeTooSkewed"),
404 status(403, "RequestTimeout"),
405 status(400, "XAmzContentSHA256Mismatch"),
406 status(400, "BadDigest"),
407 S3Error::DeadlineExceeded,
408 S3Error::Stopped,
409 S3Error::SourceChanged,
410 S3Error::SourceRead(Arc::new(io::Error::other("x"))),
411 S3Error::InvalidResponse("x"),
412 S3Error::InvalidArgument("x"),
413 S3Error::Cache(Arc::new(io::Error::other("x"))),
414 ] {
415 assert!(!permanent.is_transient(), "{permanent:?}");
416 }
417 }
418
419 fn smb(error: S3Error) -> SmbError {
420 error.into_smb_error()
421 }
422
423 fn cause(error: S3Error) -> Arc<io::Error> {
424 match error {
425 S3Error::Cache(cause) => cause,
426 other => panic!("not a cache error: {other:?}"),
427 }
428 }
429
430 #[test]
431 fn a_cache_failure_keeps_the_kind_and_the_source_of_the_error() {
432 let kept = cause(S3Error::cache(SmbError::Io(io::Error::new(
433 io::ErrorKind::PermissionDenied,
434 "no access",
435 ))));
436 assert_eq!(kept.kind(), io::ErrorKind::PermissionDenied);
437 assert_eq!(kept.to_string(), "no access");
438
439 let full = cause(S3Error::cache(SmbError::DiskFull));
440 assert_eq!(full.kind(), io::ErrorKind::StorageFull);
441 let quota = cause(S3Error::cache(SmbError::QuotaExceeded));
442 assert_eq!(quota.kind(), io::ErrorKind::QuotaExceeded);
443
444 let other = cause(S3Error::cache(SmbError::Sharing));
445 let source = other.get_ref().expect("the error is the source");
446 assert!(matches!(
447 source.downcast_ref::<SmbError>(),
448 Some(SmbError::Sharing)
449 ));
450 }
451
452 #[test]
453 fn maps_store_errors_to_share_errors() {
454 assert!(matches!(smb(status(404, "NoSuchKey")), SmbError::NotFound));
455 assert!(matches!(
456 smb(S3Error::status(404, None, None)),
457 SmbError::NotFound
458 ));
459 for code in [
460 "AccessDenied",
461 "InvalidAccessKeyId",
462 "SignatureDoesNotMatch",
463 ] {
464 assert!(
465 matches!(smb(status(403, code)), SmbError::AccessDenied),
466 "{code}"
467 );
468 }
469 assert!(matches!(
470 smb(S3Error::status(403, None, None)),
471 SmbError::AccessDenied
472 ));
473 assert!(matches!(
474 smb(status(409, "ObjectParentIsFile")),
475 SmbError::PathNotFound
476 ));
477 assert!(matches!(
478 smb(status(409, "ExistingObjectIsDirectory")),
479 SmbError::Exists
480 ));
481 assert!(matches!(
482 smb(status(400, "KeyTooLongError")),
483 SmbError::NameInvalid
484 ));
485 assert!(matches!(
486 smb(status(400, "EntityTooLarge")),
487 SmbError::DiskFull
488 ));
489 }
490
491 #[test]
492 fn every_other_failure_is_an_io_error() {
493 for error in [
494 status(403, "RequestTimeTooSkewed"),
495 status(404, "NoSuchBucket"),
496 status(409, "OperationAborted"),
497 status(503, "SlowDown"),
498 S3Error::status(500, None, None),
499 S3Error::TimedOut,
500 S3Error::transport("reset"),
501 S3Error::DeadlineExceeded,
502 S3Error::Stopped,
503 S3Error::SourceChanged,
504 S3Error::SourceRead(Arc::new(io::Error::other("x"))),
505 S3Error::InvalidResponse("x"),
506 S3Error::InvalidArgument("x"),
507 ] {
508 let shown = format!("{error:?}");
509 assert!(matches!(smb(error), SmbError::Io(_)), "{shown}");
510 }
511 }
512
513 #[test]
514 fn the_io_error_keeps_the_store_error_as_its_source() {
515 let SmbError::Io(io) = smb(status(503, "SlowDown")) else {
516 panic!("not an io error");
517 };
518 let source = io.get_ref().unwrap().downcast_ref::<S3Error>().unwrap();
519 assert_eq!(source.code(), Some("SlowDown"));
520 }
521
522 #[test]
523 fn a_rejected_clock_is_told_apart() {
524 assert!(status(403, "RequestTimeTooSkewed").is_clock_skew());
525 assert!(!status(403, "AccessDenied").is_clock_skew());
526 assert!(!status(400, "RequestTimeTooSkewed").is_clock_skew());
527 assert!(!S3Error::TimedOut.is_clock_skew());
528 }
529
530 #[test]
531 fn a_changed_source_is_told_apart() {
532 for changed in [
533 S3Error::SourceChanged,
534 status(400, "XAmzContentSHA256Mismatch"),
535 status(400, "BadDigest"),
536 ] {
537 assert!(changed.is_source_changed(), "{changed:?}");
538 }
539 for other in [
540 S3Error::status(400, None, None),
541 status(400, "InvalidRequest"),
542 S3Error::TimedOut,
543 S3Error::SourceRead(Arc::new(io::Error::other("x"))),
544 ] {
545 assert!(!other.is_source_changed(), "{other:?}");
546 }
547 }
548
549 #[test]
550 fn an_error_document_under_status_200_maps_by_its_code() {
551 for (code, expected) in [
552 ("AccessDenied", "AccessDenied"),
553 ("InvalidAccessKeyId", "AccessDenied"),
554 ("SignatureDoesNotMatch", "AccessDenied"),
555 ("NoSuchKey", "NotFound"),
556 ] {
557 let shown = format!("{:?}", smb(status(200, code)));
558 assert!(shown.starts_with(expected), "{code}: {shown}");
559 }
560 assert!(matches!(
561 smb(S3Error::status(200, None, None)),
562 SmbError::Io(_)
563 ));
564 assert!(status(200, "NoSuchKey").is_no_such_key());
565 }
566
567 #[test]
568 fn the_causes_of_a_transport_error_are_listed_outermost_first() {
569 #[derive(Debug)]
570 struct Layer(&'static str, Option<Box<Layer>>);
571 impl fmt::Display for Layer {
572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 f.write_str(self.0)
574 }
575 }
576 impl Error for Layer {
577 fn source(&self) -> Option<&(dyn Error + 'static)> {
578 self.1
579 .as_deref()
580 .map(|inner| inner as &(dyn Error + 'static))
581 }
582 }
583 let inner = Layer("connection refused", None);
584 let middle = Layer("tcp connect error", Some(Box::new(inner)));
585 let error = S3Error::transport(Layer("client error", Some(Box::new(middle))));
586 assert_eq!(
587 error.causes().as_deref(),
588 Some("client error: tcp connect error: connection refused")
589 );
590 assert_eq!(error.to_string(), "the request failed in transit");
591 assert_eq!(status(503, "SlowDown").causes(), None);
592 assert_eq!(S3Error::TimedOut.causes(), None);
593 }
594}