bao_stealth 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
// REQ-STL-002: HTTP/2 fingerprint matching (Akamai)  @trace REQ-STL-002
// PRIORITY frame mode (REQ-STL-002-C3): Firefox sends explicit PRIORITY frames with
// a stream dependency tree; Chrome dropped PRIORITY frames in v106. The
// `priority_frame_mode` field records this per-browser behaviour.  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PriorityFrameMode {
    /// Browser sends explicit PRIORITY frames (Firefox behaviour).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    Explicit,
    /// Browser no longer sends PRIORITY frames (Chrome v106+ behaviour).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    None,
}

/// One PRIORITY frame (RFC 7540 §6.3): stream id + dependency + weight.  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
///
/// `weight` is the wire value (0-255); the effective HTTP/2 weight is `weight + 1`
/// (1-256), per RFC 7540 §6.3. `stream_id` is the frame's stream — the
/// priority-tree node the frame reserves (Firefox reserves 3/5/7/11 on
/// connection setup, so real request streams start at 13).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PriorityFrame {
    pub stream_id: u32,
    pub stream_dependency: u32,
    pub exclusive: bool,
    pub weight: u8,
}

#[derive(Debug, Clone)]
pub struct Http2Fingerprint {
    pub header_table_size: u32,
    pub enable_push: bool,
    pub max_concurrent_streams: u32,
    pub initial_window_size: u32,
    pub max_frame_size: u32,
    pub max_header_list_size: u32,
    pub window_update_size: u32,
    pub pseudo_header_order: Vec<&'static str>,
    /// PRIORITY frame mode (REQ-STL-002-C3).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    pub priority_frame_mode: PriorityFrameMode,
    /// Explicit PRIORITY frames emitted on connection setup (Firefox only).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    pub priority_frames: Vec<PriorityFrame>,
}

impl Http2Fingerprint {
    pub fn firefox() -> Self {
        Http2Fingerprint {
            header_table_size: 65536,
            enable_push: false,
            max_concurrent_streams: 100,
            initial_window_size: 131072,
            max_frame_size: 16384,
            max_header_list_size: 262144,
            window_update_size: 131072,
            pseudo_header_order: vec![":method", ":path", ":authority", ":scheme"],
            // Firefox emits explicit PRIORITY frames to build its dependency tree.
            priority_frame_mode: PriorityFrameMode::Explicit,
            // Firefox default weights: streams 3/5/7/11 depending on stream 0 (the
            // root), non-exclusive. Wire weights 40/109/138/255 → effective 41/110/139/256.
            // Matches observed Firefox connection-setup traffic.
            priority_frames: vec![
                PriorityFrame {
                    stream_id: 3,
                    stream_dependency: 0,
                    exclusive: false,
                    weight: 40,
                },
                PriorityFrame {
                    stream_id: 5,
                    stream_dependency: 0,
                    exclusive: false,
                    weight: 109,
                },
                PriorityFrame {
                    stream_id: 7,
                    stream_dependency: 0,
                    exclusive: false,
                    weight: 138,
                },
                PriorityFrame {
                    stream_id: 11,
                    stream_dependency: 0,
                    exclusive: false,
                    weight: 255,
                },
            ],
        }
    }

    pub fn chrome() -> Self {
        Http2Fingerprint {
            header_table_size: 65536,
            enable_push: false,
            max_concurrent_streams: 1000,
            initial_window_size: 6291456,
            max_frame_size: 16384,
            max_header_list_size: 262144,
            window_update_size: 15663105,
            pseudo_header_order: vec![":method", ":authority", ":scheme", ":path"],
            // Chrome v106+ removed PRIORITY frames entirely.
            priority_frame_mode: PriorityFrameMode::None,
            priority_frames: Vec::new(),
        }
    }

    /// Returns true if this profile emits explicit PRIORITY frames (REQ-STL-002-C3).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    pub fn sends_priority_frames(&self) -> bool {
        self.priority_frame_mode == PriorityFrameMode::Explicit
    }

    /// Returns the PRIORITY frames this profile emits on connection setup.  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    pub fn priority_frame_payload(&self) -> &[PriorityFrame] {
        &self.priority_frames
    }

    /// Builder: returns a copy with the given PRIORITY mode (REQ-STL-002-C3).  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    pub fn with_priority_mode(mut self, mode: PriorityFrameMode) -> Self {
        self.priority_frame_mode = mode;
        if mode == PriorityFrameMode::None {
            self.priority_frames.clear();
        }
        self
    }

    pub fn akamai_fingerprint(&self) -> String {
        format!(
            "{}:{}:{}:{}:{}:{}",
            self.header_table_size,
            if self.enable_push { 1 } else { 0 },
            self.max_concurrent_streams,
            self.initial_window_size,
            self.max_frame_size,
            self.max_header_list_size,
        )
    }

    /// RFC 7540 §6.5.2 setting ids: 0x02 = ENABLE_PUSH, 0x03 =
    /// MAX_CONCURRENT_STREAMS, 0x04 = INITIAL_WINDOW_SIZE. The pairs MUST
    /// keep each value under its own id — a client advertising
    /// ENABLE_PUSH ∉ {0, 1} (e.g. a window size landing in the 0x02 slot)
    /// is a mandatory connection-error PROTOCOL_ERROR for the peer
    /// (verified against 1.1.1.1: GOAWAY(0x1) before any HEADERS).
    pub fn settings_frame_payload(&self) -> Vec<(u16, u32)> {
        vec![
            (0x01, self.header_table_size),
            (0x02, if self.enable_push { 1 } else { 0 }),
            (0x03, self.max_concurrent_streams),
            (0x04, self.initial_window_size),
            (0x05, self.max_frame_size),
            (0x06, self.max_header_list_size),
        ]
    }

    pub fn ordered_headers<'a>(&self, headers: &[(&'a str, &'a str)]) -> Vec<(&'a str, &'a str)> {
        let mut ordered = Vec::with_capacity(headers.len());
        let mut remaining: Vec<(&'a str, &'a str)> = headers.to_vec();

        for pseudo in &self.pseudo_header_order {
            if let Some(pos) = remaining.iter().position(|(k, _)| *k == *pseudo) {
                ordered.push(remaining.remove(pos));
            }
        }
        ordered.extend(remaining);
        ordered
    }
}

impl Default for Http2Fingerprint {
    /// Default = Firefox profile (SPEC REQ-STL-002 mandates Firefox-matching).  @trace REQ-STL-002
    fn default() -> Self {
        Http2Fingerprint::firefox()
    }
}

// ── Process-global HTTP/2 fingerprint snapshot ──────────────────────────
//
// U2 page-network unification: the servo-net bun bridge runs on the net
// thread, where the ScriptThread-scoped `engine_props` profile lookups
// (thread-local fallback / per-Realm map) are unreachable. The h2 SETTINGS
// payload reaches it through servo's `StealthTlsWireConfig` global, but the
// pseudo-header wire order and the connection-preface PRIORITY frames live
// only on the full `Http2Fingerprint` — so the embedder snapshots the active
// page profile's h2 fingerprint here, right next to
// `servo::set_stealth_tls_config`, and the bridge reads it when shaping its
// `SSLConfig`. Same lifecycle as the wire-config global: set on profile
// activation, cleared when the profile is deactivated.  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]

static GLOBAL_HTTP2_FINGERPRINT: std::sync::RwLock<Option<Http2Fingerprint>> =
    std::sync::RwLock::new(None);

/// Snapshot the active page profile's HTTP/2 fingerprint for cross-thread
/// consumers (see module notes). `None` deactivates.
pub fn set_global_http2_fingerprint(fingerprint: Option<&Http2Fingerprint>) {
    let mut guard = GLOBAL_HTTP2_FINGERPRINT.write().unwrap();
    *guard = fingerprint.cloned();
}

/// The active page profile's HTTP/2 fingerprint (clone), or `None` when no
/// profile is active.
pub fn global_http2_fingerprint() -> Option<Http2Fingerprint> {
    GLOBAL_HTTP2_FINGERPRINT.read().unwrap().clone()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn firefox_has_expected_values() {
        let fp = Http2Fingerprint::firefox();
        assert_eq!(fp.header_table_size, 65536);
        assert_eq!(fp.enable_push, false);
        assert_eq!(fp.max_concurrent_streams, 100);
        assert_eq!(fp.initial_window_size, 131072);
        assert_eq!(fp.max_frame_size, 16384);
        assert_eq!(fp.max_header_list_size, 262144);
        assert_eq!(fp.window_update_size, 131072);
    }

    #[test]
    fn chrome_has_expected_values() {
        let fp = Http2Fingerprint::chrome();
        assert_eq!(fp.max_concurrent_streams, 1000);
        assert_eq!(fp.initial_window_size, 6291456);
        assert_eq!(fp.window_update_size, 15663105);
    }

    #[test]
    fn firefox_pseudo_header_order() {
        let fp = Http2Fingerprint::firefox();
        assert_eq!(
            fp.pseudo_header_order,
            vec![":method", ":path", ":authority", ":scheme"]
        );
    }

    #[test]
    fn chrome_pseudo_header_order() {
        let fp = Http2Fingerprint::chrome();
        assert_eq!(
            fp.pseudo_header_order,
            vec![":method", ":authority", ":scheme", ":path"]
        );
    }

    #[test]
    fn firefox_and_chrome_have_different_akamai_fingerprints() {
        let ff = Http2Fingerprint::firefox().akamai_fingerprint();
        let ch = Http2Fingerprint::chrome().akamai_fingerprint();
        assert_ne!(ff, ch);
    }

    #[test]
    fn akamai_fingerprint_format_6_colon_separated_numbers() {
        let fp = Http2Fingerprint::firefox();
        let fingerprint = fp.akamai_fingerprint();
        let parts: Vec<&str> = fingerprint.split(':').collect();
        assert_eq!(parts.len(), 6);
        for part in &parts {
            assert!(part.parse::<u32>().is_ok());
        }
    }

    #[test]
    fn akamai_fingerprint_firefox_starts_with_65536() {
        let fp = Http2Fingerprint::firefox();
        let fingerprint = fp.akamai_fingerprint();
        assert!(fingerprint.starts_with("65536:"));
    }

    #[test]
    fn akamai_fingerprint_chrome_starts_with_65536() {
        let fp = Http2Fingerprint::chrome();
        let fingerprint = fp.akamai_fingerprint();
        assert!(fingerprint.starts_with("65536:"));
    }

    #[test]
    fn settings_frame_payload_returns_6_tuples() {
        let fp = Http2Fingerprint::firefox();
        let payload = fp.settings_frame_payload();
        assert_eq!(payload.len(), 6);
    }

    #[test]
    fn settings_frame_payload_firefox_first_is_0x01_65536() {
        let fp = Http2Fingerprint::firefox();
        let payload = fp.settings_frame_payload();
        assert_eq!(payload[0], (0x01, 65536));
    }

    #[test]
    fn settings_frame_payload_chrome_third_is_0x03_1000() {
        let fp = Http2Fingerprint::chrome();
        let payload = fp.settings_frame_payload();
        assert_eq!(payload[2], (0x03, 1000));
    }

    #[test]
    fn settings_frame_payload_enable_push_0_when_false() {
        let fp = Http2Fingerprint::firefox();
        let payload = fp.settings_frame_payload();
        assert_eq!(payload[1], (0x02, 0));
    }

    #[test]
    fn ordered_headers_pseudo_first_firefox() {
        let fp = Http2Fingerprint::firefox();
        let input: Vec<(&str, &str)> = vec![
            ("content-length", "0"),
            (":method", "GET"),
            (":path", "/"),
            ("host", "example.com"),
            (":authority", "example.com"),
            (":scheme", "https"),
        ];
        let ordered = fp.ordered_headers(&input);
        assert_eq!(ordered[0].0, ":method");
        assert_eq!(ordered[1].0, ":path");
        assert_eq!(ordered[2].0, ":authority");
        assert_eq!(ordered[3].0, ":scheme");
    }

    #[test]
    fn ordered_headers_chrome_specific_order() {
        let fp = Http2Fingerprint::chrome();
        let input: Vec<(&str, &str)> = vec![
            (":path", "/"),
            (":scheme", "https"),
            (":method", "GET"),
            (":authority", "example.com"),
        ];
        let ordered = fp.ordered_headers(&input);
        assert_eq!(ordered[0].0, ":method");
        assert_eq!(ordered[1].0, ":authority");
        assert_eq!(ordered[2].0, ":scheme");
        assert_eq!(ordered[3].0, ":path");
    }

    #[test]
    fn ordered_headers_no_pseudo_headers_preserves_order() {
        let fp = Http2Fingerprint::firefox();
        let input: Vec<(&str, &str)> = vec![
            ("host", "example.com"),
            ("content-length", "0"),
            ("accept", "*/*"),
        ];
        let ordered = fp.ordered_headers(&input);
        assert_eq!(ordered[0].0, "host");
        assert_eq!(ordered[1].0, "content-length");
        assert_eq!(ordered[2].0, "accept");
    }

    #[test]
    fn ordered_headers_empty_input_returns_empty() {
        let fp = Http2Fingerprint::firefox();
        let input: Vec<(&str, &str)> = vec![];
        let ordered = fp.ordered_headers(&input);
        assert!(ordered.is_empty());
    }

    #[test]
    fn ordered_headers_only_pseudo_headers() {
        let fp = Http2Fingerprint::firefox();
        let input: Vec<(&str, &str)> = vec![
            (":method", "GET"),
            (":path", "/"),
            (":authority", "example.com"),
            (":scheme", "https"),
        ];
        let ordered = fp.ordered_headers(&input);
        assert_eq!(ordered.len(), 4);
        assert_eq!(ordered[0].0, ":method");
        assert_eq!(ordered[1].0, ":path");
        assert_eq!(ordered[2].0, ":authority");
        assert_eq!(ordered[3].0, ":scheme");
    }

    #[test]
    fn clone_works() {
        let fp = Http2Fingerprint::firefox();
        let cloned = fp.clone();
        assert_eq!(fp.header_table_size, cloned.header_table_size);
        assert_eq!(fp.pseudo_header_order, cloned.pseudo_header_order);
    }

    #[test]
    fn debug_format_contains_http2_fingerprint() {
        let fp = Http2Fingerprint::firefox();
        let debug_str = format!("{:?}", fp);
        assert!(debug_str.contains("Http2Fingerprint"));
    }

    #[test]
    fn firefox_and_chrome_different_pseudo_order() {
        let ff = Http2Fingerprint::firefox();
        let ch = Http2Fingerprint::chrome();
        assert_ne!(ff.pseudo_header_order, ch.pseudo_header_order);
    }

    // ===========================================================================
    // REQ-STL-002-C3: PRIORITY frame mode  @trace REQ-STL-002 [criterion:REQ-STL-002-C3]
    // ===========================================================================

    #[test]
    fn firefox_emits_priority_frames() {
        // REQ-STL-002-C3: HTTP/2 PRIORITY frame mode matches Firefox.
        let ff = Http2Fingerprint::firefox();
        assert_eq!(ff.priority_frame_mode, PriorityFrameMode::Explicit);
        assert!(ff.sends_priority_frames());
        assert!(!ff.priority_frame_payload().is_empty());
    }

    #[test]
    fn chrome_does_not_emit_priority_frames() {
        // REQ-STL-002-C3: Chrome v106+ dropped PRIORITY frames.
        let ch = Http2Fingerprint::chrome();
        assert_eq!(ch.priority_frame_mode, PriorityFrameMode::None);
        assert!(!ch.sends_priority_frames());
        assert!(ch.priority_frame_payload().is_empty());
    }

    #[test]
    fn firefox_priority_frames_are_valid_rfc7540() {
        // REQ-STL-002-C3: each PRIORITY frame has a valid dependency + weight.
        // RFC 7540 §6.3: weight is wire u8 (effective = wire + 1, range 1-256).
        let ff = Http2Fingerprint::firefox();
        for frame in ff.priority_frame_payload() {
            assert!(frame.weight <= 255);
            // Stream id must be an odd client stream > 0 (or the frame would
            // target a server-initiated / invalid stream).
            assert!(frame.stream_id % 2 == 1 && frame.stream_id > 0);
            // Stream dependency references a valid prior stream (0 = root).
        }
    }

    #[test]
    fn firefox_and_chrome_priority_modes_differ() {
        // REQ-STL-002-C3: Firefox sends PRIORITY frames, Chrome does not.
        let ff = Http2Fingerprint::firefox();
        let ch = Http2Fingerprint::chrome();
        assert_ne!(ff.priority_frame_mode, ch.priority_frame_mode);
    }

    #[test]
    fn firefox_priority_frame_count_matches_firefox_observed() {
        // REQ-STL-002-C3: Firefox emits its known dependency-tree PRIORITY frames.
        let ff = Http2Fingerprint::firefox();
        assert_eq!(ff.priority_frame_payload().len(), 4);
    }

    #[test]
    fn firefox_priority_frames_reserve_streams_3_5_7_11() {
        // REQ-STL-002-C3: observed Firefox connection-setup traffic reserves
        // priority-tree nodes on streams 3/5/7/11 (real requests start at 13).
        let ff = Http2Fingerprint::firefox();
        let ids: Vec<u32> = ff
            .priority_frame_payload()
            .iter()
            .map(|f| f.stream_id)
            .collect();
        assert_eq!(ids, vec![3, 5, 7, 11]);
        // Weights stay paired with their observed stream id.
        let by_stream: Vec<(u32, u8)> = ff
            .priority_frame_payload()
            .iter()
            .map(|f| (f.stream_id, f.weight))
            .collect();
        assert_eq!(
            by_stream,
            vec![(3, 40), (5, 109), (7, 138), (11, 255)]
        );
    }
}