Skip to main content

fints_client/
trace.rs

1//! Recording dialogs as masked, anonymised traces (feature `trace`).
2//!
3//! - [`Recorder`] decorates a [`Transport`] ([`Recorder::wrap`]) and keeps
4//!   every exchange that goes through the wrapped transport, masked as it
5//!   is recorded, so credentials never sit in memory unmasked: PIN, TAN,
6//!   challenges, subaccounts and binary data other than statements, pain
7//!   messages and IDs become `*`; names, product names, amounts and the
8//!   statements in HIKAZ, HICAZ, HIWPD and HIWDU keep only their shape,
9//!   values as `#` in fixed lengths, and every date is moved by the same
10//!   few days. Identity values get a stand-in. Account identifiers (IBANs,
11//!   account numbers, user and customer ID, creditor IDs) get aliases
12//!   numbered in the order they first appear in this trace, from a random
13//!   start, with no link to the value; the same value gets the same alias
14//!   everywhere in the trace, IBANs keep country and bank code and valid
15//!   check digits, and an IBAN's account part matches the alias of the
16//!   same account number. The table lives in the recorder's memory only.
17//!   References and IDs (booking references, end-to-end, message and
18//!   payment information IDs, mandate references, system ID, order, VOP
19//!   and polling IDs) get keyed pseudonyms. Their key is a [`Salt`]:
20//!   [`Recorder::new`] draws one and forgets it, so the trace links to no
21//!   other; traces recorded with the same salt ([`Recorder::with_salt`])
22//!   give a reference the same pseudonym, while their account aliases stay
23//!   unrelated. The library writes no salt. It records exactly
24//!   the dialogs that use the wrapped transport, whatever thread they run
25//!   on; two recorders never see each other's traffic. A failed send is
26//!   recorded with a short, content-free `error`. It also names the account
27//!   each request is about ([`Exchange::account`], an alias such as `#2`
28//!   described by a [`TraceAccount`]): aliases are numbered in the order the
29//!   accounts first appear in a HIUPD, and the recorder keeps only keyed
30//!   hashes of their identifiers (a per-recorder random key that is never
31//!   written), never the identifiers themselves.
32//! - [`Trace`] is the fixture: one JSON document ([`TRACE_FORMAT`], see
33//!   [`Trace::to_json`]). [`Trace::from_exchanges`] anonymises the rest.
34//!   [`Trace::summary`] reads it for a human, one [`ExchangeSummary`] per
35//!   exchange.
36//!
37//! Independent of the `TRACE` event the transport boundary emits for log
38//! consumers ([`mask::EXCHANGE_TARGET`]).
39//!
40//! Clean room: written from the FinTS 3.0 specification and our own masking
41//! rules ([`mask`]).
42
43use std::collections::HashMap;
44use std::fmt;
45use std::hash::{BuildHasher, RandomState};
46use std::sync::{Arc, Mutex};
47
48use serde::{Deserialize, Serialize};
49use serde_json::Value;
50
51use crate::codec::{DataElement, RawSegment, wire};
52use crate::error::{FinTSError, Result};
53use crate::jobs::AccountInfo;
54use crate::mask;
55use crate::mask::pseudonym::Identities;
56pub use crate::mask::pseudonym::Salt;
57use crate::return_code::Kind;
58use crate::transport::{BoxFuture, SharedTransport, Transport};
59use crate::types::SepaAccount;
60
61/// The `format` of a trace file written by [`Trace::to_json`].
62pub const TRACE_FORMAT: &str = "fints-client-trace/4";
63
64/// One request and its response, as wire bytes (ISO 8859-1, with the
65/// PIN/TAN envelope), redacted; or the request and the error that ended it.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Exchange {
68    /// The customer message.
69    pub request: Vec<u8>,
70    /// The bank's answer; empty if `error` is set.
71    pub response: Vec<u8>,
72    /// Short summary of why the exchange failed (`HTTP 500`,
73    /// `transport: ...`), never message content.
74    pub error: Option<String>,
75    /// The alias (`#1`, `#2`, …) of the account the request is about, one of
76    /// [`Trace::accounts`]; set by the [`Recorder`].
77    pub account: Option<String>,
78    /// What this client made of the answer, without any value of it: a
79    /// segment its definition could not read (code, version, field, kind of
80    /// error) and statements with characters outside the SWIFT character
81    /// set. Written by the [`Recorder`] from the answer before masking.
82    pub notes: Vec<String>,
83}
84
85/// The client that recorded a trace.
86#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct Client {
89    /// The version of fints-client.
90    pub version: String,
91    /// How the recorded run ended: `completed`, or the kind of error that
92    /// stopped it ([`Trace::set_outcome`], [`outcome_label`]), never an
93    /// error text. `None` when the caller did not say.
94    pub outcome: Option<String>,
95}
96
97/// An account of a trace, by alias only: what the UPD says about it, never
98/// an identifier, a name or the product name.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct TraceAccount {
102    /// `#1`, `#2`, …: numbered in the order the accounts first appear in a
103    /// HIUPD.
104    pub alias: String,
105    /// The [`crate::types::AccountClass`] of the Kontoart (`checking`,
106    /// `depot`, …), or `depot` when there is none and the jobs allow HKWPD
107    /// and none of HKSAL, HKKAZ, HKCAZ ([`AccountInfo::class`]).
108    pub class: Option<String>,
109    /// The Kontoart of the HIUPD.
110    pub kontoart: Option<u8>,
111    /// The jobs the UPD allows for the account (`HKSAL`, `HKKAZ`, …).
112    pub jobs: Vec<String>,
113}
114
115impl fmt::Display for TraceAccount {
116    /// `account #2 (class depot; Kontoart -; jobs HKWPD)`.
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        let jobs = if self.jobs.is_empty() {
119            "-".to_string()
120        } else {
121            self.jobs.join(" ")
122        };
123        write!(
124            f,
125            "account {} (class {}; Kontoart {}; jobs {jobs})",
126            self.alias,
127            self.class.as_deref().unwrap_or("-"),
128            self.kontoart
129                .map_or_else(|| "-".to_string(), |k| k.to_string()),
130        )
131    }
132}
133
134/// A recorded dialog: the exchanges in order, and the accounts they name.
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
136pub struct Trace {
137    /// Free text for readers (where and how the trace was recorded).
138    pub comment: String,
139    /// The client that recorded it, and how its run ended.
140    pub client: Client,
141    /// Every account an exchange may name, listed once.
142    pub accounts: Vec<TraceAccount>,
143    /// The exchanges, in the order they happened.
144    pub exchanges: Vec<Exchange>,
145}
146
147impl Trace {
148    /// A trace from redacted exchanges (as [`Recorder::exchanges`] returns
149    /// them), anonymised further; no comment, no accounts:
150    ///
151    /// - dialog IDs (HNHBK) and order references (HITAN) become
152    ///   `DIALOG0001`, `TASK0001`, … everywhere they occur;
153    /// - the product registration in HKVVB becomes stars.
154    ///
155    /// Amounts, names and statements are shape-masked by the recorder
156    /// already.
157    pub fn from_exchanges(exchanges: Vec<Exchange>) -> Trace {
158        let mut names: HashMap<String, String> = HashMap::new();
159        let (mut dialogs, mut tasks) = (0, 0);
160        for ex in &exchanges {
161            for_each_segment(&ex.response, |seg| {
162                let (kind, counter) = match code(seg) {
163                    "HNHBK" => ("DIALOG", &mut dialogs),
164                    "HITAN" => ("TASK", &mut tasks),
165                    _ => return,
166                };
167                // HNHBK 4 Dialog-ID, HITAN 4 Auftragsreferenz.
168                if let Some(v) = text(seg, 3, 0)
169                    && v != "0"
170                    && v != "noref"
171                    && !is_starred(v)
172                    && !names.contains_key(v)
173                {
174                    *counter += 1;
175                    names.insert(v.to_string(), format!("{kind}{:04}", *counter));
176                }
177            });
178        }
179        let anonymise = |seg: &mut RawSegment| {
180            let code = code(seg).to_string();
181            for deg in seg.degs.iter_mut().skip(1) {
182                for de in deg.0.iter_mut() {
183                    let DataElement::Text(t) = de else { continue };
184                    if let Some(name) = names.get(t.as_str()) {
185                        *t = name.clone();
186                    }
187                }
188            }
189            if code == "HKVVB"
190                && let Some(DataElement::Text(t)) = seg.degs.get_mut(4).and_then(|d| d.0.get_mut(0))
191            {
192                *t = "*".repeat(t.chars().count());
193            }
194        };
195        let exchanges = exchanges
196            .into_iter()
197            .map(|ex| Exchange {
198                request: map_message(&ex.request, anonymise).unwrap_or(ex.request),
199                response: map_message(&ex.response, anonymise).unwrap_or(ex.response),
200                error: ex.error,
201                account: ex.account,
202                notes: ex.notes,
203            })
204            .collect();
205        Trace {
206            exchanges,
207            ..Trace::default()
208        }
209    }
210
211    /// Masks the trace again, with the masking rules of this version of
212    /// fints-client: for a trace recorded before the rules hid more. The
213    /// stand-ins are made anew (aliases and pseudonyms of a fresh random
214    /// salt, so they link to no other trace) and every date moves by a
215    /// further 3 to 30 days. What the trace already hides stays hidden;
216    /// unknown segments stay as they are, starred or kept. `comment`,
217    /// `client`, `accounts`, and each exchange's `account`, `error` and
218    /// `notes` stay.
219    pub fn remask(&mut self) {
220        let ids = Identities::new(Salt::random()).with_days(Identities::random_days());
221        let exchanges = std::mem::take(&mut self.exchanges)
222            .into_iter()
223            .map(|ex| Exchange {
224                request: mask::mask_for_recorder(&ex.request, &ids),
225                response: mask::mask_for_recorder(&ex.response, &ids),
226                ..ex
227            })
228            .collect();
229        self.exchanges = Trace::from_exchanges(exchanges).exchanges;
230    }
231
232    /// Records how the run ended: `completed`, or the kind of the error
233    /// that stopped it (the variant, for a bank error its code), never its
234    /// text.
235    pub fn set_outcome(&mut self, result: std::result::Result<(), &FinTSError>) {
236        self.client.outcome = Some(match result {
237            Ok(()) => "completed".to_string(),
238            Err(e) => outcome_label(e),
239        });
240    }
241
242    /// The trace as one pretty-printed JSON document:
243    ///
244    /// - `format` ([`TRACE_FORMAT`]), `comment` (lines), `bank` (`blz`, `bic`:
245    ///   [`Trace::blz`], [`Trace::bic`]), `accounts` ([`TraceAccount`]s);
246    /// - `exchanges`, each with `index`, `account` (alias or null),
247    ///   `retry_of`, `sent` (`jobs` as `CODE:version`, `tan` as
248    ///   `{process, for}` or null), `answer` (`message`: HIRMG codes,
249    ///   `segments`: HIRMS codes with the `job` they refer to), `failed`,
250    ///   `error`, `request` and `response`.
251    ///
252    /// `request` and `response` hold the message, one string per segment
253    /// (the HNVSD header up to its `@len@` and each segment inside HNVSD get
254    /// their own; the closing `'` of HNVSD is a string of its own), each byte as the ISO 8859-1 character
255    /// of the same value: joined, they are the bytes again. They are the
256    /// only source of truth; `index`, `retry_of`, `sent`, `answer`, `failed`
257    /// and `bank` are derived from them for readers (see [`Trace::summary`]),
258    /// and [`Trace::from_json`] rejects a file in which they differ.
259    pub fn to_json(&self) -> String {
260        let mut json =
261            serde_json::to_string_pretty(&self.file()).expect("a trace serializes to JSON");
262        json.push('\n');
263        json
264    }
265
266    /// Reads a trace written by [`Trace::to_json`]. Fails on another
267    /// `format`, unknown fields, a character outside ISO 8859-1, an
268    /// exchange naming an alias that `accounts` does not list, a failed
269    /// exchange with a response, and any derived field that differs from
270    /// what the raw `request`/`response` give (the error names the exchange
271    /// and the field).
272    pub fn from_json(json: &str) -> std::result::Result<Trace, String> {
273        let value: Value = serde_json::from_str(json).map_err(|e| format!("not JSON: {e}"))?;
274        let file: TraceFile = serde_json::from_value(value.clone())
275            .map_err(|e| format!("not a {TRACE_FORMAT} trace: {e}"))?;
276        if file.format != TRACE_FORMAT {
277            return Err(format!(
278                "format {:?}; this version reads {TRACE_FORMAT:?}",
279                file.format
280            ));
281        }
282        for (i, a) in file.accounts.iter().enumerate() {
283            if file.accounts[..i].iter().any(|b| b.alias == a.alias) {
284                return Err(format!("account {:?} is listed twice", a.alias));
285            }
286        }
287        let mut exchanges = Vec::with_capacity(file.exchanges.len());
288        for (i, ex) in file.exchanges.into_iter().enumerate() {
289            if let Some(alias) = &ex.account
290                && !file.accounts.iter().any(|a| &a.alias == alias)
291            {
292                return Err(format!(
293                    "exchange {i}: account {alias:?} is not in `accounts`"
294                ));
295            }
296            if ex.error.is_some() && !ex.response.is_empty() {
297                return Err(format!(
298                    "exchange {i}: a failed exchange (`error` set) has no `response`"
299                ));
300            }
301            exchanges.push(Exchange {
302                request: join_segments(&ex.request)
303                    .map_err(|e| format!("exchange {i}: request: {e}"))?,
304                response: join_segments(&ex.response)
305                    .map_err(|e| format!("exchange {i}: response: {e}"))?,
306                error: ex.error,
307                account: ex.account,
308                notes: ex.notes,
309            });
310        }
311        let trace = Trace {
312            comment: file.comment.join("\n"),
313            client: file.client,
314            accounts: file.accounts,
315            exchanges,
316        };
317        let derived = serde_json::to_value(trace.file()).expect("a trace serializes to JSON");
318        if let Some((path, found, want)) =
319            first_difference("bank", &value["bank"], &derived["bank"])
320        {
321            return Err(format!(
322                "derived field {path} is {found} in the file, but the requests give {want}"
323            ));
324        }
325        for (i, want) in derived["exchanges"]
326            .as_array()
327            .into_iter()
328            .flatten()
329            .enumerate()
330        {
331            let found = &value["exchanges"][i];
332            for field in ["index", "retry_of", "sent", "answer", "failed"] {
333                let path = field.to_string();
334                if let Some((path, found, want)) =
335                    first_difference(&path, &found[field], &want[field])
336                {
337                    return Err(format!(
338                        "exchange {i}: derived field {path} is {found} in the file, \
339                         but the recorded request and response give {want}"
340                    ));
341                }
342            }
343        }
344        Ok(trace)
345    }
346
347    /// The bank code the client logged in at (HKIDN of the first request
348    /// that has one).
349    pub fn blz(&self) -> Option<String> {
350        let mut blz = None;
351        for ex in &self.exchanges {
352            for_each_segment(&ex.request, |seg| {
353                if blz.is_none() && code(seg) == "HKIDN" {
354                    blz = text(seg, 1, 1).map(str::to_string);
355                }
356            });
357        }
358        blz
359    }
360
361    /// The bank's BIC: the BIC of the first account element (KTI,
362    /// `IBAN:BIC`) a job of a request names.
363    pub fn bic(&self) -> Option<String> {
364        let mut bic = None;
365        for ex in &self.exchanges {
366            for_each_segment(&ex.request, |seg| {
367                if bic.is_none()
368                    && ACCOUNT_JOBS.contains(&code(seg))
369                    && let Some(b) = text(seg, 1, 1).filter(|b| is_bic(b))
370                {
371                    bic = Some(b.to_string());
372                }
373            });
374        }
375        bic
376    }
377
378    /// The account with this alias.
379    pub fn account(&self, alias: &str) -> Option<&TraceAccount> {
380        self.accounts.iter().find(|a| a.alias == alias)
381    }
382
383    /// One [`ExchangeSummary`] per exchange. Never fails: a message that
384    /// does not tokenize is reported as unreadable.
385    ///
386    /// An exchange is a retry of the one before it (`retry_of`) when that
387    /// one was answered with 9075 (strong customer authentication required)
388    /// and it sends the same jobs again, now with HKTAN.
389    pub fn summary(&self) -> Vec<ExchangeSummary> {
390        let mut all: Vec<ExchangeSummary> = self
391            .exchanges
392            .iter()
393            .enumerate()
394            .map(|(i, ex)| summarize(i, ex))
395            .collect();
396        for i in 1..all.len() {
397            let (prev, cur) = (&all[i - 1], &all[i]);
398            let sca_required = prev
399                .global
400                .iter()
401                .chain(prev.segment.iter().map(|(_, c)| c))
402                .any(|c| c.kind() == Some(Kind::ScaRequired));
403            let same_jobs = |a: &[String], b: &[String]| {
404                let (mut a, mut b) = (a.to_vec(), b.to_vec());
405                a.sort();
406                b.sort();
407                a == b
408            };
409            if sca_required
410                && cur.tan.is_some()
411                && !cur.jobs.is_empty()
412                && same_jobs(&prev.jobs, &cur.jobs)
413            {
414                all[i].retry_of = Some(i - 1);
415            }
416        }
417        all
418    }
419
420    /// The summary as a table for humans: [`SUMMARY_LEGEND`], the accounts
421    /// (one line each), then one line per exchange.
422    pub fn summary_table(&self) -> String {
423        let mut out = format!("{SUMMARY_LEGEND}\n");
424        if !self.client.version.is_empty() {
425            out.push_str(&format!(
426                "fints-client {}, run {}\n",
427                self.client.version,
428                self.client.outcome.as_deref().unwrap_or("not stated")
429            ));
430        }
431        for account in &self.accounts {
432            out.push_str(&format!("{account}\n"));
433        }
434        for (line, ex) in self.summary().into_iter().zip(&self.exchanges) {
435            out.push_str(&format!("{line}\n"));
436            for note in &ex.notes {
437                out.push_str(&format!("      note: {note}\n"));
438            }
439        }
440        out
441    }
442
443    /// The JSON document, derived fields computed from the raw messages.
444    fn file(&self) -> TraceFile {
445        let exchanges = self
446            .exchanges
447            .iter()
448            .zip(self.summary())
449            .map(|(ex, s)| ExchangeJson {
450                index: s.index,
451                account: ex.account.clone(),
452                retry_of: s.retry_of,
453                failed: s.failed(),
454                sent: Sent {
455                    jobs: s.jobs,
456                    tan: s.tan.map(|(process, for_segment)| Tan {
457                        process,
458                        for_segment,
459                    }),
460                },
461                answer: Answer {
462                    message: s.global,
463                    segments: s
464                        .segment
465                        .into_iter()
466                        .map(|(job, c)| SegmentCode {
467                            job,
468                            code: c.code,
469                            text: c.text,
470                        })
471                        .collect(),
472                },
473                error: ex.error.clone(),
474                notes: ex.notes.clone(),
475                request: split_segments(&ex.request),
476                response: split_segments(&ex.response),
477            })
478            .collect();
479        TraceFile {
480            format: TRACE_FORMAT.to_string(),
481            comment: self.comment.lines().map(str::to_string).collect(),
482            client: self.client.clone(),
483            bank: Bank {
484                blz: self.blz(),
485                bic: self.bic(),
486            },
487            accounts: self.accounts.clone(),
488            exchanges,
489        }
490    }
491}
492
493// ── Rebuilding shapes ───────────────────────────────────────────────────
494
495/// The binary data of a recorded answer segment made valid again, if the
496/// segment holds a shape-masked statement (HIKAZ: MT940, HICAZ: camt.052,
497/// HIWPD/HIWDU: MT535/536): each `#` becomes `1` in an amount and `X` in
498/// text, read with the same field rules as the mask, so the result has the
499/// bank's layout. `None` for other segments.
500pub fn unshape_statement(segment: &str, data: &[u8]) -> Option<Vec<u8>> {
501    mask::shape::Format::of(segment).map(|f| mask::shape::unshape(f, data))
502}
503
504/// A shape-masked text element made valid again: `####,##` becomes
505/// `1111,11`, any other `#` becomes `X`.
506pub fn unshape_text(text: &str) -> String {
507    mask::shape::unshape_text(text)
508}
509
510// ── JSON document ───────────────────────────────────────────────────────
511
512#[derive(Serialize, Deserialize)]
513#[serde(deny_unknown_fields)]
514struct TraceFile {
515    format: String,
516    comment: Vec<String>,
517    client: Client,
518    bank: Bank,
519    accounts: Vec<TraceAccount>,
520    exchanges: Vec<ExchangeJson>,
521}
522
523#[derive(Serialize, Deserialize)]
524#[serde(deny_unknown_fields)]
525struct Bank {
526    blz: Option<String>,
527    bic: Option<String>,
528}
529
530#[derive(Serialize, Deserialize)]
531#[serde(deny_unknown_fields)]
532struct ExchangeJson {
533    index: usize,
534    account: Option<String>,
535    retry_of: Option<usize>,
536    sent: Sent,
537    answer: Answer,
538    failed: bool,
539    error: Option<String>,
540    notes: Vec<String>,
541    request: Vec<String>,
542    response: Vec<String>,
543}
544
545#[derive(Serialize, Deserialize)]
546#[serde(deny_unknown_fields)]
547struct Sent {
548    jobs: Vec<String>,
549    tan: Option<Tan>,
550}
551
552#[derive(Serialize, Deserialize)]
553#[serde(deny_unknown_fields)]
554struct Tan {
555    process: String,
556    #[serde(rename = "for")]
557    for_segment: String,
558}
559
560#[derive(Serialize, Deserialize)]
561#[serde(deny_unknown_fields)]
562struct Answer {
563    message: Vec<Code>,
564    segments: Vec<SegmentCode>,
565}
566
567#[derive(Serialize, Deserialize)]
568#[serde(deny_unknown_fields)]
569struct SegmentCode {
570    job: String,
571    code: String,
572    text: String,
573}
574
575/// The first place, as a path (`sent.jobs[0]`), where `found` differs from
576/// `want`, with both values there. A missing field counts as null.
577fn first_difference<'a>(
578    path: &str,
579    found: &'a Value,
580    want: &'a Value,
581) -> Option<(String, &'a Value, &'a Value)> {
582    match (found, want) {
583        (Value::Object(f), Value::Object(w)) if f.keys().all(|k| w.contains_key(k)) => {
584            w.iter().find_map(|(k, wv)| {
585                first_difference(&format!("{path}.{k}"), f.get(k).unwrap_or(&Value::Null), wv)
586            })
587        }
588        (Value::Array(f), Value::Array(w)) if f.len() == w.len() => f
589            .iter()
590            .zip(w)
591            .enumerate()
592            .find_map(|(i, (fv, wv))| first_difference(&format!("{path}[{i}]"), fv, wv)),
593        _ if found == want => None,
594        _ => Some((path.to_string(), found, want)),
595    }
596}
597
598/// The message as one string per segment, each byte the ISO 8859-1
599/// character of the same value. A segment ends at a `'` that is not
600/// escaped (`?'`) and not inside binary data (`@len@…`); the binary data of
601/// HNVSD is split too, since it holds the inner segments: its header up to
602/// `@len@` is a string, each inner segment one, its closing `'` one. Never
603/// fails: what
604/// does not end in `'` is the last string.
605fn split_segments(msg: &[u8]) -> Vec<String> {
606    let latin1 = |b: &[u8]| b.iter().copied().map(char::from).collect::<String>();
607    let mut parts = Vec::new();
608    let (mut start, mut segment, mut i) = (0, 0, 0);
609    while i < msg.len() {
610        match msg[i] {
611            b'?' => i += 2,
612            b'\'' => {
613                i += 1;
614                parts.push(latin1(&msg[start..i]));
615                start = i;
616                segment = i;
617            }
618            b'@' => match binary_header(msg, i) {
619                Some((_, data)) if msg[segment..].starts_with(b"HNVSD:") => {
620                    parts.push(latin1(&msg[start..data]));
621                    i = data;
622                    start = data;
623                    segment = data;
624                }
625                Some((len, data)) => i = data.saturating_add(len),
626                None => i += 1,
627            },
628            _ => i += 1,
629        }
630    }
631    if start < msg.len() {
632        parts.push(latin1(&msg[start..]));
633    }
634    parts
635}
636
637/// `@len@` at `at`: the length and where the data starts.
638fn binary_header(msg: &[u8], at: usize) -> Option<(usize, usize)> {
639    let digits = msg[at + 1..]
640        .iter()
641        .take_while(|b| b.is_ascii_digit())
642        .count();
643    let end = at + 1 + digits;
644    if digits == 0 || msg.get(end) != Some(&b'@') {
645        return None;
646    }
647    let len = std::str::from_utf8(&msg[at + 1..end]).ok()?.parse().ok()?;
648    Some((len, end + 1))
649}
650
651/// The bytes of [`split_segments`] again.
652fn join_segments(parts: &[String]) -> std::result::Result<Vec<u8>, String> {
653    let mut out = Vec::new();
654    for (n, part) in parts.iter().enumerate() {
655        for c in part.chars() {
656            out.push(
657                u8::try_from(u32::from(c))
658                    .map_err(|_| format!("string {n}: {c:?} is not an ISO 8859-1 character"))?,
659            );
660        }
661    }
662    Ok(out)
663}
664
665// ── Summary ─────────────────────────────────────────────────────────────
666
667/// The first line of [`Trace::summary_table`]: how to read the lines below.
668pub const SUMMARY_LEGEND: &str = "#ex  jobs +HKTAN(process,job)  | HIRMG codes | job HIRMS codes | transport error  \
669     FAILED = 9xxx or error  retry of #ex = resent with HKTAN after 9075  account #n; \
670     texts for 9xxx only";
671
672/// A return code with its text (one element of HIRMG or HIRMS).
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674#[serde(deny_unknown_fields)]
675pub struct Code {
676    /// The four-digit code, e.g. `9050`.
677    pub code: String,
678    /// The bank's text, as recorded.
679    pub text: String,
680}
681
682impl Code {
683    fn is_error(&self) -> bool {
684        self.code.starts_with('9')
685    }
686
687    /// The code's kind; `None` if the recorded code is not four digits.
688    fn kind(&self) -> Option<Kind> {
689        crate::return_code::Code::new(&self.code).map(|c| Kind::of(c, &[]))
690    }
691}
692
693/// One exchange of a trace, read for a human: what was asked, what the
694/// bank answered. Built by [`Trace::summary`]; never fails.
695#[derive(Debug, Clone, PartialEq, Eq)]
696pub struct ExchangeSummary {
697    /// Position in the trace, from 0.
698    pub index: usize,
699    /// Every non-envelope request segment except HKTAN, as `CODE:version`
700    /// (`(unreadable)` if the request does not tokenize).
701    pub jobs: Vec<String>,
702    /// HKTAN's process and the segment it refers to, e.g. `("4", "HKKAZ")`.
703    pub tan: Option<(String, String)>,
704    /// The codes of HIRMG.
705    pub global: Vec<Code>,
706    /// The codes of HIRMS, with the code of the request segment each
707    /// refers to.
708    pub segment: Vec<(String, Code)>,
709    /// The transport error, or `(unreadable response)`.
710    pub error: Option<String>,
711    /// The exchange's [`Exchange::account`]: the alias of the account it is
712    /// about.
713    pub account: Option<String>,
714    /// The exchange this one repeats with HKTAN after a 9075 answer.
715    pub retry_of: Option<usize>,
716}
717
718impl ExchangeSummary {
719    /// True if the exchange has an error or any 9xxx code.
720    pub fn failed(&self) -> bool {
721        self.error.is_some()
722            || self.global.iter().any(Code::is_error)
723            || self.segment.iter().any(|(_, c)| c.is_error())
724    }
725}
726
727impl fmt::Display for ExchangeSummary {
728    /// One line:
729    /// `#08  HKKAZ:7 +HKTAN(4,HKKAZ)  | 9050 | HKKAZ 9010 text  FAILED  retry of #07  account #2`
730    /// (see [`SUMMARY_LEGEND`]). Texts are printed for 9xxx codes only.
731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732        let code_text = |c: &Code| {
733            if c.is_error() && !c.text.is_empty() {
734                format!("{} {}", c.code, c.text)
735            } else {
736                c.code.clone()
737            }
738        };
739        write!(f, "#{:02}  {}", self.index, self.jobs.join(" "))?;
740        if let Some((process, seg)) = &self.tan {
741            if seg.is_empty() {
742                write!(f, " +HKTAN({process})")?;
743            } else {
744                write!(f, " +HKTAN({process},{seg})")?;
745            }
746        }
747        write!(
748            f,
749            "  | {}",
750            self.global
751                .iter()
752                .map(code_text)
753                .collect::<Vec<_>>()
754                .join(" ")
755        )?;
756        if !self.segment.is_empty() {
757            let parts: Vec<String> = self
758                .segment
759                .iter()
760                .map(|(seg, c)| format!("{seg} {}", code_text(c)))
761                .collect();
762            write!(f, " | {}", parts.join(", "))?;
763        }
764        if let Some(e) = &self.error {
765            write!(f, " | {e}")?;
766        }
767        if self.failed() {
768            write!(f, "  FAILED")?;
769        }
770        if let Some(i) = self.retry_of {
771            write!(f, "  retry of #{i:02}")?;
772        }
773        if let Some(alias) = &self.account {
774            write!(f, "  account {alias}")?;
775        }
776        Ok(())
777    }
778}
779
780/// Every segment of a message, the ones inside HNVSD first (as
781/// `for_each_segment`); `None` if anything does not tokenize.
782fn all_segments(msg: &[u8]) -> Option<Vec<RawSegment>> {
783    let mut outer = wire::tokenize(msg).ok()?;
784    let mut all = Vec::new();
785    for seg in &mut outer {
786        if let Some(inner) = hnvsd_payload(seg) {
787            all.extend(wire::tokenize(inner).ok()?);
788        }
789    }
790    all.extend(outer);
791    Some(all)
792}
793
794/// The codes of a HIRMG/HIRMS segment: its data elements 1.. are
795/// `code:reference:text:parameters`.
796fn return_codes(seg: &RawSegment) -> Vec<Code> {
797    (1..seg.degs.len())
798        .filter_map(|i| {
799            Some(Code {
800                code: text(seg, i, 0)?.to_string(),
801                text: text(seg, i, 2).unwrap_or_default().to_string(),
802            })
803        })
804        .collect()
805}
806
807fn summarize(index: usize, ex: &Exchange) -> ExchangeSummary {
808    const ENVELOPE: [&str; 6] = ["HNHBK", "HNVSK", "HNVSD", "HNSHK", "HNSHA", "HNHBS"];
809    let mut s = ExchangeSummary {
810        index,
811        jobs: Vec::new(),
812        tan: None,
813        global: Vec::new(),
814        segment: Vec::new(),
815        error: ex.error.clone(),
816        account: ex.account.clone(),
817        retry_of: None,
818    };
819    let request = all_segments(&ex.request);
820    let mut numbers: HashMap<u16, String> = HashMap::new();
821    match &request {
822        Some(segs) => {
823            for seg in segs {
824                numbers.insert(seg.segment_number(), code(seg).to_string());
825                match code(seg) {
826                    c if ENVELOPE.contains(&c) => {}
827                    "HKTAN" => {
828                        s.tan = Some((
829                            text(seg, 1, 0).unwrap_or_default().to_string(),
830                            text(seg, 2, 0).unwrap_or_default().to_string(),
831                        ));
832                    }
833                    c => s.jobs.push(format!("{c}:{}", seg.segment_version())),
834                }
835            }
836        }
837        None => s.jobs.push("(unreadable)".into()),
838    }
839    if ex.error.is_none() {
840        match all_segments(&ex.response) {
841            Some(segs) => {
842                for seg in &segs {
843                    match code(seg) {
844                        "HIRMG" => s.global.extend(return_codes(seg)),
845                        "HIRMS" => {
846                            let target = seg
847                                .segment_reference()
848                                .and_then(|r| numbers.get(&r).cloned())
849                                .unwrap_or_else(|| "?".into());
850                            s.segment
851                                .extend(return_codes(seg).into_iter().map(|c| (target.clone(), c)));
852                        }
853                        _ => {}
854                    }
855                }
856            }
857            None => s.error = Some("(unreadable response)".into()),
858        }
859    }
860    s
861}
862
863// ── Segments ────────────────────────────────────────────────────────────
864
865fn code(seg: &RawSegment) -> &str {
866    seg.segment_type()
867}
868
869fn text(seg: &RawSegment, de: usize, ge: usize) -> Option<&str> {
870    match seg.degs.get(de)?.0.get(ge)? {
871        DataElement::Text(s) => Some(s),
872        _ => None,
873    }
874}
875
876fn is_starred(s: &str) -> bool {
877    !s.is_empty() && s.bytes().all(|b| b == b'*')
878}
879
880/// A BIC: 8 or 11 letters and digits.
881fn is_bic(s: &str) -> bool {
882    matches!(s.len(), 8 | 11) && s.bytes().all(|b| b.is_ascii_alphanumeric())
883}
884
885/// The HNVSD payload of an outer segment, if it has one.
886fn hnvsd_payload(seg: &mut RawSegment) -> Option<&mut Vec<u8>> {
887    if code(seg) != "HNVSD" {
888        return None;
889    }
890    match seg.degs.get_mut(1)?.0.get_mut(0)? {
891        DataElement::Binary(b) => Some(b),
892        _ => None,
893    }
894}
895
896/// Calls `f` for every outer segment and every segment inside HNVSD.
897fn for_each_segment(msg: &[u8], mut f: impl FnMut(&RawSegment)) {
898    let Ok(mut outer) = wire::tokenize(msg) else {
899        return;
900    };
901    for seg in &mut outer {
902        if let Some(inner) = hnvsd_payload(seg)
903            && let Ok(inner) = wire::tokenize(inner)
904        {
905            inner.iter().for_each(&mut f);
906        }
907        f(seg);
908    }
909}
910
911/// Rewrites every segment (inside HNVSD first, then the outer ones).
912fn map_message(msg: &[u8], mut f: impl FnMut(&mut RawSegment)) -> Option<Vec<u8>> {
913    let mut outer = wire::tokenize(msg).ok()?;
914    for seg in &mut outer {
915        if let Some(payload) = hnvsd_payload(seg) {
916            let mut inner = wire::tokenize(payload).ok()?;
917            inner.iter_mut().for_each(&mut f);
918            *payload = wire::serialize(&inner).ok()?;
919        }
920        f(seg);
921    }
922    wire::serialize(&outer).ok()
923}
924
925// ── Account aliases ─────────────────────────────────────────────────────
926
927/// Segments whose data element 1 addresses an account (KTV or KTI).
928const ACCOUNT_JOBS: [&str; 8] = [
929    "HKSAL", "HKKAZ", "HKCAZ", "HKWPD", "HKWDU", "HKSPA", "HKCCS", "HKIPZ",
930];
931
932/// What identifies an account: the IBAN, or the national triple
933/// number (leading zeros dropped), subaccount (empty if none), BLZ.
934#[derive(Hash)]
935enum IdKey<'a> {
936    Iban(&'a str),
937    National(&'a str, &'a str, &'a str),
938}
939
940impl<'a> IdKey<'a> {
941    fn iban(iban: &'a str) -> Option<Self> {
942        (!iban.is_empty() && !is_starred(iban)).then_some(IdKey::Iban(iban))
943    }
944
945    fn national(number: &'a str, sub: &'a str, blz: &'a str) -> Option<Self> {
946        let number = number.trim_start_matches('0');
947        (!number.is_empty() && !blz.is_empty() && !is_starred(number))
948            .then_some(IdKey::National(number, sub, blz))
949    }
950}
951
952/// The accounts of the UPDs a [`Recorder`] has seen, found by keyed hashes
953/// of their identifiers. Holds no identifier.
954#[derive(Default)]
955struct AccountIndex {
956    /// Random per recorder, never written: the hashes mean nothing outside.
957    keys: RandomState,
958    /// Hash of an [`IdKey`] → position in `accounts`.
959    by_key: HashMap<u64, usize>,
960    /// The accounts; alias `#n` is position + 1.
961    accounts: Vec<TraceAccount>,
962}
963
964impl AccountIndex {
965    fn hash(&self, key: &IdKey) -> u64 {
966        self.keys.hash_one(key)
967    }
968
969    fn find(&self, keys: &[Option<IdKey>]) -> Option<usize> {
970        keys.iter()
971            .flatten()
972            .find_map(|k| self.by_key.get(&self.hash(k)).copied())
973    }
974
975    fn keys(acc: &SepaAccount) -> [Option<IdKey<'_>>; 2] {
976        [
977            IdKey::iban(acc.iban.as_str()),
978            IdKey::national(&acc.account_number, &acc.sub_account, acc.blz.as_str()),
979        ]
980    }
981
982    /// Learns every HIUPD of an unmasked answer: a new account gets the
983    /// next alias, a known one (same IBAN or national triple) keeps its own.
984    fn learn(&mut self, answer: &[u8]) {
985        let Some(segs) = all_segments(answer) else {
986            return;
987        };
988        for seg in segs.iter().filter(|s| code(s) == "HIUPD") {
989            let Some(acc) = crate::segments::read::upd_account(seg) else {
990                continue;
991            };
992            let keys = Self::keys(&acc);
993            if keys.iter().all(Option::is_none) {
994                continue;
995            }
996            let at = self.find(&keys).unwrap_or(self.accounts.len());
997            let account = trace_account(at + 1, &acc);
998            if at == self.accounts.len() {
999                self.accounts.push(account);
1000            } else {
1001                self.accounts[at] = account;
1002            }
1003            for key in keys.iter().flatten() {
1004                self.by_key.insert(self.hash(key), at);
1005            }
1006        }
1007    }
1008
1009    /// The alias of the first account a job segment of an unmasked request
1010    /// addresses: data element 1, read as KTI (`IBAN:BIC[:number:sub:280:BLZ]`)
1011    /// or KTV (`number:sub:280:BLZ`).
1012    fn alias_of_request(&self, request: &[u8]) -> Option<String> {
1013        let segs = all_segments(request)?;
1014        segs.iter()
1015            .filter(|s| ACCOUNT_JOBS.contains(&code(s)))
1016            .find_map(|seg| {
1017                let g = |i| text(seg, 1, i).unwrap_or_default();
1018                self.find(&[
1019                    IdKey::iban(g(0)),
1020                    IdKey::national(g(2), g(3), g(5)),
1021                    IdKey::national(g(0), g(1), g(3)),
1022                ])
1023            })
1024            .map(|at| self.accounts[at].alias.clone())
1025    }
1026
1027    fn account_of(&self, acc: &AccountInfo) -> Option<TraceAccount> {
1028        let blz = match &acc.key {
1029            crate::types::AccountKey::National { blz, .. } => blz.as_str(),
1030            crate::types::AccountKey::Iban { .. } => "",
1031        };
1032        let keys = [
1033            IdKey::iban(acc.iban.as_ref().map_or("", |i| i.as_str())),
1034            IdKey::national(
1035                acc.number.as_deref().unwrap_or_default(),
1036                acc.subaccount.as_deref().unwrap_or_default(),
1037                blz,
1038            ),
1039        ];
1040        self.find(&keys).map(|at| self.accounts[at].clone())
1041    }
1042}
1043
1044/// The [`TraceAccount`] `#alias` of a UPD account: class, Kontoart, jobs.
1045fn trace_account(alias: usize, acc: &SepaAccount) -> TraceAccount {
1046    use crate::types::AccountClass::*;
1047    let class = match acc.classify().map(|(class, _)| class) {
1048        Some(Checking) => Some("checking"),
1049        Some(Savings) => Some("savings"),
1050        Some(FixedDeposit) => Some("fixed-deposit"),
1051        Some(Depot) => Some("depot"),
1052        Some(Loan) => Some("loan"),
1053        Some(CreditCard) => Some("credit-card"),
1054        Some(FundDepot) => Some("fund-depot"),
1055        Some(HomeSavings) => Some("home-savings"),
1056        Some(Insurance) => Some("insurance"),
1057        Some(Other) => Some("other"),
1058        None => None,
1059    };
1060    TraceAccount {
1061        alias: format!("#{alias}"),
1062        class: class.map(str::to_string),
1063        kontoart: acc.account_type,
1064        jobs: acc.allowed_jobs.clone(),
1065    }
1066}
1067
1068// ── Recording ───────────────────────────────────────────────────────────
1069
1070/// Records the exchanges of the transports it wraps. Cheap to clone; clones
1071/// share the log. Wrap a transport ([`Recorder::wrap`]), hand it to the
1072/// dialogs (`with_transport`), run the client, then take
1073/// [`Recorder::trace`].
1074#[derive(Clone)]
1075pub struct Recorder(Arc<Shared>);
1076
1077/// A segment the recorder has no field list for, as the person recording
1078/// may look at it before deciding whether a trace shows it
1079/// ([`Recorder::unknown_segments`]).
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct UnknownSegment {
1082    /// The segment code, e.g. `HIXYZ`.
1083    pub code: String,
1084    pub version: u16,
1085    /// How many of them the dialog had.
1086    pub count: usize,
1087    /// The first one as sent, unmasked: it may hold personal data.
1088    /// ISO 8859-1 text; a byte that is not printable shows as `.`.
1089    pub example: String,
1090}
1091
1092struct Shared {
1093    /// The exchanges, masked, with the unknown segments still as sent
1094    /// (`mask::mask_for_recorder`); they are starred when a trace is taken.
1095    log: Mutex<Vec<Exchange>>,
1096    accounts: Mutex<AccountIndex>,
1097    ids: Identities,
1098}
1099
1100impl Default for Recorder {
1101    fn default() -> Self {
1102        Self::with_salt(Salt::random())
1103    }
1104}
1105
1106impl Recorder {
1107    /// An empty recorder with a fresh random [`Salt`] that is never
1108    /// written: its pseudonyms are consistent within its trace and link to
1109    /// no other trace. The default.
1110    pub fn new() -> Self {
1111        Self::default()
1112    }
1113
1114    /// An empty recorder whose pseudonyms are keyed by `salt`: every trace
1115    /// recorded with the same salt gives a reference or ID the same
1116    /// pseudonym. Account identifiers still get aliases of this trace
1117    /// only; the salt does not reach them.
1118    pub fn with_salt(salt: Salt) -> Self {
1119        Recorder(Arc::new(Shared {
1120            log: Mutex::default(),
1121            accounts: Mutex::default(),
1122            ids: Identities::new(salt).with_days(Identities::random_days()),
1123        }))
1124    }
1125
1126    /// A transport that sends through `inner` and records every exchange
1127    /// (redacted) in this recorder, in the order the sends finish.
1128    pub fn wrap(&self, inner: SharedTransport) -> SharedTransport {
1129        Arc::new(Recording {
1130            inner,
1131            log: self.clone(),
1132        })
1133    }
1134
1135    /// The exchanges so far, redacted but not anonymised. Unknown segments
1136    /// show only their header and the length of each element.
1137    pub fn exchanges(&self) -> Vec<Exchange> {
1138        self.exchanges_keeping(&[])
1139    }
1140
1141    fn exchanges_keeping(&self, keep: &[&str]) -> Vec<Exchange> {
1142        let keep = |code: &str| keep.contains(&code);
1143        self.raw_log()
1144            .into_iter()
1145            .map(|ex| Exchange {
1146                request: mask::hide_unknown(&ex.request, &keep),
1147                response: mask::hide_unknown(&ex.response, &keep),
1148                ..ex
1149            })
1150            .collect()
1151    }
1152
1153    fn raw_log(&self) -> Vec<Exchange> {
1154        self.0.log.lock().unwrap_or_else(|e| e.into_inner()).clone()
1155    }
1156
1157    /// The segments of the dialog so far that the recorder has no field
1158    /// list for, one entry per code and version. A trace shows only their
1159    /// header and element lengths, which is rarely enough to support a bank
1160    /// that sends them. Show the examples to the person recording; the
1161    /// codes they agree to go to [`Recorder::trace_keeping`].
1162    pub fn unknown_segments(&self) -> Vec<UnknownSegment> {
1163        let mut found: Vec<UnknownSegment> = Vec::new();
1164        for ex in self.raw_log() {
1165            for bytes in [&ex.request, &ex.response]
1166                .into_iter()
1167                .flat_map(|m| mask::unknown_segments(m))
1168            {
1169                let Some(seg) = wire::tokenize(&bytes).ok().and_then(|mut s| s.pop()) else {
1170                    continue;
1171                };
1172                let (code, version) = (code(&seg).to_string(), seg.segment_version());
1173                match found
1174                    .iter_mut()
1175                    .find(|u| u.code == code && u.version == version)
1176                {
1177                    Some(known) => known.count += 1,
1178                    None => found.push(UnknownSegment {
1179                        code,
1180                        version,
1181                        count: 1,
1182                        example: bytes
1183                            .iter()
1184                            .map(|&b| match b {
1185                                0x20..=0x7e | 0xa0..=0xff => char::from(b),
1186                                _ => '.',
1187                            })
1188                            .collect(),
1189                    }),
1190                }
1191            }
1192        }
1193        found
1194    }
1195
1196    /// The accounts seen so far, in alias order.
1197    pub fn accounts(&self) -> Vec<TraceAccount> {
1198        self.index().accounts.clone()
1199    }
1200
1201    /// The exchanges so far, anonymised ([`Trace::from_exchanges`]), with
1202    /// the accounts they name. Unknown segments show only their header and
1203    /// the length of each element.
1204    pub fn trace(&self) -> Trace {
1205        self.trace_keeping(&[])
1206    }
1207
1208    /// [`Recorder::trace`] in which the unknown segments with these codes
1209    /// stay as the bank sent them, unmasked. Only for codes whose examples
1210    /// ([`Recorder::unknown_segments`]) a person has read.
1211    pub fn trace_keeping(&self, codes: &[&str]) -> Trace {
1212        Trace {
1213            accounts: self.accounts(),
1214            client: Client {
1215                version: env!("CARGO_PKG_VERSION").to_string(),
1216                outcome: None,
1217            },
1218            ..Trace::from_exchanges(self.exchanges_keeping(codes))
1219        }
1220    }
1221
1222    /// The alias and description the recorder gives `account` (same IBAN
1223    /// or the same number, subaccount and BLZ as a HIUPD account it has
1224    /// seen), e.g. `account #2 (class checking; Kontoart 1; jobs HKSAL HKKAZ)`.
1225    pub fn account_of(&self, account: &AccountInfo) -> Option<TraceAccount> {
1226        self.index().account_of(account)
1227    }
1228
1229    fn index(&self) -> std::sync::MutexGuard<'_, AccountIndex> {
1230        self.0.accounts.lock().unwrap_or_else(|e| e.into_inner())
1231    }
1232}
1233
1234struct Recording {
1235    inner: SharedTransport,
1236    log: Recorder,
1237}
1238
1239/// Short, content-free summary of a failed send (an HTTP body is never
1240/// included: it may echo request data); a single line.
1241/// The kind of an error without its text: the variant, with the HTTP
1242/// status, the transport kind, the bank's code or the unreadable segment.
1243pub fn outcome_label(e: &FinTSError) -> String {
1244    let debug = format!("{e:?}");
1245    let variant: String = debug
1246        .chars()
1247        .take_while(char::is_ascii_alphanumeric)
1248        .collect();
1249    match e {
1250        FinTSError::Http { status, .. } => format!("Http {status}"),
1251        FinTSError::Transport { kind, .. } => format!("Transport {kind}"),
1252        FinTSError::Bank(bank) => format!("Bank {}", bank.code().code),
1253        FinTSError::SegmentUnreadable(error) => format!("SegmentUnreadable {}", codec_note(error)),
1254        _ => variant,
1255    }
1256}
1257
1258/// A codec error without the value: the kind and the field.
1259fn codec_note(error: &crate::codec::CodecError) -> String {
1260    let kind: String = format!("{:?}", error.kind)
1261        .chars()
1262        .take_while(char::is_ascii_alphanumeric)
1263        .collect();
1264    format!("{kind} at {}", error.field)
1265}
1266
1267/// What the client makes of an unmasked answer ([`Exchange::notes`]).
1268fn client_notes(answer: &[u8]) -> Vec<String> {
1269    let Some(segments) = all_segments(answer) else {
1270        return vec!["the answer does not tokenize".to_string()];
1271    };
1272    let mut notes = Vec::new();
1273    // SWIFT character set X: letters, digits, / - ? : ( ) . , ' + space.
1274    let swift = |b: u8| b.is_ascii_alphanumeric() || b"/-?:().,'+ \r\n".contains(&b);
1275    for seg in &segments {
1276        if !matches!(code(seg), "HIKAZ" | "HIWPD" | "HIWDU") {
1277            continue;
1278        }
1279        let odd = seg
1280            .degs
1281            .iter()
1282            .flat_map(|d| &d.0)
1283            .filter_map(DataElement::as_bytes)
1284            .flatten()
1285            .filter(|&&b| !swift(b))
1286            .count();
1287        if odd > 0 {
1288            notes.push(format!(
1289                "{}:{}: {odd} characters outside the SWIFT character set",
1290                code(seg),
1291                seg.segment_version()
1292            ));
1293        }
1294    }
1295    for parsed in crate::codec::parse_segments(segments) {
1296        if let crate::codec::ParsedSegment::Raw { segment, error } = parsed
1297            && error.kind != crate::codec::ErrorKind::UnknownSegment
1298        {
1299            notes.push(format!(
1300                "{}:{}: not read, {}",
1301                code(&segment),
1302                segment.segment_version(),
1303                codec_note(&error)
1304            ));
1305        }
1306    }
1307    notes
1308}
1309
1310fn error_summary(e: &FinTSError) -> String {
1311    match e {
1312        FinTSError::Http { status, .. } => format!("HTTP {status}"),
1313        FinTSError::Transport { kind, message } => {
1314            format!("transport {kind}: {}", message.replace(['\r', '\n'], " "))
1315        }
1316        _ => "error".to_string(),
1317    }
1318}
1319
1320impl Transport for Recording {
1321    fn send<'a>(&'a self, url: &'a str, message: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
1322        Box::pin(async move {
1323            let ids = &self.log.0.ids;
1324            let request = mask::mask_for_recorder(message, ids);
1325            let result = self.inner.send(url, message).await;
1326            // The unmasked messages are read here and only hashed.
1327            let account = {
1328                let mut accounts = self.log.index();
1329                if let Ok(answer) = &result {
1330                    accounts.learn(answer);
1331                }
1332                accounts.alias_of_request(message)
1333            };
1334            let exchange = match &result {
1335                Ok(answer) => Exchange {
1336                    request,
1337                    response: mask::mask_for_recorder(answer, ids),
1338                    error: None,
1339                    account,
1340                    notes: client_notes(answer),
1341                },
1342                Err(e) => Exchange {
1343                    request,
1344                    response: Vec::new(),
1345                    error: Some(error_summary(e)),
1346                    account,
1347                    notes: Vec::new(),
1348                },
1349            };
1350            self.log
1351                .0
1352                .log
1353                .lock()
1354                .unwrap_or_else(|e| e.into_inner())
1355                .push(exchange);
1356            result
1357        })
1358    }
1359}
1360
1361#[cfg(test)]
1362mod tests {
1363    use super::*;
1364    use crate::error::TransportKind;
1365
1366    fn wrap(inner: &str) -> Vec<u8> {
1367        format!(
1368            "HNHBK:1:3+0+300+D1+1'HNVSD:999:1+@{}@{inner}''HNHBS:9:1+1'",
1369            inner.len() + 1
1370        )
1371        .into_bytes()
1372    }
1373
1374    fn exchange(request: Vec<u8>, response: Vec<u8>) -> Exchange {
1375        Exchange {
1376            request,
1377            response,
1378            error: None,
1379            account: None,
1380            notes: Vec::new(),
1381        }
1382    }
1383
1384    #[test]
1385    fn summary_of_three_exchanges() {
1386        let ok = wrap("HIRMG:2:2+0010::Ok'HIRMS:3:2:3+0020::Done");
1387        let busy =
1388            wrap("HIRMG:2:2+9050::Teilweise fehlerhaft'HIRMS:3:2:3+9075::Freigabe in der App");
1389        let request = |job: &str| wrap(&format!("{job}:3:7+1'HKTAN:4:7+4+HKKAZ"));
1390        let trace = Trace {
1391            exchanges: vec![
1392                exchange(request("HKSAL"), ok),
1393                exchange(request("HKKAZ"), busy),
1394                Exchange {
1395                    request: b"garbage".to_vec(),
1396                    response: Vec::new(),
1397                    error: Some("HTTP 500".into()),
1398                    account: None,
1399                    notes: Vec::new(),
1400                },
1401            ],
1402            ..Trace::default()
1403        };
1404        let sum = trace.summary();
1405        assert_eq!(sum.len(), 3);
1406        assert_eq!(sum[0].jobs, ["HKSAL:7"]);
1407        assert_eq!(sum[0].tan, Some(("4".into(), "HKKAZ".into())));
1408        assert!(!sum[0].failed());
1409        assert_eq!(sum[1].segment[0].0, "HKKAZ");
1410        assert_eq!(sum[1].segment[0].1.code, "9075");
1411        assert!(sum[1].failed());
1412        let line = sum[1].to_string();
1413        assert!(
1414            line.starts_with("#01  HKKAZ:7 +HKTAN(4,HKKAZ)  | 9050 Teilweise"),
1415            "{line}"
1416        );
1417        assert!(
1418            line.ends_with("HKKAZ 9075 Freigabe in der App  FAILED"),
1419            "{line}"
1420        );
1421        assert!(!sum[0].to_string().contains("Done"));
1422        assert!(sum[2].failed());
1423        assert_eq!(sum[2].jobs, ["(unreadable)"]);
1424        assert!(sum[2].to_string().contains("| HTTP 500  FAILED"));
1425        assert!(sum.iter().all(|s| s.retry_of.is_none()));
1426    }
1427
1428    /// HKKAZ without HKTAN, answered 9075; the same HKKAZ with HKTAN.
1429    fn sca_retry() -> Trace {
1430        let sca = wrap("HIRMG:2:2+9050::Teilweise fehlerhaft'HIRMS:3:2:3+9075::SCA erforderlich");
1431        let ok = wrap("HIRMG:2:2+0010::Ok'HIRMS:3:2:3+0020::Ok'HIRMS:4:2:4+0030::Freigabe");
1432        let mut first = exchange(wrap("HKKAZ:3:7+1+N"), sca);
1433        first.account = Some("#1".into());
1434        let mut retry = exchange(wrap("HKKAZ:3:7+1+N'HKTAN:4:7+4+HKKAZ"), ok);
1435        retry.account = Some("#1".into());
1436        Trace {
1437            comment: "Synthetic SCA retry.".into(),
1438            client: Client::default(),
1439            accounts: vec![TraceAccount {
1440                alias: "#1".into(),
1441                class: Some("checking".into()),
1442                kontoart: Some(1),
1443                jobs: vec!["HKKAZ".into()],
1444            }],
1445            exchanges: vec![first, retry.clone(), retry],
1446        }
1447    }
1448
1449    #[test]
1450    fn a_resend_with_hktan_after_9075_is_a_retry() {
1451        let trace = sca_retry();
1452        let sum = trace.summary();
1453        assert_eq!(sum[1].retry_of, Some(0));
1454        assert_eq!(sum[2].retry_of, None, "the answer before was not 9075");
1455        let json = trace.to_json();
1456        assert!(json.contains("\"retry_of\": 0"), "{json}");
1457        assert!(
1458            sum[1].to_string().ends_with("  retry of #00  account #1"),
1459            "{}",
1460            sum[1]
1461        );
1462        let table = trace.summary_table();
1463        let mut lines = table.lines();
1464        assert_eq!(lines.next(), Some(SUMMARY_LEGEND));
1465        assert_eq!(
1466            lines.next(),
1467            Some("account #1 (class checking; Kontoart 1; jobs HKKAZ)")
1468        );
1469        assert!(lines.next().unwrap().starts_with("#00  HKKAZ:7  | 9050"));
1470    }
1471
1472    const REQUEST: &[u8] =
1473        b"HNHBK:1:3+000000000060+300+0+1'HKIDN:2:2+280:12345678+****+0+1'HNHBS:3:1+1'";
1474
1475    #[test]
1476    fn json_round_trips() {
1477        let mut trace = sca_retry();
1478        trace.comment = "line one\nline two".into();
1479        trace.exchanges.push(Exchange {
1480            request: REQUEST.to_vec(),
1481            response: Vec::new(),
1482            error: Some("transport: timed out".into()),
1483            account: None,
1484            notes: Vec::new(),
1485        });
1486        trace.exchanges.push(exchange(
1487            REQUEST.to_vec(),
1488            b"HNHBK:1:3+0+300+0+1'HIRMS:2:2+0010::Gr\xfc\\e\r\n\"'".to_vec(),
1489        ));
1490        let json = trace.to_json();
1491        assert!(
1492            json.starts_with("{\n  \"format\": \"fints-client-trace/4\""),
1493            "{json}"
1494        );
1495        assert!(json.contains("\"blz\": \"12345678\""), "{json}");
1496        assert!(json.contains("\"for\": \"HKKAZ\""), "{json}");
1497        assert!(json.contains("\"job\": \"HKKAZ\""), "{json}");
1498        assert!(json.contains("Grü\\\\e\\r\\n\\\"'"), "{json}");
1499        assert_eq!(Trace::from_json(&json).unwrap(), trace);
1500        assert_eq!(Trace::from_json(&json).unwrap().to_json(), json);
1501    }
1502
1503    #[test]
1504    fn a_hand_edited_derived_field_is_rejected() {
1505        let json = sca_retry().to_json();
1506        let cases = [
1507            (
1508                "\"HKKAZ:7\"",
1509                "\"HKKAZ:6\"",
1510                "exchange 0: derived field sent.jobs[0]",
1511            ),
1512            (
1513                "\"retry_of\": 0",
1514                "\"retry_of\": null",
1515                "exchange 1: derived field retry_of",
1516            ),
1517            (
1518                "\"code\": \"9075\"",
1519                "\"code\": \"0020\"",
1520                "exchange 0: derived field answer.segments[0].code",
1521            ),
1522            (
1523                "\"failed\": true",
1524                "\"failed\": false",
1525                "exchange 0: derived field failed",
1526            ),
1527            (
1528                "\"index\": 2",
1529                "\"index\": 7",
1530                "exchange 2: derived field index",
1531            ),
1532            (
1533                "\"blz\": null",
1534                "\"blz\": \"99999999\"",
1535                "derived field bank.blz",
1536            ),
1537        ];
1538        for (from, to, error) in cases {
1539            assert!(json.contains(from), "{from} not in {json}");
1540            let edited = json.replacen(from, to, 1);
1541            let e = Trace::from_json(&edited).unwrap_err();
1542            assert!(e.starts_with(error), "{from} -> {to}: {e}");
1543        }
1544        let unknown = json.replacen("\"account\": \"#1\"", "\"account\": \"#9\"", 1);
1545        assert_eq!(
1546            Trace::from_json(&unknown).unwrap_err(),
1547            "exchange 0: account \"#9\" is not in `accounts`"
1548        );
1549        let other = json.replace(TRACE_FORMAT, "fints-client-trace/2");
1550        assert!(Trace::from_json(&other).unwrap_err().starts_with("format"));
1551    }
1552
1553    #[test]
1554    fn a_message_splits_into_one_string_per_segment() {
1555        // Inside HNVSD: an escaped `'` and `?`, binary data holding `'` and
1556        // `@`, and ISO 8859-1 letters (ü, ß as single bytes).
1557        let inner: &[u8] = b"HKIDN:2:2+280:12345678+a?'b??+0+1'HKXYZ:3:1+@6@x'y@z'+M\xfc\xdfe'";
1558        let mut msg = format!("HNHBK:1:3+0+300+0+1'HNVSD:999:1+@{}@", inner.len()).into_bytes();
1559        msg.extend_from_slice(inner);
1560        msg.extend_from_slice(b"'HNHBS:3:1+1'");
1561        let parts = split_segments(&msg);
1562        assert_eq!(
1563            parts,
1564            [
1565                "HNHBK:1:3+0+300+0+1'",
1566                "HNVSD:999:1+@59@",
1567                "HKIDN:2:2+280:12345678+a?'b??+0+1'",
1568                "HKXYZ:3:1+@6@x'y@z'+Müße'",
1569                "'",
1570                "HNHBS:3:1+1'",
1571            ]
1572        );
1573        assert_eq!(join_segments(&parts).unwrap(), msg);
1574        let trace = Trace {
1575            exchanges: vec![exchange(msg.clone(), b"HNHBK:1:3+0+300+0+1".to_vec())],
1576            ..Trace::default()
1577        };
1578        assert_eq!(Trace::from_json(&trace.to_json()).unwrap(), trace);
1579        assert_eq!(split_segments(b"no end"), ["no end"]);
1580        assert_eq!(split_segments(b"X:1:1+@99@short"), ["X:1:1+@99@short"]);
1581        assert!(
1582            join_segments(&["€".into()])
1583                .unwrap_err()
1584                .contains("ISO 8859-1")
1585        );
1586    }
1587
1588    #[test]
1589    fn anonymise_renames_dialogs_and_tasks() {
1590        let trace = Trace::from_exchanges(vec![exchange(
1591            b"HNHBK:1:3+000000000010+300+0+1'HKVVB:2:3+0+0+0+REALPRODUCT+1.0'".to_vec(),
1592            b"HNHBK:1:3+000000000010+300+abc123+1+0:1'HITAN:2:7+4++tsk-9+****'HISAL:3:7+***+####+EUR+C:####,##:EUR:20260101'"
1593                .to_vec(),
1594        )]);
1595        let text = trace.to_json();
1596        assert!(
1597            !text.contains("abc123") && text.contains("DIALOG0001"),
1598            "{text}"
1599        );
1600        assert!(
1601            !text.contains("tsk-9") && text.contains("TASK0001"),
1602            "{text}"
1603        );
1604        assert!(
1605            !text.contains("REALPRODUCT") && text.contains("***********"),
1606            "{text}"
1607        );
1608        assert!(text.contains("C:####,##:EUR"), "shapes stay: {text}");
1609    }
1610
1611    struct Fixed(std::result::Result<Vec<u8>, &'static str>);
1612
1613    impl Transport for Fixed {
1614        fn send<'a>(&'a self, _: &'a str, _: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
1615            Box::pin(async move {
1616                self.0
1617                    .clone()
1618                    .map_err(|e| FinTSError::transport(TransportKind::Io, e.to_string()))
1619            })
1620        }
1621    }
1622
1623    #[tokio::test]
1624    async fn no_product_name_purpose_amount_or_account_survives() {
1625        let mt940 = ":61:260102C12,34NTRFNONREF\r\n:86:166?00Gutschrift?20SVWZ+Geheimzweck\r\n";
1626        let camt =
1627            "<Ntry><Amt Ccy=\"EUR\">98765.43</Amt><AddtlNtryInf>Geheimzweck</AddtlNtryInf></Ntry>";
1628        let response = format!(
1629            "HNHBK:1:3+0+300+D1+1'\
1630             HIUPA:2:4:4+secretuser+3+0+Erika Muster+Geheime Erweiterung'\
1631             HIUPD:3:6:4+4711:+DE02120300000000004711+secretuser+1+EUR+Erika Muster++Spargiro Spezial+\
1632             :5000,:EUR+HKSAL:1+HKKAZ:1+Geheime Kontoerweiterung'\
1633             HISAL:4:7:3+DE02120300000000004711::280:12030000+Spargiro Spezial+EUR+C:1234,56:EUR:20260102+\
1634             +5000,:EUR+777,77:EUR'\
1635             HIKAZ:5:7:3+@{}@{mt940}'\
1636             HICAZ:6:1:3+urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.02+@{}@{camt}'",
1637            mt940.len(),
1638            camt.len(),
1639        );
1640        let rec = Recorder::new();
1641        let bank = rec.wrap(Arc::new(Fixed(Ok(response.into_bytes()))));
1642        let request = b"HNHBK:1:3+0+300+0+1'HKIDN:2:2+280:12030000+secretuser+0+1'";
1643        bank.send("http://x/", request).await.unwrap();
1644        let text = rec.trace().to_json();
1645        for secret in [
1646            "Spargiro",
1647            "Geheim",
1648            "Erika",
1649            "Muster",
1650            "4711",
1651            "1234,56",
1652            "777,77",
1653            "5000,",
1654            "12,34",
1655            "98765",
1656            "secretuser",
1657        ] {
1658            assert!(!text.contains(secret), "{secret:?} survives:\n{text}");
1659        }
1660        assert!(text.contains("12030000"), "the BLZ stays");
1661        // Statements keep their shape: markup and codes stay.
1662        for shape in [
1663            "C#,##NTRFNONREF\\r\\n:86:166?00########?20SVWZ+########",
1664            "<Amt Ccy=\\\"EUR\\\">#.##</Amt><AddtlNtryInf>########</AddtlNtryInf>",
1665            "+########+EUR+C:#,##:EUR:",
1666            "++#,##:EUR+#,##:EUR'",
1667        ] {
1668            assert!(text.contains(shape), "{shape:?} not in:\n{text}");
1669        }
1670        // Every date is moved by the days of this recorder (3 to 30 back).
1671        for date in [":61:260102", "20260102"] {
1672            assert!(!text.contains(date), "{date:?} was not moved:\n{text}");
1673        }
1674        assert_eq!(
1675            unshape_statement("HIKAZ", b":61:260102C##,##NTRFNONREF\r\n:86:166?00####").unwrap(),
1676            b":61:260102C11,11NTRFNONREF\r\n:86:166?00XXXX"
1677        );
1678        assert_eq!(unshape_statement("HISAL", b"#"), None);
1679    }
1680
1681    /// Answers with the next message of a script.
1682    struct Script(Mutex<std::collections::VecDeque<Vec<u8>>>);
1683
1684    impl Transport for Script {
1685        fn send<'a>(&'a self, _: &'a str, _: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
1686            Box::pin(async move {
1687                let next = self.0.lock().unwrap().pop_front();
1688                next.ok_or_else(|| FinTSError::transport(TransportKind::Io, "end of script"))
1689            })
1690        }
1691    }
1692
1693    const UPD: &str = "HNHBK:1:3+0+300+D1+1'\
1694        HIUPD:2:6:4+0009876543::280:12345678+DE02123456780009876543+user1+1+EUR+Erika Muster++Girokonto Plus++HKSAL:1+HKKAZ:1'\
1695        HIUPD:3:6:4+7000999::280:12345678++user1++EUR+Erika Muster++Mein Depot++HKWPD:1'\
1696        HIUPD:4:4:4+5550001::280:12345678+user1+EUR+Erika Muster++Sparbuch Extra++HKSAL:1'";
1697
1698    #[tokio::test]
1699    async fn recorder_names_accounts_by_alias_only() {
1700        let ok = b"HNHBK:1:3+0+300+D1+2'HIRMG:2:2+0010::ok'".to_vec();
1701        let answers = [
1702            UPD.as_bytes().to_vec(),
1703            ok.clone(),
1704            ok.clone(),
1705            ok.clone(),
1706            UPD.as_bytes().to_vec(),
1707            ok,
1708        ];
1709        let rec = Recorder::new();
1710        let bank = rec.wrap(Arc::new(Script(Mutex::new(answers.into()))));
1711        let requests: [&[u8]; 6] = [
1712            b"HNHBK:1:3+0+300+0+1'HKIDN:2:2+280:12345678+user1+0+1'",
1713            // KTI with the national parts (HISPAS allows them).
1714            b"HNHBK:1:3+0+300+D1+2'HKSAL:3:7+DE02123456780009876543:TESTDEFFXXX:0009876543::280:12345678+N'HKTAN:4:7+4+HKSAL'",
1715            // KTV, account number with leading zeros the UPD did not have.
1716            b"HNHBK:1:3+0+300+D1+3'HKWPD:3:6+0007000999::280:12345678+EUR'",
1717            b"HNHBK:1:3+0+300+D1+4'HKKAZ:3:5+5550001::280:12345678+N'",
1718            b"HNHBK:1:3+0+300+0+1'HKIDN:2:2+280:12345678+user1+0+1'",
1719            b"HNHBK:1:3+0+300+D2+2'HKSAL:3:6+0009876543::280:12345678+N'",
1720        ];
1721        for request in requests {
1722            bank.send("http://x/", request).await.unwrap();
1723        }
1724        let aliases: Vec<_> = rec.exchanges().into_iter().map(|e| e.account).collect();
1725        let alias = |a: &str| Some(a.to_string());
1726        assert_eq!(
1727            aliases,
1728            // A second UPD keeps the aliases.
1729            [
1730                None,
1731                alias("#1"),
1732                alias("#2"),
1733                alias("#3"),
1734                None,
1735                alias("#1")
1736            ]
1737        );
1738        let trace = rec.trace();
1739        let described: Vec<String> = trace.accounts.iter().map(|a| a.to_string()).collect();
1740        assert_eq!(
1741            described,
1742            [
1743                "account #1 (class checking; Kontoart 1; jobs HKSAL HKKAZ)",
1744                "account #2 (class depot; Kontoart -; jobs HKWPD)",
1745                "account #3 (class -; Kontoart -; jobs HKSAL)",
1746            ]
1747        );
1748        let upd = crate::protocol::Upd::from_segments(
1749            &wire::tokenize(
1750                b"HIUPA:2:4:4+user1+1+0'HIUPD:3:6:4+7000999::280:12345678++user1++EUR+X++Y++HKWPD:1'",
1751            )
1752            .unwrap(),
1753        )
1754        .unwrap();
1755        let depot = AccountInfo::from_upd(&upd, &crate::types::Bic::new("TESTDEFFXXX"));
1756        assert_eq!(rec.account_of(&depot[0]).as_ref(), trace.account("#2"));
1757        let text = trace.to_json();
1758        assert!(text.contains("\"account\": \"#1\""), "{text}");
1759        assert!(text.contains("\"bic\": \"TESTDEFFXXX\""), "{text}");
1760        for secret in [
1761            "DE02123456780009876543",
1762            "9876543",
1763            "7000999",
1764            "5550001",
1765            "user1",
1766            "Erika",
1767            "Girokonto",
1768            "Depot ",
1769            "Mein",
1770            "Sparbuch",
1771        ] {
1772            assert!(!text.contains(secret), "{secret:?} survives:\n{text}");
1773        }
1774        assert_eq!(Trace::from_json(&text).unwrap(), trace);
1775        let summary = trace.summary();
1776        assert!(
1777            summary[2].to_string().ends_with("  account #2"),
1778            "{}",
1779            summary[2]
1780        );
1781    }
1782
1783    #[tokio::test]
1784    async fn recorder_redacts_and_records_failures() {
1785        let rec = Recorder::new();
1786        let ok = rec.wrap(Arc::new(Fixed(Ok(
1787            b"HNHBK:1:3+0+300+D1+1'HIRMS:2:2+0010::ok'".to_vec(),
1788        ))));
1789        let bad = rec.wrap(Arc::new(Fixed(Err("connection refused"))));
1790        let request = b"HNHBK:1:3+0+300+0+1'HKIDN:2:2+280:12345678+secretuser+0+1'";
1791        assert!(ok.send("http://x/", request).await.is_ok());
1792        assert!(bad.send("http://x/", request).await.is_err());
1793        let ex = rec.exchanges();
1794        assert_eq!(ex.len(), 2);
1795        assert!(!String::from_utf8_lossy(&ex[0].request).contains("secretuser"));
1796        assert!(!ex[0].response.is_empty() && ex[0].error.is_none());
1797        assert!(ex[1].response.is_empty());
1798        assert_eq!(
1799            ex[1].error.as_deref(),
1800            Some("transport io: connection refused")
1801        );
1802    }
1803}