custom_handlers.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. //! Generic handlers for custom payment methods
  2. //!
  3. //! These handlers work for ANY custom payment method without requiring
  4. //! method-specific validation or request parsing.
  5. //!
  6. //! Special handling for bolt11 and bolt12:
  7. //! When the method parameter is "bolt11" or "bolt12", these handlers use the
  8. //! specific Bolt11/Bolt12 request/response types instead of the generic custom types.
  9. use axum::extract::{FromRequestParts, Json, Path, State};
  10. use axum::http::request::Parts;
  11. use axum::http::StatusCode;
  12. use axum::response::{IntoResponse, Response};
  13. use cdk::mint::QuoteId;
  14. use cdk::nuts::nut21::{Method, ProtectedEndpoint, RoutePath};
  15. use cdk::nuts::{
  16. MeltQuoteBolt11Request, MeltQuoteBolt11Response, MeltQuoteBolt12Request,
  17. MeltQuoteCustomRequest, MintQuoteBolt11Request, MintQuoteBolt11Response,
  18. MintQuoteBolt12Request, MintQuoteBolt12Response, MintQuoteCustomRequest, MintRequest,
  19. MintResponse,
  20. };
  21. use serde_json::Value;
  22. use tracing::instrument;
  23. use crate::auth::AuthHeader;
  24. use crate::router_handlers::into_response;
  25. use crate::MintState;
  26. const PREFER_HEADER_KEY: &str = "Prefer";
  27. /// Header extractor for the Prefer header
  28. ///
  29. /// This extractor checks for the `Prefer: respond-async` header
  30. /// to determine if the client wants asynchronous processing
  31. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  32. pub struct PreferHeader {
  33. pub respond_async: bool,
  34. }
  35. impl<S> FromRequestParts<S> for PreferHeader
  36. where
  37. S: Send + Sync,
  38. {
  39. type Rejection = (StatusCode, String);
  40. async fn from_request_parts(
  41. parts: &mut Parts,
  42. _state: &S,
  43. ) -> anyhow::Result<Self, Self::Rejection> {
  44. // Check for Prefer header
  45. if let Some(prefer_value) = parts.headers.get(PREFER_HEADER_KEY) {
  46. let value = prefer_value.to_str().map_err(|_| {
  47. (
  48. StatusCode::BAD_REQUEST,
  49. "Invalid Prefer header value".to_string(),
  50. )
  51. })?;
  52. // Check if it contains "respond-async"
  53. let respond_async = value.to_lowercase().contains("respond-async");
  54. return Ok(PreferHeader { respond_async });
  55. }
  56. // No Prefer header found - default to synchronous processing
  57. Ok(PreferHeader {
  58. respond_async: false,
  59. })
  60. }
  61. }
  62. /// Generic handler for custom payment method mint quotes
  63. ///
  64. /// This handler works for ANY custom payment method (e.g., paypal, venmo, cashapp, bolt11, bolt12).
  65. /// For bolt11/bolt12, it handles the specific request/response types.
  66. /// For other methods, it passes the request data directly to the payment processor.
  67. #[instrument(skip_all, fields(method = ?method))]
  68. pub async fn post_mint_custom_quote(
  69. auth: AuthHeader,
  70. State(state): State<MintState>,
  71. Path(method): Path<String>,
  72. Json(payload): Json<Value>,
  73. ) -> Result<Response, Response> {
  74. state
  75. .mint
  76. .verify_auth(
  77. auth.into(),
  78. &ProtectedEndpoint::new(Method::Post, RoutePath::MintQuote(method.clone())),
  79. )
  80. .await
  81. .map_err(into_response)?;
  82. match method.as_str() {
  83. "bolt11" => {
  84. let bolt11_request: MintQuoteBolt11Request =
  85. serde_json::from_value(payload).map_err(|e| {
  86. tracing::error!("Failed to parse bolt11 request: {}", e);
  87. into_response(cdk::Error::InvalidPaymentMethod)
  88. })?;
  89. let quote = state
  90. .mint
  91. .get_mint_quote(bolt11_request.into())
  92. .await
  93. .map_err(into_response)?;
  94. let response: MintQuoteBolt11Response<QuoteId> =
  95. quote.try_into().map_err(into_response)?;
  96. Ok(Json(response).into_response())
  97. }
  98. "bolt12" => {
  99. let bolt12_request: MintQuoteBolt12Request =
  100. serde_json::from_value(payload).map_err(|e| {
  101. tracing::error!("Failed to parse bolt12 request: {}", e);
  102. into_response(cdk::Error::InvalidPaymentMethod)
  103. })?;
  104. let quote = state
  105. .mint
  106. .get_mint_quote(bolt12_request.into())
  107. .await
  108. .map_err(into_response)?;
  109. let response: MintQuoteBolt12Response<QuoteId> =
  110. quote.try_into().map_err(into_response)?;
  111. Ok(Json(response).into_response())
  112. }
  113. _ => {
  114. let custom_request: MintQuoteCustomRequest =
  115. serde_json::from_value(payload).map_err(|e| {
  116. tracing::error!("Failed to parse custom request: {}", e);
  117. into_response(cdk::Error::InvalidPaymentMethod)
  118. })?;
  119. let quote_request = cdk::mint::MintQuoteRequest::Custom {
  120. method,
  121. request: custom_request,
  122. };
  123. let response = state
  124. .mint
  125. .get_mint_quote(quote_request)
  126. .await
  127. .map_err(into_response)?;
  128. match response {
  129. cdk::mint::MintQuoteResponse::Custom { response, .. } => {
  130. Ok(Json(response).into_response())
  131. }
  132. _ => Err(into_response(cdk::Error::InvalidPaymentMethod)),
  133. }
  134. }
  135. }
  136. }
  137. /// Get custom payment method mint quote status
  138. #[instrument(skip_all, fields(method = ?method, quote_id = ?quote_id))]
  139. pub async fn get_check_mint_custom_quote(
  140. auth: AuthHeader,
  141. State(state): State<MintState>,
  142. Path((method, quote_id)): Path<(String, QuoteId)>,
  143. ) -> Result<Response, Response> {
  144. state
  145. .mint
  146. .verify_auth(
  147. auth.into(),
  148. &ProtectedEndpoint::new(Method::Get, RoutePath::MintQuote(method.clone())),
  149. )
  150. .await
  151. .map_err(into_response)?;
  152. let quote_response = state
  153. .mint
  154. .check_mint_quote(&quote_id)
  155. .await
  156. .map_err(into_response)?;
  157. match method.as_str() {
  158. "bolt11" => {
  159. let response: MintQuoteBolt11Response<QuoteId> =
  160. quote_response.try_into().map_err(into_response)?;
  161. Ok(Json(response).into_response())
  162. }
  163. "bolt12" => {
  164. let response: MintQuoteBolt12Response<QuoteId> =
  165. quote_response.try_into().map_err(into_response)?;
  166. Ok(Json(response).into_response())
  167. }
  168. _ => {
  169. // Extract and verify it's a Custom payment method
  170. match quote_response {
  171. cdk::mint::MintQuoteResponse::Custom {
  172. method: quote_method,
  173. response,
  174. } => {
  175. if quote_method != method {
  176. return Err(into_response(cdk::Error::InvalidPaymentMethod));
  177. }
  178. Ok(Json(response).into_response())
  179. }
  180. _ => Err(into_response(cdk::Error::InvalidPaymentMethod)),
  181. }
  182. }
  183. }
  184. }
  185. /// Mint tokens with custom payment method
  186. #[instrument(skip_all, fields(method = ?method, quote_id = ?payload.quote))]
  187. pub async fn post_mint_custom(
  188. auth: AuthHeader,
  189. State(state): State<MintState>,
  190. Path(method): Path<String>,
  191. Json(payload): Json<MintRequest<QuoteId>>,
  192. ) -> Result<Json<MintResponse>, Response> {
  193. state
  194. .mint
  195. .verify_auth(
  196. auth.into(),
  197. &ProtectedEndpoint::new(Method::Post, RoutePath::Mint(method.clone())),
  198. )
  199. .await
  200. .map_err(into_response)?;
  201. // Note: process_mint_request will validate the quote internally
  202. // including checking if it's paid and matches the expected payment method
  203. let res = state
  204. .mint
  205. .process_mint_request(payload)
  206. .await
  207. .map_err(into_response)?;
  208. Ok(Json(res))
  209. }
  210. /// Request a melt quote for custom payment method
  211. #[instrument(skip_all, fields(method = ?method))]
  212. pub async fn post_melt_custom_quote(
  213. auth: AuthHeader,
  214. State(state): State<MintState>,
  215. Path(method): Path<String>,
  216. Json(payload): Json<Value>,
  217. ) -> Result<Json<MeltQuoteBolt11Response<QuoteId>>, Response> {
  218. state
  219. .mint
  220. .verify_auth(
  221. auth.into(),
  222. &ProtectedEndpoint::new(Method::Post, RoutePath::MeltQuote(method.clone())),
  223. )
  224. .await
  225. .map_err(into_response)?;
  226. let response = match method.as_str() {
  227. "bolt11" => {
  228. let bolt11_request: MeltQuoteBolt11Request =
  229. serde_json::from_value(payload).map_err(|e| {
  230. tracing::error!("Failed to parse bolt11 melt request: {}", e);
  231. into_response(cdk::Error::InvalidPaymentMethod)
  232. })?;
  233. state
  234. .mint
  235. .get_melt_quote(bolt11_request.into())
  236. .await
  237. .map_err(into_response)?
  238. }
  239. "bolt12" => {
  240. let bolt12_request: MeltQuoteBolt12Request =
  241. serde_json::from_value(payload).map_err(|e| {
  242. tracing::error!("Failed to parse bolt12 melt request: {}", e);
  243. into_response(cdk::Error::InvalidPaymentMethod)
  244. })?;
  245. state
  246. .mint
  247. .get_melt_quote(bolt12_request.into())
  248. .await
  249. .map_err(into_response)?
  250. }
  251. _ => {
  252. let custom_request: MeltQuoteCustomRequest =
  253. serde_json::from_value(payload).map_err(|e| {
  254. tracing::error!("Failed to parse custom melt request: {}", e);
  255. into_response(cdk::Error::InvalidPaymentMethod)
  256. })?;
  257. state
  258. .mint
  259. .get_melt_quote(custom_request.into())
  260. .await
  261. .map_err(into_response)?
  262. }
  263. };
  264. Ok(Json(response))
  265. }
  266. /// Get custom payment method melt quote status
  267. #[instrument(skip_all, fields(method = ?method, quote_id = ?quote_id))]
  268. pub async fn get_check_melt_custom_quote(
  269. auth: AuthHeader,
  270. State(state): State<MintState>,
  271. Path((method, quote_id)): Path<(String, QuoteId)>,
  272. ) -> Result<Json<MeltQuoteBolt11Response<QuoteId>>, Response> {
  273. state
  274. .mint
  275. .verify_auth(
  276. auth.into(),
  277. &ProtectedEndpoint::new(Method::Get, RoutePath::MeltQuote(method.clone())),
  278. )
  279. .await
  280. .map_err(into_response)?;
  281. // Note: check_melt_quote returns the response directly
  282. // The payment method validation is done when the quote was created
  283. let quote = state
  284. .mint
  285. .check_melt_quote(&quote_id)
  286. .await
  287. .map_err(into_response)?;
  288. Ok(Json(quote))
  289. }
  290. /// Melt tokens with custom payment method
  291. #[instrument(skip_all, fields(method = ?method))]
  292. pub async fn post_melt_custom(
  293. auth: AuthHeader,
  294. prefer: PreferHeader,
  295. State(state): State<MintState>,
  296. Path(method): Path<String>,
  297. Json(payload): Json<cdk::nuts::MeltRequest<QuoteId>>,
  298. ) -> Result<Json<MeltQuoteBolt11Response<QuoteId>>, Response> {
  299. state
  300. .mint
  301. .verify_auth(
  302. auth.into(),
  303. &ProtectedEndpoint::new(Method::Post, RoutePath::Melt(method.clone())),
  304. )
  305. .await
  306. .map_err(into_response)?;
  307. let res = if prefer.respond_async {
  308. // Asynchronous processing - return immediately after setup
  309. state
  310. .mint
  311. .melt_async(&payload)
  312. .await
  313. .map_err(into_response)?
  314. } else {
  315. // Synchronous processing - wait for completion
  316. state.mint.melt(&payload).await.map_err(into_response)?
  317. };
  318. Ok(Json(res))
  319. }
  320. // ============================================================================
  321. // CACHED HANDLERS FOR NUT-19 SUPPORT
  322. // ============================================================================
  323. /// Cached version of post_mint_custom for NUT-19 caching support
  324. #[instrument(skip_all, fields(method = ?method, quote_id = ?payload.quote))]
  325. pub async fn cache_post_mint_custom(
  326. auth: AuthHeader,
  327. state: State<MintState>,
  328. method: Path<String>,
  329. payload: Json<MintRequest<QuoteId>>,
  330. ) -> Result<Json<MintResponse>, Response> {
  331. use std::ops::Deref;
  332. let State(mint_state) = state.clone();
  333. let json_extracted_payload = payload.deref();
  334. let cache_key = match mint_state.cache.calculate_key(json_extracted_payload) {
  335. Some(key) => key,
  336. None => {
  337. // Could not calculate key, just return the handler result
  338. return post_mint_custom(auth, state, method, payload).await;
  339. }
  340. };
  341. if let Some(cached_response) = mint_state.cache.get::<MintResponse>(&cache_key).await {
  342. return Ok(Json(cached_response));
  343. }
  344. let result = post_mint_custom(auth, state, method, payload).await?;
  345. // Cache the response
  346. mint_state.cache.set(cache_key, result.deref()).await;
  347. Ok(result)
  348. }
  349. #[cfg(test)]
  350. mod tests {
  351. use axum::http::{HeaderValue, Request, StatusCode};
  352. use super::*;
  353. fn create_test_request(prefer_header: Option<&str>) -> Request<()> {
  354. let mut req = Request::builder()
  355. .method("POST")
  356. .uri("/test")
  357. .body(())
  358. .unwrap();
  359. if let Some(header_value) = prefer_header {
  360. req.headers_mut().insert(
  361. PREFER_HEADER_KEY,
  362. HeaderValue::from_str(header_value).unwrap(),
  363. );
  364. }
  365. req
  366. }
  367. fn create_test_request_with_bytes(bytes: &[u8]) -> Request<()> {
  368. let mut req = Request::builder()
  369. .method("POST")
  370. .uri("/test")
  371. .body(())
  372. .unwrap();
  373. req.headers_mut()
  374. .insert(PREFER_HEADER_KEY, HeaderValue::from_bytes(bytes).unwrap());
  375. req
  376. }
  377. #[tokio::test]
  378. async fn test_prefer_header_respond_async() {
  379. let req = create_test_request(Some("respond-async"));
  380. let (mut parts, _) = req.into_parts();
  381. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  382. assert!(result.is_ok());
  383. assert!(result.unwrap().respond_async);
  384. }
  385. #[tokio::test]
  386. async fn test_prefer_header_respond_async_with_other_values() {
  387. let req = create_test_request(Some("respond-async; wait=10"));
  388. let (mut parts, _) = req.into_parts();
  389. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  390. assert!(result.is_ok());
  391. assert!(result.unwrap().respond_async);
  392. }
  393. #[tokio::test]
  394. async fn test_prefer_header_case_insensitive() {
  395. let req = create_test_request(Some("RESPOND-ASYNC"));
  396. let (mut parts, _) = req.into_parts();
  397. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  398. assert!(result.is_ok());
  399. assert!(result.unwrap().respond_async);
  400. }
  401. #[tokio::test]
  402. async fn test_prefer_header_no_respond_async() {
  403. let req = create_test_request(Some("wait=10"));
  404. let (mut parts, _) = req.into_parts();
  405. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  406. assert!(result.is_ok());
  407. assert!(!result.unwrap().respond_async);
  408. }
  409. #[tokio::test]
  410. async fn test_prefer_header_missing() {
  411. let req = create_test_request(None);
  412. let (mut parts, _) = req.into_parts();
  413. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  414. assert!(result.is_ok());
  415. assert!(!result.unwrap().respond_async);
  416. }
  417. #[tokio::test]
  418. async fn test_prefer_header_invalid_value() {
  419. let req = create_test_request_with_bytes(&[0xFF, 0xFE]);
  420. let (mut parts, _) = req.into_parts();
  421. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  422. assert!(result.is_err());
  423. let (status, message) = result.unwrap_err();
  424. assert_eq!(status, StatusCode::BAD_REQUEST);
  425. assert_eq!(message, "Invalid Prefer header value");
  426. }
  427. #[tokio::test]
  428. async fn test_prefer_header_empty_value() {
  429. let req = create_test_request(Some(""));
  430. let (mut parts, _) = req.into_parts();
  431. let result = PreferHeader::from_request_parts(&mut parts, &()).await;
  432. assert!(result.is_ok());
  433. assert!(!result.unwrap().respond_async);
  434. }
  435. }
  436. /// Cached version of post_melt_custom for NUT-19 caching support
  437. #[instrument(skip_all, fields(method = ?method))]
  438. pub async fn cache_post_melt_custom(
  439. auth: AuthHeader,
  440. prefer: PreferHeader,
  441. state: State<MintState>,
  442. method: Path<String>,
  443. payload: Json<cdk::nuts::MeltRequest<QuoteId>>,
  444. ) -> Result<Json<MeltQuoteBolt11Response<QuoteId>>, Response> {
  445. use std::ops::Deref;
  446. let State(mint_state) = state.clone();
  447. let json_extracted_payload = payload.deref();
  448. let cache_key = match mint_state.cache.calculate_key(json_extracted_payload) {
  449. Some(key) => key,
  450. None => {
  451. // Could not calculate key, just return the handler result
  452. return post_melt_custom(auth, prefer, state, method, payload).await;
  453. }
  454. };
  455. if let Some(cached_response) = mint_state
  456. .cache
  457. .get::<MeltQuoteBolt11Response<QuoteId>>(&cache_key)
  458. .await
  459. {
  460. return Ok(Json(cached_response));
  461. }
  462. let result = post_melt_custom(auth, prefer, state, method, payload).await?;
  463. // Cache the response
  464. mint_state.cache.set(cache_key, result.deref()).await;
  465. Ok(result)
  466. }