darkwing/server/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Error handling for the server module.
//!
//! This module provides a centralized error handling system for the
//! application, including custom error types, error mapping, and HTTP response
//! generation.

use std::borrow::Cow;
use std::{collections::HashMap, fmt::Debug};

use axum::extract::rejection::JsonRejection;
use axum::response::Response;
use axum::{http::StatusCode, response::IntoResponse, Json};
use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;
use tracing::log::error;
use validator::{ValidationErrors, ValidationErrorsKind};

/// Represents an API error response with a map of error messages.
///
/// The error structure contains a mapping of error keys to arrays of error
/// messages, allowing for multiple validation errors to be returned for
/// different fields.
#[derive(Debug, Deserialize, Serialize)]
pub struct ApiError {
  /// Map of error keys to arrays of error messages
  pub errors: HashMap<String, Vec<String>>,
}

impl ApiError {
  /// Creates a new `ApiError` with a single error message.
  ///
  /// # Arguments
  /// * `error` - The error message to include
  pub fn new(error: String) -> Self {
    let mut error_map: HashMap<String, Vec<String>> = HashMap::new();
    error_map.insert("error".to_owned(), vec![error]);
    Self { errors: error_map }
  }

  /// Creates an `ApiError` from a map of error messages.
  ///
  /// Ensures there's always an "error" field containing the first error message
  /// from the map for consistency.
  ///
  /// # Arguments
  /// * `errors` - HashMap containing field-specific error messages
  pub fn from_map(errors: HashMap<String, Vec<String>>) -> Self {
    let mut error_map = errors;
    // Ensure there's always an "error" field with the first error message
    if !error_map.contains_key("error") {
      if let Some((_key, messages)) = error_map.iter().next() {
        if let Some(first_message) = messages.first() {
          error_map.insert("error".to_owned(), vec![first_message.clone()]);
        }
      }
    }
    Self { errors: error_map }
  }
}

/// Type alias for Results that use our custom Error type
pub type AppResult<T> = Result<T, Error>;

/// Type alias for a map of error messages using static string references
pub type ErrorMap = HashMap<Cow<'static, str>, Vec<Cow<'static, str>>>;

/// The main error enum for the application.
///
/// This enum covers all possible error cases that can occur in the application,
/// from authentication failures to database errors and file processing issues.
#[derive(Error, Debug)]
pub enum Error {
  /// Authentication is required but not provided
  #[error("authentication is required to access this resource")]
  Unauthorized,
  /// Payment is required to access the resource
  #[error("payment is required to access this resource")]
  PaymentRequired,
  /// User lacks necessary permissions
  #[error("user does not have privilege to access this resource")]
  Forbidden,
  /// User's plan doesn't allow access
  #[error("plan does not allow to access this resource")]
  PlanDoesNotAllowAccess,
  /// Resource not found
  #[error("{0}")]
  NotFound(
    /// Description of what resource was not found
    String,
  ),
  /// Application startup error
  #[error("{0}")]
  ApplicationStartup(
    /// Description of what went wrong during startup
    String,
  ),
  /// Bad request error with context
  #[error("{0}")]
  BadRequest(
    /// Description of why the request was invalid
    String,
  ),
  /// Generic internal server error
  #[error("unexpected error has occurred")]
  InternalServerError,
  /// Internal server error with context
  #[error("{0}")]
  InternalServerErrorWithContext(
    /// Description of what went wrong internally
    String,
  ),
  /// Object conflict error
  #[error("{0}")]
  ObjectConflict(
    /// Description of the conflicting object state
    String,
  ),
  /// Unprocessable entity with validation errors
  #[error("unprocessable request has occurred")]
  UnprocessableEntity {
    /// Map of field names to validation error messages
    errors: ErrorMap,
  },
  /// Validation error from the validator crate
  #[error(transparent)]
  Validation(
    /// The underlying validation errors
    #[from]
    ValidationErrors,
  ),
  /// JSON parsing rejection from Axum
  #[error(transparent)]
  AxumJsonRejection(
    /// The underlying Axum JSON rejection error
    #[from]
    JsonRejection,
  ),
  /// Generic error type for wrapping any error
  #[error(transparent)]
  AnyhowError(
    /// The underlying error being wrapped
    #[from]
    anyhow::Error,
  ),
  /// Error while encrypting config
  #[error("error while encrypting config")]
  AesGcmError,
  /// Error while forming config
  #[error("{0}")]
  ConfigForming(
    /// Description of what went wrong during config formation
    String,
  ),
  /// Error while parsing database values to Rust types
  #[error("{0}")]
  DatabaseParsing(
    /// Description of what went wrong during database parsing
    String,
  ),
  /// Standard IO error
  #[error(transparent)]
  StdIO(
    /// The underlying IO error
    #[from]
    std::io::Error,
  ),
  /// Zip error
  #[error(transparent)]
  Zip(
    /// The underlying zip error
    #[from]
    zip::result::ZipError,
  ),
  /// Rusqlite error
  #[error(transparent)]
  Rusqlite(
    /// The underlying SQLite error
    #[from]
    rusqlite::Error,
  ),
  /// SqlxSqlite error
  #[cfg(test)]
  #[error(transparent)]
  SqlxSqlite(
    /// The underlying SQLx SQLite error
    #[from]
    sqlx::sqlite::SqliteError,
  ),
  /// S3 error
  #[error(transparent)]
  S3(
    /// The underlying S3 error
    #[from]
    aws_sdk_s3::Error,
  ),
  /// S3 client error
  #[error(transparent)]
  S3Client(
    /// The underlying S3 client error
    #[from]
    aws_sdk_s3::error::SdkError<
      aws_sdk_s3::operation::get_object::GetObjectError,
    >,
  ),
  /// S3 GetObjectError
  #[error("S3 GetObjectError")]
  S3GetObject(
    /// The underlying S3 GetObject error
    #[from]
    aws_sdk_s3::operation::get_object::GetObjectError,
  ),
  /// Base file hash does not match
  #[error("base file hash does not match")]
  BaseFileHashMismatch,
  /// Resulting file hash does not match
  #[error("resulting file hash does not match")]
  ResultingFileHashMismatch,
  /// Diff error
  #[error("diff error: {0}")]
  Diff(
    /// Description of what went wrong during diffing
    String,
  ),
  /// SerdeJson error
  #[error(transparent)]
  SerdeJson(
    /// The underlying Serde JSON error
    #[from]
    serde_json::Error,
  ),
  /// No previous datadir, send full zip
  #[error("no previous datadir, send full zip")]
  NoPreviousDatadir,
  /// Unknown mode
  #[error("unknown mode: {0}")]
  UnknownMode(
    /// The invalid mode that was provided
    String,
  ),
  /// Time format description error
  #[error(transparent)]
  TimeFormatDescription(
    /// The underlying time format description error
    #[from]
    time::error::InvalidFormatDescription,
  ),
  /// Time format error
  #[error(transparent)]
  TimeFormat(
    /// The underlying time format error
    #[from]
    time::error::Format,
  ),
  /// Unknown override mode
  #[error("unknown override mode: {0}")]
  UnknownOverrideMode(
    /// The invalid override mode that was provided
    String,
  ),
  /// Error while decoding field from database
  #[error("Error while decoding {0} field from database: {1}")]
  DatabaseDecoding(
    /// The name of the field that failed to decode
    String,
    /// Description of what went wrong during decoding
    String,
  ),
}

impl From<darkwing_diff::Error> for Error {
  fn from(value: darkwing_diff::Error) -> Self {
    Self::Diff(format!("{:?}", value))
  }
}

impl Error {
  /// Maps `validator`'s `ValidationErrors` to a simple map of property
  /// name/error messages structure.
  pub fn unprocessable_entity(errors: ValidationErrors) -> Response {
    let mut validation_errors = ErrorMap::new();

    // roll through the struct errors at the top level
    for (field_property, error_kind) in errors.into_errors() {
      if let ValidationErrorsKind::Field(field_meta) = error_kind.clone() {
        for error in field_meta.into_iter() {
          validation_errors
            .entry(Cow::from(field_property))
            .or_default()
            .push(error.message.unwrap_or_else(|| {
              // required validators contain None for their message, assume a
              // default response
              let params: Vec<Cow<'static, str>> = error
                .params
                .iter()
                .filter(|(key, _value)| *key.to_owned() != *"value")
                .map(|(key, value)| {
                  Cow::from(format!("{} value is {}", key, value))
                })
                .collect();

              if !params.is_empty() {
                Cow::from(params.join(", "))
              } else {
                Cow::from(format!("{} is required", field_property))
              }
            }));
        }
      }
      // structs may contain validators on themselves, roll through first-depth
      // validators
      if let ValidationErrorsKind::Struct(meta) = error_kind.clone() {
        // on structs with validation errors, roll through each of the structs
        // properties to build a list of errors
        for (struct_property, struct_error_kind) in meta.into_errors() {
          if let ValidationErrorsKind::Field(field_meta) = struct_error_kind {
            for error in field_meta.into_iter() {
              validation_errors
                .entry(Cow::from(struct_property))
                .or_default()
                .push(error.message.unwrap_or_else(|| {
                  // required validators contain None for their message, assume
                  // a default response
                  Cow::from(format!("{} is required", struct_property))
                }));
            }
          }
        }
      }
    }

    let mut errors_map: HashMap<String, Vec<String>> = validation_errors
      .into_iter()
      .map(|(k, v)| {
        (
          k.into_owned(),
          v.into_iter().map(|cow| cow.into_owned()).collect(),
        )
      })
      .collect();

    // Ensure there's an error field with the first error message
    if let Some((_key, messages)) = errors_map.iter().next() {
      if let Some(first_message) = messages.first() {
        errors_map.insert("error".to_string(), vec![first_message.clone()]);
      }
    }

    let body = Json(json!({
        "errors": errors_map,
    }));

    (StatusCode::BAD_REQUEST, body).into_response()
  }
}

impl IntoResponse for Error {
  fn into_response(self) -> Response {
    if let Self::Validation(e) = self {
      return Self::unprocessable_entity(e);
    }

    let (status, error_message) = match self {
      Self::InternalServerErrorWithContext(ref err) => {
        (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
      }
      Self::NotFound(ref err) => (StatusCode::NOT_FOUND, err.to_string()),
      Self::PaymentRequired => (
        StatusCode::PAYMENT_REQUIRED,
        Self::PaymentRequired.to_string(),
      ),
      Self::ObjectConflict(ref err) => (StatusCode::CONFLICT, err.to_string()),
      Self::Unauthorized => {
        (StatusCode::UNAUTHORIZED, Self::Unauthorized.to_string())
      }
      Self::Forbidden => (StatusCode::FORBIDDEN, Self::Forbidden.to_string()),
      Self::AxumJsonRejection(ref err) => {
        (StatusCode::BAD_REQUEST, err.body_text())
      }
      Self::NoPreviousDatadir => (
        StatusCode::FAILED_DEPENDENCY,
        Self::NoPreviousDatadir.to_string(),
      ),
      _ => (
        StatusCode::INTERNAL_SERVER_ERROR,
        String::from("unexpected error occurred"),
      ),
    };

    if status != StatusCode::UNAUTHORIZED {
      sentry::capture_error(&self);
    }

    let body = Json(ApiError::new(error_message));

    (status, body).into_response()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use axum::http::StatusCode;
  use serde_json::Value;
  use validator::Validate;

  #[derive(Debug, Validate)]
  struct TestStruct {
    #[validate(length(min = 3))]
    name: String,
    #[validate(range(min = 18))]
    age: i32,
  }

  #[test]
  fn test_api_error_new() {
    let error = ApiError::new("test error".to_string());
    assert!(error.errors.contains_key("error"));
    assert_eq!(error.errors["error"], vec!["test error"]);
  }

  #[test]
  fn test_api_error_from_map() {
    let mut errors = HashMap::new();
    errors.insert("name".to_string(), vec!["name is invalid".to_string()]);
    errors.insert("age".to_string(), vec!["age is too low".to_string()]);

    let api_error = ApiError::from_map(errors);

    // Check if error field exists and contains the first error
    assert!(api_error.errors.contains_key("error"));
    assert!(api_error.errors.contains_key("name"));
    assert!(api_error.errors.contains_key("age"));

    // The error field should contain the first error message
    assert_eq!(api_error.errors["error"].len(), 1);
  }

  #[tokio::test]
  async fn test_validation_error_response() {
    let test_struct = TestStruct {
      name: "a".to_string(),
      age: 15,
    };

    let validation_result = test_struct.validate();
    assert!(validation_result.is_err());

    let validation_errors = validation_result
      .err()
      .expect("Should have validation errors");
    let response = Error::unprocessable_entity(validation_errors);

    let response_status = response.status();
    assert_eq!(response_status, StatusCode::BAD_REQUEST);

    // Extract the body and verify it contains the expected error structure
    if let Ok(body) = String::from_utf8(
      axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("cannot parse body")
        .to_vec(),
    ) {
      let json: Value =
        serde_json::from_str(&body).expect("Should be valid JSON");

      let errors = json.get("errors").expect("Should have errors object");
      assert!(errors.is_object());

      let errors_obj = errors.as_object().unwrap();
      assert!(errors_obj.contains_key("error"));
      assert!(errors_obj.contains_key("name"));
      assert!(errors_obj.contains_key("age"));
    }
  }

  #[test]
  fn test_error_into_response() {
    // Test NotFound error
    let not_found = Error::NotFound("Resource not found".to_string());
    let response = not_found.into_response();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);

    // Test Unauthorized error
    let unauthorized = Error::Unauthorized;
    let response = unauthorized.into_response();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // Test InternalServerError
    let internal_error = Error::InternalServerError;
    let response = internal_error.into_response();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
  }

  #[test]
  fn test_error_messages() {
    let error = Error::NotFound("test resource not found".to_string());
    assert_eq!(error.to_string(), "test resource not found");

    let error = Error::Unauthorized;
    assert_eq!(
      error.to_string(),
      "authentication is required to access this resource"
    );

    let error = Error::Forbidden;
    assert_eq!(
      error.to_string(),
      "user does not have privilege to access this resource"
    );
  }
}