|
| 1 | +use std::fs; |
| 2 | +use std::io::Write; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +use anyhow::{Context, Result, bail}; |
| 6 | + |
| 7 | +/// Creates a directory (and any missing parents) that only the owner can |
| 8 | +/// access: mode 0700 on Unix, so other local users can't list saved chats, |
| 9 | +/// roles, cached responses, or the config that holds the API key. A no-op for |
| 10 | +/// permissions on non-Unix targets, which don't have this permission model. |
| 11 | +pub fn create_private_dir(path: &Path) -> Result<()> { |
| 12 | + fs::create_dir_all(path).with_context(|| format!("creating directory {}", path.display()))?; |
| 13 | + set_private_dir_permissions(path) |
| 14 | +} |
| 15 | + |
| 16 | +/// Writes `contents` to `path` with owner-only permissions (mode 0600 on Unix). |
| 17 | +/// The file is created 0600 from the start — not created world-readable and |
| 18 | +/// then narrowed — so a secret (the API key) is never briefly exposed. An |
| 19 | +/// existing file is also re-narrowed, migrating configs written by older |
| 20 | +/// versions that predate this hardening. |
| 21 | +pub fn write_private(path: &Path, contents: &str) -> Result<()> { |
| 22 | + let mut options = fs::OpenOptions::new(); |
| 23 | + options.write(true).create(true).truncate(true); |
| 24 | + #[cfg(unix)] |
| 25 | + { |
| 26 | + use std::os::unix::fs::OpenOptionsExt; |
| 27 | + options.mode(0o600); |
| 28 | + } |
| 29 | + let mut file = options |
| 30 | + .open(path) |
| 31 | + .with_context(|| format!("opening file {}", path.display()))?; |
| 32 | + file.write_all(contents.as_bytes()) |
| 33 | + .with_context(|| format!("writing file {}", path.display()))?; |
| 34 | + // `mode()` only applies when the file is newly created; enforce 0600 on a |
| 35 | + // pre-existing (possibly world-readable) file too. |
| 36 | + set_private_file_permissions(path) |
| 37 | +} |
| 38 | + |
| 39 | +/// Creates (truncating) a file for writing with owner-only permissions (mode |
| 40 | +/// 0600 on Unix) and returns the open handle, for callers that append to it |
| 41 | +/// over time rather than writing once. Like [`write_private`], the file is |
| 42 | +/// created 0600 from the start and any pre-existing file is re-narrowed. |
| 43 | +pub fn create_private_file(path: &Path) -> Result<fs::File> { |
| 44 | + let mut options = fs::OpenOptions::new(); |
| 45 | + options.write(true).create(true).truncate(true); |
| 46 | + #[cfg(unix)] |
| 47 | + { |
| 48 | + use std::os::unix::fs::OpenOptionsExt; |
| 49 | + options.mode(0o600); |
| 50 | + } |
| 51 | + let file = options |
| 52 | + .open(path) |
| 53 | + .with_context(|| format!("creating file {}", path.display()))?; |
| 54 | + set_private_file_permissions(path)?; |
| 55 | + Ok(file) |
| 56 | +} |
| 57 | + |
| 58 | +/// Rejects an identifier that is used verbatim as a filename under a storage |
| 59 | +/// directory. Chat ids and role names arrive from argv and are joined directly |
| 60 | +/// onto a base directory, so a value like `../../etc/passwd` or an absolute |
| 61 | +/// path would otherwise let a read/write/delete escape that directory. |
| 62 | +pub fn validate_identifier(kind: &str, name: &str) -> Result<()> { |
| 63 | + if name.is_empty() { |
| 64 | + bail!("{kind} name must not be empty"); |
| 65 | + } |
| 66 | + if name == "." || name == ".." { |
| 67 | + bail!("{kind} name {name:?} is not allowed"); |
| 68 | + } |
| 69 | + if name.contains('/') || name.contains('\\') || name.contains('\0') { |
| 70 | + bail!("{kind} name must not contain path separators or null bytes: {name:?}"); |
| 71 | + } |
| 72 | + Ok(()) |
| 73 | +} |
| 74 | + |
| 75 | +#[cfg(unix)] |
| 76 | +fn set_private_file_permissions(path: &Path) -> Result<()> { |
| 77 | + use std::os::unix::fs::PermissionsExt; |
| 78 | + fs::set_permissions(path, fs::Permissions::from_mode(0o600)) |
| 79 | + .with_context(|| format!("setting permissions on {}", path.display())) |
| 80 | +} |
| 81 | + |
| 82 | +#[cfg(unix)] |
| 83 | +fn set_private_dir_permissions(path: &Path) -> Result<()> { |
| 84 | + use std::os::unix::fs::PermissionsExt; |
| 85 | + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) |
| 86 | + .with_context(|| format!("setting permissions on {}", path.display())) |
| 87 | +} |
| 88 | + |
| 89 | +#[cfg(not(unix))] |
| 90 | +fn set_private_file_permissions(_path: &Path) -> Result<()> { |
| 91 | + Ok(()) |
| 92 | +} |
| 93 | + |
| 94 | +#[cfg(not(unix))] |
| 95 | +fn set_private_dir_permissions(_path: &Path) -> Result<()> { |
| 96 | + Ok(()) |
| 97 | +} |
| 98 | + |
| 99 | +#[cfg(test)] |
| 100 | +mod tests { |
| 101 | + use super::*; |
| 102 | + |
| 103 | + #[test] |
| 104 | + fn rejects_traversal_and_separators() { |
| 105 | + for bad in ["", ".", "..", "../etc", "a/b", "a\\b", "x\0y", "/abs"] { |
| 106 | + assert!(validate_identifier("chat", bad).is_err(), "{bad:?}"); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + #[test] |
| 111 | + fn accepts_ordinary_names() { |
| 112 | + for ok in ["temp", "my-chat", "ShellGPT", "Shell Command Generator", "a..b"] { |
| 113 | + assert!(validate_identifier("chat", ok).is_ok(), "{ok:?}"); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + #[cfg(unix)] |
| 118 | + #[test] |
| 119 | + fn written_file_is_owner_only() { |
| 120 | + use std::os::unix::fs::PermissionsExt; |
| 121 | + let path = std::env::temp_dir().join(format!("rgpt-fsutil-{}", std::process::id())); |
| 122 | + write_private(&path, "secret").unwrap(); |
| 123 | + let mode = std::fs::metadata(&path).unwrap().permissions().mode(); |
| 124 | + assert_eq!(mode & 0o777, 0o600); |
| 125 | + std::fs::remove_file(&path).ok(); |
| 126 | + } |
| 127 | +} |
0 commit comments