diff options
| author | tv <tv@krebsco.de> | 2026-12-04 18:09:38 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-12-04 18:59:12 +0000 |
| commit | 5c6c878ae8c7ce8b04f4b540a04cbed7a4b37f38 (patch) | |
| tree | 89ea2ea643809dca4242110df99f8d3973aaeadd /crates/config/src/import.rs | |
| parent | 9f64a8d003bd301a6499bf7a6f60e6cf0b533162 (diff) | |
A value that is gone is not a failure: a key taken out of a secret
store is one thing, a wrong passphrase another. An importer says in its
table what tells the first: absent.status = N of a command, that exit
status of a normal exit; absent.missing = true of a file; absent.unset =
true of an environment variable. Nothing is built in, as tools disagree,
and nothing is absent unless the importer says so.
Any status may be said but 0, which says that there is a value: which
one nothing else gives is the writer's to know, and the documentation
tells what gives which. A script says its status with exit, and the
shell exits with exactly that; where a shell exits by itself (a line it
can't read, an expansion that fails), POSIX leaves the status open
within 1 to 125, and bash, dash and BusyBox ash use 1 and 2; 126, 127
and those above 128 are a command that can't be run, one that isn't
found, and one a signal killed. So a script says absent with a status
from 3 to 125.
fetch and its kin give the typed error import::Absent then, with the
importer as written and what told, and Importer::found_in tells it from
a value. Only the importer asked is absent: one inside another that is
makes that one fail. continuum takes an option's absent value for a
failure.
Diffstat (limited to 'crates/config/src/import.rs')
| -rw-r--r-- | crates/config/src/import.rs | 391 |
1 files changed, 379 insertions, 12 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs index 13885a3..e3b7d98 100644 --- a/crates/config/src/import.rs +++ b/crates/config/src/import.rs @@ -46,6 +46,12 @@ //! is `pass = { command = ["pass", "show", "$(var:name)"] }`, written by who uses it. //! In a table, one is used with several variables: `{ NAME = { host = "…", key = "…" } }` //! (`Source::Named`); one it never asks for is an error, as one it lacks is. +//! +//! An importer may say what tells that its value is absent, which is no failure +//! (`Absence`: `absent.status` of a command, `absent.missing` of a file, `absent.unset` +//! of an environment variable, in its table): `fetch` and its kin then give the error +//! `Absent`, and `Importer::found_in` tells it from a value. Only the importer asked is +//! absent: one inside another that is makes that one fail. use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; @@ -84,7 +90,9 @@ static UNNAMED: Importers = Importers::new(); /// What a named importer may not be called: the kinds built in, and what else a /// value or an importer table reads as its own. -const RESERVED: [&str; 7] = ["env", "file", "cmd", "command", "var", "literal", "format"]; +const RESERVED: [&str; 8] = [ + "env", "file", "cmd", "command", "var", "literal", "format", "absent", +]; /// The variable a named importer gets what follows its name as. pub const NAME: &str = "name"; @@ -134,6 +142,48 @@ pub enum Source { Template(String), } +/// What an importer says counts as its value being absent, rather than as a +/// failure (`absent` in its table): nothing, unless it says so. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Absence { + /// Nothing: every failure is one. + #[default] + Never, + /// A command's exit status (`absent.status`), one it has to itself, of + /// a normal exit: one killed by a + /// signal has none. + Status(u8), + /// A file that isn't there (`absent.missing`). + Missing, + /// An environment variable that isn't set (`absent.unset`). + Unset, +} + +/// An importer's value is absent, as the importer says it tells (`Absence`): the +/// error `fetch` and its kin give then, found in the chain +/// (`error.downcast_ref::<Absent>()`), or by `Importer::found_in`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Absent { + /// The importer, as `Importer::describe` has it. + pub importer: String, + /// What told: never `Absence::Never`. + pub by: Absence, +} + +impl std::fmt::Display for Absent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} is absent: ", self.importer)?; + match self.by { + Absence::Status(status) => write!(f, "its command exited with {status}"), + Absence::Missing => write!(f, "there is no such file"), + Absence::Unset => write!(f, "the variable isn't set"), + Absence::Never => write!(f, "it says so"), + } + } +} + +impl std::error::Error for Absent {} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct Importer { pub source: Source, @@ -141,6 +191,8 @@ pub struct Importer { /// 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 counts as its value being absent (`Absent`). + pub absent: Absence, } /// What a command-line value is: imported, or literal. @@ -183,6 +235,7 @@ pub fn parse_argument_in<'a>(raw: &'a str, importers: &Importers) -> Raw<'a> { source, format, dir: None, + absent: Absence::Never, }) } @@ -267,6 +320,7 @@ pub fn interpolated(text: &str, dir: Option<&Path>) -> Option<Importer> { source: Source::Template(text.to_owned()), format: Format::Text, dir: dir.map(Path::to_owned), + absent: Absence::Never, }) } @@ -299,7 +353,8 @@ pub fn parse_table_in( bail!("an importer takes exactly one of env, file, command and those named"); } if let Some(unknown) = object.keys().find(|key| { - !["env", "file", "command", "format"].contains(&key.as_str()) && !named.contains(key) + !["env", "file", "command", "format", "absent"].contains(&key.as_str()) + && !named.contains(key) }) { bail!("unknown importer key {unknown:?}"); } @@ -344,13 +399,61 @@ pub fn parse_table_in( _ => bail!("importer command must be a string or a non-empty list of strings"), } }; + let absent = absence(object.get("absent"), &source)?; Ok(Some(Importer { source, format, dir: Some(dir.to_owned()), + absent, })) } +/// What an importer's table says of its value being absent (`absent`), for the +/// importer `source`: `absent.status` of a command, the exit status that says so, any +/// but 0, which says that there is a value; `absent.missing` of a file, and +/// `absent.unset` of an environment variable, whether there being none says so. One of +/// them, and the one of its kind: a named importer says it where it is named. +fn absence(value: Option<&JsonValue>, source: &Source) -> Result<Absence> { + let Some(value) = value else { + return Ok(Absence::Never); + }; + let JsonValue::Object(table) = value else { + bail!( + "importer absent must be a table (absent.status, absent.missing or absent.unset), not {value}" + ); + }; + let mut keys = table.iter(); + let (Some((key, said)), None) = (keys.next(), keys.next()) else { + bail!("importer absent takes one of status, missing and unset"); + }; + let whether = |said: &JsonValue, absence: Absence| match said { + JsonValue::Bool(true) => Ok(absence), + JsonValue::Bool(false) => Ok(Absence::Never), + other => Err(anyhow!( + "importer absent.{key} must be true or false, not {other}" + )), + }; + match (key.as_str(), source) { + ("status", Source::Shell(_) | Source::Argv(_)) => said + .as_u64() + .and_then(|status| u8::try_from(status).ok()) + .filter(|status| *status != 0) + .map(Absence::Status) + .ok_or_else(|| { + anyhow!("importer absent.status must be an exit status, 1 to 255, not {said}") + }), + ("missing", Source::File(_)) => whether(said, Absence::Missing), + ("unset", Source::Env(_)) => whether(said, Absence::Unset), + ("status" | "missing" | "unset", Source::Named { importer, .. }) => bail!( + "importer absent.{key}: the importer named {importer:?} says where it is named what tells that its value is absent" + ), + ("status", _) => bail!("importer absent.status is a command's"), + ("missing", _) => bail!("importer absent.missing is a file's"), + ("unset", _) => bail!("importer absent.unset is an environment variable's"), + (unknown, _) => bail!("unknown importer key absent.{unknown}"), + } +} + impl Importer { /// Shown instead of the value (which may be secret), e.g. `env:HOSTNAME`: as /// written, its placeholders not replaced. @@ -365,6 +468,8 @@ impl Importer { importer, variables, } => match (variables.len(), variables.get(NAME)) { + // Used with nothing: its name alone. + (1, Some(name)) if name.is_empty() => format!("{importer}{format}"), (1, Some(name)) => format!("{importer}{format}:{name}"), _ => format!("{importer}{format}({})", listed(variables)), }, @@ -372,6 +477,35 @@ impl Importer { } } + /// This importer's value being absent, by `by`. + fn absent_by(&self, by: Absence) -> Absent { + Absent { + importer: self.describe(), + by, + } + } + + /// What its command wrote, or that its exit status says its value is absent. + fn ran(&self, ran: std::result::Result<Vec<u8>, u8>) -> Result<Vec<u8>> { + ran.map_err(|status| self.absent_by(Absence::Status(status)).into()) + } + + /// The imported content, as `fetch_in`; or that it is absent, as the importer + /// says it tells, which `fetch_in` gives as an error (`Absent`). + pub fn found_in( + &self, + variables: &Variables, + importers: &Importers, + ) -> Result<std::result::Result<Imported, Absent>> { + match self.fetch_in(variables, importers) { + Ok(imported) => Ok(Ok(imported)), + Err(error) => match error.downcast::<Absent>() { + Ok(absent) => Ok(Err(absent)), + Err(error) => Err(error), + }, + } + } + /// The variables it asks for by name (`var:NAME`), in what it names and in the /// placeholders there, those of importers named among them: what a use may give /// it. None where it computes a variable's name, and so may take any. @@ -444,8 +578,9 @@ impl Importer { Source::Env(name) => { let name = filled(name, dir, raw, given)?; std::env::var_os(&name) - .ok_or_else(|| { - anyhow!("environment variable {} is not set", name.to_string_lossy()) + .ok_or_else(|| match self.absent { + Absence::Unset => anyhow::Error::new(self.absent_by(Absence::Unset)), + _ => anyhow!("environment variable {} is not set", name.to_string_lossy()), })? .into_encoded_bytes() } @@ -454,7 +589,18 @@ impl Importer { Some(text) => self.in_dir(Path::new(&filled(text, dir, raw, given)?)), None => self.in_dir(path), }; - std::fs::read(&path).with_context(|| format!("reading {}", path.display()))? + match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(error) + if self.absent == Absence::Missing + && error.kind() == std::io::ErrorKind::NotFound => + { + return Err(self.absent_by(Absence::Missing).into()); + } + Err(error) => { + return Err(error).with_context(|| format!("reading {}", path.display())); + } + } } Source::Shell(command) => { let (script, values) = shell(command, dir, raw, given)?; @@ -464,7 +610,7 @@ impl Importer { // `$0`, then the values as `$1`, `$2`, … process.arg("sh").args(values); } - run(process, dir, command)? + self.ran(run(process, dir, command, self.absent)?)? } Source::Argv(argv) => { let argv = argv @@ -473,7 +619,7 @@ impl Importer { .collect::<Result<Vec<_>>>()?; let mut process = Command::new(&argv[0]); process.args(&argv[1..]); - run(process, dir, &self.describe())? + self.ran(run(process, dir, &self.describe(), self.absent)?)? } Source::Template(template) => expand_with(template, dir, given)?.into_bytes(), Source::Named { @@ -522,8 +668,13 @@ impl Importer { importers: given.importers, depth: given.depth + 1, }) - .with_context(|| { - format!("the importer named {importer:?} ({})", listed(used)) + // Absent as it says: this one is, as written here. + .map_err(|error| match error.downcast_ref::<Absent>() { + Some(absent) => anyhow::Error::new(self.absent_by(absent.by)), + None => error.context(format!( + "the importer named {importer:?} ({})", + listed(used) + )), })?; match fetched { Imported::Raw(bytes) => bytes, @@ -670,7 +821,15 @@ fn value( ), } importer.dir = dir.map(Path::to_owned); - match importer.fetch_given(given)? { + // Absent, inside another: that one lacks what it is made of, and fails. + let fetched = + importer + .fetch_given(given) + .map_err(|error| match error.downcast_ref::<Absent>() { + Some(absent) => anyhow!("{absent}, in {within:?}"), + None => error, + })?; + match fetched { Imported::Text(text) => Ok(text.into_bytes()), Imported::Raw(bytes) => Ok(bytes), Imported::Json(_) => unreachable!("no +json importer"), @@ -1117,13 +1276,25 @@ impl Shell { } } -fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result<Vec<u8>> { +/// What `process` wrote, run in `dir`; or, where it exited with the status `absent` +/// names, that status. Every other failure is one, a signal's among them. +fn run( + mut process: Command, + dir: Option<&Path>, + shown: &str, + absent: Absence, +) -> Result<std::result::Result<Vec<u8>, u8>> { if let Some(dir) = dir { process.current_dir(dir); } let output = process .output() .with_context(|| format!("running {shown}"))?; + if let (Absence::Status(status), Some(code)) = (absent, output.status.code()) + && code == i32::from(status) + { + return Ok(Err(status)); + } if !output.status.success() { bail!( "{shown} failed ({}): {}", @@ -1131,7 +1302,7 @@ fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result<Vec<u8>> String::from_utf8_lossy(&output.stderr).trim() ); } - Ok(output.stdout) + Ok(Ok(output.stdout)) } #[cfg(test)] @@ -1144,6 +1315,7 @@ mod tests { source, format, dir: None, + absent: Absence::Never, } } @@ -1598,6 +1770,199 @@ mod tests { } } + /// An importer says what tells that its value is absent: a command's exit status, a + /// file that isn't there, a variable that isn't set. Then that is no failure but + /// `Absent`, found without reading text; anything else stays a failure, and so does + /// everything of an importer that says nothing. + #[test] + fn an_importer_says_what_tells_that_its_value_is_absent() { + let scratch = Scratch::new("config-import-absent"); + std::fs::write(scratch.0.join("there"), "a value\n").unwrap(); + let none = Importers::new(); + let variables = Variables::new(); + let table = |value: JsonValue| { + parse_table(value.as_object().unwrap(), &scratch.0) + .map(|importer| importer.expect("an importer")) + }; + let found = |importer: &Importer| importer.found_in(&variables, &none); + + // A command: the status it names, of a normal exit, and no other. + let fails = |absent: JsonValue| table(json!({ "command": ["false"], "absent": absent })); + let gone = found(&fails(json!({ "status": 1 })).unwrap()) + .unwrap() + .unwrap_err(); + assert_eq!(gone.by, Absence::Status(1)); + assert_eq!(gone.importer, "cmd:false"); + assert!(found(&fails(json!({ "status": 3 })).unwrap()).is_err()); + // One that says nothing fails, whatever it exits with. + let silent = table(json!({ "command": ["false"] })).unwrap(); + assert!(found(&silent).is_err()); + // A shell command says it by `exit`, and so does a script given to a shell. + let shell = |script: &str, status: u8| { + table(json!({ "command": script, "absent": { "status": status } })).unwrap() + }; + assert_eq!( + found(&shell("exit 3", 3)).unwrap().unwrap_err().by, + Absence::Status(3) + ); + assert!(found(&shell("exit 4", 3)).is_err()); + // With a placeholder, and the tool's status turned into the script's own. + let turned = shell("false $(env:PATH) || { test $? = 1 && exit 3; }", 3); + assert_eq!(found(&turned).unwrap().unwrap_err().by, Absence::Status(3)); + let bash = |script: &str, status: u8| { + table(json!({ "command": ["bash", "-c", script], "absent": { "status": status } })) + .unwrap() + }; + assert_eq!( + found(&bash("exit 3", 3)).unwrap().unwrap_err().by, + Absence::Status(3) + ); + // A command it doesn't find, a line it can't read, a child a signal killed: + // failures, as none of those statuses is the one said. + for broken in [ + "continuum-no-such-command", + "if then", + "bash -c 'kill -9 $$'; exit $?", + ] { + assert!(found(&shell(broken, 3)).is_err(), "{broken}"); + assert!(found(&bash(broken, 3)).is_err(), "{broken}"); + } + // Killed by a signal itself: no exit status, so a failure. + assert!(found(&bash("kill -TERM $$", 15)).is_err()); + // Any status may be said, a shell's for a command it doesn't find, too. + assert_eq!( + found(&shell("continuum-no-such-command", 127)) + .unwrap() + .unwrap_err() + .by, + Absence::Status(127) + ); + // What it wrote isn't looked at. + assert_eq!( + found(&bash("echo half; exit 4", 4)) + .unwrap() + .unwrap_err() + .by, + Absence::Status(4) + ); + // There, it is its value. + let there = table(json!({ "command": ["echo", "here"], "absent": { "status": 4 } })); + assert_eq!( + found(&there.unwrap()).unwrap().unwrap(), + Imported::Text("here".into()) + ); + // A file that isn't there; one that can't be read is a failure. + let missing = table(json!({ "file": "nowhere", "absent": { "missing": true } })).unwrap(); + assert_eq!(found(&missing).unwrap().unwrap_err().by, Absence::Missing); + let a_directory = table(json!({ "file": ".", "absent": { "missing": true } })).unwrap(); + assert!(found(&a_directory).is_err()); + assert!(found(&table(json!({ "file": "nowhere" })).unwrap()).is_err()); + assert!( + found(&table(json!({ "file": "nowhere", "absent": { "missing": false } })).unwrap()) + .is_err() + ); + // A variable that isn't set. + let unset = "CONFIG_TEST_ABSENT_VARIABLE_UNSET"; + let variable = table(json!({ "env": unset, "absent": { "unset": true } })).unwrap(); + assert_eq!(found(&variable).unwrap().unwrap_err().by, Absence::Unset); + assert!(found(&table(json!({ "env": unset })).unwrap()).is_err()); + + // The calls that give no `Result` of it give the error, typed, in the chain. + let error = missing.fetch().unwrap_err(); + let absent = error.downcast_ref::<Absent>().expect("absent"); + assert_eq!(absent.by, Absence::Missing); + assert!(error.to_string().contains("is absent"), "{error}"); + assert!( + silent + .fetch() + .unwrap_err() + .downcast_ref::<Absent>() + .is_none() + ); + + // A named importer says it where it is named, and is absent as it is used. + let named = named_in_table( + json!({ + "secrets": { + "command": ["bash", "-c", "test -e \"$1\" && cat \"$1\" || exit 3", "sh", "$(var:key)"], + "absent": { "status": 3 }, + }, + "gone": { "command": ["bash", "-c", "exit 3"], "absent": { "status": 3 } }, + }) + .as_object() + .unwrap(), + &scratch.0, + ) + .unwrap(); + let used = |key: &str| { + parse_table_in( + json!({ "secrets": { "key": key } }).as_object().unwrap(), + &scratch.0, + &named, + ) + .unwrap() + .unwrap() + }; + assert_eq!( + used("there").found_in(&variables, &named).unwrap().unwrap(), + Imported::Text("a value".into()) + ); + let gone = used("gone") + .found_in(&variables, &named) + .unwrap() + .unwrap_err(); + assert_eq!( + (gone.importer.as_str(), gone.by), + ("secrets(key = gone)", Absence::Status(3)) + ); + assert!( + parse_table_in( + json!({ "secrets": { "key": "x" }, "absent": { "status": 3 } }) + .as_object() + .unwrap(), + &scratch.0, + &named, + ) + .is_err() + ); + + // Absent inside another: that one fails, and is not absent itself. + let inside = interpolated("node-$(gone:)", Some(&scratch.0)).unwrap(); + let error = inside.fetch_in(&variables, &named).unwrap_err(); + assert!(error.downcast_ref::<Absent>().is_none()); + assert!(format!("{error:#}").contains("is absent"), "{error:#}"); + let outer = table(json!({ + "command": ["printf", "%s", "$(gone:)"], "absent": { "status": 3 } + })) + .unwrap(); + assert!(outer.found_in(&variables, &named).is_err()); + + // What `absent` takes: one key, the one of the importer's kind. + for refused in [ + json!({ "command": ["true"], "absent": { "status": 0 } }), + json!({ "command": ["true"], "absent": { "status": 256 } }), + json!({ "command": ["true"], "absent": { "status": "3" } }), + json!({ "command": ["true"], "absent": { "missing": true } }), + json!({ "command": ["true"], "absent": { "status": 3, "unset": true } }), + json!({ "command": ["true"], "absent": { "other": 1 } }), + json!({ "command": ["true"], "absent": 3 }), + json!({ "command": ["true"], "absent": {} }), + json!({ "file": "x", "absent": { "status": 3 } }), + json!({ "file": "x", "absent": { "missing": 1 } }), + json!({ "env": "X", "absent": { "missing": true } }), + ] { + assert!(table(refused.clone()).is_err(), "{refused}"); + } + // And no importer is named `absent`. + assert!( + named_in_table( + json!({ "absent": "cmd:true" }).as_object().unwrap(), + &scratch.0 + ) + .is_err() + ); + } + #[test] fn commands_with_braces_and_quotes() { let expanded = |template: &str| expand(template, None); @@ -1622,6 +1987,7 @@ mod tests { source: Source::File("key".into()), format: Format::Json, dir: Some(dir.to_owned()), + absent: Absence::Never, } ); assert_eq!(file.describe(), "file+json:/etc/continuum/key"); @@ -1849,6 +2215,7 @@ mod tests { ]), format: Format::Text, dir: Some(scratch.0.clone()), + absent: Absence::Never, }; assert_eq!( argv.fetch().unwrap(), |
