nu_data/config/
config_trust.rs1use serde::Deserialize;
2use serde::Serialize;
3use sha2::{Digest, Sha256};
4use std::{io::Read, path::Path, path::PathBuf};
5
6use indexmap::IndexMap;
7use nu_errors::ShellError;
8
9#[derive(Deserialize, Serialize, Debug, Default)]
10pub struct Trusted {
11 pub files: IndexMap<String, Vec<u8>>,
12}
13
14impl Trusted {
15 pub fn new() -> Self {
16 Trusted {
17 files: IndexMap::new(),
18 }
19 }
20}
21
22pub fn is_file_trusted(nu_env_file: &Path, content: &[u8]) -> Result<bool, ShellError> {
23 let contentdigest = Sha256::digest(content).as_slice().to_vec();
24 let nufile = nu_path::canonicalize(nu_env_file)?;
25
26 let trusted = read_trusted()?;
27 Ok(trusted.files.get(&nufile.to_string_lossy().to_string()) == Some(&contentdigest))
28}
29
30pub fn read_trusted() -> Result<Trusted, ShellError> {
31 let config_path = crate::config::default_path_for(&Some(PathBuf::from("nu-env.toml")))?;
32
33 let mut file = std::fs::OpenOptions::new()
34 .read(true)
35 .create(true)
36 .write(true)
37 .open(config_path)
38 .map_err(|_| ShellError::untagged_runtime_error("Couldn't open nu-env.toml"))?;
39 let mut doc = String::new();
40 file.read_to_string(&mut doc)?;
41
42 let allowed = toml::de::from_str(&doc).unwrap_or_else(|_| Trusted::new());
43 Ok(allowed)
44}