hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! The gRPC channel: TLS, keepalive, and the bearer-token interceptor.
//!
//! TLS is cfg-split in two layers, because tonic's own TLS items are behind
//! its features and calling one that is not compiled in is a build error:
//!
//! 1. A crypto provider (`tls-ring` or `tls-aws-lc`) gates the whole TLS code
//!    path. Without one, nothing from `tonic::transport`'s TLS module is named
//!    here and [`TlsStrategy::Tls`]/[`TlsStrategy::Mtls`] fail with
//!    [`Error::Config`].
//! 2. Inside it, the root store follows `tls-native-roots` (preferred) or
//!    `tls-webpki-roots`. With neither, the caller must supply a CA file.

#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
use std::path::Path;
use std::time::Duration;

use tonic::metadata::{Ascii, MetadataValue};
use tonic::service::interceptor::InterceptedService;
#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
use tonic::transport::{Certificate, ClientTlsConfig, Identity};
use tonic::transport::{Channel, Endpoint};

use crate::config::strip_scheme;
use crate::{ClientConfig, Error, Result, TlsStrategy};

const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(60);
/// How long [`connect`] waits for the initial TCP/TLS handshake before giving
/// up. Without this, connecting to an address that never answers (a stalled
/// network, a routable-but-silent host) could hang indefinitely.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Every generated client is built over this service.
pub(crate) type GrpcService = InterceptedService<Channel, AuthInterceptor>;

/// Adds `authorization: Bearer <token>` to every call.
///
/// `Debug` is safe: the header value is marked sensitive, so its `Debug`
/// impl prints `Sensitive` instead of the token.
#[derive(Clone, Debug)]
pub(crate) struct AuthInterceptor {
    header: MetadataValue<Ascii>,
}

impl AuthInterceptor {
    pub(crate) fn new(token: &str) -> Result<Self> {
        let mut header: MetadataValue<Ascii> = format!("Bearer {token}").parse().map_err(|_| {
            Error::Config(
                "the API token contains characters that cannot be sent in a header".to_string(),
            )
        })?;
        header.set_sensitive(true);
        Ok(Self { header })
    }
}

impl tonic::service::Interceptor for AuthInterceptor {
    fn call(
        &mut self,
        mut request: tonic::Request<()>,
    ) -> std::result::Result<tonic::Request<()>, tonic::Status> {
        request
            .metadata_mut()
            .insert("authorization", self.header.clone());
        Ok(request)
    }
}

/// Builds the lazily-connecting channel. Must be called inside a tokio runtime.
pub(crate) fn connect(config: &ClientConfig) -> Result<GrpcService> {
    warn_on_scheme_mismatch(config);

    let endpoint = Endpoint::from_shared(endpoint_uri(config))
        .map_err(|source| transport_error(config, source))?
        .http2_keep_alive_interval(KEEPALIVE_INTERVAL)
        .keep_alive_timeout(KEEPALIVE_TIMEOUT)
        .keep_alive_while_idle(true)
        .connect_timeout(CONNECT_TIMEOUT);
    let endpoint = with_tls(endpoint, config)?;

    let interceptor = AuthInterceptor::new(config.token())?;
    Ok(InterceptedService::new(
        endpoint.connect_lazy(),
        interceptor,
    ))
}

fn transport_error(config: &ClientConfig, source: tonic::transport::Error) -> Error {
    Error::Transport {
        address: config.host_port().to_string(),
        source,
    }
}

/// Applies the TLS strategy to `endpoint`, when this build can.
#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
fn with_tls(endpoint: Endpoint, config: &ClientConfig) -> Result<Endpoint> {
    match tls_config(config)? {
        Some(tls) => endpoint
            .tls_config(tls)
            .map_err(|source| transport_error(config, source)),
        None => Ok(endpoint),
    }
}

/// Without a crypto provider there is no TLS to apply: plaintext passes
/// through and anything else is a configuration error.
#[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc")))]
fn with_tls(endpoint: Endpoint, config: &ClientConfig) -> Result<Endpoint> {
    match config.tls_strategy() {
        TlsStrategy::None => Ok(endpoint),
        TlsStrategy::Tls | TlsStrategy::Mtls => Err(Error::Config(
            "this hatchet-client was built without a TLS feature; enable the `tls-ring` or \
             `tls-aws-lc` feature, or set HATCHET_CLIENT_TLS_STRATEGY=none"
                .to_string(),
        )),
    }
}

fn endpoint_uri(config: &ClientConfig) -> String {
    let authority = strip_scheme(config.host_port());
    let scheme = match config.tls_strategy() {
        TlsStrategy::None => "http",
        TlsStrategy::Tls | TlsStrategy::Mtls => "https",
    };
    format!("{scheme}://{authority}")
}

/// Warns (without ever including the token) when `host_port` carries an
/// explicit scheme that contradicts the resolved TLS strategy, since that
/// scheme is silently overridden by [`endpoint_uri`].
fn warn_on_scheme_mismatch(config: &ClientConfig) {
    let host_port = config.host_port();
    let Some((scheme, _)) = host_port.split_once("://") else {
        return;
    };
    let contradicts = match config.tls_strategy() {
        TlsStrategy::None => scheme.eq_ignore_ascii_case("https"),
        TlsStrategy::Tls | TlsStrategy::Mtls => scheme.eq_ignore_ascii_case("http"),
    };
    if contradicts {
        tracing::warn!(
            scheme,
            tls_strategy = ?config.tls_strategy(),
            "host_port's scheme contradicts the TLS strategy; the scheme is ignored"
        );
    }
}

#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
fn tls_config(config: &ClientConfig) -> Result<Option<ClientTlsConfig>> {
    if config.tls_strategy() == TlsStrategy::None {
        return Ok(None);
    }

    let mut tls = ClientTlsConfig::new().domain_name(config.tls_server_name());
    tls = match config.tls_root_ca_file() {
        Some(path) => tls.ca_certificate(Certificate::from_pem(read(path)?)),
        None => with_default_roots(tls)?,
    };

    if config.tls_strategy() == TlsStrategy::Mtls {
        let (Some(cert), Some(key)) = (config.tls_cert_file(), config.tls_key_file()) else {
            return Err(Error::Config(
                "mTLS needs a client certificate and key; set HATCHET_CLIENT_TLS_CERT_FILE and HATCHET_CLIENT_TLS_KEY_FILE".to_string(),
            ));
        };
        tls = tls.identity(Identity::from_pem(read(cert)?, read(key)?));
    }
    Ok(Some(tls))
}

/// The root store to verify the engine against when no CA file is given.
/// Native roots are preferred; webpki roots are the fallback.
#[cfg(all(
    any(feature = "tls-ring", feature = "tls-aws-lc"),
    feature = "tls-native-roots"
))]
fn with_default_roots(tls: ClientTlsConfig) -> Result<ClientTlsConfig> {
    Ok(tls.with_native_roots())
}

#[cfg(all(
    any(feature = "tls-ring", feature = "tls-aws-lc"),
    not(feature = "tls-native-roots"),
    feature = "tls-webpki-roots"
))]
fn with_default_roots(tls: ClientTlsConfig) -> Result<ClientTlsConfig> {
    Ok(tls.with_webpki_roots())
}

#[cfg(all(
    any(feature = "tls-ring", feature = "tls-aws-lc"),
    not(feature = "tls-native-roots"),
    not(feature = "tls-webpki-roots")
))]
fn with_default_roots(_tls: ClientTlsConfig) -> Result<ClientTlsConfig> {
    Err(Error::Config(
        "this hatchet-client was built without a TLS root store; enable the \
         `tls-native-roots` or `tls-webpki-roots` feature, or set \
         HATCHET_CLIENT_TLS_ROOT_CA_FILE"
            .to_string(),
    ))
}

#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
fn read(path: &Path) -> Result<Vec<u8>> {
    std::fs::read(path).map_err(|e| Error::Config(format!("reading {}: {e}", path.display())))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TlsStrategy;
    use tonic::service::Interceptor;

    /// `{"sub":"t","server_url":"http://localhost:8888","grpc_broadcast_address":"localhost:7077"}`
    const TOKEN: &str = "e30.eyJzdWIiOiJ0Iiwic2VydmVyX3VybCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODg4OCIsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyJ9.sig";

    fn config(strategy: TlsStrategy) -> crate::ClientBuilder {
        ClientConfig::builder().token(TOKEN).tls(strategy)
    }

    fn resolve(builder: crate::ClientBuilder) -> ClientConfig {
        builder.resolve(&|_| None).unwrap()
    }

    #[test]
    fn interceptor_adds_the_bearer_token() {
        let mut interceptor = AuthInterceptor::new("abc.def.ghi").unwrap();
        let request = interceptor.call(tonic::Request::new(())).unwrap();
        assert_eq!(
            request.metadata().get("authorization").unwrap(),
            "Bearer abc.def.ghi"
        );
    }

    #[test]
    fn a_token_that_cannot_be_a_header_is_a_config_error_without_the_token() {
        let err = AuthInterceptor::new("bad\ntoken").unwrap_err();
        assert!(matches!(err, Error::Config(_)), "{err:?}");
        assert!(!err.to_string().contains("bad"), "{err}");
    }

    #[test]
    fn scheme_follows_the_tls_strategy() {
        assert_eq!(
            endpoint_uri(&resolve(config(TlsStrategy::None))),
            "http://localhost:7077"
        );
        assert_eq!(
            endpoint_uri(&resolve(config(TlsStrategy::Tls))),
            "https://localhost:7077"
        );
        assert_eq!(
            endpoint_uri(&resolve(config(TlsStrategy::Mtls))),
            "https://localhost:7077"
        );
    }

    #[test]
    fn an_explicit_scheme_in_host_port_is_replaced() {
        let config = resolve(config(TlsStrategy::None).host_port("https://engine:7077"));
        assert_eq!(endpoint_uri(&config), "http://engine:7077");
    }

    #[tokio::test]
    async fn connect_is_lazy_and_succeeds_without_an_engine() {
        connect(&resolve(config(TlsStrategy::None))).unwrap();
    }

    /// Everything that names [`tls_config`], which exists only when a crypto
    /// provider is compiled in.
    #[cfg(any(feature = "tls-ring", feature = "tls-aws-lc"))]
    mod with_a_crypto_provider {
        use super::*;

        #[test]
        fn no_tls_config_for_plaintext() {
            assert!(
                tls_config(&resolve(config(TlsStrategy::None)))
                    .unwrap()
                    .is_none()
            );
        }

        #[cfg(feature = "tls-native-roots")]
        #[test]
        fn tls_uses_system_roots_when_no_ca_is_given() {
            let tls = tls_config(&resolve(config(TlsStrategy::Tls)))
                .unwrap()
                .unwrap();
            let debug = format!("{tls:?}");
            assert!(debug.contains("with_native_roots: true"), "{debug}");
            assert!(debug.contains(r#"domain: Some("localhost")"#), "{debug}");
        }

        #[cfg(all(not(feature = "tls-native-roots"), feature = "tls-webpki-roots"))]
        #[test]
        fn tls_falls_back_to_webpki_roots_when_no_ca_is_given() {
            let tls = tls_config(&resolve(config(TlsStrategy::Tls)))
                .unwrap()
                .unwrap();
            let debug = format!("{tls:?}");
            assert!(debug.contains("with_webpki_roots: true"), "{debug}");
            assert!(debug.contains(r#"domain: Some("localhost")"#), "{debug}");
        }

        #[cfg(not(any(feature = "tls-native-roots", feature = "tls-webpki-roots")))]
        #[test]
        fn without_a_roots_feature_tls_needs_a_ca_file() {
            let err = tls_config(&resolve(config(TlsStrategy::Tls))).unwrap_err();
            assert!(matches!(err, Error::Config(_)), "{err:?}");
            assert!(err.to_string().contains("tls-native-roots"), "{err}");
            assert!(
                err.to_string().contains("HATCHET_CLIENT_TLS_ROOT_CA_FILE"),
                "{err}"
            );
        }

        /// The roots are resolved before the client identity, so this needs a
        /// build that has some default root store.
        #[cfg(any(feature = "tls-native-roots", feature = "tls-webpki-roots"))]
        #[test]
        fn mtls_without_a_client_certificate_is_a_config_error() {
            let err = tls_config(&resolve(config(TlsStrategy::Mtls))).unwrap_err();
            assert!(matches!(err, Error::Config(_)), "{err:?}");
            assert!(
                err.to_string().contains("HATCHET_CLIENT_TLS_CERT_FILE"),
                "{err}"
            );
        }

        #[test]
        fn an_unreadable_ca_file_is_a_config_error_naming_the_file() {
            let config = resolve(config(TlsStrategy::Tls).tls_root_ca_file("/nonexistent/ca.pem"));
            let err = tls_config(&config).unwrap_err();
            assert!(err.to_string().contains("/nonexistent/ca.pem"), "{err}");
        }
    }

    /// A build with no crypto provider still connects in plaintext, and says
    /// why it cannot do TLS.
    #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc")))]
    mod without_a_crypto_provider {
        use super::*;

        #[test]
        fn tls_is_a_config_error_naming_the_features() {
            for strategy in [TlsStrategy::Tls, TlsStrategy::Mtls] {
                let err = connect(&resolve(config(strategy))).unwrap_err();
                assert!(matches!(err, Error::Config(_)), "{err:?}");
                assert!(err.to_string().contains("tls-ring"), "{err}");
                assert!(err.to_string().contains("tls-aws-lc"), "{err}");
            }
        }
    }
}