Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(teleport): install cookies into a Chrome that was never launched (#4436)

ddupont9867f1d3d1e1
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
index c8238e59fc..3f0cbfc0eb 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
@@ -18,13 +18,13 @@
//! 3. re-encrypts each cookie value under it and writes the row into the
//! destination's real `Cookies` SQLite database ([`install_cookies`]).
//!
-//! [`install_cookies`] expects the browser to have run at least once on this
-//! machine already, so its `Cookies` database and table exist with whatever
-//! columns that Chrome version created (the "after Chrome's first run"
-//! design: this module never invents Chromium's schema, it discovers the
-//! live one via `PRAGMA table_info` and only ever sets the columns it knows
-//! the semantics of). A profile with no `Cookies` database yet fails with a
-//! named error telling the caller to launch the browser once first.
+//! [`install_cookies`] writes into the browser's own `Cookies` database when
+//! one exists, discovering its live columns via `PRAGMA table_info` and only
+//! ever setting the columns it knows the semantics of. When the browser has
+//! never been launched on this machine (a fresh Space), there is no database
+//! yet, so [`create_cookies_db`] creates one in Chrome's current schema with
+//! the `meta` version Chrome expects; Chrome then adopts it as its own on
+//! first launch instead of discarding or migrating it.
use std::path::Path;
@@ -125,6 +125,8 @@ const KNOWN_COLUMNS: &[&str] = &[
"is_httponly",
"samesite",
"creation_utc",
+ "has_expires",
+ "is_persistent",
];
/// Microseconds since the Windows/Chrome epoch (1601-01-01 UTC) for the
@@ -172,10 +174,11 @@ fn plaintext_for(digest: bool, host_key: &str, value: &[u8]) -> Vec<u8> {
/// is the first cookie ever installed for that browser here). Returns how
/// many rows were written.
///
+/// A profile with no `Cookies` database yet (the browser was never launched
+/// here) gets one created in Chrome's current schema first
+/// ([`create_cookies_db`]); an existing database is written into as it is.
+///
/// Fails with a named error, rather than guessing a schema, when:
-/// - `profile_dir` has no `Cookies` database yet (the browser must run once
-/// first so IT creates its own, real schema and, typically, its own Safe
-/// Storage item);
/// - the `cookies` table is missing a column this module needs to identify a
/// row (`host_key`, `name`, `path` -- Chromium's own unique index).
pub fn install_cookies(
@@ -194,18 +197,16 @@ pub fn install_cookies(
"re-encrypting cookies for a Windows destination (DPAPI) is not supported yet".into(),
));
}
- let db = profile_dir.join("Cookies");
- if !db.is_file() {
- return Err(TeleportError::Provider(format!(
- "{} has no Cookies database yet; launch the browser once on this \
- machine before installing cookies into it",
- profile_dir.display()
- )));
- }
+ let db = cookies_db_path(profile_dir);
let secret = ensure_safe_storage_secret(host, platform, service, record)
.map_err(|e| TeleportError::Provider(format!("Safe Storage key for {service}: {e}")))?;
let key = chromium_crypto::derive_key(&secret, pbkdf2_rounds_for(platform));
+ if !db.is_file() {
+ // Never-launched browser: create the database Chrome itself would.
+ create_cookies_db(&db)
+ .map_err(|e| TeleportError::Provider(format!("creating Cookies failed: {e}")))?;
+ }
let conn = rusqlite::Connection::open(&db)
.map_err(|e| TeleportError::Provider(format!("opening Cookies failed: {e}")))?;
let present = existing_columns(&conn, "cookies")
@@ -256,6 +257,9 @@ pub fn install_cookies(
"is_secure" => (item.is_secure as i64).into(),
"is_httponly" => (item.is_httponly as i64).into(),
"samesite" => item.samesite.into(),
+ // Chrome's own invariant: a persistent cookie has an expiry,
+ // a session cookie (`expires_utc == 0`) does not.
+ "has_expires" | "is_persistent" => ((item.expires_utc != 0) as i64).into(),
// Chrome stamps this at insert time; this import IS the
// creation event on this machine, so "now" is correct, not a
// placeholder.
@@ -277,6 +281,87 @@ pub fn install_cookies(
Ok(written)
}
+/// The `Cookies` meta version this module creates fresh databases at: the
+/// first one with the `host_key` digest ([`HOST_KEY_DIGEST_META_VERSION`]),
+/// i.e. Chrome 130+, which [`install_cookies`] then encrypts for.
+const CREATED_META_VERSION: i64 = HOST_KEY_DIGEST_META_VERSION;
+
+/// `last_compatible_version` Chrome's cookie store writes (its
+/// `kCompatibleVersionNumber`): any Chrome at or above it opens the file.
+const CREATED_META_COMPATIBLE_VERSION: i64 = 5;
+
+/// Where `profile_dir`'s cookie database lives or should be created. Chrome 96+
+/// keeps it at `Network/Cookies`; older Chrome (and some Chromium forks) at
+/// `Cookies` in the profile root. An existing database wins, newest layout
+/// first; with none, the current layout is used.
+fn cookies_db_path(profile_dir: &Path) -> std::path::PathBuf {
+ let network = profile_dir.join("Network").join("Cookies");
+ let legacy = profile_dir.join("Cookies");
+ if !network.is_file() && legacy.is_file() {
+ legacy
+ } else {
+ network
+ }
+}
+
+/// Creates an empty `Cookies` database at `db` the way a first Chrome launch
+/// would (Chrome's current `cookies` table plus its `meta` table at
+/// [`CREATED_META_VERSION`]), so a later real launch adopts it. Every column
+/// Chrome fills itself has a default, so [`install_cookies`]'s partial
+/// `INSERT` is valid. Safe to call if another writer created it first.
+fn create_cookies_db(db: &Path) -> std::io::Result<()> {
+ if let Some(parent) = db.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let err = |e: rusqlite::Error| std::io::Error::other(e.to_string());
+ let conn = rusqlite::Connection::open(db).map_err(err)?;
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS meta (key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
+ CREATE TABLE IF NOT EXISTS cookies (
+ creation_utc INTEGER NOT NULL,
+ host_key TEXT NOT NULL,
+ top_frame_site_key TEXT NOT NULL DEFAULT '',
+ name TEXT NOT NULL,
+ value TEXT NOT NULL DEFAULT '',
+ encrypted_value BLOB NOT NULL DEFAULT X'',
+ path TEXT NOT NULL,
+ expires_utc INTEGER NOT NULL,
+ is_secure INTEGER NOT NULL,
+ is_httponly INTEGER NOT NULL,
+ last_access_utc INTEGER NOT NULL DEFAULT 0,
+ has_expires INTEGER NOT NULL DEFAULT 1,
+ is_persistent INTEGER NOT NULL DEFAULT 1,
+ priority INTEGER NOT NULL DEFAULT 1,
+ samesite INTEGER NOT NULL DEFAULT -1,
+ source_scheme INTEGER NOT NULL DEFAULT 0,
+ source_port INTEGER NOT NULL DEFAULT -1,
+ last_update_utc INTEGER NOT NULL DEFAULT 0,
+ source_type INTEGER NOT NULL DEFAULT 0,
+ has_cross_site_ancestor INTEGER NOT NULL DEFAULT 0,
+ UNIQUE (host_key, top_frame_site_key, has_cross_site_ancestor, name, path, source_scheme, source_port)
+ );
+ CREATE INDEX IF NOT EXISTS domain ON cookies(host_key);",
+ )
+ .map_err(err)?;
+ for (key, value) in [
+ ("version", CREATED_META_VERSION),
+ ("last_compatible_version", CREATED_META_COMPATIBLE_VERSION),
+ ] {
+ conn.execute(
+ "INSERT OR IGNORE INTO meta (key, value) VALUES (?1, ?2)",
+ rusqlite::params![key, value.to_string()],
+ )
+ .map_err(err)?;
+ }
+ drop(conn);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(db, std::fs::Permissions::from_mode(0o600))?;
+ }
+ Ok(())
+}
+
/// Lowercased column names of `table`, via `PRAGMA table_info` (never guessed
/// or hardcoded as a `CREATE TABLE`, since the live schema is whatever this
/// machine's own Chrome created).
@@ -503,12 +588,80 @@ mod tests {
assert!(record.keychain_items.is_empty());
}
+ /// Cookies for a browser that was never launched: the database is
+ /// created in Chrome's current schema (at the `Network/Cookies` path
+ /// current Chrome reads), and the rows read back with the Linux key.
+ #[test]
+ fn never_launched_profile_gets_a_chrome_schema_database_and_the_cookies() {
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Default");
+ let host = Arc::new(FakeHost::new());
+ let mut record = ImportRecord::default();
+ let written = install_cookies(
+ host.as_ref(),
+ &profile,
+ "Chrome Safe Storage",
+ Platform::Linux,
+ &[item(".github.com", "user_session", "gh-session-abc")],
+ &mut record,
+ )
+ .unwrap();
+ assert_eq!(written, 1);
+ let db = profile.join("Network/Cookies");
+ assert!(db.is_file());
+ assert!(!profile.join("Cookies").exists());
+ assert_eq!(record.cookie_rows.len(), 1);
+ assert_eq!(record.cookie_rows[0].db, db);
+
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ assert_eq!(cookies_meta_version(&conn), CREATED_META_VERSION);
+ let compat: String = conn
+ .query_row(
+ "SELECT value FROM meta WHERE key = 'last_compatible_version'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(compat, "5");
+ let columns = existing_columns(&conn, "cookies").unwrap();
+ for c in [
+ "top_frame_site_key",
+ "has_cross_site_ancestor",
+ "source_type",
+ ] {
+ assert!(columns.contains(c), "missing {c}");
+ }
+ // Readable as Chrome reads it: v10 under the fixed Linux key, host
+ // digest in front of the value (meta version 24).
+ let encrypted: Vec<u8> = conn
+ .query_row(
+ "SELECT encrypted_value FROM cookies WHERE host_key = '.github.com'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let key = chromium_crypto::derive_key(
+ chromium_crypto::LINUX_V10_PASSWORD,
+ chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ );
+ let plain = chromium_crypto::decrypt_prefixed(&key, &encrypted)
+ .unwrap()
+ .1;
+ assert_eq!(
+ &plain[..32],
+ <sha2::Sha256 as sha2::Digest>::digest(b".github.com").as_slice()
+ );
+ assert_eq!(&plain[32..], b"gh-session-abc");
+ // Nothing was installed in a keychain on Linux.
+ assert!(host.calls().is_empty());
+ }
+
#[test]
- fn missing_cookies_database_fails_with_a_named_error() {
+ fn never_launched_profile_creates_the_keychain_key_on_macos() {
let dir = tempfile::tempdir().unwrap();
let host = keychain_fake();
let mut record = ImportRecord::default();
- let err = install_cookies(
+ install_cookies(
host.as_ref(),
dir.path(),
"Chrome Safe Storage",
@@ -516,9 +669,42 @@ mod tests {
&[item("a.test", "n", "v")],
&mut record,
)
- .unwrap_err()
- .to_string();
- assert!(err.contains("launch the browser once"), "{err}");
+ .unwrap();
+ assert!(dir.path().join("Network/Cookies").is_file());
+ assert_eq!(record.keychain_items.len(), 1);
+ }
+
+ #[test]
+ fn an_existing_legacy_database_is_written_into_not_replaced() {
+ let dir = tempfile::tempdir().unwrap();
+ let legacy = {
+ let db = dir.path().join("Cookies");
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE cookies (creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL,
+ name TEXT NOT NULL, value TEXT NOT NULL DEFAULT '', encrypted_value BLOB NOT NULL DEFAULT '',
+ path TEXT NOT NULL, expires_utc INTEGER NOT NULL, is_secure INTEGER NOT NULL DEFAULT 0,
+ is_httponly INTEGER NOT NULL DEFAULT 0, samesite INTEGER NOT NULL DEFAULT -1);",
+ )
+ .unwrap();
+ db
+ };
+ let mut record = ImportRecord::default();
+ install_cookies(
+ &FakeHost::new(),
+ dir.path(),
+ "Chrome Safe Storage",
+ Platform::Linux,
+ &[item("a.test", "n", "v")],
+ &mut record,
+ )
+ .unwrap();
+ assert!(!dir.path().join("Network").exists());
+ let n: i64 = rusqlite::Connection::open(&legacy)
+ .unwrap()
+ .query_row("SELECT count(*) FROM cookies", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(n, 1);
}
#[test]
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index 5472e8d778..5bd210cafd 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -1560,6 +1560,7 @@ dependencies = [
"cua-spacesd-server",
"cua-spacesd-teleport",
"cua-teleport",
+ "cua-teleport-bundle",
"rusqlite",
"tempfile",
"tokio",
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml b/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
index 8851ea4896..60fd8df9b8 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
@@ -22,6 +22,7 @@ cua-teleport = { path = "../../../cua/crates/cua-teleport" }
cua-spacesd-client = { path = "../../../cua/crates/cua-spacesd-client" }
cua-spacesd-server = { path = "../../crates/cua-spacesd-server" }
cua-spacesd-teleport = { path = "../../crates/cua-spacesd-teleport" }
+cua-teleport-bundle = { path = "../../../cua/crates/cua-teleport-bundle" }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
tempfile = "3"
rusqlite = { version = "0.40.1", default-features = false, features = ["bundled"] }
diff --git a/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs b/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
index ca53ab5994..1dc905f509 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
+++ b/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
@@ -43,7 +43,18 @@ async fn guest() -> Guest {
..ServerConfig::default()
};
let ctx = ServerContext::new(config, Some(TOKEN.into()));
- let receiver_host = Arc::new(cua_spacesd_teleport::FakeHost::new());
+ // A guest that has never held a Chrome Safe Storage item: reading the
+ // secret fails (so the receiver creates one), every other `security`
+ // call succeeds. Only a macOS receiver ever asks.
+ let receiver_host = Arc::new(cua_spacesd_teleport::FakeHost::new().with_responder(|c| {
+ let reads_secret =
+ c.args.iter().any(|a| a == "find-generic-password") && c.args.iter().any(|a| a == "-w");
+ if c.program != "security" || reads_secret {
+ Ok(cua_spacesd_teleport::HostOutput::failed())
+ } else {
+ Ok(cua_spacesd_teleport::HostOutput::ok(""))
+ }
+ }));
let receiver = Arc::new(cua_spacesd_teleport::Receiver::with_host(
dest_home.path().to_path_buf(),
receiver_host.clone(),
@@ -73,8 +84,10 @@ async fn client(url: &str, transport: TransportPreference) -> SpacesdClient {
fn fake_chrome(home: &Path) {
let profile = home.join(".config/google-chrome/Default");
std::fs::create_dir_all(profile.join("Sessions")).unwrap();
- // A real (empty) Chrome cookie store: the sender reads it as SQLite.
- rusqlite::Connection::open(profile.join("Cookies"))
+ std::fs::create_dir_all(profile.join("Network")).unwrap();
+ // A real (empty) Chrome cookie store in modern Chrome's layout
+ // (`Network/Cookies`, no root `Cookies`): the sender reads it as SQLite.
+ rusqlite::Connection::open(profile.join("Network/Cookies"))
.unwrap()
.execute_batch(
"CREATE TABLE cookies (creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL,
@@ -202,6 +215,85 @@ async fn chrome_session_lands_in_the_guest_home_over_both_transports() {
}
}
+/// The receiving Space's Chrome was never launched: its profile has no
+/// `Cookies` database at all. The teleport must still land the signed-in
+/// cookies, in a database Chrome adopts on its first real launch.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cookies_land_in_a_chrome_that_was_never_launched() {
+ use cua_teleport_bundle::chromium_crypto as crypto;
+
+ let g = guest().await;
+ // Nothing exists under the guest home: not the profile, not `Cookies`.
+ assert_eq!(std::fs::read_dir(g.dest_home.path()).unwrap().count(), 0);
+ let src = tempfile::tempdir().unwrap();
+ fake_chrome(src.path());
+ {
+ let key = crypto::derive_key(crypto::LINUX_V10_PASSWORD, crypto::LINUX_V10_PBKDF2_ROUNDS);
+ let blob = crypto::encrypt_v10(&key, b"fresh-session-value");
+ let conn = rusqlite::Connection::open(
+ src.path()
+ .join(".config/google-chrome/Default/Network/Cookies"),
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO cookies (creation_utc, host_key, name, value, encrypted_value, path,
+ expires_utc, is_secure, is_httponly, samesite)
+ VALUES (1, '.github.com', 'user_session', '', ?1, '/', 13400000000000000, 1, 1, 1)",
+ [blob],
+ )
+ .unwrap();
+ }
+ let (_, teleporter) = sender(src.path());
+ let env = client(&g.url, TransportPreference::Native).await;
+ teleporter
+ .send(
+ &env,
+ &chrome(),
+ TransferScope::FullProfile,
+ Selection::All,
+ Arc::new(AutoApprove),
+ )
+ .await
+ .unwrap();
+
+ let user_data = if cfg!(target_os = "macos") {
+ "Library/Application Support/Google/Chrome"
+ } else {
+ ".config/google-chrome"
+ };
+ let db = g
+ .dest_home
+ .path()
+ .join(user_data)
+ .join("Default/Network/Cookies");
+ assert!(db.is_file(), "no cookies database was created");
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ let version: String = conn
+ .query_row("SELECT value FROM meta WHERE key = 'version'", [], |r| {
+ r.get(0)
+ })
+ .unwrap();
+ assert!(version.parse::<i64>().unwrap() >= 24, "{version}");
+ let encrypted: Vec<u8> = conn
+ .query_row(
+ "SELECT encrypted_value FROM cookies WHERE host_key = '.github.com'
+ AND name = 'user_session'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert!(encrypted.starts_with(b"v10"));
+ // On a Linux guest the key is Chrome's fixed one, so the value can be
+ // read back exactly as Chrome would (digest of host_key, then value). A
+ // macOS guest's key lives in a Keychain the fake host does not hold.
+ if cfg!(not(target_os = "macos")) {
+ let key = crypto::derive_key(crypto::LINUX_V10_PASSWORD, crypto::LINUX_V10_PBKDF2_ROUNDS);
+ let plain = crypto::decrypt_prefixed(&key, &encrypted).unwrap().1;
+ assert!(plain.ends_with(b"fresh-session-value"));
+ assert_eq!(plain.len(), 32 + b"fresh-session-value".len());
+ }
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn default_selection_withholds_credentials() {
let g = guest().await;
diff --git a/libs/cua/crates/cua-teleport-bundle/src/layout.rs b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
index 386ebf8037..8cbdc898f0 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/layout.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
@@ -124,6 +124,22 @@ pub mod chrome {
}
}
+ /// The cookie store of a Chromium-family profile directory: modern
+ /// Chrome (96+) keeps it at `Network/Cookies`, older builds at `Cookies`.
+ /// The modern location wins when it exists; with neither present the
+ /// modern one is returned (what a fresh launch would create). Applies to
+ /// every profile (`Default`, `Profile 1`, ...) and every Chromium-family
+ /// browser (Brave, Edge, Arc share the layout).
+ pub fn cookies_store(profile_dir: &std::path::Path) -> std::path::PathBuf {
+ let network = profile_dir.join("Network").join("Cookies");
+ let legacy = profile_dir.join("Cookies");
+ if !network.is_file() && legacy.is_file() {
+ legacy
+ } else {
+ network
+ }
+ }
+
/// Bundle path of a profile-relative file (canonical Linux layout).
pub fn dest_rel_path(profile: &str, rel: &str) -> String {
format!("{LINUX_USER_DATA_DIR}/{profile}/{rel}")
diff --git a/libs/cua/crates/cua-teleport/src/browser_cookies.rs b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
index 5b3f539f76..db044efe3a 100644
--- a/libs/cua/crates/cua-teleport/src/browser_cookies.rs
+++ b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
@@ -185,7 +185,8 @@ impl ChromeCookies {
/// cookie the destination needs and still report success.
pub fn read(&self, sites: &[String]) -> Result<Vec<DecryptedCookie>, TeleportError> {
let dir = self.profile_dir()?;
- let db = dir.join("Cookies");
+ // `Default/Network/Cookies` first (Chrome 96+), then `Default/Cookies`.
+ let db = cua_teleport_bundle::layout::chrome::cookies_store(&dir);
if !db.is_file() {
return Err(TeleportError::Provider(format!(
"no cookies: {} has no Cookies database",
@@ -332,11 +333,31 @@ pub fn write_cookies_db_for_tests(
profile_dir: &Path,
rows: &[TestCookieRow<'_>],
) -> Result<(), TeleportError> {
- std::fs::create_dir_all(profile_dir)
+ write_cookies_db_at(profile_dir, &profile_dir.join("Cookies"), rows)
+}
+
+/// Like [`write_cookies_db_for_tests`], in modern Chrome's layout
+/// (`Network/Cookies`, no legacy file).
+pub fn write_network_cookies_db_for_tests(
+ profile_dir: &Path,
+ rows: &[TestCookieRow<'_>],
+) -> Result<(), TeleportError> {
+ write_cookies_db_at(
+ profile_dir,
+ &profile_dir.join("Network").join("Cookies"),
+ rows,
+ )
+}
+
+fn write_cookies_db_at(
+ profile_dir: &Path,
+ db: &Path,
+ rows: &[TestCookieRow<'_>],
+) -> Result<(), TeleportError> {
+ std::fs::create_dir_all(db.parent().unwrap_or(profile_dir))
.map_err(|e| TeleportError::Provider(format!("profile dir: {e}")))?;
- let db = profile_dir.join("Cookies");
let run = || -> rusqlite::Result<()> {
- let conn = rusqlite::Connection::open(&db)?;
+ let conn = rusqlite::Connection::open(db)?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS cookies (host_key TEXT NOT NULL, name TEXT NOT NULL, \
value TEXT NOT NULL, encrypted_value BLOB NOT NULL, path TEXT NOT NULL, \
@@ -461,6 +482,70 @@ mod tests {
}
#[cfg(target_os = "macos")]
+ fn one_row() -> Vec<TestCookieRow<'static>> {
+ vec![TestCookieRow {
+ host_key: ".github.com",
+ name: "user_session",
+ encrypted_value: v10_row(chromium_crypto::LINUX_V10_PASSWORD, 1, "gh-session-abc"),
+ path: "/",
+ expires_utc: 0,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ }]
+ }
+
+ fn read_linux(profile: &Path) -> Result<Vec<DecryptedCookie>, TeleportError> {
+ ChromeCookies::new(std::sync::Arc::new(FakeHost::new()))
+ .with_platform(Platform::Linux)
+ .with_profile_dir(profile)
+ .read(&[])
+ }
+
+ /// Modern Chrome (96+): only `Network/Cookies` exists.
+ #[test]
+ fn reads_a_modern_network_cookies_only_profile() {
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Profile 1");
+ write_network_cookies_db_for_tests(&profile, &one_row()).unwrap();
+ assert!(!profile.join("Cookies").exists());
+ let got = read_linux(&profile).unwrap();
+ assert_eq!(got.len(), 1);
+ assert_eq!(got[0].value.as_str(), "gh-session-abc");
+ }
+
+ /// Older Chrome: only the legacy root `Cookies` exists.
+ #[test]
+ fn reads_a_legacy_cookies_only_profile() {
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Default");
+ write_cookies_db_for_tests(&profile, &one_row()).unwrap();
+ assert_eq!(read_linux(&profile).unwrap().len(), 1);
+ }
+
+ /// Both exist (a profile Chrome migrated): the modern one is read.
+ #[test]
+ fn prefers_network_cookies_over_a_stale_legacy_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Default");
+ write_cookies_db_for_tests(&profile, &[]).unwrap();
+ write_network_cookies_db_for_tests(&profile, &one_row()).unwrap();
+ assert_eq!(read_linux(&profile).unwrap().len(), 1);
+ }
+
+ #[test]
+ fn cookies_store_prefers_network_and_falls_back_to_legacy() {
+ use cua_teleport_bundle::layout::chrome::cookies_store;
+ let d = tempfile::tempdir().unwrap();
+ let p = d.path();
+ assert_eq!(cookies_store(p), p.join("Network/Cookies"));
+ std::fs::write(p.join("Cookies"), b"x").unwrap();
+ assert_eq!(cookies_store(p), p.join("Cookies"));
+ std::fs::create_dir_all(p.join("Network")).unwrap();
+ std::fs::write(p.join("Network/Cookies"), b"x").unwrap();
+ assert_eq!(cookies_store(p), p.join("Network/Cookies"));
+ }
+
#[test]
fn macos_cookies_use_the_named_browsers_safe_storage_item() {
let dir = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-teleport/src/providers/chrome.rs b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
index 2c2fe09def..0a61b98df0 100644
--- a/libs/cua/crates/cua-teleport/src/providers/chrome.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
@@ -454,11 +454,22 @@ fn manifest_item(
}
}
+/// Where curated profile file `name` lives on disk: `Cookies` resolves to
+/// `Network/Cookies` first (Chrome 96+), then the legacy root file; every
+/// other file is at the profile root.
+fn profile_file_path(profile_dir: &Path, name: &str) -> PathBuf {
+ if name == "Cookies" {
+ cua_teleport_bundle::layout::chrome::cookies_store(profile_dir)
+ } else {
+ profile_dir.join(name)
+ }
+}
+
/// The concrete-item count and plural noun for one curated profile file, or
/// `None` (unknown file, or a locked/absent/unreadable database) so the consent
/// UI falls back to the byte size. Pure: a path in, an `Option` out.
fn profile_file_count(profile_dir: &Path, name: &str) -> Option<(u64, &'static str)> {
- let path = profile_dir.join(name);
+ let path = profile_file_path(profile_dir, name);
match name {
"Bookmarks" => count_bookmarks(&path).map(|n| (n, "bookmarks")),
"Cookies" => count_sqlite_rows(&path, "cookies").map(|n| (n, "cookies")),
@@ -640,7 +651,7 @@ impl ExportProvider for ChromeProvider {
if scope == TransferScope::FullProfile {
for (name, sensitive) in PROFILE_FILES {
- let disk = profile_dir.join(name);
+ let disk = profile_file_path(&profile_dir, name);
items.push(manifest_item(
name,
&dest_rel_path(&profile, name),
@@ -1057,6 +1068,67 @@ mod tests {
assert!(!prefs.sensitive);
}
+ /// Modern Chrome keeps its cookies only in `Network/Cookies`. The
+ /// manifest must count them, and the export must send them as decrypted
+ /// rows without shipping the raw database (or any `Network/` file) too.
+ #[test]
+ fn modern_network_cookies_are_counted_and_exported_as_rows_only() {
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Default");
+ let key = cua_teleport_bundle::chromium_crypto::derive_key(
+ cua_teleport_bundle::chromium_crypto::LINUX_V10_PASSWORD,
+ cua_teleport_bundle::chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ );
+ crate::browser_cookies::write_network_cookies_db_for_tests(
+ &profile,
+ &[crate::browser_cookies::TestCookieRow {
+ host_key: "example.test",
+ name: "sid",
+ encrypted_value: cua_teleport_bundle::chromium_crypto::encrypt_v10(&key, b"v"),
+ path: "/",
+ expires_utc: 0,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ }],
+ )
+ .unwrap();
+ assert!(!profile.join("Cookies").exists());
+ let provider = ChromeProvider::new()
+ .without_devtools()
+ .with_profile_dir(&profile);
+
+ let manifest = provider
+ .manifest(&app(), None, TransferScope::FullProfile)
+ .unwrap();
+ let cookies = manifest
+ .items
+ .iter()
+ .find(|item| item.label == "Cookies")
+ .unwrap();
+ assert!(cookies.est_bytes > 0, "size read from Network/Cookies");
+ assert_eq!(cookies.count, Some(1));
+
+ let mut bundle = Vec::new();
+ provider
+ .export(&app(), TransferScope::FullProfile, &mut bundle)
+ .unwrap();
+ let entries = BundleReader::open(Cursor::new(bundle))
+ .unwrap()
+ .read_all()
+ .unwrap();
+ assert!(!entries.iter().any(|e| e.rel_path.ends_with("Cookies")));
+ let rows = cua_teleport_bundle::cookies::parse(
+ &entries
+ .iter()
+ .find(|e| e.rel_path == cua_teleport_bundle::cookies::COOKIES_ENTRY)
+ .unwrap()
+ .bytes,
+ );
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].value, b"v");
+ }
+
/// A full export carries the curated profile in the canonical (Linux)
/// bundle layout, checksummed, and never the caches. Where it lands on the
/// destination is the receiver's business (`cua-spacesd-teleport`).