aboutsummaryrefslogtreecommitdiffstats
path: root/src/pack.rs
blob: 7870bd03d277125bbc0825f1086818c142322e89 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! 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, Serialize};
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>,
    /// 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 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(())
}

/// One thing that keeps a source list from making a submission: what, where, and, for
/// an item read by a location, which location with which variables.
#[derive(Debug, Clone, Serialize)]
pub struct Problem {
    /// `CHANNEL/SLOT` or `CHANNEL/SLOT/KEY`; the channel alone for the channel's.
    pub address: String,
    /// What kind: `no-channel`, `not-in-schema`, `no-records`, `no-item`, `item`,
    /// `no-location`, `source`, `unreadable`, `not-json`, `whole-and-records`.
    pub problem: &'static str,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub variables: BTreeMap<String, String>,
    /// The source, as written (its placeholders not replaced).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

impl std::fmt::Display for Problem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.address)?;
        if let Some(location) = &self.location {
            write!(f, " (location {location}")?;
            for (name, value) in &self.variables {
                write!(f, ", {name} {value}")?;
            }
            write!(f, ")")?;
        }
        write!(f, ": {}", self.message)
    }
}

/// What a source list would make, and what keeps it from it.
#[derive(Debug, Clone, Serialize)]
pub struct Report {
    pub channel: String,
    /// Its items.
    pub items: usize,
    pub problems: Vec<Problem>,
    pub warnings: Vec<String>,
}

/// A source list read, its sources fetched.
struct Gathered {
    list: SourceList,
    report: Report,
    entries: BTreeMap<String, Vec<u8>>,
    records: BTreeMap<String, Map<String, Value>>,
    specs: Vec<ItemSpec>,
}

/// Reads the source list at `path` and every source in it, checked against `schema` if
/// one is given, and writes nothing: every problem, not just the first.
pub fn dry_run(path: &Path, schema: Option<&Schema>) -> Result<Report> {
    Ok(gather(path, schema)?.report)
}

/// 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; refused, with every
/// problem, if there are any.  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 Gathered {
        list,
        report,
        entries,
        records,
        specs,
    } = gather(path, schema)?;
    if !report.problems.is_empty() {
        let problems: Vec<String> = report.problems.iter().map(|p| format!("  {p}")).collect();
        bail!(
            "{} can't make a submission:\n{}",
            path.display(),
            problems.join("\n")
        );
    }
    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(report.warnings)
}

fn gather(path: &Path, schema: Option<&Schema>) -> Result<Gathered> {
    let list = SourceList::load(path)?;
    let dir = dir_of(path);
    name::check("channel", &list.channel)?;
    let mut problems = Vec::new();
    let problem = |address: String, problem: &'static str, message: String| Problem {
        address,
        problem,
        message,
        location: None,
        variables: BTreeMap::new(),
        source: None,
    };
    let mut items = Vec::new();
    for (key, item) in &list.items {
        let written = format!("{}/{key}", list.channel);
        let address: Address = match written.parse() {
            Ok(address) => address,
            Err(error) => {
                problems.push(problem(written, "item", format!("{error:#}")));
                continue;
            }
        };
        let mistake = if item.source.is_some() && item.location.is_some() {
            Some("give a source or a location, not both".to_owned())
        } else if item.location.is_none() && !item.variables.is_empty() {
            let fields: Vec<_> = item.variables.keys().map(String::as_str).collect();
            Some(format!(
                "unknown fields {} (variables are for an item with a location)",
                fields.join(", ")
            ))
        } else if item.remove == (item.source.is_some() || item.location.is_some()) {
            Some("give either a source (or a location) or \"remove\": true".to_owned())
        } else {
            None
        };
        match mistake {
            Some(message) => problems.push(problem(address.to_string(), "item", message)),
            None => items.push((address, item)),
        }
    }
    // Against the schema.
    let mut unusable: Vec<Address> = Vec::new();
    if let Some(schema) = schema {
        match schema.channel(&list.channel) {
            None => problems.push(problem(
                list.channel.clone(),
                "no-channel",
                format!("the schema has no channel {}", list.channel),
            )),
            Some(channel) => {
                for (address, _) in &items {
                    match channel.slots.get(&address.slot) {
                        None => {
                            problems.push(problem(
                                address.to_string(),
                                "not-in-schema",
                                format!("the schema has no slot {}", address.of_entry()),
                            ));
                            unusable.push(address.clone());
                        }
                        Some(slot)
                            if address.key.is_some() && !crate::media::keyed(&slot.media_type) =>
                        {
                            problems.push(problem(
                                address.to_string(),
                                "no-records",
                                format!("type {} holds no records", slot.media_type),
                            ));
                            unusable.push(address.clone());
                        }
                        Some(_) => {}
                    }
                }
                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 {
                            problems.push(problem(
                                format!("{}/{slot}", list.channel),
                                "no-item",
                                "required by the schema, but the source list, which is \
                                 complete, has no item for it"
                                    .to_owned(),
                            ));
                        }
                    }
                }
            }
        }
    }
    // Every source, even after a problem, so that all of them show.
    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 {
        specs.push(ItemSpec {
            address: address.clone(),
            op: if item.remove { Op::Remove } else { Op::Set },
            required: item.required,
            group: item.group.clone(),
        });
        if unusable.contains(address) {
            continue;
        }
        let mut problem_here = |kind: &'static str, message: String, source: Option<String>| {
            let mut found = problem(address.to_string(), kind, message);
            found.location = item.location.clone();
            found.variables = item
                .variables
                .iter()
                .map(|(name, value)| match value {
                    Value::String(text) => (name.clone(), text.clone()),
                    other => (name.clone(), other.to_string()),
                })
                .collect();
            found.source = source;
            problems.push(found);
        };
        // The item's own source, or its location's with its variables.
        let (source, source_dir) = match (&item.source, &item.location) {
            (Some(source), _) => (source, dir.as_path()),
            (None, Some(name)) => match list.locations.get(name) {
                Some(location) => (&location.source, location.dir.as_path()),
                None => {
                    problem_here("no-location", format!("no location {name}"), None);
                    continue;
                }
            },
            (None, None) => continue,
        };
        let importer = match importer(source, source_dir, address.key.is_none()) {
            Ok(importer) => importer,
            Err(error) => {
                problem_here("source", format!("{error:#}"), None);
                continue;
            }
        };
        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 fetched = variables(item).and_then(|variables| importer.fetch_with(&variables));
        let imported = match fetched {
            Ok(imported) => imported,
            Err(error) => {
                problem_here(
                    "unreadable",
                    format!("can't be read: {error:#}"),
                    Some(importer.describe()),
                );
                continue;
            }
        };
        match &address.key {
            None => {
                entries.insert(address.slot.clone(), bytes(imported));
            }
            Some(key) => {
                let value = match imported {
                    Imported::Json(value) => value,
                    other => match serde_json::from_slice(&bytes(other)) {
                        Ok(value) => value,
                        Err(error) => {
                            problem_here(
                                "not-json",
                                format!("not JSON: {error}"),
                                Some(importer.describe()),
                            );
                            continue;
                        }
                    },
                };
                records
                    .entry(address.slot.clone())
                    .or_default()
                    .insert(key.clone(), value);
            }
        }
    }
    for slot in records.keys().filter(|slot| entries.contains_key(*slot)) {
        problems.push(problem(
            format!("{}/{slot}", list.channel),
            "whole-and-records",
            "given both as a whole and by records".to_owned(),
        ));
    }
    let report = Report {
        channel: list.channel.clone(),
        items: list.items.len(),
        problems,
        warnings,
    };
    Ok(Gathered {
        list,
        report,
        entries,
        records,
        specs,
    })
}

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

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