specters 4.2.0

Rust HTTP client with browser-like Chrome and Firefox fingerprints across TLS, HTTP/1.1, HTTP/2, HTTP/3, and WebSockets
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
//! HTTP/2 connection handle - non-blocking interface for sending requests.
//!
//! The handle sends commands to a driver task and receives responses via channels.
//! Multiple handles can share the same driver, enabling true multiplexing.

use bytes::Bytes;
use http::{Method, Uri};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::io::WriteHalf;
use tokio::sync::{mpsc, oneshot};

use crate::error::{Error, Result};
use crate::headers::Headers;
use crate::request::RequestBody;
use crate::response::{Body, Response};
use crate::transport::connector::MaybeHttpsStream;
use crate::transport::h2::body::{H2Body, H2BodyShared, H2BodyTimeouts};
use crate::transport::h2::driver::{DriverCommand, InlineRegistration, StreamingHeadersResult};
use crate::transport::h2::tunnel::H2Tunnel;
use crate::transport::h2::write_half::H2WriteHalf;
use crate::transport::h2::H2TransportConfig;

/// Shared write/registration primer used by the inline streaming fast path.
///
/// `H2PooledConnection` builds one of these per pooled connection and shares
/// it with both the H2 driver and the H2 handle. The inline caller acquires
/// the write half via `Arc::clone`, writes HEADERS atomically alongside the
/// driver, and notifies the driver of the new stream via `register_tx`.
pub(crate) struct H2InlineState {
    pub(crate) write_half: Arc<H2WriteHalf<WriteHalf<MaybeHttpsStream>>>,
    pub(crate) peer_max_frame_size: Arc<AtomicU32>,
    pub(crate) initial_window_size: u32,
    pub(crate) register_tx: mpsc::UnboundedSender<InlineRegistration>,
    /// Counter used to enforce sequential eligibility. Incremented when an
    /// inline stream is in flight; decremented by the driver when the stream
    /// completes or is cancelled.
    pub(crate) inline_active: Arc<AtomicUsize>,
    /// Disabled while any RFC 8441 tunnel or pending body is in flight; the
    /// driver toggles this flag.
    pub(crate) inline_eligible: Arc<AtomicBool>,
    pub(crate) body_progress_notify: Arc<tokio::sync::Notify>,
    pub(crate) streaming_body_buffer_slots: usize,
}

/// HTTP/2 connection handle for sending requests
#[derive(Clone)]
pub struct H2Handle {
    /// Channel for sending commands to the driver
    command_tx: mpsc::Sender<DriverCommand>,
    /// Shared flag set when GOAWAY is received
    goaway_received: Arc<AtomicBool>,
    /// Optional inline streaming primer; absent in raw test contexts where
    /// no shared write half exists.
    inline: Option<Arc<H2InlineState>>,
    transport_config: H2TransportConfig,
    backpressure_stall_count: Arc<AtomicU64>,
}

impl H2Handle {
    /// Create a new handle with a command channel to the driver
    pub fn new(command_tx: mpsc::Sender<DriverCommand>, goaway_received: Arc<AtomicBool>) -> Self {
        Self::new_with_config(
            command_tx,
            goaway_received,
            H2TransportConfig::default(),
            Arc::new(AtomicU64::new(0)),
        )
    }

    pub(crate) fn new_with_config(
        command_tx: mpsc::Sender<DriverCommand>,
        goaway_received: Arc<AtomicBool>,
        transport_config: H2TransportConfig,
        backpressure_stall_count: Arc<AtomicU64>,
    ) -> Self {
        Self {
            command_tx,
            goaway_received,
            inline: None,
            transport_config: transport_config.normalized(),
            backpressure_stall_count,
        }
    }

    pub(crate) fn with_inline(
        command_tx: mpsc::Sender<DriverCommand>,
        goaway_received: Arc<AtomicBool>,
        inline: Arc<H2InlineState>,
        transport_config: H2TransportConfig,
        backpressure_stall_count: Arc<AtomicU64>,
    ) -> Self {
        Self {
            command_tx,
            goaway_received,
            inline: Some(inline),
            transport_config: transport_config.normalized(),
            backpressure_stall_count,
        }
    }

    /// Check if the driver is still running and hasn't received GOAWAY
    pub fn is_alive(&self) -> bool {
        !self.command_tx.is_closed() && !self.goaway_received.load(Ordering::Relaxed)
    }

    /// Bounded in-flight response DATA slots per streaming H2 body.
    pub fn streaming_body_buffer_slots(&self) -> usize {
        self.transport_config.streaming_body_buffer_slots
    }

    /// Number of times the driver slept 1 ms while streaming body work was
    /// pending. Useful for diagnosing bursty-server backpressure stalls.
    pub fn backpressure_stall_count(&self) -> u64 {
        self.backpressure_stall_count.load(Ordering::Relaxed)
    }

    /// Send an HTTP/2 request and receive the response.
    /// This is non-blocking - it sends the request to the driver and awaits the response channel.
    /// The driver allocates stream IDs internally.
    pub async fn send_request(
        &self,
        method: Method,
        uri: &Uri,
        headers: impl Into<Headers>,
        body: Option<Bytes>,
    ) -> Result<Response> {
        let (response_tx, response_rx) = oneshot::channel();
        let headers = headers.into();

        let command = DriverCommand::SendRequest {
            method,
            uri: uri.clone(),
            headers,
            body,
            response_tx,
        };

        self.command_tx
            .send(command)
            .await
            .map_err(|_| Error::HttpProtocol("Driver channel closed".into()))?;

        let stream_response = response_rx
            .await
            .map_err(|_| Error::HttpProtocol("Response channel closed".into()))??;

        Ok(Response::new(
            stream_response.status,
            Headers::from(stream_response.headers),
            stream_response.body,
            "HTTP/2".to_string(),
        ))
    }

    /// Send an HTTP/2 streaming request, preferring the inline shared-writer
    /// fast path for sequential body-less requests when eligible.
    /// Falls back to the driver command path otherwise.
    pub async fn send_streaming_request(
        &self,
        method: Method,
        uri: &Uri,
        headers: impl Into<Headers>,
        body: RequestBody,
        body_timeouts: H2BodyTimeouts,
    ) -> Result<Response> {
        let headers = headers.into();
        let body_is_empty = body.is_empty();
        if let Some(result) = self
            .try_send_streaming_inline(&method, uri, &headers, body_is_empty, body_timeouts)
            .await
        {
            return result;
        }
        self.send_streaming_request_command_path(method, uri, &headers, body, body_timeouts)
            .await
    }

    async fn send_streaming_request_command_path(
        &self,
        method: Method,
        uri: &Uri,
        headers: &Headers,
        body: RequestBody,
        body_timeouts: H2BodyTimeouts,
    ) -> Result<Response> {
        let (headers_tx, headers_rx) = oneshot::channel();
        // Allocate the trailer side channel ONLY when the caller requested
        // trailers (`te: trailers`). A warm non-gRPC streaming request - the
        // gate's TTFT path - constructs zero extra channels here.
        let (trailers_tx, trailers_rx) = if wants_trailers(headers) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let initial_window_size = self
            .inline
            .as_ref()
            .map(|inline| inline.initial_window_size)
            .unwrap_or(65_535);
        let body_shared = H2BodyShared::new_with_capacity(
            self.body_progress_notify(),
            initial_window_size,
            self.transport_config.streaming_body_buffer_slots,
        );

        let command = DriverCommand::SendStreamingRequest {
            method,
            uri: uri.clone(),
            headers: headers.clone(),
            body,
            body_shared: body_shared.clone(),
            headers_tx,
            trailers_tx,
        };

        self.command_tx
            .send(command)
            .await
            .map_err(|_| Error::HttpProtocol("Driver channel closed".into()))?;

        let (status, regular_headers) = headers_rx
            .await
            .map_err(|_| Error::HttpProtocol("Headers channel closed".into()))??;

        Ok(Response::with_body(
            status,
            Headers::from(regular_headers),
            Body::from_h2(H2Body::new_with_trailers(
                body_shared,
                body_timeouts,
                trailers_rx,
            )),
            "HTTP/2".to_string(),
        ))
    }

    /// Attempt the inline shared-writer streaming fast path. Returns
    /// `Some(result)` when the path was attempted (either successfully or
    /// with a transport error), or `None` when the request is ineligible
    /// and the caller must use the command path fallback.
    async fn try_send_streaming_inline(
        &self,
        method: &Method,
        uri: &Uri,
        headers: &Headers,
        body_is_empty: bool,
        body_timeouts: H2BodyTimeouts,
    ) -> Option<Result<Response>> {
        let inline = self.inline.as_ref()?;
        if !self.is_alive() {
            return None;
        }
        if !body_is_empty {
            return None;
        }
        if !inline.inline_eligible.load(Ordering::Relaxed) {
            return None;
        }

        if inline
            .inline_active
            .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return None;
        }

        let (headers_tx, headers_rx) = oneshot::channel::<StreamingHeadersResult>();
        // Allocate the trailer side channel ONLY when the caller requested
        // trailers (`te: trailers`). A warm non-gRPC inline streaming request
        // constructs zero extra channels here.
        let (trailers_tx, trailers_rx) = if wants_trailers(headers) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let body_shared = H2BodyShared::new_with_capacity(
            inline.body_progress_notify.clone(),
            inline.initial_window_size,
            inline.streaming_body_buffer_slots,
        );

        let max_frame_size = inline.peer_max_frame_size.load(Ordering::Relaxed) as usize;
        let stream_id = match inline
            .write_half
            .write_request_headers(method, uri, headers, true, max_frame_size)
            .await
        {
            Ok(id) => id,
            Err(error) => {
                inline.inline_active.fetch_sub(1, Ordering::AcqRel);
                return Some(Err(error));
            }
        };

        let registration = InlineRegistration {
            stream_id,
            headers_tx,
            body_shared: body_shared.clone(),
            recv_window: inline.initial_window_size as i32,
            trailers_tx,
        };

        if inline.register_tx.send(registration).is_err() {
            inline.inline_active.fetch_sub(1, Ordering::AcqRel);
            return Some(Err(Error::HttpProtocol("Driver channel closed".into())));
        }

        let result = match headers_rx.await {
            Ok(Ok((status, regular_headers))) => Ok(Response::with_body(
                status,
                Headers::from(regular_headers),
                Body::from_h2(H2Body::new_with_trailers(
                    body_shared,
                    body_timeouts,
                    trailers_rx,
                )),
                "HTTP/2".to_string(),
            )),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(Error::HttpProtocol("Headers channel closed".into())),
        };

        Some(result)
    }

    fn body_progress_notify(&self) -> Arc<tokio::sync::Notify> {
        self.inline
            .as_ref()
            .map(|inline| inline.body_progress_notify.clone())
            .unwrap_or_else(|| Arc::new(tokio::sync::Notify::new()))
    }

    /// Open an RFC 8441 WebSocket tunnel through the background H2 driver.
    pub async fn open_websocket_tunnel(
        &self,
        uri: Uri,
        headers: impl Into<Headers>,
    ) -> Result<H2Tunnel> {
        let (response_tx, response_rx) = oneshot::channel();
        let headers = headers.into();

        self.command_tx
            .send(DriverCommand::OpenWebSocketTunnel {
                uri,
                headers: headers.to_vec(),
                response_tx,
            })
            .await
            .map_err(|_| Error::HttpProtocol("Driver channel closed".into()))?;

        response_rx
            .await
            .map_err(|_| Error::HttpProtocol("Tunnel response channel closed".into()))?
    }
}

/// Whether the caller asked for HTTP/2 response trailers, signalled by a
/// `te: trailers` request header (the gRPC convention; `te` may be a
/// comma-separated list, or spread across multiple `te` header lines).
/// Scans all `te` lines so that `te: deflate` + `te: trailers` on separate
/// lines is detected correctly. Allocates nothing when `te` is absent -
/// the warm non-gRPC streaming path. This is the free signal that gates
/// trailer-channel allocation at both streaming construction sites.
fn wants_trailers(headers: &Headers) -> bool {
    headers.get_all("te").iter().any(|value| {
        value
            .split(',')
            .any(|token| token.trim().eq_ignore_ascii_case("trailers"))
    })
}

#[cfg(test)]
mod tests {
    use super::wants_trailers;
    use crate::headers::Headers;
    use crate::request::RequestBody;
    use crate::transport::h2::body::H2BodyShared;
    use crate::transport::h2::driver::{DriverCommand, InlineRegistration};
    use std::sync::Arc;
    use tokio::sync::{oneshot, Notify};

    #[test]
    fn wants_trailers_false_without_te() {
        let headers = Headers::from_vec(vec![(
            "content-type".to_string(),
            "application/grpc+proto".to_string(),
        )]);
        assert!(!wants_trailers(&headers));
    }

    #[test]
    fn wants_trailers_true_for_te_trailers() {
        let headers = Headers::from_vec(vec![("te".to_string(), "trailers".to_string())]);
        assert!(wants_trailers(&headers));
    }

    #[test]
    fn wants_trailers_true_in_te_list_and_case_insensitive() {
        let headers = Headers::from_vec(vec![("TE".to_string(), "deflate, Trailers".to_string())]);
        assert!(wants_trailers(&headers));
    }

    #[test]
    fn wants_trailers_false_for_unrelated_te() {
        let headers = Headers::from_vec(vec![("te".to_string(), "deflate, gzip".to_string())]);
        assert!(!wants_trailers(&headers));
    }

    #[test]
    fn wants_trailers_true_for_separate_te_lines() {
        // Two separate `te` header lines: first carries only `deflate`,
        // second carries `trailers`. A single `headers.get("te")` call would
        // return only the first line and miss the signal; `get_all` must be used.
        let headers = Headers::from_vec(vec![
            ("te".to_string(), "deflate".to_string()),
            ("te".to_string(), "trailers".to_string()),
        ]);
        assert!(wants_trailers(&headers));
    }

    // Structural no-alloc tests: confirm that the trailer-channel sender
    // field (`trailers_tx`) is `None` for requests that do not carry
    // `te: trailers`, and `Some` for those that do.

    fn make_body_shared() -> Arc<H2BodyShared> {
        H2BodyShared::new_with_capacity(Arc::new(Notify::new()), 65_535, 16)
    }

    #[test]
    fn send_streaming_request_command_no_te_has_no_trailers_tx() {
        let headers_without_te = Headers::from_vec(vec![(
            "content-type".to_string(),
            "application/grpc+proto".to_string(),
        )]);
        let (headers_tx, _headers_rx) = oneshot::channel();
        let (trailers_tx, _trailers_rx) = if wants_trailers(&headers_without_te) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let command = DriverCommand::SendStreamingRequest {
            method: http::Method::POST,
            uri: "https://example.com/svc/method".parse().unwrap(),
            headers: headers_without_te,
            body: RequestBody::Empty,
            body_shared: make_body_shared(),
            headers_tx,
            trailers_tx,
        };
        if let DriverCommand::SendStreamingRequest { trailers_tx, .. } = command {
            assert!(
                trailers_tx.is_none(),
                "no te:trailers -> trailers_tx must be None"
            );
        }
    }

    #[test]
    fn send_streaming_request_command_with_te_has_trailers_tx() {
        let headers_with_te = Headers::from_vec(vec![("te".to_string(), "trailers".to_string())]);
        let (headers_tx, _headers_rx) = oneshot::channel();
        let (trailers_tx, _trailers_rx) = if wants_trailers(&headers_with_te) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let command = DriverCommand::SendStreamingRequest {
            method: http::Method::POST,
            uri: "https://example.com/svc/method".parse().unwrap(),
            headers: headers_with_te,
            body: RequestBody::Empty,
            body_shared: make_body_shared(),
            headers_tx,
            trailers_tx,
        };
        if let DriverCommand::SendStreamingRequest { trailers_tx, .. } = command {
            assert!(
                trailers_tx.is_some(),
                "te:trailers -> trailers_tx must be Some"
            );
        }
    }

    #[test]
    fn inline_registration_no_te_has_no_trailers_tx() {
        let headers_without_te = Headers::from_vec(vec![(
            "content-type".to_string(),
            "application/grpc+proto".to_string(),
        )]);
        let (headers_tx, _headers_rx) = oneshot::channel();
        let (trailers_tx, _trailers_rx) = if wants_trailers(&headers_without_te) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let reg = InlineRegistration {
            stream_id: 1,
            headers_tx,
            body_shared: make_body_shared(),
            recv_window: 65_535,
            trailers_tx,
        };
        assert!(
            reg.trailers_tx.is_none(),
            "no te:trailers -> InlineRegistration::trailers_tx must be None"
        );
    }

    #[test]
    fn inline_registration_with_te_has_trailers_tx() {
        let headers_with_te = Headers::from_vec(vec![("te".to_string(), "trailers".to_string())]);
        let (headers_tx, _headers_rx) = oneshot::channel();
        let (trailers_tx, _trailers_rx) = if wants_trailers(&headers_with_te) {
            let (tx, rx) = oneshot::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        let reg = InlineRegistration {
            stream_id: 1,
            headers_tx,
            body_shared: make_body_shared(),
            recv_window: 65_535,
            trailers_tx,
        };
        assert!(
            reg.trailers_tx.is_some(),
            "te:trailers -> InlineRegistration::trailers_tx must be Some"
        );
    }
}