mpay 0.2.0

Machine Payment Protocol - Rust library for Web Payment Auth
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
//! Header parsing and formatting functions for Web Payment Auth.
//!
//! This module provides functions to parse and format the HTTP headers used
//! in the Web Payment Auth protocol:
//!
//! - `WWW-Authenticate: Payment ...` - Challenge from server
//! - `Authorization: Payment ...` - Credential from client  
//! - `Payment-Receipt: ...` - Receipt from server
//!
//! The parser is implemented without regex for minimal dependencies.

use super::challenge::{PaymentChallenge, PaymentCredential, Receipt};
use super::types::{base64url_decode, base64url_encode, Base64UrlJson, IntentName, MethodName};
use crate::error::{MppError, Result};
use std::collections::HashMap;

/// Maximum length for base64url-encoded tokens to prevent memory exhaustion DoS.
const MAX_TOKEN_LEN: usize = 16 * 1024;

/// Macro to extract a required parameter from the params map.
macro_rules! require_param {
    ($params:expr, $key:literal) => {
        $params.get($key).ok_or_else(|| {
            MppError::invalid_challenge_reason(format!("Missing '{}' field", $key))
        })?
    };
}

/// Strip the Payment scheme prefix (case-insensitive) from a header value.
/// Returns the remainder of the header after the scheme, or None if not a Payment header.
fn strip_payment_scheme(header: &str) -> Option<&str> {
    let header = header.trim_start();
    let scheme_len = PAYMENT_SCHEME.len();

    if header.len() >= scheme_len
        && header
            .get(..scheme_len)
            .is_some_and(|s| s.eq_ignore_ascii_case(PAYMENT_SCHEME))
    {
        header.get(scheme_len..)
    } else {
        None
    }
}

/// Escape a string for use in a quoted-string header value.
/// Rejects CRLF to prevent header injection attacks.
fn escape_quoted_value(s: &str) -> Result<String> {
    if s.contains('\r') || s.contains('\n') {
        return Err(MppError::invalid_challenge_reason(
            "Header value contains invalid CRLF characters",
        ));
    }
    Ok(s.replace('\\', "\\\\").replace('"', "\\\""))
}

/// Header name for payment challenges (from server)
pub const WWW_AUTHENTICATE_HEADER: &str = "www-authenticate";

/// Header name for payment credentials (from client)
pub const AUTHORIZATION_HEADER: &str = "authorization";

/// Header name for payment receipts (from server)
pub const PAYMENT_RECEIPT_HEADER: &str = "payment-receipt";

/// Scheme identifier for the Payment authentication scheme
pub const PAYMENT_SCHEME: &str = "Payment";

/// Parse key="value" pairs from an auth-param string.
///
/// This is a simple parser that handles:
/// - Quoted string values with escaped quotes
/// - Key=value without quotes for simple values
/// - Comma or space separated parameters
fn parse_auth_params(params_str: &str) -> HashMap<String, String> {
    let mut params = HashMap::new();
    let chars: Vec<char> = params_str.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        while i < chars.len() && (chars[i].is_whitespace() || chars[i] == ',') {
            i += 1;
        }
        if i >= chars.len() {
            break;
        }

        let key_start = i;
        while i < chars.len() && chars[i] != '=' && !chars[i].is_whitespace() {
            i += 1;
        }
        if i >= chars.len() || chars[i] != '=' {
            while i < chars.len() && !chars[i].is_whitespace() && chars[i] != ',' {
                i += 1;
            }
            continue;
        }

        let key: String = chars[key_start..i].iter().collect();
        i += 1;

        if i >= chars.len() {
            break;
        }

        let value = if chars[i] == '"' {
            i += 1;
            let mut value = String::new();
            while i < chars.len() && chars[i] != '"' {
                if chars[i] == '\\' && i + 1 < chars.len() {
                    i += 1;
                    value.push(chars[i]);
                } else {
                    value.push(chars[i]);
                }
                i += 1;
            }
            if i < chars.len() {
                i += 1;
            }
            value
        } else {
            let value_start = i;
            while i < chars.len() && !chars[i].is_whitespace() && chars[i] != ',' {
                i += 1;
            }
            chars[value_start..i].iter().collect()
        };

        params.insert(key, value);
    }

    params
}

/// Parse a single WWW-Authenticate header into a PaymentChallenge.
///
/// Format: `Payment id="<id>", realm="<realm>", method="<method>", intent="<intent>", request="<base64url-json>"`
///
/// Parsing is case-insensitive for the scheme name per RFC 7235.
///
/// # Examples
///
/// ```
/// use mpay::protocol::core::parse_www_authenticate;
///
/// let header = r#"Payment id="abc123", realm="api", method="tempo", intent="charge", request="eyJhbW91bnQiOiIxMDAwMCJ9""#;
/// let challenge = parse_www_authenticate(header).unwrap();
/// assert_eq!(challenge.id, "abc123");
/// ```
pub fn parse_www_authenticate(header: &str) -> Result<PaymentChallenge> {
    let rest = strip_payment_scheme(header).ok_or_else(|| {
        MppError::invalid_challenge_reason("Expected 'Payment' scheme".to_string())
    })?;

    let params_str = rest
        .strip_prefix(' ')
        .or_else(|| rest.strip_prefix('\t'))
        .ok_or_else(|| {
            MppError::invalid_challenge_reason("Expected space after 'Payment' scheme".to_string())
        })?
        .trim_start();
    let params = parse_auth_params(params_str);

    let id = require_param!(params, "id").clone();
    let realm = require_param!(params, "realm").clone();
    let method = MethodName::new(require_param!(params, "method"));
    let intent = IntentName::new(require_param!(params, "intent"));
    let request_b64 = require_param!(params, "request").clone();

    let _ = base64url_decode(&request_b64)?;
    let request = Base64UrlJson::from_raw(request_b64);

    Ok(PaymentChallenge {
        id,
        realm,
        method,
        intent,
        request,
        expires: params.get("expires").cloned(),
        description: params.get("description").cloned(),
        digest: params.get("digest").cloned(),
    })
}

/// Parse all WWW-Authenticate headers that use the Payment scheme.
///
/// Returns a Vec of Results - one for each Payment header found.
/// Non-Payment headers are skipped.
///
/// # Examples
///
/// ```
/// use mpay::protocol::core::parse_www_authenticate_all;
///
/// let headers = vec![
///     "Bearer token",
///     "Payment id=\"abc\", realm=\"api\", method=\"tempo\", intent=\"charge\", request=\"e30\"",
///     "Payment id=\"def\", realm=\"api\", method=\"base\", intent=\"charge\", request=\"e30\"",
/// ];
/// let challenges = parse_www_authenticate_all(headers);
/// assert_eq!(challenges.len(), 2);
/// ```
pub fn parse_www_authenticate_all<'a>(
    headers: impl IntoIterator<Item = &'a str>,
) -> Vec<Result<PaymentChallenge>> {
    headers
        .into_iter()
        .filter(|h| {
            h.trim_start()
                .get(..8)
                .is_some_and(|s| s.eq_ignore_ascii_case("payment "))
        })
        .map(parse_www_authenticate)
        .collect()
}

/// Format a PaymentChallenge as a WWW-Authenticate header value.
///
/// Format: `Payment id="<id>", realm="<realm>", method="<method>", intent="<intent>", request="<base64url-json>"`
///
/// # Examples
///
/// ```
/// use mpay::protocol::core::{PaymentChallenge, format_www_authenticate};
/// use mpay::protocol::core::types::Base64UrlJson;
///
/// let challenge = PaymentChallenge {
///     id: "abc123".to_string(),
///     realm: "api".to_string(),
///     method: "tempo".into(),
///     intent: "charge".into(),
///     request: Base64UrlJson::from_value(&serde_json::json!({"amount": "1000"})).unwrap(),
///     expires: None,
///     description: None,
///     digest: None,
/// };
/// let header = format_www_authenticate(&challenge).unwrap();
/// assert!(header.starts_with("Payment id=\"abc123\""));
/// ```
pub fn format_www_authenticate(challenge: &PaymentChallenge) -> Result<String> {
    // Escape all quoted values to prevent header injection
    let mut parts = vec![
        format!("id=\"{}\"", escape_quoted_value(&challenge.id)?),
        format!("realm=\"{}\"", escape_quoted_value(&challenge.realm)?),
        format!(
            "method=\"{}\"",
            escape_quoted_value(challenge.method.as_str())?
        ),
        format!(
            "intent=\"{}\"",
            escape_quoted_value(challenge.intent.as_str())?
        ),
        format!(
            "request=\"{}\"",
            escape_quoted_value(challenge.request.raw())?
        ),
    ];

    if let Some(ref expires) = challenge.expires {
        parts.push(format!("expires=\"{}\"", escape_quoted_value(expires)?));
    }

    if let Some(ref description) = challenge.description {
        parts.push(format!(
            "description=\"{}\"",
            escape_quoted_value(description)?
        ));
    }

    if let Some(ref digest) = challenge.digest {
        parts.push(format!("digest=\"{}\"", escape_quoted_value(digest)?));
    }

    Ok(format!("Payment {}", parts.join(", ")))
}

/// Format multiple challenges as WWW-Authenticate header values.
///
/// Per spec, servers can send multiple headers with different payment options.
///
/// # Examples
///
/// ```
/// use mpay::protocol::core::{PaymentChallenge, format_www_authenticate_many};
/// use mpay::protocol::core::types::Base64UrlJson;
///
/// let challenge = PaymentChallenge {
///     id: "abc123".to_string(),
///     realm: "api".to_string(),
///     method: "tempo".into(),
///     intent: "charge".into(),
///     request: Base64UrlJson::from_value(&serde_json::json!({"amount": "1000"})).unwrap(),
///     expires: None,
///     description: None,
///     digest: None,
/// };
/// let headers = format_www_authenticate_many(&[challenge]).unwrap();
/// assert_eq!(headers.len(), 1);
/// ```
pub fn format_www_authenticate_many(challenges: &[PaymentChallenge]) -> Result<Vec<String>> {
    challenges.iter().map(format_www_authenticate).collect()
}

/// Parse an Authorization header into a PaymentCredential.
///
/// Format: `Payment <base64url-json>`
pub fn parse_authorization(header: &str) -> Result<PaymentCredential> {
    let rest = strip_payment_scheme(header).ok_or_else(|| {
        MppError::invalid_challenge_reason("Expected 'Payment' scheme".to_string())
    })?;

    let token = rest.trim();

    // Enforce size limit to prevent memory exhaustion DoS
    if token.len() > MAX_TOKEN_LEN {
        return Err(MppError::invalid_challenge_reason(format!(
            "Token exceeds maximum length of {} bytes",
            MAX_TOKEN_LEN
        )));
    }

    let decoded = base64url_decode(token)?;
    let credential: PaymentCredential = serde_json::from_slice(&decoded).map_err(|e| {
        MppError::invalid_challenge_reason(format!("Invalid credential JSON: {}", e))
    })?;

    Ok(credential)
}

/// Format a PaymentCredential as an Authorization header value.
///
/// Format: `Payment <base64url-json>`
pub fn format_authorization(credential: &PaymentCredential) -> Result<String> {
    let json = serde_json::to_string(credential)?;
    let encoded = base64url_encode(json.as_bytes());
    Ok(format!("Payment {}", encoded))
}

/// Parse a Payment-Receipt header into a Receipt.
///
/// Format: `<base64url-json>`
pub fn parse_receipt(header: &str) -> Result<Receipt> {
    let token = header.trim();

    // Enforce size limit to prevent memory exhaustion DoS
    if token.len() > MAX_TOKEN_LEN {
        return Err(MppError::invalid_challenge_reason(format!(
            "Receipt exceeds maximum length of {} bytes",
            MAX_TOKEN_LEN
        )));
    }

    let decoded = base64url_decode(token)?;
    let receipt: Receipt = serde_json::from_slice(&decoded)
        .map_err(|e| MppError::invalid_challenge_reason(format!("Invalid receipt JSON: {}", e)))?;

    Ok(receipt)
}

/// Format a Receipt as a Payment-Receipt header value.
///
/// Format: `<base64url-json>`
pub fn format_receipt(receipt: &Receipt) -> Result<String> {
    let json = serde_json::to_string(receipt)?;
    Ok(base64url_encode(json.as_bytes()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::core::types::{PayloadType, ReceiptStatus};
    use crate::protocol::core::PaymentPayload;

    fn test_challenge() -> PaymentChallenge {
        PaymentChallenge {
            id: "abc123".to_string(),
            realm: "api".to_string(),
            method: "tempo".into(),
            intent: "charge".into(),
            request: Base64UrlJson::from_value(&serde_json::json!({
                "amount": "10000",
                "currency": "0x123"
            }))
            .unwrap(),
            expires: Some("2024-01-01T00:00:00Z".to_string()),
            description: None,
            digest: None,
        }
    }

    #[test]
    fn test_parse_www_authenticate() {
        let challenge = test_challenge();
        let header = format_www_authenticate(&challenge).unwrap();
        let parsed = parse_www_authenticate(&header).unwrap();

        assert_eq!(parsed.id, "abc123");
        assert_eq!(parsed.realm, "api");
        assert_eq!(parsed.method.as_str(), "tempo");
        assert_eq!(parsed.intent.as_str(), "charge");
        assert_eq!(parsed.expires, Some("2024-01-01T00:00:00Z".to_string()));

        // Verify request decodes correctly
        let request: serde_json::Value = parsed.request.decode_value().unwrap();
        assert_eq!(request["amount"], "10000");
    }

    #[test]
    fn test_parse_www_authenticate_case_insensitive() {
        let header =
            r#"payment id="test", realm="api", method="tempo", intent="charge", request="e30""#;
        let parsed = parse_www_authenticate(header).unwrap();
        assert_eq!(parsed.id, "test");

        let header2 =
            r#"PAYMENT id="test2", realm="api", method="tempo", intent="charge", request="e30""#;
        let parsed2 = parse_www_authenticate(header2).unwrap();
        assert_eq!(parsed2.id, "test2");
    }

    #[test]
    fn test_parse_www_authenticate_leading_whitespace() {
        let header =
            r#"  Payment id="test", realm="api", method="tempo", intent="charge", request="e30""#;
        let parsed = parse_www_authenticate(header).unwrap();
        assert_eq!(parsed.id, "test");
    }

    #[test]
    fn test_parse_www_authenticate_with_description() {
        let mut challenge = test_challenge();
        challenge.description = Some("Pay \"here\" now".to_string());
        let header = format_www_authenticate(&challenge).unwrap();

        assert!(header.contains("description=\"Pay \\\"here\\\" now\""));

        let parsed = parse_www_authenticate(&header).unwrap();
        assert_eq!(parsed.description, Some("Pay \"here\" now".to_string()));
    }

    #[test]
    fn test_parse_www_authenticate_all() {
        let headers = vec![
            "Bearer token",
            r#"Payment id="a", realm="api", method="tempo", intent="charge", request="e30""#,
            "Basic xyz",
            r#"Payment id="b", realm="api", method="base", intent="charge", request="e30""#,
        ];

        let results = parse_www_authenticate_all(headers);
        assert_eq!(results.len(), 2);

        let first = results[0].as_ref().unwrap();
        assert_eq!(first.id, "a");

        let second = results[1].as_ref().unwrap();
        assert_eq!(second.id, "b");
    }

    #[test]
    fn test_format_www_authenticate_many() {
        let c1 = test_challenge();
        let mut c2 = test_challenge();
        c2.id = "def456".to_string();
        c2.method = "base".into();

        let headers = format_www_authenticate_many(&[c1, c2]).unwrap();
        assert_eq!(headers.len(), 2);
        assert!(headers[0].contains("abc123"));
        assert!(headers[1].contains("def456"));
    }

    #[test]
    fn test_parse_authorization() {
        let challenge = test_challenge();
        let credential = PaymentCredential::with_source(
            challenge.to_echo(),
            "did:pkh:eip155:42431:0x123",
            PaymentPayload::transaction("0xabc"),
        );

        let header = format_authorization(&credential).unwrap();
        let parsed = parse_authorization(&header).unwrap();

        assert_eq!(parsed.challenge.id, "abc123");
        assert_eq!(
            parsed.source,
            Some("did:pkh:eip155:42431:0x123".to_string())
        );
        assert_eq!(parsed.payload.signed_tx(), Some("0xabc"));
        assert_eq!(parsed.payload.payload_type(), PayloadType::Transaction);
    }

    #[test]
    fn test_parse_receipt() {
        let receipt = Receipt {
            status: ReceiptStatus::Success,
            method: "tempo".into(),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
            reference: "0xabc123".to_string(),
            error: None,
        };

        let header = format_receipt(&receipt).unwrap();
        let parsed = parse_receipt(&header).unwrap();

        assert_eq!(parsed.status, ReceiptStatus::Success);
        assert_eq!(parsed.method.as_str(), "tempo");
        assert_eq!(parsed.reference, "0xabc123");
    }

    #[test]
    fn test_parse_invalid_scheme() {
        let result = parse_www_authenticate("Basic realm=\"test\"");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_missing_required_field() {
        let result = parse_www_authenticate("Payment id=\"abc\", realm=\"api\"");
        assert!(result.is_err());
    }

    #[test]
    fn test_roundtrip_preserves_request() {
        let original_request = serde_json::json!({
            "amount": "5000",
            "currency": "0xabc",
            "nested": {"key": "value"}
        });
        let mut challenge = test_challenge();
        challenge.request = Base64UrlJson::from_value(&original_request).unwrap();

        let header = format_www_authenticate(&challenge).unwrap();
        let parsed = parse_www_authenticate(&header).unwrap();

        // The raw b64 should be preserved exactly
        assert_eq!(parsed.request.raw(), challenge.request.raw());

        // And should decode to the same value
        let decoded: serde_json::Value = parsed.request.decode_value().unwrap();
        assert_eq!(decoded, original_request);
    }
}