cf-gears-toolkit-http 0.6.17

ToolKit HTTP client library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use crate::client::{BufferedService, map_buffer_error, try_acquire_buffer_slot};
use crate::config::TransportSecurity;
use crate::error::{HttpError, InvalidUriKind};
use crate::response::{HttpResponse, ResponseBody};
use bytes::Bytes;
use http::{Request, Response};
use http_body_util::Full;
use serde::Serialize;
use tower::Service;

/// Body type for the request builder
#[derive(Clone, Debug)]
enum BodyKind {
    /// Empty body
    Empty,
    /// Raw bytes body
    Bytes(Bytes),
    /// JSON-serialized body (stored as bytes after serialization)
    Json(Bytes),
    /// Form URL-encoded body (stored as bytes after serialization)
    Form(Bytes),
}

/// Per-request label for the `request_type` metrics attribute.
///
/// Attach to a request via [`RequestBuilder::with_request_type`] to break down
/// `http.client.request.duration` metrics by logical operation (e.g.
/// `"tenants_resolve"`, `"token_fetch"`). This is the Rust analogue of
/// go-appkit's `NewContextWithRequestType` / `GetRequestTypeFromContext`.
///
/// The metrics layer reads this from request extensions when the `otel` feature
/// is enabled; setting it without the feature is a safe no-op.
///
/// # Example
///
/// ```ignore
/// client
///     .get("https://api.example.com/tenants/123")
///     .with_request_type("tenants_resolve")
///     .send()
///     .await?;
/// ```
#[derive(Clone, Debug)]
pub struct RequestType(pub std::borrow::Cow<'static, str>);

impl RequestType {
    /// Create a request type label from a static string.
    #[must_use]
    pub fn new(t: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        Self(t.into())
    }
}

/// HTTP request builder with fluent API
///
/// Created by [`HttpClient::get`], [`HttpClient::post`], etc.
/// Supports chaining headers and body configuration before sending
/// with [`send()`](RequestBuilder::send).
///
/// # URL Construction
///
/// This crate does **not** provide query-string composition. Build your URL
/// externally (e.g. via `url::Url`) and pass the final string to `HttpClient`:
///
/// ```ignore
/// use url::Url;
/// use toolkit_http::HttpClient;
///
/// let mut url = Url::parse("https://api.example.com/users")?;
/// url.query_pairs_mut()
///     .append_pair("page", "1")
///     .append_pair("limit", "10");
///
/// let client = HttpClient::builder().build()?;
/// let resp = client.get(url.as_str()).send().await?;
/// ```
///
/// # Example
///
/// ```ignore
/// use toolkit_http::HttpClient;
///
/// let client = HttpClient::builder().build()?;
///
/// // Simple GET
/// let resp = client
///     .get("https://api.example.com/users")
///     .send()
///     .await?;
///
/// // POST with JSON body
/// let resp = client
///     .post("https://api.example.com/users")
///     .header("x-request-id", "123")
///     .json(&NewUser { name: "Alice" })?
///     .send()
///     .await?;
///
/// // POST with form body
/// let resp = client
///     .post("https://auth.example.com/token")
///     .header("authorization", "Basic xyz")
///     .form(&[("grant_type", "client_credentials")])?
///     .send()
///     .await?;
/// ```
#[must_use = "RequestBuilder does nothing until .send() is called"]
pub struct RequestBuilder {
    service: BufferedService,
    max_body_size: usize,
    method: http::Method,
    url: String,
    headers: Vec<(http::header::HeaderName, http::header::HeaderValue)>,
    body: BodyKind,
    /// Error captured during building (deferred to `send()`)
    error: Option<HttpError>,
    /// Transport security mode for URL scheme validation
    transport_security: TransportSecurity,
    /// Optional per-request metrics label (read by the metrics layer)
    request_type: Option<RequestType>,
}

impl RequestBuilder {
    /// Create a new request builder (internal use only)
    pub(crate) fn new(
        service: BufferedService,
        max_body_size: usize,
        method: http::Method,
        url: String,
        transport_security: TransportSecurity,
    ) -> Self {
        Self {
            service,
            max_body_size,
            method,
            url,
            headers: Vec::new(),
            body: BodyKind::Empty,
            error: None,
            transport_security,
            request_type: None,
        }
    }

    /// Add a single header to the request
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .get("https://api.example.com")
    ///     .header("authorization", "Bearer token")
    ///     .header("x-request-id", "abc123")
    ///     .send()
    ///     .await?;
    /// ```
    pub fn header(mut self, name: &str, value: &str) -> Self {
        if self.error.is_some() {
            return self;
        }

        match (
            http::header::HeaderName::try_from(name),
            http::header::HeaderValue::try_from(value),
        ) {
            (Ok(name), Ok(value)) => {
                self.headers.push((name, value));
            }
            (Err(e), _) => {
                self.error = Some(HttpError::InvalidHeaderName(e));
            }
            (_, Err(e)) => {
                self.error = Some(HttpError::InvalidHeaderValue(e));
            }
        }
        self
    }

    /// Attach a tenant-plane bearer token as a **sensitive** `Authorization`
    /// header (`Authorization: Bearer <token>`).
    ///
    /// The header value is marked sensitive (`HeaderValue::set_sensitive(true)`)
    /// so header-logging / redaction layers never emit it — the same guarantee
    /// as [`crate::security::attach_bearer_http`]. Prefer this over
    /// `.header("authorization", ..)` for credentials, which cannot mark the
    /// value sensitive. `token` is the raw credential; the `Bearer ` scheme is
    /// prepended here.
    pub fn bearer_auth(mut self, token: &str) -> Self {
        if self.error.is_some() {
            return self;
        }
        match http::header::HeaderValue::try_from(format!("Bearer {token}")) {
            Ok(mut value) => {
                value.set_sensitive(true);
                self.headers.push((http::header::AUTHORIZATION, value));
            }
            Err(e) => {
                self.error = Some(HttpError::InvalidHeaderValue(e));
            }
        }
        self
    }

    /// Attach a platform-plane internal `token` as a **sensitive**
    /// `X-ToolKit-Internal-Token` header.
    ///
    /// Carried raw (no `Bearer`) and **never** on `Authorization`, to avoid
    /// colliding with the tenant-plane JWT (`cpt-cf-adr-two-plane-auth`). The
    /// value is marked sensitive so logging/redaction layers never emit it —
    /// prefer this over `.header(..)`, which cannot. Takes a
    /// [`secrecy::SecretString`] and exposes it only here at the transport
    /// boundary, so callers never hold a bare `&str` of the token.
    pub fn internal_token_auth(mut self, token: &secrecy::SecretString) -> Self {
        use secrecy::ExposeSecret as _;
        if self.error.is_some() {
            return self;
        }
        match http::header::HeaderValue::try_from(token.expose_secret()) {
            Ok(mut value) => {
                value.set_sensitive(true);
                self.headers.push((
                    http::header::HeaderName::from_static(
                        toolkit_security::constants::INTERNAL_TOKEN_HEADER,
                    ),
                    value,
                ));
            }
            Err(e) => {
                self.error = Some(HttpError::InvalidHeaderValue(e));
            }
        }
        self
    }

    /// Add multiple headers to the request
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .get("https://api.example.com")
    ///     .headers(vec![
    ///         ("authorization".to_owned(), "Bearer token".to_owned()),
    ///         ("x-request-id".to_owned(), "abc123".to_owned()),
    ///     ])
    ///     .send()
    ///     .await?;
    /// ```
    pub fn headers(mut self, headers: Vec<(String, String)>) -> Self {
        if self.error.is_some() {
            return self;
        }

        for (name, value) in headers {
            match (
                http::header::HeaderName::try_from(name),
                http::header::HeaderValue::try_from(value),
            ) {
                (Ok(name), Ok(value)) => {
                    self.headers.push((name, value));
                }
                (Err(e), _) => {
                    self.error = Some(HttpError::InvalidHeaderName(e));
                    return self;
                }
                (_, Err(e)) => {
                    self.error = Some(HttpError::InvalidHeaderValue(e));
                    return self;
                }
            }
        }
        self
    }

    /// Attach a `request_type` label for metrics.
    ///
    /// The label is added as a `request_type` attribute on the
    /// `http.client.request.duration` histogram when the `otel` feature and a
    /// metrics layer are configured. This mirrors go-appkit's
    /// `NewContextWithRequestType` / `GetRequestTypeFromContext` pattern and lets
    /// you break down metrics by logical operation rather than route alone.
    ///
    /// Setting this without a metrics layer is a safe no-op.
    ///
    /// # Example
    ///
    /// ```ignore
    /// client
    ///     .get("https://api.example.com/tenants/123")
    ///     .with_request_type("tenants_resolve")
    ///     .send()
    ///     .await?;
    /// ```
    pub fn with_request_type(mut self, t: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        self.request_type = Some(RequestType::new(t));
        self
    }

    /// Set request body as JSON
    ///
    /// Serializes the value using `serde_json` and sets Content-Type to application/json.
    /// unless a Content-Type header was already provided.
    ///
    /// # Errors
    ///
    /// Returns `Err(HttpError::Json)` if serialization fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[derive(Serialize)]
    /// struct CreateUser { name: String }
    ///
    /// let resp = client
    ///     .post("https://api.example.com/users")
    ///     .json(&CreateUser { name: "Alice".into() })?
    ///     .send()
    ///     .await?;
    /// ```
    pub fn json<T: Serialize>(mut self, body: &T) -> Result<Self, HttpError> {
        if let Some(e) = self.error.take() {
            return Err(e);
        }

        let json_bytes = serde_json::to_vec(body)?;
        self.body = BodyKind::Json(Bytes::from(json_bytes));
        Ok(self)
    }

    /// Set request body as form URL-encoded
    ///
    /// Serializes the fields and sets Content-Type to application/x-www-form-urlencoded.
    /// unless a Content-Type header was already provided.
    ///
    /// # Errors
    ///
    /// Returns `Err(HttpError::FormEncode)` if encoding fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .post("https://auth.example.com/token")
    ///     .form(&[
    ///         ("grant_type", "client_credentials"),
    ///         ("client_id", "my-app"),
    ///     ])?
    ///     .send()
    ///     .await?;
    /// ```
    pub fn form(mut self, fields: &[(&str, &str)]) -> Result<Self, HttpError> {
        if let Some(e) = self.error.take() {
            return Err(e);
        }

        let form_string = serde_urlencoded::to_string(fields)?;
        self.body = BodyKind::Form(Bytes::from(form_string));
        Ok(self)
    }

    /// Set request body as raw bytes
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .post("https://api.example.com/upload")
    ///     .header("content-type", "application/octet-stream")
    ///     .body_bytes(Bytes::from(file_contents))
    ///     .send()
    ///     .await?;
    /// ```
    pub fn body_bytes(mut self, body: Bytes) -> Self {
        self.body = BodyKind::Bytes(body);
        self
    }

    /// Set request body as a string
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .post("https://api.example.com/text")
    ///     .header("content-type", "text/plain")
    ///     .body_string("Hello, World!".into())
    ///     .send()
    ///     .await?;
    /// ```
    pub fn body_string(mut self, body: String) -> Self {
        self.body = BodyKind::Bytes(Bytes::from(body));
        self
    }

    /// Validate URL and scheme against transport security configuration.
    ///
    /// Uses proper `http::Uri` parsing instead of string prefix matching.
    /// Returns the parsed URI on success for use in request building.
    fn validate_url(&self) -> Result<http::Uri, HttpError> {
        // Parse URL using http::Uri for proper validation
        let uri: http::Uri =
            self.url
                .parse()
                .map_err(|e: http::uri::InvalidUri| HttpError::InvalidUri {
                    url: self.url.clone(),
                    kind: InvalidUriKind::ParseError,
                    reason: e.to_string(),
                })?;

        // Require authority (host) for absolute URLs
        if uri.authority().is_none() {
            return Err(HttpError::InvalidUri {
                url: self.url.clone(),
                kind: InvalidUriKind::MissingAuthority,
                reason: "missing host/authority".to_owned(),
            });
        }

        // Validate scheme
        match uri.scheme_str() {
            Some("https") => Ok(uri),
            Some("http") => match self.transport_security {
                TransportSecurity::AllowInsecureHttp => Ok(uri),
                TransportSecurity::TlsOnly => Err(HttpError::InvalidScheme {
                    scheme: "http".to_owned(),
                    reason: "HTTPS required (transport security is TlsOnly)".to_owned(),
                }),
            },
            Some(scheme) => Err(HttpError::InvalidScheme {
                scheme: scheme.to_owned(),
                reason: "only http:// and https:// schemes are supported".to_owned(),
            }),
            None => Err(HttpError::InvalidUri {
                url: self.url.clone(),
                kind: InvalidUriKind::MissingScheme,
                reason: "missing scheme".to_owned(),
            }),
        }
    }

    /// Send the request and return the response
    ///
    /// # Errors
    ///
    /// Returns `HttpError` if:
    /// - Request building failed (invalid headers, URL, etc.)
    /// - URL scheme is invalid for the transport security mode
    /// - Network/transport error
    /// - Request timeout
    /// - Concurrency limit reached (`Overloaded`)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let resp = client
    ///     .get("https://api.example.com/data")
    ///     .send()
    ///     .await?;
    ///
    /// let data: MyData = resp.json().await?;
    /// ```
    pub async fn send(mut self) -> Result<HttpResponse, HttpError> {
        // Return any deferred error
        if let Some(e) = self.error.take() {
            return Err(e);
        }

        // Validate URL and scheme against transport security
        let uri = self.validate_url()?;

        // Build the request using the validated URI
        let mut builder = Request::builder().method(self.method).uri(uri);

        // Add default Content-Type only if caller didn't supply one
        let has_content_type = self
            .headers
            .iter()
            .any(|(name, _)| name == http::header::CONTENT_TYPE);
        if !has_content_type {
            match &self.body {
                BodyKind::Json(_) => {
                    builder = builder.header("content-type", "application/json");
                }
                BodyKind::Form(_) => {
                    builder = builder.header("content-type", "application/x-www-form-urlencoded");
                }
                BodyKind::Empty | BodyKind::Bytes(_) => {}
            }
        }

        // Add user-provided headers
        // Note: We checked has_content_type above to avoid duplicates. The http builder
        // appends headers rather than replacing, so if user provided Content-Type,
        // we skipped the default above and only their header is added here.
        for (name, value) in self.headers {
            builder = builder.header(name, value);
        }

        // Attach request_type extension so the metrics layer can read it without
        // accessing the request body or headers (go-appkit analogue: context value).
        if let Some(rt) = self.request_type {
            builder = builder.extension(rt);
        }

        // Build body
        let body_bytes = match self.body {
            BodyKind::Empty => Bytes::new(),
            BodyKind::Bytes(b) | BodyKind::Json(b) | BodyKind::Form(b) => b,
        };

        let request = builder.body(Full::new(body_bytes))?;

        // Fail-fast if buffer is full
        try_acquire_buffer_slot(&mut self.service).await?;

        let inner: Response<ResponseBody> =
            self.service.call(request).await.map_err(map_buffer_error)?;

        Ok(HttpResponse {
            inner,
            max_body_size: self.max_body_size,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::HttpClient;
    use crate::error::HttpError;

    #[tokio::test]
    async fn bearer_auth_sets_sensitive_authorization_header() {
        let client = HttpClient::new().expect("default toolkit-http build");
        let builder = client
            .get("https://example.invalid/x")
            .bearer_auth("secret-token");

        let value = builder
            .headers
            .iter()
            .find(|(name, _)| *name == http::header::AUTHORIZATION)
            .map(|(_, value)| value)
            .expect("authorization header present");

        assert_eq!(value.to_str().unwrap(), "Bearer secret-token");
        assert!(
            value.is_sensitive(),
            "bearer Authorization header must be marked sensitive"
        );
    }

    #[tokio::test]
    async fn internal_token_auth_sets_sensitive_dedicated_header() {
        let client = HttpClient::new().expect("default toolkit-http build");
        let builder = client
            .get("https://example.invalid/x")
            .internal_token_auth(&secrecy::SecretString::from("sa.jwt.token".to_owned()));

        assert!(builder.error.is_none(), "valid token must not set an error");

        let header_name = http::header::HeaderName::from_static(
            toolkit_security::constants::INTERNAL_TOKEN_HEADER,
        );
        let value = builder
            .headers
            .iter()
            .find(|(name, _)| *name == header_name)
            .map(|(_, value)| value)
            .expect("internal-token header present");

        assert_eq!(
            value.to_str().unwrap(),
            "sa.jwt.token",
            "internal token is carried raw (no Bearer scheme)"
        );
        assert!(
            value.is_sensitive(),
            "internal-token header must be marked sensitive so logging layers never emit it"
        );
        // It must NEVER ride Authorization.
        assert!(
            !builder
                .headers
                .iter()
                .any(|(name, _)| *name == http::header::AUTHORIZATION),
            "internal token must not collide with the tenant-plane Authorization header"
        );
    }

    #[tokio::test]
    async fn internal_token_auth_records_error_and_does_not_add_header_for_invalid_value() {
        let client = HttpClient::new().expect("default toolkit-http build");
        // A newline is not a valid header value; the builder must record an
        // error (so `.send()` fails) rather than sending the request
        // unauthenticated.
        let builder = client
            .get("https://example.invalid/x")
            .internal_token_auth(&secrecy::SecretString::from("bad\ntoken".to_owned()));

        assert!(
            matches!(builder.error, Some(HttpError::InvalidHeaderValue(_))),
            "a malformed internal token must record InvalidHeaderValue"
        );
        let header_name = http::header::HeaderName::from_static(
            toolkit_security::constants::INTERNAL_TOKEN_HEADER,
        );
        assert!(
            !builder.headers.iter().any(|(name, _)| *name == header_name),
            "no header must be added when the token is invalid"
        );
    }
}