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
//! Response text that remembers which bytes the engine substituted into it (issue #1203).
//!
//! Every substitution pass — `{{ }}` templating, `${request.*}`, `copy`, `lookup` — searches the
//! output of the pass before it. Without provenance none of them can tell the author's text from
//! text an earlier pass spliced in from the request, so a client that sends a complete token gets
//! it expanded: a lookup column the config never served, or a request header the client never saw.
//!
//! The rule: **a token is expanded only if the author wrote its first and last characters.** Text
//! the engine substituted is never read as a token on its own, and it cannot complete one either:
//! a client that sends `${request.headers.x` gets nothing from an authored `}` that follows it, and
//! one that sends `{request.headers.x}` gets nothing from an authored `$` before it. Only the
//! middle may be substituted, which keeps the one deliberate composition working — `${R}[${COL}]`
//! with a `copy` into `${COL}` and a `lookup` into `${R}`: the delimiters are the author's.

use regex::{Captures, Regex};
use std::ops::Range;

/// Response text plus the byte ranges the engine substituted into it.
///
/// Invariant: `inserted` is sorted, non-empty, non-overlapping and non-adjacent (neighbours are
/// merged), and every bound lies on a char boundary of `text`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Spliced {
    text: String,
    inserted: Vec<Range<usize>>,
}

/// Headers with provenance, one entry per header name and one element per header line. Names
/// carry provenance too (issue #1583): `copy` and `lookup` replace tokens in them, as Mountebank's
/// `globalObjectReplace` does in every key of the response. Kept in the stub's order (issue
/// #1606): the response builder writes the headers in this map's order, as Mountebank writes the
/// response object's keys in property order.
pub(crate) type SplicedHeaders = crate::util::OrderedMap<SplicedName, Vec<Spliced>>;

/// A response header name and the bytes the engine substituted into it (issue #1583).
///
/// Equal and hashed by its text alone, and borrowable as `&str`, so the header map is looked up by
/// name exactly as a `HashMap<String, _>` is. The provenance only decides which tokens a later
/// pass may expand in it.
#[derive(Debug, Clone, Default)]
pub(crate) struct SplicedName(Spliced);

impl SplicedName {
    /// The name as text the engine owns, for the response builder.
    pub(crate) fn into_text(self) -> String {
        self.0.into_text()
    }

    pub(crate) fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

/// A name the author wrote (or that is treated as theirs: a script's output, an upstream's).
impl From<String> for SplicedName {
    fn from(name: String) -> Self {
        Self(Spliced::authored(name))
    }
}

impl From<&str> for SplicedName {
    fn from(name: &str) -> Self {
        Self(Spliced::authored(name.to_string()))
    }
}

impl PartialEq for SplicedName {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}

impl Eq for SplicedName {}

impl std::hash::Hash for SplicedName {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Must hash as the `str` it borrows as, so `get(&str)` finds it.
        self.as_str().hash(state);
    }
}

impl std::borrow::Borrow<str> for SplicedName {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl std::ops::Deref for SplicedName {
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl std::fmt::Display for SplicedName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Replace one `copy` or `lookup` token in every field of the response it can appear in: the body,
/// the `statusCode` string (issue #1558), each header value and each header name (issue #1583) —
/// the fields Mountebank's `globalObjectReplace` walks.
///
/// `replacement` is request-derived (or a CSV cell a client picked), so it can carry a byte a header
/// cannot hold; in a header value or name it is repaired like the templating passes repair theirs
/// (issue #1067). Only the substituted text is repaired: a control character the author typed into
/// the header itself, or a token left in a name, still reaches the builder and fails the response.
pub(crate) fn replace_response_token(
    body: &mut Spliced,
    headers: &mut SplicedHeaders,
    status: &mut Option<Spliced>,
    token: &str,
    replacement: &str,
    stub: crate::imposter::headers::StubRef<'_>,
) {
    body.replace_token(token, replacement);
    // The status is read as a number when the response is written, and a value that is not one is
    // quoted back in the 500's JSON body, so it needs no header repair.
    if let Some(status) = status {
        status.replace_token(token, replacement);
    }

    // Skipped outright when no header uses this token: the repair warns when it removes
    // something, so running it for a body-only stub would log a header warning, once per request,
    // about a header that does not exist.
    let in_values = headers
        .values()
        .flatten()
        .any(|v| v.contains_authored(token));
    // In the map's order, which is the stub's (issue #1606), as `globalObjectReplace` walks
    // `Object.keys`: of two names renamed alike, the later one wins.
    let renamed: Vec<SplicedName> = headers
        .keys()
        .filter(|name| name.0.contains_authored(token))
        .cloned()
        .collect();
    if !in_values && renamed.is_empty() {
        return;
    }
    let repaired = crate::imposter::headers::sanitize_header_value(replacement, stub);

    // Per value, so multi-value headers (e.g. multiple Set-Cookie) keep their multiplicity
    // (RFC 7230 §3.2.2 forbids folding Set-Cookie).
    if in_values {
        for value in headers.values_mut().flatten() {
            value.replace_token(token, &repaired);
        }
    }

    // Names after values, as `globalObjectReplace` replaces a key's value before renaming it. The
    // renamed header replaces any header already of its name, case-insensitively — Mountebank's
    // `obj[newKey] = obj[key]` followed by Node's case-insensitive `setHeader` — and a name this
    // pass produced is not visited again.
    for old in renamed {
        // Gone when an earlier rename in this pass replaced it. `shift_remove` keeps the other
        // headers in place; the renamed one is appended, as `obj[newKey] = …; delete obj[key]` is.
        let Some(values) = headers.shift_remove(old.as_str()) else {
            continue;
        };
        let mut name = old.0;
        name.replace_token(token, &repaired);
        let name = SplicedName(name);
        headers.retain(|existing, _| !existing.eq_ignore_ascii_case(&name));
        headers.insert(name, values);
    }
}

impl Spliced {
    /// Text the author wrote (or that is treated as theirs: a script's output, a proxied body).
    /// Does not allocate beyond `text`.
    pub(crate) fn authored(text: String) -> Self {
        Self {
            text,
            inserted: Vec::new(),
        }
    }

    /// Text the engine supplied whole, so no pass reads a token in it: a `defaultResponse`
    /// `statusCode` (issue #1558), which Mountebank merges after the behaviors have run.
    pub(crate) fn supplied(text: String) -> Self {
        let mut inserted = Vec::new();
        if !text.is_empty() {
            inserted.push(0..text.len());
        }
        Self { text, inserted }
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.text
    }

    pub(crate) fn into_text(self) -> String {
        self.text
    }

    #[cfg(test)]
    fn inserted(&self) -> &[Range<usize>] {
        &self.inserted
    }

    /// Whether the byte at `pos` is text the engine inserted.
    fn byte_inserted(&self, pos: usize) -> bool {
        // The last range starting at or before `pos` is the only one that can contain it.
        let idx = self.inserted.partition_point(|r| r.start <= pos);
        idx > 0 && pos < self.inserted[idx - 1].end
    }

    /// Whether the non-empty match `span` is a token the author wrote: its first and last bytes
    /// are both authored.
    fn is_authored_token(&self, span: &Range<usize>) -> bool {
        !self.byte_inserted(span.start) && !self.byte_inserted(span.end - 1)
    }

    /// Whether `token` occurs anywhere as a token the author wrote.
    pub(crate) fn contains_authored(&self, token: &str) -> bool {
        !token.is_empty()
            && self
                .text
                .match_indices(token)
                .any(|(at, _)| self.is_authored_token(&(at..at + token.len())))
    }

    /// Replace every occurrence of `token` whose first and last bytes are authored; the
    /// replacement is recorded as inserted. One left-to-right pass over the current text, so a
    /// replacement is never itself searched. Returns the number of replacements.
    pub(crate) fn replace_token(&mut self, token: &str, replacement: &str) -> usize {
        if token.is_empty() {
            return 0;
        }
        let matches: Vec<(Range<usize>, String)> = self
            .text
            .match_indices(token)
            .map(|(at, _)| at..at + token.len())
            .filter(|span| self.is_authored_token(span))
            .map(|span| (span, replacement.to_string()))
            .collect();
        self.splice(matches)
    }

    /// [`Self::replace_token`] for a regex pass: `replacement` receives each match's captures and
    /// is called only for matches whose first and last bytes are authored.
    pub(crate) fn replace_regex(
        &mut self,
        re: &Regex,
        mut replacement: impl FnMut(&Captures) -> String,
    ) -> usize {
        let mut matches = Vec::new();
        for caps in re.captures_iter(&self.text) {
            let Some(whole) = caps.get(0) else { continue };
            let span = whole.range();
            if span.is_empty() || !self.is_authored_token(&span) {
                continue;
            }
            matches.push((span, replacement(&caps)));
        }
        self.splice(matches)
    }

    /// Apply sorted, non-overlapping `(span, replacement)` pairs, carrying the existing inserted
    /// ranges through the untouched text and recording each replacement as inserted.
    fn splice(&mut self, matches: Vec<(Range<usize>, String)>) -> usize {
        if matches.is_empty() {
            return 0;
        }
        let count = matches.len();
        let old = std::mem::take(&mut self.text);
        let old_ranges = std::mem::take(&mut self.inserted);
        let mut out = Rebuild {
            text: String::with_capacity(old.len()),
            ranges: Vec::with_capacity(old_ranges.len() + count),
            next_range: 0,
        };
        let mut pos = 0;
        for (span, replacement) in matches {
            out.copy_untouched(&old, &old_ranges, pos..span.start);
            pos = span.end;
            let start = out.text.len();
            out.text.push_str(&replacement);
            if !replacement.is_empty() {
                push_merged(&mut out.ranges, start..out.text.len());
            }
        }
        out.copy_untouched(&old, &old_ranges, pos..old.len());
        self.text = out.text;
        self.inserted = out.ranges;
        count
    }
}

/// The text and ranges [`Spliced::splice`] is building.
struct Rebuild {
    text: String,
    ranges: Vec<Range<usize>>,
    /// First old range not yet wholly behind the cursor.
    next_range: usize,
}

impl Rebuild {
    /// Copy `old[segment]` verbatim, carrying over the parts of old inserted ranges inside it.
    fn copy_untouched(&mut self, old: &str, old_ranges: &[Range<usize>], segment: Range<usize>) {
        let shift = self.text.len();
        while let Some(r) = old_ranges.get(self.next_range) {
            if r.start >= segment.end {
                break;
            }
            let (start, stop) = (r.start.max(segment.start), r.end.min(segment.end));
            if start < stop {
                push_merged(
                    &mut self.ranges,
                    shift + start - segment.start..shift + stop - segment.start,
                );
            }
            if r.end > segment.end {
                // Continues into the match that follows (consumed) or past it (clipped next time).
                break;
            }
            self.next_range += 1;
        }
        self.text.push_str(&old[segment]);
    }
}

fn push_merged(ranges: &mut Vec<Range<usize>>, next: Range<usize>) {
    if let Some(last) = ranges.last_mut()
        && next.start <= last.end
    {
        last.end = last.end.max(next.end);
        return;
    }
    ranges.push(next);
}

/// Every header name and value as authored text.
pub(crate) fn authored_headers(headers: crate::imposter::Headers) -> SplicedHeaders {
    headers
        .into_iter()
        .map(|(k, values)| {
            (
                k.into(),
                values.into_iter().map(Spliced::authored).collect(),
            )
        })
        .collect()
}

/// Drop provenance: the header map the response builder takes.
pub(crate) fn plain_headers(headers: SplicedHeaders) -> crate::imposter::Headers {
    headers
        .into_iter()
        .map(|(k, values)| {
            (
                k.into_text(),
                values.into_iter().map(Spliced::into_text).collect(),
            )
        })
        .collect()
}

// Test-only: production compares a `Spliced` by text *and* ranges (the derived `PartialEq`), never
// by text alone (#1383).
#[cfg(test)]
impl PartialEq<&str> for Spliced {
    fn eq(&self, other: &&str) -> bool {
        self.text == *other
    }
}

#[cfg(test)]
impl PartialEq<str> for Spliced {
    fn eq(&self, other: &str) -> bool {
        self.text == other
    }
}

// Range lists here are the inserted-range sets under test, so a one-element list is intended.
#[cfg(test)]
#[allow(clippy::single_range_in_vec_init)]
mod tests {
    use super::*;

    fn with_inserted(text: &str, inserted: &[Range<usize>]) -> Spliced {
        Spliced {
            text: text.to_string(),
            inserted: inserted.to_vec(),
        }
    }

    #[test]
    fn authored_text_is_replaced_and_the_replacement_is_recorded() {
        let mut s = Spliced::authored("a ${T} b ${T}".to_string());
        assert_eq!(s.replace_token("${T}", "xy"), 2);
        assert_eq!(s.as_str(), "a xy b xy");
        assert_eq!(s.inserted(), &[2..4, 7..9]);
    }

    #[test]
    fn a_token_wholly_inside_inserted_text_is_skipped() {
        // "q=" authored, "${R}[secret]" inserted, " name=${R}[name]" authored.
        let mut s = with_inserted("q=${R}[secret] name=${R}[name]", &[2..14]);
        assert!(s.contains_authored("${R}[name]"));
        assert!(!s.contains_authored("${R}[secret]"));
        assert_eq!(s.replace_token("${R}[secret]", "s3cr3t"), 0);
        assert_eq!(s.replace_token("${R}[name]", "alice"), 1);
        assert_eq!(s.as_str(), "q=${R}[secret] name=alice");
        assert_eq!(s.inserted(), &[2..14, 20..25]);
    }

    #[test]
    fn inserted_text_cannot_be_closed_by_an_authored_character() {
        // The client sent "${R}[secret" and the author's "]" follows it.
        let mut s = with_inserted("[${R}[secret]]", &[1..12]);
        assert!(!s.contains_authored("${R}[secret]"));
        assert_eq!(s.replace_token("${R}[secret]", "s3cr3t"), 0);
        assert_eq!(s.as_str(), "[${R}[secret]]");
    }

    #[test]
    fn inserted_text_cannot_be_opened_by_an_authored_character() {
        // The author wrote a literal "$" (a price) and the client sent "{R}[secret]".
        let mut s = with_inserted("${R}[secret]", &[1..12]);
        assert_eq!(s.replace_token("${R}[secret]", "s3cr3t"), 0);
        assert_eq!(s.as_str(), "${R}[secret]");
    }

    #[test]
    fn inserted_text_between_authored_delimiters_is_replaced_with_them() {
        // "${R}[" and "]" authored, "name" inserted: the author opted in to a client-chosen column.
        let mut s = with_inserted("<${R}[name]>", &[6..10]);
        assert!(s.contains_authored("${R}[name]"));
        assert_eq!(s.replace_token("${R}[name]", "alice"), 1);
        assert_eq!(s.as_str(), "<alice>");
        assert_eq!(s.inserted(), &[1..6]);
    }

    #[test]
    fn an_empty_replacement_records_no_range() {
        let mut s = Spliced::authored("a${T}b".to_string());
        assert_eq!(s.replace_token("${T}", ""), 1);
        assert_eq!(s.as_str(), "ab");
        assert!(s.inserted().is_empty());
    }

    #[test]
    fn a_token_replaced_by_itself_terminates_and_is_not_expanded_again() {
        let mut s = Spliced::authored("${T}".to_string());
        assert_eq!(s.replace_token("${T}", "${T}"), 1);
        assert_eq!(s.replace_token("${T}", "x"), 0);
        assert_eq!(s.as_str(), "${T}");
    }

    #[test]
    fn adjacent_replacements_merge_into_one_range() {
        let mut s = Spliced::authored("${A}${B}".to_string());
        s.replace_token("${A}", "${");
        s.replace_token("${B}", "B}");
        // Both halves are inserted, so the token they form together is not the author's.
        assert_eq!(s.as_str(), "${B}");
        assert_eq!(s.inserted(), &[0..4]);
        assert!(!s.contains_authored("${B}"));
    }

    #[test]
    fn a_regex_pass_skips_inserted_matches_without_evaluating_them() {
        let re = Regex::new(r"\$\{(\w+)\}").expect("regex");
        let mut s = with_inserted("${a}${b}", &[4..8]);
        let mut seen = Vec::new();
        let n = s.replace_regex(&re, |caps| {
            seen.push(caps[1].to_string());
            "A".to_string()
        });
        assert_eq!(n, 1);
        assert_eq!(seen, vec!["a"]);
        assert_eq!(s.as_str(), "A${b}");
        assert_eq!(s.inserted(), &[0..5]);
    }

    #[test]
    fn multi_byte_text_keeps_ranges_on_char_boundaries() {
        let mut s = Spliced::authored("é${T}ü".to_string());
        s.replace_token("${T}", "ß");
        assert_eq!(s.as_str(), "éßü");
        assert_eq!(s.inserted(), &[2..4]);
        assert!(s.as_str().is_char_boundary(2) && s.as_str().is_char_boundary(4));
    }

    fn invariant_holds(s: &Spliced) -> bool {
        s.inserted.iter().all(|r| {
            r.start < r.end
                && r.end <= s.text.len()
                && s.text.is_char_boundary(r.start)
                && s.text.is_char_boundary(r.end)
        }) && s.inserted.windows(2).all(|w| w[0].end < w[1].start)
    }

    /// A seeded xorshift generator: the properties below run a few thousand fixed cases without a
    /// property-testing dependency, and a failure reproduces from its printed case.
    struct Gen(u64);

    impl Gen {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn below(&mut self, n: usize) -> usize {
            (self.next() % n as u64) as usize
        }
        fn string(&mut self, alphabet: &[&str], min: usize, max: usize) -> String {
            let len = min + self.below(max - min + 1);
            (0..len)
                .map(|_| alphabet[self.below(alphabet.len())])
                .collect()
        }
    }

    const TEXT: &[&str] = &["a", "b", "c", "$", "é", "{", "}"];

    #[test]
    fn with_nothing_inserted_replace_token_is_str_replace() {
        let mut g = Gen(0x1203);
        for _ in 0..4000 {
            let text = g.string(TEXT, 0, 24);
            let token = g.string(TEXT, 1, 3);
            let replacement = g.string(&["x", "y", "ü"], 0, 3);
            let mut s = Spliced::authored(text.clone());
            s.replace_token(&token, &replacement);
            assert_eq!(
                s.as_str(),
                text.replace(&token, &replacement),
                "{text:?} {token:?} {replacement:?}"
            );
        }
    }

    #[test]
    fn the_invariant_survives_any_sequence_of_passes() {
        let mut g = Gen(0xBEEF);
        for _ in 0..3000 {
            let mut s = Spliced::authored(g.string(TEXT, 0, 24));
            for _ in 0..g.below(6) {
                let token = g.string(TEXT, 1, 3);
                let replacement = g.string(&["a", "c", "ü", "$"], 0, 4);
                let before = s.clone();
                s.replace_token(&token, &replacement);
                assert!(
                    invariant_holds(&s),
                    "{s:?} after {before:?} {token:?}->{replacement:?}"
                );
            }
        }
    }

    #[test]
    fn inserted_text_that_survives_a_pass_is_unchanged() {
        let mut g = Gen(0xC0FFEE);
        for _ in 0..4000 {
            let prefix = g.string(&["a", "b", "c"], 0, 6);
            let inserted = g.string(&["a", "b", "c", "$"], 1, 8);
            let suffix = g.string(&["a", "b", "c"], 0, 6);
            let token = g.string(&["a", "b", "c", "$"], 1, 2);
            let text = format!("{prefix}{inserted}{suffix}");
            let span = prefix.len()..prefix.len() + inserted.len();
            let mut s = with_inserted(&text, std::slice::from_ref(&span));
            s.replace_token(&token, "#");
            // Only a match whose first and last bytes are both authored is replaced, and such a
            // match touches the span only by covering it whole. Otherwise the span survives.
            let covers = text
                .match_indices(&token)
                .any(|(at, _)| at < span.start && at + token.len() > span.end);
            if !covers {
                assert!(
                    s.as_str().contains(inserted.as_str()),
                    "{text:?} {span:?} {token:?} -> {s:?}"
                );
            }
        }
    }

    // Issue #1383: every older test held at most one inserted range per untouched segment, so a
    // carry loop that stopped after the first range in a segment went unnoticed. A dropped range
    // reads as authored, which is the #1203 attack.
    #[test]
    fn two_inserted_ranges_in_one_segment_both_survive_a_later_pass() {
        let mut s = with_inserted("aXbYc!", &[1..2, 3..4]);
        assert_eq!(s.replace_token("!", "??"), 1);
        assert_eq!(s.as_str(), "aXbYc??");
        assert_eq!(s.inserted(), &[1..2, 3..4, 5..7]);

        let mut s = with_inserted("!aXbYc", &[2..3, 4..5]);
        assert_eq!(s.replace_token("!", ""), 1);
        assert_eq!(s.inserted(), &[1..2, 3..4]);
    }

    // `splice`'s own contract, independent of the token rule its callers apply: a span that starts
    // inside an inserted range clips it, and the range's tail past the span is still carried.
    #[test]
    fn a_splice_inside_an_inserted_range_clips_it_and_carries_the_rest() {
        let mut s = with_inserted("abcdefghij", &[2..8]);
        assert_eq!(s.splice(vec![(3..5, "Z".to_string())]), 1);
        assert_eq!(s.as_str(), "abcZfghij");
        assert_eq!(s.inserted(), &[2..7]);
    }

    /// The tracked ranges agree with a naive per-byte model across any sequence of passes.
    #[test]
    fn tracked_ranges_match_a_byte_model() {
        /// Maximal runs of inserted bytes.
        fn runs(flags: &[bool]) -> Vec<Range<usize>> {
            let mut out: Vec<Range<usize>> = Vec::new();
            for (i, &inserted) in flags.iter().enumerate() {
                match out.last_mut() {
                    Some(last) if inserted && last.end == i => last.end = i + 1,
                    _ if inserted => out.push(i..i + 1),
                    _ => {}
                }
            }
            out
        }

        let mut g = Gen(0x1383);
        for _ in 0..3000 {
            let mut s = Spliced::authored(g.string(TEXT, 0, 24));
            let mut text = s.as_str().to_string();
            let mut flags = vec![false; text.len()];
            for _ in 0..g.below(6) {
                let token = g.string(TEXT, 1, 3);
                let replacement = g.string(&["a", "c", "ü", "$"], 0, 4);
                let before = s.clone();
                s.replace_token(&token, &replacement);

                let (mut next_text, mut next_flags, mut pos) = (String::new(), Vec::new(), 0);
                for (at, _) in text.match_indices(&token) {
                    let end = at + token.len();
                    if flags[at] || flags[end - 1] {
                        continue;
                    }
                    next_text.push_str(&text[pos..at]);
                    next_flags.extend_from_slice(&flags[pos..at]);
                    next_text.push_str(&replacement);
                    next_flags.extend(std::iter::repeat_n(true, replacement.len()));
                    pos = end;
                }
                next_text.push_str(&text[pos..]);
                next_flags.extend_from_slice(&flags[pos..]);
                (text, flags) = (next_text, next_flags);

                let context = format!("{before:?} {token:?}->{replacement:?}");
                assert_eq!(s.as_str(), text, "{context}");
                assert_eq!(s.inserted(), runs(&flags).as_slice(), "{context}");
            }
        }
    }
}