Skip to main content

fints_client/protocol/
tan.rs

1//! Which business orders carry HKTAN process 4: one pure decision function.
2//!
3//! The answer comes from the selected security function, profile overrides,
4//! facts learned from the bank, and HIPINS, in that order (first match wins).
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use serde::{Deserialize, Serialize};
9
10use crate::return_code::Kind;
11use crate::types::SegmentType;
12
13/// A bank profile's fixed answer for one order, beating HIPINS.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum TanOverride {
17    /// Always send HKTAN with this order.
18    Always,
19    /// Never send HKTAN with this order.
20    Never,
21}
22
23/// Per-order overrides, keyed by the order's segment code (e.g. `HKSAL`).
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub struct TanOverrides(BTreeMap<SegmentType, TanOverride>);
26
27impl TanOverrides {
28    pub fn get(&self, code: &SegmentType) -> Option<TanOverride> {
29        self.0.get(code).copied()
30    }
31
32    pub fn iter(&self) -> impl Iterator<Item = (SegmentType, TanOverride)> + '_ {
33        self.0.iter().map(|(c, o)| (c.clone(), *o))
34    }
35}
36
37impl FromIterator<(SegmentType, TanOverride)> for TanOverrides {
38    fn from_iter<I: IntoIterator<Item = (SegmentType, TanOverride)>>(iter: I) -> Self {
39        Self(iter.into_iter().collect())
40    }
41}
42
43/// Why [`order_tan`] answered as it did.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum TanReason {
46    /// PIN-only method 999: HKTAN is invalid.
47    PinOnlyMethod,
48    Override,
49    Learned,
50    Hipins,
51    /// Not in HIPINS: under PIN/TAN such an order is not covered by the
52    /// bank's TAN table (PIN/TAN data dictionary, HIPINS), so no HKTAN is
53    /// sent; a `9075` answer still triggers the one retry with HKTAN.
54    Unlisted,
55    /// A payment order (HKCCS, HKIPZ): always TAN-required under a two-step
56    /// function, whatever HIPINS says (PIN/TAN B.4.2; payments design 3.1).
57    Payment,
58}
59
60/// The payment orders: HKTAN process 4 always goes with them.
61pub(crate) fn is_payment_order(code: &str) -> bool {
62    matches!(code, "HKCCS" | "HKIPZ")
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct TanDecision {
67    pub hktan: bool,
68    pub reason: TanReason,
69}
70
71/// Does the order `code` need HKTAN process 4? `two_step` is false when the
72/// selected security function is 999. First matching rule wins.
73pub fn order_tan(
74    code: &SegmentType,
75    two_step: bool,
76    hipins: Option<bool>,
77    overrides: &TanOverrides,
78    learned: &BTreeSet<SegmentType>,
79) -> TanDecision {
80    let (hktan, reason) = if !two_step {
81        (false, TanReason::PinOnlyMethod)
82    } else if let Some(o) = overrides.get(code) {
83        (o == TanOverride::Always, TanReason::Override)
84    } else if is_payment_order(code.as_str()) {
85        (true, TanReason::Payment)
86    } else if learned.contains(code) {
87        (true, TanReason::Learned)
88    } else if let Some(listed) = hipins {
89        (listed, TanReason::Hipins)
90    } else {
91        (false, TanReason::Unlisted)
92    };
93    TanDecision { hktan, reason }
94}
95
96/// What to do after a bank answered an order.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Retry {
99    /// Nothing to change; the caller sees the answer.
100    No,
101    /// 9075 without HKTAN: send the order once more with HKTAN, same dialog.
102    SameDialog,
103    /// 9075 with 9800: the bank ended the dialog. Learn, do not resend.
104    DialogGone,
105}
106
107/// Classify an order answer by its return codes (segment and global).
108/// 9075 ("strong authentication required") without HKTAN is the bank
109/// asking for one; 9050 alone is the usual summary and means nothing here.
110pub fn on_sca_required(decision: &TanDecision, codes: impl IntoIterator<Item = Kind>) -> Retry {
111    if decision.hktan
112        || matches!(
113            decision.reason,
114            TanReason::Override | TanReason::PinOnlyMethod
115        )
116    {
117        return Retry::No;
118    }
119    let (mut sca, mut gone) = (false, false);
120    for c in codes {
121        sca |= c == Kind::ScaRequired;
122        gone |= c == Kind::DialogAborted;
123    }
124    match (sca, gone) {
125        (false, _) => Retry::No,
126        (true, false) => Retry::SameDialog,
127        (true, true) => Retry::DialogGone,
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    fn st(s: &str) -> SegmentType {
136        SegmentType::new(s)
137    }
138
139    fn decide(
140        code: &str,
141        two_step: bool,
142        hipins: &[(&str, bool)],
143        overrides: &[(&str, TanOverride)],
144        learned: &[&str],
145    ) -> TanDecision {
146        order_tan(
147            &st(code),
148            two_step,
149            hipins.iter().find(|(c, _)| *c == code).map(|(_, b)| *b),
150            &overrides.iter().map(|(c, o)| (st(c), *o)).collect(),
151            &learned.iter().map(|c| st(c)).collect(),
152        )
153    }
154
155    fn is(d: TanDecision, hktan: bool, reason: TanReason) {
156        assert_eq!(d, TanDecision { hktan, reason });
157    }
158
159    #[test]
160    fn row1_pin_only_method_sends_no_hktan() {
161        is(
162            decide(
163                "HKSAL",
164                false,
165                &[("HKSAL", true)],
166                &[("HKSAL", TanOverride::Always)],
167                &["HKSAL"],
168            ),
169            false,
170            TanReason::PinOnlyMethod,
171        );
172    }
173
174    #[test]
175    fn row2_override_never() {
176        is(
177            decide(
178                "HKWPD",
179                true,
180                &[("HKWPD", true)],
181                &[("HKWPD", TanOverride::Never)],
182                &[],
183            ),
184            false,
185            TanReason::Override,
186        );
187    }
188
189    #[test]
190    fn row3_override_always() {
191        is(
192            decide(
193                "HKSAL",
194                true,
195                &[("HKSAL", false)],
196                &[("HKSAL", TanOverride::Always)],
197                &[],
198            ),
199            true,
200            TanReason::Override,
201        );
202    }
203
204    #[test]
205    fn row4_learned() {
206        is(
207            decide("HKSAL", true, &[], &[], &["HKSAL"]),
208            true,
209            TanReason::Learned,
210        );
211    }
212
213    #[test]
214    fn row5_hipins_decides() {
215        is(
216            decide("HKKAZ", true, &[("HKKAZ", true)], &[], &[]),
217            true,
218            TanReason::Hipins,
219        );
220        is(
221            decide("HKKAZ", true, &[("HKKAZ", false)], &[], &[]),
222            false,
223            TanReason::Hipins,
224        );
225    }
226
227    #[test]
228    fn row6_unlisted_sends_no_hktan() {
229        is(
230            decide("HKWDU", true, &[], &[], &[]),
231            false,
232            TanReason::Unlisted,
233        );
234        is(
235            decide("HKSAL", true, &[], &[], &[]),
236            false,
237            TanReason::Unlisted,
238        );
239    }
240
241    #[test]
242    fn payment_orders_always_carry_hktan_unless_overridden() {
243        for code in ["HKCCS", "HKIPZ"] {
244            is(
245                decide(code, true, &[(code, false)], &[], &[]),
246                true,
247                TanReason::Payment,
248            );
249            is(decide(code, true, &[], &[], &[]), true, TanReason::Payment);
250            is(
251                decide(code, false, &[], &[], &[]),
252                false,
253                TanReason::PinOnlyMethod,
254            );
255            is(
256                decide(code, true, &[], &[(code, TanOverride::Never)], &[]),
257                false,
258                TanReason::Override,
259            );
260        }
261    }
262
263    #[test]
264    fn precedence() {
265        is(
266            decide(
267                "HKWPD",
268                true,
269                &[],
270                &[("HKWPD", TanOverride::Never)],
271                &["HKWPD"],
272            ),
273            false,
274            TanReason::Override,
275        );
276        is(
277            decide(
278                "HKSAL",
279                true,
280                &[("HKSAL", false)],
281                &[("HKSAL", TanOverride::Always)],
282                &[],
283            ),
284            true,
285            TanReason::Override,
286        );
287        is(
288            decide("HKSAL", true, &[("HKSAL", false)], &[], &["HKSAL"]),
289            true,
290            TanReason::Learned,
291        );
292    }
293
294    #[test]
295    fn overrides_round_trip_as_json() {
296        let o: TanOverrides = [(st("HKSAL"), TanOverride::Always)].into_iter().collect();
297        let json = serde_json::to_string(&o).unwrap();
298        assert_eq!(json, r#"{"HKSAL":"always"}"#);
299        assert_eq!(serde_json::from_str::<TanOverrides>(&json).unwrap(), o);
300    }
301
302    #[test]
303    fn retry_classification() {
304        use Kind::*;
305        let none = TanDecision {
306            hktan: false,
307            reason: TanReason::Hipins,
308        };
309        let sent = TanDecision {
310            hktan: true,
311            reason: TanReason::Hipins,
312        };
313        let never = TanDecision {
314            hktan: false,
315            reason: TanReason::Override,
316        };
317        assert_eq!(on_sca_required(&none, [ScaRequired]), Retry::SameDialog);
318        assert_eq!(
319            on_sca_required(&none, [PartialErrors, ScaRequired]),
320            Retry::SameDialog
321        );
322        assert_eq!(
323            on_sca_required(&none, [ScaRequired, DialogAborted]),
324            Retry::DialogGone
325        );
326        assert_eq!(on_sca_required(&sent, [ScaRequired]), Retry::No);
327        assert_eq!(on_sca_required(&never, [ScaRequired]), Retry::No);
328        assert_eq!(on_sca_required(&none, [PartialErrors]), Retry::No);
329        assert_eq!(on_sca_required(&none, [DialogAborted]), Retry::No);
330    }
331}