mds-cli 0.4.0

MDS (Markdown Script) compiler — command-line interface
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
mod common;
use common::{assert_no_control_chars, fixture, mds_bin};
use std::collections::HashMap;

#[test]
fn file_size_limit_rejects_huge_file() {
    let dir = tempfile::tempdir().unwrap();
    let huge = dir.path().join("huge.mds");
    // Create a file just over 10MB
    let content = "x".repeat(10 * 1024 * 1024 + 1);
    std::fs::write(&huge, &content).unwrap();
    let result = mds::compile(&huge, None);
    assert!(result.is_err());
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("file too large"),
        "Expected 'file too large' error, got: {err}"
    );
}

#[test]
fn path_traversal_import_rejected() {
    let dir = tempfile::tempdir().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();

    // Create a file outside 'sub' directory
    let outside = dir.path().join("secret.mds");
    std::fs::write(&outside, "Secret content").unwrap();

    // Create a file inside 'sub' that tries to import outside its root
    let child = sub.join("child.mds");
    std::fs::write(&child, "@import \"../secret.mds\" as s\n\n@include s\n").unwrap();

    let result = mds::compile(&child, None);
    assert!(result.is_err(), "Traversal import should be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("escapes project directory") || err.contains("import"),
        "Expected path traversal error, got: {err}"
    );
}

#[test]
fn import_depth_limit() {
    let dir = tempfile::tempdir().unwrap();
    // Create a chain of 66 files, each importing the next
    let depth = 66;
    for i in 0..depth {
        let name = format!("mod_{i}.mds");
        let content = if i < depth - 1 {
            let next = format!("mod_{}.mds", i + 1);
            format!("@import \"./{next}\" as m{}\n\nLevel {i}\n", i + 1)
        } else {
            format!("End of chain {i}\n")
        };
        std::fs::write(dir.path().join(&name), content).unwrap();
    }
    let result = mds::compile(dir.path().join("mod_0.mds"), None);
    assert!(result.is_err(), "Deep import chain should be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("import depth") || err.contains("64"),
        "Expected import depth error, got: {err}"
    );
}

#[test]
fn stdin_size_limit_rejects_oversized_input() {
    // Feed more than 10 MB to stdin and verify the CLI returns a non-zero exit code
    // with an appropriate error message.
    use std::io::Write;

    let oversized: Vec<u8> = vec![b'x'; 10 * 1024 * 1024 + 1];

    let mut child = mds_bin()
        .args(["build", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();

    // Write oversized data; ignore broken-pipe errors (process may exit early).
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(&oversized);
    }

    let output = child.wait_with_output().unwrap();
    assert!(
        !output.status.success(),
        "build from oversized stdin must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("exceeds maximum") || stderr.contains("10 MB"),
        "error should mention size limit, got: {stderr}"
    );
}

#[test]
fn vars_file_size_limit_rejects_oversized_file() {
    let dir = tempfile::tempdir().unwrap();
    let huge_vars = dir.path().join("huge_vars.json");

    // Create a JSON file just over 10 MB (fill a JSON object with long values)
    let mut content = String::from("{\"key\": \"");
    content.push_str(&"x".repeat(10 * 1024 * 1024));
    content.push_str("\"}");
    std::fs::write(&huge_vars, &content).unwrap();

    let result = mds::load_vars_file(&huge_vars);
    assert!(result.is_err(), "oversized vars file must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("exceeds maximum size") || err.contains("vars file"),
        "error should mention vars file size limit, got: {err}"
    );
}

#[test]
fn for_loop_iteration_limit_rejects_huge_array() {
    // Build a source that iterates over an array larger than MAX_LOOP_ITERATIONS (100_000).
    // We construct the array via runtime vars to avoid a huge source string.
    let huge_array: Vec<mds::Value> = (0..100_001)
        .map(|i| mds::Value::String(format!("item{i}")))
        .collect();
    let mut vars = HashMap::new();
    vars.insert("items".to_string(), mds::Value::Array(huge_array));

    let result = mds::compile(fixture("loop.mds"), Some(vars));
    assert!(result.is_err(), "loop over 100_001 items must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("exceeding maximum loop iteration limit")
            || err.contains("100001")
            || err.contains("100_001"),
        "error should mention iteration limit, got: {err}"
    );
}

#[test]
#[cfg(unix)]
fn symlink_import_rejected() {
    let dir = tempfile::tempdir().unwrap();

    // Create a real .mds file to be the symlink target
    let real_file = dir.path().join("real.mds");
    std::fs::write(&real_file, "@define greet(name):\nHello {{name}}!\n@end\n").unwrap();

    // Create a symlink pointing to it
    let link_file = dir.path().join("linked.mds");
    std::os::unix::fs::symlink(&real_file, &link_file).unwrap();

    // Create a consumer that imports via the symlink
    let consumer = dir.path().join("consumer.mds");
    std::fs::write(
        &consumer,
        "@import { greet } from \"./linked.mds\"\n{{greet(\"Alice\")}}\n",
    )
    .unwrap();

    let result = mds::compile(&consumer, None);
    assert!(result.is_err(), "import via symlink must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("symlink") || err.contains("not allowed"),
        "error should mention symlink restriction, got: {err}"
    );
}

#[test]
fn nested_loop_total_iteration_limit() {
    // Two nested loops of 1001 × 1000 = 1,001,000 total iterations must be rejected.
    // Build the source inline: outer array has 1001 elements, inner has 1000.
    let outer: Vec<String> = (0..1001).map(|i| format!("o{i}")).collect();
    let inner: Vec<String> = (0..1000).map(|i| format!("i{i}")).collect();
    let outer_yaml = outer.join(", ");
    let inner_yaml = inner.join(", ");
    let source = format!(
        "---\nouter: [{outer_yaml}]\ninner: [{inner_yaml}]\n---\n@for x in outer:\n@for y in inner:\n{{x}}-{{y}}\n@end\n@end\n"
    );
    let result = mds::compile_str_with(&source, None, None);
    assert!(
        result.is_err(),
        "nested loops exceeding 1M total iterations must be rejected"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("total loop iterations") || err.contains("1000000"),
        "error should mention total iteration limit, got: {err}"
    );
}

#[test]
fn nested_loop_under_total_iteration_limit() {
    // With unconditional iteration counting, every iteration across all loops counts.
    // 999 outer × 1000 inner = 999,000 inner iterations + 999 outer = 999,999 total.
    // This stays under MAX_TOTAL_ITERATIONS (1,000,000) and must succeed.
    let outer: Vec<String> = (0..999).map(|i| format!("o{i}")).collect();
    let inner: Vec<String> = (0..1000).map(|i| format!("i{i}")).collect();
    let outer_yaml = outer.join(", ");
    let inner_yaml = inner.join(", ");
    let source = format!(
        "---\nouter: [{outer_yaml}]\ninner: [{inner_yaml}]\n---\n@for x in outer:\n@for y in inner:\nx\n@end\n@end\n"
    );
    let result = mds::compile_str_with(&source, None, None);
    assert!(
        result.is_ok(),
        "nested loops under 1M total iterations must succeed, got: {:?}",
        result.unwrap_err()
    );
}

#[test]
fn resolve_source_nonexistent_base_dir_errors() {
    // Passing a non-existent base_dir to compile_str_with must now return an error
    // (previously silently fell back to the raw path).
    let nonexistent_dir = std::path::Path::new("/nonexistent/path/that/does/not/exist");
    let result = mds::compile_str_with(
        "---\nname: World\n---\nHello {{name}}!\n",
        Some(nonexistent_dir),
        None,
    );
    assert!(
        result.is_err(),
        "non-existent base_dir must now return an error"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("cannot resolve base directory") || err.contains("nonexistent"),
        "error should describe the unresolvable base directory, got: {err}"
    );
}

#[test]
fn resolve_source_import_traversal_rejected() {
    // Security invariant (AC-S2): the string + base_dir route must reject a
    // relative `@import` that escapes `base_dir` via `../`, exactly like the
    // file route (`path_traversal_import_rejected` above). Regression guard for
    // PF-003 / #133 / #146 directory-anchored resolution — `ctx.base_dir` still
    // routes through the same path-traversal check (`check_path_traversal`).
    let dir = tempfile::tempdir().unwrap();
    let sub = dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();

    // Create a file outside the 'sub' base_dir.
    let outside = dir.path().join("secret.mds");
    std::fs::write(&outside, "Secret content").unwrap();

    let source = "@import \"../secret.mds\" as s\n\n@include s\n";
    let result = mds::compile_str_with(source, Some(sub.as_path()), None);
    assert!(
        result.is_err(),
        "string-route traversal import should be rejected"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("escapes project directory") || err.contains("import"),
        "Expected path traversal error, got: {err}"
    );
}

#[test]
fn parser_nesting_depth_limit_rejects_deep_nesting() {
    // Build a template with 65 nested @if blocks (just past MAX_NESTING_DEPTH=64).
    //
    // 65 levels is well within the default 2 MB thread stack, so no enlarged
    // stack is required. The depth limit error must fire before any stack overflow.
    let mut source = String::new();
    source.push_str("---\nflag: true\n---\n");
    for _ in 0..65 {
        source.push_str("@if flag:\n");
    }
    source.push_str("deep\n");
    for _ in 0..65 {
        source.push_str("@end\n");
    }

    let result = mds::compile_str(&source);
    assert!(result.is_err(), "65 nested @if blocks must be rejected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("nesting") || err.contains("depth") || err.contains("64"),
        "error should mention nesting depth limit, got: {err}"
    );
}

#[test]
fn build_mds_json_output_dir_path_traversal_rejected() {
    // mds.json with `output_dir` containing `..` components must be rejected
    // by resolve_output_path to prevent writing files outside the project root.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Hello!\n").unwrap();
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"output_dir": "../escaped"}}"#,
    )
    .unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "build with output_dir containing '..' must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("..") || stderr.contains("output_dir"),
        "error should mention the traversal or output_dir, got: {stderr}"
    );
}

#[test]
fn config_size_limit_rejects_oversized_mds_json() {
    // mds.json files larger than MAX_CONFIG_SIZE (1 MB) must be rejected to
    // prevent runaway memory use when walking up the directory tree.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("hello.mds");
    std::fs::write(&src, "Hello!\n").unwrap();

    // Build a JSON file just over 1 MB by padding the output_dir value.
    let padding = "x".repeat(1024 * 1024);
    let huge_config = format!(r#"{{"build": {{"output_dir": "{padding}"}}}}"#);
    std::fs::write(dir.path().join("mds.json"), &huge_config).unwrap();

    let output = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "build with oversized mds.json must fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("too large") || stderr.contains("1 MB") || stderr.contains("mds.json"),
        "error should mention config size limit, got: {stderr}"
    );
}

#[test]
fn exit_code_resource_limit() {
    // Trigger MAX_TOTAL_ITERATIONS (1,000,000) via two nested @for loops.
    // Outer array: 1,001 items × inner array: 1,001 items = 1,002,001 iterations.
    // Each individual loop stays well under MAX_LOOP_ITERATIONS (100,000), so
    // only MAX_TOTAL_ITERATIONS fires, producing MdsError::ResourceLimit → exit code 3.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("resource_limit.mds");

    // Build a YAML frontmatter array of 1,001 string items and a nested @for loop.
    let mut source = String::from("---\n");
    source.push_str("outer:\n");
    for i in 0..1001 {
        source.push_str(&format!("  - item{i}\n"));
    }
    source.push_str("inner:\n");
    for i in 0..1001 {
        source.push_str(&format!("  - sub{i}\n"));
    }
    source.push_str("---\n");
    source.push_str("@for x in outer:\n");
    source.push_str("@for y in inner:\n");
    source.push_str("{{x}}-{{y}}\n");
    source.push_str("@end\n");
    source.push_str("@end\n");

    std::fs::write(&src, &source).unwrap();

    let status = mds_bin()
        .args(["build"])
        .arg(&src)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("failed to run mds");

    assert_eq!(
        status.code(),
        Some(3),
        "expected exit code 3 for resource-limit error"
    );
}

// ── AC-2: load_vars_file rejects symlinked vars paths (PF-004 fix) ───────────

#[test]
#[cfg(unix)]
fn load_vars_file_rejects_symlinked_path() {
    // Proves the PF-004 fix: load_vars_file now routes the path through
    // NativeFs::check_symlink before reading, the same guard applied to every
    // other file read in the resolver.
    let dir = tempfile::tempdir().unwrap();

    let real_vars = dir.path().join("real_vars.json");
    std::fs::write(&real_vars, r#"{"name": "Alice"}"#).unwrap();

    let link_vars = dir.path().join("link_vars.json");
    std::os::unix::fs::symlink(&real_vars, &link_vars).unwrap();

    let result = mds::load_vars_file(&link_vars);
    assert!(
        result.is_err(),
        "load_vars_file must reject a symlinked vars path"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("symlink") || err.contains("not allowed"),
        "error must mention symlink restriction; got: {err}"
    );
}

// ── CWE-150: control bytes in the error MESSAGE on the CLI human path (#176) ──
//
// The pre-existing ESC e2e tests in `cli_build.rs` / `cli_fmt.rs` / `cli_lint.rs`
// all use the `@define \x1bfoo:` vector, whose message is the *fixed* string
// "syntax error: @define must have parameter list: @define name(params):" — the
// hostile byte only ever reaches the rendered **source excerpt**, which
// `MdsError::at()` already neutralized. Those tests therefore never exercised the
// message text at all (PF-013: a hostile-input test that cannot fail for the
// reason it claims). The two tests below use vectors that put attacker-controlled
// bytes into the message itself, on both of the CLI's error families:
//
//   1. `MdsError` — `parser.rs` formats the raw alias into
//      `invalid include alias: '{alias}'`.
//   2. CLI-authored `miette::miette!()` — `output.rs` formats the raw `mds.json`
//      value into `mds.json output_dir '{}' must not contain '..' components`.
//
// Both render through `eprint_error`, the single CLI stderr choke-point.

/// T-ESC-MSG-1 [security-11 / CWE-150 / PF-013 / #176]: an `MdsError` whose message
/// interpolates attacker-controlled template text must reach stderr escaped.
///
/// Non-vacuity guard: the command must actually fail *and* stderr must contain the
/// expected error text, so the escape assertions cannot pass by the build silently
/// succeeding or failing for an unrelated reason.
#[test]
fn build_mds_error_message_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("inc.mds");
    // ESC (U+001B) and RIGHT-TO-LEFT OVERRIDE (U+202E) inside the include alias.
    // `is_valid_identifier` rejects it, and the raw alias is formatted into the message.
    std::fs::write(&src, "@include \u{1b}[31mBAD\u{202e}alias\n").unwrap();

    let out = mds_bin()
        .arg("build")
        .arg(&src)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // ── Non-vacuity ──────────────────────────────────────────────────────────
    assert!(
        !out.status.success(),
        "build of an invalid include alias must fail"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("invalid include alias"),
        "non-vacuity: the alias error must be the one rendered; got: {stderr}"
    );

    // ── Negative: no raw hostile bytes survive ───────────────────────────────
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not reach stderr in the error message; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds build MdsError message");

    // ── Positive: the escaped literals are present ───────────────────────────
    assert!(
        stderr.contains("\\u001B"),
        "ESC must be rendered as the \\u001B literal in the message; got: {stderr}"
    );
    assert!(
        stderr.contains("\\u202E"),
        "U+202E must be rendered as the \\u202E literal in the message; got: {stderr}"
    );
}

/// T-ESC-MSG-2 [security-11 / CWE-150 / PF-004 / #176]: a CLI-authored
/// `miette::miette!()` error that interpolates attacker-controlled config text must
/// reach stderr escaped too.
///
/// This is the PF-004 sibling path: `miette!()` reports do **not** downcast to
/// `MdsError` (see `exit_code`'s rustdoc), so a fix that only handled `MdsError`
/// would leave this vector open while claiming the boundary was closed.
#[test]
fn build_cli_authored_error_message_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("hello.mds"), "Hello!\n").unwrap();
    // JSON `\u001b` decodes to a raw ESC byte in the parsed config value. The `..`
    // component trips the traversal guard in `resolve_output_base`, which formats the
    // raw value into its message.
    std::fs::write(
        dir.path().join("mds.json"),
        r#"{"build": {"output_dir": "../\u001b[31mBAD"}}"#,
    )
    .unwrap();

    let out = mds_bin()
        .arg("build")
        .arg(dir.path())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    // ── Non-vacuity ──────────────────────────────────────────────────────────
    assert!(
        !out.status.success(),
        "build with output_dir containing '..' must fail"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("output_dir"),
        "non-vacuity: the output_dir traversal error must be the one rendered; got: {stderr}"
    );

    // ── Negative + positive ──────────────────────────────────────────────────
    assert!(
        !out.stderr.contains(&0x1Bu8),
        "raw ESC byte (0x1B) must not reach stderr from a miette!() message; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds build miette!() message");
    assert!(
        stderr.contains("\\u001B"),
        "ESC must be rendered as the \\u001B literal; got: {stderr}"
    );
}

// ── S14 / PF-004: the two boundaries the #176 alignment review found still open ──
//
// Both are reproduced-first vectors: on the pre-fix binary each command below emits
// the raw hostile bytes (verified with `od -c`).

/// T-ESC-RULE-1 [security-11 / CWE-150 / PF-004 / PF-013 / #176 / AC-224-4 / AC-224-5]:
/// an unknown lint rule NAME from `mds.json` reaches stderr escaped; lint warns and
/// continues rather than hard-failing.
///
/// Vector: `mds.json` is read from the working tree and its rule names are arbitrary
/// JSON object keys. A JSON `\uXXXX` escape decodes to a real byte, so a repository can
/// carry a rule name containing a raw ESC without the file itself looking hostile.
/// This print site sat on a bare `eprintln!`, bypassing both `eprint_error` and
/// `eprint_warning` — the "sixth warning print" that `eprint_warning`'s own rustdoc
/// claimed was foreclosed.
///
/// `serde_json` writes the ESC as a LOWERCASE-hex JSON escape; the sanitizer emits
/// UPPERCASE. Asserting the uppercase form proves the byte genuinely decoded on the way
/// in and was genuinely escaped on the way out, rather than passing through as literal
/// text.
///
/// The vector also carries **newlines**, and the assertions below include a standalone
/// forged-line check. That combination is deliberate: routing this print through
/// `eprint_warning` closed CWE-150 on this vector (no raw control byte) while leaving
/// CWE-117 wide open, because `eprint_warning` is HUMAN mode and HUMAN mode preserves
/// `\n` by design. The earlier version of this test used a newline-free rule name and
/// `assert_no_control_chars`, which permits `\n` — so it certified the fix while the
/// forgery still worked. A rule name is a JSON object key: never legitimately
/// multi-line, so it is WIRE per the spec §7.5 per-field rule.
///
/// **AC-224-4**: run across multiple terminal widths to prove the warning never wraps
/// (eprint_warning → bare eprintln!, independent of COLUMNS). The multi-width loop
/// produces byte-identical output at all seven column values and empirically confirms
/// the single-line invariant, consistent with the sibling T-ESC-RULE-2 test.
#[test]
fn lint_unknown_rule_name_escapes_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();

    // One member of each escape sub-class: a C0 byte, a 3-byte bidi control, the 2-byte
    // bidi control (U+061C) that the class originally missed — and newlines carrying two
    // complete forged status lines.
    let rule_name = format!(
        "{}[31mEVIL{}RULE{}ALM\nClean: totally-real.mds\nOK: all-fine.mds",
        '\u{1b}', '\u{202e}', '\u{061c}'
    );
    let mut rules = serde_json::Map::new();
    rules.insert(rule_name, serde_json::Value::String("warn".to_string()));
    let config = serde_json::json!({ "lint": { "rules": rules } });
    std::fs::write(
        dir.path().join("mds.json"),
        serde_json::to_string(&config).unwrap(),
    )
    .unwrap();

    // AC-224-4: run across multiple terminal widths to prove the singular warning
    // never wraps (eprint_warning → bare eprintln!, independent of COLUMNS).
    for columns in [40u32, 60, 80, 100, 120, 160, 200] {
        let out = mds_bin()
            .arg("lint")
            .arg(dir.path())
            .env("COLUMNS", columns.to_string())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();

        let stderr = String::from_utf8_lossy(&out.stderr);

        // ── Non-vacuity: the warning fired, naming the rule and the recognised list ──
        assert!(
            stderr.contains("unknown lint rule"),
            "COLUMNS={columns}: the unknown-rule warning must be rendered; got: {stderr}"
        );
        assert!(
            stderr.contains("EVIL"),
            "COLUMNS={columns}: the rule name itself must be printed; got: {stderr}"
        );
        assert!(
            stderr.contains("recognised rules are"),
            "COLUMNS={columns}: the recognised-rules list must appear; got: {stderr}"
        );

        // ── Negative: no raw hostile byte survives ───────────────────────────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "COLUMNS={columns}: raw ESC byte (0x1B) must not reach stderr from an mds.json rule name; got: {stderr}"
        );
        assert_no_control_chars(&stderr, "mds lint unknown-rule warning");

        // ── Negative: neither forged line appears on a line of its own ───────────
        //
        // `assert_no_control_chars` deliberately permits `\n` so it can be used on HUMAN-mode
        // prose, so it cannot see this. Mirrors T-ESC-FNAME-1's standalone-line assertion.
        // The rule name carries TWO newlines so "Clean: totally-real.mds" lands as a
        // middle segment that would appear standalone if safe_inline were removed — live.
        for forged in ["Clean: totally-real.mds", "OK: all-fine.mds"] {
            assert!(
                !stderr.lines().any(|l| l.trim() == forged),
                "COLUMNS={columns}: an mds.json rule name must not be able to forge the standalone \
                 status line {forged:?}; got: {stderr}"
            );
        }

        // ── Positive: the escaped literals are present ───────────────────────────
        for escaped in ["\\u001B", "\\u202E", "\\u061C"] {
            assert!(
                stderr.contains(escaped),
                "COLUMNS={columns}: {escaped} must appear in the unknown-rule warning; got: {stderr}"
            );
        }
        assert_eq!(
            stderr.matches("\\u000A").count(),
            2,
            "COLUMNS={columns}: both embedded newlines must be escaped to their WIRE literal; got: {stderr}"
        );

        // ── Non-vacuity: the whole rule name landed on ONE line ──────────────────
        //
        // AC-224-4: the multi-width loop proves the warning occupies exactly one line
        // at every terminal width — eprint_warning never wraps.
        let warning_lines: Vec<&str> = stderr
            .lines()
            .filter(|l| l.contains("unknown lint rule"))
            .collect();
        assert_eq!(
            warning_lines.len(),
            1,
            "COLUMNS={columns}: the warning must occupy exactly one line; got: {stderr}"
        );
        assert!(
            warning_lines[0].contains("EVIL")
                && warning_lines[0].contains("recognised rules are")
                && warning_lines[0].ends_with("; ignoring"),
            "COLUMNS={columns}: the single warning line must carry the rule name, the \
             recognised-rules list, and the trailing '; ignoring'; got: {stderr}"
        );
    }
}

/// T-ESC-RULE-2 [security-11-plural / CWE-150 / PF-004 / PF-013 / AC-224-4 / AC-224-5]:
/// two unknown lint rule names containing control bytes — the plural branch of the
/// warning emitter — reach stderr fully escaped; no raw hostile byte survives.
///
/// Companion to T-ESC-RULE-1 which covers the singular path (one unknown name).
/// This test exercises the plural path (two or more unknown names) so that
/// AD-224-3's per-name safe_inline shape is verified for the multi-name loop.
///
/// Both rule names contain control bytes from different escape sub-classes to
/// confirm that each is independently escaped before it is assembled into the
/// comma-separated list.  The multi-width COLUMNS loop proves the plural warning
/// also lands on exactly one line at every terminal width.
#[test]
fn lint_plural_unknown_rule_names_escape_control_bytes() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();

    // Two distinct hostile rule names — ESC + colour code in the first,
    // RTL-override + Arabic-letter-mark in the second — plus embedded newlines
    // carrying forged status lines in each.
    // Two newlines in rule_a: "Clean: real-a.mds" is the middle segment that would
    // land standalone if safe_inline were removed — makes the forged-line assertion live.
    let rule_a = format!(
        "{}[31mAAA{}RULE\nClean: real-a.mds\nOK: fake-a.mds",
        '\u{1b}', '\u{202e}'
    );
    let rule_b = format!("BBB{}RULE\nOK: real-b.mds", '\u{061c}');
    let mut rules = serde_json::Map::new();
    rules.insert(rule_a, serde_json::Value::String("warn".to_string()));
    rules.insert(rule_b, serde_json::Value::String("warn".to_string()));
    let config = serde_json::json!({ "lint": { "rules": rules } });
    std::fs::write(
        dir.path().join("mds.json"),
        serde_json::to_string(&config).unwrap(),
    )
    .unwrap();

    // AC-224-4: run across multiple terminal widths to prove the plural warning
    // never wraps (eprint_warning → bare eprintln!, independent of COLUMNS).
    for columns in [40u32, 60, 80, 100, 120, 160, 200] {
        let out = mds_bin()
            .arg("lint")
            .arg(dir.path())
            .env("COLUMNS", columns.to_string())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();

        let stderr = String::from_utf8_lossy(&out.stderr);

        // ── Non-vacuity: the plural warning fired ────────────────────────────
        assert!(
            stderr.contains("unknown lint rules"),
            "COLUMNS={columns}: plural unknown-rule warning must be rendered; got: {stderr}"
        );
        assert!(
            stderr.contains("AAA"),
            "COLUMNS={columns}: first hostile rule prefix must appear; got: {stderr}"
        );
        assert!(
            stderr.contains("BBB"),
            "COLUMNS={columns}: second hostile rule prefix must appear; got: {stderr}"
        );
        assert!(
            stderr.contains("recognised rules are"),
            "COLUMNS={columns}: recognised-rules list must appear; got: {stderr}"
        );

        // ── Negative: no raw hostile byte survives ───────────────────────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "COLUMNS={columns}: raw ESC byte (0x1B) must not reach stderr; got: {stderr}"
        );
        assert_no_control_chars(&stderr, "mds lint plural unknown-rule warning");

        // ── Negative: no forged standalone line ──────────────────────────────
        for forged in ["Clean: real-a.mds", "OK: real-b.mds"] {
            assert!(
                !stderr.lines().any(|l| l.trim() == forged),
                "COLUMNS={columns}: rule name must not forge standalone line {forged:?}; \
                 got: {stderr}"
            );
        }

        // ── Positive: escaped literals are present for both names ────────────
        assert!(
            stderr.contains("\\u001B"),
            "COLUMNS={columns}: ESC in first name must be escaped to \\u001B; got: {stderr}"
        );
        assert!(
            stderr.contains("\\u202E"),
            "COLUMNS={columns}: RTL-override in first name must be escaped to \\u202E; \
             got: {stderr}"
        );
        assert!(
            stderr.contains("\\u061C"),
            "COLUMNS={columns}: Arabic-letter-mark in second name must be escaped to \
             \\u061C; got: {stderr}"
        );
        // Three embedded newlines total: two from rule_a, one from rule_b.
        assert_eq!(
            stderr.matches("\\u000A").count(),
            3,
            "COLUMNS={columns}: all embedded newlines (2 from first name, 1 from second) \
             must be escaped to \\u000A; got: {stderr}"
        );

        // ── Non-vacuity: the plural warning occupies exactly ONE line ────────
        let warning_lines: Vec<&str> = stderr
            .lines()
            .filter(|l| l.contains("unknown lint rules"))
            .collect();
        assert_eq!(
            warning_lines.len(),
            1,
            "COLUMNS={columns}: plural warning must occupy exactly one line; got: {stderr}"
        );
        assert!(
            warning_lines[0].ends_with("; ignoring"),
            "COLUMNS={columns}: warning line must end with '; ignoring'; got: {stderr}"
        );
    }
}

/// T-ESC-FNAME-1 [S14 / CWE-117 / PF-013 / #176]: a filename containing newlines
/// cannot forge CLI status lines.
///
/// Vector: POSIX permits a newline inside a filename and the user never types the name
/// — `mds build <dir>` discovers it by directory walk. `safe_path` used HUMAN mode,
/// which preserves newlines by design so that multi-line diagnostic *messages* keep
/// rendering, so a file named `evil.mds<LF>Clean: real.mds<LF>OK: all-fine.mds` emitted
/// two attacker-authored lines byte-identical in form to genuine status output,
/// unframed and unindented.
///
/// Unix-only: Windows filesystems reject a newline in a filename outright.
#[cfg(unix)]
#[test]
fn build_status_line_cannot_be_forged_by_a_newline_in_a_filename() {
    let dir = tempfile::tempdir().unwrap();
    let hostile = "evil.mds\nClean: real.mds\nOK: all-fine.mds";
    std::fs::write(dir.path().join(hostile), "Hello!\n").unwrap();
    let out_dir = dir.path().join("out");

    let out = mds_bin()
        .arg("build")
        .arg(dir.path())
        .arg("--out-dir")
        .arg(&out_dir)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );

    // ── Non-vacuity: the build ran and printed a status line naming the file ─
    assert!(
        out.status.success(),
        "the build must succeed; stdout+stderr: {combined}"
    );
    assert!(
        combined.contains("evil.mds"),
        "non-vacuity: the status line must name the built file; got: {combined}"
    );

    // ── Negative: neither forged line appears on a line of its own ───────────
    for forged in ["Clean: real.mds", "OK: all-fine.mds"] {
        assert!(
            !combined.lines().any(|l| l.trim() == forged),
            "a filename must not be able to forge the standalone status line \
             {forged:?}; got: {combined}"
        );
    }

    // ── Positive: both newlines escaped to their literal form ────────────────
    assert_eq!(
        combined.matches("\\u000A").count(),
        2,
        "both embedded newlines must be escaped; got: {combined}"
    );
}

/// T-ESC-FNAME-2 [S14 / PF-004 / #176]: the `Clean:` status line — which sanitized its
/// filename inline rather than through `safe_path` — is covered by the same guarantee.
///
/// This is the PF-004 sibling of T-ESC-FNAME-1: two status-line printers, one of which
/// open-coded its own escape call and so would have kept HUMAN mode when `safe_path`
/// moved to WIRE. The vector also carries U+061C, the bidi control the escape class
/// originally missed, so this pins both fixes on one line of output.
///
/// Unix-only: Windows filesystems reject a newline in a filename outright.
#[cfg(unix)]
#[test]
fn lint_clean_status_line_cannot_be_forged_by_a_newline_in_a_filename() {
    let dir = tempfile::tempdir().unwrap();
    let hostile = "ok.mds\nClean: real\u{061c}.mds";
    let path = dir.path().join(hostile);
    std::fs::write(&path, "Hello!\n").unwrap();

    let out = mds_bin()
        .arg("lint")
        .arg(&path)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);

    // ── Non-vacuity: the Clean: line actually printed, naming the file ───────
    assert!(
        stderr.contains("Clean: ok.mds"),
        "non-vacuity: the Clean: status line must name the linted file; got: {stderr}"
    );

    // ── Negative: no forged standalone line, no raw hostile codepoint ────────
    assert!(
        !stderr.lines().any(|l| l.trim().starts_with("Clean: real")),
        "a filename must not be able to forge a second Clean: line; got: {stderr}"
    );
    assert_no_control_chars(&stderr, "mds lint Clean: status line");

    // ── Positive: newline and U+061C both escaped ───────────────────────────
    assert!(
        stderr.contains("\\u000A"),
        "the embedded newline must be escaped; got: {stderr}"
    );
    assert!(
        stderr.contains("\\u061C"),
        "U+061C must be escaped; got: {stderr}"
    );
}

/// T-ESC-WALK-1 [security-11 / CWE-150 / CWE-117 / PF-004 / PF-013 / #176]: the shared
/// walker's depth-limit warning escapes the directory name it interpolates.
///
/// Vector: `collect_mds_files_inner` in `mds-cli/src/output.rs` warns when recursion
/// exceeds `MAX_DEPTH` (64) and names the directory it stopped at. The name is
/// *discovered by the walk* — the user never types it — and every directory-mode
/// subcommand shares this walker, so one hostile directory name reached `mds build`,
/// `check`, `fmt`, `lint` and `watch` at once.
///
/// This print sat on a bare `eprintln!` inside `output.rs` itself: it was neither one of
/// the `*_collecting_warnings` sites nor `watch.rs`, so two rounds of "route the warning
/// prints through `eprint_warning`" walked straight past it while the CHANGELOG claimed
/// no raw control byte reached human stderr on any warning path.
///
/// The vector carries all three sub-classes at once — a C0 byte (ESC), a 3-byte bidi
/// control (U+202E), and a newline that forges a complete status line. The ESC goes into
/// the directory name as a RAW byte and is asserted on the way out as the uppercase
/// six-character literal, which proves a genuine decode-then-escape rather than literal
/// passthrough.
///
/// Unix-only: Windows filesystems reject a newline in a path component outright.
#[cfg(unix)]
#[test]
fn walker_depth_limit_warning_cannot_be_forged_by_a_hostile_directory_name() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("root");
    std::fs::create_dir(&root).unwrap();
    std::fs::write(root.join("a.mds"), "Hello!\n").unwrap();

    // MAX_DEPTH is 64; the warning fires on the first directory at depth 65.
    let mut deep = root.clone();
    for i in 1..=64 {
        deep = deep.join(format!("d{i}"));
    }
    let hostile = format!(
        "evil{}[31m{}dir\nClean: totally-real.mds",
        '\u{1b}', '\u{202e}'
    );
    deep = deep.join(&hostile);
    std::fs::create_dir_all(&deep).unwrap();
    std::fs::write(deep.join("deep.mds"), "Hello!\n").unwrap();

    // The walker is shared, so assert on all three directory-mode subcommands rather
    // than trusting that one of them stands in for the others (PF-004).
    for subcommand in ["lint", "check", "fmt"] {
        let out = mds_bin()
            .arg(subcommand)
            .arg(&root)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        let label = format!("mds {subcommand} depth-limit warning");

        // ── Non-vacuity: the warning actually fired and named the directory ──
        assert!(
            stderr.contains("directory depth limit"),
            "non-vacuity [{label}]: the depth-limit warning must fire; got: {stderr}"
        );
        assert!(
            stderr.contains("evil"),
            "non-vacuity [{label}]: the directory name must be printed; got: {stderr}"
        );

        // ── Negative: no raw hostile byte, no forged standalone line ─────────
        assert!(
            !out.stderr.contains(&0x1Bu8),
            "raw ESC byte (0x1B) must not reach stderr from a directory name [{label}]; \
             got: {stderr}"
        );
        assert_no_control_chars(&stderr, &label);
        assert!(
            !stderr
                .lines()
                .any(|l| l.trim() == "Clean: totally-real.mds"),
            "a directory name must not be able to forge a standalone status line \
             [{label}]; got: {stderr}"
        );

        // ── Positive: each hostile codepoint appears in escaped form ─────────
        for escaped in ["\\u001B", "\\u202E", "\\u000A"] {
            assert!(
                stderr.contains(escaped),
                "{escaped} must appear in the depth-limit warning [{label}]; got: {stderr}"
            );
        }
    }
}

// ── R3 / CWE-209: analysis-failure JSON carries no absolute path ─────────────

#[test]
fn r3_lint_json_analysis_failure_message_has_no_absolute_path() {
    // Invalid UTF-8 fails on the raw-read path (lint.rs read_source_file),
    // which must anchor its display root at the project root so the
    // `--format json` analysis-failure `error.message` shows "sub/bad.mds" —
    // never a bare basename and never the canonical absolute path (R3 /
    // CWE-209). The vector is proven reachable: it produces the analysis
    // envelope asserted below (PF-013 non-vacuity).
    let dir = tempfile::tempdir().unwrap();
    // Canonical form (macOS: /var → /private/var) — what a leaked key carries.
    let root = dir.path().canonicalize().unwrap();
    // Deterministic project-root walk-up anchor.
    std::fs::write(root.join(".mdsroot"), "").unwrap();
    let sub = root.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    let input = sub.join("bad.mds");
    std::fs::write(&input, b"Hello \xFF\xFE world\n").unwrap();

    let output = mds_bin()
        .args(["lint", "--format", "json", input.to_str().unwrap()])
        .output()
        .unwrap();

    assert_eq!(
        output.status.code(),
        Some(2),
        "invalid UTF-8 is an analysis failure (exit 2); stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    let v: serde_json::Value =
        serde_json::from_str(&stdout).expect("analysis-failure envelope must be valid JSON");
    let msg = v["error"]["message"]
        .as_str()
        .expect("envelope must carry error.message");

    let root_str = root.to_str().unwrap();
    // Positive control (PF-013): a message carrying the absolute path WOULD be
    // caught by the absence assertion below.
    let planted = format!("invalid UTF-8 in {}: …", input.display());
    assert!(
        planted.contains(root_str),
        "positive control: planted absolute form must match the absence predicate"
    );
    assert!(
        msg.contains("sub/bad.mds"),
        "error.message must show the project-root-relative path; got: {msg}"
    );
    assert!(
        !msg.contains(root_str),
        "error.message must not leak the absolute path prefix; got: {msg}"
    );
}