lib.rs (17527B)
1 /* 2 * This file is part of LibEuFin. 3 * Copyright (C) 2026 Taler Systems S.A. 4 5 * LibEuFin is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU Affero General Public License as 7 * published by the Free Software Foundation; either version 3, or 8 * (at your option) any later version. 9 10 * LibEuFin is distributed in the hope that it will be useful, but 11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General 13 * Public License for more details. 14 15 * You should have received a copy of the GNU Affero General Public 16 * License along with LibEuFin; see the file COPYING. If not, see 17 * <http://www.gnu.org/licenses/> 18 */ 19 20 use std::{ 21 sync::Arc, 22 time::{Duration, Instant}, 23 }; 24 25 use anyhow::{anyhow, bail}; 26 use compact_str::CompactString; 27 use dialoguer::Password; 28 use jiff::{Timestamp, ZonedDateTime}; 29 use rand::{RngExt as _, distr::Alphanumeric}; 30 use serde::{Deserialize, Serialize}; 31 use taler_api::api::TalerRouter; 32 use taler_build::long_version; 33 use taler_common::{ 34 CommonArgs, 35 cli::ConfigCmd, 36 config::Config, 37 types::{ 38 amount::Amount, 39 base32::Base32, 40 payto::IbanPayto, 41 time::{RelativeTime, TalerTimestamp}, 42 }, 43 }; 44 use taler_macros::EnumMeta; 45 use tracing::info; 46 47 use crate::{ 48 api::{ 49 BankState, 50 account::{ 51 AccountReconfiguration, ChallengeContactData, Maybe, RegisterAccountRequest, 52 create_account, create_admin_account, 53 }, 54 bank_api, 55 }, 56 auth::{TOKEN_PREFIX, TokenScope}, 57 config::BankCfg, 58 db::{ 59 account::{ 60 CreationResult, PatchAuthResult, PatchResult, bank_info, reconfig, reconfig_password, 61 }, 62 dbinit, 63 gc::collect, 64 pool, setup_conversion, 65 token::{TokenCreationResult, access}, 66 }, 67 payto::{BankPayto, PaytoCtx}, 68 pw::{PwCrypto, checkpw}, 69 }; 70 71 pub mod api; 72 pub mod auth; 73 #[cfg(test)] 74 pub mod bench; 75 pub mod config; 76 pub mod constants; 77 pub mod db; 78 pub mod mfa; 79 pub mod payto; 80 pub mod pw; 81 82 #[derive(clap::Subcommand, Debug)] 83 pub enum Cmd { 84 /// Initialize libeufin-bank database 85 Dbinit { 86 /// Reset database (DANGEROUS: All existing data is lost) 87 #[arg(short, long)] 88 reset: bool, 89 }, 90 /// Change account password 91 Passwd { 92 /// Account username 93 username: CompactString, 94 /// Account password used for authentication 95 password: Option<String>, 96 }, 97 /// Create authentication token for a user 98 CreateToken { 99 /// Account username 100 #[arg(short, long, visible_alias("user"))] 101 username: CompactString, 102 103 /// Scope for the token 104 #[arg(short, long)] 105 scope: TokenScope, 106 107 /// Custom token validity duration 108 #[arg(short, long, value_name("forever|MICROS"))] 109 duration: Option<RelativeTime>, 110 111 /// Optional token description 112 #[arg(long)] 113 description: Option<CompactString>, 114 115 /// Make the token refreshable into a new token 116 #[arg(long)] 117 refreshable: bool, 118 119 /// Current token to reuse if still valid 120 #[arg(long)] 121 current_token: Option<Base32<32>>, 122 }, 123 /// Run libeufin-bank HTTP server 124 Serve, 125 /// Create an account, returning the payto://-URI associated with it 126 CreateAccount { 127 /// Optional JSON payload. If provided, CLI options are ignored. 128 #[arg()] 129 json: Option<String>, 130 131 /// Account unique username 132 #[arg(short, long, visible_alias("user"), required_unless_present("json"))] 133 username: Option<CompactString>, 134 135 /// Account password used for authentication 136 #[arg(short, long)] 137 password: Option<CompactString>, 138 139 /// Legal name of the account owner 140 #[arg(long, required_unless_present("json"))] 141 name: Option<CompactString>, 142 143 /// Make this account visible to anyone 144 #[arg(long)] 145 public: bool, 146 147 /// Make this account a taler exchange 148 #[arg(long)] 149 exchange: bool, 150 151 /// E-Mail address used for TAN transmission 152 #[arg(long)] 153 email: Option<CompactString>, 154 155 /// Phone number used for TAN transmission 156 #[arg(long)] 157 phone: Option<CompactString>, 158 159 /// Payto URI of a fiat account who receive cashout amount 160 #[arg(long, alias("cashout_payto_uri"))] 161 cashout_payto_uri: Option<IbanPayto>, 162 163 /// Payto URI of this account 164 #[arg(long)] 165 payto_uri: Option<BankPayto>, 166 167 /// Max debit allowed for this account 168 #[arg(long, alias("debit_threshold"))] 169 debit_threshold: Option<Amount>, 170 171 /// Enables 2FA and set the TAN channel used for challenges 172 #[arg(long, alias("tan_channel"))] 173 tan_channel: Vec<TanChannel>, 174 }, 175 /// Edit an existing account 176 EditAccount { 177 /// Account unique username 178 username: CompactString, 179 180 /// Legal name of the account owner 181 #[arg(long)] 182 name: Option<CompactString>, 183 184 /// Make this account visible to anyone 185 #[arg(long)] 186 public: Option<bool>, 187 188 /// Make this account a taler exchange 189 #[arg(long)] 190 exchange: Option<bool>, 191 192 /// E-Mail address used for TAN transmission 193 #[arg(long)] 194 email: Option<Maybe<CompactString>>, 195 196 /// Phone number used for TAN transmission 197 #[arg(long)] 198 phone: Option<Maybe<CompactString>>, 199 200 /// Payto URI of a fiat account who receive cashout amount 201 #[arg(long, alias("cashout_payto_uri"))] 202 cashout_payto_uri: Option<Maybe<IbanPayto>>, 203 204 /// Max debit allowed for this account 205 #[arg(long, alias("debit_threshold"))] 206 debit_threshold: Option<Amount>, 207 208 /// Enables 2FA and set the TAN channel used for challenges 209 #[arg(long, alias("tan_channel"))] 210 tan_channel: Option<Vec<TanChannel>>, 211 }, 212 /// Run garbage collection: abort expired operations and clean expired data 213 Gc, 214 /// Benchmark password hashing algorithm and configuration 215 BenchPwh, 216 #[command(subcommand)] 217 Config(ConfigCmd), 218 } 219 220 #[derive(clap::Parser, Debug)] 221 #[command(long_version = long_version(), about, long_about = None)] 222 pub struct Args { 223 #[clap(flatten)] 224 pub common: CommonArgs, 225 226 #[command(subcommand)] 227 pub cmd: Cmd, 228 } 229 230 // Allowed values for cashout TAN channels. 231 #[derive( 232 sqlx::Type, 233 Debug, 234 Clone, 235 Copy, 236 PartialEq, 237 Eq, 238 PartialOrd, 239 Ord, 240 EnumMeta, 241 Serialize, 242 Deserialize, 243 clap::ValueEnum, 244 )] 245 #[sqlx(type_name = "tan_enum")] 246 #[enum_meta(Str)] 247 #[allow(non_camel_case_types)] 248 pub enum TanChannel { 249 sms, 250 email, 251 } 252 253 pub async fn run(cfg: &Config, cmd: Cmd) -> anyhow::Result<()> { 254 match cmd { 255 Cmd::Dbinit { reset } => { 256 let cfg = BankCfg::parse(cfg)?; 257 let db = dbinit(&cfg.db_cfg, reset, cfg.fiat.is_some()).await?; 258 match create_admin_account(&db, &cfg, None).await? { 259 CreationResult::Success(_) => { 260 info!("Admin's account created") 261 } 262 CreationResult::UsernameReuse => {} 263 CreationResult::PayToReuse 264 | CreationResult::UnknownConversionClass 265 | CreationResult::BonusBalanceInsufficient => unreachable!(), 266 } 267 } 268 Cmd::Passwd { username, password } => { 269 let cfg = BankCfg::parse(cfg)?; 270 let db = pool(&cfg.db_cfg).await?; 271 272 let pw = match password { 273 Some(p) => p, 274 None => Password::new() 275 .with_prompt("Password") 276 .with_confirmation("Repeat for confirmation", "Values do not match, try again") 277 .interact()?, 278 }; 279 checkpw(&pw, cfg.pwd_check_quality)?; 280 match reconfig_password(&db, &cfg.pw_crypto, &username, &pw, None, true).await? { 281 PatchAuthResult::Success => { 282 info!("Password change for '{username}' account succeeded") 283 } 284 PatchAuthResult::UnknownAccount => { 285 bail!("Password change for '{username}' account failed: unknown account") 286 } 287 PatchAuthResult::OldPasswordMismatch | PatchAuthResult::TanRequired => { 288 unreachable!() 289 } 290 } 291 } 292 Cmd::CreateToken { 293 username, 294 scope, 295 duration, 296 description, 297 refreshable, 298 current_token, 299 } => { 300 let cfg = BankCfg::parse(cfg)?; 301 let db = pool(&cfg.db_cfg).await?; 302 let now = Timestamp::now(); 303 let new = if let Some(current) = current_token 304 && let Some(token) = access(&db, current.as_ref(), &now).await? 305 && token.expiration > TalerTimestamp::Timestamp(now) 306 && scope.logical().is_valid_scope(token.scope, refreshable) 307 { 308 current 309 } else { 310 let expiration = 311 match duration.unwrap_or(RelativeTime::Duration(Duration::from_hours(24))) { 312 RelativeTime::Forever => TalerTimestamp::Never, 313 RelativeTime::Duration(duration) => TalerTimestamp::Timestamp( 314 now.checked_add(duration) 315 .map_err(|e| anyhow!("Bad token duration: {e}"))?, 316 ), 317 }; 318 let token = Base32::<32>::secure_rand(); 319 match db::token::create( 320 &db, 321 &username, 322 token.as_ref(), 323 &now, 324 &expiration, 325 &scope, 326 refreshable, 327 description.as_deref(), 328 true, 329 ) 330 .await? 331 { 332 TokenCreationResult::Success(_) => token, 333 TokenCreationResult::TanRequired => unreachable!(), 334 } 335 }; 336 println!("{TOKEN_PREFIX}{new}"); 337 } 338 Cmd::Serve => { 339 let cfg = BankCfg::parse(cfg)?; 340 let db = pool(&cfg.db_cfg).await?; 341 if cfg.fiat.is_some() { 342 setup_conversion(&cfg.db_cfg, db.acquire().await?.as_mut(), true).await?; 343 info!("Ensure exchange account exists"); 344 let Some(info) = bank_info(&db, &cfg.ctx, "exchange").await? else { 345 bail!( 346 "Exchange account missing: an exchange account named 'exchange' is required for conversion to be enabled" 347 ) 348 }; 349 if !info.is_exchange { 350 bail!( 351 "Account is not an exchange: an exchange account named 'exchange' is required for conversion to be enabled" 352 ) 353 } 354 } else { 355 setup_conversion(&cfg.db_cfg, db.acquire().await?.as_mut(), false).await?; 356 } 357 let state = Arc::new(BankState::start(db, cfg).await); 358 bank_api(state.clone()) 359 .serve(&state.cfg.serve, None) 360 .await?; 361 } 362 Cmd::CreateAccount { 363 json, 364 username, 365 password, 366 name, 367 public: is_public, 368 exchange, 369 email, 370 phone, 371 cashout_payto_uri, 372 payto_uri, 373 debit_threshold, 374 tan_channel, 375 } => { 376 let cfg = BankCfg::parse(cfg)?; 377 let db = pool(&cfg.db_cfg).await?; 378 let req = if let Some(json_str) = json { 379 serde_json::from_str::<RegisterAccountRequest>(&json_str) 380 .map_err(|e| anyhow!("Failed to parse JSON: {e}"))? 381 } else { 382 RegisterAccountRequest { 383 username: username.unwrap(), 384 password: match password { 385 Some(p) => p, 386 None => Password::new() 387 .with_prompt("Password") 388 .with_confirmation( 389 "Repeat for confirmation", 390 "Values do not match, try again", 391 ) 392 .interact()? 393 .into(), 394 }, 395 name: name.unwrap(), 396 is_public, 397 is_taler_exchange: exchange, 398 contact_data: ChallengeContactData { 399 email: email.into(), 400 phone: phone.into(), 401 }, 402 cashout_payto_uri, 403 payto_uri, 404 debit_threshold, 405 tan_channel: None, 406 tan_channels: Some(tan_channel), 407 conversion_rate_class_id: None, 408 } 409 }; 410 411 match create_account(&db, &cfg, &req, true).await? { 412 CreationResult::Success(full_payto) => { 413 info!("Account '{}' created", req.username); 414 println!("{full_payto}") 415 } 416 CreationResult::UsernameReuse => { 417 bail!("Account username reuse '{}'", req.username) 418 } 419 CreationResult::PayToReuse => bail!("Bank internalPayToUri reuse"), 420 CreationResult::UnknownConversionClass => unreachable!(), 421 CreationResult::BonusBalanceInsufficient => { 422 bail!("Insufficient admin funds to grant bonus") 423 } 424 } 425 } 426 Cmd::EditAccount { 427 username, 428 name, 429 public, 430 exchange, 431 email, 432 phone, 433 cashout_payto_uri, 434 debit_threshold, 435 tan_channel, 436 } => { 437 let cfg = BankCfg::parse(cfg)?; 438 let db = pool(&cfg.db_cfg).await?; 439 let req = AccountReconfiguration { 440 name, 441 is_taler_exchange: exchange, 442 is_public: public, 443 contact_data: ChallengeContactData { 444 email: email.into(), 445 phone: phone.into(), 446 }, 447 cashout_payto_uri: cashout_payto_uri.into(), 448 debit_threshold, 449 tan_channel: Maybe::Missing, 450 tan_channels: tan_channel, 451 conversion_rate_class_id: Maybe::Missing, 452 }; 453 match reconfig( 454 &db, 455 &cfg.regional_currency, 456 &username, 457 &req, 458 true, 459 true, 460 true, 461 true, 462 ) 463 .await? 464 { 465 PatchResult::UnknownAccount => { 466 bail!("Password change for '{username}' account failed: unknown account") 467 } 468 PatchResult::NonAdminName 469 | PatchResult::NonAdminCashout 470 | PatchResult::NonAdminDebtLimit 471 | PatchResult::NonAdminConversionRateClass 472 | PatchResult::UnknownConversionClass 473 | PatchResult::Challenges(_) => unreachable!(), 474 PatchResult::MissingTanInfo(e) => bail!("{e}"), 475 PatchResult::Success => info!("Account '{username}' edited"), 476 } 477 } 478 Cmd::Gc => { 479 let cfg = BankCfg::parse(cfg)?; 480 let db = pool(&cfg.db_cfg).await?; 481 let now = ZonedDateTime::now(); 482 collect( 483 &db, 484 &(now.clone() - cfg.gc_abort_after).timestamp(), 485 &(now.clone() - cfg.gc_clean_after).timestamp(), 486 &(now - cfg.gc_delete_after).timestamp(), 487 ) 488 .await?; 489 } 490 Cmd::BenchPwh => { 491 let cfg = BankCfg::parse(cfg)?; 492 let pwc = cfg.pw_crypto; 493 494 match pwc { 495 PwCrypto::Bcrypt { cost } => { 496 println!("Benching bcrypt with cost={cost} for 10s"); 497 } 498 PwCrypto::Sha256 => unreachable!(), 499 } 500 501 let start = Instant::now(); 502 let stop = start + Duration::from_secs(10); 503 let mut count = 0; 504 505 loop { 506 let now = Instant::now(); 507 if now < stop { 508 let password: String = rand::rng() 509 .sample_iter(&Alphanumeric) 510 .take(20) 511 .map(char::from) 512 .collect(); 513 514 pwc.hashpw(&password); 515 count += 1; 516 } else { 517 let elapsed = start.elapsed().as_secs_f64(); 518 let per_sec = count as f64 / elapsed; 519 let iter_time_ms = (elapsed * 1000.0) / count as f64; 520 521 println!("hash password in {iter_time_ms:.0}ms {per_sec:.2} H/s"); 522 break; 523 } 524 } 525 } 526 Cmd::Config(cmd) => cmd.run(cfg)?, 527 } 528 Ok(()) 529 }