Use sha2 crate for hashing

This commit is contained in:
Sam Hedin
2020-06-25 19:47:11 +02:00
parent ce23b3b96e
commit 31c85f71ff
5 changed files with 76 additions and 26 deletions

View File

@ -11,7 +11,7 @@ pub struct Autoenv;
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct Trusted {
pub files: IndexMap<String, String>,
pub files: IndexMap<String, Vec<u8>>,
}
impl Trusted {
pub fn new() -> Self {

View File

@ -4,8 +4,9 @@ use crate::{path, prelude::*};
use nu_errors::ShellError;
use nu_protocol::SyntaxShape;
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
use std::hash::{Hash, Hasher};
use std::{collections::hash_map::DefaultHasher, fs, path::PathBuf};
use std::{fs, path::PathBuf};
use sha2::{Digest, Sha256};
pub struct AutoenvTrust;
#[async_trait]
@ -45,20 +46,14 @@ impl WholeStreamCommand for AutoenvTrust {
}
};
let content = std::fs::read_to_string(&file_to_trust).or_else(|_| {
Err(ShellError::untagged_runtime_error(
"No .nu-env file in the given directory",
))
})?;
let content = std::fs::read(&file_to_trust)?;
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
let file_to_trust = file_to_trust.to_string_lossy().to_string();
let filename = file_to_trust.to_string_lossy().to_string();
let mut allowed = Trusted::read_trusted()?;
allowed
.files
.insert(file_to_trust, hasher.finish().to_string());
allowed.files.insert(
filename,
Sha256::digest(&content).as_slice().to_vec()
);
let config_path = config::default_path_for(&Some(PathBuf::from("nu-env.toml")))?;
let tomlstr = toml::to_string(&allowed).or_else(|_| {

View File

@ -2,11 +2,10 @@ use crate::commands::{self, autoenv::Trusted};
use commands::autoenv;
use indexmap::{IndexMap, IndexSet};
use nu_errors::ShellError;
use sha2::{Digest, Sha256};
use std::{
collections::hash_map::DefaultHasher,
ffi::OsString,
fmt::Debug,
hash::{Hash, Hasher},
path::{Path, PathBuf},
};
@ -34,13 +33,14 @@ impl DirectorySpecificEnvironment {
fn toml_if_directory_is_trusted(&self, wdirenv: &PathBuf) -> Result<toml::Value, ShellError> {
if let Some(trusted) = &self.trusted {
let content = std::fs::read_to_string(&wdirenv)?;
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
let content = std::fs::read(&wdirenv)?;
if trusted.files.get(wdirenv.to_str().unwrap_or(""))
== Some(&hasher.finish().to_string())
== Some(&Sha256::digest(&content).as_slice().to_vec())
{
let content = std::str::from_utf8(&content.as_slice()).or_else(|_| {
Err(ShellError::untagged_runtime_error(format!("Could not read {:?} as utf8 string", content)))
})?;
return Ok(content.parse::<toml::Value>().or_else(|_| {
Err(ShellError::untagged_runtime_error(format!(
"Could not parse {:?}. Is it well-formed?",