Skip to main content

toolkit_contract/runtime/
config.rs

1//! Client, retry, and credential configuration consumed by generated clients.
2//!
3//! [`ClientConfig`] is shared by both the generated REST client and the
4//! generated gRPC client; [`InternalTokenProvider`] is the runtime source of the
5//! platform-plane credential those clients attach on `PlatformSecurityContext`
6//! methods.
7
8use std::borrow::Cow;
9use std::sync::Arc;
10use std::time::Duration;
11
12use secrecy::SecretString;
13
14/// Outcome of resolving the process's platform-plane credential on one outbound
15/// call.
16///
17/// Three-state (rather than `Option<SecretString>`) so an attach site can tell
18/// an intentionally unauthenticated deployment (Profile 1) apart from a broken
19/// credential source — e.g. the projected token file is transiently empty.
20/// Attach helpers stay silent on [`Self::NotConfigured`] and `warn!` on
21/// [`Self::Unavailable`], never emitting the token.
22#[derive(Debug)]
23pub enum CredentialState {
24    /// No credential configured (Profile 1 / `InternalCredential::None`). Attach
25    /// nothing, silently — a legitimate deployment.
26    NotConfigured,
27    /// A credential is configured and currently available; attach it.
28    Available(SecretString),
29    /// Configured but currently unavailable (empty token file, or the background
30    /// refresh has not run yet). Attach nothing but **warn** — a broken source,
31    /// not an intentional opt-out. Carries the reason (never the token).
32    Unavailable(Cow<'static, str>),
33}
34
35/// Source of the process's **platform-plane** internal credential.
36///
37/// Generated clients attach it — as the `X-ToolKit-Internal-Token` header /
38/// metadata, **never** `Authorization` — on methods whose plane marker is
39/// `PlatformSecurityContext` (`cpt-cf-adr-two-plane-auth`). The credential comes
40/// from the runtime (the bootstrap-selected `InternalCredential`), never the
41/// contract argument.
42///
43/// Invoked on every call so a rotating credential (e.g. a projected Kubernetes
44/// `ServiceAccount` token) is always attached in its current form; it returns a
45/// [`CredentialState`] to distinguish not-configured (silent) from unavailable
46/// (warn). Because it runs per-request on an async path, the closure **must not
47/// block, do I/O, or take a contended lock** (see [`InternalTokenProvider::new`]).
48#[derive(Clone)]
49pub struct InternalTokenProvider(Arc<dyn Fn() -> CredentialState + Send + Sync>);
50
51impl InternalTokenProvider {
52    /// Build a provider whose credential is resolved by `provider` on each call
53    /// (supports rotation).
54    ///
55    /// The closure **must not block, do I/O, or take a contended lock** — it is
56    /// called on every outbound platform-plane request from an async path. See
57    /// [`InternalTokenProvider`] and use `ServiceAccountTokenReader::token_provider`
58    /// as the reference pattern for a rotating credential.
59    #[must_use]
60    pub fn new(provider: impl Fn() -> CredentialState + Send + Sync + 'static) -> Self {
61        Self(Arc::new(provider))
62    }
63
64    /// Build a provider that always yields the given static `token`.
65    ///
66    /// Suitable for a non-rotating credential (e.g. a shared secret); prefer
67    /// [`InternalTokenProvider::new`] for rotating tokens.
68    #[must_use]
69    pub fn from_token(token: SecretString) -> Self {
70        Self::new(move || CredentialState::Available(token.clone()))
71    }
72
73    /// Resolve the current credential state.
74    #[must_use]
75    pub fn current(&self) -> CredentialState {
76        (self.0)()
77    }
78
79    /// Resolve the token to attach on an outbound platform-plane call, applying
80    /// the shared attach policy so the REST and gRPC helpers behave identically:
81    /// `None`/[`NotConfigured`](CredentialState::NotConfigured) → `None` (silent),
82    /// [`Available`](CredentialState::Available) → `Some`, and
83    /// [`Unavailable`](CredentialState::Unavailable) → `None` plus a `warn!`
84    /// naming the plane and `rpc` (never the token).
85    #[must_use]
86    pub fn resolve_for_attach(provider: Option<&Self>, rpc: &str) -> Option<SecretString> {
87        match provider.map(Self::current) {
88            None | Some(CredentialState::NotConfigured) => None,
89            Some(CredentialState::Available(token)) => Some(token),
90            Some(CredentialState::Unavailable(reason)) => {
91                tracing::warn!(
92                    plane = "platform",
93                    rpc,
94                    reason = %reason,
95                    "platform-plane credential configured but currently unavailable; \
96                     sending request without the internal token",
97                );
98                None
99            }
100        }
101    }
102}
103
104impl std::fmt::Debug for InternalTokenProvider {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        // Never render the credential (or even hint at its presence beyond the
107        // opaque marker) so it cannot leak through a `{:?}` sink.
108        f.write_str("InternalTokenProvider(<fn>)")
109    }
110}
111
112/// Base configuration for a generated REST client.
113///
114/// `#[non_exhaustive]`: construct via [`ClientConfig::new`] and the `with_*`
115/// chain rather than a struct literal, so future transport knobs can be added
116/// without a breaking change.
117#[derive(Debug, Clone)]
118#[non_exhaustive]
119pub struct ClientConfig {
120    /// Base URL prefix (e.g., `https://billing.internal`).
121    /// Combined with the base path declared in the projection trait.
122    pub base_url: String,
123    /// Deadline applied to a **single** unary attempt — NOT to the whole logical
124    /// call. A `#[retryable]` method may make up to `retry.max_attempts` attempts,
125    /// so the worst-case wall-clock for a logical call is bounded by
126    /// `max_attempts × (timeout + retry.max_delay)` (the per-retry backoff is
127    /// itself clamped to [`RetryConfig::max_delay`], including a server-advised
128    /// `Retry-After`). There is deliberately no separate whole-call budget field.
129    pub timeout: Duration,
130    /// Per-**item** idle deadline for streams of any framing: the maximum gap
131    /// between two received wire chunks before the stream is treated as timed
132    /// out. A long-lived stream is NOT bounded by [`timeout`](Self::timeout)
133    /// (which would kill a healthy slow stream); it is bounded by this larger
134    /// idle deadline instead. Defaults to 60s (> the unary default).
135    ///
136    /// This is *idle*, not *quiet*: any wire chunk resets it, including ones
137    /// that dispatch no item (an SSE keepalive comment, a multipart part header
138    /// block arriving on its own).
139    ///
140    /// REST only for now: the generated gRPC client does not apply it.
141    pub stream_idle_timeout: Duration,
142    /// Retry policy applied to methods marked `#[retryable]`.
143    pub retry: RetryConfig,
144    /// Reconnect policy for streams of any framing. By default
145    /// `max_attempts: 0` — stream failures bubble up unchanged. Set explicitly
146    /// to opt into transparent re-open on a transient failure.
147    ///
148    /// REST only for now: a generated gRPC client never reconnects a stream,
149    /// and wiring warns when this is set for one.
150    ///
151    /// Two limits are deliberate rather than accidental:
152    ///
153    /// - **It applies only to a method whose open is immediate**
154    ///   (`#[streaming] fn`). A fallible open (`#[streaming] async fn`) carries
155    ///   domain semantics the client must not blindly repeat — a re-open can
156    ///   collide with an exclusion lease the first open acquired, and its
157    ///   failure would land as a stream item, past the caller's open-time error
158    ///   handling. Generated code therefore passes
159    ///   [`ReconnectConfig::disabled`] for a fallible open regardless of this
160    ///   value.
161    /// - **Resume via `Last-Event-ID` is SSE-only.** A reconnected
162    ///   `multipart/mixed` stream re-issues the original request with no resume
163    ///   token, because the framing has none. The transport still reopens it,
164    ///   but that is a blind restart, not a resume: the server replays the body
165    ///   from its first part, so any items already delivered before the failure
166    ///   are **delivered again** (at-least-once, with no marker for the
167    ///   restart). Enable reconnect for a multipart stream only where the
168    ///   consumer tolerates duplicates; one needing exactly-once must instead
169    ///   leave reconnect disabled and run its own reopen loop with
170    ///   application-level dedup.
171    pub stream_reconnect: ReconnectConfig,
172    /// When `true`, the generated client refuses plaintext `http://` and
173    /// requires TLS (`toolkit_http::TransportSecurity::TlsOnly`) for every
174    /// request — including the bearer-carrying `Authorization` header, which
175    /// otherwise would ride whatever scheme `base_url` uses. Defaults to
176    /// `false`, preserving the platform's existing in-mesh service-to-service
177    /// convention where plaintext HTTP inside a secured network boundary is an
178    /// accepted, deliberate choice (see
179    /// [`build_default_http_client`](crate::runtime::client::build_default_http_client)).
180    /// In a build where `toolkit-http/fips` is enabled the default is `true`
181    /// (it follows `toolkit_http::TransportSecurity::default()`); there an
182    /// explicit `false` is the opt-in to plaintext and a warning is logged
183    /// when the client is built (by `toolkit-http` for REST, by the generated
184    /// `connect` for gRPC).
185    /// Set this when a resolved endpoint may cross an untrusted network. Read by
186    /// both the REST and gRPC transports.
187    pub require_tls: bool,
188    /// Maximum *idle* keep-alive connections retained **per upstream host**
189    /// (active in-flight requests are not capped). Defaults to 128; raise via
190    /// [`ClientTuning`](crate::wiring::ClientTuning) for higher concurrency.
191    /// **REST transport only.**
192    ///
193    /// Keep it at or above the expected per-upstream concurrency: below that,
194    /// hyper closes excess connections as they idle and reopens them per
195    /// request, producing a `connect(2)` storm that dominates CPU. The 128
196    /// default clears the ~100-concurrent gear-to-gear traffic that motivated it
197    /// (the old `toolkit-http` default of 32 did not).
198    pub pool_max_idle_per_host: usize,
199    /// How long an idle keep-alive connection is retained before it is closed —
200    /// the companion of [`pool_max_idle_per_host`](Self::pool_max_idle_per_host)
201    /// (which bounds *how many*). Keep it above the gap between bursts to an
202    /// upstream so connections stay warm. Defaults to 90s. **REST transport only.**
203    ///
204    /// `None` does **not** mean "kept indefinitely": it leaves the hyper-util
205    /// setter unset, so hyper-util's own default (~90s) applies. The default is
206    /// an explicit `Some(90s)` for that reason.
207    pub pool_idle_timeout: Option<Duration>,
208    /// Maximum in-flight requests through this client at once (across all
209    /// upstream hosts). `None` disables the limiter; `Some(n)` caps at `n`, with
210    /// `Some(0)` clamped to 1 by the transport so the client can't wedge
211    /// shedding everything. Defaults to `Some(128)`, aligned with
212    /// [`pool_max_idle_per_host`](Self::pool_max_idle_per_host) so the idle pool
213    /// is fully reusable before load is shed. **REST transport only.**
214    ///
215    /// The cap bounds requests *waiting on response headers* — the tower permit
216    /// is released once headers arrive, so a long-lived SSE/multipart body holds
217    /// no slot while it streams; size it against in-flight requests, not open
218    /// streams. A shed request surfaces as
219    /// [`TransportError::Overloaded`](crate::runtime::transport_error::TransportError::Overloaded),
220    /// which is **not** transient, so a saturated client fails fast rather than
221    /// retrying into its own overload.
222    pub max_concurrent_requests: Option<usize>,
223    /// Source of the platform-plane internal credential attached to methods
224    /// whose plane marker is `PlatformSecurityContext` (carried as
225    /// `X-ToolKit-Internal-Token`). `None` (the default) attaches nothing —
226    /// legitimate for Profile 1 / in-process (`InternalCredential::None`);
227    /// the requirement is enforced server-side. The bootstrap layer populates
228    /// this from the process's selected `InternalCredential`. Tenant-plane
229    /// methods (`SecurityContext`) never consult it; they forward the caller's
230    /// bearer token from the argument.
231    pub internal_token_provider: Option<InternalTokenProvider>,
232
233    /// Circuit breaker guarding every attempt this client sends. `None` (the
234    /// default for [`ClientConfig::new`]) sends every attempt. The wiring
235    /// paths attach one per endpoint from `ClientTuning::circuit_breaker`; see
236    /// [`crate::runtime::breaker`].
237    pub circuit_breaker: Option<Arc<toolkit_resilience::circuit_breaker::CircuitBreaker>>,
238
239    /// Runs after an attempt the breaker classified as a backend failure.
240    pub on_endpoint_failure: Option<crate::runtime::breaker::EndpointFailureHook>,
241}
242
243impl ClientConfig {
244    /// Create a new config with sensible defaults.
245    #[must_use]
246    pub fn new(base_url: impl Into<String>) -> Self {
247        Self {
248            base_url: base_url.into(),
249            timeout: Duration::from_secs(30),
250            stream_idle_timeout: Duration::from_mins(1),
251            retry: RetryConfig::default(),
252            stream_reconnect: ReconnectConfig::default(),
253            require_tls: default_require_tls(),
254            // `build_default_http_client` always sets these on the builder, so
255            // toolkit-http's own defaults (32/90s/100) never apply here.
256            pool_max_idle_per_host: 128,
257            pool_idle_timeout: Some(Duration::from_secs(90)),
258            max_concurrent_requests: Some(128),
259            internal_token_provider: None,
260            circuit_breaker: None,
261            on_endpoint_failure: None,
262        }
263    }
264
265    /// Override the per-call (unary) timeout.
266    #[must_use]
267    pub fn with_timeout(mut self, timeout: Duration) -> Self {
268        self.timeout = timeout;
269        self
270    }
271
272    /// Override the per-item stream idle deadline (max gap between wire
273    /// chunks). See [`Self::stream_idle_timeout`].
274    #[must_use]
275    pub fn with_stream_idle_timeout(mut self, idle: Duration) -> Self {
276        self.stream_idle_timeout = idle;
277        self
278    }
279
280    /// Override the retry policy.
281    #[must_use]
282    pub fn with_retry(mut self, retry: RetryConfig) -> Self {
283        self.retry = retry;
284        self
285    }
286
287    /// Override the stream reconnect policy. Use
288    /// [`ReconnectConfig::disabled()`] to disable (the default) or
289    /// [`ReconnectConfig::enabled()`] to opt in. See
290    /// [`Self::stream_reconnect`] for what it does and does not govern.
291    #[must_use]
292    pub fn with_stream_reconnect(mut self, stream_reconnect: ReconnectConfig) -> Self {
293        self.stream_reconnect = stream_reconnect;
294        self
295    }
296
297    /// Require TLS (reject plaintext `http://`) for this client. See
298    /// [`Self::require_tls`].
299    #[must_use]
300    pub fn with_require_tls(mut self, require_tls: bool) -> Self {
301        self.require_tls = require_tls;
302        self
303    }
304
305    /// Error message when [`Self::require_tls`] is set but `base_url` is not
306    /// `https://`. Transports call this when the client is constructed, so a
307    /// plaintext endpoint fails once there instead of on every call.
308    #[must_use]
309    pub(crate) fn tls_scheme_violation(&self) -> Option<String> {
310        if !self.require_tls || is_https(&self.base_url) {
311            return None;
312        }
313        let why = if default_require_tls() {
314            "require_tls is on (the default in FIPS builds); set `require_tls: false` \
315             to opt in to plaintext"
316        } else {
317            "require_tls is set"
318        };
319        Some(format!(
320            "{why}, but the endpoint scheme is not https: {}",
321            self.base_url
322        ))
323    }
324
325    /// Check `base_url` against [`Self::require_tls`], for a transport that
326    /// does not go through `toolkit-http` (the generated gRPC `connect`).
327    ///
328    /// In a FIPS build, a plaintext endpoint allowed by `require_tls: false`
329    /// passes, and the first one in the process is logged as a warning.
330    ///
331    /// # Errors
332    /// TLS is required and the endpoint is not `https://`; the message says why.
333    pub fn check_tls_scheme(&self) -> Result<(), String> {
334        if let Some(reason) = self.tls_scheme_violation() {
335            return Err(reason);
336        }
337        if default_require_tls() && !self.require_tls && !is_https(&self.base_url) {
338            static WARNED: std::sync::Once = std::sync::Once::new();
339            WARNED.call_once(|| {
340                tracing::warn!(
341                    target: "toolkit_http::security",
342                    endpoint = %self.base_url,
343                    "plaintext endpoint used in a FIPS build (require_tls: false): \
344                     requests to it are not encrypted (logged once per process)"
345                );
346            });
347        }
348        Ok(())
349    }
350
351    /// Override the max idle keep-alive connections per upstream host. See
352    /// [`Self::pool_max_idle_per_host`].
353    #[must_use]
354    pub fn with_pool_max_idle_per_host(mut self, max: usize) -> Self {
355        self.pool_max_idle_per_host = max;
356        self
357    }
358
359    /// Override how long idle keep-alive connections are retained (`None` uses
360    /// hyper-util's default). See [`Self::pool_idle_timeout`].
361    #[must_use]
362    pub fn with_pool_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
363        self.pool_idle_timeout = timeout;
364        self
365    }
366
367    /// Override the max concurrent in-flight requests (`None` disables the
368    /// limiter). See [`Self::max_concurrent_requests`].
369    #[must_use]
370    pub fn with_max_concurrent_requests(mut self, max: Option<usize>) -> Self {
371        self.max_concurrent_requests = max;
372        self
373    }
374
375    /// Guard this client's attempts with `breaker`. See [`Self::circuit_breaker`].
376    #[must_use]
377    pub fn with_circuit_breaker(
378        mut self,
379        breaker: impl Into<Option<Arc<toolkit_resilience::circuit_breaker::CircuitBreaker>>>,
380    ) -> Self {
381        self.circuit_breaker = breaker.into();
382        self
383    }
384
385    /// Run `hook` after each attempt the breaker classified as a backend
386    /// failure. See [`Self::on_endpoint_failure`].
387    #[must_use]
388    pub fn with_on_endpoint_failure(
389        mut self,
390        hook: impl Into<Option<crate::runtime::breaker::EndpointFailureHook>>,
391    ) -> Self {
392        self.on_endpoint_failure = hook.into();
393        self
394    }
395
396    /// Set (or clear) the platform-plane internal-credential provider. See
397    /// [`Self::internal_token_provider`]. Accepts either an
398    /// [`InternalTokenProvider`] or an `Option<InternalTokenProvider>`, so the
399    /// bootstrap layer can pass through whatever the process selected without a
400    /// branch.
401    #[must_use]
402    pub fn with_internal_token_provider(
403        mut self,
404        provider: impl Into<Option<InternalTokenProvider>>,
405    ) -> Self {
406        self.internal_token_provider = provider.into();
407        self
408    }
409}
410
411/// Bounded exponential-backoff retry policy with full jitter.
412#[derive(Debug, Clone)]
413pub struct RetryConfig {
414    /// Maximum number of attempts (must be at least 1).
415    pub max_attempts: u32,
416    /// Base delay before the first retry.
417    pub base_delay: Duration,
418    /// Hard cap on the delay between retries.
419    pub max_delay: Duration,
420    /// Multiplier applied between consecutive retries.
421    pub multiplier: f64,
422}
423
424impl RetryConfig {
425    /// Disable retries entirely (single attempt).
426    #[must_use]
427    pub const fn off() -> Self {
428        Self {
429            max_attempts: 1,
430            base_delay: Duration::ZERO,
431            max_delay: Duration::ZERO,
432            multiplier: 1.0,
433        }
434    }
435}
436
437impl Default for RetryConfig {
438    fn default() -> Self {
439        Self {
440            max_attempts: 3,
441            base_delay: Duration::from_millis(100),
442            max_delay: Duration::from_secs(2),
443            multiplier: 2.0,
444        }
445    }
446}
447
448/// SSE reconnect policy. The streaming client tracks the latest `id:`
449/// field seen on the wire and, on transient stream failures, re-issues
450/// the request with a `Last-Event-ID: <stored>` header so the server can
451/// resume the event sequence (per HTML5 `EventSource` spec).
452///
453/// Default is **opt-in disabled** (`max_attempts: 0`) so existing SDKs see
454/// no behaviour change.
455#[derive(Debug, Clone)]
456pub struct ReconnectConfig {
457    /// Maximum number of *consecutive* reconnect attempts with no healthy
458    /// connection in between (the burst budget). `0` (default) disables
459    /// reconnect entirely — stream errors bubble up. The budget is reset by a
460    /// connection that both delivers an item and stays up at least
461    /// [`min_healthy_uptime`](Self::min_healthy_uptime).
462    pub max_attempts: u32,
463    /// Initial delay before the first reconnect attempt.
464    pub base_delay: Duration,
465    /// Hard cap on delay between reconnect attempts.
466    pub max_delay: Duration,
467    /// Minimum time a connection must stay up — *in addition to* delivering at
468    /// least one item — before its end resets the burst budget. Delivering a
469    /// single item is too weak a health signal on its own: a peer that emits
470    /// one item and immediately drops would reset the budget on every cycle and
471    /// reopen forever, re-sending the auth token each time (#4740). A connection
472    /// shorter than this counts against `max_attempts` like any other failed
473    /// attempt.
474    pub min_healthy_uptime: Duration,
475    /// Absolute lifetime ceiling on reopens, independent of budget resets. It
476    /// bounds the pathological peer that stays up *just past*
477    /// `min_healthy_uptime`, delivers an item, and drops on a loop — which would
478    /// otherwise reset the burst budget indefinitely. Set high enough that a
479    /// genuinely healthy long-lived subscription (which reconnects rarely) never
480    /// approaches it; `0` refuses reopen outright.
481    pub max_total_reopens: u32,
482}
483
484impl Default for ReconnectConfig {
485    fn default() -> Self {
486        Self {
487            max_attempts: 0,
488            base_delay: Duration::from_millis(500),
489            max_delay: Duration::from_secs(10),
490            min_healthy_uptime: Duration::from_secs(5),
491            max_total_reopens: 10_000,
492        }
493    }
494}
495
496impl ReconnectConfig {
497    /// Build a reconnect policy with up to `max_attempts` retries and the
498    /// supplied initial delay (capped by `max_delay`, default 10s).
499    #[must_use]
500    pub fn enabled(max_attempts: u32, base_delay: Duration) -> Self {
501        Self {
502            max_attempts,
503            base_delay,
504            ..Self::default()
505        }
506    }
507
508    /// A policy that never reconnects: the stream's first transport failure
509    /// ends it.
510    ///
511    /// The counterpart to [`ReconnectConfig::enabled`]. [`Default`] already
512    /// yields `max_attempts: 0`, so this is behaviourally the same value — it
513    /// exists so a call site that *must* not reconnect reads as a deliberate
514    /// choice rather than an accepted default.
515    ///
516    /// Generated clients pass this for a method whose open is fallible
517    /// (`#[streaming] async fn`). Such an open carries domain semantics the
518    /// client must not blindly repeat: any exclusion lease it acquired is owned
519    /// by the returned stream's lifetime, resume may be specified through the
520    /// contract's own cursor rather than `Last-Event-ID`, and a reconnect-time
521    /// failure would arrive as a stream *item* — past the caller's open-time
522    /// error handling, which is the whole reason the fallible shape exists.
523    #[must_use]
524    pub const fn disabled() -> Self {
525        // Every field is named explicitly (rather than `..Self::default()`) so a
526        // future field with an *enabling* default can't silently leak into a
527        // constructor documented as never reconnecting — matching
528        // [`RetryConfig::off`]. These are the same values as [`Default`].
529        Self {
530            max_attempts: 0,
531            base_delay: Duration::from_millis(500),
532            max_delay: Duration::from_secs(10),
533            min_healthy_uptime: Duration::from_secs(5),
534            max_total_reopens: 10_000,
535        }
536    }
537
538    /// Override the maximum delay between reconnect attempts.
539    #[must_use]
540    pub fn with_max_delay(mut self, max_delay: Duration) -> Self {
541        self.max_delay = max_delay;
542        self
543    }
544
545    /// Override the minimum healthy connection uptime that resets the burst
546    /// budget. See [`min_healthy_uptime`](Self::min_healthy_uptime).
547    #[must_use]
548    pub fn with_min_healthy_uptime(mut self, min_healthy_uptime: Duration) -> Self {
549        self.min_healthy_uptime = min_healthy_uptime;
550        self
551    }
552
553    /// Override the absolute lifetime cap on reopens. See
554    /// [`max_total_reopens`](Self::max_total_reopens).
555    #[must_use]
556    pub fn with_max_total_reopens(mut self, max_total_reopens: u32) -> Self {
557        self.max_total_reopens = max_total_reopens;
558        self
559    }
560}
561
562/// `true` when `toolkit-http` defaults to `TlsOnly`, i.e. under its `fips`
563/// feature. Read from `toolkit-http` rather than a feature of this crate so it
564/// follows Cargo feature unification.
565pub(crate) fn default_require_tls() -> bool {
566    toolkit_http::TransportSecurity::default() == toolkit_http::TransportSecurity::TlsOnly
567}
568
569/// `url` has an `https` scheme (case-insensitive, leading whitespace ignored).
570pub(crate) fn is_https(url: &str) -> bool {
571    url.trim_start()
572        .get(..8)
573        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://"))
574}
575
576#[cfg(test)]
577#[cfg_attr(coverage_nightly, coverage(off))]
578mod tests {
579    use super::*;
580
581    /// Run with `--features fips` in `make test-fips`. The default follows
582    /// `toolkit-http`'s transport default, which feature unification can turn
583    /// to `TlsOnly` without this crate's `fips` feature; this crate's `fips`
584    /// always turns it on.
585    #[test]
586    fn require_tls_defaults_to_true_only_in_fips_builds() {
587        let require_tls = ClientConfig::new("http://svc").require_tls;
588        assert_eq!(
589            require_tls,
590            toolkit_http::TransportSecurity::default() == toolkit_http::TransportSecurity::TlsOnly
591        );
592        if cfg!(feature = "fips") {
593            assert!(
594                require_tls,
595                "require_tls must default to true in a FIPS build"
596            );
597        }
598    }
599
600    #[test]
601    fn tls_scheme_violation_only_for_required_tls_over_plaintext() {
602        let plain = ClientConfig::new("http://svc:8080");
603        assert!(
604            plain
605                .clone()
606                .with_require_tls(false)
607                .tls_scheme_violation()
608                .is_none()
609        );
610        let message = plain
611            .with_require_tls(true)
612            .tls_scheme_violation()
613            .expect("require_tls over http:// must be reported");
614        assert!(message.contains("http://svc:8080"), "{message}");
615        if cfg!(feature = "fips") {
616            assert!(message.contains("require_tls: false"), "{message}");
617        }
618
619        for url in ["https://svc", "HTTPS://svc", " https://svc"] {
620            let tls = ClientConfig::new(url).with_require_tls(true);
621            assert!(tls.tls_scheme_violation().is_none(), "{url}");
622        }
623    }
624
625    #[test]
626    fn check_tls_scheme_fails_only_on_violation() {
627        for (url, require_tls) in [
628            ("http://svc", false),
629            ("http://svc", true),
630            ("https://svc", false),
631            ("https://svc", true),
632        ] {
633            let config = ClientConfig::new(url).with_require_tls(require_tls);
634            assert_eq!(
635                config.check_tls_scheme().err(),
636                config.tls_scheme_violation(),
637                "{url} require_tls={require_tls}"
638            );
639        }
640    }
641
642    #[test]
643    fn default_retry_has_three_attempts() {
644        let r = RetryConfig::default();
645        assert_eq!(r.max_attempts, 3);
646        assert!(r.base_delay > Duration::ZERO);
647    }
648
649    #[test]
650    fn off_yields_single_attempt() {
651        let r = RetryConfig::off();
652        assert_eq!(r.max_attempts, 1);
653    }
654
655    // The "never a second attempt" guarantee that `disabled()` carries is
656    // pinned behaviourally by `reconnect_is_derived_from_the_open_shape_not_from_client_config`
657    // (tests/rest_client_codegen.rs), which counts real server connections on
658    // the fallible-open path and asserts exactly one. A unit test that merely
659    // read back `disabled()`'s fields couldn't fail unless struct construction
660    // itself broke, so it isn't restated here.
661
662    #[test]
663    fn client_config_chains_overrides() {
664        let cfg = ClientConfig::new("https://x.example")
665            .with_timeout(Duration::from_secs(5))
666            .with_retry(RetryConfig::off());
667        assert_eq!(cfg.base_url, "https://x.example");
668        assert_eq!(cfg.timeout, Duration::from_secs(5));
669        assert_eq!(cfg.retry.max_attempts, 1);
670    }
671}