rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Header plumbing shared across the crate: the one request-header collector both listeners use
//! (issue #1025), the response-header collector, and the outbound header-value repair (issue #359 B3).

use indexmap::IndexMap;
use std::hash::BuildHasher;

/// Flatten a request's headers into the `name -> [values]` map the imposter listener, the
/// intercept listener, and the rule/predicate matcher they both feed all share.
///
/// A repeated header keeps every value, in the order the client sent them (issue #994) — hyper's
/// `HeaderMap` iterator yields one `(name, value)` pair per occurrence, so appending rather than
/// `insert`-ing is what preserves them. A value that is not UTF-8 is dropped rather than passed
/// through `from_utf8_lossy` — matching/forwarding would otherwise see U+FFFD garbage the client
/// never sent. A name left with no surviving value is omitted entirely rather than kept with an
/// empty string, so `exists`/`equals ""` cannot be tricked into reporting a header the client
/// never actually sent readably (issue #1025).
///
/// The map keeps the order the client sent the headers (issue #1606), a repeated name at its first
/// position — exactly Mountebank's `headersMap.ofRaw`, which the journal, scripts and
/// `MB_REQUEST` all show. That relies on `hyper::HeaderMap` iterating in insertion order, which
/// hyper's HTTP/1 parser fills in wire order: true of `http` 1.x, though its docs call the order
/// arbitrary, so a canary test below pins it.
///
/// `name` maps a header's wire name to the key stored in the map: Title-Case for the imposter
/// listener (Mountebank's `keyCaseSensitive` contract, issue #87), the identity function for the
/// intercept listener, which keeps hyper's already-lowercase names.
#[must_use]
pub fn collect_request_headers<SH: BuildHasher + Default>(
    headers: &hyper::HeaderMap,
    name: impl Fn(&str) -> String,
) -> IndexMap<String, Vec<String>, SH> {
    // `keys_len` counts distinct names; `len()` counts values, which over-allocates for a request
    // carrying any repeated header.
    let mut out: IndexMap<String, Vec<String>, SH> =
        IndexMap::with_capacity_and_hasher(headers.keys_len(), SH::default());
    let mut dropped: Vec<String> = Vec::new();
    for (header_name, value) in headers {
        // `str::from_utf8`, deliberately NOT `HeaderValue::to_str` (issue #1048). `to_str` accepts
        // only *visible ASCII* (`b >= 32 && b < 127 || b == b'\t'`), so it rejected every byte
        // above 0x7F — dropping a perfectly valid UTF-8 value such as
        // `Content-Disposition: attachment; filename="résumé.pdf"` and then warning that it was
        // "non-UTF-8", which it was not. The round trip was always lossless: httparse admits
        // obs-text (`0x80..=0xFF`) in a request header value, and `HeaderValue::from_str` accepts
        // those same bytes back, so nothing was ever gained by dropping them. This is the rule
        // `collect_response_headers` below already applies (issue #1041); the two collectors now
        // decode identically, which is what makes "matched, forwarded and recorded agree" true for
        // a non-ASCII header rather than only for an ASCII one.
        match std::str::from_utf8(value.as_bytes()) {
            Ok(text) => {
                out.entry(name(header_name.as_str()))
                    .or_default()
                    .push(text.to_string());
            }
            // Dropped, not `from_utf8_lossy`-mangled (see above) — but that drop is a real
            // data-path swallow (the value becomes invisible to matching, forwarding, and
            // recording), so it is warned rather than merely debug-logged. Collected and emitted
            // once per request instead of once per header: which headers are non-UTF-8 is
            // entirely client-controlled, and a per-value warn on this path is an unbounded
            // log-volume lever for a hostile client (the shape #718 measured as a throughput
            // cost).
            // Named through the caller's `name` function, not raw off the wire: an operator
            // reading this warning is going to go looking for the header in `savedRequests` or in
            // a predicate, and those show the caller's key shape (Title-Case for imposters). The
            // allocation is confined to the Err arm, so a request that drops nothing pays nothing.
            // Named once even when several of a name's occurrences are undecodable — the operator
            // needs the name, not a count (parity with `collect_response_headers`).
            Err(_) => {
                let dropped_name = name(header_name.as_str());
                if !dropped.contains(&dropped_name) {
                    dropped.push(dropped_name);
                }
            }
        }
    }
    if !dropped.is_empty() {
        tracing::warn!(
            headers = %dropped.join(", "),
            "dropping non-UTF-8 request header value(s); they are invisible to matching, forwarding, and recording"
        );
    }
    out
}

/// Relay an upstream proxy response's headers as `(name, value)` pairs in send order.
///
/// One pair per occurrence, so a repeated header (`Set-Cookie`) keeps its multiplicity — RFC 7230
/// §3.2.2 forbids folding that one, and the three consumers of this list (the client response, the
/// `RecordedResponse`, and the stub generated by `proxyOnce`/`proxyAlways`) all emit one line per
/// pair.
///
/// A value that is not valid UTF-8 is **dropped**, with one `warn!` per response naming the
/// affected headers — not coerced to `""`. There is no slot on the wire for header bytes (unlike a
/// binary *body*, which has `_mode`), and `IsResponse.headers` is `String`-valued end to end, so
/// dropping is the honest representation. Blanking it instead put an empty string the origin never
/// sent in front of the client *and* persisted it into the recorded stub, where it was served
/// forever after (issue #1041).
///
/// Decoded with `str::from_utf8`, deliberately **not** `HeaderValue::to_str`: `to_str` accepts only
/// *visible ASCII* (`b >= 32 && b < 127 || b == b'\t'`), so it rejects a perfectly valid UTF-8
/// value such as
/// `Content-Disposition: attachment; filename="résumé.pdf"`. The serving side is looser than that
/// — `HeaderValue::from_str` accepts obs-text (`0x80..=0xFF`) — so those bytes round-trip through a
/// `String` losslessly, and using `to_str` here would drop values Rift is perfectly able to relay.
#[must_use]
pub(crate) fn collect_response_headers(headers: &hyper::HeaderMap) -> Vec<(String, String)> {
    let mut out = Vec::with_capacity(headers.len());
    let mut dropped: Vec<String> = Vec::new();
    for (name, value) in headers {
        match std::str::from_utf8(value.as_bytes()) {
            Ok(text) => out.push((name.to_string(), text.to_string())),
            // One warn per response rather than per value. That does not make the rate bounded —
            // under `proxyAlways` against a persistently broken upstream it is still one line per
            // proxied request — it divides it by the number of affected headers, which is the same
            // bound the request-side collector settled for (#718). Named once per header even if
            // several of its occurrences were undecodable: the operator needs the name, not a
            // count.
            Err(_) => {
                let name = name.to_string();
                if !dropped.contains(&name) {
                    dropped.push(name);
                }
            }
        }
    }
    if !dropped.is_empty() {
        tracing::warn!(
            headers = %dropped.join(", "),
            "dropping non-UTF-8 upstream response header value(s); they are invisible to the client and the recorded stub"
        );
    }
    out
}

/// Make a header value derived from request data at serve time safe to emit (issue #359 B3,
/// header injection) — the `{{ }}` pass, the `${request.*}` pass, and the `copy`/`lookup` behaviors.
///
/// A templated header value can resolve to attacker-controlled request data: `request.query` is
/// percent-decoded and `request.json` is an arbitrary JSON string, so either can carry CR/LF and
/// terminate the header line early to smuggle a second header. Remove every character a header
/// value cannot hold, and say so — never silently.
///
/// The filter is the `http` crate's own validity rule expressed on `char`s. That rule is
/// `is_valid(b) = b >= 32 && b != 127 || b == b'\t'` (http-1.3.1/src/header/value.rs:584-587), and
/// `c == '\t' || !c.is_ascii_control()` is equivalent: an ASCII char is its own byte, and every
/// byte of a non-ASCII char is >= 0x80 and therefore always valid.
///
/// Do **not** reach for `char::is_control` here (issue #1058). That is Unicode category Cc, which
/// also spans U+0080–U+009F — legal obs-text a header value may carry — and it rejects HTAB, which
/// is explicitly legal. Both were being stripped and reported as an injection attempt.
///
/// Which stub a serve-time log line is about (issue #1075). `port` is the bound port, `index` the
/// stub's position, `id` its optional `id`. Uses the same field names and rendering as the
/// `port`/`stub_id` on a `rift::script` event, so one grep finds a stub's lines on both targets.
///
/// Explicit fields, not a tracing span: `render_template_parts` can run on a `spawn_blocking` pool
/// thread (the blocking flow-store path), and a span's thread-local context does not follow a closure
/// across that hop — a span-based identity would silently go missing on exactly that path.
#[derive(Debug, Clone, Copy)]
pub struct StubRef<'a> {
    /// The imposter's bound port.
    pub port: u16,
    /// The matched stub's position in its imposter's stub list.
    pub index: usize,
    /// The matched stub's optional `id`, if it has one.
    pub id: Option<&'a str>,
}

#[must_use]
pub(crate) fn sanitize_header_value(value: &str, stub: StubRef<'_>) -> String {
    let mut sanitized = String::with_capacity(value.len());
    let mut removed: Vec<char> = Vec::new();
    for c in value.chars() {
        if c == '\t' || !c.is_ascii_control() {
            sanitized.push(c);
        } else if !removed.contains(&c) {
            // Distinct characters only: the filter's alphabet is 33 values wide, so `removed` is
            // bounded by construction however long the input is.
            removed.push(c);
        }
    }
    if !removed.is_empty() {
        // `?`, never `%`: this is the attacker-controlled string we just found CR/LF in, and the
        // default subscriber is a plain `fmt` layer, so `Display` would write a real line break
        // into the log and forge a second log entry. `Debug` escapes it.
        //
        // Truncated first, because escaping *expands* — one ESC byte becomes `\u{1b}`, six
        // characters — and `value` is client-sized (a templated `request.json` value is bounded
        // only by the 10 MiB body cap) while this warning is client-triggerable by a single stray
        // control character. An unbounded per-request log line is the lever #718 exists to deny.
        tracing::warn!(
            target: "rift::template",
            port = stub.port,
            stub = stub.index,
            // Bare, like every other string field in the crate: `&str` records through
            // `record_str`, so this renders byte-identically to the `stub_id` on a `rift::script`
            // event and one grep finds both. It is also escaped like any other string field, so a
            // stub `id` containing a newline cannot forge a second log line.
            stub_id = stub.id.unwrap_or(""),
            value = ?crate::imposter::response::truncate_with_ellipsis(value, 256),
            removed = ?removed,
            "removed characters a header value cannot carry from a templated header value; a CR or LF here would have terminated the header line (header injection)"
        );
    }
    debug_assert!(
        hyper::header::HeaderValue::from_str(&sanitized).is_ok(),
        "the filter above *is* the `HeaderValue` validity rule, so what survives it is always \
         representable; a failure here means the two have drifted apart"
    );
    sanitized
}

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

    fn title_case(name: &str) -> String {
        crate::behaviors::header_to_title_case(name)
    }

    /// Issue #1606, and the canary for an `http` upgrade: the collected map lists names in the
    /// order they were appended, a repeated name at its first position with every value, which is
    /// Mountebank's `headersMap.ofRaw`. `http::HeaderMap` documents its iteration order as
    /// arbitrary; it is insertion order in fact, and hyper's HTTP/1 parser appends in wire order.
    /// Should a release change that, this fails instead of the journal and scripts quietly going
    /// back to a hash order.
    #[test]
    fn collector_keeps_the_order_names_were_sent() {
        let mut headers = hyper::HeaderMap::new();
        for (name, value) in [
            ("zulu", "1"),
            ("alpha", "2"),
            ("mike", "3"),
            ("alpha", "4"),
            ("bravo", "5"),
        ] {
            headers.append(name, HeaderValue::from_static(value));
        }
        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);
        let entries: Vec<(&str, Vec<&str>)> = collected
            .iter()
            .map(|(k, v)| (k.as_str(), v.iter().map(String::as_str).collect()))
            .collect();
        assert_eq!(
            entries,
            [
                ("Zulu", vec!["1"]),
                ("Alpha", vec!["2", "4"]),
                ("Mike", vec!["3"]),
                ("Bravo", vec!["5"]),
            ]
        );
    }

    #[test]
    fn collector_keeps_every_value_in_send_order() {
        // Issue #1025: the imposter listener used to `collect()` into a single-value map, which is
        // last-wins, so a client sending the same name twice could only ever be matched on the
        // second value. Send order matters as much as the count: it is what `first()` at the
        // scripting and flow-id boundaries selects, and what proxy forwarding replays.
        let mut headers = hyper::HeaderMap::new();
        headers.append("x-test", HeaderValue::from_static("first"));
        headers.append("x-test", HeaderValue::from_static("second"));
        headers.insert("content-type", HeaderValue::from_static("application/json"));

        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);

        assert_eq!(
            collected.get("X-Test").map(Vec::as_slice),
            Some(["first".to_string(), "second".to_string()].as_slice()),
            "both values, in the order the client sent them"
        );
        assert_eq!(
            collected.get("Content-Type").map(Vec::as_slice),
            Some(["application/json".to_string()].as_slice()),
            "a single-valued header is a one-element list, not a special case"
        );
    }

    // Issue #1048: the discriminating case. `HeaderValue::to_str` accepts only visible ASCII, so
    // this value — valid UTF-8, just not ASCII — was dropped and then *warned about as non-UTF-8*,
    // which it is not. The docs promised "not valid UTF-8 is dropped"; the code dropped a strict
    // superset of that, so the promise was false for every non-ASCII header a client can legally
    // send. Fails against the old `to_str` gate on both assertions.
    #[test]
    #[tracing_test::traced_test]
    fn collector_keeps_valid_non_ascii_utf8_and_does_not_warn_about_it() {
        let disposition = r#"attachment; filename="résumé.pdf""#;
        let mut headers = hyper::HeaderMap::new();
        headers.insert(
            "content-disposition",
            HeaderValue::from_bytes(disposition.as_bytes()).expect("obs-text is a legal value"),
        );
        headers.insert(
            "x-user-name",
            HeaderValue::from_bytes("José".as_bytes()).unwrap(),
        );

        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);

        assert_eq!(
            collected.get("Content-Disposition").map(Vec::as_slice),
            Some([disposition.to_string()].as_slice()),
            "valid UTF-8 beyond ASCII must survive byte-exact"
        );
        assert_eq!(
            collected.get("X-User-Name").map(Vec::as_slice),
            Some(["José".to_string()].as_slice())
        );
        assert!(
            !logs_contain("dropping non-UTF-8 request header value"),
            "nothing was dropped, so nothing may be warned about — the old code warned that a \
             valid UTF-8 value was not UTF-8"
        );

        // Round-trip the COLLECTED value, not a literal: the reason dropping was never necessary
        // is that whatever survives this collector can go straight back out as a header, and that
        // claim is only worth anything if it is made about the collector's own output.
        let collected_value = &collected["Content-Disposition"][0];
        assert!(
            HeaderValue::from_str(collected_value).is_ok(),
            "the serving side must accept back exactly what the collector produced"
        );
    }

    // Parity with `collect_response_headers`: a name whose occurrences are all undecodable is
    // named ONCE. Before #1048 the request collector pushed per occurrence.
    #[test]
    #[tracing_test::traced_test]
    fn collector_names_a_repeatedly_undecodable_header_once() {
        let bad = HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap();
        let mut headers = hyper::HeaderMap::new();
        headers.append("x-bin", bad.clone());
        headers.append("x-bin", bad);

        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);
        assert!(!collected.contains_key("X-Bin"));

        logs_assert(|lines: &[&str]| {
            let named = lines
                .iter()
                .filter(|l| l.contains("dropping non-UTF-8 request header value"))
                .map(|l| l.matches("X-Bin").count())
                .sum::<usize>();
            if named == 1 {
                Ok(())
            } else {
                Err(format!(
                    "expected the name once in the warning, saw it {named} times"
                ))
            }
        });
    }

    #[test]
    #[tracing_test::traced_test]
    fn collector_drops_non_utf8_values_and_omits_a_name_left_with_none() {
        // Issue #1025: `v.to_str().unwrap_or("")` turned a binary value into an empty string and
        // offered it to predicates, so `{"equals":{"headers":{"x-bin":""}}}` matched a request
        // that sent bytes. Dropping is the honest answer AND is what the intercept path already
        // does, so the two listeners agree.
        let non_utf8 =
            HeaderValue::from_bytes(&[0xFF, 0xFE]).expect("a legal but non-UTF-8 header value");
        let mut headers = hyper::HeaderMap::new();
        headers.insert("x-bin", non_utf8.clone());
        headers.append("x-mixed", HeaderValue::from_static("readable"));
        headers.append("x-mixed", non_utf8);

        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);

        assert!(
            !collected.contains_key("X-Bin"),
            "a name whose only value is non-UTF-8 is ABSENT, not present-with-an-empty-value — \
             otherwise `exists` is true and `equals \"\"` matches bytes the client never sent"
        );
        assert_eq!(
            collected.get("X-Mixed").map(Vec::as_slice),
            Some(["readable".to_string()].as_slice()),
            "the readable value of a partly-undecodable name survives, alone"
        );
        // The drop is data loss. What keeps it from being the very swallow this issue removes is
        // that it is announced — so the warning is part of the contract, not a nicety, and is
        // asserted rather than assumed. Both dropped names must be named.
        assert!(
            logs_contain("dropping non-UTF-8 request header value"),
            "a dropped value must be warned, not silently discarded"
        );
        assert!(
            logs_contain("X-Bin") && logs_contain("X-Mixed"),
            "the warning must name every header it dropped a value from, or an operator cannot \
             tell which of a request's headers went missing"
        );
    }

    #[test]
    fn collector_applies_the_callers_name_function() {
        // The imposter listener needs Title-Case keys (the `keyCaseSensitive` contract, issue #87)
        // while the intercept listener keeps hyper's already-lowercase names. One collector, two
        // name functions — which is what lets AC4 ("the two listeners agree") hold structurally.
        let mut headers = hyper::HeaderMap::new();
        headers.insert("x-my-header", HeaderValue::from_static("v"));

        let titled: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);
        assert!(titled.contains_key("X-My-Header"), "imposter shape");

        let identity: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, str::to_string);
        assert!(identity.contains_key("x-my-header"), "intercept shape");
    }

    #[test]
    fn flow_id_takes_the_first_value_of_a_repeated_header() {
        // Issue #1025 behaviour change: the live path used to resolve the flow id from the
        // single-value map, i.e. the LAST value of a repeated header. It now shares one
        // implementation with the recorded path, which has taken the FIRST value since #238 — so
        // a request and its own journal entry can no longer disagree about which space it is in.
        let config: crate::imposter::types::ImposterConfig =
            serde_json::from_value(serde_json::json!({
                "port": 0, "protocol": "http", "stubs": [],
                "_rift": { "flowState": { "flowIdSource": "header:X-Flow" } }
            }))
            .expect("config");
        let imposter = crate::imposter::Imposter::new(config).expect("imposter");

        let mut headers = hyper::HeaderMap::new();
        headers.append("x-flow", HeaderValue::from_static("tenant-a"));
        headers.append("x-flow", HeaderValue::from_static("tenant-b"));
        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&headers, title_case);

        assert_eq!(
            imposter.resolve_flow_id(&collected),
            "tenant-a",
            "the first value wins, matching resolve_flow_id_recorded (#238)"
        );
    }

    #[test]
    #[tracing_test::traced_test]
    fn collector_returns_an_empty_map_for_a_request_with_no_headers() {
        let collected: crate::util::OrderedMap<String, Vec<String>> =
            collect_request_headers(&hyper::HeaderMap::new(), title_case);
        assert!(collected.is_empty());
        assert!(
            !logs_contain("dropping non-UTF-8 request header value"),
            "a request that dropped nothing must not warn — an unconditional warning would be \
             noise on every request and would train an operator to ignore the real one"
        );
    }

    // Moved here from `rift-http-proxy`'s `intercept.rs` (issue #1025): that module's own
    // collector is now a thin wrapper over this one, so the shape it guarantees — every repeated
    // value kept, a non-UTF-8 value dropped — is pinned on the shared implementation instead.
    #[test]
    fn collect_request_headers_keeps_every_repeated_value_and_drops_non_utf8() {
        let mut headers = hyper::HeaderMap::new();
        headers.append("x-repeat", HeaderValue::from_static("first"));
        headers.append("x-repeat", HeaderValue::from_static("second"));
        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
        headers.insert(
            "x-binary",
            HeaderValue::from_bytes(&[0xFF, 0xFE]).expect("a legal but non-UTF-8 header value"),
        );

        let collected: crate::imposter::Headers = collect_request_headers(&headers, str::to_string);

        assert_eq!(
            collected.get("x-repeat").map(Vec::as_slice),
            Some(["first".to_string(), "second".to_string()].as_slice()),
            "a repeated header keeps every value, in send order (issue #994)"
        );
        assert_eq!(
            collected.get("content-type").map(Vec::as_slice),
            Some(["application/json".to_string()].as_slice()),
            "lookups stay case-insensitive because hyper's header names are already lowercase"
        );
        assert!(
            !collected.contains_key("x-binary"),
            "a non-UTF-8 value is dropped, not mangled into U+FFFD for predicates to match"
        );
    }

    // ---- issue #1041: the response-relay collector ----

    #[test]
    fn response_collector_drops_a_non_utf8_value_rather_than_blanking_it() {
        let mut h = hyper::HeaderMap::new();
        h.insert("x-bin", HeaderValue::from_bytes(&[0xff, 0xfe]).unwrap());
        h.insert("x-ok", HeaderValue::from_static("1"));

        let out = collect_response_headers(&h);

        assert_eq!(
            out,
            vec![("x-ok".to_string(), "1".to_string())],
            "the undecodable header is absent entirely; before #1041 it relayed as `x-bin: \"\"` \
             and was persisted into the generated stub"
        );
    }

    // The discriminating case for `from_utf8` over `HeaderValue::to_str`: this value is valid
    // UTF-8 but not visible ASCII, so `to_str` rejected it and the old code blanked a header the
    // origin sent correctly and that Rift is perfectly able to serve back.
    // The drop is data loss, and what keeps it from being the very swallow this issue removes is
    // that it is announced — so the warning is part of the contract and is asserted, not assumed.
    // The once-per-response half matters as much as the content: a `proxyAlways` imposter pointed
    // at an upstream that emits an undecodable header on every response would, with a per-value
    // warn, hand that upstream an unbounded log-volume lever. That is the #718 shape, which this
    // repo has already paid for once, and no other test would catch a regression that moved the
    // `warn!` inside the loop.
    #[test]
    #[tracing_test::traced_test]
    fn response_collector_warns_once_per_response_naming_every_dropped_header() {
        let bad = HeaderValue::from_bytes(&[0xff, 0xfe]).unwrap();
        let mut h = hyper::HeaderMap::new();
        h.insert("x-bin", bad.clone());
        h.insert("x-also-bin", bad.clone());
        h.append("x-mixed", HeaderValue::from_static("ok"));
        h.append("x-mixed", bad);

        let out = collect_response_headers(&h);
        assert_eq!(out, vec![("x-mixed".to_string(), "ok".to_string())]);

        assert!(
            logs_contain("dropping non-UTF-8 upstream response header value"),
            "a dropped value must be warned, not silently discarded"
        );
        assert!(
            logs_contain("x-bin") && logs_contain("x-also-bin") && logs_contain("x-mixed"),
            "the warning must name every header it dropped a value from, or an operator cannot \
             tell which of a response's headers went missing"
        );
        logs_assert(|lines: &[&str]| {
            let warns = lines
                .iter()
                .filter(|l| l.contains("dropping non-UTF-8 upstream response header value"))
                .count();
            if warns == 1 {
                Ok(())
            } else {
                Err(format!(
                    "expected exactly one warning for a response that dropped three values, got \
                     {warns} — a per-value warn is an unbounded log-volume lever for a hostile or \
                     broken upstream under proxyAlways (#718)"
                ))
            }
        });
    }

    #[test]
    #[tracing_test::traced_test]
    fn response_collector_stays_silent_when_nothing_is_dropped() {
        let mut h = hyper::HeaderMap::new();
        h.insert("x-ok", HeaderValue::from_static("1"));

        let _ = collect_response_headers(&h);

        assert!(
            !logs_contain("dropping non-UTF-8 upstream response header value"),
            "an ordinary response must not warn"
        );
    }

    #[test]
    fn response_collector_keeps_valid_utf8_that_is_not_ascii() {
        let mut h = hyper::HeaderMap::new();
        let disposition = r#"attachment; filename="résumé.pdf""#;
        h.insert(
            "content-disposition",
            HeaderValue::from_bytes(disposition.as_bytes()).unwrap(),
        );

        let out = collect_response_headers(&h);

        assert_eq!(
            out,
            vec![("content-disposition".to_string(), disposition.to_string())],
            "valid UTF-8 beyond ASCII must relay byte-exact"
        );
        // The serving side accepts these bytes, which is why dropping them was never necessary.
        assert!(HeaderValue::from_str(disposition).is_ok());
    }

    #[test]
    fn response_collector_keeps_every_value_of_a_repeated_header_in_send_order() {
        let mut h = hyper::HeaderMap::new();
        h.append("set-cookie", HeaderValue::from_static("a=1"));
        h.append("set-cookie", HeaderValue::from_static("b=2"));

        let out = collect_response_headers(&h);

        assert_eq!(
            out,
            vec![
                ("set-cookie".to_string(), "a=1".to_string()),
                ("set-cookie".to_string(), "b=2".to_string()),
            ],
            "RFC 7230 §3.2.2 forbids folding Set-Cookie, so multiplicity survives the relay"
        );
    }

    #[test]
    fn response_collector_keeps_the_good_value_of_a_partly_undecodable_repeated_header() {
        let mut h = hyper::HeaderMap::new();
        h.append("x-mixed", HeaderValue::from_bytes(&[0xff]).unwrap());
        h.append("x-mixed", HeaderValue::from_static("good"));

        let out = collect_response_headers(&h);

        assert_eq!(
            out,
            vec![("x-mixed".to_string(), "good".to_string())],
            "only the undecodable occurrence is dropped, not the whole name"
        );
    }

    #[test]
    fn response_collector_on_empty_headers_yields_no_pairs() {
        assert!(collect_response_headers(&hyper::HeaderMap::new()).is_empty());
    }
}

#[cfg(test)]
mod sanitize_header_value_tests {
    use super::{StubRef, sanitize_header_value};
    use hyper::header::HeaderValue;

    /// Fixture identity for tests that only care about the repair itself, not which stub
    /// triggered it — the gate tests below (issue #1075) assert on deliberately chosen values.
    const FIXTURE_STUB: StubRef<'static> = StubRef {
        port: 0,
        index: 0,
        id: None,
    };
    use crate::test_support::{CapturedEvent, captured_logs};

    fn one_event(value: &str) -> CapturedEvent {
        let events = captured_logs(|| {
            // Only the warning is under test here; the repaired value is asserted elsewhere.
            let _ = sanitize_header_value(value, FIXTURE_STUB);
        });
        assert_eq!(
            events.len(),
            1,
            "a sanitized value warns exactly once, got {} events",
            events.len()
        );
        events[0].clone()
    }

    #[test]
    fn a_horizontal_tab_is_a_legal_header_value_character_and_is_kept() {
        let events =
            captured_logs(|| assert_eq!(sanitize_header_value("a\tb", FIXTURE_STUB), "a\tb"));
        assert!(
            events.is_empty(),
            "a legal value must not be reported as sanitized"
        );
    }

    #[test]
    fn unicode_c1_controls_are_legal_obs_text_and_are_kept() {
        // U+0080-U+009F encode as two bytes that are both >= 0x80, so `HeaderValue` accepts them.
        // Only `char::is_control` (Unicode category Cc) ever called them control characters.
        let events = captured_logs(|| {
            assert_eq!(sanitize_header_value("a\u{85}b", FIXTURE_STUB), "a\u{85}b");
            assert_eq!(sanitize_header_value("a\u{80}b", FIXTURE_STUB), "a\u{80}b");
            assert_eq!(sanitize_header_value("a\u{9f}b", FIXTURE_STUB), "a\u{9f}b");
        });
        assert!(
            events.is_empty(),
            "C1 obs-text must not be reported as sanitized"
        );
    }

    #[test]
    fn ordinary_non_ascii_passes_through_byte_exact() {
        let events =
            captured_logs(|| assert_eq!(sanitize_header_value("José", FIXTURE_STUB), "José"));
        assert!(events.is_empty());
    }

    #[test]
    fn an_empty_value_is_unchanged() {
        let events = captured_logs(|| assert_eq!(sanitize_header_value("", FIXTURE_STUB), ""));
        assert!(events.is_empty());
    }

    /// Idempotence, which is what makes it safe for the `${request.*}` pass to repair a value the
    /// `{{ }}` pass already repaired (issue #1067): the second application changes nothing and —
    /// just as importantly — does not warn again. The warning is client-triggerable, so a value
    /// with nothing left to remove must be silent.
    #[test]
    fn repairing_an_already_repaired_value_changes_nothing_and_does_not_warn_again() {
        let once = sanitize_header_value("safe\r\nInjected: yes", FIXTURE_STUB);
        assert_eq!(once, "safeInjected: yes");

        let events = captured_logs(|| {
            assert_eq!(
                sanitize_header_value(&once, FIXTURE_STUB),
                "safeInjected: yes",
                "a repaired value is a fixed point of the repair"
            );
        });
        assert!(
            events.is_empty(),
            "nothing was removed the second time, so nothing may be logged, got: {:?}",
            events.len()
        );
    }

    /// Issue #1075: the warning must say which stub produced it. Without this an operator on a
    /// server running many imposters sees a mangled header and a `removed` list, and has no way
    /// back to the config that caused it. Field names match the `rift::script` events
    /// (`port`, `stub_id`) so both targets grep alike; `stub` is the index, because a stub with no
    /// `id` — the common case — is otherwise unnameable.
    #[test]
    fn the_warning_names_the_port_and_the_stub() {
        let events = captured_logs(|| {
            let _ = sanitize_header_value(
                "safe\r\nInjected: yes",
                StubRef {
                    port: 4545,
                    index: 3,
                    id: Some("checkout"),
                },
            );
        });

        assert_eq!(events.len(), 1, "one removal, one warning");
        assert_eq!(events[0].field("port"), Some("4545"));
        assert_eq!(events[0].field("stub"), Some("3"));
        assert_eq!(events[0].field("stub_id"), Some("checkout"));
    }

    /// A stub without an `id` is the common case, and it must still be locatable: `stub_id` is the
    /// empty string rather than absent, matching what `rift::script` emits.
    #[test]
    fn a_stub_without_an_id_still_logs_an_empty_stub_id() {
        let events = captured_logs(|| {
            let _ = sanitize_header_value(
                "a\0b",
                StubRef {
                    port: 4545,
                    index: 0,
                    id: None,
                },
            );
        });

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].field("port"), Some("4545"));
        assert_eq!(events[0].field("stub"), Some("0"));
        assert_eq!(events[0].field("stub_id"), Some(""));
    }

    /// The identity fields ride with the value, so nothing about them depends on where the repair
    /// runs — which is the whole reason this is explicit fields and not a tracing span. A span's
    /// thread-local is empty on the `spawn_blocking` pool thread `run_flow_blocking` uses for a
    /// blocking flow store, so a span-based fix would be silently lossy on exactly that path.
    #[test]
    fn the_identity_does_not_depend_on_the_thread_the_repair_runs_on() {
        let stub = StubRef {
            port: 9090,
            index: 7,
            id: None,
        };

        // The capture is installed *inside* the spawned thread on purpose:
        // `tracing::subscriber::with_default` is thread-local, so a subscriber installed on the
        // parent would never see this event. That is precisely why the identity is passed as an
        // argument rather than carried in a span — a span would be just as thread-local, and
        // `run_flow_blocking` really does hop to a `spawn_blocking` pool thread.
        let events = std::thread::scope(|scope| {
            scope
                .spawn(|| {
                    captured_logs(|| {
                        let _ = sanitize_header_value("a\rb", stub);
                    })
                })
                .join()
                .expect("capture thread")
        });

        assert_eq!(events.len(), 1, "the warning still fires off-thread");
        assert_eq!(events[0].field("port"), Some("9090"));
        assert_eq!(events[0].field("stub"), Some("7"));
    }

    /// The request path and query are deliberately absent: both are client-controlled, and `value`
    /// already shows the operator the offending client data. Port and stub locate the *config*.
    #[test]
    fn the_warning_carries_no_client_controlled_location() {
        let events = captured_logs(|| {
            let _ = sanitize_header_value(
                "a\rb",
                StubRef {
                    port: 1,
                    index: 0,
                    id: None,
                },
            );
        });

        assert_eq!(events.len(), 1);
        assert!(events[0].field("path").is_none(), "no request path field");
        assert!(events[0].field("query").is_none(), "no query field");
    }

    #[test]
    fn crlf_is_still_stripped_and_still_warned() {
        let events = captured_logs(|| {
            assert_eq!(
                sanitize_header_value("safe\r\nInjected: yes", FIXTURE_STUB),
                "safeInjected: yes"
            );
        });
        assert_eq!(events.len(), 1, "CR/LF removal must stay loud");
        assert!(
            events[0]
                .field("message")
                .is_some_and(|m| m.contains("header injection")),
            "CR/LF removal is the #359 B3 injection defence and must still name it, got: {:?}",
            events[0].field("message")
        );
    }

    #[test]
    fn the_warning_does_not_echo_a_raw_control_character_into_the_log() {
        let event = one_event("safe\r\nInjected: yes");
        for (name, rendered) in &event.fields {
            assert!(
                !rendered.contains('\r') && !rendered.contains('\n'),
                "field `{name}` carries a raw CR/LF, which forges a second log line: {rendered:?}"
            );
        }
        assert_eq!(
            event.field("value"),
            Some(r#""safe\r\nInjected: yes""#),
            "the offending value stays legible, escaped"
        );
    }

    #[test]
    fn the_warning_names_the_characters_it_removed() {
        assert_eq!(
            one_event("safe\r\nInjected: yes").field("removed"),
            Some(r"['\r', '\n']"),
            "an operator must be able to tell CR/LF from a stray NUL"
        );
        assert_eq!(one_event("a\u{0}b").field("removed"), Some(r"['\0']"));
    }

    #[test]
    fn a_repeated_control_character_is_reported_once() {
        // The diagnostic is derived from client-controlled data, so the set of characters it names
        // must stay bounded by the filter's own alphabet, not by the length of the input (#718).
        assert_eq!(
            one_event("a\0\0\0\0\0b").field("removed"),
            Some(r"['\0']"),
            "the removed set names each character once"
        );
    }

    #[test]
    fn the_logged_value_is_capped_however_long_the_input_is() {
        // The warning is client-triggerable by one stray control character, and `Debug` escaping
        // expands each of them; without a cap a 10 MiB templated body becomes a 10 MiB log line
        // per request (#718).
        let value = format!("{}\u{1b}", "x".repeat(100_000));
        let event = one_event(&value);
        let logged = event.field("value").expect("value field present");
        assert!(
            logged.len() < 1_000,
            "the logged value must be capped, got {} chars",
            logged.len()
        );
        assert!(
            logged.contains("..."),
            "a truncated value must say so, got: {logged}"
        );
    }

    #[test]
    fn bytes_a_header_value_cannot_hold_are_stripped() {
        assert_eq!(sanitize_header_value("a\u{0}b", FIXTURE_STUB), "ab");
        assert_eq!(sanitize_header_value("a\u{7f}b", FIXTURE_STUB), "ab");
        assert_eq!(sanitize_header_value("a\u{1b}b", FIXTURE_STUB), "ab");
        assert_eq!(sanitize_header_value("\r\n\0", FIXTURE_STUB), "");
    }

    #[test]
    fn every_byte_agrees_with_the_http_crate_on_what_a_header_value_may_hold() {
        // The whole fix is that the filter *is* `http`'s `is_valid` rule. Cross-check it against
        // the crate itself over every code point that can differ, rather than trusting the
        // derivation in the doc comment: ASCII, plus the C1 range the old `is_control` removed.
        for cp in (0u32..=0xFF).chain([0x100, 0x2028, 0x10FFFF]) {
            let Some(c) = char::from_u32(cp) else {
                continue;
            };
            let kept = sanitize_header_value(&c.to_string(), FIXTURE_STUB) == c.to_string();
            let representable = HeaderValue::from_str(&c.to_string()).is_ok();
            assert_eq!(
                kept, representable,
                "U+{cp:04X} ({c:?}): sanitizer kept={kept}, HeaderValue accepts={representable}"
            );
        }
    }

    #[test]
    fn every_sanitized_value_is_accepted_by_header_value() {
        for raw in [
            "a\tb",
            "a\u{85}b",
            "José",
            "safe\r\nInjected: yes",
            "a\u{0}b",
            "a\u{7f}b",
            "",
            "\r\n\0",
        ] {
            let out = sanitize_header_value(raw, FIXTURE_STUB);
            assert!(
                HeaderValue::from_str(&out).is_ok(),
                "sanitized {raw:?} -> {out:?} must be a representable header value"
            );
        }
    }
}