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_auth::password::PasswordPolicyError;
11use ironflow_engine::error::{CONCURRENCY_CONFLICT_CODE, MONTHLY_BUDGET_EXCEEDED_CODE};
12use ironflow_store::error::StoreError;
13use ironflow_types::ErrorEnvelope;
14use serde_json::{Value, json};
15use thiserror::Error;
16use tracing::{error, warn};
17use uuid::Uuid;
18
19/// Error type for REST API operations.
20///
21/// Maps to appropriate HTTP status codes and error codes in the JSON response.
22///
23/// # Examples
24///
25/// ```
26/// use ironflow_api::error::ApiError;
27/// use uuid::Uuid;
28///
29/// let err = ApiError::RunNotFound(Uuid::nil());
30/// assert_eq!(err.to_string(), "run not found");
31/// ```
32#[derive(Debug, Error)]
33pub enum ApiError {
34    /// The requested run does not exist (404).
35    #[error("run not found")]
36    RunNotFound(Uuid),
37
38    /// The requested step does not exist (404).
39    #[error("step not found")]
40    StepNotFound(Uuid),
41
42    /// Workflow not found (404).
43    #[error("workflow not found")]
44    WorkflowNotFound(String),
45
46    /// Bad request: invalid input (400).
47    #[error("{0}")]
48    BadRequest(String),
49
50    /// The request conflicts with the current state of the resource (409).
51    #[error("{0}")]
52    Conflict(String),
53
54    /// Authentication required (401).
55    #[error("authentication required")]
56    Unauthorized,
57
58    /// Invalid credentials (401).
59    #[error("invalid credentials")]
60    InvalidCredentials,
61
62    /// Email already taken (409).
63    #[error("email already exists")]
64    DuplicateEmail,
65
66    /// Username already taken (409).
67    #[error("username already exists")]
68    DuplicateUsername,
69
70    /// The chosen password breaks the strength policy (400).
71    ///
72    /// The message says which rule, so the user knows what to change.
73    #[error("{0}")]
74    WeakPassword(#[from] PasswordPolicyError),
75
76    /// API key not found (404).
77    #[error("API key not found")]
78    ApiKeyNotFound(Uuid),
79
80    /// User not found (404).
81    #[error("user not found")]
82    UserNotFound(Uuid),
83
84    /// Insufficient permissions for this action (403).
85    #[error("insufficient permissions")]
86    Forbidden,
87
88    /// Secret not found (404).
89    #[error("secret not found")]
90    SecretNotFound(String),
91
92    /// Insufficient scope (403).
93    #[error("insufficient scope")]
94    InsufficientScope,
95
96    /// The idempotency key is already bound to a different request (409).
97    ///
98    /// Carries the run holding the key so the client can inspect it.
99    #[error("idempotency key already used with a different request")]
100    IdempotencyKeyConflict(Uuid),
101    /// A non-terminal run already holds the requested concurrency key (409).
102    ///
103    /// Carries the key and the run holding it so the client can follow it.
104    #[error("concurrency key {key:?} is held by active run {run_id}")]
105    ConcurrencyConflict {
106        /// The contested key.
107        key: String,
108        /// The run holding the key.
109        run_id: Uuid,
110    },
111    /// The global monthly cost quota is exhausted (429).
112    ///
113    /// Only blocks the creation of new runs; runs already in flight continue.
114    #[error("{0}")]
115    MonthlyBudgetExceeded(String),
116
117    /// The requested artifact does not exist (404).
118    #[error("artifact not found")]
119    ArtifactNotFound(String),
120
121    /// No artifact storage backend is configured (501).
122    ///
123    /// Every other endpoint keeps working: an upgraded deployment that has not
124    /// opted into artifacts is degraded here only.
125    #[error("artifact storage is not configured")]
126    ArtifactStorageUnavailable,
127
128    /// The uploaded payload exceeded the artifact size limit (413).
129    #[error("artifact exceeds the size limit")]
130    ArtifactTooLarge,
131
132    /// Schedule not found (404).
133    #[error("schedule not found")]
134    ScheduleNotFound(Uuid),
135
136    /// Approval delegation not found (404).
137    #[error("approval delegation not found")]
138    DelegationNotFound(Uuid),
139
140    /// Provider Account not found (404), by id or name.
141    #[error("provider account not found: {0}")]
142    ProviderAccountNotFound(String),
143
144    /// The account credential was rejected, by format or by the provider (422).
145    #[error("{0}")]
146    AccountCredentialRejected(String),
147
148    /// Store operation failed (500).
149    #[error("database error")]
150    Store(StoreError),
151
152    /// Internal server error (500).
153    #[error("internal server error")]
154    Internal(String),
155
156    /// An upstream service is unreachable or returned an error (502).
157    #[error("upstream service unavailable")]
158    BadGateway(String),
159
160    /// No template registry exists at the configured URL (404).
161    #[error("template registry not found, check IRONFLOW_REGISTRY_URL")]
162    RegistryNotFound,
163
164    /// The template registry host cannot be reached (502).
165    #[error("template registry unreachable")]
166    RegistryUnreachable,
167
168    /// A submitted value does not match the expected JSON schema (422).
169    ///
170    /// Carries one human-readable message per violation, returned to the
171    /// caller under `details.errors`.
172    #[error("input does not match the expected schema")]
173    InvalidInput(Vec<String>),
174}
175
176impl From<StoreError> for ApiError {
177    fn from(e: StoreError) -> Self {
178        match e {
179            StoreError::ScheduleNotFound(id) => ApiError::ScheduleNotFound(id),
180            StoreError::DelegationNotFound(id) => ApiError::DelegationNotFound(id),
181            StoreError::ProviderAccountNotFound(id) => {
182                ApiError::ProviderAccountNotFound(id.to_string())
183            }
184            StoreError::DuplicateProviderAccount(name) => {
185                ApiError::Conflict(format!("provider account '{name}' already exists"))
186            }
187            StoreError::ConcurrencyConflict { key, run_id } => {
188                ApiError::ConcurrencyConflict { key, run_id }
189            }
190            other => ApiError::Store(other),
191        }
192    }
193}
194
195impl ApiError {
196    /// Return the error code for JSON serialization.
197    fn code(&self) -> &str {
198        match self {
199            ApiError::RunNotFound(_) => "RUN_NOT_FOUND",
200            ApiError::StepNotFound(_) => "STEP_NOT_FOUND",
201            ApiError::WorkflowNotFound(_) => "WORKFLOW_NOT_FOUND",
202            ApiError::BadRequest(_) => "BAD_REQUEST",
203            ApiError::Conflict(_) => "CONFLICT",
204            ApiError::Unauthorized => "UNAUTHORIZED",
205            ApiError::InvalidCredentials => "INVALID_CREDENTIALS",
206            ApiError::DuplicateEmail => "DUPLICATE_EMAIL",
207            ApiError::DuplicateUsername => "DUPLICATE_USERNAME",
208            ApiError::WeakPassword(_) => "WEAK_PASSWORD",
209            ApiError::ApiKeyNotFound(_) => "API_KEY_NOT_FOUND",
210            ApiError::UserNotFound(_) => "USER_NOT_FOUND",
211            ApiError::SecretNotFound(_) => "SECRET_NOT_FOUND",
212            ApiError::Forbidden => "FORBIDDEN",
213            ApiError::InsufficientScope => "INSUFFICIENT_SCOPE",
214            ApiError::IdempotencyKeyConflict(_) => "IDEMPOTENCY_KEY_CONFLICT",
215            ApiError::ConcurrencyConflict { .. } => CONCURRENCY_CONFLICT_CODE,
216            ApiError::MonthlyBudgetExceeded(_) => MONTHLY_BUDGET_EXCEEDED_CODE,
217            ApiError::ArtifactNotFound(_) => "ARTIFACT_NOT_FOUND",
218            ApiError::ArtifactStorageUnavailable => "ARTIFACT_STORAGE_UNAVAILABLE",
219            ApiError::ArtifactTooLarge => "ARTIFACT_TOO_LARGE",
220            ApiError::ScheduleNotFound(_) => "SCHEDULE_NOT_FOUND",
221            ApiError::DelegationNotFound(_) => "DELEGATION_NOT_FOUND",
222            ApiError::ProviderAccountNotFound(_) => "PROVIDER_ACCOUNT_NOT_FOUND",
223            ApiError::AccountCredentialRejected(_) => "ACCOUNT_CREDENTIAL_REJECTED",
224            ApiError::Store(StoreError::Crypto(_)) => "SECRET_STORE_UNAVAILABLE",
225            ApiError::Store(StoreError::DuplicateArtifact { .. }) => "DUPLICATE_ARTIFACT",
226            ApiError::Store(StoreError::LeaseLost { .. }) => "LEASE_LOST",
227            ApiError::Store(_) => "DATABASE_ERROR",
228            ApiError::Internal(_) => "INTERNAL_ERROR",
229            ApiError::BadGateway(_) => "BAD_GATEWAY",
230            ApiError::RegistryNotFound => "REGISTRY_NOT_FOUND",
231            ApiError::RegistryUnreachable => "REGISTRY_UNREACHABLE",
232            ApiError::InvalidInput(_) => "INVALID_INPUT",
233        }
234    }
235
236    /// Return the HTTP status code for this error.
237    fn status(&self) -> StatusCode {
238        match self {
239            ApiError::RunNotFound(_) => StatusCode::NOT_FOUND,
240            ApiError::StepNotFound(_) => StatusCode::NOT_FOUND,
241            ApiError::WorkflowNotFound(_) => StatusCode::NOT_FOUND,
242            ApiError::SecretNotFound(_) => StatusCode::NOT_FOUND,
243            ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
244            ApiError::Conflict(_) => StatusCode::CONFLICT,
245            ApiError::Unauthorized => StatusCode::UNAUTHORIZED,
246            ApiError::InvalidCredentials => StatusCode::UNAUTHORIZED,
247            ApiError::DuplicateEmail => StatusCode::CONFLICT,
248            ApiError::DuplicateUsername => StatusCode::CONFLICT,
249            ApiError::WeakPassword(_) => StatusCode::BAD_REQUEST,
250            ApiError::ApiKeyNotFound(_) => StatusCode::NOT_FOUND,
251            ApiError::UserNotFound(_) => StatusCode::NOT_FOUND,
252            ApiError::Forbidden => StatusCode::FORBIDDEN,
253            ApiError::InsufficientScope => StatusCode::FORBIDDEN,
254            ApiError::IdempotencyKeyConflict(_) => StatusCode::CONFLICT,
255            ApiError::ConcurrencyConflict { .. } => StatusCode::CONFLICT,
256            ApiError::MonthlyBudgetExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
257            ApiError::ArtifactNotFound(_) => StatusCode::NOT_FOUND,
258            ApiError::ArtifactStorageUnavailable => StatusCode::NOT_IMPLEMENTED,
259            ApiError::ArtifactTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
260            ApiError::ScheduleNotFound(_) => StatusCode::NOT_FOUND,
261            ApiError::DelegationNotFound(_) => StatusCode::NOT_FOUND,
262            ApiError::ProviderAccountNotFound(_) => StatusCode::NOT_FOUND,
263            ApiError::AccountCredentialRejected(_) => StatusCode::UNPROCESSABLE_ENTITY,
264            ApiError::Store(StoreError::Crypto(_)) => StatusCode::NOT_IMPLEMENTED,
265            ApiError::Store(StoreError::DuplicateArtifact { .. }) => StatusCode::CONFLICT,
266            ApiError::Store(StoreError::LeaseLost { .. }) => StatusCode::CONFLICT,
267            ApiError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
268            ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
269            ApiError::BadGateway(_) => StatusCode::BAD_GATEWAY,
270            ApiError::RegistryNotFound => StatusCode::NOT_FOUND,
271            ApiError::RegistryUnreachable => StatusCode::BAD_GATEWAY,
272            ApiError::InvalidInput(_) => StatusCode::UNPROCESSABLE_ENTITY,
273        }
274    }
275
276    /// Structured context attached to the JSON error body, if any.
277    ///
278    /// Never carries internal detail: only identifiers the caller is already
279    /// entitled to see.
280    fn details(&self) -> Option<Value> {
281        match self {
282            ApiError::IdempotencyKeyConflict(run_id) => Some(json!({ "run_id": run_id })),
283            ApiError::ConcurrencyConflict { key, run_id } => {
284                Some(json!({ "key": key, "run_id": run_id }))
285            }
286            ApiError::InvalidInput(errors) => Some(json!({ "errors": errors })),
287            _ => None,
288        }
289    }
290}
291
292impl IntoResponse for ApiError {
293    fn into_response(self) -> Response {
294        let status = self.status();
295        let code = self.code().to_string();
296        let details = self.details();
297
298        let message = match &self {
299            ApiError::Store(StoreError::Crypto(_)) => {
300                "secret store not configured (set IRONFLOW_SECRET_KEYS)".to_string()
301            }
302            // Carries the caller-facing detail in its own Display impl,
303            // unlike the generic "database error" of ApiError::Store.
304            ApiError::Store(e @ StoreError::LeaseLost { .. }) => e.to_string(),
305            _ => self.to_string(),
306        };
307
308        match &self {
309            // A lost lease is a client-side condition, not a server fault:
310            // it must not page anyone.
311            ApiError::Store(e @ StoreError::LeaseLost { .. }) => {
312                warn!(error = %e, code = %code, "lease refused")
313            }
314            ApiError::Store(e) => error!(error = %e, code = %code, "store error"),
315            ApiError::Internal(detail) => {
316                error!(detail = %detail, code = %code, "internal error")
317            }
318            _ => {}
319        }
320
321        let envelope = ErrorEnvelope {
322            code,
323            message,
324            details,
325        };
326
327        (status, Json(json!({ "error": envelope }))).into_response()
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn run_not_found_code() {
337        let err = ApiError::RunNotFound(Uuid::nil());
338        assert_eq!(err.code(), "RUN_NOT_FOUND");
339    }
340
341    #[test]
342    fn run_not_found_status() {
343        let err = ApiError::RunNotFound(Uuid::nil());
344        assert_eq!(err.status(), StatusCode::NOT_FOUND);
345    }
346
347    #[test]
348    fn bad_request_status() {
349        let err = ApiError::BadRequest("invalid field".to_string());
350        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
351        assert_eq!(err.code(), "BAD_REQUEST");
352    }
353
354    #[test]
355    fn conflict_status() {
356        let err = ApiError::Conflict("run is already waiting for a retry".to_string());
357        assert_eq!(err.status(), StatusCode::CONFLICT);
358        assert_eq!(err.code(), "CONFLICT");
359    }
360
361    #[test]
362    fn invalid_input_status_and_details() {
363        let err = ApiError::InvalidInput(vec!["\"answers\" is a required property".to_string()]);
364        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
365        assert_eq!(err.code(), "INVALID_INPUT");
366        assert_eq!(
367            err.details(),
368            Some(json!({ "errors": ["\"answers\" is a required property"] }))
369        );
370    }
371
372    #[test]
373    fn internal_error_status() {
374        let err = ApiError::Internal("something went wrong".to_string());
375        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
376        assert_eq!(err.code(), "INTERNAL_ERROR");
377    }
378
379    #[test]
380    fn error_to_response() {
381        let err = ApiError::BadRequest("invalid input".to_string());
382        let response = err.into_response();
383        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
384    }
385
386    #[test]
387    fn unauthorized_status() {
388        let err = ApiError::Unauthorized;
389        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
390        assert_eq!(err.code(), "UNAUTHORIZED");
391    }
392
393    #[test]
394    fn invalid_credentials_status() {
395        let err = ApiError::InvalidCredentials;
396        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
397        assert_eq!(err.code(), "INVALID_CREDENTIALS");
398    }
399
400    #[test]
401    fn duplicate_email_status() {
402        let err = ApiError::DuplicateEmail;
403        assert_eq!(err.status(), StatusCode::CONFLICT);
404        assert_eq!(err.code(), "DUPLICATE_EMAIL");
405    }
406
407    #[test]
408    fn duplicate_username_status() {
409        let err = ApiError::DuplicateUsername;
410        assert_eq!(err.status(), StatusCode::CONFLICT);
411        assert_eq!(err.code(), "DUPLICATE_USERNAME");
412    }
413
414    #[test]
415    fn weak_password_status_carries_the_rule() {
416        let err = ApiError::from(PasswordPolicyError::TooCommon);
417        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
418        assert_eq!(err.code(), "WEAK_PASSWORD");
419        assert_eq!(err.to_string(), PasswordPolicyError::TooCommon.to_string());
420    }
421
422    #[test]
423    fn workflow_not_found_status() {
424        let err = ApiError::WorkflowNotFound("test".to_string());
425        assert_eq!(err.status(), StatusCode::NOT_FOUND);
426        assert_eq!(err.code(), "WORKFLOW_NOT_FOUND");
427    }
428
429    #[test]
430    fn step_not_found_status() {
431        let err = ApiError::StepNotFound(Uuid::nil());
432        assert_eq!(err.status(), StatusCode::NOT_FOUND);
433        assert_eq!(err.code(), "STEP_NOT_FOUND");
434    }
435
436    #[test]
437    fn user_not_found_status() {
438        let err = ApiError::UserNotFound(Uuid::nil());
439        assert_eq!(err.status(), StatusCode::NOT_FOUND);
440        assert_eq!(err.code(), "USER_NOT_FOUND");
441    }
442
443    #[test]
444    fn forbidden_status() {
445        let err = ApiError::Forbidden;
446        assert_eq!(err.status(), StatusCode::FORBIDDEN);
447        assert_eq!(err.code(), "FORBIDDEN");
448    }
449
450    #[test]
451    fn secret_not_found_status() {
452        let err = ApiError::SecretNotFound("demo/api-key".to_string());
453        assert_eq!(err.status(), StatusCode::NOT_FOUND);
454        assert_eq!(err.code(), "SECRET_NOT_FOUND");
455    }
456
457    #[test]
458    fn delegation_not_found_status_and_code() {
459        let err = ApiError::DelegationNotFound(Uuid::nil());
460        assert_eq!(err.status(), StatusCode::NOT_FOUND);
461        assert_eq!(err.code(), "DELEGATION_NOT_FOUND");
462    }
463
464    #[test]
465    fn provider_account_errors_status_and_code() {
466        let err = ApiError::ProviderAccountNotFound("perso".to_string());
467        assert_eq!(err.status(), StatusCode::NOT_FOUND);
468        assert_eq!(err.code(), "PROVIDER_ACCOUNT_NOT_FOUND");
469
470        let err = ApiError::AccountCredentialRejected("token rejected".to_string());
471        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
472        assert_eq!(err.code(), "ACCOUNT_CREDENTIAL_REJECTED");
473        assert_eq!(err.to_string(), "token rejected");
474    }
475
476    #[test]
477    fn provider_account_store_errors_map_to_http() {
478        let id = Uuid::now_v7();
479        let err = ApiError::from(StoreError::ProviderAccountNotFound(id));
480        assert_eq!(err.status(), StatusCode::NOT_FOUND);
481        assert!(err.to_string().contains(&id.to_string()));
482
483        let err = ApiError::from(StoreError::DuplicateProviderAccount("perso".to_string()));
484        assert_eq!(err.status(), StatusCode::CONFLICT);
485        assert!(err.to_string().contains("perso"));
486    }
487
488    #[test]
489    fn concurrency_conflict_status_code_and_details() {
490        let run_id = Uuid::now_v7();
491        let err = ApiError::from(StoreError::ConcurrencyConflict {
492            key: "issue:12".to_string(),
493            run_id,
494        });
495        assert_eq!(err.status(), StatusCode::CONFLICT);
496        assert_eq!(err.code(), "CONCURRENCY_CONFLICT");
497        assert_eq!(
498            err.details(),
499            Some(json!({ "key": "issue:12", "run_id": run_id }))
500        );
501        assert!(err.to_string().contains(&run_id.to_string()));
502    }
503
504    #[test]
505    fn monthly_budget_exceeded_status_and_code() {
506        let err = ApiError::MonthlyBudgetExceeded("quota exhausted".to_string());
507        assert_eq!(err.status(), StatusCode::TOO_MANY_REQUESTS);
508        assert_eq!(err.code(), "MONTHLY_BUDGET_EXCEEDED");
509        assert_eq!(err.to_string(), "quota exhausted");
510    }
511}