teloxide-fork-core 0.16.0

Core part of the `teloxide` library - telegram bot API client
Documentation
//! Network-specific API.

use std::{io, time::Duration};

pub use self::download::{download_file, download_file_stream, Download};

pub(crate) use self::{
    request::{request_json, request_multipart},
    telegram_response::TelegramResponse,
};

mod download;
mod request;
mod telegram_response;

/// The default Telegram API URL.
pub const TELEGRAM_API_URL: &str = "https://api.telegram.org";

pub(super) const REQUEST_TIMEOUT: Duration = Duration::from_secs(17);

/// Constructs a network client from the `TELOXIDE_PROXY` environmental
/// variable.
///
/// This function passes the value of `TELOXIDE_PROXY` into
/// [`reqwest::Proxy::all`], if it exists, otherwise returns the default
/// client.
///
/// ## Note
///
/// The created client will have safe settings, meaning that it will be able to
/// work in long time durations, see the [issue 223].
///
/// [`reqwest::Proxy::all`]: https://docs.rs/reqwest/latest/reqwest/struct.Proxy.html#method.all
/// [issue 223]: https://github.com/teloxide/teloxide/issues/223
///
/// ## Panics
///
/// If `TELOXIDE_PROXY` exists, but isn't correct url.
#[must_use]
pub fn client_from_env() -> reqwest::Client {
    use reqwest::Proxy;

    const TELOXIDE_PROXY: &str = "TELOXIDE_PROXY";

    let builder = default_reqwest_settings();

    match std::env::var(TELOXIDE_PROXY).ok() {
        Some(proxy) => builder.proxy(Proxy::all(proxy).expect("reqwest::Proxy creation failed")),
        None => builder,
    }
    .build()
    .expect("creating reqwest::Client")
}

/// Returns a reqwest client builder with default settings.
///
/// Client built from default settings is supposed to work over long time
/// durations, see the [issue 223].
///
/// The current settings are:
///  - A connection timeout of 5 seconds.
///  - A timeout of 17 seconds.
///  - `tcp_nodelay` is on.
///  - Referer headers and cross-origin redirects are disabled.
///
/// ## Notes
///
/// 1. The settings may change in the future.
/// 2. Long polling uses a per-request timeout based on the Telegram timeout.
/// 3. If you alter the current settings listed above, your bot will not be
///    guaranteed to work over long time durations.
///
/// [issue 223]: https://github.com/teloxide/teloxide/issues/223
pub fn default_reqwest_settings() -> reqwest::ClientBuilder {
    reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(5))
        .timeout(REQUEST_TIMEOUT)
        .tcp_nodelay(true)
        .referer(false)
        .redirect(reqwest::redirect::Policy::custom(|attempt| {
            if attempt.previous().len() >= 10 {
                return attempt.error("too many redirects");
            }
            if attempt.previous().first().is_some_and(|url| url.origin() == attempt.url().origin())
            {
                attempt.follow()
            } else {
                attempt.error("cross-origin redirect blocked")
            }
        }))
}

/// Creates URL for making HTTPS requests. See the [Telegram documentation].
///
/// [Telegram documentation]: https://core.telegram.org/bots/api#making-requests
fn method_url(base: reqwest::Url, token: &str, method_name: &str) -> reqwest::Url {
    let mut url = base;
    {
        let mut segments = url.path_segments_mut().expect("base URL cannot be a cannot-be-a-base");
        segments.pop_if_empty().push(&format!("bot{token}"));
        segments.push(method_name);
    }
    url
}

/// Creates URL for downloading a file. See the [Telegram documentation].
///
/// [Telegram documentation]: https://core.telegram.org/bots/api#file
fn file_url(mut base: reqwest::Url, token: &str, file_path: &str) -> io::Result<reqwest::Url> {
    let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "invalid Telegram file path");
    if file_path.contains(['\\', ':'])
        || file_path.chars().any(char::is_control)
        || file_path.split('/').any(|part| matches!(part, "" | "." | ".."))
    {
        return Err(invalid());
    }
    base.path_segments_mut()
        .map_err(|()| invalid())?
        .pop_if_empty()
        .push("file")
        .push(&format!("bot{token}"))
        .extend(file_path.split('/'));
    Ok(base)
}

#[cfg(test)]
mod tests {
    use crate::net::*;

    #[test]
    fn method_url_test() {
        let url = method_url(
            reqwest::Url::parse(TELEGRAM_API_URL).unwrap(),
            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
            "methodName",
        );

        assert_eq!(
            url.as_str(),
            "https://api.telegram.org/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/methodName"
        );
    }

    #[test]
    fn method_url_with_custom_url_test() {
        let url = method_url(
            reqwest::Url::parse("https://example.com/telegram/").unwrap(),
            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
            "methodName",
        );

        assert_eq!(
	    url.as_str(),
	    "https://example.com/telegram/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/methodName"
	);
    }

    #[test]
    fn file_url_test() {
        let url = file_url(
            reqwest::Url::parse(TELEGRAM_API_URL).unwrap(),
            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
            "photos/file_12.jpg",
        )
        .unwrap();

        assert_eq!(
            url.as_str(),
            "https://api.telegram.org/file/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/photos/file_12.jpg"
        );
    }

    #[test]
    fn file_url_with_custom_url_test() {
        let url = file_url(
            reqwest::Url::parse("https://example.com/telegram/").unwrap(),
            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
            "photos/file_12.jpg",
        )
        .unwrap();

        assert_eq!(
	    url.as_str(),
	    "https://example.com/telegram/file/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/photos/file_12.jpg"
	);
    }

    fn reply_server(
        responses: Vec<String>,
    ) -> (reqwest::Url, std::thread::JoinHandle<Vec<String>>) {
        use std::{
            io::{BufRead, BufReader, Write},
            net::TcpListener,
        };
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/prefix/", listener.local_addr().unwrap()).parse().unwrap();
        let server = std::thread::spawn(move || {
            responses
                .into_iter()
                .map(|response| {
                    let (mut conn, _) = listener.accept().unwrap();
                    conn.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
                    let mut reader = BufReader::new(&mut conn);
                    let mut headers = String::new();
                    loop {
                        let start = headers.len();
                        if reader.read_line(&mut headers).unwrap() == 0
                            || &headers[start..] == "\r\n"
                        {
                            break;
                        }
                    }
                    conn.write_all(response.as_bytes()).unwrap();
                    headers
                })
                .collect()
        });
        (url, server)
    }

    #[tokio::test]
    async fn default_redirects_never_send_referer_or_cross_origin() {
        use futures::TryStreamExt;
        let client = default_reqwest_settings().build().unwrap();
        let (url, server) = reply_server(vec![
            "HTTP/1.1 302 Found\r\nLocation: /other\r\nContent-Length: 0\r\nConnection: \
             close\r\n\r\n"
                .to_owned(),
            "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_owned(),
        ]);
        let body = download_file_stream(&client, url, "secret-token", "photos/file_12.jpg")
            .try_collect::<Vec<_>>()
            .await
            .unwrap();
        assert_eq!(body.concat(), b"ok");
        let headers = server.join().unwrap();
        assert!(headers[0].starts_with("GET /prefix/file/botsecret-token/photos/file_12.jpg "));
        assert!(headers[1].starts_with("GET /other "));
        assert!(!headers[1].to_ascii_lowercase().contains("referer:"));

        let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        other.set_nonblocking(true).unwrap();
        let (url, server) = reply_server(vec![format!(
            "HTTP/1.1 302 Found\r\nLocation: http://{}/botsecret-token\r\nContent-Length: \
             0\r\nConnection: close\r\n\r\n",
            other.local_addr().unwrap()
        )]);
        let err = download_file_stream(&client, url, "secret-token", "photos/file_12.jpg")
            .try_collect::<Vec<_>>()
            .await
            .unwrap_err();
        assert!(!format!("{err} {err:?}").contains("secret-token"));
        assert!(
            matches!(err, crate::DownloadError::Network(error) if error.is_redirect() && error.url().is_none())
        );
        assert_eq!(other.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
        server.join().unwrap();
    }

    #[test]
    fn special_download_paths_are_not_url_components() {
        for path in [
            "",
            "/etc/passwd",
            "photos/../etc",
            "photos/./foo",
            "photos//foo",
            "https://other/file",
            "C:\\photo.jpg",
        ] {
            assert!(file_url(TELEGRAM_API_URL.parse().unwrap(), "token", path).is_err(), "{path}");
        }
        let url =
            file_url(TELEGRAM_API_URL.parse().unwrap(), "token", "photos/%2e%2e?q#f").unwrap();
        assert_eq!(url.path(), "/file/bottoken/photos/%252e%252e%3Fq%23f");
    }

    #[tokio::test]
    async fn long_poll_hint_overrides_the_client_timeout() {
        use crate::{payloads::GetUpdatesSetters, requests::Requester, Bot};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
        let server = std::thread::spawn(move || {
            use std::io::{BufRead, BufReader, Write};
            let (mut conn, _) = listener.accept().unwrap();
            conn.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
            let mut reader = BufReader::new(&mut conn);
            loop {
                let mut line = String::new();
                if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
                    break;
                }
            }
            std::thread::sleep(Duration::from_millis(100));
            let body = r#"{"ok":true,"result":[]}"#;
            write!(
                conn,
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            )
            .unwrap();
        });
        let client = default_reqwest_settings().timeout(Duration::from_millis(20)).build().unwrap();
        let bot = Bot::with_client("poll-token", client).set_api_url(url);
        assert!(bot.get_updates().timeout(1).await.unwrap().is_empty());
        server.join().unwrap();
    }
}