use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::auth::Session;
use crate::error::StorageError;
use super::CredentialStore;
#[derive(Debug)]
pub struct FileStore {
path: PathBuf,
}
impl FileStore {
#[must_use]
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
}
impl CredentialStore for FileStore {
fn load(&self) -> Result<Session, StorageError> {
match fs::read_to_string(&self.path) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Session::empty()),
Err(err) => Err(StorageError::Io(err)),
Ok(contents) => {
warn_if_permissions_are_loose(&self.path);
let (session, migrated) = Session::from_json_migrating(&contents)?;
if migrated {
super::migrate_and_verify(self, &session, "file");
}
Ok(session)
}
}
}
fn save(&self, session: &Session) -> Result<(), StorageError> {
if let Some(parent) = self.path.parent()
&& !parent.as_os_str().is_empty()
{
create_private_dir_all(parent)?;
}
let json = session.to_json()?;
write_private_atomically(&self.path, json.as_bytes())
}
fn clear(&self) -> Result<(), StorageError> {
let result = match fs::remove_file(&self.path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(StorageError::Io(err)),
};
remove_orphaned_temp_files(&self.path);
result
}
}
fn write_private_atomically(path: &Path, contents: &[u8]) -> Result<(), StorageError> {
let tmp_path = unique_temp_path(path);
let result = write_to_temp_and_rename(&tmp_path, path, contents);
if result.is_err() {
let _ = fs::remove_file(&tmp_path);
}
result.map_err(StorageError::Io)
}
fn write_to_temp_and_rename(tmp_path: &Path, path: &Path, contents: &[u8]) -> std::io::Result<()> {
let mut file = create_private_file(tmp_path)?;
file.write_all(contents)?;
file.sync_all()?;
fs::rename(tmp_path, path)?;
Ok(())
}
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
fn temp_file_prefix(path: &Path) -> String {
let base = path
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new("rusteero-session"));
format!("{}.", base.to_string_lossy())
}
fn unique_temp_path(path: &Path) -> PathBuf {
let counter = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
let file_name = format!(
"{}{}-{counter}.tmp",
temp_file_prefix(path),
std::process::id()
);
path.with_file_name(file_name)
}
fn remove_orphaned_temp_files(path: &Path) {
let parent = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
let prefix = temp_file_prefix(path);
let Ok(entries) = fs::read_dir(parent) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let has_tmp_extension = Path::new(&name)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("tmp"));
if name.starts_with(&prefix) && has_tmp_extension {
let _ = fs::remove_file(entry.path());
}
}
}
#[cfg(unix)]
fn create_private_file(path: &Path) -> std::io::Result<File> {
use std::os::unix::fs::OpenOptionsExt;
OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
}
#[cfg(not(unix))]
fn create_private_file(path: &Path) -> std::io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
#[cfg(unix)]
fn create_private_dir_all(parent: &Path) -> std::io::Result<()> {
use std::os::unix::fs::DirBuilderExt;
fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(parent)
}
#[cfg(not(unix))]
fn create_private_dir_all(parent: &Path) -> std::io::Result<()> {
fs::create_dir_all(parent)
}
#[cfg(unix)]
fn has_loose_permissions(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o077 != 0)
}
#[cfg(unix)]
fn warn_if_permissions_are_loose(path: &Path) {
if has_loose_permissions(path) {
tracing::warn!(
path = %path.display(),
"credential file has group/other-accessible permissions; expected owner-only (0600)"
);
}
}
#[cfg(not(unix))]
fn warn_if_permissions_are_loose(_path: &Path) {}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::fs;
use super::{CredentialStore, FileStore};
use crate::auth::Session;
use crate::error::StorageError;
#[test]
fn save_then_load_round_trips_the_session() {
let dir = tempfile::tempdir().expect("tempdir");
let store = FileStore::new(dir.path().join("cookies.json"));
let session = Session::from_token("tok-123");
store.save(&session).expect("save succeeds");
let loaded = store.load().expect("load succeeds");
assert_eq!(loaded.expose_token(), "tok-123");
assert!(loaded.is_valid());
}
#[test]
fn round_trip_through_v8_0_4_cookies_json_shape() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
let python_written = r#"{"session_id": "session_valid_id", "schema_version": 2}"#;
fs_write(&path, python_written);
let store = FileStore::new(&path);
let session = store.load().expect("load succeeds");
assert_eq!(session.expose_token(), "session_valid_id");
store.save(&session).expect("save succeeds");
let reloaded = store.load().expect("load succeeds");
assert_eq!(reloaded.expose_token(), "session_valid_id");
}
#[test]
fn load_migrates_a_legacy_record_and_the_migration_read_back_matches() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(
&path,
r#"{"session_id":"legacy-token","refresh_token":"rt-1","session_expiry":"2099-01-01T00:00:00"}"#,
);
let store = FileStore::new(&path);
let session = store
.load()
.expect("load succeeds, legacy record tolerated");
assert_eq!(session.expose_token(), "legacy-token");
let on_disk = fs::read_to_string(&path).expect("file still exists");
assert!(on_disk.contains("\"schema_version\":2"));
assert!(!on_disk.contains("refresh_token"));
assert!(!on_disk.contains("session_expiry"));
let reloaded = store.load().expect("second load succeeds");
assert_eq!(reloaded.expose_token(), "legacy-token");
}
#[test]
fn load_of_a_current_schema_record_is_not_treated_as_a_migration() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(&path, r#"{"session_id":"tok","schema_version":2}"#);
let store = FileStore::new(&path);
let before = fs::read_to_string(&path).expect("file exists");
let session = store.load().expect("load succeeds");
assert_eq!(session.expose_token(), "tok");
let after = fs::read_to_string(&path).expect("file still exists");
assert_eq!(
before, after,
"a current-schema record must not be rewritten"
);
}
#[cfg(unix)]
#[test]
fn save_replaces_a_symlink_at_the_destination_rather_than_following_it() {
let dir = tempfile::tempdir().expect("tempdir");
let real_target = dir.path().join("attacker-owned-target.json");
fs_write(&real_target, "should never be written to");
let cookie_path = dir.path().join("cookies.json");
std::os::unix::fs::symlink(&real_target, &cookie_path).expect("symlink created");
let store = FileStore::new(&cookie_path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds even though the destination is a symlink");
assert!(
!cookie_path.is_symlink(),
"save must replace the symlink, not write through it"
);
let target_contents =
fs::read_to_string(&real_target).expect("the original target file still exists");
assert_eq!(target_contents, "should never be written to");
}
#[cfg(unix)]
#[test]
fn save_creates_the_file_with_owner_only_permissions() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
let mode = std::fs::metadata(&path)
.expect("file exists")
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600, "expected owner-only permissions, got {mode:o}");
}
#[cfg(unix)]
#[test]
fn overwriting_an_existing_looser_file_still_ends_up_0600() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(&path, "{}");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
.expect("chmod succeeds");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
let mode = std::fs::metadata(&path)
.expect("file exists")
.permissions()
.mode()
& 0o777;
assert_eq!(
mode, 0o600,
"expected save() to tighten permissions, got {mode:o}"
);
}
#[test]
fn save_creates_missing_parent_directories() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("nested").join("dirs").join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
assert!(path.exists());
}
#[cfg(unix)]
#[test]
fn save_creates_every_missing_parent_directory_with_owner_only_permissions() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("nested").join("dirs").join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
for created in [dir.path().join("nested"), dir.path().join("nested/dirs")] {
let mode = fs::metadata(&created)
.expect("directory exists")
.permissions()
.mode()
& 0o777;
assert_eq!(
mode, 0o700,
"expected {created:?} to be owner-only, got {mode:o}"
);
}
}
#[cfg(unix)]
#[test]
fn has_loose_permissions_is_false_for_a_freshly_saved_file() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
assert!(!super::has_loose_permissions(&path));
}
#[cfg(unix)]
#[test]
fn has_loose_permissions_is_true_for_a_world_readable_file_and_load_still_succeeds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(&path, r#"{"session_id":"tok","schema_version":2}"#);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
.expect("chmod succeeds");
assert!(super::has_loose_permissions(&path));
let store = FileStore::new(&path);
let session = store.load().expect(
"a loosely-permissioned file must still load — this is a warning, not a failure",
);
assert_eq!(session.expose_token(), "tok");
}
#[test]
fn load_missing_file_returns_an_empty_session_not_an_error() {
let dir = tempfile::tempdir().expect("tempdir");
let store = FileStore::new(dir.path().join("does-not-exist.json"));
let session = store.load().expect("missing file is not an error");
assert!(!session.is_valid());
assert_eq!(session.expose_token(), "");
}
#[test]
fn load_malformed_json_returns_a_storage_error() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(&path, "not json");
let store = FileStore::new(&path);
let err = store.load().expect_err("malformed json is an error");
assert!(matches!(err, StorageError::Serde(_)));
}
#[test]
fn load_accepts_the_legacy_user_token_key() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs_write(&path, r#"{"user_token":"old_token_123","session_id":null}"#);
let store = FileStore::new(&path);
let session = store.load().expect("load succeeds");
assert_eq!(session.expose_token(), "old_token_123");
}
#[test]
fn clear_on_a_missing_file_is_ok() {
let dir = tempfile::tempdir().expect("tempdir");
let store = FileStore::new(dir.path().join("does-not-exist.json"));
store
.clear()
.expect("clearing a missing file is not an error");
}
#[test]
fn clear_removes_an_existing_file() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
assert!(path.exists());
store.clear().expect("clear succeeds");
assert!(!path.exists());
}
#[test]
fn clear_removes_a_stale_temporary_file_left_by_a_crashed_write() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect("save succeeds");
let orphan = dir.path().join("cookies.json.99999-7.tmp");
fs_write(&orphan, "leftover plaintext credential");
store.clear().expect("clear succeeds");
assert!(!path.exists());
assert!(
!orphan.exists(),
"clear() must remove orphaned temp files too, not just the main file"
);
}
#[test]
fn clear_with_no_file_and_no_orphan_is_still_ok() {
let dir = tempfile::tempdir().expect("tempdir");
let store = FileStore::new(dir.path().join("does-not-exist.json"));
store
.clear()
.expect("clearing with nothing on disk at all is not an error");
}
#[test]
fn failed_write_leaves_no_temporary_file_behind() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cookies.json");
fs::create_dir(&path).expect("create a directory at the target path");
let store = FileStore::new(&path);
store
.save(&Session::from_token("tok"))
.expect_err("rename onto an existing directory must fail");
let leftovers: Vec<OsString> = fs::read_dir(dir.path())
.expect("read dir")
.filter_map(Result::ok)
.map(|entry| entry.file_name())
.collect();
assert_eq!(
leftovers,
vec![OsString::from("cookies.json")],
"a failed write must not leave any temporary file behind, got {leftovers:?}"
);
}
#[test]
fn debug_only_ever_prints_the_path() {
let store = FileStore::new("/tmp/example/cookies.json");
let debug = format!("{store:?}");
assert!(debug.contains("cookies.json"));
}
fn fs_write(path: &std::path::Path, contents: &str) {
std::fs::write(path, contents).expect("write succeeds");
}
}