aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/import.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 00:50:42 +0000
committertv <tv@krebsco.de>2026-11-29 01:00:16 +0000
commit7a8e8ecd650ddb253c08445f6f60686e1c8b8bf5 (patch)
tree4309216f7e96201c3ed71fc49aa594ba8ae62452 /crates/config/src/import.rs
parentd56436c3e5ee7b5659e1c2171c5c7af2d3c4eccb (diff)
config: +raw imports the bytes as they are
file+raw:, cmd+raw: and env+raw:, and format = "raw" in a table, give what is there byte for byte (Imported::Raw): no line break removed at its end, and what is no text taken, as a key or a certificate needs. Text and JSON still must be UTF-8, and say +raw where they aren't. A placeholder gives text; in a +raw importer one may be +raw too, and its bytes go in as they are, into a name, a path, an argument or a shell's positional parameter. Into text none does: not into a text or JSON importer, nor into text with placeholders. continuum takes a +raw value as one text, read as nothing else; one that is no UTF-8 it refuses, an option being text.
Diffstat (limited to 'crates/config/src/import.rs')
-rw-r--r--crates/config/src/import.rs213
1 files changed, 174 insertions, 39 deletions
diff --git a/crates/config/src/import.rs b/crates/config/src/import.rs
index 39b259f..a9ad603 100644
--- a/crates/config/src/import.rs
+++ b/crates/config/src/import.rs
@@ -7,12 +7,14 @@
//! * `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.
+//! 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"`.
+//! 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
@@ -25,8 +27,11 @@
//! 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.
+//! 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;
@@ -35,8 +40,23 @@ 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.
@@ -79,6 +99,7 @@ pub fn parse_argument(raw: &str) -> 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 {
@@ -133,7 +154,10 @@ pub fn parse_table(object: &JsonMap<String, JsonValue>, dir: &Path) -> Result<Op
None => Format::Text,
Some(JsonValue::String(format)) if format == "text" => Format::Text,
Some(JsonValue::String(format)) if format == "json" => Format::Json,
- Some(other) => bail!("importer format must be \"text\" or \"json\", not {other}"),
+ 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<String> {
match object.get(key) {
@@ -173,10 +197,7 @@ 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 = match self.format {
- Format::Text => "",
- Format::Json => "+json",
- };
+ 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()),
@@ -200,26 +221,29 @@ impl Importer {
}
}
- /// The imported content: text, or JSON.
+ /// The imported content: text, JSON, or bytes.
pub fn fetch(&self) -> Result<Imported> {
let dir = self.dir.as_deref();
- let text = match &self.source {
+ // 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)?;
- std::env::var(&name).with_context(|| {
- format!("environment variable {name} is not set (or not UTF-8)")
- })?
+ 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)?)),
+ Some(text) => self.in_dir(Path::new(&filled(text, dir, raw)?)),
None => self.in_dir(path),
};
- std::fs::read_to_string(&path)
- .with_context(|| format!("reading {}", path.display()))?
+ std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?
}
Source::Shell(command) => {
- let (script, values) = shell(command, dir)?;
+ let (script, values) = shell(command, dir, raw)?;
let mut process = Command::new("sh");
process.arg("-c").arg(script);
if !values.is_empty() {
@@ -231,29 +255,41 @@ impl Importer {
Source::Argv(argv) => {
let argv = argv
.iter()
- .map(|argument| filled(argument, dir))
+ .map(|argument| filled(argument, dir, raw))
.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)?,
+ 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::Text => Imported::Text(text.to_owned()),
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<u8>),
}
/// Where the placeholder that `text` starts (after its `${`) ends: at the `}` that
@@ -295,20 +331,30 @@ 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> {
+/// 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>> {
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)");
+ 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),
- Imported::Json(_) => unreachable!("text importer"),
+ Imported::Text(text) => Ok(text.into_bytes()),
+ Imported::Raw(bytes) => Ok(bytes),
+ Imported::Json(_) => unreachable!("no +json importer"),
}
}
@@ -325,7 +371,8 @@ 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:?}"))?;
- out.push_str(&value(&after[..end], template, dir)?);
+ 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.
@@ -349,7 +396,7 @@ 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; 3] = ["env:", "file:", "cmd:"];
+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
@@ -389,15 +436,15 @@ 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>) -> Result<String> {
- let mut out = String::new();
+fn filled(text: &str, dir: Option<&Path>, raw: bool) -> Result<OsString> {
+ let mut out = Vec::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)?),
+ Part::Text(plain) => out.extend(plain.into_bytes()),
+ Part::Placeholder(placeholder) => out.extend(value(placeholder, text, dir, raw)?),
}
}
- Ok(out)
+ Ok(OsString::from_vec(out))
}
/// A shell command with placeholders as a script for `sh -c` and the values to give it
@@ -405,7 +452,7 @@ fn filled(text: &str, dir: Option<&Path>) -> Result<String> {
/// `"${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>)> {
+fn shell(command: &str, dir: Option<&Path>, raw: bool) -> Result<(String, Vec<OsString>)> {
let mut script = String::new();
let mut values = Vec::new();
let mut at = Shell::default();
@@ -419,7 +466,7 @@ fn shell(command: &str, dir: Option<&Path>) -> Result<(String, Vec<String>)> {
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)?);
+ values.push(OsString::from_vec(value(placeholder, command, dir, raw)?));
script.push_str(&reference);
}
}
@@ -616,7 +663,7 @@ impl Shell {
}
}
-fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result<String> {
+fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result<Vec<u8>> {
if let Some(dir) = dir {
process.current_dir(dir);
}
@@ -630,7 +677,7 @@ fn run(mut process: Command, dir: Option<&Path>, shown: &str) -> Result<String>
String::from_utf8_lossy(&output.stderr).trim()
);
}
- String::from_utf8(output.stdout).with_context(|| format!("output of {shown} is not UTF-8"))
+ Ok(output.stdout)
}
#[cfg(test)]
@@ -797,10 +844,98 @@ mod tests {
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);