Skip to main content

stateknot_integrations/
http.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{fmt, net::IpAddr, time::Duration};
5
6use reqwest::Url;
7use thiserror::Error;
8
9const MEBIBYTE: usize = 1024 * 1024;
10
11/// Validated base endpoint for one immutable provider binding.
12#[derive(Clone, Eq, PartialEq)]
13pub struct ProviderEndpoint {
14    base: Url,
15    transport: EndpointTransport,
16}
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19enum EndpointTransport {
20    Https,
21    LoopbackHttp,
22}
23
24impl ProviderEndpoint {
25    /// Constructs a production HTTPS endpoint.
26    ///
27    /// # Errors
28    ///
29    /// Rejects non-HTTPS URLs, embedded credentials, query/fragment data, an
30    /// absent host, or a base URL that cannot be normalized as a directory.
31    pub fn https(value: &str) -> Result<Self, ProviderEndpointError> {
32        Self::parse(value, EndpointTransport::Https)
33    }
34
35    /// Constructs an HTTP endpoint limited to a literal loopback IP address.
36    ///
37    /// This constructor exists for local integration tests and explicitly
38    /// managed sidecars. Hostnames such as `localhost` are rejected to avoid
39    /// DNS rebinding and deployment-dependent resolution.
40    ///
41    /// # Errors
42    ///
43    /// Returns [`ProviderEndpointError`] unless the URL uses `http` and a
44    /// literal loopback address with the same structural restrictions as
45    /// [`Self::https`].
46    pub fn loopback_http(value: &str) -> Result<Self, ProviderEndpointError> {
47        Self::parse(value, EndpointTransport::LoopbackHttp)
48    }
49
50    fn parse(value: &str, transport: EndpointTransport) -> Result<Self, ProviderEndpointError> {
51        let mut base = Url::parse(value).map_err(|_| ProviderEndpointError::InvalidUrl)?;
52        if !base.username().is_empty() || base.password().is_some() {
53            return Err(ProviderEndpointError::EmbeddedCredentials);
54        }
55        if base.query().is_some() || base.fragment().is_some() {
56            return Err(ProviderEndpointError::QueryOrFragment);
57        }
58        let host = base.host_str().ok_or(ProviderEndpointError::MissingHost)?;
59        match transport {
60            EndpointTransport::Https if base.scheme() != "https" => {
61                return Err(ProviderEndpointError::HttpsRequired);
62            }
63            EndpointTransport::LoopbackHttp => {
64                if base.scheme() != "http" {
65                    return Err(ProviderEndpointError::LoopbackHttpRequired);
66                }
67                let address = host
68                    .parse::<IpAddr>()
69                    .map_err(|_| ProviderEndpointError::LiteralLoopbackRequired)?;
70                if !address.is_loopback() {
71                    return Err(ProviderEndpointError::LiteralLoopbackRequired);
72                }
73            }
74            EndpointTransport::Https => {}
75        }
76
77        if !base.path().ends_with('/') {
78            let mut path = base.path().to_owned();
79            path.push('/');
80            base.set_path(&path);
81        }
82        Ok(Self { base, transport })
83    }
84
85    pub(crate) fn join(&self, relative: &str) -> Result<Url, ProviderEndpointError> {
86        self.base
87            .join(relative)
88            .map_err(|_| ProviderEndpointError::InvalidRelativePath)
89    }
90
91    /// Returns whether this endpoint uses TLS.
92    #[must_use]
93    pub const fn is_https(&self) -> bool {
94        matches!(self.transport, EndpointTransport::Https)
95    }
96}
97
98impl fmt::Debug for ProviderEndpoint {
99    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
100        formatter
101            .debug_struct("ProviderEndpoint")
102            .field("transport", &self.transport)
103            .field("host", &"[REDACTED]")
104            .finish_non_exhaustive()
105    }
106}
107
108/// Invalid provider endpoint configuration.
109#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
110#[non_exhaustive]
111pub enum ProviderEndpointError {
112    /// URL parsing failed.
113    #[error("provider endpoint is not an absolute URL")]
114    InvalidUrl,
115    /// Production endpoints must use HTTPS.
116    #[error("provider endpoint must use HTTPS")]
117    HttpsRequired,
118    /// The local-only constructor requires HTTP.
119    #[error("loopback provider endpoint must use HTTP")]
120    LoopbackHttpRequired,
121    /// A local-only endpoint was not a literal loopback IP.
122    #[error("loopback provider endpoint must use a literal loopback IP address")]
123    LiteralLoopbackRequired,
124    /// URL authority had no host.
125    #[error("provider endpoint must include a host")]
126    MissingHost,
127    /// URL userinfo could leak credentials.
128    #[error("provider endpoint must not contain embedded credentials")]
129    EmbeddedCredentials,
130    /// Query and fragment data are not part of an immutable API base.
131    #[error("provider endpoint must not contain a query or fragment")]
132    QueryOrFragment,
133    /// An adapter requested an invalid fixed API path.
134    #[error("provider API path could not be joined to the configured endpoint")]
135    InvalidRelativePath,
136}
137
138/// Bounded HTTP and SSE resource policy for provider exchanges.
139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
140pub struct ProviderHttpOptions {
141    connect_timeout: Duration,
142    pool_idle_timeout: Duration,
143    maximum_request_bytes: usize,
144    maximum_response_bytes: usize,
145    maximum_sse_line_bytes: usize,
146    maximum_sse_event_bytes: usize,
147    maximum_sse_total_bytes: usize,
148}
149
150impl ProviderHttpOptions {
151    /// Absolute request body ceiling.
152    pub const HARD_MAXIMUM_REQUEST_BYTES: usize = 32 * MEBIBYTE;
153    /// Absolute complete-response body ceiling.
154    pub const HARD_MAXIMUM_RESPONSE_BYTES: usize = 128 * MEBIBYTE;
155    /// Absolute SSE line ceiling.
156    pub const HARD_MAXIMUM_SSE_LINE_BYTES: usize = 128 * MEBIBYTE;
157    /// Absolute SSE event ceiling.
158    pub const HARD_MAXIMUM_SSE_EVENT_BYTES: usize = 128 * MEBIBYTE;
159    /// Absolute total streaming body ceiling.
160    pub const HARD_MAXIMUM_SSE_TOTAL_BYTES: usize = 256 * MEBIBYTE;
161
162    /// Constructs an explicit bounded transport policy.
163    ///
164    /// # Errors
165    ///
166    /// Rejects zero durations/byte ceilings, implementation ceiling breaches,
167    /// or an event ceiling smaller than its line ceiling.
168    #[allow(clippy::too_many_arguments)]
169    pub const fn new(
170        connect_timeout: Duration,
171        pool_idle_timeout: Duration,
172        maximum_request_bytes: usize,
173        maximum_response_bytes: usize,
174        maximum_sse_line_bytes: usize,
175        maximum_sse_event_bytes: usize,
176        maximum_sse_total_bytes: usize,
177    ) -> Result<Self, ProviderHttpOptionsError> {
178        if connect_timeout.is_zero() || pool_idle_timeout.is_zero() {
179            return Err(ProviderHttpOptionsError::ZeroDuration);
180        }
181        if maximum_request_bytes == 0
182            || maximum_response_bytes == 0
183            || maximum_sse_line_bytes == 0
184            || maximum_sse_event_bytes == 0
185            || maximum_sse_total_bytes == 0
186        {
187            return Err(ProviderHttpOptionsError::ZeroBytes);
188        }
189        if maximum_request_bytes > Self::HARD_MAXIMUM_REQUEST_BYTES
190            || maximum_response_bytes > Self::HARD_MAXIMUM_RESPONSE_BYTES
191            || maximum_sse_line_bytes > Self::HARD_MAXIMUM_SSE_LINE_BYTES
192            || maximum_sse_event_bytes > Self::HARD_MAXIMUM_SSE_EVENT_BYTES
193            || maximum_sse_total_bytes > Self::HARD_MAXIMUM_SSE_TOTAL_BYTES
194        {
195            return Err(ProviderHttpOptionsError::AboveHardMaximum);
196        }
197        if maximum_sse_event_bytes < maximum_sse_line_bytes {
198            return Err(ProviderHttpOptionsError::EventBelowLine);
199        }
200        if maximum_sse_total_bytes < maximum_sse_event_bytes {
201            return Err(ProviderHttpOptionsError::TotalBelowEvent);
202        }
203        Ok(Self {
204            connect_timeout,
205            pool_idle_timeout,
206            maximum_request_bytes,
207            maximum_response_bytes,
208            maximum_sse_line_bytes,
209            maximum_sse_event_bytes,
210            maximum_sse_total_bytes,
211        })
212    }
213
214    /// Returns the TCP/TLS connection timeout.
215    #[must_use]
216    pub const fn connect_timeout(self) -> Duration {
217        self.connect_timeout
218    }
219
220    /// Returns the idle connection retention bound.
221    #[must_use]
222    pub const fn pool_idle_timeout(self) -> Duration {
223        self.pool_idle_timeout
224    }
225
226    /// Returns the serialized request ceiling.
227    #[must_use]
228    pub const fn maximum_request_bytes(self) -> usize {
229        self.maximum_request_bytes
230    }
231
232    /// Returns the complete successful response ceiling.
233    #[must_use]
234    pub const fn maximum_response_bytes(self) -> usize {
235        self.maximum_response_bytes
236    }
237
238    /// Returns the SSE line ceiling.
239    #[must_use]
240    pub const fn maximum_sse_line_bytes(self) -> usize {
241        self.maximum_sse_line_bytes
242    }
243
244    /// Returns the assembled SSE event ceiling.
245    #[must_use]
246    pub const fn maximum_sse_event_bytes(self) -> usize {
247        self.maximum_sse_event_bytes
248    }
249
250    /// Returns the total stream transport-byte ceiling.
251    #[must_use]
252    pub const fn maximum_sse_total_bytes(self) -> usize {
253        self.maximum_sse_total_bytes
254    }
255}
256
257impl Default for ProviderHttpOptions {
258    fn default() -> Self {
259        Self {
260            connect_timeout: Duration::from_secs(10),
261            pool_idle_timeout: Duration::from_secs(90),
262            maximum_request_bytes: 16 * MEBIBYTE,
263            maximum_response_bytes: 2 * MEBIBYTE,
264            maximum_sse_line_bytes: 512 * 1024,
265            maximum_sse_event_bytes: 2 * MEBIBYTE,
266            maximum_sse_total_bytes: 64 * MEBIBYTE,
267        }
268    }
269}
270
271/// Invalid provider transport resource policy.
272#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
273#[non_exhaustive]
274pub enum ProviderHttpOptionsError {
275    /// A timeout was zero.
276    #[error("provider HTTP timeouts must be positive")]
277    ZeroDuration,
278    /// A byte ceiling was zero.
279    #[error("provider HTTP byte ceilings must be positive")]
280    ZeroBytes,
281    /// A configured ceiling exceeded the implementation maximum.
282    #[error("provider HTTP byte ceiling exceeds the implementation maximum")]
283    AboveHardMaximum,
284    /// One event could not contain one maximum-size line.
285    #[error("provider SSE event ceiling must be at least its line ceiling")]
286    EventBelowLine,
287    /// The stream total could not contain one maximum-size event.
288    #[error("provider SSE total ceiling must be at least its event ceiling")]
289    TotalBelowEvent,
290}
291
292pub(crate) fn build_client(
293    options: ProviderHttpOptions,
294) -> Result<reqwest::Client, reqwest::Error> {
295    reqwest::Client::builder()
296        .connect_timeout(options.connect_timeout())
297        .pool_idle_timeout(options.pool_idle_timeout())
298        .redirect(reqwest::redirect::Policy::none())
299        .retry(reqwest::retry::never())
300        .user_agent(concat!(
301            "stateknot-integrations/",
302            env!("CARGO_PKG_VERSION")
303        ))
304        .build()
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn endpoints_fail_closed_on_transport_and_authority_ambiguity() {
313        assert_eq!(
314            ProviderEndpoint::https("http://api.example.com/v1/"),
315            Err(ProviderEndpointError::HttpsRequired)
316        );
317        assert_eq!(
318            ProviderEndpoint::https("https://user:secret@api.example.com/v1/"),
319            Err(ProviderEndpointError::EmbeddedCredentials)
320        );
321        assert_eq!(
322            ProviderEndpoint::https("https://api.example.com/v1/?tenant=secret"),
323            Err(ProviderEndpointError::QueryOrFragment)
324        );
325        assert_eq!(
326            ProviderEndpoint::loopback_http("http://localhost:8080/v1/"),
327            Err(ProviderEndpointError::LiteralLoopbackRequired)
328        );
329        assert_eq!(
330            ProviderEndpoint::loopback_http("http://10.0.0.1:8080/v1/"),
331            Err(ProviderEndpointError::LiteralLoopbackRequired)
332        );
333
334        let endpoint = ProviderEndpoint::https("https://private.example.com/tenant-a").unwrap();
335        let debug = format!("{endpoint:?}");
336        assert!(!debug.contains("private.example.com"));
337        assert!(!debug.contains("tenant-a"));
338    }
339
340    #[test]
341    fn transport_limits_are_positive_nested_and_hard_bounded() {
342        assert_eq!(
343            ProviderHttpOptions::new(Duration::ZERO, Duration::from_secs(1), 1, 1, 1, 1, 1,),
344            Err(ProviderHttpOptionsError::ZeroDuration)
345        );
346        assert_eq!(
347            ProviderHttpOptions::new(
348                Duration::from_secs(1),
349                Duration::from_secs(1),
350                1,
351                1,
352                2,
353                1,
354                2,
355            ),
356            Err(ProviderHttpOptionsError::EventBelowLine)
357        );
358    }
359}