aboutsummaryrefslogtreecommitdiffstats
path: root/src/pack.rs
blob: dda4f6a8a235f4c115867ecc511e779c8ee39115 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! 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.  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<String>,
    pub items: BTreeMap<String, ItemSource>,
    #[serde(default)]
    pub groups: BTreeMap<String, GroupSpec>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ItemSource {
    #[serde(default)]
    pub source: Option<Value>,
    #[serde(default)]
    pub remove: bool,
    #[serde(default)]
    pub required: Option<bool>,
    #[serde(default)]
    pub group: Option<String>,
}

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()))
    }
}

/// 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("."));
    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");
        }
        items.push((address, item));
    }
    if let Some(schema) = schema {
        check(schema, &list, &items)?;
    }
    // Read every source before writing anything.
    let mut entries: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    let mut records: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
    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}"))?;
            if address.key.is_none() && importer.is_interpolation() {
                warnings.push(format!(
                    "item {address}: 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 imported = importer
                .fetch()
                .with_context(|| format!("item {address}: {}", 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<Importer> {
    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<u8> {
    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(())
}