taler-rust

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

test.rs (14244B)


      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     str::FromStr,
     19     sync::{Arc, LazyLock},
     20 };
     21 
     22 use axum::{
     23     Router,
     24     http::{StatusCode, header},
     25 };
     26 use serde_json::json;
     27 use sqlx::{PgPool, Row as _, postgres::PgRow};
     28 use taler_common::{
     29     api::{
     30         ErrorDetail, HashCode, ShortHashCode,
     31         prepared::PreparedTransferConfig,
     32         revenue::RevenueConfig,
     33         wire::{TransferRequest, TransferResponse, TransferState, WireConfig},
     34     },
     35     config::Config,
     36     db::IncomingType,
     37     error_code::ErrorCode,
     38     types::{
     39         amount::{Amount, Currency, amount},
     40         base32::Base32,
     41         payto::{FullIbanPayto, PaytoURI, payto},
     42         url,
     43     },
     44 };
     45 use taler_macros::db_test;
     46 use taler_test_utils::{
     47     routine::{
     48         Status, admin_add_incoming_routine, in_history_routine, out_history_routine,
     49         registration_routine, revenue_routine, transfer_routine,
     50     },
     51     server::TestServer,
     52     tasks,
     53 };
     54 use tokio::sync::watch::Sender;
     55 
     56 use crate::{
     57     api::TalerRouter,
     58     auth::AuthMethod,
     59     config::{AuthCfg, WireGatewayCfg},
     60     constants::SAFE_BODY_LENGTH,
     61     db::TypeHelper as _,
     62     test::{api::TestApi, db::notification_listener},
     63 };
     64 
     65 mod api;
     66 mod db;
     67 
     68 static PAYTO: LazyLock<FullIbanPayto> = LazyLock::new(|| {
     69     FullIbanPayto::from_str("payto://iban/HU02162000031000164800000000?receiver-name=Smith")
     70         .unwrap()
     71 });
     72 static EXCHANGE: LazyLock<PaytoURI> = LazyLock::new(|| PAYTO.as_uri());
     73 static UNKNOWN: LazyLock<PaytoURI> =
     74     LazyLock::new(|| payto("payto://iban/HU60162006491000639900000000?receiver-name=Unknown"));
     75 
     76 fn test_api(pool: PgPool, currency: Currency) -> Router {
     77     let outgoing_channel = Sender::new(0);
     78     let incoming_channel = Sender::new(0);
     79     let wg = TestApi::new(
     80         currency,
     81         pool.clone(),
     82         outgoing_channel.clone(),
     83         incoming_channel.clone(),
     84         PAYTO.clone(),
     85     );
     86     tokio::spawn(notification_listener(
     87         pool,
     88         outgoing_channel,
     89         incoming_channel,
     90     ));
     91     let state = Arc::new(wg);
     92     Router::new()
     93         .wire_gateway(
     94             state.clone(),
     95             &WireGatewayCfg {
     96                 auth: AuthCfg::None,
     97                 enable_admin_endpoints: true,
     98             },
     99         )
    100         .prepared_transfer(state.clone())
    101         .revenue(state.clone(), AuthMethod::None)
    102         .observability(state, AuthMethod::None)
    103 }
    104 
    105 async fn setup(db: &PgPool) -> Router {
    106     test_api(db.clone(), "EUR".parse().unwrap()).finalize()
    107 }
    108 
    109 #[tokio::test]
    110 async fn wire_gateway_admin_endpoints_are_opt_in() {
    111     let api = Arc::new(TestApi::new(
    112         "EUR".parse().unwrap(),
    113         PgPool::connect_lazy("postgres:///unused").unwrap(),
    114         Sender::new(0),
    115         Sender::new(0),
    116         PAYTO.clone(),
    117     ));
    118     for (option, expected) in [
    119         ("", StatusCode::NOT_IMPLEMENTED),
    120         ("ENABLE_ADMIN_ENDPOINTS = NO", StatusCode::NOT_IMPLEMENTED),
    121         (
    122             "# Whether to enable the admin operations\nENABLE_ADMIN_ENDPOINTS = YES",
    123             StatusCode::BAD_REQUEST,
    124         ),
    125     ] {
    126         let config = Config::from_mem(&format!(
    127             "[wire-gateway]\nENABLED = YES\nAUTH_METHOD = bearer\nTOKEN = test\n{option}\n"
    128         ))
    129         .unwrap();
    130         let cfg = WireGatewayCfg::parse(config.section("wire-gateway"))
    131             .unwrap()
    132             .unwrap();
    133         let server = Router::new()
    134             .wire_gateway(api.clone(), &cfg)
    135             .finalize()
    136             .prefix("/taler-wire-gateway");
    137 
    138         server.get("/config").await.assert_ok();
    139         server
    140             .post("/admin/unknown")
    141             .await
    142             .assert_error(ErrorCode::GENERIC_ENDPOINT_UNKNOWN);
    143         for path in [
    144             "/admin/add-incoming",
    145             "/admin/add-kycauth",
    146             "/admin/add-mapped",
    147         ] {
    148             server
    149                 .post(path)
    150                 .await
    151                 .assert_error(ErrorCode::GENERIC_UNAUTHORIZED);
    152             let response = server
    153                 .post(path)
    154                 .header(header::AUTHORIZATION, "Bearer test")
    155                 .json(json!({}))
    156                 .await;
    157             response.assert_status(expected);
    158             if expected == StatusCode::NOT_IMPLEMENTED {
    159                 response.assert_error(ErrorCode::GENERIC_FEATURE_NOT_IMPLEMENTED);
    160             }
    161         }
    162     }
    163 }
    164 
    165 #[tokio::test]
    166 async fn options_requests() {
    167     use axum::{
    168         body::Body,
    169         http::{Method, Request},
    170         routing::options,
    171     };
    172     use hyper::service::Service as _;
    173     use hyper_util::service::TowerToHyperService;
    174 
    175     let server = TowerToHyperService::new(
    176         Router::new()
    177             .route("/resource", options(async || StatusCode::NO_CONTENT))
    178             .finalize(),
    179     );
    180 
    181     for (origin, request_method) in [(false, false), (true, false), (false, true), (true, true)] {
    182         let mut request = Request::builder().method(Method::OPTIONS).uri("/resource");
    183         if origin {
    184             request = request.header(header::ORIGIN, "https://example.com");
    185         }
    186         if request_method {
    187             request = request.header(header::ACCESS_CONTROL_REQUEST_METHOD, "OPTIONS");
    188         }
    189         let response = server
    190             .call(request.body(Body::empty()).unwrap())
    191             .await
    192             .unwrap();
    193         assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
    194         if origin && request_method {
    195             assert_eq!(response.status(), StatusCode::OK);
    196             assert_eq!(
    197                 response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS],
    198                 "*"
    199             );
    200             assert_eq!(
    201                 response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS],
    202                 "*"
    203             );
    204         } else {
    205             assert_eq!(response.status(), StatusCode::NO_CONTENT);
    206             assert!(
    207                 !response
    208                     .headers()
    209                     .contains_key(header::ACCESS_CONTROL_ALLOW_METHODS)
    210             );
    211         }
    212     }
    213 }
    214 
    215 #[db_test(sql_dir = "db", component = "taler-api")]
    216 async fn body_parsing(db: PgPool) {
    217     let server = setup(&db).await;
    218     let normal_body = TransferRequest {
    219         request_uid: Base32::rand(),
    220         amount: Amount::zero(&Currency::EUR),
    221         exchange_base_url: url("https://test.com"),
    222         wtid: Base32::rand(),
    223         credit_account: EXCHANGE.clone(),
    224         metadata: None,
    225     };
    226 
    227     // Check OK
    228     server
    229         .post("/taler-wire-gateway/transfer")
    230         .json(&normal_body)
    231         .deflate()
    232         .await
    233         .assert_ok_json::<TransferResponse>();
    234 
    235     for content_type in [
    236         "application/json; charset=utf-8",
    237         "Application/JSON",
    238         "Application/JSON \t; charset=\"UTF-8\"",
    239     ] {
    240         server
    241             .post("/taler-wire-gateway/transfer")
    242             .json(&normal_body)
    243             .header(header::CONTENT_TYPE, content_type)
    244             .await
    245             .assert_ok_json::<TransferResponse>();
    246     }
    247 
    248     // Headers check
    249     server
    250         .post("/taler-wire-gateway/transfer")
    251         .json(&normal_body)
    252         .remove(header::CONTENT_TYPE)
    253         .await
    254         .assert_error_status(
    255             ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED,
    256             StatusCode::UNSUPPORTED_MEDIA_TYPE,
    257         );
    258     server
    259         .post("/taler-wire-gateway/transfer")
    260         .json(&normal_body)
    261         .deflate()
    262         .remove(header::CONTENT_ENCODING)
    263         .await
    264         .assert_error(ErrorCode::GENERIC_JSON_INVALID);
    265     for content_type in ["invalid", "application/json-seq; charset=utf-8"] {
    266         server
    267             .post("/taler-wire-gateway/transfer")
    268             .json(&normal_body)
    269             .header(header::CONTENT_TYPE, content_type)
    270             .await
    271             .assert_error_status(
    272                 ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED,
    273                 StatusCode::UNSUPPORTED_MEDIA_TYPE,
    274             );
    275     }
    276     server
    277         .post("/taler-wire-gateway/transfer")
    278         .json(&normal_body)
    279         .header(header::CONTENT_ENCODING, "deflate")
    280         .await
    281         .assert_error(ErrorCode::GENERIC_COMPRESSION_INVALID);
    282     server
    283         .post("/taler-wire-gateway/transfer")
    284         .json(&normal_body)
    285         .header(header::CONTENT_ENCODING, "invalid")
    286         .await
    287         .assert_error_status(
    288             ErrorCode::GENERIC_HTTP_HEADERS_MALFORMED,
    289             StatusCode::UNSUPPORTED_MEDIA_TYPE,
    290         );
    291 
    292     // Body size limit
    293     let huge_body = TransferRequest {
    294         credit_account: payto(format!(
    295             "payto:://test?message={:A<1$}",
    296             "payout", SAFE_BODY_LENGTH
    297         )),
    298         ..normal_body
    299     };
    300     server
    301         .post("/taler-wire-gateway/transfer")
    302         .json(&huge_body)
    303         .await
    304         .assert_error(ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT);
    305     server
    306         .post("/taler-wire-gateway/transfer")
    307         .json(&huge_body)
    308         .deflate()
    309         .await
    310         .assert_error(ErrorCode::GENERIC_UPLOAD_EXCEEDS_LIMIT);
    311 }
    312 
    313 #[db_test(sql_dir = "db", component = "taler-api")]
    314 async fn errors(db: PgPool) {
    315     let server = setup(&db).await;
    316     server
    317         .get("/unknown")
    318         .await
    319         .assert_error(ErrorCode::GENERIC_ENDPOINT_UNKNOWN);
    320     server
    321         .post("/taler-revenue/config")
    322         .await
    323         .assert_error(ErrorCode::GENERIC_METHOD_INVALID);
    324 }
    325 
    326 #[db_test(sql_dir = "db", component = "taler-api")]
    327 async fn config(db: PgPool) {
    328     let server = setup(&db).await;
    329     server
    330         .get("/taler-wire-gateway/config")
    331         .await
    332         .assert_ok_json::<WireConfig>();
    333     server
    334         .get("/taler-prepared-transfer/config")
    335         .await
    336         .assert_ok_json::<PreparedTransferConfig>();
    337     server
    338         .get("/taler-revenue/config")
    339         .await
    340         .assert_ok_json::<RevenueConfig>();
    341 }
    342 
    343 #[db_test(sql_dir = "db", component = "taler-api")]
    344 async fn transfer(db: PgPool) {
    345     let server = setup(&db).await;
    346     transfer_routine(
    347         &server.prefix("/taler-wire-gateway"),
    348         TransferState::success,
    349         &EXCHANGE,
    350     )
    351     .await;
    352 }
    353 
    354 #[db_test(sql_dir = "db", component = "taler-api")]
    355 async fn outgoing_history(db: PgPool) {
    356     let server = setup(&db).await;
    357     out_history_routine(
    358         &server.prefix("/taler-wire-gateway"),
    359         tasks!({
    360             server
    361                 .post("/taler-wire-gateway/transfer")
    362                 .json(json!({
    363                     "request_uid": HashCode::rand(),
    364                     "amount": amount("EUR:1"),
    365                     "exchange_base_url": url("http://exchange.taler"),
    366                     "wtid": ShortHashCode::rand(),
    367                     "credit_account": EXCHANGE.clone(),
    368                 }))
    369                 .await
    370                 .assert_ok_json::<TransferResponse>();
    371         }),
    372         tasks!(),
    373     )
    374     .await;
    375 }
    376 
    377 #[db_test(sql_dir = "db", component = "taler-api")]
    378 async fn admin_add_incoming(db: PgPool) {
    379     let server = setup(&db).await;
    380     admin_add_incoming_routine(
    381         &server.prefix("/taler-wire-gateway"),
    382         &server.prefix("/taler-prepared-transfer"),
    383         &EXCHANGE,
    384         &EXCHANGE,
    385     )
    386     .await;
    387 }
    388 
    389 #[db_test(sql_dir = "db", component = "taler-api")]
    390 async fn in_history(db: PgPool) {
    391     let server = setup(&db).await;
    392     in_history_routine(
    393         &server.prefix("/taler-wire-gateway"),
    394         &server.prefix("/taler-prepared-transfer"),
    395         &EXCHANGE,
    396         &EXCHANGE,
    397         tasks!(),
    398         tasks!(),
    399     )
    400     .await;
    401 }
    402 
    403 #[db_test(sql_dir = "db", component = "taler-api")]
    404 async fn revenue(db: PgPool) {
    405     let server = setup(&db).await;
    406     revenue_routine(
    407         &server.prefix("/taler-wire-gateway"),
    408         &server.prefix("/taler-revenue"),
    409         &EXCHANGE,
    410         tasks!(),
    411         tasks!(),
    412     )
    413     .await;
    414 }
    415 
    416 #[db_test(sql_dir = "db", component = "taler-api")]
    417 async fn account_check(db: PgPool) {
    418     let server = setup(&db).await;
    419     server
    420         .get("/taler-wire-gateway/account/check")
    421         .query("account", "payto://test")
    422         .await
    423         .assert_status(StatusCode::NOT_IMPLEMENTED);
    424 }
    425 
    426 async fn check_in(pool: &PgPool) -> Vec<Status> {
    427     sqlx::query(
    428             "
    429             SELECT pending_recurrent_in.authorization_pub IS NOT NULL, bounced.tx_in_id IS NOT NULL, type, taler_in.account_pub
    430             FROM tx_in
    431                 LEFT JOIN taler_in USING (tx_in_id)
    432                 LEFT JOIN pending_recurrent_in USING (tx_in_id)
    433                 LEFT JOIN bounced USING (tx_in_id)
    434             ORDER BY tx_in.tx_in_id
    435         ",
    436         )
    437         .try_map(|r: PgRow| {
    438             Ok(
    439                 if r.try_get_flag(0)? {
    440                     Status::Pending
    441                 } else if r.try_get_flag(1)? {
    442                     Status::Bounced
    443                 } else {
    444                     match r.try_get(2)? {
    445                         None => Status::Simple,
    446                         Some(IncomingType::reserve) => Status::Reserve(r.try_get(3)?),
    447                         Some(IncomingType::kyc) => Status::Kyc(r.try_get(3)?),
    448                         Some(e) => unreachable!("{e:?}")
    449                     }
    450                 }
    451             )
    452         })
    453         .fetch_all(pool)
    454         .await
    455         .unwrap()
    456 }
    457 
    458 #[db_test(sql_dir = "db", component = "taler-api")]
    459 async fn registration(db: PgPool) {
    460     let server = setup(&db).await;
    461     registration_routine(
    462         &server.prefix("/taler-wire-gateway"),
    463         &server.prefix("/taler-prepared-transfer"),
    464         &EXCHANGE,
    465         &EXCHANGE,
    466         &UNKNOWN,
    467         || check_in(&db),
    468     )
    469     .await;
    470 }