aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock2
-rw-r--r--nix/package.nix2
-rw-r--r--src/pack.rs185
-rw-r--r--tests/receptor.rs98
4 files changed, 258 insertions, 29 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 2ebe613..2e25278 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -94,7 +94,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "config"
version = "0.1.0"
-source = "git+https://cgit.krebsco.de/continuum#34434f7fd5a6bab1884a63c96679f48045f4bffd"
+source = "git+https://cgit.krebsco.de/continuum#45b067620bce84cb1fae440efd7e4de78c6af63e"
dependencies = [
"anyhow",
"clap",
diff --git a/nix/package.nix b/nix/package.nix
index 997d2a3..554dc4f 100644
--- a/nix/package.nix
+++ b/nix/package.nix
@@ -32,7 +32,7 @@ rustPlatform.buildRustPackage {
cargoLock = {
lockFile = ../Cargo.lock;
- outputHashes."config-0.1.0" = "sha256-uulfkMx4Nuh22xd7sujqQKSr9AikY8j0CgQygqvs/zw=";
+ outputHashes."config-0.1.0" = "sha256-wkXTqFGIEyPcwwOGoHcIxIwAlYOGDf03hwRI/qmdZTk=";
};
meta = {
diff --git a/src/pack.rs b/src/pack.rs
index dda4f6a..5bbed1d 100644
--- a/src/pack.rs
+++ b/src/pack.rs
@@ -18,8 +18,14 @@
//! continuum's `config` crate: `env:`, `file:`, `cmd:`, the tables `{ "env": … }`,
//! `{ "file": … }`, `{ "command": … }`, and text with placeholders. An entry is taken
//! byte-exact (as `+raw`), a record as JSON. Relative paths are relative to the
-//! source list, and commands run in its directory. JSON, or TOML by the extension
-//! `.toml`.
+//! source list, and commands run in its directory.
+//!
+//! A location is a source declared once (`locations`, or in a file of them the source
+//! list includes, `include`), which items use by name, `{ "location": NAME, … }`: their
+//! other fields are its variables, which its placeholders take as `$(var:NAME)`, as
+//! data. Its paths are relative to the file that declares it.
+//!
+//! JSON, or TOML by the extension `.toml`.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -45,56 +51,152 @@ pub struct SourceList {
pub items: BTreeMap<String, ItemSource>,
#[serde(default)]
pub groups: BTreeMap<String, GroupSpec>,
+ /// Sources declared once, by name, for items to use with variables of their own.
+ #[serde(default)]
+ pub locations: BTreeMap<String, Location>,
+ /// Files of locations, relative to the source list.
+ #[serde(default)]
+ pub include: Vec<PathBuf>,
+}
+
+/// A source declared once (`locations`): its placeholders take the variables of each
+/// item that uses it, as `$(var:NAME)`.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Location {
+ pub source: Value,
+ /// Where its relative paths are relative to, and its commands run: the directory of
+ /// the file that declares it.
+ #[serde(skip)]
+ pub dir: PathBuf,
}
+/// A file of locations, which a source list includes.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
+struct Locations {
+ #[serde(default)]
+ locations: BTreeMap<String, Location>,
+ #[serde(default)]
+ include: Vec<PathBuf>,
+}
+
+#[derive(Debug, Deserialize)]
pub struct ItemSource {
#[serde(default)]
pub source: Option<Value>,
+ /// A location's name, instead of a source.
+ #[serde(default)]
+ pub location: Option<String>,
#[serde(default)]
pub remove: bool,
#[serde(default)]
pub required: Option<bool>,
#[serde(default)]
pub group: Option<String>,
+ /// For an item with a location: its variables, the item's other fields.
+ #[serde(flatten)]
+ pub variables: BTreeMap<String, Value>,
+}
+
+/// The JSON, or TOML by the extension `.toml`, in `path`.
+fn read(path: &Path) -> Result<Value> {
+ let text =
+ std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
+ if path
+ .extension()
+ .is_some_and(|extension| extension == "toml")
+ {
+ Ok(toml::from_str(&text)?)
+ } else {
+ Ok(serde_json::from_str(&text)?)
+ }
+}
+
+/// The directory of `path`, for what is relative to it.
+fn dir_of(path: &Path) -> PathBuf {
+ path.parent()
+ .map(Path::to_owned)
+ .filter(|dir| !dir.as_os_str().is_empty())
+ .unwrap_or_else(|| PathBuf::from("."))
}
impl SourceList {
pub fn load(path: &Path) -> Result<Self> {
- let text =
- std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
- let value: Value = if path
- .extension()
- .is_some_and(|extension| extension == "toml")
- {
- toml::from_str(&text).with_context(|| format!("source list {}", path.display()))?
- } else {
- serde_json::from_str(&text)
- .with_context(|| format!("source list {}", path.display()))?
- };
- serde_json::from_value(value).with_context(|| format!("source list {}", path.display()))
+ let context = || format!("source list {}", path.display());
+ let mut list: SourceList =
+ serde_json::from_value(read(path).with_context(context)?).with_context(context)?;
+ let dir = dir_of(path);
+ for location in list.locations.values_mut() {
+ location.dir = dir.clone();
+ }
+ let mut seen = vec![std::path::absolute(path)?];
+ let includes = std::mem::take(&mut list.include);
+ for include in includes {
+ include_locations(&dir.join(include), &mut list.locations, &mut seen)
+ .with_context(context)?;
+ }
+ Ok(list)
}
}
+/// Adds the locations of the file `path`, and of those it includes, to `locations`; a
+/// name declared twice is an error, as is a file included in a circle.
+fn include_locations(
+ path: &Path,
+ locations: &mut BTreeMap<String, Location>,
+ seen: &mut Vec<PathBuf>,
+) -> Result<()> {
+ let absolute = std::path::absolute(path)?;
+ if seen.contains(&absolute) {
+ bail!("{} includes itself", path.display());
+ }
+ seen.push(absolute);
+ let context = || format!("locations {}", path.display());
+ let file: Locations =
+ serde_json::from_value(read(path).with_context(context)?).with_context(context)?;
+ let dir = dir_of(path);
+ for (name, mut location) in file.locations {
+ if locations.contains_key(&name) {
+ bail!(
+ "location {name} is declared twice (again in {})",
+ path.display()
+ );
+ }
+ location.dir = dir.clone();
+ locations.insert(name, location);
+ }
+ for include in file.include {
+ include_locations(&dir.join(include), locations, seen)?;
+ }
+ seen.pop();
+ Ok(())
+}
+
/// Packs the source list at `path` into a submission in `out` (which must not exist,
/// or be empty), checked against `schema` if one is given. Returns warnings: an
/// entry whose source is text with placeholders loses its trailing line breaks.
pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<Vec<String>> {
let list = SourceList::load(path)?;
- let dir = path
- .parent()
- .map(Path::to_owned)
- .filter(|dir| !dir.as_os_str().is_empty())
- .unwrap_or_else(|| PathBuf::from("."));
+ let dir = dir_of(path);
name::check("channel", &list.channel)?;
let mut items = Vec::new();
for (key, item) in &list.items {
let address: Address = format!("{}/{key}", list.channel)
.parse()
.with_context(|| format!("item {key}"))?;
- if item.remove == item.source.is_some() {
- bail!("item {key}: give either a source or \"remove\": true");
+ if item.source.is_some() && item.location.is_some() {
+ bail!("item {key}: give a source or a location, not both");
+ }
+ if item.location.is_none() && !item.variables.is_empty() {
+ let fields: Vec<_> = item.variables.keys().map(String::as_str).collect();
+ bail!(
+ "item {key}: unknown fields {} (variables are for an item with a location)",
+ fields.join(", ")
+ );
+ }
+ if item.remove == (item.source.is_some() || item.location.is_some()) {
+ bail!("item {key}: give either a source (or a location) or \"remove\": true");
}
items.push((address, item));
}
@@ -107,19 +209,36 @@ pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<Vec<Stri
let mut specs = Vec::new();
let mut warnings = Vec::new();
for (address, item) in &items {
- if let Some(source) = &item.source {
- let importer = importer(source, &dir, address.key.is_none())
- .with_context(|| format!("item {address}"))?;
+ // The item's own source, or its location's with its variables.
+ let source = match (&item.source, &item.location) {
+ (Some(source), _) => Some((source, dir.as_path(), None)),
+ (None, Some(name)) => {
+ let location = list
+ .locations
+ .get(name)
+ .with_context(|| format!("item {address}: no location {name}"))?;
+ Some((&location.source, location.dir.as_path(), Some(name)))
+ }
+ (None, None) => None,
+ };
+ if let Some((source, source_dir, location)) = source {
+ let what = match location {
+ Some(name) => format!("item {address} (location {name})"),
+ None => format!("item {address}"),
+ };
+ let importer = importer(source, source_dir, address.key.is_none())
+ .with_context(|| what.clone())?;
if address.key.is_none() && importer.is_interpolation() {
warnings.push(format!(
- "item {address}: its source is text with placeholders, which loses \
+ "{what}: its source is text with placeholders, which loses \
trailing line breaks; for the entry as it is, a whole-value source \
(cmd:…, file:…, or a table) takes it byte-exact"
));
}
+ let variables = variables(item).with_context(|| what.clone())?;
let imported = importer
- .fetch()
- .with_context(|| format!("item {address}: {}", importer.describe()))?;
+ .fetch_with(&variables)
+ .with_context(|| format!("{what}: {}", importer.describe()))?;
match &address.key {
None => {
entries.insert(address.slot.clone(), bytes(imported));
@@ -240,3 +359,15 @@ fn check(schema: &Schema, list: &SourceList, items: &[(Address, &ItemSource)]) -
}
Ok(())
}
+
+/// An item's variables, for its location's placeholders: its other fields, which must
+/// be text.
+fn variables(item: &ItemSource) -> Result<import::Variables> {
+ item.variables
+ .iter()
+ .map(|(name, value)| match value {
+ Value::String(text) => Ok((name.clone(), text.clone().into_bytes())),
+ other => bail!("variable {name} is {other}, not text"),
+ })
+ .collect()
+}
diff --git a/tests/receptor.rs b/tests/receptor.rs
index fb99497..170fbae 100644
--- a/tests/receptor.rs
+++ b/tests/receptor.rs
@@ -644,3 +644,101 @@ if env | grep -v '^PWD=\|^SHLVL=\|^_=\|^OLDPWD=' | grep -q .; then object "has a
assert!(plan.accepted, "{plan:?}");
assert!(!escaped.exists());
}
+
+/// Locations: a source declared once, in a file the source list includes, used by
+/// items with variables of their own; and the mistakes.
+#[test]
+fn pack_from_locations() {
+ let host = Host::new("locations");
+ let schema = host.schema(secrets_schema(&host));
+ let secrets = host.program("secrets", r#"printf '%s of %s\n' "$3" "$1""#);
+ std::fs::create_dir_all(host.root.join("shared")).unwrap();
+ std::fs::write(
+ host.root.join("shared/locations.json"),
+ json!({ "locations": { "secrets": {
+ "source": { "command": [secrets, "$(env:LOCATION_HOST)", "show", "$(var:key)"] }
+ } } })
+ .to_string(),
+ )
+ .unwrap();
+ let list = |items: Value| {
+ let path = host.root.join("sources.json");
+ std::fs::write(
+ &path,
+ json!({
+ "channel": "secrets",
+ "include": ["shared/locations.json"],
+ "items": items
+ })
+ .to_string(),
+ )
+ .unwrap();
+ path
+ };
+ // SAFETY: the tests here don't read the environment concurrently.
+ unsafe { std::env::set_var("LOCATION_HOST", "ru") };
+ let out = host.root.join("packed");
+ enstate::pack::pack(
+ &list(json!({
+ "a.key": { "location": "secrets", "key": "retiolum.ed25519_key.priv; rm -rf /" },
+ "a.pub": { "location": "secrets", "key": "retiolum.ed25519_key.pub" }
+ })),
+ &out,
+ Some(&schema.0),
+ )
+ .unwrap();
+ // The variable went in as one argument, as data.
+ assert_eq!(
+ std::fs::read(out.join("channels/secrets/a.key")).unwrap(),
+ b"retiolum.ed25519_key.priv; rm -rf / of ru\n"
+ );
+ assert_eq!(
+ std::fs::read(out.join("channels/secrets/a.pub")).unwrap(),
+ b"retiolum.ed25519_key.pub of ru\n"
+ );
+
+ let mistake = |items: Value| {
+ let out = host.root.join("mistake");
+ let _ = std::fs::remove_dir_all(&out);
+ format!(
+ "{:#}",
+ enstate::pack::pack(&list(items), &out, None).unwrap_err()
+ )
+ };
+ let said = mistake(json!({ "a.key": { "location": "nope", "key": "x" } }));
+ assert!(said.contains("no location nope"), "{said}");
+ let said = mistake(json!({ "a.key": { "location": "secrets" } }));
+ assert!(said.contains("key"), "{said}");
+ let said = mistake(json!({ "a.key": { "source": "env:X", "key": "x" } }));
+ assert!(said.contains("unknown fields key"), "{said}");
+ let said = mistake(json!({ "a.key": { "location": "secrets", "key": 5 } }));
+ assert!(said.contains("variable key is 5, not text"), "{said}");
+ std::fs::write(
+ host.root.join("shared/more.json"),
+ json!({ "locations": { "secrets": { "source": "env:X" } } }).to_string(),
+ )
+ .unwrap();
+ std::fs::write(
+ host.root.join("twice.json"),
+ json!({
+ "channel": "secrets",
+ "include": ["shared/locations.json", "shared/more.json"],
+ "items": {}
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let said = format!(
+ "{:#}",
+ enstate::pack::pack(
+ &host.root.join("twice.json"),
+ &host.root.join("twice"),
+ None
+ )
+ .unwrap_err()
+ );
+ assert!(
+ said.contains("location secrets is declared twice"),
+ "{said}"
+ );
+}