iban-check 0.1.0

A dependency-free IBAN validation library for Rust.
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
use crate::countries::country_iban_length;
use crate::error::ValidationError;
use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

/// Maximum input length to prevent DoS via memory exhaustion.
/// Longest IBAN is 32 chars (LC). With whitespace, allow generous margin.
const MAX_INPUT_LENGTH: usize = 256;

/// Validates an IBAN string.
///
/// Whitespace characters are ignored. The input is case-insensitive.
///
/// # Examples
///
/// ```
/// use iban_check::validate;
///
/// assert!(validate("DE89370400440532013000").is_ok());
/// assert!(validate("DE89 3704 0044 0532 0130 00").is_ok());
/// assert!(validate("invalid").is_err());
/// ```
pub fn validate(iban: &str) -> Result<(), ValidationError> {
    validate_cow(iban).map(|_| ())
}

/// Validates an IBAN and returns the sanitized, normalized string as a `Cow<str>`.
///
/// This internal function is shared by [`validate`] and [`Iban::new`] to avoid
/// redundant sanitization. On the fast path (already uppercase, no whitespace),
/// this performs zero allocations.
fn validate_cow(iban: &str) -> Result<Cow<'_, str>, ValidationError> {
    // Security: reject unreasonably long inputs before any allocation
    if iban.len() > MAX_INPUT_LENGTH {
        return Err(ValidationError::InvalidLength {
            expected: MAX_INPUT_LENGTH,
            found: iban.len(),
        });
    }

    // Check if sanitization is needed (whitespace removal or case conversion)
    let needs_sanitization = iban
        .chars()
        .any(|c| c.is_whitespace() || c.is_ascii_lowercase());

    let cow: Cow<'_, str> = if needs_sanitization {
        let normalized: String = iban
            .chars()
            .filter(|c| !c.is_whitespace())
            .map(|c| c.to_ascii_uppercase())
            .collect();
        Cow::Owned(normalized)
    } else {
        Cow::Borrowed(iban)
    };

    let s = cow.as_ref();

    // Empty check
    if s.is_empty() {
        return Err(ValidationError::Empty);
    }

    // Minimum length check (need at least country code + check digits + 1 BBAN char = 5)
    if s.len() < 5 {
        return Err(ValidationError::InvalidLength {
            expected: 5,
            found: s.len(),
        });
    }

    // Extract country code and look up expected length
    let country_code = &s[0..2];
    let expected_length = country_iban_length(country_code)
        .ok_or(ValidationError::InvalidCountryCode)?;

    // Length check
    if s.len() != expected_length {
        return Err(ValidationError::InvalidLength {
            expected: expected_length,
            found: s.len(),
        });
    }

    let bytes = s.as_bytes();

    // Character validity check
    for (i, &b) in bytes.iter().enumerate() {
        if !b.is_ascii_alphanumeric() {
            return Err(ValidationError::InvalidCharacter {
                character: b as char,
                position: i,
            });
        }
    }

    // Mod-97-10 checksum without physical rearrangement
    // Process BBAN first (chars 4..end), then prefix (chars 0..4)
    let mut remainder = 0u32;

    for &b in bytes[4..].iter().chain(&bytes[0..4]) {
        if b.is_ascii_digit() {
            let digit = (b - b'0') as u32;
            remainder = (remainder * 10 + digit) % 97;
        } else {
            // b.is_ascii_uppercase() is guaranteed by the alphanumeric check above
            let value = (b - b'A' + 10) as u32;
            let tens = value / 10;
            let ones = value % 10;
            remainder = (remainder * 10 + tens) % 97;
            remainder = (remainder * 10 + ones) % 97;
        }
    }

    if remainder != 1 {
        return Err(ValidationError::InvalidChecksum);
    }

    Ok(cow)
}

/// Parsed and validated IBAN.
///
/// This type guarantees that the underlying string is a valid IBAN.
/// It can only be constructed through validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Iban(String);

impl Iban {
    /// Attempts to parse and validate an IBAN string.
    ///
    /// # Examples
    ///
    /// ```
    /// use iban_check::Iban;
    ///
    /// let iban = Iban::new("DE89370400440532013000").unwrap();
    /// ```
    pub fn new(iban: &str) -> Result<Self, ValidationError> {
        validate_cow(iban).map(|cow| Iban(cow.into_owned()))
    }

    /// Returns the country code (first two characters).
    pub fn country_code(&self) -> &str {
        // Safe: Iban is only constructible through validation which ensures len >= 5
        &self.0[0..2]
    }

    /// Returns the check digits (characters 2-4).
    pub fn check_digits(&self) -> &str {
        // Safe: Iban is only constructible through validation which ensures len >= 5
        &self.0[2..4]
    }

    /// Returns the BBAN (Basic Bank Account Number) portion.
    pub fn bban(&self) -> &str {
        // Safe: Iban is only constructible through validation which ensures len >= 5
        &self.0[4..]
    }

    /// Returns the full IBAN string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Iban {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for Iban {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

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

    // 7.1 Valid IBANs
    #[test]
    fn test_valid_ibans() {
        assert!(validate("DE89370400440532013000").is_ok()); // Germany
        assert!(validate("GB82WEST12345698765432").is_ok()); // United Kingdom
        assert!(validate("FR1420041010050500013M02606").is_ok()); // France
        assert!(validate("AL35202111090000000001234567").is_ok()); // Albania
        assert!(validate("NO9386011117947").is_ok()); // Norway (shortest)
    }

    // 7.2 Invalid Checksums
    #[test]
    fn test_invalid_checksum() {
        assert_eq!(
            validate("DE89370400440532013001"),
            Err(ValidationError::InvalidChecksum)
        );
        assert_eq!(
            validate("GB82WEST12345698765433"),
            Err(ValidationError::InvalidChecksum)
        );
    }

    // 7.3 Wrong Length for Known Country
    #[test]
    fn test_wrong_length() {
        assert_eq!(
            validate("DE8937040044053201300"),
            Err(ValidationError::InvalidLength {
                expected: 22,
                found: 21,
            })
        );
        assert_eq!(
            validate("GB82WEST1234569876543"),
            Err(ValidationError::InvalidLength {
                expected: 22,
                found: 21,
            })
        );
        assert_eq!(
            validate("FR1420041010050500013M0260"),
            Err(ValidationError::InvalidLength {
                expected: 27,
                found: 26,
            })
        );
    }

    // 7.4 Unknown Country Code
    #[test]
    fn test_unknown_country() {
        assert_eq!(
            validate("XX89370400440532013000"),
            Err(ValidationError::InvalidCountryCode)
        );
        assert_eq!(
            validate("ZZ1420041010050500013M02606"),
            Err(ValidationError::InvalidCountryCode)
        );
    }

    // 7.5 Invalid Characters
    #[test]
    fn test_with_whitespace() {
        // Should be sanitized
        assert!(validate("DE89 3704 0044 0532 0130 00").is_ok());
    }

    #[test]
    fn test_invalid_characters() {
        assert_eq!(
            validate("DE89.37040044053201300"),
            Err(ValidationError::InvalidCharacter {
                character: '.',
                position: 4,
            })
        );
    }

    #[test]
    fn test_invalid_characters_later() {
        assert_eq!(
            validate("GB82WEST1234569876543!"),
            Err(ValidationError::InvalidCharacter {
                character: '!',
                position: 21,
            })
        );
    }

    // 7.6 Case Insensitivity
    #[test]
    fn test_lowercase() {
        assert!(validate("de89370400440532013000").is_ok());
    }

    #[test]
    fn test_mixed_case() {
        assert!(validate("De89370400440532013000").is_ok());
        assert!(validate("gB82WEST12345698765432").is_ok());
    }

    // 7.7 Whitespace Handling
    #[test]
    fn test_leading_whitespace() {
        assert!(validate(" DE89370400440532013000").is_ok());
    }

    #[test]
    fn test_trailing_whitespace() {
        assert!(validate("DE89370400440532013000\n").is_ok());
    }

    #[test]
    fn test_tabs_and_newlines() {
        assert!(validate("DE89\t3704\n0044 0532\t0130\n00").is_ok());
    }

    // 7.8 Empty Input
    #[test]
    fn test_empty() {
        assert_eq!(validate(""), Err(ValidationError::Empty));
    }

    #[test]
    fn test_whitespace_only() {
        assert_eq!(validate("   "), Err(ValidationError::Empty));
    }

    #[test]
    fn test_tabs_only() {
        assert_eq!(validate("\t\n"), Err(ValidationError::Empty));
    }

    // 7.9 Edge Cases
    #[test]
    fn test_single_char() {
        assert_eq!(
            validate("D"),
            Err(ValidationError::InvalidLength {
                expected: 5,
                found: 1,
            })
        );
    }

    #[test]
    fn test_three_chars() {
        assert_eq!(
            validate("DE8"),
            Err(ValidationError::InvalidLength {
                expected: 5,
                found: 3,
            })
        );
    }

    #[test]
    fn test_country_code_only() {
        assert_eq!(
            validate("DE"),
            Err(ValidationError::InvalidLength {
                expected: 5,
                found: 2,
            })
        );
    }

    #[test]
    fn test_four_chars() {
        assert_eq!(
            validate("DE89"),
            Err(ValidationError::InvalidLength {
                expected: 5,
                found: 4,
            })
        );
    }

    // Iban type tests
    #[test]
    fn test_iban_new_valid() {
        let iban = Iban::new("DE89370400440532013000").unwrap();
        assert_eq!(iban.as_str(), "DE89370400440532013000");
        assert_eq!(iban.country_code(), "DE");
        assert_eq!(iban.check_digits(), "89");
        assert_eq!(iban.bban(), "370400440532013000");
    }

    #[test]
    fn test_iban_new_invalid() {
        assert!(Iban::new("DE89").is_err());
        assert!(Iban::new("XX89370400440532013000").is_err());
        assert!(Iban::new("DE89370400440532013001").is_err());
    }

    #[test]
    fn test_iban_from_str() {
        let iban: Iban = "DE89370400440532013000".parse().unwrap();
        assert_eq!(iban.as_str(), "DE89370400440532013000");
    }

    #[test]
    fn test_iban_display() {
        let iban = Iban::new("DE89370400440532013000").unwrap();
        assert_eq!(format!("{}", iban), "DE89370400440532013000");
    }

    #[test]
    fn test_iban_equality() {
        let iban1 = Iban::new("DE89370400440532013000").unwrap();
        let iban2 = Iban::new("de89370400440532013000").unwrap();
        assert_eq!(iban1, iban2);
    }

    // New tests for security and performance fixes

    #[test]
    fn test_input_too_long() {
        let long_input = "A".repeat(257);
        assert_eq!(
            validate(&long_input),
            Err(ValidationError::InvalidLength {
                expected: MAX_INPUT_LENGTH,
                found: 257,
            })
        );
    }

    #[test]
    fn test_input_at_max_length_with_whitespace() {
        // 22 chars IBAN + lots of whitespace = still ok if total <= 256
        // The IBAN itself must be valid (checksum correct)
        let iban = "DE89370400440532013000";
        let with_ws = format!("{} {}", iban, " ".repeat(200));
        assert!(validate(&with_ws).is_ok());
    }

    #[test]
    fn test_clone_validation_error() {
        let err = ValidationError::InvalidChecksum;
        let cloned = err.clone();
        assert_eq!(err, cloned);
    }

    #[test]
    fn test_iban_clone() {
        let iban1 = Iban::new("DE89370400440532013000").unwrap();
        let iban2 = iban1.clone();
        assert_eq!(iban1, iban2);
    }

    #[test]
    fn test_all_countries_basic() {
        // Spot-check a few countries to ensure the data is loaded
        assert!(validate("DE89370400440532013000").is_ok());
        assert!(validate("GB82WEST12345698765432").is_ok());
        assert!(validate("FR1420041010050500013M02606").is_ok());
        assert!(validate("CH9300762011623852957").is_ok());
        assert!(validate("NL91ABNA0417164300").is_ok());
        assert!(validate("BE71096123456769").is_ok());
    }
}