use std::path::Path;
pub fn restrict_file(path: &Path) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
}
#[cfg(windows)]
{
restrict_acl(path)
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
Ok(())
}
}
pub fn restrict_dir(path: &Path) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
}
#[cfg(windows)]
{
restrict_acl(path)
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
Ok(())
}
}
#[cfg(unix)]
pub fn set_create_mode(opts: &mut std::fs::OpenOptions) {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(not(unix))]
pub fn set_create_mode(_opts: &mut std::fs::OpenOptions) {}
#[cfg(windows)]
fn restrict_acl(path: &Path) -> std::io::Result<()> {
let username = std::env::var("USERNAME").map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
"USERNAME environment variable not set",
)
})?;
let run = || {
std::process::Command::new("icacls")
.arg(path.as_os_str())
.arg("/inheritance:r")
.arg("/grant:r")
.arg(format!("{username}:F"))
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
};
if run()?.success() || run()?.success() {
return Ok(());
}
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!(
"Failed to restrict permissions on {} via icacls",
path.display()
),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_restrict_file() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test_file.txt");
std::fs::write(&file_path, b"secret").unwrap();
restrict_file(&file_path).unwrap();
}
#[test]
fn test_restrict_dir() {
let dir = tempfile::tempdir().unwrap();
restrict_dir(dir.path()).unwrap();
}
#[test]
fn test_set_create_mode() {
let mut opts = std::fs::OpenOptions::new();
set_create_mode(&mut opts);
}
}