aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 00:29:50 +0000
committertv <tv@krebsco.de>2026-11-29 00:29:50 +0000
commitd56436c3e5ee7b5659e1c2171c5c7af2d3c4eccb (patch)
treec4da35c7acdf8b250ada8ec9adec65274e1c4016 /crates/config/src
parent479246f98be360b5943458bd58d07e6d46f81fd0 (diff)
config: placeholders nest, what one gives going in as data
A name, a path, a command and each argument of an importer may hold placeholders of their own. There only ${env:, ${file: and ${cmd: begin one, $${ is a ${, and every other $ stays: a command's are its shell's. What a placeholder gives is never run. Into a name, a path and an argument it goes as text, an argument staying one. A shell command gets it as a positional parameter, the placeholder becoming a reference to it, "${1}", or ${1} inside double quotes: no part of the script, whatever it holds. import::Shell tells where in a script a place is, as far as that reference needs; where it can't be written as one word (single quotes, backquotes, $((…)), the shell's ${…}, after a backslash or a here-document), the command is refused. What it gets wrong can refuse a reference or have the shell split it, never run it. An importer has its directory itself (Importer::dir), a file's path joined with it when read, so that a path may hold placeholders.
Diffstat (limited to 'crates/config/src')
-rw-r--r--crates/config/src/import.rs756
1 files changed, 637 insertions, 119 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs
index 886caf2..39b259f 100644
--- a/crates/config/src/import.rs
+++ b/crates/config/src/import.rs
@@ -16,8 +16,16 @@
//!
//! 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 first `}`), e.g. `node-${env:HOSTNAME}`. Relative paths are relative to
-//! the file, and commands run in its directory, in placeholders too.
+//! 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.
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -31,29 +39,26 @@ pub enum Format {
Json,
}
+/// 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),
- Shell {
- command: String,
- dir: Option<PathBuf>,
- },
- Argv {
- argv: Vec<String>,
- dir: Option<PathBuf>,
- },
+ /// A command for `sh -c`.
+ Shell(String),
+ /// A program and its arguments, run without a shell.
+ Argv(Vec<String>),
/// Text with placeholders (`interpolated`).
- Template {
- template: String,
- dir: Option<PathBuf>,
- },
+ 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<PathBuf>,
}
/// What a command-line value is: imported, or literal.
@@ -79,13 +84,14 @@ pub fn parse_argument(raw: &str) -> Raw<'_> {
let source = match kind {
"env" => Source::Env(rest.to_owned()),
"file" => Source::File(PathBuf::from(rest)),
- "cmd" => Source::Shell {
- command: rest.to_owned(),
- dir: None,
- },
+ "cmd" => Source::Shell(rest.to_owned()),
_ => return literal_or_interpolated(raw),
};
- Raw::Import(Importer { source, format })
+ Raw::Import(Importer {
+ source,
+ format,
+ dir: None,
+ })
}
fn literal_or_interpolated(raw: &str) -> Raw<'_> {
@@ -99,11 +105,9 @@ fn literal_or_interpolated(raw: &str) -> Raw<'_> {
/// expanding it reports), read in `dir`; None if it is plain text.
pub fn interpolated(text: &str, dir: Option<&Path>) -> Option<Importer> {
text.contains('$').then(|| Importer {
- source: Source::Template {
- template: text.to_owned(),
- dir: dir.map(Path::to_owned),
- },
+ source: Source::Template(text.to_owned()),
format: Format::Text,
+ dir: dir.map(Path::to_owned),
})
}
@@ -140,13 +144,10 @@ pub fn parse_table(object: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Op
let source = if object.contains_key("env") {
Source::Env(text("env")?)
} else if object.contains_key("file") {
- Source::File(dir.join(text("file")?))
+ Source::File(PathBuf::from(text("file")?))
} else {
match &object["command"] {
- JsonValue::String(command) => Source::Shell {
- command: command.clone(),
- dir: Some(dir.to_owned()),
- },
+ JsonValue::String(command) => Source::Shell(command.clone()),
JsonValue::Array(items) => {
let argv = items
.iter()
@@ -156,19 +157,21 @@ pub fn parse_table(object: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Op
.ok_or_else(|| {
anyhow!("importer command must be a string or a non-empty list of strings")
})?;
- Source::Argv {
- argv,
- dir: Some(dir.to_owned()),
- }
+ Source::Argv(argv)
}
_ => bail!("importer command must be a string or a non-empty list of strings"),
}
};
- Ok(Some(Importer { source, format }))
+ 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`.
+ /// 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 = match self.format {
Format::Text => "",
@@ -176,38 +179,65 @@ impl Importer {
};
match &self.source {
Source::Env(name) => format!("env{format}:{name}"),
- Source::File(path) => format!("file{format}:{}", path.display()),
- Source::Shell { command, .. } => format!("cmd{format}:{command}"),
- Source::Argv { argv, .. } => format!("cmd{format}:{}", argv.join(" ")),
- Source::Template { template, .. } => template.clone(),
+ 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 { .. })
+ 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, or JSON.
pub fn fetch(&self) -> Result<Imported> {
+ let dir = self.dir.as_deref();
let text = match &self.source {
- Source::Env(name) => std::env::var(name).with_context(|| {
- format!("environment variable {name} is not set (or not UTF-8)")
- })?,
- Source::File(path) => std::fs::read_to_string(path)
- .with_context(|| format!("reading {}", path.display()))?,
- Source::Shell { command, dir } => {
+ Source::Env(name) => {
+ let name = filled(name, dir)?;
+ std::env::var(&name).with_context(|| {
+ format!("environment variable {name} is not set (or not UTF-8)")
+ })?
+ }
+ Source::File(path) => {
+ let path = match path.to_str() {
+ Some(text) => self.in_dir(Path::new(&filled(text, dir)?)),
+ None => self.in_dir(path),
+ };
+ std::fs::read_to_string(&path)
+ .with_context(|| format!("reading {}", path.display()))?
+ }
+ Source::Shell(command) => {
+ let (script, values) = shell(command, dir)?;
let mut process = Command::new("sh");
- process.arg("-c").arg(command);
- run(process, dir.as_deref(), command)?
+ 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, dir } => {
+ Source::Argv(argv) => {
+ let argv = argv
+ .iter()
+ .map(|argument| filled(argument, dir))
+ .collect::<Result<Vec<_>>>()?;
let mut process = Command::new(&argv[0]);
process.args(&argv[1..]);
- run(process, dir.as_deref(), &argv.join(" "))?
+ run(process, dir, &self.describe())?
}
- Source::Template { template, dir } => expand(template, dir.as_deref())?,
+ Source::Template(template) => expand(template, dir)?,
};
let text = text.trim_end_matches(['\n', '\r']);
Ok(match self.format {
@@ -228,8 +258,8 @@ pub enum Imported {
/// 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); in a command (`cmd:`), braces in shell quotes (`'...'`, `"..."`) or
-/// escaped with a backslash don't count either.
+/// 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<usize> {
let shell = text.starts_with("cmd:") || text.starts_with("cmd+");
let mut depth = 0usize;
@@ -265,6 +295,23 @@ fn placeholder_end(text: &str) -> Option<usize> {
None
}
+/// What the placeholder `placeholder` (between its `${` and `}`) gives, as text, read in
+/// `dir`: an `env:`, a `file:` or a `cmd:`, without `+json`.
+fn value(placeholder: &str, within: &str, dir: Option<&Path>) -> Result<String> {
+ 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:"),
+ };
+ if importer.format != Format::Text {
+ bail!("placeholder {placeholder:?} must be text (+json isn't for placeholders)");
+ }
+ importer.dir = dir.map(Path::to_owned);
+ match importer.fetch()? {
+ Imported::Text(text) => Ok(text),
+ Imported::Json(_) => unreachable!("text importer"),
+ }
+}
+
/// Text with its placeholders replaced by their content.
fn expand(template: &str, dir: Option<&Path>) -> Result<String> {
let mut out = String::new();
@@ -278,29 +325,7 @@ fn expand(template: &str, dir: Option<&Path>) -> Result<String> {
} else if let Some(after) = after.strip_prefix('{') {
let end = placeholder_end(after)
.ok_or_else(|| anyhow!("unterminated placeholder in template {template:?}"))?;
- let placeholder = &after[..end];
- let Raw::Import(mut importer) = parse_argument(placeholder) else {
- bail!(
- "placeholder {placeholder:?} in template {template:?} isn't env:, file: or cmd:"
- );
- };
- match &mut importer.source {
- Source::File(path) => {
- if let Some(dir) = dir {
- *path = dir.join(&*path);
- }
- }
- Source::Shell { dir: run_in, .. } => *run_in = dir.map(Path::to_owned),
- Source::Template { .. } => bail!("placeholders don't nest: {placeholder:?}"),
- Source::Env(_) | Source::Argv { .. } => {}
- }
- if importer.format != Format::Text {
- bail!("placeholder {placeholder:?} must be text (+json isn't for placeholders)");
- }
- match importer.fetch()? {
- Imported::Text(text) => out.push_str(&text),
- Imported::Json(_) => unreachable!("text importer"),
- }
+ out.push_str(&value(&after[..end], template, dir)?);
rest = &after[end + 1..];
} else {
// Most likely a shell-style `$NAME` that would silently stay as it is.
@@ -314,6 +339,283 @@ fn expand(template: &str, dir: Option<&Path>) -> Result<String> {
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; 3] = ["env:", "file:", "cmd:"];
+
+/// 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<Vec<Part<'_>>> {
+ 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>) -> Result<String> {
+ let mut out = String::new();
+ for part in parts(text)? {
+ match part {
+ Part::Text(plain) => out.push_str(&plain),
+ Part::Placeholder(placeholder) => out.push_str(&value(placeholder, text, dir)?),
+ }
+ }
+ Ok(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>) -> Result<(String, Vec<String>)> {
+ 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(value(placeholder, command, dir)?);
+ 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<Inside>,
+ /// 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<String, &'static str> {
+ 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<String> {
if let Some(dir) = dir {
process.current_dir(dir);
@@ -336,6 +638,14 @@ 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"));
@@ -346,20 +656,11 @@ mod tests {
assert_eq!(parse_argument("literal:env:X"), Raw::Literal("env:X"));
assert_eq!(
parse_argument("env+json:SEEDS"),
- Raw::Import(Importer {
- source: Source::Env("SEEDS".into()),
- format: Format::Json
- })
+ Raw::Import(import(Source::Env("SEEDS".into()), Format::Json))
);
assert_eq!(
parse_argument("cmd:hostname -f"),
- Raw::Import(Importer {
- source: Source::Shell {
- command: "hostname -f".into(),
- dir: None
- },
- format: Format::Text
- })
+ 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.
@@ -367,13 +668,10 @@ mod tests {
assert_eq!(parse_argument("literal:a $5"), Raw::Literal("a $5"));
assert_eq!(
parse_argument("node-${env:HOST}"),
- Raw::Import(Importer {
- source: Source::Template {
- template: "node-${env:HOST}".into(),
- dir: None
- },
- format: Format::Text
- })
+ 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!(
@@ -399,6 +697,7 @@ mod tests {
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]
@@ -419,6 +718,11 @@ mod tests {
// 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]
@@ -436,13 +740,18 @@ mod tests {
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!(
- table(json!({ "file": "key", "format": "json" })).unwrap(),
- Some(Importer {
- source: Source::File("/etc/continuum/key".into()),
- format: Format::Json
- })
+ 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());
@@ -450,29 +759,238 @@ mod tests {
#[test]
fn fetching() {
- let echo = Importer {
- source: Source::Argv {
- argv: vec!["printf".into(), "[1, 2]\\n\\n".into()],
- dir: None,
- },
- format: Format::Json,
- };
+ 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 = Importer {
- source: Source::Shell {
- command: "echo hello".into(),
- dir: None,
- },
- format: Format::Text,
- };
+ let shell = import(Source::Shell("echo hello".into()), Format::Text);
assert_eq!(shell.fetch().unwrap(), Imported::Text("hello".into()));
- let failing = Importer {
- source: Source::Shell {
- command: "exit 3".into(),
- dir: None,
- },
- format: Format::Text,
- };
+ 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<String> {
+ 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()),
+ }
+ }
+ }
+
+ 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 <<EOF\n${file:value}\nEOF", "here-document"),
+ ("cat <<EOF\nEOF\nprintf '%s' ${file:value}", "here-document"),
+ ("printf '%s' \\${file:value}", "backslash"),
+ ("printf '%s' $${file:value}", ""),
+ ("printf '%s' \"it's ${file:value}", ""),
+ ] {
+ let got = scratch.fetch(&format!("cmd:{command}"));
+ if why.is_empty() {
+ // Not refused: the shell's own `${file:value}`, and an unended quote,
+ // which the shell refuses.
+ continue;
+ }
+ let said = format!("{:#}", got.expect_err(command));
+ assert!(said.contains(why), "{command:?}: {said}");
+ assert!(said.contains("file:value"), "{command:?}: {said}");
+ }
+ // `$${` is the shell's: its variable `file`, unset, with a default.
+ assert_eq!(
+ scratch.fetch("cmd:printf '%s' \"$${file:-none}\"").unwrap(),
+ "none"
+ );
+ // The shell's `$` stay its own beside placeholders, and `$1` is the first value.
+ assert_eq!(
+ scratch
+ .fetch("cmd:x=a; printf '%s%s%s' \"$x\" ${file:value} \"$(printf b)\"")
+ .unwrap(),
+ "a1b"
+ );
+ }
+
+ #[test]
+ fn placeholders_nest() {
+ let scratch = Scratch::new("nest");
+ scratch.file("name", "key file");
+ scratch.file("key file", "secret\n");
+ // A path from a file, a command's argument from that.
+ assert_eq!(scratch.fetch("file:${file:name}").unwrap(), "secret");
+ assert_eq!(
+ scratch
+ .fetch("cmd:printf '%s' ${file:${file:name}}")
+ .unwrap(),
+ "secret"
+ );
+ assert_eq!(
+ scratch
+ .fetch("cmd:cat ${cmd:printf '%s' ${file:name}}")
+ .unwrap(),
+ "secret"
+ );
+ assert_eq!(
+ expand("a-${cmd:cat ${file:name}}-b", Some(&scratch.0)).unwrap(),
+ "a-secret-b"
+ );
+ // More values than the shell has single digits for.
+ let many = (0..12)
+ .map(|_| "${cmd:printf x}")
+ .collect::<Vec<_>>()
+ .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");
+ }
}