pub(crate) mod namespace;
mod token;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use crate::{Error, Result};
const ENV_TOKEN: &str = "HATCHET_CLIENT_TOKEN";
const ENV_HOST_PORT: &str = "HATCHET_CLIENT_HOST_PORT";
const ENV_SERVER_URL: &str = "HATCHET_CLIENT_SERVER_URL";
const ENV_TENANT_ID: &str = "HATCHET_CLIENT_TENANT_ID";
const ENV_NAMESPACE: &str = "HATCHET_CLIENT_NAMESPACE";
const ENV_TLS_STRATEGY: &str = "HATCHET_CLIENT_TLS_STRATEGY";
const ENV_TLS_CERT_FILE: &str = "HATCHET_CLIENT_TLS_CERT_FILE";
const ENV_TLS_KEY_FILE: &str = "HATCHET_CLIENT_TLS_KEY_FILE";
const ENV_TLS_ROOT_CA_FILE: &str = "HATCHET_CLIENT_TLS_ROOT_CA_FILE";
const ENV_TLS_SERVER_NAME: &str = "HATCHET_CLIENT_TLS_SERVER_NAME";
const ENV_DISABLE_GZIP: &str = "HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TlsStrategy {
None,
#[default]
Tls,
Mtls,
}
impl FromStr for TlsStrategy {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value.to_ascii_lowercase().as_str() {
"none" => Ok(Self::None),
"tls" => Ok(Self::Tls),
"mtls" => Ok(Self::Mtls),
_ => Err(Error::Config(format!(
"unknown TLS strategy {value:?}; expected none, tls, or mtls"
))),
}
}
}
#[derive(Clone)]
pub struct ClientConfig {
token: String,
tenant_id: String,
host_port: String,
server_url: String,
namespace: String,
tls_strategy: TlsStrategy,
tls_cert_file: Option<PathBuf>,
tls_key_file: Option<PathBuf>,
tls_root_ca_file: Option<PathBuf>,
tls_server_name: String,
gzip: bool,
}
impl fmt::Debug for ClientConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientConfig")
.field("token", &"<redacted>")
.field("tenant_id", &self.tenant_id)
.field("host_port", &self.host_port)
.field("server_url", &self.server_url)
.field("namespace", &self.namespace)
.field("tls_strategy", &self.tls_strategy)
.field("tls_cert_file", &self.tls_cert_file)
.field("tls_key_file", &self.tls_key_file)
.field("tls_root_ca_file", &self.tls_root_ca_file)
.field("tls_server_name", &self.tls_server_name)
.field("gzip", &self.gzip)
.finish()
}
}
impl ClientConfig {
pub fn builder() -> ClientBuilder {
ClientBuilder::default()
}
pub fn from_env() -> Result<Self> {
Self::builder().build_config()
}
pub fn token(&self) -> &str {
&self.token
}
pub fn tenant_id(&self) -> &str {
&self.tenant_id
}
pub fn host_port(&self) -> &str {
&self.host_port
}
pub fn server_url(&self) -> &str {
&self.server_url
}
pub fn namespace(&self) -> &str {
&self.namespace
}
pub fn tls_strategy(&self) -> TlsStrategy {
self.tls_strategy
}
pub fn tls_cert_file(&self) -> Option<&Path> {
self.tls_cert_file.as_deref()
}
pub fn tls_key_file(&self) -> Option<&Path> {
self.tls_key_file.as_deref()
}
pub fn tls_root_ca_file(&self) -> Option<&Path> {
self.tls_root_ca_file.as_deref()
}
pub fn tls_server_name(&self) -> &str {
&self.tls_server_name
}
pub fn gzip(&self) -> bool {
self.gzip
}
pub fn apply_namespace(&self, name: &str) -> String {
namespace::apply(&self.namespace, name)
}
}
#[derive(Clone, Default)]
#[must_use = "a client builder configures nothing until `build` is called"]
pub struct ClientBuilder {
token: Option<String>,
host_port: Option<String>,
server_url: Option<String>,
tenant_id: Option<String>,
namespace: Option<String>,
tls_strategy: Option<TlsStrategy>,
tls_cert_file: Option<PathBuf>,
tls_key_file: Option<PathBuf>,
tls_root_ca_file: Option<PathBuf>,
tls_server_name: Option<String>,
gzip: Option<bool>,
}
impl ClientBuilder {
pub fn token(mut self, token: impl Into<String>) -> Self {
self.token = Some(token.into());
self
}
pub fn host_port(mut self, host_port: impl Into<String>) -> Self {
self.host_port = Some(host_port.into());
self
}
pub fn server_url(mut self, server_url: impl Into<String>) -> Self {
self.server_url = Some(server_url.into());
self
}
pub fn tenant_id(mut self, tenant_id: impl Into<String>) -> Self {
self.tenant_id = Some(tenant_id.into());
self
}
pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
self.namespace = Some(namespace.into());
self
}
pub fn tls(mut self, strategy: TlsStrategy) -> Self {
self.tls_strategy = Some(strategy);
self
}
pub fn tls_cert_file(mut self, path: impl Into<PathBuf>) -> Self {
self.tls_cert_file = Some(path.into());
self
}
pub fn tls_key_file(mut self, path: impl Into<PathBuf>) -> Self {
self.tls_key_file = Some(path.into());
self
}
pub fn tls_root_ca_file(mut self, path: impl Into<PathBuf>) -> Self {
self.tls_root_ca_file = Some(path.into());
self
}
pub fn tls_server_name(mut self, name: impl Into<String>) -> Self {
self.tls_server_name = Some(name.into());
self
}
pub fn gzip(mut self, enabled: bool) -> Self {
self.gzip = Some(enabled);
self
}
pub fn build_config(self) -> Result<ClientConfig> {
self.resolve(&|key| std::env::var(key).ok())
}
pub fn build(self) -> Result<crate::Client> {
crate::Client::new(self.build_config()?)
}
pub(crate) fn resolve(self, env: &dyn Fn(&str) -> Option<String>) -> Result<ClientConfig> {
let env = |key: &str| env(key).filter(|value| !value.is_empty());
let token = self.token.or_else(|| env(ENV_TOKEN)).ok_or_else(|| {
Error::Config(format!(
"an API token is required; set {ENV_TOKEN} or call `.token(..)`"
))
})?;
let claims = token::decode_claims(&token)?;
let missing = |claim: &str, variable: &str| {
Error::InvalidToken(format!("the token has no `{claim}` claim; set {variable}"))
};
let host_port = self
.host_port
.or_else(|| env(ENV_HOST_PORT))
.or(claims.grpc_broadcast_address)
.ok_or_else(|| missing("grpc_broadcast_address", ENV_HOST_PORT))?;
let server_url = self
.server_url
.or_else(|| env(ENV_SERVER_URL))
.or(claims.server_url)
.ok_or_else(|| missing("server_url", ENV_SERVER_URL))?;
let tenant_id = self
.tenant_id
.or_else(|| env(ENV_TENANT_ID))
.or(claims.sub)
.ok_or_else(|| missing("sub", ENV_TENANT_ID))?;
let tls_strategy = match self.tls_strategy {
Some(strategy) => strategy,
None => env(ENV_TLS_STRATEGY)
.map(|s| s.parse())
.transpose()?
.unwrap_or_default(),
};
let tls_server_name = self
.tls_server_name
.or_else(|| env(ENV_TLS_SERVER_NAME))
.unwrap_or_else(|| host_of(&host_port).to_string());
let path = |explicit: Option<PathBuf>, variable: &str| {
explicit.or_else(|| env(variable).map(PathBuf::from))
};
let gzip = match self.gzip {
Some(enabled) => enabled,
None => match env(ENV_DISABLE_GZIP) {
Some(value) => !parse_bool(&value, ENV_DISABLE_GZIP)?,
None => true,
},
};
Ok(ClientConfig {
namespace: namespace::normalize(
&self
.namespace
.or_else(|| env(ENV_NAMESPACE))
.unwrap_or_default(),
),
tls_cert_file: path(self.tls_cert_file, ENV_TLS_CERT_FILE),
tls_key_file: path(self.tls_key_file, ENV_TLS_KEY_FILE),
tls_root_ca_file: path(self.tls_root_ca_file, ENV_TLS_ROOT_CA_FILE),
token,
tenant_id,
host_port,
server_url,
tls_strategy,
tls_server_name,
gzip,
})
}
}
fn parse_bool(value: &str, variable: &str) -> Result<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Ok(true),
"false" | "0" | "no" | "off" => Ok(false),
_ => Err(Error::Config(format!(
"{variable} is {value:?}; expected true or false"
))),
}
}
pub(crate) fn strip_scheme(host_port: &str) -> &str {
host_port
.split_once("://")
.map_or(host_port, |(_, rest)| rest)
}
fn host_of(host_port: &str) -> &str {
let without_scheme = strip_scheme(host_port);
if let Some(rest) = without_scheme.strip_prefix('[')
&& let Some(end) = rest.find(']')
{
return &rest[..end];
}
without_scheme
.rsplit_once(':')
.map_or(without_scheme, |(host, _)| host)
}
#[cfg(test)]
mod tests {
use super::token::tests::{full_token, token_with};
use super::*;
use std::collections::HashMap;
fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
move |key| map.get(key).cloned()
}
fn no_env(_: &str) -> Option<String> {
None
}
#[test]
fn token_claims_fill_tenant_server_url_and_grpc_address() {
let config = ClientConfig::builder()
.token(full_token())
.resolve(&no_env)
.unwrap();
assert_eq!(config.tenant_id(), "707d0855-80ab-4e1f-a156-f1c4546cbf52");
assert_eq!(config.server_url(), "https://hatchet.example.com");
assert_eq!(config.host_port(), "grpc.example.com:443");
assert_eq!(config.namespace(), "");
assert_eq!(config.tls_strategy(), TlsStrategy::Tls);
assert_eq!(config.tls_server_name(), "grpc.example.com");
}
#[test]
fn token_comes_from_the_environment_when_not_explicit() {
let token = full_token();
let env = env_of(&[("HATCHET_CLIENT_TOKEN", &token)]);
let config = ClientConfig::builder().resolve(&env).unwrap();
assert_eq!(config.token(), token);
}
#[test]
fn environment_overrides_claims() {
let env = env_of(&[
("HATCHET_CLIENT_HOST_PORT", "localhost:7077"),
("HATCHET_CLIENT_SERVER_URL", "http://localhost:8888"),
("HATCHET_CLIENT_TENANT_ID", "env-tenant"),
("HATCHET_CLIENT_NAMESPACE", "Dev"),
("HATCHET_CLIENT_TLS_STRATEGY", "none"),
("HATCHET_CLIENT_TLS_SERVER_NAME", "engine.internal"),
]);
let config = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap();
assert_eq!(config.host_port(), "localhost:7077");
assert_eq!(config.server_url(), "http://localhost:8888");
assert_eq!(config.tenant_id(), "env-tenant");
assert_eq!(config.namespace(), "dev_");
assert_eq!(config.tls_strategy(), TlsStrategy::None);
assert_eq!(config.tls_server_name(), "engine.internal");
}
#[test]
fn explicit_settings_override_the_environment() {
let env = env_of(&[
("HATCHET_CLIENT_TOKEN", "env.token.ignored"),
("HATCHET_CLIENT_HOST_PORT", "env-host:1"),
("HATCHET_CLIENT_NAMESPACE", "env"),
("HATCHET_CLIENT_TLS_STRATEGY", "mtls"),
]);
let config = ClientConfig::builder()
.token(full_token())
.host_port("explicit-host:2")
.namespace("Explicit")
.tls(TlsStrategy::None)
.resolve(&env)
.unwrap();
assert_eq!(config.host_port(), "explicit-host:2");
assert_eq!(config.namespace(), "explicit_");
assert_eq!(config.tls_strategy(), TlsStrategy::None);
assert_eq!(config.tls_server_name(), "explicit-host");
}
#[test]
fn empty_environment_values_count_as_unset() {
let env = env_of(&[
("HATCHET_CLIENT_HOST_PORT", ""),
("HATCHET_CLIENT_NAMESPACE", ""),
]);
let config = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap();
assert_eq!(config.host_port(), "grpc.example.com:443");
assert_eq!(config.namespace(), "");
}
#[test]
fn a_missing_token_is_a_config_error_naming_the_variable() {
let err = ClientConfig::builder().resolve(&no_env).unwrap_err();
assert!(matches!(err, Error::Config(_)), "{err:?}");
assert!(err.to_string().contains("HATCHET_CLIENT_TOKEN"), "{err}");
}
#[test]
fn a_claim_missing_everywhere_is_an_error_naming_it() {
let token = token_with(serde_json::json!({"sub": "tenant"}));
let err = ClientConfig::builder()
.token(token)
.resolve(&no_env)
.unwrap_err();
assert!(matches!(err, Error::InvalidToken(_)), "{err:?}");
assert!(err.to_string().contains("grpc_broadcast_address"), "{err}");
assert!(
err.to_string().contains("HATCHET_CLIENT_HOST_PORT"),
"{err}"
);
}
#[test]
fn a_missing_claim_is_fine_when_supplied_another_way() {
let token = token_with(serde_json::json!({"sub": "tenant"}));
let config = ClientConfig::builder()
.token(token)
.host_port("localhost:7077")
.server_url("http://localhost:8888")
.resolve(&no_env)
.unwrap();
assert_eq!(config.tenant_id(), "tenant");
}
#[test]
fn unknown_tls_strategy_is_a_config_error() {
let env = env_of(&[("HATCHET_CLIENT_TLS_STRATEGY", "ssl")]);
let err = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap_err();
assert!(err.to_string().contains("ssl"), "{err}");
}
#[test]
fn tls_files_come_from_the_environment() {
let env = env_of(&[
("HATCHET_CLIENT_TLS_CERT_FILE", "/certs/client.pem"),
("HATCHET_CLIENT_TLS_KEY_FILE", "/certs/client.key"),
("HATCHET_CLIENT_TLS_ROOT_CA_FILE", "/certs/ca.pem"),
]);
let config = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap();
assert_eq!(config.tls_cert_file(), Some(Path::new("/certs/client.pem")));
assert_eq!(config.tls_key_file(), Some(Path::new("/certs/client.key")));
assert_eq!(config.tls_root_ca_file(), Some(Path::new("/certs/ca.pem")));
}
#[test]
fn host_of_strips_scheme_port_and_ipv6_brackets() {
assert_eq!(host_of("engine.example.com:7077"), "engine.example.com");
assert_eq!(host_of("localhost"), "localhost");
assert_eq!(host_of("[::1]:7077"), "::1");
assert_eq!(host_of("https://[2001:db8::1]:443"), "2001:db8::1");
}
#[test]
fn server_name_defaults_to_the_host_without_port_or_scheme() {
let config = ClientConfig::builder()
.token(full_token())
.host_port("https://engine.example.com:7077")
.resolve(&no_env)
.unwrap();
assert_eq!(config.tls_server_name(), "engine.example.com");
}
#[test]
fn apply_namespace_uses_the_configured_namespace() {
let config = ClientConfig::builder()
.token(full_token())
.namespace("Dev")
.resolve(&no_env)
.unwrap();
assert_eq!(config.apply_namespace("agent-run"), "dev_agent-run");
assert_eq!(config.apply_namespace("dev_agent-run"), "dev_agent-run");
}
#[test]
fn gzip_is_on_by_default() {
let config = ClientConfig::builder()
.token(full_token())
.resolve(&no_env)
.unwrap();
assert!(config.gzip());
}
#[test]
fn the_environment_can_turn_gzip_off() {
for value in ["true", "TRUE", "1", "yes", "on"] {
let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
let config = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap();
assert!(!config.gzip(), "{value}");
}
for value in ["false", "0", "no", "off"] {
let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
let config = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap();
assert!(config.gzip(), "{value}");
}
}
#[test]
fn an_explicit_gzip_setting_overrides_the_environment() {
let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "true")]);
let config = ClientConfig::builder()
.token(full_token())
.gzip(true)
.resolve(&env)
.unwrap();
assert!(config.gzip());
}
#[test]
fn an_unparseable_gzip_value_is_a_config_error_naming_the_variable() {
let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "maybe")]);
let err = ClientConfig::builder()
.token(full_token())
.resolve(&env)
.unwrap_err();
assert!(matches!(err, Error::Config(_)), "{err:?}");
assert!(
err.to_string()
.contains("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION"),
"{err}"
);
assert!(err.to_string().contains("maybe"), "{err}");
}
#[test]
fn debug_output_shows_the_gzip_setting() {
let config = ClientConfig::builder()
.token(full_token())
.gzip(false)
.resolve(&no_env)
.unwrap();
assert!(format!("{config:?}").contains("gzip"), "{config:?}");
}
#[test]
fn debug_output_redacts_the_token() {
let token = full_token();
let config = ClientConfig::builder()
.token(token.clone())
.resolve(&no_env)
.unwrap();
let debug = format!("{config:?}");
assert!(!debug.contains(&token), "{debug}");
assert!(debug.contains("redacted"), "{debug}");
}
}