fake_auth.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. use std::env;
  2. use std::str::FromStr;
  3. use std::sync::Arc;
  4. use bip39::Mnemonic;
  5. use cashu::{MintAuthRequest, MintInfo};
  6. use cdk::amount::{Amount, SplitTarget};
  7. use cdk::mint_url::MintUrl;
  8. use cdk::nuts::nut00::{KnownMethod, ProofsMethods};
  9. use cdk::nuts::{
  10. AuthProof, AuthToken, BlindAuthToken, CheckStateRequest, CurrencyUnit, MeltQuoteBolt11Request,
  11. MeltQuoteState, MeltRequest, MintQuoteBolt11Request, MintRequest, PaymentMethod,
  12. RestoreRequest, State, SwapRequest,
  13. };
  14. use cdk::wallet::{AuthHttpClient, AuthMintConnector, HttpClient, MintConnector, WalletBuilder};
  15. use cdk::{Error, OidcClient};
  16. use cdk_http_client::HttpClient as CommonHttpClient;
  17. use cdk_fake_wallet::create_fake_invoice;
  18. use cdk_integration_tests::fund_wallet;
  19. use cdk_sqlite::wallet::memory;
  20. const MINT_URL: &str = "http://127.0.0.1:8087";
  21. const ENV_OIDC_USER: &str = "CDK_TEST_OIDC_USER";
  22. const ENV_OIDC_PASSWORD: &str = "CDK_TEST_OIDC_PASSWORD";
  23. fn get_oidc_credentials() -> (String, String) {
  24. let user = env::var(ENV_OIDC_USER).unwrap_or_else(|_| "test".to_string());
  25. let password = env::var(ENV_OIDC_PASSWORD).unwrap_or_else(|_| "test".to_string());
  26. (user, password)
  27. }
  28. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  29. async fn test_invalid_credentials() {
  30. let db = Arc::new(memory::empty().await.unwrap());
  31. let wallet = WalletBuilder::new()
  32. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  33. .unit(CurrencyUnit::Sat)
  34. .localstore(db.clone())
  35. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  36. .build()
  37. .expect("Wallet");
  38. let mint_info = wallet
  39. .fetch_mint_info()
  40. .await
  41. .expect("mint info")
  42. .expect("could not get mint info");
  43. // Try to get a token with invalid credentials
  44. let token_result =
  45. get_custom_access_token(&mint_info, "invalid_user", "invalid_password").await;
  46. // Should fail with an error
  47. assert!(
  48. token_result.is_err(),
  49. "Expected authentication to fail with invalid credentials"
  50. );
  51. }
  52. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  53. async fn test_quote_status_without_auth() {
  54. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  55. // Test mint quote status
  56. {
  57. let quote_res = client
  58. .get_mint_quote_status("123e4567-e89b-12d3-a456-426614174000")
  59. .await;
  60. assert!(
  61. matches!(quote_res, Err(Error::BlindAuthRequired)),
  62. "Expected AuthRequired error, got {:?}",
  63. quote_res
  64. );
  65. }
  66. // Test melt quote status
  67. {
  68. let quote_res = client
  69. .get_melt_quote_status("123e4567-e89b-12d3-a456-426614174000")
  70. .await;
  71. assert!(
  72. matches!(quote_res, Err(Error::BlindAuthRequired)),
  73. "Expected AuthRequired error, got {:?}",
  74. quote_res
  75. );
  76. }
  77. }
  78. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  79. async fn test_mint_without_auth() {
  80. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  81. {
  82. let request = MintQuoteBolt11Request {
  83. unit: CurrencyUnit::Sat,
  84. amount: 10.into(),
  85. description: None,
  86. pubkey: None,
  87. };
  88. let quote_res = client.post_mint_quote(request).await;
  89. assert!(
  90. matches!(quote_res, Err(Error::BlindAuthRequired)),
  91. "Expected AuthRequired error, got {:?}",
  92. quote_res
  93. );
  94. }
  95. {
  96. let request = MintRequest {
  97. quote: "123e4567-e89b-12d3-a456-426614174000".to_string(),
  98. outputs: vec![],
  99. signature: None,
  100. };
  101. let mint_res = client
  102. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request)
  103. .await;
  104. assert!(
  105. matches!(mint_res, Err(Error::BlindAuthRequired)),
  106. "Expected AuthRequired error, got {:?}",
  107. mint_res
  108. );
  109. }
  110. {
  111. let mint_res = client
  112. .get_mint_quote_status("123e4567-e89b-12d3-a456-426614174000")
  113. .await;
  114. assert!(
  115. matches!(mint_res, Err(Error::BlindAuthRequired)),
  116. "Expected AuthRequired error, got {:?}",
  117. mint_res
  118. );
  119. }
  120. }
  121. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  122. async fn test_mint_bat_without_cat() {
  123. let client = AuthHttpClient::new(MintUrl::from_str(MINT_URL).expect("valid mint url"), None);
  124. let res = client
  125. .post_mint_blind_auth(MintAuthRequest { outputs: vec![] })
  126. .await;
  127. assert!(
  128. matches!(res, Err(Error::ClearAuthRequired)),
  129. "Expected AuthRequired error, got {:?}",
  130. res
  131. );
  132. }
  133. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  134. async fn test_swap_without_auth() {
  135. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  136. let request = SwapRequest::new(vec![], vec![]);
  137. let quote_res = client.post_swap(request).await;
  138. assert!(
  139. matches!(quote_res, Err(Error::BlindAuthRequired)),
  140. "Expected AuthRequired error, got {:?}",
  141. quote_res
  142. );
  143. }
  144. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  145. async fn test_melt_without_auth() {
  146. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  147. // Test melt quote request
  148. {
  149. let request = MeltQuoteBolt11Request {
  150. request: create_fake_invoice(100, "".to_string()),
  151. unit: CurrencyUnit::Sat,
  152. options: None,
  153. };
  154. let quote_res = client.post_melt_quote(request).await;
  155. assert!(
  156. matches!(quote_res, Err(Error::BlindAuthRequired)),
  157. "Expected AuthRequired error, got {:?}",
  158. quote_res
  159. );
  160. }
  161. // Test melt quote
  162. {
  163. let request = MeltQuoteBolt11Request {
  164. request: create_fake_invoice(100, "".to_string()),
  165. unit: CurrencyUnit::Sat,
  166. options: None,
  167. };
  168. let quote_res = client.post_melt_quote(request).await;
  169. assert!(
  170. matches!(quote_res, Err(Error::BlindAuthRequired)),
  171. "Expected AuthRequired error, got {:?}",
  172. quote_res
  173. );
  174. }
  175. // Test melt
  176. {
  177. let request = MeltRequest::new(
  178. "123e4567-e89b-12d3-a456-426614174000".to_string(),
  179. vec![],
  180. None,
  181. );
  182. let melt_res = client
  183. .post_melt(&PaymentMethod::Known(KnownMethod::Bolt11), request)
  184. .await;
  185. assert!(
  186. matches!(melt_res, Err(Error::BlindAuthRequired)),
  187. "Expected AuthRequired error, got {:?}",
  188. melt_res
  189. );
  190. }
  191. // Check melt quote state
  192. {
  193. let melt_res = client
  194. .get_melt_quote_status("123e4567-e89b-12d3-a456-426614174000")
  195. .await;
  196. assert!(
  197. matches!(melt_res, Err(Error::BlindAuthRequired)),
  198. "Expected AuthRequired error, got {:?}",
  199. melt_res
  200. );
  201. }
  202. }
  203. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  204. async fn test_check_without_auth() {
  205. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  206. let request = CheckStateRequest { ys: vec![] };
  207. let quote_res = client.post_check_state(request).await;
  208. assert!(
  209. matches!(quote_res, Err(Error::BlindAuthRequired)),
  210. "Expected AuthRequired error, got {:?}",
  211. quote_res
  212. );
  213. }
  214. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  215. async fn test_restore_without_auth() {
  216. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  217. let request = RestoreRequest { outputs: vec![] };
  218. let restore_res = client.post_restore(request).await;
  219. assert!(
  220. matches!(restore_res, Err(Error::BlindAuthRequired)),
  221. "Expected AuthRequired error, got {:?}",
  222. restore_res
  223. );
  224. }
  225. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  226. async fn test_mint_blind_auth() {
  227. let db = Arc::new(memory::empty().await.unwrap());
  228. let wallet = WalletBuilder::new()
  229. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  230. .unit(CurrencyUnit::Sat)
  231. .localstore(db.clone())
  232. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  233. .build()
  234. .expect("Wallet");
  235. let mint_info = wallet.fetch_mint_info().await.unwrap().unwrap();
  236. let (access_token, _) = get_access_token(&mint_info).await;
  237. wallet.set_cat(access_token).await.unwrap();
  238. wallet
  239. .mint_blind_auth(10.into())
  240. .await
  241. .expect("Could not mint blind auth");
  242. let proofs = wallet
  243. .get_unspent_auth_proofs()
  244. .await
  245. .expect("Could not get auth proofs");
  246. assert!(proofs.len() == 10)
  247. }
  248. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  249. async fn test_mint_with_auth() {
  250. let db = Arc::new(memory::empty().await.unwrap());
  251. let wallet = WalletBuilder::new()
  252. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  253. .unit(CurrencyUnit::Sat)
  254. .localstore(db.clone())
  255. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  256. .build()
  257. .expect("Wallet");
  258. let mint_info = wallet
  259. .fetch_mint_info()
  260. .await
  261. .expect("mint info")
  262. .expect("could not get mint info");
  263. let (access_token, _) = get_access_token(&mint_info).await;
  264. println!("st{}", access_token);
  265. wallet.set_cat(access_token).await.unwrap();
  266. wallet
  267. .mint_blind_auth(10.into())
  268. .await
  269. .expect("Could not mint blind auth");
  270. let wallet = Arc::new(wallet);
  271. let mint_amount: Amount = 100.into();
  272. let quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  273. let proofs = wallet
  274. .wait_and_mint_quote(
  275. quote.clone(),
  276. SplitTarget::default(),
  277. None,
  278. tokio::time::Duration::from_secs(60),
  279. )
  280. .await
  281. .expect("payment");
  282. assert!(proofs.total_amount().expect("Could not get proofs amount") == mint_amount);
  283. }
  284. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  285. async fn test_swap_with_auth() {
  286. let db = Arc::new(memory::empty().await.unwrap());
  287. let wallet = WalletBuilder::new()
  288. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  289. .unit(CurrencyUnit::Sat)
  290. .localstore(db.clone())
  291. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  292. .build()
  293. .expect("Wallet");
  294. let mint_info = wallet.fetch_mint_info().await.unwrap().unwrap();
  295. let (access_token, _) = get_access_token(&mint_info).await;
  296. wallet.set_cat(access_token).await.unwrap();
  297. let wallet = Arc::new(wallet);
  298. wallet.mint_blind_auth(10.into()).await.unwrap();
  299. fund_wallet(wallet.clone(), 100.into()).await;
  300. let proofs = wallet
  301. .get_unspent_proofs()
  302. .await
  303. .expect("Could not get proofs");
  304. let swapped_proofs = wallet
  305. .swap(
  306. Some(proofs.total_amount().unwrap()),
  307. SplitTarget::default(),
  308. proofs.clone(),
  309. None,
  310. false,
  311. )
  312. .await
  313. .expect("Could not swap")
  314. .expect("Could not swap");
  315. let check_spent = wallet
  316. .check_proofs_spent(proofs.clone())
  317. .await
  318. .expect("Could not check proofs");
  319. for state in check_spent {
  320. if state.state != State::Spent {
  321. panic!("Input proofs should be spent");
  322. }
  323. }
  324. assert!(swapped_proofs.total_amount().unwrap() == proofs.total_amount().unwrap())
  325. }
  326. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  327. async fn test_melt_with_auth() {
  328. let db = Arc::new(memory::empty().await.unwrap());
  329. let wallet = WalletBuilder::new()
  330. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  331. .unit(CurrencyUnit::Sat)
  332. .localstore(db.clone())
  333. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  334. .build()
  335. .expect("Wallet");
  336. let mint_info = wallet
  337. .fetch_mint_info()
  338. .await
  339. .expect("Mint info not found")
  340. .expect("Mint info not found");
  341. let (access_token, _) = get_access_token(&mint_info).await;
  342. wallet.set_cat(access_token).await.unwrap();
  343. let wallet = Arc::new(wallet);
  344. wallet.mint_blind_auth(10.into()).await.unwrap();
  345. fund_wallet(wallet.clone(), 100.into()).await;
  346. let bolt11 = create_fake_invoice(2_000, "".to_string());
  347. let melt_quote = wallet
  348. .melt_quote(bolt11.to_string(), None)
  349. .await
  350. .expect("Could not get melt quote");
  351. let after_melt = wallet.melt(&melt_quote.id).await.expect("Could not melt");
  352. assert!(after_melt.state == MeltQuoteState::Paid);
  353. }
  354. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  355. async fn test_mint_auth_over_max() {
  356. let db = Arc::new(memory::empty().await.unwrap());
  357. let wallet = WalletBuilder::new()
  358. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  359. .unit(CurrencyUnit::Sat)
  360. .localstore(db.clone())
  361. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  362. .build()
  363. .expect("Wallet");
  364. let wallet = Arc::new(wallet);
  365. let mint_info = wallet
  366. .fetch_mint_info()
  367. .await
  368. .expect("Mint info not found")
  369. .expect("Mint info not found");
  370. let (access_token, _) = get_access_token(&mint_info).await;
  371. wallet.set_cat(access_token).await.unwrap();
  372. let auth_proofs = wallet
  373. .mint_blind_auth((mint_info.nuts.nut22.expect("Auth enabled").bat_max_mint + 1).into())
  374. .await;
  375. assert!(
  376. matches!(
  377. auth_proofs,
  378. Err(Error::AmountOutofLimitRange(
  379. Amount::ZERO,
  380. Amount::ZERO,
  381. Amount::ZERO,
  382. ))
  383. ),
  384. "Expected amount out of limit error, got {:?}",
  385. auth_proofs
  386. );
  387. }
  388. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  389. async fn test_reuse_auth_proof() {
  390. let db = Arc::new(memory::empty().await.unwrap());
  391. let wallet = WalletBuilder::new()
  392. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  393. .unit(CurrencyUnit::Sat)
  394. .localstore(db.clone())
  395. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  396. .build()
  397. .expect("Wallet");
  398. let mint_info = wallet.fetch_mint_info().await.unwrap().unwrap();
  399. let (access_token, _) = get_access_token(&mint_info).await;
  400. wallet.set_cat(access_token).await.unwrap();
  401. wallet.mint_blind_auth(1.into()).await.unwrap();
  402. let proofs = wallet
  403. .localstore
  404. .get_proofs(None, Some(CurrencyUnit::Auth), None, None)
  405. .await
  406. .unwrap();
  407. assert!(proofs.len() == 1);
  408. {
  409. let quote = wallet
  410. .mint_quote(10.into(), None)
  411. .await
  412. .expect("Quote should be allowed");
  413. assert!(quote.amount == Some(10.into()));
  414. }
  415. wallet
  416. .localstore
  417. .update_proofs(proofs, vec![])
  418. .await
  419. .unwrap();
  420. {
  421. let quote_res = wallet.mint_quote(10.into(), None).await;
  422. assert!(
  423. matches!(quote_res, Err(Error::TokenAlreadySpent)),
  424. "Expected AuthRequired error, got {:?}",
  425. quote_res
  426. );
  427. }
  428. }
  429. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  430. async fn test_melt_with_invalid_auth() {
  431. let db = Arc::new(memory::empty().await.unwrap());
  432. let wallet = WalletBuilder::new()
  433. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  434. .unit(CurrencyUnit::Sat)
  435. .localstore(db.clone())
  436. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  437. .build()
  438. .expect("Wallet");
  439. let mint_info = wallet.fetch_mint_info().await.unwrap().unwrap();
  440. let (access_token, _) = get_access_token(&mint_info).await;
  441. wallet.set_cat(access_token).await.unwrap();
  442. wallet.mint_blind_auth(10.into()).await.unwrap();
  443. fund_wallet(Arc::new(wallet.clone()), 1.into()).await;
  444. let proofs = wallet
  445. .get_unspent_proofs()
  446. .await
  447. .expect("wallet has proofs");
  448. println!("{:#?}", proofs);
  449. let proof = proofs.first().expect("wallet has one proof");
  450. let client = HttpClient::new(MintUrl::from_str(MINT_URL).expect("Valid mint url"), None);
  451. {
  452. let invalid_auth_proof = AuthProof {
  453. keyset_id: proof.keyset_id,
  454. secret: proof.secret.clone(),
  455. c: proof.c,
  456. dleq: proof.dleq.clone(),
  457. };
  458. let _auth_token = AuthToken::BlindAuth(BlindAuthToken::new(invalid_auth_proof));
  459. let request = MintQuoteBolt11Request {
  460. unit: CurrencyUnit::Sat,
  461. amount: 10.into(),
  462. description: None,
  463. pubkey: None,
  464. };
  465. let quote_res = client.post_mint_quote(request).await;
  466. assert!(
  467. matches!(quote_res, Err(Error::BlindAuthRequired)),
  468. "Expected AuthRequired error, got {:?}",
  469. quote_res
  470. );
  471. }
  472. {
  473. let (access_token, _) = get_access_token(&mint_info).await;
  474. wallet.set_cat(access_token).await.unwrap();
  475. }
  476. }
  477. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  478. async fn test_refresh_access_token() {
  479. let db = Arc::new(memory::empty().await.unwrap());
  480. let wallet = WalletBuilder::new()
  481. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  482. .unit(CurrencyUnit::Sat)
  483. .localstore(db.clone())
  484. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  485. .build()
  486. .expect("Wallet");
  487. let mint_info = wallet
  488. .fetch_mint_info()
  489. .await
  490. .expect("mint info")
  491. .expect("could not get mint info");
  492. let (access_token, refresh_token) = get_access_token(&mint_info).await;
  493. // Set the initial access token and refresh token
  494. wallet.set_cat(access_token.clone()).await.unwrap();
  495. wallet
  496. .set_refresh_token(refresh_token.clone())
  497. .await
  498. .unwrap();
  499. // Mint some blind auth tokens with the initial access token
  500. wallet.mint_blind_auth(5.into()).await.unwrap();
  501. // Refresh the access token
  502. wallet.refresh_access_token().await.unwrap();
  503. // Verify we can still perform operations with the refreshed token
  504. let mint_amount: Amount = 10.into();
  505. // Try to mint more blind auth tokens with the refreshed token
  506. let auth_proofs = wallet.mint_blind_auth(5.into()).await.unwrap();
  507. assert_eq!(auth_proofs.len(), 5);
  508. let total_auth_proofs = wallet.get_unspent_auth_proofs().await.unwrap();
  509. assert_eq!(total_auth_proofs.len(), 10); // 5 from before refresh + 5 after refresh
  510. // Try to get a mint quote with the refreshed token
  511. let mint_quote = wallet
  512. .mint_quote(mint_amount, None)
  513. .await
  514. .expect("failed to get mint quote with refreshed token");
  515. assert_eq!(mint_quote.amount, Some(mint_amount));
  516. // Verify the total number of auth tokens
  517. let total_auth_proofs = wallet.get_unspent_auth_proofs().await.unwrap();
  518. assert_eq!(total_auth_proofs.len(), 9); // 5 from before refresh + 5 after refresh - 1 for the quote
  519. }
  520. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  521. async fn test_invalid_refresh_token() {
  522. let db = Arc::new(memory::empty().await.unwrap());
  523. let wallet = WalletBuilder::new()
  524. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  525. .unit(CurrencyUnit::Sat)
  526. .localstore(db.clone())
  527. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  528. .build()
  529. .expect("Wallet");
  530. let mint_info = wallet
  531. .fetch_mint_info()
  532. .await
  533. .expect("mint info")
  534. .expect("could not get mint info");
  535. let (access_token, _) = get_access_token(&mint_info).await;
  536. // Set the initial access token
  537. wallet.set_cat(access_token.clone()).await.unwrap();
  538. // Set an invalid refresh token
  539. wallet
  540. .set_refresh_token("invalid_refresh_token".to_string())
  541. .await
  542. .unwrap();
  543. // Attempt to refresh the access token with an invalid refresh token
  544. let refresh_result = wallet.refresh_access_token().await;
  545. // Should fail with an error
  546. assert!(refresh_result.is_err(), "Expected refresh token error");
  547. }
  548. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  549. async fn test_auth_token_spending_order() {
  550. let db = Arc::new(memory::empty().await.unwrap());
  551. let wallet = WalletBuilder::new()
  552. .mint_url(MintUrl::from_str(MINT_URL).expect("Valid mint url"))
  553. .unit(CurrencyUnit::Sat)
  554. .localstore(db.clone())
  555. .seed(Mnemonic::generate(12).unwrap().to_seed_normalized(""))
  556. .build()
  557. .expect("Wallet");
  558. let mint_info = wallet
  559. .fetch_mint_info()
  560. .await
  561. .expect("mint info")
  562. .expect("could not get mint info");
  563. let (access_token, _) = get_access_token(&mint_info).await;
  564. wallet.set_cat(access_token).await.unwrap();
  565. // Mint auth tokens in two batches to test ordering
  566. wallet.mint_blind_auth(2.into()).await.unwrap();
  567. // Get the first batch of auth proofs
  568. let first_batch = wallet.get_unspent_auth_proofs().await.unwrap();
  569. assert_eq!(first_batch.len(), 2);
  570. // Mint a second batch
  571. wallet.mint_blind_auth(3.into()).await.unwrap();
  572. // Get all auth proofs
  573. let all_proofs = wallet.get_unspent_auth_proofs().await.unwrap();
  574. assert_eq!(all_proofs.len(), 5);
  575. // Use tokens and verify they're used in the expected order (FIFO)
  576. for i in 0..3 {
  577. let mint_quote = wallet
  578. .mint_quote(10.into(), None)
  579. .await
  580. .expect("failed to get mint quote");
  581. assert_eq!(mint_quote.amount, Some(10.into()));
  582. // Check remaining tokens after each operation
  583. let remaining = wallet.get_unspent_auth_proofs().await.unwrap();
  584. assert_eq!(
  585. remaining.len(),
  586. 5 - (i + 1),
  587. "Expected {} remaining auth tokens after {} operations",
  588. 5 - (i + 1),
  589. i + 1
  590. );
  591. }
  592. }
  593. async fn get_access_token(mint_info: &MintInfo) -> (String, String) {
  594. let openid_discovery = mint_info
  595. .nuts
  596. .nut21
  597. .clone()
  598. .expect("Nut21 defined")
  599. .openid_discovery;
  600. let oidc_client = OidcClient::new(openid_discovery, None);
  601. // Get the token endpoint from the OIDC configuration
  602. let token_url = oidc_client
  603. .get_oidc_config()
  604. .await
  605. .expect("Failed to get OIDC config")
  606. .token_endpoint;
  607. // Create the request parameters
  608. let (user, password) = get_oidc_credentials();
  609. let params = [
  610. ("grant_type", "password"),
  611. ("client_id", "cashu-client"),
  612. ("username", &user),
  613. ("password", &password),
  614. ];
  615. // Make the token request directly
  616. let client = CommonHttpClient::new();
  617. let token_response: serde_json::Value = client
  618. .post(&token_url)
  619. .form(&params)
  620. .send()
  621. .await
  622. .expect("Failed to send token request")
  623. .json()
  624. .await
  625. .expect("Failed to parse token response");
  626. let access_token = token_response["access_token"]
  627. .as_str()
  628. .expect("No access token in response")
  629. .to_string();
  630. let refresh_token = token_response["refresh_token"]
  631. .as_str()
  632. .expect("No access token in response")
  633. .to_string();
  634. (access_token, refresh_token)
  635. }
  636. /// Get a new access token with custom credentials
  637. async fn get_custom_access_token(
  638. mint_info: &MintInfo,
  639. username: &str,
  640. password: &str,
  641. ) -> Result<(String, String), Error> {
  642. let openid_discovery = mint_info
  643. .nuts
  644. .nut21
  645. .clone()
  646. .expect("Nut21 defined")
  647. .openid_discovery;
  648. let oidc_client = OidcClient::new(openid_discovery, None);
  649. // Get the token endpoint from the OIDC configuration
  650. let token_url = oidc_client
  651. .get_oidc_config()
  652. .await
  653. .map_err(|_| Error::Custom("Failed to get OIDC config".to_string()))?
  654. .token_endpoint;
  655. // Create the request parameters
  656. let params = [
  657. ("grant_type", "password"),
  658. ("client_id", "cashu-client"),
  659. ("username", username),
  660. ("password", password),
  661. ];
  662. // Make the token request directly
  663. let client = CommonHttpClient::new();
  664. let response = client
  665. .post(&token_url)
  666. .form(&params)
  667. .send()
  668. .await
  669. .map_err(|_| Error::Custom("Failed to send token request".to_string()))?;
  670. if !response.is_success() {
  671. return Err(Error::Custom(format!(
  672. "Token request failed with status: {}",
  673. response.status()
  674. )));
  675. }
  676. let token_response: serde_json::Value = response
  677. .json()
  678. .await
  679. .map_err(|_| Error::Custom("Failed to parse token response".to_string()))?;
  680. let access_token = token_response["access_token"]
  681. .as_str()
  682. .ok_or_else(|| Error::Custom("No access token in response".to_string()))?
  683. .to_string();
  684. let refresh_token = token_response["refresh_token"]
  685. .as_str()
  686. .ok_or_else(|| Error::Custom("No refresh token in response".to_string()))?
  687. .to_string();
  688. Ok((access_token, refresh_token))
  689. }