1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! Small helpers for writing files with restrictive (owner-only) permissions.
//!
//! On Unix these create/restrict files to `0o600` so secret-bearing artifacts
//! (the vault, its snapshots, the audit log) are never readable by other local
//! users — even transiently during an atomic write-then-rename. On non-Unix
//! platforms the mode bits are not meaningful, so these degrade to a plain
//! write / no-op (Windows ACLs inherit from the parent directory's DACL, which
//! is the platform-appropriate boundary).
use std::path::Path;
use crate::errors::SafeResult;
/// Write `contents` to `path`, creating (and truncating) the file with
/// owner-only `0o600` permissions on Unix.
pub fn write_owner_only(path: &Path, contents: &[u8]) -> SafeResult<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
file.write_all(contents)?;
file.flush()?;
}
#[cfg(not(unix))]
{
std::fs::write(path, contents)?;
}
Ok(())
}
/// Tighten an existing file to owner-only `0o600` on Unix. No-op elsewhere.
///
/// Used after an atomic rename to ensure a pre-existing destination file that
/// may have had looser permissions is brought down to owner-only.
pub fn set_owner_only(path: &Path) -> SafeResult<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
}
#[cfg(not(unix))]
{
let _ = path;
}
Ok(())
}