Skip to content

Commit a77fc35

Browse files
eladynphotovoltex
andauthored
fix: credential file shouldn't be world readable (#1650)
* fix: credential file shouldn't be world readable * fix whitespace Co-authored-by: Felix Prillwitz <[email protected]> --------- Co-authored-by: Felix Prillwitz <[email protected]>
1 parent 414432a commit a77fc35

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

core/src/cache.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#[cfg(unix)]
2+
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
13
use std::{
24
cmp::Reverse,
35
collections::HashMap,
@@ -315,10 +317,14 @@ impl Cache {
315317

316318
// This closure is just convencience to enable the question mark operator
317319
let read = || -> Result<Credentials, Error> {
318-
let mut file = File::open(location)?;
319-
let mut contents = String::new();
320-
file.read_to_string(&mut contents)?;
321-
Ok(serde_json::from_str(&contents)?)
320+
let file = File::open(location)?;
321+
#[cfg(unix)]
322+
if file.metadata()?.mode() & 0o004 != 0 {
323+
warn!(
324+
"credential file {location:?} is currently world readable, consider using chmod 600 {location:?} to fix this"
325+
)
326+
}
327+
Ok(serde_json::from_reader(file)?)
322328
};
323329

324330
match read() {
@@ -336,10 +342,15 @@ impl Cache {
336342

337343
pub fn save_credentials(&self, cred: &Credentials) {
338344
if let Some(location) = &self.credentials_location {
339-
let result = File::create(location).and_then(|mut file| {
340-
let data = serde_json::to_string(cred)?;
341-
write!(file, "{data}")
342-
});
345+
let mut file = File::options();
346+
#[cfg(unix)]
347+
let file = file.mode(0o600);
348+
let result = file
349+
.create(true)
350+
.write(true)
351+
.truncate(true)
352+
.open(location)
353+
.and_then(|file| Ok(serde_json::to_writer(file, cred)?));
343354

344355
if let Err(e) = result {
345356
warn!("Cannot save credentials to cache: {e}")

0 commit comments

Comments
 (0)