taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

error.rs (11419B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2024, 2025, 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use std::fmt::Display;
     18 
     19 use axum::{
     20     Json,
     21     extract::{path::ErrorKind, rejection::PathRejection},
     22     http::{HeaderMap, HeaderValue, StatusCode, header::IntoHeaderName},
     23     response::{IntoResponse, Response},
     24 };
     25 use serde_json::value::RawValue;
     26 use serde_path_to_error::Error as DeserializeError;
     27 use taler_common::{
     28     api::{ErrorDetail, params::ParamsErr},
     29     error_code::ErrorCode,
     30     types::payto::PaytoErr,
     31 };
     32 use tracing::debug;
     33 
     34 pub type ApiResult<T> = Result<T, ApiError>;
     35 
     36 /// Metadata supplied by an error code from a GANA registry
     37 pub trait GanaErrorCode {
     38     fn value(&self) -> u32;
     39     fn name(&self) -> &'static str;
     40     fn description(&self) -> &'static str;
     41     fn status_code(&self) -> u16;
     42 }
     43 
     44 impl GanaErrorCode for ErrorCode {
     45     fn value(&self) -> u32 {
     46         *self as u32
     47     }
     48 
     49     fn name(&self) -> &'static str {
     50         self.as_str()
     51     }
     52 
     53     fn description(&self) -> &'static str {
     54         ErrorCode::description(self)
     55     }
     56 
     57     fn status_code(&self) -> u16 {
     58         self.status_code()
     59     }
     60 }
     61 
     62 /// A numeric GANA error code with its symbolic name and description
     63 #[derive(Debug)]
     64 struct Code {
     65     value: u32,
     66     name: &'static str,
     67     description: &'static str,
     68 }
     69 
     70 #[derive(Debug, thiserror::Error)]
     71 #[error("{}", .hint.as_deref().unwrap_or(.code.description))]
     72 pub struct ApiError {
     73     code: Code,
     74     hint: Option<Box<str>>,
     75     log: Option<Box<str>>,
     76     status: Option<StatusCode>,
     77     path: Option<Box<str>>,
     78     headers: Option<Box<HeaderMap>>,
     79     extra: Option<Box<RawValue>>,
     80 }
     81 
     82 impl ApiError {
     83     pub fn new(code: impl GanaErrorCode) -> Self {
     84         Self {
     85             code: Code {
     86                 value: code.value(),
     87                 name: code.name(),
     88                 description: code.description(),
     89             },
     90             hint: None,
     91             log: None,
     92             status: StatusCode::from_u16(code.status_code()).ok(),
     93             path: None,
     94             headers: None,
     95             extra: None,
     96         }
     97     }
     98 
     99     pub fn with_hint(self, hint: impl Display) -> Self {
    100         Self {
    101             hint: Some(hint.to_string().into_boxed_str()),
    102             ..self
    103         }
    104     }
    105 
    106     pub fn with_log(self, log: impl Into<Box<str>>) -> Self {
    107         Self {
    108             log: Some(log.into()),
    109             ..self
    110         }
    111     }
    112 
    113     pub fn with_status(self, status: StatusCode) -> Self {
    114         Self {
    115             status: Some(status),
    116             ..self
    117         }
    118     }
    119 
    120     pub fn with_path(self, path: impl Display) -> Self {
    121         Self {
    122             path: Some(path.to_string().into_boxed_str()),
    123             ..self
    124         }
    125     }
    126 
    127     /// Include a JSON value in the error response's `extra` field.
    128     pub fn with_extra(self, extra: Box<RawValue>) -> Self {
    129         Self {
    130             extra: Some(extra),
    131             ..self
    132         }
    133     }
    134 
    135     pub fn with_header(mut self, key: impl IntoHeaderName, value: HeaderValue) -> Self {
    136         let headers = self.headers.get_or_insert_default();
    137         headers.append(key, value);
    138         self
    139     }
    140 }
    141 
    142 impl From<sqlx::Error> for ApiError {
    143     fn from(value: sqlx::Error) -> Self {
    144         let (code, status) = match value {
    145             sqlx::Error::Configuration(_) => {
    146                 (ErrorCode::GENERIC_DB_SETUP_FAILED, StatusCode::BAD_GATEWAY)
    147             }
    148             sqlx::Error::Database(_)
    149             | sqlx::Error::Io(_)
    150             | sqlx::Error::Tls(_)
    151             | sqlx::Error::PoolTimedOut => {
    152                 (ErrorCode::GENERIC_DB_FETCH_FAILED, StatusCode::BAD_GATEWAY)
    153             }
    154             _ => (ErrorCode::GENERIC_DB_FETCH_FAILED, StatusCode::BAD_GATEWAY),
    155         };
    156         Self::new(code)
    157             .with_status(status)
    158             .with_log(value.to_string())
    159     }
    160 }
    161 
    162 impl From<PaytoErr> for ApiError {
    163     fn from(value: PaytoErr) -> Self {
    164         failure(ErrorCode::GENERIC_PAYTO_URI_MALFORMED, value)
    165     }
    166 }
    167 
    168 impl From<ParamsErr> for ApiError {
    169     fn from(value: ParamsErr) -> Self {
    170         failure(ErrorCode::GENERIC_PARAMETER_MALFORMED, &value).with_path(value.param)
    171     }
    172 }
    173 
    174 // Serde data errors can contain arbitrary input, including in custom messages.
    175 // Only return fixed labels, never a substring of the message.
    176 fn serde_error_kind(message: &str) -> &'static str {
    177     [
    178         "invalid type",
    179         "invalid value",
    180         "invalid length",
    181         "unknown variant",
    182         "unknown field",
    183         "missing field",
    184         "duplicate field",
    185         "invalid digit",
    186     ]
    187     .into_iter()
    188     .find(|kind| message.starts_with(kind))
    189     .unwrap_or("invalid data")
    190 }
    191 
    192 /// Describe a JSON deserialization error for logging without quoting the input.
    193 fn json_error_kind(error: &serde_json::Error) -> &'static str {
    194     use serde_json::error::Category;
    195 
    196     match error.classify() {
    197         Category::Io => "I/O error",
    198         Category::Syntax => "syntax error",
    199         Category::Eof => "unexpected end of input",
    200         Category::Data => serde_error_kind(&error.to_string()),
    201     }
    202 }
    203 
    204 /// Describe a path deserialization error for logging without quoting the input.
    205 fn path_error_kind(error: &ErrorKind) -> String {
    206     match error {
    207         ErrorKind::ParseError { expected_type, .. } => format!("expected {expected_type}"),
    208         ErrorKind::ParseErrorAtIndex {
    209             index,
    210             expected_type,
    211             ..
    212         } => format!("{index}: expected {expected_type}"),
    213         ErrorKind::ParseErrorAtKey {
    214             key, expected_type, ..
    215         } => format!("{key}: expected {expected_type}"),
    216         ErrorKind::InvalidUtf8InPathParam { key } => format!("{key}: invalid UTF-8"),
    217         ErrorKind::DeserializeError { key, message, .. } => {
    218             format!("{key}: {}", serde_error_kind(message))
    219         }
    220         ErrorKind::Message(message) => serde_error_kind(message).into(),
    221         ErrorKind::WrongNumberOfParameters { got, expected } => {
    222             format!("expected {expected} path parameters, got {got}")
    223         }
    224         ErrorKind::UnsupportedType { name } => format!("unsupported type {name}"),
    225         _ => "invalid data".into(),
    226     }
    227 }
    228 
    229 fn deserialization_failure(
    230     code: ErrorCode,
    231     hint: impl Display,
    232     path: &serde_path_to_error::Path,
    233     kind: &'static str,
    234 ) -> ApiError {
    235     failure(code, hint)
    236         .with_path(path)
    237         .with_log(format!("{path}: {kind}"))
    238 }
    239 
    240 impl From<DeserializeError<serde_urlencoded::de::Error>> for ApiError {
    241     fn from(error: DeserializeError<serde_urlencoded::de::Error>) -> Self {
    242         let hint = error.inner().to_string();
    243         let kind = serde_error_kind(&hint);
    244         let code = if kind == "missing field" {
    245             ErrorCode::GENERIC_PARAMETER_MISSING
    246         } else {
    247             ErrorCode::GENERIC_PARAMETER_MALFORMED
    248         };
    249         deserialization_failure(code, hint, error.path(), kind)
    250     }
    251 }
    252 
    253 impl From<DeserializeError<serde_json::Error>> for ApiError {
    254     fn from(error: DeserializeError<serde_json::Error>) -> Self {
    255         let source = error.inner();
    256         deserialization_failure(
    257             ErrorCode::GENERIC_JSON_INVALID,
    258             source,
    259             error.path(),
    260             json_error_kind(source),
    261         )
    262     }
    263 }
    264 
    265 impl From<serde_json::Error> for ApiError {
    266     fn from(value: serde_json::Error) -> Self {
    267         failure(ErrorCode::GENERIC_JSON_INVALID, &value).with_log(json_error_kind(&value))
    268     }
    269 }
    270 
    271 impl From<PathRejection> for ApiError {
    272     fn from(value: PathRejection) -> Self {
    273         match value {
    274             PathRejection::FailedToDeserializePathParams(err) => {
    275                 let kind = err.into_kind();
    276                 let err = failure(ErrorCode::GENERIC_PATH_SEGMENT_MALFORMED, &kind)
    277                     .with_log(path_error_kind(&kind));
    278                 match kind {
    279                     ErrorKind::ParseErrorAtKey { key, .. }
    280                     | ErrorKind::InvalidUtf8InPathParam { key }
    281                     | ErrorKind::DeserializeError { key, .. } => err.with_path(key),
    282                     ErrorKind::ParseErrorAtIndex { index, .. } => err.with_path(index),
    283                     _ => err,
    284                 }
    285             }
    286             PathRejection::MissingPathParams(err) => {
    287                 failure(ErrorCode::BANK_UNMANAGED_EXCEPTION, err)
    288             }
    289             _ => failure(ErrorCode::BANK_UNMANAGED_EXCEPTION, value),
    290         }
    291     }
    292 }
    293 
    294 impl IntoResponse for ApiError {
    295     fn into_response(self) -> Response {
    296         let ApiError {
    297             code,
    298             hint,
    299             log,
    300             status,
    301             path,
    302             headers,
    303             extra,
    304         } = self;
    305         let log = if let Some(log) = log {
    306             // Hint contains sensitive data that is skipped in logs, reveal full hint if debugging
    307             if let Some(hint) = &hint {
    308                 debug!(target: "api", "{} {hint}", code.name);
    309             }
    310             Some(log)
    311         } else {
    312             hint.clone()
    313         };
    314 
    315         let mut resp = (
    316             status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
    317             Json(ErrorDetail {
    318                 code: code.value,
    319                 hint,
    320                 detail: None,
    321                 parameter: None,
    322                 path,
    323                 offset: None,
    324                 index: None,
    325                 object: None,
    326                 currency: None,
    327                 type_expected: None,
    328                 type_actual: None,
    329                 extra,
    330             }),
    331         )
    332             .into_response();
    333         if let Some(headers) = headers {
    334             for (k, v) in *headers {
    335                 resp.headers_mut().append(k.unwrap(), v);
    336             }
    337         }
    338         resp.extensions_mut().insert(LoggedError {
    339             code: code.name,
    340             info: log,
    341         });
    342 
    343         resp
    344     }
    345 }
    346 
    347 #[derive(Debug, Clone)]
    348 pub struct LoggedError {
    349     pub code: &'static str,
    350     pub info: Option<Box<str>>,
    351 }
    352 
    353 pub fn failure_code(code: impl GanaErrorCode) -> ApiError {
    354     ApiError::new(code)
    355 }
    356 
    357 pub fn failure(code: impl GanaErrorCode, hint: impl Display) -> ApiError {
    358     ApiError::new(code).with_hint(hint)
    359 }
    360 
    361 pub fn failure_status(
    362     code: impl GanaErrorCode,
    363     hint: impl Display,
    364     status: StatusCode,
    365 ) -> ApiError {
    366     ApiError::new(code).with_hint(hint).with_status(status)
    367 }
    368 
    369 pub fn not_implemented() -> ApiError {
    370     ApiError::new(ErrorCode::END).with_status(StatusCode::NOT_IMPLEMENTED)
    371 }
    372 
    373 pub fn unauthorized(hint: impl Display) -> ApiError {
    374     ApiError::new(ErrorCode::GENERIC_UNAUTHORIZED).with_hint(hint)
    375 }
    376 
    377 pub fn forbidden(hint: impl Display) -> ApiError {
    378     ApiError::new(ErrorCode::GENERIC_FORBIDDEN).with_hint(hint)
    379 }
    380 
    381 pub fn bad_request(hint: impl Display) -> ApiError {
    382     ApiError::new(ErrorCode::GENERIC_JSON_INVALID).with_hint(hint)
    383 }