diff options
| author | tv <tv@krebsco.de> | 2026-12-01 04:51:21 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-12-01 05:03:57 +0000 |
| commit | 45b067620bce84cb1fae440efd7e4de78c6af63e (patch) | |
| tree | 8b7821269d667a7edb1c23324e5d5d116ae4c9f9 /crates/config/src/import.rs | |
| parent | 79396943ec9eee8ffd64669baaa3484fcad33feb (diff) | |
A placeholder var:NAME is replaced by what the program gives under that
name (Variables, Importer::fetch_with), under the rules of env:, file:
and cmd:: nested in a name, a path, an argument and a shell command, as
data, never as code; var+raw: where bytes go. One the program doesn't
give is an error naming it and those given. So an importer that differs
from one use to the next by a value is written once, with a variable.
Diffstat (limited to 'crates/config/src/import.rs')
| -rw-r--r-- | crates/config/src/import.rs | 220 |
1 files changed, 199 insertions, 21 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs index 61d162f..7305b49 100644 --- a/crates/config/src/import.rs +++ b/crates/config/src/import.rs @@ -25,12 +25,19 @@ //! //! 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, or the same with `$(`, `$${` is a `${` and -//! `$$(` 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 +//! `${env:`, `${file:`, `${cmd:` and `${var:` begin one, or the same with `$(`, `$${` is +//! a `${` and `$$(` 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. +//! +//! A program may give variables of its own (`Variables`, `Importer::fetch_with`): +//! `${var:NAME}` is replaced by the one of that name, as the program gives it, under the +//! same rules; `${var+raw:NAME}` where bytes go. One it doesn't give is an error that +//! names it, and those given. So what differs from one use to the next is a variable, +//! and the importer is written once: `["secrets", "$(env:HOSTNAME)", "show", +//! "$(var:key)"]`. use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; @@ -40,6 +47,13 @@ use std::process::Command; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map as JsonMap, Value as JsonValue}; +/// What the program that reads a configuration gives its importers, by name +/// (`Importer::fetch_with`): a `var:NAME` placeholder is replaced by it. +pub type Variables = std::collections::BTreeMap<String, Vec<u8>>; + +/// No variables: what `Importer::fetch` gives. +static NONE: Variables = Variables::new(); + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Format { /// Text, its trailing line breaks removed. @@ -223,14 +237,21 @@ impl Importer { } } - /// The imported content: text, JSON, or bytes. + /// The imported content: text, JSON, or bytes. Of a program that gives no variables: + /// a `var:` placeholder is an error. pub fn fetch(&self) -> Result<Imported> { + self.fetch_with(&NONE) + } + + /// The imported content: text, JSON, or bytes; its `var:` placeholders, and those + /// of the placeholders in it, replaced by what `variables` gives. + pub fn fetch_with(&self, variables: &Variables) -> Result<Imported> { 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)?; + let name = filled(name, dir, raw, variables)?; std::env::var_os(&name) .ok_or_else(|| { anyhow!("environment variable {} is not set", name.to_string_lossy()) @@ -239,13 +260,13 @@ impl Importer { } Source::File(path) => { let path = match path.to_str() { - Some(text) => self.in_dir(Path::new(&filled(text, dir, raw)?)), + Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, variables)?)), 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 (script, values) = shell(command, dir, raw, variables)?; let mut process = Command::new("sh"); process.arg("-c").arg(script); if !values.is_empty() { @@ -257,13 +278,13 @@ impl Importer { Source::Argv(argv) => { let argv = argv .iter() - .map(|argument| filled(argument, dir, raw)) + .map(|argument| filled(argument, dir, raw, variables)) .collect::<Result<Vec<_>>>()?; let mut process = Command::new(&argv[0]); process.args(&argv[1..]); run(process, dir, &self.describe())? } - Source::Template(template) => expand(template, dir)?.into_bytes(), + Source::Template(template) => expand_with(template, dir, variables)?.into_bytes(), }; if self.format == Format::Raw { return Ok(Imported::Raw(bytes)); @@ -352,10 +373,45 @@ fn placeholder_end(text: &str, open: char, close: char) -> Option<usize> { /// 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<Vec<u8>> { +fn value( + placeholder: &str, + within: &str, + dir: Option<&Path>, + raw: bool, + variables: &Variables, +) -> Result<Vec<u8>> { + if let Some((bytes, name)) = variable(placeholder) { + // Its name may hold placeholders, as an environment variable's. + let name = filled(name, dir, false, variables)?; + let name = name.to_string_lossy(); + let Some(value) = variables.get(name.as_ref()) else { + let given: Vec<&str> = variables.keys().map(String::as_str).collect(); + bail!( + "unknown variable {name:?} in {within:?}: {}", + if given.is_empty() { + "no variables are given here (a shell's own `${var:…}` is written `$${var:…}`)" + .to_owned() + } else { + format!("given are {}", given.join(", ")) + } + ); + }; + return match (bytes, raw) { + (true, true) => Ok(value.clone()), + (true, false) => bail!( + "placeholder {placeholder:?} in {within:?} gives bytes as they are, and goes into \ + text: a +raw placeholder is for a +raw importer" + ), + (false, _) if std::str::from_utf8(value).is_ok() => Ok(value.clone()), + (false, _) => bail!( + "variable {name:?} in {within:?} is not UTF-8: text is, and `var+raw:` in a \ + `+raw` importer takes bytes as they are" + ), + }; + } 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:"), + _ => bail!("placeholder {placeholder:?} in {within:?} isn't env:, file:, cmd: or var:"), }; match importer.format { Format::Text => {} @@ -369,15 +425,33 @@ fn value(placeholder: &str, within: &str, dir: Option<&Path>, raw: bool) -> Resu ), } importer.dir = dir.map(Path::to_owned); - match importer.fetch()? { + match importer.fetch_with(variables)? { 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. +/// The name in a placeholder that is a variable's, `var:NAME` or `var+raw:NAME`, and +/// whether it is `+raw`. +fn variable(placeholder: &str) -> Option<(bool, &str)> { + if let Some(name) = placeholder.strip_prefix("var:") { + Some((false, name)) + } else { + placeholder + .strip_prefix("var+raw:") + .map(|name| (true, name)) + } +} + +/// Text with its placeholders replaced by their content, without variables. +#[cfg(test)] fn expand(template: &str, dir: Option<&Path>) -> Result<String> { + expand_with(template, dir, &NONE) +} + +/// Text with its placeholders replaced by their content. +fn expand_with(template: &str, dir: Option<&Path>, variables: &Variables) -> Result<String> { let mut out = String::new(); let mut rest = template; while let Some(at) = rest.find('$') { @@ -389,7 +463,7 @@ fn expand(template: &str, dir: Option<&Path>) -> Result<String> { } else if let Some((after, close)) = opened(after) { let end = placeholder_end(after, opener(close), close) .ok_or_else(|| anyhow!("unterminated placeholder in template {template:?}"))?; - let text = value(&after[..end], template, dir, false)?; + let text = value(&after[..end], template, dir, false, variables)?; out.push_str(&String::from_utf8(text).expect("a text importer gives text")); rest = &after[end + 1..]; } else { @@ -414,11 +488,20 @@ enum Part<'a> { /// 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:"]; +const NESTED: [&str; 8] = [ + "env:", + "file:", + "cmd:", + "var:", + "env+raw:", + "file+raw:", + "cmd+raw:", + "var+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. +/// `${env:`, `${file:`, `${cmd:` and `${var:` 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(); @@ -453,12 +536,14 @@ fn parts(text: &str) -> Result<Vec<Part<'_>>> { /// 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<OsString> { +fn filled(text: &str, dir: Option<&Path>, raw: bool, variables: &Variables) -> Result<OsString> { 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)?), + Part::Placeholder(placeholder) => { + out.extend(value(placeholder, text, dir, raw, variables)?) + } } } Ok(OsString::from_vec(out)) @@ -469,7 +554,12 @@ fn filled(text: &str, dir: Option<&Path>, raw: bool) -> Result<OsString> { /// `"${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<OsString>)> { +fn shell( + command: &str, + dir: Option<&Path>, + raw: bool, + variables: &Variables, +) -> Result<(String, Vec<OsString>)> { let mut script = String::new(); let mut values = Vec::new(); let mut at = Shell::default(); @@ -483,7 +573,13 @@ fn shell(command: &str, dir: Option<&Path>, raw: bool) -> Result<(String, Vec<Os 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)?)); + values.push(OsString::from_vec(value( + placeholder, + command, + dir, + raw, + variables, + )?)); script.push_str(&reference); } } @@ -853,6 +949,88 @@ mod tests { ); } + /// A `var:` placeholder is replaced by what the program gives under that name: in + /// text, in a name, a path, an argument and a shell command, as data; an unknown one + /// is an error naming it, and the shell's own `${var:…}` is written `$${var:…}`. + #[test] + fn variables_the_program_gives() { + let scratch = Scratch::new("config-import-variables"); + std::fs::write(scratch.0.join("retiolum"), "a key\n").unwrap(); + let variables: Variables = [ + ("key", &b"retiolum"[..]), + ("code", b"$(echo no); echo no"), + ("bytes", b"\xff\n"), + ] + .into_iter() + .map(|(name, value)| (name.to_owned(), value.to_vec())) + .collect(); + let dir = Some(scratch.0.as_path()); + let text = |template: &str| expand_with(template, dir, &variables); + let fetch = |raw: &str| { + let Raw::Import(mut importer) = parse_argument(raw) else { + panic!("no importer: {raw}"); + }; + importer.dir = Some(scratch.0.clone()); + importer.fetch_with(&variables) + }; + + // In text, of either spelling. + assert_eq!( + text("<${var:key}|$(var:key)>").unwrap(), + "<retiolum|retiolum>" + ); + // In a path, an argument, and a shell command: one word, never script. + assert_eq!( + fetch("file:${var:key}").unwrap(), + Imported::Text("a key".into()) + ); + assert_eq!( + fetch("cmd:printf '%s' $(var:code)").unwrap(), + Imported::Text("$(echo no); echo no".into()) + ); + let argv = parse_table( + json!({ "command": ["printf", "%s|%s", "$(var:key)", "$(var:code)"] }) + .as_object() + .unwrap(), + &scratch.0, + ) + .unwrap() + .unwrap(); + assert_eq!( + argv.fetch_with(&variables).unwrap(), + Imported::Text("retiolum|$(echo no); echo no".into()) + ); + // Inside another placeholder, and naming a variable by one. + assert_eq!(text("${cmd:cat ${var:key}}").unwrap(), "a key"); + assert_eq!(text("${var:${cmd:echo key}}").unwrap(), "retiolum"); + // Bytes as they are go into a `+raw` importer only; text is UTF-8. + assert_eq!( + fetch("cmd+raw:printf '%s' ${var+raw:bytes}").unwrap(), + Imported::Raw(b"\xff\n".to_vec()) + ); + assert!(text("${var+raw:bytes}").is_err()); + let not_text = text("${var:bytes}").unwrap_err().to_string(); + assert!(not_text.contains("not UTF-8"), "{not_text}"); + + // An unknown one is an error that names it, and those given. + let unknown = text("${var:kye}").unwrap_err().to_string(); + assert!( + unknown.contains("\"kye\"") && unknown.contains("bytes, code, key"), + "{unknown}" + ); + let unknown = fetch("cmd:echo $(var:kye)").unwrap_err().to_string(); + assert!(unknown.contains("\"kye\""), "{unknown}"); + // Where the program gives none, each is unknown. + let none = expand("${var:key}", dir).unwrap_err().to_string(); + assert!(none.contains("no variables are given"), "{none}"); + // The shell's own. + assert_eq!( + fetch("cmd:var=mine; printf '%s' \"$${var:-x}\"").unwrap(), + Imported::Text("mine".into()) + ); + assert!(fetch("cmd:var=mine; printf '%s' \"${var:-x}\"").is_err()); + } + #[test] fn commands_with_braces_and_quotes() { let expanded = |template: &str| expand(template, None); |
