mx20022-validate 0.2.0

ISO 20022 message validation: XSD constraints, IBAN/BIC/LEI rules, FedNow, SEPA, and CBPR+ scheme checks
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
//! `FedNow` payment scheme validator.
//!
//! The Federal Reserve's real-time gross settlement service imposes
//! additional constraints on top of the base ISO 20022 schema:
//!
//! - Only USD transactions are accepted.
//! - Settlement method must be `CLRG`.
//! - Charges bearer must be `SLEV`.
//! - A single transaction per group (`NbOfTxs = "1"`).
//! - UETR is mandatory (UUID v4 format).
//! - End-to-end ID is mandatory (≤ 35 characters).
//! - Amount in `[0.01, 500_000.00]` USD (the upper bound is configurable up to
//!   25,000,000.00 USD for high-value participants).
//! - Message size limits: 64 KB for pacs.008 / pacs.004, 32 KB for pacs.028.

use std::any::Any;
use std::sync::OnceLock;

use regex::Regex;

use super::xml_scan::{extract_attribute, extract_element, has_element, xml_byte_size};
use super::SchemeValidator;
use crate::error::{Severity, ValidationError, ValidationResult};

/// `FedNow` scheme validator.
///
/// # Examples
///
/// ```
/// use mx20022_validate::schemes::fednow::FedNowValidator;
/// use mx20022_validate::schemes::SchemeValidator;
///
/// let validator = FedNowValidator::new();
/// assert_eq!(validator.name(), "FedNow");
/// assert!(validator.supported_messages().contains(&"pacs.008"));
/// ```
pub struct FedNowValidator {
    /// Maximum permitted settlement amount in USD cents.
    max_amount_cents: u64,
}

impl FedNowValidator {
    /// Create a validator with the standard 500,000 USD limit.
    pub fn new() -> Self {
        Self {
            max_amount_cents: 50_000_000,
        }
    }

    /// Create a validator with a custom maximum amount (e.g. 25,000,000 USD for
    /// high-value participants).
    ///
    /// # Panics
    ///
    /// Panics if `max_amount` is not positive or not finite.
    pub fn with_max_amount(max_amount: f64) -> Self {
        assert!(
            max_amount > 0.0 && max_amount.is_finite(),
            "max_amount must be positive and finite"
        );
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        Self {
            max_amount_cents: (max_amount * 100.0).round() as u64,
        }
    }
}

impl Default for FedNowValidator {
    fn default() -> Self {
        Self::new()
    }
}

/// Compiled UUID v4 regex, cached for the lifetime of the process.
fn uetr_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
            .expect("valid regex")
    })
}

/// UUID v4 pattern (8-4-4-4-12 hex groups).
fn is_valid_uetr(value: &str) -> bool {
    uetr_re().is_match(value)
}

impl SchemeValidator for FedNowValidator {
    fn name(&self) -> &'static str {
        "FedNow"
    }

    fn supported_messages(&self) -> &[&str] {
        &[
            "pacs.008", "pacs.002", "pacs.004", "pacs.028", "camt.056", "pain.013",
        ]
    }

    fn validate(&self, xml: &str, message_type: &str) -> ValidationResult {
        let short_type = super::short_message_type(message_type);

        if !self.supported_messages().contains(&short_type.as_str()) {
            return ValidationResult::default();
        }

        let mut errors: Vec<ValidationError> = Vec::new();

        // --- Message size ---------------------------------------------------
        let size = xml_byte_size(xml);
        let size_limit: usize = if short_type == "pacs.028" {
            32 * 1024
        } else {
            64 * 1024
        };
        if size > size_limit {
            errors.push(ValidationError::new(
                "/Document",
                Severity::Error,
                "FEDNOW_MSG_SIZE",
                format!(
                    "Message size {size} bytes exceeds FedNow limit of {size_limit} bytes for {short_type}"
                ),
            ));
        }

        // The remaining checks are pacs.008-specific field rules.
        if short_type != "pacs.008" {
            return ValidationResult::new(errors);
        }

        // --- NbOfTxs must be "1" -------------------------------------------
        if let Some(nb) = extract_element(xml, "NbOfTxs") {
            if nb != "1" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/GrpHdr/NbOfTxs",
                    Severity::Error,
                    "FEDNOW_SINGLE_TX",
                    format!(
                        "FedNow requires exactly one transaction per group (NbOfTxs = \"1\"), got \"{nb}\""
                    ),
                ));
            }
        }

        // --- Settlement method must be CLRG ---------------------------------
        if let Some(sttlm_mtd) = extract_element(xml, "SttlmMtd") {
            if sttlm_mtd != "CLRG" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/GrpHdr/SttlmInf/SttlmMtd",
                    Severity::Error,
                    "FEDNOW_STTLM_MTD",
                    format!("FedNow requires SttlmMtd = \"CLRG\", got \"{sttlm_mtd}\""),
                ));
            }
        }

        // --- ChrgBr must be SLEV --------------------------------------------
        if let Some(chrg_br) = extract_element(xml, "ChrgBr") {
            if chrg_br != "SLEV" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                    Severity::Error,
                    "FEDNOW_CHRGBR",
                    format!("FedNow requires ChrgBr = \"SLEV\", got \"{chrg_br}\""),
                ));
            }
        }

        // --- Currency must be USD -------------------------------------------
        if let Some(ccy) = extract_attribute(xml, "IntrBkSttlmAmt", "Ccy") {
            if ccy != "USD" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt/@Ccy",
                    Severity::Error,
                    "FEDNOW_CURRENCY",
                    format!("FedNow only accepts USD transactions; found currency \"{ccy}\""),
                ));
            }
        }

        // --- Amount range ---------------------------------------------------
        if let Some(amt_str) = extract_element(xml, "IntrBkSttlmAmt") {
            self.validate_amount(
                amt_str,
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt",
                &mut errors,
            );
        }

        // --- UETR is required and must be UUID v4 ---------------------------
        if let Some(uetr) = extract_element(xml, "UETR") {
            if !is_valid_uetr(uetr) {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                    Severity::Error,
                    "FEDNOW_UETR_FORMAT",
                    format!("UETR must be a valid UUID v4; got \"{uetr}\""),
                ));
            }
        } else {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                Severity::Error,
                "FEDNOW_UETR_REQUIRED",
                "FedNow requires a UETR (UUID v4) in PmtId",
            ));
        }

        // --- End-to-end ID is required and max 35 chars ---------------------
        if let Some(e2e) = extract_element(xml, "EndToEndId") {
            if e2e.chars().count() > 35 {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/EndToEndId",
                    Severity::Error,
                    "FEDNOW_E2E_LENGTH",
                    format!(
                        "EndToEndId must be at most 35 characters; got {} characters",
                        e2e.chars().count()
                    ),
                ));
            }
        } else {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/EndToEndId",
                Severity::Error,
                "FEDNOW_E2E_REQUIRED",
                "FedNow requires an EndToEndId in PmtId",
            ));
        }

        // --- Debtor name max 140 chars --------------------------------------
        // We check the first <Nm> inside <Dbtr>. A simple heuristic: scan for
        // the Dbtr block and extract the Nm within it.
        check_name_length(xml, "Dbtr", &mut errors, "FEDNOW_DBTR_NM_LENGTH");
        check_name_length(xml, "Cdtr", &mut errors, "FEDNOW_CDTR_NM_LENGTH");

        // --- RmtInf/Ustrd max 140 chars per element -------------------------
        for ustrd in super::xml_scan::extract_all_elements(xml, "Ustrd") {
            if ustrd.chars().count() > 140 {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/Ustrd",
                    Severity::Error,
                    "FEDNOW_USTRD_LENGTH",
                    format!(
                        "Ustrd element must be at most 140 characters; got {} characters",
                        ustrd.chars().count()
                    ),
                ));
            }
        }

        // --- AppHdr presence is a soft check (not required but common) ------
        if !has_element(xml, "AppHdr") && !has_element(xml, "BizMsgIdr") {
            errors.push(ValidationError::new(
                "/AppHdr",
                Severity::Warning,
                "FEDNOW_APPHDR_MISSING",
                "Business Application Header (AppHdr) is recommended for FedNow messages",
            ));
        }

        ValidationResult::new(errors)
    }

    fn validate_typed(&self, msg: &dyn Any, message_type: &str) -> Option<ValidationResult> {
        use mx20022_model::generated::pacs::pacs_008_001_13;

        let short_type = super::short_message_type(message_type);
        if !self.supported_messages().contains(&short_type.as_str()) {
            return None;
        }

        // Only pacs.008 has typed field-level checks.
        if short_type != "pacs.008" {
            return None;
        }

        let doc = msg.downcast_ref::<pacs_008_001_13::Document>()?;

        Some(self.validate_pacs008_typed(doc))
    }
}

impl FedNowValidator {
    fn validate_amount(&self, amt_str: &str, path: &str, errors: &mut Vec<ValidationError>) {
        let decimal_ok = amt_str
            .find('.')
            .is_some_and(|dot| amt_str.len() - dot - 1 == 2);
        if !decimal_ok {
            errors.push(ValidationError::new(
                path,
                Severity::Error,
                "FEDNOW_AMOUNT_DECIMALS",
                format!("FedNow amounts must have exactly 2 decimal places; got \"{amt_str}\""),
            ));
        }
        match parse_amount_cents(amt_str) {
            Some(cents) => {
                if cents < 1 {
                    errors.push(ValidationError::new(
                        path,
                        Severity::Error,
                        "FEDNOW_AMOUNT_MIN",
                        format!("FedNow minimum amount is 0.01 USD; got \"{amt_str}\""),
                    ));
                }
                if cents > self.max_amount_cents {
                    errors.push(ValidationError::new(
                        path,
                        Severity::Error,
                        "FEDNOW_AMOUNT_LIMIT",
                        format!(
                            "FedNow maximum amount is {}.{:02} USD; got \"{amt_str}\"",
                            self.max_amount_cents / 100,
                            self.max_amount_cents % 100
                        ),
                    ));
                }
            }
            None => {
                errors.push(ValidationError::new(
                    path,
                    Severity::Error,
                    "FEDNOW_AMOUNT_FORMAT",
                    format!("Cannot parse amount as a number: \"{amt_str}\""),
                ));
            }
        }
    }

    /// Typed validation for pacs.008 messages.
    fn validate_pacs008_typed(
        &self,
        doc: &mx20022_model::generated::pacs::pacs_008_001_13::Document,
    ) -> ValidationResult {
        use mx20022_model::generated::pacs::pacs_008_001_13::{
            ChargeBearerType1Code, SettlementMethod1Code,
        };

        let mut errors: Vec<ValidationError> = Vec::new();
        let msg = &doc.fi_to_fi_cstmr_cdt_trf;

        // --- NbOfTxs must be "1" -------------------------------------------
        if msg.grp_hdr.nb_of_txs.0 != "1" {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/GrpHdr/NbOfTxs",
                Severity::Error,
                "FEDNOW_SINGLE_TX",
                format!(
                    "FedNow requires exactly one transaction per group (NbOfTxs = \"1\"), got \"{}\"",
                    msg.grp_hdr.nb_of_txs.0
                ),
            ));
        }

        // --- Settlement method must be CLRG ---------------------------------
        if msg.grp_hdr.sttlm_inf.sttlm_mtd != SettlementMethod1Code::Clrg {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/GrpHdr/SttlmInf/SttlmMtd",
                Severity::Error,
                "FEDNOW_STTLM_MTD",
                format!(
                    "FedNow requires SttlmMtd = \"CLRG\", got {:?}",
                    msg.grp_hdr.sttlm_inf.sttlm_mtd
                ),
            ));
        }

        // Validate each credit transfer transaction.
        for tx in &msg.cdt_trf_tx_inf {
            // --- ChrgBr must be SLEV ----------------------------------------
            if tx.chrg_br != ChargeBearerType1Code::Slev {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                    Severity::Error,
                    "FEDNOW_CHRGBR",
                    format!("FedNow requires ChrgBr = \"SLEV\", got {:?}", tx.chrg_br),
                ));
            }

            // --- Currency must be USD ---------------------------------------
            let ccy = &tx.intr_bk_sttlm_amt.ccy.0;
            if ccy != "USD" {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt/@Ccy",
                    Severity::Error,
                    "FEDNOW_CURRENCY",
                    format!("FedNow only accepts USD transactions; found currency \"{ccy}\""),
                ));
            }

            // --- Amount range -----------------------------------------------
            let amt_str = &tx.intr_bk_sttlm_amt.value.0;
            self.validate_amount(
                amt_str,
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmAmt",
                &mut errors,
            );

            // --- UETR is required and must be UUID v4 -----------------------
            match &tx.pmt_id.uetr {
                Some(uetr) if !is_valid_uetr(&uetr.0) => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                        Severity::Error,
                        "FEDNOW_UETR_FORMAT",
                        format!("UETR must be a valid UUID v4; got \"{}\"", uetr.0),
                    ));
                }
                None => {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                        Severity::Error,
                        "FEDNOW_UETR_REQUIRED",
                        "FedNow requires a UETR (UUID v4) in PmtId",
                    ));
                }
                Some(_) => {} // Valid UETR
            }

            // --- End-to-end ID is required (length covered by XSD) ----------
            // Max35Text is the type — XSD validation handles the 35-char limit.
            // We only need to check it's not empty/whitespace for FedNow.
            if tx.pmt_id.end_to_end_id.0.trim().is_empty() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/EndToEndId",
                    Severity::Error,
                    "FEDNOW_E2E_REQUIRED",
                    "FedNow requires a non-empty EndToEndId in PmtId",
                ));
            }

            // --- Debtor name max 140 chars ----------------------------------
            if let Some(nm) = &tx.dbtr.nm {
                if nm.0.chars().count() > 140 {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Dbtr/Nm",
                        Severity::Error,
                        "FEDNOW_DBTR_NM_LENGTH",
                        format!(
                            "Dbtr/Nm must be at most 140 characters; got {} characters",
                            nm.0.chars().count()
                        ),
                    ));
                }
            }

            // --- Creditor name max 140 chars --------------------------------
            if let Some(nm) = &tx.cdtr.nm {
                if nm.0.chars().count() > 140 {
                    errors.push(ValidationError::new(
                        "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Cdtr/Nm",
                        Severity::Error,
                        "FEDNOW_CDTR_NM_LENGTH",
                        format!(
                            "Cdtr/Nm must be at most 140 characters; got {} characters",
                            nm.0.chars().count()
                        ),
                    ));
                }
            }

            // --- RmtInf/Ustrd max 140 chars per element ---------------------
            if let Some(rmt_inf) = &tx.rmt_inf {
                for ustrd in &rmt_inf.ustrd {
                    if ustrd.0.chars().count() > 140 {
                        errors.push(ValidationError::new(
                            "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/Ustrd",
                            Severity::Error,
                            "FEDNOW_USTRD_LENGTH",
                            format!(
                                "Ustrd element must be at most 140 characters; got {} characters",
                                ustrd.0.chars().count()
                            ),
                        ));
                    }
                }
            }
        }

        // Note: AppHdr check and message size check require raw XML and are
        // not covered by the typed path. Those remain in the XML-based
        // `validate` method.

        ValidationResult::new(errors)
    }
}

// Amount parsing functions are defined in `super::common`.
use super::common::parse_amount_cents;

/// Check that the `<Nm>` child inside `<parent_tag>` does not exceed 140 chars.
fn check_name_length(
    xml: &str,
    parent_tag: &str,
    errors: &mut Vec<ValidationError>,
    rule_id: &str,
) {
    let path = format!("/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/{parent_tag}");
    super::common::check_name_in_parent(
        xml,
        parent_tag,
        Some(140),
        &path,
        rule_id,
        "FedNow",
        errors,
        false, // FedNow doesn't require names, only limits length
    );
}

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

    #[test]
    fn name_is_fednow() {
        assert_eq!(FedNowValidator::new().name(), "FedNow");
    }

    #[test]
    fn supports_pacs008() {
        let v = FedNowValidator::new();
        assert!(v.supported_messages().contains(&"pacs.008"));
    }

    #[test]
    fn unsupported_message_returns_empty() {
        let v = FedNowValidator::new();
        let result = v.validate("<xml/>", "pacs.009.001.10");
        assert!(result.errors.is_empty());
    }

    #[test]
    fn valid_uetr_accepted() {
        assert!(is_valid_uetr("97ed4827-7b6f-4491-a06f-b548d5a7512d"));
    }

    #[test]
    fn invalid_uetr_rejected() {
        assert!(!is_valid_uetr("not-a-uuid"));
        assert!(!is_valid_uetr("97ed4827-7b6f-3491-a06f-b548d5a7512d")); // version 3, not 4
    }

    #[test]
    fn default_max_amount_is_500k() {
        let v = FedNowValidator::default();
        assert_eq!(v.max_amount_cents, 50_000_000);
    }

    #[test]
    fn custom_max_amount() {
        let v = FedNowValidator::with_max_amount(25_000_000.0);
        assert_eq!(v.max_amount_cents, 2_500_000_000);
    }
}