mod common;
use common::{assert_no_control_chars, mds_bin};
use std::ffi::OsStr;
use std::io::Read;
use std::path::Path;
use std::process::Stdio;
use std::time::{Duration, Instant};
const ESC: char = '\x1b';
fn escaped(ch: char) -> String {
format!("\\u{:04X}", u32::from(ch))
}
fn run<S: AsRef<OsStr> + std::fmt::Debug>(dir: &Path, args: &[S]) -> (Option<i32>, String) {
let mut child = mds_bin()
.current_dir(dir)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let drain = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
buf
})
};
let stdout = drain(Box::new(child.stdout.take().unwrap()));
let stderr = drain(Box::new(child.stderr.take().unwrap()));
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
panic!("mds {args:?} was still running after 20 s");
}
std::thread::sleep(Duration::from_millis(10));
};
let text = format!(
"{}{}",
String::from_utf8_lossy(&stdout.join().unwrap()),
String::from_utf8_lossy(&stderr.join().unwrap())
);
(status.code(), text)
}
fn assert_refusal(text: &str, ch: char, shown_escaped: &str, label: &str) {
assert!(text.contains("mds::io"), "{label}: mds::io; got: {text}");
assert!(
text.contains(&format!("U+{:04X}", u32::from(ch))) && text.contains("forbidden"),
"{label}: must name U+{:04X}; got: {text}",
u32::from(ch)
);
assert!(
text.contains(shown_escaped),
"{label}: must show {shown_escaped:?}; got: {text}"
);
assert_no_control_chars(text, label);
}
fn squash(s: &str) -> String {
s.chars()
.filter(|c| !c.is_whitespace() && *c != '\u{2502}')
.collect()
}
type Frame<'a> = (&'a str, &'a str);
#[cfg(unix)]
const QUOTED: Frame<'static> = ("\"", "\"");
fn assert_names_as_typed(text: &str, frame: Frame<'_>, shown: &str, resolved: &Path, label: &str) {
let (open, close) = frame;
let text = squash(text);
let canonical = resolved.canonicalize().unwrap();
assert!(
!text.contains(&squash(&format!("{open}{}", canonical.display()))),
"{label}: must not name the absolute path; got: {text}"
);
assert!(
text.contains(&squash(&format!("{open}{shown}{close}"))),
"{label}: must name {shown:?} as typed; got: {text}"
);
}
#[cfg(unix)]
mod walker {
use super::*;
use common::{make_symlink, spawn_watch_ready, write_atomic, ChildGuard};
fn is_line(text: &str, line: &str) -> bool {
text.lines().any(|l| l.trim() == line)
}
fn tree() -> (tempfile::TempDir, String) {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("ok.mds"), "Hello!\n").unwrap();
std::fs::write(dir.path().join(format!("evil{ESC}[31m.mds")), "Evil!\n").unwrap();
(dir, format!("evil{}[31m.mds", escaped(ESC)))
}
#[test]
fn build_refuses_the_hostile_file_and_builds_its_sibling() {
let (dir, shown) = tree();
let (code, text) = run(dir.path(), &["build", ".", "--out-dir", "out"]);
assert_eq!(
code,
Some(2),
"an mds::io per-file failure exits 2; got: {text}"
);
assert_refusal(&text, ESC, &shown, "build");
assert!(is_line(&text, "1 built, 1 failed"), "got: {text}");
let out = dir.path().join("out");
assert_eq!(
std::fs::read_to_string(out.join("ok.md")).unwrap(),
"Hello!\n"
);
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 1, "only ok.md");
}
#[test]
fn build_refuses_a_file_under_a_hostile_directory() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("ok.mds"), "Hello!\n").unwrap();
let hostile = dir.path().join(format!("sub{ESC}dir"));
std::fs::create_dir(&hostile).unwrap();
std::fs::write(hostile.join("a.mds"), "A\n").unwrap();
let (code, text) = run(dir.path(), &["build", ".", "--out-dir", "out"]);
assert_eq!(code, Some(2), "got: {text}");
assert_refusal(
&text,
ESC,
&format!("./sub{}dir/a.mds", escaped(ESC)),
"build dir",
);
assert!(is_line(&text, "1 built, 1 failed"), "got: {text}");
assert!(dir.path().join("out").join("ok.md").is_file());
}
#[test]
fn check_refuses_the_hostile_file_and_checks_its_sibling() {
let (dir, shown) = tree();
let (code, text) = run(dir.path(), &["check", "."]);
assert_eq!(code, Some(2), "got: {text}");
assert_refusal(&text, ESC, &shown, "check");
assert!(is_line(&text, "1 passed, 1 failed"), "got: {text}");
}
#[test]
fn fmt_refuses_the_hostile_file_and_formats_its_sibling() {
let (dir, shown) = tree();
std::fs::write(dir.path().join("ok.mds"), "Hello!").unwrap();
let (code, text) = run(dir.path(), &["fmt", "."]);
assert_eq!(code, Some(2), "got: {text}");
assert_refusal(&text, ESC, &shown, "fmt");
assert!(
is_line(&text, "1 formatted, 0 unchanged, 1 failed"),
"got: {text}"
);
assert_eq!(
std::fs::read_to_string(dir.path().join("ok.mds")).unwrap(),
"Hello!\n"
);
}
#[test]
fn lint_refuses_the_hostile_file_and_lints_its_sibling() {
let (dir, shown) = tree();
let (code, text) = run(dir.path(), &["lint", "."]);
assert_eq!(
code,
Some(2),
"a refused file is an error-severity file; got: {text}"
);
assert_refusal(&text, ESC, &shown, "lint");
assert!(
is_line(
&text,
"1 clean, 0 with warnings, 1 with errors, 0 resource-limited"
),
"got: {text}"
);
}
#[test]
fn watch_refuses_the_hostile_file_and_keeps_running() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("ok.mds"), "Hello!\n").unwrap();
std::fs::write(src.join(format!("evil{ESC}[31m.mds")), "Evil!\n").unwrap();
let shown = format!("evil{}[31m.mds", escaped(ESC));
let out = dir.path().join("out");
let (child, tap, _) = spawn_watch_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "src", "--out-dir", "out"])
.args(["--debounce", "0"])
.stdout(Stdio::null()),
);
let mut child = ChildGuard(child);
let wait_for = |path: &Path, needle: &str| {
let deadline = Instant::now() + Duration::from_secs(2);
while Instant::now() < deadline {
if std::fs::read_to_string(path).is_ok_and(|c| c.contains(needle)) {
return true;
}
std::thread::sleep(Duration::from_millis(20));
}
false
};
assert!(
wait_for(&out.join("ok.md"), "Hello!"),
"sibling built at startup"
);
write_atomic(&src.join("ok.mds"), "Edited!\n");
assert!(
wait_for(&out.join("ok.md"), "Edited!"),
"watch keeps running after the refusal; stderr: {}",
tap.text()
);
assert!(
child.0.try_wait().unwrap().is_none(),
"watch must still be running"
);
let stderr = tap.finish_text(&mut child);
assert_refusal(&stderr, ESC, &shown, "watch");
assert_names_as_typed(
&stderr,
QUOTED,
&format!("src/{shown}"),
dir.path(),
"watch",
);
assert!(
!out.join(format!("evil{ESC}[31m.md")).exists(),
"nothing is written for the refused file"
);
}
#[test]
fn watch_file_mode_names_the_hostile_file_as_typed() {
let (dir, shown) = tree();
let hostile = format!("evil{ESC}[31m.mds");
let (code, text) = run(dir.path(), &["watch", hostile.as_str()]);
assert_eq!(code, Some(2), "refused at startup; got: {text}");
assert_refusal(&text, ESC, &shown, "watch file");
assert_names_as_typed(&text, QUOTED, &shown, dir.path(), "watch file");
}
#[test]
fn watch_vars_errors_keep_their_real_message() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hello!\n").unwrap();
let vars = format!("v{ESC}.json");
std::fs::write(dir.path().join(&vars), "{}").unwrap();
let (code, text) = run(dir.path(), &["watch", "in.mds", "--vars", vars.as_str()]);
assert_eq!(code, Some(2), "got: {text}");
assert_refusal(
&text,
ESC,
&format!("v{}.json", escaped(ESC)),
"watch --vars",
);
assert!(!text.contains("must not be a symlink"), "got: {text}");
std::fs::write(dir.path().join("real.json"), "{}").unwrap();
assert!(make_symlink(
&dir.path().join("real.json"),
&dir.path().join("link.json")
));
let (code, text) = run(dir.path(), &["watch", "in.mds", "--vars", "link.json"]);
assert_eq!(code, Some(2), "got: {text}");
assert!(
text.contains("--vars file must not be a symlink: \"link.json\""),
"control: a symlink keeps the symlink message; got: {text}"
);
}
}
#[test]
fn a_symlinked_vars_file_is_an_io_error_on_every_command() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hello {{name}}!\n").unwrap();
std::fs::write(dir.path().join("real.json"), r#"{"name": "vars"}"#).unwrap();
if !common::make_symlink(&dir.path().join("real.json"), &dir.path().join("link.json")) {
return;
}
for command in ["build", "check", "lint", "watch"] {
let (code, text) = run(dir.path(), &[command, "in.mds", "--vars", "link.json"]);
assert_eq!(code, Some(2), "{command}: exit 2; got: {text}");
assert!(text.contains("mds::io"), "{command}: mds::io; got: {text}");
assert!(
squash(&text).contains(&squash("--vars file must not be a symlink: \"link.json\"")),
"{command}: names the file as typed, in quotes, in the words mds watch uses; got: \
{text}"
);
assert!(
!text.contains("mds::import") && !text.contains("symlinks are not allowed"),
"{command}: not the library's own refusal; got: {text}"
);
}
let (code, text) = run(
dir.path(),
&["build", "in.mds", "--vars", "real.json", "-o", "-"],
);
assert_eq!(code, Some(0), "control: the real file is read; got: {text}");
assert!(
text.contains("Hello vars!"),
"control: its variables are used; got: {text}"
);
}
#[cfg(unix)]
mod stdin_cwd {
use super::*;
use std::io::Write;
fn run_stdin(dir: &Path, args: &[&str], input: &str) -> (Option<i32>, String) {
let mut child = mds_bin()
.current_dir(dir)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(input.as_bytes())
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
while child.try_wait().unwrap().is_none() {
if Instant::now() >= deadline {
let _ = child.kill();
panic!("mds {args:?} was still running after 20 s");
}
std::thread::sleep(Duration::from_millis(10));
}
let out = child.wait_with_output().unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
(out.status.code(), text)
}
#[test]
fn stdin_refuses_a_hostile_working_directory_shown_as_dot() {
let tmp = tempfile::tempdir().unwrap();
let tmp_name = tmp.path().file_name().unwrap().to_str().unwrap().to_owned();
for ch in ['\t', ESC] {
let cwd = tmp.path().join(format!("d{ch}e"));
std::fs::create_dir(&cwd).unwrap();
for sub in ["build", "check", "lint", "fmt"] {
let (code, text) = run_stdin(&cwd, &[sub, "-"], "Hello\n");
let label = format!("{sub} - in d<U+{:04X}>e", u32::from(ch));
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(
text.contains(&format!(
"resolved path contains forbidden character U+{:04X}: \".\"",
u32::from(ch)
)),
"{label}: got: {text:?}"
);
assert_refusal(&text, ch, "\".\"", &label);
assert!(!text.contains(ch), "{label}: raw char; got: {text:?}");
assert!(
!text.contains(&tmp_name),
"{label}: absolute path; got: {text:?}"
);
}
}
let clean = tmp.path().join("clean");
std::fs::create_dir(&clean).unwrap();
for sub in ["build", "check", "lint", "fmt"] {
let (code, text) = run_stdin(&clean, &[sub, "-"], "Hello\n");
assert_eq!(code, Some(0), "{sub} - control: got: {text}");
}
}
}
#[test]
fn single_file_argument_is_refused_before_the_existence_check() {
let dir = tempfile::tempdir().unwrap();
for ch in [ESC, '\t', '\n', '\u{202E}'] {
for ext in ["mds", "txt"] {
let value = format!("in{ch}x.{ext}");
let shown = format!("in{}x.{ext}", escaped(ch));
for sub in ["build", "check", "lint", "fmt", "watch"] {
let (code, text) = run(dir.path(), &[sub, value.as_str()]);
let label = format!("{sub} in<U+{:04X}>x.{ext}", u32::from(ch));
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_refusal(&text, ch, &shown, &label);
assert!(!text.contains(&value), "{label}: raw name; got: {text}");
assert!(
!text.contains("not found") && !text.contains("not an MDS file"),
"{label}: the refusal comes first; got: {text}"
);
}
let (code, text) = run(dir.path(), &["lint", "--format", "json", value.as_str()]);
let label = format!("lint --format json in<U+{:04X}>x.{ext}", u32::from(ch));
assert_eq!(code, Some(2), "{label}: got: {text}");
let json: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|e| panic!("{label}: stdout must be JSON ({e}); got: {text}"));
assert_eq!(json["error"]["code"], "mds::io", "{label}: got: {text}");
let message = json["error"]["message"].as_str().unwrap_or_default();
assert!(
message.contains(&format!(
"contains forbidden character U+{:04X}",
u32::from(ch)
)) && message.contains(&shown),
"{label}: got: {message:?}"
);
assert!(!message.contains(ch), "{label}: raw char; got: {message:?}");
}
}
for sub in ["lint", "fmt"] {
let (code, text) = run(dir.path(), &[sub, "missing.mds"]);
assert_eq!(code, Some(2), "{sub} control: got: {text}");
assert!(
text.contains("mds::file_not_found") && text.contains("missing.mds"),
"{sub} control: got: {text}"
);
}
}
#[test]
fn not_mds_cli_names_typed_path() {
use common::{spawn_watch_ready, ChildGuard};
const NOT_MDS: Frame<'static> = ("not an MDS file: ", "help:");
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("sub")).unwrap();
let doc = dir.path().join("doc.txt");
std::fs::write(&doc, "Hello!\n").unwrap();
let absolute = dir
.path()
.join("sub")
.join("..")
.join("doc.txt")
.display()
.to_string();
for typed in ["doc.txt", "./sub/../doc.txt", absolute.as_str()] {
for sub in ["build", "check", "lint", "fmt"] {
let label = format!("{sub} {typed}");
let (code, text) = run(dir.path(), &[sub, typed]);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(text.contains("mds::not_mds"), "{label}: got: {text}");
assert_names_as_typed(&text, NOT_MDS, typed, &doc, &label);
}
let label = format!("watch {typed}");
let (child, tap, _) = spawn_watch_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", typed, "--out-dir", "out", "--debounce", "0"])
.stdout(Stdio::null()),
);
let mut child = ChildGuard(child);
assert!(
child.0.try_wait().unwrap().is_none(),
"{label}: watch keeps running after the startup error"
);
let text = tap.finish_text(&mut child);
assert!(text.contains("mds::not_mds"), "{label}: got: {text}");
assert_names_as_typed(&text, NOT_MDS, typed, &doc, &label);
}
std::fs::write(dir.path().join("doc.mds"), "Hello!\n").unwrap();
let (code, text) = run(dir.path(), &["build", "./sub/../doc.mds", "-o", "-"]);
assert_eq!(code, Some(0), "control: got: {text}");
assert!(!text.contains("not an MDS file"), "control: got: {text}");
}
#[test]
fn watch_vars_path_is_refused_before_it_is_watched() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
std::fs::create_dir(dir.path().join("src")).unwrap();
std::fs::write(dir.path().join("src").join("a.mds"), "A\n").unwrap();
for ch in [ESC, '\t', '\u{202E}'] {
let vars = format!("v{ch}q/x.json");
let shown = format!("\"v{}q/x.json\"", escaped(ch));
for target in ["in.mds", "src"] {
let label = format!("watch {target} --vars v<U+{:04X}>q/x.json", u32::from(ch));
let (code, text) = run(dir.path(), &["watch", target, "--vars", vars.as_str()]);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(
text.contains(&format!(
"path contains forbidden character U+{:04X}",
u32::from(ch)
)),
"{label}: got: {text:?}"
);
assert_refusal(&text, ch, &shown, &label);
assert!(!text.contains(ch), "{label}: raw char; got: {text:?}");
assert!(
!text.contains("failed to watch"),
"{label}: refused before it is watched; got: {text:?}"
);
}
}
}
#[test]
fn output_flags_are_refused_up_front() {
let dir = tempfile::tempdir().unwrap();
for ch in [ESC, '\t', '\n', '\u{202E}'] {
for (sub, flag, what) in [
("build", "-o", "-o/--output"),
("build", "--out-dir", "--out-dir"),
("watch", "-o", "-o/--output"),
("watch", "--out-dir", "--out-dir"),
] {
let value = format!("out{ch}x");
let (code, text) = run(dir.path(), &[sub, "missing.mds", flag, value.as_str()]);
let label = format!("{sub} {flag} U+{:04X}", u32::from(ch));
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(
text.contains(&format!(
"{what} contains forbidden character U+{:04X}",
u32::from(ch)
)),
"{label}: got: {text}"
);
assert_refusal(&text, ch, &format!("out{}x", escaped(ch)), &label);
assert!(
!text.contains("not found"),
"{label}: flag first; got: {text}"
);
}
}
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
0,
"nothing is created"
);
}
#[test]
fn clean_output_locations_are_accepted() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
let (code, text) = run(dir.path(), &["build", "in.mds", "-o", "o.md"]);
assert_eq!(code, Some(0), "got: {text}");
let (code, text) = run(dir.path(), &["build", "in.mds", "--out-dir", "out"]);
assert_eq!(code, Some(0), "got: {text}");
assert!(dir.path().join("o.md").is_file());
assert!(dir.path().join("out").join("in.md").is_file());
}
#[cfg(unix)]
fn paths_under(dir: &Path) -> Vec<std::path::PathBuf> {
fn walk(dir: &Path, depth: usize, out: &mut Vec<std::path::PathBuf>) {
assert!(depth < 8, "fixture trees are shallow");
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if std::fs::symlink_metadata(&path).unwrap().is_dir() {
walk(&path, depth + 1, out);
}
out.push(path);
}
}
let mut out = Vec::new();
walk(dir, 0, &mut out);
out.sort();
out
}
#[cfg(unix)]
#[test]
fn an_output_location_that_is_not_utf8_is_refused_before_anything_is_created() {
use std::os::unix::ffi::OsStrExt as _;
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
std::fs::create_dir(dir.path().join("src")).unwrap();
std::fs::write(dir.path().join("src").join("a.mds"), "A\n").unwrap();
let before = paths_under(dir.path());
let replaced = char::REPLACEMENT_CHARACTER;
for (flag, value, expected) in [
(
"--out-dir",
OsStr::from_bytes(b"o\x80ut"),
format!("--out-dir is not valid UTF-8: \"o{replaced}ut\""),
),
(
"-o",
OsStr::from_bytes(b"o\x80ut.md"),
format!("-o/--output is not valid UTF-8: \"o{replaced}ut.md\""),
),
] {
for (sub, input) in [
("build", "in.mds"),
("build", "src"),
("watch", "in.mds"),
("watch", "src"),
] {
let args = [OsStr::new(sub), OsStr::new(input), OsStr::new(flag), value];
let label = format!("{sub} {input} {flag}");
let (code, text) = run(dir.path(), &args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(text.contains("mds::io"), "{label}: mds::io; got: {text}");
assert!(
squash(&text).contains(&squash(&expected)),
"{label}: expected {expected:?}; got: {text}"
);
assert_eq!(
paths_under(dir.path()),
before,
"{label}: nothing is created"
);
}
}
for (flag, value) in [
("--out-dir", OsStr::from_bytes(b"o\x1b\x80")),
("-o", OsStr::from_bytes(b"o\x1b\x80.md")),
] {
let args = [
OsStr::new("build"),
OsStr::new("in.mds"),
OsStr::new(flag),
value,
];
let label = format!("build in.mds {flag} with U+001B and 0x80");
let (code, text) = run(dir.path(), &args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_refusal(&text, ESC, &format!("o{}{replaced}", escaped(ESC)), &label);
assert_eq!(
paths_under(dir.path()),
before,
"{label}: nothing is created"
);
}
let (code, text) = run(dir.path(), &["build", "in.mds", "-o", "-"]);
assert_eq!(code, Some(0), "control -o -: got: {text}");
assert!(text.contains("Hi"), "control -o -: to stdout; got: {text}");
assert_eq!(
paths_under(dir.path()),
before,
"control -o -: stdout, no file"
);
let clean = "o\u{e9}ut";
let (code, text) = run(dir.path(), &["build", "in.mds", "--out-dir", clean]);
assert_eq!(code, Some(0), "control --out-dir: got: {text}");
assert!(
dir.path().join(clean).join("in.md").is_file(),
"control: a UTF-8 --out-dir is created and written"
);
let clean = "o\u{e9}ut.md";
let (code, text) = run(dir.path(), &["build", "in.mds", "-o", clean]);
assert_eq!(code, Some(0), "control -o: got: {text}");
assert!(
dir.path().join(clean).is_file(),
"control: a UTF-8 -o is written"
);
}
fn write_mds_json(dir: &Path, output_dir: &str) {
let json = serde_json::json!({ "build": { "output_dir": output_dir } });
std::fs::write(dir.join("mds.json"), json.to_string()).unwrap();
}
#[cfg(unix)]
mod resolved_output {
use super::*;
use common::make_symlink;
fn tree() -> (tempfile::TempDir, String) {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
std::fs::create_dir(dir.path().join("src")).unwrap();
std::fs::write(dir.path().join("src").join("a.mds"), "A\n").unwrap();
let hostile = dir.path().join("x\ty");
std::fs::create_dir(&hostile).unwrap();
assert!(make_symlink(&hostile, &dir.path().join("link")));
std::fs::create_dir(dir.path().join("clean")).unwrap();
assert!(make_symlink(
&dir.path().join("clean"),
&dir.path().join("clean_link")
));
let name = dir.path().file_name().unwrap().to_str().unwrap().to_owned();
(dir, name)
}
fn assert_resolved_refusal(text: &str, what: &str, shown: &str, tmp_name: &str, label: &str) {
let expected =
format!("{what} resolved path contains forbidden character U+0009: \"{shown}\"");
assert!(
squash(text).contains(&squash(&expected)),
"{label}: expected {expected:?}; got: {text:?}"
);
assert_no_control_chars(text, label);
assert!(!text.contains('\t'), "{label}: raw TAB; got: {text:?}");
let refusal = &text[text
.find("mds::io")
.unwrap_or_else(|| panic!("{label}: mds::io; got: {text:?}"))..];
assert!(
!refusal.contains(tmp_name),
"{label}: absolute path; got: {text:?}"
);
}
#[test]
fn output_flags_resolving_into_a_hostile_directory_are_refused() {
let (dir, tmp_name) = tree();
for (args, what, shown) in [
(
&["build", "in.mds", "--out-dir", "link"][..],
"--out-dir",
"link",
),
(&["build", "src", "--out-dir", "link"], "--out-dir", "link"),
(
&["build", "in.mds", "--out-dir", "link/new/sub"],
"--out-dir",
"link/new/sub",
),
(
&["build", "in.mds", "-o", "link/x.md"],
"-o/--output",
"link/x.md",
),
(
&["build", "-", "-o", "link/x.md"],
"-o/--output",
"link/x.md",
),
(
&["watch", "in.mds", "--out-dir", "link"],
"--out-dir",
"link",
),
(&["watch", "src", "--out-dir", "link"], "--out-dir", "link"),
(
&["watch", "in.mds", "-o", "link/x.md"],
"-o/--output",
"link/x.md",
),
] {
let label = args.join(" ");
let (code, text) = run(dir.path(), args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_resolved_refusal(&text, what, shown, &tmp_name, &label);
}
assert_eq!(
std::fs::read_dir(dir.path().join("x\ty")).unwrap().count(),
0,
"nothing is written into the hostile directory"
);
for (args, written) in [
(&["build", "in.mds", "--out-dir", "clean_link"][..], "in.md"),
(&["build", "src", "--out-dir", "clean_link"], "a.md"),
(&["build", "in.mds", "-o", "clean_link/x.md"], "x.md"),
] {
let (code, text) = run(dir.path(), args);
assert_eq!(code, Some(0), "{args:?} control: got: {text}");
assert!(dir.path().join("clean").join(written).is_file(), "{args:?}");
}
}
#[test]
fn output_dir_in_mds_json_resolving_into_a_hostile_directory_is_refused() {
let (dir, tmp_name) = tree();
write_mds_json(dir.path(), "link");
for args in [
&["build", "in.mds"][..],
&["build", "src"],
&["lint", "in.mds"],
&["watch", "in.mds"],
] {
let label = args.join(" ");
let (code, text) = run(dir.path(), args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_resolved_refusal(
&text,
"mds.json build.output_dir",
"link",
&tmp_name,
&label,
);
}
assert_eq!(
std::fs::read_dir(dir.path().join("x\ty")).unwrap().count(),
0,
"nothing is written into the hostile directory"
);
write_mds_json(dir.path(), "clean_link");
let (code, text) = run(dir.path(), &["build", "in.mds"]);
assert_eq!(code, Some(2), "got: {text}");
assert!(
text.contains("refusing to follow a symlink") && !text.contains("forbidden character"),
"got: {text}"
);
write_mds_json(dir.path(), "clean");
let (code, text) = run(dir.path(), &["build", "in.mds"]);
assert_eq!(code, Some(0), "got: {text}");
assert!(dir.path().join("clean").join("in.md").is_file());
}
}
#[test]
fn output_dir_in_mds_json_is_refused_at_load() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
let value = format!("out{ESC}[31m");
write_mds_json(dir.path(), &value);
let shown = format!("out{}[31m", escaped(ESC));
for args in [
&["build", "in.mds"][..],
&["build", "."],
&["lint", "in.mds"],
&["lint", "."],
&["fmt", "."],
&["watch", "in.mds"],
] {
let (code, text) = run(dir.path(), args);
let label = args.join(" ");
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(
text.contains("mds.json build.output_dir contains forbidden character U+001B"),
"{label}: got: {text}"
);
assert_refusal(&text, ESC, &shown, &label);
}
let (code, text) = run(dir.path(), &["check", "in.mds"]);
assert_eq!(code, Some(0), "check does not load mds.json; got: {text}");
write_mds_json(dir.path(), "out");
let (code, text) = run(dir.path(), &["build", "in.mds"]);
assert_eq!(code, Some(0), "got: {text}");
assert!(dir.path().join("out").join("in.md").is_file());
}
#[test]
fn output_dir_traversal_is_io_exit_2() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("in.mds"), "Hi\n").unwrap();
write_mds_json(dir.path(), "../escaped");
for args in [&["build", "in.mds"][..], &["build", "."]] {
let (code, text) = run(dir.path(), args);
let label = args.join(" ");
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(text.contains("mds::io"), "{label}: got: {text}");
assert!(
text.contains("mds.json output_dir '../escaped' must not contain '..' components"),
"{label}: got: {text}"
);
}
assert!(!dir.path().parent().unwrap().join("escaped").exists());
}
#[cfg(unix)]
mod config_errors {
use super::*;
fn set_mode(path: &Path, mode: u32) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
}
#[test]
fn config_load_errors_name_the_file_as_reached_from_the_input() {
let tmp = tempfile::tempdir().unwrap();
let tmp_name = tmp.path().file_name().unwrap().to_str().unwrap().to_owned();
let cwd = tmp.path().join("d\te");
let clean = tmp.path().join("clean");
for project in [&cwd, &clean] {
std::fs::create_dir_all(project.join("sub")).unwrap();
std::fs::write(project.join("in.mds"), "Hi\n").unwrap();
std::fs::write(project.join("sub").join("in.mds"), "Hi\n").unwrap();
}
let config = cwd.join("mds.json");
let clean_config = clean.join("mds.json");
let mut cases: Vec<(Vec<u8>, u32, &str, &str)> = vec![
(b"{".to_vec(), 0o644, "invalid mds.json at ", ":"),
(
vec![b' '; 1024 * 1024 + 1],
0o644,
"mds.json at ",
" is too large",
),
(vec![0xFF, 0xFE], 0o644, "invalid UTF-8 in ", ":"),
];
std::fs::write(&clean_config, "{}").unwrap();
std::fs::write(&config, "{}").unwrap();
set_mode(&config, 0o000);
if std::fs::read(&config).is_err() {
cases.push((b"{}".to_vec(), 0o000, "cannot read ", ":"));
}
for (content, mode, before, after) in &cases {
for path in [&config, &clean_config] {
set_mode(path, 0o644);
std::fs::write(path, content).unwrap();
set_mode(path, *mode);
}
for (dir, args, shown, exit) in [
(&cwd, &["build", "in.mds"][..], "./mds.json", 1),
(&cwd, &["build", "sub/in.mds"], "sub/../mds.json", 1),
(&cwd, &["lint", "in.mds"], "./mds.json", 2),
(&clean, &["fmt", "."], "./mds.json", 1),
(&clean, &["watch", "-q", "in.mds"], "./mds.json", 1),
(&clean, &["watch", "-q", "sub/in.mds"], "sub/../mds.json", 1),
(&clean, &["watch", "-q", "."], "./mds.json", 1),
(&clean, &["watch", "-q", "sub"], "sub/../mds.json", 1),
] {
let label = format!("{} [{before}]", args.join(" "));
let (code, text) = run(dir, args);
assert_eq!(code, Some(exit), "{label}: got: {text:?}");
let expected = format!("{before}{shown}{after}");
assert!(
squash(&text).contains(&squash(&expected)),
"{label}: expected {expected:?}; got: {text:?}"
);
assert_no_control_chars(&text, &label);
assert!(!text.contains('\t'), "{label}: raw TAB; got: {text:?}");
assert!(
!text.contains(&tmp_name),
"{label}: absolute path; got: {text:?}"
);
}
}
set_mode(&config, 0o644);
set_mode(&clean_config, 0o644);
let (code, text) = run(&cwd, &["fmt", "."]);
assert_eq!(code, Some(2), "fmt .: got: {text:?}");
assert!(
squash(&text).contains(&squash(
"resolved path contains forbidden character U+0009: \".\""
)),
"fmt .: got: {text:?}"
);
assert!(!text.contains("mds.json"), "fmt .: got: {text:?}");
assert_no_control_chars(&text, "fmt .");
assert!(
!text.contains(&tmp_name),
"fmt .: absolute path; got: {text:?}"
);
}
}
#[test]
fn init_filename_is_refused_up_front() {
let dir = tempfile::tempdir().unwrap();
for ch in [ESC, '\t', '\n', '\u{202E}'] {
let value = format!("out{ch}x");
let (code, text) = run(dir.path(), &["init", value.as_str()]);
let label = format!("init U+{:04X}", u32::from(ch));
assert_eq!(code, Some(2), "{label}: got: {text}");
assert!(
text.contains(&format!(
"init filename contains forbidden character U+{:04X}",
u32::from(ch)
)),
"{label}: got: {text}"
);
assert_refusal(&text, ch, &format!("out{}x", escaped(ch)), &label);
}
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
0,
"nothing is created"
);
}
#[test]
fn init_clean_filename_is_accepted() {
let dir = tempfile::tempdir().unwrap();
let (code, text) = run(dir.path(), &["init", "hello.mds"]);
assert_eq!(code, Some(0), "got: {text}");
assert!(dir.path().join("hello.mds").is_file());
}
fn walk_commands<'a>(target: &'a str, out: &'a str) -> [Vec<&'a str>; 5] {
[
vec!["build", target, "--out-dir", out],
vec!["check", target],
vec!["lint", target],
vec!["fmt", "--check", target],
vec!["watch", target, "--out-dir", out],
]
}
fn assert_io_refusal(text: &str, message: &str, label: &str) {
assert!(text.contains("mds::io"), "{label}: mds::io; got: {text}");
assert!(
squash(text).contains(&squash(message)),
"{label}: expected {message:?}; got: {text}"
);
assert_no_control_chars(text, label);
}
fn assert_lint_json_refusal(dir: &Path, target: &str, message: &str) {
let label = format!("lint --format json {target}");
let (code, text) = run(dir, &["lint", "--format", "json", target]);
assert_eq!(code, Some(2), "{label}: got: {text}");
let json: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|e| panic!("{label}: stdout must be JSON ({e}); got: {text}"));
assert_eq!(json["error"]["code"], "mds::io", "{label}: got: {text}");
assert_eq!(json["error"]["message"], message, "{label}: got: {text}");
}
#[cfg(unix)]
#[test]
fn directory_argument_filesystem_root_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("out");
let out_str = out.to_str().unwrap();
for (cwd, typed) in [
(tmp.path(), "/"),
(tmp.path(), "/.."),
(Path::new("/"), "."),
] {
let message = format!("directory argument must not be the filesystem root: \"{typed}\"");
for args in walk_commands(typed, out_str) {
let label = format!("(in {}) {}", cwd.display(), args.join(" "));
let (code, text) = run(cwd, &args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_io_refusal(&text, &message, &label);
}
assert_lint_json_refusal(cwd, typed, &message);
}
assert!(!out.exists(), "nothing is written");
let file = tmp.path().join("in.mds");
std::fs::write(&file, "Hi\n").unwrap();
for args in [&["check", "-"][..], &["check", file.to_str().unwrap()]] {
let (code, text) = run(Path::new("/"), args);
assert_eq!(code, Some(0), "control (in /) {args:?}: got: {text}");
}
let (code, text) = run(
Path::new("/"),
&["build", file.to_str().unwrap(), "-o", "-"],
);
assert_eq!(code, Some(0), "control (in /) build: got: {text}");
assert!(text.contains("Hi"), "control (in /) build: got: {text}");
}
#[cfg(windows)]
#[test]
fn directory_argument_drive_root_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let drive = tmp.path().ancestors().last().unwrap().to_path_buf();
let plain = drive.display().to_string();
let verbatim = format!(r"\\?\{plain}");
let out = tmp.path().join("out");
let out_str = out.to_str().unwrap();
for (cwd, typed) in [
(tmp.path(), plain.as_str()),
(tmp.path(), verbatim.as_str()),
(drive.as_path(), "."),
] {
let message = format!("directory argument must not be the filesystem root: \"{typed}\"");
for args in walk_commands(typed, out_str) {
let label = format!("(in {}) {}", cwd.display(), args.join(" "));
let (code, text) = run(cwd, &args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_io_refusal(&text, &message, &label);
}
assert_lint_json_refusal(cwd, typed, &message);
}
assert!(!out.exists(), "nothing is written");
let file = tmp.path().join("in.mds");
std::fs::write(&file, "Hi\n").unwrap();
for args in [&["check", "-"][..], &["check", file.to_str().unwrap()]] {
let (code, text) = run(&drive, args);
assert_eq!(code, Some(0), "control (in {plain}) {args:?}: got: {text}");
}
let (code, text) = run(&drive, &["build", file.to_str().unwrap(), "-o", "-"]);
assert_eq!(code, Some(0), "control (in {plain}) build: got: {text}");
assert!(
text.contains("Hi"),
"control (in {plain}) build: got: {text}"
);
}
#[test]
fn directory_argument_symlink_is_refused_everywhere() {
use common::{make_symlink, spawn_watch_ready, ChildGuard};
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("real")).unwrap();
std::fs::write(dir.path().join("real").join("a.mds"), "Hello!\n").unwrap();
if !make_symlink(&dir.path().join("real"), &dir.path().join("link")) {
return;
}
for typed in ["link", "link/", "link/."] {
let message = format!("directory argument must not be a symlink: \"{typed}\"");
for args in walk_commands(typed, "out") {
let label = args.join(" ");
let (code, text) = run(dir.path(), &args);
assert_eq!(code, Some(2), "{label}: got: {text}");
assert_io_refusal(&text, &message, &label);
}
assert_lint_json_refusal(dir.path(), typed, &message);
}
assert!(!dir.path().join("out").exists(), "nothing is written");
for args in [
&["build", "link/..", "--out-dir", "out"][..],
&["check", "link/.."],
&["lint", "link/.."],
&["fmt", "--check", "link/.."],
] {
let (code, text) = run(dir.path(), args);
assert_eq!(code, Some(0), "{args:?}: link/.. is accepted; got: {text}");
}
assert_eq!(
std::fs::read_to_string(dir.path().join("out").join("real").join("a.md")).unwrap(),
"Hello!\n"
);
let (child, tap, _) = spawn_watch_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "link/..", "--out-dir", "wout", "--debounce", "0"])
.stdout(Stdio::null()),
);
let mut child = ChildGuard(child);
let written = dir.path().join("wout").join("real").join("a.md");
let deadline = Instant::now() + Duration::from_secs(2);
while !written.is_file() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
assert!(
written.is_file(),
"watch link/.. walks the directory above the link's target; stderr: {}",
tap.finish_text(&mut child)
);
}
#[test]
fn build_refuses_a_directory_link_before_it_loads_the_config() {
use std::path::MAIN_SEPARATOR_STR;
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real");
std::fs::create_dir(&real).unwrap();
std::fs::write(real.join("mds.json"), "!").unwrap();
let (code, text) = run(dir.path(), &["build", "real", "--out-dir", "out"]);
assert_eq!(code, Some(1), "real directory: {text}");
let expected = format!(
"invalid mds.json at real{MAIN_SEPARATOR_STR}mds.json: expected value at line 1 column 1"
);
assert!(squash(&text).contains(&squash(&expected)), "{text}");
if !common::make_symlink(&real, &dir.path().join("link")) {
return;
}
let (code, text) = run(dir.path(), &["build", "link", "--out-dir", "out"]);
assert_eq!(code, Some(2), "directory link: {text}");
assert_io_refusal(
&text,
"directory argument must not be a symlink: \"link\"",
"build link",
);
assert!(!text.contains("invalid mds.json"), "{text}");
assert!(!dir.path().join("out").exists());
}
#[cfg(unix)]
#[test]
fn directory_argument_forbidden_characters_are_refused_naming_the_typed_form() {
use common::make_symlink;
let dir = tempfile::tempdir().unwrap();
let tmp_name = dir.path().file_name().unwrap().to_str().unwrap().to_owned();
let hostile = format!("d{ESC}e");
std::fs::create_dir(dir.path().join(&hostile)).unwrap();
std::fs::write(dir.path().join(&hostile).join("a.mds"), "A\n").unwrap();
std::fs::create_dir_all(dir.path().join("x\ty").join("sub")).unwrap();
std::fs::write(dir.path().join("x\ty").join("sub").join("b.mds"), "B\n").unwrap();
assert!(make_symlink(
&dir.path().join("x\ty"),
&dir.path().join("clink")
));
let hostile_slash = format!("{hostile}/");
for (typed, what, ch, shown) in [
(hostile.as_str(), "path", ESC, format!("d{}e", escaped(ESC))),
(
hostile_slash.as_str(),
"path",
ESC,
format!("d{}e/", escaped(ESC)),
),
("clink/sub", "resolved path", '\t', "clink/sub".to_owned()),
(
"clink/sub/..",
"resolved path",
'\t',
"clink/sub/..".to_owned(),
),
] {
let message = format!(
"{what} contains forbidden character U+{:04X}: \"{shown}\"",
u32::from(ch)
);
for args in walk_commands(typed, "out") {
let label = format!("{} [{shown}]", args[0]);
let (code, text) = run(dir.path(), &args);
assert_eq!(code, Some(2), "{label}: got: {text:?}");
assert_refusal(&text, ch, &shown, &label);
assert!(
squash(&text).contains(&squash(&message)),
"{label}: expected {message:?}; got: {text:?}"
);
assert_eq!(
text.contains("resolved path"),
what == "resolved path",
"{label}: the typed form is refused before it is resolved; got: {text:?}"
);
assert!(!text.contains(ch), "{label}: raw char; got: {text:?}");
assert!(
!text.contains(&tmp_name),
"{label}: absolute path; got: {text:?}"
);
assert!(
!text.contains("built") && !text.contains("passed") && !text.contains("clean"),
"{label}: refused before the walk, so no summary; got: {text:?}"
);
}
}
assert!(!dir.path().join("out").exists(), "nothing is written");
}