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    /// Typed values for the client's layers (never sent on the wire)
122    extensions: http::Extensions,
123}
124
125impl RequestBuilder {
126    /// Create a new request builder (internal use only)
127    pub(crate) fn new(
128        service: BufferedService,
129        max_body_size: usize,
130        method: http::Method,
131        url: String,
132        transport_security: TransportSecurity,
133    ) -> Self {
134        Self {
135            service,
136            max_body_size,
137            method,
138            url,
139            headers: Vec::new(),
140            body: BodyKind::Empty,
141            error: None,
142            transport_security,
143            request_type: None,
144            extensions: http::Extensions::new(),
145        }
146    }
147
148    /// Add a single header to the request
149    ///
150    /// # Example
151    ///
152    /// ```ignore
153    /// let resp = client
154    ///     .get("https://api.example.com")
155    ///     .header("authorization", "Bearer token")
156    ///     .header("x-request-id", "abc123")
157    ///     .send()
158    ///     .await?;
159    /// ```
160    pub fn header(mut self, name: &str, value: &str) -> Self {
161        if self.error.is_some() {
162            return self;
163        }
164
165        match (
166            http::header::HeaderName::try_from(name),
167            http::header::HeaderValue::try_from(value),
168        ) {
169            (Ok(name), Ok(value)) => {
170                self.headers.push((name, value));
171            }
172            (Err(e), _) => {
173                self.error = Some(HttpError::InvalidHeaderName(e));
174            }
175            (_, Err(e)) => {
176                self.error = Some(HttpError::InvalidHeaderValue(e));
177            }
178        }
179        self
180    }
181
182    /// Attach a tenant-plane bearer token as a **sensitive** `Authorization`
183    /// header (`Authorization: Bearer <token>`).
184    ///
185    /// The header value is marked sensitive (`HeaderValue::set_sensitive(true)`)
186    /// so header-logging / redaction layers never emit it — the same guarantee
187    /// as [`crate::security::attach_bearer_http`]. Prefer this over
188    /// `.header("authorization", ..)` for credentials, which cannot mark the
189    /// value sensitive. `token` is the raw credential; the `Bearer ` scheme is
190    /// prepended here.
191    pub fn bearer_auth(mut self, token: &str) -> Self {
192        if self.error.is_some() {
193            return self;
194        }
195        match http::header::HeaderValue::try_from(format!("Bearer {token}")) {
196            Ok(mut value) => {
197                value.set_sensitive(true);
198                self.headers.push((http::header::AUTHORIZATION, value));
199            }
200            Err(e) => {
201                self.error = Some(HttpError::InvalidHeaderValue(e));
202            }
203        }
204        self
205    }
206
207    /// Attach a platform-plane internal `token` as a **sensitive**
208    /// `X-ToolKit-Internal-Token` header.
209    ///
210    /// Carried raw (no `Bearer`) and **never** on `Authorization`, to avoid
211    /// colliding with the tenant-plane JWT (`cpt-cf-adr-two-plane-auth`). The
212    /// value is marked sensitive so logging/redaction layers never emit it —
213    /// prefer this over `.header(..)`, which cannot. Takes a
214    /// [`secrecy::SecretString`] and exposes it only here at the transport
215    /// boundary, so callers never hold a bare `&str` of the token.
216    pub fn internal_token_auth(mut self, token: &secrecy::SecretString) -> Self {
217        use secrecy::ExposeSecret as _;
218        if self.error.is_some() {
219            return self;
220        }
221        match http::header::HeaderValue::try_from(token.expose_secret()) {
222            Ok(mut value) => {
223                value.set_sensitive(true);
224                self.headers.push((
225                    http::header::HeaderName::from_static(
226                        toolkit_security::constants::INTERNAL_TOKEN_HEADER,
227                    ),
228                    value,
229                ));
230            }
231            Err(e) => {
232                self.error = Some(HttpError::InvalidHeaderValue(e));
233            }
234        }
235        self
236    }
237
238    /// Add multiple headers to the request
239    ///
240    /// # Example
241    ///
242    /// ```ignore
243    /// let resp = client
244    ///     .get("https://api.example.com")
245    ///     .headers(vec![
246    ///         ("authorization".to_owned(), "Bearer token".to_owned()),
247    ///         ("x-request-id".to_owned(), "abc123".to_owned()),
248    ///     ])
249    ///     .send()
250    ///     .await?;
251    /// ```
252    pub fn headers(mut self, headers: Vec<(String, String)>) -> Self {
253        if self.error.is_some() {
254            return self;
255        }
256
257        for (name, value) in headers {
258            match (
259                http::header::HeaderName::try_from(name),
260                http::header::HeaderValue::try_from(value),
261            ) {
262                (Ok(name), Ok(value)) => {
263                    self.headers.push((name, value));
264                }
265                (Err(e), _) => {
266                    self.error = Some(HttpError::InvalidHeaderName(e));
267                    return self;
268                }
269                (_, Err(e)) => {
270                    self.error = Some(HttpError::InvalidHeaderValue(e));
271                    return self;
272                }
273            }
274        }
275        self
276    }
277
278    /// Attach a `request_type` label for metrics.
279    ///
280    /// The label is added as a `request_type` attribute on the
281    /// `http.client.request.duration` histogram when the `otel` feature and a
282    /// metrics layer are configured. This mirrors go-appkit's
283    /// `NewContextWithRequestType` / `GetRequestTypeFromContext` pattern and lets
284    /// you break down metrics by logical operation rather than route alone.
285    ///
286    /// Setting this without a metrics layer is a safe no-op.
287    ///
288    /// # Example
289    ///
290    /// ```ignore
291    /// client
292    ///     .get("https://api.example.com/tenants/123")
293    ///     .with_request_type("tenants_resolve")
294    ///     .send()
295    ///     .await?;
296    /// ```
297    pub fn with_request_type(mut self, t: impl Into<std::borrow::Cow<'static, str>>) -> Self {
298        self.request_type = Some(RequestType::new(t));
299        self
300    }
301
302    /// Attach a typed value for the client's layers to read, such as a marker
303    /// that tells a circuit breaker to let this request through. Extensions
304    /// are never sent on the wire.
305    pub fn extension<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
306        self.extensions.insert(value);
307        self
308    }
309
310    /// Set request body as JSON
311    ///
312    /// Serializes the value using `serde_json` and sets Content-Type to application/json.
313    /// unless a Content-Type header was already provided.
314    ///
315    /// # Errors
316    ///
317    /// Returns `Err(HttpError::Json)` if serialization fails.
318    ///
319    /// # Example
320    ///
321    /// ```ignore
322    /// #[derive(Serialize)]
323    /// struct CreateUser { name: String }
324    ///
325    /// let resp = client
326    ///     .post("https://api.example.com/users")
327    ///     .json(&CreateUser { name: "Alice".into() })?
328    ///     .send()
329    ///     .await?;
330    /// ```
331    pub fn json<T: Serialize>(mut self, body: &T) -> Result<Self, HttpError> {
332        if let Some(e) = self.error.take() {
333            return Err(e);
334        }
335
336        let json_bytes = serde_json::to_vec(body)?;
337        self.body = BodyKind::Json(Bytes::from(json_bytes));
338        Ok(self)
339    }
340
341    /// Set request body as form URL-encoded
342    ///
343    /// Serializes the fields and sets Content-Type to application/x-www-form-urlencoded.
344    /// unless a Content-Type header was already provided.
345    ///
346    /// # Errors
347    ///
348    /// Returns `Err(HttpError::FormEncode)` if encoding fails.
349    ///
350    /// # Example
351    ///
352    /// ```ignore
353    /// let resp = client
354    ///     .post("https://auth.example.com/token")
355    ///     .form(&[
356    ///         ("grant_type", "client_credentials"),
357    ///         ("client_id", "my-app"),
358    ///     ])?
359    ///     .send()
360    ///     .await?;
361    /// ```
362    pub fn form(mut self, fields: &[(&str, &str)]) -> Result<Self, HttpError> {
363        if let Some(e) = self.error.take() {
364            return Err(e);
365        }
366
367        let form_string = serde_urlencoded::to_string(fields)?;
368        self.body = BodyKind::Form(Bytes::from(form_string));
369        Ok(self)
370    }
371
372    /// Set request body as raw bytes
373    ///
374    /// # Example
375    ///
376    /// ```ignore
377    /// let resp = client
378    ///     .post("https://api.example.com/upload")
379    ///     .header("content-type", "application/octet-stream")
380    ///     .body_bytes(Bytes::from(file_contents))
381    ///     .send()
382    ///     .await?;
383    /// ```
384    pub fn body_bytes(mut self, body: Bytes) -> Self {
385        self.body = BodyKind::Bytes(body);
386        self
387    }
388
389    /// Set request body as a string
390    ///
391    /// # Example
392    ///
393    /// ```ignore
394    /// let resp = client
395    ///     .post("https://api.example.com/text")
396    ///     .header("content-type", "text/plain")
397    ///     .body_string("Hello, World!".into())
398    ///     .send()
399    ///     .await?;
400    /// ```
401    pub fn body_string(mut self, body: String) -> Self {
402        self.body = BodyKind::Bytes(Bytes::from(body));
403        self
404    }
405
406    /// Validate URL and scheme against transport security configuration.
407    ///
408    /// Uses proper `http::Uri` parsing instead of string prefix matching.
409    /// Returns the parsed URI on success for use in request building.
410    fn validate_url(&self) -> Result<http::Uri, HttpError> {
411        // Parse URL using http::Uri for proper validation
412        let uri: http::Uri =
413            self.url
414                .parse()
415                .map_err(|e: http::uri::InvalidUri| HttpError::InvalidUri {
416                    url: self.url.clone(),
417                    kind: InvalidUriKind::ParseError,
418                    reason: e.to_string(),
419                })?;
420
421        // Require authority (host) for absolute URLs
422        if uri.authority().is_none() {
423            return Err(HttpError::InvalidUri {
424                url: self.url.clone(),
425                kind: InvalidUriKind::MissingAuthority,
426                reason: "missing host/authority".to_owned(),
427            });
428        }
429
430        // Validate scheme
431        match uri.scheme_str() {
432            Some("https") => Ok(uri),
433            Some("http") => match self.transport_security {
434                TransportSecurity::AllowInsecureHttp => Ok(uri),
435                TransportSecurity::TlsOnly => Err(HttpError::InvalidScheme {
436                    scheme: "http".to_owned(),
437                    reason: "HTTPS required (transport security is TlsOnly)".to_owned(),
438                }),
439            },
440            Some(scheme) => Err(HttpError::InvalidScheme {
441                scheme: scheme.to_owned(),
442                reason: "only http:// and https:// schemes are supported".to_owned(),
443            }),
444            None => Err(HttpError::InvalidUri {
445                url: self.url.clone(),
446                kind: InvalidUriKind::MissingScheme,
447                reason: "missing scheme".to_owned(),
448            }),
449        }
450    }
451
452    /// Send the request and return the response
453    ///
454    /// # Errors
455    ///
456    /// Returns `HttpError` if:
457    /// - Request building failed (invalid headers, URL, etc.)
458    /// - URL scheme is invalid for the transport security mode
459    /// - Network/transport error
460    /// - Request timeout
461    /// - Concurrency limit reached (`Overloaded`)
462    ///
463    /// # Example
464    ///
465    /// ```ignore
466    /// let resp = client
467    ///     .get("https://api.example.com/data")
468    ///     .send()
469    ///     .await?;
470    ///
471    /// let data: MyData = resp.json().await?;
472    /// ```
473    pub async fn send(mut self) -> Result<HttpResponse, HttpError> {
474        // Return any deferred error
475        if let Some(e) = self.error.take() {
476            return Err(e);
477        }
478
479        // Validate URL and scheme against transport security
480        let uri = self.validate_url()?;
481
482        // Build the request using the validated URI
483        let mut builder = Request::builder().method(self.method).uri(uri);
484
485        // Add default Content-Type only if caller didn't supply one
486        let has_content_type = self
487            .headers
488            .iter()
489            .any(|(name, _)| name == http::header::CONTENT_TYPE);
490        if !has_content_type {
491            match &self.body {
492                BodyKind::Json(_) => {
493                    builder = builder.header("content-type", "application/json");
494                }
495                BodyKind::Form(_) => {
496                    builder = builder.header("content-type", "application/x-www-form-urlencoded");
497                }
498                BodyKind::Empty | BodyKind::Bytes(_) => {}
499            }
500        }
501
502        // Add user-provided headers
503        // Note: We checked has_content_type above to avoid duplicates. The http builder
504        // appends headers rather than replacing, so if user provided Content-Type,
505        // we skipped the default above and only their header is added here.
506        for (name, value) in self.headers {
507            builder = builder.header(name, value);
508        }
509
510        // Attach request_type extension so the metrics layer can read it without
511        // accessing the request body or headers (go-appkit analogue: context value).
512        if let Some(rt) = self.request_type {
513            builder = builder.extension(rt);
514        }
515
516        // Build body
517        let body_bytes = match self.body {
518            BodyKind::Empty => Bytes::new(),
519            BodyKind::Bytes(b) | BodyKind::Json(b) | BodyKind::Form(b) => b,
520        };
521
522        let mut request = builder.body(Full::new(body_bytes))?;
523        request.extensions_mut().extend(self.extensions);
524
525        // Forward the chain-scoped `x-request-id` of the request being served,
526        // if any. Runs here (not as a layer) because `Buffer` dispatches on a
527        // worker task that sees no task-locals — see `inject_request_id`.
528        toolkit_trace_context::inject_request_id(request.headers_mut());
529
530        // Fail-fast if buffer is full
531        try_acquire_buffer_slot(&mut self.service).await?;
532
533        let inner: Response<ResponseBody> =
534            self.service.call(request).await.map_err(map_buffer_error)?;
535
536        Ok(HttpResponse {
537            inner,
538            max_body_size: self.max_body_size,
539        })
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use crate::HttpClient;
546    use crate::error::HttpError;
547
548    #[tokio::test]
549    async fn bearer_auth_sets_sensitive_authorization_header() {
550        let client = HttpClient::new().expect("default toolkit-http build");
551        let builder = client
552            .get("https://example.invalid/x")
553            .bearer_auth("secret-token");
554
555        let value = builder
556            .headers
557            .iter()
558            .find(|(name, _)| *name == http::header::AUTHORIZATION)
559            .map(|(_, value)| value)
560            .expect("authorization header present");
561
562        assert_eq!(value.to_str().unwrap(), "Bearer secret-token");
563        assert!(
564            value.is_sensitive(),
565            "bearer Authorization header must be marked sensitive"
566        );
567    }
568
569    #[tokio::test]
570    async fn internal_token_auth_sets_sensitive_dedicated_header() {
571        let client = HttpClient::new().expect("default toolkit-http build");
572        let builder = client
573            .get("https://example.invalid/x")
574            .internal_token_auth(&secrecy::SecretString::from("sa.jwt.token".to_owned()));
575
576        assert!(builder.error.is_none(), "valid token must not set an error");
577
578        let header_name = http::header::HeaderName::from_static(
579            toolkit_security::constants::INTERNAL_TOKEN_HEADER,
580        );
581        let value = builder
582            .headers
583            .iter()
584            .find(|(name, _)| *name == header_name)
585            .map(|(_, value)| value)
586            .expect("internal-token header present");
587
588        assert_eq!(
589            value.to_str().unwrap(),
590            "sa.jwt.token",
591            "internal token is carried raw (no Bearer scheme)"
592        );
593        assert!(
594            value.is_sensitive(),
595            "internal-token header must be marked sensitive so logging layers never emit it"
596        );
597        // It must NEVER ride Authorization.
598        assert!(
599            !builder
600                .headers
601                .iter()
602                .any(|(name, _)| *name == http::header::AUTHORIZATION),
603            "internal token must not collide with the tenant-plane Authorization header"
604        );
605    }
606
607    #[tokio::test]
608    async fn internal_token_auth_records_error_and_does_not_add_header_for_invalid_value() {
609        let client = HttpClient::new().expect("default toolkit-http build");
610        // A newline is not a valid header value; the builder must record an
611        // error (so `.send()` fails) rather than sending the request
612        // unauthenticated.
613        let builder = client
614            .get("https://example.invalid/x")
615            .internal_token_auth(&secrecy::SecretString::from("bad\ntoken".to_owned()));
616
617        assert!(
618            matches!(builder.error, Some(HttpError::InvalidHeaderValue(_))),
619            "a malformed internal token must record InvalidHeaderValue"
620        );
621        let header_name = http::header::HeaderName::from_static(
622            toolkit_security::constants::INTERNAL_TOKEN_HEADER,
623        );
624        assert!(
625            !builder.headers.iter().any(|(name, _)| *name == header_name),
626            "no header must be added when the token is invalid"
627        );
628    }
629}