Skip to main content

fints_client/quirks/
mod.rs

1//! Repairs for bank messages that break the message layout.
2//!
3//! A [`QuirkChain`] holds [`Quirk`]s. Each quirk recognises one kind of
4//! damage and leaves every other message as it is, so all of them run on
5//! every message. An answer from the bank goes through three stages
6//! ([`QuirkChain::incoming`]):
7//!
8//! 1. raw: [`Quirk::incoming_raw`] sees the answer as it arrived, still in
9//!    its PIN/TAN envelope (HNVSK, HNVSD). Damage to the message head
10//!    HNHBK is repaired here.
11//! 2. The envelope is opened: HNVSK goes, HNVSD is replaced by the segments
12//!    it carries. What remains is HNHBK, the inner segments and HNHBS.
13//! 3. clear text: [`Quirk::incoming`] sees that result.
14//!
15//! A request passes [`Quirk::outgoing`] before it is sent.
16//!
17//! [`tolerant`] holds the repairs of the default chain and explains their
18//! order.
19
20use std::borrow::Cow;
21
22pub mod tolerant;
23pub(crate) mod wire;
24
25/// Facts about the request that an answer belongs to.
26#[derive(Debug, Clone, Copy)]
27pub struct QuirkContext<'a> {
28    /// The HBCI version in our HNHBK, normally `300`.
29    pub hbci_version: &'a str,
30    /// Our dialog ID; `0` in the first message of a dialog.
31    pub dialog_id: &'a str,
32    /// Our message number.
33    pub message_number: u16,
34}
35
36/// The repair of one kind of damage.
37///
38/// Each method returns its input unchanged unless overridden. A method must
39/// not panic, and it returns `Cow::Borrowed` for a message it does not
40/// change; the chain logs every `Cow::Owned` as a repair.
41pub trait Quirk: Send + Sync {
42    /// The name in log lines, such as `SegmentNumbering`.
43    fn name(&self) -> &'static str;
44
45    /// Repair an answer as it arrived, envelope included.
46    fn incoming_raw<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
47        Cow::Borrowed(msg)
48    }
49
50    /// Repair an answer after the envelope was opened.
51    fn incoming<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
52        Cow::Borrowed(msg)
53    }
54
55    /// Change a request before it is sent.
56    fn outgoing<'a>(&self, msg: &'a [u8], _ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
57        Cow::Borrowed(msg)
58    }
59}
60
61/// The quirks of one connection, in the order they run.
62pub struct QuirkChain {
63    quirks: Vec<Box<dyn Quirk>>,
64}
65
66/// The three places a quirk can act.
67#[derive(Debug, Clone, Copy)]
68enum Stage {
69    Raw,
70    ClearText,
71    Outgoing,
72}
73
74impl Stage {
75    fn apply<'a>(self, quirk: &dyn Quirk, msg: &'a [u8], ctx: &QuirkContext<'_>) -> Cow<'a, [u8]> {
76        match self {
77            Self::Raw => quirk.incoming_raw(msg, ctx),
78            Self::ClearText => quirk.incoming(msg, ctx),
79            Self::Outgoing => quirk.outgoing(msg, ctx),
80        }
81    }
82}
83
84impl std::fmt::Debug for QuirkChain {
85    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        out.debug_tuple("QuirkChain").field(&self.names()).finish()
87    }
88}
89
90impl Default for QuirkChain {
91    /// The repairs of [`tolerant`]: [`MissingMessageReference`](tolerant::MissingMessageReference),
92    /// [`HeaderVersion`](tolerant::HeaderVersion),
93    /// [`StatusSegmentOrder`](tolerant::StatusSegmentOrder) and
94    /// [`SegmentNumbering`](tolerant::SegmentNumbering), in that order.
95    fn default() -> Self {
96        let mut chain = Self::none();
97        chain.quirks = vec![
98            Box::new(tolerant::MissingMessageReference),
99            Box::new(tolerant::HeaderVersion),
100            Box::new(tolerant::StatusSegmentOrder),
101            Box::new(tolerant::SegmentNumbering),
102        ];
103        chain
104    }
105}
106
107impl QuirkChain {
108    /// An empty chain. The envelope of answers is still opened.
109    pub fn none() -> Self {
110        Self { quirks: Vec::new() }
111    }
112
113    /// The chain with `quirk` added at the end, for example a repair for
114    /// one bank.
115    pub fn with(mut self, quirk: impl Quirk + 'static) -> Self {
116        self.quirks.push(Box::new(quirk));
117        self
118    }
119
120    /// The names of the quirks, in order.
121    pub fn names(&self) -> Vec<&'static str> {
122        self.quirks.iter().map(|quirk| quirk.name()).collect()
123    }
124
125    /// An answer from the bank, repaired and taken out of its envelope.
126    pub fn incoming(&self, raw: &[u8], ctx: &QuirkContext<'_>) -> Vec<u8> {
127        let repaired = self.run(Stage::Raw, raw.to_vec(), ctx);
128        self.run(Stage::ClearText, unwrap_envelope(&repaired), ctx)
129    }
130
131    /// A request, changed by the outgoing quirks.
132    pub fn outgoing(&self, msg: &[u8], ctx: &QuirkContext<'_>) -> Vec<u8> {
133        self.run(Stage::Outgoing, msg.to_vec(), ctx)
134    }
135
136    fn run(&self, stage: Stage, mut msg: Vec<u8>, ctx: &QuirkContext<'_>) -> Vec<u8> {
137        for quirk in &self.quirks {
138            if let Cow::Owned(repaired) = stage.apply(quirk.as_ref(), &msg, ctx) {
139                tracing::warn!(
140                    quirk = quirk.name(),
141                    ?stage,
142                    "[FinTS] bank message repaired"
143                );
144                msg = repaired;
145            }
146        }
147        msg
148    }
149}
150
151/// The clear-text form of an answer: HNVSK dropped and HNVSD replaced by
152/// the segments in its binary element. An answer without envelope (some
153/// banks send errors that way) comes back unchanged.
154pub(crate) fn unwrap_envelope(msg: &[u8]) -> Vec<u8> {
155    let mut clear = Vec::with_capacity(msg.len());
156    for segment in wire::segments(msg).into_iter().map(|range| &msg[range]) {
157        let keep = match wire::segment_type(segment) {
158            b"HNVSK" => continue,
159            b"HNVSD" => encrypted_data(segment).unwrap_or(segment),
160            _ => segment,
161        };
162        clear.extend_from_slice(keep);
163    }
164    clear
165}
166
167/// The binary content of HNVSD's data element "Verschlüsselte Daten".
168fn encrypted_data(hnvsd: &[u8]) -> Option<&[u8]> {
169    let group = wire::degs(hnvsd).into_iter().nth(1)?;
170    wire::binary_payload(&hnvsd[group])
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    const CTX: QuirkContext<'static> = QuirkContext {
178        hbci_version: "300",
179        dialog_id: "D-1",
180        message_number: 3,
181    };
182
183    const HEAD: &str = "HNHBK:1:3+000000000120+300+D-1+3+D-1:3'";
184
185    fn enveloped(inner: &str) -> Vec<u8> {
186        format!(
187            "{HEAD}HNVSK:998:3+PIN:2+998+1+2::sys+1:20260101:120000+2:2:13:@8@00000000:5:1+280:10000000:user:V:0:0+0'\
188             HNVSD:999:1+@{}@{inner}'HNHBS:5:1+3'",
189            inner.len()
190        )
191        .into_bytes()
192    }
193
194    #[test]
195    fn envelope_is_replaced_by_its_content() {
196        let inner =
197            "HIRMG:2:2+0010::Nachricht entgegengenommen.'HIRMS:3:2:3+0020::Auftrag ausgeführt.'";
198        let clear = format!("{HEAD}{inner}HNHBS:5:1+3'");
199        assert_eq!(unwrap_envelope(&enveloped(inner)), clear.as_bytes());
200    }
201
202    #[test]
203    fn answer_without_envelope_is_unchanged() {
204        let plain = format!("{HEAD}HIRMG:2:2+9800::Dialog abgebrochen.'HNHBS:3:1+3'");
205        assert_eq!(unwrap_envelope(plain.as_bytes()), plain.as_bytes());
206    }
207
208    #[test]
209    fn default_chain_leaves_a_sound_answer_alone() {
210        let inner = "HIRMG:2:2+0010::ok'HIRMS:3:2:3+0020::ok'HISAL:4:7:3+x'";
211        let clear = format!("{HEAD}{inner}HNHBS:5:1+3'");
212        let chain = QuirkChain::default();
213        assert_eq!(chain.incoming(&enveloped(inner), &CTX), clear.as_bytes());
214        assert_eq!(chain.outgoing(clear.as_bytes(), &CTX), clear.as_bytes());
215    }
216
217    /// Test quirk: replaces every `x` by `y` in the stage it is built for.
218    struct XToY(Stage);
219
220    impl XToY {
221        fn swap<'a>(&self, stage: Stage, msg: &'a [u8]) -> Cow<'a, [u8]> {
222            let wanted = std::mem::discriminant(&self.0) == std::mem::discriminant(&stage);
223            if wanted && msg.contains(&b'x') {
224                Cow::Owned(
225                    msg.iter()
226                        .map(|&b| if b == b'x' { b'y' } else { b })
227                        .collect(),
228                )
229            } else {
230                Cow::Borrowed(msg)
231            }
232        }
233    }
234
235    impl Quirk for XToY {
236        fn name(&self) -> &'static str {
237            "XToY"
238        }
239        fn incoming_raw<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
240            self.swap(Stage::Raw, msg)
241        }
242        fn incoming<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
243            self.swap(Stage::ClearText, msg)
244        }
245        fn outgoing<'a>(&self, msg: &'a [u8], _: &QuirkContext<'_>) -> Cow<'a, [u8]> {
246            self.swap(Stage::Outgoing, msg)
247        }
248    }
249
250    #[test]
251    fn each_stage_sees_its_own_form_of_the_message() {
252        let answer = enveloped("HIRMG:2:2+0010::x'");
253        // Raw stage: the envelope is still there; the repair reaches the
254        // inner segments too, as their length does not change.
255        let raw = QuirkChain::none()
256            .with(XToY(Stage::Raw))
257            .incoming(&answer, &CTX);
258        assert!(raw.windows(9).any(|w| w == b"0010::y'H"));
259        // Clear text: no HNVSK is left to see.
260        let clear = QuirkChain::none()
261            .with(XToY(Stage::ClearText))
262            .incoming(&answer, &CTX);
263        assert!(!clear.windows(5).any(|w| w == b"HNVSK"));
264        assert!(clear.windows(8).any(|w| w == b"0010::y'"));
265        // Outgoing quirks do not touch answers, and the other way round.
266        let out_only = QuirkChain::none().with(XToY(Stage::Outgoing));
267        assert!(out_only.incoming(&answer, &CTX).contains(&b'x'));
268        assert_eq!(out_only.outgoing(b"x", &CTX), b"y");
269    }
270
271    #[test]
272    fn names_in_order() {
273        assert!(QuirkChain::none().names().is_empty());
274        let chain = QuirkChain::default().with(XToY(Stage::Raw));
275        let names = chain.names();
276        assert_eq!(names.len(), 5);
277        assert_eq!(names.first(), Some(&"MissingMessageReference"));
278        assert_eq!(names.last(), Some(&"XToY"));
279    }
280}