api.rs (21322B)
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; 509 use taler_api::{ 510 api::TalerRouter as _, 511 config::{ApiCfg, AuthCfg, WireGatewayCfg}, 512 subject::IncomingKey, 513 }; 514 use taler_common::{ 515 api::{ 516 EddsaPublicKey, observability::Config, prepared::PreparedTransferConfig, 517 revenue::RevenueConfig, wire::WireConfig, 518 }, 519 types::{ 520 amount::{Currency, amount}, 521 iban::iban, 522 payto::{BankID, PaytoURI}, 523 }, 524 }; 525 use taler_macros::db_test; 526 use taler_test_utils::{ 527 Router, 528 routine::{admin_add_incoming_routine, in_history_routine, revenue_routine}, 529 server::TestServer, 530 tasks, 531 }; 532 533 use crate::{ 534 api, 535 config::{ApiEnv, WiseBalance}, 536 db::{TxIn, register_tx_in}, 537 payto::{FullWisePayto, WiseAccount}, 538 }; 539 540 static PAYTO: LazyLock<FullWisePayto> = LazyLock::new(|| { 541 "payto://ach/021000021/024030222?receiver-name=Exchange" 542 .parse() 543 .unwrap() 544 }); 545 static EXCHANGE: LazyLock<PaytoURI> = LazyLock::new(|| PAYTO.as_uri()); 546 547 async fn setup(pool: &PgPool) -> Router { 548 let balances = vec![ 549 WiseBalance { 550 id: 42, 551 currency: Currency::TEST, 552 payto: PAYTO.clone().into_inner().0, 553 }, 554 WiseBalance { 555 id: 34, 556 currency: Currency::KUDOS, 557 payto: PAYTO.clone().into_inner().0, 558 }, 559 ]; 560 api::start( 561 pool.clone(), 562 "Exchange", 563 balances, 564 ApiEnv::sandbox.public_key(), 565 7, 566 &Some(WireGatewayCfg { 567 auth: AuthCfg::None, 568 enable_admin_endpoints: true, 569 }), 570 &Some(ApiCfg { 571 auth: AuthCfg::None, 572 }), 573 &Some(ApiCfg { 574 auth: AuthCfg::None, 575 }), 576 ) 577 .await 578 .finalize() 579 } 580 581 #[db_test] 582 async fn config(db: PgPool) { 583 let server = setup(&db).await; 584 for id in [42, 34] { 585 server 586 .get(format!("/balances/{id}/taler-wire-gateway/config")) 587 .await 588 .assert_ok_json::<WireConfig>(); 589 server 590 .get(format!("/balances/{id}/taler-prepared-transfer/config")) 591 .await 592 .assert_ok_json::<PreparedTransferConfig>(); 593 server 594 .get(format!("/balances/{id}/taler-revenue/config")) 595 .await 596 .assert_ok_json::<RevenueConfig>(); 597 server 598 .get(format!("/balances/{id}/taler-observability/config")) 599 .await 600 .assert_ok_json::<Config>(); 601 server 602 .get(format!("/balances/{id}/taler-observability/metrics")) 603 .await 604 .assert_ok(); 605 } 606 } 607 608 async fn r#in(db: &PgPool, subject: Option<IncomingKey>) { 609 register_tx_in( 610 db, 611 &TxIn { 612 balance_id: 42, 613 wise_ref: None, 614 amount: amount("EUR:10"), 615 subject: "subject".into(), 616 name: CompactString::const_new("Name"), 617 debtor: Some(WiseAccount::IBAN(BankID { 618 iban: iban("HU30162000031000163100000000"), 619 bic: None, 620 })), 621 value_at: Timestamp::now(), 622 }, 623 &subject, 624 &Timestamp::now(), 625 ) 626 .await 627 .unwrap(); 628 } 629 630 async fn in_malformed(db: &PgPool) { 631 r#in(db, None).await 632 } 633 634 async fn in_talerable(db: &PgPool) { 635 r#in(db, Some(IncomingKey::reserve(EddsaPublicKey::rand()))).await 636 } 637 638 #[db_test] 639 async fn admin_add_incoming(db: PgPool) { 640 let server = setup(&db).await; 641 admin_add_incoming_routine( 642 &server.prefix("/balances/42/taler-wire-gateway"), 643 &server.prefix("/balances/42/taler-prepared-transfer"), 644 &EXCHANGE, 645 &EXCHANGE, 646 ) 647 .await; 648 } 649 650 #[db_test] 651 async fn in_history(db: PgPool) { 652 let server = setup(&db).await; 653 let db = &db; 654 in_history_routine( 655 &server.prefix("/balances/42/taler-wire-gateway"), 656 &server.prefix("/balances/42/taler-prepared-transfer"), 657 &EXCHANGE, 658 &EXCHANGE, 659 tasks!({ in_talerable(db).await }), 660 tasks!({ in_malformed(db).await }), 661 ) 662 .await; 663 } 664 665 #[db_test] 666 async fn revenue(db: PgPool) { 667 let server = setup(&db).await; 668 let db = &db; 669 revenue_routine( 670 &server.prefix("/balances/42/taler-wire-gateway"), 671 &server.prefix("/balances/42/taler-revenue"), 672 &EXCHANGE, 673 tasks!({ in_malformed(db).await }, { in_talerable(db).await },), 674 tasks!(), 675 ) 676 .await; 677 } 678 }