mx20022-validate 0.3.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
//! CBPR+ (Cross-Border Payments and Reporting Plus) scheme validator.
//!
//! Enforces Swift's CBPR+ usage guidelines for pacs.008 and related messages:
//!
//! - Business Application Header (`AppHdr`) is mandatory.
//! - Instructing and instructed agent BICs are required.
//! - Debtor agent and creditor agent BICs are required.
//! - Debtor and creditor names are required.
//! - UETR is mandatory in `PmtId`.
//! - End-to-end ID is mandatory.
//! - Charges bearer (`ChrgBr`) is required and must be one of: CRED, DEBT,
//!   SHAR, SLEV.
//! - Interbank settlement date is required.
//! - All BICs should be 11 characters (8-char BICs generate a warning).
//! - UTF-8 only; no control characters other than LF, CR, TAB.

use std::any::Any;

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

/// CBPR+ scheme validator.
///
/// # Examples
///
/// ```
/// use mx20022_validate::schemes::cbpr::CbprPlusValidator;
/// use mx20022_validate::schemes::SchemeValidator;
///
/// let validator = CbprPlusValidator::new();
/// assert_eq!(validator.name(), "CBPR+");
/// assert!(validator.supported_messages().contains(&"pacs.008"));
/// ```
pub struct CbprPlusValidator;

impl CbprPlusValidator {
    /// Create a new `CbprPlusValidator`.
    pub fn new() -> Self {
        Self
    }
}

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

/// Valid `ChrgBr` values under CBPR+.
const VALID_CHRGBR: &[&str] = &["CRED", "DEBT", "SHAR", "SLEV"];

impl SchemeValidator for CbprPlusValidator {
    fn name(&self) -> &'static str {
        "CBPR+"
    }

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

    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();

        // --- UTF-8 control character check ----------------------------------
        // The XML string is already valid UTF-8 (Rust strings), so we only need
        // to look for disallowed control characters.
        check_control_characters(xml, &mut errors);

        // --- Business Application Header ------------------------------------
        if !has_element(xml, "AppHdr") && !has_element(xml, "BizMsgIdr") {
            errors.push(ValidationError::new(
                "/AppHdr",
                Severity::Error,
                "CBPR_BAH_REQUIRED",
                "CBPR+ requires a Business Application Header (AppHdr / BizMsgIdr)",
            ));
        }

        // Field-level checks are pacs.008-specific.
        if short_type != "pacs.008" {
            return ValidationResult::new(errors);
        }

        // --- Mandatory BICs -------------------------------------------------
        let bic_fields: &[(&str, &str, &str)] = &[
            (
                "InstgAgt",
                "CBPR_INSTG_AGT_BIC",
                "/Document/FIToFICstmrCdtTrf/GrpHdr/InstgAgt/FinInstnId/BICFI",
            ),
            (
                "InstdAgt",
                "CBPR_INSTD_AGT_BIC",
                "/Document/FIToFICstmrCdtTrf/GrpHdr/InstdAgt/FinInstnId/BICFI",
            ),
            (
                "DbtrAgt",
                "CBPR_DBTR_AGT_BIC",
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/DbtrAgt/FinInstnId/BICFI",
            ),
            (
                "CdtrAgt",
                "CBPR_CDTR_AGT_BIC",
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/CdtrAgt/FinInstnId/BICFI",
            ),
        ];
        for (parent, rule_id, path) in bic_fields {
            check_bic_in_parent(xml, parent, path, rule_id, &mut errors);
        }

        // --- Debtor and creditor names required -----------------------------
        check_name_required(xml, "Dbtr", "CBPR_DBTR_NM_REQUIRED", &mut errors);
        check_name_required(xml, "Cdtr", "CBPR_CDTR_NM_REQUIRED", &mut errors);

        // --- UETR required --------------------------------------------------
        if !has_element(xml, "UETR") {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                Severity::Error,
                "CBPR_UETR_REQUIRED",
                "CBPR+ requires a UETR in PmtId",
            ));
        }

        // --- End-to-end ID required -----------------------------------------
        if !has_element(xml, "EndToEndId") {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/EndToEndId",
                Severity::Error,
                "CBPR_E2E_REQUIRED",
                "CBPR+ requires an EndToEndId in PmtId",
            ));
        }

        // --- ChrgBr required and must be valid ------------------------------
        if let Some(chrg_br) = extract_element(xml, "ChrgBr") {
            if !VALID_CHRGBR.contains(&chrg_br) {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                    Severity::Error,
                    "CBPR_CHRGBR_VALUE",
                    format!("ChrgBr must be one of CRED, DEBT, SHAR, SLEV; got \"{chrg_br}\""),
                ));
            }
        } else {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/ChrgBr",
                Severity::Error,
                "CBPR_CHRGBR_REQUIRED",
                "CBPR+ requires ChrgBr (one of CRED, DEBT, SHAR, SLEV)",
            ));
        }

        // --- Interbank settlement date required -----------------------------
        if !has_element(xml, "IntrBkSttlmDt") {
            errors.push(ValidationError::new(
                "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmDt",
                Severity::Error,
                "CBPR_STTLM_DT_REQUIRED",
                "CBPR+ requires IntrBkSttlmDt",
            ));
        }

        // --- BIC padding check (8-char BICs should be 11) ------------------
        for bic in extract_all_elements(xml, "BICFI") {
            if bic.len() == 8 {
                errors.push(ValidationError::new(
                    "//BICFI",
                    Severity::Warning,
                    "CBPR_BIC_PADDING",
                    format!(
                        "CBPR+ recommends 11-character BICs; \"{bic}\" is 8 characters (pad with XXX)"
                    ),
                ));
            }
        }

        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;
        }

        if short_type != "pacs.008" {
            return None;
        }

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

        Some(self.validate_pacs008_typed(doc))
    }
}

impl CbprPlusValidator {
    /// Typed validation for pacs.008 messages under CBPR+ rules.
    #[allow(clippy::unused_self)]
    fn validate_pacs008_typed(
        &self,
        doc: &mx20022_model::generated::pacs::pacs_008_001_13::Document,
    ) -> ValidationResult {
        let mut errors: Vec<ValidationError> = Vec::new();
        let msg = &doc.fi_to_fi_cstmr_cdt_trf;

        // --- Instructing agent BIC required (GrpHdr level) ------------------
        check_bic_typed(
            msg.grp_hdr.instg_agt.as_ref(),
            "InstgAgt",
            "/Document/FIToFICstmrCdtTrf/GrpHdr/InstgAgt/FinInstnId/BICFI",
            "CBPR_INSTG_AGT_BIC",
            &mut errors,
        );

        // --- Instructed agent BIC required (GrpHdr level) -------------------
        check_bic_typed(
            msg.grp_hdr.instd_agt.as_ref(),
            "InstdAgt",
            "/Document/FIToFICstmrCdtTrf/GrpHdr/InstdAgt/FinInstnId/BICFI",
            "CBPR_INSTD_AGT_BIC",
            &mut errors,
        );

        // --- BIC padding check for GrpHdr-level agents ---
        for agent in [
            msg.grp_hdr.instg_agt.as_ref(),
            msg.grp_hdr.instd_agt.as_ref(),
        ]
        .into_iter()
        .flatten()
        {
            if let Some(bic) = &agent.fin_instn_id.bicfi {
                if bic.0.len() == 8 {
                    errors.push(ValidationError::new(
                        "//BICFI",
                        Severity::Warning,
                        "CBPR_BIC_PADDING",
                        format!(
                            "CBPR+ recommends 11-character BICs; \"{}\" is 8 characters (pad with XXX)",
                            bic.0
                        ),
                    ));
                }
            }
        }

        for tx in &msg.cdt_trf_tx_inf {
            // --- Debtor agent BIC required ----------------------------------
            if tx.dbtr_agt.fin_instn_id.bicfi.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/DbtrAgt/FinInstnId/BICFI",
                    Severity::Error,
                    "CBPR_DBTR_AGT_BIC",
                    "DbtrAgt/FinInstnId/BICFI is required for CBPR+",
                ));
            }

            // --- Creditor agent BIC required --------------------------------
            if tx.cdtr_agt.fin_instn_id.bicfi.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/CdtrAgt/FinInstnId/BICFI",
                    Severity::Error,
                    "CBPR_CDTR_AGT_BIC",
                    "CdtrAgt/FinInstnId/BICFI is required for CBPR+",
                ));
            }

            // --- BIC padding check (8-char BICs should be 11) ---------------
            for bic in [
                tx.dbtr_agt.fin_instn_id.bicfi.as_ref(),
                tx.cdtr_agt.fin_instn_id.bicfi.as_ref(),
            ]
            .into_iter()
            .flatten()
            {
                if bic.0.len() == 8 {
                    errors.push(ValidationError::new(
                        "//BICFI",
                        Severity::Warning,
                        "CBPR_BIC_PADDING",
                        format!(
                            "CBPR+ recommends 11-character BICs; \"{}\" is 8 characters (pad with XXX)",
                            bic.0
                        ),
                    ));
                }
            }

            // --- Debtor name required ---------------------------------------
            if tx.dbtr.nm.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Dbtr/Nm",
                    Severity::Error,
                    "CBPR_DBTR_NM_REQUIRED",
                    "Dbtr/Nm is required for CBPR+",
                ));
            }

            // --- Creditor name required -------------------------------------
            if tx.cdtr.nm.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/Cdtr/Nm",
                    Severity::Error,
                    "CBPR_CDTR_NM_REQUIRED",
                    "Cdtr/Nm is required for CBPR+",
                ));
            }

            // --- UETR required ----------------------------------------------
            if tx.pmt_id.uetr.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/PmtId/UETR",
                    Severity::Error,
                    "CBPR_UETR_REQUIRED",
                    "CBPR+ requires a UETR in PmtId",
                ));
            }

            // --- End-to-end ID is a required field (always present) ----------
            // (Max35Text is required on PaymentIdentification13, nothing to
            // check beyond XSD.)

            // ChrgBr validity is enforced by the ChargeBearerType1Code enum — all
            // variants (Cred, Debt, Shar, Slev) are valid for CBPR+.

            // --- Interbank settlement date required -------------------------
            if tx.intr_bk_sttlm_dt.is_none() {
                errors.push(ValidationError::new(
                    "/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/IntrBkSttlmDt",
                    Severity::Error,
                    "CBPR_STTLM_DT_REQUIRED",
                    "CBPR+ requires IntrBkSttlmDt",
                ));
            }
        }

        // Note: AppHdr check and UTF-8 control character check require raw
        // XML context and are not covered by the typed path.

        ValidationResult::new(errors)
    }
}

/// Check that a `BICFI` element exists inside a parent block (XML scan).
fn check_bic_in_parent(
    xml: &str,
    parent_tag: &str,
    path: &str,
    rule_id: &str,
    errors: &mut Vec<ValidationError>,
) {
    super::common::check_bic_in_parent(xml, parent_tag, path, rule_id, "CBPR+", errors);
}

/// Check that a `Nm` element exists inside a parent block (XML scan).
fn check_name_required(
    xml: &str,
    parent_tag: &str,
    rule_id: &str,
    errors: &mut Vec<ValidationError>,
) {
    let path = format!("/Document/FIToFICstmrCdtTrf/CdtTrfTxInf/{parent_tag}");
    super::common::check_name_in_parent(
        xml, parent_tag, None, &path, rule_id, "CBPR+", errors, true,
    );
}

/// Check that a BIC is present in an optional agent struct (typed).
fn check_bic_typed(
    agent: Option<
        &mx20022_model::generated::pacs::pacs_008_001_13::BranchAndFinancialInstitutionIdentification8,
    >,
    parent_name: &str,
    path: &str,
    rule_id: &str,
    errors: &mut Vec<ValidationError>,
) {
    match agent {
        None => {
            errors.push(ValidationError::new(
                path,
                Severity::Error,
                rule_id,
                format!("{parent_name}/FinInstnId/BICFI is required for CBPR+ but the parent element is missing"),
            ));
        }
        Some(agt) if agt.fin_instn_id.bicfi.is_none() => {
            errors.push(ValidationError::new(
                path,
                Severity::Error,
                rule_id,
                format!("{parent_name}/FinInstnId/BICFI is required for CBPR+"),
            ));
        }
        Some(_) => {}
    }
}

/// Check for disallowed control characters in the XML string.
///
/// CBPR+ requires UTF-8 encoding with no control characters except:
/// - LF (0x0A)
/// - CR (0x0D)
/// - TAB (0x09)
fn check_control_characters(xml: &str, errors: &mut Vec<ValidationError>) {
    for (i, c) in xml.char_indices() {
        if c.is_control() && !matches!(c, '\n' | '\r' | '\t') {
            errors.push(ValidationError::new(
                "/Document",
                Severity::Error,
                "CBPR_CONTROL_CHAR",
                format!(
                    "Disallowed control character U+{:04X} at byte offset {i}",
                    c as u32
                ),
            ));
            // Report only the first occurrence to avoid noise.
            break;
        }
    }
}

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

    #[test]
    fn name_is_cbpr_plus() {
        assert_eq!(CbprPlusValidator::new().name(), "CBPR+");
    }

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

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

    #[test]
    fn control_character_produces_error() {
        let mut errors = Vec::new();
        check_control_characters("hello\x01world", &mut errors);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].rule_id, "CBPR_CONTROL_CHAR");
    }

    #[test]
    fn allowed_whitespace_is_fine() {
        let mut errors = Vec::new();
        check_control_characters("hello\nworld\r\n\t", &mut errors);
        assert!(errors.is_empty());
    }
}