oxblade 0.3.2

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
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
//! WP17b: render limits and deep nesting. Runaway templates, hostile data and absurd nesting must end in a
//! clean `oxblade::Error`, never a panic, an abort, a stack overflow or an unbounded allocation.
//!
//! Each deep-nesting case runs on a thread with the 2 MiB stack Rust gives test threads, since a web server's
//! worker threads are no bigger. A case that overflows the stack aborts the whole test binary, so each is its
//! own test and a known failure is `#[ignore]`d with the reason.
#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)] // Test, bench and example code may unwrap.

use oxblade::{
    engine::{Environment, Limits, Options},
    error::{ErrorKind, Result},
    loader::{Loader, Source, missing_view},
    value::{Value, ValueMap},
};
use serde_json::{Value as Json, json};
use std::time::{Duration, Instant};

struct Views(Vec<(String, String)>);

impl Views {
    fn new(views: &[(&str, &str)]) -> Self {
        Self(
            views
                .iter()
                .map(|(name, text)| ((*name).to_owned(), (*text).to_owned()))
                .collect(),
        )
    }
}

impl Loader for Views {
    fn load(&self, name: &str) -> Result<Source> {
        self.0
            .iter()
            .find(|(view, _)| view == name)
            .map(|(_, text)| Source::new(name, text.as_str()))
            .ok_or_else(|| missing_view(name))
    }
}

fn limited(depth: usize, output: usize, iterations: usize, expansion: usize) -> Options {
    Options {
        limits: Limits {
            depth,
            output,
            iterations,
            expansion,
        },
        ..Options::default()
    }
}

fn run(views: &[(&str, &str)], options: Options, data: &Json) -> (Result<String>, Duration) {
    let engine = Environment::builder(Views::new(views))
        .options(options)
        .build();
    let values: ValueMap<'_> = data
        .as_object()
        .unwrap()
        .iter()
        .map(|(key, value)| (key.clone(), Value::Json(value)))
        .collect();
    let started = Instant::now();
    let result = engine.render("main", values);
    (result, started.elapsed())
}

fn assert_limit(views: &[(&str, &str)], options: Options, data: &Json, reason: &str) {
    let (result, elapsed) = run(views, options, data);
    eprintln!("{reason}: {elapsed:?}");
    let error = result.expect_err(reason);
    assert_eq!(error.kind, ErrorKind::Limit, "{reason}: {error}");
    assert!(
        elapsed < Duration::from_secs(20),
        "{reason} took {elapsed:?}"
    );
    assert!(!error.message.is_empty());
}

fn on_small_stack<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(work)
        .unwrap()
        .join()
        .expect("the render must not panic")
}

// --- limits -------------------------------------------------------------------------------------------

#[test]
fn recursion_stops_at_the_depth_limit_in_every_form() {
    let recursive: &[&[(&str, &str)]] = &[
        &[("main", "@include('main')")],
        &[
            ("main", "@if(true)@include('a')@endif"),
            ("a", "x @include('b')"),
            ("b", "y @include('a')"),
        ],
        &[("main", "<x-r/>"), ("components.r", "<x-r/>")],
        &[
            ("main", "<x-r>a</x-r>"),
            ("components.r", "<x-r>{{ slot }}</x-r>"),
        ],
        &[
            ("main", "<x-r><x-slot:s><x-r/></x-slot:s></x-r>"),
            ("components.r", "{{ s ?? '' }}<x-r/>"),
        ],
        &[("main", "@extends('main')@section('x')y @endsection")],
        &[
            ("main", "@extends('layout')@section('x')y @endsection"),
            ("layout", "@extends('main')"),
        ],
        &[("main", "@each('main', [1, 2], 'item')")],
        &[("main", "@include(name)")],
    ];
    for views in recursive {
        for depth in [1, 2, 8, 64] {
            let (result, elapsed) = run(
                views,
                limited(depth, 1 << 20, 1 << 20, 1 << 20),
                &json!({ "name": "main" }),
            );
            let error = result.expect_err("recursion must be stopped");
            assert_eq!(
                error.kind,
                ErrorKind::Limit,
                "depth {depth}, views {views:?}: {error}"
            );
            assert!(elapsed < Duration::from_secs(20));
        }
    }
}

#[test]
fn the_default_limits_stop_recursion_loops_output_and_expansion() {
    let defaults = Options::default();
    let huge = json!({});
    for (template, reason) in [
        ("@include('main')", "include recursion"),
        ("@while(true)@endwhile", "endless loop"),
        (
            "@foreach(i in 0..1000000000){{ i }} @endforeach",
            "huge range loop",
        ),
        (
            "@foreach(i in 0..400)@foreach(j in 0..400) @endforeach @endforeach",
            "nested loops multiply",
        ),
        (
            "@foreach(i in 0..100){{ str::repeat('x', 100000) }} @endforeach",
            "output grows past the cap",
        ),
        ("{{ str::repeat('x', 10000000000) }}", "one huge string"),
        (
            "{{ str::repeat('x', 9223372036854775807) }}",
            "string size overflows",
        ),
        ("{{ 'x'.repeat(10000000000) }}", "repeat method"),
        (
            "{{ 'xxx'.replace('x', str::repeat('y', 5000000)) }}",
            "replace grows past the cap",
        ),
    ] {
        let (result, elapsed) = run(&[("main", template)], defaults, &huge);
        let error = result.expect_err(reason);
        assert_eq!(
            error.kind,
            ErrorKind::Limit,
            "{reason}: `{template}` gave {error}"
        );
        assert!(
            elapsed < Duration::from_secs(20),
            "{reason} took {elapsed:?}"
        );
    }
}

#[test]
fn collection_methods_stop_at_the_expansion_limit() {
    let list: Vec<u32> = (0..5000).collect();
    let data = json!({ "list": list });
    for template in [
        "{{ list.sliding(1000, 1).len() }}",
        "{{ list.cross_join(list).len() }}",
        "{{ list.multiply(1000).len() }}",
        "{{ list.pad(1000000000, 0).len() }}",
    ] {
        assert_limit(&[("main", template)], Options::default(), &data, template);
    }
    let list: Vec<u32> = (0..400).collect();
    let data = json!({ "list": list });
    for template in [
        "{{ list.flat_map(|i| list).len() }}",
        "{{ list.map(|i| list).flatten().len() }}",
    ] {
        assert_limit(&[("main", template)], Options::default(), &data, template);
    }
}

#[test]
fn flat_map_and_flatten_are_checked_while_they_grow() {
    let list: Vec<u32> = (0..100_000).collect();
    let data = json!({ "list": list });
    for template in [
        "{{ list.flat_map(|i| list).len() }}",
        "{{ list.map(|i| list).flatten().len() }}",
    ] {
        let (result, elapsed) = run(&[("main", template)], Options::default(), &data);
        assert_eq!(result.unwrap_err().kind, ErrorKind::Limit, "{template}");
        assert!(
            elapsed < Duration::from_secs(2),
            "{template} took {elapsed:?}"
        );
    }
}

#[test]
fn string_padding_is_checked_before_it_allocates() {
    for template in [
        "{{ 'x'.pad_left(1500000000) }}",
        "{{ 'x'.pad_right(1500000000) }}",
        "{{ 'x'.pad_both(1500000000) }}",
        "{{ str::pad_left('x', 1500000000) }}",
    ] {
        assert_limit(
            &[("main", template)],
            Options::default(),
            &json!({}),
            template,
        );
    }
}

#[test]
fn formatting_widths_are_checked_before_they_allocate() {
    for template in [
        "{{ sprintf('%1500000000s', 'x') }}",
        "{{ php::sprintf('%1500000000s', 'x') }}",
        "{{ number_format(1.5, 1500000000) }}",
        "{{ php::number_format(1.5, 1500000000) }}",
    ] {
        let (result, elapsed) = run(&[("main", template)], Options::default(), &json!({}));
        assert!(result.is_err(), "{template}");
        assert!(
            elapsed < Duration::from_secs(2),
            "{template} took {elapsed:?}"
        );
    }
}

#[test]
fn string_building_in_a_loop_is_capped_too() {
    assert_limit(
        &[(
            "main",
            "@let(mut s = 'x')@foreach(i in 0..60)@code(s = s + s;) @endforeach {{ s.len() }}",
        )],
        Options::default(),
        &json!({}),
        "doubling a string 60 times",
    );
}

#[test]
fn list_building_in_a_loop_is_capped_too() {
    assert_limit(
        &[(
            "main",
            "@let(mut l = [1])@foreach(i in 0..60)@code(l = l.merge(l);) @endforeach {{ l.len() }}",
        )],
        Options::default(),
        &json!({}),
        "doubling a list 60 times",
    );
}

#[test]
fn small_limits_hold_exactly() {
    let options = limited(4, 16, 10, 8);
    for (template, reason) in [
        ("0123456789abcdefg", "17 bytes against a 16 byte cap"),
        (
            "@foreach(i in 0..11) @endforeach",
            "11 iterations against a cap of 10",
        ),
        (
            "@foreach(i in 0..9) @endforeach",
            "9 items against an expansion cap of 8",
        ),
    ] {
        let (result, _) = run(&[("main", template)], options, &json!({}));
        let error = result.expect_err(reason);
        assert_eq!(error.kind, ErrorKind::Limit, "{reason}: {error}");
    }
    for template in [
        "0123456789abcdef",
        "@foreach(i in 0..8) @endforeach",
        "@foreach(i in 0..8)@endforeach",
    ] {
        let (result, _) = run(&[("main", template)], options, &json!({}));
        assert!(result.is_ok(), "{template}: {result:?}");
    }
}

#[test]
fn successful_renders_never_exceed_the_output_limit() {
    for cap in [0, 1, 7, 64, 1000] {
        let template = "@foreach(i in 0..50){{ i }}, @endforeach<p>{{ v }}</p>";
        let (result, _) = run(
            &[("main", template)],
            limited(8, cap, 1 << 16, 1 << 16),
            &json!({ "v": "<&>" }),
        );
        match result {
            Ok(output) => assert!(output.len() <= cap, "cap {cap}: {} bytes", output.len()),
            Err(error) => assert_eq!(error.kind, ErrorKind::Limit, "cap {cap}: {error}"),
        }
    }
}

#[test]
fn intermediate_captures_count_against_the_output_limit() {
    let views = [
        (
            "main",
            "<x-box>@foreach(i in 0..2000)abcdefgh @endforeach</x-box>",
        ),
        ("components.box", "{{ '' }}"),
    ];
    assert_limit(
        &views,
        limited(8, 1000, 1 << 20, 1 << 20),
        &json!({}),
        "a slot nobody prints",
    );
    assert_limit(
        &[(
            "main",
            "@push('s')@foreach(i in 0..2000)abcdefgh @endforeach @endpush",
        )],
        limited(8, 1000, 1 << 20, 1 << 20),
        &json!({}),
        "a stack nobody prints",
    );
}

#[test]
fn expansion_limit_applies_to_data_as_well_as_to_ranges() {
    let big: Vec<u32> = (0..5000).collect();
    let data = json!({ "list": big });
    assert_limit(
        &[("main", "@foreach(x in list) @endforeach")],
        limited(8, 1 << 20, 1 << 20, 100),
        &data,
        "iterating 5000 items with an expansion cap of 100",
    );
}

#[test]
fn errors_name_the_view_chain_that_led_to_the_limit() {
    let (result, _) = run(
        &[
            ("main", "<x-outer/>"),
            ("components.outer", "@include('inner')"),
            ("inner", "@foreach(i in 0..1000000) @endforeach"),
        ],
        Options::default(),
        &json!({}),
    );
    let error = result.unwrap_err();
    assert_eq!(error.kind, ErrorKind::Limit);
    assert!(error.span.is_some() || !error.chain.is_empty(), "{error:?}");
}

// --- deep nesting -------------------------------------------------------------------------------------

fn clean(result: Result<String>) {
    match result {
        Ok(_) => {}
        Err(error) => assert!(
            matches!(
                error.kind,
                ErrorKind::Lex
                    | ErrorKind::Parse
                    | ErrorKind::Syntax
                    | ErrorKind::Compile
                    | ErrorKind::Limit
                    | ErrorKind::Render
            ),
            "{error:?}"
        ),
    }
}

fn render_deep(template: String) -> Result<String> {
    let engine = Environment::builder(Views(vec![("main".into(), template)])).build();
    engine.render("main", ValueMap::new())
}

#[test]
fn deeply_nested_directives_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000, 100_000] {
        let template = format!(
            "{}x\n{}",
            "@if(true)\n".repeat(depth),
            "@endif\n".repeat(depth)
        );
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn deeply_nested_loops_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000, 50_000] {
        let template = format!(
            "{}x\n{}",
            "@foreach(i in 0..1)\n".repeat(depth),
            "@endforeach\n".repeat(depth)
        );
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn deeply_nested_parentheses_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000, 100_000] {
        let template = format!("{{{{ {}1{} }}}}", "(".repeat(depth), ")".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn deeply_nested_list_literals_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000, 100_000] {
        let template = format!("@json({}1{})", "[".repeat(depth), "]".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn long_operator_chains_do_not_overflow_the_stack() {
    for depth in [1_000, 10_000, 100_000] {
        for operator in ["+", "-", "*", "&&", "||", "??", "==", "<"] {
            let template = format!("{{{{ 1{} }}}}", format!(" {operator} 1").repeat(depth));
            clean(on_small_stack(move || render_deep(template)));
        }
    }
}

#[test]
fn long_prefix_chains_do_not_overflow_the_stack() {
    for depth in [1_000, 10_000, 100_000] {
        for prefix in ["!", "-"] {
            let template = format!("{{{{ {}1 }}}}", prefix.repeat(depth));
            clean(on_small_stack(move || render_deep(template)));
        }
    }
}

#[test]
fn long_method_and_field_chains_do_not_overflow_the_stack() {
    for depth in [1_000, 10_000, 100_000] {
        let template = format!("{{{{ v{} }}}}", ".trim()".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
        let template = format!("{{{{ v{} }}}}", ".a".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
        let template = format!("{{{{ v{} }}}}", "?.a".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn deeply_nested_closures_and_calls_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000] {
        let calls = format!("{{{{ {}1{} }}}}", "e(".repeat(depth), ")".repeat(depth));
        clean(on_small_stack(move || render_deep(calls)));
        let closures = format!("{{{{ [1].map({}1) }}}}", "|x| ".repeat(depth));
        clean(on_small_stack(move || render_deep(closures)));
    }
}

#[test]
fn deeply_nested_components_and_slots_do_not_overflow_the_stack() {
    for depth in [100, 1_000, 10_000, 50_000] {
        let template = format!("{}x{}", "<x-a>".repeat(depth), "</x-a>".repeat(depth));
        clean(on_small_stack(move || {
            let engine = Environment::builder(Views(vec![
                ("main".into(), template),
                ("components.a".into(), "<b>{{ slot }}</b>".into()),
            ]))
            .build();
            engine.render("main", ValueMap::new())
        }));
        let template = format!("{}x{}", "<div>".repeat(depth), "</div>".repeat(depth));
        clean(on_small_stack(move || render_deep(template)));
    }
}

#[test]
fn deeply_nested_block_syntax_does_not_overflow_the_stack() {
    for depth in [1_000, 100_000] {
        for template in [
            "@section('a') ".repeat(depth),
            "@push('a') ".repeat(depth),
            "<x-slot:a> ".repeat(depth),
        ] {
            clean(on_small_stack(move || render_deep(template)));
        }
    }
}

#[test]
fn unterminated_openers_stay_cheap_at_moderate_sizes() {
    for unit in [
        "{{-- ",
        "{{ ",
        "{!! ",
        "@verbatim ",
        "@php ",
        "@json(",
        "@include('main', {",
    ] {
        let template = unit.repeat(500);
        let (result, elapsed) = on_small_stack(move || {
            let started = Instant::now();
            (render_deep(template), started.elapsed())
        });
        clean(result);
        assert!(
            elapsed < Duration::from_secs(5),
            "{unit:?} x 500 took {elapsed:?}"
        );
    }
}

#[test]
fn unterminated_openers_are_lexed_in_linear_time() {
    for unit in [
        "{{ ",
        "{{-- ",
        "{!! ",
        "@verbatim ",
        "@php ",
        "@json(",
        "@include('main', {",
    ] {
        // The fastest of three runs, so that a busy machine doesn't fail the comparison. Quadratic work took
        // seconds at 16,000 openers; linear work takes milliseconds.
        let time = |count: usize| {
            let template = unit.repeat(count);
            (0..3)
                .map(|_| {
                    let started = Instant::now();
                    clean(render_deep(template.clone()));
                    started.elapsed()
                })
                .min()
                .unwrap_or_default()
        };
        let small = time(4_000);
        let large = time(16_000);
        assert!(
            large < small * 8 + Duration::from_millis(250),
            "{unit:?}: 4000 openers took {small:?}, 16000 took {large:?}; linear work would take about four times as long"
        );
    }
}

/// `{ "v": [[[…1…]]] }`, built by hand: `json!` would serialize the nested value recursively on the test's stack.
fn deep_data(depth: usize) -> Json {
    let mut value = Json::from(1);
    for _ in 0..depth {
        value = Json::Array(vec![value]);
    }
    let mut object = serde_json::Map::new();
    object.insert("v".into(), value);
    Json::Object(object)
}

#[test]
fn deeply_nested_data_encodes_or_fails_cleanly() {
    let owned = std::sync::Arc::new(deep_data(3_000));
    let shared = std::sync::Arc::clone(&owned);
    let result = on_small_stack(move || {
        let values: ValueMap<'_> = shared
            .as_object()
            .unwrap()
            .iter()
            .map(|(key, value)| (key.clone(), Value::Json(value)))
            .collect();
        let engine =
            Environment::builder(Views::new(&[("main", "@json(v)|@js(v)|{{ v.len() }}")])).build();
        engine.render("main", values)
    });
    clean(result);
    // Dropping the nested value recursively is the test's own cost, not the engine's; do it on a big stack.
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024)
        .spawn(move || drop(owned))
        .unwrap()
        .join()
        .unwrap();
}

/// Operations that recurse over the data itself. Parsed JSON is capped at 128 levels by `serde_json`, but a
/// recursive Rust type (a comment tree, a linked list) reaches the engine as deep data.
macro_rules! deep_data_cases {
    ($($name:ident: $template:expr;)*) => {$(
        #[test]
        fn $name() {
            let data = std::sync::Arc::new(deep_data(4_000));
            let shared = std::sync::Arc::clone(&data);
            let result = on_small_stack(move || {
                let values: ValueMap<'_> = shared
                    .as_object()
                    .unwrap()
                    .iter()
                    .map(|(key, value)| (key.clone(), Value::Json(value)))
                    .collect();
                Environment::builder(Views::new(&[("main", $template)])).build().render("main", values)
            });
            clean(result);
            std::thread::Builder::new()
                .stack_size(256 * 1024 * 1024)
                .spawn(move || drop(data))
                .unwrap()
                .join()
                .unwrap();
        }
    )*};
}

deep_data_cases! {
    flatten_over_deeply_nested_data: "{{ v.flatten().len() }}";
    dot_over_deeply_nested_data: "{{ v.dot().len() }}";
    replace_recursive_over_deeply_nested_data: "{{ v.replace_recursive(v).len() }}";
    equality_over_deeply_nested_data: "{{ v == v }}";
    contains_over_deeply_nested_data: "{{ v.contains(v) }}";
    search_over_deeply_nested_data: "{{ v.search(v) }}";
    diff_over_deeply_nested_data: "{{ v.diff(v).len() }}";
    intersect_over_deeply_nested_data: "{{ v.intersect(v).len() }}";
    sort_over_deeply_nested_data: "{{ [v, v].sort().len() }}";
    to_json_over_deeply_nested_data: "{{ v.to_json() }}";
    php_json_encode_over_deeply_nested_data: "{{ php::json_encode(v) }}";
}