fake_auth.rs 25 KB

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