taler-rust

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

api.rs (9684B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 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::{
     18     sync::{
     19         Arc,
     20         atomic::{AtomicU32, Ordering},
     21     },
     22     time::Instant,
     23 };
     24 
     25 use axum::{
     26     extract::{MatchedPath, OriginalUri, Request, State},
     27     http::{HeaderValue, Method, header},
     28     middleware::{self, Next},
     29     response::{IntoResponse as _, Response},
     30 };
     31 use compact_str::CompactString;
     32 use rand::RngExt as _;
     33 use revenue::Revenue;
     34 use taler_common::{
     35     error_code::ErrorCode,
     36     log::LOG_TASK_ID,
     37     types::amount::{Amount, Currency},
     38 };
     39 use tokio::signal;
     40 use tracing::{Level, debug, info};
     41 use wire::WireGateway;
     42 
     43 use crate::{
     44     Listener, Serve,
     45     api::{observability::Observability, prepared::PreparedTransfer},
     46     auth::{AuthMethod, AuthMiddlewareState},
     47     config::WireGatewayCfg,
     48     error::{ApiResult, LoggedError, failure, failure_code},
     49 };
     50 
     51 pub mod observability;
     52 pub mod prepared;
     53 pub mod revenue;
     54 mod serve;
     55 pub mod wire;
     56 
     57 pub use axum::Router;
     58 
     59 pub trait Validation {
     60     fn check(&self, currency: &Currency) -> ApiResult<()>;
     61 }
     62 
     63 fn check_currency(currency: &Currency, amount: &Amount) -> ApiResult<()> {
     64     if &amount.currency != currency {
     65         Err(failure(
     66             ErrorCode::GENERIC_CURRENCY_MISMATCH,
     67             format!(
     68                 "wrong currency expected {} got {}",
     69                 currency, amount.currency
     70             ),
     71         ))
     72     } else {
     73         Ok(())
     74     }
     75 }
     76 
     77 pub trait TalerApi: Send + Sync + 'static {
     78     fn currency(&self) -> Currency;
     79     fn implementation(&self) -> &'static str;
     80 }
     81 
     82 pub trait RouterUtils {
     83     fn auth(self, auth: AuthMethod, realm: &str) -> Self;
     84 }
     85 
     86 impl<S: Send + Clone + Sync + 'static> RouterUtils for Router<S> {
     87     fn auth(self, auth: AuthMethod, realm: &str) -> Self {
     88         self.route_layer(middleware::from_fn_with_state(
     89             Arc::new(AuthMiddlewareState::new(auth, realm)),
     90             crate::auth::auth_middleware,
     91         ))
     92     }
     93 }
     94 
     95 pub trait TalerRouter {
     96     fn wire_gateway<T: WireGateway>(self, api: Arc<T>, cfg: &WireGatewayCfg) -> Self;
     97     fn prepared_transfer<T: PreparedTransfer>(self, api: Arc<T>) -> Self;
     98     fn revenue<T: Revenue>(self, api: Arc<T>, auth: AuthMethod) -> Self;
     99     fn observability<T: Observability>(self, api: Arc<T>, auth: AuthMethod) -> Self;
    100     fn finalize(self) -> Self;
    101     fn serve(
    102         self,
    103         serve: &Serve,
    104         lifetime: Option<u32>,
    105     ) -> impl std::future::Future<Output = std::io::Result<()>> + Send;
    106 }
    107 
    108 impl TalerRouter for Router {
    109     fn wire_gateway<T: WireGateway>(self, api: Arc<T>, cfg: &WireGatewayCfg) -> Self {
    110         self.nest("/taler-wire-gateway", wire::router(api, cfg))
    111     }
    112 
    113     fn prepared_transfer<T: PreparedTransfer>(self, api: Arc<T>) -> Self {
    114         self.nest("/taler-prepared-transfer", prepared::router(api))
    115     }
    116 
    117     fn revenue<T: Revenue>(self, api: Arc<T>, auth: AuthMethod) -> Self {
    118         self.nest("/taler-revenue", revenue::router(api, auth))
    119     }
    120 
    121     fn observability<T: Observability>(self, api: Arc<T>, auth: AuthMethod) -> Self {
    122         self.nest("/taler-observability", observability::router(api, auth))
    123     }
    124 
    125     fn finalize(self) -> Router {
    126         self.method_not_allowed_fallback(async || failure_code(ErrorCode::GENERIC_METHOD_INVALID))
    127             .fallback(async || failure_code(ErrorCode::GENERIC_ENDPOINT_UNKNOWN))
    128             .layer(middleware::from_fn(cors_middleware))
    129             .layer(middleware::from_fn(logger_middleware))
    130     }
    131 
    132     async fn serve(mut self, serve: &Serve, lifetime: Option<u32>) -> std::io::Result<()> {
    133         let listener = serve.resolve()?;
    134 
    135         let notify = Arc::new(tokio::sync::Notify::new());
    136         if let Some(lifetime) = lifetime {
    137             self = self.layer(middleware::from_fn_with_state(
    138                 Arc::new(LifetimeMiddlewareState {
    139                     notify: notify.clone(),
    140                     lifetime: AtomicU32::new(lifetime),
    141                 }),
    142                 lifetime_middleware,
    143             ))
    144         }
    145         let router = self.finalize();
    146         let signal = shutdown_signal(notify);
    147         match listener {
    148             Listener::Tcp(listener) => serve::run(listener, router, signal).await,
    149             Listener::Unix(listener) => serve::run(listener, router, signal).await,
    150         }
    151 
    152         info!(target: "api", "Server stopped");
    153         Ok(())
    154     }
    155 }
    156 
    157 async fn cors_middleware(request: Request, next: Next) -> Response {
    158     let headers = request.headers();
    159     if request.method() == Method::OPTIONS
    160         && headers.contains_key(header::ORIGIN)
    161         && headers.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)
    162     {
    163         return [
    164             (header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
    165             (header::ACCESS_CONTROL_ALLOW_METHODS, "*"),
    166             (header::ACCESS_CONTROL_ALLOW_HEADERS, "*"),
    167         ]
    168         .into_response();
    169     }
    170 
    171     let mut response = next.run(request).await;
    172     response.headers_mut().insert(
    173         header::ACCESS_CONTROL_ALLOW_ORIGIN,
    174         HeaderValue::from_static("*"),
    175     );
    176     response
    177 }
    178 
    179 struct LifetimeMiddlewareState {
    180     lifetime: AtomicU32,
    181     notify: Arc<tokio::sync::Notify>,
    182 }
    183 
    184 async fn lifetime_middleware(
    185     State(state): State<Arc<LifetimeMiddlewareState>>,
    186     request: Request,
    187     next: Next,
    188 ) -> Response {
    189     let mut current = state.lifetime.load(Ordering::Relaxed);
    190     while current != 0 {
    191         match state.lifetime.compare_exchange_weak(
    192             current,
    193             current - 1,
    194             Ordering::Relaxed,
    195             Ordering::Relaxed,
    196         ) {
    197             Ok(_) => break,
    198             Err(new) => current = new,
    199         }
    200     }
    201     if current == 0 {
    202         state.notify.notify_one();
    203     }
    204     next.run(request).await
    205 }
    206 
    207 /** Wait for manual shutdown or system signal shutdown */
    208 async fn shutdown_signal(manual_shutdown: Arc<tokio::sync::Notify>) {
    209     let ctrl_c = async {
    210         signal::ctrl_c()
    211             .await
    212             .expect("failed to install Ctrl+C handler");
    213     };
    214 
    215     #[cfg(unix)]
    216     let terminate = async {
    217         signal::unix::signal(signal::unix::SignalKind::terminate())
    218             .expect("failed to install signal handler")
    219             .recv()
    220             .await;
    221     };
    222 
    223     #[cfg(not(unix))]
    224     let terminate = std::future::pending::<()>();
    225 
    226     let manual = async { manual_shutdown.notified().await };
    227 
    228     tokio::select! {
    229         _ = ctrl_c => {},
    230         _ = terminate => {},
    231         _ = manual => {}
    232     }
    233 }
    234 
    235 #[macro_export]
    236 macro_rules! dyn_event {
    237     ($lvl:ident, $($arg:tt)+) => {
    238         match $lvl {
    239             ::tracing::Level::TRACE => ::tracing::trace!($($arg)+),
    240             ::tracing::Level::DEBUG => ::tracing::debug!($($arg)+),
    241             ::tracing::Level::INFO => ::tracing::info!($($arg)+),
    242             ::tracing::Level::WARN => ::tracing::warn!($($arg)+),
    243             ::tracing::Level::ERROR => ::tracing::error!($($arg)+),
    244         }
    245     };
    246 }
    247 
    248 /** Taler API logger */
    249 async fn logger_middleware(
    250     matched_path: Option<MatchedPath>,
    251     request: Request,
    252     next: Next,
    253 ) -> Response {
    254     let now = Instant::now();
    255     let request_id: compact_str::CompactString = {
    256         let charset = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    257         let mut rng = rand::rng();
    258 
    259         let mut ansi = [0u8; 10];
    260         for c in ansi.iter_mut() {
    261             let idx = rng.random_range(0..charset.len());
    262             *c = charset[idx];
    263         }
    264         unsafe { CompactString::from_utf8_unchecked(ansi) }
    265     };
    266     let method = request.method().clone();
    267     LOG_TASK_ID
    268         .scope(request_id, async {
    269             debug!(target: "api", "{method} {}", {
    270                request.extensions().get::<OriginalUri>()
    271                     .map_or_else(|| request.uri(), |original| &original.0).path_and_query().map_or("-", |value| value.as_str())
    272             });
    273             let response = next.run(request).await;
    274             let elapsed = now.elapsed();
    275             let status = response.status();
    276             let level = match status.as_u16() {
    277                 400..500 => Level::WARN,
    278                 500..600 => Level::ERROR,
    279                 _ => Level::INFO,
    280             };
    281 
    282             let route = matched_path.as_ref().map_or("-", MatchedPath::as_str);
    283             if let Some(log) = response.extensions().get::<LoggedError>() {
    284                 let LoggedError { code, info } = log;
    285                 dyn_event!(level, target: "api",
    286                     "{} {method} {route} {}ms: {code}{}",
    287                     response.status(),
    288                     elapsed.as_millis(),
    289                     std::fmt::from_fn(|f|{
    290                         if let Some(info) = info {
    291                             write!(f, " {info}")?;
    292                         }
    293                         Ok(())
    294                     })
    295                 );
    296             } else {
    297                 dyn_event!(level, target: "api",
    298                     "{} {method} {route} {}ms",
    299                     response.status(),
    300                     elapsed.as_millis()
    301                 );
    302             }
    303             response
    304         })
    305         .await
    306 }