From 17508aadb59ff7b6922e29e42c502abf9396f1a2 Mon Sep 17 00:00:00 2001 From: Christian Grothoff Date: Tue, 29 Sep 2026 13:48:22 +0200 Subject: [PATCH 1/9] api: accept error codes from other GANA registries ApiError only took Taler's 16-bit ErrorCode, so a component with its own registry (Beekeeper uses 100000 to 110000) could not report its errors through it. --- common/taler-api/src/error.rs | 161 ++++++++++++++++++++++++++++++---- 1 file changed, 143 insertions(+), 18 deletions(-) diff --git a/common/taler-api/src/error.rs b/common/taler-api/src/error.rs index 02f1fe6..a6e5897 100644 --- a/common/taler-api/src/error.rs +++ b/common/taler-api/src/error.rs @@ -22,17 +22,114 @@ use axum::{ http::{HeaderMap, HeaderValue, StatusCode, header::IntoHeaderName}, response::{IntoResponse, Response}, }; -use taler_common::{ - api::{ErrorDetail, params::ParamsErr}, - error_code::ErrorCode, - types::payto::PaytoErr, -}; +use serde::Serialize; +use taler_common::{api::params::ParamsErr, error_code::ErrorCode, types::payto::PaytoErr}; pub type ApiResult = Result; +/// An error code with the HTTP status it is returned with. Codes come from +/// the GNU Taler registry ([`ErrorCode`]) or from another GANA registry, such +/// as a component's own, whose values are above the Taler range (0 to 9999) +/// and so may not fit in 16 bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Code { + value: u32, + status: u16, + source: Source, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Source { + Taler(ErrorCode), + Other { + name: &'static str, + description: &'static str, + }, +} + +impl Code { + /// A code from another registry. + pub const fn new( + value: u32, + status: u16, + name: &'static str, + description: &'static str, + ) -> Self { + Self { + value, + status, + source: Source::Other { name, description }, + } + } + + pub fn value(&self) -> u32 { + self.value + } + + pub fn status(&self) -> u16 { + self.status + } + + pub fn name(&self) -> &str { + match &self.source { + Source::Taler(code) => code.as_ref(), + Source::Other { name, .. } => name, + } + } + + pub fn description(&self) -> &'static str { + match self.source { + Source::Taler(code) => code.description(), + Source::Other { description, .. } => description, + } + } + + /// The Taler error code, if it is one. + pub fn taler(&self) -> Option { + match self.source { + Source::Taler(code) => Some(code), + Source::Other { .. } => None, + } + } +} + +impl From for Code { + fn from(code: ErrorCode) -> Self { + Self { + value: code as u32, + status: code.status_code(), + source: Source::Taler(code), + } + } +} + +impl Display for Code { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.name()) + } +} + +/// The body of an error response: `ErrorDetail`, with room for codes of more +/// than 16 bits. +#[derive(Serialize)] +struct ErrorBody { + code: u32, + hint: Option>, + detail: Option>, + parameter: Option>, + path: Option>, + offset: Option>, + index: Option>, + object: Option>, + currency: Option>, + type_expected: Option>, + type_actual: Option>, + extra: Option>, +} + #[derive(Debug, thiserror::Error)] pub struct ApiError { - code: ErrorCode, + code: Code, hint: Option>, log: Option>, status: Option, @@ -51,9 +148,9 @@ impl Display for ApiError { } impl ApiError { - pub fn new(code: ErrorCode) -> Self { + pub fn new(code: impl Into) -> Self { Self { - code, + code: code.into(), hint: None, log: None, status: None, @@ -112,7 +209,7 @@ impl From for ApiError { _ => (ErrorCode::GENERIC_DB_FETCH_FAILED, StatusCode::BAD_GATEWAY), }; Self { - code, + code: code.into(), hint: None, status: Some(status), log: Some(format!("{value}").into_boxed_str()), @@ -189,15 +286,14 @@ impl IntoResponse for ApiError { path, headers, } = self; - let status_code = status.unwrap_or_else(|| { - StatusCode::from_u16(code.status_code()).expect("Invalid status code") - }); + let status_code = status + .unwrap_or_else(|| StatusCode::from_u16(code.status()).expect("Invalid status code")); let log = log.or(hint.clone()); let mut resp = ( status_code, - Json(ErrorDetail { - code: code as u16, + Json(ErrorBody { + code: code.value(), hint, detail: None, parameter: None, @@ -226,19 +322,19 @@ impl IntoResponse for ApiError { #[derive(Debug, Clone)] pub struct LoggedError { - pub code: ErrorCode, + pub code: Code, pub info: Option>, } -pub fn failure_code(code: ErrorCode) -> ApiError { +pub fn failure_code(code: impl Into) -> ApiError { ApiError::new(code) } -pub fn failure(code: ErrorCode, hint: impl Display) -> ApiError { +pub fn failure(code: impl Into, hint: impl Display) -> ApiError { ApiError::new(code).with_hint(hint) } -pub fn failure_status(code: ErrorCode, hint: impl Display, status: StatusCode) -> ApiError { +pub fn failure_status(code: impl Into, hint: impl Display, status: StatusCode) -> ApiError { ApiError::new(code).with_hint(hint).with_status(status) } @@ -257,3 +353,32 @@ pub fn forbidden(hint: impl Display) -> ApiError { pub fn bad_request(hint: impl Display) -> ApiError { ApiError::new(ErrorCode::GENERIC_JSON_INVALID).with_hint(hint) } + +#[cfg(test)] +mod tests { + use http_body_util::BodyExt as _; + + use super::*; + + async fn body(err: ApiError) -> (StatusCode, serde_json::Value) { + let resp = err.into_response(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + (status, serde_json::from_slice(&bytes).unwrap()) + } + + #[tokio::test] + async fn codes_from_other_registries() { + const OWN: Code = Code::new(100_000, 429, "OWN_RATE_LIMITED", "Too many requests."); + let (status, json) = body(failure(OWN, "slow down")).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(json["code"], 100_000); + assert_eq!(json["hint"], "slow down"); + + let (status, json) = body(failure_code(ErrorCode::GENERIC_JSON_INVALID)).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(json["code"], ErrorCode::GENERIC_JSON_INVALID as u16); + // Same shape as ErrorDetail: absent fields are null. + assert!(json["detail"].is_null() && json.get("detail").is_some()); + } +} -- 2.47.3