mpp 0.15.0

Rust SDK for the Machine Payments Protocol (MPP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
//! Tower middleware for payment gating.
//!
//! Provides a [`PaymentLayer`] that wraps the 402 challenge/verify flow
//! into a standard Tower `Layer`/`Service`, compatible with axum, tonic,
//! and any Tower-based framework.
//!
//! # Example (axum)
//!
#![cfg_attr(feature = "tempo", doc = "```no_run")]
#![cfg_attr(not(feature = "tempo"), doc = "```ignore")]
//! use axum::{routing::get, Router};
//! use mpp::server::middleware::PaymentLayer;
//! use mpp::server::{tempo, Mpp, TempoConfig};
//!
//! # fn main() -> mpp::Result<()> {
//! let mpp = Mpp::create(tempo(TempoConfig {
//!     recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f1B0F2",
//! }))?;
//!
//! let app: Router = Router::new()
//!     .route("/premium", get(|| async { "paid content" }))
//!     .route_layer(PaymentLayer::charge(&mpp, "0.10")?);
//! # Ok(())
//! # }
//! ```
//!
//! Prefer axum's `route_layer` over `layer`: `layer` also wraps the fallback,
//! so requests for unknown paths are answered with 402 instead of 404. Apply
//! CORS handling outside the payment layer so preflight requests, which never
//! carry credentials, are answered before payment is checked.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use bytes::Bytes;
use http_body_util::BodyExt;
use http_types::{header, HeaderValue, Request, Response, StatusCode};

use crate::error::{MppError, PaymentError};
use crate::protocol::core::headers::{
    extract_payment_scheme, format_receipt, format_www_authenticate_many, parse_authorization,
    with_private_cache_control, PAYMENT_RECEIPT_HEADER, WWW_AUTHENTICATE_HEADER,
};

/// Trait for payment verification in middleware context.
///
/// This abstracts over the `Mpp` type's generics so the middleware
/// can be used without propagating generic parameters.
pub trait PaymentVerifier: Send + Sync + 'static {
    /// Generate a `WWW-Authenticate: Payment ...` challenge header value.
    fn challenge(&self) -> Result<String, String>;

    /// Generate a body-bound `WWW-Authenticate: Payment ...` challenge header value.
    fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
        let _ = body;
        self.challenge()
    }

    /// Verify a credential string and return a `Payment-Receipt` header value.
    ///
    /// The `credential` is the raw Payment credential header value
    /// (e.g., `"Payment eyJ..."` including the scheme prefix).
    fn verify(
        &self,
        credential: &str,
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>>;

    /// Verify a credential string against the actual request body bytes.
    fn verify_with_body(
        &self,
        credential: &str,
        body: &[u8],
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
        let _ = body;
        self.verify(credential)
    }

    /// Verify a credential string, against the request body bytes when the
    /// layer is body-bound, keeping the failure typed.
    ///
    /// The layers call this method and answer a failure by its kind: a
    /// payment problem gets a fresh challenge, a server-side failure a `500`
    /// without one. The default delegates to [`verify`](Self::verify) and
    /// [`verify_with_body`](Self::verify_with_body) and reports every failure
    /// as `verification-failed`.
    fn verify_credential(
        &self,
        credential: &str,
        body: Option<&[u8]>,
    ) -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>> {
        let verified = match body {
            Some(body) => self.verify_with_body(credential, body),
            None => self.verify(credential),
        };
        Box::pin(async move { verified.await.map_err(MppError::verification_failed) })
    }

    /// HTTP field containing the Payment credential.
    ///
    /// Defaults to `Authorization`. Servers created with `requires_auth`
    /// return `Payment-Authorization`.
    fn credential_header(&self) -> &str {
        header::AUTHORIZATION.as_str()
    }
}

// ==================== FnVerifier ====================

/// A [`PaymentVerifier`] built from closures.
#[allow(clippy::type_complexity)]
pub struct FnVerifier {
    challenge_fn: Box<dyn Fn() -> Result<String, String> + Send + Sync>,
    challenge_with_body_fn: Option<Box<dyn Fn(&[u8]) -> Result<String, String> + Send + Sync>>,
    verify_fn: Box<
        dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>>
            + Send
            + Sync,
    >,
    verify_with_body_fn: Option<
        Box<
            dyn Fn(String, Vec<u8>) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>>
                + Send
                + Sync,
        >,
    >,
}

impl PaymentVerifier for FnVerifier {
    fn challenge(&self) -> Result<String, String> {
        (self.challenge_fn)()
    }

    fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
        match &self.challenge_with_body_fn {
            Some(f) => f(body),
            None => self.challenge(),
        }
    }

    fn verify(
        &self,
        credential: &str,
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
        (self.verify_fn)(credential.to_string())
    }

    fn verify_with_body(
        &self,
        credential: &str,
        body: &[u8],
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
        match &self.verify_with_body_fn {
            Some(f) => f(credential.to_string(), body.to_vec()),
            None => self.verify(credential),
        }
    }
}

// ==================== PaymentLayer ====================

/// Tower [`Layer`](tower_layer::Layer) that gates requests behind payment verification.
///
/// Requests without a valid `Authorization: Payment ...` header receive
/// a `402 Payment Required` response with a `WWW-Authenticate` challenge.
/// Valid payments are verified and a `Payment-Receipt` header is attached
/// to the inner service's response.
///
/// A credential that cannot be verified because of a server-side failure
/// (RPC, store) is answered with `500` and no challenge, so the client does
/// not pay again. The layer is generic over the response body, so its own
/// responses have an empty body and carry no problem details.
pub struct PaymentLayer<V> {
    verifier: Arc<V>,
}

impl<V> Clone for PaymentLayer<V> {
    fn clone(&self) -> Self {
        Self {
            verifier: Arc::clone(&self.verifier),
        }
    }
}

impl<V: PaymentVerifier> PaymentLayer<V> {
    /// Create a payment layer with a custom [`PaymentVerifier`].
    pub fn new(verifier: V) -> Self {
        Self {
            verifier: Arc::new(verifier),
        }
    }
}

impl PaymentLayer<FnVerifier> {
    /// Create a payment layer from challenge/verify closures.
    pub fn from_fns(
        challenge_fn: impl Fn() -> Result<String, String> + Send + Sync + 'static,
        verify_fn: impl Fn(String) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>>
            + Send
            + Sync
            + 'static,
    ) -> Self {
        Self::new(FnVerifier {
            challenge_fn: Box::new(challenge_fn),
            challenge_with_body_fn: None,
            verify_fn: Box::new(verify_fn),
            verify_with_body_fn: None,
        })
    }
}

impl<S, V: PaymentVerifier> tower_layer::Layer<S> for PaymentLayer<V> {
    type Service = PaymentService<S, V>;

    fn layer(&self, inner: S) -> Self::Service {
        PaymentService {
            inner,
            verifier: Arc::clone(&self.verifier),
        }
    }
}

// ==================== PaymentService ====================

/// Tower [`Service`](tower_service::Service) that wraps an inner service with payment verification.
pub struct PaymentService<S, V> {
    inner: S,
    verifier: Arc<V>,
}

impl<S: Clone, V> Clone for PaymentService<S, V> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            verifier: Arc::clone(&self.verifier),
        }
    }
}

impl<S, V, ReqBody, ResBody> tower_service::Service<Request<ReqBody>> for PaymentService<S, V>
where
    S: tower_service::Service<Request<ReqBody>, Response = Response<ResBody>>
        + Clone
        + Send
        + 'static,
    S::Future: Send,
    S::Error: Send,
    V: PaymentVerifier,
    ReqBody: Send + 'static,
    ResBody: Default + Send + 'static,
{
    type Response = Response<ResBody>;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Response<ResBody>, S::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        let verifier = Arc::clone(&self.verifier);
        // Keep a clone in `self` for future poll_ready cycles and call the
        // currently-ready service instance moved out of `self`.
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);

        Box::pin(async move {
            // Extract the Payment credential from the header selected by the challenge.
            let auth_header = req
                .headers()
                .get(verifier.credential_header())
                .and_then(|v| v.to_str().ok())
                .and_then(extract_payment_scheme)
                .map(|s| s.to_string());

            let credential = match auth_header {
                Some(c) => c,
                None => {
                    // No credential — return a fresh, retryable 402 challenge.
                    return Ok(match verifier.challenge() {
                        Ok(challenge) => {
                            challenge_response(StatusCode::PAYMENT_REQUIRED, &challenge)
                        }
                        Err(e) => error_response(
                            StatusCode::INTERNAL_SERVER_ERROR,
                            &format!("Failed to generate challenge: {}", e),
                        ),
                    });
                }
            };

            // Verify the credential.
            let receipt_header = match verifier.verify_credential(&credential, None).await {
                Ok(r) => r,
                Err(error) => return Ok(rejection_response(&error, || verifier.challenge())),
            };

            // Call the inner service.
            let mut resp = inner.call(req).await?;
            attach_receipt(&mut resp, &receipt_header);

            Ok(resp)
        })
    }
}

// ==================== PaymentBodyLayer ====================

/// Default cap on the request body bytes buffered by [`PaymentBodyLayer`],
/// matching axum's `DefaultBodyLimit`.
const DEFAULT_MAX_BODY_BYTES: usize = 2 * 1024 * 1024;

/// Tower [`Layer`](tower_layer::Layer) that binds payment verification to request body bytes.
///
/// The request body is buffered, used for body-digest challenge/verification,
/// and then replayed to the inner service as `http_body_util::Full<Bytes>`.
///
/// Buffering happens before any payment is made, so bodies larger than
/// [`max_body_bytes`](Self::max_body_bytes) (2 MiB by default) are rejected
/// with `413 Payload Too Large`.
pub struct PaymentBodyLayer<V> {
    verifier: Arc<V>,
    max_body_bytes: usize,
}

impl<V> Clone for PaymentBodyLayer<V> {
    fn clone(&self) -> Self {
        Self {
            verifier: Arc::clone(&self.verifier),
            max_body_bytes: self.max_body_bytes,
        }
    }
}

impl<V: PaymentVerifier> PaymentBodyLayer<V> {
    /// Create a body-aware payment layer with a custom [`PaymentVerifier`].
    pub fn new(verifier: V) -> Self {
        Self {
            verifier: Arc::new(verifier),
            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
        }
    }
}

impl<V> PaymentBodyLayer<V> {
    /// Set the maximum number of request body bytes to buffer.
    ///
    /// Defaults to 2 MiB.
    pub fn max_body_bytes(mut self, max_body_bytes: usize) -> Self {
        self.max_body_bytes = max_body_bytes;
        self
    }
}

impl<S, V: PaymentVerifier> tower_layer::Layer<S> for PaymentBodyLayer<V> {
    type Service = PaymentBodyService<S, V>;

    fn layer(&self, inner: S) -> Self::Service {
        PaymentBodyService {
            inner,
            verifier: Arc::clone(&self.verifier),
            max_body_bytes: self.max_body_bytes,
        }
    }
}

/// Tower [`Service`](tower_service::Service) for body-bound payment verification.
pub struct PaymentBodyService<S, V> {
    inner: S,
    verifier: Arc<V>,
    max_body_bytes: usize,
}

impl<S: Clone, V> Clone for PaymentBodyService<S, V> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            verifier: Arc::clone(&self.verifier),
            max_body_bytes: self.max_body_bytes,
        }
    }
}

impl<S, V, ReqBody, ResBody> tower_service::Service<Request<ReqBody>> for PaymentBodyService<S, V>
where
    S: tower_service::Service<Request<http_body_util::Full<Bytes>>, Response = Response<ResBody>>
        + Clone
        + Send
        + 'static,
    S::Future: Send,
    S::Error: Send,
    V: PaymentVerifier,
    ReqBody: http_body::Body<Data = Bytes> + Send + 'static,
    ReqBody::Error: std::fmt::Display + Send + Sync + 'static,
    ResBody: Default + Send + 'static,
{
    type Response = Response<ResBody>;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Response<ResBody>, S::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        let verifier = Arc::clone(&self.verifier);
        let max_body_bytes = self.max_body_bytes;
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);

        Box::pin(async move {
            let (parts, body) = req.into_parts();
            let body =
                http_body_util::Limited::new(body.map_err(|e| e.to_string()), max_body_bytes);
            let body = match body.collect().await {
                Ok(collected) => collected.to_bytes(),
                Err(e) if e.is::<http_body_util::LengthLimitError>() => {
                    return Ok(error_response(
                        StatusCode::PAYLOAD_TOO_LARGE,
                        "Request body too large",
                    ));
                }
                Err(e) => {
                    return Ok(error_response(
                        StatusCode::BAD_REQUEST,
                        &format!("Failed to read request body: {e}"),
                    ));
                }
            };

            // Extract the Payment credential from the header selected by the challenge.
            let auth_header = parts
                .headers
                .get(verifier.credential_header())
                .and_then(|v| v.to_str().ok())
                .and_then(extract_payment_scheme)
                .map(|s| s.to_string());

            let credential = match auth_header {
                Some(c) => c,
                None => {
                    let challenge = match verifier.challenge_with_body(&body) {
                        Ok(c) => c,
                        Err(e) => {
                            return Ok(error_response(
                                StatusCode::INTERNAL_SERVER_ERROR,
                                &format!("Failed to generate challenge: {e}"),
                            ));
                        }
                    };
                    return Ok(challenge_response(StatusCode::PAYMENT_REQUIRED, &challenge));
                }
            };

            let receipt_header = match verifier.verify_credential(&credential, Some(&body)).await {
                Ok(r) => r,
                Err(error) => {
                    return Ok(rejection_response(&error, || {
                        verifier.challenge_with_body(&body)
                    }));
                }
            };

            let req = Request::from_parts(parts, http_body_util::Full::new(body));
            let mut resp = inner.call(req).await?;
            attach_receipt(&mut resp, &receipt_header);

            Ok(resp)
        })
    }
}

/// Build a minimal error response.
fn error_response<B: Default>(status: StatusCode, _message: &str) -> Response<B> {
    let mut resp = Response::new(B::default());
    *resp.status_mut() = status;
    resp
}

/// Attach a receipt only to successful responses and prevent shared caching.
fn attach_receipt<B>(resp: &mut Response<B>, receipt_header: &str) {
    if !resp.status().is_success() {
        return;
    }

    let Ok(receipt) = HeaderValue::from_str(receipt_header) else {
        return;
    };

    let existing_cc = resp
        .headers()
        .get_all(header::CACHE_CONTROL)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .collect::<Vec<_>>()
        .join(", ");
    let cache_control = with_private_cache_control(Some(existing_cc.as_str()));
    if let Ok(value) = HeaderValue::from_str(&cache_control) {
        resp.headers_mut().insert(header::CACHE_CONTROL, value);
    }
    resp.headers_mut().insert(PAYMENT_RECEIPT_HEADER, receipt);
}

/// Build a retryable response carrying a fresh `WWW-Authenticate: Payment`
/// challenge and `Cache-Control: no-store`.
///
/// A challenge that is not a valid header value cannot be offered to the
/// client, so it is answered as a server-side failure.
fn challenge_response<B: Default>(status: StatusCode, challenge: &str) -> Response<B> {
    let Ok(challenge) = HeaderValue::from_str(challenge) else {
        return internal_error_response();
    };
    let mut resp = Response::new(B::default());
    *resp.status_mut() = status;
    resp.headers_mut()
        .insert(WWW_AUTHENTICATE_HEADER, challenge);
    resp.headers_mut()
        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    resp
}

/// Build a `500` response without a challenge.
fn internal_error_response<B: Default>() -> Response<B> {
    let mut resp = error_response(StatusCode::INTERNAL_SERVER_ERROR, "");
    resp.headers_mut()
        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    resp
}

/// Build the response for a credential that failed with `error`.
///
/// A payment problem is answered with its status and the fresh challenge
/// from `challenge` so the client can retry. A server-side failure is
/// answered with `500` and no challenge, so the client does not pay again.
fn rejection_response<B: Default>(
    error: &MppError,
    challenge: impl FnOnce() -> Result<String, String>,
) -> Response<B> {
    if !error.is_payment_problem() {
        return internal_error_response();
    }
    let status = StatusCode::from_u16(error.to_problem_details(None).status)
        .unwrap_or(StatusCode::PAYMENT_REQUIRED);
    match challenge() {
        Ok(challenge) => challenge_response(status, &challenge),
        Err(_) => internal_error_response(),
    }
}

// ==================== Mpp integration ====================

/// A [`PaymentVerifier`] backed by an `Mpp` instance's charge flow.
///
/// Created via [`PaymentLayer::charge()`] and [`PaymentBodyLayer::charge()`].
#[allow(clippy::type_complexity)]
pub struct ChargeVerifier {
    /// Builds a fresh `WWW-Authenticate` header value per request.
    challenge_fn: Box<dyn Fn() -> Result<String, String> + Send + Sync>,
    /// Builds a fresh body-bound `WWW-Authenticate` header value per request.
    challenge_with_body_fn: Box<dyn Fn(&[u8]) -> Result<String, String> + Send + Sync>,
    /// HTTP field containing the Payment credential.
    credential_header: String,
    /// Shared mpp instance for verification (type-erased).
    verify_fn: Box<
        dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>>
            + Send
            + Sync,
    >,
    /// Shared mpp instance for body-bound verification (type-erased).
    verify_with_body_fn: Box<
        dyn Fn(String, Vec<u8>) -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>>
            + Send
            + Sync,
    >,
}

impl PaymentVerifier for ChargeVerifier {
    fn challenge(&self) -> Result<String, String> {
        (self.challenge_fn)()
    }

    fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
        (self.challenge_with_body_fn)(body)
    }

    fn verify(
        &self,
        credential: &str,
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
        let verified = self.verify_credential(credential, None);
        Box::pin(async move { verified.await.map_err(|e| e.to_string()) })
    }

    fn verify_with_body(
        &self,
        credential: &str,
        body: &[u8],
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
        let verified = self.verify_credential(credential, Some(body));
        Box::pin(async move { verified.await.map_err(|e| e.to_string()) })
    }

    fn verify_credential(
        &self,
        credential: &str,
        body: Option<&[u8]>,
    ) -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>> {
        match body {
            Some(body) => (self.verify_with_body_fn)(credential.to_string(), body.to_vec()),
            None => (self.verify_fn)(credential.to_string()),
        }
    }

    fn credential_header(&self) -> &str {
        &self.credential_header
    }
}

impl PaymentLayer<ChargeVerifier> {
    /// Create a payment layer that charges a dollar amount per request.
    ///
    /// Generates a fresh challenge for each request and verifies each
    /// incoming credential against the provided `Mpp` instance.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use mpp::server::middleware::PaymentLayer;
    ///
    /// let layer = PaymentLayer::charge(&mpp, "0.10").unwrap();
    /// ```
    #[cfg(feature = "tempo")]
    pub fn charge<M, S>(mpp: &super::Mpp<M, S>, amount: &str) -> crate::error::Result<Self>
    where
        M: crate::protocol::traits::ChargeMethod + Clone + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
    {
        // Capture route-scoped expected request once so credential verification
        // compares against endpoint configuration, not echoed credential data.
        let expected_challenge = mpp.charge(amount).map(|mut offers| offers.remove(0))?;
        let expected_request: crate::protocol::intents::ChargeRequest =
            expected_challenge.request.decode().map_err(|e| {
                crate::error::MppError::InvalidConfig(format!(
                    "Failed to decode route charge request: {e}"
                ))
            })?;

        let mpp_for_challenge = mpp.clone();
        let charge_amount = amount.to_string();
        // One challenge per accepted currency, comma-joined into a single
        // `WWW-Authenticate` value (RFC 9110 §11.6.1).
        let challenge_fn = Box::new(move || {
            let challenges = mpp_for_challenge
                .charge(&charge_amount)
                .map_err(|e| format!("Failed to generate challenge: {e}"))?;
            format_www_authenticate_many(&challenges)
                .map(|values| values.join(", "))
                .map_err(|e| format!("Failed to format challenge: {e}"))
        });

        let mpp_for_body_challenge = mpp.clone();
        let charge_amount_for_body = amount.to_string();
        let challenge_with_body_fn = Box::new(move |body: &[u8]| {
            let challenges = mpp_for_body_challenge
                .charge_with_options_and_body(
                    &charge_amount_for_body,
                    super::ChargeOptions::default(),
                    body,
                )
                .map_err(|e| format!("Failed to generate challenge: {e}"))?;
            format_www_authenticate_many(&challenges)
                .map(|values| values.join(", "))
                .map_err(|e| format!("Failed to format challenge: {e}"))
        });

        let mpp_for_verify = mpp.clone();
        let expected_request_for_body = expected_request.clone();
        let verify_fn = Box::new(move |credential_str: String| -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>> {
            let mpp = mpp_for_verify.clone();
            let expected_request = expected_request.clone();
            Box::pin(async move {
                let credential = parse_authorization(&credential_str)?;

                let receipt = mpp
                    .verify_credential_with_expected_request(&credential, &expected_request)
                    .await?;

                format_receipt(&receipt)
            })
        });

        let mpp_for_body_verify = mpp.clone();
        let verify_with_body_fn = Box::new(
            move |credential_str: String,
                  body: Vec<u8>|
                  -> Pin<Box<dyn Future<Output = Result<String, MppError>> + Send>> {
                let mpp = mpp_for_body_verify.clone();
                let expected_request = expected_request_for_body.clone();
                Box::pin(async move {
                    let credential = parse_authorization(&credential_str)?;

                    let receipt = mpp
                        .verify_credential_with_expected_request_and_body(
                            &credential,
                            &expected_request,
                            &body,
                        )
                        .await?;

                    format_receipt(&receipt)
                })
            },
        );

        Ok(Self::new(ChargeVerifier {
            challenge_fn,
            challenge_with_body_fn,
            credential_header: mpp.credential_header().to_string(),
            verify_fn,
            verify_with_body_fn,
        }))
    }
}

impl PaymentBodyLayer<ChargeVerifier> {
    /// Create a body-aware payment layer that charges a dollar amount per request.
    ///
    /// This buffers the request body, binds issued challenges to its digest,
    /// verifies credentials against the same bytes, and replays the body to
    /// the inner service.
    #[cfg(feature = "tempo")]
    pub fn charge<M, S>(mpp: &super::Mpp<M, S>, amount: &str) -> crate::error::Result<Self>
    where
        M: crate::protocol::traits::ChargeMethod + Clone + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
    {
        let layer = PaymentLayer::charge(mpp, amount)?;
        Ok(Self {
            verifier: layer.verifier,
            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tower_layer::Layer;

    #[derive(Clone)]
    struct MockVerifier {
        challenge_value: String,
        accept: bool,
    }

    impl PaymentVerifier for MockVerifier {
        fn challenge(&self) -> Result<String, String> {
            Ok(self.challenge_value.clone())
        }

        fn verify(
            &self,
            _credential: &str,
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
            let accept = self.accept;
            Box::pin(async move {
                if accept {
                    Ok("mock-receipt-token".to_string())
                } else {
                    Err("payment rejected".to_string())
                }
            })
        }
    }

    #[derive(Clone)]
    struct StatusService(StatusCode);

    impl<B: Send + 'static> tower_service::Service<Request<B>> for StatusService {
        type Response = Response<()>;
        type Error = std::convert::Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Response<()>, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: Request<B>) -> Self::Future {
            let status = self.0;
            Box::pin(async move {
                let mut resp = Response::new(());
                *resp.status_mut() = status;
                Ok(resp)
            })
        }
    }

    #[test]
    fn test_payment_verifier_challenge() {
        let v = MockVerifier {
            challenge_value: "Payment id=\"test\"".to_string(),
            accept: true,
        };
        assert_eq!(v.challenge().unwrap(), "Payment id=\"test\"");
    }

    #[tokio::test]
    async fn test_payment_verifier_verify_accept() {
        let v = MockVerifier {
            challenge_value: String::new(),
            accept: true,
        };
        let result = v.verify("Payment eyJ...").await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "mock-receipt-token");
    }

    #[tokio::test]
    async fn test_payment_verifier_verify_reject() {
        let v = MockVerifier {
            challenge_value: String::new(),
            accept: false,
        };
        let result = v.verify("Payment eyJ...").await;
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "payment rejected");
    }

    #[test]
    fn test_fn_verifier_challenge() {
        let v = FnVerifier {
            challenge_fn: Box::new(|| Ok("Payment test".to_string())),
            challenge_with_body_fn: None,
            verify_fn: Box::new(|_| Box::pin(async { Ok("receipt".to_string()) })),
            verify_with_body_fn: None,
        };
        assert_eq!(v.challenge().unwrap(), "Payment test");
    }

    #[test]
    fn test_payment_layer_clones() {
        let layer = PaymentLayer::new(MockVerifier {
            challenge_value: "test".into(),
            accept: true,
        });
        let _clone = layer.clone();
    }

    /// Test the full Tower service flow: no auth → 402.
    #[tokio::test]
    async fn test_service_no_auth_returns_402() {
        use tower_service::Service;

        let layer = PaymentLayer::new(MockVerifier {
            challenge_value: "Payment id=\"challenge\"".to_string(),
            accept: true,
        });

        // A trivial inner service that returns 200.
        #[derive(Clone)]
        struct OkService;

        impl tower_service::Service<Request<()>> for OkService {
            type Response = Response<()>;
            type Error = std::convert::Infallible;
            type Future = Pin<Box<dyn Future<Output = Result<Response<()>, Self::Error>> + Send>>;

            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                Poll::Ready(Ok(()))
            }

            fn call(&mut self, _req: Request<()>) -> Self::Future {
                Box::pin(async { Ok(Response::new(())) })
            }
        }

        let mut svc =
            <PaymentLayer<MockVerifier> as tower_layer::Layer<OkService>>::layer(&layer, OkService);

        let req = Request::builder().uri("/premium").body(()).unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        assert!(resp.headers().contains_key(WWW_AUTHENTICATE_HEADER));
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-store"
        );
    }

    /// Test: valid auth → 200 with receipt.
    #[tokio::test]
    async fn test_service_valid_auth_returns_receipt() {
        use tower_service::Service;

        let layer = PaymentLayer::new(MockVerifier {
            challenge_value: "Payment id=\"challenge\"".to_string(),
            accept: true,
        });

        #[derive(Clone)]
        struct OkService;

        impl tower_service::Service<Request<()>> for OkService {
            type Response = Response<()>;
            type Error = std::convert::Infallible;
            type Future = Pin<Box<dyn Future<Output = Result<Response<()>, Self::Error>> + Send>>;

            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                Poll::Ready(Ok(()))
            }

            fn call(&mut self, _req: Request<()>) -> Self::Future {
                Box::pin(async { Ok(Response::new(())) })
            }
        }

        let mut svc =
            <PaymentLayer<MockVerifier> as tower_layer::Layer<OkService>>::layer(&layer, OkService);

        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
            .body(())
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get(PAYMENT_RECEIPT_HEADER).unwrap(),
            "mock-receipt-token"
        );
        // Per spec, receipt responses must be Cache-Control: private.
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "private"
        );
    }

    #[tokio::test]
    async fn test_service_does_not_attach_receipt_to_error_response() {
        use tower_service::Service;

        for status in [
            StatusCode::FOUND,
            StatusCode::FORBIDDEN,
            StatusCode::INTERNAL_SERVER_ERROR,
        ] {
            let layer = PaymentLayer::new(MockVerifier {
                challenge_value: "Payment id=\"challenge\"".to_string(),
                accept: true,
            });
            let mut svc = layer.layer(StatusService(status));
            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
                .body(())
                .unwrap();

            let resp = svc.call(req).await.unwrap();
            assert_eq!(resp.status(), status);
            assert!(!resp.headers().contains_key(PAYMENT_RECEIPT_HEADER));
            assert!(!resp.headers().contains_key(header::CACHE_CONTROL));
        }
    }

    #[test]
    fn test_attach_receipt_preserves_existing_cache_control() {
        let mut resp = Response::new(());
        resp.headers_mut()
            .append(header::CACHE_CONTROL, HeaderValue::from_static("public"));
        resp.headers_mut().append(
            header::CACHE_CONTROL,
            HeaderValue::from_static("max-age=60"),
        );

        attach_receipt(&mut resp, "mock-receipt-token");

        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "public, max-age=60, private"
        );
        assert_eq!(
            resp.headers().get(PAYMENT_RECEIPT_HEADER).unwrap(),
            "mock-receipt-token"
        );
    }

    #[test]
    fn test_attach_receipt_rejects_invalid_header_without_changing_cache_control() {
        let mut resp = Response::new(());
        resp.headers_mut().insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static("public, max-age=60"),
        );

        attach_receipt(&mut resp, "invalid\nreceipt");

        assert!(!resp.headers().contains_key(PAYMENT_RECEIPT_HEADER));
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "public, max-age=60"
        );
    }

    #[tokio::test]
    async fn test_service_unusable_challenge_returns_500_without_challenge() {
        use tower_service::Service;

        for authorization in [None, Some("Payment eyJmYWtlIjp0cnVlfQ")] {
            let layer = PaymentLayer::new(MockVerifier {
                challenge_value: "Payment id=\"a\nb\"".to_string(),
                accept: false,
            });
            let mut svc = layer.layer(StatusService(StatusCode::OK));
            let mut req = Request::builder().uri("/premium");
            if let Some(authorization) = authorization {
                req = req.header(header::AUTHORIZATION, authorization);
            }

            let resp = svc.call(req.body(()).unwrap()).await.unwrap();
            assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
            assert!(!resp.headers().contains_key(WWW_AUTHENTICATE_HEADER));
        }
    }

    /// Test: invalid auth → retryable 402 with a fresh challenge.
    ///
    /// A failed credential must yield a 402 that carries a new
    /// `WWW-Authenticate: Payment` challenge and `Cache-Control: no-store`,
    /// so the client can pay again. A bare 402 (no challenge) is a dead end
    /// the Payment auth scheme — and this SDK's own client — reject.
    #[tokio::test]
    async fn test_service_invalid_auth_returns_retryable_402() {
        use tower_service::Service;

        let layer = PaymentLayer::new(MockVerifier {
            challenge_value: "Payment id=\"challenge\"".to_string(),
            accept: false,
        });

        #[derive(Clone)]
        struct OkService;

        impl tower_service::Service<Request<()>> for OkService {
            type Response = Response<()>;
            type Error = std::convert::Infallible;
            type Future = Pin<Box<dyn Future<Output = Result<Response<()>, Self::Error>> + Send>>;

            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                Poll::Ready(Ok(()))
            }

            fn call(&mut self, _req: Request<()>) -> Self::Future {
                Box::pin(async { Ok(Response::new(())) })
            }
        }

        let mut svc =
            <PaymentLayer<MockVerifier> as tower_layer::Layer<OkService>>::layer(&layer, OkService);

        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
            .body(())
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        // Must carry a fresh challenge so the client can retry.
        assert_eq!(
            resp.headers().get(WWW_AUTHENTICATE_HEADER).unwrap(),
            "Payment id=\"challenge\""
        );
        // 402 responses must not be cached.
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-store"
        );
    }

    #[derive(Clone)]
    struct BodyAwareVerifier {
        challenge_body: Arc<std::sync::Mutex<Option<Vec<u8>>>>,
        verify_body: Arc<std::sync::Mutex<Option<Vec<u8>>>>,
    }

    impl PaymentVerifier for BodyAwareVerifier {
        fn challenge(&self) -> Result<String, String> {
            Ok("Payment id=\"legacy\"".to_string())
        }

        fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
            *self.challenge_body.lock().unwrap() = Some(body.to_vec());
            Ok("Payment id=\"body-bound\"".to_string())
        }

        fn verify(
            &self,
            _credential: &str,
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
            Box::pin(async { Err("legacy verifier should not be called".to_string()) })
        }

        fn verify_with_body(
            &self,
            _credential: &str,
            body: &[u8],
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
            *self.verify_body.lock().unwrap() = Some(body.to_vec());
            Box::pin(async { Ok("mock-receipt-token".to_string()) })
        }
    }

    #[derive(Clone)]
    struct BodyEchoService;

    impl tower_service::Service<Request<http_body_util::Full<Bytes>>> for BodyEchoService {
        type Response = Response<Vec<u8>>;
        type Error = std::convert::Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Response<Vec<u8>>, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, req: Request<http_body_util::Full<Bytes>>) -> Self::Future {
            Box::pin(async move {
                let body = req.into_body().collect().await.unwrap().to_bytes();
                let mut response = Response::new(body.to_vec());
                response.headers_mut().insert(
                    header::CACHE_CONTROL,
                    HeaderValue::from_static("max-age=60"),
                );
                Ok(response)
            })
        }
    }

    #[tokio::test]
    async fn test_body_service_no_auth_binds_challenge_to_body() {
        use tower_service::Service;

        let challenge_body = Arc::new(std::sync::Mutex::new(None));
        let layer = PaymentBodyLayer::new(BodyAwareVerifier {
            challenge_body: challenge_body.clone(),
            verify_body: Arc::new(std::sync::Mutex::new(None)),
        });
        let mut svc = layer.layer(BodyEchoService);

        let req = Request::builder()
            .uri("/premium")
            .body(http_body_util::Full::new(Bytes::from_static(
                br#"{"query":"paid"}"#,
            )))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        assert_eq!(
            resp.headers().get(WWW_AUTHENTICATE_HEADER).unwrap(),
            "Payment id=\"body-bound\""
        );
        assert_eq!(
            challenge_body.lock().unwrap().as_deref(),
            Some(br#"{"query":"paid"}"#.as_slice())
        );
    }

    #[tokio::test]
    async fn test_body_service_valid_auth_verifies_and_replays_body() {
        use tower_service::Service;

        let verify_body = Arc::new(std::sync::Mutex::new(None));
        let layer = PaymentBodyLayer::new(BodyAwareVerifier {
            challenge_body: Arc::new(std::sync::Mutex::new(None)),
            verify_body: verify_body.clone(),
        });
        let mut svc = layer.layer(BodyEchoService);

        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
            .body(http_body_util::Full::new(Bytes::from_static(
                br#"{"query":"paid"}"#,
            )))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.body(), br#"{"query":"paid"}"#);
        assert_eq!(
            resp.headers().get(PAYMENT_RECEIPT_HEADER).unwrap(),
            "mock-receipt-token"
        );
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "max-age=60, private"
        );
        assert_eq!(
            verify_body.lock().unwrap().as_deref(),
            Some(br#"{"query":"paid"}"#.as_slice())
        );
    }

    fn body_aware_layer() -> PaymentBodyLayer<BodyAwareVerifier> {
        PaymentBodyLayer::new(BodyAwareVerifier {
            challenge_body: Arc::new(std::sync::Mutex::new(None)),
            verify_body: Arc::new(std::sync::Mutex::new(None)),
        })
    }

    #[tokio::test]
    async fn test_body_service_stops_reading_oversized_body() {
        use futures_util::StreamExt;
        use tower_service::Service;

        let mut svc = body_aware_layer()
            .max_body_bytes(1024)
            .layer(BodyEchoService);

        let chunks = futures_util::stream::iter(0..).map(|i| {
            assert!(i < 4, "body read past the limit");
            Ok::<_, std::convert::Infallible>(http_body::Frame::data(Bytes::from_static(&[0; 512])))
        });
        let req = Request::builder()
            .uri("/premium")
            .body(http_body_util::StreamBody::new(chunks))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
        assert!(!resp.headers().contains_key(WWW_AUTHENTICATE_HEADER));
    }

    #[tokio::test]
    async fn test_body_service_default_body_limit() {
        use tower_service::Service;

        for (len, status) in [
            (DEFAULT_MAX_BODY_BYTES, StatusCode::PAYMENT_REQUIRED),
            (DEFAULT_MAX_BODY_BYTES + 1, StatusCode::PAYLOAD_TOO_LARGE),
        ] {
            let mut svc = body_aware_layer().layer(BodyEchoService);
            let req = Request::builder()
                .uri("/premium")
                .body(http_body_util::Full::new(Bytes::from(vec![0; len])))
                .unwrap();

            let resp = svc.call(req).await.unwrap();
            assert_eq!(resp.status(), status);
        }
    }

    #[tokio::test]
    async fn test_body_service_body_read_error_returns_400() {
        use tower_service::Service;

        let mut svc = body_aware_layer().layer(BodyEchoService);

        let chunks = futures_util::stream::iter([Err::<http_body::Frame<Bytes>, _>(
            std::io::Error::other("reset"),
        )]);
        let req = Request::builder()
            .uri("/premium")
            .body(http_body_util::StreamBody::new(chunks))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// A body-aware verifier that, like `Mpp::requires_auth`, advertises
    /// `Payment-Authorization` as the credential header.
    #[derive(Clone)]
    struct PaymentAuthorizationBodyVerifier(BodyAwareVerifier);

    impl PaymentVerifier for PaymentAuthorizationBodyVerifier {
        fn challenge(&self) -> Result<String, String> {
            self.0.challenge()
        }

        fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
            self.0.challenge_with_body(body)
        }

        fn verify(
            &self,
            credential: &str,
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
            self.0.verify(credential)
        }

        fn verify_with_body(
            &self,
            credential: &str,
            body: &[u8],
        ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
            self.0.verify_with_body(credential, body)
        }

        fn credential_header(&self) -> &str {
            "Payment-Authorization"
        }
    }

    #[tokio::test]
    async fn test_body_service_reads_credential_from_verifier_header() {
        use tower_service::Service;

        let verify_body = Arc::new(std::sync::Mutex::new(None));
        let layer = PaymentBodyLayer::new(PaymentAuthorizationBodyVerifier(BodyAwareVerifier {
            challenge_body: Arc::new(std::sync::Mutex::new(None)),
            verify_body: verify_body.clone(),
        }));
        let mut svc = layer.layer(BodyEchoService);

        // `Authorization` carries the app's own bearer token; the Payment
        // credential travels in the header the challenge advertised.
        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Bearer app-token")
            .header("Payment-Authorization", "Payment eyJmYWtlIjp0cnVlfQ")
            .body(http_body_util::Full::new(Bytes::from_static(
                br#"{"query":"paid"}"#,
            )))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.body(), br#"{"query":"paid"}"#);
        assert_eq!(
            resp.headers().get(PAYMENT_RECEIPT_HEADER).unwrap(),
            "mock-receipt-token"
        );
        assert_eq!(
            verify_body.lock().unwrap().as_deref(),
            Some(br#"{"query":"paid"}"#.as_slice())
        );
    }

    #[tokio::test]
    async fn test_body_service_ignores_credential_in_unselected_header() {
        use tower_service::Service;

        let verify_body = Arc::new(std::sync::Mutex::new(None));
        let layer = PaymentBodyLayer::new(PaymentAuthorizationBodyVerifier(BodyAwareVerifier {
            challenge_body: Arc::new(std::sync::Mutex::new(None)),
            verify_body: verify_body.clone(),
        }));
        let mut svc = layer.layer(BodyEchoService);

        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
            .body(http_body_util::Full::new(Bytes::from_static(
                br#"{"query":"paid"}"#,
            )))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        assert_eq!(
            resp.headers().get(WWW_AUTHENTICATE_HEADER).unwrap(),
            "Payment id=\"body-bound\""
        );
        assert!(verify_body.lock().unwrap().is_none());
    }

    #[tokio::test]
    async fn test_body_service_invalid_auth_returns_body_bound_challenge() {
        use tower_service::Service;

        #[derive(Clone)]
        struct RejectingBodyVerifier;

        impl PaymentVerifier for RejectingBodyVerifier {
            fn challenge(&self) -> Result<String, String> {
                unreachable!("body middleware must use challenge_with_body")
            }

            fn challenge_with_body(&self, body: &[u8]) -> Result<String, String> {
                assert_eq!(body, br#"{"query":"paid"}"#);
                Ok(concat!(
                    "Payment id=\"replacement\", realm=\"test\", method=\"tempo\", ",
                    "intent=\"charge\", request=\"e30\""
                )
                .to_string())
            }

            fn verify(
                &self,
                _credential: &str,
            ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
                unreachable!("body middleware must use verify_with_body")
            }

            fn verify_with_body(
                &self,
                _credential: &str,
                _body: &[u8],
            ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send>> {
                Box::pin(async { Err("payment rejected".to_string()) })
            }
        }

        let layer = PaymentBodyLayer::new(RejectingBodyVerifier);
        let mut svc = layer.layer(BodyEchoService);
        let req = Request::builder()
            .uri("/premium")
            .header(header::AUTHORIZATION, "Payment invalid")
            .body(http_body_util::Full::new(Bytes::from_static(
                br#"{"query":"paid"}"#,
            )))
            .unwrap();

        let resp = svc.call(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        let challenge = resp.headers().get(WWW_AUTHENTICATE_HEADER).unwrap();
        let parsed =
            crate::protocol::core::headers::parse_www_authenticate(challenge.to_str().unwrap())
                .unwrap();
        assert_eq!(parsed.id, "replacement");
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-store"
        );
    }

    #[tokio::test]
    async fn test_body_service_does_not_attach_receipt_to_error_response() {
        use tower_service::Service;

        for status in [
            StatusCode::FOUND,
            StatusCode::FORBIDDEN,
            StatusCode::INTERNAL_SERVER_ERROR,
        ] {
            let layer = PaymentBodyLayer::new(BodyAwareVerifier {
                challenge_body: Arc::new(std::sync::Mutex::new(None)),
                verify_body: Arc::new(std::sync::Mutex::new(None)),
            });
            let mut svc = layer.layer(StatusService(status));
            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, "Payment eyJmYWtlIjp0cnVlfQ")
                .body(http_body_util::Full::new(Bytes::from_static(b"paid")))
                .unwrap();

            let resp = svc.call(req).await.unwrap();
            assert_eq!(resp.status(), status);
            assert!(!resp.headers().contains_key(PAYMENT_RECEIPT_HEADER));
            assert!(!resp.headers().contains_key(header::CACHE_CONTROL));
        }
    }

    // ==================== Real ChargeVerifier tests ====================
    //
    // These tests exercise PaymentLayer with real challenge formatting,
    // HMAC-bound IDs, and the full parse_authorization → verify_credential
    // round-trip, using a mock ChargeMethod to avoid RPC calls.

    #[cfg(feature = "tempo")]
    mod real_charge_verifier {
        use super::*;
        use crate::protocol::core::challenge::{PaymentCredential, PaymentPayload, Receipt};
        use crate::protocol::core::headers::{
            format_authorization, parse_receipt, parse_www_authenticate, parse_www_authenticate_all,
        };
        use crate::protocol::core::PaymentChallenge;
        use crate::protocol::intents::ChargeRequest;
        use crate::protocol::traits::{ChargeMethod, VerificationError};
        use crate::server::Mpp;
        use tower_layer::Layer;
        use tower_service::Service;

        #[derive(Clone)]
        struct SuccessChargeMethod;

        impl ChargeMethod for SuccessChargeMethod {
            fn method(&self) -> &str {
                "tempo"
            }

            async fn verify(
                &self,
                _credential: &PaymentCredential,
                _request: &ChargeRequest,
            ) -> std::result::Result<Receipt, VerificationError> {
                Ok(Receipt::success("tempo", "0xabc123"))
            }
        }

        fn create_mpp_with_mock() -> Mpp<SuccessChargeMethod> {
            Mpp::new_with_config(
                SuccessChargeMethod,
                "test-realm",
                "test-secret-key-at-least-32-bytes",
                "0x20c0000000000000000000000000000000000000",
                "0x742d35Cc6634C0532925a3b844Bc9e7595f1B0F2",
            )
        }

        #[derive(Clone)]
        struct OkService;

        impl tower_service::Service<Request<()>> for OkService {
            type Response = Response<()>;
            type Error = std::convert::Infallible;
            type Future = Pin<Box<dyn Future<Output = Result<Response<()>, Self::Error>> + Send>>;

            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                Poll::Ready(Ok(()))
            }

            fn call(&mut self, _req: Request<()>) -> Self::Future {
                Box::pin(async { Ok(Response::new(())) })
            }
        }

        #[tokio::test]
        async fn test_no_auth_returns_402_with_parseable_challenge() {
            let mpp = create_mpp_with_mock();
            let layer = PaymentLayer::charge(&mpp, "0.10").unwrap();
            let mut svc = layer.layer(OkService);

            let req = Request::builder().uri("/premium").body(()).unwrap();
            let resp = svc.call(req).await.unwrap();

            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);

            let www_auth = resp
                .headers()
                .get(WWW_AUTHENTICATE_HEADER)
                .expect("missing WWW-Authenticate header")
                .to_str()
                .unwrap();

            let challenge = parse_www_authenticate(www_auth)
                .expect("WWW-Authenticate header should be parseable");

            assert_eq!(challenge.method.as_str(), "tempo");
            assert_eq!(challenge.intent.as_str(), "charge");
            assert_eq!(challenge.realm, "test-realm");
            assert!(!challenge.id.is_empty());

            let request: ChargeRequest = challenge.request.decode().unwrap();
            assert_eq!(request.amount, "100000");
            assert_eq!(
                request.currency,
                "0x20c0000000000000000000000000000000000000"
            );
            assert_eq!(
                request.recipient,
                Some("0x742d35Cc6634C0532925a3b844Bc9e7595f1B0F2".into())
            );
        }

        #[tokio::test]
        async fn test_valid_credential_roundtrip_returns_200_with_receipt() {
            let mpp = create_mpp_with_mock();
            let layer = PaymentLayer::charge(&mpp, "0.10").unwrap();

            // First call: get the challenge from 402.
            let mut svc = layer.layer(OkService);
            let req = Request::builder().uri("/premium").body(()).unwrap();
            let resp = svc.call(req).await.unwrap();
            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);

            let www_auth = resp
                .headers()
                .get(WWW_AUTHENTICATE_HEADER)
                .unwrap()
                .to_str()
                .unwrap();
            let challenge = parse_www_authenticate(www_auth).unwrap();

            // Build a credential from the challenge.
            let credential =
                PaymentCredential::new(challenge.to_echo(), PaymentPayload::hash("0xdeadbeef"));
            let auth_header = format_authorization(&credential).unwrap();

            // Second call: send credential, expect 200 + receipt.
            let mut svc = layer.layer(OkService);
            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, &auth_header)
                .body(())
                .unwrap();
            let resp = svc.call(req).await.unwrap();

            assert_eq!(resp.status(), StatusCode::OK);

            let receipt_header = resp
                .headers()
                .get(PAYMENT_RECEIPT_HEADER)
                .expect("missing Payment-Receipt header")
                .to_str()
                .unwrap();
            let receipt =
                parse_receipt(receipt_header).expect("Payment-Receipt header should be parseable");
            assert!(receipt.is_success());
            assert_eq!(receipt.method.as_str(), "tempo");
            assert_eq!(receipt.reference, "0xabc123");
        }

        #[tokio::test]
        async fn test_wrong_scheme_returns_402() {
            let mpp = create_mpp_with_mock();
            let layer = PaymentLayer::charge(&mpp, "0.10").unwrap();
            let mut svc = layer.layer(OkService);

            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, "Bearer some-token")
                .body(())
                .unwrap();
            let resp = svc.call(req).await.unwrap();

            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
            assert!(resp.headers().contains_key(WWW_AUTHENTICATE_HEADER));
        }

        fn create_multi_currency_mpp() -> Mpp<SuccessChargeMethod> {
            create_mpp_with_mock().with_currencies(vec![
                crate::protocol::methods::tempo::OUSD.to_string(),
                crate::protocol::methods::tempo::USDC.to_string(),
            ])
        }

        fn offered_challenges<B>(resp: &Response<B>) -> Vec<PaymentChallenge> {
            let values = resp
                .headers()
                .get_all(WWW_AUTHENTICATE_HEADER)
                .iter()
                .map(|v| v.to_str().unwrap())
                .collect::<Vec<_>>();
            parse_www_authenticate_all(values)
                .into_iter()
                .map(|challenge| challenge.unwrap())
                .collect()
        }

        fn currencies_of(challenges: &[PaymentChallenge]) -> Vec<String> {
            challenges
                .iter()
                .map(|c| c.request.decode::<ChargeRequest>().unwrap().currency)
                .collect()
        }

        #[tokio::test]
        async fn test_no_auth_returns_every_currency_offer_in_order() {
            use crate::protocol::methods::tempo::{OUSD, USDC};

            let layer = PaymentLayer::charge(&create_multi_currency_mpp(), "0.10").unwrap();
            let mut svc = layer.layer(OkService);
            let req = Request::builder().uri("/premium").body(()).unwrap();
            let resp = svc.call(req).await.unwrap();

            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
            let challenges = offered_challenges(&resp);
            assert_eq!(currencies_of(&challenges), [OUSD, USDC]);
            assert!(challenges
                .iter()
                .all(|c| c.verify("test-secret-key-at-least-32-bytes")));
        }

        #[tokio::test]
        async fn test_credential_for_each_offer_returns_200() {
            use crate::protocol::methods::tempo::{OUSD, USDC};

            let layer = PaymentLayer::charge(&create_multi_currency_mpp(), "0.10").unwrap();
            let resp = layer
                .layer(OkService)
                .call(Request::builder().uri("/premium").body(()).unwrap())
                .await
                .unwrap();
            let challenges = offered_challenges(&resp);

            for (challenge, currency) in challenges.iter().zip([OUSD, USDC]) {
                let credential =
                    PaymentCredential::new(challenge.to_echo(), PaymentPayload::hash("0xdeadbeef"));
                let auth_header = format_authorization(&credential).unwrap();
                let req = Request::builder()
                    .uri("/premium")
                    .header(header::AUTHORIZATION, &auth_header)
                    .body(())
                    .unwrap();
                let resp = layer.layer(OkService).call(req).await.unwrap();
                assert_eq!(resp.status(), StatusCode::OK, "{currency} offer rejected");
                assert!(resp.headers().contains_key(PAYMENT_RECEIPT_HEADER));
            }
        }

        #[tokio::test]
        async fn test_credential_for_non_offered_currency_returns_402() {
            use crate::protocol::methods::tempo::{OUSD, USDC};

            // pathUSD challenge signed with the same secret/realm but not offered.
            let foreign = create_mpp_with_mock().charge("0.10").unwrap().remove(0);
            let credential =
                PaymentCredential::new(foreign.to_echo(), PaymentPayload::hash("0xdeadbeef"));
            let auth_header = format_authorization(&credential).unwrap();

            let layer = PaymentLayer::charge(&create_multi_currency_mpp(), "0.10").unwrap();
            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, &auth_header)
                .body(())
                .unwrap();
            let resp = layer.layer(OkService).call(req).await.unwrap();
            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
            assert_eq!(currencies_of(&offered_challenges(&resp)), [OUSD, USDC]);
        }

        #[tokio::test]
        async fn test_body_layer_binds_every_currency_offer() {
            use crate::protocol::methods::tempo::{OUSD, USDC};

            let verifier = PaymentBodyLayer::charge(&create_multi_currency_mpp(), "0.10")
                .unwrap()
                .verifier;
            let header = verifier.challenge_with_body(b"{}").unwrap();
            let challenges = parse_www_authenticate_all([header.as_str()])
                .into_iter()
                .map(|challenge| challenge.unwrap())
                .collect::<Vec<_>>();
            assert_eq!(currencies_of(&challenges), [OUSD, USDC]);
            let digest = crate::body_digest::compute(b"{}");
            assert!(challenges
                .iter()
                .all(|c| c.digest.as_deref() == Some(digest.as_str())));
        }

        #[tokio::test]
        async fn test_garbage_authorization_returns_402() {
            let mpp = create_mpp_with_mock();
            let layer = PaymentLayer::charge(&mpp, "0.10").unwrap();
            let mut svc = layer.layer(OkService);

            let req = Request::builder()
                .uri("/premium")
                .header(header::AUTHORIZATION, "Payment not-valid-base64!!!")
                .body(())
                .unwrap();
            let resp = svc.call(req).await.unwrap();

            assert_eq!(resp.status(), StatusCode::PAYMENT_REQUIRED);
        }
    }
}