Skip to main content

fints_client/jobs/
paused.rs

1//! A dialog frozen between two calls (docs/session-state-design.md §3–§4).
2//!
3//! [`Dialog::freeze`] turns an open or paused dialog into a
4//! [`PausedDialog`]: plain, versioned data the caller stores (encrypted: it
5//! holds the user ID, system ID, UPD with IBANs and names, dialog ID, task
6//! reference and challenge) and passes to [`Dialog::thaw`] later, in
7//! another process if need be, with the bank client and the PIN. A paused
8//! transfer also holds its pain.001 (payee name, IBAN, amount) and payee
9//! check result. The
10//! thawed dialog sends its next message with the same dialog ID and the
11//! next message number, as if it had never been frozen.
12//!
13//! Never stored: PIN, TAN, transport, quirk chain, product ID. The library
14//! sets no expiry of its own: [`PausedDialog::expires_at`] tells the caller
15//! the bank's timeout, and a dialog the bank has dropped answers 9800
16//! ([`FinTSError::DialogEnded`]), a TAN past its window 9951.
17
18use super::*;
19use crate::codec::RawSegment;
20use crate::protocol::{Bpd, TanOverrides};
21use crate::session::{format_tag, stars, wire_segments};
22
23/// The `format` tag of a stored [`PausedDialog`]. Bumped on any change to
24/// its shape; no other version is read.
25pub const PAUSED_DIALOG_FORMAT: &str = "fints-client-paused/4";
26
27format_tag!(
28    /// The format tag of [`PausedDialog`] ([`PAUSED_DIALOG_FORMAT`]).
29    PausedFormat,
30    PAUSED_DIALOG_FORMAT,
31    "paused dialog"
32);
33
34/// A dialog frozen by [`Dialog::freeze`]: everything to continue it except
35/// the transport and the PIN. Self-contained: it carries the dialog's own
36/// BPD and UPD (also a UPD valid for this dialog only, which no
37/// [`SessionState`] keeps) and TAN selection.
38///
39/// `Debug` shows no user ID, system ID, dialog ID, UPD or challenge.
40#[derive(Clone, Serialize, Deserialize)]
41#[serde(deny_unknown_fields)]
42pub struct PausedDialog {
43    format: PausedFormat,
44    /// Checked against the client on thaw.
45    blz: Blz,
46    url: String,
47    /// Checked against the credentials on thaw.
48    user_id: UserId,
49    system_id: SystemId,
50    dialog_id: DialogId,
51    /// The number the next message carries.
52    message_number: u16,
53    params: StoredParams,
54    /// The bank profile's HKTAN overrides at open; profile changes apply
55    /// to new dialogs only.
56    tan_overrides: TanOverrides,
57    /// The job waiting for a TAN; `None` for a dialog frozen while open.
58    pending: Option<PendingJob>,
59    /// Wall clock of the bank's last response.
60    last_message_at: Timestamp,
61}
62
63/// The dialog's [`BankParams`] as data: the raw BPD and UPD as the bank
64/// sent them, and the state the dialog added to them.
65#[derive(Clone, Serialize, Deserialize)]
66#[serde(deny_unknown_fields)]
67struct StoredParams {
68    bpd_version: u16,
69    upd_version: u16,
70    #[serde(with = "wire_segments")]
71    bpd: Vec<RawSegment>,
72    #[serde(with = "wire_segments")]
73    upd: Vec<RawSegment>,
74    selected_security_function: SecurityFunction,
75    preferred_security_function: Option<SecurityFunction>,
76    selected_tan_medium: Option<TanMediumName>,
77    allowed_security_functions: Vec<SecurityFunction>,
78    changed_user_id: Option<UserId>,
79    tan_required_learned: Vec<SegmentType>,
80}
81
82impl StoredParams {
83    fn new(p: &BankParams) -> Self {
84        Self {
85            bpd_version: p.bpd_version,
86            upd_version: p.upd_version,
87            bpd: p.bpd_segments.clone(),
88            upd: p.upd_segments.clone(),
89            selected_security_function: p.selected_security_function.clone(),
90            preferred_security_function: p.preferred_security_function.clone(),
91            selected_tan_medium: p.selected_tan_medium.clone(),
92            allowed_security_functions: p.allowed_security_functions.clone(),
93            changed_user_id: p.changed_user_id.clone(),
94            tan_required_learned: p.tan_required_learned.iter().cloned().collect(),
95        }
96    }
97
98    fn to_params(&self) -> BankParams {
99        let mut p = BankParams::new();
100        p.set_bpd(self.bpd.clone());
101        p.set_upd(self.upd.clone());
102        p.bpd_version = self.bpd_version;
103        p.upd_version = self.upd_version;
104        p.selected_security_function = self.selected_security_function.clone();
105        p.preferred_security_function = self.preferred_security_function.clone();
106        p.selected_tan_medium = self.selected_tan_medium.clone();
107        p.allowed_security_functions = self.allowed_security_functions.clone();
108        p.changed_user_id = self.changed_user_id.clone();
109        p.tan_required_learned = self.tan_required_learned.iter().cloned().collect();
110        p
111    }
112}
113
114/// The typed ticket of a paused job, rebuilt from a [`PausedDialog`] (one
115/// variant per job), so a restarted caller can resume it.
116#[derive(Debug)]
117pub enum AnyResume {
118    Open(Resume<Opened>),
119    Balance(Resume<Option<AccountBalance>>),
120    Transactions(Resume<Statement>),
121    Holdings(Resume<Vec<SecurityHolding>>),
122    DepotTransactions(Resume<Vec<DepotTransaction>>),
123    Transfer(Resume<TransferReceipt>),
124    InstantStatus(Resume<InstantStatus>),
125}
126
127/// Which job a paused step belongs to ([`AnyResume::kind`]).
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129pub enum ResumeKind {
130    Open,
131    Balance,
132    Transactions,
133    Holdings,
134    DepotTransactions,
135    Transfer,
136    InstantStatus,
137}
138
139impl AnyResume {
140    /// The job this ticket resumes, to label or log it without matching
141    /// every variant.
142    pub fn kind(&self) -> ResumeKind {
143        match self {
144            Self::Open(_) => ResumeKind::Open,
145            Self::Balance(_) => ResumeKind::Balance,
146            Self::Transactions(_) => ResumeKind::Transactions,
147            Self::Holdings(_) => ResumeKind::Holdings,
148            Self::DepotTransactions(_) => ResumeKind::DepotTransactions,
149            Self::Transfer(_) => ResumeKind::Transfer,
150            Self::InstantStatus(_) => ResumeKind::InstantStatus,
151        }
152    }
153
154    fn of(pending: &PendingJob) -> Self {
155        fn ticket<T>(pending: &PendingJob) -> Resume<T> {
156            Resume {
157                ticket: pending.ticket.clone(),
158                _value: PhantomData,
159            }
160        }
161        match pending.job.job() {
162            Job::Open => Self::Open(ticket(pending)),
163            Job::Balance => Self::Balance(ticket(pending)),
164            Job::Transactions => Self::Transactions(ticket(pending)),
165            Job::Holdings => Self::Holdings(ticket(pending)),
166            Job::DepotTransactions => Self::DepotTransactions(ticket(pending)),
167            Job::Transfer => Self::Transfer(ticket(pending)),
168            Job::InstantStatus => Self::InstantStatus(ticket(pending)),
169        }
170    }
171}
172
173impl PausedDialog {
174    /// The ticket of the paused job; `None` for a dialog frozen while open.
175    /// Take it before [`Dialog::thaw`], which consumes the value.
176    pub fn pending(&self) -> Option<AnyResume> {
177        self.pending.as_ref().map(AnyResume::of)
178    }
179
180    /// The TAN challenge the paused job waits on, to show without thawing;
181    /// `None` while a transfer waits on its payee check.
182    pub fn challenge(&self) -> Option<&TanChallenge> {
183        self.pending.as_ref().and_then(PendingJob::challenge)
184    }
185
186    /// The payee check result a paused transfer waits to have confirmed,
187    /// to show without thawing.
188    pub fn vop(&self) -> Option<&VopConfirmation> {
189        self.pending.as_ref().and_then(PendingJob::vop)
190    }
191
192    /// The bank the dialog belongs to.
193    pub fn blz(&self) -> &Blz {
194        &self.blz
195    }
196
197    /// Wall clock of the bank's last response.
198    pub fn last_message_at(&self) -> Timestamp {
199        self.last_message_at
200    }
201
202    /// When the bank's timeout ends the dialog, if it announced one:
203    /// `last_message_at` plus the BPD's maximum timeout (HIBPA "Maximaler
204    /// Timeout-Wert", seconds; absent or 0 = no limit). Only our own clock
205    /// goes into it. The challenge's validity (HITAN "Gültigkeitsdatum und
206    /// -uhrzeit für Challenge") is a bank-local wall-clock value without a
207    /// zone; it stays readable on the challenge itself as a civil
208    /// [`DateTime`]. `None`: no timeout announced. Informational:
209    /// [`Dialog::thaw`] never refuses on time, and the bank may end a
210    /// dialog earlier.
211    pub fn expires_at(&self) -> Option<Timestamp> {
212        let secs = Bpd::from_segments(&self.params.bpd)
213            .ok()
214            .and_then(|b| b.max_timeout)
215            .filter(|s| *s > 0)?;
216        self.last_message_at
217            .checked_add(jiff::SignedDuration::from_secs(i64::from(secs)))
218            .ok()
219    }
220
221    /// Serialize to JSON.
222    pub fn to_json(&self) -> Result<String> {
223        serde_json::to_string(self)
224            .map_err(|e| FinTSError::Serialize(format!("paused dialog: {e}")))
225    }
226
227    /// Deserialize from JSON produced by [`PausedDialog::to_json`]. Any
228    /// other format tag fails with [`FinTSError::StateFormat`].
229    pub fn from_json(json: &str) -> Result<Self> {
230        crate::session::check_format(json, PAUSED_DIALOG_FORMAT)?;
231        serde_json::from_str(json).map_err(|e| FinTSError::Parse(format!("paused dialog: {e}")))
232    }
233}
234
235impl std::fmt::Debug for PausedDialog {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        f.debug_struct("PausedDialog")
238            .field("blz", &self.blz)
239            .field("user_id", &stars(self.user_id.as_str()))
240            .field("system_id", &stars(self.system_id.as_str()))
241            .field("dialog_id", &stars(self.dialog_id.as_str()))
242            .field("message_number", &self.message_number)
243            .field("bpd_version", &self.params.bpd_version)
244            .field("upd_version", &self.params.upd_version)
245            .field("bpd_segments", &self.params.bpd.len())
246            .field("upd_segments", &self.params.upd.len())
247            .field(
248                "phase",
249                &if self.pending.is_some() {
250                    "Paused"
251                } else {
252                    "Open"
253                },
254            )
255            .field("pending_job", &self.pending.as_ref().map(|p| p.job.job()))
256            .field("last_message_at", &self.last_message_at)
257            .finish()
258    }
259}
260
261impl Dialog {
262    /// Freeze the dialog into plain data to store, for an open dialog
263    /// between two jobs and for one paused on a TAN. Sends nothing;
264    /// consumes the dialog, so no live copy can send the same message
265    /// number. An ended dialog fails with [`FinTSError::DialogEnded`]; one
266    /// whose transfer request was dropped mid-flight with
267    /// [`FinTSError::PaymentOutcomeUnknown`].
268    pub fn freeze(mut self) -> Result<PausedDialog> {
269        self.check_in_flight()?;
270        let pending = match self.phase {
271            Phase::Ended => return Err(FinTSError::DialogEnded),
272            Phase::Open => None,
273            Phase::Paused(p) => Some(*p),
274        };
275        let inner = &self.inner;
276        Ok(PausedDialog {
277            format: PausedFormat,
278            blz: inner.blz().clone(),
279            url: inner.url().to_string(),
280            user_id: inner.user_id().clone(),
281            system_id: inner.system_id().clone(),
282            dialog_id: inner.dialog_id().clone(),
283            message_number: inner.message_number(),
284            params: StoredParams::new(inner.bank_params()),
285            tan_overrides: inner.tan_overrides().clone(),
286            pending,
287            last_message_at: self.last_message_at,
288        })
289    }
290
291    /// Continue a frozen dialog through `client` with the PIN of `creds`.
292    /// Fails with [`FinTSError::PausedDialogMismatch`] when the client's
293    /// BLZ or URL, or the user ID, differ from the frozen dialog's; sends
294    /// nothing. The thawed dialog is paused on the same job (resume it with
295    /// the ticket of [`PausedDialog::pending`]) or open. It never refuses
296    /// on time: a dialog the bank has dropped answers with
297    /// [`FinTSError::DialogEnded`].
298    pub fn thaw(paused: PausedDialog, client: &BankClient, creds: &Credentials) -> Result<Dialog> {
299        let config = client.config();
300        let field = if paused.blz != config.blz {
301            Some("blz")
302        } else if paused.url != config.url.as_str() {
303            Some("url")
304        } else if paused.user_id != client.effective_user_id(&creds.user_id) {
305            Some("user_id")
306        } else {
307            None
308        };
309        if let Some(field) = field {
310            return Err(FinTSError::PausedDialogMismatch { field });
311        }
312        let inner = client
313            .new_dialog(creds)?
314            .with_system_id(&paused.system_id)
315            .with_params(&paused.params.to_params())
316            .with_tan_overrides(paused.tan_overrides)
317            .resume(paused.dialog_id, paused.message_number);
318        Ok(Dialog {
319            inner,
320            bic: client.config().bic.clone(),
321            booking_id: client.config().profile.booking_id,
322            phase: match paused.pending {
323                Some(p) => Phase::Paused(Box::new(p)),
324                None => Phase::Open,
325            },
326            last_message_at: paused.last_message_at,
327            in_flight: None,
328        })
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use crate::codec::wire;
336
337    const BPD: &str = "HIBPA:6:3:4+78+280:12345678+Test Bank+1+1+300+500+10+300'\
338        HITANS:53:5:4+1+1+1+N:N:0:942:2:MTAN2:mobileTAN::mobile TAN:6:1:SMS:3:1:J:1:0:N:0:2:N:J:00:1:1'\
339        HIPINS:54:1:4+1+1+1+5:20:6:Benutzer ID::HKKAZ:N:HKSAL:N:HKTAN:N'";
340    const UPD: &str = "HIUPA:57:4:4+test1+0+0'\
341        HIUPD:58:6:4+1::280:12345678+DE111234567800000001+test1++EUR+Fullname++Girokonto++HKSAL:1'";
342
343    #[test]
344    fn any_resume_kind() {
345        let p = sample(None);
346        assert_eq!(p.pending().unwrap().kind(), ResumeKind::Balance);
347    }
348
349    fn sample(valid_until: Option<DateTime>) -> PausedDialog {
350        let mut p = BankParams::new();
351        p.set_bpd(wire::tokenize(BPD.as_bytes()).unwrap());
352        p.set_upd(wire::tokenize(UPD.as_bytes()).unwrap());
353        p.allowed_security_functions = vec![SecurityFunction::new("942")];
354        p.select_security_function();
355        PausedDialog {
356            format: PausedFormat,
357            blz: Blz::new("12345678"),
358            url: "https://bank.example/fints".into(),
359            user_id: UserId::new("test1"),
360            system_id: SystemId::new("SYS;001"),
361            dialog_id: DialogId::new("DLG4711"),
362            message_number: 4,
363            params: StoredParams::new(&p),
364            tan_overrides: TanOverrides::default(),
365            pending: Some(PendingJob {
366                ticket: Ticket::Task(TaskReference::new("TASK0001")),
367                wait: Wait::Tan(TanChallenge {
368                    challenge: ChallengeText::new("Ueberweisung an Beispiel 12,00"),
369                    challenge_markup: false,
370                    kind: TanKind::Typed { media: None },
371                    valid_until,
372                    not_before: None,
373                    payee_check: None,
374                    rejected: None,
375                }),
376                job: JobInput::Balance {
377                    account: Account::new("DE02120300000000202051", "BYLADEM1001").unwrap(),
378                },
379                notices: Vec::new(),
380            }),
381            last_message_at: Timestamp::constant(1_768_471_200, 0),
382        }
383    }
384
385    /// The dialog-only UPD (version 0) survives, unlike in `SessionState`.
386    #[test]
387    fn round_trips_through_json_with_a_dialog_only_upd() {
388        let paused = sample(None);
389        let json = paused.to_json().unwrap();
390        assert!(json.contains("\"format\":\"fints-client-paused/4\""));
391        let back = PausedDialog::from_json(&json).unwrap();
392        assert_eq!(back.to_json().unwrap(), json);
393        let p = back.params.to_params();
394        assert!(p.upd().unwrap().is_dialog_only());
395        assert_eq!(p.upd().unwrap().accounts().len(), 1);
396        assert_eq!(p.selected_security_function, SecurityFunction::new("942"));
397        assert!(matches!(back.pending(), Some(AnyResume::Balance(_))));
398    }
399
400    #[test]
401    fn other_formats_and_unknown_fields_are_rejected() {
402        let json = sample(None).to_json().unwrap();
403        for other in [
404            "fints-client-paused/3",
405            "fints-client-paused/5",
406            "fints-client-session/1",
407        ] {
408            match PausedDialog::from_json(&json.replace(PAUSED_DIALOG_FORMAT, other)) {
409                Err(FinTSError::StateFormat { found, expected }) => {
410                    assert_eq!((found.as_str(), expected), (other, PAUSED_DIALOG_FORMAT));
411                }
412                r => panic!("{other}: {r:?}"),
413            }
414        }
415        let bad = json.replace(PAUSED_DIALOG_FORMAT, "fints-client-paused/5");
416        assert!(serde_json::from_str::<PausedDialog>(&bad).is_err());
417        let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
418        v["extra"] = serde_json::json!(1);
419        assert!(matches!(
420            PausedDialog::from_json(&v.to_string()),
421            Err(FinTSError::Parse(_))
422        ));
423        v.as_object_mut().unwrap().remove("extra");
424        v.as_object_mut().unwrap().remove("format");
425        assert!(matches!(
426            PausedDialog::from_json(&v.to_string()),
427            Err(FinTSError::StateFormat { .. })
428        ));
429    }
430
431    #[test]
432    fn debug_hides_identifiers_upd_and_challenge() {
433        let out = format!("{:?}", sample(None));
434        for secret in [
435            "test1", "SYS;001", "DLG4711", "DE11", "DE02", "Fullname", "Beispiel", "TASK",
436        ] {
437            assert!(!out.contains(secret), "{secret} in {out}");
438        }
439        assert!(out.contains("12345678") && out.contains("Paused"), "{out}");
440    }
441
442    /// HIBPA maximum timeout 300 s from our own clock; the challenge
443    /// validity does not enter.
444    #[test]
445    fn expires_at_from_the_banks_limits() {
446        let paused = sample(None);
447        assert_eq!(
448            paused.expires_at(),
449            Some(Timestamp::constant(1_768_471_200 + 300, 0))
450        );
451        let valid_until = Date::new(2026, 1, 15).unwrap().at(10, 2, 0, 0);
452        assert_eq!(
453            sample(Some(valid_until)).expires_at(),
454            paused.expires_at(),
455            "challenge validity is not part of it"
456        );
457
458        let mut none = sample(None);
459        let bpd = BPD.replace("+10+300'", "+10+0'");
460        none.params.bpd = wire::tokenize(bpd.as_bytes()).unwrap();
461        assert_eq!(none.expires_at(), None, "0 = no limit");
462        none.params.bpd = wire::tokenize(BPD.replace("+500+10+300'", "'").as_bytes()).unwrap();
463        assert_eq!(none.expires_at(), None, "absent = no limit");
464    }
465}