Skip to main content

fints_client/
transport.rs

1//! Transport layer: how a FinTS message reaches the bank.
2//!
3//! [`Transport`] carries one message to a URL and returns the answer as wire
4//! bytes. [`HttpTransport`] is the default (HTTPS POST, base64 body). The
5//! library owns the single call site, `exchange`: it applies the quirks
6//! around the transport and emits the masked `TRACE` event, so a custom
7//! transport can neither skip the quirks nor leak message content.
8
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12use tracing::trace;
13#[cfg(feature = "http")]
14use {
15    base64::{Engine, engine::general_purpose::STANDARD as B64},
16    std::time::Duration,
17    tracing::debug,
18};
19
20use crate::error::{FinTSError, Result, TransportKind};
21use crate::quirks::{QuirkChain, QuirkContext};
22
23/// Boxed, `Send` future returned by [`Transport::send`] (keeps the trait
24/// object safe).
25pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
26
27/// Carries FinTS messages to a bank.
28///
29/// Implementors return [`FinTSError::Timeout`] for a request that timed out,
30/// [`FinTSError::Transport`] (with its [`TransportKind`]) for connect, TLS and
31/// decode failures and [`FinTSError::Http`] for status errors, and own their
32/// timeouts. Implementations must not log message content.
33pub trait Transport: Send + Sync {
34    /// Send one FinTS message (wire bytes, PIN/TAN envelope included) to
35    /// `url` and return the bank's answer as wire bytes. Encoding for the
36    /// medium (base64 over HTTP) is the transport's business.
37    fn send<'a>(&'a self, url: &'a str, message: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>>;
38}
39
40/// A transport shared between dialogs.
41pub type SharedTransport = Arc<dyn Transport>;
42
43/// HTTPS transport: POSTs the base64-encoded message as `text/plain`.
44/// Needs feature `http` (on by default).
45#[cfg(feature = "http")]
46pub struct HttpTransport {
47    client: reqwest::Client,
48}
49
50#[cfg(feature = "http")]
51impl HttpTransport {
52    /// Default settings: 60 s request timeout.
53    pub fn new() -> Result<Self> {
54        Self::with_timeout(Duration::from_secs(60))
55    }
56
57    /// Like [`HttpTransport::new`] with a custom total timeout per request.
58    pub fn with_timeout(timeout: Duration) -> Result<Self> {
59        let client = reqwest::Client::builder()
60            .timeout(timeout)
61            .pool_idle_timeout(Duration::from_secs(2))
62            .pool_max_idle_per_host(0)
63            .tcp_nodelay(true)
64            .build()
65            .map_err(|e| {
66                FinTSError::transport(
67                    TransportKind::Config,
68                    format!("Failed to create HTTP client: {}", e),
69                )
70            })?;
71        Ok(Self { client })
72    }
73
74    /// FinTS over HTTPS (Formals B.1): the request body is the message in
75    /// base64, and so is the answer. Line breaks in the answer are allowed
76    /// and dropped before decoding.
77    async fn post(&self, url: &str, message: &[u8]) -> Result<Vec<u8>> {
78        let body = B64.encode(message);
79        debug!(
80            bytes = message.len(),
81            base64 = body.len(),
82            url,
83            "posting message"
84        );
85        let request = self
86            .client
87            .post(url)
88            .header("Content-Type", "text/plain")
89            .body(body);
90        let response = request.send().await.map_err(request_failed)?;
91
92        let status = response.status().as_u16();
93        if !response.status().is_success() {
94            debug!(status, url, "bank answered with an HTTP error");
95            let message = response.text().await.unwrap_or_default();
96            return Err(FinTSError::Http { status, message });
97        }
98
99        let answer = response.bytes().await.map_err(|e| match e.is_timeout() {
100            true => FinTSError::Timeout,
101            false => FinTSError::transport(TransportKind::Io, format!("reading the answer: {e}")),
102        })?;
103        let base64: Vec<u8> = answer
104            .iter()
105            .copied()
106            .filter(|b| !b.is_ascii_whitespace())
107            .collect();
108        let decoded = B64.decode(&base64).map_err(|e| {
109            FinTSError::transport(TransportKind::Decode, format!("answer is not base64: {e}"))
110        })?;
111        debug!(
112            base64 = base64.len(),
113            bytes = decoded.len(),
114            "answer decoded"
115        );
116        Ok(decoded)
117    }
118}
119
120/// The error for a request that got no HTTP answer.
121#[cfg(feature = "http")]
122fn request_failed(e: reqwest::Error) -> FinTSError {
123    if e.is_timeout() {
124        return FinTSError::Timeout;
125    }
126    FinTSError::transport(
127        classify_request_error(&e),
128        format!("sending the request: {e}"),
129    )
130}
131
132/// What failed when sending a request, from the error and its causes.
133#[cfg(feature = "http")]
134fn classify_request_error(e: &reqwest::Error) -> TransportKind {
135    let kind = classify_chain(e);
136    if kind == TransportKind::Io && e.is_connect() {
137        TransportKind::Connect
138    } else {
139        kind
140    }
141}
142
143/// Walks the cause chain: a `rustls::Error` (also inside an `io::Error`,
144/// which hides its inner error from `source`) is `Tls`; a hyper connect
145/// error that says "dns error" is `Dns`; anything else is `Io`.
146#[cfg(feature = "http")]
147fn classify_chain(e: &(dyn std::error::Error + 'static)) -> TransportKind {
148    let mut dns = false;
149    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(e);
150    while let Some(err) = cur {
151        if err.is::<rustls::Error>() {
152            return TransportKind::Tls;
153        }
154        if let Some(io) = err.downcast_ref::<std::io::Error>()
155            && io
156                .get_ref()
157                .is_some_and(|inner| inner.is::<rustls::Error>())
158        {
159            return TransportKind::Tls;
160        }
161        if err.to_string().starts_with("dns error") {
162            dns = true;
163        }
164        cur = err.source();
165    }
166    if dns {
167        TransportKind::Dns
168    } else {
169        TransportKind::Io
170    }
171}
172
173#[cfg(feature = "http")]
174impl Transport for HttpTransport {
175    fn send<'a>(&'a self, url: &'a str, message: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
176        Box::pin(self.post(url, message))
177    }
178}
179
180/// Placeholder transport when feature `http` is off and the caller set none.
181#[cfg(not(feature = "http"))]
182pub(crate) struct NoTransport;
183
184#[cfg(not(feature = "http"))]
185impl Transport for NoTransport {
186    fn send<'a>(&'a self, _: &'a str, _: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
187        Box::pin(async {
188            Err(FinTSError::transport(
189                TransportKind::Config,
190                "no transport: enable feature `http` or call with_transport",
191            ))
192        })
193    }
194}
195
196/// The transport a new dialog starts with.
197pub(crate) fn default_transport() -> Result<SharedTransport> {
198    #[cfg(feature = "http")]
199    {
200        Ok(Arc::new(HttpTransport::new()?))
201    }
202    #[cfg(not(feature = "http"))]
203    {
204        Ok(Arc::new(NoTransport))
205    }
206}
207
208/// Short, content-free summary of a failed exchange for the trace event.
209/// An HTTP body is never included: it may echo request data.
210fn error_summary(e: &FinTSError) -> String {
211    match e {
212        FinTSError::Http { status, .. } => format!("HTTP {status}"),
213        FinTSError::Timeout => "timeout".to_string(),
214        FinTSError::Transport { kind, message } => format!("transport {kind}: {message}"),
215        _ => "error".to_string(),
216    }
217}
218
219/// The one place the library calls [`Transport::send`]: quirks (outgoing),
220/// send, masked `TRACE` event (success or failure), quirks (incoming).
221/// Returns the answer as clear text with all quirks applied.
222pub(crate) async fn exchange(
223    transport: &dyn Transport,
224    url: &str,
225    quirks: &QuirkChain,
226    ctx: &QuirkContext<'_>,
227    message_bytes: &[u8],
228) -> Result<Vec<u8>> {
229    let outgoing = quirks.outgoing(message_bytes, ctx);
230    trace!("Request (masked): {}", crate::mask::mask_for_log(&outgoing));
231    match transport.send(url, &outgoing).await {
232        Ok(raw) => {
233            trace!("Response (masked): {}", crate::mask::mask_for_log(&raw));
234            trace!(
235                target: crate::mask::EXCHANGE_TARGET,
236                request = %crate::mask::redacted_text(&outgoing),
237                response = %crate::mask::redacted_text(&raw),
238                "exchange"
239            );
240            Ok(quirks.incoming(&raw, ctx))
241        }
242        Err(e) => {
243            trace!(
244                target: crate::mask::EXCHANGE_TARGET,
245                request = %crate::mask::redacted_text(&outgoing),
246                error = %error_summary(&e),
247                "exchange"
248            );
249            Err(e)
250        }
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    #[cfg(feature = "http")]
258    use tokio::io::{AsyncReadExt, AsyncWriteExt};
259    #[cfg(feature = "http")]
260    use tokio::net::TcpListener;
261
262    /// A local HTTP server for one request. `answer` gets the request body
263    /// and returns status and body of the reply. Returns the server's URL.
264    #[cfg(feature = "http")]
265    async fn one_shot_server(
266        answer: impl FnOnce(Vec<u8>) -> (u16, Vec<u8>) + Send + 'static,
267    ) -> String {
268        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
269        let url = format!("http://{}/fints", listener.local_addr().unwrap());
270        tokio::spawn(async move {
271            let (mut stream, _) = listener.accept().await.unwrap();
272            let body = read_request_body(&mut stream).await;
273            let (status, reply) = answer(body);
274            let head = format!(
275                "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
276                reply.len()
277            );
278            stream
279                .write_all(&[head.as_bytes(), &reply].concat())
280                .await
281                .unwrap();
282            stream.shutdown().await.ok();
283        });
284        url
285    }
286
287    /// Reads one request and returns its body, as long as Content-Length says.
288    #[cfg(feature = "http")]
289    async fn read_request_body(stream: &mut tokio::net::TcpStream) -> Vec<u8> {
290        let mut request = Vec::new();
291        let mut chunk = [0u8; 4096];
292        loop {
293            let read = stream.read(&mut chunk).await.unwrap();
294            request.extend_from_slice(&chunk[..read]);
295            let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else {
296                assert!(read > 0, "request ended inside the head");
297                continue;
298            };
299            let head = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
300            let length: usize = head
301                .lines()
302                .find_map(|l| l.strip_prefix("content-length:"))
303                .map_or(0, |v| v.trim().parse().unwrap());
304            if request.len() >= end + 4 + length || read == 0 {
305                return request[end + 4..].to_vec();
306            }
307        }
308    }
309
310    #[cfg(feature = "http")]
311    fn is_transport(err: &FinTSError, expected: TransportKind) -> bool {
312        matches!(err, FinTSError::Transport { kind, .. } if *kind == expected)
313    }
314
315    /// The request goes out as base64; the answer comes back as base64,
316    /// here broken into lines as some banks send it.
317    #[cfg(feature = "http")]
318    #[tokio::test]
319    async fn message_and_answer_travel_as_base64() {
320        let message = b"HNHBK:1:3+000000000123+300+0+1'";
321        let url = one_shot_server(|body| {
322            assert_eq!(
323                body,
324                B64.encode(b"HNHBK:1:3+000000000123+300+0+1'").into_bytes()
325            );
326            let encoded = B64.encode("HIRMG:2:2+0010::Nachricht entgegengenommen'");
327            let (first, second) = encoded.split_at(20);
328            (200, format!("{first}\r\n{second}\r\n").into_bytes())
329        })
330        .await;
331        let answer = HttpTransport::new()
332            .unwrap()
333            .send(&url, message)
334            .await
335            .unwrap();
336        assert_eq!(answer, b"HIRMG:2:2+0010::Nachricht entgegengenommen'");
337    }
338
339    /// A status other than 2xx is `Http` with the body as the message.
340    #[cfg(feature = "http")]
341    #[tokio::test]
342    async fn an_http_error_keeps_status_and_body() {
343        let url = one_shot_server(|_| (502, b"upstream unavailable".to_vec())).await;
344        let err = HttpTransport::new()
345            .unwrap()
346            .send(&url, b"m")
347            .await
348            .unwrap_err();
349        let FinTSError::Http { status, message } = &err else {
350            panic!("{err}");
351        };
352        assert_eq!((*status, message.as_str()), (502, "upstream unavailable"));
353    }
354
355    #[cfg(feature = "http")]
356    #[tokio::test]
357    async fn an_answer_that_is_not_base64_is_a_decode_error() {
358        let url = one_shot_server(|_| (200, b"<html>Wartung</html>".to_vec())).await;
359        let err = HttpTransport::new()
360            .unwrap()
361            .send(&url, b"m")
362            .await
363            .unwrap_err();
364        assert!(is_transport(&err, TransportKind::Decode), "{err}");
365    }
366
367    /// Nobody listens on a port just released: the connection is refused.
368    #[cfg(feature = "http")]
369    #[tokio::test]
370    async fn a_closed_port_is_a_connect_error() {
371        let address = TcpListener::bind("127.0.0.1:0")
372            .await
373            .unwrap()
374            .local_addr()
375            .unwrap();
376        let url = format!("http://{address}/fints");
377        let err = HttpTransport::new()
378            .unwrap()
379            .send(&url, b"m")
380            .await
381            .unwrap_err();
382        assert!(is_transport(&err, TransportKind::Connect), "{err}");
383    }
384
385    #[cfg(feature = "http")]
386    #[tokio::test]
387    async fn http_5xx_is_the_status_error_and_retryable() {
388        let url = one_shot_server(|_| (503, Vec::new())).await;
389        let err = HttpTransport::new()
390            .unwrap()
391            .send(&url, b"hex")
392            .await
393            .unwrap_err();
394        assert!(matches!(err, FinTSError::Http { status: 503, .. }));
395        assert!(err.is_retryable());
396    }
397
398    #[cfg(feature = "http")]
399    #[tokio::test]
400    async fn a_slow_server_is_a_timeout() {
401        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
402        let port = listener.local_addr().unwrap().port();
403        // Accepts and never answers.
404        let _held = tokio::spawn(async move {
405            let conn = listener.accept().await;
406            tokio::time::sleep(Duration::from_secs(5)).await;
407            drop(conn);
408        });
409        let url = format!("http://127.0.0.1:{port}/");
410        let err = HttpTransport::with_timeout(Duration::from_millis(100))
411            .unwrap()
412            .send(&url, b"hex")
413            .await
414            .unwrap_err();
415        assert!(matches!(err, FinTSError::Timeout), "got: {err}");
416    }
417
418    #[cfg(feature = "http")]
419    #[test]
420    fn a_rustls_error_in_the_chain_is_tls() {
421        use std::io::{Error, ErrorKind};
422        let cert = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
423        // Direct, and wrapped in an io::Error the way tokio-rustls reports it
424        // (io::Error::source skips the wrapped error, so it needs its own check).
425        assert_eq!(classify_chain(&cert), TransportKind::Tls);
426        let wrapped = Error::new(ErrorKind::InvalidData, cert);
427        assert_eq!(classify_chain(&wrapped), TransportKind::Tls);
428        let alert = rustls::Error::AlertReceived(rustls::AlertDescription::HandshakeFailure);
429        assert_eq!(classify_chain(&Error::other(alert)), TransportKind::Tls);
430    }
431
432    #[cfg(feature = "http")]
433    #[test]
434    fn dns_and_other_causes() {
435        use std::io::{Error, ErrorKind};
436        #[derive(Debug)]
437        struct Outer(Error);
438        impl std::fmt::Display for Outer {
439            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440                f.write_str("dns error: failed to lookup address information")
441            }
442        }
443        impl std::error::Error for Outer {
444            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
445                Some(&self.0)
446            }
447        }
448        assert_eq!(
449            classify_chain(&Outer(Error::new(ErrorKind::NotFound, "x"))),
450            TransportKind::Dns
451        );
452        assert_eq!(
453            classify_chain(&Error::new(ErrorKind::ConnectionReset, "reset")),
454            TransportKind::Io
455        );
456    }
457
458    #[cfg(not(feature = "http"))]
459    #[tokio::test]
460    async fn without_http_the_default_transport_is_a_config_error() {
461        let t = default_transport().unwrap();
462        let err = t.send("http://x/", b"m").await.unwrap_err();
463        assert!(matches!(
464            err,
465            FinTSError::Transport {
466                kind: TransportKind::Config,
467                ..
468            }
469        ));
470    }
471
472    #[cfg(feature = "http")]
473    #[test]
474    fn new_accepts_valid_url_and_errors_on_bad_url() {
475        assert!(HttpTransport::new().is_ok());
476        // A non-URL input still builds an HTTP client (reqwest parses lazily),
477        // so we only assert the happy path here.
478        assert!(HttpTransport::new().is_ok());
479    }
480
481    // ── Failure event ──
482
483    #[derive(Clone, Default)]
484    struct Capture(std::sync::Arc<std::sync::Mutex<Vec<String>>>);
485
486    struct Fields(String);
487
488    impl tracing::field::Visit for Fields {
489        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
490            self.0.push_str(&format!("{}={:?} ", field.name(), value));
491        }
492    }
493
494    impl tracing::Subscriber for Capture {
495        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
496            true
497        }
498        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
499            tracing::span::Id::from_u64(1)
500        }
501        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
502        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
503        fn event(&self, event: &tracing::Event<'_>) {
504            if event.metadata().target() == crate::mask::EXCHANGE_TARGET {
505                let mut fields = Fields(String::new());
506                event.record(&mut fields);
507                self.0.lock().unwrap().push(fields.0);
508            }
509        }
510        fn enter(&self, _: &tracing::span::Id) {}
511        fn exit(&self, _: &tracing::span::Id) {}
512    }
513
514    struct Failing;
515
516    impl Transport for Failing {
517        fn send<'a>(&'a self, _: &'a str, _: &'a [u8]) -> BoxFuture<'a, Result<Vec<u8>>> {
518            Box::pin(async {
519                Err(FinTSError::Http {
520                    status: 503,
521                    message: "echoed secret body".into(),
522                })
523            })
524        }
525    }
526
527    #[tokio::test]
528    async fn failing_send_emits_an_event_with_error_and_no_response() {
529        let logs = Capture::default();
530        let _guard = tracing::subscriber::set_default(logs.clone());
531        let ctx = QuirkContext {
532            hbci_version: "300",
533            dialog_id: "0",
534            message_number: 1,
535        };
536        let r = exchange(&Failing, "http://x/", &QuirkChain::none(), &ctx, b"HNHBK:1").await;
537        assert!(matches!(r, Err(FinTSError::Http { status: 503, .. })));
538        let events = logs.0.lock().unwrap().clone();
539        assert_eq!(events.len(), 1, "{events:?}");
540        assert!(events[0].contains("error=HTTP 503"), "{events:?}");
541        assert!(events[0].contains("request="), "{events:?}");
542        assert!(!events[0].contains("response="), "{events:?}");
543        assert!(!events[0].contains("secret"), "{events:?}");
544    }
545}