Skip to main content

toolkit_http/
request.rs

1use crate::client::{BufferedService, map_buffer_error, try_acquire_buffer_slot};
2use crate::config::TransportSecurity;
3use crate::error::{HttpError, InvalidUriKind};
4use crate::response::{HttpResponse, ResponseBody};
5use bytes::Bytes;
6use http::{Request, Response};
7use http_body_util::Full;
8use serde::Serialize;
9use tower::Service;
10
11/// Body type for the request builder
12#[derive(Clone, Debug)]
13enum BodyKind {
14    /// Empty body
15    Empty,
16    /// Raw bytes body
17    Bytes(Bytes),
18    /// JSON-serialized body (stored as bytes after serialization)
19    Json(Bytes),
20    /// Form URL-encoded body (stored as bytes after serialization)
21    Form(Bytes),
22}
23
24/// Per-request label for the `request_type` metrics attribute.
25///
26/// Attach to a request via [`RequestBuilder::with_request_type`] to break down
27/// `http.client.request.duration` metrics by logical operation (e.g.
28/// `"tenants_resolve"`, `"token_fetch"`). This is the Rust analogue of
29/// go-appkit's `NewContextWithRequestType` / `GetRequestTypeFromContext`.
30///
31/// The metrics layer reads this from request extensions when the `otel` feature
32/// is enabled; setting it without the feature is a safe no-op.
33///
34/// # Example
35///
36/// ```ignore
37/// client
38///     .get("https://api.example.com/tenants/123")
39///     .with_request_type("tenants_resolve")
40///     .send()
41///     .await?;
42/// ```
43#[derive(Clone, Debug)]
44pub struct RequestType(pub std::borrow::Cow<'static, str>);
45
46impl RequestType {
47    /// Create a request type label from a static string.
48    #[must_use]
49    pub fn new(t: impl Into<std::borrow::Cow<'static, str>>) -> Self {
50        Self(t.into())
51    }
52}
53
54/// HTTP request builder with fluent API
55///
56/// Created by [`HttpClient::get`], [`HttpClient::post`], etc.
57/// Supports chaining headers and body configuration before sending
58/// with [`send()`](RequestBuilder::send).
59///
60/// # URL Construction
61///
62/// This crate does **not** provide query-string composition. Build your URL
63/// externally (e.g. via `url::Url`) and pass the final string to `HttpClient`:
64///
65/// ```ignore
66/// use url::Url;
67/// use toolkit_http::HttpClient;
68///
69/// let mut url = Url::parse("https://api.example.com/users")?;
70/// url.query_pairs_mut()
71///     .append_pair("page", "1")
72///     .append_pair("limit", "10");
73///
74/// let client = HttpClient::builder().build()?;
75/// let resp = client.get(url.as_str()).send().await?;
76/// ```
77///
78/// # Example
79///
80/// ```ignore
81/// use toolkit_http::HttpClient;
82///
83/// let client = HttpClient::builder().build()?;
84///
85/// // Simple GET
86/// let resp = client
87///     .get("https://api.example.com/users")
88///     .send()
89///     .await?;
90///
91/// // POST with JSON body
92/// let resp = client
93///     .post("https://api.example.com/users")
94///     .header("x-request-id", "123")
95///     .json(&NewUser { name: "Alice" })?
96///     .send()
97///     .await?;
98///
99/// // POST with form body
100/// let resp = client
101///     .post("https://auth.example.com/token")
102///     .header("authorization", "Basic xyz")
103///     .form(&[("grant_type", "client_credentials")])?
104///     .send()
105///     .await?;
106/// ```
107#[must_use = "RequestBuilder does nothing until .send() is called"]
108pub struct RequestBuilder {
109    service: BufferedService,
110    max_body_size: usize,
111    method: http::Method,
112    url: String,
113    headers: Vec<(http::header::HeaderName, http::header::HeaderValue)>,
114    body: BodyKind,
115    /// Error captured during building (deferred to `send()`)
116    error: Option<HttpError>,
117    /// Transport security mode for URL scheme validation
118    transport_security: TransportSecurity,
119    /// Optional per-request metrics label (read by the metrics layer)
120    request_type: Option<RequestType>,
121}
122
123impl RequestBuilder {
124    /// Create a new request builder (internal use only)
125    pub(crate) fn new(
126        service: BufferedService,
127        max_body_size: usize,
128        method: http::Method,
129        url: String,
130        transport_security: TransportSecurity,
131    ) -> Self {
132        Self {
133            service,
134            max_body_size,
135            method,
136            url,
137            headers: Vec::new(),
138            body: BodyKind::Empty,
139            error: None,
140            transport_security,
141            request_type: None,
142        }
143    }
144
145    /// Add a single header to the request
146    ///
147    /// # Example
148    ///
149    /// ```ignore
150    /// let resp = client
151    ///     .get("https://api.example.com")
152    ///     .header("authorization", "Bearer token")
153    ///     .header("x-request-id", "abc123")
154    ///     .send()
155    ///     .await?;
156    /// ```
157    pub fn header(mut self, name: &str, value: &str) -> Self {
158        if self.error.is_some() {
159            return self;
160        }
161
162        match (
163            http::header::HeaderName::try_from(name),
164            http::header::HeaderValue::try_from(value),
165        ) {
166            (Ok(name), Ok(value)) => {
167                self.headers.push((name, value));
168            }
169            (Err(e), _) => {
170                self.error = Some(HttpError::InvalidHeaderName(e));
171            }
172            (_, Err(e)) => {
173                self.error = Some(HttpError::InvalidHeaderValue(e));
174            }
175        }
176        self
177    }
178
179    /// Attach a tenant-plane bearer token as a **sensitive** `Authorization`
180    /// header (`Authorization: Bearer <token>`).
181    ///
182    /// The header value is marked sensitive (`HeaderValue::set_sensitive(true)`)
183    /// so header-logging / redaction layers never emit it — the same guarantee
184    /// as [`crate::security::attach_bearer_http`]. Prefer this over
185    /// `.header("authorization", ..)` for credentials, which cannot mark the
186    /// value sensitive. `token` is the raw credential; the `Bearer ` scheme is
187    /// prepended here.
188    pub fn bearer_auth(mut self, token: &str) -> Self {
189        if self.error.is_some() {
190            return self;
191        }
192        match http::header::HeaderValue::try_from(format!("Bearer {token}")) {
193            Ok(mut value) => {
194                value.set_sensitive(true);
195                self.headers.push((http::header::AUTHORIZATION, value));
196            }
197            Err(e) => {
198                self.error = Some(HttpError::InvalidHeaderValue(e));
199            }
200        }
201        self
202    }
203
204    /// Add multiple headers to the request
205    ///
206    /// # Example
207    ///
208    /// ```ignore
209    /// let resp = client
210    ///     .get("https://api.example.com")
211    ///     .headers(vec![
212    ///         ("authorization".to_owned(), "Bearer token".to_owned()),
213    ///         ("x-request-id".to_owned(), "abc123".to_owned()),
214    ///     ])
215    ///     .send()
216    ///     .await?;
217    /// ```
218    pub fn headers(mut self, headers: Vec<(String, String)>) -> Self {
219        if self.error.is_some() {
220            return self;
221        }
222
223        for (name, value) in headers {
224            match (
225                http::header::HeaderName::try_from(name),
226                http::header::HeaderValue::try_from(value),
227            ) {
228                (Ok(name), Ok(value)) => {
229                    self.headers.push((name, value));
230                }
231                (Err(e), _) => {
232                    self.error = Some(HttpError::InvalidHeaderName(e));
233                    return self;
234                }
235                (_, Err(e)) => {
236                    self.error = Some(HttpError::InvalidHeaderValue(e));
237                    return self;
238                }
239            }
240        }
241        self
242    }
243
244    /// Attach a `request_type` label for metrics.
245    ///
246    /// The label is added as a `request_type` attribute on the
247    /// `http.client.request.duration` histogram when the `otel` feature and a
248    /// metrics layer are configured. This mirrors go-appkit's
249    /// `NewContextWithRequestType` / `GetRequestTypeFromContext` pattern and lets
250    /// you break down metrics by logical operation rather than route alone.
251    ///
252    /// Setting this without a metrics layer is a safe no-op.
253    ///
254    /// # Example
255    ///
256    /// ```ignore
257    /// client
258    ///     .get("https://api.example.com/tenants/123")
259    ///     .with_request_type("tenants_resolve")
260    ///     .send()
261    ///     .await?;
262    /// ```
263    pub fn with_request_type(mut self, t: impl Into<std::borrow::Cow<'static, str>>) -> Self {
264        self.request_type = Some(RequestType::new(t));
265        self
266    }
267
268    /// Set request body as JSON
269    ///
270    /// Serializes the value using `serde_json` and sets Content-Type to application/json.
271    /// unless a Content-Type header was already provided.
272    ///
273    /// # Errors
274    ///
275    /// Returns `Err(HttpError::Json)` if serialization fails.
276    ///
277    /// # Example
278    ///
279    /// ```ignore
280    /// #[derive(Serialize)]
281    /// struct CreateUser { name: String }
282    ///
283    /// let resp = client
284    ///     .post("https://api.example.com/users")
285    ///     .json(&CreateUser { name: "Alice".into() })?
286    ///     .send()
287    ///     .await?;
288    /// ```
289    pub fn json<T: Serialize>(mut self, body: &T) -> Result<Self, HttpError> {
290        if let Some(e) = self.error.take() {
291            return Err(e);
292        }
293
294        let json_bytes = serde_json::to_vec(body)?;
295        self.body = BodyKind::Json(Bytes::from(json_bytes));
296        Ok(self)
297    }
298
299    /// Set request body as form URL-encoded
300    ///
301    /// Serializes the fields and sets Content-Type to application/x-www-form-urlencoded.
302    /// unless a Content-Type header was already provided.
303    ///
304    /// # Errors
305    ///
306    /// Returns `Err(HttpError::FormEncode)` if encoding fails.
307    ///
308    /// # Example
309    ///
310    /// ```ignore
311    /// let resp = client
312    ///     .post("https://auth.example.com/token")
313    ///     .form(&[
314    ///         ("grant_type", "client_credentials"),
315    ///         ("client_id", "my-app"),
316    ///     ])?
317    ///     .send()
318    ///     .await?;
319    /// ```
320    pub fn form(mut self, fields: &[(&str, &str)]) -> Result<Self, HttpError> {
321        if let Some(e) = self.error.take() {
322            return Err(e);
323        }
324
325        let form_string = serde_urlencoded::to_string(fields)?;
326        self.body = BodyKind::Form(Bytes::from(form_string));
327        Ok(self)
328    }
329
330    /// Set request body as raw bytes
331    ///
332    /// # Example
333    ///
334    /// ```ignore
335    /// let resp = client
336    ///     .post("https://api.example.com/upload")
337    ///     .header("content-type", "application/octet-stream")
338    ///     .body_bytes(Bytes::from(file_contents))
339    ///     .send()
340    ///     .await?;
341    /// ```
342    pub fn body_bytes(mut self, body: Bytes) -> Self {
343        self.body = BodyKind::Bytes(body);
344        self
345    }
346
347    /// Set request body as a string
348    ///
349    /// # Example
350    ///
351    /// ```ignore
352    /// let resp = client
353    ///     .post("https://api.example.com/text")
354    ///     .header("content-type", "text/plain")
355    ///     .body_string("Hello, World!".into())
356    ///     .send()
357    ///     .await?;
358    /// ```
359    pub fn body_string(mut self, body: String) -> Self {
360        self.body = BodyKind::Bytes(Bytes::from(body));
361        self
362    }
363
364    /// Validate URL and scheme against transport security configuration.
365    ///
366    /// Uses proper `http::Uri` parsing instead of string prefix matching.
367    /// Returns the parsed URI on success for use in request building.
368    fn validate_url(&self) -> Result<http::Uri, HttpError> {
369        // Parse URL using http::Uri for proper validation
370        let uri: http::Uri =
371            self.url
372                .parse()
373                .map_err(|e: http::uri::InvalidUri| HttpError::InvalidUri {
374                    url: self.url.clone(),
375                    kind: InvalidUriKind::ParseError,
376                    reason: e.to_string(),
377                })?;
378
379        // Require authority (host) for absolute URLs
380        if uri.authority().is_none() {
381            return Err(HttpError::InvalidUri {
382                url: self.url.clone(),
383                kind: InvalidUriKind::MissingAuthority,
384                reason: "missing host/authority".to_owned(),
385            });
386        }
387
388        // Validate scheme
389        match uri.scheme_str() {
390            Some("https") => Ok(uri),
391            Some("http") => match self.transport_security {
392                TransportSecurity::AllowInsecureHttp => Ok(uri),
393                TransportSecurity::TlsOnly => Err(HttpError::InvalidScheme {
394                    scheme: "http".to_owned(),
395                    reason: "HTTPS required (transport security is TlsOnly)".to_owned(),
396                }),
397            },
398            Some(scheme) => Err(HttpError::InvalidScheme {
399                scheme: scheme.to_owned(),
400                reason: "only http:// and https:// schemes are supported".to_owned(),
401            }),
402            None => Err(HttpError::InvalidUri {
403                url: self.url.clone(),
404                kind: InvalidUriKind::MissingScheme,
405                reason: "missing scheme".to_owned(),
406            }),
407        }
408    }
409
410    /// Send the request and return the response
411    ///
412    /// # Errors
413    ///
414    /// Returns `HttpError` if:
415    /// - Request building failed (invalid headers, URL, etc.)
416    /// - URL scheme is invalid for the transport security mode
417    /// - Network/transport error
418    /// - Request timeout
419    /// - Concurrency limit reached (`Overloaded`)
420    ///
421    /// # Example
422    ///
423    /// ```ignore
424    /// let resp = client
425    ///     .get("https://api.example.com/data")
426    ///     .send()
427    ///     .await?;
428    ///
429    /// let data: MyData = resp.json().await?;
430    /// ```
431    pub async fn send(mut self) -> Result<HttpResponse, HttpError> {
432        // Return any deferred error
433        if let Some(e) = self.error.take() {
434            return Err(e);
435        }
436
437        // Validate URL and scheme against transport security
438        let uri = self.validate_url()?;
439
440        // Build the request using the validated URI
441        let mut builder = Request::builder().method(self.method).uri(uri);
442
443        // Add default Content-Type only if caller didn't supply one
444        let has_content_type = self
445            .headers
446            .iter()
447            .any(|(name, _)| name == http::header::CONTENT_TYPE);
448        if !has_content_type {
449            match &self.body {
450                BodyKind::Json(_) => {
451                    builder = builder.header("content-type", "application/json");
452                }
453                BodyKind::Form(_) => {
454                    builder = builder.header("content-type", "application/x-www-form-urlencoded");
455                }
456                BodyKind::Empty | BodyKind::Bytes(_) => {}
457            }
458        }
459
460        // Add user-provided headers
461        // Note: We checked has_content_type above to avoid duplicates. The http builder
462        // appends headers rather than replacing, so if user provided Content-Type,
463        // we skipped the default above and only their header is added here.
464        for (name, value) in self.headers {
465            builder = builder.header(name, value);
466        }
467
468        // Attach request_type extension so the metrics layer can read it without
469        // accessing the request body or headers (go-appkit analogue: context value).
470        if let Some(rt) = self.request_type {
471            builder = builder.extension(rt);
472        }
473
474        // Build body
475        let body_bytes = match self.body {
476            BodyKind::Empty => Bytes::new(),
477            BodyKind::Bytes(b) | BodyKind::Json(b) | BodyKind::Form(b) => b,
478        };
479
480        let request = builder.body(Full::new(body_bytes))?;
481
482        // Fail-fast if buffer is full
483        try_acquire_buffer_slot(&mut self.service).await?;
484
485        let inner: Response<ResponseBody> =
486            self.service.call(request).await.map_err(map_buffer_error)?;
487
488        Ok(HttpResponse {
489            inner,
490            max_body_size: self.max_body_size,
491        })
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use crate::HttpClient;
498
499    #[tokio::test]
500    async fn bearer_auth_sets_sensitive_authorization_header() {
501        let client = HttpClient::new().expect("default toolkit-http build");
502        let builder = client
503            .get("https://example.invalid/x")
504            .bearer_auth("secret-token");
505
506        let value = builder
507            .headers
508            .iter()
509            .find(|(name, _)| *name == http::header::AUTHORIZATION)
510            .map(|(_, value)| value)
511            .expect("authorization header present");
512
513        assert_eq!(value.to_str().unwrap(), "Bearer secret-token");
514        assert!(
515            value.is_sensitive(),
516            "bearer Authorization header must be marked sensitive"
517        );
518    }
519}