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    /// Schedule not found (404).
116    #[error("schedule not found")]
117    ScheduleNotFound(Uuid),
118
119    /// Approval delegation not found (404).
120    #[error("approval delegation not found")]
121    DelegationNotFound(Uuid),
122
123    /// Store operation failed (500).
124    #[error("database error")]
125    Store(StoreError),
126
127    /// Internal server error (500).
128    #[error("internal server error")]
129    Internal(String),
130
131    /// An upstream service is unreachable or returned an error (502).
132    #[error("upstream service unavailable")]
133    BadGateway(String),
134}
135
136impl From<StoreError> for ApiError {
137    fn from(e: StoreError) -> Self {
138        match e {
139            StoreError::ScheduleNotFound(id) => ApiError::ScheduleNotFound(id),
140            StoreError::DelegationNotFound(id) => ApiError::DelegationNotFound(id),
141            other => ApiError::Store(other),
142        }
143    }
144}
145
146impl ApiError {
147    /// Return the error code for JSON serialization.
148    fn code(&self) -> &str {
149        match self {
150            ApiError::RunNotFound(_) => "RUN_NOT_FOUND",
151            ApiError::StepNotFound(_) => "STEP_NOT_FOUND",
152            ApiError::WorkflowNotFound(_) => "WORKFLOW_NOT_FOUND",
153            ApiError::BadRequest(_) => "BAD_REQUEST",
154            ApiError::Conflict(_) => "CONFLICT",
155            ApiError::Unauthorized => "UNAUTHORIZED",
156            ApiError::InvalidCredentials => "INVALID_CREDENTIALS",
157            ApiError::DuplicateEmail => "DUPLICATE_EMAIL",
158            ApiError::DuplicateUsername => "DUPLICATE_USERNAME",
159            ApiError::ApiKeyNotFound(_) => "API_KEY_NOT_FOUND",
160            ApiError::UserNotFound(_) => "USER_NOT_FOUND",
161            ApiError::SecretNotFound(_) => "SECRET_NOT_FOUND",
162            ApiError::Forbidden => "FORBIDDEN",
163            ApiError::InsufficientScope => "INSUFFICIENT_SCOPE",
164            ApiError::IdempotencyKeyConflict(_) => "IDEMPOTENCY_KEY_CONFLICT",
165            ApiError::MonthlyBudgetExceeded(_) => MONTHLY_BUDGET_EXCEEDED_CODE,
166            ApiError::ArtifactNotFound(_) => "ARTIFACT_NOT_FOUND",
167            ApiError::ArtifactStorageUnavailable => "ARTIFACT_STORAGE_UNAVAILABLE",
168            ApiError::ArtifactTooLarge => "ARTIFACT_TOO_LARGE",
169            ApiError::ScheduleNotFound(_) => "SCHEDULE_NOT_FOUND",
170            ApiError::DelegationNotFound(_) => "DELEGATION_NOT_FOUND",
171            ApiError::Store(StoreError::Crypto(_)) => "SECRET_STORE_UNAVAILABLE",
172            ApiError::Store(StoreError::DuplicateArtifact { .. }) => "DUPLICATE_ARTIFACT",
173            ApiError::Store(StoreError::LeaseLost { .. }) => "LEASE_LOST",
174            ApiError::Store(_) => "DATABASE_ERROR",
175            ApiError::Internal(_) => "INTERNAL_ERROR",
176            ApiError::BadGateway(_) => "BAD_GATEWAY",
177        }
178    }
179
180    /// Return the HTTP status code for this error.
181    fn status(&self) -> StatusCode {
182        match self {
183            ApiError::RunNotFound(_) => StatusCode::NOT_FOUND,
184            ApiError::StepNotFound(_) => StatusCode::NOT_FOUND,
185            ApiError::WorkflowNotFound(_) => StatusCode::NOT_FOUND,
186            ApiError::SecretNotFound(_) => StatusCode::NOT_FOUND,
187            ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
188            ApiError::Conflict(_) => StatusCode::CONFLICT,
189            ApiError::Unauthorized => StatusCode::UNAUTHORIZED,
190            ApiError::InvalidCredentials => StatusCode::UNAUTHORIZED,
191            ApiError::DuplicateEmail => StatusCode::CONFLICT,
192            ApiError::DuplicateUsername => StatusCode::CONFLICT,
193            ApiError::ApiKeyNotFound(_) => StatusCode::NOT_FOUND,
194            ApiError::UserNotFound(_) => StatusCode::NOT_FOUND,
195            ApiError::Forbidden => StatusCode::FORBIDDEN,
196            ApiError::InsufficientScope => StatusCode::FORBIDDEN,
197            ApiError::IdempotencyKeyConflict(_) => StatusCode::CONFLICT,
198            ApiError::MonthlyBudgetExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
199            ApiError::ArtifactNotFound(_) => StatusCode::NOT_FOUND,
200            ApiError::ArtifactStorageUnavailable => StatusCode::NOT_IMPLEMENTED,
201            ApiError::ArtifactTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
202            ApiError::ScheduleNotFound(_) => StatusCode::NOT_FOUND,
203            ApiError::DelegationNotFound(_) => StatusCode::NOT_FOUND,
204            ApiError::Store(StoreError::Crypto(_)) => StatusCode::NOT_IMPLEMENTED,
205            ApiError::Store(StoreError::DuplicateArtifact { .. }) => StatusCode::CONFLICT,
206            ApiError::Store(StoreError::LeaseLost { .. }) => StatusCode::CONFLICT,
207            ApiError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
208            ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
209            ApiError::BadGateway(_) => StatusCode::BAD_GATEWAY,
210        }
211    }
212
213    /// Structured context attached to the JSON error body, if any.
214    ///
215    /// Never carries internal detail: only identifiers the caller is already
216    /// entitled to see.
217    fn details(&self) -> Option<Value> {
218        match self {
219            ApiError::IdempotencyKeyConflict(run_id) => Some(json!({ "run_id": run_id })),
220            _ => None,
221        }
222    }
223}
224
225impl IntoResponse for ApiError {
226    fn into_response(self) -> Response {
227        let status = self.status();
228        let code = self.code().to_string();
229        let details = self.details();
230
231        let message = match &self {
232            ApiError::Store(StoreError::Crypto(_)) => {
233                "secret store not configured (set IRONFLOW_SECRET_KEYS)".to_string()
234            }
235            // Carries the caller-facing detail in its own Display impl,
236            // unlike the generic "database error" of ApiError::Store.
237            ApiError::Store(e @ StoreError::LeaseLost { .. }) => e.to_string(),
238            _ => self.to_string(),
239        };
240
241        match &self {
242            // A lost lease is a client-side condition, not a server fault:
243            // it must not page anyone.
244            ApiError::Store(e @ StoreError::LeaseLost { .. }) => {
245                warn!(error = %e, code = %code, "lease refused")
246            }
247            ApiError::Store(e) => error!(error = %e, code = %code, "store error"),
248            ApiError::Internal(detail) => {
249                error!(detail = %detail, code = %code, "internal error")
250            }
251            _ => {}
252        }
253
254        let envelope = ErrorEnvelope {
255            code,
256            message,
257            details,
258        };
259
260        (status, Json(json!({ "error": envelope }))).into_response()
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn run_not_found_code() {
270        let err = ApiError::RunNotFound(Uuid::nil());
271        assert_eq!(err.code(), "RUN_NOT_FOUND");
272    }
273
274    #[test]
275    fn run_not_found_status() {
276        let err = ApiError::RunNotFound(Uuid::nil());
277        assert_eq!(err.status(), StatusCode::NOT_FOUND);
278    }
279
280    #[test]
281    fn bad_request_status() {
282        let err = ApiError::BadRequest("invalid field".to_string());
283        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
284        assert_eq!(err.code(), "BAD_REQUEST");
285    }
286
287    #[test]
288    fn conflict_status() {
289        let err = ApiError::Conflict("run is already waiting for a retry".to_string());
290        assert_eq!(err.status(), StatusCode::CONFLICT);
291        assert_eq!(err.code(), "CONFLICT");
292    }
293
294    #[test]
295    fn internal_error_status() {
296        let err = ApiError::Internal("something went wrong".to_string());
297        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
298        assert_eq!(err.code(), "INTERNAL_ERROR");
299    }
300
301    #[test]
302    fn error_to_response() {
303        let err = ApiError::BadRequest("invalid input".to_string());
304        let response = err.into_response();
305        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
306    }
307
308    #[test]
309    fn unauthorized_status() {
310        let err = ApiError::Unauthorized;
311        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
312        assert_eq!(err.code(), "UNAUTHORIZED");
313    }
314
315    #[test]
316    fn invalid_credentials_status() {
317        let err = ApiError::InvalidCredentials;
318        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
319        assert_eq!(err.code(), "INVALID_CREDENTIALS");
320    }
321
322    #[test]
323    fn duplicate_email_status() {
324        let err = ApiError::DuplicateEmail;
325        assert_eq!(err.status(), StatusCode::CONFLICT);
326        assert_eq!(err.code(), "DUPLICATE_EMAIL");
327    }
328
329    #[test]
330    fn duplicate_username_status() {
331        let err = ApiError::DuplicateUsername;
332        assert_eq!(err.status(), StatusCode::CONFLICT);
333        assert_eq!(err.code(), "DUPLICATE_USERNAME");
334    }
335
336    #[test]
337    fn workflow_not_found_status() {
338        let err = ApiError::WorkflowNotFound("test".to_string());
339        assert_eq!(err.status(), StatusCode::NOT_FOUND);
340        assert_eq!(err.code(), "WORKFLOW_NOT_FOUND");
341    }
342
343    #[test]
344    fn step_not_found_status() {
345        let err = ApiError::StepNotFound(Uuid::nil());
346        assert_eq!(err.status(), StatusCode::NOT_FOUND);
347        assert_eq!(err.code(), "STEP_NOT_FOUND");
348    }
349
350    #[test]
351    fn user_not_found_status() {
352        let err = ApiError::UserNotFound(Uuid::nil());
353        assert_eq!(err.status(), StatusCode::NOT_FOUND);
354        assert_eq!(err.code(), "USER_NOT_FOUND");
355    }
356
357    #[test]
358    fn forbidden_status() {
359        let err = ApiError::Forbidden;
360        assert_eq!(err.status(), StatusCode::FORBIDDEN);
361        assert_eq!(err.code(), "FORBIDDEN");
362    }
363
364    #[test]
365    fn secret_not_found_status() {
366        let err = ApiError::SecretNotFound("demo/api-key".to_string());
367        assert_eq!(err.status(), StatusCode::NOT_FOUND);
368        assert_eq!(err.code(), "SECRET_NOT_FOUND");
369    }
370
371    #[test]
372    fn delegation_not_found_status_and_code() {
373        let err = ApiError::DelegationNotFound(Uuid::nil());
374        assert_eq!(err.status(), StatusCode::NOT_FOUND);
375        assert_eq!(err.code(), "DELEGATION_NOT_FOUND");
376    }
377
378    #[test]
379    fn monthly_budget_exceeded_status_and_code() {
380        let err = ApiError::MonthlyBudgetExceeded("quota exhausted".to_string());
381        assert_eq!(err.status(), StatusCode::TOO_MANY_REQUESTS);
382        assert_eq!(err.code(), "MONTHLY_BUDGET_EXCEEDED");
383        assert_eq!(err.to_string(), "quota exhausted");
384    }
385}