Skip to main content

scyph_storage/
error.rs

1//! Storage error type definitions for `scyph-storage`.
2//!
3//! Categorizes all possible failures occurring during multipart parsing, MIME validation,
4//! file size limits, AWS S3 operations, and environment configuration.
5
6use scyph_core::{AppError, ErrorDetails};
7use thiserror::Error;
8
9/// Error type for all storage services and extractors in `scyph-storage`.
10///
11/// `StorageError` covers the full lifecycle of file upload and storage operations:
12/// from multipart parsing and validation at the HTTP boundary, through to S3 transmission
13/// and presigned URL generation.
14///
15/// # HTTP Status Mapping
16///
17/// `StorageError` implements `From<StorageError> for AppError` for automatic conversion in
18/// Axum handlers. The mapping is:
19///
20/// | Variant | HTTP Status | Typical Cause |
21/// |---|---|---|
22/// | [`Configuration`](Self::Configuration) | 400 Bad Request | Missing `S3_BUCKET`, invalid env var, or bad S3 credentials found by the boot check |
23/// | [`InvalidFile`](Self::InvalidFile) | 400 Bad Request | Missing field, wrong field name, no filename |
24/// | [`UnsupportedMediaType`](Self::UnsupportedMediaType) | 422 Unprocessable Entity | MIME type not in allowlist or magic byte mismatch |
25/// | [`FileTooLarge`](Self::FileTooLarge) | 422 Unprocessable Entity | File exceeds `FileConfig::max_size()` |
26/// | [`TooManyFiles`](Self::TooManyFiles) | 422 Unprocessable Entity | Batch exceeds `FileConfig::max_files()` |
27/// | [`ValidationError`](Self::ValidationError) | 422 Unprocessable Entity | Structured field-level validation failures |
28/// | [`NotFound`](Self::NotFound) | 404 Not Found | Object key not in bucket or memory store |
29/// | [`Presign`](Self::Presign) | 500 Internal Server Error | Signature calculation failure |
30/// | [`Forbidden`](Self::Forbidden) | 500 Internal Server Error | S3 answered 403 `AccessDenied`: credentials lack permission for the bucket (it is reachable) |
31/// | [`S3`](Self::S3) | 500 Internal Server Error | S3 SDK transmission/auth error |
32/// | [`Internal`](Self::Internal) | 500 Internal Server Error | Unclassified internal failure |
33///
34/// # Example
35///
36/// ```rust,ignore
37/// use scyph_storage::{StorageService, StorageError};
38/// use bytes::Bytes;
39///
40/// async fn upload_or_report(
41///     storage: &impl StorageService,
42///     path: &str,
43/// ) {
44///     match storage.retrieve(path).await {
45///         Ok(data) => println!("Got {} bytes", data.len()),
46///         Err(StorageError::NotFound(msg)) => eprintln!("Object not found: {msg}"),
47///         Err(StorageError::S3(msg)) => eprintln!("S3 error: {msg}"),
48///         Err(e) => eprintln!("Unexpected error: {e}"),
49///     }
50/// }
51/// ```
52#[derive(Debug, Error)]
53pub enum StorageError {
54    /// Missing, empty, or unparseable configuration settings or environment variables.
55    ///
56    /// Examples: `S3_BUCKET` is not set, `S3_REGION` contains whitespace, a
57    /// required credential is missing from the environment, or the `from_env()`
58    /// boot check finds that the configured S3 credentials are rejected.
59    #[error("Configuration error: {0}")]
60    Configuration(String),
61
62    /// Missing field, non-file field, or malformed multipart stream.
63    ///
64    /// Returned by [`FileExtractor`](crate::multipart::FileExtractor) when the expected
65    /// multipart field is absent, lacks a filename, or the multipart boundary is invalid.
66    #[error("Invalid file upload: {0}")]
67    InvalidFile(String),
68
69    /// Uploaded file MIME type is not in the allowed types list defined by [`FileConfig::allowed_mime_types`](crate::multipart::FileConfig::allowed_mime_types).
70    ///
71    /// Also returned when magic byte verification fails (binary content does not match
72    /// the declared `Content-Type` header), preventing MIME-spoofing attacks.
73    #[error("Unsupported media type: {0}")]
74    UnsupportedMediaType(String),
75
76    /// Uploaded file size exceeds the configured maximum byte threshold defined by [`FileConfig::max_size`](crate::multipart::FileConfig::max_size).
77    ///
78    /// Checked during streaming chunk accumulation to abort uploads early and prevent OOM.
79    #[error("File too large: {0}")]
80    FileTooLarge(String),
81
82    /// Number of uploaded files in a batch exceeds the limit defined by [`FileConfig::max_files`](crate::multipart::FileConfig::max_files).
83    ///
84    /// Returned by [`MultiFileExtractor`](crate::multipart::MultiFileExtractor) when more
85    /// files than the configured maximum are present in a single request.
86    #[error("Too many files: {0}")]
87    TooManyFiles(String),
88
89    /// Structured validation failure for file upload parameters.
90    ///
91    /// Used when multiple field-level errors need to be reported together (e.g., in a form
92    /// with several file upload fields). The `details` vector contains per-field error context.
93    ///
94    /// Construct via [`StorageError::validation`].
95    #[error("Storage validation failed: {message}")]
96    ValidationError {
97        /// Summary validation error message.
98        message: String,
99        /// Field-level file upload error details.
100        details: Vec<ErrorDetails>,
101    },
102
103    /// Object was not found in storage.
104    ///
105    /// Returned by [`StorageService::retrieve`](crate::traits::StorageService::retrieve) and
106    /// the URL generation methods when the given path or key does not exist in the bucket or
107    /// in-memory store.
108    #[error("Object not found: {0}")]
109    NotFound(String),
110
111    /// Failure generating a cryptographically signed presigned URL.
112    ///
113    /// Occurs when the S3 SDK fails to compute a request signature, usually due to invalid
114    /// credentials, clock skew, or malformed region configuration.
115    #[error("Presign error: {0}")]
116    Presign(String),
117
118    /// S3 answered `403 Forbidden` with `AccessDenied`: the bucket is reachable, but the
119    /// credentials may not perform the probe's action.
120    ///
121    /// Returned by [`StorageService::test_connection`](crate::traits::StorageService::test_connection)
122    /// when the bucket is reachable but the policy lacks the required permission (e.g. a
123    /// least-privilege policy without `s3:ListBucket`), or when an S3-compatible gateway
124    /// answers `403` without a parseable error body. Wrong credentials are reported as
125    /// [`Configuration`](Self::Configuration) instead, so a typo can be told apart from a
126    /// deliberate least-privilege policy.
127    /// Typed so callers can classify the failure without string-matching the message.
128    #[error("S3 access denied: {0}")]
129    Forbidden(String),
130
131    /// AWS S3 SDK transmission, authentication, or network operation error.
132    ///
133    /// Covers connection timeouts, throttling (503), and other S3-specific transport errors.
134    /// A `403 Forbidden` bucket answer is returned as [`Forbidden`](Self::Forbidden), and a 403
135    /// that names bad credentials as [`Configuration`](Self::Configuration), instead.
136    #[error("S3 storage error: {0}")]
137    S3(String),
138
139    /// Generic internal storage processing error for unclassified failure paths.
140    #[error("Storage error: {0}")]
141    Internal(String),
142}
143
144impl StorageError {
145    /// Constructs a [`StorageError::ValidationError`] with a summary message and field-level details.
146    ///
147    /// # Example
148    ///
149    /// ```rust
150    /// use scyph_storage::StorageError;
151    /// use scyph_core::ErrorDetails;
152    ///
153    /// let err = StorageError::validation(
154    ///     "File upload validation failed",
155    ///     vec![ErrorDetails {
156    ///         code: "FILE_TOO_LARGE".into(),
157    ///         message: "File too large".into(),
158    ///         field: Some("avatar".into()),
159    ///     }],
160    /// );
161    /// ```
162    pub fn validation(message: impl Into<String>, details: Vec<ErrorDetails>) -> Self {
163        Self::ValidationError {
164            message: message.into(),
165            details,
166        }
167    }
168}
169
170impl From<StorageError> for AppError {
171    /// Maps a [`StorageError`] to the appropriate HTTP status code and RFC 7807 [`AppError`] response.
172    fn from(err: StorageError) -> Self {
173        match err {
174            StorageError::Configuration(msg) => {
175                AppError::BadRequest(format!("Storage configuration error: {msg}"))
176            }
177            StorageError::InvalidFile(msg) => AppError::BadRequest(msg),
178            StorageError::UnsupportedMediaType(msg) => AppError::UnprocessableEntity(msg),
179            StorageError::FileTooLarge(msg) => AppError::UnprocessableEntity(msg),
180            StorageError::TooManyFiles(msg) => AppError::UnprocessableEntity(msg),
181            StorageError::ValidationError { message, details } => {
182                AppError::ValidationError { message, details }
183            }
184            StorageError::NotFound(msg) => AppError::NotFound(msg),
185            StorageError::Presign(msg) => AppError::internal(format!("Presigning error: {msg}")),
186            StorageError::Forbidden(msg) => AppError::internal(format!("S3 access denied: {msg}")),
187            StorageError::S3(msg) => AppError::internal(format!("S3 storage error: {msg}")),
188            StorageError::Internal(msg) => AppError::internal(msg),
189        }
190    }
191}