taler-rust

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

commit c83014e724dc454e611e270b9f4054fdbd00472f
parent c15fe83abd8f5ce43ab3fab83bab94c2aff6c94b
Author: Antoine A <>
Date:   Fri, 20 Nov 2026 11:52:32 +0100

taler-wise: add webhook registration command

Diffstat:
MCargo.lock | 20++++++++++----------
Madapters/taler-wise/src/api.rs | 15++++++++++++---
Madapters/taler-wise/src/config.rs | 45+++++++++++++++++++++++++++++++++++----------
Madapters/taler-wise/src/constants.rs | 8++++++++
Madapters/taler-wise/src/main.rs | 40+++++++++++++++++++++++++++++++++++++---
Madapters/taler-wise/src/wise_api/client.rs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
6 files changed, 164 insertions(+), 34 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -305,9 +305,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" dependencies = [ "clap_builder", "clap_derive", @@ -327,9 +327,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" dependencies = [ "heck", "proc-macro2", @@ -1572,9 +1572,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" [[package]] name = "pkg-config" @@ -2001,9 +2001,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.24.0" +version = "3.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +checksum = "56cb1ca7c93ae63d6439b5250f6b6b040f7e121f32e5dd2f5d523dd4149b3204" dependencies = [ "serde_core", "serde_with_macros", @@ -2011,9 +2011,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.24.0" +version = "3.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f" dependencies = [ "darling", "proc-macro2", diff --git a/adapters/taler-wise/src/api.rs b/adapters/taler-wise/src/api.rs @@ -66,6 +66,7 @@ use tokio::sync::watch::Sender; use crate::{ config::WiseBalance, + constants::{BALANCE_UPDATE_EVENT, WEBHOOK_PATH, supports_balance_update_schema}, db::{self, AddIncomingResult, TxIn}, payto::FullWisePayto, }; @@ -82,7 +83,7 @@ pub async fn start( observability: &Option<ApiCfg>, ) -> Router { let mut main_router = Router::new() - .route("/wise-webhooks", post(receive_webhook)) + .route(WEBHOOK_PATH, post(receive_webhook)) .with_state(Arc::new(WebhookState { pool: pool.clone(), key, @@ -454,6 +455,13 @@ async fn receive_webhook( .verify_sig(&body, &signature) .map_err(|_| StatusCode::UNAUTHORIZED)?; + if headers + .get(HeaderName::from_static("x-test-notification")) + .is_some_and(|v| v == "true") + { + return Ok(StatusCode::NO_CONTENT); + } + // Parse webhook event let event: WebhookEvent<'_> = serde_json::from_slice(&body).map_err(|_| StatusCode::BAD_REQUEST)?; @@ -465,8 +473,9 @@ async fn receive_webhook( "received Wise webhook" ); - // We only handle balances update right now - if event.event_type != "balances#update" || event.schema_version != "4.0.0" { + if event.event_type != BALANCE_UPDATE_EVENT + || !supports_balance_update_schema(&event.schema_version) + { return Ok(StatusCode::NO_CONTENT); } let balance: BalanceEvent = diff --git a/adapters/taler-wise/src/config.rs b/adapters/taler-wise/src/config.rs @@ -18,12 +18,13 @@ use std::{str::FromStr as _, sync::LazyLock, time::Duration}; use aws_lc_rs::signature::{ParsedPublicKey, RSA_PKCS1_2048_8192_SHA256}; use compact_str::CompactString; +use http::HeaderValue; use taler_api::{ Serve, config::{ApiCfg, DbCfg}, }; use taler_common::{ - config::{CfgErr, Config}, + config::{CfgErr, Config, Section}, config_bail, map_config, types::{ amount::Currency, @@ -138,7 +139,7 @@ fn balances(cfg: &Config) -> Result<Vec<WiseBalance>, CfgErr> { /// taler-wise setup config pub struct SetupCfg { pub api: ApiEnv, - pub token: String, + pub token: HeaderValue, pub profile_id: Option<u64>, pub name: Option<CompactString>, pub balances: Vec<WiseBalance>, @@ -151,13 +152,32 @@ impl SetupCfg { Ok(Self { api: ms.parse("env", "API_ENV").require()?, profile_id: ms.number("PROFILE_ID").opt()?, - token: s.str("TOKEN").require()?, + token: parse_token(&s)?, name: ms.cstr("NAME").opt()?, balances: balances(cfg)?, }) } } +/// taler-wise webhook subscription config +pub struct SubscribeWebhooksCfg { + pub api: ApiEnv, + pub profile_id: u64, + pub token: HeaderValue, +} + +impl SubscribeWebhooksCfg { + pub fn parse(cfg: &Config) -> Result<Self, CfgErr> { + let wise = cfg.section("wise"); + let worker = cfg.section("wise-worker"); + Ok(Self { + api: wise.parse("env", "API_ENV").require()?, + profile_id: wise.number("PROFILE_ID").require()?, + token: parse_token(&worker)?, + }) + } +} + /// taler-wise httpd config pub struct ServeCfg { pub api: ApiEnv, @@ -190,11 +210,21 @@ impl ServeCfg { pub struct WorkerCfg { pub api: ApiEnv, pub profile_id: u64, - pub token: String, + pub token: HeaderValue, pub frequency: Duration, pub balances: Vec<WiseBalance>, } +fn parse_token(section: &Section<'_, '_>) -> Result<HeaderValue, CfgErr> { + section + .value("string", "TOKEN", |token| { + let mut value = HeaderValue::from_str(&format!("Bearer {token}"))?; + value.set_sensitive(true); + Ok::<_, http::header::InvalidHeaderValue>(value) + }) + .require() +} + impl WorkerCfg { pub fn parse(cfg: &Config) -> Result<Self, CfgErr> { let ms = cfg.section("wise"); @@ -202,7 +232,7 @@ impl WorkerCfg { let cfg = Self { api: ms.parse("env", "API_ENV").require()?, profile_id: ms.number("PROFILE_ID").require()?, - token: s.str("TOKEN").require()?, + token: parse_token(&s)?, frequency: s.duration("FREQUENCY").require()?, balances: balances(cfg)?, }; @@ -212,11 +242,6 @@ impl WorkerCfg { if cfg.frequency.is_zero() { return Err(s.invalid("FREQUENCY", "must be positive")); } - if cfg.token.is_empty() - || http::header::HeaderValue::from_str(&format!("Bearer {}", cfg.token)).is_err() - { - return Err(s.invalid("TOKEN", "must be a nonempty valid HTTP header value")); - } Ok(cfg) } } diff --git a/adapters/taler-wise/src/constants.rs b/adapters/taler-wise/src/constants.rs @@ -19,6 +19,14 @@ use std::time::Duration; use taler_common::config::parser::ConfigSource; pub const CONFIG_SOURCE: ConfigSource = ConfigSource::new("taler-wise", "wise", "taler-wise"); +pub const WEBHOOK_PATH: &str = "/wise-webhooks"; + +pub(crate) const BALANCE_UPDATE_EVENT: &str = "balances#update"; +pub(crate) const BALANCE_UPDATE_SCHEMA_VERSION: &str = "4.0.0"; + +pub(crate) fn supports_balance_update_schema(version: &str) -> bool { + matches!(version, "2.2.0" | "3.0.0" | BALANCE_UPDATE_SCHEMA_VERSION) +} pub(crate) static HOUR: Duration = Duration::from_secs(60 * 60); pub(crate) static DAY: Duration = Duration::from_secs(24 * 60 * 60); diff --git a/adapters/taler-wise/src/main.rs b/adapters/taler-wise/src/main.rs @@ -17,15 +17,19 @@ use clap::Parser as _; use taler_api::api::TalerRouter as _; use taler_build::long_version; -use taler_common::{CommonArgs, cli::ConfigCmd, config::Config, taler_main}; +use taler_common::{ + CommonArgs, cli::ConfigCmd, config::Config, taler_main, types::validate_base_url, +}; use taler_wise::{ api, - config::ServeCfg, - constants::CONFIG_SOURCE, + config::{ServeCfg, SubscribeWebhooksCfg}, + constants::{CONFIG_SOURCE, WEBHOOK_PATH}, db::{dbinit, pool}, setup::{self}, + wise_api::client::Client, worker::run_worker, }; +use url::Url; #[derive(clap::Parser, Debug)] #[command(long_version = long_version(), about, long_about = None)] @@ -65,9 +69,29 @@ enum Command { check: bool, }, #[command(subcommand)] + TalerDeployment(TalerDeployment), + #[command(subcommand)] Config(ConfigCmd), } +/// Helpers to deploy taler-wise +#[derive(clap::Subcommand, Debug)] +enum TalerDeployment { + /// Subscribe to webhooks for instant registration + SubscribeWebhooks { + /// Base URL of taler-wise + #[arg(value_name = "BASE_URL", value_parser = webhook_url)] + callback_url: Url, + }, +} + +fn webhook_url(prefix: &str) -> Result<Url, String> { + let url = Url::parse(prefix).map_err(|e| e.to_string())?; + validate_base_url(&url)?; + url.join(WEBHOOK_PATH.trim_start_matches('/')) + .map_err(|e| e.to_string()) +} + async fn run(cmd: Command, cfg: &Config) -> anyhow::Result<()> { match cmd { Command::Dbinit { reset } => { @@ -105,6 +129,16 @@ async fn run(cmd: Command, cfg: &Config) -> anyhow::Result<()> { run_worker(cfg, &pool, &client, transient).await?; } Command::Config(cmd) => cmd.run(cfg)?, + Command::TalerDeployment(cmd) => match cmd { + TalerDeployment::SubscribeWebhooks { callback_url } => { + let cfg = SubscribeWebhooksCfg::parse(cfg)?; + let http = http_client::client(); + let id = Client::new(&http, cfg.api, &cfg.token) + .subscribe_balance_updates(cfg.profile_id, &callback_url) + .await?; + println!("{id}"); + } + }, } Ok(()) } diff --git a/adapters/taler-wise/src/wise_api/client.rs b/adapters/taler-wise/src/wise_api/client.rs @@ -22,12 +22,16 @@ use http::{ }; use http_client::{ApiErr, ClientErr, builder::Req, headers::HeaderParser as _}; use jiff::{SignedDuration, Timestamp, fmt::rfc2822::DateTimeParser}; -use serde::de::DeserializeOwned; +use serde::{Deserialize, de::DeserializeOwned}; +use serde_json::json; use taler_common::types::amount::Currency; use thiserror::Error; +use url::Url; +use uuid::Uuid; use crate::{ config::ApiEnv, + constants::{BALANCE_UPDATE_EVENT, BALANCE_UPDATE_SCHEMA_VERSION}, wise_api::types::{Balance, BalanceStatement, MultiCurrencyAccount, Profile}, }; @@ -58,18 +62,31 @@ fn retry_after(value: &str) -> Option<Duration> { std::time::Instant::now().checked_add(delay).map(|_| delay) } +#[derive(Deserialize)] +pub(crate) struct WebhookSubscription { + pub id: Uuid, + trigger_on: String, + pub delivery: WebhookDelivery, +} + +#[derive(Deserialize)] +pub(crate) struct WebhookDelivery { + pub version: String, + pub url: Url, +} + pub struct Client<'a> { base_url: &'a url::Url, client: &'a http_client::Client, - token: HeaderValue, + token: &'a HeaderValue, } impl<'a> Client<'a> { - pub fn new(client: &'a http_client::Client, env: ApiEnv, token: &str) -> Self { + pub fn new(client: &'a http_client::Client, env: ApiEnv, token: &'a HeaderValue) -> Self { Self { client, base_url: env.api(), - token: HeaderValue::from_str(&format!("Bearer {token}")).unwrap(), + token, } } @@ -84,10 +101,7 @@ impl<'a> Client<'a> { .await .map_err(|(ctx, e)| ctx.wrap(e.into()))?; match res.status() { - StatusCode::OK => { - // Parse json - res.json().await.map_err(|e| ctx.wrap(e.into())) - } + StatusCode::OK => res.json().await.map_err(|e| ctx.wrap(e.into())), StatusCode::TOO_MANY_REQUESTS => Err(ctx.wrap(WiseErr::TooManyRequest(retry_after( &res.str_header(RETRY_AFTER).unwrap_or_default(), )))), @@ -99,6 +113,46 @@ impl<'a> Client<'a> { Self::send(self, self.request(Method::GET, "/v2/profiles")).await } + pub(crate) async fn balance_update_webhooks( + &self, + profile_id: u64, + ) -> ApiResult<Vec<WebhookSubscription>> { + let subscriptions: Vec<WebhookSubscription> = self + .send(self.request( + Method::GET, + format!("/v3/profiles/{profile_id}/subscriptions"), + )) + .await?; + Ok(subscriptions + .into_iter() + .filter(|subscription| subscription.trigger_on == BALANCE_UPDATE_EVENT) + .collect()) + } + + pub async fn subscribe_balance_updates(&self, profile_id: u64, url: &Url) -> ApiResult<Uuid> { + if let Some(subscription) = self + .balance_update_webhooks(profile_id) + .await? + .into_iter() + .find(|subscription| subscription.delivery.url == *url) + { + return Ok(subscription.id); + } + + let path = format!("/v3/profiles/{profile_id}/subscriptions"); + let subscription: WebhookSubscription = self + .send(self.request(Method::POST, path).json(&json!({ + "name": "Taler Wise balance updates", + "trigger_on": BALANCE_UPDATE_EVENT, + "delivery": { + "version": BALANCE_UPDATE_SCHEMA_VERSION, + "url": url, + }, + }))) + .await?; + Ok(subscription.id) + } + pub async fn standard_balances(&self, profile_id: u64) -> ApiResult<Vec<Balance>> { Self::send( self,