Skip to main content

sequoia_cryptoki/
config.rs

1//! Configuration model and file parsing.
2
3use std::{
4    collections::HashSet,
5    fs,
6    io,
7    path::{Path, PathBuf},
8    sync::Mutex,
9};
10
11use aho_corasick::AhoCorasick;
12use anyhow::Context as _;
13
14use toml_edit::{
15    DocumentMut,
16    Item,
17    Table,
18    Value,
19};
20use crate::toml_edit_tree::Node;
21
22use sequoia_directories::Component;
23use sequoia_directories::Home;
24
25use crate::Result;
26
27/// A configuration.
28///
29/// To get a configuration, you normally convert a parsed
30/// configuration file to a configuration using
31/// [`ConfigFile::to_config`].
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Config {
34    /// The PKCS#11 modules.
35    modules: Vec<PathBuf>,
36}
37
38impl Default for Config {
39    fn default() -> Self {
40        Config {
41            modules: Vec::new(),
42        }
43    }
44}
45
46impl Config {
47    /// Returns the PKCS#11 modules that should be loaded.
48    pub fn modules(&self) -> &[PathBuf] {
49        &self.modules
50    }
51
52    /// Converts the configuration to a configuration file.
53    ///
54    /// Warning: Don't update a configuration file by reading it
55    /// using, e.g., [`ConfigFile::parse_home`], converting it back to
56    /// a [`ConfigFile`] using this function, and then writing it to
57    /// disk.  That is a lossy operation: it loses comments, and any
58    /// `ignore_invalid` values.
59    pub fn to_config_file(&self) -> Result<ConfigFile> {
60        // Start with an empty document.
61        let mut doc = DocumentMut::new();
62
63        // Add the values.
64
65        // modules.
66        doc.as_table_mut()
67            .insert("modules", Item::ArrayOfTables(Default::default()));
68
69        let modules = doc
70            .get_mut("modules").expect("created")
71            .as_array_of_tables_mut().expect("invalid type");
72        for file_name in self.modules.iter() {
73            let mut table = Table::new();
74            table.set(
75                &"path".into(),
76                file_name.to_str()
77                    .ok_or_else(|| {
78                        anyhow::anyhow!("Path ({}) is not valid UTF-8",
79                                         file_name.display())
80                    })?
81                    .into())?;
82
83            modules.push(table);
84        }
85
86        // Double check that it is well-formed.
87        let mut config = Config::default();
88        apply_schema(&mut Some(&mut config), None, doc.iter(),
89                     TOP_LEVEL_SCHEMA)?;
90
91        Ok(ConfigFile {
92            doc,
93            config: Mutex::new(Some(config.clone())),
94        })
95    }
96
97    /// Adds the specified module to the set of PKCS#11 modules to
98    /// load.
99    pub fn add_module<P>(&mut self, path: P) -> &mut Self
100        where P: Into<PathBuf>
101    {
102        self.modules.push(path.into());
103        self
104    }
105
106    /// Adds the specified modules to the set of PKCS#11 modules to
107    /// load.
108    pub fn extend_modules<P>(&mut self, paths: impl Iterator<Item=P>)
109        -> &mut Self
110    where P: Into<PathBuf>
111    {
112        self.modules.extend(paths.map(|p| p.into()));
113        self
114    }
115}
116
117/// A validated configuration file.
118///
119/// This structure contains the raw document tree.
120///
121/// # Examples
122///
123/// ```toml
124/// [[modules]]
125/// path = "/some/pkcs11/libmod.so"
126///
127/// [[modules]]
128/// path = "/other/pkcs11/libmod.so"
129/// ```
130#[derive(Debug, Default)]
131pub struct ConfigFile {
132    doc: DocumentMut,
133    config: Mutex<Option<Config>>,
134}
135
136impl Clone for ConfigFile {
137    fn clone(&self) -> Self {
138        if let Ok(config) = self.config.try_lock() {
139            Self {
140                doc: self.doc.clone(),
141                config: Mutex::new(config.clone()),
142            }
143        } else {
144            Self {
145                doc: self.doc.clone(),
146                config: Mutex::new(None),
147            }
148        }
149    }
150}
151
152impl ConfigFile {
153    /// A template for the configuration containing the default
154    /// values.
155    const TEMPLATE: &'static str = "\
156# Configuration template for sq-cryptoki <SQ-CRYPTOKI-VERSION>
157<SQ-CRYPTOKI-CONFIG-PATH-HINT>
158
159# [[module]]
160# path = \"/path/to/some/pkcs11/module\"
161#
162# [[module]]
163# path = \"/path/to/another/pkcs11/module\"
164";
165
166    /// Patterns to match on in `Self::DEFAULT` to be replaced with
167    /// the default values.
168    const TEMPLATE_PATTERNS: &'static [&'static str] = &[
169        "<SQ-CRYPTOKI-VERSION>",
170        "<SQ-CRYPTOKI-CONFIG-PATH-HINT>",
171    ];
172
173    /// Returns a configuration template with the defaults.
174    ///
175    /// The specified file is not actually read.  Instead, it embedded
176    /// in configuration file as a comment so that the user can figure
177    /// out where to save the template.
178    ///
179    /// If `path_hint` is `None`, no hint is embedded in the
180    /// configuration file.
181    fn config_template(path_hint: Option<&Path>) -> Result<String> {
182        let ac = AhoCorasick::new(Self::TEMPLATE_PATTERNS)?;
183
184        let mut path_hint = path_hint;
185        let path_hint_;
186        if let Some(ph) = path_hint.as_ref() {
187            if let Some(home) = dirs::home_dir() {
188                let home = home.display().to_string();
189                if let Ok(rest) = ph.strip_prefix(&home) {
190                    path_hint_ = PathBuf::from("$HOME").join(rest);
191                    path_hint = Some(path_hint_.as_ref());
192                }
193            }
194        };
195
196        Ok(ac.replace_all(Self::TEMPLATE, &[
197            &env!("CARGO_PKG_VERSION").to_string(),
198            &if let Some(path_hint) = path_hint {
199                format!(
200                    "\n\
201                     # To use it, edit it to your liking and write it to\n\
202                     # {}",
203                    &path_hint.display())
204            } else {
205                "".into()
206            }
207        ]))
208    }
209
210    /// Returns the default configuration in template form.
211    ///
212    /// All the configuration options with their defaults are
213    /// commented out.
214    ///
215    /// The configuration file from the specified home directory is
216    /// not read; the home directory is just used to determine the
217    /// location of the configuration file, which is embedded in the
218    /// returned configuration file as a hint.
219    ///
220    /// If `home` is `None`, no hint about the location of the
221    /// configuration file is embedded in the returned template.
222    pub fn default_template(home: Option<&Home>) -> Result<Self> {
223        Self::parse_str(&Self::config_template(home.map(Self::file_name).as_deref())?)
224    }
225
226    /// Returns the absolute path of the config file for the specified
227    /// home directory.
228    pub fn file_name(home: &Home) -> PathBuf {
229        home.config_dir(Component::Keystore)
230            .join("cryptoki")
231            .join("config.toml")
232    }
233
234    /// Reads and validates the configuration file from the default
235    /// home directory.
236    ///
237    /// If the configuration file does not exist, the default
238    /// configuration file is returned.  Any other error that occurs
239    /// while reading the configuration is propagated to the caller.
240    pub fn parse_default_home() -> Result<Self> {
241        if let Some(home) = sequoia_directories::Home::default() {
242            Self::parse_home(home)
243        } else {
244            Err(anyhow::anyhow!("Platform does not have a default home directory"))
245        }
246    }
247
248    /// Reads and validates the configuration file from the specified
249    /// home directory.
250    ///
251    /// If the configuration file does not exist, the default
252    /// configuration file is returned.  Any other error that occurs
253    /// while reading the configuration is propagated to the caller.
254    pub fn parse_home(home: &Home) -> Result<Self> {
255        Self::parse_file(&Self::file_name(home))
256    }
257
258    /// Reads and validates the configuration file from the specified
259    /// file.
260    ///
261    /// The file must contain a valid toml document, which is
262    /// consistent with the schema.
263    ///
264    /// If the file does not exist, the default configuration file (as
265    /// returned by is used.  Any other error that occurs while
266    /// reading the configuration is propagated to the caller.
267    pub fn parse_file(path: &Path) -> Result<Self> {
268        let config = match fs::read_to_string(&path) {
269            Ok(r) => r,
270            Err(e) if e.kind() == io::ErrorKind::NotFound =>
271                Self::config_template(Some(path))?,
272            Err(e) => return Err(anyhow::Error::from(e).context(
273                format!("Reading configuration file {} failed",
274                        path.display()))),
275        };
276
277        Self::parse_str(&config)
278            .with_context(|| {
279                format!("Reading configuration file {}", path.display())
280            })
281    }
282
283    /// Reads and validates the configuration.
284    ///
285    /// The string must contain a valid toml document, which is
286    /// consistent with the schema.
287    pub fn parse_str(config: &str) -> Result<Self> {
288        let doc: DocumentMut = config.parse()
289            .context("Parsing configuration failed")?;
290
291        let mut config = Config::default();
292        apply_schema(&mut Some(&mut config), None, doc.iter(), TOP_LEVEL_SCHEMA)
293            .context("Parsing configuration failed")?;
294
295        Ok(Self {
296            doc,
297            config: Mutex::new(Some(config)),
298        })
299    }
300
301    /// Writes the configuration to the home directory.
302    pub fn persist_to_home(&self, home: &Home) -> Result<()> {
303        let path = Self::file_name(home);
304        self.persist(path)
305    }
306
307    /// Writes the configuration to the specified file.
308    pub fn persist<P>(&self, path: P) -> Result<()>
309    where P: AsRef<Path>
310    {
311        let path = path.as_ref();
312        let dir = path.parent().unwrap();
313
314        fs::create_dir_all(dir)?;
315
316        let mut t = tempfile::NamedTempFile::new_in(dir)?;
317        self.dump(&mut t)?;
318        t.persist(path)?;
319
320        Ok(())
321    }
322
323    /// Writes the configuration to the given writer.
324    pub fn dump(&self, sink: &mut dyn io::Write) -> Result<()> {
325        write!(sink, "{}", self.doc.to_string())?;
326        Ok(())
327    }
328
329    /// Return a `Config` based on the parsed configuration file.
330    ///
331    /// This function is falliable, because a caller that modifies the
332    /// document returned by [`ConfigFile::as_item_mut`] may modify
333    /// the configuration to be invalid.
334    pub fn to_config(&self) -> Result<Config> {
335        let config = self.config.lock().unwrap();
336
337        if let Some(config) = config.as_ref() {
338            Ok(config.clone())
339        } else {
340            let mut c = Default::default();
341            apply_schema(&mut Some(&mut c), None, self.doc.iter(),
342                         TOP_LEVEL_SCHEMA)?;
343            Ok(c)
344        }
345    }
346
347    /// Returns the document tree.
348    pub fn as_item(&self) -> &Item {
349        self.doc.as_item()
350    }
351
352    /// Returns the mutable document tree.
353    ///
354    /// This allows the caller to modify the configuration file
355    /// directly.  As such, the resulting configuration may no longer
356    /// be valid.
357    pub fn as_item_mut(&mut self) -> &mut Item {
358        // Invalidate the parsed configuration.
359        *self.config.lock().unwrap() = None;
360        self.doc.as_item_mut()
361    }
362}
363
364/// Validates a configuration section using a schema, and optionally
365/// applies changes to the configuration.
366///
367/// Returns an error if a key is unknown and not explicitly ignored.
368///
369/// `schema`'s keys must be lowercase, and sorted.
370fn apply_schema<'toml>(config: &mut Option<&mut Config>,
371                       path: Option<&str>,
372                       section: toml_edit::Iter<'toml>,
373                       schema: Schema) -> Result<()> {
374    let section = section.collect::<Vec<_>>();
375    let known_keys: Vec<_> =
376        schema.iter().map(|(key, _)| *key).collect();
377
378    // Schema keys better be lowercase.
379    debug_assert!(known_keys.iter().all(|&s| &s.to_lowercase() == s),
380                  "keys in schema must be lowercase");
381
382    // Schema keys better be sorted.
383    debug_assert!(known_keys.windows(2).all(|v| v[0] <= v[1]),
384                  "keys in schema must be sorted");
385    // XXX: once [].is_sorted is stabilized:
386    // debug_assert!(known_keys.is_sorted(), "keys in schema must be sorted");
387
388    let prefix = if let Some(path) = path {
389        format!("{}.", path)
390    } else {
391        "".to_string()
392    };
393
394    let keys: HashSet<&str> = section
395        .iter().map(|(key, _value)| *key)
396        .collect();
397
398    // The set of allowed keys are the known keys, plus
399    // "ignore_invalid", and the value of "ignore_invalid".
400    let mut allowed_keys: Vec<&str> = known_keys.to_vec();
401    if let Some(ignore) = section.iter()
402        .find_map(|(k, v)| (*k == "ignore_invalid").then_some(*v))
403    {
404        allowed_keys.push("ignore_invalid");
405        match ignore {
406            Item::Value(Value::String(k)) =>
407                allowed_keys.push(k.value().as_str()),
408            Item::Value(Value::Array(ks)) => {
409                for k in ks {
410                    if let Value::String(k) = k {
411                        allowed_keys.push(k.value().as_str());
412                    } else {
413                        Err(Error::ParseError(format!(
414                            "'{}ignore_invalid' takes a string \
415                             or an array of strings",
416                            prefix)))?
417                    }
418                }
419            }
420            _ => {
421                return Err(Error::ParseError(format!(
422                    "Invalid value for '{}ignore_invalid': {}, \
423                     expected a string or an array of strings",
424                    prefix, ignore)).into());
425            }
426        }
427    }
428
429    // Now check if there are any unknown sections.
430    let unknown_keys = keys
431        .difference(&allowed_keys.into_iter().collect())
432        .map(|s| *s)
433        .collect::<Vec<_>>();
434    if ! unknown_keys.is_empty() {
435        return Err(Error::ParseError(format!(
436            "{} has unknown keys: {}, valid keys are: {}",
437            if let Some(path) = path {
438                path
439            } else {
440                "top-level section"
441            },
442            unknown_keys.join(", "),
443            // We don't include the keys listed in ignore_invalid.
444            known_keys.join(", "))).into());
445    }
446
447    // Now validate the values.
448    for (key, value) in &section {
449        if let Ok(i) = schema.binary_search_by_key(key, |(k, _)| k) {
450            let apply = schema[i].1;
451            (apply)(config, &format!("{}{}", prefix, key), value)
452                .with_context(|| format!("Error validating {:?}", key))?;
453        }
454    }
455
456    Ok(())
457}
458
459/// Errors used in this module.
460///
461/// Note: This enum cannot be exhaustively matched to allow future
462/// extensions.
463#[non_exhaustive]
464#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
465pub enum Error {
466    /// Parse error
467    #[error("Parse error: {0}")]
468    ParseError(String),
469
470    #[error("Configuration item {0:?} is not a {1} but a {2}")]
471    BadType(String, &'static str, &'static str),
472}
473
474impl Error {
475    /// Returns an `Error::BadType` given an item.
476    fn bad_item_type(path: &str, i: &Item, want_type: &'static str)
477                     -> anyhow::Error
478    {
479        Error::BadType(path.into(), want_type, i.type_name()).into()
480    }
481
482    /// Returns an `Error::BadType` given a value.
483    #[allow(unused)]
484    fn bad_value_type(path: &str, v: &Value, want_type: &'static str)
485                      -> anyhow::Error
486    {
487        Error::BadType(path.into(), want_type, v.type_name()).into()
488    }
489}
490
491/// A function that validates a node in the configuration tree with
492/// the given path, and optionally adds it to the configuration.
493type Applicator = fn(&mut Option<&mut Config>, &str, &Item)
494                     -> Result<()>;
495
496/// Ignores a node.
497#[allow(unused)]
498fn apply_nop(_: &mut Option<&mut Config>,
499             _: &str, _: &Item)
500             -> Result<()>
501{
502    Ok(())
503}
504
505/// A [`Schema`] maps keys to [`Applicator`]s.
506type Schema = &'static [(&'static str, Applicator)];
507
508/// Schema for the toplevel.
509const TOP_LEVEL_SCHEMA: Schema = &[
510    ("modules", apply_modules),
511];
512
513/// Schema for the `modules` section.
514const MODULES_SCHEMA: Schema = &[
515    ("path", apply_modules_path),
516];
517
518/// Validates the `modules` array of tables.
519fn apply_modules(config: &mut Option<&mut Config>,
520                 path: &str, item: &Item)
521            -> Result<()>
522{
523    let tables = item.as_array_of_tables()
524        .ok_or_else(|| Error::bad_item_type(path, item, "array of tables"))?;
525    for (i, table) in tables.iter().enumerate() {
526        let path = format!("{}.{}", path, i);
527        apply_schema(config, Some(&path), table.iter(), MODULES_SCHEMA)?;
528    }
529    Ok(())
530}
531
532/// Validates the `modules.path` value.
533fn apply_modules_path(config: &mut Option<&mut Config>,
534                      path: &str, item: &Item)
535                      -> Result<()>
536{
537    let path = item.as_str()
538        .ok_or_else(|| Error::bad_item_type(path, item, "string"))?;
539
540    if let Some(config) = config {
541        config.modules.push(path.into());
542    }
543
544    Ok(())
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    use toml_edit::Array;
552    use toml_edit::Formatted;
553
554    /// Checks that the configuration template matches the default
555    /// configuration.
556    #[test]
557    fn default_template_is_default() {
558        let default_template
559            = ConfigFile::default_template(None).expect("invalid template")
560            .to_config().expect("invalid template");
561
562        assert_eq!(Config::default(), default_template);
563    }
564
565    /// Checks that a configure file is parsed correctly.
566    #[test]
567    fn config_file() {
568        let modules = [ "/some/pkcs11.dll", "/other/pkcs11.dll" ];
569
570        // A valid config with two modules.
571        let base = modules.iter()
572            .map(|module| {
573                format!("\
574[[modules]]
575path = \"{}\"", module)
576            })
577            .collect::<Vec<String>>()
578            .join("\n");
579
580        let config = ConfigFile::parse_str(&base)
581            .expect("invalid template")
582            .to_config()
583            .expect("invalid template");
584
585        let modules = modules
586            .into_iter()
587            .map(PathBuf::from).collect::<Vec<PathBuf>>();
588        assert_eq!(&config.modules(), &modules);
589
590        let invalid = format!("{}
591foo = \"blah\"", base);
592        assert!(ConfigFile::parse_str(&invalid).is_err());
593
594        let ignore_invalid = format!("{}
595ignore_invalid = [ \"foo\", \"nonexistent\" ]", invalid);
596        let config = ConfigFile::parse_str(&ignore_invalid)
597            .expect("invalid template")
598            .to_config()
599            .expect("invalid template");
600
601        assert_eq!(&config.modules(), &modules);
602    }
603
604    /// Checks that a configure file is parsed correctly.
605    #[test]
606    fn modify_config_file() {
607        let modules = [ "/some/pkcs11.dll", "/other/pkcs11.dll" ];
608
609        // A valid config with two modules.
610        let base = modules.iter()
611            .map(|module| {
612                format!("\
613[[modules]]
614path = \"{}\"", module)
615            })
616            .collect::<Vec<String>>()
617            .join("\n");
618
619        let mut config_file = ConfigFile::parse_str(&base)
620            .expect("invalid template");
621
622        let config = config_file
623            .to_config()
624            .expect("invalid template");
625
626        let modules = modules
627            .into_iter()
628            .map(PathBuf::from).collect::<Vec<PathBuf>>();
629        assert_eq!(&config.modules(), &modules);
630
631        // Add an unknown key to the configuration document and make
632        // sure ConfigFile::to_config fails to reparse it.
633        let doc = config_file.as_item_mut();
634        doc.set(&"foo".into(), Value::String(Formatted::new("bar".to_string())))
635            .expect("couldn't set");
636
637        assert!(config_file.to_config().is_err());
638
639        // Add the key to ignore_invalid.
640        let doc = config_file.as_item_mut();
641        let mut ignore_invalid = Array::new();
642        ignore_invalid.push("foo");
643        doc.set(&"ignore_invalid".into(), Value::Array(ignore_invalid))
644            .expect("couldn't set");
645
646        let config = config_file
647            .to_config()
648            .expect("invalid template");
649
650        let modules = modules
651            .into_iter()
652            .map(PathBuf::from).collect::<Vec<PathBuf>>();
653        assert_eq!(&config.modules(), &modules);
654    }
655}