api.rs (23110B)
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::{collections::BTreeMap, sync::Arc}; 18 19 use aws_lc_rs::signature::ParsedPublicKey; 20 use axum::{ 21 Router, 22 body::Bytes, 23 extract::State, 24 http::{HeaderMap, HeaderName, StatusCode}, 25 routing::post, 26 }; 27 use compact_str::{CompactString, format_compact}; 28 use http_client::headers::HeaderParser; 29 use jiff::Timestamp; 30 use prometheus_client::{ 31 encoding::EncodeLabelSet, 32 metrics::{family::Family, gauge::Gauge}, 33 registry::{Registry, Unit}, 34 }; 35 use serde::Deserialize; 36 use serde_json::value::RawValue; 37 use sqlx::PgPool; 38 use taler_api::{ 39 api::{ 40 TalerApi, TalerRouter as _, observability::Observability, prepared::PreparedTransfer, 41 revenue::Revenue, wire::WireGateway, 42 }, 43 config::{ApiCfg, WireGatewayCfg}, 44 error::{ApiResult, failure_code, not_implemented}, 45 subject::{IncomingKey, fmt_in_subject}, 46 }; 47 use taler_common::{ 48 api::{ 49 params::{History, Page}, 50 prepared::{ 51 RegistrationRequest, RegistrationResponse, SubjectFormat, TransferSubject, 52 Unregistration, 53 }, 54 revenue::RevenueIncomingHistory, 55 wire::{ 56 AddIncomingRequest, AddIncomingResponse, AddKycauthRequest, AddMappedRequest, 57 IncomingHistory, OutgoingHistory, TransferList, TransferRequest, TransferResponse, 58 TransferState, TransferStatus, 59 }, 60 }, 61 db::IncomingType, 62 error_code::ErrorCode, 63 types::{amount::Currency, payto::PaytoImpl, time::TalerTimestamp}, 64 }; 65 use tokio::sync::watch::Sender; 66 67 use crate::{ 68 config::WiseBalance, 69 constants::{BALANCE_UPDATE_EVENT, WEBHOOK_PATH, supports_balance_update_schema}, 70 db::{self, AddIncomingResult, TxIn}, 71 payto::FullWisePayto, 72 }; 73 74 #[allow(clippy::too_many_arguments)] 75 pub async fn start( 76 pool: PgPool, 77 name: &str, 78 balances: Vec<WiseBalance>, 79 key: ParsedPublicKey, 80 profile_id: u64, 81 wire_gateway: &Option<WireGatewayCfg>, 82 revenue: &Option<ApiCfg>, 83 observability: &Option<ApiCfg>, 84 ) -> Router { 85 let mut main_router = Router::new() 86 .route(WEBHOOK_PATH, post(receive_webhook)) 87 .with_state(Arc::new(WebhookState { 88 pool: pool.clone(), 89 key, 90 profile: profile_id, 91 balances: balances.iter().map(|b| (b.id, b.currency)).collect(), 92 })); 93 let apis: Vec<_> = balances 94 .into_iter() 95 .map(|b| { 96 let metrics = Metrics::default(); 97 WiseBalanceApi { 98 id: b.id, 99 currency: b.currency, 100 pool: pool.clone(), 101 payto: b.payto.full(name), 102 in_channel: Sender::new(0), 103 taler_in_channel: Sender::new(0), 104 registry: metrics.registry(), 105 metrics, 106 } 107 }) 108 .collect(); 109 let in_channels = Arc::new(BTreeMap::from_iter( 110 apis.iter().map(|b| (b.id, b.in_channel.clone())), 111 )); 112 let taler_in_channels = Arc::new(BTreeMap::from_iter( 113 apis.iter().map(|b| (b.id, b.taler_in_channel.clone())), 114 )); 115 tokio::spawn(db::notification_listener( 116 pool, 117 in_channels, 118 taler_in_channels, 119 )); 120 for api in apis { 121 let api = Arc::new(api); 122 let mut balance_router = Router::new(); 123 if let Some(cfg) = wire_gateway { 124 balance_router = balance_router 125 .wire_gateway(api.clone(), cfg) 126 .prepared_transfer(api.clone()); 127 } 128 if let Some(cfg) = revenue { 129 balance_router = balance_router.revenue(api.clone(), cfg.auth.method()); 130 } 131 if let Some(cfg) = observability { 132 balance_router = balance_router.observability(api.clone(), cfg.auth.method()); 133 } 134 main_router = main_router.nest(&format!("/balances/{}", api.id), balance_router); 135 } 136 main_router 137 } 138 139 pub struct WiseBalanceApi { 140 pub id: u32, 141 pub currency: Currency, 142 pub pool: sqlx::PgPool, 143 pub payto: FullWisePayto, 144 pub in_channel: Sender<i64>, 145 pub taler_in_channel: Sender<i64>, 146 metrics: Metrics, 147 registry: Registry, 148 } 149 150 #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)] 151 struct TaskLabel { 152 name: &'static str, 153 } 154 155 #[derive(Default)] 156 struct Metrics { 157 db_access: Gauge, 158 task_execution: Family<TaskLabel, Gauge>, 159 task_success: Family<TaskLabel, Gauge>, 160 } 161 162 impl Metrics { 163 pub fn registry(&self) -> Registry { 164 let mut registry = Registry::default(); 165 166 registry.register( 167 "db_access", 168 "Whether the last database metrics refresh succeeded", 169 self.db_access.clone(), 170 ); 171 registry.register_with_unit( 172 "task_execution_timestamp_seconds", 173 "Unix timestamp of the last task execution", 174 Unit::Seconds, 175 self.task_execution.clone(), 176 ); 177 registry.register_with_unit( 178 "task_success_timestamp_seconds", 179 "Unix timestamp of the last successful task execution", 180 Unit::Seconds, 181 self.task_success.clone(), 182 ); 183 registry 184 } 185 186 pub async fn sync(&self, db: &PgPool, balance_id: u32) { 187 let success = match db::load_sync_state(db, balance_id).await { 188 Ok(state) => { 189 let label = TaskLabel { name: "sync" }; 190 if let Some(time) = state.as_ref().and_then(|s| s.execution) { 191 self.task_execution 192 .get_or_create(&label) 193 .set(time.as_second()); 194 } else { 195 self.task_execution.remove(&label); 196 } 197 let success = state.and_then(|s| { 198 s.early_success 199 .max(s.sync_success) 200 .max(s.checkpoint_success) 201 }); 202 if let Some(time) = success { 203 self.task_success 204 .get_or_create(&label) 205 .set(time.as_second()); 206 } else { 207 self.task_success.remove(&label); 208 } 209 true 210 } 211 Err(_) => false, 212 }; 213 self.db_access.set(if success { 1 } else { 0 }); 214 } 215 } 216 217 impl TalerApi for WiseBalanceApi { 218 fn currency(&self) -> Currency { 219 self.currency 220 } 221 222 fn implementation(&self) -> &'static str { 223 "urn:net:taler:specs:taler-wise:taler-rust" 224 } 225 } 226 227 impl WiseBalanceApi { 228 async fn add_incoming( 229 &self, 230 tx: &TxIn, 231 subject: IncomingKey, 232 ) -> ApiResult<AddIncomingResponse> { 233 let now = Timestamp::now(); 234 match db::register_tx_in(&self.pool, tx, &Some(subject), &now).await? { 235 AddIncomingResult::Success { 236 row_id, valued_at, .. 237 } => Ok(AddIncomingResponse { 238 row_id, 239 timestamp: valued_at.into(), 240 }), 241 AddIncomingResult::ReservePubReuse => { 242 Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT)) 243 } 244 AddIncomingResult::UnknownMapping => { 245 Err(failure_code(ErrorCode::BANK_TRANSFER_MAPPING_UNKNOWN)) 246 } 247 AddIncomingResult::MappingReuse => { 248 Err(failure_code(ErrorCode::BANK_TRANSFER_MAPPING_REUSED)) 249 } 250 } 251 } 252 } 253 254 impl WireGateway for WiseBalanceApi { 255 async fn transfer(&self, _: TransferRequest) -> ApiResult<TransferResponse> { 256 Err(not_implemented()) 257 } 258 259 async fn transfer_page(&self, _: Page, _: Option<TransferState>) -> ApiResult<TransferList> { 260 Ok(TransferList { 261 transfers: Vec::new(), 262 debit_account: self.payto.as_uri(), 263 }) 264 } 265 266 async fn transfer_by_id(&self, _: u64) -> ApiResult<Option<TransferStatus>> { 267 Ok(None) 268 } 269 270 async fn outgoing_history(&self, _: History) -> ApiResult<OutgoingHistory> { 271 Ok(OutgoingHistory { 272 outgoing_transactions: Vec::new(), 273 debit_account: self.payto.as_uri(), 274 }) 275 } 276 277 async fn incoming_history(&self, params: History) -> ApiResult<IncomingHistory> { 278 Ok(IncomingHistory { 279 incoming_transactions: db::incoming_history( 280 &self.pool, 281 self.id, 282 &self.currency, 283 ¶ms, 284 || self.taler_in_channel.subscribe(), 285 ) 286 .await?, 287 credit_account: self.payto.as_uri(), 288 }) 289 } 290 291 async fn add_incoming_reserve( 292 &self, 293 req: AddIncomingRequest, 294 ) -> ApiResult<AddIncomingResponse> { 295 let (account, name) = FullWisePayto::try_from(&req.debit_account)?.into_inner(); 296 let subject = format_compact!("Admin incoming {}", req.reserve_pub); 297 self.add_incoming( 298 &TxIn { 299 balance_id: self.id, 300 wise_ref: None, 301 amount: req.amount, 302 subject, 303 name, 304 debtor: Some(account), 305 value_at: Timestamp::now(), 306 }, 307 IncomingKey::reserve(req.reserve_pub), 308 ) 309 .await 310 } 311 312 async fn add_incoming_kyc(&self, req: AddKycauthRequest) -> ApiResult<AddIncomingResponse> { 313 let (account, name) = FullWisePayto::try_from(&req.debit_account)?.into_inner(); 314 let subject = format_compact!("Admin incoming KYC:{}", req.account_pub); 315 self.add_incoming( 316 &TxIn { 317 balance_id: self.id, 318 wise_ref: None, 319 amount: req.amount, 320 subject, 321 name, 322 debtor: Some(account), 323 value_at: Timestamp::now(), 324 }, 325 IncomingKey::kyc(req.account_pub), 326 ) 327 .await 328 } 329 330 async fn add_incoming_mapped(&self, req: AddMappedRequest) -> ApiResult<AddIncomingResponse> { 331 let (account, name) = FullWisePayto::try_from(&req.debit_account)?.into_inner(); 332 let subject = format_compact!("Admin incoming MAP:{}", req.authorization_pub); 333 self.add_incoming( 334 &TxIn { 335 balance_id: self.id, 336 wise_ref: None, 337 amount: req.amount, 338 subject, 339 name, 340 debtor: Some(account), 341 value_at: Timestamp::now(), 342 }, 343 IncomingKey::map(req.authorization_pub), 344 ) 345 .await 346 } 347 348 fn support_account_check(&self) -> bool { 349 false 350 } 351 } 352 353 impl Revenue for WiseBalanceApi { 354 async fn history(&self, params: History) -> ApiResult<RevenueIncomingHistory> { 355 Ok(RevenueIncomingHistory { 356 incoming_transactions: db::revenue_history( 357 &self.pool, 358 self.id, 359 &self.currency, 360 ¶ms, 361 || self.in_channel.subscribe(), 362 ) 363 .await?, 364 credit_account: self.payto.as_uri(), 365 }) 366 } 367 } 368 369 impl PreparedTransfer for WiseBalanceApi { 370 fn supported_formats(&self) -> &[SubjectFormat] { 371 &[SubjectFormat::SIMPLE] 372 } 373 374 async fn registration(&self, req: RegistrationRequest) -> ApiResult<RegistrationResponse> { 375 let creditor = FullWisePayto::try_from(&req.credit_account)?; 376 if creditor != self.payto { 377 return Err(failure_code(ErrorCode::BANK_UNKNOWN_CREDITOR)); 378 } 379 match db::transfer_register(&self.pool, self.id, &req).await? { 380 db::RegistrationResult::Success => { 381 let simple = TransferSubject::Simple { 382 credit_amount: req.credit_amount, 383 subject: if req.authorization_pub == req.account_pub && !req.recurrent { 384 fmt_in_subject(req.r#type.into(), &req.account_pub).to_string() 385 } else { 386 fmt_in_subject(IncomingType::map, &req.authorization_pub).to_string() 387 }, 388 }; 389 ApiResult::Ok(RegistrationResponse { 390 subjects: vec![simple], 391 expiration: TalerTimestamp::Never, 392 }) 393 } 394 db::RegistrationResult::ReservePubReuse => { 395 ApiResult::Err(failure_code(ErrorCode::BANK_DUPLICATE_RESERVE_PUB_SUBJECT)) 396 } 397 } 398 } 399 400 async fn unregistration(&self, req: Unregistration) -> ApiResult<bool> { 401 Ok(db::transfer_unregister(&self.pool, self.id, &req).await?) 402 } 403 } 404 405 impl Observability for WiseBalanceApi { 406 async fn metrics(&self) -> ApiResult<&Registry> { 407 self.metrics.sync(&self.pool, self.id).await; 408 Ok(&self.registry) 409 } 410 } 411 412 struct WebhookState { 413 pool: PgPool, 414 key: ParsedPublicKey, 415 profile: u64, 416 balances: BTreeMap<u32, Currency>, 417 } 418 419 #[derive(Deserialize)] 420 struct WebhookEvent<'a> { 421 event_type: CompactString, 422 schema_version: CompactString, 423 subscription_id: uuid::Uuid, 424 sent_at: Timestamp, 425 #[serde(borrow)] 426 data: &'a RawValue, 427 } 428 429 #[derive(Deserialize)] 430 struct BalanceEvent { 431 resource: Resource, 432 balance_id: u32, 433 currency: Currency, 434 occurred_at: Timestamp, 435 transfer_reference: Option<CompactString>, 436 transaction_type: CompactString, 437 } 438 439 #[derive(Deserialize)] 440 struct Resource { 441 profile_id: u64, 442 } 443 444 async fn receive_webhook( 445 State(state): State<Arc<WebhookState>>, 446 headers: HeaderMap, 447 body: Bytes, 448 ) -> Result<StatusCode, StatusCode> { 449 // Verify signature 450 let signature = headers 451 .b64_header(HeaderName::from_static("x-signature-sha256")) 452 .map_err(|_| StatusCode::UNAUTHORIZED)?; 453 state 454 .key 455 .verify_sig(&body, &signature) 456 .map_err(|_| StatusCode::UNAUTHORIZED)?; 457 458 if headers 459 .get(HeaderName::from_static("x-test-notification")) 460 .is_some_and(|v| v == "true") 461 { 462 return Ok(StatusCode::NO_CONTENT); 463 } 464 465 // Parse webhook event 466 let event: WebhookEvent<'_> = 467 serde_json::from_slice(&body).map_err(|_| StatusCode::BAD_REQUEST)?; 468 tracing::debug!(target: "webhook", 469 event_type = %event.event_type, 470 schema_version = %event.schema_version, 471 subscription_id = %event.subscription_id, 472 sent_at = %event.sent_at, 473 "received Wise webhook" 474 ); 475 476 if event.event_type != BALANCE_UPDATE_EVENT 477 || !supports_balance_update_schema(&event.schema_version) 478 { 479 return Ok(StatusCode::NO_CONTENT); 480 } 481 let balance: BalanceEvent = 482 serde_json::from_str(event.data.get()).map_err(|_| StatusCode::BAD_REQUEST)?; 483 if balance.transaction_type != "credit" 484 || balance.resource.profile_id != state.profile 485 || state.balances.get(&balance.balance_id) != Some(&balance.currency) 486 { 487 return Ok(StatusCode::NO_CONTENT); 488 } 489 sqlx::query("SELECT pg_notify('wise_balance_credit', $1)") 490 .bind(balance.balance_id.to_string()) 491 .execute(&state.pool) 492 .await 493 .map_err(|err| { 494 tracing::error!(target: "webhook", "cannot notify balance change: {err}"); 495 StatusCode::SERVICE_UNAVAILABLE 496 })?; 497 tracing::debug!(target: "webhook", balance_id = balance.balance_id, transfer_reference = ?balance.transfer_reference, occurred_at = %balance.occurred_at, "notified balance change"); 498 Ok(StatusCode::NO_CONTENT) 499 } 500 501 #[cfg(test)] 502 mod test { 503 504 use std::sync::LazyLock; 505 506 use compact_str::CompactString; 507 use jiff::Timestamp; 508 use sqlx::{PgPool, Row, postgres::PgRow}; 509 use taler_api::{ 510 api::TalerRouter as _, 511 config::{ApiCfg, AuthCfg, WireGatewayCfg}, 512 db::TypeHelper, 513 subject::IncomingKey, 514 }; 515 use taler_common::{ 516 api::{ 517 EddsaPublicKey, observability::Config, prepared::PreparedTransferConfig, 518 revenue::RevenueConfig, wire::WireConfig, 519 }, 520 types::{ 521 amount::{Currency, amount}, 522 iban::iban, 523 payto::{BankID, PaytoURI}, 524 }, 525 }; 526 use taler_macros::db_test; 527 use taler_test_utils::{ 528 Router, 529 routine::{ 530 Status, admin_add_incoming_routine, in_history_routine, registration_routine, 531 revenue_routine, 532 }, 533 server::TestServer, 534 tasks, 535 }; 536 537 use super::IncomingType; 538 use crate::{ 539 api, 540 config::{ApiEnv, WiseBalance}, 541 db::{TxIn, register_tx_in}, 542 payto::{FullWisePayto, WiseAccount}, 543 }; 544 545 const BALANCE_ID: u32 = 2_147_483_689; // i32::MAX as u32 + 42 546 const WIRE_PREFIX: &str = "/balances/2147483689/taler-wire-gateway"; 547 const PREPARED_PREFIX: &str = "/balances/2147483689/taler-prepared-transfer"; 548 const REVENUE_PREFIX: &str = "/balances/2147483689/taler-revenue"; 549 static PAYTO: LazyLock<FullWisePayto> = LazyLock::new(|| { 550 "payto://ach/021000021/024030222?receiver-name=Exchange" 551 .parse() 552 .unwrap() 553 }); 554 static EXCHANGE: LazyLock<PaytoURI> = LazyLock::new(|| PAYTO.as_uri()); 555 static UNKNOWN: LazyLock<PaytoURI> = LazyLock::new(|| { 556 "payto://ach/021000021/024030223?receiver-name=Unknown" 557 .parse() 558 .unwrap() 559 }); 560 561 async fn setup(pool: &PgPool) -> Router { 562 let balances = vec![ 563 WiseBalance { 564 id: BALANCE_ID, 565 currency: Currency::TEST, 566 payto: PAYTO.clone().into_inner().0, 567 }, 568 WiseBalance { 569 id: 34, 570 currency: Currency::KUDOS, 571 payto: PAYTO.clone().into_inner().0, 572 }, 573 ]; 574 api::start( 575 pool.clone(), 576 "Exchange", 577 balances, 578 ApiEnv::sandbox.public_key(), 579 7, 580 &Some(WireGatewayCfg { 581 auth: AuthCfg::None, 582 enable_admin_endpoints: true, 583 }), 584 &Some(ApiCfg { 585 auth: AuthCfg::None, 586 }), 587 &Some(ApiCfg { 588 auth: AuthCfg::None, 589 }), 590 ) 591 .await 592 .finalize() 593 } 594 595 #[db_test] 596 async fn config(db: PgPool) { 597 let server = setup(&db).await; 598 for id in [BALANCE_ID, 34] { 599 server 600 .get(format!("/balances/{id}/taler-wire-gateway/config")) 601 .await 602 .assert_ok_json::<WireConfig>(); 603 server 604 .get(format!("/balances/{id}/taler-prepared-transfer/config")) 605 .await 606 .assert_ok_json::<PreparedTransferConfig>(); 607 server 608 .get(format!("/balances/{id}/taler-revenue/config")) 609 .await 610 .assert_ok_json::<RevenueConfig>(); 611 server 612 .get(format!("/balances/{id}/taler-observability/config")) 613 .await 614 .assert_ok_json::<Config>(); 615 server 616 .get(format!("/balances/{id}/taler-observability/metrics")) 617 .await 618 .assert_ok(); 619 } 620 } 621 622 async fn r#in(db: &PgPool, subject: Option<IncomingKey>) { 623 register_tx_in( 624 db, 625 &TxIn { 626 balance_id: BALANCE_ID, 627 wise_ref: None, 628 amount: amount("EUR:10"), 629 subject: "subject".into(), 630 name: CompactString::const_new("Name"), 631 debtor: Some(WiseAccount::IBAN(BankID { 632 iban: iban("HU30162000031000163100000000"), 633 bic: None, 634 })), 635 value_at: Timestamp::now(), 636 }, 637 &subject, 638 &Timestamp::now(), 639 ) 640 .await 641 .unwrap(); 642 } 643 644 async fn in_malformed(db: &PgPool) { 645 r#in(db, None).await 646 } 647 648 async fn in_talerable(db: &PgPool) { 649 r#in(db, Some(IncomingKey::reserve(EddsaPublicKey::rand()))).await 650 } 651 652 #[db_test] 653 async fn admin_add_incoming(db: PgPool) { 654 let server = setup(&db).await; 655 admin_add_incoming_routine( 656 &server.prefix(WIRE_PREFIX), 657 &server.prefix(PREPARED_PREFIX), 658 &EXCHANGE, 659 &EXCHANGE, 660 ) 661 .await; 662 } 663 664 #[db_test] 665 async fn in_history(db: PgPool) { 666 let server = setup(&db).await; 667 let db = &db; 668 in_history_routine( 669 &server.prefix(WIRE_PREFIX), 670 &server.prefix(PREPARED_PREFIX), 671 &EXCHANGE, 672 &EXCHANGE, 673 tasks!({ in_talerable(db).await }), 674 tasks!({ in_malformed(db).await }), 675 ) 676 .await; 677 } 678 679 #[db_test] 680 async fn revenue(db: PgPool) { 681 let server = setup(&db).await; 682 let db = &db; 683 revenue_routine( 684 &server.prefix(WIRE_PREFIX), 685 &server.prefix(REVENUE_PREFIX), 686 &EXCHANGE, 687 tasks!({ in_malformed(db).await }, { in_talerable(db).await },), 688 tasks!(), 689 ) 690 .await; 691 } 692 693 async fn check_in(pool: &PgPool) -> Vec<Status> { 694 sqlx::query( 695 " 696 SELECT pending_recurrent_in.authorization_pub IS NOT NULL, type, metadata 697 FROM tx_in 698 LEFT JOIN taler_in USING (tx_in_id, balance_id) 699 LEFT JOIN pending_recurrent_in USING (tx_in_id, balance_id) 700 ORDER BY tx_in.tx_in_id 701 ", 702 ) 703 .try_map(|r: PgRow| { 704 Ok(if r.try_get_flag(0)? { 705 Status::Pending 706 } else { 707 match r.try_get(1)? { 708 None => Status::Simple, 709 Some(IncomingType::reserve) => Status::Reserve(r.try_get(2)?), 710 Some(IncomingType::kyc) => Status::Kyc(r.try_get(2)?), 711 Some(e) => unreachable!("{e:?}"), 712 } 713 }) 714 }) 715 .fetch_all(pool) 716 .await 717 .unwrap() 718 } 719 720 #[db_test] 721 async fn registration(db: PgPool) { 722 let server = setup(&db).await; 723 registration_routine( 724 &server.prefix(WIRE_PREFIX), 725 &server.prefix(PREPARED_PREFIX), 726 &EXCHANGE, 727 &EXCHANGE, 728 &UNKNOWN, 729 false, 730 || check_in(&db), 731 ) 732 .await; 733 } 734 }