Skip to main content

config_lib/
load.rs

1//! # Options for loading configuration
2//!
3//! [`LoadOptions`] holds the limits and the include policy that every load
4//! applies. The defaults are safe for files the application owns:
5//!
6//! - files larger than 16 MiB, and anything that is not a regular file
7//!   (a directory, a FIFO, a device), are refused;
8//! - NOML `include` may only read files inside the directory of the file
9//!   being loaded (or the current directory, for text);
10//! - NOML `${...}` references may expand the document to at most 64 MiB,
11//!   with at most 10,000 references and chains at most 32 references deep.
12//!
13//! [`LoadOptions::strict`] turns on strict NOML for files and hot reload as
14//! well: `include` and `env()` are refused (see
15//! [`Config::from_string_strict`](crate::Config::from_string_strict)).
16//!
17//! Since v1.4.0.
18
19use crate::error::{Error, Result};
20use std::io::{self, Read};
21use std::path::{Path, PathBuf};
22
23/// Default largest configuration file read: 16 MiB.
24pub const DEFAULT_MAX_FILE_SIZE: u64 = 16 * 1024 * 1024;
25
26/// Default largest size a NOML document may expand to through `${...}`:
27/// 64 MiB.
28pub const DEFAULT_MAX_EXPANDED_SIZE: u64 = 64 * 1024 * 1024;
29
30/// Default largest number of `${...}` references in one NOML document.
31pub const DEFAULT_MAX_EXPANSIONS: usize = 10_000;
32
33/// Default longest chain of `${...}` references (a reference to a value
34/// that is itself a reference, and so on).
35pub const DEFAULT_MAX_EXPANSION_DEPTH: usize = 32;
36
37/// Default largest number of files a NOML document may include, counted
38/// over every level.
39pub const DEFAULT_MAX_INCLUDES: usize = 64;
40
41/// Deepest nesting of NOML includes (an included file that includes another
42/// file, and so on). The same limit the noml crate applies.
43#[cfg(feature = "noml")]
44pub(crate) const MAX_INCLUDE_DEPTH: usize = 10;
45
46/// Limits and include policy for loading configuration.
47///
48/// Build with [`LoadOptions::new`] (the safe defaults) and the builder
49/// methods, then pass to [`Config::from_file_with`](crate::Config::from_file_with),
50/// [`Config::from_string_with`](crate::Config::from_string_with),
51/// [`ConfigBuilder::load_options`](crate::ConfigBuilder::load_options) or
52/// [`HotReloadConfig::from_file_with`](crate::hot_reload::HotReloadConfig::from_file_with).
53///
54/// # Examples
55///
56/// ```rust
57/// use config_lib::{Config, LoadOptions};
58///
59/// // Strict NOML for a file: no include, no env()
60/// let options = LoadOptions::new().strict(true);
61/// let config = Config::from_string_with("port = 8080", Some("conf"), &options)?;
62/// assert_eq!(config.get_or("port", 0u16), 8080);
63/// # Ok::<(), config_lib::Error>(())
64/// ```
65#[derive(Debug, Clone)]
66pub struct LoadOptions {
67    pub(crate) strict: bool,
68    pub(crate) include_dirs: Vec<PathBuf>,
69    pub(crate) includes_anywhere: bool,
70    pub(crate) max_file_size: u64,
71    pub(crate) max_includes: usize,
72    pub(crate) max_expanded_size: u64,
73    pub(crate) max_expansions: usize,
74    pub(crate) max_expansion_depth: usize,
75}
76
77impl Default for LoadOptions {
78    fn default() -> Self {
79        Self {
80            strict: false,
81            include_dirs: Vec::new(),
82            includes_anywhere: false,
83            max_file_size: DEFAULT_MAX_FILE_SIZE,
84            max_includes: DEFAULT_MAX_INCLUDES,
85            max_expanded_size: DEFAULT_MAX_EXPANDED_SIZE,
86            max_expansions: DEFAULT_MAX_EXPANSIONS,
87            max_expansion_depth: DEFAULT_MAX_EXPANSION_DEPTH,
88        }
89    }
90}
91
92impl LoadOptions {
93    /// The default options (see the [module documentation](self)).
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// Strict options: the defaults with [`LoadOptions::strict`] set.
99    pub fn strict_defaults() -> Self {
100        Self::default().strict(true)
101    }
102
103    /// Read NOML strictly: `include` and every function call (`env()`
104    /// included) are refused with [`Error::Parse`]. Other formats read only
105    /// their own text either way.
106    pub fn strict(mut self, strict: bool) -> Self {
107        self.strict = strict;
108        self
109    }
110
111    /// Whether NOML is read strictly.
112    pub fn is_strict(&self) -> bool {
113        self.strict
114    }
115
116    /// Also allow NOML includes of files inside `dir` (and its
117    /// subdirectories). The directory of the file being loaded is always
118    /// allowed. The check is made on the canonical path, so `..` and
119    /// symbolic links cannot leave the allowed directories.
120    pub fn allow_include_dir(mut self, dir: impl Into<PathBuf>) -> Self {
121        self.include_dirs.push(dir.into());
122        self
123    }
124
125    /// Allow NOML includes of any regular file the process can read. Not
126    /// recommended for files other users can write.
127    pub fn allow_includes_anywhere(mut self) -> Self {
128        self.includes_anywhere = true;
129        self
130    }
131
132    /// Largest file read, in bytes, for the configuration file and each
133    /// included file. Default [`DEFAULT_MAX_FILE_SIZE`].
134    pub fn max_file_size(mut self, bytes: u64) -> Self {
135        self.max_file_size = bytes;
136        self
137    }
138
139    /// Largest number of included files, over all levels. Default
140    /// [`DEFAULT_MAX_INCLUDES`].
141    pub fn max_includes(mut self, count: usize) -> Self {
142        self.max_includes = count;
143        self
144    }
145
146    /// Largest size, in bytes, a NOML document may expand to through
147    /// `${...}` references. Default [`DEFAULT_MAX_EXPANDED_SIZE`]. The size
148    /// is an estimate that counts a small overhead for every value, so it
149    /// is somewhat larger than the text of the values.
150    pub fn max_expanded_size(mut self, bytes: u64) -> Self {
151        self.max_expanded_size = bytes;
152        self
153    }
154
155    /// Largest number of `${...}` references in a NOML document, included
156    /// files counted. Default [`DEFAULT_MAX_EXPANSIONS`].
157    pub fn max_expansions(mut self, count: usize) -> Self {
158        self.max_expansions = count;
159        self
160    }
161
162    /// Longest chain of `${...}` references. Default
163    /// [`DEFAULT_MAX_EXPANSION_DEPTH`].
164    pub fn max_expansion_depth(mut self, depth: usize) -> Self {
165        self.max_expansion_depth = depth;
166        self
167    }
168}
169
170fn refuse(path: &Path, kind: io::ErrorKind, why: &str) -> Error {
171    Error::io(
172        path.display().to_string(),
173        io::Error::new(kind, why.to_string()),
174    )
175}
176
177/// Read a configuration file as text.
178///
179/// Refuses anything that is not a regular file and anything larger than
180/// `max` bytes. The size is checked before reading and again while reading,
181/// so a file that grows in between is still refused.
182pub(crate) fn read_file(path: &Path, max: u64) -> Result<String> {
183    let io_err = |e| Error::io(path.display().to_string(), e);
184    let meta = std::fs::metadata(path).map_err(io_err)?;
185    check_meta(path, &meta, max)?;
186    let file = std::fs::File::open(path).map_err(io_err)?;
187    let meta = file.metadata().map_err(io_err)?;
188    check_meta(path, &meta, max)?;
189    let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
190    file.take(max.saturating_add(1))
191        .read_to_end(&mut bytes)
192        .map_err(io_err)?;
193    finish(path, bytes, max)
194}
195
196/// Async version of [`read_file`]
197#[cfg(feature = "async")]
198pub(crate) async fn read_file_async(path: &Path, max: u64) -> Result<String> {
199    use tokio::io::AsyncReadExt;
200    let io_err = |e| Error::io(path.display().to_string(), e);
201    let meta = tokio::fs::metadata(path).await.map_err(io_err)?;
202    check_meta(path, &meta, max)?;
203    let file = tokio::fs::File::open(path).await.map_err(io_err)?;
204    let meta = file.metadata().await.map_err(io_err)?;
205    check_meta(path, &meta, max)?;
206    let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
207    file.take(max.saturating_add(1))
208        .read_to_end(&mut bytes)
209        .await
210        .map_err(io_err)?;
211    finish(path, bytes, max)
212}
213
214fn check_meta(path: &Path, meta: &std::fs::Metadata, max: u64) -> Result<()> {
215    if !meta.is_file() {
216        return Err(refuse(
217            path,
218            io::ErrorKind::InvalidInput,
219            "not a regular file",
220        ));
221    }
222    if meta.len() > max {
223        return Err(refuse(
224            path,
225            io::ErrorKind::InvalidData,
226            "file is larger than the size limit",
227        ));
228    }
229    Ok(())
230}
231
232fn finish(path: &Path, bytes: Vec<u8>, max: u64) -> Result<String> {
233    if bytes.len() as u64 > max {
234        return Err(refuse(
235            path,
236            io::ErrorKind::InvalidData,
237            "file is larger than the size limit",
238        ));
239    }
240    String::from_utf8(bytes)
241        .map_err(|_| refuse(path, io::ErrorKind::InvalidData, "file is not valid UTF-8"))
242}
243
244/// Where NOML includes are read from, for one load.
245#[cfg(feature = "noml")]
246#[derive(Debug, Clone)]
247pub(crate) struct IncludePolicy {
248    /// Directory relative includes in the top-level document resolve
249    /// against
250    pub(crate) base_dir: PathBuf,
251    /// Canonical directories an included file must be inside
252    roots: Vec<PathBuf>,
253    anywhere: bool,
254    pub(crate) max_file_size: u64,
255    pub(crate) max_includes: usize,
256}
257
258#[cfg(feature = "noml")]
259impl IncludePolicy {
260    /// The policy for a document read from `file`, or from text when `file`
261    /// is `None` (relative includes then resolve against the current
262    /// directory, as they always have).
263    pub(crate) fn new(file: Option<&Path>, options: &LoadOptions) -> Self {
264        let base_dir = match file.and_then(Path::parent) {
265            Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
266            _ => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
267        };
268        let mut roots = Vec::with_capacity(options.include_dirs.len() + 1);
269        roots.extend(std::fs::canonicalize(&base_dir).ok());
270        roots.extend(
271            options
272                .include_dirs
273                .iter()
274                .filter_map(|dir| std::fs::canonicalize(dir).ok()),
275        );
276        Self {
277            base_dir,
278            roots,
279            anywhere: options.includes_anywhere,
280            max_file_size: options.max_file_size,
281            max_includes: options.max_includes,
282        }
283    }
284
285    /// Resolve and read the file an `include` names.
286    ///
287    /// `from_dir` is the directory of the file holding the include. Returns
288    /// the canonical path and the text, or a fixed reason that never quotes
289    /// the path or the file's contents.
290    pub(crate) fn read(
291        &self,
292        from_dir: &Path,
293        include: &str,
294    ) -> std::result::Result<(PathBuf, String), &'static str> {
295        if include.starts_with("http://") || include.starts_with("https://") {
296            return Err("remote includes are not supported");
297        }
298        let joined = from_dir.join(include);
299        let canonical =
300            std::fs::canonicalize(&joined).map_err(|_| "the included file does not exist")?;
301        if !self.anywhere && !self.roots.iter().any(|root| canonical.starts_with(root)) {
302            return Err("the included file is outside the allowed directories");
303        }
304        let text = read_file(&canonical, self.max_file_size).map_err(|e| match e {
305            Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidInput => {
306                "the included path is not a regular file"
307            }
308            Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidData => {
309                "the included file is too large or not UTF-8"
310            }
311            _ => "the included file could not be read",
312        })?;
313        Ok((canonical, text))
314    }
315}