Skip to main content

ironflow_api/
error.rs

1//! REST API error types and responses.
2//!
3//! [`ApiError`] is the primary error type for all API handlers. It implements
4//! [`IntoResponse`] to serialize errors to JSON
5//! with proper HTTP status codes.
6
7use axum::Json;
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Response};
10use ironflow_engine::error::MONTHLY_BUDGET_EXCEEDED_CODE;
11use ironflow_store::error::StoreError;
12use ironflow_types::ErrorEnvelope;
13use serde_json::{Value, json};
14use thiserror::Error;
15use tracing::{error, warn};
16use uuid::Uuid;
17
18/// Error type for REST API operations.
19///
20/// Maps to appropriate HTTP status codes and error codes in the JSON response.
21///
22/// # Examples
23///
24/// ```
25/// use ironflow_api::error::ApiError;
26/// use uuid::Uuid;
27///
28/// let err = ApiError::RunNotFound(Uuid::nil());
29/// assert_eq!(err.to_string(), "run not found");
30/// ```
31#[derive(Debug, Error)]
32pub enum ApiError {
33    /// The requested run does not exist (404).
34    #[error("run not found")]
35    RunNotFound(Uuid),
36
37    /// The requested step does not exist (404).
38    #[error("step not found")]
39    StepNotFound(Uuid),
40
41    /// Workflow not found (404).
42    #[error("workflow not found")]
43    WorkflowNotFound(String),
44
45    /// Bad request: invalid input (400).
46    #[error("{0}")]
47    BadRequest(String),
48
49    /// The request conflicts with the current state of the resource (409).
50    #[error("{0}")]
51    Conflict(String),
52
53    /// Authentication required (401).
54    #[error("authentication required")]
55    Unauthorized,
56
57    /// Invalid credentials (401).
58    #[error("invalid credentials")]
59    InvalidCredentials,
60
61    /// Email already taken (409).
62    #[error("email already exists")]
63    DuplicateEmail,
64
65    /// Username already taken (409).
66    #[error("username already exists")]
67    DuplicateUsername,
68
69    /// API key not found (404).
70    #[error("API key not found")]
71    ApiKeyNotFound(Uuid),
72
73    /// User not found (404).
74    #[error("user not found")]
75    UserNotFound(Uuid),
76
77    /// Insufficient permissions for this action (403).
78    #[error("insufficient permissions")]
79    Forbidden,
80
81    /// Secret not found (404).
82    #[error("secret not found")]
83    SecretNotFound(String),
84
85    /// Insufficient scope (403).
86    #[error("insufficient scope")]
87    InsufficientScope,
88
89    /// The idempotency key is already bound to a different request (409).
90    ///
91    /// Carries the run holding the key so the client can inspect it.
92    #[error("idempotency key already used with a different request")]
93    IdempotencyKeyConflict(Uuid),
94    /// The global monthly cost quota is exhausted (429).
95    ///
96    /// Only blocks the creation of new runs; runs already in flight continue.
97    #[error("{0}")]
98    MonthlyBudgetExceeded(String),
99
100    /// The requested artifact does not exist (404).
101    #[error("artifact not found")]
102    ArtifactNotFound(String),
103
104    /// No artifact storage backend is configured (501).
105    ///
106    /// Every other endpoint keeps working: an upgraded deployment that has not
107    /// opted into artifacts is degraded here only.
108    #[error("artifact storage is not configured")]
109    ArtifactStorageUnavailable,
110
111    /// The uploaded payload exceeded the artifact size limit (413).
112    #[error("artifact exceeds the size limit")]
113    ArtifactTooLarge,
114
115    /// Store operation failed (500).
116    #[error("database error")]
117    Store(#[from] StoreError),
118
119    /// Internal server error (500).
120    #[error("internal server error")]
121    Internal(String),
122}
123
124impl ApiError {
125    /// Return the error code for JSON serialization.
126    fn code(&self) -> &str {
127        match self {
128            ApiError::RunNotFound(_) => "RUN_NOT_FOUND",
129            ApiError::StepNotFound(_) => "STEP_NOT_FOUND",
130            ApiError::WorkflowNotFound(_) => "WORKFLOW_NOT_FOUND",
131            ApiError::BadRequest(_) => "BAD_REQUEST",
132            ApiError::Conflict(_) => "CONFLICT",
133            ApiError::Unauthorized => "UNAUTHORIZED",
134            ApiError::InvalidCredentials => "INVALID_CREDENTIALS",
135            ApiError::DuplicateEmail => "DUPLICATE_EMAIL",
136            ApiError::DuplicateUsername => "DUPLICATE_USERNAME",
137            ApiError::ApiKeyNotFound(_) => "API_KEY_NOT_FOUND",
138            ApiError::UserNotFound(_) => "USER_NOT_FOUND",
139            ApiError::SecretNotFound(_) => "SECRET_NOT_FOUND",
140            ApiError::Forbidden => "FORBIDDEN",
141            ApiError::InsufficientScope => "INSUFFICIENT_SCOPE",
142            ApiError::IdempotencyKeyConflict(_) => "IDEMPOTENCY_KEY_CONFLICT",
143            ApiError::MonthlyBudgetExceeded(_) => MONTHLY_BUDGET_EXCEEDED_CODE,
144            ApiError::ArtifactNotFound(_) => "ARTIFACT_NOT_FOUND",
145            ApiError::ArtifactStorageUnavailable => "ARTIFACT_STORAGE_UNAVAILABLE",
146            ApiError::ArtifactTooLarge => "ARTIFACT_TOO_LARGE",
147            ApiError::Store(StoreError::Crypto(_)) => "SECRET_STORE_UNAVAILABLE",
148            ApiError::Store(StoreError::DuplicateArtifact { .. }) => "DUPLICATE_ARTIFACT",
149            ApiError::Store(StoreError::LeaseLost { .. }) => "LEASE_LOST",
150            ApiError::Store(_) => "DATABASE_ERROR",
151            ApiError::Internal(_) => "INTERNAL_ERROR",
152        }
153    }
154
155    /// Return the HTTP status code for this error.
156    fn status(&self) -> StatusCode {
157        match self {
158            ApiError::RunNotFound(_) => StatusCode::NOT_FOUND,
159            ApiError::StepNotFound(_) => StatusCode::NOT_FOUND,
160            ApiError::WorkflowNotFound(_) => StatusCode::NOT_FOUND,
161            ApiError::SecretNotFound(_) => StatusCode::NOT_FOUND,
162            ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
163            ApiError::Conflict(_) => StatusCode::CONFLICT,
164            ApiError::Unauthorized => StatusCode::UNAUTHORIZED,
165            ApiError::InvalidCredentials => StatusCode::UNAUTHORIZED,
166            ApiError::DuplicateEmail => StatusCode::CONFLICT,
167            ApiError::DuplicateUsername => StatusCode::CONFLICT,
168            ApiError::ApiKeyNotFound(_) => StatusCode::NOT_FOUND,
169            ApiError::UserNotFound(_) => StatusCode::NOT_FOUND,
170            ApiError::Forbidden => StatusCode::FORBIDDEN,
171            ApiError::InsufficientScope => StatusCode::FORBIDDEN,
172            ApiError::IdempotencyKeyConflict(_) => StatusCode::CONFLICT,
173            ApiError::MonthlyBudgetExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
174            ApiError::ArtifactNotFound(_) => StatusCode::NOT_FOUND,
175            ApiError::ArtifactStorageUnavailable => StatusCode::NOT_IMPLEMENTED,
176            ApiError::ArtifactTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
177            ApiError::Store(StoreError::Crypto(_)) => StatusCode::NOT_IMPLEMENTED,
178            ApiError::Store(StoreError::DuplicateArtifact { .. }) => StatusCode::CONFLICT,
179            ApiError::Store(StoreError::LeaseLost { .. }) => StatusCode::CONFLICT,
180            ApiError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
181            ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
182        }
183    }
184
185    /// Structured context attached to the JSON error body, if any.
186    ///
187    /// Never carries internal detail: only identifiers the caller is already
188    /// entitled to see.
189    fn details(&self) -> Option<Value> {
190        match self {
191            ApiError::IdempotencyKeyConflict(run_id) => Some(json!({ "run_id": run_id })),
192            _ => None,
193        }
194    }
195}
196
197impl IntoResponse for ApiError {
198    fn into_response(self) -> Response {
199        let status = self.status();
200        let code = self.code().to_string();
201        let details = self.details();
202
203        let message = match &self {
204            ApiError::Store(StoreError::Crypto(_)) => {
205                "secret store not configured (set IRONFLOW_SECRET_KEYS)".to_string()
206            }
207            // Carries the caller-facing detail in its own Display impl,
208            // unlike the generic "database error" of ApiError::Store.
209            ApiError::Store(e @ StoreError::LeaseLost { .. }) => e.to_string(),
210            _ => self.to_string(),
211        };
212
213        match &self {
214            // A lost lease is a client-side condition, not a server fault:
215            // it must not page anyone.
216            ApiError::Store(e @ StoreError::LeaseLost { .. }) => {
217                warn!(error = %e, code = %code, "lease refused")
218            }
219            ApiError::Store(e) => error!(error = %e, code = %code, "store error"),
220            ApiError::Internal(detail) => {
221                error!(detail = %detail, code = %code, "internal error")
222            }
223            _ => {}
224        }
225
226        let envelope = ErrorEnvelope {
227            code,
228            message,
229            details,
230        };
231
232        (status, Json(json!({ "error": envelope }))).into_response()
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn run_not_found_code() {
242        let err = ApiError::RunNotFound(Uuid::nil());
243        assert_eq!(err.code(), "RUN_NOT_FOUND");
244    }
245
246    #[test]
247    fn run_not_found_status() {
248        let err = ApiError::RunNotFound(Uuid::nil());
249        assert_eq!(err.status(), StatusCode::NOT_FOUND);
250    }
251
252    #[test]
253    fn bad_request_status() {
254        let err = ApiError::BadRequest("invalid field".to_string());
255        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
256        assert_eq!(err.code(), "BAD_REQUEST");
257    }
258
259    #[test]
260    fn conflict_status() {
261        let err = ApiError::Conflict("run is already waiting for a retry".to_string());
262        assert_eq!(err.status(), StatusCode::CONFLICT);
263        assert_eq!(err.code(), "CONFLICT");
264    }
265
266    #[test]
267    fn internal_error_status() {
268        let err = ApiError::Internal("something went wrong".to_string());
269        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
270        assert_eq!(err.code(), "INTERNAL_ERROR");
271    }
272
273    #[test]
274    fn error_to_response() {
275        let err = ApiError::BadRequest("invalid input".to_string());
276        let response = err.into_response();
277        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
278    }
279
280    #[test]
281    fn unauthorized_status() {
282        let err = ApiError::Unauthorized;
283        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
284        assert_eq!(err.code(), "UNAUTHORIZED");
285    }
286
287    #[test]
288    fn invalid_credentials_status() {
289        let err = ApiError::InvalidCredentials;
290        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
291        assert_eq!(err.code(), "INVALID_CREDENTIALS");
292    }
293
294    #[test]
295    fn duplicate_email_status() {
296        let err = ApiError::DuplicateEmail;
297        assert_eq!(err.status(), StatusCode::CONFLICT);
298        assert_eq!(err.code(), "DUPLICATE_EMAIL");
299    }
300
301    #[test]
302    fn duplicate_username_status() {
303        let err = ApiError::DuplicateUsername;
304        assert_eq!(err.status(), StatusCode::CONFLICT);
305        assert_eq!(err.code(), "DUPLICATE_USERNAME");
306    }
307
308    #[test]
309    fn workflow_not_found_status() {
310        let err = ApiError::WorkflowNotFound("test".to_string());
311        assert_eq!(err.status(), StatusCode::NOT_FOUND);
312        assert_eq!(err.code(), "WORKFLOW_NOT_FOUND");
313    }
314
315    #[test]
316    fn step_not_found_status() {
317        let err = ApiError::StepNotFound(Uuid::nil());
318        assert_eq!(err.status(), StatusCode::NOT_FOUND);
319        assert_eq!(err.code(), "STEP_NOT_FOUND");
320    }
321
322    #[test]
323    fn user_not_found_status() {
324        let err = ApiError::UserNotFound(Uuid::nil());
325        assert_eq!(err.status(), StatusCode::NOT_FOUND);
326        assert_eq!(err.code(), "USER_NOT_FOUND");
327    }
328
329    #[test]
330    fn forbidden_status() {
331        let err = ApiError::Forbidden;
332        assert_eq!(err.status(), StatusCode::FORBIDDEN);
333        assert_eq!(err.code(), "FORBIDDEN");
334    }
335
336    #[test]
337    fn secret_not_found_status() {
338        let err = ApiError::SecretNotFound("demo/api-key".to_string());
339        assert_eq!(err.status(), StatusCode::NOT_FOUND);
340        assert_eq!(err.code(), "SECRET_NOT_FOUND");
341    }
342
343    #[test]
344    fn monthly_budget_exceeded_status_and_code() {
345        let err = ApiError::MonthlyBudgetExceeded("quota exhausted".to_string());
346        assert_eq!(err.status(), StatusCode::TOO_MANY_REQUESTS);
347        assert_eq!(err.code(), "MONTHLY_BUDGET_EXCEEDED");
348        assert_eq!(err.to_string(), "quota exhausted");
349    }
350}