The headless browser for AI agents and web scraping
fix(net): keep the cookie store private and report failed saves (#1512)
Kristofer Jussmann1b259b95bece
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rsindex 8fc4ce14..28cf43e1 100644--- a/crates/obscura-browser/src/context.rs+++ b/crates/obscura-browser/src/context.rs@@ -356,10 +356,15 @@ impl BrowserContext {/// Called during graceful shutdown.pub fn save_cookies(&self) {if let Some(ref dir) = self.storage_dir {- let _ = std::fs::create_dir_all(dir);+ // `save_to_file` creates the directory itself, with owner-only+ // permissions on unix, so any failure to do so is reported below.let cookie_path = dir.join("cookies.json");if let Err(e) = self.cookie_jar.save_to_file(&cookie_path) {- tracing::warn!("Failed to save cookies to {}: {}", cookie_path.display(), e);+ tracing::error!(+ "Could not save cookies to {}: {}. They will not be persisted, so the next run starts without them.",+ cookie_path.display(),+ e+ );} else {tracing::info!("Saved cookies to {}", cookie_path.display());}diff --git a/crates/obscura-net/src/cookies.rs b/crates/obscura-net/src/cookies.rsindex 4a3996f7..24f130de 100644--- a/crates/obscura-net/src/cookies.rs+++ b/crates/obscura-net/src/cookies.rs@@ -591,11 +591,19 @@ impl CookieJar {std::io::Error::new(std::io::ErrorKind::InvalidData, e)})?;if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent)?;+ create_private_dir_all(parent)?;}let mut tmp = tempfile::NamedTempFile::new_in(path.parent().unwrap_or(std::path::Path::new(".")),)?;+ // Cookie values are live session tokens. Do not depend on the tempfile+ // crate's default mode for keeping them private.+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ tmp.as_file()+ .set_permissions(std::fs::Permissions::from_mode(0o600))?;+ }tmp.write_all(json.as_bytes())?;tmp.persist(path).map_err(|e| e.error)?;Ok(())@@ -621,6 +629,21 @@ impl CookieJar {}}+/// Create `dir` and any missing parents. On unix, directories created here+/// are owner-only (0700) because the cookie file inside holds session tokens.+/// A directory that already exists keeps the mode its owner gave it. On+/// Windows a new directory inherits the ACL of its parent.+fn create_private_dir_all(dir: &std::path::Path) -> std::io::Result<()> {+ let mut builder = std::fs::DirBuilder::new();+ builder.recursive(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::DirBuilderExt;+ builder.mode(0o700);+ }+ builder.create(dir)+}+impl Default for CookieJar {fn default() -> Self {Self::new()@@ -1490,6 +1513,77 @@ mod tests {assert!(header.contains("token=xyz"));}+ #[test]+ fn save_to_file_reports_an_uncreatable_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let blocker = tmp.path().join("not-a-dir");+ std::fs::write(&blocker, "x").unwrap();++ let jar = CookieJar::new();+ let url = Url::parse("https://example.com/").unwrap();+ jar.set_cookie("session=abc123; Path=/", &url);++ let result = jar.save_to_file(&blocker.join("profile").join("cookies.json"));+ assert!(result.is_err(), "a save that cannot create its directory must fail");+ assert!(!blocker.join("profile").exists());+ }++ #[cfg(unix)]+ mod private_storage {+ use super::*;+ use std::os::unix::fs::PermissionsExt;++ fn mode(path: &std::path::Path) -> u32 {+ std::fs::metadata(path).unwrap().permissions().mode() & 0o777+ }++ fn jar_with_session() -> CookieJar {+ let jar = CookieJar::new();+ let url = Url::parse("https://example.com/").unwrap();+ jar.set_cookie("session=abc123; Path=/", &url);+ jar+ }++ #[test]+ fn creates_directories_0700_and_file_0600() {+ let tmp = tempfile::tempdir().unwrap();+ let profile = tmp.path().join("profile");+ let path = profile.join("nested").join("cookies.json");++ jar_with_session().save_to_file(&path).unwrap();++ assert_eq!(mode(&profile), 0o700);+ assert_eq!(mode(&profile.join("nested")), 0o700);+ assert_eq!(mode(&path), 0o600);+ }++ #[test]+ fn leaves_an_existing_directory_mode_alone() {+ let tmp = tempfile::tempdir().unwrap();+ let profile = tmp.path().join("profile");+ std::fs::create_dir(&profile).unwrap();+ std::fs::set_permissions(&profile, std::fs::Permissions::from_mode(0o750)).unwrap();++ jar_with_session()+ .save_to_file(&profile.join("cookies.json"))+ .unwrap();++ assert_eq!(mode(&profile), 0o750);+ }++ #[test]+ fn tightens_a_cookie_file_left_world_readable() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("cookies.json");+ std::fs::write(&path, "[]").unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();++ jar_with_session().save_to_file(&path).unwrap();++ assert_eq!(mode(&path), 0o600);+ }+ }+#[test]fn test_load_nonexistent_file_returns_zero() {let jar = CookieJar::new();diff --git a/docs/Persist-cookies-and-storage.md b/docs/Persist-cookies-and-storage.mdindex ef34c780..9a15e725 100644--- a/docs/Persist-cookies-and-storage.md+++ b/docs/Persist-cookies-and-storage.md@@ -47,6 +47,22 @@ The format is stable. Inspect with `jq`:jq '.[] | select(.domain == "example.com")' ./obscura-data/cookies.json```+## Keep the profile private++`cookies.json` holds live session tokens in plaintext. For a logged-in site the+cookie value is the login, so anyone who can read the file can act as you.+Treat the profile directory like a credential store: keep it out of version+control, backups you share and container images.++On unix, a directory Obscura creates to save into is owner-only (0700) and+`cookies.json` is written with mode 0600. A directory that already exists keeps+its mode. On Windows a new directory inherits the permissions of its parent, so+keep the profile somewhere only your user can read, such as your home folder.++If the cookies cannot be saved (for example the directory cannot be created),+Obscura logs an error saying they will not be persisted. `--quiet` turns the log+off, so check that `cookies.json` appears when persistence matters.+## When state is written- After every navigation completes (CDP `Page.navigate`, MCP `browser_navigate`),