mpp 0.14.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
//! Server-side transport abstraction.
//!
//! Abstracts how challenges are issued and credentials are received
//! across different transport protocols (HTTP, WebSocket, MCP, etc.).
//!
//! This matches the mppx `Transport` interface from `mppx/server`.
//!
//! # Built-in transports
//!
//! - [`http()`]: HTTP transport (Authorization/WWW-Authenticate headers)
//!
//! # Custom transports
//!
//! Implement [`Transport`] for custom protocols:
//!
//! ```ignore
//! use mpp::server::transport::{Transport, ChallengeContext};
//! use mpp::protocol::core::{PaymentChallenge, PaymentCredential, Receipt};
//!
//! struct MyTransport;
//!
//! impl Transport for MyTransport {
//!     type Input = MyRequest;
//!     type ChallengeOutput = MyResponse;
//!     type ReceiptOutput = MyResponse;
//!
//!     fn name(&self) -> &str { "custom" }
//!     // ...
//! }
//! ```

use crate::error::MppError;
use crate::protocol::core::{
    with_private_cache_control, PaymentChallenge, PaymentCredential, Receipt,
};

/// Context passed to [`Transport::respond_challenge`].
pub struct ChallengeContext<'a, I> {
    /// The payment challenge to send to the client.
    pub challenge: &'a PaymentChallenge,
    /// The original transport input (e.g., HTTP request).
    pub input: &'a I,
    /// Optional error message for the client.
    pub error: Option<&'a str>,
}

/// Context passed to [`Transport::respond_receipt`].
pub struct ReceiptContext<'a, R> {
    /// The challenge ID this receipt corresponds to.
    pub challenge_id: &'a str,
    /// The payment receipt.
    pub receipt: &'a Receipt,
    /// The application response to attach the receipt to.
    pub response: R,
}

/// Server-side transport trait.
///
/// Abstracts how the server extracts credentials from incoming requests,
/// issues payment challenges, and attaches receipts to responses.
pub trait Transport: Send + Sync {
    /// The incoming request/message type (e.g., `http::Request<Body>`).
    type Input;
    /// The response type for payment challenges (e.g., `http::Response<Body>`).
    type ChallengeOutput;
    /// The response type after attaching a receipt.
    type ReceiptOutput;

    /// Transport name for identification (e.g., "http", "ws", "mcp").
    fn name(&self) -> &str;

    /// Extract a payment credential from the transport input.
    ///
    /// Returns `Ok(Some(credential))` if a valid credential is present,
    /// `Ok(None)` if no credential was provided (trigger challenge),
    /// or `Err` if the credential is malformed.
    fn get_credential(&self, input: &Self::Input) -> Result<Option<PaymentCredential>, MppError>;

    /// Create a transport response for a payment challenge.
    fn respond_challenge(&self, ctx: ChallengeContext<'_, Self::Input>) -> Self::ChallengeOutput;

    /// Attach a receipt to a successful response.
    fn respond_receipt(&self, ctx: ReceiptContext<'_, Self::ReceiptOutput>) -> Self::ReceiptOutput;
}

/// HTTP transport for server-side payment handling.
///
/// - Reads credentials from `Authorization`, or from `Payment-Authorization`
///   when constructed with [`HttpTransport::requires_auth`]
/// - Issues challenges via `WWW-Authenticate` header with 402 status
/// - Attaches receipts via `Payment-Receipt` header
///
/// This is the default transport, matching mppx's `Transport.http()`.
#[derive(Debug, Clone, Copy, Default)]
pub struct HttpTransport {
    requires_auth: bool,
}

/// Create an HTTP transport instance.
pub fn http() -> HttpTransport {
    HttpTransport {
        requires_auth: false,
    }
}

impl HttpTransport {
    /// Use `Payment-Authorization` for Payment credentials so `Authorization`
    /// remains available for application authentication.
    pub fn requires_auth(mut self, enabled: bool) -> Self {
        self.requires_auth = enabled;
        self
    }

    fn credential_header(&self) -> &'static str {
        if self.requires_auth {
            crate::protocol::core::PAYMENT_AUTHORIZATION_HEADER
        } else {
            http_types::header::AUTHORIZATION.as_str()
        }
    }
}

impl Transport for HttpTransport {
    type Input = http_types::Request<()>;
    type ChallengeOutput = http_types::Response<String>;
    type ReceiptOutput = http_types::Response<String>;

    fn name(&self) -> &str {
        "http"
    }

    fn get_credential(&self, input: &Self::Input) -> Result<Option<PaymentCredential>, MppError> {
        let Some(header) = input.headers().get(self.credential_header()) else {
            return Ok(None);
        };

        let header_str = header
            .to_str()
            .map_err(|e| MppError::MalformedCredential(Some(format!("invalid header: {e}"))))?;

        let Some(payment) = crate::protocol::core::extract_payment_scheme(header_str) else {
            return Ok(None);
        };

        // extract_payment_scheme returns the full "Payment ..." fragment
        let credential = crate::protocol::core::parse_authorization(payment).map_err(|e| {
            MppError::MalformedCredential(Some(format!("failed to parse credential: {e}")))
        })?;

        Ok(Some(credential))
    }

    fn respond_challenge(&self, ctx: ChallengeContext<'_, Self::Input>) -> Self::ChallengeOutput {
        let www_auth = crate::protocol::core::format_www_authenticate(ctx.challenge)
            .unwrap_or_else(|_| "Payment".to_string());

        let body = match ctx.error {
            Some(msg) => serde_json::json!({ "error": msg }).to_string(),
            None => serde_json::json!({ "error": "Payment Required" }).to_string(),
        };

        let mut resp = http_types::Response::builder()
            .status(http_types::StatusCode::PAYMENT_REQUIRED)
            .header(http_types::header::WWW_AUTHENTICATE, &www_auth)
            .header(http_types::header::CONTENT_TYPE, "application/json")
            .body(body)
            .expect("response builder cannot fail");

        // Add Cache-Control: no-store to prevent caching of challenges
        resp.headers_mut().insert(
            http_types::header::CACHE_CONTROL,
            http_types::HeaderValue::from_static("no-store"),
        );

        resp
    }

    fn respond_receipt(&self, ctx: ReceiptContext<'_, Self::ReceiptOutput>) -> Self::ReceiptOutput {
        let receipt_header =
            crate::protocol::core::format_receipt(ctx.receipt).unwrap_or_else(|_| String::new());

        let mut resp = ctx.response;

        // Receipt responses MUST be Cache-Control: private (spec §11.10),
        // merged across any existing directives.
        let existing_cc = resp
            .headers()
            .get_all(http_types::header::CACHE_CONTROL)
            .iter()
            .filter_map(|v| v.to_str().ok())
            .collect::<Vec<_>>()
            .join(", ");
        let cache_control = with_private_cache_control(Some(existing_cc.as_str()));
        if let Ok(value) = http_types::HeaderValue::from_str(&cache_control) {
            resp.headers_mut()
                .insert(http_types::header::CACHE_CONTROL, value);
        }

        if let Ok(value) = http_types::HeaderValue::from_str(&receipt_header) {
            resp.headers_mut()
                .insert(crate::protocol::core::PAYMENT_RECEIPT_HEADER, value);
        }
        resp
    }
}

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

    #[test]
    fn test_http_transport_name() {
        let transport = http();
        assert_eq!(transport.name(), "http");
    }

    #[test]
    fn test_http_get_credential_none() {
        let transport = http();
        let req = http_types::Request::builder()
            .uri("/test")
            .body(())
            .unwrap();
        let result = transport.get_credential(&req).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_http_get_credential_non_payment_auth() {
        let transport = http();
        let req = http_types::Request::builder()
            .uri("/test")
            .header("Authorization", "Bearer some-token")
            .body(())
            .unwrap();
        let result = transport.get_credential(&req).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_http_get_credential_valid_payment() {
        let transport = http();

        // Build a valid Payment authorization header
        let challenge = PaymentChallenge::new(
            "test-id",
            "test.example.com",
            "tempo",
            "charge",
            crate::protocol::core::Base64UrlJson::from_value(
                &serde_json::json!({"amount": "1000"}),
            )
            .unwrap(),
        );
        let credential = crate::protocol::core::PaymentCredential::new(
            challenge.to_echo(),
            crate::protocol::core::PaymentPayload::hash("0xdeadbeef"),
        );
        let auth_header = crate::protocol::core::format_authorization(&credential).unwrap();

        let req = http_types::Request::builder()
            .uri("/test")
            .header("Authorization", &auth_header)
            .body(())
            .unwrap();

        let result = transport.get_credential(&req).unwrap();
        assert!(result.is_some(), "should parse valid Payment credential");
        let parsed = result.unwrap();
        assert_eq!(parsed.challenge.id, "test-id");
    }

    #[test]
    fn test_http_get_credential_from_payment_authorization() {
        let transport = http().requires_auth(true);

        let mut challenge = PaymentChallenge::new(
            "test-id",
            "test.example.com",
            "tempo",
            "charge",
            crate::protocol::core::Base64UrlJson::from_value(
                &serde_json::json!({"amount": "1000"}),
            )
            .unwrap(),
        );
        challenge.header = Some("Payment-Authorization".to_string());
        let credential = crate::protocol::core::PaymentCredential::new(
            challenge.to_echo(),
            crate::protocol::core::PaymentPayload::hash("0xdeadbeef"),
        );
        let auth_header = crate::protocol::core::format_authorization(&credential).unwrap();

        let req = http_types::Request::builder()
            .uri("/test")
            .header("Authorization", "Bearer ordinary-authentication")
            .header("Payment-Authorization", &auth_header)
            .body(())
            .unwrap();

        let result = transport.get_credential(&req).unwrap();
        assert!(
            result.is_some(),
            "should parse Payment-Authorization credential"
        );
        let parsed = result.unwrap();
        assert_eq!(parsed.challenge.id, "test-id");
    }

    #[test]
    fn test_http_respond_challenge() {
        let transport = http();
        let challenge = PaymentChallenge::new(
            "test-id",
            "test.example.com",
            "tempo",
            "charge",
            crate::protocol::core::Base64UrlJson::from_value(
                &serde_json::json!({"amount": "1000"}),
            )
            .unwrap(),
        );
        let req = http_types::Request::builder()
            .uri("/test")
            .body(())
            .unwrap();

        let resp = transport.respond_challenge(ChallengeContext {
            challenge: &challenge,
            input: &req,
            error: None,
        });

        assert_eq!(resp.status(), http_types::StatusCode::PAYMENT_REQUIRED);
        assert!(resp
            .headers()
            .get(http_types::header::WWW_AUTHENTICATE)
            .is_some());
        assert!(resp.body().contains("Payment Required"));
    }

    #[test]
    fn test_http_respond_challenge_with_error() {
        let transport = http();
        let challenge = PaymentChallenge::new(
            "test-id",
            "test.example.com",
            "tempo",
            "charge",
            crate::protocol::core::Base64UrlJson::from_value(
                &serde_json::json!({"amount": "1000"}),
            )
            .unwrap(),
        );
        let req = http_types::Request::builder()
            .uri("/test")
            .body(())
            .unwrap();

        let resp = transport.respond_challenge(ChallengeContext {
            challenge: &challenge,
            input: &req,
            error: Some("Verification failed"),
        });

        assert_eq!(resp.status(), http_types::StatusCode::PAYMENT_REQUIRED);
        assert!(resp.body().contains("Verification failed"));
    }

    #[test]
    fn test_http_respond_receipt() {
        let transport = http();
        let receipt = Receipt::success("tempo", "0xabc123");

        let resp = http_types::Response::builder()
            .status(http_types::StatusCode::OK)
            .body("ok".to_string())
            .unwrap();

        let resp = transport.respond_receipt(ReceiptContext {
            challenge_id: "ch-1",
            receipt: &receipt,
            response: resp,
        });

        assert_eq!(resp.status(), http_types::StatusCode::OK);
        assert!(resp
            .headers()
            .get(crate::protocol::core::PAYMENT_RECEIPT_HEADER)
            .is_some());
        // Per spec, receipt responses must be Cache-Control: private.
        assert_eq!(
            resp.headers()
                .get(http_types::header::CACHE_CONTROL)
                .unwrap(),
            "private"
        );
    }

    #[test]
    fn test_http_respond_receipt_merges_existing_cache_control() {
        let transport = http();
        let receipt = Receipt::success("tempo", "0xabc123");

        let resp = http_types::Response::builder()
            .status(http_types::StatusCode::OK)
            .header(http_types::header::CACHE_CONTROL, "no-store")
            .body("ok".to_string())
            .unwrap();

        let resp = transport.respond_receipt(ReceiptContext {
            challenge_id: "ch-1",
            receipt: &receipt,
            response: resp,
        });

        // Existing directive preserved, `private` appended (not overwritten).
        assert_eq!(
            resp.headers()
                .get(http_types::header::CACHE_CONTROL)
                .unwrap(),
            "no-store, private"
        );
    }

    #[test]
    fn test_http_respond_receipt_merges_multiple_cache_control_values() {
        let transport = http();
        let receipt = Receipt::success("tempo", "0xabc123");

        // Two separate Cache-Control header lines (both valid HTTP).
        let resp = http_types::Response::builder()
            .status(http_types::StatusCode::OK)
            .header(http_types::header::CACHE_CONTROL, "no-cache")
            .header(http_types::header::CACHE_CONTROL, "max-age=60")
            .body("ok".to_string())
            .unwrap();

        let resp = transport.respond_receipt(ReceiptContext {
            challenge_id: "ch-1",
            receipt: &receipt,
            response: resp,
        });

        // Both existing directives preserved (not dropped) and `private` added,
        // collapsed into a single normalized header value.
        let values: Vec<_> = resp
            .headers()
            .get_all(http_types::header::CACHE_CONTROL)
            .iter()
            .map(|v| v.to_str().unwrap())
            .collect();
        assert_eq!(values, vec!["no-cache, max-age=60, private"]);
    }
}