fints-client 0.1.0

FinTS 3.0 PIN/TAN client for German online banking: accounts, balances, transactions, holdings, SEPA transfers and the payee check
Documentation
//! Bank directory: known German banks with their FinTS endpoint URLs and
//! bank profiles.
//!
//! Banks are identified solely by their BLZ (Bankleitzahl). The bank
//! directory (`data/fints_institutes.csv`, generated by `build.rs`) gives
//! name, BIC and URL per BLZ; the profile table ([`BankProfile`]) gives what
//! the bank does differently, generic for banks without an entry.
//!
//! Selection: [`bank_by_blz`] and [`all_banks`] take the directory entry and
//! the profile from `table.rs`, found by an explicit BLZ list (never by URL
//! or range); [`profile_by_blz`] gives the profile alone, generic for a code
//! without an entry. `BankConfig::with_url` keeps the profile. A profile
//! holds `id`, `init`, `tan_overrides`, `user_id` and `booking_id`; BIC
//! fill, KTI form, account class and UPD storage are generic and come from
//! the parameters.

mod profile;
mod table;

/// One row of the bank directory that `build.rs` writes from
/// `data/fints_institutes.csv`.
struct DirectoryEntry {
    blz: &'static str,
    bic: &'static str,
    name: &'static str,
    url: &'static str,
}

impl DirectoryEntry {
    fn config(&self) -> BankConfig {
        BankConfig::new(self.name, self.blz, self.bic, self.url)
    }
}

// `DIRECTORY`: every PIN/TAN bank, sorted by bank code.
include!(concat!(env!("OUT_DIR"), "/bank_directory.rs"));

/// Directory row for a bank code.
fn directory_entry(blz: &str) -> Option<&'static DirectoryEntry> {
    let at = DIRECTORY.binary_search_by(|e| e.blz.cmp(blz)).ok()?;
    Some(&DIRECTORY[at])
}

use serde::{Deserialize, Serialize};

pub use profile::{BankProfile, BookingIdSource, InitMode, ProfileId, UserIdRule};

use crate::protocol::TanOverride;
use crate::types::{BankName, Bic, Blz, FinTSUrl};

/// Configuration for a known bank.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankConfig {
    pub name: BankName,
    pub blz: Blz,
    pub bic: Bic,
    pub url: FinTSUrl,
    /// What this bank does differently; generic for most banks.
    pub profile: BankProfile,
}

impl BankConfig {
    /// A bank with the generic profile. For a bank in the directory use
    /// [`bank_by_blz`] (and [`BankConfig::with_url`] for another endpoint),
    /// which keeps the bank's profile.
    pub fn new(
        name: impl Into<String>,
        blz: impl Into<String>,
        bic: impl Into<String>,
        url: impl Into<String>,
    ) -> Self {
        let profile = BankProfile::generic();
        let (name, blz) = (BankName::new(name), Blz::new(blz));
        let (bic, url) = (Bic::new(bic), FinTSUrl::new(url));
        Self {
            name,
            blz,
            bic,
            url,
            profile,
        }
    }

    /// The same bank at another endpoint (a recording proxy, a replay, a
    /// test server); the profile stays.
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = FinTSUrl::new(url);
        self
    }

    /// Replace the profile.
    pub fn with_profile(mut self, profile: BankProfile) -> Self {
        self.profile = profile;
        self
    }

    /// Fix whether HKTAN is sent with the order `code` (e.g. `HKSAL`).
    pub fn with_tan_override(mut self, code: &str, rule: TanOverride) -> Self {
        let mut all: Vec<_> = self.profile.tan_overrides.iter().collect();
        all.retain(|(c, _)| c.as_str() != code);
        all.push((crate::types::SegmentType::new(code), rule));
        self.profile.tan_overrides = all.into_iter().collect();
        self
    }
}

/// Bank code of the synthetic test bank (`testbank/`). Not in the bank list;
/// it is only known with the `testbank` feature.
pub const TESTBANK_BLZ: &str = "12345678";
/// Default port of the standalone test bank (`fints-testbank`). Chosen to be
/// unlikely to collide with development servers.
pub const TESTBANK_PORT: u16 = 47331;

/// The standalone test bank at its default address.
#[cfg(feature = "testbank")]
fn testbank_config() -> BankConfig {
    BankConfig::new(
        "Testbank (synthetic, local)",
        TESTBANK_BLZ,
        "TESTDEFFXXX",
        format!("http://127.0.0.1:{TESTBANK_PORT}/fints"),
    )
}

/// The profile for a bank code: the table entry that lists it, else
/// [`BankProfile::generic`]. Also for codes outside the directory.
pub fn profile_by_blz(blz: &str) -> BankProfile {
    table::profile_for(blz)
}

fn with_profile(config: BankConfig) -> BankConfig {
    let profile = profile_by_blz(config.blz.as_str());
    config.with_profile(profile)
}

/// Get all known banks with FinTS PIN/TAN access, each with its profile.
pub fn all_banks() -> Vec<BankConfig> {
    DIRECTORY
        .iter()
        .map(|entry| with_profile(entry.config()))
        .collect()
}

/// Look up a bank by its BLZ (bank code): directory entry plus profile.
pub fn bank_by_blz(blz: &str) -> Option<BankConfig> {
    #[cfg(feature = "testbank")]
    if blz == TESTBANK_BLZ {
        return Some(testbank_config());
    }
    directory_entry(blz).map(|entry| with_profile(entry.config()))
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeSet, HashSet};

    use super::*;
    use crate::protocol::TanOverrides;

    fn directory_url(blz: &str) -> Option<&'static str> {
        directory_entry(blz).map(|entry| entry.url)
    }

    #[test]
    fn every_profiled_code_is_in_the_directory() {
        for (codes, make) in table::PROFILES {
            for blz in *codes {
                assert!(directory_url(blz).is_some(), "{} {blz}", make().id);
            }
        }
    }

    #[test]
    fn no_code_is_in_two_profiles() {
        let mut seen = HashSet::new();
        for (codes, _) in table::PROFILES {
            for blz in *codes {
                assert!(seen.insert(*blz), "{blz} listed twice");
            }
        }
    }

    /// A new directory code of a profiled bank (another comdirect code)
    /// must be added to its profile's list.
    #[test]
    fn every_code_at_a_profiled_url_is_listed() {
        for (codes, make) in table::PROFILES {
            let urls: BTreeSet<_> = codes.iter().filter_map(|b| directory_url(b)).collect();
            let at_urls: BTreeSet<_> = DIRECTORY
                .iter()
                .filter(|entry| urls.contains(entry.url))
                .map(|entry| entry.blz)
                .collect();
            let listed: BTreeSet<_> = codes.iter().copied().collect();
            assert_eq!(at_urls, listed, "{}", make().id);
        }
    }

    #[test]
    fn comdirect_has_all_eight_directory_codes() {
        let codes: Vec<_> = all_banks()
            .into_iter()
            .filter(|b| b.profile.id == ProfileId::Comdirect)
            .map(|b| b.blz.as_str().to_string())
            .collect();
        assert_eq!(codes.len(), 8, "{codes:?}");
    }

    #[test]
    fn lookup_and_list_agree() {
        for bank in all_banks() {
            let one = bank_by_blz(bank.blz.as_str()).unwrap();
            assert_eq!(one.profile, bank.profile, "{}", bank.blz.as_str());
        }
    }

    #[test]
    fn profiles_by_code() {
        let id = |blz| bank_by_blz(blz).unwrap().profile.id;
        assert_eq!(id("12030000"), ProfileId::Dkb);
        assert_eq!(id("20041155"), ProfileId::Comdirect);
        assert_eq!(id("76030080"), ProfileId::Consorsbank);
        assert_eq!(id("50010517"), ProfileId::Ing);
        assert_eq!(id("10010010"), ProfileId::Generic);
        assert_eq!(profile_by_blz("00000000"), BankProfile::generic());
    }

    #[test]
    fn ing_opens_without_a_sync_dialog_and_others_do_not() {
        let ing = bank_by_blz("50010517").expect("ING is in the directory");
        assert_eq!(
            ing.profile.init,
            InitMode::Direct {
                security_function: "900".into()
            }
        );
        let dkb = bank_by_blz("12030000").expect("DKB is in the directory");
        assert_eq!(dkb.profile.init, InitMode::Standard);
    }

    #[test]
    fn with_url_keeps_the_profile() {
        let ing = bank_by_blz("50010517")
            .unwrap()
            .with_tan_override("HKSAL", TanOverride::Always);
        let moved = ing.clone().with_url("http://127.0.0.1:1/fints");
        assert_eq!(moved.url.as_str(), "http://127.0.0.1:1/fints");
        assert_eq!(moved.profile, ing.profile);
        assert!(matches!(moved.profile.init, InitMode::Direct { .. }));
        assert_eq!(
            moved
                .profile
                .tan_overrides
                .get(&crate::types::SegmentType::new("HKSAL")),
            Some(TanOverride::Always)
        );
    }

    /// Learning on 9075 covers every shipped bank (decision 2026-11-16,
    /// confirmed live at Consorsbank); the mechanism stays for a bank where
    /// learning is not enough.
    #[test]
    fn the_shipped_profiles_have_no_tan_overrides() {
        for (_, make) in table::PROFILES {
            assert_eq!(make().tan_overrides, TanOverrides::default());
        }
    }

    #[test]
    fn a_profile_round_trips_through_json() {
        let p = bank_by_blz("50010517").unwrap().profile;
        let json = serde_json::to_string(&p).unwrap();
        assert!(json.contains("\"ing\""), "{json}");
        assert_eq!(serde_json::from_str::<BankProfile>(&json).unwrap(), p);
    }

    #[test]
    fn consorsbank_completes_short_user_ids() {
        let rule = table::PROFILES
            .iter()
            .find(|(codes, _)| codes.contains(&"76030080"))
            .and_then(|(_, make)| make().user_id)
            .expect("rule");
        assert_eq!(rule.apply("123456789"), "123456789001");
        assert_eq!(rule.apply("1234567890"), "1234567890001");
        // Already complete, other lengths, not only digits: as given.
        assert_eq!(rule.apply("123456789001"), "123456789001");
        assert_eq!(rule.apply("1234567890001"), "1234567890001");
        assert_eq!(rule.apply("12345678"), "12345678");
        assert_eq!(rule.apply("12345678901"), "12345678901");
        assert_eq!(rule.apply("12345678a"), "12345678a");
        assert_eq!(rule.apply("abcdefghi"), "abcdefghi");
        assert_eq!(rule.apply(""), "");
        assert_eq!(profile_by_blz("70120400").user_id, Some(rule));
        assert_eq!(profile_by_blz("12030000").user_id, None);
    }
}

#[cfg(all(test, feature = "testbank"))]
mod testbank_tests {
    #[test]
    fn testbank_is_a_known_bank_with_the_feature() {
        let bank = super::bank_by_blz(super::TESTBANK_BLZ).unwrap();
        assert_eq!(bank.url.as_str(), "http://127.0.0.1:47331/fints");
        assert!(
            super::all_banks()
                .iter()
                .all(|b| b.blz.as_str() != super::TESTBANK_BLZ),
            "the bank list stays the published one"
        );
    }
}