//! Importers: values taken from elsewhere instead of written out, so a configuration //! can say where a value comes from without holding it (secrets, host facts): as //! continuum's does (its `docs/configuration.md`, Importing values). //! //! * `env:NAME`: an environment variable; //! * `file:PATH`: a file's contents; //! * `cmd:COMMAND`: the standard output of a shell command (`sh -c`). //! //! The content is text (trailing line breaks removed), converted like a value written //! on the command line; with `+json` (`env+json:NAME`, …) it is parsed as JSON instead; //! with `+raw` (`file+raw:PATH`, …) it is the bytes as they are, nothing removed, text or //! not: a key, a certificate. //! //! On the command line, a value with one of these prefixes is imported; `literal:` //! passes the rest as is. In configuration files, an importer is a table: //! `{ env = "NAME" }`, `{ file = "PATH" }`, `{ command = "COMMAND" }` (or an argument //! list, run without a shell), each with an optional `format = "json"` or `"raw"`. //! //! Any other text value may hold placeholders, `${env:NAME}`, `${file:PATH}` or //! `${cmd:COMMAND}`, each replaced by its content as text (`$$` is a `$`; a placeholder //! ends at the `}` matching its `{`), e.g. `node-${env:HOSTNAME}`. Relative paths are //! relative to the file, and commands run in its directory, in placeholders too. //! //! Placeholders nest: a name, a path, a command and each argument of an argument list //! may hold placeholders of their own, `${cmd:secrets ${env:HOST} show x}`. There, only //! `${env:`, `${file:` and `${cmd:` begin one, `$${` is a `${`, and every other `$` stays //! as it is: a command's are its shell's. What a placeholder gives goes in as data, never //! as code: into a name, a path and an argument as it is, an argument staying one //! argument; into a shell command as a positional parameter (`shell`), so the shell never //! reads it as part of its script. In a `+raw` importer a placeholder may be `+raw` too //! (`cmd+raw:sign ${file+raw:key}`), its bytes going in as they are; into text, none is. use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; use std::path::{Path, PathBuf}; use std::process::Command; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map as JsonMap, Value as JsonValue}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Format { /// Text, its trailing line breaks removed. Text, /// Text read as JSON. Json, /// The bytes as they are. Raw, } impl Format { /// What it adds to a prefix: `+json` in `env+json:NAME`. fn suffix(self) -> &'static str { match self { Format::Text => "", Format::Json => "+json", Format::Raw => "+raw", } } } /// Where a value comes from. All but a template may hold placeholders of their own. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Source { Env(String), File(PathBuf), /// A command for `sh -c`. Shell(String), /// A program and its arguments, run without a shell. Argv(Vec), /// Text with placeholders (`interpolated`). Template(String), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Importer { pub source: Source, pub format: Format, /// Where relative paths are relative to, and commands run: the directory of the file /// the importer is from; none for one from the command line. pub dir: Option, } /// What a command-line value is: imported, or literal. #[derive(Debug, PartialEq, Eq)] pub enum Raw<'a> { Import(Importer), Literal(&'a str), } /// Reads a command-line value. pub fn parse_argument(raw: &str) -> Raw<'_> { if let Some(rest) = raw.strip_prefix("literal:") { return Raw::Literal(rest); } let Some((prefix, rest)) = raw.split_once(':') else { return literal_or_interpolated(raw); }; let (kind, format) = match prefix.split_once('+') { None => (prefix, Format::Text), Some((kind, "json")) => (kind, Format::Json), Some((kind, "raw")) => (kind, Format::Raw), Some(_) => return literal_or_interpolated(raw), }; let source = match kind { "env" => Source::Env(rest.to_owned()), "file" => Source::File(PathBuf::from(rest)), "cmd" => Source::Shell(rest.to_owned()), _ => return literal_or_interpolated(raw), }; Raw::Import(Importer { source, format, dir: None, }) } fn literal_or_interpolated(raw: &str) -> Raw<'_> { match interpolated(raw, None) { Some(importer) => Raw::Import(importer), None => Raw::Literal(raw), } } /// `text` as an importer if it holds a `$` (a placeholder, `$$`, or a mistake that /// expanding it reports), read in `dir`; None if it is plain text. pub fn interpolated(text: &str, dir: Option<&Path>) -> Option { text.contains('$').then(|| Importer { source: Source::Template(text.to_owned()), format: Format::Text, dir: dir.map(Path::to_owned), }) } /// Reads an importer table from a file in `dir`; None if `object` isn't one. pub fn parse_table(object: &JsonMap, dir: &Path) -> Result> { let sources = ["env", "file", "command"] .into_iter() .filter(|key| object.contains_key(*key)) .count(); if sources == 0 { return Ok(None); } if sources > 1 { bail!("an importer takes exactly one of env, file and command"); } if let Some(unknown) = object .keys() .find(|key| !["env", "file", "command", "format"].contains(&key.as_str())) { bail!("unknown importer key {unknown:?}"); } let format = match object.get("format") { None => Format::Text, Some(JsonValue::String(format)) if format == "text" => Format::Text, Some(JsonValue::String(format)) if format == "json" => Format::Json, Some(JsonValue::String(format)) if format == "raw" => Format::Raw, Some(other) => { bail!("importer format must be \"text\", \"json\" or \"raw\", not {other}") } }; let text = |key: &str| -> Result { match object.get(key) { Some(JsonValue::String(value)) => Ok(value.clone()), _ => Err(anyhow!("importer {key} must be a string")), } }; let source = if object.contains_key("env") { Source::Env(text("env")?) } else if object.contains_key("file") { Source::File(PathBuf::from(text("file")?)) } else { match &object["command"] { JsonValue::String(command) => Source::Shell(command.clone()), JsonValue::Array(items) => { let argv = items .iter() .map(|item| item.as_str().map(str::to_owned)) .collect::>>() .filter(|argv| !argv.is_empty()) .ok_or_else(|| { anyhow!("importer command must be a string or a non-empty list of strings") })?; Source::Argv(argv) } _ => bail!("importer command must be a string or a non-empty list of strings"), } }; Ok(Some(Importer { source, format, dir: Some(dir.to_owned()), })) } impl Importer { /// Shown instead of the value (which may be secret), e.g. `env:HOSTNAME`: as /// written, its placeholders not replaced. pub fn describe(&self) -> String { let format = self.format.suffix(); match &self.source { Source::Env(name) => format!("env{format}:{name}"), Source::File(path) => format!("file{format}:{}", self.in_dir(path).display()), Source::Shell(command) => format!("cmd{format}:{command}"), Source::Argv(argv) => format!("cmd{format}:{}", argv.join(" ")), Source::Template(template) => template.clone(), } } /// Whether this is text with placeholders (`interpolated`) rather than an importer /// of the whole value: its result is shown, the importers' are not. pub fn is_interpolation(&self) -> bool { matches!(self.source, Source::Template(_)) } /// `path`, relative to the importer's directory where it has one. fn in_dir(&self, path: &Path) -> PathBuf { match &self.dir { Some(dir) => dir.join(path), None => path.to_owned(), } } /// The imported content: text, JSON, or bytes. pub fn fetch(&self) -> Result { let dir = self.dir.as_deref(); // Its placeholders may give bytes where it does. let raw = self.format == Format::Raw; let bytes = match &self.source { Source::Env(name) => { let name = filled(name, dir, raw)?; std::env::var_os(&name) .ok_or_else(|| { anyhow!("environment variable {} is not set", name.to_string_lossy()) })? .into_encoded_bytes() } Source::File(path) => { let path = match path.to_str() { Some(text) => self.in_dir(Path::new(&filled(text, dir, raw)?)), None => self.in_dir(path), }; std::fs::read(&path).with_context(|| format!("reading {}", path.display()))? } Source::Shell(command) => { let (script, values) = shell(command, dir, raw)?; let mut process = Command::new("sh"); process.arg("-c").arg(script); if !values.is_empty() { // `$0`, then the values as `$1`, `$2`, … process.arg("sh").args(values); } run(process, dir, command)? } Source::Argv(argv) => { let argv = argv .iter() .map(|argument| filled(argument, dir, raw)) .collect::>>()?; let mut process = Command::new(&argv[0]); process.args(&argv[1..]); run(process, dir, &self.describe())? } Source::Template(template) => expand(template, dir)?.into_bytes(), }; if self.format == Format::Raw { return Ok(Imported::Raw(bytes)); } let text = String::from_utf8(bytes).map_err(|_| { anyhow!( "{} is not UTF-8: text is, and `+raw` takes bytes as they are", self.describe() ) })?; let text = text.trim_end_matches(['\n', '\r']); Ok(match self.format { Format::Json => Imported::Json( serde_json::from_str(text) .with_context(|| format!("{} is not valid JSON", self.describe()))?, ), Format::Text | Format::Raw => Imported::Text(text.to_owned()), }) } } #[derive(Debug, Clone, PartialEq)] pub enum Imported { /// Text, its trailing line breaks removed. Text(String), Json(JsonValue), /// The bytes as they are (`+raw`): nothing removed, text or not. Raw(Vec), } /// Where the placeholder that `text` starts (after its `${`) ends: at the `}` that /// matches its `{`. Braces inside balance, so a command may hold `{...}` (a jq object, a /// shell group) and a placeholder others; in a command (`cmd:`), braces in shell quotes /// (`'...'`, `"..."`) or escaped with a backslash don't count either. fn placeholder_end(text: &str) -> Option { let shell = text.starts_with("cmd:") || text.starts_with("cmd+"); let mut depth = 0usize; let mut quote: Option = None; let mut escaped = false; for (at, char) in text.char_indices() { if shell { if escaped { escaped = false; continue; } match (quote, char) { // Nothing escapes in single quotes. (Some('\''), '\'') => quote = None, (Some('\''), _) => {} (_, '\\') => escaped = true, (Some('"'), '"') => quote = None, (Some('"'), _) => {} (None, '\'' | '"') => quote = Some(char), _ => {} } if quote.is_some() || char == '\'' || char == '"' || char == '\\' { continue; } } match char { '{' => depth += 1, '}' if depth == 0 => return Some(at), '}' => depth -= 1, _ => {} } } None } /// What the placeholder `placeholder` (between its `${` and `}`) gives, read in `dir`: an /// `env:`, a `file:` or a `cmd:`, as text; or, where what it goes into takes bytes (`raw`: /// a `+raw` importer), with `+raw` as bytes. Never `+json`. fn value(placeholder: &str, within: &str, dir: Option<&Path>, raw: bool) -> Result> { let mut importer = match parse_argument(placeholder) { Raw::Import(importer) if !importer.is_interpolation() => importer, _ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file: or cmd:"), }; match importer.format { Format::Text => {} Format::Json => { bail!("placeholder {placeholder:?} must be text (+json isn't for placeholders)") } Format::Raw if raw => {} Format::Raw => bail!( "placeholder {placeholder:?} in {within:?} gives bytes as they are, and goes into \ text: a +raw placeholder is for a +raw importer" ), } importer.dir = dir.map(Path::to_owned); match importer.fetch()? { Imported::Text(text) => Ok(text.into_bytes()), Imported::Raw(bytes) => Ok(bytes), Imported::Json(_) => unreachable!("no +json importer"), } } /// Text with its placeholders replaced by their content. fn expand(template: &str, dir: Option<&Path>) -> Result { let mut out = String::new(); let mut rest = template; while let Some(at) = rest.find('$') { out.push_str(&rest[..at]); let after = &rest[at + 1..]; if let Some(after) = after.strip_prefix('$') { out.push('$'); rest = after; } else if let Some(after) = after.strip_prefix('{') { let end = placeholder_end(after) .ok_or_else(|| anyhow!("unterminated placeholder in template {template:?}"))?; let text = value(&after[..end], template, dir, false)?; out.push_str(&String::from_utf8(text).expect("a text importer gives text")); rest = &after[end + 1..]; } else { // Most likely a shell-style `$NAME` that would silently stay as it is. bail!( "a `$` in {template:?} that starts no placeholder: write `$$` for a `$`, or \ e.g. `${{env:NAME}}` for a variable" ); } } out.push_str(rest); Ok(out) } /// A part of what an importer names: text as it is, or a placeholder (between its `${` /// and `}`). #[derive(Debug, PartialEq, Eq)] enum Part<'a> { Text(String), Placeholder(&'a str), } /// What begins a placeholder inside an importer, after its `${`: nothing else there is /// one, as a command's `$` are its shell's. const NESTED: [&str; 6] = ["env:", "file:", "cmd:", "env+raw:", "file+raw:", "cmd+raw:"]; /// The parts of what an importer names (a name, a path, a command, an argument): only /// `${env:`, `${file:` and `${cmd:` begin a placeholder, `$${` is a `${`, and every other /// `$` stays as it is. fn parts(text: &str) -> Result>> { let mut parts = Vec::new(); let mut plain = String::new(); let mut rest = text; while let Some(at) = rest.find('$') { plain.push_str(&rest[..at]); let from = &rest[at..]; if from.starts_with("$${") { plain.push('$'); rest = &from[2..]; } else if let Some(after) = from .strip_prefix("${") .filter(|after| NESTED.iter().any(|prefix| after.starts_with(prefix))) { let end = placeholder_end(after) .ok_or_else(|| anyhow!("unterminated placeholder in {text:?}"))?; if !plain.is_empty() { parts.push(Part::Text(std::mem::take(&mut plain))); } parts.push(Part::Placeholder(&after[..end])); rest = &after[end + 1..]; } else { plain.push('$'); rest = &from[1..]; } } plain.push_str(rest); if !plain.is_empty() { parts.push(Part::Text(plain)); } Ok(parts) } /// What an importer names, its placeholders replaced by their content, as it is: a /// name, a path, or one argument, which stays one whatever a placeholder gives. fn filled(text: &str, dir: Option<&Path>, raw: bool) -> Result { let mut out = Vec::new(); for part in parts(text)? { match part { Part::Text(plain) => out.extend(plain.into_bytes()), Part::Placeholder(placeholder) => out.extend(value(placeholder, text, dir, raw)?), } } Ok(OsString::from_vec(out)) } /// A shell command with placeholders as a script for `sh -c` and the values to give it /// as positional parameters: each placeholder becomes a reference to its parameter, /// `"${1}"`, or `${1}` inside double quotes, so that what it gives is one word of the /// command as it is, and the shell reads none of it as script, whatever it holds. Where /// a reference can't be written so, the command is refused (`Shell::reference`). fn shell(command: &str, dir: Option<&Path>, raw: bool) -> Result<(String, Vec)> { let mut script = String::new(); let mut values = Vec::new(); let mut at = Shell::default(); for part in parts(command)? { match part { Part::Text(plain) => { plain.chars().for_each(|char| at.read(char)); script.push_str(&plain); } Part::Placeholder(placeholder) => { let reference = at.reference(values.len() + 1).map_err(|why| { anyhow!("placeholder {placeholder:?} in the command {command:?} is {why}") })?; values.push(OsString::from_vec(value(placeholder, command, dir, raw)?)); script.push_str(&reference); } } } Ok((script, values)) } /// What of a shell script a place is inside of, innermost last. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Inside { /// `'…'` Single, /// `"…"` Double, /// `` `…` `` Backquotes, /// `$(…)`: a script of its own. Substitution, /// `(…)` Group, /// `$((…))`, and how many `(` are open in it. Arithmetic(usize), /// `${…}`, the shell's. Parameter, } /// Where in a shell script a place is, as far as it matters for writing a reference to /// a positional parameter there: read character by character (`read`). Not a shell's /// parser: it tells quotes, substitutions, comments and here-documents, and where it /// can't tell how a reference is written, none is (`reference`). What it gets wrong can /// make a reference refused, or split into words by the shell; never read as script, /// as a value is no part of the script. #[derive(Debug, Default)] struct Shell { inside: Vec, /// After a backslash. escaped: bool, /// After a `$` (1), after `$(` (2). dollar: u8, /// After the `)` that ends an arithmetic expansion but for its second `)`. closing: bool, /// Where a word begins: a `#` there begins a comment. word: bool, comment: bool, /// After a `<`; and after `<<`, a here-document, whose text follows somewhere. less: bool, here: bool, started: bool, } impl Shell { fn read(&mut self, char: char) { let first = !std::mem::replace(&mut self.started, true); if self.comment { self.comment = char != '\n'; self.word = true; return; } if std::mem::take(&mut self.closing) && char == ')' { return; } let top = self.inside.last().copied(); if top == Some(Inside::Single) { if char == '\'' { self.inside.pop(); } return; } if std::mem::take(&mut self.escaped) { self.dollar = 0; self.word = false; return; } let dollar = std::mem::take(&mut self.dollar); if top != Some(Inside::Backquotes) { match (dollar, char) { (1, '(') => { self.inside.push(Inside::Substitution); self.dollar = 2; self.word = true; return; } (2, '(') => { self.inside.pop(); self.inside.push(Inside::Arithmetic(0)); return; } (1, '{') => { self.inside.push(Inside::Parameter); return; } _ => {} } } let unquoted = matches!(top, None | Some(Inside::Substitution) | Some(Inside::Group)); let word = std::mem::replace(&mut self.word, false) || first; let less = std::mem::replace(&mut self.less, false); match (top, char) { (Some(Inside::Backquotes), '`') => { self.inside.pop(); } (Some(Inside::Backquotes), '\\') => self.escaped = true, (Some(Inside::Backquotes), _) => {} (Some(Inside::Arithmetic(open)), '(') => { self.inside.pop(); self.inside.push(Inside::Arithmetic(open + 1)); } (Some(Inside::Arithmetic(0)), ')') => { self.inside.pop(); self.closing = true; } (Some(Inside::Arithmetic(open)), ')') => { self.inside.pop(); self.inside.push(Inside::Arithmetic(open - 1)); } (Some(Inside::Arithmetic(_)), '$') => self.dollar = 1, (Some(Inside::Arithmetic(_)), _) => {} (_, '\\') => self.escaped = true, (_, '$') => self.dollar = 1, (_, '`') => self.inside.push(Inside::Backquotes), (Some(Inside::Double), '"') => { self.inside.pop(); } (Some(Inside::Double), _) => {} (_, '"') => self.inside.push(Inside::Double), (_, '\'') => self.inside.push(Inside::Single), (Some(Inside::Parameter), '}') => { self.inside.pop(); } (Some(Inside::Parameter), _) => {} (_, '(') => { self.inside.push(Inside::Group); self.word = true; } (Some(Inside::Substitution | Inside::Group), ')') => { self.inside.pop(); } (_, '#') if word => self.comment = true, (_, '<') => { self.here |= less; self.less = true; } _ => {} } if unquoted && (char.is_whitespace() || matches!(char, ';' | '&' | '|')) { self.word = true; } } /// A reference to the positional parameter `number` as it is written here, so that /// the shell takes it as one word, as it is; or why none is written here. fn reference(&mut self, number: usize) -> Result { if self.comment { return Ok(format!("\"${{{number}}}\"")); } if self.escaped { return Err("after a backslash"); } if self.dollar != 0 && self.inside.last() != Some(&Inside::Substitution) { return Err("after a `$`"); } if self.here { return Err( "after a here-document (`<<`), where it can't tell the document's text from \ the script", ); } self.dollar = 0; self.closing = false; self.less = false; self.started = true; let reference = match self.inside.last() { None | Some(Inside::Substitution | Inside::Group) => format!("\"${{{number}}}\""), Some(Inside::Double) => format!("${{{number}}}"), Some(Inside::Single) => { return Err( "inside single quotes, where the shell replaces nothing: end them before \ it, or use double quotes", ); } Some(Inside::Backquotes) => return Err("inside backquotes: write `$(…)` instead"), Some(Inside::Arithmetic(_)) => { return Err( "inside `$((…))`, where the shell would read what it gives as an \ expression", ); } Some(Inside::Parameter) => { return Err("inside a `${…}` of the shell's: assign it to a variable first"); } }; self.word = false; Ok(reference) } } fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result> { if let Some(dir) = dir { process.current_dir(dir); } let output = process .output() .with_context(|| format!("running {shown}"))?; if !output.status.success() { bail!( "{shown} failed ({}): {}", output.status, String::from_utf8_lossy(&output.stderr).trim() ); } Ok(output.stdout) } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn import(source: Source, format: Format) -> Importer { Importer { source, format, dir: None, } } #[test] fn command_line_values() { assert_eq!(parse_argument("plain"), Raw::Literal("plain")); assert_eq!( parse_argument("tls://host:9651"), Raw::Literal("tls://host:9651") ); assert_eq!(parse_argument("literal:env:X"), Raw::Literal("env:X")); assert_eq!( parse_argument("env+json:SEEDS"), Raw::Import(import(Source::Env("SEEDS".into()), Format::Json)) ); assert_eq!( parse_argument("cmd:hostname -f"), Raw::Import(import(Source::Shell("hostname -f".into()), Format::Text)) ); assert_eq!(parse_argument("env+yaml:X"), Raw::Literal("env+yaml:X")); // A `$` makes it interpolated; expanding it then says what's wrong. assert!(matches!(parse_argument("a $5 price"), Raw::Import(_))); assert_eq!(parse_argument("literal:a $5"), Raw::Literal("a $5")); assert_eq!( parse_argument("node-${env:HOST}"), Raw::Import(import( Source::Template("node-${env:HOST}".into()), Format::Text )) ); // A placeholder in a value that looks like a prefix is interpolated too. assert!(matches!( parse_argument("tls://${env:HOST}:9651"), Raw::Import(_) )); assert_eq!( parse_argument("literal:${env:HOST}"), Raw::Literal("${env:HOST}") ); } #[test] fn templates() { let expanded = |template: &str| expand(template, None); assert_eq!(expanded("a-${cmd:echo b}-c $$5").unwrap(), "a-b-c $5"); assert!(expanded("$HOME/x").is_err()); assert!(expanded("a $5 price").is_err()); assert_eq!( expanded("${cmd:printf one}${cmd:printf two}").unwrap(), "onetwo" ); assert!(expanded("${cmd:echo b").is_err()); assert!(expanded("${plain}").is_err()); assert!(expanded("${env+json:X}").is_err()); assert!(expanded("${${cmd:echo env}:X}").is_err()); } #[test] fn placeholders_end_at_their_matching_brace() { fn end(text: &str) -> Option<&str> { placeholder_end(text).map(|at| &text[..at]) } assert_eq!(end("env:HOST}-x"), Some("env:HOST")); // Balanced braces, as a jq object has them. assert_eq!(end("cmd:jq -r '{a: .b}'}/tcp"), Some("cmd:jq -r '{a: .b}'")); assert_eq!(end("cmd:sh -c { true; }}"), Some("cmd:sh -c { true; }")); // In a command, braces in quotes or escaped don't count. assert_eq!(end("cmd:printf '}'}x"), Some("cmd:printf '}'")); assert_eq!(end(r#"cmd:printf "}\""}x"#), Some(r#"cmd:printf "}\"""#)); assert_eq!(end(r"cmd:printf \}}x"), Some(r"cmd:printf \}")); assert_eq!(end("cmd:printf '}"), None); assert_eq!(end("env:X"), None); // The kind of command this is for: quotes of both kinds, and `$` inside. let command = r#"cmd:ip -j addr show wireguard | jq -r '.[].addr_info[]|select(.family=="inet6" and .scope=="global").local'"#; assert_eq!(end(&format!("{command}}}/tcp/9661")), Some(command)); // A placeholder inside. assert_eq!( end("cmd:secrets ${env:HOST} show x}-y"), Some("cmd:secrets ${env:HOST} show x") ); } #[test] fn commands_with_braces_and_quotes() { let expanded = |template: &str| expand(template, None); assert_eq!( expanded(r#"/ip6/${cmd:printf '%s' "$(echo '::1')" | tr -d '{}'}/tcp/9661"#).unwrap(), "/ip6/::1/tcp/9661" ); assert_eq!(expanded("x${cmd:printf '{%s}' a}y").unwrap(), "x{a}y"); } #[test] fn tables() { let dir = Path::new("/etc/continuum"); let table = |value: JsonValue| parse_table(value.as_object().unwrap(), dir); assert_eq!(table(json!({ "x": 1 })).unwrap(), None); let file = table(json!({ "file": "key", "format": "json" })) .unwrap() .unwrap(); assert_eq!( file, Importer { source: Source::File("key".into()), format: Format::Json, dir: Some(dir.to_owned()), } ); assert_eq!(file.describe(), "file+json:/etc/continuum/key"); assert!(table(json!({ "env": "A", "file": "b" })).is_err()); assert!(table(json!({ "env": "A", "extra": 1 })).is_err()); assert!(table(json!({ "command": [] })).is_err()); } #[test] fn fetching() { let echo = import( Source::Argv(vec!["printf".into(), "[1, 2]\\n\\n".into()]), Format::Json, ); assert_eq!(echo.fetch().unwrap(), Imported::Json(json!([1, 2]))); let shell = import(Source::Shell("echo hello".into()), Format::Text); assert_eq!(shell.fetch().unwrap(), Imported::Text("hello".into())); let failing = import(Source::Shell("exit 3".into()), Format::Text); assert!(failing.fetch().is_err()); } /// A directory of a test's files, removed with it. struct Scratch(PathBuf); impl Scratch { fn new(name: &str) -> Scratch { let dir = std::env::temp_dir().join(format!("config-import-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Scratch(dir) } /// A file holding `content`: its name. fn file(&self, name: &str, content: &str) -> String { std::fs::write(self.0.join(name), content).unwrap(); name.to_owned() } /// What a command-line value gives, read in this directory. fn fetch(&self, raw: &str) -> Result { let Raw::Import(mut importer) = parse_argument(raw) else { bail!("{raw:?} imports nothing"); }; importer.dir = Some(self.0.clone()); match importer.fetch()? { Imported::Text(text) => Ok(text), Imported::Json(value) => Ok(value.to_string()), Imported::Raw(bytes) => Ok(String::from_utf8_lossy(&bytes).into_owned()), } } } /// With `+raw`, what is imported is the bytes as they are: line breaks at its end /// kept, and what is no text taken; without, text, and what is none refused. #[test] fn raw_is_the_bytes_as_they_are() { let scratch = Scratch::new("raw"); let key = b"-----BEGIN KEY-----\nAAAA\n-----END KEY-----\n\n"; std::fs::write(scratch.0.join("key"), key).unwrap(); let bytes = [0u8, 159, 146, 150, b'\n', 255, b'\r', b'\n']; std::fs::write(scratch.0.join("bytes"), bytes).unwrap(); let fetch = |raw: &str| { let Raw::Import(mut importer) = parse_argument(raw) else { panic!("{raw:?} imports nothing"); }; importer.dir = Some(scratch.0.clone()); importer.fetch() }; assert_eq!(fetch("file+raw:key").unwrap(), Imported::Raw(key.to_vec())); assert_eq!( fetch("file:key").unwrap(), Imported::Text("-----BEGIN KEY-----\nAAAA\n-----END KEY-----".into()) ); assert_eq!( fetch("file+raw:bytes").unwrap(), Imported::Raw(bytes.to_vec()) ); assert_eq!( fetch("cmd+raw:cat bytes").unwrap(), Imported::Raw(bytes.to_vec()) ); assert_eq!( fetch("cmd+raw:printf 'a\\n\\n'").unwrap(), Imported::Raw(b"a\n\n".to_vec()) ); let said = format!("{:#}", fetch("file:bytes").unwrap_err()); assert!( said.contains("not UTF-8") && said.contains("+raw"), "{said}" ); assert!(fetch("cmd:cat bytes").is_err()); // In a table, and said as written. let table = json!({ "file": "key", "format": "raw" }); let importer = parse_table(table.as_object().unwrap(), &scratch.0) .unwrap() .unwrap(); assert_eq!(importer.fetch().unwrap(), Imported::Raw(key.to_vec())); assert!(importer.describe().starts_with("file+raw:")); // A path may hold a placeholder. scratch.file("name", "key\n"); assert_eq!( fetch("file+raw:${file:name}").unwrap(), Imported::Raw(key.to_vec()) ); // Bytes go into bytes as they are: an argument of a command, of a shell's or of // a list's, the line breaks at its end kept, and what is no text. assert_eq!( fetch("cmd+raw:printf '%s' ${file+raw:key}").unwrap(), Imported::Raw(key.to_vec()) ); let unreadable = [159u8, 146, 150, b'\n', 255, b' ', b';', b'\n']; std::fs::write(scratch.0.join("unreadable"), unreadable).unwrap(); assert_eq!( fetch("cmd+raw:printf '%s' \"${file+raw:unreadable}\"").unwrap(), Imported::Raw(unreadable.to_vec()) ); let table = json!({ "command": ["printf", "%s|%s", "${file+raw:unreadable}", "${file:name}"], "format": "raw", }); let importer = parse_table(table.as_object().unwrap(), &scratch.0) .unwrap() .unwrap(); let mut expected = unreadable.to_vec(); expected.extend(b"|key"); assert_eq!(importer.fetch().unwrap(), Imported::Raw(expected)); // Into text, none: a text importer, and text with placeholders. for text in [ "cmd:printf '%s' ${file+raw:key}", "file:${file+raw:name}", "cmd+json:printf '%s' ${file+raw:key}", ] { let said = format!("{:#}", fetch(text).unwrap_err()); assert!(said.contains("+raw importer"), "{text:?}: {said}"); } assert!(expand("${file+raw:key}", Some(&scratch.0)).is_err()); assert!(expand("a${cmd+raw:cat key}", Some(&scratch.0)).is_err()); } impl Drop for Scratch { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } #[test] fn the_parts_of_what_an_importer_names() { let text = |text: &str| Part::Text(text.to_owned()); assert_eq!(parts("hostname -f").unwrap(), [text("hostname -f")]); assert_eq!( parts("secrets ${env:HOST} show x").unwrap(), [ text("secrets "), Part::Placeholder("env:HOST"), text(" show x") ] ); // The shell's own: left as they are. let own = r#"echo $HOME ${HOME} ${x:-y} $(date) $$ $((1 + 1)) ${env} ${cmd+x} "$@""#; assert_eq!(parts(own).unwrap(), [text(own)]); // `$${` gives the shell a `${` that would be a placeholder's. assert_eq!( parts("echo $${env:-x} $$").unwrap(), [text("echo ${env:-x} $$")] ); assert_eq!( parts("${cmd:a ${file:b}}${env:C}").unwrap(), [ Part::Placeholder("cmd:a ${file:b}"), Part::Placeholder("env:C") ] ); assert!(parts("echo ${env:HOST").is_err()); } /// What a placeholder gives is one word of a shell command, as it is, whatever it /// holds: the shell reads none of it as script, nor splits it, nor matches files by /// it, wherever a placeholder may be written. #[test] fn what_a_placeholder_gives_is_no_part_of_the_script() { let scratch = Scratch::new("script"); let hostile = [ "plain", "two words", "; touch injected", "$(touch injected)", "`touch injected`", "a\nb; touch injected", "' ; touch injected ; '", "\" ; touch injected ; \"", "\\", "*", "-n", "$HOME ${HOME} $1 $$", "x' \"$(touch injected)\" 'y", "| touch injected", "> injected", "& touch injected", ")\"; touch injected; (\"", "}; touch injected; {", ]; let commands = [ "printf '%s' ${file:value}", "printf '%s' \"${file:value}\"", "printf '%s' \"$(printf '%s' ${file:value})\"", "printf '%s' \"$(printf '%s' \"${file:value}\")\"", "x=${file:value}; printf '%s' \"$x\"", "(printf '%s' ${file:value})", "{ printf '%s' ${file:value}; }", "true # it's a comment\nprintf '%s' ${file:value}", "printf '%s' 'a'${file:value}'b' | sed 's/^a//; s/b$//'", "printf '%s' \"${x:-}\"${file:value}", "printf '%s' $((1 + 1))${file:value} | sed 's/^2//'", "printf '%s' `printf ''`${file:value}", "if true; then printf '%s' ${file:value}; fi", "printf '%s' ${file:value} 2>/dev/null", ]; for content in hostile { scratch.file("value", content); for command in commands { let got = scratch .fetch(&format!("cmd:{command}")) .unwrap_or_else(|why| panic!("{command:?} with {content:?}: {why:#}")); assert_eq!(got, content, "{command:?} with {content:?}"); assert!( !scratch.0.join("injected").exists(), "{command:?} with {content:?} ran what the value holds" ); } // In a template, in an argument and in a path alike. assert_eq!( expand("<${cmd:printf '%s' ${file:value}}>", Some(&scratch.0)).unwrap(), format!("<{content}>") ); let argv = Importer { source: Source::Argv(vec![ "printf".into(), "%s|%s".into(), "${file:value}".into(), "end".into(), ]), format: Format::Text, dir: Some(scratch.0.clone()), }; assert_eq!( argv.fetch().unwrap(), Imported::Text(format!("{content}|end")) ); assert!(!scratch.0.join("injected").exists()); } } /// Where a reference to a parameter can't be written so that the shell takes it as /// one word, as it is, the command is refused, and says where the placeholder is. #[test] fn a_placeholder_is_refused_where_it_cant_be_one_word() { let scratch = Scratch::new("refused"); scratch.file("value", "1"); for (command, why) in [ ("printf '%s' '${file:value}'", "single quotes"), ("printf '%s' `echo ${file:value}`", "backquotes"), ("printf '%s' $((${file:value} + 1))", "$((…))"), ("printf '%s' \"${x:-${file:value}}\"", "of the shell's"), ("cat <>() .join(" "); assert_eq!( scratch.fetch(&format!("cmd:printf '%s' {many}")).unwrap(), "x".repeat(12) ); // An importer says what it names as written, not what its placeholders give. let Raw::Import(importer) = parse_argument("cmd:secrets ${env:HOST} show x") else { panic!("an importer"); }; assert_eq!(importer.describe(), "cmd:secrets ${env:HOST} show x"); } }