Skip to main content

fints_client/
mask.rs

1//! Masking of FinTS messages for logs and tooling.
2//!
3//! Every message that crosses the transport boundary (request and response)
4//! is logged through [`mask_for_log`]. The function is segment-aware: it
5//! tokenizes with `codec::wire` (so `?` escapes and `@len@` binary
6//! data are respected), looks up per segment code and version which data
7//! elements hold credentials or identifiers, and writes the message again
8//! with those elements replaced.
9//!
10//! # The rule
11//!
12//! - A masked text element becomes one `*` per character: the length class
13//!   stays visible, the value does not. (No prefix or suffix of an IBAN is
14//!   kept.) PIN and TAN are always eight stars: their length says something.
15//! - Names and amounts are shown as a fixed shape (`shape`): a name is
16//!   eight `#` whatever its length, an amount is `#,##` whatever its size
17//!   and its decimals. Holder and user names (HIUPA 4, HIUPD 6 6 and
18//!   7), product names (HIUPD 6 8, HISAL 2), the extensions (HIUPA 5,
19//!   HIUPD 6 12) and every amount in HISAL and HIUPD 6.
20//! - A binary element (MT940, camt, MT535/536, keys, certificates) becomes
21//!   `@<original length>@<masked>` in the log and `@n@` + `n` stars in
22//!   [`redact_credentials`]. Binary data is never shown. Only the trace
23//!   recorder (`mask_for_recorder`) shows statements as their shape, field
24//!   by field, with the length of the shaped data in `@len@`: a trace is a reviewed artefact, the log goes to any sink, so the
25//!   log stays the more masked of the two.
26//! - HNVSD carries the signed segments as binary data; its contents are
27//!   masked recursively and written in place, so the log shows the whole
28//!   dialog.
29//! - Masked with stars in the log, with a stand-in in a trace
30//!   (`pseudonym`: equal values give equal stand-ins; a counterparty's
31//!   IBAN, a creditor ID and a reference have one fixed form each). In a
32//!   trace every date is moved by the same number of days (`dates`). A per-trace alias for the account identifiers: user
33//!   ID / customer ID (HKIDN, HNSHK, HNVSK, HIUPA, HIUPD); account number
34//!   and IBAN in every account group of HKSAL/HISAL, HKKAZ/HIKAZ,
35//!   HKCAZ/HICAZ, HKWPD, HKWDU, HKSPA/HISPA, HKTAN and HIUPD. A keyed
36//!   pseudonym for the system ID (HKIDN, HNSHK, HNVSK, HISYN). Always starred: PIN and
37//!   TAN (HNSHA), subaccounts, the TAN challenge (HITAN). BIC and bank code
38//!   are kept.
39//! - Payment orders (HKCCS, HKIPZ, HKIPS, HKVPP, HKVPA and their answers
40//!   HIIPZ, HIIPS, HIVPP): the debtor account (KTI), the instant order ID,
41//!   the payee IBAN in HIVPP and the binary VOP-ID and polling ID are
42//!   starred in the log; in a trace the accounts get aliases, the IDs
43//!   pseudonyms; the VoP touchdown
44//!   point and the payee's additional information, registered name, other
45//!   ID and RVNA reason are starred; the explanation text of HIVPP is shown
46//!   as its shape. The pain.001/pain.002 messages are binary and so starred
47//!   in the log; the trace recorder shows them as their shape (`shape`:
48//!   markup, status and service level codes and currency stay; names, BICs,
49//!   dates, remittance text and amounts do not) with aliases for IBANs,
50//!   account numbers and creditor IDs and pseudonyms for references. Descriptors, flags, outcome codes and
51//!   waits are kept.
52//! - Segments known to carry only protocol data (envelope, feedback,
53//!   parameter segments `HI…S`, HKEND, HKSYN, and HKVVB except its product registration, which is starred) are kept; feedback texts
54//!   have IBAN-like words masked (an alias in a trace). Every other segment is unknown and masked
55//!   completely except its header (better too much than too little); the
56//!   recorder can keep the ones a person has looked at (`hide_unknown`).
57//! - Input that does not tokenize is never shown: the log gets only a length.
58//!
59//! The function never panics. It is a logging aid, not a security boundary:
60//! a bank that sends an identifier in a place the table does not list, inside
61//! a known segment, is not caught.
62
63// Used by the trace recorder only; the log stars identity values.
64pub(crate) mod dates;
65#[cfg_attr(not(feature = "trace"), allow(dead_code))]
66pub(crate) mod pseudonym;
67pub(crate) mod shape;
68
69use crate::codec::wire;
70use crate::parser::{DEG, DataElement};
71use pseudonym::{IdClass, Identities};
72
73/// Longest nesting of HNVSD inside HNVSD that is looked into.
74const MAX_DEPTH: usize = 2;
75
76/// How binary data and unparseable input are shown.
77#[derive(Clone, Copy)]
78enum Mode<'a> {
79    /// `@n@<masked>`; unparseable input becomes a length marker.
80    Log,
81    /// `@n@` followed by `n` stars: the result is valid wire syntax again
82    /// (for tooling that parses the masked message).
83    Parseable,
84    /// Like `Parseable`, but statements (HIKAZ, HICAZ, HIWPD, HIWDU) and
85    /// pain messages are shape-masked by field instead of starred
86    /// ([`shape`]), and identity values get aliases or keyed pseudonyms
87    /// instead of stars (`mask::pseudonym`).
88    #[cfg_attr(not(feature = "trace"), allow(dead_code))]
89    Trace(&'a Identities),
90    /// Like `Trace`, but a segment the table does not know stays as it is
91    /// ([`is_unknown`]). The recorder holds messages in this form until the
92    /// caller has decided which unknown segments a trace may show
93    /// ([`hide_unknown`]).
94    #[cfg_attr(not(feature = "trace"), allow(dead_code))]
95    Recorder(&'a Identities),
96}
97
98/// Masks a message (or the clear text of an HNVSD) for logging. The result
99/// is not wire syntax (binary data are shown as `@n@<masked>`).
100pub fn mask_for_log(message: &[u8]) -> String {
101    mask(message, Mode::Log, 0)
102        .into_iter()
103        .map(char::from)
104        .collect()
105}
106
107/// Masks a message like [`mask_for_log`], but keeps it parseable: binary
108/// data are replaced by as many `*` as they were long, and input that does
109/// not tokenize keeps only its separators. Used by `debug` before it parses
110/// a message for display.
111pub fn redact_credentials(message: &[u8]) -> Vec<u8> {
112    mask(message, Mode::Parseable, 0)
113}
114
115/// Masks a message like [`redact_credentials`], but shows the statements
116/// in HIKAZ (MT940), HICAZ (camt), HIWPD and HIWDU (MT535/536) and the
117/// pain messages as their shape: markup and codes stay, every letter,
118/// digit and space of values becomes `#` ([`shape`]). Account identifiers
119/// (IBAN, account number, user and customer ID, creditor ID) get per-trace
120/// aliases, the other identity values (system ID, booking and payment
121/// references, order, VOP and polling IDs) keyed pseudonyms
122/// (`mask::pseudonym`), instead of stars or shapes. The trace recorder uses
123/// [`mask_for_recorder`] and [`hide_unknown`], which together give this.
124#[cfg(test)]
125pub(crate) fn mask_for_trace(message: &[u8], ids: &Identities) -> Vec<u8> {
126    mask(message, Mode::Trace(ids), 0)
127}
128
129/// [`mask_for_trace`] with the unknown segments left as they are. Pass the
130/// result through [`hide_unknown`] before it leaves the recorder.
131#[cfg_attr(not(feature = "trace"), allow(dead_code))]
132pub(crate) fn mask_for_recorder(message: &[u8], ids: &Identities) -> Vec<u8> {
133    mask(message, Mode::Recorder(ids), 0)
134}
135
136/// A segment the table of masked fields does not know: a trace shows only
137/// its header and the length of each element, unless the person recording
138/// looked at it and chose to keep it. HIUPD in a version without a field
139/// list is never offered: it holds the account and its holder.
140#[cfg_attr(not(feature = "trace"), allow(dead_code))]
141pub(crate) fn is_unknown(code: &str, version: u16) -> bool {
142    !code.is_empty() && code != "HIUPD" && Policy::of(code, version) == Policy::All
143}
144
145/// A message of [`mask_for_recorder`] with every unknown segment starred
146/// after its header, except those `keep` names (by segment code). Every
147/// other segment is written back unchanged.
148#[cfg_attr(not(feature = "trace"), allow(dead_code))]
149pub(crate) fn hide_unknown(input: &[u8], keep: &dyn Fn(&str) -> bool) -> Vec<u8> {
150    let Ok(segments) = wire::tokenize(input) else {
151        return input.to_vec();
152    };
153    let mut out = Vec::with_capacity(input.len());
154    for seg in &segments {
155        let (code, version) = (seg.segment_type(), seg.segment_version());
156        let hide = is_unknown(code, version) && !keep(code);
157        for (i, deg) in seg.degs.iter().enumerate() {
158            if i > 0 {
159                out.push(b'+');
160            }
161            for (j, de) in deg.0.iter().enumerate() {
162                if j > 0 {
163                    out.push(b':');
164                }
165                match de {
166                    DataElement::Empty => {}
167                    DataElement::Binary(data) => {
168                        let shown = if code == "HNVSD" && i == 1 && j == 0 {
169                            hide_unknown(data, keep)
170                        } else if hide && i > 0 {
171                            vec![b'*'; data.len()]
172                        } else {
173                            data.clone()
174                        };
175                        out.extend_from_slice(format!("@{}@", shown.len()).as_bytes());
176                        out.extend(shown);
177                    }
178                    DataElement::Text(text) if hide && i > 0 => {
179                        out.extend(std::iter::repeat_n(b'*', text.chars().count()));
180                    }
181                    DataElement::Text(text) => write_text(text, &mut out),
182                }
183            }
184        }
185        out.push(b'\'');
186    }
187    out
188}
189
190/// The unknown segments of a message of [`mask_for_recorder`], each as its
191/// wire bytes, those inside HNVSD included.
192#[cfg_attr(not(feature = "trace"), allow(dead_code))]
193pub(crate) fn unknown_segments(input: &[u8]) -> Vec<Vec<u8>> {
194    let Ok(segments) = wire::tokenize(input) else {
195        return Vec::new();
196    };
197    let mut found = Vec::new();
198    for seg in &segments {
199        if seg.segment_type() == "HNVSD"
200            && let Some(DataElement::Binary(inner)) = seg.degs.get(1).and_then(|d| d.0.first())
201        {
202            found.extend(unknown_segments(inner));
203        } else if is_unknown(seg.segment_type(), seg.segment_version())
204            && let Ok(bytes) = wire::serialize_segment(seg)
205        {
206            found.push(bytes);
207        }
208    }
209    found
210}
211
212/// Target of the one `TRACE` event the library emits per exchange (success
213/// or failure), for callers that record a dialog (e.g. as a replay fixture).
214/// It is emitted around the [`Transport`](crate::transport::Transport) call,
215/// so no transport can skip it.
216///
217/// Field `request`: the message as sent (with the PIN/TAN envelope, after the
218/// outgoing quirks), passed through [`redact_credentials`] and given as
219/// ISO 8859-1 text (one `char` per byte). On success, field `response`: the
220/// answer as received (before the incoming quirks), redacted the same way.
221/// On failure there is no `response`; field `error` holds a short summary
222/// (`HTTP 500`, or `transport: <text>`). An HTTP body is never logged, because
223/// it may echo request data. Enable it with a `tracing` subscriber for this
224/// target; the library itself stores nothing.
225pub const EXCHANGE_TARGET: &str = "fints_client::exchange";
226
227/// [`redact_credentials`] as ISO 8859-1 text: one `char` per byte, so
228/// `text.chars().map(|c| c as u8)` gives the bytes back.
229pub fn redacted_text(message: &[u8]) -> String {
230    redact_credentials(message)
231        .into_iter()
232        .map(char::from)
233        .collect()
234}
235
236fn mask(input: &[u8], mode: Mode<'_>, depth: usize) -> Vec<u8> {
237    let Ok(segments) = wire::tokenize(input) else {
238        return match mode {
239            Mode::Log => format!("<{} bytes, unparseable, masked>", input.len()).into_bytes(),
240            Mode::Parseable | Mode::Trace(_) | Mode::Recorder(_) => input
241                .iter()
242                .map(|&b| {
243                    if matches!(b, b'+' | b':' | b'\'') {
244                        b
245                    } else {
246                        b'*'
247                    }
248                })
249                .collect(),
250        };
251    };
252    let mut out = Vec::with_capacity(input.len());
253    for seg in &segments {
254        write_segment(seg.degs.as_slice(), mode, depth, &mut out);
255    }
256    out
257}
258
259fn write_segment(degs: &[DEG], given: Mode<'_>, depth: usize, out: &mut Vec<u8>) {
260    let (mode, keep_unknown) = match given {
261        Mode::Recorder(ids) => (Mode::Trace(ids), true),
262        mode => (mode, false),
263    };
264    let ids = match mode {
265        Mode::Trace(ids) | Mode::Recorder(ids) => Some(ids),
266        Mode::Log | Mode::Parseable => None,
267    };
268    let code = match degs.first().and_then(|d| d.0.first()) {
269        Some(DataElement::Text(s)) => s.as_str(),
270        _ => "",
271    };
272    let version = degs
273        .first()
274        .and_then(|d| d.0.get(2))
275        .and_then(DataElement::as_str)
276        .and_then(|v| v.parse::<u16>().ok())
277        .unwrap_or(0);
278    let policy = Policy::of(code, version);
279    let envelope = code == "HNVSD" && depth < MAX_DEPTH;
280    let clear = keep_unknown && is_unknown(code, version);
281
282    for (i, deg) in degs.iter().enumerate() {
283        if i > 0 {
284            out.push(b'+');
285        }
286        for (j, de) in deg.0.iter().enumerate() {
287            if j > 0 {
288                out.push(b':');
289            }
290            match de {
291                DataElement::Empty => {}
292                DataElement::Binary(data) if envelope && i == 1 && j == 0 => {
293                    let inner = mask(data, given, depth + 1);
294                    out.extend_from_slice(format!("@{}@", inner.len()).as_bytes());
295                    out.extend_from_slice(&inner);
296                }
297                DataElement::Binary(data) if clear => {
298                    out.extend_from_slice(format!("@{}@", data.len()).as_bytes());
299                    out.extend_from_slice(data);
300                }
301                DataElement::Text(text) if clear => write_text(text, out),
302                DataElement::Binary(data) => {
303                    let format = shape::Format::of(code).or_else(|| shape::Format::pain(code, i));
304                    // A shaped statement has its own length: names and
305                    // amounts are written in fixed shapes.
306                    let shown = match (mode, format, binary_id(code, version, i)) {
307                        (Mode::Log, _, _) => {
308                            out.extend_from_slice(format!("@{}@<masked>", data.len()).as_bytes());
309                            continue;
310                        }
311                        (Mode::Trace(ids), Some(format), _) => {
312                            shape::shape(format, data, Some(ids))
313                        }
314                        (Mode::Trace(ids), None, Some(class)) => ids.bytes(class, data),
315                        _ => vec![b'*'; data.len()],
316                    };
317                    out.extend_from_slice(format!("@{}@", shown.len()).as_bytes());
318                    out.extend(shown);
319                }
320                DataElement::Text(text) => {
321                    let shape = if i > 0 {
322                        shaped(code, version, i, deg.0.len(), text)
323                    } else {
324                        None
325                    };
326                    // A balance of HISAL (`C:1,00:EUR:20260101:120000`) in
327                    // a trace: the debit mark is written as credit, so an
328                    // overdrawn account does not show, and its date moves
329                    // with the other dates of the trace.
330                    let balance = match ids {
331                        Some(ids) if code == "HISAL" && i >= 3 => {
332                            if j == 0 && text == "D" && deg.0.len() >= 3 {
333                                Some("C".to_string())
334                            } else if dates::is_date(text.as_bytes(), dates::Form::Ymd8) {
335                                Some(dates::shift_text(text, ids.days()))
336                            } else if j > 0
337                                && deg.0[j - 1].as_str().is_some_and(|d| {
338                                    dates::is_date(d.as_bytes(), dates::Form::Ymd8)
339                                })
340                            {
341                                Some(dates::noon_text(text))
342                            } else {
343                                None
344                            }
345                        }
346                        _ => None,
347                    };
348                    let shown = if let Some(balance) = balance {
349                        balance
350                    } else if let Some(shape) = shape {
351                        match shape {
352                            Shape::Name(limit) => shape::name_shape(text.chars().count(), limit),
353                            Shape::Amount => shape::amount_shape(text),
354                            Shape::Text => shape::shape_text(text),
355                        }
356                    } else if let Some(hide) = policy.masks(i, j).filter(|_| i > 0) {
357                        match (hide, ids) {
358                            (Hide::Id(class), Some(ids)) => ids.text(class, text),
359                            (Hide::Date, Some(ids)) => dates::shift_text(text, ids.days()),
360                            (Hide::Time, Some(_)) => dates::noon_text(text),
361                            (Hide::Date | Hide::Time, None) => text.clone(),
362                            // PIN and TAN: a fixed length, so the trace does
363                            // not say how long the PIN is.
364                            _ if code == "HNSHA" => "*".repeat(SECRET_LEN),
365                            _ => "*".repeat(text.chars().count()),
366                        }
367                    } else if i > 0 && policy == Policy::Feedback {
368                        scrub_ibans(text, ids)
369                    } else {
370                        text.clone()
371                    };
372                    write_text(&shown, out);
373                }
374            }
375        }
376    }
377    out.push(b'\'');
378}
379
380/// Stars written for a PIN or a TAN, whatever its length.
381const SECRET_LEN: usize = 8;
382
383/// How a free text or an amount of a segment is shown, in every mode.
384enum Shape {
385    /// A name whose format allows this many characters
386    /// ([`shape::name_shape`]): `Erika Beispiel` → `########`.
387    Name(usize),
388    /// [`shape::amount_shape`]: `1234,56` → `#,##`.
389    Amount,
390    /// [`shape::shape_text`]: eight `#` per line.
391    Text,
392}
393
394/// Free text (names, product names, extensions) and amounts, which are
395/// shown as a shape. Positions count data elements from 1.
396fn shaped(code: &str, version: u16, de: usize, group_len: usize, text: &str) -> Option<Shape> {
397    let amount = || shape::is_amount(text).then_some(Shape::Amount);
398    match code {
399        // 4 Benutzername (an ..35), 5 Erweiterung (an ..2048).
400        "HIUPA" if de == 4 => Some(Shape::Name(35)),
401        "HIUPA" if de == 5 => Some(Shape::Name(2048)),
402        // 6, 7 Name des Kontoinhabers (an ..27), 8 Kontoproduktbezeichnung
403        // (an ..30); amounts in 9 Kontolimit and the allowed orders; 12
404        // Erweiterung (an ..2048) follows the repeated allowed orders (data
405        // elements 10 on, each at least two group elements) as a single
406        // element.
407        "HIUPD" if version == 6 => match de {
408            6 | 7 => Some(Shape::Name(27)),
409            8 => Some(Shape::Name(30)),
410            _ if de >= 10 && group_len == 1 => Some(Shape::Name(2048)),
411            _ if de >= 9 => amount(),
412            _ => None,
413        },
414        // 2 Kontoproduktbezeichnung (an ..30); balances, credit line,
415        // available and used amounts.
416        "HISAL" if de == 2 => Some(Shape::Name(30)),
417        "HISAL" if de >= 3 => amount(),
418        // 8 Aufklaerungstext Autorisierung trotz Abweichung: may quote the
419        // names.
420        "HIVPP" if version == 1 && de == 7 && group_len == 1 => Some(Shape::Text),
421        _ => None,
422    }
423}
424
425/// Writes text as ISO 8859-1 with the FinTS escapes.
426fn write_text(text: &str, out: &mut Vec<u8>) {
427    for c in text.chars() {
428        let byte = u8::try_from(u32::from(c)).unwrap_or(b'?');
429        if matches!(byte, b'?' | b'+' | b':' | b'\'' | b'@') {
430            out.push(b'?');
431        }
432        out.push(byte);
433    }
434}
435
436/// Replaces words that look like an IBAN (two letters, two digits, at least
437/// 15 letters and digits in all) with `*`, in a trace with their alias.
438fn scrub_ibans(text: &str, ids: Option<&Identities>) -> String {
439    let flush = |word: &mut String, out: &mut String| {
440        let chars: Vec<char> = word.chars().collect();
441        let iban_like = chars.len() >= 15
442            && chars[..2].iter().all(char::is_ascii_uppercase)
443            && chars[2..4].iter().all(char::is_ascii_digit);
444        match ids {
445            Some(ids) if iban_like => out.push_str(&ids.text(IdClass::OtherIban, word)),
446            None if iban_like => out.extend(std::iter::repeat_n('*', chars.len())),
447            _ => out.push_str(word),
448        }
449        word.clear();
450    };
451    let mut out = String::with_capacity(text.len());
452    let mut word = String::new();
453    for c in text.chars() {
454        if c.is_ascii_alphanumeric() {
455            word.push(c);
456        } else {
457            flush(&mut word, &mut out);
458            out.push(c);
459        }
460    }
461    flush(&mut word, &mut out);
462    out
463}
464
465/// How a masked data element is hidden.
466#[derive(Clone, Copy, Debug, PartialEq, Eq)]
467enum Hide {
468    /// One `*` per character, in every mode.
469    Star,
470    /// Stars in the log, the stand-in of this class in a trace (an alias
471    /// or a keyed pseudonym).
472    Id(IdClass),
473    /// A date (`YYYYMMDD`): as sent in the log, moved by the days of the
474    /// trace in a trace (`dates`).
475    Date,
476    /// A time of day (`hhmmss`): as sent in the log, noon in a trace.
477    Time,
478}
479
480use Hide::{Id, Star};
481
482/// Which data elements of a segment are masked. Positions count data
483/// elements from 1 (the header is 0, never masked) and group elements from 0.
484#[derive(Debug, PartialEq, Eq)]
485enum Policy {
486    /// Only binary data is masked.
487    Safe,
488    /// Like `Safe`, IBAN-like words in the text are masked.
489    Feedback,
490    /// The listed (data element, group elements, how) entries; no group
491    /// elements listed means the whole data element.
492    At(Vec<(usize, Vec<usize>, Hide)>),
493    /// Every data element from this position on, with stars.
494    From(usize),
495    /// Unknown segment: everything after the header, with stars.
496    All,
497}
498
499/// Group elements of a data element and how they are hidden.
500type Parts = &'static [(&'static [usize], Hide)];
501
502/// `Ktv3` (number, subaccount): the number identifies the account.
503const KTV: Parts = &[(&[0], Id(IdClass::Account)), (&[1], Star)];
504/// `Kti1` (IBAN, BIC, number, subaccount, …); the BIC is kept.
505const KTI: Parts = &[
506    (&[0], Id(IdClass::Iban)),
507    (&[2], Id(IdClass::Account)),
508    (&[3], Star),
509];
510/// `Ktz1` (use, IBAN, BIC, number, subaccount, …); the BIC is kept.
511const KTZ: Parts = &[
512    (&[1], Id(IdClass::Iban)),
513    (&[3], Id(IdClass::Account)),
514    (&[4], Star),
515];
516/// Sicherheitsidentifikation, Details (HNSHK 6, HNVSK 4): CID and
517/// Kundensystem-ID.
518const SECURITY_ID: Parts = &[(&[1], Star), (&[2], Id(IdClass::SystemId))];
519/// Schlüsselname (HNSHK 11, HNVSK 7): the Benutzerkennung.
520const KEY_NAME: Parts = &[(&[2], Id(IdClass::UserId))];
521const USER: Parts = &[(&[], Id(IdClass::UserId))];
522const SYSTEM: Parts = &[(&[], Id(IdClass::SystemId))];
523const ORDER: Parts = &[(&[], Id(IdClass::OrderId))];
524const IBAN: Parts = &[(&[], Id(IdClass::Iban))];
525const STARS: Parts = &[(&[], Star)];
526const DATE: Parts = &[(&[], Hide::Date)];
527/// Sicherheitsdatum und -uhrzeit (HNSHK 8, HNVSK 5): type, date, time.
528const SECURITY_DATE: Parts = &[(&[1], Hide::Date), (&[2], Hide::Time)];
529/// Gültigkeit der VOP-ID (HIVPP 2): date, time.
530const VALIDITY: Parts = &[(&[0], Hide::Date), (&[1], Hide::Time)];
531/// HIVPP 6 Ergebnis Einzeltransaktion: the IBAN; IBAN info, registered
532/// name, other ID and reason RVNA starred; the outcome (4) stays.
533const PAYEE: Parts = &[(&[0], Id(IdClass::OtherIban)), (&[1, 2, 3, 5], Star)];
534
535impl Policy {
536    fn of(code: &str, version: u16) -> Policy {
537        fn at(list: &[(usize, Parts)]) -> Policy {
538            Policy::At(
539                list.iter()
540                    .flat_map(|&(d, parts)| parts.iter().map(move |&(e, h)| (d, e.to_vec(), h)))
541                    .collect(),
542            )
543        }
544        match code {
545            "HNHBK" | "HNHBS" | "HNVSD" | "HKEND" | "HKSYN" => Policy::Safe,
546            // 4 Produktbezeichnung: the product registration number.
547            "HKVVB" => at(&[(4, STARS)]),
548            "HIRMG" | "HIRMS" => Policy::Feedback,
549            "HNSHA" => Policy::From(3),
550            // 2 Kunden-ID, 3 Kundensystem-ID.
551            "HKIDN" => at(&[(2, USER), (3, SYSTEM)]),
552            "HNSHK" => at(&[(6, SECURITY_ID), (8, SECURITY_DATE), (11, KEY_NAME)]),
553            "HNVSK" => at(&[(4, SECURITY_ID), (5, SECURITY_DATE), (7, KEY_NAME)]),
554            "HISYN" => at(&[(1, SYSTEM)]),
555            "HIUPA" => at(&[(1, USER)]),
556            "HIUPD" if version == 6 => at(&[(1, KTV), (2, IBAN), (3, USER)]),
557            "HIUPD" => Policy::All,
558            "HISAL" if version >= 7 => at(&[(1, KTI)]),
559            "HISAL" => at(&[(1, KTV)]),
560            // 3 Von Datum, 4 Bis Datum.
561            "HKKAZ" if version >= 7 => at(&[(1, KTI), (3, DATE), (4, DATE)]),
562            "HKKAZ" => at(&[(1, KTV), (3, DATE), (4, DATE)]),
563            "HKSAL" | "HIKAZ" if version >= 7 => at(&[(1, KTI)]),
564            // 4 Von Datum, 5 Bis Datum.
565            "HKWDU" => at(&[(1, KTV), (4, DATE), (5, DATE)]),
566            "HKSAL" | "HIKAZ" | "HKWPD" | "HIWPD" | "HIWDU" => at(&[(1, KTV)]),
567            "HKCAZ" => at(&[(1, KTI), (4, DATE), (5, DATE)]),
568            "HICAZ" => at(&[(1, KTI)]),
569            "HKTAN" => at(&[(3, KTI)]),
570            // Payment orders (docs/payments-design.md): the debtor account,
571            // the order IDs and the payee check IDs are masked. The
572            // descriptor, flags, outcome codes and waits are kept. The pain
573            // messages (binary) are starred, or shaped in a trace.
574            "HKCCS" | "HKIPZ" if version <= 2 => at(&[(1, KTI)]),
575            "HKIPS" if version == 1 => at(&[(1, KTI), (3, ORDER)]),
576            "HIIPS" if version == 1 => at(&[(1, KTI), (4, ORDER)]),
577            "HIIPZ" if version <= 2 => at(&[(1, ORDER)]),
578            // 4 Aufsetzpunkt.
579            "HKVPP" if version == 1 => at(&[(4, STARS)]),
580            "HKVPA" if version == 1 => Policy::Safe,
581            // 2 Gültigkeit der VOP-ID: date, time.
582            "HIVPP" if version == 1 => at(&[(2, VALIDITY), (6, PAYEE)]),
583            "HITAN" => Policy::From(4),
584            "HKSPA" => at(&(1..=99).map(|d| (d, KTV)).collect::<Vec<_>>()),
585            "HISPA" => at(&(1..=99).map(|d| (d, KTZ)).collect::<Vec<_>>()),
586            c if is_parameter_segment(c) => Policy::Safe,
587            _ => Policy::All,
588        }
589    }
590
591    /// How data element `de`, group element `element` is hidden, if it is.
592    fn masks(&self, de: usize, element: usize) -> Option<Hide> {
593        match self {
594            Policy::Safe | Policy::Feedback => None,
595            Policy::At(list) => list
596                .iter()
597                .find(|(d, e, _)| *d == de && (e.is_empty() || e.contains(&element)))
598                .map(|&(_, _, h)| h),
599            Policy::From(n) => (de >= *n).then_some(Star),
600            Policy::All => Some(Star),
601        }
602    }
603}
604
605/// The identity class of binary data element `de` of a segment that holds
606/// no statement or pain message: the VOP-ID and polling ID of the payee
607/// check (HIVPP 1 and 3, HKVPA 1, HKVPP 2). Other binary data (keys,
608/// certificates, order hashes) is starred.
609fn binary_id(code: &str, version: u16, de: usize) -> Option<IdClass> {
610    match (code, version, de) {
611        ("HIVPP", 1, 1) | ("HKVPA", 1, 1) => Some(IdClass::VopId),
612        ("HIVPP", 1, 3) | ("HKVPP", 1, 2) => Some(IdClass::PollingId),
613        _ => None,
614    }
615}
616
617/// Bank parameter segments carry no personal data: the general ones
618/// (Formals D.2 to D.5: HIBPA, HIKOM with the bank's addresses, HISHV,
619/// HIKPV) and the job parameters (`HIPINS`, `HITANS`, `HIKAZS`, ...).
620/// The code of a job parameter segment is the order's code with `I` for
621/// `K` and an `S` at the end (Formals D.6), whoever defined the order:
622/// `HI…S`, `DI…S` for the banks' common orders (comdirect: DIKKUS) and
623/// any other first letter for a bank's own (Consorsbank: XIADAS).
624fn is_parameter_segment(code: &str) -> bool {
625    let b = code.as_bytes();
626    matches!(code, "HIBPA" | "HIKOM" | "HISHV" | "HIKPV")
627        || (code.starts_with("HI") && code.ends_with('S') && code.len() == 5)
628        || (b.len() == 6 && b[1] == b'I' && b[5] == b'S' && b.iter().all(u8::is_ascii_uppercase))
629}
630
631#[cfg(test)]
632mod tests;