autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Render hooks: a sandboxed plugin filling a host-declared slot (issue #1632).
//!
//! The host application declares named slots; a plugin granted a slot returns
//! something for it, and the host puts it on the page. That last clause is the
//! whole problem — the fragment is served from the *host's* origin, so anything
//! executable in it executes with the host page's authority.
//!
//! # The fragment is a tree, not a string of HTML
//!
//! The obvious design is "the guest returns HTML and the host sanitises it".
//! Sanitising is a filter in front of a parser, and every notable sanitiser bug
//! in the last decade has been a *parser differential*: the sanitiser's HTML
//! parser and the browser's disagree about one input — `<noscript>` contents,
//! foreign content in `<svg>`/`<math>`, a mutation the serialiser makes on the
//! way out — and the filter approves a string that means something else once
//! parsed. Getting that right requires a full HTML5 tokeniser and an ongoing
//! commitment to track browser behaviour.
//!
//! So the guest does not send HTML. It sends a [`FragmentNode`] tree, and the
//! host renders it:
//!
//! ```text
//! guest → {"op":"fragment","nodes":[{"node":"element","tag":"p",
//!            "children":[{"node":"text","text":"3 orders"}]}]}
//! host  → <p>3 orders</p>
//! ```
//!
//! There is no parser to disagree with, because there is no parsing. The output
//! is a function this module writes, from a closed tag list, a closed attribute
//! list, and text that is escaped on the way out. Script, styles, event
//! handlers, `javascript:` URLs, `<iframe>`, `<object>` and inline SVG are not
//! filtered out — there is no way to express them.
//!
//! That also makes the result **CSP-safe** in the strict sense: nothing rendered
//! here needs `unsafe-inline` for scripts or styles, so a host page with a
//! nonce-based policy keeps it.
//!
//! # A slow or trapping hook omits the fragment
//!
//! A render hook is decoration on somebody else's page. If the guest traps,
//! exhausts its fuel, answers with something this module refuses, or overruns
//! the `render_bytes` quota, the host omits the fragment and serves the page.
//! There is no path where a plugin's failure becomes the page's.

use serde::{Deserialize, Serialize};

/// Tags a fragment may use.
///
/// A closed list of *structural* elements. Everything absent is absent because
/// it carries authority the host page's own markup would not: `<script>` and
/// `<style>` execute, `<iframe>`/`<object>`/`<embed>` load an origin,
/// `<form>`/`<input>`/`<button>` submit somewhere, `<img>`/`<video>` fetch and
/// leak a viewer's IP to a third party, `<link>`/`<meta>`/`<base>` re-point the
/// document, and `<svg>`/`<math>` open the foreign-content parsing modes that
/// most sanitiser bypasses live in.
pub const ALLOWED_TAGS: &[&str] = &[
    "a", "abbr", "b", "br", "code", "dd", "div", "dl", "dt", "em", "h3", "h4", "h5", "h6", "hr",
    "i", "li", "ol", "p", "pre", "small", "span", "strong", "table", "tbody", "td", "tfoot", "th",
    "thead", "time", "tr", "ul",
];

/// Tags rendered as a single self-closing element, with no children.
pub const VOID_TAGS: &[&str] = &["br", "hr"];

/// Attributes a fragment may set, and on which tags.
///
/// `style` is absent: an inline style needs `unsafe-inline` in a style policy,
/// and CSS alone can exfiltrate — `background: url(https://…)` keyed off an
/// attribute selector is a well-known read of the surrounding page. `id` is
/// absent because a duplicate id changes what the *host's* own scripts and
/// labels resolve to. `target` and `rel` are absent because a fragment's links
/// are same-origin by construction (see `check_href`), so neither has
/// anything to say: `target="_blank"` without `rel="noopener"` is a
/// window-opener hazard, and there is no cross-origin link for `rel` to
/// annotate.
pub const ALLOWED_ATTRIBUTES: &[(&str, &str)] = &[
    ("a", "href"),
    ("a", "title"),
    ("time", "datetime"),
    ("td", "colspan"),
    ("th", "colspan"),
    ("td", "rowspan"),
    ("th", "rowspan"),
    ("*", "class"),
    ("*", "lang"),
    ("*", "dir"),
];

/// How deep a fragment may nest.
///
/// Rendering recurses, so the depth is stack the guest chooses. Eight is far
/// past what a panel needs and far short of anything that could matter.
pub const MAX_DEPTH: usize = 8;

/// How many nodes one fragment may carry, counted across the whole tree.
pub const MAX_NODES: usize = 512;

/// The most attributes one element may carry.
///
/// The allow-list bounds *which* attributes appear and says nothing about how
/// many: an element repeating `title` a thousand times is inside every other
/// ceiling. Above the widest legal element — the allow-list itself is shorter
/// than this — so it never refuses a fragment anyone would write.
pub const MAX_ATTRIBUTES: usize = 32;

/// Longest accepted text run or attribute value, in bytes.
pub const MAX_TEXT_BYTES: usize = 8 * 1024;

/// One node of a fragment.
///
/// Internally tagged by `node`, like every other frame in this protocol, so a
/// plugin author writes `{"node":"text","text":"…"}` rather than a nested
/// object per variant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "node", rename_all = "snake_case", deny_unknown_fields)]
#[non_exhaustive]
pub enum FragmentNode {
    /// A run of text, escaped on the way out.
    Text {
        /// The text.
        text: String,
    },
    /// An element from [`ALLOWED_TAGS`].
    Element {
        /// The tag name.
        tag: String,
        /// Attributes, each of which must appear in [`ALLOWED_ATTRIBUTES`].
        ///
        /// Bounded while it is *read*, not after: see
        /// [`bounded_vec`](super::bounded_vec).
        #[serde(
            default,
            deserialize_with = "super::bounded_vec::<_, _, MAX_ATTRIBUTES>"
        )]
        attributes: Vec<(String, String)>,
        /// Children.
        ///
        /// Bounded against a budget shared by the *whole* tree, not per vector:
        /// see [`bounded_subtree`](super::bounded_subtree).
        #[serde(default, deserialize_with = "super::bounded_subtree")]
        children: Vec<Self>,
    },
}

/// Why a fragment was not rendered.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RenderError {
    /// The plugin was not granted this slot.
    SlotNotGranted(String),
    /// A tag outside [`ALLOWED_TAGS`].
    ForbiddenTag(String),
    /// An attribute outside [`ALLOWED_ATTRIBUTES`] for its tag.
    ForbiddenAttribute {
        /// The tag it appeared on.
        tag: String,
        /// The attribute name.
        name: String,
    },
    /// An attribute value this build will not emit.
    InvalidAttributeValue {
        /// The attribute name.
        name: String,
        /// Why it was refused.
        reason: &'static str,
    },
    /// The tree nests deeper than [`MAX_DEPTH`].
    TooDeep,
    /// The tree carries more than [`MAX_NODES`] nodes.
    TooManyNodes,
    /// One element carries more than [`MAX_ATTRIBUTES`] attributes.
    TooManyAttributes(usize),
    /// A text run or attribute value is over [`MAX_TEXT_BYTES`].
    TextTooLong(usize),
    /// The rendered fragment is over the `render_bytes` quota.
    TooLarge {
        /// What it came to.
        found: usize,
        /// The ceiling.
        max: usize,
    },
}

impl std::fmt::Display for RenderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SlotNotGranted(slot) => {
                write!(f, "`[grants].slots` does not name {slot:?}")
            }
            Self::ForbiddenTag(tag) => write!(
                f,
                "<{tag}> is not one of the structural tags a render hook may use"
            ),
            Self::ForbiddenAttribute { tag, name } => {
                write!(f, "attribute `{name}` is not allowed on <{tag}>")
            }
            Self::InvalidAttributeValue { name, reason } => {
                write!(f, "attribute `{name}`: {reason}")
            }
            Self::TooDeep => write!(f, "a fragment may nest at most {MAX_DEPTH} deep"),
            Self::TooManyNodes => write!(f, "a fragment may carry at most {MAX_NODES} nodes"),
            Self::TooManyAttributes(found) => write!(
                f,
                "an element may carry at most {MAX_ATTRIBUTES} attributes; this one carries {found}"
            ),
            Self::TextTooLong(found) => write!(
                f,
                "a text run or attribute value of {found} bytes is over the \
                 {MAX_TEXT_BYTES}-byte ceiling"
            ),
            Self::TooLarge { found, max } => write!(
                f,
                "the rendered fragment came to {found} bytes, over the {max}-byte `render_bytes` \
                 quota"
            ),
        }
    }
}

impl std::error::Error for RenderError {}

/// Render a fragment to HTML, or say why it will not be.
///
/// # Errors
///
/// See [`RenderError`]. Every one of them makes the host omit the fragment.
pub fn render(nodes: &[FragmentNode], max_bytes: usize) -> Result<String, RenderError> {
    let mut out = String::new();
    let mut budget = MAX_NODES;
    for node in nodes {
        write_node(&mut out, node, 0, &mut budget, max_bytes)?;
    }
    if out.len() > max_bytes {
        return Err(RenderError::TooLarge {
            found: out.len(),
            max: max_bytes,
        });
    }
    Ok(out)
}

fn write_node(
    out: &mut String,
    node: &FragmentNode,
    depth: usize,
    budget: &mut usize,
    max_bytes: usize,
) -> Result<(), RenderError> {
    if depth > MAX_DEPTH {
        return Err(RenderError::TooDeep);
    }
    *budget = budget.checked_sub(1).ok_or(RenderError::TooManyNodes)?;
    // Checked as the string grows rather than only at the end: a tree within
    // every structural bound can still render to megabytes (512 nodes each
    // carrying 8 KiB of text is 4 MiB), and the point of the ceiling is not to
    // *report* that but to stop building it.
    if out.len() > max_bytes {
        return Err(RenderError::TooLarge {
            found: out.len(),
            max: max_bytes,
        });
    }
    match node {
        FragmentNode::Text { text } => {
            if text.len() > MAX_TEXT_BYTES {
                return Err(RenderError::TextTooLong(text.len()));
            }
            escape_into(out, text);
        }
        FragmentNode::Element {
            tag,
            attributes,
            children,
        } => {
            // Matched without folding the guest's string first. The allow-list
            // is a handful of short names, and `eq_ignore_ascii_case` compares
            // lengths before bytes, so an overlong tag loses against `p` in
            // constant time. Folding first copied whatever arrived — up to the
            // stdout-frame ceiling, per concurrent render, outside the Wasm
            // memory limiter — before anything decided it was a tag at all.
            // The same shape as the outbound method a few commits back; this is
            // the sibling that pass did not look for.
            let Some(tag) = ALLOWED_TAGS
                .iter()
                .find(|known| known.eq_ignore_ascii_case(tag))
            else {
                return Err(RenderError::ForbiddenTag(super::super::manifest::rejected(
                    tag,
                )));
            };
            let tag = (*tag).to_owned();
            if attributes.len() > MAX_ATTRIBUTES {
                return Err(RenderError::TooManyAttributes(attributes.len()));
            }
            out.push('<');
            out.push_str(&tag);
            for (name, value) in attributes {
                write_attribute(out, &tag, name, value)?;
                // Re-checked per attribute, not once per node. Escaping expands
                // a value severalfold — `&` becomes `&amp;` — so an element
                // inside every structural bound can still render megabytes
                // before the check at the top of the next node runs, and the
                // point of the ceiling is to stop the string being built rather
                // than to report its size afterwards.
                if out.len() > max_bytes {
                    return Err(RenderError::TooLarge {
                        found: out.len(),
                        max: max_bytes,
                    });
                }
            }
            if VOID_TAGS.contains(&tag.as_str()) {
                // Rendered `<br />` rather than `<br>`: the fragment is spliced
                // into a host page whose author may be serving XHTML, and the
                // self-closing form parses the same in HTML5.
                out.push_str(" />");
                return Ok(());
            }
            out.push('>');
            for child in children {
                write_node(out, child, depth.saturating_add(1), budget, max_bytes)?;
            }
            out.push_str("</");
            out.push_str(&tag);
            out.push('>');
        }
    }
    Ok(())
}

fn write_attribute(
    out: &mut String,
    tag: &str,
    name: &str,
    value: &str,
) -> Result<(), RenderError> {
    // As for the tag above: compared without allocating, so an overlong
    // attribute name is refused on its length rather than after a full copy.
    let Some((_, known)) = ALLOWED_ATTRIBUTES
        .iter()
        .find(|(on, known)| known.eq_ignore_ascii_case(name) && (*on == "*" || *on == tag))
    else {
        return Err(RenderError::ForbiddenAttribute {
            tag: tag.to_owned(),
            name: super::super::manifest::rejected(name),
        });
    };
    let name = (*known).to_owned();
    if value.len() > MAX_TEXT_BYTES {
        return Err(RenderError::TextTooLong(value.len()));
    }
    match name.as_str() {
        "href" => check_href(value)?,
        "class" | "lang" | "dir" | "datetime" => {
            // A closed charset rather than escaping: these values end up in
            // selectors, in `lang` matching and in date parsing, and a value
            // that needs escaping to be safe here is a value that was never
            // going to work anyway.
            if !value.bytes().all(|byte| {
                byte.is_ascii_alphanumeric()
                    || matches!(byte, b' ' | b'-' | b'_' | b':' | b'.' | b'+')
            }) {
                return Err(RenderError::InvalidAttributeValue {
                    name: name.clone(),
                    reason: "expected letters, digits, spaces and `-_:.+`",
                });
            }
        }
        // The condition is a guard rather than an `if` inside the arm: an arm
        // whose whole body is one `if` is an arm clippy asks to be written this
        // way, and the `_ => {}` below already accepts everything that falls
        // through, so the guard failing lands there rather than anywhere new.
        "colspan" | "rowspan"
            if value.is_empty()
                || value.len() > 3
                || !value.bytes().all(|byte| byte.is_ascii_digit()) =>
        {
            return Err(RenderError::InvalidAttributeValue {
                name: name.clone(),
                reason: "expected one to three digits",
            });
        }
        // `title` is the only free-form value, and it is escaped like text.
        _ => {}
    }
    out.push(' ');
    out.push_str(&name);
    out.push_str("=\"");
    escape_into(out, value);
    out.push('"');
    Ok(())
}

/// Refuse any `href` that is not a same-document or same-origin path.
///
/// An allow-list of *shapes* rather than a deny-list of schemes. `javascript:`
/// is the famous one, but `data:text/html`, `vbscript:`, and every scheme a
/// browser or an OS handler adds next are the same hole, and a deny-list is
/// never finished.
///
/// # Backslashes are refused outright
///
/// `//host` is the obvious protocol-relative escape and is refused. `/\host` is
/// the same escape spelled the way the WHATWG URL parser reads it: for a
/// *special* scheme (`http`, `https`) a backslash is a path separator, so
/// `/\attacker.test/login` parses as `//attacker.test/login` and every major
/// browser navigates off-origin. `\/`, `\\` and a backslash anywhere later in
/// the value are the same class of bug one variation along, so the character is
/// refused wherever it appears rather than pattern-matched at the front.
fn check_href(value: &str) -> Result<(), RenderError> {
    // Before the shape test, and unconditionally: `/\evil` passes every
    // prefix check a reader would write, because the byte that makes it an
    // authority is the *second* one.
    if value.contains('\\') {
        return Err(RenderError::InvalidAttributeValue {
            name: "href".to_owned(),
            reason: "may not carry a backslash: a browser reads it as a path \
                     separator, so `/\\host` is `//host` by another spelling",
        });
    }
    let shaped = (value.starts_with('/') && !value.starts_with("//"))
        || value.starts_with('#')
        || value.starts_with('?');
    if !shaped {
        return Err(RenderError::InvalidAttributeValue {
            name: "href".to_owned(),
            reason: "expected a same-origin link: `/path`, `?query` or `#fragment`",
        });
    }
    // Control characters are how `java\tscript:` gets past a scheme check in a
    // browser that strips them. Nothing here needs one.
    if value.chars().any(char::is_control) {
        return Err(RenderError::InvalidAttributeValue {
            name: "href".to_owned(),
            reason: "may not carry control characters",
        });
    }
    Ok(())
}

/// Escape text for both element content and a double-quoted attribute value.
///
/// One function for both contexts, escaping the union of what each needs: `&`
/// and `<` and `>` for content, plus `"` and `'` for attributes. Two functions
/// would be one function and a place to use the wrong one.
fn escape_into(out: &mut String, text: &str) {
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            other => out.push(other),
        }
    }
}

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

    fn text(value: &str) -> FragmentNode {
        FragmentNode::Text {
            text: value.to_owned(),
        }
    }

    fn element(
        tag: &str,
        attributes: &[(&str, &str)],
        children: Vec<FragmentNode>,
    ) -> FragmentNode {
        FragmentNode::Element {
            tag: tag.to_owned(),
            attributes: attributes
                .iter()
                .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
                .collect(),
            children,
        }
    }

    #[test]
    fn a_fragment_renders_to_escaped_html() {
        let nodes = vec![element(
            "p",
            &[("class", "panel")],
            vec![text("3 orders <b>& counting</b>")],
        )];
        assert_eq!(
            render(&nodes, 4096),
            Ok(r#"<p class="panel">3 orders &lt;b&gt;&amp; counting&lt;/b&gt;</p>"#.to_owned())
        );
    }

    #[test]
    fn a_void_tag_never_carries_children_into_the_page() {
        let nodes = vec![element("br", &[], vec![text("smuggled")])];
        assert_eq!(render(&nodes, 4096), Ok("<br />".to_owned()));
    }

    #[test]
    fn nothing_executable_can_be_expressed() {
        for tag in [
            "script", "style", "iframe", "object", "embed", "form", "input", "button", "img",
            "svg", "math", "link", "meta", "base", "template", "noscript",
        ] {
            assert!(
                matches!(
                    render(&[element(tag, &[], Vec::new())], 4096),
                    Err(RenderError::ForbiddenTag(_))
                ),
                "<{tag}> was rendered"
            );
        }
    }

    #[test]
    fn no_event_handler_or_style_survives() {
        for name in [
            "onclick",
            "onerror",
            "onload",
            "style",
            "id",
            "srcdoc",
            "formaction",
            "xlink:href",
        ] {
            assert!(
                matches!(
                    render(&[element("div", &[(name, "x")], Vec::new())], 4096),
                    Err(RenderError::ForbiddenAttribute { .. })
                ),
                "{name} was rendered"
            );
        }
    }

    #[test]
    fn an_href_may_only_point_back_at_the_host() {
        for href in ["/orders/7", "?page=2", "#top"] {
            assert!(
                render(&[element("a", &[("href", href)], Vec::new())], 4096).is_ok(),
                "{href}"
            );
        }
        for href in [
            "javascript:alert(1)",
            "JavaScript:alert(1)",
            "java\tscript:alert(1)",
            "data:text/html,<script>alert(1)</script>",
            "vbscript:msgbox",
            "https://attacker.test/",
            "//attacker.test/",
            // A browser reads `\` as a path separator for http(s), so each of
            // these is `//attacker.test` by another spelling and navigates
            // off-origin. `/\` is the one a `!starts_with("//")` guard misses.
            "/\\attacker.test/login",
            "\\/attacker.test/login",
            "\\\\attacker.test\\share",
            "/path\\..\\..\\etc",
        ] {
            assert!(
                matches!(
                    render(&[element("a", &[("href", href)], Vec::new())], 4096),
                    Err(RenderError::InvalidAttributeValue { .. })
                ),
                "{href} was rendered"
            );
        }
    }

    #[test]
    fn an_attribute_value_cannot_break_out_of_its_quotes() {
        let rendered = render(
            &[element(
                "a",
                &[("title", "\" onmouseover=\"alert(1)")],
                Vec::new(),
            )],
            4096,
        )
        .expect("title is free-form and escaped");
        assert!(!rendered.contains("onmouseover=\"alert"), "{rendered}");
        assert!(rendered.contains("&quot;"), "{rendered}");
    }

    #[test]
    fn a_class_value_is_a_closed_charset_rather_than_an_escaped_one() {
        assert!(render(&[element("div", &[("class", "a b-c_d")], Vec::new())], 4096).is_ok());
        assert!(matches!(
            render(&[element("div", &[("class", "a\"b")], Vec::new())], 4096),
            Err(RenderError::InvalidAttributeValue { .. })
        ));
    }

    #[test]
    fn a_tree_deeper_or_wider_than_the_ceilings_is_refused() {
        let mut deep = text("leaf");
        for _ in 0..(MAX_DEPTH + 2) {
            deep = element("div", &[], vec![deep]);
        }
        assert_eq!(render(&[deep], 1 << 20), Err(RenderError::TooDeep));

        let wide: Vec<FragmentNode> = (0..=MAX_NODES).map(|_| text("x")).collect();
        assert_eq!(render(&wide, 1 << 20), Err(RenderError::TooManyNodes));
    }

    #[test]
    fn an_overlong_tag_or_attribute_name_is_refused_without_being_copied() {
        // The outbound method got this treatment a few rounds back and the pass
        // stopped there. These are the siblings: a tag and an attribute name
        // were both `to_ascii_lowercase`d before anything decided they were
        // names at all, so a megabyte of either was copied once for the fold
        // and again for the denial -- per concurrent render, outside the Wasm
        // memory limiter.
        let huge = "p".repeat(512 * 1024);
        assert!(matches!(
            render(
                &[FragmentNode::Element {
                    tag: huge.clone(),
                    attributes: Vec::new(),
                    children: Vec::new(),
                }],
                1 << 20
            ),
            Err(RenderError::ForbiddenTag(_))
        ));
        assert!(matches!(
            render(
                &[FragmentNode::Element {
                    tag: "p".to_owned(),
                    attributes: vec![(huge, "x".to_owned())],
                    children: Vec::new(),
                }],
                1 << 20
            ),
            Err(RenderError::ForbiddenAttribute { .. })
        ));

        // And the case-insensitivity the fold existed for still holds, so the
        // allocation-free match did not quietly become a case-sensitive one.
        assert_eq!(
            render(
                &[FragmentNode::Element {
                    tag: "P".to_owned(),
                    attributes: vec![("CLASS".to_owned(), "a".to_owned())],
                    children: Vec::new(),
                }],
                1 << 20
            ),
            Ok("<p class=\"a\"></p>".to_owned())
        );
    }

    #[test]
    fn a_fragment_over_the_render_bytes_quota_is_refused_rather_than_truncated() {
        // A truncated fragment is a fragment with an unclosed tag, which
        // reflows the host page around it.
        let nodes: Vec<FragmentNode> = (0..64).map(|_| text(&"x".repeat(1024))).collect();
        assert!(matches!(
            render(&nodes, 4096),
            Err(RenderError::TooLarge { .. })
        ));
    }

    #[test]
    fn an_over_long_text_run_is_refused_before_it_is_escaped() {
        let long = "x".repeat(MAX_TEXT_BYTES + 1);
        assert_eq!(
            render(&[text(&long)], 1 << 20),
            Err(RenderError::TextTooLong(MAX_TEXT_BYTES + 1))
        );
    }

    #[test]
    fn every_allowed_tag_actually_renders() {
        for tag in ALLOWED_TAGS {
            assert!(
                render(&[element(tag, &[], Vec::new())], 4096).is_ok(),
                "<{tag}> is allowed but does not render"
            );
        }
    }

    #[test]
    fn a_fragment_round_trips_through_the_wire_shape_a_guest_writes() {
        let json = r#"[{"node":"element","tag":"p","children":[{"node":"text","text":"hi"}]}]"#;
        let nodes: Vec<FragmentNode> = serde_json::from_str(json).expect("parses");
        assert_eq!(render(&nodes, 4096), Ok("<p>hi</p>".to_owned()));
        // Anything the shape does not define is refused, like every other frame.
        assert!(
            serde_json::from_str::<Vec<FragmentNode>>(
                r#"[{"node":"element","tag":"p","onclick":"x"}]"#
            )
            .is_err()
        );
    }

    #[test]
    fn one_element_may_not_carry_unbounded_attributes() {
        // The allow-list bounds *which* attributes appear and says nothing
        // about how many. An element repeating `title` is inside every other
        // ceiling — depth, node count, per-value length — and still renders
        // megabytes, because escaping expands each value severalfold and the
        // byte check used to run once per node rather than per attribute.
        // `a`, because `title` is the one free-form value the allow-list
        // permits and it permits it there. On any other tag this would be
        // refused for the attribute's *name* and prove nothing about its size.
        let wide = FragmentNode::Element {
            tag: "a".to_owned(),
            attributes: (0..=MAX_ATTRIBUTES)
                .map(|_| ("title".to_owned(), "x".to_owned()))
                .collect(),
            children: Vec::new(),
        };
        assert!(matches!(
            render(&[wide], 1024 * 1024),
            Err(RenderError::TooManyAttributes(_))
        ));

        // And the byte ceiling stops the string being *built*, not merely
        // reports its size: every value here escapes to five bytes.
        let heavy = FragmentNode::Element {
            tag: "a".to_owned(),
            attributes: (0..MAX_ATTRIBUTES)
                .map(|_| ("title".to_owned(), "&".repeat(MAX_TEXT_BYTES)))
                .collect(),
            children: Vec::new(),
        };
        assert!(
            matches!(render(&[heavy], 4096), Err(RenderError::TooLarge { .. })),
            "a fragment far over the ceiling should be refused"
        );
    }
}