//! Making a submission from a source list (docs/design.md, section 10). //! //! ```json //! { //! "channel": "secrets", //! "complete": true, //! "items": { //! "retiolum.key": { "source": "cmd:secrets ${env:HOST} show retiolum.ed25519_key.priv" }, //! "tls.pem": { "source": { "file": "/etc/ssl/some.pem" }, "required": false }, //! "hosts/ne": { "source": { "file": "ne.json" }, "group": "ne" }, //! "hosts/wu": { "remove": true } //! }, //! "groups": { "ne": { "required": false } } //! } //! ``` //! //! An item is named `SLOT` (an entry) or `SLOT/KEY` (a record). Sources are those of //! 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. //! //! 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}; use anyhow::{Context, Result, anyhow, bail}; use config::import::{self, Format, Imported, Importer, Raw, Source}; use serde::Deserialize; use serde_json::{Map, Value}; use crate::content; use crate::name::{self, Address}; use crate::schema::Schema; use crate::submission::{self, GroupSpec, ItemSpec, Manifest, Op}; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct SourceList { pub channel: String, #[serde(default)] pub complete: bool, #[serde(default)] pub base: Option, pub items: BTreeMap, #[serde(default)] pub groups: BTreeMap, /// Sources declared once, by name, for items to use with variables of their own. #[serde(default)] pub locations: BTreeMap, /// Files of locations, relative to the source list. #[serde(default)] pub include: Vec, } /// 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, #[serde(default)] include: Vec, } #[derive(Debug, Deserialize)] pub struct ItemSource { #[serde(default)] pub source: Option, /// A location's name, instead of a source. #[serde(default)] pub location: Option, #[serde(default)] pub remove: bool, #[serde(default)] pub required: Option, #[serde(default)] pub group: Option, /// For an item with a location: its variables, the item's other fields. #[serde(flatten)] pub variables: BTreeMap, } /// The JSON, or TOML by the extension `.toml`, in `path`. fn read(path: &Path) -> Result { 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 { 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, seen: &mut Vec, ) -> 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> { let list = SourceList::load(path)?; 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.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)); } if let Some(schema) = schema { check(schema, &list, &items)?; } // Read every source before writing anything. let mut entries: BTreeMap> = BTreeMap::new(); let mut records: BTreeMap> = BTreeMap::new(); let mut specs = Vec::new(); let mut warnings = Vec::new(); for (address, item) in &items { // 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!( "{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(&variables) .with_context(|| format!("{what}: {}", importer.describe()))?; match &address.key { None => { entries.insert(address.slot.clone(), bytes(imported)); } Some(key) => { let value = match imported { Imported::Json(value) => value, other => serde_json::from_slice(&bytes(other)) .with_context(|| format!("item {address}: not JSON"))?, }; records .entry(address.slot.clone()) .or_default() .insert(key.clone(), value); } } } specs.push(ItemSpec { address: address.clone(), op: if item.remove { Op::Remove } else { Op::Set }, required: item.required, group: item.group.clone(), }); } if let Some(slot) = records.keys().find(|slot| entries.contains_key(*slot)) { bail!("slot {slot} is given both as a whole and by records"); } let manifest = Manifest { submission: submission::VERSION, channel: list.channel.clone(), complete: list.complete, base: list.base.clone(), items: specs, groups: list.groups, }; match std::fs::read_dir(out) { Ok(mut existing) => { if existing.next().is_some() { bail!("{} is not empty", out.display()); } } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error).with_context(|| format!("reading {}", out.display())), } let channel_dir = out.join(submission::CHANNELS).join(&list.channel); content::write_dir(&entries, &channel_dir, 0o600)?; for (slot, records) in &records { content::write_file( &channel_dir.join(slot), &content::from_records(records), 0o600, )?; } let mut manifest_bytes = serde_json::to_vec_pretty(&manifest)?; manifest_bytes.push(b'\n'); content::write_file(&out.join(submission::MANIFEST), &manifest_bytes, 0o600)?; // What was written is a submission the receptor reads. submission::Submission::load(out)?; Ok(warnings) } /// The importer `source` describes, in `dir`: raw for an entry, JSON for a record. fn importer(source: &Value, dir: &Path, entry: bool) -> Result { let mut importer = match source { Value::String(text) => match import::parse_argument(text) { Raw::Import(mut importer) => { importer.dir = Some(dir.to_owned()); importer } Raw::Literal(_) => { bail!("source {text:?} is neither env:, file:, cmd: nor text with placeholders") } }, Value::Object(table) => import::parse_table(table, dir)? .ok_or_else(|| anyhow!("source is not a table of env, file or command"))?, other => bail!("source {other} is neither a text nor a table"), }; if !matches!(importer.source, Source::Template(_)) { importer.format = if entry { Format::Raw } else { Format::Json }; } Ok(importer) } fn bytes(imported: Imported) -> Vec { match imported { Imported::Raw(bytes) => bytes, Imported::Text(text) => text.into_bytes(), Imported::Json(value) => value.to_string().into_bytes(), } } /// The source list against the schema: the channel, the slots, records only in keyed /// types, and for a complete submission every required slot given. fn check(schema: &Schema, list: &SourceList, items: &[(Address, &ItemSource)]) -> Result<()> { let Some(channel) = schema.channel(&list.channel) else { bail!("the schema has no channel {}", list.channel); }; for (address, _) in items { let Some(slot) = channel.slots.get(&address.slot) else { bail!("the schema has no slot {}", address.of_entry()); }; if address.key.is_some() && !crate::media::keyed(&slot.media_type) { bail!("item {address}: type {} holds no records", slot.media_type); } } if list.complete { for (slot, spec) in &channel.slots { let given = items .iter() .any(|(address, item)| address.slot == *slot && !item.remove); if spec.required && !given { bail!( "required slot {}/{slot} has no source, and the submission is complete", list.channel ); } } } Ok(()) } /// An item's variables, for its location's placeholders: its other fields, which must /// be text. fn variables(item: &ItemSource) -> Result { 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() }