Skip to main content

hatchet_client/config/
mod.rs

1//! Client configuration: explicit settings > `HATCHET_CLIENT_*` environment
2//! variables > claims inside the API token.
3
4pub(crate) mod namespace;
5mod token;
6
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10
11use crate::{Error, Result};
12
13const ENV_TOKEN: &str = "HATCHET_CLIENT_TOKEN";
14const ENV_HOST_PORT: &str = "HATCHET_CLIENT_HOST_PORT";
15const ENV_SERVER_URL: &str = "HATCHET_CLIENT_SERVER_URL";
16const ENV_TENANT_ID: &str = "HATCHET_CLIENT_TENANT_ID";
17const ENV_NAMESPACE: &str = "HATCHET_CLIENT_NAMESPACE";
18const ENV_TLS_STRATEGY: &str = "HATCHET_CLIENT_TLS_STRATEGY";
19const ENV_TLS_CERT_FILE: &str = "HATCHET_CLIENT_TLS_CERT_FILE";
20const ENV_TLS_KEY_FILE: &str = "HATCHET_CLIENT_TLS_KEY_FILE";
21const ENV_TLS_ROOT_CA_FILE: &str = "HATCHET_CLIENT_TLS_ROOT_CA_FILE";
22const ENV_TLS_SERVER_NAME: &str = "HATCHET_CLIENT_TLS_SERVER_NAME";
23const ENV_DISABLE_GZIP: &str = "HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION";
24
25/// How the gRPC connection is secured.
26///
27/// [`Tls`](TlsStrategy::Tls) and [`Mtls`](TlsStrategy::Mtls) need TLS
28/// compiled in: a rustls crypto provider (`tls-ring`, on by default, or
29/// `tls-aws-lc`) and a root store (`tls-native-roots`, on by default, or
30/// `tls-webpki-roots`) — unless `HATCHET_CLIENT_TLS_ROOT_CA_FILE` supplies
31/// the roots. A build missing either fails at [`Client::new`](crate::Client::new)
32/// with an [`Error::Config`] naming the feature to enable;
33/// [`None`](TlsStrategy::None) still works there.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum TlsStrategy {
36    /// Plaintext. For local development against `hatchet-lite`, which speaks
37    /// plaintext gRPC. Needs no `tls-*` feature.
38    None,
39    /// TLS with server verification (the default). Needs a crypto provider
40    /// feature, and a root store feature or a root CA file.
41    #[default]
42    Tls,
43    /// TLS with a client certificate: [`Tls`](TlsStrategy::Tls) plus
44    /// `HATCHET_CLIENT_TLS_CERT_FILE` and `HATCHET_CLIENT_TLS_KEY_FILE`,
45    /// without which [`Client::new`](crate::Client::new) fails.
46    Mtls,
47}
48
49impl FromStr for TlsStrategy {
50    type Err = Error;
51
52    fn from_str(value: &str) -> Result<Self> {
53        match value.to_ascii_lowercase().as_str() {
54            "none" => Ok(Self::None),
55            "tls" => Ok(Self::Tls),
56            "mtls" => Ok(Self::Mtls),
57            _ => Err(Error::Config(format!(
58                "unknown TLS strategy {value:?}; expected none, tls, or mtls"
59            ))),
60        }
61    }
62}
63
64/// Resolved, immutable client configuration.
65#[derive(Clone)]
66pub struct ClientConfig {
67    token: String,
68    tenant_id: String,
69    host_port: String,
70    server_url: String,
71    namespace: String,
72    tls_strategy: TlsStrategy,
73    tls_cert_file: Option<PathBuf>,
74    tls_key_file: Option<PathBuf>,
75    tls_root_ca_file: Option<PathBuf>,
76    tls_server_name: String,
77    gzip: bool,
78}
79
80impl fmt::Debug for ClientConfig {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.debug_struct("ClientConfig")
83            .field("token", &"<redacted>")
84            .field("tenant_id", &self.tenant_id)
85            .field("host_port", &self.host_port)
86            .field("server_url", &self.server_url)
87            .field("namespace", &self.namespace)
88            .field("tls_strategy", &self.tls_strategy)
89            .field("tls_cert_file", &self.tls_cert_file)
90            .field("tls_key_file", &self.tls_key_file)
91            .field("tls_root_ca_file", &self.tls_root_ca_file)
92            .field("tls_server_name", &self.tls_server_name)
93            .field("gzip", &self.gzip)
94            .finish()
95    }
96}
97
98impl ClientConfig {
99    /// Starts a configuration with nothing set explicitly.
100    pub fn builder() -> ClientBuilder {
101        ClientBuilder::default()
102    }
103
104    /// Resolves the configuration from `HATCHET_CLIENT_*` variables alone.
105    ///
106    /// # Errors
107    ///
108    /// The same as [`ClientBuilder::build_config`], which this is the
109    /// no-explicit-settings case of.
110    pub fn from_env() -> Result<Self> {
111        Self::builder().build_config()
112    }
113
114    /// The API token. Treat it as a secret.
115    pub fn token(&self) -> &str {
116        &self.token
117    }
118
119    /// The tenant the token belongs to.
120    pub fn tenant_id(&self) -> &str {
121        &self.tenant_id
122    }
123
124    /// The engine's gRPC address, `host:port`.
125    pub fn host_port(&self) -> &str {
126        &self.host_port
127    }
128
129    /// The engine's REST/UI base URL.
130    pub fn server_url(&self) -> &str {
131        &self.server_url
132    }
133
134    /// The normalised namespace prefix (`"dev_"`), or `""` when unset.
135    pub fn namespace(&self) -> &str {
136        &self.namespace
137    }
138
139    /// How the connection is secured.
140    pub fn tls_strategy(&self) -> TlsStrategy {
141        self.tls_strategy
142    }
143
144    /// Client certificate for mTLS.
145    pub fn tls_cert_file(&self) -> Option<&Path> {
146        self.tls_cert_file.as_deref()
147    }
148
149    /// Client key for mTLS.
150    pub fn tls_key_file(&self) -> Option<&Path> {
151        self.tls_key_file.as_deref()
152    }
153
154    /// Root CA to trust instead of the system roots.
155    pub fn tls_root_ca_file(&self) -> Option<&Path> {
156        self.tls_root_ca_file.as_deref()
157    }
158
159    /// The name the server certificate is verified against.
160    pub fn tls_server_name(&self) -> &str {
161        &self.tls_server_name
162    }
163
164    /// Whether requests are sent gzip-compressed. Responses are always
165    /// accepted compressed, whatever this says.
166    pub fn gzip(&self) -> bool {
167        self.gzip
168    }
169
170    /// Prefixes a workflow name, event key, or run name with the namespace,
171    /// unless it already carries it. Never apply this to cron expressions.
172    pub fn apply_namespace(&self, name: &str) -> String {
173        namespace::apply(&self.namespace, name)
174    }
175}
176
177/// Builds a [`ClientConfig`]. Anything not set here falls back to the
178/// `HATCHET_CLIENT_*` environment variable, then to the token's claims. An
179/// environment variable set to the empty string counts as unset.
180///
181/// ```no_run
182/// # use hatchet_client::{Client, TlsStrategy};
183/// # fn example(token: String) -> hatchet_client::Result<()> {
184/// // Everything explicit: a local hatchet-lite, which speaks plaintext.
185/// let client = Client::builder()
186///     .token(token)
187///     .host_port("localhost:7077")
188///     .namespace("dev")
189///     .tls(TlsStrategy::None)
190///     .build()?;
191/// assert_eq!(client.config().namespace(), "dev_");
192/// # Ok(())
193/// # }
194/// ```
195#[derive(Clone, Default)]
196#[must_use = "a client builder configures nothing until `build` is called"]
197pub struct ClientBuilder {
198    token: Option<String>,
199    host_port: Option<String>,
200    server_url: Option<String>,
201    tenant_id: Option<String>,
202    namespace: Option<String>,
203    tls_strategy: Option<TlsStrategy>,
204    tls_cert_file: Option<PathBuf>,
205    tls_key_file: Option<PathBuf>,
206    tls_root_ca_file: Option<PathBuf>,
207    tls_server_name: Option<String>,
208    gzip: Option<bool>,
209}
210
211impl ClientBuilder {
212    /// The API token (`HATCHET_CLIENT_TOKEN`).
213    pub fn token(mut self, token: impl Into<String>) -> Self {
214        self.token = Some(token.into());
215        self
216    }
217
218    /// The engine's gRPC `host:port` (`HATCHET_CLIENT_HOST_PORT`).
219    pub fn host_port(mut self, host_port: impl Into<String>) -> Self {
220        self.host_port = Some(host_port.into());
221        self
222    }
223
224    /// The engine's REST base URL (`HATCHET_CLIENT_SERVER_URL`).
225    pub fn server_url(mut self, server_url: impl Into<String>) -> Self {
226        self.server_url = Some(server_url.into());
227        self
228    }
229
230    /// The tenant ID (`HATCHET_CLIENT_TENANT_ID`).
231    pub fn tenant_id(mut self, tenant_id: impl Into<String>) -> Self {
232        self.tenant_id = Some(tenant_id.into());
233        self
234    }
235
236    /// The namespace (`HATCHET_CLIENT_NAMESPACE`); normalised to `lowercase_`.
237    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
238        self.namespace = Some(namespace.into());
239        self
240    }
241
242    /// The TLS strategy (`HATCHET_CLIENT_TLS_STRATEGY`, default `tls`).
243    pub fn tls(mut self, strategy: TlsStrategy) -> Self {
244        self.tls_strategy = Some(strategy);
245        self
246    }
247
248    /// Client certificate for mTLS (`HATCHET_CLIENT_TLS_CERT_FILE`).
249    pub fn tls_cert_file(mut self, path: impl Into<PathBuf>) -> Self {
250        self.tls_cert_file = Some(path.into());
251        self
252    }
253
254    /// Client key for mTLS (`HATCHET_CLIENT_TLS_KEY_FILE`).
255    pub fn tls_key_file(mut self, path: impl Into<PathBuf>) -> Self {
256        self.tls_key_file = Some(path.into());
257        self
258    }
259
260    /// Root CA to trust (`HATCHET_CLIENT_TLS_ROOT_CA_FILE`).
261    pub fn tls_root_ca_file(mut self, path: impl Into<PathBuf>) -> Self {
262        self.tls_root_ca_file = Some(path.into());
263        self
264    }
265
266    /// Name to verify the server certificate against
267    /// (`HATCHET_CLIENT_TLS_SERVER_NAME`, default: the host of `host_port`).
268    pub fn tls_server_name(mut self, name: impl Into<String>) -> Self {
269        self.tls_server_name = Some(name.into());
270        self
271    }
272
273    /// Whether to gzip outgoing requests (`HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION`
274    /// — note the negation — default: on).
275    ///
276    /// Turning it off stops this client *sending* compressed requests; it
277    /// still accepts compressed responses, which is exactly what the official
278    /// Go SDK's `DisableGzipCompression` does. **The official SDKs have no
279    /// environment variable for this at all** — the name above is this SDK's
280    /// own, chosen to match Go's configuration field.
281    pub fn gzip(mut self, enabled: bool) -> Self {
282        self.gzip = Some(enabled);
283        self
284    }
285
286    /// Resolves the configuration against the process environment.
287    ///
288    /// # Errors
289    ///
290    /// [`Error::Config`] when no token was given and `HATCHET_CLIENT_TOKEN` is
291    /// unset, or when `HATCHET_CLIENT_TLS_STRATEGY` is not `none`, `tls` or
292    /// `mtls`; [`Error::InvalidToken`] when the token is not a JWT whose
293    /// payload decodes, or when a setting has neither an explicit value, an
294    /// environment variable, nor the claim it falls back to (`host_port` ←
295    /// `grpc_broadcast_address`, `server_url` ← `server_url`, `tenant_id` ←
296    /// `sub`).
297    pub fn build_config(self) -> Result<ClientConfig> {
298        self.resolve(&|key| std::env::var(key).ok())
299    }
300
301    /// Resolves the configuration and creates a [`Client`](crate::Client).
302    ///
303    /// # Errors
304    ///
305    /// Those of [`build_config`](ClientBuilder::build_config) and
306    /// [`Client::new`](crate::Client::new).
307    ///
308    /// # Panics
309    ///
310    /// Panics if called outside a tokio runtime.
311    pub fn build(self) -> Result<crate::Client> {
312        crate::Client::new(self.build_config()?)
313    }
314
315    /// Resolves with an injected environment lookup (tests pass a map).
316    pub(crate) fn resolve(self, env: &dyn Fn(&str) -> Option<String>) -> Result<ClientConfig> {
317        let env = |key: &str| env(key).filter(|value| !value.is_empty());
318
319        let token = self.token.or_else(|| env(ENV_TOKEN)).ok_or_else(|| {
320            Error::Config(format!(
321                "an API token is required; set {ENV_TOKEN} or call `.token(..)`"
322            ))
323        })?;
324        let claims = token::decode_claims(&token)?;
325
326        let missing = |claim: &str, variable: &str| {
327            Error::InvalidToken(format!("the token has no `{claim}` claim; set {variable}"))
328        };
329        let host_port = self
330            .host_port
331            .or_else(|| env(ENV_HOST_PORT))
332            .or(claims.grpc_broadcast_address)
333            .ok_or_else(|| missing("grpc_broadcast_address", ENV_HOST_PORT))?;
334        let server_url = self
335            .server_url
336            .or_else(|| env(ENV_SERVER_URL))
337            .or(claims.server_url)
338            .ok_or_else(|| missing("server_url", ENV_SERVER_URL))?;
339        let tenant_id = self
340            .tenant_id
341            .or_else(|| env(ENV_TENANT_ID))
342            .or(claims.sub)
343            .ok_or_else(|| missing("sub", ENV_TENANT_ID))?;
344
345        let tls_strategy = match self.tls_strategy {
346            Some(strategy) => strategy,
347            None => env(ENV_TLS_STRATEGY)
348                .map(|s| s.parse())
349                .transpose()?
350                .unwrap_or_default(),
351        };
352        let tls_server_name = self
353            .tls_server_name
354            .or_else(|| env(ENV_TLS_SERVER_NAME))
355            .unwrap_or_else(|| host_of(&host_port).to_string());
356        let path = |explicit: Option<PathBuf>, variable: &str| {
357            explicit.or_else(|| env(variable).map(PathBuf::from))
358        };
359        let gzip = match self.gzip {
360            Some(enabled) => enabled,
361            None => match env(ENV_DISABLE_GZIP) {
362                Some(value) => !parse_bool(&value, ENV_DISABLE_GZIP)?,
363                None => true,
364            },
365        };
366
367        Ok(ClientConfig {
368            namespace: namespace::normalize(
369                &self
370                    .namespace
371                    .or_else(|| env(ENV_NAMESPACE))
372                    .unwrap_or_default(),
373            ),
374            tls_cert_file: path(self.tls_cert_file, ENV_TLS_CERT_FILE),
375            tls_key_file: path(self.tls_key_file, ENV_TLS_KEY_FILE),
376            tls_root_ca_file: path(self.tls_root_ca_file, ENV_TLS_ROOT_CA_FILE),
377            token,
378            tenant_id,
379            host_port,
380            server_url,
381            tls_strategy,
382            tls_server_name,
383            gzip,
384        })
385    }
386}
387
388/// The boolean spellings this SDK accepts in an environment variable.
389/// Deliberately narrow: a typo must be an error, not a silent `false`.
390fn parse_bool(value: &str, variable: &str) -> Result<bool> {
391    match value.trim().to_ascii_lowercase().as_str() {
392        "true" | "1" | "yes" | "on" => Ok(true),
393        "false" | "0" | "no" | "off" => Ok(false),
394        _ => Err(Error::Config(format!(
395            "{variable} is {value:?}; expected true or false"
396        ))),
397    }
398}
399
400/// Strips a leading `scheme://`, if any: `"https://engine.example.com:7077"`
401/// → `"engine.example.com:7077"`; `"engine.example.com:7077"` unchanged.
402pub(crate) fn strip_scheme(host_port: &str) -> &str {
403    host_port
404        .split_once("://")
405        .map_or(host_port, |(_, rest)| rest)
406}
407
408/// `"https://engine.example.com:7077"` → `"engine.example.com"`.
409/// Bracketed IPv6 literals keep their address without the brackets or port:
410/// `"[::1]:7077"` → `"::1"`.
411fn host_of(host_port: &str) -> &str {
412    let without_scheme = strip_scheme(host_port);
413    if let Some(rest) = without_scheme.strip_prefix('[')
414        && let Some(end) = rest.find(']')
415    {
416        return &rest[..end];
417    }
418    without_scheme
419        .rsplit_once(':')
420        .map_or(without_scheme, |(host, _)| host)
421}
422
423#[cfg(test)]
424mod tests {
425    use super::token::tests::{full_token, token_with};
426    use super::*;
427    use std::collections::HashMap;
428
429    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
430        let map: HashMap<String, String> = pairs
431            .iter()
432            .map(|(k, v)| (k.to_string(), v.to_string()))
433            .collect();
434        move |key| map.get(key).cloned()
435    }
436
437    fn no_env(_: &str) -> Option<String> {
438        None
439    }
440
441    #[test]
442    fn token_claims_fill_tenant_server_url_and_grpc_address() {
443        let config = ClientConfig::builder()
444            .token(full_token())
445            .resolve(&no_env)
446            .unwrap();
447        assert_eq!(config.tenant_id(), "707d0855-80ab-4e1f-a156-f1c4546cbf52");
448        assert_eq!(config.server_url(), "https://hatchet.example.com");
449        assert_eq!(config.host_port(), "grpc.example.com:443");
450        assert_eq!(config.namespace(), "");
451        assert_eq!(config.tls_strategy(), TlsStrategy::Tls);
452        assert_eq!(config.tls_server_name(), "grpc.example.com");
453    }
454
455    #[test]
456    fn token_comes_from_the_environment_when_not_explicit() {
457        let token = full_token();
458        let env = env_of(&[("HATCHET_CLIENT_TOKEN", &token)]);
459        let config = ClientConfig::builder().resolve(&env).unwrap();
460        assert_eq!(config.token(), token);
461    }
462
463    #[test]
464    fn environment_overrides_claims() {
465        let env = env_of(&[
466            ("HATCHET_CLIENT_HOST_PORT", "localhost:7077"),
467            ("HATCHET_CLIENT_SERVER_URL", "http://localhost:8888"),
468            ("HATCHET_CLIENT_TENANT_ID", "env-tenant"),
469            ("HATCHET_CLIENT_NAMESPACE", "Dev"),
470            ("HATCHET_CLIENT_TLS_STRATEGY", "none"),
471            ("HATCHET_CLIENT_TLS_SERVER_NAME", "engine.internal"),
472        ]);
473        let config = ClientConfig::builder()
474            .token(full_token())
475            .resolve(&env)
476            .unwrap();
477        assert_eq!(config.host_port(), "localhost:7077");
478        assert_eq!(config.server_url(), "http://localhost:8888");
479        assert_eq!(config.tenant_id(), "env-tenant");
480        assert_eq!(config.namespace(), "dev_");
481        assert_eq!(config.tls_strategy(), TlsStrategy::None);
482        assert_eq!(config.tls_server_name(), "engine.internal");
483    }
484
485    #[test]
486    fn explicit_settings_override_the_environment() {
487        let env = env_of(&[
488            ("HATCHET_CLIENT_TOKEN", "env.token.ignored"),
489            ("HATCHET_CLIENT_HOST_PORT", "env-host:1"),
490            ("HATCHET_CLIENT_NAMESPACE", "env"),
491            ("HATCHET_CLIENT_TLS_STRATEGY", "mtls"),
492        ]);
493        let config = ClientConfig::builder()
494            .token(full_token())
495            .host_port("explicit-host:2")
496            .namespace("Explicit")
497            .tls(TlsStrategy::None)
498            .resolve(&env)
499            .unwrap();
500        assert_eq!(config.host_port(), "explicit-host:2");
501        assert_eq!(config.namespace(), "explicit_");
502        assert_eq!(config.tls_strategy(), TlsStrategy::None);
503        assert_eq!(config.tls_server_name(), "explicit-host");
504    }
505
506    #[test]
507    fn empty_environment_values_count_as_unset() {
508        let env = env_of(&[
509            ("HATCHET_CLIENT_HOST_PORT", ""),
510            ("HATCHET_CLIENT_NAMESPACE", ""),
511        ]);
512        let config = ClientConfig::builder()
513            .token(full_token())
514            .resolve(&env)
515            .unwrap();
516        assert_eq!(config.host_port(), "grpc.example.com:443");
517        assert_eq!(config.namespace(), "");
518    }
519
520    #[test]
521    fn a_missing_token_is_a_config_error_naming_the_variable() {
522        let err = ClientConfig::builder().resolve(&no_env).unwrap_err();
523        assert!(matches!(err, Error::Config(_)), "{err:?}");
524        assert!(err.to_string().contains("HATCHET_CLIENT_TOKEN"), "{err}");
525    }
526
527    #[test]
528    fn a_claim_missing_everywhere_is_an_error_naming_it() {
529        let token = token_with(serde_json::json!({"sub": "tenant"}));
530        let err = ClientConfig::builder()
531            .token(token)
532            .resolve(&no_env)
533            .unwrap_err();
534        assert!(matches!(err, Error::InvalidToken(_)), "{err:?}");
535        assert!(err.to_string().contains("grpc_broadcast_address"), "{err}");
536        assert!(
537            err.to_string().contains("HATCHET_CLIENT_HOST_PORT"),
538            "{err}"
539        );
540    }
541
542    #[test]
543    fn a_missing_claim_is_fine_when_supplied_another_way() {
544        let token = token_with(serde_json::json!({"sub": "tenant"}));
545        let config = ClientConfig::builder()
546            .token(token)
547            .host_port("localhost:7077")
548            .server_url("http://localhost:8888")
549            .resolve(&no_env)
550            .unwrap();
551        assert_eq!(config.tenant_id(), "tenant");
552    }
553
554    #[test]
555    fn unknown_tls_strategy_is_a_config_error() {
556        let env = env_of(&[("HATCHET_CLIENT_TLS_STRATEGY", "ssl")]);
557        let err = ClientConfig::builder()
558            .token(full_token())
559            .resolve(&env)
560            .unwrap_err();
561        assert!(err.to_string().contains("ssl"), "{err}");
562    }
563
564    #[test]
565    fn tls_files_come_from_the_environment() {
566        let env = env_of(&[
567            ("HATCHET_CLIENT_TLS_CERT_FILE", "/certs/client.pem"),
568            ("HATCHET_CLIENT_TLS_KEY_FILE", "/certs/client.key"),
569            ("HATCHET_CLIENT_TLS_ROOT_CA_FILE", "/certs/ca.pem"),
570        ]);
571        let config = ClientConfig::builder()
572            .token(full_token())
573            .resolve(&env)
574            .unwrap();
575        assert_eq!(config.tls_cert_file(), Some(Path::new("/certs/client.pem")));
576        assert_eq!(config.tls_key_file(), Some(Path::new("/certs/client.key")));
577        assert_eq!(config.tls_root_ca_file(), Some(Path::new("/certs/ca.pem")));
578    }
579
580    #[test]
581    fn host_of_strips_scheme_port_and_ipv6_brackets() {
582        assert_eq!(host_of("engine.example.com:7077"), "engine.example.com");
583        assert_eq!(host_of("localhost"), "localhost");
584        assert_eq!(host_of("[::1]:7077"), "::1");
585        assert_eq!(host_of("https://[2001:db8::1]:443"), "2001:db8::1");
586    }
587
588    #[test]
589    fn server_name_defaults_to_the_host_without_port_or_scheme() {
590        let config = ClientConfig::builder()
591            .token(full_token())
592            .host_port("https://engine.example.com:7077")
593            .resolve(&no_env)
594            .unwrap();
595        assert_eq!(config.tls_server_name(), "engine.example.com");
596    }
597
598    #[test]
599    fn apply_namespace_uses_the_configured_namespace() {
600        let config = ClientConfig::builder()
601            .token(full_token())
602            .namespace("Dev")
603            .resolve(&no_env)
604            .unwrap();
605        assert_eq!(config.apply_namespace("agent-run"), "dev_agent-run");
606        assert_eq!(config.apply_namespace("dev_agent-run"), "dev_agent-run");
607    }
608
609    #[test]
610    fn gzip_is_on_by_default() {
611        let config = ClientConfig::builder()
612            .token(full_token())
613            .resolve(&no_env)
614            .unwrap();
615        assert!(config.gzip());
616    }
617
618    #[test]
619    fn the_environment_can_turn_gzip_off() {
620        for value in ["true", "TRUE", "1", "yes", "on"] {
621            let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
622            let config = ClientConfig::builder()
623                .token(full_token())
624                .resolve(&env)
625                .unwrap();
626            assert!(!config.gzip(), "{value}");
627        }
628        for value in ["false", "0", "no", "off"] {
629            let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", value)]);
630            let config = ClientConfig::builder()
631                .token(full_token())
632                .resolve(&env)
633                .unwrap();
634            assert!(config.gzip(), "{value}");
635        }
636    }
637
638    #[test]
639    fn an_explicit_gzip_setting_overrides_the_environment() {
640        let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "true")]);
641        let config = ClientConfig::builder()
642            .token(full_token())
643            .gzip(true)
644            .resolve(&env)
645            .unwrap();
646        assert!(config.gzip());
647    }
648
649    #[test]
650    fn an_unparseable_gzip_value_is_a_config_error_naming_the_variable() {
651        let env = env_of(&[("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION", "maybe")]);
652        let err = ClientConfig::builder()
653            .token(full_token())
654            .resolve(&env)
655            .unwrap_err();
656        assert!(matches!(err, Error::Config(_)), "{err:?}");
657        assert!(
658            err.to_string()
659                .contains("HATCHET_CLIENT_DISABLE_GZIP_COMPRESSION"),
660            "{err}"
661        );
662        assert!(err.to_string().contains("maybe"), "{err}");
663    }
664
665    #[test]
666    fn debug_output_shows_the_gzip_setting() {
667        let config = ClientConfig::builder()
668            .token(full_token())
669            .gzip(false)
670            .resolve(&no_env)
671            .unwrap();
672        assert!(format!("{config:?}").contains("gzip"), "{config:?}");
673    }
674
675    #[test]
676    fn debug_output_redacts_the_token() {
677        let token = full_token();
678        let config = ClientConfig::builder()
679            .token(token.clone())
680            .resolve(&no_env)
681            .unwrap();
682        let debug = format!("{config:?}");
683        assert!(!debug.contains(&token), "{debug}");
684        assert!(debug.contains("redacted"), "{debug}");
685    }
686}