kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! The `Transport` seam (ADR 0017 §1): HTTP requests and one WebSocket.
//!
//! The default ([`NativeTransport`], feature `transport-native`) is tokio-tungstenite
//! for the socket and ureq for HTTP, both over rustls with the platform
//! certificate verifier. The Swift package brings a `URLSession` transport
//! instead. Either way the core reads the socket on its own task, so slow
//! work never delays a pong.

use std::path::PathBuf;
use std::sync::Arc;

use async_trait::async_trait;

use crate::error::{Error, Result};

/// An HTTP request. Transports MUST NOT follow redirects: the PKCE flow reads `Location`.
#[derive(Debug, Clone, Default)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Body,
    /// Stream the response body to this file instead of returning it.
    pub save_to: Option<PathBuf>,
}

#[derive(Debug, Clone, Default)]
pub enum Body {
    #[default]
    Empty,
    Bytes(Vec<u8>),
    /// Stream this file as the body.
    File(PathBuf),
}

#[derive(Debug, Clone, Default)]
pub struct HttpResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl HttpResponse {
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
    }
}

/// What a socket delivers.
#[derive(Debug, Clone, PartialEq)]
pub enum WsEvent {
    Text(String),
    /// A binary message (a protocol violation by the server; the core ignores it).
    Binary(usize),
    /// The peer closed the socket. `code` 1005 when it sent none.
    Close {
        code: u16,
        reason: String,
    },
}

/// One open WebSocket. `recv` is only ever called by one task at a time; `send`
/// and `close` may be called concurrently with it. Implementations answer
/// WebSocket ping control frames themselves while `recv` is being awaited.
#[async_trait]
pub trait Socket: Send + Sync {
    async fn send(&self, text: String) -> Result<()>;
    /// The next event; `None` when the connection dropped without a close frame (1006).
    async fn recv(&self) -> Option<WsEvent>;
    async fn close(&self, code: u16, reason: &str);
}

#[async_trait]
pub trait Transport: Send + Sync {
    async fn http(&self, req: HttpRequest) -> Result<HttpResponse>;
    async fn connect(&self, url: &str) -> Result<Box<dyn Socket>>;
}

/// The default transport for this build.
pub fn default_transport() -> Result<Arc<dyn Transport>> {
    #[cfg(feature = "transport-native")]
    {
        Ok(Arc::new(native::NativeTransport::new()?))
    }
    #[cfg(not(feature = "transport-native"))]
    {
        Err(Error::config("this build has no default transport (feature transport-native is off): pass one with ClientBuilder::transport"))
    }
}

#[cfg(feature = "transport-native")]
pub use native::NativeTransport;

#[cfg(feature = "transport-native")]
mod native {
    use std::io::Read;
    use std::sync::Arc;
    use std::time::Duration;

    use async_trait::async_trait;
    use futures_util::stream::{SplitSink, SplitStream};
    use futures_util::{SinkExt, StreamExt};
    use tokio::net::TcpStream;
    use tokio::sync::Mutex;
    use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
    use tokio_tungstenite::tungstenite::protocol::{CloseFrame, WebSocketConfig};
    use tokio_tungstenite::tungstenite::Message;
    use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};

    use super::{Body, HttpRequest, HttpResponse, Socket, Transport, WsEvent};
    use crate::error::{Error, Result};

    type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;

    /// tokio-tungstenite + ureq over rustls.
    pub struct NativeTransport {
        agent: ureq::Agent,
        tls: Arc<rustls::ClientConfig>,
    }

    fn provider() -> Arc<rustls::crypto::CryptoProvider> {
        Arc::new(rustls::crypto::ring::default_provider())
    }

    #[cfg(not(target_os = "android"))]
    fn tls_config() -> Result<rustls::ClientConfig> {
        use rustls_platform_verifier::BuilderVerifierExt;
        rustls::ClientConfig::builder_with_provider(provider())
            .with_safe_default_protocol_versions()
            .map_err(Error::network)?
            .with_platform_verifier()
            .map(|b| b.with_no_client_auth())
            .map_err(Error::network)
    }

    /// Android's system and user CA stores (the platform verifier needs a JNI
    /// context, which a library loaded through UniFFI doesn't have).
    #[cfg(target_os = "android")]
    fn android_roots() -> Vec<rustls_pki_types::CertificateDer<'static>> {
        use rustls_pki_types::pem::PemObject;
        let mut out = Vec::new();
        for dir in
            ["/system/etc/security/cacerts", "/apex/com.android.conscrypt/cacerts", "/data/misc/user/0/cacerts-added"]
        {
            let Ok(entries) = std::fs::read_dir(dir) else { continue };
            for e in entries.flatten() {
                if let Ok(c) = rustls_pki_types::CertificateDer::from_pem_file(e.path()) {
                    out.push(c);
                }
            }
        }
        out
    }

    #[cfg(target_os = "android")]
    fn tls_config() -> Result<rustls::ClientConfig> {
        let mut roots = rustls::RootCertStore::empty();
        roots.add_parsable_certificates(android_roots());
        Ok(rustls::ClientConfig::builder_with_provider(provider())
            .with_safe_default_protocol_versions()
            .map_err(Error::network)?
            .with_root_certificates(roots)
            .with_no_client_auth())
    }

    #[cfg(not(target_os = "android"))]
    fn ureq_roots() -> ureq::tls::RootCerts {
        ureq::tls::RootCerts::PlatformVerifier
    }

    #[cfg(target_os = "android")]
    fn ureq_roots() -> ureq::tls::RootCerts {
        let certs: Vec<ureq::tls::Certificate<'static>> =
            android_roots().into_iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect();
        ureq::tls::RootCerts::new_with_certs(&certs)
    }

    impl NativeTransport {
        pub fn new() -> Result<NativeTransport> {
            let tls = Arc::new(tls_config()?);
            let agent = ureq::Agent::config_builder()
                .max_redirects(0)
                .http_status_as_error(false)
                .timeout_connect(Some(Duration::from_secs(15)))
                .timeout_recv_response(Some(Duration::from_secs(60)))
                .tls_config(
                    ureq::tls::TlsConfig::builder()
                        .provider(ureq::tls::TlsProvider::Rustls)
                        .root_certs(ureq_roots())
                        .unversioned_rustls_crypto_provider(provider())
                        .build(),
                )
                .build()
                .into();
            Ok(NativeTransport { agent, tls })
        }

        fn http_blocking(agent: &ureq::Agent, req: HttpRequest) -> Result<HttpResponse> {
            let mut b = ureq::http::Request::builder().method(req.method.as_str()).uri(req.url.as_str());
            for (k, v) in &req.headers {
                b = b.header(k.as_str(), v.as_str());
            }
            let res = match req.body {
                Body::Empty => {
                    let r = b.body(()).map_err(Error::network)?;
                    agent.run(r)
                }
                Body::Bytes(bytes) => {
                    let r = b.body(bytes).map_err(Error::network)?;
                    agent.run(r)
                }
                Body::File(path) => {
                    let f = std::fs::File::open(&path).map_err(Error::storage)?;
                    let len = f.metadata().map_err(Error::storage)?.len();
                    let r = b
                        .header("content-length", len.to_string())
                        .body(ureq::SendBody::from_owned_reader(f))
                        .map_err(Error::network)?;
                    agent.run(r)
                }
            };
            let mut res = res.map_err(Error::network)?;
            let status = res.status().as_u16();
            let headers = res
                .headers()
                .iter()
                .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or_default().to_string()))
                .collect();
            let mut body = Vec::new();
            match (&req.save_to, status) {
                (Some(path), 200..=299) => {
                    let mut f = std::fs::File::create(path).map_err(Error::storage)?;
                    let mut reader = res.body_mut().with_config().limit(u64::MAX).reader();
                    std::io::copy(&mut reader, &mut f).map_err(Error::network)?;
                }
                _ => {
                    res.body_mut()
                        .with_config()
                        .limit(64 << 20)
                        .reader()
                        .read_to_end(&mut body)
                        .map_err(Error::network)?;
                }
            }
            Ok(HttpResponse { status, headers, body })
        }
    }

    #[async_trait]
    impl Transport for NativeTransport {
        async fn http(&self, req: HttpRequest) -> Result<HttpResponse> {
            let agent = self.agent.clone();
            tokio::task::spawn_blocking(move || NativeTransport::http_blocking(&agent, req))
                .await
                .map_err(|e| Error::network(format!("http task failed: {e}")))?
        }

        async fn connect(&self, url: &str) -> Result<Box<dyn Socket>> {
            let mut cfg = WebSocketConfig::default();
            // At least the protocol's 8 MiB cap, with room for framing.
            cfg.max_message_size = Some(16 << 20);
            cfg.max_frame_size = Some(16 << 20);
            let connector = tokio_tungstenite::Connector::Rustls(self.tls.clone());
            let (ws, _) = tokio::time::timeout(
                Duration::from_secs(20),
                tokio_tungstenite::connect_async_tls_with_config(url, Some(cfg), true, Some(connector)),
            )
            .await
            .map_err(|_| Error::network("websocket connect timed out"))?
            .map_err(Error::network)?;
            let (sink, stream) = ws.split();
            Ok(Box::new(NativeSocket { sink: Mutex::new(sink), stream: Mutex::new(stream) }))
        }
    }

    struct NativeSocket {
        sink: Mutex<SplitSink<Ws, Message>>,
        stream: Mutex<SplitStream<Ws>>,
    }

    #[async_trait]
    impl Socket for NativeSocket {
        async fn send(&self, text: String) -> Result<()> {
            let mut s = self.sink.lock().await;
            tokio::time::timeout(Duration::from_secs(10), s.send(Message::text(text)))
                .await
                .map_err(|_| Error::network("websocket write timed out"))?
                .map_err(Error::network)
        }

        async fn recv(&self) -> Option<WsEvent> {
            let mut st = self.stream.lock().await;
            loop {
                match st.next().await? {
                    Ok(Message::Text(t)) => return Some(WsEvent::Text(t.to_string())),
                    Ok(Message::Binary(b)) => return Some(WsEvent::Binary(b.len())),
                    Ok(Message::Close(f)) => {
                        return Some(match f {
                            Some(f) => WsEvent::Close { code: u16::from(f.code), reason: f.reason.to_string() },
                            None => WsEvent::Close { code: 1005, reason: String::new() },
                        })
                    }
                    // Pings are answered by tungstenite while we read; flush the pong now.
                    Ok(Message::Ping(_)) => {
                        let mut s = self.sink.lock().await;
                        let _ = s.flush().await;
                    }
                    Ok(_) => {}
                    Err(tokio_tungstenite::tungstenite::Error::Capacity(_)) => {
                        return Some(WsEvent::Close { code: 1009, reason: "message too big".into() })
                    }
                    Err(_) => return None,
                }
            }
        }

        async fn close(&self, code: u16, reason: &str) {
            let mut s = self.sink.lock().await;
            let frame = CloseFrame { code: CloseCode::from(code), reason: reason.to_string().into() };
            let _ = tokio::time::timeout(Duration::from_secs(2), s.send(Message::Close(Some(frame)))).await;
            let _ = s.close().await;
        }
    }
}

/// Resolves a URL that may be relative to the base URL (`/blobs/…`).
pub fn resolve(base: &str, url: &str) -> String {
    if url.starts_with('/') {
        format!("{}{}", base.trim_end_matches('/'), url)
    } else {
        url.to_string()
    }
}

/// `application/x-www-form-urlencoded` encoding.
pub fn form(pairs: &[(&str, &str)]) -> Vec<u8> {
    let mut s = form_urlencoded::Serializer::new(String::new());
    for (k, v) in pairs {
        s.append_pair(k, v);
    }
    s.finish().into_bytes()
}

#[allow(dead_code)]
fn _assert_object_safe(_: &dyn Transport, _: &dyn Socket) {}

#[allow(unused_imports)]
use Error as _;