Skip to main content

fints_client/
session.rs

1//! The state a client keeps between runs.
2//!
3//! Formals has the customer system keep what the bank handed out: the
4//! system ID from synchronisation, and the bank and user parameter data
5//! (BPD, UPD) with their version numbers. HKVVB names the versions the
6//! client holds, and the bank sends parameter data again only when its own
7//! version is newer. [`SessionState`] is all of that in one value the
8//! caller stores; the library writes no files.
9//!
10//! Keep the system ID: banks tie strong customer authentication
11//! exemptions to it, and a client that comes back with a new ID every run
12//! gets asked for TANs more often. Store the state after each run and hand
13//! it back the next time.
14//!
15//! The state holds neither PIN nor TAN, but it names the user and the
16//! accounts. Keep it encrypted.
17
18use jiff::Timestamp;
19use serde::{Deserialize, Serialize};
20
21use crate::codec::{RawSegment, wire};
22use crate::error::{FinTSError, Result};
23use crate::protocol::{BankParams, Bpd, Upd};
24use crate::types::*;
25
26/// The `format` tag of a stored [`SessionState`]. Bumped on any change to
27/// its shape; no other version is read.
28pub const SESSION_STATE_FORMAT: &str = "fints-client-session/2";
29
30/// A format tag as a value: serialises as its string and deserialises only
31/// from exactly that string, so the check holds in every serde format, not
32/// only in `from_json`.
33macro_rules! format_tag {
34    ($(#[$meta:meta])* $name:ident, $tag:expr, $what:literal) => {
35        $(#[$meta])*
36        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37        pub struct $name;
38
39        impl serde::Serialize for $name {
40            fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
41                s.serialize_str($tag)
42            }
43        }
44
45        impl<'de> serde::Deserialize<'de> for $name {
46            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
47                let found = String::deserialize(d)?;
48                if found == $tag {
49                    Ok(Self)
50                } else {
51                    Err(serde::de::Error::custom(format!(
52                        concat!($what, " format {:?}; this version reads {:?}"),
53                        found, $tag
54                    )))
55                }
56            }
57        }
58    };
59}
60pub(crate) use format_tag;
61
62format_tag!(
63    /// The format tag of [`SessionState`] ([`SESSION_STATE_FORMAT`]).
64    SessionFormat,
65    SESSION_STATE_FORMAT,
66    "session state"
67);
68
69/// Fail with [`FinTSError::StateFormat`] when `json` is an object whose
70/// `format` is not `expected` (or missing). Anything else is left to the
71/// full parse.
72pub(crate) fn check_format(json: &str, expected: &'static str) -> Result<()> {
73    #[derive(Deserialize)]
74    struct Tag {
75        format: Option<String>,
76    }
77    if let Ok(Tag { format }) = serde_json::from_str(json) {
78        let found = format.unwrap_or_default();
79        if found != expected {
80            return Err(FinTSError::StateFormat { found, expected });
81        }
82    }
83    Ok(())
84}
85
86/// What one user's dialogs with one bank leave behind for the next run.
87///
88/// Store the state that `Dialog::end` or `jobs::synchronise` returns after
89/// every dialog and pass it to the next `jobs::open`. With it, the next
90/// dialog skips the sync dialog, announces the cached BPD/UPD versions so
91/// the bank sends nothing it has already sent, and keeps the system ID the
92/// bank knows. A lost state gets a new system ID, and a bank that granted
93/// an SCA exemption (3076) to the old one may ask for a login TAN again.
94///
95/// `Debug` hides user ID, system ID and the UPD content.
96#[derive(Clone, Serialize, Deserialize)]
97#[serde(deny_unknown_fields)]
98pub struct SessionState {
99    /// Checked on every read; see [`SESSION_STATE_FORMAT`].
100    format: SessionFormat,
101    /// The bank code.
102    pub blz: Blz,
103    /// The login. When the bank announces a new one (return code 3072) it
104    /// replaces the old one here.
105    pub user_id: UserId,
106    /// The customer system ID from HISYN; `0` until the bank gave one.
107    pub system_id: SystemId,
108    /// The BPD version HKVVB announces; `0` asks for the BPD.
109    pub bpd_version: u16,
110    /// The UPD version HKVVB announces; `0` asks for the UPD.
111    pub upd_version: u16,
112    /// The BPD segments, kept in their wire form, byte for byte.
113    #[serde(with = "wire_segments")]
114    bpd: Vec<RawSegment>,
115    /// The UPD segments, kept in their wire form, byte for byte.
116    #[serde(with = "wire_segments")]
117    upd: Vec<RawSegment>,
118    /// The security function (TAN method) the user prefers, such as `902`.
119    pub tan_method: Option<SecurityFunction>,
120    /// The TAN medium (device) to name for methods that need one.
121    pub tan_medium: Option<TanMediumName>,
122    /// The security functions of the bank's last return code 3920.
123    pub allowed_security_functions: Vec<SecurityFunction>,
124    /// The login used before the bank's last 3072, so the caller can update
125    /// what it stores; `user_id` already holds the new one.
126    pub previous_user_id: Option<UserId>,
127    /// Order codes (e.g. `HKSAL`) for which the bank answered 9075 without
128    /// HKTAN; the library sends HKTAN with them at once. Dropped by `reset`.
129    pub tan_required_learned: Vec<SegmentType>,
130    /// When the state was written.
131    pub updated_at: Timestamp,
132}
133
134/// `0` for a segment list that is empty, so that the bank sends it again.
135fn version_if_present(segments: &[RawSegment], version: u16) -> u16 {
136    if segments.is_empty() { 0 } else { version }
137}
138
139impl SessionState {
140    /// The state before the first dialog: nothing known.
141    pub fn new(blz: &Blz, user_id: &UserId) -> Self {
142        Self::fresh(blz.clone(), user_id.clone(), SystemId::unassigned())
143    }
144
145    fn fresh(blz: Blz, user_id: UserId, system_id: SystemId) -> Self {
146        Self {
147            format: SessionFormat,
148            blz,
149            user_id,
150            system_id,
151            bpd_version: 0,
152            upd_version: 0,
153            bpd: Vec::new(),
154            upd: Vec::new(),
155            tan_method: None,
156            tan_medium: None,
157            allowed_security_functions: Vec::new(),
158            previous_user_id: None,
159            tan_required_learned: Vec::new(),
160            updated_at: Timestamp::now(),
161        }
162    }
163
164    /// Start from a known system ID. The host stores the ID itself, so a
165    /// state format change keeps the bank's device entry: the new state has
166    /// no BPD or UPD (one parameter dialog fetches them) but no new sync
167    /// dialog either.
168    pub fn with_system_id(self, system_id: &SystemId) -> Self {
169        Self {
170            system_id: system_id.clone(),
171            ..self
172        }
173    }
174
175    /// Ask for this security function whenever the bank offers it.
176    pub fn with_tan_method(self, security_function: &SecurityFunction) -> Self {
177        Self {
178            tan_method: Some(security_function.clone()),
179            ..self
180        }
181    }
182
183    /// Name this device to methods that ask for a TAN medium.
184    pub fn with_tan_medium(self, medium: &TanMediumName) -> Self {
185        Self {
186            tan_medium: Some(medium.clone()),
187            ..self
188        }
189    }
190
191    /// Whether the next dialog can go straight to business: the bank gave a
192    /// system ID and the BPD (with the TAN methods) is cached.
193    pub fn can_skip_sync(&self) -> bool {
194        let has_bpd = !self.bpd.is_empty() && self.bpd_version != 0;
195        has_bpd && self.system_id.is_assigned()
196    }
197
198    /// The TAN methods of the cached BPD.
199    pub fn tan_methods(&self) -> Vec<TanMethod> {
200        self.to_params().tan_methods
201    }
202
203    /// The cached BPD as a typed model, rebuilt from the stored segments.
204    /// `None` when no readable BPD is stored.
205    #[cfg(feature = "tooling")]
206    pub fn bpd(&self) -> Option<Bpd> {
207        Bpd::from_segments(&self.bpd).ok()
208    }
209
210    #[cfg(not(feature = "tooling"))]
211    #[allow(dead_code)]
212    pub(crate) fn bpd(&self) -> Option<Bpd> {
213        Bpd::from_segments(&self.bpd).ok()
214    }
215
216    /// The cached UPD as a typed model, rebuilt from the stored segments.
217    /// `None` when no UPD is stored, which includes banks that send it for
218    /// one dialog only (UPD version 0): the next dialog asks for it again.
219    #[cfg(feature = "tooling")]
220    pub fn upd(&self) -> Option<Upd> {
221        Upd::from_segments(&self.upd).ok()
222    }
223
224    #[cfg(not(feature = "tooling"))]
225    pub(crate) fn upd(&self) -> Option<Upd> {
226        Upd::from_segments(&self.upd).ok()
227    }
228
229    /// What the bank offers per account (`accounts`, or the cached UPD's
230    /// accounts when empty), from the cached BPD and UPD and the learned
231    /// TAN codes; sends nothing. Without a stored UPD (none yet, or a bank
232    /// that sends it for one dialog only, see `SessionState::upd`) pass
233    /// the accounts; every UPD allowance is then `Unknown`, and
234    /// [`Dialog::capabilities`](crate::jobs::Dialog::capabilities) knows the
235    /// dialog's UPD. TAN overrides of the client config are not applied here.
236    pub fn capabilities(&self, accounts: &[crate::Account]) -> crate::jobs::Capabilities {
237        crate::jobs::Capabilities::build(
238            &self.to_params(),
239            &crate::protocol::TanOverrides::default(),
240            accounts,
241        )
242    }
243
244    /// Accounts listed in the cached UPD (none when the bank sends the UPD
245    /// for one dialog only, see `SessionState::upd`), as
246    /// [`Opened::accounts`](crate::jobs::Opened::accounts) lists them;
247    /// `bank_bic` fills in the BIC the UPD does not give.
248    pub fn accounts(&self, bank_bic: &Bic) -> Vec<crate::jobs::AccountInfo> {
249        self.upd()
250            .map(|u| crate::jobs::AccountInfo::from_upd(&u, bank_bic))
251            .unwrap_or_default()
252    }
253
254    /// Forget everything the bank sent, for instance when it no longer
255    /// accepts the system ID (9391); the next run synchronises again. Bank,
256    /// login and the user's TAN choice stay.
257    pub fn reset(&mut self) {
258        let mut fresh = Self::fresh(
259            self.blz.clone(),
260            self.user_id.clone(),
261            SystemId::unassigned(),
262        );
263        fresh.tan_method = self.tan_method.take();
264        fresh.tan_medium = self.tan_medium.take();
265        *self = fresh;
266    }
267
268    /// The state as JSON, for the caller to store.
269    pub fn to_json(&self) -> Result<String> {
270        serde_json::to_string(self)
271            .map_err(|e| FinTSError::Serialize(format!("session state: {e}")))
272    }
273
274    /// Deserialize from JSON produced by [`SessionState::to_json`]. Any
275    /// other format tag, older or newer, fails with
276    /// [`FinTSError::StateFormat`]; there is no migration.
277    pub fn from_json(json: &str) -> Result<Self> {
278        check_format(json, SESSION_STATE_FORMAT)?;
279        serde_json::from_str(json).map_err(|e| FinTSError::Parse(format!("session state: {e}")))
280    }
281
282    /// The parameters a dialog starts with.
283    pub(crate) fn to_params(&self) -> BankParams {
284        let mut params = BankParams::new();
285        params.set_bpd(self.bpd.clone());
286        params.set_upd(self.upd.clone());
287        // Announce the stored version only together with the stored data;
288        // without the data, version 0 makes the bank send it again.
289        params.bpd_version = version_if_present(&self.bpd, self.bpd_version);
290        params.upd_version = version_if_present(&self.upd, self.upd_version);
291        params.allowed_security_functions = self.allowed_security_functions.clone();
292        params.tan_required_learned = self.tan_required_learned.iter().cloned().collect();
293        params.preferred_security_function = self.tan_method.clone();
294        params.selected_tan_medium = self.tan_medium.clone();
295        params.select_security_function();
296        params
297    }
298
299    /// The state a finished dialog leaves.
300    pub(crate) fn capture(
301        blz: &Blz,
302        user_id: &UserId,
303        system_id: &SystemId,
304        params: &BankParams,
305    ) -> Self {
306        let mut state = Self::fresh(blz.clone(), user_id.clone(), system_id.clone());
307
308        if let Some(renamed) = params.changed_user_id.as_ref().filter(|id| *id != user_id) {
309            state.previous_user_id = Some(std::mem::replace(&mut state.user_id, renamed.clone()));
310        }
311
312        state.bpd = params.bpd_segments.clone();
313        state.bpd_version = params.bpd_version;
314        // UPD version 0 means "valid in this dialog only" (Formals C.3.2.3);
315        // keeping nothing makes the next dialog ask again.
316        if !params.upd().is_some_and(Upd::is_dialog_only) {
317            state.upd = params.upd_segments.clone();
318            state.upd_version = params.upd_version;
319        }
320
321        let chosen = &params.selected_security_function;
322        if *chosen != SecurityFunction::pin_only() {
323            state.tan_method = Some(chosen.clone());
324        }
325        state.tan_medium = params.selected_tan_medium.clone();
326        state.allowed_security_functions = params.allowed_security_functions.clone();
327        state.tan_required_learned = params.tan_required_learned.iter().cloned().collect();
328        state
329    }
330}
331
332/// One star per character, as `mask` does for identifiers.
333pub(crate) fn stars(s: &str) -> String {
334    "*".repeat(s.chars().count())
335}
336
337impl std::fmt::Debug for SessionState {
338    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        f.debug_struct("SessionState")
340            .field("blz", &self.blz)
341            .field("user_id", &stars(self.user_id.as_str()))
342            .field("system_id", &stars(self.system_id.as_str()))
343            .field("bpd_version", &self.bpd_version)
344            .field("upd_version", &self.upd_version)
345            .field("bpd_segments", &self.bpd.len())
346            .field("upd_segments", &self.upd.len())
347            .field("tan_method", &self.tan_method)
348            .field("tan_medium", &self.tan_medium.as_ref().map(|_| "<set>"))
349            .field(
350                "allowed_security_functions",
351                &self.allowed_security_functions,
352            )
353            .field(
354                "previous_user_id",
355                &self.previous_user_id.as_ref().map(|u| stars(u.as_str())),
356            )
357            .field("tan_required_learned", &self.tan_required_learned)
358            .field("updated_at", &self.updated_at)
359            .finish()
360    }
361}
362
363/// Serialize segments as their FinTS wire form (ISO-8859-1 mapped 1:1 to
364/// chars), which is compact, diffable, and exactly what the bank sent.
365pub(crate) mod wire_segments {
366    use super::*;
367    use serde::{Deserializer, Serializer};
368
369    pub fn serialize<S: Serializer>(
370        segments: &[RawSegment],
371        s: S,
372    ) -> std::result::Result<S::Ok, S::Error> {
373        let out = wire::serialize(segments).map_err(serde::ser::Error::custom)?;
374        s.serialize_str(&out.iter().map(|&b| b as char).collect::<String>())
375    }
376
377    pub fn deserialize<'de, D: Deserializer<'de>>(
378        d: D,
379    ) -> std::result::Result<Vec<RawSegment>, D::Error> {
380        let text = String::deserialize(d)?;
381        let bytes = text
382            .chars()
383            .map(|c| {
384                u8::try_from(u32::from(c))
385                    .map_err(|_| serde::de::Error::custom("non-Latin-1 char in segment data"))
386            })
387            .collect::<std::result::Result<Vec<u8>, _>>()?;
388        wire::tokenize(&bytes).map_err(serde::de::Error::custom)
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    /// Synthetic parameter data in the style of `testbank/`: one decoupled
397    /// method 902, HKSAL and HKKAZ without TAN.
398    const BPD: &str = "HIBPA:5:3:4+12+280:12345678+Testbank+3+1+300'\
399        HISALS:6:7:4+1+1+0'\
400        HITANS:7:7:4+1+1+1+J:N:0:902:2:TEST902:Decoupled:1.0:Test-App:::Freigabe:0:N:1:N:0:0:N:N:00:0:N:0:0:0:0:N:J'\
401        HIPINS:8:1:4+1+1+0+5:20:6:Benutzerkennung:Kunden-ID:HKKAZ:N:HKSAL:N'";
402    const UPD: &str = "HIUPA:9:4:4+kunde7+4+0'\
403        HIUPD:10:6:4+4711::280:12345678+DE00123456780000004711+kunde7++EUR+Erika Muster++Girokonto++HKSAL:1'";
404
405    const BANK: &str = "12345678";
406    const USER: &str = "kunde7";
407    const SYSTEM: &str = "SYS-0042";
408
409    fn segments(text: &str) -> Vec<RawSegment> {
410        wire::tokenize(text.as_bytes()).unwrap()
411    }
412
413    /// Parameters as a dialog leaves them: BPD, UPD, 902 allowed and chosen.
414    fn dialog_params() -> BankParams {
415        let mut params = BankParams::new();
416        params.set_bpd(segments(BPD));
417        params.set_upd(segments(UPD));
418        params.allowed_security_functions = vec![SecurityFunction::new("902")];
419        params.select_security_function();
420        params
421    }
422
423    fn captured(user: &str, params: &BankParams) -> SessionState {
424        SessionState::capture(
425            &Blz::new(BANK),
426            &UserId::new(user),
427            &SystemId::new(SYSTEM),
428            params,
429        )
430    }
431
432    fn sample() -> SessionState {
433        captured(USER, &dialog_params())
434    }
435
436    fn method_902() -> Option<SecurityFunction> {
437        Some(SecurityFunction::new("902"))
438    }
439
440    #[test]
441    fn state_survives_json_and_gives_the_same_parameters() {
442        let state = sample();
443        assert_eq!(state.bpd_version, 12);
444        assert_eq!(state.upd_version, 4);
445        assert_eq!(state.tan_method, method_902());
446        assert!(state.can_skip_sync());
447
448        let json = state.to_json().unwrap();
449        assert!(
450            json.contains("HIBPA:5:3:4+12"),
451            "wire form expected: {json}"
452        );
453
454        let back = SessionState::from_json(&json).unwrap();
455        assert_eq!(back.system_id.as_str(), SYSTEM);
456        let params = back.to_params();
457        assert_eq!(params.bpd_version, 12);
458        assert_eq!(params.upd_version, 4);
459        assert_eq!(params.selected_security_function.as_str(), "902");
460        assert_eq!(params.tan_methods.len(), 1);
461        assert_eq!(params.upd().unwrap().accounts().len(), 1);
462        assert_eq!(params.bpd().unwrap().tan_required("HKKAZ"), Some(false));
463    }
464
465    #[test]
466    fn new_state_asks_for_everything() {
467        let state = SessionState::new(&Blz::new(BANK), &UserId::new(USER));
468        assert!(!state.can_skip_sync());
469        assert!(state.tan_methods().is_empty());
470        let params = state.to_params();
471        assert_eq!(params.bpd_version, 0);
472        assert_eq!(params.upd_version, 0);
473    }
474
475    /// Formals C.3.2.3: a UPD of version 0 holds for the dialog that
476    /// received it. The dialog sees the accounts; the state forgets them.
477    #[test]
478    fn upd_version_zero_is_not_kept() {
479        let mut params = dialog_params();
480        params.set_upd(segments(&UPD.replace("+kunde7+4+0'", "+kunde7+0+0'")));
481        let upd = params.upd().unwrap();
482        assert!(upd.is_dialog_only());
483        assert_eq!(upd.accounts().len(), 1);
484
485        let state = captured(USER, &params);
486        assert_eq!(state.upd_version, 0);
487        assert!(state.upd().is_none());
488        assert!(state.accounts(&Bic::new("TESTDEFFXXX")).is_empty());
489        assert_eq!(state.to_params().upd_version, 0);
490        // The BPD is not affected.
491        assert_eq!(state.bpd().unwrap().version, 12);
492    }
493
494    #[test]
495    fn new_user_id_from_the_bank_replaces_the_old_one() {
496        let mut params = dialog_params();
497        params.changed_user_id = Some(UserId::new("kunde8"));
498        let state = captured(USER, &params);
499        assert_eq!(state.user_id.as_str(), "kunde8");
500        assert_eq!(state.previous_user_id, Some(UserId::new(USER)));
501
502        // Reporting the ID that is already in use changes nothing.
503        params.changed_user_id = Some(UserId::new(USER));
504        let state = captured(USER, &params);
505        assert_eq!(state.user_id.as_str(), USER);
506        assert_eq!(state.previous_user_id, None);
507    }
508
509    #[test]
510    fn learned_tan_requirements_are_kept_until_reset() {
511        let mut params = dialog_params();
512        let hksal = SegmentType::new("HKSAL");
513        params.tan_required_learned.insert(hksal.clone());
514        let mut state = captured(USER, &params);
515
516        let back = SessionState::from_json(&state.to_json().unwrap()).unwrap();
517        assert_eq!(back.tan_required_learned, std::slice::from_ref(&hksal));
518        assert!(back.to_params().tan_required_learned.contains(&hksal));
519
520        state.reset();
521        assert!(state.tan_required_learned.is_empty());
522    }
523
524    #[test]
525    fn reset_forgets_the_bank_data_but_not_the_tan_choice() {
526        let device = TanMediumName::new("Test-Phone");
527        let mut state = sample().with_tan_medium(&device);
528        state.reset();
529        assert_eq!(state.system_id, SystemId::unassigned());
530        assert!(state.bpd().is_none());
531        assert!(!state.can_skip_sync());
532        assert_eq!(state.tan_method, method_902());
533        assert_eq!(state.tan_medium, Some(device));
534        assert_eq!(state.user_id.as_str(), USER);
535    }
536
537    #[test]
538    fn builders_set_what_they_name() {
539        let state = SessionState::new(&Blz::new(BANK), &UserId::new(USER))
540            .with_system_id(&SystemId::new(SYSTEM))
541            .with_tan_method(&SecurityFunction::new("902"));
542        assert!(state.system_id.is_assigned());
543        assert_eq!(state.tan_method, method_902());
544        // A system ID alone is not enough: the BPD is still missing.
545        assert!(!state.can_skip_sync());
546    }
547
548    /// Bytes 0x80 to 0x9F are control characters in ISO 8859-1
549    /// (codec::wire); the stored BPD still gives back the exact bytes.
550    #[test]
551    fn stored_bpd_keeps_every_byte() {
552        let mut bytes = BPD.as_bytes().to_vec();
553        let at = bytes.windows(8).position(|w| w == b"Testbank").unwrap();
554        bytes[at] = 0x85;
555        let mut params = BankParams::new();
556        params.set_bpd(wire::tokenize(&bytes).unwrap());
557        let state = captured(USER, &params);
558        let back = SessionState::from_json(&state.to_json().unwrap()).unwrap();
559        assert_eq!(wire::serialize(&back.bpd).unwrap(), bytes);
560    }
561
562    #[test]
563    fn json_carries_the_format_tag_and_round_trips() {
564        let json = sample().to_json().unwrap();
565        assert!(json.contains("\"format\":\"fints-client-session/2\""));
566        let back = SessionState::from_json(&json).unwrap();
567        assert_eq!(back.to_json().unwrap(), json);
568    }
569
570    #[test]
571    fn other_formats_are_rejected_with_state_format() {
572        let json = sample().to_json().unwrap();
573        for other in [
574            "fints-client-session/1",
575            "fints-client-session/3",
576            "fints-client-trace/3",
577        ] {
578            let bad = json.replace(SESSION_STATE_FORMAT, other);
579            match SessionState::from_json(&bad) {
580                Err(FinTSError::StateFormat { found, expected }) => {
581                    assert_eq!((found.as_str(), expected), (other, SESSION_STATE_FORMAT));
582                }
583                r => panic!("{other}: {r:?}"),
584            }
585        }
586        let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
587        v["format"] = serde_json::json!(1);
588        assert!(SessionState::from_json(&v.to_string()).is_err());
589        v.as_object_mut().unwrap().remove("format");
590        assert!(matches!(
591            SessionState::from_json(&v.to_string()),
592            Err(FinTSError::StateFormat { .. })
593        ));
594        let err = FinTSError::StateFormat {
595            found: String::new(),
596            expected: SESSION_STATE_FORMAT,
597        };
598        assert_eq!(err.kind(), crate::return_code::Category::ClientFault);
599    }
600
601    #[test]
602    fn tag_check_holds_outside_from_json() {
603        let bad = sample()
604            .to_json()
605            .unwrap()
606            .replace(SESSION_STATE_FORMAT, "fints-client-session/3");
607        assert!(serde_json::from_str::<SessionState>(&bad).is_err());
608    }
609
610    #[test]
611    fn unknown_and_missing_fields_are_rejected() {
612        let json = sample().to_json().unwrap();
613        let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
614        v["extra"] = serde_json::json!(1);
615        assert!(matches!(
616            SessionState::from_json(&v.to_string()),
617            Err(FinTSError::Parse(_))
618        ));
619        let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
620        v.as_object_mut().unwrap().remove("tan_required_learned");
621        assert!(matches!(
622            SessionState::from_json(&v.to_string()),
623            Err(FinTSError::Parse(_))
624        ));
625    }
626
627    #[test]
628    fn debug_hides_user_id_system_id_and_upd() {
629        let mut state = sample();
630        state.previous_user_id = Some(UserId::new("altkunde3"));
631        let out = format!("{state:?}");
632        for secret in [USER, SYSTEM, "altkunde3", "DE00", "Erika", "HIUPD"] {
633            assert!(!out.contains(secret), "{secret} in {out}");
634        }
635        assert!(out.contains(BANK) && out.contains("upd_segments"));
636    }
637}